Skip to main content

exarmo_aarch32/
lib.rs

1#![doc = include_str!("../README.md")]
2//!
3//! A32 and T32 decode to the same [`Instruction`] type, so code that reads
4//! instructions handles both instruction sets at once. The decoders in [`a32`]
5//! only return A32 encodings, and those in [`t32`] only return T32 encodings.
6//!
7//! ## Examples
8//!
9//! ### Decoding A32
10//!
11//! [`a32::disassemble`] returns an iterator over the instructions in a buffer
12//! of A32 code and their addresses. [`a32::decode_bytes`] decodes one
13//! instruction from a byte slice, and [`a32::decode_word`] one from a 32-bit
14//! word. For a word that is not an instruction, each returns a [`DecodeError`]
15//! that says why.
16//!
17//! ```
18//! use exarmo_aarch32::a32;
19//!
20//! // push {r4, lr}
21//! // bx lr
22//! let code = [0x10, 0x40, 0x2d, 0xe9, 0x1e, 0xff, 0x2f, 0xe1];
23//! let text: Vec<_> = a32::disassemble(&code, 0x1000)
24//!     .map(|(address, instruction)| instruction.unwrap().at(address).to_string())
25//!     .collect();
26//! assert_eq!(text, ["push\t{r4, lr}", "bx\tlr"]);
27//! ```
28//!
29//! ### Decoding T32
30//!
31//! A T32 instruction is 16 or 32 bits long. [`t32::disassemble`] and
32//! [`t32::decode_bytes`] read as many bytes as each instruction takes.
33//!
34//! A T32 decode also takes the IT state, as an instruction inside an IT block
35//! takes its condition from the block. [`t32::disassemble`] advances the state
36//! from one instruction to the next with [`ItState::after`], which assumes no
37//! branch intervenes.
38//!
39//! ```
40//! use exarmo_aarch32::{ItState, t32};
41//!
42//! // ite eq
43//! // moveq r0, #1
44//! // movne r0, #0
45//! // bx lr
46//! let code = [0x0c, 0xbf, 0x01, 0x20, 0x00, 0x20, 0x70, 0x47];
47//! let text: Vec<_> = t32::disassemble(&code, 0x1000, ItState::Outside)
48//!     .map(|(address, instruction)| instruction.unwrap().at(address).to_string())
49//!     .collect();
50//! assert_eq!(text, ["ite\teq", "moveq\tr0, #0x1", "movne\tr0, #0x0", "bx\tlr"]);
51//!
52//! // Outside a block, the same 16 bits decode as the flag-setting form.
53//! let movs = t32::decode_bytes(&[0x01, 0x20], ItState::Outside).unwrap();
54//! assert_eq!(movs.at(0).to_string(), "movs\tr0, #0x1");
55//! ```
56//!
57//! ### What an instruction is
58//!
59//! An [`Instruction`] is an enum with a variant for every encoding and alias
60//! the specification describes. Each variant holds the fields of its
61//! encoding. For example, `push {r4, lr}` decodes to `PushStmdbA1`. Its
62//! `cond` field is a [`Cond`], and its `registers` field is a [`RegList`].
63//!
64//! There are thousands of variants, so most code does not match on them.
65//! [`Instruction::encoding`] returns the variant as an [`Encoding`], a
66//! fieldless enum with a name for each. [`Instruction::mnemonic`] returns a
67//! [`Mnemonic`], which many encodings share. [`Instruction::operands`],
68//! below, reads the operands of any variant in one shape.
69//!
70//! ```
71//! use exarmo_aarch32::{Encoding, GpReg, Instruction, Mnemonic, Reg, a32};
72//!
73//! // push {r4, lr}
74//! let push = a32::decode_word(0xe92d4010).unwrap();
75//! let Instruction::PushStmdbA1 { registers, .. } = push else {
76//!     unreachable!()
77//! };
78//! assert_eq!(
79//!     registers.regs().collect::<Vec<_>>(),
80//!     [Reg::Core(GpReg::new(4)), Reg::Core(GpReg::new(14))]
81//! );
82//!
83//! assert_eq!(push.encoding(), Encoding::PushStmdbA1);
84//! assert_eq!(push.encoding().name(), "PushStmdbA1");
85//! assert_eq!(push.mnemonic(), Mnemonic::Push);
86//! assert_eq!(push.mnemonic().name(), "push");
87//! ```
88//!
89//! ### Operands
90//!
91//! [`Instruction::operands`] returns the operands in the order the assembly
92//! writes them, each an [`Operand`]. For an instruction that can be
93//! conditional, the first operand is its condition. It will be `al` when none
94//! is written. An instruction that is always unconditional, such as `bkpt` or
95//! an A32 Advanced SIMD instruction, has no condition operand. A register list
96//! is one operand, and a memory operand is a single value that holds its base,
97//! offset and writeback.
98//!
99//! ```
100//! use exarmo_aarch32::{Cond, GpReg, Mem, Offset, Operand, Reg, RegOperand, Writeback, a32};
101//!
102//! // push {r4, lr}
103//! let operands = a32::decode_word(0xe92d4010).unwrap().operands();
104//! let [Operand::Cond(Cond::Al), Operand::List(list)] = operands.as_slice() else {
105//!     unreachable!()
106//! };
107//! assert_eq!(
108//!     list.regs().collect::<Vec<_>>(),
109//!     [Reg::Core(GpReg::new(4)), Reg::Core(GpReg::new(14))]
110//! );
111//!
112//! // ldrne r0, [r1, #-8]
113//! let ldr = a32::decode_word(0x15110008).unwrap();
114//! assert_eq!(
115//!     ldr.operands().as_slice(),
116//!     [
117//!         Operand::Cond(Cond::Ne),
118//!         Operand::Reg(RegOperand::plain(Reg::Core(GpReg::new(0)))),
119//!         Operand::Mem(Mem {
120//!             base: Reg::Core(GpReg::new(1)),
121//!             offset: Offset::Imm { value: -8, subtract: true },
122//!             writeback: Writeback::None,
123//!             align: None,
124//!         }),
125//!     ]
126//! );
127//! ```
128//!
129//! ### Tokens
130//!
131//! [`InstructionAt::write_tokens`] writes the text to a [`TokenSink`] as
132//! tokens, each with its [`TokenKind`] and the index of the operand it is
133//! part of. Number tokens carry their values, so you never need to parse the
134//! text.
135//! The [`tokens`] module shows how to write your own sink.
136//!
137//! ```
138//! use exarmo_aarch32::{Token, TokenKind, a32};
139//!
140//! // addeq r2, r1, #4
141//! let mut tokens: Vec<Token> = Vec::new();
142//! a32::decode_word(0x02812004).unwrap().at(0).write_tokens(&mut tokens).unwrap();
143//!
144//! let kinds: Vec<_> = tokens.iter().map(|t| (t.kind, t.operand, t.text.as_str())).collect();
145//! assert_eq!(
146//!     kinds,
147//!     [
148//!         (TokenKind::Mnemonic, None, "add"),
149//!         (TokenKind::Mnemonic, Some(0), "eq"),
150//!         (TokenKind::Text, None, "\t"),
151//!         (TokenKind::Register, Some(1), "r2"),
152//!         (TokenKind::Separator, None, ", "),
153//!         (TokenKind::Register, Some(2), "r1"),
154//!         (TokenKind::Separator, None, ", "),
155//!         (TokenKind::Text, Some(3), "#"),
156//!         (TokenKind::Immediate(4), Some(3), "0x4"),
157//!     ]
158//! );
159//! ```
160//!
161//! ### Flags and control flow
162//!
163//! [`Instruction::flags`] returns the condition flags an instruction writes
164//! and reads. [`InstructionAt::branch`] returns what it does to the flow of
165//! control, and for a direct branch, the address it branches to. Any
166//! instruction that writes the PC is a branch, including a load such as
167//! `ldr pc, [r1]`.
168//!
169//! ```
170//! use exarmo_aarch32::{BranchKind, Flags, a32};
171//!
172//! // adds r2, r1, r3
173//! let adds = a32::decode_word(0xe0912003).unwrap();
174//! assert_eq!(adds.flags().writes, Flags::NZCV);
175//!
176//! // beq #16, which A32 reads from 8 bytes ahead
177//! let beq = a32::decode_word(0x0a000002).unwrap().at(0x1000).branch();
178//! assert_eq!(beq.kind, BranchKind::Direct);
179//! assert!(beq.conditional);
180//! assert_eq!(beq.target, Some(0x1010));
181//!
182//! // ldr pc, [r1]
183//! let jump = a32::decode_word(0xe591f000).unwrap().at(0x1000).branch();
184//! assert_eq!(jump.kind, BranchKind::Indirect);
185//!
186//! // ldr r0, [r1]
187//! let load = a32::decode_word(0xe5910000).unwrap().at(0x1000).branch();
188//! assert_eq!(load.kind, BranchKind::None);
189//! ```
190//!
191//! ### CONSTRAINED UNPREDICTABLE words
192//!
193//! For some words, the architecture permits the processor to execute the
194//! instruction or to do something else. Decoding one of these words returns
195//! the instruction, and [`Instruction::unpredictable`] returns true for it.
196//!
197//! ```
198//! use exarmo_aarch32::a32;
199//!
200//! // ldr r0, [r0], #4, which loads into the base it writes back
201//! let ldr = a32::decode_word(0xe4900004).unwrap();
202//! assert_eq!(ldr.at(0).to_string(), "ldr\tr0, [r0], #0x4");
203//! assert!(ldr.unpredictable());
204//! ```
205//!
206//! ### System registers
207//!
208//! [`Instruction::system_register`] returns the system register an MRC, MCR,
209//! MRRC or MCRR accesses. [`SysReg::name`] returns the architecture's name for
210//! it, where there is one.
211//!
212//! ```
213//! use exarmo_aarch32::a32;
214//!
215//! // mrc p15, #0, r0, c1, c0, #0
216//! let mrc = a32::decode_word(0xee110f10).unwrap();
217//! let register = mrc.system_register().unwrap();
218//! assert_eq!(register.name(), Some("sctlr"));
219//! assert!(!register.is_write());
220//! ```
221
222#![no_std]
223#![cfg_attr(docsrs, feature(doc_cfg))]
224#![deny(unsafe_code)]
225#![warn(missing_docs)]
226
227#[cfg(test)]
228extern crate alloc;
229
230pub mod a32;
231pub mod generated;
232pub mod operands;
233pub mod rendering;
234pub mod t32;
235pub mod tokens;
236mod types;
237
238pub use exarmo_core::DecodeError;
239pub use exarmo_core::branch::{Branch, BranchEffect, BranchKind};
240pub use exarmo_core::flags::{FlagEffect, Flags};
241pub use generated::enums::*;
242pub use generated::{
243    Cond, Encoding, Instruction, InstructionAt, Mnemonic, ModifierKind, PROVENANCE, Provenance,
244    SysRegSpace,
245};
246pub use operands::{
247    Lane, ListFile, Mem, Modifier, Offset, Operand, Operands, PcRead, Reg, RegList, RegOperand,
248    Symbol, Writeback,
249};
250pub use tokens::{Decoded, Hex, TokenKind, TokenSink};
251pub use types::{DReg, GpReg, ItState, QReg, SReg, Scalar, SysReg, SysRegDef};
252
253#[cfg(feature = "alloc")]
254pub use tokens::Token;