rapx 0.7.28

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
//! Discharge pointer obligations from struct field invariants.
//!
//! When a raw pointer handed to an ownership-consuming API (e.g.
//! `Box::from_raw`) or a raw-pointer dereference was loaded from a struct
//! field reached through a reference or raw pointer, and the field's struct
//! declares a matching invariant such as
//! `#[rapx::invariant(Owning(field.unwrap_some()))]`,
//! `#[rapx::invariant(Allocated(field, T, n))]`,
//! `#[rapx::invariant(ValidPtr(field, T, n))]` or
//! `#[rapx::invariant(Typed(field, T))]`, the invariant is a caller-provided
//! assumption about that memory (exactly like the `Align` struct invariants
//! already asserted as entry facts) and can discharge the obligation.
//!
//! The trace walks the forward value snapshot from the checkpoint argument
//! back through value copies (`x = y`, `x = (y as Some).0`, pointer-returning
//! `as_ptr`-style calls) and stops at each place of shape
//! `base_local[.field...]`.  Whenever `base_local` is a reference/raw pointer
//! to a local ADT declaring an invariant whose projection matches the
//! remaining field path, the obligation is discharged.
//!
//! Like the existing `Align` handling, this assumes the invariant holds on
//! function entry and that the traced field has not been re-established
//! mid-function; mutators are expected to restore invariants before their
//! endpoint checkpoints.

use rustc_hir::def_id::DefId;
use rustc_middle::ty::{Ty, TyCtxt, TyKind};

use rustc_abi::FieldIdx;

use crate::verify::{
    contract::{ContractExpr, ContractPlace, Property, PropertyArg, PropertyKind},
    def_use::{PlaceBaseKey, PlaceKey},
    helpers::Checkpoint,
    target::get_struct_invariants_for_adt,
    verifier::{AbstractValue, ForwardVisitResult, StateFact},
};

/// Maximum substitution steps while tracing the pointer back to a field.
const MAX_TRACE_STEPS: usize = 32;

/// Try to discharge `kind` for `target` from a struct field invariant.
///
/// When given, `required_ty` and `required_elements` must both be satisfied
/// by the declared invariant.  Returns a human-readable reason on success.
pub(super) fn discharge_from_field_invariant<'tcx>(
    tcx: TyCtxt<'tcx>,
    caller: DefId,
    target: &PlaceKey,
    forward: &ForwardVisitResult<'tcx>,
    kind: PropertyKind,
    required_ty: Option<Ty<'tcx>>,
    required_elements: Option<u64>,
) -> Option<String> {
    let body = tcx.optimized_mir(caller);
    let mut current = target.clone();
    let mut visited: Vec<PlaceKey> = Vec::new();

    for _ in 0..MAX_TRACE_STEPS {
        if visited.contains(&current) {
            break;
        }
        visited.push(current.clone());

        if let Some(reason) = field_invariant_matches(
            tcx,
            caller,
            body,
            &current,
            kind.clone(),
            required_ty,
            required_elements,
        ) {
            return Some(reason);
        }

        let Some(next) = substitute_base(&current, forward) else {
            break;
        };
        current = next;
    }

    None
}

/// Replace the base local of `place` with its recorded forward value,
/// splicing the remaining field path onto the source place.
fn substitute_base<'tcx>(place: &PlaceKey, forward: &ForwardVisitResult<'tcx>) -> Option<PlaceKey> {
    let local = place.local()?;

    let source = match forward.values.get(&local) {
        Some(AbstractValue::Place(source))
        | Some(AbstractValue::Ref(source))
        | Some(AbstractValue::RawPtr(source)) => Some(source.clone()),
        Some(AbstractValue::Cast(inner, _)) => match inner.as_ref() {
            AbstractValue::Place(source)
            | AbstractValue::Ref(source)
            | AbstractValue::RawPtr(source) => Some(source.clone()),
            _ => None,
        },
        _ => None,
    };

    let source = source.or_else(|| {
        // Pointer-returning calls (`as_ptr`, `NonNull::from`, ...) record a
        // PointsTo edge from the destination to the pointer-carrying
        // argument.
        forward.facts.iter().find_map(|fact| match fact {
            StateFact::PointsTo { pointer, source }
                if pointer.base == place.base && pointer.fields.is_empty() =>
            {
                Some(source.clone())
            }
            _ => None,
        })
    })?;

    let mut fields = source.fields.clone();
    fields.extend_from_slice(&place.fields);
    Some(PlaceKey {
        base: source.base,
        fields,
    })
}

/// Check whether `place` reads a pointee field covered by a struct invariant
/// of the requested kind.
fn field_invariant_matches<'tcx>(
    tcx: TyCtxt<'tcx>,
    caller: DefId,
    body: &rustc_middle::mir::Body<'tcx>,
    place: &PlaceKey,
    kind: PropertyKind,
    required_ty: Option<Ty<'tcx>>,
    required_elements: Option<u64>,
) -> Option<String> {
    if place.fields.is_empty() {
        return None;
    }
    let local = place.local()?;
    if local.as_usize() >= body.local_decls.len() {
        return None;
    }
    let base_ty = body.local_decls[local].ty;
    let (adt_def, substs) = match base_ty.kind() {
        TyKind::Ref(_, pointee, _) | TyKind::RawPtr(pointee, _) => match pointee.kind() {
            TyKind::Adt(adt, subs) => (*adt, *subs),
            _ => return None,
        },
        TyKind::Adt(adt, subs) => (*adt, *subs),
        _ => return None,
    };
    if !adt_def.is_struct() {
        return None;
    }
    let struct_def_id = adt_def.did();

    for invariant in get_struct_invariants_for_adt(tcx, struct_def_id) {
        if !invariant_kind_implies(tcx, caller, &invariant.kind, &kind, required_ty) {
            continue;
        }
        let Some(PropertyArg::Place(contract_place)) = invariant.args.first() else {
            continue;
        };
        let invariant_key = PlaceKey::from_contract_place(contract_place);
        if invariant_key.fields != place.fields {
            continue;
        }
        if !invariant_args_cover(&invariant, required_ty, required_elements) {
            continue;
        }
        let struct_name = tcx.def_path_str(struct_def_id);
        return Some(format!(
            "{kind:?} assumed from struct invariant on `{struct_name}` for pointee field path {:?}",
            place.fields
        ));
    }

    // No explicit invariant matched — fall back to type-based reasoning.
    // When the pointer traces to a struct field whose type is a Rust
    // reference (`&'a T`, `&'a [T]`, `&'a mut T`), `Alive` is trivially
    // satisfied because a live reference always points to live memory for
    // its declared lifetime.  The base local must also be behind a reference
    // (to reach the struct), but the *field* governs the safety: a raw-pointer
    // field like `*mut T` behind a reference to its struct is NOT trivially
    // alive.
    if kind == PropertyKind::Alive
        && matches!(base_ty.kind(), TyKind::Ref(..))
        && place.fields.len() == 1
    {
        let field_idx = FieldIdx::from_usize(place.fields[0]);
        let variant = adt_def.non_enum_variant();
        if field_idx.as_usize() < variant.fields.len() {
            #[cfg(not(rapx_rustc_ge_198))]
            let field_ty = variant.fields[field_idx].ty(tcx, substs);
            #[cfg(rapx_rustc_ge_198)]
            let field_ty = variant.fields[field_idx].ty(tcx, substs).skip_norm_wip();
            if matches!(field_ty.kind(), TyKind::Ref(..)) {
                let struct_name = tcx.def_path_str(struct_def_id);
                return Some(format!(
                    "Alive inferred from reference-typed field in `{struct_name}`"
                ));
            }
        }
    }

    None
}

/// True when a declared invariant of kind `declared` establishes the checked
/// kind `required`.
///
/// Besides exact matches, two documented implications are used
/// (primitive-sp.md):
/// - `Init(p, T, len)` implies `Typed(p, T)` (psp III.4: initialized memory
///   always satisfies the type invariant, while the converse does not hold).
/// - For non-ZST `T`, `ValidPtr(p, T, len)` implies
///   `Deref(p, T, len) = Allocated(p, T, len) && InBound(p, T, len)`
///   (compound-SP table).  The ZST guard matters because
///   `ValidPtr = Size(T, 0) || (!Size(T, 0) && Deref)` holds vacuously for
///   zero-sized pointees without any allocation.
fn invariant_kind_implies<'tcx>(
    tcx: TyCtxt<'tcx>,
    caller: DefId,
    declared: &PropertyKind,
    required: &PropertyKind,
    required_ty: Option<Ty<'tcx>>,
) -> bool {
    if crate::verify::contract::decomp::kind_implies(declared, required) {
        // For ValidPtr ⇒ Allocated|InBound, ZST types are vacuously valid
        // without allocation — the implication only holds for non-ZST.
        if matches!(declared, PropertyKind::ValidPtr)
            && matches!(required, PropertyKind::Allocated | PropertyKind::InBound)
            && !required_ty.is_some_and(|ty| {
                super::common::safe_type_layout(tcx, caller, ty).is_some_and(|(_, size)| size > 0)
            })
        {
            return false;
        }
        return true;
    }
    false
}

/// True when a declared invariant's type/count arguments cover the requested
/// type and element count.  Kinds without type or count arguments (e.g.
/// `Owning`) are covered trivially.
fn invariant_args_cover<'tcx>(
    invariant: &Property<'tcx>,
    required_ty: Option<Ty<'tcx>>,
    required_elements: Option<u64>,
) -> bool {
    let declared_ty = invariant.args.iter().find_map(|arg| match arg {
        PropertyArg::Ty(ty) => Some(*ty),
        _ => None,
    });
    let declared_elements = invariant.args.iter().find_map(|arg| match arg {
        PropertyArg::Expr(ContractExpr::Const(value)) => u64::try_from(*value).ok(),
        _ => None,
    });

    let ty_ok = match (required_ty, declared_ty) {
        (Some(required), Some(declared)) => {
            required == declared || format!("{required:?}") == format!("{declared:?}")
        }
        (None, _) => true,
        (Some(_), None) => false,
    };
    let elements_ok = match (required_elements, declared_elements) {
        (Some(required), Some(declared)) => declared >= required,
        (None, _) => true,
        (Some(_), None) => false,
    };
    ty_ok && elements_ok
}

/// Discharge a struct-invariant checkpoint obligation from an equivalent
/// entry contract fact.
///
/// Struct invariants become entry assumptions for every method
/// (`caller_requires`), and constructor/method endpoint checks re-verify the
/// same properties at return checkpoints.  When an entry `Contract` fact of
/// the same kind covers the same place (and its type/count arguments), the
/// property is preserved by the frame unless the function re-assigned the
/// field with something weaker; this mirrors how `Align` invariants are
/// already asserted into the SMT model and then proved against themselves.
pub(super) fn discharge_from_contract_fact<'tcx>(
    property: &Property<'tcx>,
    forward: &ForwardVisitResult<'tcx>,
) -> Option<String> {
    let target_key = contract_property_key(property)?;

    for fact in &forward.facts {
        let StateFact::Contract(contract) = fact else {
            continue;
        };
        if !crate::verify::contract::decomp::kind_implies(&contract.kind, &property.kind) {
            continue;
        }
        let Some(contract_key) = contract_property_key(contract) else {
            continue;
        };
        if contract_key != target_key {
            continue;
        }
        if !contract_args_cover(contract, property) {
            continue;
        }
        return Some(format!(
            "{:?} assumed from an entry contract covering the same place",
            property.kind
        ));
    }

    None
}

/// Resolve the first place argument of a property, normalising `Arg(n)` bases
/// to their MIR locals so entry facts and checkpoint targets compare equal.
fn contract_property_key<'tcx>(property: &Property<'tcx>) -> Option<PlaceKey> {
    let arg = property.args.first()?;
    let place = match arg {
        PropertyArg::Place(place) => place,
        PropertyArg::Expr(ContractExpr::Place(place)) => place,
        _ => return None,
    };
    let mut key = PlaceKey::from_contract_place(place);
    if let PlaceBaseKey::Arg(index) = key.base {
        key.base = PlaceBaseKey::Local(index + 1);
    }
    Some(key)
}

/// True when the entry contract's type/count arguments are at least as
/// strong as the checked invariant's.  Kinds without such arguments are
/// covered trivially.
fn contract_args_cover<'tcx>(contract: &Property<'tcx>, property: &Property<'tcx>) -> bool {
    let ty_of = |candidate: &Property<'tcx>| {
        candidate.args.iter().find_map(|arg| match arg {
            PropertyArg::Ty(ty) => Some(*ty),
            _ => None,
        })
    };
    let elements_of = |candidate: &Property<'tcx>| {
        candidate.args.iter().find_map(|arg| match arg {
            PropertyArg::Expr(ContractExpr::Const(value)) => u64::try_from(*value).ok(),
            _ => None,
        })
    };

    let ty_ok = match (ty_of(property), ty_of(contract)) {
        (Some(required), Some(declared)) => {
            required == declared || format!("{required:?}") == format!("{declared:?}")
        }
        (None, _) => true,
        (Some(_), None) => false,
    };
    let elements_ok = match (elements_of(property), elements_of(contract)) {
        (Some(required), Some(declared)) => declared >= required,
        (None, _) => true,
        (Some(_), None) => false,
    };
    ty_ok && elements_ok
}

pub(super) fn discharge_from_contract_fact_with_checkpoint<'tcx>(
    property: &Property<'tcx>,
    forward: &ForwardVisitResult<'tcx>,
    checkpoint: &Checkpoint<'tcx>,
) -> Option<String> {
    let target_key = checkpoint_target_key(checkpoint, property)
        .or_else(|| contract_property_key(property))?;

    for fact in &forward.facts {
        let StateFact::Contract(contract) = fact else {
            continue;
        };
        if !crate::verify::contract::decomp::kind_implies(&contract.kind, &property.kind) {
            continue;
        }
        let Some(contract_key) = contract_property_key(contract) else {
            continue;
        };
        if contract_key != target_key
            && !provenance_chain_reaches(&contract_key, &target_key, forward)
        {
            continue;
        }
        if !contract_args_cover(contract, property) {
            continue;
        }
        return Some(format!(
            "{:?} assumed from an entry contract covering the same place",
            property.kind
        ));
    }

    None
}

fn checkpoint_target_key<'tcx>(
    checkpoint: &Checkpoint<'tcx>,
    property: &Property<'tcx>,
) -> Option<PlaceKey> {
    let arg = property.args.first()?;
    let place = match arg {
        PropertyArg::Place(place) => place,
        PropertyArg::Expr(ContractExpr::Place(place)) => place,
        _ => return None,
    };
    if let ContractPlace {
        base: crate::verify::contract::PlaceBase::Arg(index),
        ..
    } = place
    {
        let operand = checkpoint.args.get(*index)?;
        match operand {
            rustc_middle::mir::Operand::Copy(mir_place)
            | rustc_middle::mir::Operand::Move(mir_place) => {
                Some(PlaceKey::from_mir_place(mir_place))
            }
            _ => None,
        }
    } else {
        None
    }
}

fn provenance_chain_reaches<'tcx>(
    contract: &PlaceKey,
    target: &PlaceKey,
    forward: &ForwardVisitResult<'tcx>,
) -> bool {
    let mut seen: std::collections::HashSet<PlaceKey> = std::collections::HashSet::new();
    let mut queue: Vec<PlaceKey> = vec![target.clone()];
    while let Some(cur) = queue.pop() {
        if &cur == contract {
            return true;
        }
        if !seen.insert(cur.clone()) {
            continue;
        }
        if cur.fields.is_empty() {
            if let Some(local) = cur.local()
                && let Some(def) = forward
                    .latest_value_definition_before(local, forward.value_definitions.len())
            {
                match &def.value {
                    AbstractValue::Place(p)
                    | AbstractValue::Ref(p)
                    | AbstractValue::RawPtr(p) => queue.push(p.clone()),
                    _ => {}
                }
            }
        }
        for fact in &forward.facts {
            let StateFact::Cast { target, source, .. } = fact else { continue; };
            if target == &cur {
                match source {
                    AbstractValue::Place(p)
                    | AbstractValue::Ref(p)
                    | AbstractValue::RawPtr(p) => queue.push(p.clone()),
                    _ => {}
                }
            }
        }
    }
    false
}