rapx 0.7.32

A static analysis platform for Rust program analysis and verification
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
use rustc_middle::mir::{
    Body, Local, Operand, Rvalue, StatementKind,
    TerminatorKind,
};
use rustc_middle::ty::TyCtxt;
use rustc_span::DUMMY_SP;

use crate::compat::FxHashMap;

pub(crate) fn follow_parents(parents: &FxHashMap<Local, Local>, start: Local) -> Local {
    let mut current = start;
    let mut seen = std::collections::HashSet::new();
    while seen.insert(current) {
        let Some(next) = parents.get(&current) else {
            break;
        };
        current = *next;
    }
    current
}

pub(crate) fn resolve_through_casts<'tcx>(body: &Body<'tcx>, local: Local) -> Local {
    let mut current = local;
    let mut seen = std::collections::HashSet::new();
    while seen.insert(current) {
        let found = body.basic_blocks.iter().any(|data| {
            data.statements.iter().any(|stmt| {
                let StatementKind::Assign(assign) = &stmt.kind else {
                    return false;
                };
                let (target, rvalue) = assign.as_ref();
                if target.local != current || !target.projection.is_empty() {
                    return false;
                }
                if let Rvalue::Cast(_, operand, _) = rvalue {
                    #[allow(unreachable_patterns)]
                match operand {
                        Operand::Copy(p) | Operand::Move(p) if p.projection.is_empty() => {
                            current = p.local;
                            return true;
                        }
                        _ => {}
                    }
                }
                false
            })
        });
        if !found {
            break;
        }
    }
    current
}

fn scalar_constant(operand: &Operand<'_>) -> Option<u128> {
    let constant = match operand {
        Operand::Constant(c) => c,
        _ => return None,
    };
    constant.const_.try_to_scalar_int().map(|s| s.to_uint(s.size()))
}

pub(crate) fn collect_all_const_bytes_worklist<'tcx>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    root: Local,
) -> Vec<Vec<u8>> {
    let mut results: Vec<Vec<u8>> = Vec::new();
    let mut worklist: Vec<Local> = vec![root];
    let mut visited: std::collections::HashSet<Local> = std::collections::HashSet::new();

    while let Some(local) = worklist.pop() {
        if !visited.insert(local) {
            continue;
        }

        for data in body.basic_blocks.iter() {
            for statement in &data.statements {
                let StatementKind::Assign(assign) = &statement.kind else {
                    continue;
                };
                let (target, rvalue) = assign.as_ref();
                if target.local != local || !target.projection.is_empty() {
                    continue;
                }

                if let Rvalue::Ref(_, _, place) = rvalue {
                    if let Some(bytes) = const_bytes_for_local(tcx, body, place.local) {
                        results.push(bytes);
                    }
                    continue;
                }

                if let Rvalue::Use(operand, ..) = rvalue {
                    #[allow(unreachable_patterns)]
                match operand {
                    Operand::Copy(p) | Operand::Move(p) => {
                        worklist.push(p.local);
                        if let Some(bytes) = const_bytes_for_local(tcx, body, p.local) {
                            results.push(bytes);
                        }
                        continue;
                    }
                    Operand::Constant(_) => {}
                    _ => continue,
                    }
                }

                let constant = match rvalue {
                    Rvalue::Use(Operand::Constant(constant), ..)
                    | Rvalue::Cast(_, Operand::Constant(constant), _) => constant,
                    _ => continue,
                };
                let Ok(value) = constant.const_.eval(
                    tcx,
                    rustc_middle::ty::TypingEnv::fully_monomorphized(),
                    DUMMY_SP,
                ) else {
                    continue;
                };
                if let Some(bytes) = crate::helpers::mir_utils::const_value_bytes(tcx, value, 0) {
                    results.push(bytes);
                }
            }
        }

        for data in body.basic_blocks.iter() {
            if let Some(terminator) = &data.terminator {
                if let TerminatorKind::Call { destination, func, args, .. } = &terminator.kind {
                    let dlocal = destination.local;
                    if dlocal != local {
                        continue;
                    }
                    if !destination.projection.is_empty() {
                        continue;
                    }
                    let name = crate::helpers::mir_utils::call_name(tcx, func);
                    if name.contains("as_ptr") || name.contains("::as_") {
                        for arg in args {
                            if let Some(bytes) = const_bytes_from_operand(tcx, body, &arg.node) {
                                results.push(bytes);
                            }
                        }
                    }
                    if name.contains("::add") {
                        if let Some(offset) = args.get(1).and_then(|a| scalar_constant(&a.node)) {
                            if let Some(base) = args.first() {
                                if let Some(bytes) = const_bytes_from_operand(tcx, body, &base.node) {
                                    let start = offset as usize;
                                    if start < bytes.len() {
                                        results.push(bytes[start..].to_vec());
                                    }
                                }
                            }
                        }
                    }
                    if name.contains("box_assume_init_into_vec_unsafe") {
                        if let Some(box_op) = args.first() {
                            if let Operand::Copy(p) | Operand::Move(p) = &box_op.node {
                                if p.projection.is_empty() {
                                    worklist.push(p.local);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    {
        let mut agg_roots = std::collections::HashSet::new();
        let mut seen = std::collections::HashSet::new();
        let mut work = vec![root];
        while let Some(local) = work.pop() {
            if !seen.insert(local) {
                continue;
            }
            for data in body.basic_blocks.iter() {
                for statement in &data.statements {
                    let StatementKind::Assign(assign) = &statement.kind else {
                        continue;
                    };
                    let (target, rvalue) = assign.as_ref();
                    if target.local != local || !target.projection.is_empty() {
                        continue;
                    }
                    if let Rvalue::Use(Operand::Copy(p) | Operand::Move(p), ..) = rvalue {
                        work.push(p.local);
                    }
                    if let Rvalue::Cast(_, Operand::Copy(p) | Operand::Move(p), _) = rvalue {
                        if p.projection.is_empty() {
                            work.push(p.local);
                        }
                    }
                }
            }
            for data in body.basic_blocks.iter() {
                if let Some(terminator) = &data.terminator {
                    if let TerminatorKind::Call { destination, func, args, .. } = &terminator.kind {
                        if destination.local == local
                            && destination.projection.is_empty()
                        {
                            let name = crate::helpers::mir_utils::call_name(tcx, func);
                            if name.contains("box_assume_init_into_vec_unsafe") {
                                if let Some(box_op) = args.first() {
                                    if let Operand::Copy(p) | Operand::Move(p) = &box_op.node {
                                        if p.projection.is_empty() {
                                            work.push(p.local);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            agg_roots.insert(local);
        }

        for data in body.basic_blocks.iter() {
            for statement in &data.statements {
                let StatementKind::Assign(assign) = &statement.kind else {
                    continue;
                };
                let (_, rvalue) = assign.as_ref();
                let Rvalue::Aggregate(_, operands) = rvalue else {
                    continue;
                };
                if operands.len() < 2 {
                    continue;
                }
                let last_op = operands.iter().last().unwrap();
                if !is_constant_zero_u8(last_op) {
                    continue;
                }
                let mut all_nonzero = true;
                for op in operands.iter().take(operands.len() - 1) {
                    if !aggregate_op_is_nonzero(tcx, body, op) {
                        all_nonzero = false;
                        break;
                    }
                }
                if all_nonzero {
                    let len = operands.len();
                    let mut bytes = Vec::with_capacity(len);
                    for _ in 0..len - 1 {
                        bytes.push(b'x');
                    }
                    bytes.push(0);
                    results.push(bytes);
                }
            }
        }
    }

    for data in body.basic_blocks.iter() {
        if let Some(terminator) = &data.terminator {
            if let TerminatorKind::Call { func, args, .. } = &terminator.kind {
                let name = crate::helpers::mir_utils::call_name(tcx, func);
                if name.contains("as_ptr") || name.contains("::as_") {
                    for arg in args {
                        if let Some(bytes) = operand_const_bytes(tcx, &arg.node) {
                            results.push(bytes);
                        } else if let Operand::Copy(p) | Operand::Move(p) = &arg.node {
                            if p.projection.is_empty() {
                                if let Some(bytes) = const_bytes_for_local(tcx, body, p.local) {
                                    results.push(bytes);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    results
}

fn const_bytes_from_operand<'tcx>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    operand: &Operand<'tcx>,
) -> Option<Vec<u8>> {
    if let Some(bytes) = operand_const_bytes(tcx, operand) {
        return Some(bytes);
    }
    match operand {
        Operand::Copy(p) | Operand::Move(p) if p.projection.is_empty() => {
            if let Some(bytes) = const_bytes_for_local(tcx, body, p.local) {
                return Some(bytes);
            }
            const_bytes_from_call_dest(tcx, body, p.local)
        }
        _ => None,
    }
}

fn const_bytes_from_call_dest<'tcx>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    local: Local,
) -> Option<Vec<u8>> {
    for data in body.basic_blocks.iter() {
        if let Some(terminator) = &data.terminator {
            if let TerminatorKind::Call { destination, func, args, .. } = &terminator.kind {
                if destination.local != local || !destination.projection.is_empty() {
                    continue;
                }
                let name = crate::helpers::mir_utils::call_name(tcx, func);
                if name.contains("as_ptr") || name.contains("::as_") {
                    for arg in args {
                        if let Some(bytes) = const_bytes_from_operand(tcx, body, &arg.node) {
                            return Some(bytes);
                        }
                    }
                }
            }
        }
    }
    None
}

pub(crate) fn const_bytes_for_local<'tcx>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    root: Local,
) -> Option<Vec<u8>> {
    for data in body.basic_blocks.iter() {
        for statement in &data.statements {
            let StatementKind::Assign(assign) = &statement.kind else {
                continue;
            };
            let (target, rvalue) = assign.as_ref();
            if target.local != root || !target.projection.is_empty() {
                continue;
            }
            if let Rvalue::Ref(_, _, place) = rvalue {
                let deref_local = place.local;
                if let Some(bytes) = const_bytes_for_local(tcx, body, deref_local) {
                    return Some(bytes);
                }
                continue;
            }
            if let Rvalue::Use(operand, ..) = rvalue {
                #[allow(unreachable_patterns)]
                match operand {
                Operand::Copy(p) | Operand::Move(p) => {
                    if let Some(bytes) = const_bytes_for_local(tcx, body, p.local) {
                        return Some(bytes);
                    }
                    if let Some(bytes) = const_bytes_from_call_dest(tcx, body, p.local) {
                        return Some(bytes);
                    }
                    continue;
                }
                Operand::Constant(_) => {}
                _ => continue,
                }
            }
            if let Rvalue::Cast(_, operand, _) = rvalue {
                if let Operand::Copy(p) | Operand::Move(p) = operand {
                    if p.projection.is_empty() {
                        if let Some(bytes) = const_bytes_for_local(tcx, body, p.local) {
                            return Some(bytes);
                        }
                    }
                }
                continue;
            }
            let constant = match rvalue {
                Rvalue::Use(Operand::Constant(constant), ..)
                | Rvalue::Cast(_, Operand::Constant(constant), _) => constant,
                _ => continue,
            };
            let value = constant
                .const_
                .eval(
                    tcx,
                    rustc_middle::ty::TypingEnv::fully_monomorphized(),
                    DUMMY_SP,
                )
                .ok()?;
            return crate::helpers::mir_utils::const_value_bytes(tcx, value, 0);
        }
    }
    None
}

fn aggregate_op_is_nonzero<'tcx>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
    operand: &Operand<'tcx>,
) -> bool {
    if is_constant_zero_u8(operand) {
        return false;
    }
    if operand_const_bytes(tcx, operand).is_some() {
        return true;
    }
    match operand {
        Operand::Copy(p) | Operand::Move(p) if p.projection.is_empty() => {
            for data in body.basic_blocks.iter() {
                if let Some(terminator) = &data.terminator {
                    if let TerminatorKind::Call { destination, func, .. } = &terminator.kind {
                        if destination.local == p.local && destination.projection.is_empty() {
                            return fn_always_returns_nonzero(tcx, func);
                        }
                    }
                }
            }
            false
        }
        Operand::Constant(c) => {
            c.const_
                .try_to_scalar_int()
                .map_or(false, |s| s.to_uint(s.size()) != 0)
        }
        _ => false,
    }
}

fn operand_const_bytes<'tcx>(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>) -> Option<Vec<u8>> {
    let constant = match operand {
        Operand::Constant(c) => c,
        _ => return None,
    };
    let value = constant
        .const_
        .eval(
            tcx,
            rustc_middle::ty::TypingEnv::fully_monomorphized(),
            DUMMY_SP,
        )
        .ok()?;
    crate::helpers::mir_utils::const_value_bytes(tcx, value, 0)
}

fn is_constant_zero_u8(operand: &Operand<'_>) -> bool {
    let constant = match operand {
        Operand::Constant(c) => c,
        _ => return false,
    };
    constant
        .const_
        .try_to_scalar_int()
        .map_or(false, |s| s.to_uint(s.size()) == 0)
}

fn fn_always_returns_nonzero<'tcx>(
    tcx: TyCtxt<'tcx>,
    func: &Operand<'tcx>,
) -> bool {
    let Some(fn_def_id) = crate::helpers::mir_utils::dep_callee_def_id(func) else { return false };
    let callee_body = tcx.optimized_mir(fn_def_id);

    let mut has_return = false;
    for bb_data in callee_body.basic_blocks.iter() {
        if let Some(terminator) = &bb_data.terminator {
            if matches!(terminator.kind, TerminatorKind::Return) {
                has_return = true;
            }
        }
        for stmt in &bb_data.statements {
            let StatementKind::Assign(assign) = &stmt.kind else { continue };
            let (target, rvalue) = assign.as_ref();
            if target.local != Local::from_usize(0) || !target.projection.is_empty() {
                continue;
            }
            if !rvalue_is_nonzero(tcx, rvalue, callee_body) {
                return false;
            }
        }
    }

    has_return
}

fn rvalue_is_nonzero<'tcx>(_tcx: TyCtxt<'tcx>, rvalue: &Rvalue<'tcx>, _body: &Body<'tcx>) -> bool {
    match rvalue {
        Rvalue::Use(Operand::Constant(c), ..) => {
            c.const_
                .try_to_scalar_int()
                .map_or(false, |s| s.to_uint(s.size()) != 0)
        }
        Rvalue::Use(Operand::Copy(_), ..) | Rvalue::Use(Operand::Move(_), ..) => true,
        _ => false,
    }
}

pub(crate) fn body_parents<'tcx>(
    tcx: TyCtxt<'tcx>,
    body: &Body<'tcx>,
) -> FxHashMap<Local, Local> {
    let mut parents: FxHashMap<Local, Local> = Default::default();
    for data in body.basic_blocks.iter() {
        for statement in &data.statements {
            let StatementKind::Assign(assign) = &statement.kind else {
                continue;
            };
            let (target, rvalue) = assign.as_ref();
            let source = match rvalue {
                Rvalue::Use(Operand::Copy(place) | Operand::Move(place), ..)
                | Rvalue::Cast(_, Operand::Copy(place) | Operand::Move(place), _)
                | Rvalue::Ref(_, _, place)
                | Rvalue::RawPtr(_, place)
                | Rvalue::CopyForDeref(place) => Some(place.local),
                _ => None,
            };
            if let Some(source) = source {
                parents.entry(target.local).or_insert(source);
            }
        }
        let Some(terminator) = &data.terminator else {
            continue;
        };
        let TerminatorKind::Call {
            func,
            args,
            destination,
            ..
        } = &terminator.kind
        else {
            continue;
        };
        let name = crate::helpers::mir_utils::call_name(tcx, func);
        if !crate::helpers::api_classify::is_as_ptr(&name) {
            continue;
        }
        let Some(source) = args.first().and_then(|arg| match &arg.node {
            Operand::Copy(place) | Operand::Move(place) => Some(place.local),
            _ => None,
        }) else {
            continue;
        };
        parents.entry(destination.local).or_insert(source);
    }
    parents
}