Skip to main content

rapx/vm/mir_rules/
statement.rs

1use rustc_abi::VariantIdx;
2#[cfg(rapx_const_ext)]
3use rustc_middle::ty::consts::ConstExt;
4use rustc_middle::{
5    mir::{
6        AggregateKind, CopyNonOverlapping, Local, Operand, Place, ProjectionElem, Rvalue,
7        Statement, StatementKind,
8    },
9    ty::{TyKind, TypingEnv},
10};
11use z3::ast::{Ast, Bool, Int};
12
13use super::super::state::{AllocKind, MemoryContent, Provenance, ValueSource, VmExecutor, VmValue};
14use super::eval_rvalue;
15use crate::def_ids::type_ids;
16use crate::util::mir_utils;
17
18pub(crate) fn exec_assume<'z3, 'tcx>(state: &mut VmExecutor<'z3, 'tcx>, operand: &Operand<'tcx>) {
19    let value = state.value_of_operand(operand);
20    let zero = Int::from_u64(state.z3_ctx, 0);
21    state.path_state
22        .constraints
23        .assertions
24        .push(value.z3_term._eq(&zero).not());
25}
26
27pub(crate) fn refine_contract_method_const<'z3, 'tcx>(
28    state: &mut VmExecutor<'z3, 'tcx>,
29    statement: &Statement<'tcx>,
30) {
31    let StatementKind::Assign(assign) = &statement.kind else {
32        return;
33    };
34    let (place, rvalue) = &**assign;
35    if !place.projection.is_empty() {
36        return;
37    }
38    let Rvalue::Use(Operand::Constant(constant), ..) = rvalue else {
39        return;
40    };
41    let Ok(value) = constant.const_.eval(
42        state.tcx,
43        TypingEnv::fully_monomorphized(),
44        rustc_span::DUMMY_SP,
45    ) else {
46        return;
47    };
48    let Some(bits) = value
49        .try_to_scalar_int()
50        .and_then(|scalar| u64::try_from(scalar.to_bits(scalar.size())).ok())
51    else {
52        return;
53    };
54    if let Some(mut assigned) = state.local_value(place.local).cloned() {
55        assigned.z3_term = Int::from_u64(state.z3_ctx, bits);
56        state.set_local(place.local, assigned);
57    }
58}
59
60pub(crate) fn exec_copy_nonoverlapping<'z3, 'tcx>(
61    state: &mut VmExecutor<'z3, 'tcx>,
62    copy: &CopyNonOverlapping<'tcx>,
63) {
64    let source = state.value_of_operand(&copy.src);
65    let target = state.value_of_operand(&copy.dst);
66    let count = state.value_of_operand(&copy.count);
67    state.copy_memory_values(&source, &target, &count);
68}
69
70pub(crate) fn exec_set_discriminant<'z3, 'tcx>(
71    state: &mut VmExecutor<'z3, 'tcx>,
72    place: &Place<'tcx>,
73    variant_index: VariantIdx,
74) {
75    let ty = place.ty(state.body(), state.tcx).ty;
76    let TyKind::Adt(adt, _) = ty.kind() else {
77        state.record_unsupported("SetDiscriminant non-enum target");
78        return;
79    };
80    let deref =
81        place.projection.len() == 1 && matches!(place.projection[0].kind(), ProjectionElem::Deref);
82    if (!place.projection.is_empty() && !deref) || !adt.is_enum() {
83        state.record_unsupported("SetDiscriminant target");
84        return;
85    }
86    let Some(term) = state.enum_discriminant_term(ty, variant_index) else {
87        state.record_unsupported("SetDiscriminant value");
88        return;
89    };
90    let fields = &adt.variants()[variant_index].fields;
91    let target_alloc = if deref {
92        state.local_value(place.local).and_then(|value| value.provenance_alloc_id())
93    } else {
94        state.path_state.current_frame.local_alloc.get(&place.local).copied()
95    };
96    let payload_complete = fields.is_empty() || target_alloc.is_some_and(|alloc_id| {
97        state.load_value(alloc_id, ty, &[]).is_some_and(|value| {
98            matches!(&value.source, ValueSource::PendingEnumVariant(pending)
99                if pending._eq(&term).simplify().as_bool() == Some(true))
100        })
101            && fields.iter().enumerate().all(|(index, _)| {
102                state.load_value(alloc_id, ty, &[index]).is_some_and(|value| value.facts.init)
103            })
104    });
105    if !payload_complete {
106        state.record_unsupported("SetDiscriminant incomplete payload");
107    }
108    let value_term = if fields.is_empty() {
109        term.clone()
110    } else {
111        state.fresh_int("enum_value")
112    };
113    let mut value = VmValue::new(value_term, ty);
114    value.source = ValueSource::KnownDiscriminant(term);
115    value.facts.init = payload_complete;
116    if deref {
117        let Some(pointer) = state.local_value(place.local).cloned() else {
118            state.record_unsupported("SetDiscriminant pointer");
119            return;
120        };
121        if !pointer.facts.init || mir_utils::pointee_ty(pointer.ty) != Some(ty) {
122            state.record_unsupported("SetDiscriminant pointer");
123            return;
124        }
125        if !fields.is_empty() {
126            if !payload_complete {
127                state.record_unsupported("SetDiscriminant projected payload");
128                return;
129            }
130            if let Some(provenance) = &pointer.provenance
131                && provenance.offset.simplify().as_u64() == Some(0)
132                && state.alloc(provenance.alloc_id).element_ty.as_ty() == Some(ty)
133            {
134                let alloc_id = provenance.alloc_id;
135                state.clear_write_evidence(alloc_id);
136                state.store_value(alloc_id, ty, Vec::new(), value);
137                state.content_mut(alloc_id).facts.initialized = true;
138                return;
139            }
140            state.record_unsupported("SetDiscriminant pointer target");
141            return;
142        }
143        let deferred_before = state.path_state.inline.deferred_field_writes.len();
144        let referent = state.find_local_by_address(&pointer.z3_term);
145        let written = state.write_through_pointer(&pointer, Vec::new(), value.clone());
146        if written || state.path_state.inline.deferred_field_writes.len() != deferred_before {
147            if let Some(local) = referent
148                && let Some(&alloc_id) = state.path_state.current_frame.local_alloc.get(&local)
149            {
150                state.content_mut(alloc_id).facts.initialized = true;
151            }
152            return;
153        }
154        if let Some(provenance) = &pointer.provenance
155            && provenance.offset.simplify().as_u64() == Some(0)
156            && matches!(state.alloc(provenance.alloc_id).kind, AllocKind::Object)
157            && state.alloc(provenance.alloc_id).element_ty.as_ty() == Some(ty)
158        {
159            let alloc_id = provenance.alloc_id;
160            state.clear_write_evidence(alloc_id);
161            let content = state.content_mut(alloc_id);
162            content.values.clear();
163            content.indexed_elements.clear();
164            content.indexed_elements_modified = true;
165            content.clear_byte_writes();
166            content.facts.initialized = true;
167            state.store_value(alloc_id, ty, Vec::new(), value);
168            return;
169        }
170        state.record_unsupported("SetDiscriminant pointer target");
171        return;
172    }
173    if !payload_complete || fields.is_empty() {
174        state.invalidate_field_descendants(place.local, &[]);
175    }
176    state.set_local(place.local, value);
177    let alloc_id = state.path_state.current_frame.local_alloc[&place.local];
178    state.content_mut(alloc_id).facts.initialized = payload_complete;
179    if !payload_complete {
180        state.content_mut(alloc_id).facts.may_be_uninit = true;
181    }
182}
183
184fn prepare_enum_field_write<'z3, 'tcx>(
185    state: &mut VmExecutor<'z3, 'tcx>,
186    place: &Place<'tcx>,
187    rvalue: &Rvalue<'tcx>,
188) -> Option<bool> {
189    let start = usize::from(
190        place
191            .projection
192            .first()
193            .is_some_and(|projection| matches!(projection.kind(), ProjectionElem::Deref)),
194    );
195    if place.projection.len() != start + 2 {
196        return None;
197    }
198    let ProjectionElem::Downcast(_, variant) = place.projection[start].kind() else {
199        return None;
200    };
201    let ProjectionElem::Field(..) = place.projection[start + 1].kind() else {
202        return None;
203    };
204    let ty = if start == 0 {
205        state.body().local_decls[place.local].ty
206    } else {
207        mir_utils::pointee_ty(state.body().local_decls[place.local].ty)?
208    };
209    if !matches!(ty.kind(), TyKind::Adt(adt, _) if adt.is_enum()) {
210        return None;
211    }
212    let alloc_id = if start == 0 {
213        state.ensure_local_allocation(place.local);
214        state.path_state.current_frame.local_alloc[&place.local]
215    } else {
216        state.local_value(place.local)?.provenance_alloc_id()?
217    };
218    let pending = state.load_value(alloc_id, ty, &[]).and_then(|value| match &value.source {
219        ValueSource::PendingEnumVariant(term) => Some(term.clone()),
220        _ => None,
221    });
222    let target = state.enum_discriminant_term(ty, variant)?;
223    if !pending.as_ref().is_some_and(|term| term._eq(&target).simplify().as_bool() == Some(true)) {
224        let same_active = state
225            .load_value(alloc_id, ty, &[])
226            .and_then(VmValue::discriminant)
227            .is_some_and(|current| current._eq(&target).simplify().as_bool() == Some(true));
228        if pending.is_some() || !same_active {
229            state.invalidate_field_descendants(place.local, &[]);
230            if start == 1 {
231                state.content_mut(alloc_id).values.retain(|(view_ty, path), _| *view_ty != ty || path.is_empty());
232            }
233        }
234        let mut marker = VmValue::new(state.alloc(alloc_id).base.clone(), ty);
235        marker.source = ValueSource::PendingEnumVariant(target);
236        state.store_value(alloc_id, ty, Vec::new(), marker);
237    }
238    let initialized = match rvalue {
239        Rvalue::Use(Operand::Constant(_), ..) => true,
240        Rvalue::Use(Operand::Copy(source) | Operand::Move(source), ..)
241            if source.projection.is_empty() =>
242        {
243            state.local_value(source.local).is_some_and(|value| value.facts.init)
244        }
245        _ => false,
246    };
247    Some(initialized)
248}
249
250pub(crate) fn exec_assign<'z3, 'tcx>(
251    state: &mut VmExecutor<'z3, 'tcx>,
252    place: &Place<'tcx>,
253    rvalue: &Rvalue<'tcx>,
254) {
255    let source_place = match rvalue {
256        Rvalue::Use(Operand::Copy(source) | Operand::Move(source), ..)
257        | Rvalue::WrapUnsafeBinder(Operand::Copy(source) | Operand::Move(source), _)
258        | Rvalue::Cast(
259            rustc_middle::mir::CastKind::Transmute,
260            Operand::Copy(source) | Operand::Move(source),
261            _,
262        )
263        | Rvalue::CopyForDeref(source) => Some(source),
264        Rvalue::Reborrow(_, _, source) => Some(source),
265        _ => None,
266    };
267    let uninit_source = source_place
268        .and_then(|source| state.path_state.current_frame.local_alloc.get(&source.local))
269        .is_some_and(|id| state.content(*id).facts.may_be_uninit);
270    let inner_uninit_source = source_place
271        .and_then(|source| state.path_state.current_frame.local_alloc.get(&source.local))
272        .is_some_and(|id| state.content(*id).facts.inner_uninit);
273    let inner_uninit_aggregate = matches!(rvalue, Rvalue::Aggregate(kind, _)
274        if matches!(kind.as_ref(), AggregateKind::Adt(did, _, _, _, Some(field))
275            if type_ids::is_maybe_uninit_type(*did)
276                && field.as_usize() == 0));
277    let source_fields = source_place
278        .map(|source| {
279            let prefix = source
280                .projection
281                .iter()
282                .filter_map(|projection| match projection.kind() {
283                    ProjectionElem::Field(field, _) => Some(field.as_usize()),
284                    _ => None,
285                })
286                .collect::<Vec<_>>();
287            if !source.projection.iter().all(|projection| {
288                matches!(
289                    projection.kind(),
290                    ProjectionElem::Field(..)
291                        | ProjectionElem::Deref
292                        | ProjectionElem::Downcast(..)
293                        | ProjectionElem::UnwrapUnsafeBinder(..)
294                )
295            }) {
296                return Vec::new();
297            }
298            state
299                .field_paths(source.local)
300                .into_iter()
301                .filter_map(|path| {
302                    let rest = if prefix.is_empty() {
303                        Some(path.clone())
304                    } else if path.len() > prefix.len() && path.starts_with(&prefix) {
305                        Some(path[prefix.len()..].to_vec())
306                    } else {
307                        None
308                    }?;
309                    state
310                        .field_value(source.local, &path)
311                        .cloned()
312                        .map(|value| (rest, value))
313                })
314                .collect::<Vec<_>>()
315        })
316        .unwrap_or_default();
317    if place.projection.is_empty() && source_place.is_none_or(|source| source.local != place.local)
318    {
319        state.invalidate_indexed_array(place.local);
320        state.invalidate_field_descendants(place.local, &[]);
321    }
322    if !place.projection.is_empty()
323        && place.projection.iter().all(|projection| {
324            matches!(
325                projection.kind(),
326                ProjectionElem::Field(..) | ProjectionElem::Downcast(..)
327            )
328        })
329    {
330        let path = place
331            .projection
332            .iter()
333            .filter_map(|projection| match projection.kind() {
334                ProjectionElem::Field(field, _) => Some(field.as_usize()),
335                _ => None,
336            })
337            .collect::<Vec<_>>();
338        if !path.is_empty() {
339            state.invalidate_field_descendants(place.local, &path);
340        }
341    }
342    let mut value = eval_rvalue(state, place, rvalue);
343
344    let has_deref = place
345        .projection
346        .iter()
347        .any(|p| matches!(p.kind(), ProjectionElem::Deref));
348
349    if !place.projection.is_empty() {
350        state.record_projected_store(place, &value);
351        if !matches!(rvalue, Rvalue::Repeat(..))
352            || super::rvalue::symbolic_repeat_target(state, place).is_none()
353        {
354            state.record_indexed_store(place, &value);
355        }
356    }
357    value.facts.init = true;
358
359    if place.projection.is_empty() {
360        state.set_local(place.local, value);
361        if !uninit_source
362            && !inner_uninit_source
363            && !inner_uninit_aggregate
364            && let Some(&id) = state.path_state.current_frame.local_alloc.get(&place.local)
365        {
366            state.content_mut(id).facts.initialized = true;
367        }
368        if uninit_source && let Some(id) = state.path_state.current_frame.local_alloc.get(&place.local) {
369            state.content_mut(*id).facts.may_be_uninit = true;
370        }
371        if (inner_uninit_source || inner_uninit_aggregate)
372            && let Some(&id) = state.path_state.current_frame.local_alloc.get(&place.local)
373        {
374            state.content_mut(id).facts.inner_uninit = true;
375        }
376        // On a whole-place move (`_3 = move _4`), the destination is a fresh
377        // container slot: re-point its whole-value provenance from the source's
378        // stack slot to its own, so `container_data_alloc` later reads the
379        // destination's owning field (copied below) rather than the moved-out
380        // source's (which is invalidated after the propagation).
381        let moved_from = match rvalue {
382            Rvalue::Use(operand, ..) | Rvalue::WrapUnsafeBinder(operand, _) => match operand {
383                Operand::Move(p) if p.projection.is_empty() => Some(p.local),
384                _ => None,
385            },
386            _ => None,
387        };
388        if let Some(src) = moved_from
389            && let Some(&src_alloc) = state.path_state.current_frame.local_alloc.get(&src)
390            && let Some(mut wv) = state.local_value(place.local).cloned()
391            && wv
392                .provenance
393                .as_ref()
394                .is_some_and(|p| p.alloc_id == src_alloc)
395        {
396            let dest_alloc = state.path_state.current_frame.local_alloc[&place.local];
397            wv.provenance = Some(Provenance {
398                alloc_id: dest_alloc,
399                offset: Int::from_u64(state.z3_ctx, 0),
400                offset_kind: None,
401            });
402            state.set_local(place.local, wv);
403        }
404        for (path, mut field) in source_fields {
405            if matches!(rvalue, Rvalue::Reborrow(..))
406                && path.len() == 1
407                && let TyKind::Adt(adt, args) = state.body().local_decls[place.local].ty.kind()
408                && !adt.is_enum()
409                && let Some(field_def) = adt.non_enum_variant().fields.iter().nth(path[0])
410            {
411                field.ty = mir_utils::field_ty(state.tcx, field_def, args);
412            }
413            state.set_field_value(place.local, path, field);
414        }
415        // Invalidate the moved-out source's owner-field provenance *after* the
416        // field propagation, so a later `Owning` check does not treat the source
417        // as a second owner while the destination kept the pointer.
418        if let Some(src) = moved_from {
419            state.invalidate_owner_field(src);
420        }
421    } else if !has_deref {
422        let field_indices: Vec<usize> = place
423            .projection
424            .iter()
425            .filter_map(|p| match p.kind() {
426                ProjectionElem::Field(idx, _) => Some(idx.as_usize()),
427                _ => None,
428            })
429            .collect();
430        if !field_indices.is_empty() {
431            if let Some(initialized) = prepare_enum_field_write(state, place, rvalue) {
432                value.facts.init = initialized;
433            }
434            let track_iter = field_indices == [0];
435            state.set_field_value(place.local, field_indices.clone(), value);
436            for (path, field) in source_fields {
437                let mut full = field_indices.clone();
438                full.extend(path);
439                state.set_field_value(place.local, full, field);
440            }
441            if track_iter {
442                state.track_iter_ptr_update(place.local);
443            }
444        }
445    } else {
446        // Deref projection (`(*ptr).field = val`): resolve the referent local and
447        // write the field there, so `&mut self` setters (`set_len`, `clear`, …)
448        // actually update the referent's materialized fields instead of being
449        // silently dropped.
450        //
451        // A pure `*ptr = val` (no trailing Field) still must NOT overwrite the
452        // pointer local — writing through a pointer should not reassign the
453        // pointer variable.
454        let mut proj = place.projection.iter();
455        if matches!(proj.next().map(|p| p.kind()), Some(ProjectionElem::Deref)) {
456            let field_indices: Vec<usize> = proj
457                .filter_map(|p| match p.kind() {
458                    ProjectionElem::Field(idx, _) => Some(idx.as_usize()),
459                    _ => None,
460                })
461                .collect();
462            if field_indices.is_empty() {
463                let pointed = state.local_value(place.local).cloned();
464                if let Some(pointed) = pointed {
465                    let written_ty = value.ty;
466                    let fully_initialized = value.facts.init;
467                    let byte_buffer = pointed.provenance_alloc_id().filter(|&id| {
468                        (matches!(
469                            state.alloc(id).kind,
470                            AllocKind::Slice { .. } | AllocKind::ExternalSlice { .. }
471                        ) || state.alloc(id).facts.locally_allocated)
472                            && state.alloc(id).element_ty.as_ty() == Some(state.tcx.types.u8)
473                    });
474                    let wrote_object = state.write_through_pointer(&pointed, Vec::new(), value);
475                    for (path, field) in source_fields {
476                        state.write_through_pointer(&pointed, path.clone(), field.clone());
477                        if wrote_object && let Some(id) = byte_buffer {
478                            state.store_value(id, written_ty, path, field);
479                        }
480                    }
481                    // A whole-object write through a reinterpreted byte buffer
482                    // establishes the type at this address, without changing
483                    // the element type of the entire allocation.
484                    if wrote_object
485                        && fully_initialized
486                        && mir_utils::pointee_ty(pointed.ty) == Some(written_ty)
487                        && pointed
488                            .provenance
489                            .as_ref()
490                            .is_some_and(|prov| prov.offset.simplify().as_u64() == Some(0))
491                        && let Some(alloc_id) = pointed.provenance_alloc_id()
492                    {
493                        state.content_mut(alloc_id).facts.written_pointee_ty = Some(written_ty);
494                    }
495                }
496                return;
497            } else {
498                let enum_field = place.projection.len() == 3
499                    && matches!(place.projection[1].kind(), ProjectionElem::Downcast(..))
500                    && matches!(place.projection[2].kind(), ProjectionElem::Field(..));
501                if enum_field {
502                    if let Some(initialized) = prepare_enum_field_write(state, place, rvalue) {
503                        value.facts.init = initialized;
504                    }
505                }
506                let has_local_field = state.field_value(place.local, &field_indices).is_some();
507                let pointed = state.local_value(place.local).cloned();
508                let mut writes = vec![(field_indices.clone(), value)];
509                for (path, field) in source_fields {
510                    let mut full = field_indices.clone();
511                    full.extend(path);
512                    writes.push((full, field));
513                }
514                for (path, field) in writes {
515                    if has_local_field {
516                        state.write_local_path(place.local, path.clone(), field.clone());
517                    }
518                    if let Some(pointed) = &pointed {
519                        if enum_field
520                            && let Some(provenance) = &pointed.provenance
521                            && provenance.offset.simplify().as_u64() == Some(0)
522                            && let Some(ty) = mir_utils::pointee_ty(pointed.ty)
523                            && state.alloc(provenance.alloc_id).element_ty.as_ty() == Some(ty)
524                        {
525                            state.clear_write_evidence(provenance.alloc_id);
526                            state.store_value(provenance.alloc_id, ty, path.clone(), field.clone());
527                            state.set_field_value(place.local, path, field);
528                        } else {
529                            state.write_through_pointer(pointed, path, field);
530                        }
531                    }
532                }
533                if has_local_field && field_indices == [0] {
534                    state.track_iter_ptr_update(place.local);
535                }
536            }
537        }
538    }
539}
540
541pub(crate) fn exec_storage_live<'z3, 'tcx>(state: &mut VmExecutor<'z3, 'tcx>, local: Local) {
542    state.ensure_local_allocation(local);
543    let alloc_id = state.path_state.current_frame.local_alloc[&local];
544    *state.content_mut(alloc_id) = MemoryContent::default();
545    state.alloc_mut(alloc_id).facts.dead = false;
546}
547
548pub(crate) fn exec_storage_dead<'z3, 'tcx>(state: &mut VmExecutor<'z3, 'tcx>, local: Local) {
549    if let Some(alloc_id) = state.path_state.current_frame.local_alloc.get(&local).copied() {
550        state.alloc_mut(alloc_id).facts.dead = true;
551    }
552}
553
554impl<'z3, 'tcx> VmExecutor<'z3, 'tcx> {
555    /// Record byte-level values when assigning to a place with projections.
556    /// This handles patterns like `buf[i] = 0u8` (nul-store) and `arr[i] = val`.
557    fn record_projected_store(&mut self, place: &Place<'tcx>, value: &VmValue<'z3, 'tcx>) {
558        // Prefer the value's provenance (pointee alloc) over slots
559        // (reference alloc) for ref/ptr parameters.
560        let Some(alloc_id) = self
561            .local_value(place.local)
562            .and_then(|v| v.provenance_alloc_id())
563            .or_else(|| self.path_state.current_frame.local_alloc.get(&place.local).copied())
564        else {
565            return;
566        };
567
568        let value_ty = value.ty;
569        let value_size = self.size_of_ty(value_ty) as usize;
570
571        let mut byte_offset: usize = 0;
572        let mut concrete = true;
573
574        let base_ty = self.body().local_decls[place.local].ty;
575        let mut cur_ty = base_ty;
576
577        for proj in place.projection.iter() {
578            match proj.kind() {
579                rustc_middle::mir::ProjectionElem::Field(field_idx, _) => {
580                    let off = self.field_offset_in_bytes(cur_ty, field_idx.as_usize()) as usize;
581                    byte_offset += off;
582                    if let rustc_middle::ty::TyKind::Adt(adt_def, substs) = cur_ty.kind()
583                        && !adt_def.is_enum()
584                    {
585                        let variant = adt_def.non_enum_variant();
586                        if let Some(field_def) = variant.fields.get(field_idx) {
587                            cur_ty = mir_utils::field_ty(self.tcx, field_def, substs);
588                        }
589                    }
590                }
591                rustc_middle::mir::ProjectionElem::Deref => {
592                    if let rustc_middle::ty::TyKind::Ref(_, inner, _) = cur_ty.kind() {
593                        cur_ty = *inner;
594                    }
595                }
596                rustc_middle::mir::ProjectionElem::Index(_local) => {
597                    concrete = false;
598                    break;
599                }
600                rustc_middle::mir::ProjectionElem::Subslice {
601                    from,
602                    to: _,
603                    from_end: _,
604                } => {
605                    byte_offset += from as usize;
606                }
607                _ => {}
608            }
609        }
610
611        if concrete && value_size > 0 {
612            self.content_mut(alloc_id).facts.initialized = true;
613            if byte_offset == 0
614                && self.alloc(alloc_id).element_ty.as_ty().is_some_and(|ty| {
615                    matches!(ty.kind(), rustc_middle::ty::TyKind::Adt(def, args)
616                        if type_ids::is_maybe_uninit_type(def.did())
617                        && args.first().and_then(|arg| arg.as_type()) == Some(value_ty))
618                })
619            {
620                self.content_mut(alloc_id).facts.written_pointee_ty = Some(value_ty);
621            }
622
623            let is_u8_write = matches!(
624                value_ty.kind(),
625                rustc_middle::ty::TyKind::Uint(rustc_middle::ty::UintTy::U8)
626            );
627
628            if is_u8_write {
629                self.record_byte_value(alloc_id, byte_offset, value.z3_term.clone());
630            }
631        }
632    }
633
634    /// Track byte-level values for index-based stores (e.g. `buf[i] = 0u8`)
635    /// that `record_projected_store` skips due to Index projections.
636    fn record_indexed_store(&mut self, place: &Place<'tcx>, value: &VmValue<'z3, 'tcx>) {
637        let index_count = place
638            .projection
639            .iter()
640            .filter(|projection| {
641                matches!(
642                    projection.kind(),
643                    rustc_middle::mir::ProjectionElem::Index(_)
644                        | rustc_middle::mir::ProjectionElem::ConstantIndex { .. }
645                )
646            })
647            .count();
648        if let Some((alloc_id, index)) = self.indexed_element_target(place)
649            && (index_count > 1
650                || matches!(value.ty.kind(), rustc_middle::ty::TyKind::RawPtr(..))
651                || self.content(alloc_id).indexed_elements_modified)
652        {
653            self.store_indexed_element(alloc_id, index, value.clone());
654            if index_count > 1 || matches!(value.ty.kind(), rustc_middle::ty::TyKind::RawPtr(..)) {
655                return;
656            }
657        }
658        let mut element_ty = place.ty(self.body(), self.tcx).ty;
659        let array_ty = element_ty;
660        let mut array_depth = 0;
661        while let rustc_middle::ty::TyKind::Array(inner, _) = element_ty.kind() {
662            element_ty = *inner;
663            array_depth += 1;
664        }
665        if array_depth > 0
666            && matches!(
667                element_ty.kind(),
668                rustc_middle::ty::TyKind::RawPtr(..)
669                    | rustc_middle::ty::TyKind::Int(..)
670                    | rustc_middle::ty::TyKind::Uint(..)
671                    | rustc_middle::ty::TyKind::Bool
672                    | rustc_middle::ty::TyKind::Char
673                    | rustc_middle::ty::TyKind::Float(..)
674            )
675            && let Some(address) = self.address_of_place(place)
676            && let Some(provenance) = address.provenance
677        {
678            let element_size = self.size_of_ty(element_ty);
679            if element_size > 0 {
680                let start = provenance
681                    .offset
682                    .div(&Int::from_u64(self.z3_ctx, element_size));
683                let count = Int::from_u64(self.z3_ctx, self.size_of_ty(array_ty) / element_size);
684                let end = Int::add(self.z3_ctx, &[&start, &count]);
685                let retained = self
686                    .content(provenance.alloc_id)
687                    .indexed_elements
688                    .iter()
689                    .filter(|(index, _)| {
690                        let distinct = Bool::or(self.z3_ctx, &[&index.lt(&start), &index.ge(&end)]);
691                        self.path_implies(&distinct)
692                    })
693                    .cloned()
694                    .collect();
695                let content = self.content_mut(provenance.alloc_id);
696                content.indexed_elements = retained;
697                content.indexed_elements_modified = true;
698                return;
699            }
700        }
701        if place.projection.len() == 1
702            && let rustc_middle::mir::ProjectionElem::Index(index_local) = place.projection[0]
703            && let rustc_middle::ty::TyKind::Array(elem_ty, _) =
704                self.body().local_decls[place.local].ty.kind()
705            && *elem_ty == value.ty
706        {
707            let array_ty = self.body().local_decls[place.local].ty;
708            let index = self
709                .local_value(index_local)
710                .and_then(|v| v.z3_term.simplify().as_u64())
711                .and_then(|v| usize::try_from(v).ok());
712            if let Some(index) = index {
713                if let Some(alloc_id) = self.path_state.current_frame.local_alloc.get(&place.local).copied() {
714                    self.content_mut(alloc_id)
715                        .values
716                        .retain(|(ty, path), _| *ty != array_ty || path.first() != Some(&index));
717                }
718                if matches!(
719                    value.ty.kind(),
720                    rustc_middle::ty::TyKind::Int(_)
721                        | rustc_middle::ty::TyKind::Uint(_)
722                        | rustc_middle::ty::TyKind::Bool
723                        | rustc_middle::ty::TyKind::Char
724                ) {
725                    self.set_field_value(place.local, vec![index], value.clone());
726                }
727            } else {
728                let index_term = self.local_value(index_local).map(|v| v.z3_term.clone());
729                let length = match array_ty.kind() {
730                    rustc_middle::ty::TyKind::Array(_, length) => {
731                        length.try_to_target_usize(self.tcx)
732                    }
733                    _ => None,
734                };
735                let elements = length.and_then(|length| {
736                    (0..length)
737                        .map(|element| self.field_value(place.local, &[element as usize]).cloned())
738                        .collect::<Option<Vec<_>>>()
739                });
740                if let (Some(index_term), Some(elements)) = (index_term, elements)
741                    && matches!(
742                        value.ty.kind(),
743                        rustc_middle::ty::TyKind::Int(_)
744                            | rustc_middle::ty::TyKind::Uint(_)
745                            | rustc_middle::ty::TyKind::Bool
746                            | rustc_middle::ty::TyKind::Char
747                    )
748                {
749                    for (element, old) in elements.into_iter().enumerate() {
750                        let selected = index_term._eq(&Int::from_u64(self.z3_ctx, element as u64));
751                        let updated =
752                            VmValue::new(selected.ite(&value.z3_term, &old.z3_term), value.ty);
753                        self.set_field_value(place.local, vec![element], updated);
754                    }
755                } else {
756                    self.path_state.diagnostics.mark_unsupported();
757                    if let Some(alloc_id) =
758                        self.path_state.current_frame.local_alloc.get(&place.local).copied()
759                    {
760                        self.content_mut(alloc_id)
761                            .values
762                            .retain(|(ty, path), _| *ty != array_ty || path.is_empty());
763                    }
764                }
765            }
766        }
767        let is_u8 = matches!(
768            value.ty.kind(),
769            rustc_middle::ty::TyKind::Uint(rustc_middle::ty::UintTy::U8)
770        );
771        if !is_u8 {
772            return;
773        }
774        let has_index_with_concrete = place.projection.iter().any(|p| {
775            if let rustc_middle::mir::ProjectionElem::Index(local) = p {
776                self.local_value(local)
777                    .and_then(|v| v.z3_term.simplify().as_u64())
778                    .is_some()
779            } else {
780                false
781            }
782        });
783        if !has_index_with_concrete {
784            return;
785        }
786        if let Some(addr) = self.address_of_place(place)
787            && let Some(ref prov) = addr.provenance
788        {
789            let alloc_id = prov.alloc_id;
790            self.content_mut(alloc_id).facts.initialized = true;
791            self.byte_write(alloc_id, &prov.offset, &value.z3_term);
792        }
793    }
794}