1use std::num::NonZero;
2use std::sync::Mutex;
3use std::{cmp, iter};
4
5use rand::Rng;
6use rustc_abi::{Align, ExternAbi, FieldIdx, FieldsShape, Size, Variants};
7use rustc_data_structures::fx::{FxBuildHasher, FxHashSet};
8use rustc_hir::def::{DefKind, Namespace};
9use rustc_hir::def_id::{CRATE_DEF_INDEX, CrateNum, DefId, LOCAL_CRATE};
10use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
11use rustc_middle::middle::dependency_format::Linkage;
12use rustc_middle::middle::exported_symbols::ExportedSymbol;
13use rustc_middle::ty::layout::{LayoutOf, MaybeResult, TyAndLayout};
14use rustc_middle::ty::{self, FnSigKind, IntTy, Ty, TyCtxt, UintTy};
15use rustc_session::config::CrateType;
16use rustc_span::{Span, Symbol};
17use rustc_symbol_mangling::mangle_internal_symbol;
18use rustc_target::spec::Os;
19
20use crate::*;
21
22fn try_resolve_did(tcx: TyCtxt<'_>, path: &[&str], namespace: Option<Namespace>) -> Option<DefId> {
26 let _trace = enter_trace_span!("try_resolve_did", ?path);
27
28 fn find_children<'tcx: 'a, 'a>(
30 tcx: TyCtxt<'tcx>,
31 item: DefId,
32 name: &'a str,
33 ) -> impl Iterator<Item = DefId> + 'a {
34 let name = Symbol::intern(name);
35 tcx.module_children(item)
36 .iter()
37 .filter(move |item| item.ident.name == name)
38 .map(move |item| item.res.def_id())
39 }
40
41 let (&crate_name, path) = path.split_first().expect("paths must have at least one segment");
43 let (modules, item) = if let Some(namespace) = namespace {
44 let (&item_name, modules) =
45 path.split_last().expect("non-module paths must have at least 2 segments");
46 (modules, Some((item_name, namespace)))
47 } else {
48 (path, None)
49 };
50
51 'crates: for krate in
56 tcx.crates(()).iter().filter(|&&krate| tcx.crate_name(krate).as_str() == crate_name)
57 {
58 let mut cur_item = DefId { krate: *krate, index: CRATE_DEF_INDEX };
59 for &segment in modules {
61 let Some(next_item) = find_children(tcx, cur_item, segment)
62 .find(|&item| tcx.def_kind(item) == DefKind::Mod)
63 else {
64 continue 'crates;
65 };
66 cur_item = next_item;
67 }
68 match item {
70 Some((item_name, namespace)) => {
71 let Some(item) = find_children(tcx, cur_item, item_name)
72 .find(|&item| tcx.def_kind(item).ns() == Some(namespace))
73 else {
74 continue 'crates;
75 };
76 return Some(item);
77 }
78 None => {
79 return Some(cur_item);
81 }
82 }
83 }
84 None
86}
87
88pub fn try_resolve_path<'tcx>(
90 tcx: TyCtxt<'tcx>,
91 path: &[&str],
92 namespace: Namespace,
93) -> Option<ty::Instance<'tcx>> {
94 let did = try_resolve_did(tcx, path, Some(namespace))?;
95 Some(ty::Instance::mono(tcx, did))
96}
97
98#[track_caller]
100pub fn resolve_path<'tcx>(
101 tcx: TyCtxt<'tcx>,
102 path: &[&str],
103 namespace: Namespace,
104) -> ty::Instance<'tcx> {
105 try_resolve_path(tcx, path, namespace)
106 .unwrap_or_else(|| panic!("failed to find required Rust item: {path:?}"))
107}
108
109#[track_caller]
111pub fn path_ty_layout<'tcx>(cx: &impl LayoutOf<'tcx>, path: &[&str]) -> TyAndLayout<'tcx> {
112 let ty = resolve_path(cx.tcx(), path, Namespace::TypeNS).ty(cx.tcx(), cx.typing_env());
113 cx.layout_of(ty).to_result().ok().unwrap()
114}
115
116pub fn iter_exported_symbols<'tcx>(
118 tcx: TyCtxt<'tcx>,
119 mut f: impl FnMut(CrateNum, DefId, bool) -> InterpResult<'tcx>,
120) -> InterpResult<'tcx> {
121 let crate_items = tcx.hir_crate_items(());
125 for def_id in crate_items.definitions() {
126 if !tcx.def_kind(def_id).has_codegen_attrs() || tcx.is_foreign_item(def_id) {
127 continue;
128 }
129 let codegen_attrs = tcx.codegen_fn_attrs(def_id);
130 let used = codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
131 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER);
132 if !(used || codegen_attrs.contains_extern_indicator()) {
133 continue;
134 }
135 f(LOCAL_CRATE, def_id.into(), used)?;
136 }
137
138 let dependency_formats = tcx.dependency_formats(());
142 let dependency_format = dependency_formats
144 .get(&CrateType::Executable)
145 .expect("interpreting a non-executable crate");
146 for cnum in dependency_format
147 .iter_enumerated()
148 .filter_map(|(num, &linkage)| (linkage != Linkage::NotLinked).then_some(num))
149 {
150 if cnum == LOCAL_CRATE {
151 continue; }
153
154 for &(symbol, export_info) in tcx.exported_non_generic_symbols(cnum) {
155 if let ExportedSymbol::NonGeneric(def_id) = symbol
156 && !tcx.is_foreign_item(def_id)
158 {
159 f(cnum, def_id, export_info.used)?;
160 }
161 }
162 }
163 interp_ok(())
164}
165
166impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
167pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
168 fn have_module(&self, path: &[&str]) -> bool {
170 try_resolve_did(*self.eval_context_ref().tcx, path, None).is_some()
171 }
172
173 fn eval_path(&self, path: &[&str]) -> MPlaceTy<'tcx> {
175 let this = self.eval_context_ref();
176 let instance = resolve_path(*this.tcx, path, Namespace::ValueNS);
177 this.eval_global(instance).unwrap_or_else(|err| {
179 panic!("failed to evaluate required Rust item: {path:?}\n{err:?}")
180 })
181 }
182 fn eval_path_scalar(&self, path: &[&str]) -> Scalar {
183 let this = self.eval_context_ref();
184 let val = this.eval_path(path);
185 this.read_scalar(&val)
186 .unwrap_or_else(|err| panic!("failed to read required Rust item: {path:?}\n{err:?}"))
187 }
188
189 fn eval_libc(&self, name: &str) -> Scalar {
191 if self.eval_context_ref().tcx.sess.target.os == Os::Windows {
192 panic!(
193 "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
194 );
195 }
196 self.eval_path_scalar(&["libc", name])
197 }
198
199 fn eval_libc_i16(&self, name: &str) -> i16 {
201 self.eval_libc(name).to_i16().unwrap_or_else(|_err| {
203 panic!("required libc item has unexpected type (not `i16`): {name}")
204 })
205 }
206
207 fn eval_libc_u16(&self, name: &str) -> u16 {
209 self.eval_libc(name).to_u16().unwrap_or_else(|_err| {
211 panic!("required libc item has unexpected type (not `u16`): {name}")
212 })
213 }
214
215 fn eval_libc_i32(&self, name: &str) -> i32 {
217 self.eval_libc(name).to_i32().unwrap_or_else(|_err| {
219 panic!("required libc item has unexpected type (not `i32`): {name}")
220 })
221 }
222
223 fn eval_libc_u32(&self, name: &str) -> u32 {
225 self.eval_libc(name).to_u32().unwrap_or_else(|_err| {
227 panic!("required libc item has unexpected type (not `u32`): {name}")
228 })
229 }
230
231 fn eval_libc_u64(&self, name: &str) -> u64 {
233 self.eval_libc(name).to_u64().unwrap_or_else(|_err| {
235 panic!("required libc item has unexpected type (not `u64`): {name}")
236 })
237 }
238
239 fn eval_windows(&self, module: &str, name: &str) -> Scalar {
241 self.eval_context_ref().eval_path_scalar(&["std", "sys", "pal", "windows", module, name])
242 }
243
244 fn eval_windows_u32(&self, module: &str, name: &str) -> u32 {
246 self.eval_windows(module, name).to_u32().unwrap_or_else(|_err| {
248 panic!("required Windows item has unexpected type (not `u32`): {module}::{name}")
249 })
250 }
251
252 fn eval_windows_u64(&self, module: &str, name: &str) -> u64 {
254 self.eval_windows(module, name).to_u64().unwrap_or_else(|_err| {
256 panic!("required Windows item has unexpected type (not `u64`): {module}::{name}")
257 })
258 }
259
260 fn libc_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
262 let this = self.eval_context_ref();
263 if this.tcx.sess.target.os == Os::Windows {
264 panic!(
265 "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
266 );
267 }
268 path_ty_layout(this, &["libc", name])
269 }
270
271 fn windows_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
273 let this = self.eval_context_ref();
274 path_ty_layout(this, &["std", "sys", "pal", "windows", "c", name])
275 }
276
277 fn libc_array_ty_layout(&self, name: &str, size: u64) -> TyAndLayout<'tcx> {
279 let this = self.eval_context_ref();
280 let elem_ty_layout = this.libc_ty_layout(name);
281 let array_ty = Ty::new_array(*this.tcx, elem_ty_layout.ty, size);
282 this.layout_of(array_ty).unwrap()
283 }
284
285 fn try_project_field_named<P: Projectable<'tcx, Provenance>>(
287 &self,
288 base: &P,
289 name: &str,
290 ) -> InterpResult<'tcx, Option<P>> {
291 let this = self.eval_context_ref();
292 let adt = base.layout().ty.ty_adt_def().unwrap();
293 for (idx, field) in adt.non_enum_variant().fields.iter_enumerated() {
294 if field.name.as_str() == name {
295 return interp_ok(Some(this.project_field(base, idx)?));
296 }
297 }
298 interp_ok(None)
299 }
300
301 fn project_field_named<P: Projectable<'tcx, Provenance>>(
303 &self,
304 base: &P,
305 name: &str,
306 ) -> InterpResult<'tcx, P> {
307 interp_ok(
308 self.try_project_field_named(base, name)?
309 .unwrap_or_else(|| bug!("no field named {} in type {}", name, base.layout().ty)),
310 )
311 }
312
313 fn write_int(
317 &mut self,
318 i: impl Into<i128>,
319 dest: &impl Writeable<'tcx, Provenance>,
320 ) -> InterpResult<'tcx> {
321 assert!(
322 dest.layout().backend_repr.is_scalar(),
323 "write_int on non-scalar type {}",
324 dest.layout().ty
325 );
326 let val = if dest.layout().backend_repr.is_signed() {
327 Scalar::from_int(i, dest.layout().size)
328 } else {
329 Scalar::from_uint(u128::try_from(i.into()).unwrap(), dest.layout().size)
331 };
332 self.eval_context_mut().write_scalar(val, dest)
333 }
334
335 fn write_int_fields(
337 &mut self,
338 values: &[i128],
339 dest: &impl Writeable<'tcx, Provenance>,
340 ) -> InterpResult<'tcx> {
341 let this = self.eval_context_mut();
342 for (idx, &val) in values.iter().enumerate() {
343 let idx = FieldIdx::from_usize(idx);
344 let field = this.project_field(dest, idx)?;
345 this.write_int(val, &field)?;
346 }
347 interp_ok(())
348 }
349
350 fn write_int_fields_named(
352 &mut self,
353 values: &[(&str, i128)],
354 dest: &impl Writeable<'tcx, Provenance>,
355 ) -> InterpResult<'tcx> {
356 let this = self.eval_context_mut();
357 for &(name, val) in values.iter() {
358 let field = this.project_field_named(dest, name)?;
359 this.write_int(val, &field)?;
360 }
361 interp_ok(())
362 }
363
364 fn write_null(&mut self, dest: &impl Writeable<'tcx, Provenance>) -> InterpResult<'tcx> {
366 self.write_int(0, dest)
367 }
368
369 fn ptr_is_null(&self, ptr: Pointer) -> InterpResult<'tcx, bool> {
371 interp_ok(ptr.addr().bytes() == 0)
372 }
373
374 fn gen_random(&mut self, ptr: Pointer, len: u64) -> InterpResult<'tcx> {
376 if len == 0 {
382 return interp_ok(());
383 }
384 let this = self.eval_context_mut();
385
386 let mut data = vec![0; usize::try_from(len).unwrap()];
387
388 if this.machine.communicate() {
389 getrandom::fill(&mut data)
391 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
392 } else {
393 let rng = this.machine.rng.get_mut();
394 rng.fill_bytes(&mut data);
395 }
396
397 this.write_bytes_ptr(ptr, data.iter().copied())
398 }
399
400 fn call_function(
406 &mut self,
407 f: ty::Instance<'tcx>,
408 caller_abi: ExternAbi,
409 args: &[ImmTy<'tcx>],
410 dest: Option<&MPlaceTy<'tcx>>,
411 cont: ReturnContinuation,
412 ) -> InterpResult<'tcx> {
413 let this = self.eval_context_mut();
414
415 let mir = this.load_mir(f.def, None)?;
417 let dest = match dest {
418 Some(dest) => dest.clone(),
419 None => MPlaceTy::fake_alloc_zst(this.machine.layouts.unit),
420 };
421
422 let sig = this.tcx.mk_fn_sig(
424 args.iter().map(|a| a.layout.ty),
425 dest.layout.ty,
426 FnSigKind::default().set_abi(caller_abi).set_safety(rustc_hir::Safety::Safe),
429 );
430 let caller_fn_abi = this.fn_abi_of_fn_ptr(ty::Binder::dummy(sig), ty::List::empty())?;
431
432 this.init_stack_frame(
434 f,
435 mir,
436 caller_fn_abi,
437 &args.iter().map(|a| FnArg::Copy(a.clone().into())).collect::<Vec<_>>(),
438 false,
439 &dest.into(),
440 cont,
441 )
442 }
443
444 fn call_thread_root_function(
446 &mut self,
447 f: ty::Instance<'tcx>,
448 caller_abi: ExternAbi,
449 args: &[ImmTy<'tcx>],
450 dest: Option<&MPlaceTy<'tcx>>,
451 span: Span,
452 ) -> InterpResult<'tcx> {
453 let this = self.eval_context_mut();
454 assert!(this.active_thread_stack().is_empty());
455 assert!(this.active_thread_ref().origin_span.is_dummy());
456 this.active_thread_mut().origin_span = span;
457 this.call_function(f, caller_abi, args, dest, ReturnContinuation::Stop { cleanup: true })
458 }
459
460 fn visit_freeze_sensitive(
464 &self,
465 place: &MPlaceTy<'tcx>,
466 size: Size,
467 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
468 ) -> InterpResult<'tcx> {
469 let this = self.eval_context_ref();
470 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
471 debug_assert_eq!(
472 size,
473 this.size_and_align_of_val(place)?
474 .map(|(size, _)| size)
475 .unwrap_or_else(|| place.layout.size)
476 );
477 let start_addr = place.ptr().addr();
481 let mut cur_addr = start_addr;
482 let mut unsafe_cell_action = |unsafe_cell_ptr: &Pointer, unsafe_cell_size: Size| {
485 let unsafe_cell_addr = unsafe_cell_ptr.addr();
488 assert!(unsafe_cell_addr >= cur_addr);
489 let frozen_size = unsafe_cell_addr - cur_addr;
490 if frozen_size != Size::ZERO {
492 action(alloc_range(cur_addr - start_addr, frozen_size), true)?;
493 }
494 cur_addr += frozen_size;
495 if unsafe_cell_size != Size::ZERO {
497 action(
498 alloc_range(cur_addr - start_addr, unsafe_cell_size),
499 false,
500 )?;
501 }
502 cur_addr += unsafe_cell_size;
503 interp_ok(())
505 };
506 {
508 let mut visitor = UnsafeCellVisitor {
509 ecx: this,
510 unsafe_cell_action: |place| {
511 trace!("unsafe_cell_action on {:?}", place.ptr());
512 let unsafe_cell_size = this
514 .size_and_align_of_val(place)?
515 .map(|(size, _)| size)
516 .unwrap_or_else(|| place.layout.size);
518 if unsafe_cell_size != Size::ZERO {
520 unsafe_cell_action(&place.ptr(), unsafe_cell_size)
521 } else {
522 interp_ok(())
523 }
524 },
525 };
526 visitor.visit_value(place)?;
527 }
528 unsafe_cell_action(&place.ptr().wrapping_offset(size, this), Size::ZERO)?;
531 return interp_ok(());
533
534 struct UnsafeCellVisitor<'ecx, 'tcx, F>
537 where
538 F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
539 {
540 ecx: &'ecx MiriInterpCx<'tcx>,
541 unsafe_cell_action: F,
542 }
543
544 impl<'ecx, 'tcx, F> ValueVisitor<'tcx, MiriMachine<'tcx>> for UnsafeCellVisitor<'ecx, 'tcx, F>
545 where
546 F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
547 {
548 type V = MPlaceTy<'tcx>;
549
550 #[inline(always)]
551 fn ecx(&self) -> &MiriInterpCx<'tcx> {
552 self.ecx
553 }
554
555 fn visit_value(&mut self, v: &MPlaceTy<'tcx>) -> InterpResult<'tcx> {
557 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
558 let is_unsafe_cell = match v.layout.ty.kind() {
559 ty::Adt(adt, _) =>
560 Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
561 _ => false,
562 };
563 if is_unsafe_cell {
564 (self.unsafe_cell_action)(v)
566 } else if self.ecx.type_is_freeze(v.layout.ty) {
567 interp_ok(())
569 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
570 (self.unsafe_cell_action)(v)
572 } else {
573 match v.layout.variants {
580 Variants::Multiple { .. } => {
581 (self.unsafe_cell_action)(v)
589 }
590 Variants::Single { .. } | Variants::Empty => {
591 self.walk_value(v)
594 }
595 }
596 }
597 }
598
599 fn visit_union(
600 &mut self,
601 _v: &MPlaceTy<'tcx>,
602 _fields: NonZero<usize>,
603 ) -> InterpResult<'tcx> {
604 bug!("we should have already handled unions in `visit_value`")
605 }
606 }
607 }
608
609 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
613 if !self.eval_context_ref().machine.communicate() {
614 self.reject_in_isolation(name, RejectOpWith::Abort)?;
615 }
616 interp_ok(())
617 }
618
619 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
622 let this = self.eval_context_ref();
623 match reject_with {
624 RejectOpWith::Abort => isolation_abort_error(op_name),
625 RejectOpWith::WarningWithoutBacktrace => {
626 static DEDUP: Mutex<FxHashSet<String>> =
628 Mutex::new(FxHashSet::with_hasher(FxBuildHasher));
629 let mut emitted_warnings = DEDUP.lock().unwrap();
630 if !emitted_warnings.contains(op_name) {
631 emitted_warnings.insert(op_name.to_owned());
633 this.tcx
634 .dcx()
635 .warn(format!("{op_name} was made to return an error due to isolation"));
636 }
637
638 interp_ok(())
639 }
640 RejectOpWith::Warning => {
641 this.emit_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
642 interp_ok(())
643 }
644 RejectOpWith::NoWarning => interp_ok(()), }
646 }
647
648 fn assert_target_os(&self, target_os: Os, name: &str) {
652 assert_eq!(
653 self.eval_context_ref().tcx.sess.target.os,
654 target_os,
655 "`{name}` is only available on the `{target_os}` target OS",
656 )
657 }
658
659 fn check_target_os(&self, target_oses: &[Os], name: Symbol) -> InterpResult<'tcx> {
663 let target_os = &self.eval_context_ref().tcx.sess.target.os;
664 if !target_oses.contains(target_os) {
665 throw_unsup_format!("`{name}` is not supported on {target_os}");
666 }
667 interp_ok(())
668 }
669
670 fn assert_target_os_is_unix(&self, name: &str) {
674 assert!(self.target_os_is_unix(), "`{name}` is only available for unix targets",);
675 }
676
677 fn target_os_is_unix(&self) -> bool {
678 self.eval_context_ref().tcx.sess.target.families.iter().any(|f| f == "unix")
679 }
680
681 fn deref_pointer_as(
683 &self,
684 op: &impl Projectable<'tcx, Provenance>,
685 layout: TyAndLayout<'tcx>,
686 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
687 let this = self.eval_context_ref();
688 let ptr = this.read_pointer(op)?;
689 interp_ok(this.ptr_to_mplace(ptr, layout))
690 }
691
692 fn deref_pointer_and_offset(
694 &self,
695 op: &impl Projectable<'tcx, Provenance>,
696 offset: u64,
697 base_layout: TyAndLayout<'tcx>,
698 value_layout: TyAndLayout<'tcx>,
699 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
700 let this = self.eval_context_ref();
701 let op_place = this.deref_pointer_as(op, base_layout)?;
702 let offset = Size::from_bytes(offset);
703
704 assert!(base_layout.size >= offset + value_layout.size);
706 let value_place = op_place.offset(offset, value_layout, this)?;
707 interp_ok(value_place)
708 }
709
710 fn deref_pointer_and_read(
711 &self,
712 op: &impl Projectable<'tcx, Provenance>,
713 offset: u64,
714 base_layout: TyAndLayout<'tcx>,
715 value_layout: TyAndLayout<'tcx>,
716 ) -> InterpResult<'tcx, Scalar> {
717 let this = self.eval_context_ref();
718 let value_place = this.deref_pointer_and_offset(op, offset, base_layout, value_layout)?;
719 this.read_scalar(&value_place)
720 }
721
722 fn deref_pointer_and_write(
723 &mut self,
724 op: &impl Projectable<'tcx, Provenance>,
725 offset: u64,
726 value: impl Into<Scalar>,
727 base_layout: TyAndLayout<'tcx>,
728 value_layout: TyAndLayout<'tcx>,
729 ) -> InterpResult<'tcx, ()> {
730 let this = self.eval_context_mut();
731 let value_place = this.deref_pointer_and_offset(op, offset, base_layout, value_layout)?;
732 this.write_scalar(value, &value_place)
733 }
734
735 fn read_byte_slice<'a>(&'a self, slice: &ImmTy<'tcx>) -> InterpResult<'tcx, &'a [u8]>
737 where
738 'tcx: 'a,
739 {
740 let this = self.eval_context_ref();
741 let (ptr, len) = slice.to_scalar_pair();
742 let ptr = ptr.to_pointer(this)?;
743 let len = len.to_target_usize(this)?;
744 let bytes = this.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
745 interp_ok(bytes)
746 }
747
748 fn read_c_str<'a>(&'a self, ptr: Pointer) -> InterpResult<'tcx, &'a [u8]>
750 where
751 'tcx: 'a,
752 {
753 let this = self.eval_context_ref();
754 let size1 = Size::from_bytes(1);
755
756 let mut len = Size::ZERO;
758 loop {
759 let alloc = this.get_ptr_alloc(ptr.wrapping_offset(len, this), size1)?.unwrap(); let byte = alloc.read_integer(alloc_range(Size::ZERO, size1))?.to_u8()?;
763 if byte == 0 {
764 break;
765 } else {
766 len += size1;
767 }
768 }
769
770 this.read_bytes_ptr_strip_provenance(ptr, len)
772 }
773
774 fn write_c_str(
780 &mut self,
781 c_str: &[u8],
782 ptr: Pointer,
783 size: u64,
784 ) -> InterpResult<'tcx, (bool, u64)> {
785 let string_length = u64::try_from(c_str.len()).unwrap();
788 let string_length = string_length.strict_add(1);
789 if size < string_length {
790 return interp_ok((false, string_length));
791 }
792 self.eval_context_mut()
793 .write_bytes_ptr(ptr, c_str.iter().copied().chain(iter::once(0u8)))?;
794 interp_ok((true, string_length))
795 }
796
797 fn read_c_str_with_char_size<T>(
800 &self,
801 mut ptr: Pointer,
802 size: Size,
803 align: Align,
804 ) -> InterpResult<'tcx, Vec<T>>
805 where
806 T: TryFrom<u128>,
807 <T as TryFrom<u128>>::Error: std::fmt::Debug,
808 {
809 assert_ne!(size, Size::ZERO);
810
811 let this = self.eval_context_ref();
812
813 this.check_ptr_align(ptr, align)?;
814
815 let mut wchars = Vec::new();
816 loop {
817 let alloc = this.get_ptr_alloc(ptr, size)?.unwrap(); let wchar_int = alloc.read_integer(alloc_range(Size::ZERO, size))?.to_bits(size)?;
821 if wchar_int == 0 {
822 break;
823 } else {
824 wchars.push(wchar_int.try_into().unwrap());
825 ptr = ptr.wrapping_offset(size, this);
826 }
827 }
828
829 interp_ok(wchars)
830 }
831
832 fn read_wide_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u16>> {
834 self.read_c_str_with_char_size(ptr, Size::from_bytes(2), Align::from_bytes(2).unwrap())
835 }
836
837 fn write_wide_str(
844 &mut self,
845 wide_str: &[u16],
846 ptr: Pointer,
847 size: u64,
848 ) -> InterpResult<'tcx, (bool, u64)> {
849 let string_length = u64::try_from(wide_str.len()).unwrap();
852 let string_length = string_length.strict_add(1);
853 if size < string_length {
854 return interp_ok((false, string_length));
855 }
856
857 let size2 = Size::from_bytes(2);
859 let this = self.eval_context_mut();
860 this.check_ptr_align(ptr, Align::from_bytes(2).unwrap())?;
861 let mut alloc = this.get_ptr_alloc_mut(ptr, size2 * string_length)?.unwrap(); for (offset, wchar) in wide_str.iter().copied().chain(iter::once(0x0000)).enumerate() {
863 let offset = u64::try_from(offset).unwrap();
864 alloc.write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar))?;
865 }
866 interp_ok((true, string_length))
867 }
868
869 fn read_wchar_t_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u32>> {
872 let this = self.eval_context_ref();
873 let wchar_t = if this.tcx.sess.target.os == Os::Windows {
874 this.machine.layouts.u16
876 } else {
877 this.libc_ty_layout("wchar_t")
878 };
879 self.read_c_str_with_char_size(ptr, wchar_t.size, wchar_t.align.abi)
880 }
881
882 fn frame_in_std(&self) -> bool {
883 let this = self.eval_context_ref();
884 let frame = this.frame();
885 let instance: Option<_> = try {
887 let scope = frame.current_source_info()?.scope;
888 let inlined_parent = frame.body().source_scopes[scope].inlined_parent_scope?;
889 let source = &frame.body().source_scopes[inlined_parent];
890 source.inlined.expect("inlined_parent_scope points to scope without inline info").0
891 };
892 let instance = instance.unwrap_or(frame.instance());
894 let frame_crate = this.tcx.def_path(instance.def_id()).krate;
899 let crate_name = this.tcx.crate_name(frame_crate);
900 let crate_name = crate_name.as_str();
901 crate_name == "std"
902 }
903
904 fn mark_immutable(&mut self, mplace: &MPlaceTy<'tcx>) {
906 let this = self.eval_context_mut();
907 let provenance = mplace.ptr().into_pointer_or_addr().unwrap().provenance;
909 this.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
910 }
911
912 fn get_twice_wide_int_ty(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
914 let this = self.eval_context_ref();
915 match ty.kind() {
916 ty::Uint(UintTy::U8) => this.tcx.types.u16,
918 ty::Uint(UintTy::U16) => this.tcx.types.u32,
919 ty::Uint(UintTy::U32) => this.tcx.types.u64,
920 ty::Uint(UintTy::U64) => this.tcx.types.u128,
921 ty::Int(IntTy::I8) => this.tcx.types.i16,
923 ty::Int(IntTy::I16) => this.tcx.types.i32,
924 ty::Int(IntTy::I32) => this.tcx.types.i64,
925 ty::Int(IntTy::I64) => this.tcx.types.i128,
926 _ => span_bug!(this.cur_span(), "unexpected type: {ty:?}"),
927 }
928 }
929
930 fn expect_target_feature_for_intrinsic(
935 &self,
936 intrinsic: Symbol,
937 target_feature: &str,
938 ) -> InterpResult<'tcx, ()> {
939 let this = self.eval_context_ref();
940 if !this.tcx.sess.internal_target_features.contains(&Symbol::intern(target_feature)) {
941 throw_ub_format!(
942 "attempted to call intrinsic `{intrinsic}` that requires missing target feature {target_feature}"
943 );
944 }
945 interp_ok(())
946 }
947
948 fn lookup_link_section(
951 &mut self,
952 include_name: impl Fn(&str) -> bool,
953 ) -> InterpResult<'tcx, Vec<(ImmTy<'tcx>, Span)>> {
954 let this = self.eval_context_mut();
955 let tcx = this.tcx.tcx;
956
957 let mut array = vec![];
958
959 iter_exported_symbols(tcx, |_cnum, def_id, used| {
960 let attrs = tcx.codegen_fn_attrs(def_id);
961 if !used {
962 return interp_ok(());
965 }
966 let Some(link_section) = attrs.link_section else {
967 return interp_ok(());
968 };
969 if include_name(link_section.as_str()) {
970 let instance = ty::Instance::mono(tcx, def_id);
971 let span = tcx.def_span(def_id);
972 let const_val = this.eval_global(instance).unwrap_or_else(|err| {
973 panic!(
974 "failed to evaluate static in required link_section: {def_id:?}\n{err:?}"
975 )
976 });
977 match const_val.layout.ty.kind() {
978 ty::FnPtr(..) => {
979 array.push((this.read_immediate(&const_val)?, span));
980 }
981 ty::Array(elem_ty, _) if matches!(elem_ty.kind(), ty::FnPtr(..)) => {
982 let mut elems = this.project_array_fields(&const_val)?;
983 while let Some((_idx, elem)) = elems.next(this)? {
984 array.push((this.read_immediate(&elem)?, span));
985 }
986 }
987 _ =>
988 throw_unsup_format!(
989 "only function pointers and arrays of function pointers are supported in well-known linker sections"
990 ),
991 }
992 }
993 interp_ok(())
994 })?;
995
996 interp_ok(array)
997 }
998
999 fn mangle_internal_symbol<'a>(&'a mut self, name: &'static str) -> &'a str
1000 where
1001 'tcx: 'a,
1002 {
1003 let this = self.eval_context_mut();
1004 let tcx = *this.tcx;
1005 this.machine
1006 .mangle_internal_symbol_cache
1007 .entry(name)
1008 .or_insert_with(|| mangle_internal_symbol(tcx, name))
1009 }
1010}
1011
1012impl<'tcx> MiriMachine<'tcx> {
1013 pub fn current_user_relevant_span(&self) -> Span {
1018 self.threads.active_thread_ref().current_user_relevant_span()
1019 }
1020
1021 pub fn caller_span(&self) -> Span {
1027 let frame_idx = self.top_user_relevant_frame().unwrap();
1030 let frame_idx = cmp::min(frame_idx, self.stack().len().saturating_sub(2));
1031 self.stack()[frame_idx].current_span()
1032 }
1033
1034 fn stack(&self) -> &[Frame<'tcx, Provenance, machine::FrameExtra<'tcx>>] {
1035 self.threads.active_thread_stack()
1036 }
1037
1038 fn top_user_relevant_frame(&self) -> Option<usize> {
1039 self.threads.active_thread_ref().top_user_relevant_frame()
1040 }
1041
1042 pub fn user_relevance(&self, frame: &Frame<'tcx, Provenance>) -> u8 {
1044 if frame.instance().def.requires_caller_location(self.tcx) {
1045 return 0;
1046 }
1047 if self.is_local(frame.instance()) {
1048 u8::MAX
1049 } else {
1050 1
1053 }
1054 }
1055}
1056
1057pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
1058 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
1059 "{name} not available when isolation is enabled",
1060 )))
1061}
1062
1063pub(crate) fn bool_to_simd_element(b: bool, size: Size) -> Scalar {
1064 let val = if b { -1 } else { 0 };
1068 Scalar::from_int(val, size)
1069}
1070
1071pub(crate) fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
1075 if success {
1076 u32::try_from(len.strict_sub(1)).unwrap()
1079 } else {
1080 u32::try_from(len).unwrap()
1083 }
1084}
1085
1086pub fn is_no_core(tcx: TyCtxt<'_>) -> bool {
1088 rustc_hir::find_attr!(tcx, crate, NoCore)
1089}
1090
1091pub trait ToUsize {
1093 fn to_usize(self) -> usize;
1094}
1095
1096impl ToUsize for u32 {
1097 fn to_usize(self) -> usize {
1098 self.try_into().unwrap()
1099 }
1100}
1101
1102pub trait ToU64 {
1105 fn to_u64(self) -> u64;
1106}
1107
1108impl ToU64 for usize {
1109 fn to_u64(self) -> u64 {
1110 self.try_into().unwrap()
1111 }
1112}
1113
1114#[macro_export]
1120macro_rules! enter_trace_span {
1121 ($($tt:tt)*) => {
1122 rustc_const_eval::enter_trace_span!($crate::MiriMachine<'static>, $($tt)*)
1123 };
1124}