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
//! Building the blocks of a function from its decoded instructions.

use std::collections::{HashMap, HashSet};

use vlk_base::error::LiftError;
use vlk_base::target::Isa;
use vlk_ir::ir::{Block, Stmt};
use vlk_loader::loader::Image;
use vlk_program::program::Program;

use super::carry::{self, Carried, Exit, drop_unread_compare_operands, finish_block};
use super::machine::{Decoded, Machine};
use super::{Summaries, arm32, calls, constants, execution, exits};

/// Completes what an instruction's statements leave open: a note where
/// the lifter could not express an operand, the registers an unsupported
/// instruction may write, and what the instruction does to the flags where
/// the lifter did not say.
fn finish_instruction<M: Machine>(
    machine: &mut M,
    instruction: &M::Instruction,
    from: usize,
    address: u64,
) {
    if machine.out().incomplete.get() {
        let note = format!("{} operands at 0x{address:x}", machine.name(instruction));
        machine.out().stmts.push(Stmt::unsupported(note));
    }
    let from = from.min(machine.out().stmts.len());
    let open = |stmt: &Stmt| matches!(stmt, Stmt::Unsupported { writes: None, .. });
    if machine.out().stmts[from..].iter().any(open)
        && let Some(changed) = machine.written(instruction)
    {
        for stmt in &mut machine.out().stmts[from..] {
            if let Stmt::Unsupported { writes, .. } = stmt
                && writes.is_none()
            {
                *writes = Some(changed.clone());
            }
        }
    }
    let unsupported = machine.out().stmts[from..]
        .iter()
        .any(|stmt| matches!(stmt, Stmt::Unsupported { .. }));
    let sets = machine.sets_flags(instruction);
    let reads = machine.reads_flags(instruction);
    let state = &mut machine.out().flags;
    // Flags the instruction sets in a way not modelled are unknown.
    if sets && !state.written {
        state.pending = None;
    }
    state.touched |= sets || state.written || (unsupported && !reads);
}

/// The block at `address` begins: with the flags and the constants an
/// earlier lift found the blocks before it to leave.
fn begin<M: Machine>(machine: &mut M, calls: &mut calls::Calls, carried: &Carried, address: u64) {
    calls.enter(address, carried.constants.get(&address));
    let state = &mut machine.out().flags;
    state.pending = carried.entry.get(&address).cloned();
    state.touched = false;
    machine.enter_block();
}

/// The block that began at `start` and holds `stmts`, with the flags the
/// machine's code leaves.
fn end<M: Machine>(
    machine: &mut M,
    isa: Isa,
    start: u64,
    stmts: Vec<Stmt>,
    carried: &Carried,
    exits: &mut HashMap<u64, Exit>,
) -> Block {
    let state = &machine.out().flags;
    let (pending, touched) = (state.pending.clone(), state.touched);
    finish_block(pending, touched, isa, start, stmts, carried, exits)
}

pub(super) type Decoder<'a, I> = &'a dyn Fn(&[u8], u64) -> (Vec<Decoded<I>>, Option<String>);

/// The function's blocks, lifted again with the code its branches out
/// continue in, which is no tail call, until no more such code turns up.
pub(super) fn lift_continuing<M: Machine>(
    program: &Program,
    summaries: Summaries<'_>,
    machine: impl Fn() -> M,
    addr: u64,
    bytes: &[u8],
    decode: Decoder<'_, M::Instruction>,
    extra_targets: &HashSet<u64>,
) -> Result<Vec<Block>, LiftError> {
    let image = &program.image;
    let mut pulled = exits::ContinuedCode::new();
    let mut rounds = 0;
    loop {
        rounds += 1;
        let (decoded, stop) =
            decode_with_fragments(image, &machine(), addr, bytes, decode, &pulled);
        let (blocks, more) = match build_carrying(
            program,
            summaries,
            &machine,
            addr,
            &decoded,
            stop,
            extra_targets,
        ) {
            Ok(result) => result,
            Err(error) => return Err(error),
        };
        let known = pulled.len();
        pulled.extend(more);
        if pulled.len() == known || rounds == 4 {
            return Ok(blocks);
        }
    }
}

/// The function's instructions, followed by those of the code `pulled`
/// names and of every fragment split off it, such as a cold part, that its
/// branches reach.
fn decode_with_fragments<M: Machine>(
    image: &Image,
    machine: &M,
    addr: u64,
    bytes: &[u8],
    decode: Decoder<'_, M::Instruction>,
    pulled: &exits::ContinuedCode,
) -> (Vec<Decoded<M::Instruction>>, Option<String>) {
    let (mut decoded, stop) = decode(bytes, addr);
    for (start, size) in pulled {
        if let Some(bytes) = image.read_vaddr(*start, *size) {
            decoded.extend(decode(bytes, *start).0);
        }
    }
    let mut included = HashSet::new();
    let mut scanned = 0;
    while scanned < decoded.len() {
        let reached: Vec<(u64, u64)> = decoded[scanned..]
            .iter()
            .filter_map(|d| machine.branch_target(&d.instruction, d.pc))
            .filter(|target| !image.functions.contains_key(target))
            .filter_map(|target| image.fragment_at(target))
            .filter(|(start, _)| included.insert(*start))
            .collect();
        scanned = decoded.len();
        for (start, size) in reached {
            if let Some(bytes) = image.read_vaddr(start, size) {
                decoded.extend(decode(bytes, start).0);
            }
        }
    }
    (decoded, stop)
}

/// The blocks, lifted once to find the blocks that read flags they do not
/// know and the flags each block ends with, and again where every block
/// before such a block ends with flags of one shape, which then carry over.
/// Also returns the code the branches out of it continue in.
fn build_carrying<M: Machine>(
    program: &Program,
    summaries: Summaries<'_>,
    machine: impl Fn() -> M,
    start: u64,
    decoded: &[Decoded<M::Instruction>],
    stop: Option<String>,
    extra_targets: &HashSet<u64>,
) -> Result<(Vec<Block>, exits::ContinuedCode), LiftError> {
    let image = &program.image;
    let none = Carried::default();
    let (blocks, exits, pulled) = match build(
        program,
        summaries,
        machine(),
        start,
        decoded,
        stop.clone(),
        extra_targets,
        &none,
    ) {
        Ok(result) => result,
        Err(error) => return Err(error),
    };
    let mut carried = carry::flags(image.isa, &blocks, &exits, extra_targets);
    // Constants matter to a second lift only where a call through a
    // register is left that they may resolve.
    let through = |stmt: &Stmt| {
        matches!(
            stmt,
            Stmt::Call {
                target: None,
                through: Some(_),
                ..
            }
        )
    };
    let rules = machine().rules();
    if rules.folds || blocks.iter().any(|block| block.stmts.iter().any(through)) {
        carried.constants = constants::entries(image, &blocks, extra_targets, &rules);
    }
    if carried.entry.is_empty() && carried.constants.is_empty() {
        return Ok((blocks, pulled));
    }
    let (blocks, _, pulled) = match build(
        program,
        summaries,
        machine(),
        start,
        decoded,
        stop,
        extra_targets,
        &carried,
    ) {
        Ok(result) => result,
        Err(error) => return Err(error),
    };
    Ok((blocks, pulled))
}

/// The blocks, the flags each leaves, and the code its branches out continue
/// in.
type BuiltBlocks = (Vec<Block>, HashMap<u64, Exit>, exits::ContinuedCode);

#[expect(
    clippy::too_many_arguments,
    reason = "Block construction needs the decoded instructions, branch targets, and incoming machine state together."
)]
fn build<M: Machine>(
    program: &Program,
    summaries: Summaries<'_>,
    mut machine: M,
    start: u64,
    decoded: &[Decoded<M::Instruction>],
    stop: Option<String>,
    extra_targets: &HashSet<u64>,
    carried: &Carried,
) -> Result<BuiltBlocks, LiftError> {
    let image = &program.image;
    let mut exits = HashMap::new();
    // The address of the instruction ending each block that a branch ends.
    let mut ends = HashMap::new();
    // Where the code goes on past each start that left no block.
    let mut passed: HashMap<u64, u64> = HashMap::new();
    if decoded.is_empty() {
        return Err(LiftError::NoInstructions);
    }
    let mut targets: HashSet<u64> = decoded
        .iter()
        .filter_map(|d| machine.branch_target(&d.instruction, d.pc))
        .collect();
    targets.extend(extra_targets);

    let mut blocks = Vec::new();
    let mut block_start = start;
    let mut pending = Vec::new();
    let mut expected = start;
    let rules = machine.rules();
    let mut calls = calls::Calls::new(rules.clone(), start);
    begin(&mut machine, &mut calls, carried, start);
    for d in decoded {
        // A fragment follows the code before it in the list, not in memory:
        // code running off the end goes on at the next address.
        if d.pc != expected {
            pending.extend(std::mem::take(&mut machine.out().stmts));
            if block_start != expected || !pending.is_empty() {
                pending.push(Stmt::Br {
                    target: Some(expected),
                    at: None,
                });
                let stmts = std::mem::take(&mut pending);
                blocks.push(end(
                    &mut machine,
                    image.isa,
                    block_start,
                    stmts,
                    carried,
                    &mut exits,
                ));
            }
            block_start = d.pc;
            begin(&mut machine, &mut calls, carried, block_start);
        }
        expected = d.next;
        if d.pc != block_start && targets.contains(&d.pc) {
            pending.extend(std::mem::take(&mut machine.out().stmts));
            // Instructions without statements, such as padding, leave no
            // block, unless they set flags a later block may read or a
            // jump table lands on them. The branches to them go on to the
            // next block instead.
            if pending.is_empty()
                && !machine.out().flags.touched
                && !extra_targets.contains(&block_start)
            {
                passed.insert(block_start, d.pc);
            } else {
                let stmts = std::mem::take(&mut pending);
                blocks.push(end(
                    &mut machine,
                    image.isa,
                    block_start,
                    stmts,
                    carried,
                    &mut exits,
                ));
            }
            block_start = d.pc;
            begin(&mut machine, &mut calls, carried, block_start);
        }
        let from = machine.out().stmts.len();
        machine.out().flags.written = false;
        machine.out().incomplete.set(false);
        let mut ended = machine.step(&d.instruction, d.pc);
        let origin = machine.origin(&d.instruction, d.pc);
        finish_instruction(&mut machine, &d.instruction, from, origin);
        let stmts = &mut machine.out().stmts;
        ended |= calls.settle(image, summaries, stmts, from);
        // Each statement names its instruction; a temporary's assignment
        // and the mark of an instruction's address do not.
        let from = from.min(stmts.len());
        for stmt in &mut stmts[from..] {
            if !matches!(stmt, Stmt::Assign { dest, .. }
                if vlk_ir::ir::is_temp(dest.index) || dest.index == execution::ADDRESS)
            {
                stmt.set_origin(Some(origin));
            }
        }
        if ended {
            pending.extend(std::mem::take(&mut machine.out().stmts));
            ends.insert(block_start, d.pc);
            let stmts = std::mem::take(&mut pending);
            blocks.push(end(
                &mut machine,
                image.isa,
                block_start,
                stmts,
                carried,
                &mut exits,
            ));
            for (extra, flags) in machine.take_extra_blocks() {
                let touched = flags.is_some();
                blocks.push(finish_block(
                    flags,
                    touched,
                    image.isa,
                    extra.start,
                    extra.stmts,
                    carried,
                    &mut exits,
                ));
            }
            block_start = d.next;
            begin(&mut machine, &mut calls, carried, block_start);
        }
    }
    pending.extend(std::mem::take(&mut machine.out().stmts));
    if let Some(text) = stop {
        pending.push(Stmt::unsupported(text));
    }
    if !pending.is_empty() {
        blocks.push(Block {
            start: block_start,
            stmts: pending,
        });
    }
    // Code that ends in a call, with nothing after it, never returns from it.
    if let Some(last) = blocks.last_mut()
        && matches!(last.stmts.last(), Some(Stmt::Call { .. }))
    {
        last.stmts.push(Stmt::Trap { at: None });
    }
    for stmt in blocks.iter_mut().flat_map(|block| &mut block.stmts) {
        if let Stmt::Br {
            target: Some(target),
            ..
        }
        | Stmt::Brif { target, .. }
        | Stmt::BrifFlags { target, .. } = stmt
        {
            while let Some(next) = passed.get(target) {
                *target = *next;
            }
        }
    }
    if image.isa == Isa::Arm32 {
        let starts = blocks.iter().map(|block| block.start).collect();
        arm32::resolve_internal_pc_loads(program, &mut blocks, &starts);
    }
    let pulled = exits::resolve_exits(image, summaries, start, &mut blocks, &ends);
    if image.isa == Isa::Mips32 {
        super::mips32::split_shared_calls(image, summaries, extra_targets, &mut blocks);
        calls::count_tail_formats(
            image,
            summaries,
            &rules,
            start,
            &carried.constants,
            &mut blocks,
        );
    }
    drop_unread_compare_operands(&mut blocks);
    Ok((blocks, exits, pulled))
}

#[cfg(test)]
mod tests;