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
use pcode_ir::{PcodeOp, Varnode};

// ---- Identifiers ----

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct BlockId(pub usize);

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct VarId(pub u32);

// ---- Diagnostics ----

/// Severity of a diagnostic emitted during decode/lift/SSA construction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Severity {
    /// Informational; benign approximation.
    Info,
    /// Approximation that may produce wrong output but is recoverable.
    Warn,
    /// Hard fallback — semantics likely lost (e.g. silent zero, sentinel).
    Error,
}

/// What kind of approximation/fallback fired.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DiagKind {
    /// `safe_var` returned the sentinel for an out-of-bounds VarId.
    OobVarId,
    /// CFG could not resolve a direct Branch/CBranch target to a leader; the
    /// terminator was downgraded to `Indirect`.
    UnresolvedBranchTarget,
    /// `build_expr` hit a PcodeOp variant it does not lower; the var carries
    /// `Expr::Unknown`.
    UnknownPcodeOp,
    /// Generated lift code emitted a zero-default for a missing dynamic
    /// token-field or context value.
    DynamicValueMissing,
    /// Generated lift code emitted a zero-default for a context-dependent
    /// value that was not wired through `ConstructorStruct.context_fields`.
    ContextNotWired,
    /// Memory aliasing/SSA stack-slot fallback to conservative unknown.
    StackAliasingUnknown,
    /// Indirect call could not be resolved through Load chain / GP-relative
    /// trace; left as `CallTarget::Indirect`.
    UnresolvedIndirectCall,
    /// Return value was inferred from a `call_return` clobber (the previous
    /// call wrote EAX/RAX/x0 etc. and the function returned without an
    /// explicit write). Without callsite information the decompiler cannot
    /// distinguish `int wrap() { return foo(); }` from `void f() { foo(); }`
    /// — both produce identical machine code. This diagnostic surfaces the
    /// ambiguity so callers can audit the inferred return.
    StaleReturnInherited,
}

/// One observation surfaced from the decode/lift/SSA pipeline.
#[derive(Clone, Debug)]
pub struct Diagnostic {
    pub severity: Severity,
    pub kind: DiagKind,
    /// Instruction address where the fallback fired, if known.
    pub addr: Option<u64>,
    pub detail: String,
}

// ---- CFG types ----

pub struct Cfg {
    pub blocks: Vec<BasicBlock>,
    pub entry: BlockId,
    /// Approximations recorded during CFG build (unresolved branch targets, etc.).
    pub diagnostics: Vec<Diagnostic>,
}

pub struct BasicBlock {
    pub id: BlockId,
    pub addr: u64,
    /// (instruction address, pcode op)
    pub ops: Vec<(u64, PcodeOp)>,
    pub terminator: Terminator,
}

#[derive(Debug, Clone)]
pub enum Terminator {
    Fallthrough(BlockId),
    Branch(BlockId),
    CBranch {
        cond: Varnode,
        taken: BlockId,
        fallthrough: BlockId,
    },
    Call {
        target: CallTarget,
        fallthrough: BlockId,
    },
    Return,
    Indirect(Varnode),
}

#[derive(Debug, Clone)]
pub enum CallTarget {
    Direct(u64),
    Indirect(Varnode),
}

// ---- SSA types ----

pub struct SsaCfg {
    pub blocks: Vec<SsaBlock>,
    pub vars: Vec<VarDef>,
    pub entry: BlockId,
    /// Approximations recorded during CFG construction and SSA build.
    /// Inherited from `Cfg.diagnostics` and extended by lift/SSA passes.
    pub diagnostics: Vec<Diagnostic>,
}

pub struct SsaBlock {
    pub id: BlockId,
    pub addr: u64,
    pub stmts: Vec<Stmt>,
    pub terminator: SsaTerminator,
}

#[derive(Debug, Clone)]
pub enum SsaTerminator {
    Fallthrough(BlockId),
    Branch(BlockId),
    CBranch {
        cond: VarId,
        taken: BlockId,
        fallthrough: BlockId,
    },
    Call {
        target: CallTarget,
        args: Vec<VarId>,
        out: Option<VarId>,
        fallthrough: BlockId,
    },
    Return(Option<VarId>),
    Indirect(VarId),
}

#[derive(Debug, Clone)]
pub enum Stmt {
    Assign(VarId),
    Store {
        addr: VarId,
        val: VarId,
    },
    Call {
        target: CallTarget,
        args: Vec<VarId>,
        out: Option<VarId>,
    },
}

/// Inferred type for a variable, propagated by the type inference pass.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InferredType {
    /// No type inferred yet — prints as uintN_t based on size
    Unknown,
    /// Explicitly unsigned (from unsigned ops like IntDiv, IntLess, IntZext)
    Unsigned,
    /// Signed integer (from IntSDiv, IntSLess, IntSext, IntSRight, IntNeg)
    Signed,
    /// IEEE 754 float (from FloatAdd, FloatMult, Int2Float, etc.)
    Float,
    /// Pointer (used as Load/Store address)
    Pointer,
    /// Boolean (comparison result, flag register, BoolAnd/BoolOr operand)
    Bool,
}

impl InferredType {
    /// Merge two types: if they agree, keep it; if they conflict, prefer the more specific.
    pub fn merge(self, other: InferredType) -> InferredType {
        if self == other {
            return self;
        }
        match (self, other) {
            (InferredType::Unknown, t) | (t, InferredType::Unknown) => t,
            // Signed wins over Unsigned (common in mixed contexts)
            (InferredType::Signed, InferredType::Unsigned)
            | (InferredType::Unsigned, InferredType::Signed) => InferredType::Signed,
            // Everything else: keep the first (don't corrupt)
            _ => self,
        }
    }
}

pub struct VarDef {
    pub id: VarId,
    pub varnode: Varnode,
    pub expr: Expr,
    pub size: u32,
    pub use_count: u32,
    /// If this var is a function parameter, its name (e.g. "param_0")
    pub param_name: Option<String>,
    /// If this var holds a call return value, the call's VarId
    pub call_return: bool,
    /// Inferred type from dataflow analysis
    pub inferred_type: InferredType,
    /// Display type name from signature database (e.g. "HANDLE", "DWORD", "LPCWSTR").
    /// When set, the printer uses this instead of mapping InferredType to a generic C type.
    /// Propagates through Var/Copy chains alongside InferredType.
    pub display_type: Option<&'static str>,
}

#[derive(Debug, Clone)]
pub enum Expr {
    Var(VarId),
    Const(u64, u32),
    BinOp(BinOpKind, VarId, VarId),
    UnaryOp(UnaryOpKind, VarId),
    Load(VarId),
    /// Struct field access: base pointer + byte offset.
    /// Recognized from Load(Add(base, Const(offset))) patterns.
    FieldAccess(VarId, u64),
    Phi(Vec<VarId>),
    /// Conditional select: cond != 0 ? then_val : else_val
    /// Generated from AArch64 CSEL-family intra-instruction CBranch patterns.
    Ternary(VarId, VarId, VarId),
    /// User-defined pcodeop / CALLOTHER. Corresponds to SLEIGH
    /// `define pcodeop` declarations (e.g. `software_interrupt`,
    /// `supervisor_call`). `func_id` is the SLEIGH user-function index;
    /// printer maps well-known IDs to readable names.
    UserOp {
        func_id: u64,
        inputs: Vec<VarId>,
    },
    Unknown,
}

#[derive(Debug, Clone, Copy)]
pub enum BinOpKind {
    Add,
    Sub,
    Mult,
    Div,
    SDiv,
    Rem,
    SRem,
    And,
    Or,
    Xor,
    Lsl,
    Lsr,
    Asr,
    Eq,
    NotEq,
    Less,
    LessEq,
    SLess,
    SLessEq,
    Carry,
    SCarry,
    SBorrow,
    BoolAnd,
    BoolOr,
    BoolXor,
    FloatAdd,
    FloatSub,
    FloatMult,
    FloatDiv,
    FloatEq,
    FloatNotEq,
    FloatLess,
    FloatLessEq,
}

#[derive(Debug, Clone, Copy)]
pub enum UnaryOpKind {
    Neg,
    Not,
    Zext,
    Sext,
    BoolNot,
    FloatNeg,
    FloatAbs,
    FloatSqrt,
    FloatNan,
    Int2Float,
    Float2Float,
    Trunc,
    FloatCeil,
    FloatFloor,
    FloatRound,
    Popcount,
    Lzcount,
}

// ---- Structured output types ----

#[derive(Debug, Clone)]
pub enum StructuredStmt {
    Assign {
        lhs: VarId,
        rhs: VarId,
    },
    Store {
        addr: VarId,
        val: VarId,
    },
    Call {
        target: CallTarget,
        args: Vec<VarId>,
        out: Option<VarId>,
    },
    Return(Option<VarId>),
    IfElse {
        cond: VarId,
        then_body: Vec<StructuredStmt>,
        else_body: Vec<StructuredStmt>,
    },
    While {
        cond: VarId,
        negate: bool,
        body: Vec<StructuredStmt>,
    },
    /// Post-tested loop: do { body } while (cond)
    DoWhile {
        cond: VarId,
        negate: bool,
        body: Vec<StructuredStmt>,
    },
    /// Switch/case recovered from if-else chains or jump tables.
    Switch {
        expr: VarId,
        cases: Vec<(Vec<i64>, Vec<StructuredStmt>)>, // (case values, body)
        default: Vec<StructuredStmt>,
    },
    Break,
    Continue,
    Goto(u64),
    Label(u64),
}

std::thread_local! {
    /// Counter for `safe_var` sentinel fallbacks within the current fold pass.
    /// Drained by `take_safe_var_oob_count` and surfaced as a single
    /// `OobVarId` diagnostic on `SsaCfg.diagnostics` so silent sentinel
    /// returns become observable without forcing the borrow checker to
    /// thread `&mut Vec<Diagnostic>` through every safe_var call site.
    static SAFE_VAR_OOB_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// Drain and return the in-thread safe_var OOB counter. Call once per
/// fold round; the returned value is the number of sentinel fallbacks
/// that fired since the last drain.
pub fn take_safe_var_oob_count() -> usize {
    SAFE_VAR_OOB_COUNT.with(|c| {
        let n = c.get();
        c.set(0);
        n
    })
}

/// Sentinel VarDef returned for out-of-bounds VarId lookups.
/// Prevents panics on malformed/adversarial input.
/// Safe VarDef lookup from a slice — returns sentinel for OOB access.
pub fn safe_var(vars: &[VarDef], id: VarId) -> &VarDef {
    match vars.get(id.0 as usize) {
        Some(v) => v,
        None => {
            SAFE_VAR_OOB_COUNT.with(|c| c.set(c.get() + 1));
            &SENTINEL_VARDEF
        }
    }
}

static SENTINEL_VARDEF: std::sync::LazyLock<VarDef> = std::sync::LazyLock::new(|| VarDef {
    id: VarId(u32::MAX),
    varnode: Varnode {
        space: pcode_ir::AddressSpaceId::Const,
        offset: 0,
        size: 0,
    },
    expr: Expr::Unknown,
    size: 0,
    use_count: 0,
    param_name: None,
    call_return: false,
    inferred_type: InferredType::Unknown,
    display_type: None,
});

impl SsaCfg {
    /// Safe variable lookup — returns a sentinel for out-of-bounds VarId
    /// instead of panicking. This is critical for handling malformed binaries
    /// that produce pathological P-code with invalid varnode references.
    pub fn var(&self, id: VarId) -> &VarDef {
        self.vars.get(id.0 as usize).unwrap_or(&SENTINEL_VARDEF)
    }

    pub fn var_mut(&mut self, id: VarId) -> &mut VarDef {
        let idx = id.0 as usize;
        if idx >= self.vars.len() {
            // Extend with sentinel entries to accommodate the index
            // This shouldn't happen in normal operation but prevents panic
            while self.vars.len() <= idx {
                self.vars.push(VarDef {
                    id: VarId(self.vars.len() as u32),
                    varnode: Varnode {
                        space: pcode_ir::AddressSpaceId::Const,
                        offset: 0,
                        size: 0,
                    },
                    expr: Expr::Unknown,
                    size: 0,
                    use_count: 0,
                    param_name: None,
                    call_return: false,
                    inferred_type: InferredType::Unknown,
                    display_type: None,
                });
            }
        }
        &mut self.vars[idx]
    }

    pub fn new_var(&mut self, varnode: Varnode, expr: Expr, size: u32) -> VarId {
        let id = VarId(self.vars.len() as u32);
        self.vars.push(VarDef {
            id,
            varnode,
            expr,
            size,
            use_count: 0,
            param_name: None,
            call_return: false,
            inferred_type: InferredType::Unknown,
            display_type: None,
        });
        id
    }
}