Skip to main content

hexicon_bytecode/
discover.rs

1//! Finding the functions in an image.
2//!
3//! An image has no table of its functions unless it was compiled for
4//! debugging. Otherwise functions are found by following references: the
5//! entry point, exported symbols, method values in static objects, function
6//! pointers in constant lists, and calls from functions already found.
7
8use std::collections::{BTreeMap, BTreeSet};
9
10use hexicon_image::{GlobalSymbolKind, Image, Value};
11
12use crate::decode::{Operand, Payload};
13use crate::function::{DisassembleError, Extent, Function, disassemble};
14
15/// The functions found in an image.
16#[derive(Debug, Clone, Default)]
17pub struct Functions {
18    /// Each function found, by code pool address. An address that was
19    /// referenced as a function but could not be disassembled maps to the
20    /// error.
21    pub by_address: BTreeMap<u32, Result<Function, DisassembleError>>,
22    /// Functions nothing refers to. They were found because they sit
23    /// directly after another function, in bytes that are not part of it.
24    pub unreferenced: BTreeSet<u32>,
25    /// Referenced addresses that lie beyond the code the image supplies.
26    /// Pre-initialization discards static initializer code, which leaves
27    /// such references behind in the properties that code initialized.
28    pub dangling: BTreeSet<u32>,
29}
30
31impl Functions {
32    /// The functions that disassembled, in address order.
33    pub fn functions(&self) -> impl Iterator<Item = &Function> {
34        self.by_address.values().filter_map(|f| f.as_ref().ok())
35    }
36
37    /// The addresses that failed to disassemble, with their errors.
38    pub fn errors(&self) -> impl Iterator<Item = (u32, &DisassembleError)> {
39        self.by_address
40            .iter()
41            .filter_map(|(address, f)| f.as_ref().err().map(|e| (*address, e)))
42    }
43}
44
45/// Find and disassemble every function reachable from an image's roots.
46pub fn discover(image: &Image) -> Functions {
47    discover_from(image, true)
48}
49
50/// Like [`discover`], but ignoring the function lists that debug builds
51/// carry, so the result is what would be found in a release build of the
52/// same program. Comparing the two measures how complete discovery is.
53pub fn discover_without_debug_info(image: &Image) -> Functions {
54    discover_from(image, false)
55}
56
57fn discover_from(image: &Image, use_debug_info: bool) -> Functions {
58    let mut finder = Finder {
59        image,
60        pending: Vec::new(),
61        seen_lists: BTreeSet::new(),
62        found: BTreeMap::new(),
63        speculative: BTreeSet::new(),
64        rejected: BTreeSet::new(),
65        unreferenced: BTreeSet::new(),
66        dangling: BTreeSet::new(),
67    };
68    finder.roots(use_debug_info);
69    finder.run();
70
71    // Code nothing refers to can still be found if it starts a page, since
72    // the first function in a page starts at the page's first byte. The
73    // static initializer code, which begins a page of its own, is the usual
74    // case.
75    for index in 0..image.code_pool.page_count() {
76        let address = index as u32 * image.code_pool.page_size();
77        let has_code = image.code_pool.page(index).is_some_and(|p| !p.is_empty());
78        if has_code && !finder.found.contains_key(&address) {
79            finder.speculative.insert(address);
80            finder.pending.push(address);
81        }
82    }
83    finder.run();
84
85    // With every start known, each function can be bounded by the next,
86    // which brings unreachable code into view. That code can refer to
87    // further functions, so repeat until nothing new turns up.
88    let page_size = image.code_pool.page_size().max(1);
89    loop {
90        let starts: Vec<u32> = finder.found.keys().copied().collect();
91        for (index, &address) in starts.iter().enumerate() {
92            // The bound is the next function in the same page, or failing
93            // that the end of the page's data.
94            let page_start = address - address % page_size;
95            let page_len = image
96                .code_pool
97                .page((address / page_size) as usize)
98                .map_or(0, |page| page.len() as u32);
99            let limit = starts
100                .get(index + 1)
101                .copied()
102                .filter(|next| next / page_size == address / page_size)
103                .unwrap_or(page_start + page_len);
104            let bounded = disassemble(image, address, Some(limit));
105            if let Ok(function) = &bounded {
106                finder.references(function);
107                // Bytes after a function that are not more of its code are
108                // most likely a function nothing refers to.
109                // The next function usually starts where this one's
110                // reachable code ends. If that fails, this function may end
111                // in unreachable code, and the next starts after that.
112                let tail = function.tail_address();
113                let candidates = match function.extent {
114                    Extent::Gap { decodable_end, .. } => {
115                        [Some(tail), Some(address + decodable_end)]
116                    }
117                    Extent::Table if tail < limit => [Some(tail), None],
118                    _ => [None, None],
119                };
120                let untried = candidates.into_iter().flatten().find(|candidate| {
121                    !finder.found.contains_key(candidate) && !finder.rejected.contains(candidate)
122                });
123                if let Some(candidate) = untried {
124                    finder.speculative.insert(candidate);
125                    finder.pending.push(candidate);
126                }
127            }
128            finder.found.insert(address, bounded);
129        }
130        let found = &finder.found;
131        finder
132            .pending
133            .retain(|address| !found.contains_key(address));
134        if finder.pending.is_empty() {
135            break;
136        }
137        finder.run();
138    }
139
140    Functions {
141        by_address: finder.found,
142        unreferenced: finder.unreferenced,
143        dangling: finder.dangling,
144    }
145}
146
147struct Finder<'a> {
148    image: &'a Image,
149    pending: Vec<u32>,
150    seen_lists: BTreeSet<u32>,
151    found: BTreeMap<u32, Result<Function, DisassembleError>>,
152    /// Addresses being tried as functions without a reference to them.
153    speculative: BTreeSet<u32>,
154    /// Guesses that did not disassemble.
155    rejected: BTreeSet<u32>,
156    unreferenced: BTreeSet<u32>,
157    dangling: BTreeSet<u32>,
158}
159
160impl Finder<'_> {
161    fn roots(&mut self, use_debug_info: bool) {
162        let image = self.image;
163        self.pending.push(image.entry_point.code_offset);
164        for symbol in &image.symbols {
165            self.value(symbol.value);
166        }
167        if use_debug_info {
168            self.pending.extend(&image.debug.method_headers);
169            for symbol in &image.debug.global_symbols {
170                if let GlobalSymbolKind::Function { code_offset, .. } = symbol.kind {
171                    self.pending.push(code_offset);
172                }
173            }
174        }
175        for block in &image.object_blocks {
176            let layout = match image.metaclass_of(block).base_name() {
177                "hexicon-object" | "int-class-mod" => ObjectLayout::Properties,
178                "vector" | "anon-func-ptr" => ObjectLayout::Vector,
179                "lookuptable" | "weakreflookuptable" => ObjectLayout::Map,
180                _ => continue,
181            };
182            for object in &block.objects {
183                // Object data this crate cannot follow is skipped; it only
184                // means fewer roots.
185                let _ = self.object(layout, &object.data);
186            }
187        }
188    }
189
190    fn run(&mut self) {
191        while let Some(address) = self.pending.pop() {
192            if self.found.contains_key(&address) {
193                continue;
194            }
195            let result = disassemble(self.image, address, None);
196            let speculative = self.speculative.remove(&address);
197            match &result {
198                Ok(function) => {
199                    self.references(function);
200                    if speculative {
201                        self.unreferenced.insert(address);
202                    }
203                }
204                // A guess that did not work out is not a finding, but it
205                // must not be tried again.
206                Err(_) if speculative => {
207                    self.rejected.insert(address);
208                    continue;
209                }
210                Err(DisassembleError::BadAddress) if self.is_beyond_code(address) => {
211                    self.dangling.insert(address);
212                    continue;
213                }
214                Err(_) => {}
215            }
216            self.found.insert(address, result);
217        }
218    }
219
220    /// Whether an address is past the last byte of code in the image.
221    fn is_beyond_code(&self, address: u32) -> bool {
222        let pool = &self.image.code_pool;
223        let page_size = pool.page_size().max(1);
224        let index = (address / page_size) as usize;
225        match pool.page(index) {
226            Some(page) => (address % page_size) as usize >= page.len(),
227            None => true,
228        }
229    }
230
231    /// Queue everything a function's code refers to.
232    fn references(&mut self, function: &Function) {
233        for instruction in &function.instructions {
234            for operand in &instruction.operands {
235                match *operand {
236                    Operand::Function(address) => self.pending.push(address),
237                    Operand::List(offset) => self.list(offset),
238                    _ => {}
239                }
240            }
241            if let Payload::Switch { cases, .. } = &instruction.payload {
242                for (value, _) in cases {
243                    self.value(*value);
244                }
245            }
246        }
247    }
248
249    fn value(&mut self, value: Value) {
250        match value {
251            Value::CodeOffset(address) | Value::FunctionPointer(address) => {
252                self.pending.push(address);
253            }
254            Value::List(offset) => self.list(offset),
255            _ => {}
256        }
257    }
258
259    /// Follow a constant list: a count followed by that many values.
260    fn list(&mut self, offset: u32) {
261        if !self.seen_lists.insert(offset) {
262            return;
263        }
264        let Some(data) = self.image.constant_pool.at(offset) else {
265            return;
266        };
267        let Some(count) = data.get(..2).map(|b| u16::from_le_bytes([b[0], b[1]])) else {
268            return;
269        };
270        let values: Vec<Value> = data[2..]
271            .as_chunks::<{ Value::ENCODED_SIZE }>()
272            .0
273            .iter()
274            .take(count as usize)
275            .map(|chunk| holder(chunk))
276            .collect();
277        for value in values {
278            self.value(value);
279        }
280    }
281
282    fn object(&mut self, layout: ObjectLayout, data: &[u8]) -> Option<()> {
283        let u16_at = |at: usize| Some(u16::from_le_bytes([*data.get(at)?, *data.get(at + 1)?]));
284        match layout {
285            ObjectLayout::Properties => {
286                // Superclass count, property count, flags, the superclass
287                // IDs, then each property's ID and value.
288                let superclasses = u16_at(0)? as usize;
289                let properties = u16_at(2)? as usize;
290                let table = data.get(6 + superclasses * 4..)?;
291                for entry in table
292                    .as_chunks::<{ 2 + Value::ENCODED_SIZE }>()
293                    .0
294                    .iter()
295                    .take(properties)
296                {
297                    self.value(holder(&entry[2..]));
298                }
299            }
300            ObjectLayout::Vector => {
301                // Allocated count, used count, then the used elements.
302                let used = u16_at(2)? as usize;
303                for element in data
304                    .get(4..)?
305                    .as_chunks::<{ Value::ENCODED_SIZE }>()
306                    .0
307                    .iter()
308                    .take(used)
309                {
310                    self.value(holder(element));
311                }
312            }
313            ObjectLayout::Map => {
314                // Bucket count, entry count, first free index, the bucket
315                // indexes, then each entry's key, value, and next index.
316                let buckets = u16_at(0)? as usize;
317                let entries = u16_at(2)? as usize;
318                let table = data.get(6 + buckets * 2..)?;
319                for entry in table
320                    .as_chunks::<{ Value::ENCODED_SIZE * 2 + 2 }>()
321                    .0
322                    .iter()
323                    .take(entries)
324                {
325                    self.value(holder(&entry[..Value::ENCODED_SIZE]));
326                    self.value(holder(&entry[Value::ENCODED_SIZE..]));
327                }
328            }
329        }
330        Some(())
331    }
332}
333
334#[derive(Clone, Copy)]
335enum ObjectLayout {
336    Properties,
337    Vector,
338    Map,
339}
340
341fn holder(bytes: &[u8]) -> Value {
342    Value::decode([bytes[0], bytes[1], bytes[2], bytes[3], bytes[4]])
343}