Skip to main content

ruso_runtime/runtime/
disasm.rs

1//! Human-readable bytecode disassembly.
2
3use std::fmt::Write as _;
4
5use crate::contract::{
6    CmpOp, CmpValue, EvidenceKind, ExtractSource, FieldKind, MatchPredicate, QualifiedMatch,
7};
8use crate::runtime::binary;
9use crate::runtime::bytecode::{BytecodeProgram, Instr};
10use crate::runtime::spec::ProbeKind;
11
12/// Render a program as human-readable disassembly: metadata, the probe table,
13/// each constant pool, and the instruction stream with its operands resolved
14/// back to the strings and matchers they point at.
15///
16/// A debugging aid for inspecting what a compiler emitted — the output is not
17/// a format that can be parsed back into a program.
18pub fn format_human(bytecode: &BytecodeProgram) -> String {
19    let mut out = String::new();
20
21    writeln!(out, ";; metadata").ok();
22    format_metadata(&mut out, &bytecode.spec.metadata);
23    writeln!(out).ok();
24
25    writeln!(out, ";; probes ({})", bytecode.spec.probes.len()).ok();
26    let mut probe_names: Vec<_> = bytecode.spec.probes.keys().collect();
27    probe_names.sort();
28    for name in probe_names {
29        let kind = &bytecode.spec.probes[name];
30        writeln!(out, ";;   probe {name}: {}", format_probe_kind(kind)).ok();
31    }
32    writeln!(out).ok();
33
34    if !bytecode.strings.is_empty() {
35        writeln!(out, ";; strings").ok();
36        for (idx, value) in bytecode.strings.iter().enumerate() {
37            writeln!(out, ";;   [{idx}] {value:?}").ok();
38        }
39        writeln!(out).ok();
40    }
41
42    if !bytecode.matchers.is_empty() {
43        writeln!(out, ";; matchers").ok();
44        for (idx, matcher) in bytecode.matchers.iter().enumerate() {
45            writeln!(out, ";;   [{idx}] {}", format_matcher(matcher)).ok();
46        }
47        writeln!(out).ok();
48    }
49
50    if !bytecode.extracts.is_empty() {
51        writeln!(out, ";; extracts").ok();
52        for (idx, source) in bytecode.extracts.iter().enumerate() {
53            writeln!(out, ";;   [{idx}] {}", format_extract(source)).ok();
54        }
55        writeln!(out).ok();
56    }
57
58    if !bytecode.evidence.is_empty() {
59        writeln!(out, ";; evidence").ok();
60        for (idx, kind) in bytecode.evidence.iter().enumerate() {
61            writeln!(out, ";;   [{idx}] {}", format_evidence(kind)).ok();
62        }
63        writeln!(out).ok();
64    }
65
66    writeln!(out, ";; code ({} instructions)", bytecode.code.len()).ok();
67    for (pc, instr) in bytecode.code.iter().enumerate() {
68        writeln!(out, "  pc {pc:>3}: {}", format_instr(instr, bytecode)).ok();
69    }
70
71    out
72}
73
74fn format_metadata(out: &mut String, metadata: &crate::runtime::spec::CheckMetadata) {
75    if let Some(name) = &metadata.name {
76        writeln!(out, ";;   name: {name:?}").ok();
77    }
78    if let Some(description) = &metadata.description {
79        writeln!(out, ";;   description: {description:?}").ok();
80    }
81    if let Some(impact) = &metadata.impact {
82        writeln!(out, ";;   impact: {impact:?}").ok();
83    }
84    if let Some(severity) = &metadata.severity {
85        writeln!(out, ";;   severity: {}", severity.as_str()).ok();
86    }
87    if let Some(author) = &metadata.author {
88        writeln!(out, ";;   author: {author:?}").ok();
89    }
90    for cve in &metadata.cve {
91        writeln!(out, ";;   cve: {cve:?}").ok();
92    }
93    for cwe in &metadata.cwe {
94        writeln!(out, ";;   cwe: {cwe:?}").ok();
95    }
96    for reference in &metadata.references {
97        writeln!(out, ";;   references: {reference:?}").ok();
98    }
99    for cvss in &metadata.cvss {
100        writeln!(out, ";;   cvss: {cvss:?}").ok();
101    }
102    for score in &metadata.cvss_score {
103        writeln!(out, ";;   cvss_score: {score:?}").ok();
104    }
105    if let Some(mitigation) = &metadata.mitigation {
106        writeln!(out, ";;   mitigation: {mitigation:?}").ok();
107    }
108    for tag in &metadata.tags {
109        writeln!(out, ";;   tag: {tag:?}").ok();
110    }
111    if let Some(version) = &metadata.version {
112        writeln!(out, ";;   version: {version:?}").ok();
113    }
114    if let Some(family) = &metadata.family {
115        writeln!(out, ";;   family: {family:?}").ok();
116    }
117}
118
119fn format_probe_kind(kind: &ProbeKind) -> String {
120    match kind {
121        ProbeKind::Http(spec) => {
122            format!("http {} {}", format_http_method(&spec.method), spec.path)
123        }
124        ProbeKind::Dns(spec) => format_socket_probe("dns", spec),
125        ProbeKind::Tcp(spec) => format_socket_probe("tcp", spec),
126        ProbeKind::Udp(spec) => format_socket_probe("udp", spec),
127    }
128}
129
130fn format_socket_probe(label: &str, spec: &crate::runtime::spec::SocketProbeSpec) -> String {
131    let mut line = format!("{label} host={:?}", spec.host);
132    if let Some(port) = spec.port {
133        line.push_str(&format!(" port={port}"));
134    }
135    if let Some(payload) = &spec.payload {
136        let is_text = payload.iter().all(|b| {
137            b.is_ascii_graphic() || *b == b' ' || *b == b'\r' || *b == b'\n' || *b == b'\t'
138        });
139        let shown = if is_text {
140            // Decode lossy as text — `format!("{:?}", Vec<u8>)` would
141            // print "[80, 73, 78, 71]" instead of "\"PING\"".
142            let text = String::from_utf8_lossy(payload);
143            format!("{text:?}")
144        } else {
145            format!("0x{}", crate::runtime::binary::bytes_to_hex(payload))
146        };
147        line.push_str(&format!(" payload={shown}"));
148    }
149    if label == "dns" && spec.is_dns_resolver_mode() {
150        line.push_str(" (resolver)");
151    }
152    line
153}
154
155fn format_http_method(method: &crate::contract::HttpMethod) -> &'static str {
156    use crate::contract::HttpMethod;
157    match method {
158        HttpMethod::Get => "GET",
159        HttpMethod::Post => "POST",
160        HttpMethod::Put => "PUT",
161        HttpMethod::Patch => "PATCH",
162        HttpMethod::Delete => "DELETE",
163        HttpMethod::Head => "HEAD",
164        HttpMethod::Options => "OPTIONS",
165    }
166}
167
168fn format_matcher(matcher: &QualifiedMatch) -> String {
169    let field = match &matcher.field.kind {
170        FieldKind::Status => "status".to_string(),
171        FieldKind::Body => "body".to_string(),
172        FieldKind::Header(name) => format!("header({name:?})"),
173        FieldKind::ResponseTime => "response_time".to_string(),
174        FieldKind::ResponseSize => "response_size".to_string(),
175        FieldKind::Answer => "answer".to_string(),
176        FieldKind::Banner => "banner".to_string(),
177        FieldKind::Response => "response".to_string(),
178    };
179    format!(
180        "{}.{} {}",
181        matcher.field.target,
182        field,
183        format_predicate(&matcher.predicate)
184    )
185}
186
187fn format_predicate(predicate: &MatchPredicate) -> String {
188    match predicate {
189        MatchPredicate::Compare { op, value } => {
190            format!("{} {}", format_cmp_op(*op), format_cmp_value(value))
191        }
192        MatchPredicate::Contains(text) => format!("contains {text:?}"),
193        MatchPredicate::NotContains(text) => format!("not_contains {text:?}"),
194        MatchPredicate::Regex(pattern) => format!("regex {pattern:?}"),
195    }
196}
197
198fn format_cmp_op(op: CmpOp) -> &'static str {
199    match op {
200        CmpOp::Eq => "==",
201        CmpOp::Ne => "!=",
202        CmpOp::Lt => "<",
203        CmpOp::Gt => ">",
204        CmpOp::Le => "<=",
205        CmpOp::Ge => ">=",
206    }
207}
208
209fn format_cmp_value(value: &CmpValue) -> String {
210    match value {
211        CmpValue::Number(n) => n.to_string(),
212        CmpValue::String(s) => format!("{s:?}"),
213        CmpValue::Duration(d) => d.clone(),
214    }
215}
216
217fn format_extract(source: &ExtractSource) -> String {
218    match source {
219        ExtractSource::Body { target, regex } => match regex {
220            Some(pattern) => format!("body from {target} regex {pattern:?}"),
221            None => format!("body from {target}"),
222        },
223        ExtractSource::Header { target, name } => {
224            format!("header {name:?} from {target}")
225        }
226    }
227}
228
229fn format_evidence(kind: &EvidenceKind) -> String {
230    let re = |p: &Option<String>| match p {
231        Some(pat) => format!(" regex {pat:?}"),
232        None => String::new(),
233    };
234    match kind {
235        EvidenceKind::Body { target, pattern } => format!("{target}.body{}", re(pattern)),
236        EvidenceKind::Response { target, pattern } => format!("{target}.response{}", re(pattern)),
237        EvidenceKind::Header {
238            target,
239            name,
240            pattern,
241        } => format!("{target}.header {name:?}{}", re(pattern)),
242    }
243}
244
245fn format_instr(instr: &Instr, bytecode: &BytecodeProgram) -> String {
246    let str_at = |idx: u32| -> String {
247        bytecode
248            .strings
249            .get(idx as usize)
250            .map(|s| format!("{s:?}"))
251            .unwrap_or_else(|| format!("#{idx}?"))
252    };
253    // Use `.get()` rather than direct slicing so corrupt-but-decodable
254    // bytecode (start/len pointing past the string pool) cannot panic the
255    // disassembler — important because `ruso disasm` is reachable from
256    // untrusted `.rbc` files.
257    let string_span = |start: u32, len: u16| -> String {
258        let start = start as usize;
259        let end = start.saturating_add(len as usize);
260        match bytecode.strings.get(start..end) {
261            Some(slice) => slice
262                .iter()
263                .map(|value| format!("{value:?}"))
264                .collect::<Vec<_>>()
265                .join(", "),
266            None => format!("<oob {start}..{end}>"),
267        }
268    };
269
270    match instr {
271        Instr::Set { name, value } => {
272            format!("Set name={} value={}", str_at(*name), str_at(*value))
273        }
274        Instr::SetList { name, start, len } => {
275            format!(
276                "SetList name={} values=[{}]",
277                str_at(*name),
278                string_span(*start, *len)
279            )
280        }
281        Instr::Send { probe, payload } => {
282            if let Some(id) = payload {
283                format!(
284                    "Send {} payload=[{}]",
285                    str_at(*probe),
286                    bytecode
287                        .payloads
288                        .get(*id as usize)
289                        .map(|p| binary::bytes_to_hex(p))
290                        .unwrap_or_else(|| format!("#{id}?"))
291                )
292            } else {
293                format!("Send {}", str_at(*probe))
294            }
295        }
296        Instr::Match(matcher) => format!("Match [{}]", matcher),
297        Instr::MatchAll { start, len } => format!("MatchAll [{start}..{}]", start + *len as u32),
298        Instr::MatchAny { start, len } => format!("MatchAny [{start}..{}]", start + *len as u32),
299        Instr::Assert(matcher) => format!("Assert [{}]", matcher),
300        Instr::Extract { name, source } => {
301            format!("Extract name={} source=[{}]", str_at(*name), source)
302        }
303        Instr::IfMatch { matcher, else_pc } => {
304            format!("IfMatch [{}] else_pc={else_pc}", matcher)
305        }
306        Instr::ForList {
307            item,
308            start,
309            len,
310            end_pc,
311        } => format!(
312            "ForList item={} values=[{}] end_pc={end_pc}",
313            str_at(*item),
314            string_span(*start, *len)
315        ),
316        Instr::ForVar { item, list, end_pc } => {
317            format!(
318                "ForVar item={} list={} end_pc={end_pc}",
319                str_at(*item),
320                str_at(*list)
321            )
322        }
323        Instr::LoopBack => "LoopBack".into(),
324        Instr::Break => "Break".into(),
325        Instr::Save { from, to } => {
326            format!("Save {} as {}", str_at(*from), str_at(*to))
327        }
328        Instr::Evidence(kind) => format!("Evidence [{}]", kind),
329        Instr::Retry { probe, count } => {
330            format!("Retry {} count={count}", str_at(*probe))
331        }
332        Instr::RetryDelay(value) => format!("RetryDelay {}", str_at(*value)),
333        Instr::Sleep(value) => format!("Sleep {}", str_at(*value)),
334        Instr::Stop => "Stop".into(),
335        Instr::Fail => "Fail".into(),
336        Instr::Continue => "Continue".into(),
337        Instr::Exit => "Exit".into(),
338    }
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344    use crate::runtime::bytecode::Instr;
345    use crate::runtime::spec::{CheckMetadata, ProgramSpec};
346
347    fn empty_bytecode() -> BytecodeProgram {
348        BytecodeProgram {
349            spec: ProgramSpec {
350                probes: Default::default(),
351                metadata: CheckMetadata::default(),
352            },
353            code: vec![],
354            strings: vec![],
355            payloads: vec![],
356            matchers: vec![],
357            extracts: vec![],
358            evidence: vec![],
359        }
360    }
361
362    #[test]
363    fn out_of_bounds_string_span_does_not_panic() {
364        // Crafted (corrupt) bytecode where ForList claims a string span
365        // beyond the actual pool. Pre-fix this would panic in the
366        // disassembler — now it should render a sentinel.
367        let bytecode = BytecodeProgram {
368            code: vec![Instr::ForList {
369                item: 99,
370                start: 99,
371                len: 5,
372                end_pc: 0,
373            }],
374            ..empty_bytecode()
375        };
376        let out = format_human(&bytecode);
377        assert!(out.contains("<oob"), "expected oob sentinel, got:\n{out}");
378    }
379}