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) -> InterpResult<'tcx>,
120) -> InterpResult<'tcx> {
121 let crate_items = tcx.hir_crate_items(());
125 for def_id in crate_items.definitions() {
126 let exported = tcx.def_kind(def_id).has_codegen_attrs() && {
127 let codegen_attrs = tcx.codegen_fn_attrs(def_id);
128 codegen_attrs.contains_extern_indicator()
129 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
130 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
131 };
132 if exported {
133 f(LOCAL_CRATE, def_id.into())?;
134 }
135 }
136
137 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) {
157 if let ExportedSymbol::NonGeneric(def_id) = symbol {
158 f(cnum, def_id)?;
159 }
160 }
161 }
162 interp_ok(())
163}
164
165impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
166pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
167 fn have_module(&self, path: &[&str]) -> bool {
169 try_resolve_did(*self.eval_context_ref().tcx, path, None).is_some()
170 }
171
172 fn eval_path(&self, path: &[&str]) -> MPlaceTy<'tcx> {
174 let this = self.eval_context_ref();
175 let instance = resolve_path(*this.tcx, path, Namespace::ValueNS);
176 this.eval_global(instance).unwrap_or_else(|err| {
178 panic!("failed to evaluate required Rust item: {path:?}\n{err:?}")
179 })
180 }
181 fn eval_path_scalar(&self, path: &[&str]) -> Scalar {
182 let this = self.eval_context_ref();
183 let val = this.eval_path(path);
184 this.read_scalar(&val)
185 .unwrap_or_else(|err| panic!("failed to read required Rust item: {path:?}\n{err:?}"))
186 }
187
188 fn eval_libc(&self, name: &str) -> Scalar {
190 if self.eval_context_ref().tcx.sess.target.os == Os::Windows {
191 panic!(
192 "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
193 );
194 }
195 self.eval_path_scalar(&["libc", name])
196 }
197
198 fn eval_libc_i32(&self, name: &str) -> i32 {
200 self.eval_libc(name).to_i32().unwrap_or_else(|_err| {
202 panic!("required libc item has unexpected type (not `i32`): {name}")
203 })
204 }
205
206 fn eval_libc_u32(&self, name: &str) -> u32 {
208 self.eval_libc(name).to_u32().unwrap_or_else(|_err| {
210 panic!("required libc item has unexpected type (not `u32`): {name}")
211 })
212 }
213
214 fn eval_libc_u64(&self, name: &str) -> u64 {
216 self.eval_libc(name).to_u64().unwrap_or_else(|_err| {
218 panic!("required libc item has unexpected type (not `u64`): {name}")
219 })
220 }
221
222 fn eval_windows(&self, module: &str, name: &str) -> Scalar {
224 self.eval_context_ref().eval_path_scalar(&["std", "sys", "pal", "windows", module, name])
225 }
226
227 fn eval_windows_u32(&self, module: &str, name: &str) -> u32 {
229 self.eval_windows(module, name).to_u32().unwrap_or_else(|_err| {
231 panic!("required Windows item has unexpected type (not `u32`): {module}::{name}")
232 })
233 }
234
235 fn eval_windows_u64(&self, module: &str, name: &str) -> u64 {
237 self.eval_windows(module, name).to_u64().unwrap_or_else(|_err| {
239 panic!("required Windows item has unexpected type (not `u64`): {module}::{name}")
240 })
241 }
242
243 fn libc_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
245 let this = self.eval_context_ref();
246 if this.tcx.sess.target.os == Os::Windows {
247 panic!(
248 "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
249 );
250 }
251 path_ty_layout(this, &["libc", name])
252 }
253
254 fn windows_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
256 let this = self.eval_context_ref();
257 path_ty_layout(this, &["std", "sys", "pal", "windows", "c", name])
258 }
259
260 fn libc_array_ty_layout(&self, name: &str, size: u64) -> TyAndLayout<'tcx> {
262 let this = self.eval_context_ref();
263 let elem_ty_layout = this.libc_ty_layout(name);
264 let array_ty = Ty::new_array(*this.tcx, elem_ty_layout.ty, size);
265 this.layout_of(array_ty).unwrap()
266 }
267
268 fn try_project_field_named<P: Projectable<'tcx, Provenance>>(
270 &self,
271 base: &P,
272 name: &str,
273 ) -> InterpResult<'tcx, Option<P>> {
274 let this = self.eval_context_ref();
275 let adt = base.layout().ty.ty_adt_def().unwrap();
276 for (idx, field) in adt.non_enum_variant().fields.iter_enumerated() {
277 if field.name.as_str() == name {
278 return interp_ok(Some(this.project_field(base, idx)?));
279 }
280 }
281 interp_ok(None)
282 }
283
284 fn project_field_named<P: Projectable<'tcx, Provenance>>(
286 &self,
287 base: &P,
288 name: &str,
289 ) -> InterpResult<'tcx, P> {
290 interp_ok(
291 self.try_project_field_named(base, name)?
292 .unwrap_or_else(|| bug!("no field named {} in type {}", name, base.layout().ty)),
293 )
294 }
295
296 fn write_int(
300 &mut self,
301 i: impl Into<i128>,
302 dest: &impl Writeable<'tcx, Provenance>,
303 ) -> InterpResult<'tcx> {
304 assert!(
305 dest.layout().backend_repr.is_scalar(),
306 "write_int on non-scalar type {}",
307 dest.layout().ty
308 );
309 let val = if dest.layout().backend_repr.is_signed() {
310 Scalar::from_int(i, dest.layout().size)
311 } else {
312 Scalar::from_uint(u128::try_from(i.into()).unwrap(), dest.layout().size)
314 };
315 self.eval_context_mut().write_scalar(val, dest)
316 }
317
318 fn write_int_fields(
320 &mut self,
321 values: &[i128],
322 dest: &impl Writeable<'tcx, Provenance>,
323 ) -> InterpResult<'tcx> {
324 let this = self.eval_context_mut();
325 for (idx, &val) in values.iter().enumerate() {
326 let idx = FieldIdx::from_usize(idx);
327 let field = this.project_field(dest, idx)?;
328 this.write_int(val, &field)?;
329 }
330 interp_ok(())
331 }
332
333 fn write_int_fields_named(
335 &mut self,
336 values: &[(&str, i128)],
337 dest: &impl Writeable<'tcx, Provenance>,
338 ) -> InterpResult<'tcx> {
339 let this = self.eval_context_mut();
340 for &(name, val) in values.iter() {
341 let field = this.project_field_named(dest, name)?;
342 this.write_int(val, &field)?;
343 }
344 interp_ok(())
345 }
346
347 fn write_null(&mut self, dest: &impl Writeable<'tcx, Provenance>) -> InterpResult<'tcx> {
349 self.write_int(0, dest)
350 }
351
352 fn ptr_is_null(&self, ptr: Pointer) -> InterpResult<'tcx, bool> {
354 interp_ok(ptr.addr().bytes() == 0)
355 }
356
357 fn gen_random(&mut self, ptr: Pointer, len: u64) -> InterpResult<'tcx> {
359 if len == 0 {
365 return interp_ok(());
366 }
367 let this = self.eval_context_mut();
368
369 let mut data = vec![0; usize::try_from(len).unwrap()];
370
371 if this.machine.communicate() {
372 getrandom::fill(&mut data)
374 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
375 } else {
376 let rng = this.machine.rng.get_mut();
377 rng.fill_bytes(&mut data);
378 }
379
380 this.write_bytes_ptr(ptr, data.iter().copied())
381 }
382
383 fn call_function(
389 &mut self,
390 f: ty::Instance<'tcx>,
391 caller_abi: ExternAbi,
392 args: &[ImmTy<'tcx>],
393 dest: Option<&MPlaceTy<'tcx>>,
394 cont: ReturnContinuation,
395 ) -> InterpResult<'tcx> {
396 let this = self.eval_context_mut();
397
398 let mir = this.load_mir(f.def, None)?;
400 let dest = match dest {
401 Some(dest) => dest.clone(),
402 None => MPlaceTy::fake_alloc_zst(this.machine.layouts.unit),
403 };
404
405 let sig = this.tcx.mk_fn_sig(
407 args.iter().map(|a| a.layout.ty),
408 dest.layout.ty,
409 FnSigKind::default().set_abi(caller_abi).set_safety(rustc_hir::Safety::Safe),
412 );
413 let caller_fn_abi = this.fn_abi_of_fn_ptr(ty::Binder::dummy(sig), ty::List::empty())?;
414
415 this.init_stack_frame(
417 f,
418 mir,
419 caller_fn_abi,
420 &args.iter().map(|a| FnArg::Copy(a.clone().into())).collect::<Vec<_>>(),
421 false,
422 &dest.into(),
423 cont,
424 )
425 }
426
427 fn call_thread_root_function(
429 &mut self,
430 f: ty::Instance<'tcx>,
431 caller_abi: ExternAbi,
432 args: &[ImmTy<'tcx>],
433 dest: Option<&MPlaceTy<'tcx>>,
434 span: Span,
435 ) -> InterpResult<'tcx> {
436 let this = self.eval_context_mut();
437 assert!(this.active_thread_stack().is_empty());
438 assert!(this.active_thread_ref().origin_span.is_dummy());
439 this.active_thread_mut().origin_span = span;
440 this.call_function(f, caller_abi, args, dest, ReturnContinuation::Stop { cleanup: true })
441 }
442
443 fn visit_freeze_sensitive(
447 &self,
448 place: &MPlaceTy<'tcx>,
449 size: Size,
450 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
451 ) -> InterpResult<'tcx> {
452 let this = self.eval_context_ref();
453 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
454 debug_assert_eq!(
455 size,
456 this.size_and_align_of_val(place)?
457 .map(|(size, _)| size)
458 .unwrap_or_else(|| place.layout.size)
459 );
460 let start_addr = place.ptr().addr();
464 let mut cur_addr = start_addr;
465 let mut unsafe_cell_action = |unsafe_cell_ptr: &Pointer, unsafe_cell_size: Size| {
468 let unsafe_cell_addr = unsafe_cell_ptr.addr();
471 assert!(unsafe_cell_addr >= cur_addr);
472 let frozen_size = unsafe_cell_addr - cur_addr;
473 if frozen_size != Size::ZERO {
475 action(alloc_range(cur_addr - start_addr, frozen_size), true)?;
476 }
477 cur_addr += frozen_size;
478 if unsafe_cell_size != Size::ZERO {
480 action(
481 alloc_range(cur_addr - start_addr, unsafe_cell_size),
482 false,
483 )?;
484 }
485 cur_addr += unsafe_cell_size;
486 interp_ok(())
488 };
489 {
491 let mut visitor = UnsafeCellVisitor {
492 ecx: this,
493 unsafe_cell_action: |place| {
494 trace!("unsafe_cell_action on {:?}", place.ptr());
495 let unsafe_cell_size = this
497 .size_and_align_of_val(place)?
498 .map(|(size, _)| size)
499 .unwrap_or_else(|| place.layout.size);
501 if unsafe_cell_size != Size::ZERO {
503 unsafe_cell_action(&place.ptr(), unsafe_cell_size)
504 } else {
505 interp_ok(())
506 }
507 },
508 };
509 visitor.visit_value(place)?;
510 }
511 unsafe_cell_action(&place.ptr().wrapping_offset(size, this), Size::ZERO)?;
514 return interp_ok(());
516
517 struct UnsafeCellVisitor<'ecx, 'tcx, F>
520 where
521 F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
522 {
523 ecx: &'ecx MiriInterpCx<'tcx>,
524 unsafe_cell_action: F,
525 }
526
527 impl<'ecx, 'tcx, F> ValueVisitor<'tcx, MiriMachine<'tcx>> for UnsafeCellVisitor<'ecx, 'tcx, F>
528 where
529 F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
530 {
531 type V = MPlaceTy<'tcx>;
532
533 #[inline(always)]
534 fn ecx(&self) -> &MiriInterpCx<'tcx> {
535 self.ecx
536 }
537
538 fn visit_value(&mut self, v: &MPlaceTy<'tcx>) -> InterpResult<'tcx> {
540 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
541 let is_unsafe_cell = match v.layout.ty.kind() {
542 ty::Adt(adt, _) =>
543 Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
544 _ => false,
545 };
546 if is_unsafe_cell {
547 (self.unsafe_cell_action)(v)
549 } else if self.ecx.type_is_freeze(v.layout.ty) {
550 interp_ok(())
552 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
553 (self.unsafe_cell_action)(v)
555 } else {
556 match v.layout.variants {
563 Variants::Multiple { .. } => {
564 (self.unsafe_cell_action)(v)
572 }
573 Variants::Single { .. } | Variants::Empty => {
574 self.walk_value(v)
577 }
578 }
579 }
580 }
581
582 fn visit_union(
583 &mut self,
584 _v: &MPlaceTy<'tcx>,
585 _fields: NonZero<usize>,
586 ) -> InterpResult<'tcx> {
587 bug!("we should have already handled unions in `visit_value`")
588 }
589 }
590 }
591
592 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
596 if !self.eval_context_ref().machine.communicate() {
597 self.reject_in_isolation(name, RejectOpWith::Abort)?;
598 }
599 interp_ok(())
600 }
601
602 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
605 let this = self.eval_context_ref();
606 match reject_with {
607 RejectOpWith::Abort => isolation_abort_error(op_name),
608 RejectOpWith::WarningWithoutBacktrace => {
609 static DEDUP: Mutex<FxHashSet<String>> =
611 Mutex::new(FxHashSet::with_hasher(FxBuildHasher));
612 let mut emitted_warnings = DEDUP.lock().unwrap();
613 if !emitted_warnings.contains(op_name) {
614 emitted_warnings.insert(op_name.to_owned());
616 this.tcx
617 .dcx()
618 .warn(format!("{op_name} was made to return an error due to isolation"));
619 }
620
621 interp_ok(())
622 }
623 RejectOpWith::Warning => {
624 this.emit_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
625 interp_ok(())
626 }
627 RejectOpWith::NoWarning => interp_ok(()), }
629 }
630
631 fn assert_target_os(&self, target_os: Os, name: &str) {
635 assert_eq!(
636 self.eval_context_ref().tcx.sess.target.os,
637 target_os,
638 "`{name}` is only available on the `{target_os}` target OS",
639 )
640 }
641
642 fn check_target_os(&self, target_oses: &[Os], name: Symbol) -> InterpResult<'tcx> {
646 let target_os = &self.eval_context_ref().tcx.sess.target.os;
647 if !target_oses.contains(target_os) {
648 throw_unsup_format!("`{name}` is not supported on {target_os}");
649 }
650 interp_ok(())
651 }
652
653 fn assert_target_os_is_unix(&self, name: &str) {
657 assert!(self.target_os_is_unix(), "`{name}` is only available for unix targets",);
658 }
659
660 fn target_os_is_unix(&self) -> bool {
661 self.eval_context_ref().tcx.sess.target.families.iter().any(|f| f == "unix")
662 }
663
664 fn deref_pointer_as(
666 &self,
667 op: &impl Projectable<'tcx, Provenance>,
668 layout: TyAndLayout<'tcx>,
669 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
670 let this = self.eval_context_ref();
671 let ptr = this.read_pointer(op)?;
672 interp_ok(this.ptr_to_mplace(ptr, layout))
673 }
674
675 fn deref_pointer_and_offset(
677 &self,
678 op: &impl Projectable<'tcx, Provenance>,
679 offset: u64,
680 base_layout: TyAndLayout<'tcx>,
681 value_layout: TyAndLayout<'tcx>,
682 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
683 let this = self.eval_context_ref();
684 let op_place = this.deref_pointer_as(op, base_layout)?;
685 let offset = Size::from_bytes(offset);
686
687 assert!(base_layout.size >= offset + value_layout.size);
689 let value_place = op_place.offset(offset, value_layout, this)?;
690 interp_ok(value_place)
691 }
692
693 fn deref_pointer_and_read(
694 &self,
695 op: &impl Projectable<'tcx, Provenance>,
696 offset: u64,
697 base_layout: TyAndLayout<'tcx>,
698 value_layout: TyAndLayout<'tcx>,
699 ) -> InterpResult<'tcx, Scalar> {
700 let this = self.eval_context_ref();
701 let value_place = this.deref_pointer_and_offset(op, offset, base_layout, value_layout)?;
702 this.read_scalar(&value_place)
703 }
704
705 fn deref_pointer_and_write(
706 &mut self,
707 op: &impl Projectable<'tcx, Provenance>,
708 offset: u64,
709 value: impl Into<Scalar>,
710 base_layout: TyAndLayout<'tcx>,
711 value_layout: TyAndLayout<'tcx>,
712 ) -> InterpResult<'tcx, ()> {
713 let this = self.eval_context_mut();
714 let value_place = this.deref_pointer_and_offset(op, offset, base_layout, value_layout)?;
715 this.write_scalar(value, &value_place)
716 }
717
718 fn read_byte_slice<'a>(&'a self, slice: &ImmTy<'tcx>) -> InterpResult<'tcx, &'a [u8]>
720 where
721 'tcx: 'a,
722 {
723 let this = self.eval_context_ref();
724 let (ptr, len) = slice.to_scalar_pair();
725 let ptr = ptr.to_pointer(this)?;
726 let len = len.to_target_usize(this)?;
727 let bytes = this.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
728 interp_ok(bytes)
729 }
730
731 fn read_c_str<'a>(&'a self, ptr: Pointer) -> InterpResult<'tcx, &'a [u8]>
733 where
734 'tcx: 'a,
735 {
736 let this = self.eval_context_ref();
737 let size1 = Size::from_bytes(1);
738
739 let mut len = Size::ZERO;
741 loop {
742 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()?;
746 if byte == 0 {
747 break;
748 } else {
749 len += size1;
750 }
751 }
752
753 this.read_bytes_ptr_strip_provenance(ptr, len)
755 }
756
757 fn write_c_str(
763 &mut self,
764 c_str: &[u8],
765 ptr: Pointer,
766 size: u64,
767 ) -> InterpResult<'tcx, (bool, u64)> {
768 let string_length = u64::try_from(c_str.len()).unwrap();
771 let string_length = string_length.strict_add(1);
772 if size < string_length {
773 return interp_ok((false, string_length));
774 }
775 self.eval_context_mut()
776 .write_bytes_ptr(ptr, c_str.iter().copied().chain(iter::once(0u8)))?;
777 interp_ok((true, string_length))
778 }
779
780 fn read_c_str_with_char_size<T>(
783 &self,
784 mut ptr: Pointer,
785 size: Size,
786 align: Align,
787 ) -> InterpResult<'tcx, Vec<T>>
788 where
789 T: TryFrom<u128>,
790 <T as TryFrom<u128>>::Error: std::fmt::Debug,
791 {
792 assert_ne!(size, Size::ZERO);
793
794 let this = self.eval_context_ref();
795
796 this.check_ptr_align(ptr, align)?;
797
798 let mut wchars = Vec::new();
799 loop {
800 let alloc = this.get_ptr_alloc(ptr, size)?.unwrap(); let wchar_int = alloc.read_integer(alloc_range(Size::ZERO, size))?.to_bits(size)?;
804 if wchar_int == 0 {
805 break;
806 } else {
807 wchars.push(wchar_int.try_into().unwrap());
808 ptr = ptr.wrapping_offset(size, this);
809 }
810 }
811
812 interp_ok(wchars)
813 }
814
815 fn read_wide_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u16>> {
817 self.read_c_str_with_char_size(ptr, Size::from_bytes(2), Align::from_bytes(2).unwrap())
818 }
819
820 fn write_wide_str(
827 &mut self,
828 wide_str: &[u16],
829 ptr: Pointer,
830 size: u64,
831 ) -> InterpResult<'tcx, (bool, u64)> {
832 let string_length = u64::try_from(wide_str.len()).unwrap();
835 let string_length = string_length.strict_add(1);
836 if size < string_length {
837 return interp_ok((false, string_length));
838 }
839
840 let size2 = Size::from_bytes(2);
842 let this = self.eval_context_mut();
843 this.check_ptr_align(ptr, Align::from_bytes(2).unwrap())?;
844 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() {
846 let offset = u64::try_from(offset).unwrap();
847 alloc.write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar))?;
848 }
849 interp_ok((true, string_length))
850 }
851
852 fn read_wchar_t_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u32>> {
855 let this = self.eval_context_ref();
856 let wchar_t = if this.tcx.sess.target.os == Os::Windows {
857 this.machine.layouts.u16
859 } else {
860 this.libc_ty_layout("wchar_t")
861 };
862 self.read_c_str_with_char_size(ptr, wchar_t.size, wchar_t.align.abi)
863 }
864
865 fn frame_in_std(&self) -> bool {
866 let this = self.eval_context_ref();
867 let frame = this.frame();
868 let instance: Option<_> = try {
870 let scope = frame.current_source_info()?.scope;
871 let inlined_parent = frame.body().source_scopes[scope].inlined_parent_scope?;
872 let source = &frame.body().source_scopes[inlined_parent];
873 source.inlined.expect("inlined_parent_scope points to scope without inline info").0
874 };
875 let instance = instance.unwrap_or(frame.instance());
877 let frame_crate = this.tcx.def_path(instance.def_id()).krate;
882 let crate_name = this.tcx.crate_name(frame_crate);
883 let crate_name = crate_name.as_str();
884 crate_name == "std"
885 }
886
887 fn mark_immutable(&mut self, mplace: &MPlaceTy<'tcx>) {
889 let this = self.eval_context_mut();
890 let provenance = mplace.ptr().into_pointer_or_addr().unwrap().provenance;
892 this.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
893 }
894
895 fn get_twice_wide_int_ty(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
897 let this = self.eval_context_ref();
898 match ty.kind() {
899 ty::Uint(UintTy::U8) => this.tcx.types.u16,
901 ty::Uint(UintTy::U16) => this.tcx.types.u32,
902 ty::Uint(UintTy::U32) => this.tcx.types.u64,
903 ty::Uint(UintTy::U64) => this.tcx.types.u128,
904 ty::Int(IntTy::I8) => this.tcx.types.i16,
906 ty::Int(IntTy::I16) => this.tcx.types.i32,
907 ty::Int(IntTy::I32) => this.tcx.types.i64,
908 ty::Int(IntTy::I64) => this.tcx.types.i128,
909 _ => span_bug!(this.cur_span(), "unexpected type: {ty:?}"),
910 }
911 }
912
913 fn expect_target_feature_for_intrinsic(
918 &self,
919 intrinsic: Symbol,
920 target_feature: &str,
921 ) -> InterpResult<'tcx, ()> {
922 let this = self.eval_context_ref();
923 if !this.tcx.sess.unstable_target_features.contains(&Symbol::intern(target_feature)) {
924 throw_ub_format!(
925 "attempted to call intrinsic `{intrinsic}` that requires missing target feature {target_feature}"
926 );
927 }
928 interp_ok(())
929 }
930
931 fn lookup_link_section(
934 &mut self,
935 include_name: impl Fn(&str) -> bool,
936 ) -> InterpResult<'tcx, Vec<(ImmTy<'tcx>, Span)>> {
937 let this = self.eval_context_mut();
938 let tcx = this.tcx.tcx;
939
940 let mut array = vec![];
941
942 iter_exported_symbols(tcx, |_cnum, def_id| {
943 let attrs = tcx.codegen_fn_attrs(def_id);
944 let Some(link_section) = attrs.link_section else {
945 return interp_ok(());
946 };
947 if include_name(link_section.as_str()) {
948 let instance = ty::Instance::mono(tcx, def_id);
949 let span = tcx.def_span(def_id);
950 let const_val = this.eval_global(instance).unwrap_or_else(|err| {
951 panic!(
952 "failed to evaluate static in required link_section: {def_id:?}\n{err:?}"
953 )
954 });
955 match const_val.layout.ty.kind() {
956 ty::FnPtr(..) => {
957 array.push((this.read_immediate(&const_val)?, span));
958 }
959 ty::Array(elem_ty, _) if matches!(elem_ty.kind(), ty::FnPtr(..)) => {
960 let mut elems = this.project_array_fields(&const_val)?;
961 while let Some((_idx, elem)) = elems.next(this)? {
962 array.push((this.read_immediate(&elem)?, span));
963 }
964 }
965 _ =>
966 throw_unsup_format!(
967 "only function pointers and arrays of function pointers are supported in well-known linker sections"
968 ),
969 }
970 }
971 interp_ok(())
972 })?;
973
974 interp_ok(array)
975 }
976
977 fn mangle_internal_symbol<'a>(&'a mut self, name: &'static str) -> &'a str
978 where
979 'tcx: 'a,
980 {
981 let this = self.eval_context_mut();
982 let tcx = *this.tcx;
983 this.machine
984 .mangle_internal_symbol_cache
985 .entry(name)
986 .or_insert_with(|| mangle_internal_symbol(tcx, name))
987 }
988}
989
990impl<'tcx> MiriMachine<'tcx> {
991 pub fn current_user_relevant_span(&self) -> Span {
996 self.threads.active_thread_ref().current_user_relevant_span()
997 }
998
999 pub fn caller_span(&self) -> Span {
1005 let frame_idx = self.top_user_relevant_frame().unwrap();
1008 let frame_idx = cmp::min(frame_idx, self.stack().len().saturating_sub(2));
1009 self.stack()[frame_idx].current_span()
1010 }
1011
1012 fn stack(&self) -> &[Frame<'tcx, Provenance, machine::FrameExtra<'tcx>>] {
1013 self.threads.active_thread_stack()
1014 }
1015
1016 fn top_user_relevant_frame(&self) -> Option<usize> {
1017 self.threads.active_thread_ref().top_user_relevant_frame()
1018 }
1019
1020 pub fn user_relevance(&self, frame: &Frame<'tcx, Provenance>) -> u8 {
1022 if frame.instance().def.requires_caller_location(self.tcx) {
1023 return 0;
1024 }
1025 if self.is_local(frame.instance()) {
1026 u8::MAX
1027 } else {
1028 1
1031 }
1032 }
1033}
1034
1035pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
1036 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
1037 "{name} not available when isolation is enabled",
1038 )))
1039}
1040
1041pub(crate) fn bool_to_simd_element(b: bool, size: Size) -> Scalar {
1042 let val = if b { -1 } else { 0 };
1046 Scalar::from_int(val, size)
1047}
1048
1049pub(crate) fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
1053 if success {
1054 u32::try_from(len.strict_sub(1)).unwrap()
1057 } else {
1058 u32::try_from(len).unwrap()
1061 }
1062}
1063
1064pub fn is_no_core(tcx: TyCtxt<'_>) -> bool {
1066 rustc_hir::find_attr!(tcx, crate, NoCore)
1067}
1068
1069pub trait ToUsize {
1071 fn to_usize(self) -> usize;
1072}
1073
1074impl ToUsize for u32 {
1075 fn to_usize(self) -> usize {
1076 self.try_into().unwrap()
1077 }
1078}
1079
1080pub trait ToU64 {
1083 fn to_u64(self) -> u64;
1084}
1085
1086impl ToU64 for usize {
1087 fn to_u64(self) -> u64 {
1088 self.try_into().unwrap()
1089 }
1090}
1091
1092#[macro_export]
1098macro_rules! enter_trace_span {
1099 ($($tt:tt)*) => {
1100 rustc_const_eval::enter_trace_span!($crate::MiriMachine<'static>, $($tt)*)
1101 };
1102}