Skip to main content

h8_asm/
lib.rs

1//! A decoder, disassembler, assembler and detour installer for the Renesas H8
2//! family (H8/300, H8/300H, H8S/2000, H8S/2600 and H8SX), operating on a flat
3//! big-endian `&[u8]` image where file offset and load address are the same
4//! number.
5//!
6//! [`isa::insn_len`], [`isa::decode_insn`], [`isa::encode_insn`] and
7//! [`isa::disassemble_insn`] cover all five targets through the legacy opcode
8//! maps and all 8,493 reviewed H8SX manual rows. The original narrow H8/300 and
9//! H8SX APIs remain available. [`Asm`], [`relocate`], [`detour`], [`image`] and
10//! [`analysis`] provide checked assembly, patch planning and conservative
11//! control-flow analysis. Delayed, PC-indexed and compound relative relocation
12//! is explicitly refused where safe rewriting cannot be established.
13//!
14//! Instruction-aware APIs require the core ([`Target`]) and operating mode
15//! ([`Mode`]). Both change what bytes mean and must come from the caller's
16//! knowledge of the firmware, not a guess from its byte patterns.
17//!
18//! ```
19//! use h8_asm::{isa, Mode, Target};
20//!
21//! let bytes = [0x0c, 0x89]; // MOV.B R0L,R1L
22//! let decoded = isa::decode_insn(&bytes, Target::H8_300, Mode::Normal).unwrap();
23//! assert_eq!(decoded.len, 2);
24//! assert_eq!(
25//!     isa::encode_insn(decoded.insn, Target::H8_300, Mode::Normal).unwrap(),
26//!     bytes
27//! );
28//! ```
29//!
30//! Every encoding claim in this crate cites its section in Renesas' software
31//! manuals under `spec/` (H8/300 ADE-602-025, H8/300H REJ09B0213, H8S
32//! REJ09B0139, H8SX REJ09B0102).
33
34#![forbid(unsafe_code)]
35#![deny(missing_docs)]
36
37pub mod analysis;
38pub mod asm;
39pub mod detour;
40pub mod image;
41pub mod isa;
42pub use image::{
43    find, find_free_space, insert, read_u16, read_u32, read_u8, write, CommandRecord, CommandTable,
44    ImageError, Needle, TableError,
45};
46pub mod relocate;
47pub use asm::Asm;
48
49/// The H8 core an image was written for.
50///
51/// Each generation is a superset of the one before it, so the same bytes can
52/// decode differently, or only decode at all, depending on the target. This
53/// is the same "confident wrong answer" risk that `thumb_asm::isa::Target`
54/// exists for.
55///
56/// `#[non_exhaustive]` so that adding a core, or splitting one (the H8SX
57/// manual notes product-specific differences), is not a breaking change.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59#[non_exhaustive]
60pub enum Target {
61    /// H8/300: 16-bit registers, 64 KB address space, no operating modes
62    /// (ADE-602-025).
63    H8_300,
64    /// H8/300H: adds the 32-bit `ERn` registers and normal/advanced modes
65    /// (REJ09B0213).
66    H8_300H,
67    /// H8S/2000: adds `EXR`, `LDM`/`STM` and `TAS` to the H8/300H set
68    /// (REJ09B0139).
69    H8S2000,
70    /// H8S/2600: H8S/2000 plus the multiply-accumulate (`MAC`) family
71    /// (REJ09B0139).
72    H8S2600,
73    /// H8SX: the superset, with four operating modes and the extended
74    /// addressing modes (REJ09B0102).
75    H8SX,
76}
77
78/// The CPU operating mode, which sets the width of the address space, of
79/// branch and call targets, of vector-table entries and of stacked `PC`s.
80///
81/// The mode is fixed by the chip's mode pins or its configuration and cannot be
82/// read from the image, so the caller has to state it. Guessing wrong corrupts
83/// every absolute address and every vector-table decode, not just a single
84/// instruction.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86#[non_exhaustive]
87pub enum Mode {
88    /// 64 KB address space, 16-bit branch addresses. This is the only mode
89    /// H8/300 has.
90    Normal,
91    /// H8SX only: 16 MB program area, 64 KB data area (H8SX §1.2.2).
92    Middle,
93    /// A 16 MB program area on every core that has this mode. The data area is
94    /// 16 MB on H8/300H (REJ09B0213 §1.1) and 4 GB on H8S (REJ09B0139 §1.2) and
95    /// H8SX (REJ09B0102 §1.2.3).
96    Advanced,
97    /// H8SX only: 4 GB program and data areas (H8SX §1.2.4).
98    Maximum,
99}
100
101impl Target {
102    /// Whether `mode` exists on this core.
103    ///
104    /// H8/300 has no modes and is treated as permanently [`Mode::Normal`].
105    /// H8/300H and H8S have normal and advanced modes (H8S REJ09B0139 §1.2).
106    /// H8SX has all four (REJ09B0102 §1.2).
107    ///
108    /// ```
109    /// use h8_asm::{Mode, Target};
110    /// assert!(Target::H8SX.supports(Mode::Maximum));
111    /// assert!(!Target::H8S2600.supports(Mode::Middle));
112    /// ```
113    pub fn supports(self, mode: Mode) -> bool {
114        match self {
115            Target::H8_300 => mode == Mode::Normal,
116            Target::H8_300H | Target::H8S2000 | Target::H8S2600 => {
117                matches!(mode, Mode::Normal | Mode::Advanced)
118            }
119            Target::H8SX => true,
120        }
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    const TARGETS: [Target; 5] = [
129        Target::H8_300,
130        Target::H8_300H,
131        Target::H8S2000,
132        Target::H8S2600,
133        Target::H8SX,
134    ];
135    const MODES: [Mode; 4] = [Mode::Normal, Mode::Middle, Mode::Advanced, Mode::Maximum];
136
137    /// The whole target × mode table, written out as a literal, so a change to
138    /// `supports` fails here rather than slipping through.
139    #[test]
140    fn mode_support_table() {
141        let expected = [
142            [true, false, false, false],
143            [true, false, true, false],
144            [true, false, true, false],
145            [true, false, true, false],
146            [true, true, true, true],
147        ];
148        for (t, row) in TARGETS.iter().zip(expected.iter()) {
149            for (m, &want) in MODES.iter().zip(row.iter()) {
150                assert_eq!(t.supports(*m), want, "{t:?} / {m:?}");
151            }
152        }
153    }
154}