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
//! Resolving a callee's declaration for printing. Binding a declaration to
//! a call's registers and stack slots runs in the tests only and lives there.

use std::collections::{BTreeSet, HashSet};
use std::sync::Arc;

use vlk_loader::loader::Image;
use vlk_loader::loader::dwarf::calls::{self as dwarf, Answer, CallUnit};
use vlk_program::program::Program;
use vlk_types::types::calls::{
    CallDeclaration, CallMember, CallSource, FunctionSource, TypeSource,
};
use vlk_types::types::{AbiIssue, AbiProfile, CType, DeclaredSignature, Definition};

pub fn declaration(image: &Image, address: u64) -> Answer {
    let cell = {
        let mut addresses = image
            .call_declarations
            .addresses
            .lock()
            .expect("call declarations lock");
        addresses.entry(address).or_default().clone()
    };
    cell.get_or_init(|| resolve(image, address)).clone()
}

/// Declarations usable for direct calls and function addresses: nonvariadic,
/// with whole scalar parameters in the named arguments' order and a scalar
/// result in the first result register under the call's convention.
pub(crate) fn printable_signatures(
    program: &Program,
    ir: &vlk_ir::ir::FunctionIr,
) -> std::collections::BTreeMap<u64, DeclaredSignature> {
    let image = &program.image;
    let mut found = std::collections::BTreeMap::new();
    if image.go {
        return found;
    }
    let mut refused = HashSet::new();
    for stmt in ir.blocks.iter().flat_map(|block| &block.stmts) {
        let vlk_ir::ir::Stmt::Call {
            target: Some(target),
            through: None,
            convention,
            args,
            ..
        } = stmt
        else {
            continue;
        };
        if refused.contains(target) {
            continue;
        }
        let Ok(Some(declaration)) = declaration(image, *target) else {
            continue;
        };
        let signature = &declaration.signature;
        // A call of the function itself is printed with the types its
        // definition is printed with, when those are the declared ones.
        let compatible = *target != ir.addr
            || (ir.ret_type == signature.ret
                && ir.params.len() == signature.params.len()
                && ir
                    .params
                    .iter()
                    .zip(&signature.params)
                    .all(|(param, (_, ty))| param.ty == *ty));
        if compatible
            && args
                .as_ref()
                .is_some_and(|args| args.len() == signature.params.len())
            && printable(signature, *convention)
            // A 32-bit declaration alone says nothing about the upper
            // return-register bits that the caller may still read.
            && (!signature.ret.integer().is_some_and(|(bits, _)| bits == 32)
                || super::summary::summary(program, *target).narrow_return)
        {
            found.insert(*target, signature.clone());
        } else {
            // Every call sharing the prototype must fit it.
            found.remove(target);
            refused.insert(*target);
        }
    }
    // An address of the same function needs the same prototype when
    // standalone outputs are combined.
    let mut pending: Vec<_> = ir
        .blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .flat_map(vlk_ir::ir::Stmt::operands)
        .collect();
    while let Some(value) = pending.pop() {
        pending.extend(vlk_ir::ir::visit::children(value));
        let vlk_ir::ir::Expr::Const(target) = value else {
            continue;
        };
        if *target == 0
            || *target == ir.addr
            || found.contains_key(target)
            || refused.contains(target)
            || !image.functions.contains_key(target)
        {
            continue;
        }
        let Ok(Some(declaration)) = declaration(image, *target) else {
            continue;
        };
        if printable(
            &declaration.signature,
            crate::lift::convention_of(image, *target),
        ) {
            found.insert(*target, declaration.signature.clone());
        }
    }
    found
}

/// Scalar virtual-call declarations with object pointers represented as void pointers.
pub fn virtual_signature(program: &Program, address: u64) -> Option<DeclaredSignature> {
    let image = &program.image;
    let Some(types) = vlk_loader::loader::dwarf::virtual_calls::function_types(image, address)
    else {
        return None;
    };
    let mut signature = super::abi::callee_declaration(&types);
    for (_, ty) in &mut signature.params {
        if ty.is_pointer() {
            *ty = CType::Pointer(Box::new(CType::Void));
        }
    }
    if !printable(&signature, crate::lift::convention_of(image, address))
        || (signature.ret.integer().is_some_and(|(bits, _)| bits == 32)
            && !super::summary::summary(program, address).narrow_return)
    {
        return None;
    }
    Some(signature)
}

fn printable(signature: &DeclaredSignature, convention: vlk_types::types::Convention) -> bool {
    use vlk_types::types::{AbiLocation, Passing, RegisterClass};
    let Ok(abi) = &signature.abi else {
        return false;
    };
    // A void prototype cannot represent a live return-register value.
    if signature.ret == CType::Void {
        return false;
    }
    if signature.variadic || super::abi::convention(abi.profile) != convention {
        return false;
    }
    let scalar = |ty: &CType| {
        let mut target = ty;
        while let CType::Pointer(inner) = target {
            target = inner;
        }
        (*target == CType::Void && ty.is_pointer())
            || target
                .integer()
                .is_some_and(|(bits, _)| matches!(bits, 8 | 16 | 32 | 64))
    };
    let size_matches = |ty: &CType, value: &vlk_types::types::ValueAbi| {
        let bytes = if ty.is_pointer() {
            Some(8)
        } else {
            ty.integer().map(|(bits, _)| u64::from(bits / 8))
        };
        bytes == Some(value.size)
            && !matches!(ty, CType::Named(name) if name.split_whitespace().any(|word| matches!(word, "bool" | "_Bool")))
    };
    let location = |value: &vlk_types::types::ValueAbi| match &value.passing {
        Passing::Direct(pieces) if !value.aggregate => match pieces.as_slice() {
            [piece]
                if value.validate().is_ok()
                    && piece.object_offset == 0
                    && piece.bytes == value.size
                    && match piece.location {
                        AbiLocation::Register(_) => piece.class == Some(RegisterClass::Integer),
                        AbiLocation::Stack(_) => piece.class.is_none(),
                    } =>
            {
                Some(piece.location)
            }
            _ => None,
        },
        _ => None,
    };
    let arguments = convention.arguments();
    let params = signature.params.len() == abi.arguments.len()
        && signature.params.iter().zip(&abi.arguments).enumerate().all(
            |(position, ((_, ty), value))| {
                scalar(ty)
                    && size_matches(ty, value)
                    && location(value).is_some_and(|at| {
                        if let Some(register) = arguments.get(position) {
                            return at == AbiLocation::Register(*register);
                        }
                        let offset = i64::try_from(position - arguments.len())
                            .ok()
                            .and_then(|slot| slot.checked_mul(8))
                            .and_then(|offset| {
                                convention
                                    .stack_arguments()
                                    .and_then(|start| start.checked_add(offset))
                            });
                        offset.is_some_and(|offset| at == AbiLocation::Stack(offset))
                    })
            },
        );
    let result = match (&abi.result, &signature.ret) {
        (Some(value), ty) => {
            scalar(ty)
                && size_matches(ty, value)
                && (ty.is_pointer() || ty.integer().is_some_and(|(bits, _)| bits >= 32))
                && location(value).is_some_and(|at| {
                    convention
                        .results()
                        .first()
                        .is_some_and(|register| at == AbiLocation::Register(*register))
                })
        }
        _ => false,
    };
    params && result
}

fn unit(image: &Image, source: u64) -> Result<Arc<CallUnit>, AbiIssue> {
    let cell = {
        let mut units = image
            .call_declarations
            .units
            .lock()
            .expect("call type units lock");
        units.entry(source).or_default().clone()
    };
    cell.get_or_init(|| dwarf::call_unit(image, source).map(Arc::new))
        .clone()
}

fn resolve(image: &Image, address: u64) -> Answer {
    if image.go {
        return Err(AbiIssue::UnsupportedProfile);
    }
    vlk_types::types::abi::profile(image.isa, image.format)?;
    let index = image
        .call_declarations
        .index
        .get_or_init(|| dwarf::call_index(image))
        .as_ref()
        .map_err(|issue| *issue)?;
    let Some(candidates) = index.addresses.get(&address) else {
        return if index
            .unresolved_ranges
            .iter()
            .any(|range| range.contains(&address))
        {
            Err(AbiIssue::UnknownLayout)
        } else {
            Ok(None)
        };
    };
    let mut found: Option<CallDeclaration> = None;
    for candidate in candidates {
        let unit = unit(image, candidate.unit)?;
        let types = unit
            .functions
            .get(candidate)
            .ok_or(AbiIssue::UnknownLayout)?
            .as_ref()
            .map_err(|issue| *issue)?;
        let signature = super::abi::callee_declaration(types);
        let profile = signature.abi.as_ref().map_err(|issue| *issue)?.profile;
        if types.source.parameters.len() != signature.params.len()
            || types.source.parameters.iter().any(Option::is_none)
            || (signature.ret != CType::Void && types.source.result.is_none())
        {
            return Err(AbiIssue::UnknownLayout);
        }
        let (required_types, required_definitions) = required(&unit, &types.source, profile)?;
        let source = CallSource {
            source: types.source.clone(),
            graph: unit.graph.clone(),
            required_types,
            required_definitions,
        };
        match &mut found {
            None => {
                found = Some(CallDeclaration {
                    signature,
                    sources: vec![source],
                })
            }
            Some(before) => {
                if !same_signature(&before.signature, &signature)
                    || !same_types(&before.sources[0], &source)
                {
                    return Err(AbiIssue::IncompatibleDefinition);
                }
                before.sources.push(source);
            }
        }
    }
    Ok(found.map(Arc::new))
}

fn required(
    unit: &CallUnit,
    source: &FunctionSource,
    profile: AbiProfile,
) -> Result<(Vec<TypeSource>, Vec<TypeSource>), AbiIssue> {
    let mut pending: Vec<_> = source
        .parameters
        .iter()
        .copied()
        .flatten()
        .chain(source.result)
        .map(|id| (id, true))
        .collect();
    let mut seen = BTreeSet::new();
    let mut types = BTreeSet::new();
    let mut definitions = BTreeSet::new();
    while let Some((id, by_value)) = pending.pop() {
        if !seen.insert((id, by_value)) {
            continue;
        }
        if seen.len() > 65536 {
            return Err(AbiIssue::UnknownLayout);
        }
        let node = unit.graph.types.get(&id).ok_or(AbiIssue::UnknownLayout)?;
        if !node.complete || node.spelling.is_none() {
            return Err(AbiIssue::UnknownLayout);
        }
        if node.pointer {
            let target = match node.references.as_slice() {
                [] => &CType::Void,
                [target] => unit
                    .graph
                    .types
                    .get(target)
                    .and_then(|node| node.spelling.as_ref())
                    .ok_or(AbiIssue::UnknownLayout)?,
                _ => return Err(AbiIssue::UnknownLayout),
            };
            if node.spelling.as_ref() != Some(&CType::pointer_to(target.clone())) {
                return Err(AbiIssue::UnknownLayout);
            }
        }
        types.insert(id);
        if by_value && node.aggregate {
            let definition = unit
                .graph
                .definitions
                .get(&id)
                .ok_or(AbiIssue::IncompatibleDefinition)?;
            if !definition.compatible_profiles.contains(&profile) {
                return Err(AbiIssue::IncompatibleDefinition);
            }
            definitions.insert(id);
        }
        pending.extend(
            node.references
                .iter()
                .map(|next| (*next, by_value && !node.pointer)),
        );
    }
    Ok((
        types.into_iter().collect(),
        definitions.into_iter().collect(),
    ))
}

fn same_signature(left: &DeclaredSignature, right: &DeclaredSignature) -> bool {
    left.ret == right.ret
        && left.variadic == right.variadic
        && left.abi == right.abi
        && left.params.len() == right.params.len()
        && left
            .params
            .iter()
            .zip(&right.params)
            .all(|((_, left), (_, right))| left == right)
}

fn same_definition(left: Option<&Definition>, right: Option<&Definition>) -> bool {
    match (left, right) {
        (None, None) => true,
        (Some(left), Some(right)) => {
            left.name == right.name
                && left.members == right.members
                && left.fields == right.fields
                && left.contains == right.contains
                && left.size == right.size
                && left.alignment == right.alignment
                && left.compatible_profiles == right.compatible_profiles
        }
        _ => false,
    }
}

fn same_types(left: &CallSource, right: &CallSource) -> bool {
    if left.source.parameters.len() != right.source.parameters.len()
        || left.source.result.is_some() != right.source.result.is_some()
    {
        return false;
    }
    let mut pending: Vec<_> = left
        .source
        .parameters
        .iter()
        .copied()
        .flatten()
        .zip(right.source.parameters.iter().copied().flatten())
        .collect();
    if let (Some(left), Some(right)) = (left.source.result, right.source.result) {
        pending.push((left, right));
    }
    let mut seen = HashSet::new();
    while let Some((left_id, right_id)) = pending.pop() {
        if !seen.insert((left_id, right_id)) {
            continue;
        }
        if seen.len() > 65536 {
            return false;
        }
        let (Some(a), Some(b)) = (
            left.graph.types.get(&left_id),
            right.graph.types.get(&right_id),
        ) else {
            return false;
        };
        if a.tag != b.tag
            || a.name != b.name
            || a.spelling != b.spelling
            || a.size != b.size
            || a.encoding != b.encoding
            || a.layout != b.layout
            || a.dimensions != b.dimensions
            || a.enumerators != b.enumerators
            || a.complete != b.complete
            || a.pointer != b.pointer
            || a.aggregate != b.aggregate
            || a.references.len() != b.references.len()
            || a.members
                .iter()
                .map(|(name, _)| name)
                .ne(b.members.iter().map(|(name, _)| name))
            || !same_definition(
                left.graph.definitions.get(&left_id),
                right.graph.definitions.get(&right_id),
            )
        {
            return false;
        }
        match (
            left.graph.generated_members.get(&left_id),
            right.graph.generated_members.get(&right_id),
        ) {
            (None, None) => {}
            (Some(a), Some(b)) if a.len() == b.len() => {
                for (a, b) in a.iter().zip(b) {
                    match (a, b) {
                        (
                            CallMember::Field {
                                name: a,
                                ty: left,
                                offset: x,
                                bytes: n,
                            },
                            CallMember::Field {
                                name: b,
                                ty: right,
                                offset: y,
                                bytes: m,
                            },
                        ) if a == b && x == y && n == m => pending.push((*left, *right)),
                        (
                            CallMember::Bytes {
                                offset: a,
                                bytes: x,
                            },
                            CallMember::Bytes {
                                offset: b,
                                bytes: y,
                            },
                        ) if a == b && x == y => {}
                        _ => return false,
                    }
                }
            }
            _ => return false,
        }
        pending.extend(
            a.references
                .iter()
                .copied()
                .zip(b.references.iter().copied()),
        );
    }
    true
}

#[cfg(test)]
mod tests;