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
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
//! Recovery of arguments and results in the caller's stack frame.

use std::collections::HashMap;

use vlk_base::target::Isa;
use vlk_ir::ir::{Block, Expr, Stmt};
use vlk_types::types::Convention;

/// What the body uses of the caller's frame past the register arguments.
#[derive(Default)]
pub(super) struct StackFrame {
    /// The offsets of the 8-byte arguments.
    pub(super) offsets: Vec<i64>,
    /// How many bytes of each argument the body reads, under Go's assembly
    /// ABI; eight elsewhere.
    pub(super) widths: Vec<u8>,
    /// The results the body writes past the arguments, under Go's assembly
    /// ABI: offset and width.
    pub(super) results: Vec<(i64, u8)>,
}

/// How many 8-byte slots of the caller's frame are followed.
const STACK_SLOTS: usize = 64;

/// The registers holding a known offset from the stack pointer on entry.
type Frame = std::collections::BTreeMap<u16, i64>;

/// One bit for each followed byte of the caller's frame the body has written.
type Written = [u8; STACK_SLOTS];

/// Where the stack arguments of a function lie and which registers may
/// address them.
struct CallerFrame {
    isa: Isa,
    sp: u16,
    fp: u16,
    /// The offset of the first stack argument from the stack pointer on entry.
    start: i64,
    slot_bytes: i64,
    /// Whether results follow the arguments, as under Go's assembly ABI.
    go_assembly: bool,
    /// Whether the body may write an argument's slot before reading it:
    /// then only a read of bytes it has not written reads an argument.
    tracks_writes: bool,
}

/// What the body does with the caller's frame.
#[derive(Default)]
struct FrameUses {
    /// The last argument slot read.
    last: Option<i64>,
    /// How far into each slot the body reads.
    extent: HashMap<i64, i64>,
    /// The bytes the body writes: offset and width.
    written: Vec<(i64, i64)>,
    /// The slots whose address the body passes to a call.
    handed: Vec<i64>,
}

/// The offsets of the arguments past the registers the body reads: loads
/// from the caller's frame, through the stack pointer or a frame pointer
/// set from it, up to the last one read. And under Go's assembly ABI, the
/// results that follow them: what the body writes past the last argument
/// read, or the slot whose address it hands to a call. The arguments then
/// run up to the first result.
pub(super) fn stack_arguments(
    blocks: &[Block],
    landing_pads: &[(u64, Vec<(u64, u64)>)],
    isa: Isa,
    convention: Convention,
) -> StackFrame {
    let Some(start) = convention.stack_arguments() else {
        return StackFrame::default();
    };
    if blocks.is_empty() {
        return StackFrame::default();
    }
    let caller = CallerFrame {
        isa,
        sp: vlk_arch::arch::stack_pointer(isa),
        fp: vlk_arch::arch::frame_pointer(isa),
        start,
        slot_bytes: i64::from(vlk_arch::arch::pointer_bytes(isa)),
        go_assembly: convention.go_assembly(),
        tracks_writes: matches!(
            convention,
            Convention::Aapcs32
                | Convention::Aapcs64
                | Convention::Lp64
                | Convention::O32
                | Convention::GoAmd64
                | Convention::GoArm64
        ),
    };
    let entries = caller.entry_states(blocks, landing_pads);
    let mut uses = FrameUses::default();
    for (index, block) in blocks.iter().enumerate() {
        if let Some(frame) = entries.frames[index].clone() {
            caller.scan(block, frame, entries.written[index], true, &mut uses);
        }
    }
    // Re-entry can erase the joined frame, but not a read on the first entry.
    caller.scan(
        &blocks[0],
        Frame::from([(caller.sp, 0)]),
        [0; STACK_SLOTS],
        false,
        &mut uses,
    );
    caller.arguments_and_results(&uses, convention.results().len())
}

/// A register plus constants, nested as the upper half of a vector load
/// adds its eight bytes.
fn based(expr: &Expr, i386: bool) -> Option<(u16, i64)> {
    match expr {
        Expr::Reg { index, width: 64 } => Some((*index, 0)),
        Expr::Bin {
            op: vlk_ir::ir::BinOp::And,
            lhs,
            rhs,
        } if i386 && matches!(rhs.as_ref(), Expr::Const(0xffff_ffff)) => based(lhs, i386),
        Expr::Bin {
            op: vlk_ir::ir::BinOp::Sub,
            lhs,
            rhs,
        } if i386 => match rhs.as_ref() {
            Expr::Const(delta) => based(lhs, i386)
                .and_then(|(base, inner)| inner.checked_sub(*delta as i64).map(|at| (base, at))),
            _ => None,
        },
        Expr::Bin {
            op: vlk_ir::ir::BinOp::Add,
            lhs,
            rhs,
        } => match rhs.as_ref() {
            Expr::Const(delta) => based(lhs, i386)
                .and_then(|(base, inner)| inner.checked_add(*delta as i64).map(|at| (base, at))),
            _ => None,
        },
        _ => None,
    }
}

/// Every load in `expr`, the ones vector operations make included.
fn all_loads<'a>(expr: &'a Expr, out: &mut Vec<(&'a Expr, u8)>) {
    if let Expr::Load { addr, width, .. } = expr {
        out.push((addr, *width));
    }
    for child in vlk_ir::ir::visit::children(expr) {
        all_loads(child, out);
    }
}

/// The frame and the written bytes each block starts with, and the blocks
/// still to be followed.
struct EntryStates {
    frames: Vec<Option<Frame>>,
    written: Vec<Written>,
    queued: Vec<bool>,
    work: Vec<usize>,
}

impl EntryStates {
    /// Joins the state a predecessor leaves into what block `next` starts
    /// with, and queues the block when that changes.
    fn offer(&mut self, next: usize, frame: &Frame, written: &Written) {
        let merged = match &self.frames[next] {
            None => frame.clone(),
            Some(old) => old
                .iter()
                .filter(|(register, at)| frame.get(register) == Some(at))
                .map(|(register, at)| (*register, *at))
                .collect(),
        };
        let merged_written = if self.frames[next].is_none() {
            *written
        } else {
            std::array::from_fn(|slot| self.written[next][slot] & written[slot])
        };
        if self.frames[next].as_ref() != Some(&merged) || self.written[next] != merged_written {
            self.frames[next] = Some(merged);
            self.written[next] = merged_written;
            if !std::mem::replace(&mut self.queued[next], true) {
                self.work.push(next);
            }
        }
    }
}

impl CallerFrame {
    /// Whether the offset `register` holds from the stack pointer on entry
    /// is followed from block to block: the stack pointer and the frame
    /// pointer, and under Go's assembly ABI, whose code may keep the stack
    /// pointer in another register while it moves to another stack, any
    /// register.
    fn tracked(&self, register: u16) -> bool {
        register == self.sp
            || register == self.fp
            || (self.isa == Isa::Arm32 && register == 7)
            || self.go_assembly
    }

    /// The first offset of the slot holding `at`.
    fn slot(&self, at: i64) -> i64 {
        at - (at - self.start).rem_euclid(self.slot_bytes)
    }

    /// The offset `expr` holds from the stack pointer on entry, when it is
    /// a tracked register of `frame` plus a constant.
    fn offset_of(&self, expr: &Expr, frame: &Frame) -> Option<i64> {
        let (base, delta) = match expr {
            Expr::Reg { .. }
            | Expr::Bin {
                op: vlk_ir::ir::BinOp::Add | vlk_ir::ir::BinOp::And,
                ..
            } => {
                let Some(base) = based(expr, self.isa == Isa::I386) else {
                    return None;
                };
                base
            }
            Expr::Bin {
                op: vlk_ir::ir::BinOp::Sub,
                lhs,
                rhs,
            } => match (lhs.as_ref(), rhs.as_ref()) {
                (Expr::Reg { index, width: 64 }, Expr::Const(delta)) => {
                    let Some(delta) = (*delta as i64).checked_neg() else {
                        return None;
                    };
                    (*index, delta)
                }
                _ => return None,
            },
            _ => return None,
        };
        if !self.tracked(base) {
            return None;
        }
        frame.get(&base).and_then(|at| at.checked_add(delta))
    }

    /// The offset of `addr` when it lies in the followed part of the
    /// caller's frame, through a register of `frame` or one of `held`.
    fn located(&self, addr: &Expr, frame: &Frame, held: &HashMap<u16, i64>) -> Option<i64> {
        let through = based(addr, self.isa == Isa::I386)
            .and_then(|(base, delta)| held.get(&base).and_then(|at| at.checked_add(delta)));
        self.offset_of(addr, frame)
            .or(through)
            .filter(|at| *at >= self.start && at - self.start < 8 * STACK_SLOTS as i64)
    }

    /// The offsets of the `width` bytes at `at`, when they end inside the
    /// followed part of the caller's frame.
    fn bounded_bytes(&self, at: i64, width: u8) -> Option<std::ops::Range<i64>> {
        if !matches!(width, 1 | 2 | 4 | 8) {
            return None;
        }
        let Some(end) = at.checked_add(i64::from(width)) else {
            return None;
        };
        (end <= self.start + 8 * STACK_SLOTS as i64).then_some(at..end)
    }

    /// Follows one statement: marks in `written` the bytes of the caller's
    /// frame it stores to, and updates the registers of `frame` and `held`,
    /// those the block set to an address in the caller's frame.
    fn step(
        &self,
        stmt: &Stmt,
        frame: &mut Frame,
        held: &mut HashMap<u16, i64>,
        written: &mut Written,
    ) {
        let assigned = match stmt {
            Stmt::Assign { dest, value, .. } if dest.width == 64 => self.offset_of(value, frame),
            _ => None,
        };
        let preserved: Vec<_> = stmt
            .preserved_output_sources()
            .into_iter()
            .filter_map(|(output, source)| {
                let dest = stmt.call_outputs()[output].dest;
                if dest.width != 64 {
                    return None;
                }
                frame
                    .get(&source)
                    .or_else(|| held.get(&source))
                    .map(|offset| (dest.index, *offset))
            })
            .collect();
        if self.tracks_writes
            && let Stmt::Store { addr, width, .. } = stmt
            && let Some(at) = self.located(addr, frame, held)
            && let Some(bytes) = self.bounded_bytes(at, *width)
        {
            for at in bytes {
                let byte = (at - self.start) as usize;
                written[byte / 8] |= 1 << (byte % 8);
            }
        }
        for register in vlk_ir::ir::visit::statement_registers(stmt).0 {
            held.remove(&register);
            if self.tracked(register) {
                frame.remove(&register);
            }
        }
        let mut insert = |destination, at| {
            if self.tracked(destination) {
                frame.insert(destination, at);
            }
            if destination != self.sp && destination != self.fp && at >= self.start {
                held.insert(destination, at);
            }
        };
        if let Stmt::Assign { dest, .. } = stmt
            && let Some(at) = assigned
        {
            insert(dest.index, at);
        }
        for (destination, at) in preserved {
            insert(destination, at);
        }
    }

    /// The frame and the written bytes every path to each block agrees on,
    /// along the normal and the exceptional edges.
    fn entry_states(
        &self,
        blocks: &[Block],
        landing_pads: &[(u64, Vec<(u64, u64)>)],
    ) -> EntryStates {
        let mut entries = EntryStates {
            frames: vec![None; blocks.len()],
            written: vec![[0; STACK_SLOTS]; blocks.len()],
            queued: vec![false; blocks.len()],
            work: vec![0],
        };
        entries.frames[0] = Some(Frame::from([(self.sp, 0)]));
        entries.queued[0] = true;
        let graph: Vec<_> = (0..blocks.len())
            .map(|index| {
                vlk_ir::ir::cfg::block_successors_with_exceptions(blocks, index, landing_pads)
            })
            .collect();
        let all: Vec<_> = (0..blocks.len()).collect();
        while let Some(index) = entries.work.pop() {
            entries.queued[index] = false;
            let mut frame = entries.frames[index].clone().expect("visited");
            let mut held = HashMap::new();
            let mut written = entries.written[index];
            let edges = &graph[index];
            let mut exceptional: Option<(Frame, Written)> = None;
            for stmt in &blocks[index].stmts {
                self.step(stmt, &mut frame, &mut held, &mut written);
                if matches!(stmt, Stmt::Call { .. })
                    && (!edges.exceptional.is_empty() || edges.unknown_exceptional)
                {
                    match &mut exceptional {
                        None => exceptional = Some((frame.clone(), written)),
                        Some((before, bytes)) => {
                            before.retain(|register, at| frame.get(register) == Some(&*at));
                            for (byte, after) in bytes.iter_mut().zip(written) {
                                *byte &= after;
                            }
                        }
                    }
                }
            }
            // An opaque instruction can unwind with unmodeled frame or memory effects.
            if blocks[index]
                .stmts
                .iter()
                .any(|stmt| matches!(stmt, Stmt::Unsupported { .. }))
            {
                exceptional = None;
            }
            let normal = if edges.unknown_normal {
                &all
            } else {
                &edges.normal
            };
            for &next in normal {
                entries.offer(next, &frame, &written);
            }
            let exceptional_targets = if edges.unknown_exceptional {
                &all
            } else {
                &edges.exceptional
            };
            if !exceptional_targets.is_empty() {
                let (frame, written) =
                    exceptional.unwrap_or_else(|| (Frame::new(), [0; STACK_SLOTS]));
                for &next in exceptional_targets {
                    entries.offer(next, &frame, &written);
                }
            }
        }
        entries
    }

    /// Records what `block` reads of the caller's frame, starting from
    /// `frame` with the bytes of `initialized` written, and with `effects`
    /// also what it writes there and the addresses in it that it passes to
    /// a call.
    fn scan(
        &self,
        block: &Block,
        mut frame: Frame,
        mut initialized: Written,
        effects: bool,
        uses: &mut FrameUses,
    ) {
        // Registers the block sets to an address in the caller's frame, as
        // an argument structure's address the body reads it through.
        let mut held: HashMap<u16, i64> = HashMap::new();
        for stmt in &block.stmts {
            let mut loads = Vec::new();
            for value in stmt.operands() {
                all_loads(value, &mut loads);
            }
            for (addr, width) in loads {
                let Some(at) = self.located(addr, &frame, &held) else {
                    continue;
                };
                if self.tracks_writes {
                    if let Some(bytes) = self.bounded_bytes(at, width)
                        && let Some(needed) = bytes.rev().find(|at| {
                            let byte = (at - self.start) as usize;
                            initialized[byte / 8] & (1 << (byte % 8)) == 0
                        })
                    {
                        uses.last = uses.last.max(Some(self.slot(needed)));
                    }
                } else if (at - self.start) % self.slot_bytes == 0 {
                    uses.last = uses.last.max(Some(at));
                }
                if self.go_assembly {
                    let reach = uses.extent.entry(self.slot(at)).or_default();
                    *reach = (*reach).max(at - self.slot(at) + i64::from(width));
                }
            }
            match stmt {
                Stmt::Store { addr, width, .. } if self.go_assembly && effects => {
                    if let Some(at) = self.located(addr, &frame, &held) {
                        uses.written.push((at, i64::from(*width)));
                    }
                }
                Stmt::Call { .. } if self.go_assembly && effects => {
                    uses.handed.extend(
                        vlk_ir::ir::visit::statement_registers(stmt)
                            .1
                            .iter()
                            .filter_map(|register| frame.get(register))
                            .filter(|at| **at >= self.start)
                            .map(|at| self.slot(*at)),
                    );
                }
                _ => {}
            }
            self.step(stmt, &mut frame, &mut held, &mut initialized);
        }
    }

    /// The arguments up to the last one read or the first result, and at
    /// most `result_limit` results from the first one on.
    fn arguments_and_results(&self, uses: &FrameUses, result_limit: usize) -> StackFrame {
        let last = uses.last;
        // A result follows every argument read. An address handed on may be
        // that of the arguments, unless some argument is read before it.
        let past = |at: i64| last.is_none_or(|last| at > last);
        let first = uses
            .written
            .iter()
            .map(|(at, _)| self.slot(*at))
            .filter(|at| past(*at))
            .chain(
                uses.handed
                    .iter()
                    .copied()
                    .filter(|at| last.is_some() && past(*at)),
            )
            .min();
        let step = self.slot_bytes as usize;
        let offsets: Vec<i64> = match (first, last) {
            (Some(first), _) => (self.start..first).step_by(step).collect(),
            (None, Some(last)) => (self.start..=last).step_by(step).collect(),
            (None, None) => Vec::new(),
        };
        let widths = offsets
            .iter()
            .map(|at| match uses.extent.get(at) {
                Some(reach) => (*reach as u64).next_power_of_two().min(8) as u8,
                None => self.slot_bytes as u8,
            })
            .collect();
        let results = first.map_or_else(Vec::new, |first| {
            results_from(first, &uses.written, &uses.handed, result_limit)
        });
        StackFrame {
            offsets,
            widths,
            results,
        }
    }
}

/// The results at `first` and after: the written bytes and the slots handed
/// to a call, joined where they overlap. Empty when one of them is not a
/// value a register holds, aligned to its size.
fn results_from(
    first: i64,
    written: &[(i64, i64)],
    handed: &[i64],
    limit: usize,
) -> Vec<(i64, u8)> {
    // A result handed on is written whole.
    let mut fields: Vec<(i64, i64)> = written
        .iter()
        .copied()
        .chain(handed.iter().map(|at| (*at, 8)))
        .filter(|(at, _)| *at >= first)
        .map(|(at, width)| (at, at + width))
        .collect();
    fields.sort_unstable();
    let mut merged: Vec<(i64, i64)> = Vec::new();
    for (from, to) in fields {
        match merged.last_mut() {
            Some(last) if from < last.1 => last.1 = last.1.max(to),
            _ => merged.push((from, to)),
        }
    }
    if merged.iter().any(|(from, to)| {
        let width = to - from;
        !matches!(width, 1 | 2 | 4 | 8) || from % width != 0
    }) {
        return Vec::new();
    }
    merged
        .into_iter()
        .take(limit)
        .map(|(from, to)| (from, (to - from) as u8))
        .collect()
}