Skip to main content

binbun/
cfg.rs

1//! Control-flow recovery for any instruction set: basic blocks, functions,
2//! and which calls return, from a [`Memory`] and a few starting points.
3//!
4//! The recovery sees instructions only through [`binbun_isa`]'s traits, and
5//! memory only through [`Memory`], so the same code serves x86 and AArch64,
6//! a loaded file and a live target.
7//!
8//! Recursive descent: from each seed (an entry point, a symbol, an unwind
9//! table entry) code is decoded and followed along jumps and branches;
10//! call targets become functions. A call's fallthrough is followed only once
11//! the callee is known to return, so that bytes after a call to a function
12//! that never returns (`exit`, `abort`, a `noreturn` helper) are not taken
13//! for code. Computed jumps (through a register or a computed memory
14//! operand) are asked about through a [`Resolver`] once the rest of their
15//! function is recovered, computed calls once reached. One that always
16//! goes through the same pointer slot (a GOT or IAT entry the code
17//! addresses in a register: an AArch64 PLT stub) becomes a jump or call
18//! through that slot, as if the instruction named it: its block's exit
19//! says so from then on. Otherwise a jump's table (a switch) is asked for:
20//! the targets it knows
21//! become the jump's table, and the function's code. Those it does not
22//! know, and other jumps and calls it cannot follow (virtual calls, tail
23//! calls through a pointer), are recorded as unresolved.
24//!
25//! A function whose only block jumps to an import (a PLT stub, a PE import
26//! thunk) is an import thunk: an ordinary function, which returns if the
27//! import does, so calls to `exit@plt` do not return either.
28//!
29//! What recovery cannot see, imports above all, it asks about through
30//! [`Callees`]; it holds no knowledge of library functions itself.
31//!
32//! A compiler may split a function into parts placed apart (GCC's
33//! `-freorder-blocks-and-partition` moves cold blocks to
34//! `.text.unlikely` as `foo.cold`; Clang's `-fsplit-machine-functions`
35//! likewise), each with its own unwind table entry, so recovery first finds
36//! such a part as a function of its own. Afterwards a function `p` is
37//! joined into the function `f` it is a part of (its blocks become `f`'s,
38//! [`Function::parts`] lists it) when:
39//!
40//! 1. only `f`'s code enters it, and only by jumps or branches (at least
41//!    one, or an exception unwinding to a landing pad; none from another
42//!    function; no call to it), and nothing else
43//!    says it is a function: it is not the entry point, not exported, no
44//!    pointer stored in data nor an address code computes, and its unwind
45//!    table entry does not start an outermost frame (code that starts a
46//!    stack of its own, as a `clone` child does, is another thread's, not
47//!    a part of the function that made the thread); and
48//! 2. something says it is not a function of its own: it jumps back into
49//!    `f` (into `f`'s unwind extent or code, not to its entry; a function
50//!    never jumps into the middle of another), or its unwind table entry
51//!    starts inside a frame (no call could have entered it), or `f` enters
52//!    it by a conditional branch (compilers' tail calls are unconditional
53//!    jumps; a conditional jump out of a function is how they reach a
54//!    part split off it).
55//!
56//! A part entered from several functions, or called, stays a function;
57//! so does a function only tail-called by one other (an unconditional
58//! jump and no other evidence). Symbols are not evidence: stripped
59//! binaries have none, and the rule finds the parts their names show
60//! without them. Joining repeats until nothing changes (a part may enter
61//! another).
62//!
63//! Exceptions: a call through which an exception unwinds to a landing
64//! pad ([`Seed::Unwind`], from the exception tables) has an
65//! [`EdgeKind::Unwind`] edge there, so a function's landing pads, and
66//! the parts only they lead to, are reached from its entry like the rest
67//! of its code. A part only landing pads that no recovered call unwinds
68//! to reach (code the unwinder enters, through call sites recovery did
69//! not find) stays a function of its own, marked [`Function::part_of`],
70//! since its function's decompilation would not show its code.
71//!
72//! Funclets: code that a function's exception handler calls, with the
73//! function's frame (Microsoft x64: `__except` filters, `__finally`
74//! blocks, C++ catch blocks and unwind actions), is a function in the
75//! binary but a part of the function in the source. The exception tables
76//! say whose ([`Seed::Funclet`]); recovered as a function of its own (its
77//! own frame and unwind entry), it is joined to its function: listed in
78//! its [`Function::funclets`] and marked [`Function::part_of`] (a
79//! function's funclets are its root's: joined parts' funclets too).
80
81mod parts;
82mod recover;
83
84use std::collections::BTreeMap;
85
86use binbun_isa::Target;
87use binbun_semantics::core::{Arena, Id, Memory};
88
89pub use recover::{Options, recover};
90
91/// A basic block's id.
92#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Id)]
93pub struct BlockId(u32);
94
95/// A function's id.
96#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Id)]
97pub struct FunctionId(u32);
98
99/// Whether a function returns to its caller.
100#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
101pub enum Returns {
102    /// It can return.
103    Yes,
104    /// It never returns.
105    No,
106    /// Not known: assumed to return.
107    Unknown,
108}
109
110/// Code a call or jump reaches, as recovery asks [`Callees`] about it.
111#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
112pub enum Callee {
113    /// The function whose address is in the pointer slot at this address
114    /// (an import).
115    Import(u64),
116    /// The function at this address.
117    Address(u64),
118}
119
120/// What the caller of recovery knows about code it reaches but cannot
121/// recover itself (imports) or knows better (functions identified as
122/// library code).
123pub trait Callees {
124    /// Whether the pointer slot at `slot` holds an import's address.
125    fn is_import(&self, slot: u64) -> bool;
126
127    /// The code address the pointer slot at `slot` (of `size` bytes)
128    /// always holds while the program runs: one the dynamic loader writes
129    /// (a relative relocation) or the file holds, where the program
130    /// cannot change it. `None` if not known.
131    fn slot(&self, slot: u64, size: u8) -> Option<u64> {
132        let _ = (slot, size);
133        None
134    }
135
136    /// Whether `callee` returns, if known. For an address, a known answer
137    /// overrides what recovery infers from the code.
138    fn returns(&self, callee: Callee) -> Returns;
139}
140
141/// Nothing known: no imports, every callee's return found from its code
142/// (or assumed).
143#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
144pub struct NothingKnown;
145
146impl Callees for NothingKnown {
147    fn is_import(&self, _: u64) -> bool {
148        false
149    }
150
151    fn returns(&self, _: Callee) -> Returns {
152        Returns::Unknown
153    }
154}
155
156/// Where a computed jump goes, as a [`Resolver`] found it.
157#[derive(Clone, Debug, Default, PartialEq, Eq)]
158pub struct Table {
159    /// The addresses it can go to, sorted.
160    pub targets: Vec<u64>,
161    /// Whether where the table ends was inferred (its index bounded only
162    /// by its width, the entries cut where they stop looking like the
163    /// function's code) rather than proven.
164    pub inferred: bool,
165}
166
167/// What recovery asks about computed jumps and calls it cannot follow:
168/// where one goes when it always goes to one place (a pointer slot), and
169/// where a jump can go when it reads a table (a switch).
170pub trait Resolver {
171    /// Where the computed jump or call ending block `jump` (a block of the
172    /// function at `entry`, whose blocks so far are `blocks`) always goes:
173    /// [`Target::Pointer`] if its address is read from a pointer slot at a
174    /// fixed address (a GOT or IAT entry: `adrp x16, slot; ldr x17, [x16,
175    /// :lo12:slot]; br x17`, x86 `mov rax, [rip+slot]; jmp rax`), which
176    /// recovery then treats as it treats `jmp [rip+slot]` (an import, the
177    /// slot's fixed value, or unresolved); [`Target::Address`] if the
178    /// address is a constant. `None` (the default) if not known: a jump is
179    /// then asked about its [`table`](Self::table).
180    ///
181    /// A call is asked about as soon as recovery reaches it, with its
182    /// block alone as the function (`entry` its start, `blocks` just
183    /// `jump`), so that its fallthrough need not wait for the rest of the
184    /// function.
185    fn target(&mut self, entry: u64, blocks: &[Block], jump: Block) -> Option<Target> {
186        let _ = (entry, blocks, jump);
187        None
188    }
189
190    /// Where the computed jump ending block `jump` (a block of the function
191    /// at `entry`, whose blocks so far are `blocks`) can go; `None` if not
192    /// known.
193    fn table(&mut self, entry: u64, blocks: &[Block], jump: Block) -> Option<Table>;
194
195    /// The end of the data the bytes at `address` are, if they are known
196    /// to be data rather than code whatever decodes there (text: a string
197    /// and its terminator, as a compiler places in a code section). A
198    /// computed address ([`SeedKind::Reference`]) or a pointer stored in
199    /// data ([`SeedKind::Pointer`]) there, the only evidence of code
200    /// there, then makes no function ([`Program::data`]); stronger seeds
201    /// (an entry, a symbol, an unwind table entry, a call) still do.
202    /// `None` (the default): they may be code.
203    fn data(&mut self, address: u64) -> Option<u64> {
204        let _ = address;
205        None
206    }
207}
208
209/// Knows nothing: every computed jump stays unresolved.
210#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
211pub struct NoResolver;
212
213impl Resolver for NoResolver {
214    fn table(&mut self, _: u64, _: &[Block], _: Block) -> Option<Table> {
215        None
216    }
217}
218
219/// Why an address is a function's start.
220#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
221pub enum SeedKind {
222    /// The program's entry point.
223    Entry,
224    /// A function symbol the image does not export.
225    Symbol,
226    /// A symbol the image exports (a dynamic symbol, a PE export): code
227    /// outside the image may call it.
228    Export,
229    /// The start of an unwind table entry.
230    Unwind,
231    /// The target of a call found during recovery.
232    Call,
233    /// A pointer to code stored in data (a relocation's target): only a
234    /// function if no code recovered from the other seeds contains it.
235    Pointer,
236    /// An address code computes (an x86 RIP-relative `lea`), found while
237    /// recovering: only a function if no other recovered code contains it.
238    Reference,
239    /// The user's word ([`Seed::Function`] of a correction): a function's
240    /// start, never joined into another as a part.
241    User,
242}
243
244impl SeedKind {
245    const fn bit(self) -> u8 {
246        match self {
247            Self::Entry => 1,
248            Self::Symbol => 2,
249            Self::Unwind => 4,
250            Self::Call => 8,
251            Self::Pointer => 16,
252            Self::Reference => 32,
253            Self::Export => 64,
254            Self::User => 128,
255        }
256    }
257}
258
259/// Where recovery starts.
260#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
261pub enum Seed {
262    /// A function's start.
263    Function(u64, SeedKind),
264    /// Code of the function at `function` that its blocks do not reach, such
265    /// as a landing pad, which only the unwinder jumps to.
266    Code {
267        /// The function's start.
268        function: u64,
269        /// The code's address.
270        address: u64,
271    },
272    /// The function at `function` occupies `function..end` (an unwind
273    /// table entry says so). A jump out of it is a tail call: into a new
274    /// function, unless the target lies within another known extent (code
275    /// of that function, as when a cold part jumps back).
276    Extent {
277        /// The function's start.
278        function: u64,
279        /// The address after its last byte.
280        end: u64,
281        /// How the unwind table entry says its code is entered.
282        frame: Frame,
283    },
284    /// `start..end` is code split off a function (an x64 `.pdata` entry
285    /// whose unwind information chains to another's: MSVC's
286    /// profile-guided hot and cold splitting), which its function may
287    /// enter anywhere: what is recovered there is a part of `owner` (the
288    /// function the chain ends at) where known, else of the one function
289    /// that enters it, not a function of its own.
290    Split {
291        /// The first byte.
292        start: u64,
293        /// The byte after the last.
294        end: u64,
295        /// The function it was split off, where known.
296        owner: Option<u64>,
297    },
298    /// An exception that unwinds through a call in `start..end` (the
299    /// call's return address minus one in it, as the unwinder looks it
300    /// up) continues at the landing pad `pad` (an exception table's call
301    /// site): the call's block has an [`EdgeKind::Unwind`] edge there.
302    Unwind {
303        /// The first byte of the range.
304        start: u64,
305        /// The byte after it.
306        end: u64,
307        /// The landing pad.
308        pad: u64,
309    },
310    /// The code at `address`, recovered as a function, is a funclet of the
311    /// function at `function`: code its exception handler calls with its
312    /// frame (from the exception tables).
313    Funclet {
314        /// The function's start.
315        function: u64,
316        /// The funclet's start.
317        address: u64,
318    },
319    /// The user's correction: the code at the address is code, of no
320    /// function unless one reaches it (`C`): decoded and followed
321    /// from there (its calls' targets become functions).
322    Flow(u64),
323    /// The user's correction: no instruction overlaps `start..end` (bytes
324    /// the user undefined or typed as data); code that reaches them ends
325    /// there ([`Exit::Invalid`]).
326    NotCode {
327        /// The first byte.
328        start: u64,
329        /// The byte after the last.
330        end: u64,
331    },
332    /// The user's correction: the function at `function` ends at `end`
333    /// (Edit Function). `end` is a block boundary; control leaving
334    /// `function..end` (a jump, or falling through) is a tail call into
335    /// the function there; the extent replaces an unwind table's
336    /// ([`Seed::Extent`]), and no part is joined into the function.
337    End {
338        /// The function's start.
339        function: u64,
340        /// The address after its last byte.
341        end: u64,
342    },
343    /// The user's correction: no function starts at the address (a
344    /// deleted function): seeds there make none, and a call there is a
345    /// call to code of no function, assumed to return.
346    NoFunction(u64),
347}
348
349impl Seed {
350    /// The address of a pointer's target ([`SeedKind::Pointer`]).
351    const fn pointer(&self) -> Option<u64> {
352        match *self {
353            Self::Function(address, SeedKind::Pointer) => Some(address),
354            Self::Function(..)
355            | Self::Code { .. }
356            | Self::Extent { .. }
357            | Self::Split { .. }
358            | Self::Unwind { .. }
359            | Self::Funclet { .. }
360            | Self::Flow(_)
361            | Self::NotCode { .. }
362            | Self::End { .. }
363            | Self::NoFunction(_) => None,
364        }
365    }
366
367    /// The address it is about, as seeds are sorted by.
368    pub const fn address(&self) -> u64 {
369        match *self {
370            Self::Function(address, _)
371            | Self::Code { address, .. }
372            | Self::Extent {
373                function: address, ..
374            }
375            | Self::Split { start: address, .. }
376            | Self::Unwind { start: address, .. }
377            | Self::Funclet { address, .. }
378            | Self::Flow(address)
379            | Self::NotCode { start: address, .. }
380            | Self::End {
381                function: address, ..
382            }
383            | Self::NoFunction(address) => address,
384        }
385    }
386}
387
388/// How an unwind table entry says its code is entered.
389#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
390pub enum Frame {
391    /// As a function is, by a call.
392    Call,
393    /// Inside a frame (code split off a function, which no call enters):
394    /// evidence that it is a part of the function that jumps to it.
395    Inside,
396    /// As the outermost frame (where a process or thread starts its own
397    /// stack): a function's start, never a part of another.
398    Outermost,
399}
400
401/// A set of [`SeedKind`]s.
402#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
403pub struct SeedKinds(u8);
404
405impl SeedKinds {
406    /// Whether `kind` is in the set.
407    pub const fn contains(self, kind: SeedKind) -> bool {
408        self.0 & kind.bit() != 0
409    }
410
411    /// Adds `kind`.
412    pub const fn insert(&mut self, kind: SeedKind) {
413        self.0 |= kind.bit();
414    }
415}
416
417/// Where a jump or call goes, as recovery resolved it.
418#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
419pub enum Destination {
420    /// Code at an address.
421    Address(u64),
422    /// An import, by the address of its pointer slot.
423    Import(u64),
424    /// The address stored at an address that is no import (unresolved).
425    Pointer(u64),
426    /// A register or computed memory operand (unresolved).
427    Indirect,
428    /// A segmented address (unresolved).
429    Far,
430}
431
432impl Destination {
433    /// Whether recovery could not tell where it goes.
434    pub const fn is_unresolved(self) -> bool {
435        matches!(self, Self::Pointer(_) | Self::Indirect | Self::Far)
436    }
437}
438
439/// How control leaves a block.
440#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
441pub enum Exit {
442    /// It continues at the block's end, where another block starts.
443    Next,
444    /// An unconditional jump.
445    Jump(Destination),
446    /// A conditional jump; otherwise it continues at the block's end.
447    Branch(Destination),
448    /// A call; it continues at the block's end if the callee returns.
449    Call {
450        /// The callee.
451        callee: Destination,
452        /// Whether the callee returns.
453        returns: Returns,
454    },
455    /// A return from the function.
456    Return,
457    /// A trap, a halt or an exception return: execution does not go on.
458    Stop,
459    /// The instruction at the block's end does not decode, is not mapped,
460    /// or is not executable.
461    Invalid,
462    /// The block hit [`Options::max_block_instructions`].
463    Limit,
464}
465
466/// A basic block.
467#[derive(Clone, Copy, Debug, PartialEq, Eq)]
468pub struct Block {
469    /// Its first instruction's address.
470    pub start: u64,
471    /// The address after its last instruction.
472    pub end: u64,
473    /// Number of instructions.
474    pub instructions: u32,
475    /// How control leaves it.
476    pub exit: Exit,
477}
478
479/// Why control goes from one block to another.
480#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
481pub enum EdgeKind {
482    /// Falling into the next block.
483    Next,
484    /// An unconditional jump.
485    Jump,
486    /// A conditional jump, taken.
487    Taken,
488    /// A conditional jump, not taken.
489    NotTaken,
490    /// Returning from a call to the instruction after it.
491    CallReturn,
492    /// A computed jump, to one of the targets resolved for it.
493    Table,
494    /// An exception unwinding through a call, to the landing pad the
495    /// exception table names for it ([`Seed::Unwind`]).
496    Unwind,
497}
498
499/// The addresses control can go to next from `block` within the program,
500/// as its exit states them: a computed jump's table is not included, and
501/// calls' callees are not successors (their return is).
502fn static_successors(block: Block) -> impl Iterator<Item = (EdgeKind, u64)> {
503    let (first, second) = match block.exit {
504        Exit::Next => (Some((EdgeKind::Next, block.end)), None),
505        Exit::Jump(Destination::Address(target)) => (Some((EdgeKind::Jump, target)), None),
506        Exit::Branch(Destination::Address(target)) => (
507            Some((EdgeKind::Taken, target)),
508            Some((EdgeKind::NotTaken, block.end)),
509        ),
510        Exit::Branch(_) => (Some((EdgeKind::NotTaken, block.end)), None),
511        Exit::Call {
512            returns: Returns::Yes | Returns::Unknown,
513            ..
514        } => (Some((EdgeKind::CallReturn, block.end)), None),
515        Exit::Jump(_)
516        | Exit::Call {
517            returns: Returns::No,
518            ..
519        }
520        | Exit::Return
521        | Exit::Stop
522        | Exit::Invalid
523        | Exit::Limit => (None, None),
524    };
525    first.into_iter().chain(second)
526}
527
528/// The call-site ranges of exception tables with a landing pad
529/// ([`Seed::Unwind`]): start to end and landing pad.
530pub(crate) type Unwind = BTreeMap<u64, (u64, u64)>;
531
532/// The landing pad an exception unwinding through a call that returns to
533/// `return_address` goes to, from `unwind`: the range holding the address
534/// before it, as the unwinder looks it up.
535fn landing_pad(unwind: &Unwind, return_address: u64) -> Option<u64> {
536    let at = return_address.checked_sub(1)?;
537    let (_, &(end, pad)) = unwind.range(..=at).next_back()?;
538    (at < end).then_some(pad)
539}
540
541/// `block`'s [`EdgeKind::Unwind`] edge, if it ends in a call through which
542/// an exception unwinds to a landing pad.
543fn unwind_successor(unwind: &Unwind, block: Block) -> Option<(EdgeKind, u64)> {
544    match block.exit {
545        Exit::Call { .. } => landing_pad(unwind, block.end).map(|pad| (EdgeKind::Unwind, pad)),
546        Exit::Next
547        | Exit::Jump(_)
548        | Exit::Branch(_)
549        | Exit::Return
550        | Exit::Stop
551        | Exit::Invalid
552        | Exit::Limit => None,
553    }
554}
555
556/// A function.
557#[derive(Clone, Debug, PartialEq, Eq)]
558pub struct Function {
559    /// Its entry point.
560    pub entry: u64,
561    /// Why it is one.
562    pub seeds: SeedKinds,
563    /// Its blocks, by address: those reachable from the entry without
564    /// passing into another function's entry, from its landing pads, and
565    /// those of its [`parts`](Self::parts).
566    pub blocks: Vec<BlockId>,
567    /// Whether it can return to its caller.
568    pub returns: bool,
569    /// The entries of the parts of it that recovery first found as
570    /// functions of their own and joined into it (cold parts: the
571    /// [crate]'s rule), by address. Their blocks are among
572    /// [`blocks`](Self::blocks); each part's entry is a block start.
573    pub parts: Vec<u64>,
574    /// Its landing pads, and those of its parts, by address: code only
575    /// the unwinder enters (from its exception tables).
576    pub landing_pads: Vec<u64>,
577    /// For a part of another function that only that function's landing
578    /// pads lead to, or a funclet of another function: that function's
579    /// entry. Such a part is kept a function of its own (the [crate]'s
580    /// rule).
581    pub part_of: Option<u64>,
582    /// The entries of its funclets ([`Seed::Funclet`]), by address: each is
583    /// a function [`part_of`](Self::part_of) it.
584    pub funclets: Vec<u64>,
585}
586
587/// Bytes decoded as two different instructions: an instruction that
588/// overlaps another block's start.
589#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
590pub struct Conflict {
591    /// The instruction's address.
592    pub instruction: u64,
593    /// The start of the block it overlaps.
594    pub block: u64,
595}
596
597/// The recovered control flow of a program.
598#[derive(Clone, Debug, Default)]
599pub struct Program {
600    /// Every block decoded (including any after calls later found not to
601    /// return, which belong to no function).
602    pub blocks: Arena<BlockId, Block>,
603    /// The functions.
604    pub functions: Arena<FunctionId, Function>,
605    /// Overlapping instructions.
606    pub conflicts: Vec<Conflict>,
607    by_start: BTreeMap<u64, BlockId>,
608    by_entry: BTreeMap<u64, FunctionId>,
609    /// The resolved targets of computed jumps, by the block they end.
610    tables: BTreeMap<BlockId, Table>,
611    /// The call-site ranges with a landing pad, by start.
612    unwind: Unwind,
613    /// The data in code that computed addresses and pointers in data point
614    /// to and that made no function ([`Resolver::data`]): start to end.
615    data: BTreeMap<u64, u64>,
616}
617
618impl Program {
619    /// The data in code that computed addresses and pointers in data point
620    /// to, which is no function: its bytes are data ([`Resolver::data`]),
621    /// and no stronger seed made a function there nor does a block hold
622    /// it. Start to end, not overlapping.
623    pub fn data(&self) -> &BTreeMap<u64, u64> {
624        &self.data
625    }
626
627    /// The block that starts at `address`.
628    pub fn block_at(&self, address: u64) -> Option<BlockId> {
629        self.by_start.get(&address).copied()
630    }
631
632    /// The block that contains `address`: the one starting nearest before
633    /// it, if it reaches it. (Where code overlaps, an address can also be
634    /// in a block that starts earlier.)
635    pub fn block_containing(&self, address: u64) -> Option<BlockId> {
636        let (_, &id) = self.by_start.range(..=address).next_back()?;
637        self.blocks.get(id).filter(|b| address < b.end).map(|_| id)
638    }
639
640    /// The function that starts at `address`.
641    pub fn function_at(&self, address: u64) -> Option<FunctionId> {
642        self.by_entry.get(&address).copied()
643    }
644
645    /// Blocks, sorted by start.
646    pub fn blocks_by_address(&self) -> impl Iterator<Item = (u64, BlockId)> + '_ {
647        self.by_start.iter().map(|(&start, &id)| (start, id))
648    }
649
650    /// Where the computed jump ending `block` goes, when the [`Resolver`]
651    /// knew (a switch table's cases).
652    pub fn table(&self, block: BlockId) -> Option<&Table> {
653        self.tables.get(&block)
654    }
655
656    /// The addresses control can go to next from `block` within the
657    /// program: those its exit states, and its computed jump's
658    /// [`table`](Self::table), and a call's landing pad (calls' callees are
659    /// not successors; their return is).
660    pub fn successors(&self, block: BlockId) -> impl Iterator<Item = (EdgeKind, u64)> + '_ {
661        let table = self
662            .table(block)
663            .into_iter()
664            .flat_map(|table| &table.targets)
665            .map(|&target| (EdgeKind::Table, target));
666        let block = self.blocks.get(block).copied();
667        let unwind = block.and_then(|block| unwind_successor(&self.unwind, block));
668        block
669            .into_iter()
670            .flat_map(static_successors)
671            .chain(table)
672            .chain(unwind)
673    }
674
675    /// The landing pad an exception unwinding through the call that
676    /// returns to `return_address` goes to ([`Seed::Unwind`]), if one.
677    pub fn landing_pad(&self, return_address: u64) -> Option<u64> {
678        landing_pad(&self.unwind, return_address)
679    }
680
681    /// The jumps and calls whose destination recovery could not tell, with
682    /// their block (switch tables the [`Resolver`] did not know, virtual and
683    /// function-pointer calls).
684    pub fn unresolved(&self) -> impl Iterator<Item = (BlockId, Destination)> + '_ {
685        self.blocks
686            .iter()
687            .filter_map(|(id, block)| match block.exit {
688                Exit::Jump(destination)
689                | Exit::Branch(destination)
690                | Exit::Call {
691                    callee: destination,
692                    ..
693                } if destination.is_unresolved() && !self.tables.contains_key(&id) => {
694                    Some((id, destination))
695                }
696                Exit::Jump(_)
697                | Exit::Branch(_)
698                | Exit::Call { .. }
699                | Exit::Next
700                | Exit::Return
701                | Exit::Stop
702                | Exit::Invalid
703                | Exit::Limit => None,
704            })
705    }
706}
707
708/// Builds the result from recovery's tables.
709fn program(
710    blocks: Arena<BlockId, Block>,
711    by_start: BTreeMap<u64, BlockId>,
712    functions: Arena<FunctionId, Function>,
713    conflicts: Vec<Conflict>,
714    tables: BTreeMap<BlockId, Table>,
715    unwind: Unwind,
716    data: BTreeMap<u64, u64>,
717) -> Program {
718    let by_entry = functions.iter().map(|(id, f)| (f.entry, id)).collect();
719    Program {
720        blocks,
721        functions,
722        conflicts,
723        by_start,
724        by_entry,
725        tables,
726        unwind,
727        data,
728    }
729}
730
731/// Recovers the one function at `entry`, without recovering its callees:
732/// calls are assumed to return unless they go to an import known not to
733/// (for debuggers, which want one function's graph from a live target).
734/// `resolver` tells where its computed jumps go.
735pub fn recover_function<A: binbun_isa::Architecture, M: Memory>(
736    architecture: &A,
737    mode: A::Mode,
738    memory: &M,
739    entry: u64,
740    callees: &impl Callees,
741    resolver: &mut dyn Resolver,
742) -> Program {
743    let options = Options {
744        follow_calls: false,
745        ..Options::default()
746    };
747    recover(
748        architecture,
749        mode,
750        memory,
751        &[Seed::Function(entry, SeedKind::Symbol)],
752        callees,
753        resolver,
754        &options,
755    )
756}