Skip to main content

sleigh/
runtime.rs

1//! Runtime decoding facade for compiled SLEIGH specifications.
2
3use std::{borrow::Cow, fmt};
4
5mod context;
6mod context_db;
7mod effects;
8mod pcode;
9mod refs;
10pub(crate) mod shape;
11pub(crate) mod walker;
12
13use self::pcode::{pcode_ast_for_instance, stream_instance};
14use crate::{
15    builder::SymbolId,
16    instance::ConstructorInstance,
17    objects::{
18        field::{FieldId, FieldParent, FieldTableId},
19        table::TableId,
20    },
21    register_map::RegisterSlice,
22    semantics::{EmitError, InstructionInfo, PcodeAst, SemanticsSink},
23    spec::Spec,
24    token::{BitRangeFieldId, TokenContext},
25};
26pub use context::{Context, ContextBytes, ContextError};
27pub use context_db::ContextDatabase;
28pub use effects::{ContextEffect, ContextScope};
29use pcode_types::{
30    BitRangeInfo, InstructionPcode, PcodeLoweringContext, PcodeOp, PcodePlan, PcodeSink,
31    RegisterId, SpaceId, Varnode, lower_instruction, lower_instruction_into,
32};
33pub use refs::{FieldRef, RegisterRef, SpaceRef, SymbolKind, SymbolRef, TableRef, TokenRef};
34use serde::{Deserialize, Serialize};
35pub use shape::{Exclusion, ParamField, RegisterField, Shape};
36use walker::Walker;
37
38pub use walker::{DecodeError, DelaySlotError};
39
40/// Supplies compiled-SLEIGH storage metadata to the generic flat p-code
41/// lowerer. Kept private so SLEIGH remains only a producer of that metadata.
42pub(crate) struct InstructionPcodeContext<'a> {
43    spec: &'a Spec,
44}
45
46impl<'a> InstructionPcodeContext<'a> {
47    pub(crate) fn new(spec: &'a Spec) -> Self {
48        Self { spec }
49    }
50}
51
52impl PcodeLoweringContext for InstructionPcodeContext<'_> {
53    fn default_space(&self) -> SpaceId {
54        self.spec.default_space
55    }
56
57    fn unique_space(&self) -> SpaceId {
58        self.spec.unique_space
59    }
60
61    fn register_varnode(&self, id: RegisterId) -> Option<Varnode> {
62        (usize::from(id) < self.spec.registers.len()).then(|| {
63            let register = &self.spec.registers[id];
64            Varnode::new(register.space, register.offset as u64, register.size)
65        })
66    }
67
68    fn bitrange_info(&self, id: BitRangeFieldId) -> Option<BitRangeInfo> {
69        if usize::from(id) >= self.spec.bitranges.len() {
70            return None;
71        }
72        let bitrange = &self.spec.bitranges[id];
73        if usize::from(bitrange.register) >= self.spec.registers.len() {
74            return None;
75        }
76        let register = &self.spec.registers[bitrange.register];
77        Some(BitRangeInfo {
78            storage: Varnode::new(register.space, register.offset as u64, register.size),
79            start: bitrange.offset(),
80            size: bitrange.size(),
81        })
82    }
83
84    fn address_size(&self, space: SpaceId) -> Option<usize> {
85        (usize::from(space) < self.spec.spaces.len()).then(|| self.spec.spaces[space].addr_size)
86    }
87}
88
89/// The identity of a compiled specification's content.
90///
91/// A fingerprint is a digest of everything a compilation depends on: the
92/// specification's source text as the preprocessor delivered it to the parser
93/// — every included file, every `$(NAME)` expansion and every conditional
94/// already resolved, so the defines are in — and the version of this crate,
95/// whose compiler turned that text into the specification. Compiling the
96/// same text with the same compiler yields the same fingerprint, in any
97/// process and at any time; any change to the text or the compiler yields a
98/// different one. It is computed once, when the specification is compiled,
99/// and travels with the serialized specification, so a precompiled
100/// specification carries the fingerprint of the build that made it.
101///
102/// It is what a consumer stamps on state derived from a specification — a
103/// lifter's register map, a module built for an architecture — to establish
104/// later that another specification is *the same one*, rather than one that
105/// merely looks alike. It says nothing about decode configuration: the
106/// default processor context ([`CompiledSpec::set_context_bytes`]) is not
107/// part of it, since it changes what an instruction decodes to, not what the
108/// specification is.
109///
110/// The digest is 128-bit FNV-1a. It is not a cryptographic commitment; it
111/// distinguishes specifications that differ, which is all provenance needs.
112#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
113pub struct SpecFingerprint(u128);
114
115impl SpecFingerprint {
116    const FNV_OFFSET: u128 = 0x6c62_272e_07bb_0142_62b8_2175_6295_c58d;
117    const FNV_PRIME: u128 = 0x0000_0000_0100_0000_0000_0000_0000_013b;
118
119    /// Digests the preprocessed source text a compilation consumed, under the
120    /// compiler version doing it.
121    pub(crate) fn of_compilation(preprocessed: &str) -> Self {
122        let mut hash = Self::FNV_OFFSET;
123        let mut absorb = |bytes: &[u8]| {
124            for &byte in bytes {
125                hash ^= u128::from(byte);
126                hash = hash.wrapping_mul(Self::FNV_PRIME);
127            }
128        };
129        let version = env!("CARGO_PKG_VERSION");
130        absorb(&(version.len() as u64).to_le_bytes());
131        absorb(version.as_bytes());
132        absorb(&(preprocessed.len() as u64).to_le_bytes());
133        absorb(preprocessed.as_bytes());
134        Self(hash)
135    }
136
137    /// The digest as a number, for a consumer that stores it in state of
138    /// its own.
139    pub const fn as_u128(self) -> u128 {
140        self.0
141    }
142
143    /// A fingerprint a consumer stored with [`as_u128`](Self::as_u128).
144    pub const fn from_u128(digest: u128) -> Self {
145        Self(digest)
146    }
147}
148
149impl fmt::Debug for SpecFingerprint {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        write!(f, "SpecFingerprint({self})")
152    }
153}
154
155impl fmt::Display for SpecFingerprint {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        write!(f, "{:032x}", self.0)
158    }
159}
160
161/// A compiled SLEIGH specification.
162#[derive(Serialize, Deserialize)]
163pub struct CompiledSpec {
164    spec: Spec,
165    context_len: crate::Size,
166    context_bytes: ContextBytes,
167    fingerprint: SpecFingerprint,
168}
169
170impl CompiledSpec {
171    /// Constructors whose p-code has a local variable with no width, and that
172    /// nothing a decode can supply one for.
173    ///
174    /// A SLEIGH local takes its width from its uses. When none of them gives
175    /// one — the name was never declared, or every use is a width-less literal
176    /// — the body cannot be lowered, and no encoding of that constructor can
177    /// change it. Widths are resolved when the specification is compiled, so
178    /// this is a property of the specification rather than of a decode, and a
179    /// tool that compiles a specification should report it there.
180    ///
181    /// Each item is the constructor's source file, its byte range in that
182    /// file, and how many of its locals are unsizable.
183    pub fn unsized_locals(&self) -> impl Iterator<Item = (crate::FileId, usize, usize, usize)> {
184        self.spec.trees.iter().flat_map(|tree| {
185            tree.constructors
186                .iter()
187                .filter(|constructor| !constructor.pmacro.unsized_locals.is_empty())
188                .map(|constructor| {
189                    let src = constructor.src;
190                    (
191                        crate::FileId::from_index(src.file as usize),
192                        src.start as usize,
193                        src.end as usize,
194                        constructor.pmacro.unsized_locals.len(),
195                    )
196                })
197                .collect::<Vec<_>>()
198        })
199    }
200
201    pub(crate) fn from_spec(spec: Spec, fingerprint: SpecFingerprint) -> Self {
202        let context_len = spec.context_len() as crate::Size;
203        Self {
204            spec,
205            context_len,
206            context_bytes: ContextBytes {
207                bytes: vec![0; context_len as usize],
208            },
209            fingerprint,
210        }
211    }
212
213    /// The identity of this specification's content; see [`SpecFingerprint`].
214    pub fn fingerprint(&self) -> SpecFingerprint {
215        self.fingerprint
216    }
217
218    fn context_len(&self) -> usize {
219        self.context_len as usize
220    }
221
222    /// The internal compiled specification, for in-crate consumers such as
223    /// [`crate::introspect`] and [`crate::annotate`].
224    pub(crate) fn inner(&self) -> &Spec {
225        &self.spec
226    }
227
228    /// Creates a zero-initialized processor context for this specification.
229    pub fn new_context(&self) -> ContextBytes {
230        self.context_bytes.clone()
231    }
232
233    /// Replaces the default processor context this specification decodes with.
234    ///
235    /// # Errors
236    ///
237    /// Returns [`ContextError::InvalidLength`] if `context_bytes` is not the
238    /// length this specification's context registers require — a buffer built
239    /// with [`ContextBytes::from_raw`] carries no such guarantee.
240    pub fn set_context_bytes(&mut self, context_bytes: ContextBytes) -> Result<(), ContextError> {
241        self.validate_context(&context_bytes)?;
242        self.context_bytes = context_bytes;
243        Ok(())
244    }
245
246    /// Sets a named context field in an owned context buffer.
247    pub fn set_context_field(
248        &self,
249        context: &mut ContextBytes,
250        field: FieldId,
251        value: u64,
252    ) -> Result<(), ContextError> {
253        self.validate_context(context)?;
254
255        if usize::from(field) >= self.spec.fields.len() {
256            return Err(ContextError::UnknownField { field });
257        }
258        let field_ref = self.spec.fields.get(field);
259
260        if field_ref.parent != FieldParent::Context {
261            return Err(ContextError::NotContextField { field });
262        }
263
264        let width = field_ref.width();
265        if width < u64::BITS as usize && value >= (1u64 << width) {
266            return Err(ContextError::ValueOutOfRange {
267                field,
268                width,
269                value,
270            });
271        }
272
273        self.spec
274            .set_context_field(context.as_mut_bytes(), field, value);
275        Ok(())
276    }
277
278    fn validate_context(&self, context: &ContextBytes) -> Result<(), ContextError> {
279        let expected = self.context_len();
280        let actual = context.len();
281        if actual == expected {
282            Ok(())
283        } else {
284            Err(ContextError::InvalidLength { expected, actual })
285        }
286    }
287
288    /// Looks up a register by name.
289    pub fn register(&self, name: &str) -> Option<RegisterRef<'_>> {
290        self.spec
291            .get_register_by_name(name)
292            .map(|register| RegisterRef::new(register.id, register.inner))
293    }
294
295    /// Iterates over registers in stable registry order.
296    pub fn registers(&self) -> impl Iterator<Item = RegisterRef<'_>> {
297        self.spec
298            .registers
299            .iter()
300            .map(|register| RegisterRef::new(register.id, register.inner))
301    }
302
303    /// The registers an `attach variables` table binds to a field's values,
304    /// by value — the table a [`RegisterField`] indexes. `None` where the
305    /// table binds no register (`_`); a value past the end has none either.
306    pub fn attached_registers(&self, table: FieldTableId) -> &[Option<RegisterId>] {
307        self.spec.field_tables.register_table(table)
308    }
309
310    /// The varnode register `id` is declared at: its space, offset and
311    /// size. The inverse of [`register_at`](Self::register_at).
312    pub fn register_varnode(&self, id: RegisterId) -> Option<Varnode> {
313        (usize::from(id) < self.spec.registers.len()).then(|| {
314            let register = &self.spec.registers[id];
315            Varnode::new(register.space, register.offset as u64, register.size)
316        })
317    }
318
319    /// The register declared at exactly `varnode`: same space, offset and
320    /// size.
321    pub fn register_at(&self, varnode: Varnode) -> Option<RegisterId> {
322        self.spec.register_map.at(varnode)
323    }
324
325    /// `varnode` as a slice of the widest register that wholly contains it:
326    /// `AH` is byte 1 of `RAX`, `XMM0` is the low 16 bytes of `ZMM0`.
327    /// `None` when no register contains it, which includes every varnode
328    /// outside a register space and any spanning two registers. See
329    /// [`RegisterSlice`] for what the slice does and does not say.
330    pub fn enclosing_register(&self, varnode: Varnode) -> Option<RegisterSlice> {
331        self.spec.register_map.enclosing(varnode)
332    }
333
334    /// Every register sharing at least one byte with `varnode`, in offset
335    /// order, widest first among registers at the same offset: for `AH`,
336    /// `RAX`, `EAX`, `AX` and `AH` itself.
337    pub fn overlapping_registers(&self, varnode: Varnode) -> impl Iterator<Item = RegisterId> + '_ {
338        self.spec.register_map.overlapping(varnode)
339    }
340
341    /// Looks up a field by name.
342    pub fn field(&self, name: &str) -> Option<FieldRef<'_>> {
343        self.spec
344            .get_field_by_name(name)
345            .map(|field| FieldRef::new(field.id, field.inner))
346    }
347
348    /// Looks up a token by name.
349    pub fn token(&self, name: &str) -> Option<TokenRef<'_>> {
350        self.spec
351            .get_token_by_name(name)
352            .map(|token| TokenRef::new(token.id, token.inner))
353    }
354
355    /// Looks up a constructor table by name.
356    pub fn table(&self, name: &str) -> Option<TableRef<'_>> {
357        if let Some(&SymbolId::Table(id)) = self.spec.symbols.get(name) {
358            Some(TableRef::new(id, &self.spec.trees[id.into()]))
359        } else {
360            None
361        }
362    }
363
364    /// Looks up a memory space by name.
365    pub fn space(&self, name: &str) -> Option<SpaceRef<'_>> {
366        if let Some(&SymbolId::Space(id)) = self.spec.symbols.get(name) {
367            Some(SpaceRef::new(id, &self.spec.spaces[id]))
368        } else {
369            None
370        }
371    }
372
373    /// Iterates over public symbols known to the compiled spec.
374    pub fn symbols(&self) -> impl Iterator<Item = SymbolRef<'_>> {
375        self.spec.symbols.iter().map(|(name, &kind)| SymbolRef {
376            name: name.as_ref(),
377            kind: SymbolKind::from(kind),
378        })
379    }
380
381    /// Returns the parent kind for a named token/context field.
382    pub fn field_parent(&self, name: &str) -> Option<FieldParent> {
383        if let Some(&SymbolId::Field(id)) = self.spec.symbols.get(name) {
384            Some(self.spec.fields[id].parent)
385        } else {
386            None
387        }
388    }
389
390    /// Returns the bit start position for a named token/context field.
391    pub fn field_start(&self, name: &str) -> Option<usize> {
392        if let Some(&SymbolId::Field(id)) = self.spec.symbols.get(name) {
393            Some(self.spec.fields[id].range.start())
394        } else {
395            None
396        }
397    }
398
399    /// Returns the name of the parent token for a named token field.
400    pub fn field_token_name(&self, name: &str) -> Option<&str> {
401        if let Some(&SymbolId::Field(id)) = self.spec.symbols.get(name)
402            && let FieldParent::Token(tok_id) = self.spec.fields[id].parent
403        {
404            return Some(self.spec.token_name(tok_id));
405        }
406        None
407    }
408
409    /// Returns (offset_bits, size_bits) for a named bitrange field.
410    pub fn bitrange_bits(&self, name: &str) -> Option<(usize, usize)> {
411        if let Some(&SymbolId::BitRangeField(id)) = self.spec.symbols.get(name) {
412            let br = &self.spec.bitranges[id];
413            Some((br.offset(), br.size()))
414        } else {
415            None
416        }
417    }
418
419    /// The space that bare addresses in this specification refer to.
420    pub fn default_space(&self) -> SpaceId {
421        self.spec.default_space
422    }
423
424    /// Iterates over memory spaces in stable registry order.
425    ///
426    /// The iteration order matches the [`SpaceId`] numbering, so a consumer can
427    /// rebuild an equivalently-keyed collection by collecting in order.
428    pub fn spaces(&self) -> impl Iterator<Item = SpaceRef<'_>> {
429        self.spec
430            .spaces
431            .iter()
432            .map(|space| SpaceRef::new(space.id, space.inner))
433    }
434
435    /// Iterates over user-defined p-code op names in stable registry order.
436    ///
437    /// These are the `define pcodeop` names; their position is the
438    /// `PCodeOpId` used by [`PcodeAst`] call statements.
439    pub fn pcode_ops(&self) -> impl Iterator<Item = &str> {
440        self.spec.pcode_ops.iter().map(|op| &**op.inner)
441    }
442
443    /// Returns `(parent register, byte start, byte size)` for a bit-range field.
444    pub fn bitrange_info(&self, id: BitRangeFieldId) -> Option<(RegisterId, usize, usize)> {
445        if usize::from(id) >= self.spec.bitranges.len() {
446            return None;
447        }
448        let field = self.spec.bitranges.get(id);
449        Some((field.register, field.offset() / 8, field.size().div_ceil(8)))
450    }
451
452    pub(crate) fn spec(&self) -> &Spec {
453        &self.spec
454    }
455}
456
457impl fmt::Debug for CompiledSpec {
458    /// A summary, not a dump: a compiled specification holds every constructor
459    /// of every table and printing it in full is unreadable and slow.
460    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461        f.debug_struct("CompiledSpec")
462            .field("tables", &self.spec.trees.len())
463            .field("registers", &self.spec.registers.len())
464            .field("spaces", &self.spec.spaces.len())
465            .field("context_len", &self.context_len())
466            .finish_non_exhaustive()
467    }
468}
469
470/// Decoder for a compiled SLEIGH specification.
471pub struct Decoder<'spec> {
472    spec: &'spec CompiledSpec,
473}
474
475impl<'spec> Decoder<'spec> {
476    /// Creates a decoder for `spec`.
477    pub fn new(spec: &'spec CompiledSpec) -> Self {
478        Self { spec }
479    }
480
481    /// Decodes one instruction at `addr` from `bytes`.
482    ///
483    /// # Errors
484    ///
485    /// Returns a [`DecodeError`]: [`NoMatch`] if no constructor matches the
486    /// bytes (including when they run out mid-instruction), [`InvalidContext`]
487    /// if `context` is not this specification's context length,
488    /// [`InvalidAction`] if a disassembly action divides by zero or shifts past
489    /// the word width, and [`AmbiguousMatch`] if several constructors match and
490    /// none is more specific.
491    ///
492    /// [`NoMatch`]: DecodeError::NoMatch
493    /// [`InvalidContext`]: DecodeError::InvalidContext
494    /// [`InvalidAction`]: DecodeError::InvalidAction
495    /// [`AmbiguousMatch`]: DecodeError::AmbiguousMatch
496    ///
497    /// Decoding is pure: `context` is read, never written. An instruction that
498    /// wants to change it for later instructions says so through
499    /// [`Instruction::context_effects`], and [`ContextDatabase`] is the opt-in
500    /// store that feeds those back.
501    ///
502    /// ```
503    /// # use sleigh::{Compiler, Decoder, SourceDb};
504    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
505    /// # let mut sources = SourceDb::new();
506    /// # let root = sources.add_file("tiny.slaspec", "define endian=little;
507    /// #     define space ram type=ram_space size=4 default;
508    /// #     define space register type=register_space size=4;
509    /// #     define register offset=0 size=4 [ r0 ];
510    /// #     define token instr(8) op=(0,7);
511    /// #     :inc is op=1 { r0 = r0 + 1; }");
512    /// # let spec = Compiler::new(&mut sources).compile(root)?;
513    /// let decoder = Decoder::new(&spec);
514    /// let context = spec.new_context();
515    ///
516    /// // `bytes` is the stream from `addr` on; only what the instruction
517    /// // needs is read, and the rest is left for the next call.
518    /// let instruction = decoder.decode_one(0x1000, &[1, 1, 1], &context)?;
519    /// assert_eq!(instruction.display()?, "inc");
520    /// assert_eq!(instruction.len(), 1);
521    /// assert_eq!(instruction.next_address(), 0x1001);
522    /// # Ok(())
523    /// # }
524    /// ```
525    pub fn decode_one<'bytes>(
526        &self,
527        addr: u64,
528        bytes: &'bytes [u8],
529        context: &ContextBytes,
530    ) -> Result<Instruction<'spec, 'bytes>, DecodeError> {
531        self.spec
532            .validate_context(context)
533            .map_err(|_| DecodeError::InvalidContext)?;
534        let instance = Walker::try_get(
535            addr,
536            bytes,
537            &self.spec.spec,
538            self.spec.context_len(),
539            context.as_bytes(),
540        )?;
541        if instance.size > bytes.len() {
542            return Err(DecodeError::InternalInvariant);
543        }
544        // Covers the delay slot as well, so `Instruction::delay_slots` can hand
545        // each delayed instruction its own bytes. `Instruction::bytes` still
546        // returns only this instruction's.
547        let consumed = instance.size + instance.delay_slot_len;
548        if consumed > bytes.len() {
549            return Err(DecodeError::InternalInvariant);
550        }
551        let raw_bytes = Cow::Borrowed(&bytes[..consumed]);
552        Ok(Instruction {
553            spec: self.spec,
554            instance,
555            raw_bytes,
556        })
557    }
558
559    /// [`decode_one`](Self::decode_one), also reporting the instruction's
560    /// [`Shape`]: which bits chose its constructors and which fields are
561    /// its parameters. Costs a little more than a plain decode.
562    ///
563    /// Two encodings of one shape — equal after masking, whatever their
564    /// parameters — decode to the same constructors and operand layout
565    /// under the same context, so per-encoding work can be shared across
566    /// them; see [`Shape`].
567    pub fn decode_one_shaped<'bytes>(
568        &self,
569        addr: u64,
570        bytes: &'bytes [u8],
571        context: &ContextBytes,
572    ) -> Result<(Instruction<'spec, 'bytes>, Shape), DecodeError> {
573        self.spec
574            .validate_context(context)
575            .map_err(|_| DecodeError::InvalidContext)?;
576        let recorder = shape::ShapeRecorder::default();
577        let instance = Walker::try_get_shaped(
578            addr,
579            bytes,
580            &self.spec.spec,
581            self.spec.context_len(),
582            context.as_bytes(),
583            &recorder,
584        )?;
585        let consumed = instance.size + instance.delay_slot_len;
586        if consumed > bytes.len() {
587            return Err(DecodeError::InternalInvariant);
588        }
589        let shape = recorder.finish(instance.size);
590        let raw_bytes = Cow::Borrowed(&bytes[..consumed]);
591        Ok((
592            Instruction {
593                spec: self.spec,
594                instance,
595                raw_bytes,
596            },
597            shape,
598        ))
599    }
600}
601
602/// A constructor selected while decoding an [`Instruction`].
603///
604/// SLEIGH instruction patterns recursively enter operand tables, so one encoded
605/// instruction usually selects more than its top-level constructor. This value
606/// identifies one entry in that complete selected-constructor path.
607pub struct ConstructorMatch<'spec> {
608    table: TableRef<'spec>,
609    index: usize,
610}
611
612impl<'spec> ConstructorMatch<'spec> {
613    fn from_instance(spec: &'spec CompiledSpec, instance: &ConstructorInstance) -> Self {
614        let table_id = TableId::from(usize::from(instance.tree));
615        Self {
616            table: TableRef::new(table_id, &spec.spec.trees[instance.tree]),
617            index: instance.id.into(),
618        }
619    }
620
621    /// Table containing the selected constructor.
622    pub fn table(&self) -> &TableRef<'spec> {
623        &self.table
624    }
625
626    /// Zero-based index of the selected constructor within [`table`](Self::table).
627    pub fn index(&self) -> usize {
628        self.index
629    }
630}
631
632/// Decoded instruction plus access to its compiled specification.
633#[derive(Clone)]
634pub struct Instruction<'spec, 'bytes> {
635    spec: &'spec CompiledSpec,
636    instance: ConstructorInstance,
637    raw_bytes: Cow<'bytes, [u8]>,
638}
639
640impl<'spec, 'bytes> Instruction<'spec, 'bytes> {
641    /// Instruction address.
642    pub fn address(&self) -> u64 {
643        self.instance.inst_start
644    }
645
646    /// Address immediately after this instruction *and its delay slot*.
647    ///
648    /// This is SLEIGH's semantic `inst_next` (manual §7.11): the delay-slot
649    /// bytes belong to this instruction's p-code, so control resumes past them.
650    /// A listing walker that wants the next *encoded* instruction and intends
651    /// to render the delayed ones itself should use
652    /// [`address`](Self::address)` + `[`len`](Self::len) instead; stepping by
653    /// `next_address` skips them, which is correct for a lifter and wrong for a
654    /// disassembly view.
655    pub fn next_address(&self) -> u64 {
656        self.instance.semantic_inst_next()
657    }
658
659    /// Length of this instruction alone, in bytes, excluding its delay slot.
660    pub fn len(&self) -> usize {
661        self.instance.size
662    }
663
664    /// Total length of the instructions filling this one's delay slot.
665    ///
666    /// Zero for everything but a delay-slot branch on MIPS, SPARC, SuperH and
667    /// friends.
668    pub fn delay_slot_len(&self) -> usize {
669        self.instance.delay_slot_len
670    }
671
672    /// The instructions filling this one's delay slot, in address order.
673    ///
674    /// Their p-code is already spliced into
675    /// [`pcode_ast`](Self::pcode_ast) at the point the `delayslot` directive
676    /// sits, so a lifter does not need these — a disassembly listing does.
677    pub fn delay_slots(&self) -> impl Iterator<Item = Instruction<'spec, '_>> + '_ {
678        let mut offset = self.instance.size;
679        self.instance.delay_slots.iter().map(move |delayed| {
680            let start = offset;
681            offset += delayed.size;
682            Instruction {
683                spec: self.spec,
684                instance: delayed.clone(),
685                raw_bytes: Cow::Borrowed(&self.raw_bytes[start..offset]),
686            }
687        })
688    }
689
690    /// Returns true when the instruction has zero encoded bytes.
691    pub fn is_empty(&self) -> bool {
692        self.len() == 0
693    }
694
695    /// Encoded bytes of this instruction, excluding its delay slot.
696    pub fn bytes(&self) -> &[u8] {
697        &self.raw_bytes[..self.len()]
698    }
699
700    /// Compiled specification that decoded this instruction.
701    pub fn spec(&self) -> &'spec CompiledSpec {
702        self.spec
703    }
704
705    /// Constructor table that produced this instruction.
706    pub fn constructor_table(&self) -> TableRef<'spec> {
707        TableRef::new(
708            TableId::from(usize::from(self.instance.tree)),
709            &self.spec.spec.trees[self.instance.tree],
710        )
711    }
712
713    /// Index of the matched constructor within its table.
714    pub fn constructor_index(&self) -> usize {
715        self.instance.id.into()
716    }
717
718    /// Number of decoded operand values attached to the matched constructor.
719    pub fn operand_count(&self) -> usize {
720        self.instance.operand_values.len()
721    }
722
723    /// Iterates over every constructor selected while decoding this instruction.
724    ///
725    /// The root instruction constructor is first, followed recursively by
726    /// constructors selected from operand tables. Constructors of decoded delay
727    /// slots are included after the root instruction's operand path.
728    pub fn constructor_matches(&self) -> impl Iterator<Item = ConstructorMatch<'spec>> + '_ {
729        fn collect<'a>(
730            instance: &'a ConstructorInstance,
731            matches: &mut Vec<&'a ConstructorInstance>,
732        ) {
733            matches.push(instance);
734            for operand in &instance.operand_values {
735                if let crate::instance::OperandValue::Constructor(child) = operand {
736                    collect(child, matches);
737                }
738            }
739            for delay_slot in &instance.delay_slots {
740                collect(delay_slot, matches);
741            }
742        }
743
744        let mut matches = Vec::new();
745        collect(&self.instance, &mut matches);
746        matches
747            .into_iter()
748            .map(move |instance| ConstructorMatch::from_instance(self.spec, instance))
749    }
750
751    /// Context changes this instruction's disassembly actions request.
752    ///
753    /// Empty for the vast majority of instructions. Decoding is pure, so a
754    /// caller that wants these to affect later decodes has to remember them —
755    /// [`ContextDatabase`] does that.
756    pub fn context_effects(&self) -> &[ContextEffect] {
757        &self.instance.context_effects
758    }
759
760    /// Renders the SLEIGH display string for this instruction.
761    ///
762    /// # Errors
763    ///
764    /// Returns [`DecodeError::UnresolvedDisplay`] if the matched constructor's
765    /// display references a sub-table or field this decode supplies no value
766    /// for, or an attach-table entry that is out of range or unattached.
767    pub fn display(&self) -> Result<String, DecodeError> {
768        self.instance.try_to_string(&self.spec.spec)
769    }
770
771    /// Returns the backend-neutral p-code AST for this instruction.
772    ///
773    /// # Errors
774    ///
775    /// Returns an [`EmitError`] if the matched constructor's semantics cannot
776    /// be expanded — an unresolvable operand, or a construct this crate does
777    /// not yet lower.
778    ///
779    /// The AST is owned and borrows nothing from this instruction or its
780    /// specification, so it outlives both. See the [`semantics`](crate::semantics)
781    /// module for the type graph and what has already been expanded away.
782    ///
783    /// ```
784    /// # use sleigh::{Compiler, Decoder, SourceDb};
785    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
786    /// # let mut sources = SourceDb::new();
787    /// # let root = sources.add_file("tiny.slaspec", "define endian=little;
788    /// #     define space ram type=ram_space size=4 default;
789    /// #     define space register type=register_space size=4;
790    /// #     define register offset=0 size=4 [ r0 ];
791    /// #     define token instr(8) op=(0,7);
792    /// #     :inc is op=1 { r0 = r0 + 1; }");
793    /// # let spec = Compiler::new(&mut sources).compile(root)?;
794    /// let instruction = Decoder::new(&spec)
795    ///     .decode_one(0x1000, &[1], &spec.new_context())?;
796    ///
797    /// let ast = instruction.pcode_ast()?;
798    /// assert_eq!(ast.pretty_print(&spec), "r0 = (r0 + 1);");
799    /// # Ok(())
800    /// # }
801    /// ```
802    pub fn pcode_ast(&self) -> Result<PcodeAst, EmitError> {
803        pcode_ast_for_instance(&self.spec.spec, &self.instance)
804    }
805
806    /// Returns raw Ghidra-style flat p-code operations for this instruction.
807    ///
808    /// This lowers the fully expanded [`PcodeAst`] returned by
809    /// [`pcode_ast`](Self::pcode_ast), allocating instruction-local temporaries
810    /// in the compiled specification's real unique space.
811    pub fn pcode_ops(&self) -> Result<InstructionPcode, EmitError> {
812        let ast = self.pcode_ast()?;
813        lower_instruction(&ast, &InstructionPcodeContext::new(&self.spec.spec))
814            .map_err(|error| EmitError::new(error.to_string()))
815    }
816
817    /// Lowers flat p-code into `sink` without returning an owned
818    /// [`InstructionPcode`].
819    ///
820    /// This is the production-path counterpart to [`pcode_ops`](Self::pcode_ops):
821    /// consumers can synchronously lower the resolved p-code while it remains
822    /// internal to this call. `pcode_ops` remains available for inspection,
823    /// serialization, and differential tests.
824    pub fn pcode_ops_into<R>(&self, sink: impl FnOnce(&[PcodeOp]) -> R) -> Result<R, EmitError> {
825        let ast = self.pcode_ast()?;
826        lower_instruction_into(&ast, &InstructionPcodeContext::new(&self.spec.spec), sink)
827            .map_err(|error| EmitError::new(error.to_string()))
828    }
829
830    /// Plans this instruction's flat p-code, then streams it into a sink.
831    ///
832    /// `make_sink` receives the [`PcodePlan`] — the labels and the branch and
833    /// call destinations of the whole instruction — so a consumer can prepare
834    /// its instruction-wide state before any operation arrives, and never has
835    /// to re-scan a flat p-code vector. The sink is returned so the consumer
836    /// can recover its result.
837    ///
838    /// This is the production path: it plans and emits straight from the
839    /// resolved semantics, and never builds the [`PcodeAst`] that
840    /// [`pcode_ops`](Self::pcode_ops) lowers. The operations are the same.
841    pub fn pcode_ops_streamed<S: PcodeSink>(
842        &self,
843        make_sink: impl FnOnce(&PcodePlan) -> S,
844    ) -> Result<S, EmitError> {
845        self.try_pcode_ops_streamed(|plan| Ok(make_sink(plan)))
846    }
847
848    /// [`pcode_ops_streamed`](Self::pcode_ops_streamed) for a consumer whose
849    /// preparation can fail: resolving the plan's destinations may be refused
850    /// by the module it lowers into, and then nothing is streamed.
851    pub fn try_pcode_ops_streamed<S: PcodeSink, E: From<EmitError>>(
852        &self,
853        make_sink: impl FnOnce(&PcodePlan) -> Result<S, E>,
854    ) -> Result<S, E> {
855        stream_instance(&self.spec.spec, &self.instance, make_sink)
856    }
857
858    /// Alias for [`pcode_ops`](Self::pcode_ops).
859    pub fn instruction_pcode(&self) -> Result<InstructionPcode, EmitError> {
860        self.pcode_ops()
861    }
862
863    /// Emits backend-neutral semantics into `sink`.
864    ///
865    /// # Errors
866    ///
867    /// Returns an [`EmitError`] if the p-code AST cannot be built (see
868    /// [`Instruction::pcode_ast`]) or if `sink` rejects it.
869    pub fn emit_into<S: SemanticsSink>(&self, sink: &mut S) -> Result<(), EmitError> {
870        let info = InstructionInfo {
871            address: self.address(),
872            length: self.len(),
873        };
874        let pcode = self.pcode_ast()?;
875        sink.instruction(&info, &pcode)
876    }
877
878    /// Converts borrowed instruction bytes into owned bytes.
879    pub fn into_owned_bytes(self) -> Instruction<'spec, 'static> {
880        Instruction {
881            spec: self.spec,
882            instance: self.instance,
883            raw_bytes: Cow::Owned(self.raw_bytes.into_owned()),
884        }
885    }
886}
887
888impl fmt::Debug for Instruction<'_, '_> {
889    /// Address, encoding and rendered assembly — enough to identify the
890    /// instruction in a test failure without dumping the whole decode tree.
891    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892        f.debug_struct("Instruction")
893            .field("address", &format_args!("{:#x}", self.address()))
894            .field("bytes", &self.bytes())
895            .field("display", &format_args!("{self}"))
896            .finish_non_exhaustive()
897    }
898}
899
900impl fmt::Display for Instruction<'_, '_> {
901    /// Renders the display string, or the reason it could not be rendered —
902    /// `fmt::Display` has nowhere to report an error, and a silently truncated
903    /// disassembly line would be worse than a visible marker. Use
904    /// [`Instruction::display`] to handle the failure.
905    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
906        match self.instance.try_to_string(&self.spec.spec) {
907            Ok(text) => f.write_str(&text),
908            Err(err) => write!(f, "<{err}>"),
909        }
910    }
911}