Skip to main content

exarmo_aarch64/
lib.rs

1#![doc = include_str!("../README.md")]
2//!
3//! ## Examples
4//!
5//! ### Decoding
6//!
7//! [`disassemble`] returns an iterator over the instructions in a byte buffer
8//! and their addresses. [`decode_bytes`] decodes one instruction from a byte
9//! slice, and [`decode_word`] one from a 32-bit word. For a word that is not an
10//! instruction, each returns a [`DecodeError`] that says why.
11//!
12//! ```
13//! use exarmo_aarch64::{DecodeError, decode_word, disassemble};
14//!
15//! // str x0, [sp, #-16]!
16//! // ldr x0, [sp], #16
17//! let code = [0xe0, 0x0f, 0x1f, 0xf8, 0xe0, 0x07, 0x41, 0xf8];
18//! let text: Vec<_> = disassemble(&code, 0x1000)
19//!     .map(|(address, instruction)| instruction.unwrap().at(address).to_string())
20//!     .collect();
21//! assert_eq!(text, ["str\tx0, [sp, #-0x10]!", "ldr\tx0, [sp], #0x10"]);
22//!
23//! // No row of the exception generation class allocates this word.
24//! assert_eq!(decode_word(0xd478da60), Err(DecodeError::Unallocated));
25//! ```
26//!
27//! ### What an instruction is
28//!
29//! An [`Instruction`] is an enum with a variant for every encoding and alias
30//! the specification describes. Each variant holds the fields of its
31//! encoding. For example, `cset x0, eq` decodes to `CsetCsinc64Condsel`.
32//! Its `Xd` field is an [`XRegZr`], a 64-bit register where 31 is the zero
33//! register. Its `invcond` field holds `ne`, the inverse of the condition
34//! the assembly writes.
35//!
36//! There are thousands of variants, so most code does not match on them.
37//! [`Instruction::encoding`] returns the variant as an [`Encoding`], a
38//! fieldless enum with a name for each. [`Instruction::mnemonic`] returns a
39//! [`Mnemonic`], which many encodings share. [`Instruction::operands`],
40//! below, reads the operands of any variant in one shape.
41//!
42//! ```
43//! use exarmo_aarch64::{Encoding, Instruction, Mnemonic, decode_word};
44//!
45//! // cset x0, eq
46//! let cset = decode_word(0x9a9f17e0).unwrap();
47//! let Instruction::CsetCsinc64Condsel { Xd, .. } = cset else {
48//!     unreachable!()
49//! };
50//! assert_eq!(Xd.num(), 0);
51//!
52//! assert_eq!(cset.encoding(), Encoding::CsetCsinc64Condsel);
53//! assert_eq!(cset.encoding().name(), "CsetCsinc64Condsel");
54//! assert_eq!(cset.mnemonic(), Mnemonic::Cset);
55//! assert_eq!(cset.mnemonic().name(), "cset");
56//! ```
57//!
58//! ### Operands
59//!
60//! [`Instruction::operands`] gives the operands in the order the assembly
61//! writes them, each an [`Operand`]. A memory operand is a single value that
62//! holds its base, offset and writeback.
63//!
64//! ```
65//! use exarmo_aarch64::{
66//!     Mem, Offset, Operand, Reg, RegOperand, Writeback, XRegSp, XRegZr, decode_word,
67//! };
68//!
69//! // str x0, [sp, #-16]!
70//! let str = decode_word(0xf81f0fe0).unwrap();
71//! assert_eq!(
72//!     str.operands().as_slice(),
73//!     [
74//!         Operand::Reg(RegOperand::plain(Reg::X(XRegZr::new(0)))),
75//!         Operand::Mem(Mem {
76//!             base: Reg::XSp(XRegSp::new(31)),
77//!             base_arrangement: None,
78//!             offset: Offset::Imm { value: -16, mul_vl: false },
79//!             writeback: Writeback::Pre,
80//!         }),
81//!     ]
82//! );
83//! ```
84//!
85//! A condition operand holds the condition as the assembly writes it. The
86//! field of `cset x0, eq` holds `ne`, and its operand is `eq`.
87//!
88//! ```
89//! use exarmo_aarch64::{Cond, Operand, decode_word};
90//!
91//! // cset x0, eq
92//! let cset = decode_word(0x9a9f17e0).unwrap();
93//! assert_eq!(cset.operands()[1], Operand::Cond(Cond::Eq));
94//! ```
95//!
96//! ### Tokens
97//!
98//! [`InstructionAt::write_tokens`] writes the text to a [`TokenSink`] as
99//! tokens, each with its [`TokenKind`] and the index of the operand it is
100//! part of. Number tokens carry their values, so you never need to parse the
101//! text.
102//! The [`tokens`] module shows how to write your own sink.
103//!
104//! ```
105//! use exarmo_aarch64::{Token, TokenKind, decode_word};
106//!
107//! // ldr x0, [x1, #8]
108//! let mut tokens: Vec<Token> = Vec::new();
109//! decode_word(0xf9400420).unwrap().at(0).write_tokens(&mut tokens).unwrap();
110//!
111//! let kinds: Vec<_> = tokens.iter().map(|t| (t.kind, t.operand, t.text.as_str())).collect();
112//! assert_eq!(
113//!     kinds,
114//!     [
115//!         (TokenKind::Mnemonic, None, "ldr"),
116//!         (TokenKind::Text, None, "\t"),
117//!         (TokenKind::Register, Some(0), "x0"),
118//!         (TokenKind::Separator, None, ", "),
119//!         (TokenKind::Bracket, Some(1), "["),
120//!         (TokenKind::Register, Some(1), "x1"),
121//!         (TokenKind::Text, Some(1), ", "),
122//!         (TokenKind::Text, Some(1), "#"),
123//!         (TokenKind::Immediate(8), Some(1), "0x8"),
124//!         (TokenKind::Bracket, Some(1), "]"),
125//!     ]
126//! );
127//! ```
128//!
129//! ### Flags and control flow
130//!
131//! [`Instruction::flags`] returns the condition flags an instruction writes
132//! and reads. [`InstructionAt::branch`] returns what it does to the flow of
133//! control, and for a direct branch, the address it branches to.
134//!
135//! ```
136//! use exarmo_aarch64::{BranchKind, Flags, decode_word};
137//!
138//! // cmp x0, #0x41
139//! let cmp = decode_word(0xf101041f).unwrap();
140//! assert_eq!(cmp.flags().writes, Flags::NZCV);
141//! assert!(cmp.flags().reads.is_empty());
142//!
143//! // b.ne #12
144//! let branch = decode_word(0x54000061).unwrap().at(0x1000).branch();
145//! assert_eq!(branch.kind, BranchKind::Direct);
146//! assert!(branch.conditional);
147//! assert_eq!(branch.target, Some(0x100c));
148//!
149//! // bl #64
150//! let call = decode_word(0x94000010).unwrap().at(0x1000).branch();
151//! assert_eq!(call.kind, BranchKind::DirectCall);
152//! assert_eq!(call.target, Some(0x1040));
153//!
154//! // ret
155//! let ret = decode_word(0xd65f03c0).unwrap().at(0x1000).branch();
156//! assert_eq!(ret.kind, BranchKind::Return);
157//! assert_eq!(ret.target, None);
158//! ```
159//!
160//! ### CONSTRAINED UNPREDICTABLE words
161//!
162//! For some words, the architecture permits the processor to execute the
163//! instruction or to do something else. Decoding one of these words returns
164//! the instruction, and [`Instruction::unpredictable`] returns true for it.
165//!
166//! ```
167//! use exarmo_aarch64::decode_word;
168//!
169//! // rcwsetp x0, x0, [sp], which names x0 for both registers of its pair
170//! let rcwsetp = decode_word(0x1920b3e0).unwrap();
171//! assert_eq!(rcwsetp.at(0).to_string(), "rcwsetp\tx0, x0, [sp]");
172//! assert!(rcwsetp.unpredictable());
173//! ```
174//!
175//! ### System registers and operations
176//!
177//! MRS and MSR take a [`SysReg`] operand, which gives the register's name
178//! where the architecture has one. AT, DC, IC and TLBI take a system
179//! operation, and MSR (immediate) a PSTATE field. Their operands refer to
180//! rows of [`SysOp::all`].
181//!
182//! ```
183//! use exarmo_aarch64::{Mnemonic, Operand, decode_word};
184//!
185//! // msr vbar_el3, x0
186//! let Operand::SysReg(register) = decode_word(0xd51ec000).unwrap().operands()[0] else {
187//!     unreachable!()
188//! };
189//! assert_eq!(register.name(), Some("vbar_el3"));
190//! assert!(register.is_write());
191//!
192//! // ic iallu
193//! let Operand::SysOp(operation) = decode_word(0xd508751f).unwrap().operands()[0] else {
194//!     unreachable!()
195//! };
196//! assert_eq!(operation.def().name, "iallu");
197//! assert_eq!(operation.def().instruction, Mnemonic::Ic);
198//! ```
199//!
200//! ### Intrinsics
201//!
202//! [`Instruction::intrinsics`] lists the ACLE Advanced SIMD intrinsics an
203//! instruction implements, and binds each argument to one of the
204//! instruction's operands.
205//!
206//! ```
207//! use exarmo_aarch64::{Output, Source, decode_word};
208//!
209//! // addp v0.8b, v1.8b, v0.8b
210//! let addp = decode_word(0x0e20bc20).unwrap();
211//! let vpadd = addp.intrinsics().iter().find(|i| i.name() == "vpadd_s8").unwrap();
212//! assert_eq!(vpadd.arguments, [Source::Operand(1), Source::Operand(2)]);
213//! assert_eq!(vpadd.result, Output::Operand(0));
214//! ```
215#![no_std]
216#![cfg_attr(docsrs, feature(doc_cfg))]
217#![deny(unsafe_code)]
218#![warn(missing_docs)]
219
220#[cfg(test)]
221extern crate alloc;
222
223mod bytes;
224/// The decoder, instruction model and tables generated from ARM's XML.
225pub mod generated;
226pub mod intrinsics;
227pub mod operands;
228pub mod rendering;
229pub mod tokens;
230mod types;
231
232pub mod sysops;
233pub use sysops::{RegisterAccess, RegisterUse, SysOp, SysOpRef};
234
235pub use bytes::{decode_bytes, disassemble};
236pub use exarmo_core::DecodeError;
237pub use exarmo_core::branch::{Branch, BranchEffect, BranchKind};
238pub use exarmo_core::flags::{FlagEffect, Flags};
239pub use generated::enums::*;
240pub use generated::{
241    Encoding, Instruction, InstructionAt, Mnemonic, ModifierKind, PROVENANCE, Provenance,
242    decode_word,
243};
244pub use intrinsics::{
245    Intrinsic, IntrinsicDef, IntrinsicType, IntrinsicTypeDef, Output, Source, TypeKind,
246};
247pub use operands::{
248    Mem, Modifier, Offset, Operand, Operands, PcRead, Reg, RegList, RegOperand, Symbol, Writeback,
249    ZaArray, ZaSlice,
250};
251pub use tokens::{Decoded, Hex, TokenKind, TokenSink};
252pub use types::{
253    Arrangement, BReg, DReg, DynRegSp, DynRegZr, DynScalarSimd, ElementWidth, GpReg, HReg, PNReg,
254    PReg, QReg, SReg, SysReg, SysRegDef, VReg, WRegSp, WRegZr, XRegSp, XRegZr, ZATile, ZReg,
255    ZaTileMask, ZaTileName,
256};
257
258#[cfg(feature = "alloc")]
259pub use tokens::Token;
260
261/// Decode the 32-bit AArch64 instruction word `bits`.
262#[deprecated(
263    since = "0.4.0",
264    note = "renamed to `decode_word`. Use `decode_bytes` to decode from a byte slice"
265)]
266#[inline]
267pub fn decode(bits: u32) -> Result<Instruction, DecodeError> {
268    decode_word(bits)
269}