binbun_aarch64/lib.rs
1//! A64 instruction decoder.
2//!
3//! The tables in `generated/` are produced by `cargo xtask codegen` from Arm's
4//! machine-readable A-profile specification (AARCHMRS, the BSD package in
5//! `third_party/aarchmrs`) and binbun's hand-written tables of decode-time
6//! UNDEFINED checks (`xtask/src/aarch64/undefined.rs`); the code around them
7//! is written by hand. The crate is `no_std`; its one dependency is
8//! `binbun-isa`, the vocabulary of control flow analyses share.
9//!
10//! Decoding finds the word's [`Encoding`] (Arm's name for one bit pattern of
11//! an instruction, e.g. `ADD_32_addsub_imm`): every A64 encoding of the
12//! 2026-09 specification is decoded, whatever features it needs, including
13//! those of unannounced architecture versions ([`Encoding::fat`]). Which
14//! words decode agrees with LLVM 22's disassembler with every feature
15//! enabled, on all 2^32 words, apart from encodings newer than LLVM and two
16//! LLVM quirks documented in `tests/oracle.rs`. Where the architecture makes
17//! a word CONSTRAINED UNPREDICTABLE (should-be bits not as specified,
18//! overlapping registers), the word decodes if LLVM decodes it and is
19//! [`Error::Unpredictable`] otherwise.
20//!
21//! Operands ([`Instruction::operands`], typed: [`operand`]) and text
22//! ([`Instruction::display`], or [`Instruction::format`] into a token
23//! [`Sink`]) are computed from the word on demand, after alias selection,
24//! and the text is LLVM's (every feature, hexadecimal immediates), with
25//! labels as the addresses they name, as llvm-objdump writes them;
26//! [`LabelStyle::Relative`] writes them as offsets, as LLVM's C API does.
27//! Text equals LLVM 22's for every word both decode, apart from a few
28//! places where LLVM's text contradicts Arm's syntax (typos, an annotation,
29//! an alias Arm withdrew), listed in `tests/oracle.rs`.
30//!
31//! For analyses: how an instruction transfers control
32//! ([`Instruction::flow`]) and the condition it tests
33//! ([`Instruction::condition`]); [`AArch64`] implements
34//! [`binbun_isa::Architecture`]; [`Decoder`] sweeps a buffer.
35//!
36//! ```
37//! use binbun_aarch64::{Encoding, Error, LabelStyle, decode, decode_bytes};
38//!
39//! let add = decode(0x8b02_0020)?; // add x0, x1, x2
40//! assert_eq!(add.encoding(), Encoding::ADD_64_addsub_shift);
41//! assert_eq!(add.encoding().mnemonic(), "ADD");
42//! assert_eq!(decode_bytes(&[0x1f, 0x20, 0x03, 0xd5])?.encoding(), Encoding::NOP_HI_hints);
43//! // add w0, w1, w2 with shift == '11', a reserved shift type
44//! assert_eq!(decode(0x0bc2_0020), Err(Error::Undefined));
45//!
46//! // Operands and text, as LLVM writes them; aliases are resolved.
47//! let mov = decode(0xaa01_03e0)?; // orr x0, xzr, x1
48//! assert_eq!(mov.mnemonic(), "mov");
49//! assert_eq!(mov.display(0x1000).to_string(), "mov\tx0, x1");
50//!
51//! // Labels: the address by default, the offset as LLVM's C API writes it.
52//! let b = decode(0x1400_0010)?; // b +0x40
53//! assert_eq!(b.display(0x1000).to_string(), "b\t0x1040");
54//! assert_eq!(b.display_with(0x1000, LabelStyle::Relative).to_string(), "b\t#0x40");
55//! # Ok::<(), Error>(())
56//! ```
57
58#![no_std]
59
60mod access;
61mod decoder;
62mod error;
63mod flow;
64mod format;
65mod generated;
66mod isa;
67pub mod operand;
68mod pseudocode;
69
70use core::fmt;
71
72pub use access::{Access, Accesses, FlagSet, Flags, Implicit, MemoryAccess, MemoryKind};
73pub use decoder::Decoder;
74pub use error::Error;
75pub use flow::{CompareOperand, Condition};
76pub use format::{Display, LabelStyle, Sink, TokenKind};
77pub use generated::encoding::Encoding;
78pub use generated::feature::Feature;
79pub use isa::{AArch64, Mode};
80pub use operand::{Operand, Operands};
81
82use generated::syntax;
83
84/// Error of parsing a name that names nothing.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct UnknownName;
87
88impl fmt::Display for UnknownName {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 f.write_str("unknown name")
91 }
92}
93
94impl core::error::Error for UnknownName {}
95
96/// A decoded A64 instruction: the word and its encoding.
97#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
98pub struct Instruction {
99 word: u32,
100 encoding: Encoding,
101}
102
103impl Instruction {
104 /// The instruction word.
105 #[inline]
106 pub const fn word(self) -> u32 {
107 self.word
108 }
109
110 /// The encoding the word is an instance of.
111 #[inline]
112 pub const fn encoding(self) -> Encoding {
113 self.encoding
114 }
115
116 /// The features the encoding needs; see [`Encoding::features`].
117 #[inline]
118 pub const fn features(self) -> &'static [Feature] {
119 self.encoding.features()
120 }
121
122 /// The mnemonic as written, after alias selection, lower case and with
123 /// any suffix (`mov` for `orr x0, xzr, x1`, `b.eq`).
124 pub fn mnemonic(self) -> &'static str {
125 let alias = syntax::select(self.encoding, self.word);
126 syntax::mnemonic(self.encoding, alias, self.word)
127 }
128
129 /// The operands as written, after alias selection.
130 pub fn operands(self) -> Operands {
131 let mut operands = Operands::new();
132 let alias = syntax::select(self.encoding, self.word);
133 syntax::operands(self.encoding, alias, self.word, &mut operands);
134 operands
135 }
136
137 /// The operands of the encoding's own syntax, whatever alias the text
138 /// would use (`orr x0, xzr, x1` for `mov x0, x1`, `subs xzr, x1, #0x5`
139 /// for `cmp x1, #0x5`): what Arm's pseudocode for the encoding names,
140 /// for lifting. Optional parts are omitted as the text omits them
141 /// (`{, <shift> #<amount>}` with `lsl #0`, `ret`'s `x30`).
142 pub fn encoding_operands(self) -> Operands {
143 let mut operands = Operands::new();
144 syntax::operands(self.encoding, 0, self.word, &mut operands);
145 operands
146 }
147}
148
149/// Decodes one instruction word.
150///
151/// # Errors
152///
153/// [`Error::Unallocated`] if no encoding has the word, [`Error::Undefined`]
154/// if its encoding's decode checks reject it, [`Error::Unpredictable`] if it
155/// is a CONSTRAINED UNPREDICTABLE form LLVM rejects.
156#[inline]
157pub fn decode(word: u32) -> Result<Instruction, Error> {
158 let encoding = generated::decode::decode(word)?;
159 Ok(Instruction { word, encoding })
160}
161
162/// Decodes the instruction at the start of `bytes` (little-endian; A64
163/// instructions are always 4 bytes).
164///
165/// # Errors
166///
167/// [`Error::TooShort`] if `bytes` has fewer than 4 bytes; otherwise as
168/// [`decode`].
169#[inline]
170pub fn decode_bytes(bytes: &[u8]) -> Result<Instruction, Error> {
171 let word = bytes.first_chunk::<4>().ok_or(Error::TooShort)?;
172 decode(u32::from_le_bytes(*word))
173}