1use std::num::NonZero;
2use std::sync::Mutex;
3use std::{assert_matches, 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, TyAndLayout};
14use rustc_middle::ty::{self, FnSigKind, IntTy, Ty, TyCtxt, UintTy};
15use rustc_span::{Span, Symbol};
16use rustc_structures::CrateType;
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 use rustc_middle::ty::layout::MaybeResult;
113
114 let ty = resolve_path(cx.tcx(), path, Namespace::TypeNS).ty(cx.tcx(), cx.typing_env());
115 cx.layout_of(ty).to_result().ok().unwrap()
116}
117
118pub fn iter_exported_symbols<'tcx>(
120 tcx: TyCtxt<'tcx>,
121 mut f: impl FnMut(CrateNum, DefId, bool) -> InterpResult<'tcx>,
122) -> InterpResult<'tcx> {
123 let crate_items = tcx.hir_crate_items(());
127 for def_id in crate_items.definitions() {
128 if !tcx.def_kind(def_id).has_codegen_attrs() || tcx.is_foreign_item(def_id) {
129 continue;
130 }
131 let codegen_attrs = tcx.codegen_fn_attrs(def_id);
132 let used = codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
133 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER);
134 if !(used || codegen_attrs.contains_extern_indicator()) {
135 continue;
136 }
137 f(LOCAL_CRATE, def_id.into(), used)?;
138 }
139
140 let dependency_formats = tcx.dependency_formats(());
144 let dependency_format = dependency_formats
146 .get(&CrateType::Executable)
147 .expect("interpreting a non-executable crate");
148 for cnum in dependency_format
149 .iter_enumerated()
150 .filter_map(|(num, &linkage)| (linkage != Linkage::NotLinked).then_some(num))
151 {
152 if cnum == LOCAL_CRATE {
153 continue; }
155
156 for &(symbol, export_info) in tcx.exported_non_generic_symbols(cnum) {
157 if let ExportedSymbol::NonGeneric(def_id) = symbol
158 && !tcx.is_foreign_item(def_id)
160 {
161 f(cnum, def_id, export_info.used)?;
162 }
163 }
164 }
165 interp_ok(())
166}
167
168impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
169pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
170 fn have_module(&self, path: &[&str]) -> bool {
172 try_resolve_did(*self.eval_context_ref().tcx, path, None).is_some()
173 }
174
175 fn eval_path(&self, path: &[&str]) -> MPlaceTy<'tcx> {
177 let ecx = self.eval_context_ref();
178 let instance = resolve_path(*ecx.tcx, path, Namespace::ValueNS);
179 ecx.eval_global(instance).unwrap_or_else(|err| {
181 panic!("failed to evaluate required Rust item: {path:?}\n{err:?}")
182 })
183 }
184 fn eval_path_scalar(&self, path: &[&str]) -> Scalar {
185 let ecx = self.eval_context_ref();
186 let val = ecx.eval_path(path);
187 ecx.read_scalar(&val)
188 .unwrap_or_else(|err| panic!("failed to read required Rust item: {path:?}\n{err:?}"))
189 }
190
191 fn eval_libc(&self, name: &str) -> Scalar {
193 if self.eval_context_ref().tcx.sess.target.os == Os::Windows {
194 panic!(
195 "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
196 );
197 }
198 self.eval_path_scalar(&["libc", name])
200 }
201
202 fn eval_libc_int<T: TryFrom<i128>>(&self, name: &str) -> T {
205 let ecx = self.eval_context_ref();
206 if ecx.tcx.sess.target.os == Os::Windows {
207 panic!(
208 "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
209 );
210 }
211 let path = &["libc", name];
213 let val = self.eval_path(path);
214 ecx.read_int::<T>(&val)
215 .unwrap_or_else(|err| panic!("failed to read required Rust item: {path:?}\n{err:?}"))
216 }
217
218 fn eval_libc_i16(&self, name: &str) -> i16 {
220 self.eval_libc(name).to_i16().unwrap_or_else(|_err| {
221 panic!("required libc item has unexpected type (not `i16`): {name}")
222 })
223 }
224
225 fn eval_libc_u16(&self, name: &str) -> u16 {
227 self.eval_libc(name).to_u16().unwrap_or_else(|_err| {
228 panic!("required libc item has unexpected type (not `u16`): {name}")
229 })
230 }
231
232 fn eval_libc_i32(&self, name: &str) -> i32 {
234 self.eval_libc(name).to_i32().unwrap_or_else(|_err| {
235 panic!("required libc item has unexpected type (not `i32`): {name}")
236 })
237 }
238
239 fn eval_libc_u32(&self, name: &str) -> u32 {
241 self.eval_libc(name).to_u32().unwrap_or_else(|_err| {
242 panic!("required libc item has unexpected type (not `u32`): {name}")
243 })
244 }
245
246 fn eval_libc_u64(&self, name: &str) -> u64 {
248 self.eval_libc(name).to_u64().unwrap_or_else(|_err| {
250 panic!("required libc item has unexpected type (not `u64`): {name}")
251 })
252 }
253
254 fn eval_windows(&self, module: &str, name: &str) -> Scalar {
256 self.eval_context_ref().eval_path_scalar(&["std", "sys", "pal", "windows", module, name])
257 }
258
259 fn eval_windows_u32(&self, module: &str, name: &str) -> u32 {
261 self.eval_windows(module, name).to_u32().unwrap_or_else(|_err| {
263 panic!("required Windows item has unexpected type (not `u32`): {module}::{name}")
264 })
265 }
266
267 fn eval_windows_u64(&self, module: &str, name: &str) -> u64 {
269 self.eval_windows(module, name).to_u64().unwrap_or_else(|_err| {
271 panic!("required Windows item has unexpected type (not `u64`): {module}::{name}")
272 })
273 }
274
275 fn libc_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
277 let ecx = self.eval_context_ref();
278 if ecx.tcx.sess.target.os == Os::Windows {
279 panic!(
280 "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
281 );
282 }
283 path_ty_layout(ecx, &["libc", name])
284 }
285
286 fn windows_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
288 let ecx = self.eval_context_ref();
289 path_ty_layout(ecx, &["std", "sys", "pal", "windows", "c", name])
290 }
291
292 fn try_project_field_named<P: Projectable<'tcx, Provenance>>(
294 &self,
295 base: &P,
296 name: &str,
297 ) -> InterpResult<'tcx, Option<P>> {
298 let ecx = self.eval_context_ref();
299 let adt = base.layout().ty.ty_adt_def().unwrap();
300 for (idx, field) in adt.non_enum_variant().fields.iter_enumerated() {
301 if field.name.as_str() == name {
302 return interp_ok(Some(ecx.project_field(base, idx)?));
303 }
304 }
305 interp_ok(None)
306 }
307
308 fn project_field_named<P: Projectable<'tcx, Provenance>>(
310 &self,
311 base: &P,
312 name: &str,
313 ) -> InterpResult<'tcx, P> {
314 interp_ok(
315 self.try_project_field_named(base, name)?
316 .unwrap_or_else(|| bug!("no field named {} in type {}", name, base.layout().ty)),
317 )
318 }
319
320 fn project_c_array_field<P: Projectable<'tcx, Provenance>>(
323 &self,
324 base: &P,
325 idx: u64,
326 ) -> InterpResult<'tcx, P> {
327 let ecx = self.eval_context_ref();
328 let offset = base.layout().size * idx; base.offset(offset, base.layout(), ecx)
330 }
331
332 #[track_caller]
336 fn write_int(
337 &mut self,
338 i: impl Into<i128>,
339 dest: &impl Writeable<'tcx, Provenance>,
340 ) -> InterpResult<'tcx> {
341 assert!(
342 dest.layout().backend_repr.is_scalar(),
343 "write_int on non-scalar type {}",
344 dest.layout().ty
345 );
346 let val = if dest.layout().backend_repr.is_signed() {
347 Scalar::from_int(i, dest.layout().size)
348 } else {
349 Scalar::from_uint(
350 u128::try_from(i.into())
351 .expect("should not store a negative value in an unsigned type"),
352 dest.layout().size,
353 )
354 };
355 self.eval_context_mut().write_scalar(val, dest)
356 }
357
358 fn write_int_fields(
360 &mut self,
361 values: &[i128],
362 dest: &impl Writeable<'tcx, Provenance>,
363 ) -> InterpResult<'tcx> {
364 let ecx = self.eval_context_mut();
365 for (idx, &val) in values.iter().enumerate() {
366 let idx = FieldIdx::from_usize(idx);
367 let field = ecx.project_field(dest, idx)?;
368 ecx.write_int(val, &field)?;
369 }
370 interp_ok(())
371 }
372
373 fn write_int_fields_named(
375 &mut self,
376 values: &[(&str, i128)],
377 dest: &impl Writeable<'tcx, Provenance>,
378 ) -> InterpResult<'tcx> {
379 let ecx = self.eval_context_mut();
380 for &(name, val) in values.iter() {
381 let field = ecx.project_field_named(dest, name)?;
382 ecx.write_int(val, &field)?;
383 }
384 interp_ok(())
385 }
386
387 #[track_caller]
389 fn read_int<T: TryFrom<i128>>(
390 &self,
391 val: &impl Projectable<'tcx, Provenance>,
392 ) -> InterpResult<'tcx, T> {
393 let ecx = self.eval_context_ref();
394 let scalar = ecx.read_scalar(val)?;
395
396 let size = val.layout().size;
397 let host_type_signed = T::try_from(-1).is_ok();
401 if size_of::<T>() < size.bytes_usize()
402 || (size_of::<T>() == size.bytes_usize()
403 && host_type_signed != val.layout().backend_repr.is_signed())
404 {
405 panic!(
406 "reading value of machine type {} which does not fit into the chosen host type",
407 val.layout().ty
408 );
409 }
410 let int = if val.layout().backend_repr.is_signed() {
411 scalar.to_int(size)?
412 } else {
413 i128::try_from(scalar.to_uint(size)?).unwrap()
415 };
416 interp_ok(int.try_into().ok().unwrap())
418 }
419
420 fn ptr_is_null(&self, ptr: Pointer) -> InterpResult<'tcx, bool> {
422 interp_ok(ptr.addr().bytes() == 0)
423 }
424
425 fn gen_random(&mut self, ptr: Pointer, len: u64) -> InterpResult<'tcx> {
427 if len == 0 {
433 return interp_ok(());
434 }
435 let ecx = self.eval_context_mut();
436
437 let mut data = vec![0; usize::try_from(len).unwrap()];
438
439 if ecx.machine.communicate() {
440 getrandom::fill(&mut data)
442 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
443 } else {
444 let rng = ecx.machine.rng.get_mut();
445 rng.fill_bytes(&mut data);
446 }
447
448 ecx.write_bytes_ptr(ptr, data.iter().copied())
449 }
450
451 fn call_function(
457 &mut self,
458 f: ty::Instance<'tcx>,
459 caller_abi: ExternAbi,
460 args: &[ImmTy<'tcx>],
461 dest: Option<&MPlaceTy<'tcx>>,
462 cont: ReturnContinuation,
463 ) -> InterpResult<'tcx> {
464 let ecx = self.eval_context_mut();
465
466 let mir = ecx.load_mir(f.def, None)?;
468 let dest = match dest {
469 Some(dest) => dest.clone(),
470 None => MPlaceTy::fake_alloc_zst(ecx.machine.layouts.unit),
471 };
472
473 let with_caller_location = f.def.requires_caller_location(*ecx.tcx);
474
475 let sig = ecx.tcx.mk_fn_sig(
477 args.iter()
478 .map(|a| a.layout.ty)
479 .chain(with_caller_location.then(|| ecx.tcx.caller_location_ty())),
480 dest.layout.ty,
481 FnSigKind::default().set_abi(caller_abi).set_safety(rustc_hir::Safety::Safe),
484 );
485 let caller_fn_abi = ecx.fn_abi_of_fn_ptr(ty::Binder::dummy(sig), ty::List::empty())?;
486
487 ecx.init_stack_frame(
489 f,
490 mir,
491 caller_fn_abi,
492 &args.iter().map(|a| FnArg::Copy(a.clone().into())).collect::<Vec<_>>(),
493 with_caller_location,
494 &dest.into(),
495 cont,
496 )
497 }
498
499 fn call_thread_root_function(
501 &mut self,
502 f: ty::Instance<'tcx>,
503 caller_abi: ExternAbi,
504 args: &[ImmTy<'tcx>],
505 dest: Option<&MPlaceTy<'tcx>>,
506 span: Span,
507 ) -> InterpResult<'tcx> {
508 let ecx = self.eval_context_mut();
509 assert!(ecx.active_thread_stack().is_empty());
510 assert!(ecx.active_thread_ref().origin_span.is_dummy());
511 ecx.active_thread_mut().origin_span = span;
512 ecx.call_function(f, caller_abi, args, dest, ReturnContinuation::Stop { cleanup: true })
513 }
514
515 fn visit_freeze_sensitive(
519 &self,
520 place: &MPlaceTy<'tcx>,
521 size: Size,
522 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
523 ) -> InterpResult<'tcx> {
524 let ecx = self.eval_context_ref();
525 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
526 debug_assert_eq!(
527 size,
528 ecx.size_and_align_of_val(place)?
529 .map(|(size, _)| size)
530 .unwrap_or_else(|| place.layout.size)
531 );
532 let start_addr = place.ptr().addr();
536 let mut cur_addr = start_addr;
537 let mut unsafe_cell_action = |unsafe_cell_ptr: &Pointer, unsafe_cell_size: Size| {
540 let unsafe_cell_addr = unsafe_cell_ptr.addr();
543 assert!(unsafe_cell_addr >= cur_addr);
544 let frozen_size = unsafe_cell_addr - cur_addr;
545 if frozen_size != Size::ZERO {
547 action(alloc_range(cur_addr - start_addr, frozen_size), true)?;
548 }
549 cur_addr += frozen_size;
550 if unsafe_cell_size != Size::ZERO {
552 action(
553 alloc_range(cur_addr - start_addr, unsafe_cell_size),
554 false,
555 )?;
556 }
557 cur_addr += unsafe_cell_size;
558 interp_ok(())
560 };
561 {
563 let mut visitor = UnsafeCellVisitor {
564 ecx,
565 unsafe_cell_action: |place| {
566 trace!("unsafe_cell_action on {:?}", place.ptr());
567 let unsafe_cell_size = ecx
569 .size_and_align_of_val(place)?
570 .map(|(size, _)| size)
571 .unwrap_or_else(|| place.layout.size);
573 if unsafe_cell_size != Size::ZERO {
575 unsafe_cell_action(&place.ptr(), unsafe_cell_size)
576 } else {
577 interp_ok(())
578 }
579 },
580 };
581 visitor.visit_value(place)?;
582 }
583 unsafe_cell_action(&place.ptr().wrapping_offset(size, ecx), Size::ZERO)?;
586 return interp_ok(());
588
589 struct UnsafeCellVisitor<'ecx, 'tcx, F>
592 where
593 F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
594 {
595 ecx: &'ecx MiriInterpCx<'tcx>,
596 unsafe_cell_action: F,
597 }
598
599 impl<'ecx, 'tcx, F> ValueVisitor<'tcx, MiriMachine<'tcx>> for UnsafeCellVisitor<'ecx, 'tcx, F>
600 where
601 F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
602 {
603 type V = MPlaceTy<'tcx>;
604
605 #[inline(always)]
606 fn ecx(&self) -> &MiriInterpCx<'tcx> {
607 self.ecx
608 }
609
610 fn visit_value(&mut self, v: &MPlaceTy<'tcx>) -> InterpResult<'tcx> {
612 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
613 let is_unsafe_cell = match v.layout.ty.kind() {
614 ty::Adt(adt, _) =>
615 Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
616 _ => false,
617 };
618 if is_unsafe_cell {
619 (self.unsafe_cell_action)(v)
621 } else if self.ecx.type_is_freeze(v.layout.ty) {
622 interp_ok(())
624 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
625 (self.unsafe_cell_action)(v)
627 } else {
628 match v.layout.variants {
635 Variants::Multiple { .. } => {
636 (self.unsafe_cell_action)(v)
644 }
645 Variants::Single { .. } | Variants::Empty => {
646 self.walk_value(v)
649 }
650 }
651 }
652 }
653
654 fn visit_union(
655 &mut self,
656 _v: &MPlaceTy<'tcx>,
657 _fields: NonZero<usize>,
658 ) -> InterpResult<'tcx> {
659 bug!("we should have already handled unions in `visit_value`")
660 }
661 }
662 }
663
664 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
668 if !self.eval_context_ref().machine.communicate() {
669 self.reject_in_isolation(name, RejectOpWith::Abort)?;
670 }
671 interp_ok(())
672 }
673
674 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
677 let ecx = self.eval_context_ref();
678 match reject_with {
679 RejectOpWith::Abort => isolation_abort_error(op_name),
680 RejectOpWith::WarningWithoutBacktrace => {
681 static DEDUP: Mutex<FxHashSet<String>> =
683 Mutex::new(FxHashSet::with_hasher(FxBuildHasher));
684 let mut emitted_warnings = DEDUP.lock().unwrap();
685 if !emitted_warnings.contains(op_name) {
686 emitted_warnings.insert(op_name.to_owned());
688 ecx.tcx
689 .dcx()
690 .warn(format!("{op_name} was made to return an error due to isolation"));
691 }
692
693 interp_ok(())
694 }
695 RejectOpWith::Warning => {
696 ecx.emit_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
697 interp_ok(())
698 }
699 RejectOpWith::NoWarning => interp_ok(()), }
701 }
702
703 fn assert_target_os(&self, target_os: Os, name: &str) {
707 assert_eq!(
708 self.eval_context_ref().tcx.sess.target.os,
709 target_os,
710 "`{name}` is only available on the `{target_os}` target OS",
711 )
712 }
713
714 fn assert_target_os_is_linux_like(&self, name: &str) {
715 assert_matches!(
716 self.eval_context_ref().tcx.sess.target.os,
717 Os::Linux | Os::Android,
718 "`{name}` is only available on Linux-like targets",
719 )
720 }
721
722 fn check_target_os(&self, target_oses: &[Os], name: Symbol) -> InterpResult<'tcx> {
726 let target_os = &self.eval_context_ref().tcx.sess.target.os;
727 if !target_oses.contains(target_os) {
728 throw_unsup_format!("`{name}` is not supported on {target_os}");
729 }
730 interp_ok(())
731 }
732
733 fn assert_target_os_is_unix(&self, name: &str) {
737 assert!(self.target_os_is_unix(), "`{name}` is only available for unix targets",);
738 }
739
740 fn target_os_is_unix(&self) -> bool {
741 self.eval_context_ref().tcx.sess.target.families.iter().any(|f| f == "unix")
742 }
743
744 fn read_byte_slice<'a>(&'a self, slice: &ImmTy<'tcx>) -> InterpResult<'tcx, &'a [u8]>
746 where
747 'tcx: 'a,
748 {
749 let ecx = self.eval_context_ref();
750 let (ptr, len) = slice.to_scalar_pair();
751 let ptr = ptr.to_pointer(ecx);
752 let len = len.to_target_usize(ecx)?;
753 let bytes = ecx.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
754 interp_ok(bytes)
755 }
756
757 fn read_c_str<'a>(&'a self, ptr: Pointer) -> InterpResult<'tcx, &'a [u8]>
759 where
760 'tcx: 'a,
761 {
762 let ecx = self.eval_context_ref();
763 let size1 = Size::from_bytes(1);
764
765 let mut len = Size::ZERO;
767 loop {
768 let place = ecx.ptr_to_mplace(ptr.wrapping_offset(len, ecx), ecx.machine.layouts.u8);
771 let byte = ecx.read_scalar(&place)?.to_u8()?;
772 if byte == 0 {
773 break;
774 } else {
775 len += size1;
776 }
777 }
778
779 ecx.read_bytes_ptr_strip_provenance(ptr, len)
781 }
782
783 fn write_c_str(
789 &mut self,
790 c_str: &[u8],
791 ptr: Pointer,
792 size: u64,
793 ) -> InterpResult<'tcx, (bool, u64)> {
794 let string_length = u64::try_from(c_str.len()).unwrap();
797 let string_length = string_length.strict_add(1);
798 if size < string_length {
799 return interp_ok((false, string_length));
800 }
801 self.eval_context_mut()
802 .write_bytes_ptr(ptr, c_str.iter().copied().chain(iter::once(0u8)))?;
803 interp_ok((true, string_length))
804 }
805
806 fn read_c_str_with_char_type<T>(
809 &self,
810 mut ptr: Pointer,
811 char_type: TyAndLayout<'tcx>,
812 ) -> InterpResult<'tcx, Vec<T>>
813 where
814 T: TryFrom<i128> + From<u8> + PartialEq,
815 {
816 let ecx = self.eval_context_ref();
817
818 ecx.check_ptr_align(ptr, char_type.align)?;
819
820 let mut wchars = Vec::new();
821 loop {
822 let place = ecx.ptr_to_mplace(ptr, char_type);
825 let wchar = ecx.read_int::<T>(&place)?;
826 if wchar == 0u8.into() {
827 break;
828 } else {
829 wchars.push(wchar);
830 ptr = ptr.wrapping_offset(char_type.size, ecx);
832 }
833 }
834
835 interp_ok(wchars)
836 }
837
838 fn read_wide_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u16>> {
840 let ecx = self.eval_context_ref();
841 ecx.read_c_str_with_char_type(ptr, ecx.machine.layouts.u16)
842 }
843
844 fn write_wide_str(
851 &mut self,
852 wide_str: &[u16],
853 ptr: Pointer,
854 size: u64,
855 ) -> InterpResult<'tcx, (bool, u64)> {
856 let string_length = u64::try_from(wide_str.len()).unwrap();
859 let string_length = string_length.strict_add(1);
860 if size < string_length {
861 return interp_ok((false, string_length));
862 }
863
864 let size2 = Size::from_bytes(2);
866 let ecx = self.eval_context_mut();
867 ecx.check_ptr_align(ptr, Align::from_bytes(2).unwrap())?;
868 let mut alloc = ecx.get_ptr_alloc_mut(ptr, size2 * string_length)?.unwrap(); for (offset, wchar) in wide_str.iter().copied().chain(iter::once(0x0000)).enumerate() {
870 let offset = u64::try_from(offset).unwrap();
871 alloc.write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar))?;
872 }
873 interp_ok((true, string_length))
874 }
875
876 fn read_wchar_t_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u32>> {
879 let ecx = self.eval_context_ref();
880 let wchar_t = if ecx.tcx.sess.target.os == Os::Windows {
881 ecx.machine.layouts.u16
883 } else {
884 let real_type = ecx.libc_ty_layout("wchar_t");
886 assert_eq!(real_type.size.bytes(), 4);
887 ecx.machine.layouts.u32
888 };
889 self.read_c_str_with_char_type(ptr, wchar_t)
890 }
891
892 fn frame_in_std(&self) -> bool {
893 let ecx = self.eval_context_ref();
894 let frame = ecx.frame();
895 let instance: Option<_> = try {
897 let scope = frame.current_source_info()?.scope;
898 let inlined_parent = frame.body().source_scopes[scope].inlined_parent_scope?;
899 let source = &frame.body().source_scopes[inlined_parent];
900 source.inlined.expect("inlined_parent_scope points to scope without inline info").0
901 };
902 let instance = instance.unwrap_or(frame.instance());
904 let frame_crate = ecx.tcx.def_path(instance.def_id()).krate;
909 let crate_name = ecx.tcx.crate_name(frame_crate);
910 let crate_name = crate_name.as_str();
911 crate_name == "std"
912 }
913
914 fn mark_immutable(&mut self, mplace: &MPlaceTy<'tcx>) {
916 let ecx = self.eval_context_mut();
917 let provenance = mplace.ptr().into_pointer_or_addr().unwrap().provenance;
919 ecx.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
920 }
921
922 fn get_twice_wide_int_ty(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
924 let ecx = self.eval_context_ref();
925 match ty.kind() {
926 ty::Uint(UintTy::U8) => ecx.tcx.types.u16,
928 ty::Uint(UintTy::U16) => ecx.tcx.types.u32,
929 ty::Uint(UintTy::U32) => ecx.tcx.types.u64,
930 ty::Uint(UintTy::U64) => ecx.tcx.types.u128,
931 ty::Int(IntTy::I8) => ecx.tcx.types.i16,
933 ty::Int(IntTy::I16) => ecx.tcx.types.i32,
934 ty::Int(IntTy::I32) => ecx.tcx.types.i64,
935 ty::Int(IntTy::I64) => ecx.tcx.types.i128,
936 _ => span_bug!(ecx.cur_span(), "unexpected type: {ty:?}"),
937 }
938 }
939
940 fn expect_target_feature_for_intrinsic(
945 &self,
946 intrinsic: Symbol,
947 target_feature: &str,
948 ) -> InterpResult<'tcx, ()> {
949 let ecx = self.eval_context_ref();
950 if !ecx.tcx.sess.internal_target_features.contains(&Symbol::intern(target_feature)) {
951 throw_ub_format!(
952 "attempted to call intrinsic `{intrinsic}` that requires missing target feature {target_feature}"
953 );
954 }
955 interp_ok(())
956 }
957
958 fn lookup_link_section(
961 &self,
962 include_name: impl Fn(&str) -> bool,
963 ) -> InterpResult<'tcx, Vec<(ImmTy<'tcx>, Span)>> {
964 let ecx = self.eval_context_ref();
965 let tcx = ecx.tcx.tcx;
966
967 let mut array = vec![];
968
969 iter_exported_symbols(tcx, |_cnum, def_id, used| {
970 let attrs = tcx.codegen_fn_attrs(def_id);
971 if !used {
972 return interp_ok(());
975 }
976 let Some(link_section) = attrs.link_section else {
977 return interp_ok(());
978 };
979 if include_name(link_section.as_str()) {
980 let instance = ty::Instance::mono(tcx, def_id);
981 let span = tcx.def_span(def_id);
982 let const_val = ecx.eval_global(instance).unwrap_or_else(|err| {
983 panic!(
984 "failed to evaluate static in required link_section: {def_id:?}\n{err:?}"
985 )
986 });
987 match const_val.layout.ty.kind() {
988 ty::FnPtr(..) => {
989 array.push((ecx.read_immediate(&const_val)?, span));
990 }
991 ty::Array(elem_ty, _) if matches!(elem_ty.kind(), ty::FnPtr(..)) => {
992 let mut elems = ecx.project_array_fields(&const_val)?;
993 while let Some((_idx, elem)) = elems.next(ecx)? {
994 array.push((ecx.read_immediate(&elem)?, span));
995 }
996 }
997 _ =>
998 throw_unsup_format!(
999 "only function pointers and arrays of function pointers are supported in well-known linker sections"
1000 ),
1001 }
1002 }
1003 interp_ok(())
1004 })?;
1005
1006 interp_ok(array)
1007 }
1008
1009 fn mangle_internal_symbol<'a>(&'a mut self, name: &'static str) -> &'a str
1010 where
1011 'tcx: 'a,
1012 {
1013 let ecx = self.eval_context_mut();
1014 let tcx = *ecx.tcx;
1015 ecx.machine
1016 .mangle_internal_symbol_cache
1017 .entry(name)
1018 .or_insert_with(|| mangle_internal_symbol(tcx, name))
1019 }
1020}
1021
1022impl<'tcx> MiriMachine<'tcx> {
1023 pub fn current_user_relevant_span(&self) -> Span {
1028 self.threads.active_thread_ref().current_user_relevant_span()
1029 }
1030
1031 pub fn caller_span(&self) -> Span {
1037 let frame_idx = self.top_user_relevant_frame().unwrap();
1040 let frame_idx = cmp::min(frame_idx, self.stack().len().saturating_sub(2));
1041 self.stack()[frame_idx].current_span()
1042 }
1043
1044 fn stack(&self) -> &[Frame<'tcx, Provenance, machine::FrameExtra<'tcx>>] {
1045 self.threads.active_thread_stack()
1046 }
1047
1048 fn top_user_relevant_frame(&self) -> Option<usize> {
1049 self.threads.active_thread_ref().top_user_relevant_frame()
1050 }
1051
1052 pub fn user_relevance(&self, frame: &Frame<'tcx, Provenance>) -> u8 {
1054 if frame.instance().def.requires_caller_location(self.tcx) {
1055 return 0;
1056 }
1057 if self.is_local(frame.instance()) {
1058 u8::MAX
1059 } else {
1060 1
1063 }
1064 }
1065}
1066
1067pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
1068 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
1069 "{name} not available when isolation is enabled",
1070 )))
1071}
1072
1073pub(crate) fn bool_to_simd_element(b: bool, size: Size) -> Scalar {
1074 let val = if b { -1 } else { 0 };
1078 Scalar::from_int(val, size)
1079}
1080
1081pub(crate) fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
1085 if success {
1086 u32::try_from(len.strict_sub(1)).unwrap()
1089 } else {
1090 u32::try_from(len).unwrap()
1093 }
1094}
1095
1096pub fn is_no_core(tcx: TyCtxt<'_>) -> bool {
1098 rustc_attr_ir::find_attr!(tcx, crate, NoCore)
1099}
1100
1101pub trait ToUsize {
1103 fn to_usize(self) -> usize;
1104}
1105
1106impl ToUsize for u32 {
1107 fn to_usize(self) -> usize {
1108 self.try_into().unwrap()
1109 }
1110}
1111
1112pub trait ToU64 {
1115 fn to_u64(self) -> u64;
1116}
1117
1118impl ToU64 for usize {
1119 fn to_u64(self) -> u64 {
1120 self.try_into().unwrap()
1121 }
1122}
1123
1124#[macro_export]
1130macro_rules! enter_trace_span {
1131 ($($tt:tt)*) => {
1132 rustc_const_eval::enter_trace_span!($crate::MiriMachine<'static>, $($tt)*)
1133 };
1134}