Skip to main content

hexicon_bytecode/
listing.rs

1//! Text listings of disassembled functions.
2
3use std::collections::HashMap;
4use std::fmt::Write as _;
5
6use hexicon_image::{GlobalSymbolKind, Image, Value};
7
8use crate::decode::{Instruction, Operand, Payload};
9use crate::function::{Extent, Function};
10use crate::opcode::Opcode;
11
12/// Names for the functions, objects, and properties of an image.
13///
14/// Names come from the image's debug symbols, when it has them, and from
15/// the symbols every image exports to the VM.
16#[derive(Debug, Clone, Default)]
17pub struct Names {
18    functions: HashMap<u32, String>,
19    objects: HashMap<u32, String>,
20    properties: HashMap<u16, String>,
21    enums: HashMap<u32, String>,
22}
23
24impl Names {
25    /// Collect the names an image provides.
26    pub fn new(image: &Image) -> Self {
27        let mut names = Self::default();
28        for symbol in &image.symbols {
29            match symbol.value {
30                Value::FunctionPointer(address) | Value::CodeOffset(address) => {
31                    names.functions.insert(address, symbol.name.clone());
32                }
33                Value::Object(id) => {
34                    names.objects.insert(id, symbol.name.clone());
35                }
36                Value::Property(id) => {
37                    names.properties.insert(id, symbol.name.clone());
38                }
39                _ => {}
40            }
41        }
42        // Debug symbols are the program's own names, so they take priority.
43        for symbol in &image.debug.global_symbols {
44            let name = symbol.name.clone();
45            match symbol.kind {
46                GlobalSymbolKind::Function { code_offset, .. } => {
47                    names.functions.insert(code_offset, name);
48                }
49                GlobalSymbolKind::Object { id, .. } => {
50                    names.objects.insert(id, name);
51                }
52                GlobalSymbolKind::Property { id, .. } => {
53                    names.properties.insert(id, name);
54                }
55                GlobalSymbolKind::Enumerator { id, .. } => {
56                    names.enums.insert(id, name);
57                }
58                _ => {}
59            }
60        }
61        names
62    }
63
64    /// The name of the function at a code pool address.
65    pub fn function(&self, address: u32) -> Option<&str> {
66        self.functions.get(&address).map(String::as_str)
67    }
68
69    fn function_label(&self, address: u32) -> String {
70        self.function(address)
71            .map_or_else(|| format!("function {address:#x}"), str::to_owned)
72    }
73
74    fn object_label(&self, id: u32) -> String {
75        self.objects
76            .get(&id)
77            .map_or_else(|| format!("object {id}"), Clone::clone)
78    }
79
80    fn property_label(&self, id: u16) -> String {
81        self.properties
82            .get(&id)
83            .map_or_else(|| format!("property {id}"), Clone::clone)
84    }
85
86    fn enum_label(&self, id: u32) -> String {
87        self.enums
88            .get(&id)
89            .map_or_else(|| format!("enum {id}"), Clone::clone)
90    }
91}
92
93/// Append a listing of one function.
94pub fn write_function(out: &mut String, image: &Image, names: &Names, function: &Function) {
95    // Writing to a String cannot fail.
96    let header = &function.header;
97    let _ = write!(out, "function {:#x}", function.address);
98    if let Some(name) = names.function(function.address) {
99        let _ = write!(out, "  {name}");
100    }
101    let _ = write!(
102        out,
103        "\n  parameters {}{}",
104        header.param_count,
105        if header.varargs { "+" } else { "" }
106    );
107    if header.optional_param_count != 0 {
108        let _ = write!(out, " (+{} optional)", header.optional_param_count);
109    }
110    let _ = writeln!(
111        out,
112        ", locals {}, stack {}",
113        header.local_count, header.stack_depth
114    );
115
116    for instruction in &function.instructions {
117        let _ = write!(
118            out,
119            "  {:04x}  {:<16}",
120            instruction.offset,
121            instruction.opcode.name()
122        );
123        let text = operands(image, names, instruction);
124        let _ = writeln!(out, "{}", text.trim_end());
125    }
126
127    for handler in &function.handlers {
128        let class = if handler.exception_class == 0 {
129            "anything".to_owned()
130        } else {
131            names.object_label(handler.exception_class)
132        };
133        let _ = writeln!(
134            out,
135            "  catch {class} in {:04x}..={:04x} -> {:04x}",
136            handler.start, handler.end, handler.handler
137        );
138    }
139    if let Extent::Gap { len, .. } = function.extent {
140        let _ = writeln!(out, "  ; {len} bytes after this function were not decoded");
141    }
142}
143
144fn operands(image: &Image, names: &Names, instruction: &Instruction) -> String {
145    let mut parts: Vec<String> = instruction
146        .operands
147        .iter()
148        .map(|operand| match *operand {
149            Operand::Unsigned(n) => n.to_string(),
150            Operand::Signed(n) => n.to_string(),
151            Operand::Argc(n) => format!("argc {n}"),
152            Operand::Local(n) => format!("local {n}"),
153            Operand::Arg(n) => format!("arg {n}"),
154            Operand::String(offset) => string_label(image, offset),
155            Operand::List(offset) => format!("list {offset:#x}"),
156            Operand::Object(id) => names.object_label(id),
157            Operand::Property(id) => names.property_label(id),
158            Operand::Function(address) => names.function_label(address),
159            Operand::Enum(id) => names.enum_label(id),
160            Operand::Branch(target) => format!("-> {target:04x}"),
161            Operand::Table(offset) => format!("table {offset:04x}"),
162            Operand::Metaclass(index) => image.metaclasses.get(index as usize).map_or_else(
163                || format!("metaclass {index}"),
164                |m| m.base_name().to_owned(),
165            ),
166            Operand::FunctionSet(index) => function_set_label(image, index),
167            Operand::FunctionIndex(index) => format!("#{index}"),
168        })
169        .collect();
170
171    // The four short built-in calls name their function set in the opcode.
172    let implied_set = match instruction.opcode {
173        Opcode::BuiltinA => Some(0),
174        Opcode::BuiltinB => Some(1),
175        Opcode::BuiltinC => Some(2),
176        Opcode::BuiltinD => Some(3),
177        _ => None,
178    };
179    if let Some(set) = implied_set {
180        parts.push(function_set_label(image, set));
181    }
182
183    match &instruction.payload {
184        Payload::None => {}
185        Payload::InlineString(text) => parts.push(quote(text)),
186        Payload::NamedArgs(args) => parts.push(args.join(", ")),
187        Payload::Switch { cases, default } => {
188            for (value, target) in cases {
189                parts.push(format!(
190                    "{} -> {target:04x}",
191                    value_label(image, names, *value)
192                ));
193            }
194            parts.push(format!("default -> {default:04x}"));
195        }
196    }
197    parts.join(", ")
198}
199
200fn function_set_label(image: &Image, index: u16) -> String {
201    image.function_sets.get(index as usize).map_or_else(
202        || format!("function set {index}"),
203        |name| name.split('/').next().unwrap_or(name).to_owned(),
204    )
205}
206
207fn value_label(image: &Image, names: &Names, value: Value) -> String {
208    match value {
209        Value::Nil => "nil".into(),
210        Value::True => "true".into(),
211        Value::Empty => "empty".into(),
212        Value::Int(n) => n.to_string(),
213        Value::Object(id) => names.object_label(id),
214        Value::Property(id) => format!("&{}", names.property_label(id)),
215        Value::Enum(id) => names.enum_label(id),
216        Value::String(offset) | Value::SelfPrintingString(offset) => string_label(image, offset),
217        Value::List(offset) => format!("list {offset:#x}"),
218        Value::CodeOffset(address) | Value::FunctionPointer(address) => {
219            names.function_label(address)
220        }
221        Value::BuiltinFunction { set, index } => {
222            format!("{} #{index}", function_set_label(image, set))
223        }
224        Value::Other { type_code, .. } => format!("type {type_code}"),
225    }
226}
227
228/// A constant string: a 16-bit length followed by its text.
229fn string_label(image: &Image, offset: u32) -> String {
230    let text = image.constant_pool.at(offset).and_then(|data| {
231        let len = u16::from_le_bytes([*data.first()?, *data.get(1)?]) as usize;
232        data.get(2..2 + len)
233    });
234    match text {
235        Some(text) => quote(text),
236        None => format!("string {offset:#x}"),
237    }
238}
239
240/// Quote text for a listing, shortening long strings.
241fn quote(text: &[u8]) -> String {
242    const LIMIT: usize = 48;
243    let text = String::from_utf8_lossy(text);
244    let mut out = String::from("\"");
245    for (count, c) in text.chars().enumerate() {
246        if count == LIMIT {
247            out.push_str("...");
248            break;
249        }
250        match c {
251            '"' => out.push_str("\\\""),
252            '\\' => out.push_str("\\\\"),
253            '\n' => out.push_str("\\n"),
254            '\t' => out.push_str("\\t"),
255            c if c.is_control() => {
256                let _ = write!(out, "\\x{:02x}", c as u32);
257            }
258            c => out.push(c),
259        }
260    }
261    out.push('"');
262    out
263}