rapx 0.7.63

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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Initialize symbolic function parameters and their backing allocations.

use rustc_middle::mir::{Local, Operand, Rvalue, StatementKind};
use rustc_middle::ty::{Ty, TyKind};
use z3::ast::Int;

use crate::compat::FxHashMap;
use crate::helpers::mir_utils;
use crate::verify::api_classify;

use super::state::{AllocId, Provenance, ValueFacts, ValueSource, VmState, VmValue};

impl<'z3, 'tcx> VmState<'z3, 'tcx> {
    pub(crate) fn init_parameters(&mut self) {
        let arg_count = self.body().arg_count;
        let local_count = self.body().local_decls.len();

        for local_idx in 1..local_count {
            let local = Local::from_usize(local_idx);
            if self.current_frame.local_alloc.contains_key(&local) {
                continue;
            }
            let decl = &self.body().local_decls[local];
            let ty = decl.ty;

            self.ensure_local_allocation(local);

            let mut invariants = ValueFacts::default();
            if local_idx <= arg_count {
                if self.init_box_vec_param(local, ty, local_idx, &mut invariants) {
                    continue;
                }
                if self.init_struct_param(local, ty, local_idx, &mut invariants) {
                    continue;
                }
                if self.init_reference_param(local, ty, local_idx, &mut invariants) {
                    continue;
                }
                let is_scalar = matches!(
                    ty.kind(),
                    rustc_middle::ty::TyKind::Uint(_)
                        | rustc_middle::ty::TyKind::Int(_)
                        | rustc_middle::ty::TyKind::Float(_)
                        | rustc_middle::ty::TyKind::Bool
                        | rustc_middle::ty::TyKind::Char
                );
                if is_scalar {
                    let val = self.fresh_int(&format!("arg_{}", local_idx));
                    self.set_local(
                        local,
                        VmValue {
                            z3_term: val,
                            ty,
                            provenance: None,
                            facts: invariants,
                            source: ValueSource::None,
                        },
                    );
                    continue;
                }
                if let rustc_middle::ty::TyKind::RawPtr(pointee, _mutbl) = ty.kind() {
                    let max_size = Int::from_u64(self.z3_ctx, i64::MAX as u64);
                    let pointee_align = self.align_sym(*pointee);
                    let (alloc_id, base) =
                        self.allocate_external(max_size, pointee_align, Some(*pointee));
                    self.set_local(
                        local,
                        VmValue {
                            z3_term: base,
                            ty,
                            provenance: Some(Provenance {
                                alloc_id,
                                offset: Int::from_u64(self.z3_ctx, 0),
                                offset_kind: None,
                            }),
                            facts: invariants,
                            source: ValueSource::None,
                        },
                    );
                    continue;
                }
                if self.init_array_param(local, ty, local_idx, &mut invariants) {
                    continue;
                }
                let term = self.fresh_int(&format!("param_{}", local_idx));
                self.set_local(
                    local,
                    VmValue {
                        z3_term: term,
                        ty,
                        provenance: None,
                        facts: invariants,
                        source: ValueSource::None,
                    },
                );
                continue;
            }
            // assignments). For reference/raw-pointer locals the value *is* the
            // stack address; for scalar locals use a fresh symbolic value so a
            // stale stack address never leaks into scalar arithmetic (e.g. the
            // `offset <= len` bound check in memchr-style loops).
            let term = match ty.kind() {
                rustc_middle::ty::TyKind::Ref(..) | rustc_middle::ty::TyKind::RawPtr(..) => {
                    self.local_address(local)
                }
                _ => self.fresh_int(&format!("local_{}", local_idx)),
            };
            self.set_local(
                local,
                VmValue {
                    z3_term: term,
                    ty,
                    provenance: None,
                    facts: invariants,
                    source: ValueSource::None,
                },
            );
        }

        self.propagate_entry_block_provenance();
        self.prewarm_generic_size_align();
    }

    /// Initialize a struct/tuple/enum parameter (a non-`Box`/`Vec` ADT):
    /// decompose it into per-field symbolic values for field-level checking.
    fn init_struct_param(
        &mut self,
        local: Local,
        ty: Ty<'tcx>,
        local_idx: usize,
        invariants: &mut ValueFacts<'z3>,
    ) -> bool {
        let rustc_middle::ty::TyKind::Adt(adt_def, _) = ty.kind() else {
            return false;
        };
        if adt_def.is_enum() {
            let term = self.fresh_int(&format!("param_{}", local_idx));
            self.set_local(
                local,
                VmValue {
                    z3_term: term,
                    ty,
                    provenance: None,
                    facts: invariants.clone(),
                    source: ValueSource::None,
                },
            );
            return true;
        }
        let mut elem_alloc: FxHashMap<Ty<'tcx>, (AllocId, Int<'z3>)> = FxHashMap::default();
        self.decompose_adt_fields(local, vec![], ty, local_idx, &mut elem_alloc, 0);
        // A single-raw-pointer wrapper (e.g. `NonNull<T>`) *is* its pointer, so
        // carry the field's provenance onto the whole local — otherwise
        // alias/ownership reasoning can't trace a deref of `self.pointer` back to
        // "owned" (the local's provenance would be `None`).
        if mir_utils::is_raw_ptr_wrapper(self.tcx, adt_def.did())
            && let Some(f0) = self.field_value(local, &[0]).cloned() {
                let prov = f0.provenance.clone();
                self.set_local(
                    local,
                    VmValue {
                        z3_term: f0.z3_term,
                        ty,
                        provenance: prov,
                        facts: ValueFacts {
                            init: true,
                            ..Default::default()
                        },
                        source: ValueSource::None,
                    },
                );
                return true;
            }
        let term = self.fresh_int(&format!("param_{}", local_idx));
        self.set_local(
            local,
            VmValue {
                z3_term: term,
                ty,
                provenance: None,
                facts: ValueFacts {
                    init: true,
                    ..Default::default()
                },
                source: ValueSource::None,
            },
        );
        true
    }

    /// Initialize a `Box`/`Vec`/`CString` parameter: allocate its heap pointee,
    /// expose the owning pointer field, and (for `Vec`) bind symbolic
    /// `len`/`cap`.
    fn init_box_vec_param(
        &mut self,
        local: Local,
        ty: Ty<'tcx>,
        local_idx: usize,
        invariants: &mut ValueFacts<'z3>,
    ) -> bool {
        let rustc_middle::ty::TyKind::Adt(adt_def, substs) = ty.kind() else {
            return false;
        };
        let is_vec = api_classify::is_std_vec(adt_def.did());
        let is_cstring = api_classify::is_std_cstring(adt_def.did());
        if !(api_classify::is_std_box(adt_def.did()) || is_vec || is_cstring) {
            return false;
        }
        let heap_ty = substs.first().and_then(|s| s.as_type()).unwrap_or(ty);
        let heap_size = self.size_of_ty(heap_ty);
        let heap_align = self.align_sym(heap_ty);
        let heap_size_term = Int::from_u64(self.z3_ctx, heap_size.max(1));
        // Vec/CString can hold many elements — use an external allocation so
        // Allocated checks can pass for arbitrary capacity queries.
        let (heap_alloc_id, heap_base) = if is_vec || is_cstring {
            let max_size = Int::from_u64(self.z3_ctx, i64::MAX as u64);
            self.allocate_external(max_size, heap_align.clone(), Some(heap_ty))
        } else {
            self.allocate(heap_size_term, heap_align, Some(heap_ty))
        };
        invariants.non_null = true;
        invariants.init = true;
        self.content_mut(heap_alloc_id).facts.initialized = true;
        // Also expose the container's owning pointer field (Box's inner
        // `Unique<T>.pointer` → `NonNull<T>`, Vec's `buf.ptr.pointer`) so that
        // inlined bodies like `Box::into_non_null_with_allocator` — which reads
        // `(_1.0).0` and transmutes it to `NonNull<T>` — inherit the heap
        // pointer's non-null/aligned/allocated facts.
        let owner_path = self
            .container_ptr_field(ty)
            .expect("container parameter has no owning pointer field");
        self.set_field_value(
            local,
            owner_path,
            VmValue {
                z3_term: heap_base.clone(),
                ty,
                provenance: Some(Provenance {
                    alloc_id: heap_alloc_id,
                    offset: Int::from_u64(self.z3_ctx, 0),
                    offset_kind: None,
                }),
                facts: ValueFacts {
                    non_null: true,
                    init: true,
                    ..Default::default()
                },
                source: ValueSource::None,
            },
        );
        if is_vec {
            let cap = self.fresh_int(&format!("vec_cap_{}", local_idx));
            let len = self.fresh_int(&format!("vec_len_{}", local_idx));
            self.materialize_vec_len_cap(cap, len, heap_size);
        }
        self.set_local(
            local,
            VmValue {
                z3_term: heap_base,
                ty,
                provenance: Some(Provenance {
                    alloc_id: heap_alloc_id,
                    offset: Int::from_u64(self.z3_ctx, 0),
                    offset_kind: None,
                }),
                facts: invariants.clone(),
                source: ValueSource::None,
            },
        );
        true
    }

    /// Initialize an array parameter (`[T; N]`): give it a real allocation with
    /// provenance so downstream call effects can record the alloc_id.
    fn init_array_param(
        &mut self,
        local: Local,
        ty: Ty<'tcx>,
        local_idx: usize,
        invariants: &mut ValueFacts<'z3>,
    ) -> bool {
        let rustc_middle::ty::TyKind::Array(elem_ty, const_len) = ty.kind() else {
            return false;
        };
        let n: Option<usize> = mir_utils::eval_array_len(self.tcx, const_len).map(|v| v as usize);
        let elem_size = self.size_of_ty(*elem_ty);
        let step = (elem_size.max(1)) as usize;
        let align = self.align_sym(*elem_ty);
        let elem_sym = self.size_sym(*elem_ty);
        let n_term = self.const_len_term(const_len);
        let (alloc_id, base) = self.allocate_slice(n_term, elem_sym, align, Some(*elem_ty));
        self.content_mut(alloc_id).facts.initialized = true;
        self.current_frame.local_alloc.insert(local, alloc_id);
        invariants.init = true;
        for i in 0..n.unwrap_or(16) {
            let off = i * step;
            let elem_term = self.fresh_int(&format!("array_{}_idx_{}", local_idx, i));
            self.record_byte_value(alloc_id, off, elem_term);
        }
        self.set_local(
            local,
            VmValue {
                z3_term: base,
                ty,
                provenance: Some(Provenance {
                    alloc_id,
                    offset: Int::from_u64(self.z3_ctx, 0),
                    offset_kind: None,
                }),
                facts: invariants.clone(),
                source: ValueSource::None,
            },
        );
        true
    }

    /// Initialize a reference parameter (`&T`, `&mut T`): create a symbolic
    /// allocation for the pointee, attach provenance, and (for a struct pointee)
    /// materialize its pointer/scalar fields.
    fn init_reference_param(
        &mut self,
        local: Local,
        ty: Ty<'tcx>,
        local_idx: usize,
        invariants: &mut ValueFacts<'z3>,
    ) -> bool {
        let rustc_middle::ty::TyKind::Ref(..) = ty.kind() else {
            return false;
        };
        let precise_pointee = crate::verify::vm::region::fn_arg_ty(
            self.tcx,
            self.current_frame.current_def_id,
            local_idx - 1,
        )
        .and_then(|precise_ty| match precise_ty.kind() {
            rustc_middle::ty::TyKind::Ref(_, inner, _) => Some(*inner),
            _ => None,
        });
        let pointee_ty = precise_pointee.unwrap_or_else(|| {
            if let rustc_middle::ty::TyKind::Ref(_, inner_ty, _) = ty.kind() {
                *inner_ty
            } else {
                ty
            }
        });
        // `&MaybeUninit<T>` / `&[MaybeUninit<T>]` carry no validity invariant —
        // the content need not be initialized — so do not claim `Init` for them
        // (the content property reduces to `Typed`).
        let pointee_is_maybe_uninit = api_classify::is_maybe_uninit_ty(pointee_ty);

        invariants.non_null = true;
        if !pointee_is_maybe_uninit {
            invariants.init = true;
        }
        // A reference always points within a live allocation, so it carries the
        // pointer-validity facts (`NonNull`, `Allocated`, `InBound`) explicitly —
        // the content property `Init` must not be the only source of pointer
        // validity (see std-subsumption.rs).
        invariants.in_bounds = true;

        if let rustc_middle::ty::TyKind::Slice(elem_ty) = pointee_ty.kind() {
            let elem_size = self.size_of_ty(*elem_ty);
            let len = self.fresh_int(&format!("slice_len_{}", local_idx));
            let zero = Int::from_u64(self.z3_ctx, 0);
            self.constraints.assertions.push(len.ge(&zero));
            let isize_max = Int::from_i64(self.z3_ctx, i64::MAX);
            let elem_sz = if elem_size > 0 {
                elem_size
            } else {
                mir_utils::size_of_generic_param(
                    self.tcx,
                    self.current_frame.current_def_id,
                    *elem_ty,
                )
                .max(1)
            };
            let elem_sz_term = Int::from_u64(self.z3_ctx, elem_sz);
            self.constraints
                .assertions
                .push(Int::mul(self.z3_ctx, &[&len, &elem_sz_term]).le(&isize_max));
            if let TyKind::Array(inner_ty, count) = elem_ty.kind() {
                let inner_size = self.size_sym(*inner_ty);
                let count = self.const_len_term(count);
                self.constraints.assertions.push(count.ge(&zero));
                let flat_len = Int::mul(self.z3_ctx, &[&len, &count]);
                self.constraints
                    .assertions
                    .push(inner_size.gt(&zero).implies(&flat_len.le(&isize_max)));
            }
            // The data allocation's byte size uses the shared symbolic `sizeof_T`
            // so `InBound` can cancel the factor (`len·S / S == len`);
            // `allocate_slice` computes `size = len * sizeof_T` and materializes
            // `len` together so the two can never diverge. The alignment is the
            // element type's alignment — symbolic (`align_T`) for a generic
            // element type, with the layout constraint `sizeof_T % align_T == 0`
            // established by `align_sym`.
            let elem_align = self.align_sym(*elem_ty);
            let elem_size_sym = self.size_sym(*elem_ty);
            let (data_alloc_id, data_base) =
                self.allocate_slice(len, elem_size_sym, elem_align, Some(*elem_ty));
            if !pointee_is_maybe_uninit {
                self.content_mut(data_alloc_id).facts.initialized = true;
            }
            // Record placeholder per-byte symbols for the first few elements so
            // byte-level checkers (`ValidCStr` interior-NUL, `ValidString` UTF-8)
            // can reason over symbolic slice bytes (the length is symbolic, so
            // only a bounded prefix is materialized — mirrors the array parameter
            // handling).
            let step = (elem_size.max(1)) as usize;
            let m = 16usize;
            for i in 0..m {
                let off = i * step;
                let elem_term = self.fresh_int(&format!("slice_{}_idx_{}", local_idx, i));
                self.record_byte_value(data_alloc_id, off, elem_term);
            }
            self.set_local(
                local,
                VmValue {
                    z3_term: data_base,
                    ty,
                    provenance: Some(Provenance {
                        alloc_id: data_alloc_id,
                        offset: Int::from_u64(self.z3_ctx, 0),
                        offset_kind: None,
                    }),
                    facts: invariants.clone(),
                    source: ValueSource::None,
                },
            );
            return true;
        }

        let (pointee_alloc_id, pointee_base) = if let rustc_middle::ty::TyKind::Array(elem_ty, const_len) = pointee_ty.kind() {
            let n = self.const_len_term(const_len);
            let elem_size = self.size_sym(*elem_ty);
            let elem_align = self.align_sym(*elem_ty);
            self.allocate_slice(n, elem_size, elem_align, Some(*elem_ty))
        } else {
            let pointee_align = self.align_sym(pointee_ty);
            let pointee_size_term = self
                .struct_size_sym(pointee_ty)
                .unwrap_or_else(|| self.size_sym(pointee_ty));
            self.allocate(pointee_size_term, pointee_align, Some(pointee_ty))
        };
        if !pointee_is_maybe_uninit {
            self.content_mut(pointee_alloc_id).facts.initialized = true;
        }
        self.set_local(
            local,
            VmValue {
                z3_term: pointee_base,
                ty,
                provenance: Some(Provenance {
                    alloc_id: pointee_alloc_id,
                    offset: Int::from_u64(self.z3_ctx, 0),
                    offset_kind: None,
                }),
                facts: invariants.clone(),
                source: ValueSource::None,
            },
        );

        if let rustc_middle::ty::TyKind::Adt(adt_def, substs) = pointee_ty.kind()
            && !adt_def.is_enum() {
                let variant = adt_def.non_enum_variant();
                let mut elem_alloc: FxHashMap<Ty<'tcx>, (AllocId, Int<'z3>)> =
                    FxHashMap::default();
                for (idx, field_def) in variant.fields.iter().enumerate() {
                    let field_ty: Ty<'tcx> = mir_utils::field_ty(self.tcx, field_def, substs);
                    if let rustc_middle::ty::TyKind::RawPtr(inner, _) = field_ty.kind() {
                        self.init_ptr_field(
                            local,
                            vec![idx],
                            field_ty,
                            *inner,
                            local_idx,
                            idx,
                            &mut elem_alloc,
                            true,
                            "field_nn",
                        );
                    } else if let Some(pointee) = self.find_nn_pointee(field_ty) {
                        self.init_ptr_field(
                            local,
                            vec![idx],
                            field_ty,
                            pointee,
                            local_idx,
                            idx,
                            &mut elem_alloc,
                            false,
                            "ref_field",
                        );
                    } else if let rustc_middle::ty::TyKind::Ref(region, pointee, _) =
                        field_ty.kind()
                    {
                        let elem_ty = match pointee.kind() {
                            rustc_middle::ty::TyKind::Slice(e) => *e,
                            _ => *pointee,
                        };
                        self.materialize_external_field(local, idx, field_ty, elem_ty, Some(*region));
                    } else if let rustc_middle::ty::TyKind::Slice(elem_ty) = field_ty.kind() {
                        // DST slice field (e.g. `CStr { inner: [u8] }`): model it
                        // as an external allocation so its length stays symbolic
                        // instead of defaulting to a single element (which would
                        // make `inner.len()` == 1).
                        self.materialize_external_field(local, idx, field_ty, *elem_ty, None);
                    } else if let rustc_middle::ty::TyKind::Adt(adt, substs) = field_ty.kind() {
                        // A heap-backed smart-pointer field (`Box<[T]>`, `Vec<T>`)
                        // inside a referenced struct: materialize the pointee
                        // allocation so field access (e.g. `self.buckets.iter()`)
                        // resolves to the *data* elements, not the whole struct.
                        if (api_classify::is_std_box(adt.did())
                            || api_classify::is_std_vec(adt.did()))
                            && let Some(pointee) = substs.first().and_then(|s| s.as_type())
                            {
                                let elem_ty = match pointee.kind() {
                                    rustc_middle::ty::TyKind::Slice(e) => *e,
                                    _ => pointee,
                                };
                                self.materialize_external_field(local, idx, field_ty, elem_ty, None);
                            } else if !adt.is_enum() && api_classify::is_std_vec(adt.did()) {
                                self.materialize_vec_ptr_field(local, vec![idx], field_ty);
                            }
                    } else if matches!(
                        field_ty.kind(),
                        rustc_middle::ty::TyKind::Uint(_)
                            | rustc_middle::ty::TyKind::Int(_)
                            | rustc_middle::ty::TyKind::Float(_)
                            | rustc_middle::ty::TyKind::Bool
                            | rustc_middle::ty::TyKind::Char
                    ) {
                        // Scalar field (e.g. `size: usize`) inside a referenced
                        // struct. Materialize a fresh symbolic value so that field
                        // reads return the correct term instead of the whole struct
                        // term. Non-scalar, non-pointer ADT fields (Box/Vec/etc.)
                        // are left unset so they keep their pre-existing heap
                        // modeling.
                        let field_term =
                            self.fresh_int(&format!("ref_field_{}_{}", local_idx, idx));
                        self.set_field_value(
                            local,
                            vec![idx],
                            VmValue {
                                z3_term: field_term,
                                ty: field_ty,
                                provenance: None,
                                facts: ValueFacts {
                                    init: true,
                                    ..Default::default()
                                },
                                source: ValueSource::None,
                            },
                        );
                    }
                }
            }
        true
    }

    /// Propagate parameter provenance through the entry block's simple
    /// assignments (`_tmp = _1`, `_tmp = _1 as *const T`), which the backward
    /// slicer may omit as same-block definitions.
    fn propagate_entry_block_provenance(&mut self) {
        let Some(entry_bb) = self.body().basic_blocks.iter().next() else {
            return;
        };
        for stmt in &entry_bb.statements {
            let StatementKind::Assign(assign) = &stmt.kind else {
                continue;
            };
            let (dest, rvalue) = &**assign;
            let dest_local = dest.local;
            let src = match rvalue {
                Rvalue::Use(operand, ..) => Some(operand),
                Rvalue::Cast(_, operand, _) => Some(operand),
                _ => None,
            }
            .and_then(|operand| match operand {
                Operand::Copy(place) | Operand::Move(place) if place.projection.is_empty() => {
                    Some(place.local)
                }
                _ => None,
            });
            if let Some(src_local) = src
                && let Some(src_val) = self.local_value(src_local) {
                    let has_better_prov = src_val.is_pointer()
                        && src_val.facts.non_null
                        && self.local_value(dest_local).is_none_or(|d| {
                            d.provenance.is_none() || !d.facts.non_null
                        });
                    if has_better_prov {
                        self.set_local(
                            dest_local,
                            VmValue {
                                z3_term: src_val.z3_term.clone(),
                                ty: dest.ty(self.body(), self.tcx).ty,
                                provenance: src_val.provenance.clone(),
                                facts: src_val.facts.clone(),
                                source: ValueSource::None,
                            },
                        );
                    }
                }
        }
    }

}