rsleigh-decompile 0.4.2

P-code decompiler — turns rsleigh P-code IR into C-like pseudocode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
pub mod analysis;
pub mod callgraph;
pub mod cfg;
// Heuristic-heavy modules whose shape may shift across patch versions.
// `experimental` is the only fully-isolated feature today: gating cpp_class
// and seh_static is the maximum we can do without unwinding the deeper
// fold/printer/decompile-pipeline coupling. Pinning the boundary at these
// two modules makes the limitation honest and gives the gate something
// concrete to enforce.
pub mod antidebug_timing;
pub mod api_resolver;
#[cfg(feature = "experimental")]
pub mod cpp_class;
pub mod crypto_constants;
pub mod dominators;
pub mod dwarf;
pub mod eh_frame;
pub mod eqsat;
pub mod fold;
pub mod function_summary;
pub mod go_pclntab;
pub mod handler_summary;
pub mod imports;
pub mod iot_capabilities;
pub mod iot_family;
pub mod ir;
pub mod jmp_rax_trampoline;
pub mod opaque_pred;
pub mod pdb_info;
pub mod peb_walk;
pub mod peb_walk_detect;
pub mod printer;
pub mod region;
pub mod rip_xref;
pub mod scratch_leak;
#[cfg(feature = "experimental")]
pub mod seh_static;
pub mod sha256_func_detect;
pub mod signatures;
mod signatures_crypto;
mod signatures_cxxabi;
mod signatures_libc;
mod signatures_msvcrt;
mod signatures_python;
mod signatures_win32;
pub mod smt_explore;
pub mod smt_verify;
pub mod ssa;
pub mod structure;
pub mod syscall_table;
pub mod tag_dispatch;
pub mod vm_bytecode_disasm;
pub mod vm_dispatch_extract;
pub mod vm_fingerprint;
pub mod vm_handler_classify;
pub mod vm_handler_cluster;
pub mod xor_strings;
pub mod xor_vtable; // used by printer

use pcode_ir::Instruction;
use rsleigh_api::Architecture;
use std::path::Path;

/// Detect calling convention from binary format and architecture.
fn detect_cc(arch: Architecture, binary: Option<&[u8]>) -> fold::CallingConv {
    if let Some(binary) = binary {
        // Go binaries carry a `.gopclntab` section. On amd64 use Go
        // internal ABI (RAX, RBX, RCX, RDI, RSI, R8-R11). Other arches
        // fall back to their platform convention for now.
        if arch == Architecture::X86_64 && is_go_binary(binary) {
            return fold::CallingConv::GoAmd64;
        }
        if let Ok(goblin::Object::PE(pe)) = goblin::Object::parse(binary) {
            return if pe.is_64 {
                fold::CallingConv::Win64
            } else {
                fold::CallingConv::Cdecl32
            };
        }
    }
    match arch {
        Architecture::X86_32 | Architecture::MIPS32 => fold::CallingConv::Cdecl32,
        Architecture::ARM32 => fold::CallingConv::Arm32,
        Architecture::AArch64 => fold::CallingConv::AArch64,
        _ => fold::CallingConv::SysV,
    }
}

fn is_go_binary(binary: &[u8]) -> bool {
    let Ok(obj) = goblin::Object::parse(binary) else {
        return false;
    };
    match &obj {
        goblin::Object::Elf(elf) => elf
            .section_headers
            .iter()
            .any(|sh| elf.shdr_strtab.get_at(sh.sh_name) == Some(".gopclntab")),
        goblin::Object::PE(pe) => pe
            .sections
            .iter()
            .any(|s| s.name().ok() == Some(".gopclntab")),
        _ => false,
    }
}

/// Decompile a function's instructions into C-like pseudocode.
pub fn decompile(arch: Architecture, instructions: &[(u64, Instruction)]) -> String {
    decompile_with_binary(arch, instructions, None, None)
}

/// Decompile with optional binary data for string literals and import resolution.
/// If `binary_path` is provided, DWARF debug info will be extracted (including from
/// macOS .dSYM bundles) to recover parameter and local variable names.
pub fn decompile_with_binary(
    arch: Architecture,
    instructions: &[(u64, Instruction)],
    binary: Option<&[u8]>,
    binary_path: Option<&Path>,
) -> String {
    if instructions.is_empty() {
        return "// empty function\n".to_string();
    }

    // Pass instructions through unchanged — intra-instruction CBranch (CSEL/CMOV)
    // patterns are handled by the SSA builder as Expr::Ternary, not as CFG branches.
    let expanded: Vec<(u64, pcode_ir::Instruction)> = instructions.to_vec();

    let cfg = cfg::build_cfg(&expanded);
    if cfg.blocks.is_empty() {
        return "// no blocks\n".to_string();
    }

    let import_map = binary
        .map(|b| imports::resolve_imports(b))
        .unwrap_or_default();

    let cc = detect_cc(arch, binary);
    let mut ssa = ssa::build_ssa_with_cc(&cfg, cc);

    fold::fold_with_cc(&mut ssa, cc);

    // Apply function signature parameter names and return types
    fold::apply_signature_names(&mut ssa, &import_map);
    fold::propagate_signature_return_types(&mut ssa, &import_map);

    // Phi → Ternary rewrite at conditional (non-loop) merges.
    // Runs AFTER fold + signature propagation so the Phi inputs are at
    // their simplest form (Const/Var after DCE). 2-way merges become
    // `(c) ? a : b`; N-way (3+) merges build a nested-ternary chain
    // when the predecessor groups partition cleanly across a CBranch
    // dominator tree. Non-destructive when the merge isn't a clean
    // dominator tree (loop / irreducible / cross-arm edges).
    fold::rewrite_conditional_phi_to_ternary(&mut ssa, &cfg);

    // Apply DWARF debug info if available: replace param_N with actual names
    let debug_info = if let Some(path) = binary_path {
        let info = dwarf::parse_dwarf_from_path(path);
        if !info.is_empty() {
            Some(info)
        } else {
            None
        }
    } else if let Some(binary) = binary {
        let info = dwarf::parse_dwarf(binary);
        if !info.is_empty() {
            Some(info)
        } else {
            None
        }
    } else {
        None
    };

    // Try PDB debug info for PE binaries when DWARF is absent
    let (pdb_debug_info, pdb_struct_fields) = if debug_info.is_none() {
        if let Some(path) = binary_path {
            pdb_info::parse_pdb_from_path(path)
        } else {
            (
                std::collections::HashMap::new(),
                std::collections::HashMap::new(),
            )
        }
    } else {
        (
            std::collections::HashMap::new(),
            std::collections::HashMap::new(),
        )
    };

    // Merge: prefer DWARF, fall back to PDB
    let effective_debug_info = if debug_info.is_some() {
        debug_info.clone()
    } else if !pdb_debug_info.is_empty() {
        Some(pdb_debug_info)
    } else {
        None
    };

    // Build local variable name map from debug info: var_N → actual_name
    let mut local_var_names = std::collections::HashMap::new();
    if let Some(ref debug_info) = effective_debug_info {
        let func_addr = instructions[0].0;
        if let Some(info) = debug_info.get(&func_addr) {
            // Apply parameter names
            for v in &mut ssa.vars {
                if let Some(ref param_name) = v.param_name {
                    if let Some(idx) = param_name
                        .strip_prefix("param_")
                        .and_then(|s| s.parse::<usize>().ok())
                    {
                        if let Some(dwarf_name) = info.param_names.get(idx) {
                            v.param_name = Some(dwarf_name.clone());
                        }
                    }
                }
            }
            // Build local variable name map: fbreg/stack offset → var_N name
            // Try both the direct mapping and an 8-byte adjusted mapping
            // (some toolchains have a consistent 8-byte offset between DWARF and actual layout)
            for (offset, name) in &info.local_names {
                if *offset < 0 {
                    let positive = (-offset) as u64;
                    let var_name = format!("var_{:x}", positive);
                    local_var_names.insert(var_name, name.clone());
                    let local_name = format!("local_{:x}", positive);
                    local_var_names.insert(local_name, name.clone());
                    // Also try with 8-byte adjustment (CFA vs RBP frame base mismatch)
                    let adjusted = positive + 8;
                    let adj_name = format!("var_{:x}", adjusted);
                    local_var_names
                        .entry(adj_name)
                        .or_insert_with(|| name.clone());
                    let adj_local_name = format!("local_{:x}", adjusted);
                    local_var_names
                        .entry(adj_local_name)
                        .or_insert_with(|| name.clone());
                } else if *offset > 0 {
                    let var_name = format!("var_{:x}", *offset as u64);
                    local_var_names.insert(var_name, name.clone());
                    let local_name = format!("local_{:x}", *offset as u64);
                    local_var_names.insert(local_name, name.clone());
                }
            }
        }
    }

    // Parse struct field names from DWARF, then PDB
    let mut struct_fields = if let Some(path) = binary_path {
        dwarf::parse_struct_fields_from_path(path)
    } else if let Some(binary) = binary {
        dwarf::parse_struct_fields(binary)
    } else {
        std::collections::HashMap::new()
    };
    // Merge PDB struct fields (don't overwrite DWARF fields)
    for (offset, name) in pdb_struct_fields {
        struct_fields.entry(offset).or_insert(name);
    }

    // Resolve function name from import map or DWARF
    let func_addr = instructions[0].0;
    let func_name = import_map
        .get(&func_addr)
        .cloned()
        .or_else(|| {
            debug_info
                .as_ref()
                .and_then(|di| {
                    di.get(&func_addr)
                        .and_then(|f| Some(f.param_names.first()?.clone()))
                })
                .and(None)
        }) // DWARF doesn't have func name easily
        .unwrap_or_else(|| format!("func_{:x}", func_addr));

    // Resolve try/catch regions from .eh_frame LSDA (C++ only; empty otherwise).
    let try_regions_map = if let Some(bin) = binary {
        eh_frame::parse_eh_frame(bin)
    } else {
        std::collections::HashMap::new()
    };
    let empty_regions: Vec<eh_frame::TryRegion> = Vec::new();
    let try_regions = try_regions_map.get(&func_addr).unwrap_or(&empty_regions);

    let structured = structure::recover_structure(&ssa, &cfg);
    printer::print_c_with_try(
        &structured,
        &ssa,
        arch,
        binary,
        &import_map,
        &local_var_names,
        &struct_fields,
        &func_name,
        try_regions,
    )
}

/// Learned type information for a function, extracted after decompilation.
/// Used for two-pass interprocedural type propagation.
#[derive(Debug, Clone)]
pub struct LearnedFuncType {
    pub addr: u64,
    pub param_types: Vec<Option<&'static str>>, // display_type per param (None = unknown)
    pub return_type: Option<&'static str>,      // display_type of return value
}

/// Extract type information from a function's SSA (after fold pass).
/// Call this after decompile_with_binary to learn parameter/return types,
/// then register them as synthetic signatures for the second pass.
pub fn extract_learned_types(
    arch: Architecture,
    instructions: &[(u64, Instruction)],
    binary: Option<&[u8]>,
) -> Option<LearnedFuncType> {
    if instructions.is_empty() {
        return None;
    }

    let mut expanded = Vec::new();
    for (addr, inst) in instructions {
        expanded.push((*addr, inst.clone()));
    }

    let cfg = cfg::build_cfg(&expanded);
    if cfg.blocks.is_empty() {
        return None;
    }

    let import_map = binary
        .map(|b| imports::resolve_imports(b))
        .unwrap_or_default();

    let cc = detect_cc(arch, binary);
    let mut ssa = ssa::build_ssa_with_cc(&cfg, cc);

    fold::fold_with_cc(&mut ssa, cc);
    fold::apply_signature_names(&mut ssa, &import_map);
    fold::propagate_signature_return_types(&mut ssa, &import_map);

    let func_addr = instructions[0].0;

    // Collect parameter types
    let mut params: Vec<(u32, Option<&'static str>)> = Vec::new();
    for v in &ssa.vars {
        if let Some(ref name) = v.param_name {
            if let Some(idx) = name
                .strip_prefix("param_")
                .and_then(|s| s.parse::<u32>().ok())
            {
                params.push((idx, v.display_type));
            }
        }
    }
    params.sort_by_key(|(idx, _)| *idx);
    params.dedup_by_key(|(idx, _)| *idx);
    let param_types: Vec<Option<&'static str>> = params.into_iter().map(|(_, dt)| dt).collect();

    // Collect return type
    let mut return_type = None;
    for block in &ssa.blocks {
        if let ir::SsaTerminator::Return(Some(v)) = &block.terminator {
            let vdef = ssa.var(*v);
            if let Some(dt) = vdef.display_type {
                return_type = Some(dt);
            }
            break;
        }
    }

    // Also detect non-void return even without display_type:
    // If any Return terminator has Some(var), the function returns a value.
    let has_return_val = ssa
        .blocks
        .iter()
        .any(|b| matches!(&b.terminator, ir::SsaTerminator::Return(Some(_))));
    if has_return_val && return_type.is_none() {
        // We know it returns something, just don't know the display type.
        // Mark as "int" (conservative — better than void).
        return_type = Some("int");
    }

    // Only return if we learned something useful
    if param_types.iter().any(|t| t.is_some()) || return_type.is_some() {
        Some(LearnedFuncType {
            addr: func_addr,
            param_types,
            return_type,
        })
    } else {
        None
    }
}

/// Learned struct parameter: records that a function's parameter was identified as a struct pointer.
/// Used for cross-function struct propagation in two-pass decompilation.
#[derive(Debug, Clone)]
pub struct LearnedStructParam {
    pub func_addr: u64,
    pub param_index: u32,
    pub struct_name: String,
}

/// Extract struct parameter identifications from decompiled output.
/// Parses "// param_N is STRUCT_NAME *" comments emitted by the printer's struct identification.
/// Also parses call sites to learn which arguments are struct pointers, enabling
/// propagation to callees.
pub fn extract_learned_structs(func_addr: u64, output: &str) -> Vec<LearnedStructParam> {
    let mut results = Vec::new();

    for line in output.lines() {
        let t = line.trim();
        // Match: "// param_N is STRUCT_NAME *"
        if let Some(rest) = t.strip_prefix("// param_") {
            if let Some(is_pos) = rest.find(" is ") {
                if let Ok(idx) = rest[..is_pos].parse::<u32>() {
                    let struct_part = &rest[is_pos + 4..];
                    let struct_name = struct_part.trim().trim_end_matches('*').trim();
                    if !struct_name.is_empty() {
                        results.push(LearnedStructParam {
                            func_addr,
                            param_index: idx,
                            struct_name: struct_name.to_string(),
                        });
                    }
                }
            }
        }
    }

    results
}

/// Analyze call sites in a function's SSA to infer which callees return non-void.
/// Returns a list of (callee_addr, inferred_return_type) pairs.
///
/// A callee is non-void if the caller:
/// - Reads the call return register (EAX/RAX) after the call
/// - Uses the result in a comparison, store, or as an argument to another call
pub fn infer_returns_from_callsites(
    arch: Architecture,
    instructions: &[(u64, Instruction)],
    binary: Option<&[u8]>,
) -> Vec<(u64, &'static str)> {
    if instructions.is_empty() {
        return Vec::new();
    }

    let mut expanded = Vec::new();
    for (addr, inst) in instructions {
        expanded.push((*addr, inst.clone()));
    }
    let cfg_result = cfg::build_cfg(&expanded);
    if cfg_result.blocks.is_empty() {
        return Vec::new();
    }

    let import_map = binary
        .map(|b| imports::resolve_imports(b))
        .unwrap_or_default();
    let cc = detect_cc(arch, binary);
    let mut ssa = ssa::build_ssa_with_cc(&cfg_result, cc);

    fold::fold_with_cc(&mut ssa, cc);

    let mut results = Vec::new();

    // Check Call terminators: if the fallthrough block reads EAX, the call returns a value
    for bi in 0..ssa.blocks.len() {
        let (target_addr, ft) = match &ssa.blocks[bi].terminator {
            ir::SsaTerminator::Call {
                target: ir::CallTarget::Direct(addr),
                fallthrough,
                ..
            } => (*addr, fallthrough.0),
            _ => continue,
        };

        // Skip known imports (they already have signatures)
        if import_map.contains_key(&target_addr) {
            continue;
        }

        // Check if the fallthrough block reads the call return register
        if ft < ssa.blocks.len() {
            for stmt in &ssa.blocks[ft].stmts {
                if let ir::Stmt::Assign(var_id) = stmt {
                    let vdef = &ssa.vars[var_id.0 as usize];
                    if vdef.call_return && vdef.use_count > 0 {
                        // The return value is used — callee is not void
                        results.push((target_addr, "int"));
                        break;
                    }
                }
            }
        }
    }

    // Also check Stmt::Call with out variable that has use_count > 0
    for block in &ssa.blocks {
        for stmt in &block.stmts {
            if let ir::Stmt::Call {
                target: ir::CallTarget::Direct(addr),
                out: Some(out_var),
                ..
            } = stmt
            {
                if import_map.contains_key(addr) {
                    continue;
                }
                let vdef = &ssa.vars[out_var.0 as usize];
                if vdef.use_count > 0 {
                    results.push((*addr, "int"));
                }
            }
        }
    }

    results.sort_by_key(|(addr, _)| *addr);
    results.dedup_by_key(|(addr, _)| *addr);
    results
}