vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
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
use super::*;

#[test]
fn a_flagless_check_bounds_the_table() {
    // v0 = idx < 24 ? 1 : 0; if (v0 == 0) goto default
    let check = |limit: Expr, then: u64| Block {
        start: 0x1000,
        stmts: vec![
            Stmt::Assign {
                dest: vlk_ir::ir::RegRef {
                    index: 0,
                    width: 64,
                },
                value: Expr::bin(
                    BinOp::And,
                    Expr::Select {
                        cond: vlk_ir::ir::Cond::Cc,
                        lhs: Box::new(Expr::reg(3, 32)),
                        rhs: Box::new(limit),
                        then: Box::new(Expr::Const(then)),
                        els: Box::new(Expr::Const(0)),
                    },
                    Expr::Const(0xffff_ffff),
                ),
                at: None,
            },
            Stmt::Brif {
                cond: vlk_ir::ir::Cond::Eq,
                lhs: Expr::reg(0, 32),
                rhs: Expr::Const(0),
                target: 0x2000,
                at: None,
            },
        ],
    };
    let found = bound(&check(Expr::Const(24), 1)).expect("a bound");
    assert_eq!(
        (found.count, found.default, found.minimum),
        (24, Some(0x2000), 0)
    );
    assert_eq!(found.switch_base, Expr::reg(3, 32));
    // A limit that is no constant, or a value that is not one for
    // "below", bounds nothing.
    assert!(bound(&check(Expr::reg(5, 32), 1)).is_none());
    assert!(bound(&check(Expr::Const(24), 2)).is_none());
}

#[test]
fn a_table_address_plus_an_index_is_held_until_a_register_of_it_is_written() {
    const WORD: u64 = 0xffff_ffff;
    let assign = |register: u16, value: Expr| Stmt::Assign {
        dest: vlk_ir::ir::RegRef {
            index: register,
            width: 64,
        },
        value,
        at: None,
    };
    // s5 = table; v0 = s6 << 2; s5 = s5 + v0; v0 = 7; then `after`,
    // and a second block that the first falls into.
    let held = |after: Vec<Stmt>, table: Option<&dyn Fn(u64) -> bool>| {
        let mut stmts = vec![
            assign(21, Expr::Const(0x2000)),
            assign(
                0,
                Expr::bin(
                    BinOp::And,
                    Expr::bin(BinOp::Shl, Expr::reg(22, 32), Expr::Const(2)),
                    Expr::Const(WORD),
                ),
            ),
            assign(
                21,
                Expr::bin(
                    BinOp::And,
                    Expr::bin(BinOp::Add, Expr::reg(21, 32), Expr::reg(0, 32)),
                    Expr::Const(WORD),
                ),
            ),
            assign(0, Expr::Const(7)),
        ];
        stmts.extend(after);
        let blocks = [
            Block {
                start: 0x1000,
                stmts,
            },
            Block {
                start: 0x1010,
                stmts: vec![Stmt::Ret {
                    value: Expr::reg(0, 32),
                    at: None,
                }],
            },
        ];
        held_constants(&blocks, &[], table).remove(1)
    };
    let table = |address: u64| address == 0x2000;
    // The sum is held in what v0 was computed from, which v0 no
    // longer is.
    let kept = held(Vec::new(), Some(&table));
    let sum = kept.get(&21).expect("the sum");
    let mut read = std::collections::HashSet::new();
    vlk_ir::ir::visit::collect_reads(sum, &mut read);
    assert_eq!(read, std::collections::HashSet::from([22]));
    // A write of the index ends it.
    assert!(!held(vec![assign(22, Expr::Const(1))], Some(&table)).contains_key(&21));
    // An address that is no table's is not held, nor is any sum
    // where sums are not looked for.
    assert!(!held(Vec::new(), Some(&|_| false)).contains_key(&21));
    assert!(!held(Vec::new(), None).contains_key(&21));
}

#[test]
fn absolute32_entries_are_unsigned_and_checked() {
    let start = 0x8000_0000u64;
    let mut bytes = vec![0; 40];
    bytes[16..20].copy_from_slice(&((start + 32) as u32).to_le_bytes());
    let program = vlk_program::program::Program::new(Image::from_code(
        vlk_base::target::Isa::I386,
        start,
        bytes,
    ));
    let block = |table| Block {
        start,
        stmts: vec![Stmt::BrIndirect {
            target: Expr::Load {
                addr: Box::new(Expr::Const(table)),
                width: 4,
                signed: false,
            },
            at: None,
        }],
    };
    let recovered = recover(&[block(start + 16)], &program, start..start + 40);
    assert_eq!(recovered.len(), 1);
    assert_eq!(recovered[0].cases, [(0, start + 32)]);
    assert_eq!(recovered[0].table, (start + 16, 4));
    for table in [start + 20, start + 38, u64::MAX - 1] {
        assert!(recover(&[block(table)], &program, start..start + 40).is_empty());
    }
    assert_eq!(entry_address(u64::MAX - 3, 1, 4), None);
    for stride in [1, 2, 4, 8] {
        let target = Expr::Load {
            addr: Box::new(Expr::bin(
                BinOp::And,
                Expr::bin(
                    BinOp::Add,
                    Expr::bin(BinOp::Mul, Expr::reg(0, 32), Expr::Const(stride)),
                    Expr::Const(0xffff_ffff_8000_0010),
                ),
                Expr::Const(0xffff_ffff),
            )),
            width: 4,
            signed: false,
        };
        let pattern = table_pattern(&target);
        if stride == 4 {
            let (_, table, index, _, entry) = pattern.unwrap();
            assert_eq!(table, start + 16);
            assert_eq!(index, Expr::reg(0, 32));
            assert!(entry == Entry::Absolute32);
        } else {
            assert!(pattern.is_none());
        }
    }
}

#[test]
fn offsets_added_in_32_bits_reach_cases_on_either_side_of_the_table() {
    // Three 4-byte offsets at start + 8, then the code they reach.
    let start = 0x2_0000u64;
    let table = start + 8;
    let mut bytes = vec![0; 64];
    for (position, case) in [start + 32, start + 40, start].into_iter().enumerate() {
        let offset = (case as u32).wrapping_sub(table as u32);
        bytes[8 + position * 4..12 + position * 4].copy_from_slice(&offset.to_le_bytes());
    }
    // What follows the table reads as an offset far outside the code.
    bytes[20..24].copy_from_slice(&0xe59f_0430u32.to_le_bytes());
    let program = vlk_program::program::Program::new(Image::from_code(
        vlk_base::target::Isa::Arm32,
        start,
        bytes,
    ));
    let low = |value| Expr::bin(BinOp::And, value, Expr::Const(0xffff_ffff));
    let entry = Expr::Load {
        addr: Box::new(low(Expr::bin(
            BinOp::Add,
            Expr::Const(table),
            Expr::bin(BinOp::Shl, Expr::reg(0, 32), Expr::Const(2)),
        ))),
        width: 4,
        signed: false,
    };
    let block = Block {
        start,
        stmts: vec![Stmt::BrIndirect {
            target: low(Expr::bin(BinOp::Add, Expr::Const(table), low(entry))),
            at: None,
        }],
    };
    let recovered = recover(&[block], &program, start..start + 64);
    assert_eq!(recovered.len(), 1);
    assert_eq!(
        recovered[0].cases,
        [(0, start + 32), (1, start + 40), (2, start)]
    );
}

#[test]
fn an_index_scaled_by_a_shift_up_and_a_shorter_shift_down_counts_entries() {
    // Four 4-byte offsets at start + 64, each to its own case; the
    // index is `(x << 32) >> 30`, four times the low half of x.
    let start = 0x2_0000u64;
    let table = start + 64;
    let cases = [start + 8, start + 16, start + 24, start + 32];
    let mut bytes = vec![0; 96];
    for (position, case) in cases.into_iter().enumerate() {
        let offset = (case as u32).wrapping_sub(table as u32);
        bytes[64 + position * 4..68 + position * 4].copy_from_slice(&offset.to_le_bytes());
    }
    let mut program = vlk_program::program::Program::new(Image::from_code(
        vlk_base::target::Isa::RiscV64,
        start,
        bytes,
    ));
    program.image.sections[0].read_only = true;
    let scaled = Expr::Bin {
        op: BinOp::Shr,
        lhs: Box::new(Expr::Bin {
            op: BinOp::Shl,
            lhs: Box::new(Expr::reg(0, 64)),
            rhs: Box::new(Expr::Const(32)),
        }),
        rhs: Box::new(Expr::Const(30)),
    };
    let entry = Expr::Load {
        addr: Box::new(Expr::bin(BinOp::Add, scaled, Expr::Const(table))),
        width: 4,
        signed: true,
    };
    let check = Block {
        start,
        stmts: vec![Stmt::Brif {
            cond: vlk_ir::ir::Cond::Cc,
            lhs: Expr::Const(3),
            rhs: Expr::reg(0, 64),
            target: start + 40,
            at: None,
        }],
    };
    let dispatch = Block {
        start: start + 4,
        stmts: vec![Stmt::BrIndirect {
            target: Expr::bin(BinOp::Add, entry, Expr::Const(table)),
            at: None,
        }],
    };
    let recovered = recover(&[check, dispatch], &program, start..start + 64);
    assert_eq!(recovered.len(), 1);
    assert_eq!(
        recovered[0].cases,
        [
            (0, start + 8),
            (1, start + 16),
            (2, start + 24),
            (3, start + 32)
        ]
    );
}

#[test]
fn a_byte_table_ends_at_its_first_case_and_at_a_case_inside_itself() {
    let start = 0x2_0000u64;
    let table = start + 4;
    let byte_table = |entries: &[u8]| {
        let mut bytes = vec![0xff; 64];
        bytes[4..4 + entries.len()].copy_from_slice(entries);
        let program = vlk_program::program::Program::new(Image::from_code(
            vlk_base::target::Isa::Arm32,
            start,
            bytes,
        ));
        let low = |value| Expr::bin(BinOp::And, value, Expr::Const(0xffff_ffff));
        let entry = Expr::Load {
            addr: Box::new(low(Expr::bin(
                BinOp::Add,
                Expr::Const(table),
                low(Expr::reg(0, 32)),
            ))),
            width: 1,
            signed: false,
        };
        let block = Block {
            start,
            stmts: vec![Stmt::BrIndirect {
                target: low(Expr::bin(
                    BinOp::Add,
                    Expr::Const(table),
                    Expr::bin(BinOp::Shl, entry, Expr::Const(1)),
                )),
                at: None,
            }],
        };
        recover(&[block], &program, start..start + 64)
            .into_iter()
            .map(|table| table.cases)
            .collect::<Vec<_>>()
    };
    // Four entries; the first case begins right after them, so the byte
    // there, which would read as a fifth entry, is code.
    assert_eq!(
        byte_table(&[2, 5, 9, 12, 6]),
        [vec![
            (0, table + 4),
            (1, table + 10),
            (2, table + 18),
            (3, table + 24)
        ]]
    );
    // Three entries and a padding byte, whose case would be the table.
    assert_eq!(
        byte_table(&[4, 6, 8, 0, 7]),
        [vec![(0, table + 8), (1, table + 12), (2, table + 16)]]
    );
}

#[test]
fn bounds_checks_with_extreme_constants_do_not_overflow() {
    let check_at = |cond, bits, op, offset: u64, limit: u64| Block {
        start: 0,
        stmts: vec![Stmt::Brif {
            cond,
            lhs: Expr::bin(op, Expr::reg(0, bits), Expr::Const(offset)),
            rhs: Expr::Const(limit),
            target: 8,
            at: None,
        }],
    };
    let check = |op, offset, limit| check_at(vlk_ir::ir::Cond::Hi, 64, op, offset, limit);
    let counted = |block| {
        let bound = bound(&block).unwrap();
        (bound.count, bound.minimum)
    };
    assert_eq!(counted(check(BinOp::Add, 1 << 63, 3)), (4, i64::MIN));
    assert_eq!(counted(check(BinOp::Sub, 5, i64::MAX as u64)), (0, 5));
    assert_eq!(counted(check(BinOp::Sub, 5, u64::MAX)).0, 0);
    assert_eq!(case_value(i64::MAX, 2), i64::MIN + 1);
    // `x >= 6` takes the default, so six cases pass; `x > 6` passes seven.
    assert_eq!(
        counted(check_at(vlk_ir::ir::Cond::Cs, 64, BinOp::Sub, 5, 6)),
        (6, 5)
    );
    assert_eq!(
        counted(check_at(vlk_ir::ir::Cond::Hi, 64, BinOp::Sub, 5, 6)),
        (7, 5)
    );
    // A 32-bit check counts at its own width.
    assert_eq!(
        counted(check_at(
            vlk_ir::ir::Cond::Hi,
            32,
            BinOp::Sub,
            5,
            0x1_0000_0003
        ))
        .0,
        4
    );
    assert_eq!(byte_offset(1, 64), None);
    assert_eq!(byte_offset(1, -1), None);
    assert_eq!(byte_offset(3, 2), Some(12));
    assert_eq!(entry_address(u64::MAX - 7, 1, 8), None);
}

#[test]
fn direct_control_flow_does_not_scan_table_addresses() {
    for isa in [
        vlk_base::target::Isa::X86_64,
        vlk_base::target::Isa::AArch64,
        vlk_base::target::Isa::I386,
        vlk_base::target::Isa::Arm32,
    ] {
        let program = vlk_program::program::Program::new(Image::from_code(isa, 0, Vec::new()));
        let blocks = vec![
            Block {
                start: 0,
                stmts: vec![Stmt::Brif {
                    cond: vlk_ir::ir::Cond::Eq,
                    lhs: Expr::reg(0, 32),
                    rhs: Expr::Const(0),
                    target: 8,
                    at: None,
                }],
            },
            Block {
                start: 4,
                stmts: vec![Stmt::Ret {
                    value: Expr::Const(1),
                    at: None,
                }],
            },
            Block {
                start: 8,
                stmts: vec![Stmt::Ret {
                    value: Expr::Const(2),
                    at: None,
                }],
            },
        ];
        assert!(recover(&blocks, &program, 0..12).is_empty());
        assert!(program.addressed.get().is_none());
    }
}

#[test]
fn table_data_keeps_normal_exceptional_and_unknown_entries() {
    let table = Recovered {
        block_start: 0,
        index: Expr::Const(0),
        cases: vec![(0, 20)],
        default: None,
        table: (10, 4),
    };
    let ret = || Stmt::Ret {
        value: Expr::Const(0),
        at: None,
    };
    let blocks = |entry| {
        vec![
            Block {
                start: 0,
                stmts: vec![entry],
            },
            Block {
                start: 10,
                stmts: vec![ret()],
            },
            Block {
                start: 20,
                stmts: vec![ret()],
            },
        ]
    };
    let mut dead = blocks(Stmt::Br {
        target: Some(20),
        at: None,
    });
    drop_data(&mut dead, std::slice::from_ref(&table), &[]);
    assert_eq!(
        dead.iter().map(|block| block.start).collect::<Vec<_>>(),
        [0, 20]
    );
    for entry in [
        Stmt::Br {
            target: Some(10),
            at: None,
        },
        Stmt::BrIndirect {
            target: Expr::reg(0, 64),
            at: None,
        },
    ] {
        let mut live = blocks(entry);
        drop_data(&mut live, std::slice::from_ref(&table), &[]);
        assert_eq!(live.len(), 3);
    }
    let mut exceptional = blocks(ret());
    exceptional[0].stmts.insert(
        0,
        Stmt::Unsupported {
            at: None,
            text: "unknown call".into(),
            writes: Some(Vec::new()),
        },
    );
    drop_data(&mut exceptional, &[table], &[(10, vec![(0, 1)])]);
    assert_eq!(exceptional.len(), 3);
}