1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
//! # bad64
//!
//! bad64 is a set of Rust bindings to the Binja Arm64 Disassembler.
//!
//! For more information about the disassembler, please see the
//! [upstream](https://github.com/Vector35/arch-arm64/tree/dev/disassembler)
//! repo.
//!
//! There are two main entry points:
//! 1. [`decode`] for decoding a single instruction.
//! ```
//! use bad64::{decode, Op};
//! // nop - "\x1f\x20\x03\xd5"
//! let decoded = decode(0xd503201f, 0x1000).unwrap();
//!
//! assert_eq!(decoded.address(), 0x1000);
//! assert_eq!(decoded.operands().len(), 0);
//! assert_eq!(decoded.op(), Op::NOP);
//! assert_eq!(decoded.op().mnem(), "nop");
//! ```
//!
//! 2. [`disasm`] for disassembling a byte sequence.
//! ```
//! use bad64::{disasm, Op, Operand, Reg, Imm};
//!
//! // 1000: str   x0, [sp, #-16]! ; "\xe0\x0f\x1f\xf8"
//! // 1004: ldr   x0, [sp], #16   ; "\xe0\x07\x41\xf8"
//! let mut decoded_iter = disasm(b"\xe0\x0f\x1f\xf8\xe0\x07\x41\xf8", 0x1000);
//!
//! let push = decoded_iter.next().unwrap().unwrap();
//!
//! // check out the push
//! assert_eq!(push.address(), 0x1000);
//! assert_eq!(push.operands().len(), 2);
//! assert_eq!(push.op(), Op::STR);
//! assert_eq!(
//!     push.operands()[0],
//!     Operand::Reg { reg: Reg::X0, arrspec: None }
//! );
//! assert_eq!(
//!     push.operands()[1],
//!     Operand::MemPreIdx { reg: Reg::SP, imm: Imm::Signed(-16) }
//! );
//! assert_eq!(push.operands().get(2), None);
//!
//! let pop = decoded_iter.next().unwrap().unwrap();
//!
//! // check out the pop
//! assert_eq!(pop.address(), 0x1004);
//! assert_eq!(pop.operands().len(), 2);
//! assert_eq!(pop.op(), Op::LDR);
//! assert_eq!(
//!     pop.operands().get(0),
//!     Some(&Operand::Reg { reg: Reg::X0, arrspec: None })
//! );
//! assert_eq!(
//!     pop.operands().get(1),
//!     Some(&Operand::MemPostIdxImm { reg: Reg::SP, imm: Imm::Signed(16) })
//! );
//! assert_eq!(pop.operands().get(2), None);
//!
//! // make sure there's nothing left
//! assert_eq!(decoded_iter.next(), None);
//! ```

#![no_std]
#![feature(maybe_uninit_uninit_array, maybe_uninit_extra, maybe_uninit_slice)]

#[macro_use]
extern crate num_derive;

#[macro_use]
extern crate static_assertions;

use core::convert::{TryFrom, TryInto};
use core::fmt;
use core::hash::{Hash, Hasher};
use core::mem::MaybeUninit;

use num_traits::FromPrimitive;

use bad64_sys::*;

mod arrspec;
mod condition;
mod op;
mod operand;
mod reg;
mod shift;
mod sysreg;

pub use arrspec::ArrSpec;
pub use condition::Condition;
pub use op::Op;
pub use operand::{Imm, Operand};
pub use reg::Reg;
pub use shift::Shift;
pub use sysreg::SysReg;

/// A decoded instruction
#[derive(Clone)]
pub struct Instruction {
    address: u64,
    opcode: u32,
    op: Op,
    num_operands: usize,
    operands: [MaybeUninit<Operand>; MAX_OPERANDS as usize],
}

// Needed because MaybeUninit doesn't allow derives
impl PartialEq for Instruction {
    fn eq(&self, other: &Self) -> bool {
        self.address() == other.address()
            && self.op() == other.op()
            && self.opcode() == other.opcode()
            && self.num_operands == other.num_operands
            && self
                .operands()
                .iter()
                .zip(other.operands().iter())
                .all(|(a, b)| a == b)
    }
}

impl Eq for Instruction {}

impl Hash for Instruction {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.address.hash(state);
        self.opcode.hash(state);
        self.op.hash(state);
        self.num_operands.hash(state);

        for o in self.operands() {
            o.hash(state);
        }
    }
}

impl fmt::Display for Instruction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.op())?;

        let mut ops = self.operands().iter();

        if let Some(op) = ops.next() {
            write!(f, " {}", op)?;

            for op in ops {
                write!(f, ", {}", op)?;
            }
        }

        Ok(())
    }
}

impl fmt::Debug for Instruction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Instruction")
            .field("address", &self.address)
            .field("opcode", &self.opcode)
            .field("op", &self.op)
            .field("num_operands", &self.num_operands)
            .field("operands", &self.operands())
            .finish()
    }
}

impl Instruction {
    /// Returns the instruction address
    ///
    /// # Example
    /// ```
    /// use bad64::decode;
    /// // nop - "\x1f\x20\x03\xd4"
    /// let decoded = decode(0xd503201f, 0x1000).unwrap();
    /// assert_eq!(decoded.address(), 0x1000);
    /// ```
    pub fn address(&self) -> u64 {
        self.address
    }

    /// Returns the instruction opcode
    ///
    /// # Example
    /// ```
    /// use bad64::decode;
    /// // nop - "\x1f\x20\x03\xd4"
    /// let decoded = decode(0xd503201f, 0x1000).unwrap();
    /// assert_eq!(decoded.opcode(), 0xd503201f);
    /// ```
    pub fn opcode(&self) -> u32 {
        self.opcode
    }

    /// Returns the instruction operation
    ///
    /// # Example
    /// ```
    /// use bad64::{decode, Op};
    /// // nop - "\x1f\x20\x03\xd4"
    /// let decoded = decode(0xd503201f, 0x1000).unwrap();
    /// assert_eq!(decoded.op(), Op::NOP);
    // ```
    pub fn op(&self) -> Op {
        self.op
    }

    /// Returns a slice of Operands
    ///
    /// # Example
    /// ```
    /// use bad64::{decode, Operand, Reg};
    ///
    /// // eor x0, x1, x2  - "\x20\x00\x02\xca"
    /// let decoded = decode(0xca020020, 0x1000).unwrap();
    ///
    /// let mut ops = decoded.operands();
    ///
    /// assert_eq!(ops.len(), 3);
    /// assert_eq!(ops[0], Operand::Reg { reg: Reg::X0, arrspec: None });
    /// assert_eq!(ops[1], Operand::Reg { reg: Reg::X1, arrspec: None });
    /// assert_eq!(ops[2], Operand::Reg { reg: Reg::X2, arrspec: None });
    /// ```
    pub fn operands(&self) -> &[Operand] {
        unsafe { MaybeUninit::slice_assume_init_ref(&self.operands[..self.num_operands]) }
    }
}
/// Decoding errors types
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
#[repr(i32)]
pub enum DecodeError {
    Reserved(u64),
    Unmatched(u64),
    Unallocated(u64),
    Undefined(u64),
    EndOfInstruction(u64),
    Lost(u64),
    Unreachable(u64),
    Short(u64),
}

impl DecodeError {
    fn new(code: i32, address: u64) -> Self {
        match code {
            DECODE_STATUS_RESERVED => Self::Reserved(address),
            DECODE_STATUS_UNMATCHED => Self::Unmatched(address),
            DECODE_STATUS_UNALLOCATED => Self::Unallocated(address),
            DECODE_STATUS_UNDEFINED => Self::Undefined(address),
            DECODE_STATUS_END_OF_INSTRUCTION => Self::EndOfInstruction(address),
            DECODE_STATUS_LOST => Self::Lost(address),
            DECODE_STATUS_UNREACHABLE => Self::Unreachable(address),
            _ => panic!("unknown decode error code"),
        }
    }

    pub fn address(&self) -> u64 {
        match self {
            Self::Reserved(a) => *a,
            Self::Unmatched(a) => *a,
            Self::Unallocated(a) => *a,
            Self::Undefined(a) => *a,
            Self::EndOfInstruction(a) => *a,
            Self::Lost(a) => *a,
            Self::Unreachable(a) => *a,
            Self::Short(a) => *a,
        }
    }
}

/// Decode a single instruction
///
/// # Arguments
///
/// * `ins` - A little endian u32 of code to be decoded
/// * `address` - Location of code in memory
///
/// # Examples
/// ```
/// use bad64::{decode, Op};
///
/// // NOTE: little endian
/// let decoded = decode(0xd503201f, 0x1000).unwrap();
///
/// assert_eq!(decoded.operands().len(), 0);
/// assert_eq!(decoded.operands(), &[]);
/// assert_eq!(decoded.op(), Op::NOP);
/// assert_eq!(decoded.op().mnem(), "nop");
/// assert_eq!(decoded.address(), 0x1000);
/// ```
pub fn decode(ins: u32, address: u64) -> Result<Instruction, DecodeError> {
    let mut decoded = MaybeUninit::zeroed();

    let r = unsafe { aarch64_decompose(ins, decoded.as_mut_ptr(), address) };

    match r {
        0 => {
            let decoded = unsafe { decoded.assume_init() };
            let op = Op::from_u32(decoded.operation as u32).unwrap();
            let mut operands: [MaybeUninit<Operand>; MAX_OPERANDS as usize] =
                MaybeUninit::uninit_array();
            let mut num_operands = 0;

            for (n, operand) in decoded.operands.iter().enumerate() {
                match Operand::try_from(operand) {
                    Ok(o) => {
                        operands[n] = MaybeUninit::new(o);
                        num_operands += 1;
                    }
                    Err(_) => break,
                }
            }

            Ok(Instruction {
                address,
                opcode: decoded.insword,
                op,
                num_operands,
                operands,
            })
        }
        _ => Err(DecodeError::new(r, address)),
    }
}

/// Disassemble byte slice
///
/// # Arguments
///
/// * `code` - u8 slice to zero or more instructions
/// * `address` - Location of code in memory
///
/// # Examples
/// ```
/// use bad64::{disasm, Op};
///
/// let mut decoded_iter = disasm(b"\x1f\x20\x03\xd5", 0x1000);
///
/// let decoded = decoded_iter.next().unwrap().unwrap();
///
/// assert_eq!(decoded.address(), 0x1000);
/// assert_eq!(decoded.operands().len(), 0);
/// assert_eq!(decoded.op(), Op::NOP);
/// assert_eq!(decoded.op().mnem(), "nop");
///
/// assert_eq!(decoded_iter.next(), None);
/// ```
pub fn disasm(
    code: &[u8],
    address: u64,
) -> impl Iterator<Item = Result<Instruction, DecodeError>> + '_ {
    (address..)
        .step_by(4)
        .zip(code.chunks(4))
        .map(|(addr, bytes)| match bytes.try_into() {
            Ok(v) => {
                let vv = u32::from_le_bytes(v);

                decode(vv, addr)
            }
            Err(_) => Err(DecodeError::Short(addr)),
        })
}