neo-decompiler 0.11.0

Neo N3 NEF decompiler: parse, disassemble, lift bytecode to high-level pseudocode and C# skeletons, with a CLI, JSON reports, and optional WebAssembly bindings.
Documentation
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
use super::*;
use crate::decompiler::cfg::ssa::DominanceInfo;
use crate::decompiler::cfg::ssa::SsaForm;
use crate::decompiler::cfg::ssa::{SsaBlock, SsaExpr, SsaStmt, SsaVariable};
use crate::decompiler::cfg::{BasicBlock, BlockId, Cfg, EdgeKind, Terminator};
use crate::decompiler::ir::{BinOp, ControlFlow, Literal, Stmt};

fn v(base: &str, n: usize) -> SsaVariable {
    SsaVariable::new(base.to_string(), n)
}

/// Build a diamond: BB0 branches to BB1/BB2, both jump to BB3 (merge/ret).
fn diamond_cfg() -> Cfg {
    let mut cfg = Cfg::new();
    cfg.add_block(BasicBlock::new(
        BlockId(0),
        0,
        1,
        0..1,
        Terminator::Branch {
            then_target: BlockId(1),
            else_target: BlockId(2),
        },
    ));
    cfg.add_block(BasicBlock::new(
        BlockId(1),
        1,
        2,
        1..2,
        Terminator::Jump { target: BlockId(3) },
    ));
    cfg.add_block(BasicBlock::new(
        BlockId(2),
        2,
        3,
        2..3,
        Terminator::Jump { target: BlockId(3) },
    ));
    cfg.add_block(BasicBlock::new(BlockId(3), 3, 4, 3..4, Terminator::Return));
    cfg.add_edge(BlockId(0), BlockId(1), EdgeKind::ConditionalTrue);
    cfg.add_edge(BlockId(0), BlockId(2), EdgeKind::ConditionalFalse);
    cfg.add_edge(BlockId(1), BlockId(3), EdgeKind::Unconditional);
    cfg.add_edge(BlockId(2), BlockId(3), EdgeKind::Unconditional);
    cfg
}

fn block_with(stmts: Vec<SsaStmt>) -> SsaBlock {
    let mut b = SsaBlock::new();
    for s in stmts {
        b.add_stmt(s);
    }
    b
}

#[test]
fn structures_a_diamond_into_an_if_else() {
    let cfg = diamond_cfg();
    let mut blocks = std::collections::BTreeMap::new();
    // BB0: condition def  b0_0 = (loc0 < 1)
    blocks.insert(
        BlockId(0),
        block_with(vec![SsaStmt::assign(
            v("b0", 0),
            SsaExpr::binary(
                BinOp::Lt,
                SsaExpr::var(v("loc0", 0)),
                SsaExpr::lit(Literal::Int(1)),
            ),
        )]),
    );
    // BB1 (then): b1_0 = 10
    blocks.insert(
        BlockId(1),
        block_with(vec![SsaStmt::assign(
            v("b1", 0),
            SsaExpr::lit(Literal::Int(10)),
        )]),
    );
    // BB2 (else): b2_0 = 20
    blocks.insert(
        BlockId(2),
        block_with(vec![SsaStmt::assign(
            v("b2", 0),
            SsaExpr::lit(Literal::Int(20)),
        )]),
    );
    blocks.insert(BlockId(3), SsaBlock::new());

    let ssa = SsaForm {
        cfg,
        dominance: DominanceInfo::new(),
        blocks,
        definitions: std::collections::BTreeMap::new(),
        uses: std::collections::BTreeMap::new(),
    };

    let structured = structure(&ssa);

    // Expect: condition assign, then an If ControlFlow with both branches.
    let has_if = structured
        .stmts
        .iter()
        .any(|s| matches!(s, Stmt::ControlFlow(cf) if matches!(**cf, ControlFlow::If { .. })));
    assert!(
        has_if,
        "expected an If ControlFlow; got {:?}",
        structured.stmts
    );

    let if_cf = structured
        .stmts
        .iter()
        .rev()
        .find_map(|s| match s {
            Stmt::ControlFlow(cf) => Some(cf),
            _ => None,
        })
        .expect("an If node");
    let ControlFlow::If {
        then_branch,
        else_branch,
        ..
    } = if_cf.as_ref()
    else {
        panic!("expected If, got {if_cf:?}");
    };
    assert!(!then_branch.is_empty(), "then-branch should carry BB1 body");
    assert!(
        else_branch.is_some(),
        "an if-else diamond should yield an else branch"
    );
}

/// The if-condition must inline the comparison that drives the branch, not
/// render the bare reaching-definition variable. When BB0's last def is
/// `t = (loc0 < 1)`, the condition must be `(loc0 < 1)` and the def must
/// NOT be duplicated as a body statement.
#[test]
fn inlines_branch_comparison_condition_and_does_not_duplicate_it() {
    let mut cfg = Cfg::new();
    cfg.add_block(BasicBlock::new(
        BlockId(0),
        0,
        1,
        0..1,
        Terminator::Branch {
            then_target: BlockId(1),
            else_target: BlockId(2),
        },
    ));
    cfg.add_block(BasicBlock::new(
        BlockId(1),
        1,
        2,
        1..2,
        Terminator::Jump { target: BlockId(3) },
    ));
    cfg.add_block(BasicBlock::new(
        BlockId(2),
        2,
        3,
        2..3,
        Terminator::Jump { target: BlockId(3) },
    ));
    cfg.add_block(BasicBlock::new(BlockId(3), 3, 4, 3..4, Terminator::Return));
    cfg.add_edge(BlockId(0), BlockId(1), EdgeKind::ConditionalTrue);
    cfg.add_edge(BlockId(0), BlockId(2), EdgeKind::ConditionalFalse);
    cfg.add_edge(BlockId(1), BlockId(3), EdgeKind::Unconditional);
    cfg.add_edge(BlockId(2), BlockId(3), EdgeKind::Unconditional);

    let mut blocks = std::collections::BTreeMap::new();
    // BB0: only the comparison def — it IS the branch condition.
    blocks.insert(
        BlockId(0),
        block_with(vec![SsaStmt::assign(
            v("t", 0),
            SsaExpr::binary(
                BinOp::Lt,
                SsaExpr::var(v("loc0", 0)),
                SsaExpr::lit(Literal::Int(1)),
            ),
        )]),
    );
    blocks.insert(
        BlockId(1),
        block_with(vec![SsaStmt::assign(
            v("b1", 0),
            SsaExpr::lit(Literal::Int(10)),
        )]),
    );
    blocks.insert(
        BlockId(2),
        block_with(vec![SsaStmt::assign(
            v("b2", 0),
            SsaExpr::lit(Literal::Int(20)),
        )]),
    );
    blocks.insert(BlockId(3), SsaBlock::new());

    let ssa = SsaForm {
        cfg,
        dominance: DominanceInfo::new(),
        blocks,
        definitions: std::collections::BTreeMap::new(),
        uses: std::collections::BTreeMap::new(),
    };

    let structured = structure(&ssa);
    let rendered = crate::decompiler::ir::render_block(&structured, 0);

    // The condition must be the inlined comparison (versioned SSA name `loc0_0`,
    // double parens are a renderer quirk around a parenthesised Binary).
    assert!(
        rendered.contains("loc0 < 1"),
        "branch condition should inline the comparison; got:\n{rendered}"
    );
    // And it must NOT render the bare reaching-definition variable as the
    // condition.
    assert!(
        !rendered.contains("if (t_0)") && !rendered.contains("if (t)"),
        "branch condition should not be the bare t_0; got:\n{rendered}"
    );
    // The comparison def must not be duplicated as a body assignment.
    assert!(
        !rendered.contains("t_0 ="),
        "the comparison def must be consumed by the condition, not emitted in the body; got:\n{rendered}"
    );
}

#[test]
fn straight_line_cfg_emits_flat_block() {
    let mut cfg = Cfg::new();
    cfg.add_block(BasicBlock::new(BlockId(0), 0, 1, 0..2, Terminator::Return));
    let mut blocks = std::collections::BTreeMap::new();
    blocks.insert(
        BlockId(0),
        block_with(vec![
            SsaStmt::assign(v("b0", 0), SsaExpr::lit(Literal::Int(1))),
            SsaStmt::assign(v("b0", 1), SsaExpr::lit(Literal::Int(2))),
        ]),
    );
    let ssa = SsaForm {
        cfg,
        dominance: DominanceInfo::new(),
        blocks,
        definitions: std::collections::BTreeMap::new(),
        uses: std::collections::BTreeMap::new(),
    };
    let structured = structure(&ssa);
    let assigns = structured
        .stmts
        .iter()
        .filter(|s| matches!(s, Stmt::Assign { .. }))
        .count();
    // One assignment emitted directly; the last assignment becomes the
    // return value (the block's terminator is Return).
    assert_eq!(
        assigns,
        1,
        "first assignment emitted, last becomes return value:\n{}",
        crate::decompiler::ir::render_block(&structured, 0)
    );
    assert!(matches!(structured.stmts[0], Stmt::Assign { .. }));
    // The return statement should carry the last assignment's expression.
    assert!(matches!(structured.stmts[1], Stmt::Return(Some(_))));
}

/// A while loop: BB0 (header) branches to BB1 (body) / BB2 (exit); BB1
/// jumps back to BB0. dominance(BB0 ≥ BB1) makes BB0 a loop header.
#[test]
fn structures_a_back_edge_into_a_while_loop() {
    let mut cfg = Cfg::new();
    cfg.add_block(BasicBlock::new(
        BlockId(0),
        0,
        1,
        0..1,
        Terminator::Branch {
            then_target: BlockId(1),
            else_target: BlockId(2),
        },
    ));
    cfg.add_block(BasicBlock::new(
        BlockId(1),
        1,
        2,
        1..2,
        Terminator::Jump { target: BlockId(0) },
    ));
    cfg.add_block(BasicBlock::new(BlockId(2), 2, 3, 2..3, Terminator::Return));
    cfg.add_edge(BlockId(0), BlockId(1), EdgeKind::ConditionalTrue);
    cfg.add_edge(BlockId(0), BlockId(2), EdgeKind::ConditionalFalse);
    cfg.add_edge(BlockId(1), BlockId(0), EdgeKind::Unconditional);
    let dominance = crate::decompiler::cfg::ssa::compute(&cfg);

    let mut blocks = std::collections::BTreeMap::new();
    // header condition def: b0_0 = (loc0 < 3)
    blocks.insert(
        BlockId(0),
        block_with(vec![SsaStmt::assign(
            v("t", 0),
            SsaExpr::binary(
                BinOp::Lt,
                SsaExpr::var(v("loc0", 0)),
                SsaExpr::lit(Literal::Int(3)),
            ),
        )]),
    );
    // body: b1_0 = 1
    blocks.insert(
        BlockId(1),
        block_with(vec![SsaStmt::assign(
            v("t", 1),
            SsaExpr::lit(Literal::Int(1)),
        )]),
    );
    blocks.insert(BlockId(2), SsaBlock::new());

    let ssa = SsaForm {
        cfg,
        dominance,
        blocks,
        definitions: std::collections::BTreeMap::new(),
        uses: std::collections::BTreeMap::new(),
    };

    let structured = structure(&ssa);
    let has_while = structured
        .stmts
        .iter()
        .any(|s| matches!(s, Stmt::ControlFlow(cf) if matches!(**cf, ControlFlow::While { .. })));
    assert!(
        has_while,
        "a back-edge branch should structure as a While; got {:?}",
        structured.stmts
    );
}

/// A try/catch: TryEntry{body, catch, finally=None}; body and catch both
/// reach an EndTry whose continuation is the post-try block.
#[test]
fn structures_a_try_entry_into_try_catch() {
    let mut cfg = Cfg::new();
    cfg.add_block(BasicBlock::new(
        BlockId(0),
        0,
        1,
        0..1,
        Terminator::TryEntry {
            body_target: BlockId(1),
            catch_target: Some(BlockId(2)),
            finally_target: None,
        },
    ));
    cfg.add_block(BasicBlock::new(
        BlockId(1),
        1,
        2,
        1..2,
        Terminator::Jump { target: BlockId(3) },
    ));
    cfg.add_block(BasicBlock::new(
        BlockId(2),
        2,
        3,
        2..3,
        Terminator::Jump { target: BlockId(3) },
    ));
    cfg.add_block(BasicBlock::new(
        BlockId(3),
        3,
        4,
        3..4,
        Terminator::EndTry {
            continuation: BlockId(4),
        },
    ));
    cfg.add_block(BasicBlock::new(BlockId(4), 4, 5, 4..5, Terminator::Return));
    cfg.add_edge(BlockId(0), BlockId(1), EdgeKind::Unconditional);
    cfg.add_edge(BlockId(0), BlockId(2), EdgeKind::Unconditional);
    cfg.add_edge(BlockId(1), BlockId(3), EdgeKind::Unconditional);
    cfg.add_edge(BlockId(2), BlockId(3), EdgeKind::Unconditional);
    let dominance = crate::decompiler::cfg::ssa::compute(&cfg);

    let mut blocks = std::collections::BTreeMap::new();
    blocks.insert(
        BlockId(1),
        block_with(vec![SsaStmt::assign(
            v("t", 0),
            SsaExpr::lit(Literal::Int(1)),
        )]),
    );
    blocks.insert(
        BlockId(2),
        block_with(vec![SsaStmt::assign(
            v("t", 1),
            SsaExpr::lit(Literal::Int(2)),
        )]),
    );
    blocks.insert(BlockId(0), SsaBlock::new());
    blocks.insert(BlockId(3), SsaBlock::new());
    blocks.insert(BlockId(4), SsaBlock::new());

    let ssa = SsaForm {
        cfg,
        dominance,
        blocks,
        definitions: std::collections::BTreeMap::new(),
        uses: std::collections::BTreeMap::new(),
    };

    let structured = structure(&ssa);
    let has_try = structured.stmts.iter().any(
        |s| matches!(s, Stmt::ControlFlow(cf) if matches!(**cf, ControlFlow::TryCatch { .. })),
    );
    assert!(
        has_try,
        "a TryEntry should structure as TryCatch; got {:?}",
        structured.stmts
    );
}

/// A do-while: BB0 (body entry, falls through to the latch) is the loop
/// header; BB1 (latch) tests the condition and branches back to BB0 or out
/// to BB2. BB0 dominates BB1, so BB0 is a loop header whose terminator is
/// not a Branch → do-while.
#[test]
fn structures_a_bottom_tested_loop_into_do_while() {
    let mut cfg = Cfg::new();
    cfg.add_block(BasicBlock::new(
        BlockId(0),
        0,
        1,
        0..1,
        Terminator::Fallthrough { target: BlockId(1) },
    ));
    cfg.add_block(BasicBlock::new(
        BlockId(1),
        1,
        2,
        1..2,
        Terminator::Branch {
            then_target: BlockId(0),
            else_target: BlockId(2),
        },
    ));
    cfg.add_block(BasicBlock::new(BlockId(2), 2, 3, 2..3, Terminator::Return));
    cfg.add_edge(BlockId(0), BlockId(1), EdgeKind::Unconditional);
    cfg.add_edge(BlockId(1), BlockId(0), EdgeKind::ConditionalTrue);
    cfg.add_edge(BlockId(1), BlockId(2), EdgeKind::ConditionalFalse);
    let dominance = crate::decompiler::cfg::ssa::compute(&cfg);

    let mut blocks = std::collections::BTreeMap::new();
    // body: b0_0 = step()
    blocks.insert(
        BlockId(0),
        block_with(vec![SsaStmt::assign(
            v("t", 0),
            SsaExpr::call("step".to_string(), vec![]),
        )]),
    );
    // latch condition: b1_0 = (loc0 < 3)
    blocks.insert(
        BlockId(1),
        block_with(vec![SsaStmt::assign(
            v("t", 1),
            SsaExpr::binary(
                BinOp::Lt,
                SsaExpr::var(v("loc0", 0)),
                SsaExpr::lit(Literal::Int(3)),
            ),
        )]),
    );
    blocks.insert(BlockId(2), SsaBlock::new());

    let ssa = SsaForm {
        cfg,
        dominance,
        blocks,
        definitions: std::collections::BTreeMap::new(),
        uses: std::collections::BTreeMap::new(),
    };

    let structured = structure(&ssa);
    let has_dowhile = structured
        .stmts
        .iter()
        .any(|s| matches!(s, Stmt::ControlFlow(cf) if matches!(**cf, ControlFlow::DoWhile { .. })));
    assert!(
        has_dowhile,
        "a bottom-tested loop should structure as DoWhile; got {:?}",
        structured.stmts
    );
}

/// A switch: an equality cascade on one scrutinee. B0 compares `loc0 == 0`
/// → case0 body, else B1; B1 compares `loc0 == 1` → case1 body, else B2
/// (default); all bodies join at the merge B5.
#[test]
fn structures_an_equality_cascade_into_a_switch() {
    let mut cfg = Cfg::new();
    // B0: loc0 == 0 ? case0 : B1
    cfg.add_block(BasicBlock::new(
        BlockId(0),
        0,
        1,
        0..1,
        Terminator::Branch {
            then_target: BlockId(3),
            else_target: BlockId(1),
        },
    ));
    // B1: loc0 == 1 ? case1 : default(B2)
    cfg.add_block(BasicBlock::new(
        BlockId(1),
        1,
        2,
        1..2,
        Terminator::Branch {
            then_target: BlockId(4),
            else_target: BlockId(2),
        },
    ));
    // B2 (default) -> merge
    cfg.add_block(BasicBlock::new(
        BlockId(2),
        2,
        3,
        2..3,
        Terminator::Jump { target: BlockId(5) },
    ));
    // B3 (case0 body) -> merge
    cfg.add_block(BasicBlock::new(
        BlockId(3),
        3,
        4,
        3..4,
        Terminator::Jump { target: BlockId(5) },
    ));
    // B4 (case1 body) -> merge
    cfg.add_block(BasicBlock::new(
        BlockId(4),
        4,
        5,
        4..5,
        Terminator::Jump { target: BlockId(5) },
    ));
    // B5 (merge)
    cfg.add_block(BasicBlock::new(BlockId(5), 5, 6, 5..6, Terminator::Return));
    cfg.add_edge(BlockId(0), BlockId(3), EdgeKind::ConditionalTrue);
    cfg.add_edge(BlockId(0), BlockId(1), EdgeKind::ConditionalFalse);
    cfg.add_edge(BlockId(1), BlockId(4), EdgeKind::ConditionalTrue);
    cfg.add_edge(BlockId(1), BlockId(2), EdgeKind::ConditionalFalse);
    cfg.add_edge(BlockId(2), BlockId(5), EdgeKind::Unconditional);
    cfg.add_edge(BlockId(3), BlockId(5), EdgeKind::Unconditional);
    cfg.add_edge(BlockId(4), BlockId(5), EdgeKind::Unconditional);
    let dominance = crate::decompiler::cfg::ssa::compute(&cfg);

    let mut blocks = std::collections::BTreeMap::new();
    // B0: t0 = (loc0 == 0)
    blocks.insert(
        BlockId(0),
        block_with(vec![SsaStmt::assign(
            v("t", 0),
            SsaExpr::binary(
                BinOp::Eq,
                SsaExpr::var(v("loc0", 0)),
                SsaExpr::lit(Literal::Int(0)),
            ),
        )]),
    );
    // B1: t1 = (loc0 == 1)
    blocks.insert(
        BlockId(1),
        block_with(vec![SsaStmt::assign(
            v("t", 1),
            SsaExpr::binary(
                BinOp::Eq,
                SsaExpr::var(v("loc0", 1)),
                SsaExpr::lit(Literal::Int(1)),
            ),
        )]),
    );
    blocks.insert(
        BlockId(2),
        block_with(vec![SsaStmt::assign(
            v("loc0", 4),
            SsaExpr::lit(Literal::Int(12)),
        )]),
    );
    blocks.insert(
        BlockId(3),
        block_with(vec![SsaStmt::assign(
            v("loc0", 2),
            SsaExpr::lit(Literal::Int(10)),
        )]),
    );
    blocks.insert(
        BlockId(4),
        block_with(vec![SsaStmt::assign(
            v("loc0", 3),
            SsaExpr::lit(Literal::Int(11)),
        )]),
    );
    blocks.insert(BlockId(5), SsaBlock::new());

    let ssa = SsaForm {
        cfg,
        dominance,
        blocks,
        definitions: std::collections::BTreeMap::new(),
        uses: std::collections::BTreeMap::new(),
    };

    let structured = structure(&ssa);
    let has_switch = structured
        .stmts
        .iter()
        .any(|s| matches!(s, Stmt::ControlFlow(cf) if matches!(**cf, ControlFlow::Switch { .. })));
    assert!(
        has_switch,
        "an equality cascade on one scrutinee should structure as a Switch; got {:?}",
        structured.stmts
    );
}