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, 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 this = self.eval_context_ref();
178 let instance = resolve_path(*this.tcx, path, Namespace::ValueNS);
179 this.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 this = self.eval_context_ref();
186 let val = this.eval_path(path);
187 this.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])
199 }
200
201 fn eval_libc_i16(&self, name: &str) -> i16 {
203 self.eval_libc(name).to_i16().unwrap_or_else(|_err| {
205 panic!("required libc item has unexpected type (not `i16`): {name}")
206 })
207 }
208
209 fn eval_libc_u16(&self, name: &str) -> u16 {
211 self.eval_libc(name).to_u16().unwrap_or_else(|_err| {
213 panic!("required libc item has unexpected type (not `u16`): {name}")
214 })
215 }
216
217 fn eval_libc_i32(&self, name: &str) -> i32 {
219 self.eval_libc(name).to_i32().unwrap_or_else(|_err| {
221 panic!("required libc item has unexpected type (not `i32`): {name}")
222 })
223 }
224
225 fn eval_libc_u32(&self, name: &str) -> u32 {
227 self.eval_libc(name).to_u32().unwrap_or_else(|_err| {
229 panic!("required libc item has unexpected type (not `u32`): {name}")
230 })
231 }
232
233 fn eval_libc_u64(&self, name: &str) -> u64 {
235 self.eval_libc(name).to_u64().unwrap_or_else(|_err| {
237 panic!("required libc item has unexpected type (not `u64`): {name}")
238 })
239 }
240
241 fn eval_windows(&self, module: &str, name: &str) -> Scalar {
243 self.eval_context_ref().eval_path_scalar(&["std", "sys", "pal", "windows", module, name])
244 }
245
246 fn eval_windows_u32(&self, module: &str, name: &str) -> u32 {
248 self.eval_windows(module, name).to_u32().unwrap_or_else(|_err| {
250 panic!("required Windows item has unexpected type (not `u32`): {module}::{name}")
251 })
252 }
253
254 fn eval_windows_u64(&self, module: &str, name: &str) -> u64 {
256 self.eval_windows(module, name).to_u64().unwrap_or_else(|_err| {
258 panic!("required Windows item has unexpected type (not `u64`): {module}::{name}")
259 })
260 }
261
262 fn libc_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
264 let this = self.eval_context_ref();
265 if this.tcx.sess.target.os == Os::Windows {
266 panic!(
267 "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
268 );
269 }
270 path_ty_layout(this, &["libc", name])
271 }
272
273 fn windows_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
275 let this = self.eval_context_ref();
276 path_ty_layout(this, &["std", "sys", "pal", "windows", "c", name])
277 }
278
279 fn libc_array_ty_layout(&self, name: &str, size: u64) -> TyAndLayout<'tcx> {
281 let this = self.eval_context_ref();
282 let elem_ty_layout = this.libc_ty_layout(name);
283 let array_ty = Ty::new_array(*this.tcx, elem_ty_layout.ty, size);
284 this.layout_of(array_ty).unwrap()
285 }
286
287 fn try_project_field_named<P: Projectable<'tcx, Provenance>>(
289 &self,
290 base: &P,
291 name: &str,
292 ) -> InterpResult<'tcx, Option<P>> {
293 let this = self.eval_context_ref();
294 let adt = base.layout().ty.ty_adt_def().unwrap();
295 for (idx, field) in adt.non_enum_variant().fields.iter_enumerated() {
296 if field.name.as_str() == name {
297 return interp_ok(Some(this.project_field(base, idx)?));
298 }
299 }
300 interp_ok(None)
301 }
302
303 fn project_field_named<P: Projectable<'tcx, Provenance>>(
305 &self,
306 base: &P,
307 name: &str,
308 ) -> InterpResult<'tcx, P> {
309 interp_ok(
310 self.try_project_field_named(base, name)?
311 .unwrap_or_else(|| bug!("no field named {} in type {}", name, base.layout().ty)),
312 )
313 }
314
315 fn write_int(
319 &mut self,
320 i: impl Into<i128>,
321 dest: &impl Writeable<'tcx, Provenance>,
322 ) -> InterpResult<'tcx> {
323 assert!(
324 dest.layout().backend_repr.is_scalar(),
325 "write_int on non-scalar type {}",
326 dest.layout().ty
327 );
328 let val = if dest.layout().backend_repr.is_signed() {
329 Scalar::from_int(i, dest.layout().size)
330 } else {
331 Scalar::from_uint(u128::try_from(i.into()).unwrap(), dest.layout().size)
333 };
334 self.eval_context_mut().write_scalar(val, dest)
335 }
336
337 fn write_int_fields(
339 &mut self,
340 values: &[i128],
341 dest: &impl Writeable<'tcx, Provenance>,
342 ) -> InterpResult<'tcx> {
343 let this = self.eval_context_mut();
344 for (idx, &val) in values.iter().enumerate() {
345 let idx = FieldIdx::from_usize(idx);
346 let field = this.project_field(dest, idx)?;
347 this.write_int(val, &field)?;
348 }
349 interp_ok(())
350 }
351
352 fn write_int_fields_named(
354 &mut self,
355 values: &[(&str, i128)],
356 dest: &impl Writeable<'tcx, Provenance>,
357 ) -> InterpResult<'tcx> {
358 let this = self.eval_context_mut();
359 for &(name, val) in values.iter() {
360 let field = this.project_field_named(dest, name)?;
361 this.write_int(val, &field)?;
362 }
363 interp_ok(())
364 }
365
366 fn write_null(&mut self, dest: &impl Writeable<'tcx, Provenance>) -> InterpResult<'tcx> {
368 self.write_int(0, dest)
369 }
370
371 fn ptr_is_null(&self, ptr: Pointer) -> InterpResult<'tcx, bool> {
373 interp_ok(ptr.addr().bytes() == 0)
374 }
375
376 fn gen_random(&mut self, ptr: Pointer, len: u64) -> InterpResult<'tcx> {
378 if len == 0 {
384 return interp_ok(());
385 }
386 let this = self.eval_context_mut();
387
388 let mut data = vec![0; usize::try_from(len).unwrap()];
389
390 if this.machine.communicate() {
391 getrandom::fill(&mut data)
393 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
394 } else {
395 let rng = this.machine.rng.get_mut();
396 rng.fill_bytes(&mut data);
397 }
398
399 this.write_bytes_ptr(ptr, data.iter().copied())
400 }
401
402 fn call_function(
408 &mut self,
409 f: ty::Instance<'tcx>,
410 caller_abi: ExternAbi,
411 args: &[ImmTy<'tcx>],
412 dest: Option<&MPlaceTy<'tcx>>,
413 cont: ReturnContinuation,
414 ) -> InterpResult<'tcx> {
415 let this = self.eval_context_mut();
416
417 let mir = this.load_mir(f.def, None)?;
419 let dest = match dest {
420 Some(dest) => dest.clone(),
421 None => MPlaceTy::fake_alloc_zst(this.machine.layouts.unit),
422 };
423
424 let with_caller_location = f.def.requires_caller_location(*this.tcx);
425
426 let sig = this.tcx.mk_fn_sig(
428 args.iter()
429 .map(|a| a.layout.ty)
430 .chain(with_caller_location.then(|| this.tcx.caller_location_ty())),
431 dest.layout.ty,
432 FnSigKind::default().set_abi(caller_abi).set_safety(rustc_hir::Safety::Safe),
435 );
436 let caller_fn_abi = this.fn_abi_of_fn_ptr(ty::Binder::dummy(sig), ty::List::empty())?;
437
438 this.init_stack_frame(
440 f,
441 mir,
442 caller_fn_abi,
443 &args.iter().map(|a| FnArg::Copy(a.clone().into())).collect::<Vec<_>>(),
444 with_caller_location,
445 &dest.into(),
446 cont,
447 )
448 }
449
450 fn call_thread_root_function(
452 &mut self,
453 f: ty::Instance<'tcx>,
454 caller_abi: ExternAbi,
455 args: &[ImmTy<'tcx>],
456 dest: Option<&MPlaceTy<'tcx>>,
457 span: Span,
458 ) -> InterpResult<'tcx> {
459 let this = self.eval_context_mut();
460 assert!(this.active_thread_stack().is_empty());
461 assert!(this.active_thread_ref().origin_span.is_dummy());
462 this.active_thread_mut().origin_span = span;
463 this.call_function(f, caller_abi, args, dest, ReturnContinuation::Stop { cleanup: true })
464 }
465
466 fn visit_freeze_sensitive(
470 &self,
471 place: &MPlaceTy<'tcx>,
472 size: Size,
473 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
474 ) -> InterpResult<'tcx> {
475 let this = self.eval_context_ref();
476 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
477 debug_assert_eq!(
478 size,
479 this.size_and_align_of_val(place)?
480 .map(|(size, _)| size)
481 .unwrap_or_else(|| place.layout.size)
482 );
483 let start_addr = place.ptr().addr();
487 let mut cur_addr = start_addr;
488 let mut unsafe_cell_action = |unsafe_cell_ptr: &Pointer, unsafe_cell_size: Size| {
491 let unsafe_cell_addr = unsafe_cell_ptr.addr();
494 assert!(unsafe_cell_addr >= cur_addr);
495 let frozen_size = unsafe_cell_addr - cur_addr;
496 if frozen_size != Size::ZERO {
498 action(alloc_range(cur_addr - start_addr, frozen_size), true)?;
499 }
500 cur_addr += frozen_size;
501 if unsafe_cell_size != Size::ZERO {
503 action(
504 alloc_range(cur_addr - start_addr, unsafe_cell_size),
505 false,
506 )?;
507 }
508 cur_addr += unsafe_cell_size;
509 interp_ok(())
511 };
512 {
514 let mut visitor = UnsafeCellVisitor {
515 ecx: this,
516 unsafe_cell_action: |place| {
517 trace!("unsafe_cell_action on {:?}", place.ptr());
518 let unsafe_cell_size = this
520 .size_and_align_of_val(place)?
521 .map(|(size, _)| size)
522 .unwrap_or_else(|| place.layout.size);
524 if unsafe_cell_size != Size::ZERO {
526 unsafe_cell_action(&place.ptr(), unsafe_cell_size)
527 } else {
528 interp_ok(())
529 }
530 },
531 };
532 visitor.visit_value(place)?;
533 }
534 unsafe_cell_action(&place.ptr().wrapping_offset(size, this), Size::ZERO)?;
537 return interp_ok(());
539
540 struct UnsafeCellVisitor<'ecx, 'tcx, F>
543 where
544 F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
545 {
546 ecx: &'ecx MiriInterpCx<'tcx>,
547 unsafe_cell_action: F,
548 }
549
550 impl<'ecx, 'tcx, F> ValueVisitor<'tcx, MiriMachine<'tcx>> for UnsafeCellVisitor<'ecx, 'tcx, F>
551 where
552 F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
553 {
554 type V = MPlaceTy<'tcx>;
555
556 #[inline(always)]
557 fn ecx(&self) -> &MiriInterpCx<'tcx> {
558 self.ecx
559 }
560
561 fn visit_value(&mut self, v: &MPlaceTy<'tcx>) -> InterpResult<'tcx> {
563 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
564 let is_unsafe_cell = match v.layout.ty.kind() {
565 ty::Adt(adt, _) =>
566 Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
567 _ => false,
568 };
569 if is_unsafe_cell {
570 (self.unsafe_cell_action)(v)
572 } else if self.ecx.type_is_freeze(v.layout.ty) {
573 interp_ok(())
575 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
576 (self.unsafe_cell_action)(v)
578 } else {
579 match v.layout.variants {
586 Variants::Multiple { .. } => {
587 (self.unsafe_cell_action)(v)
595 }
596 Variants::Single { .. } | Variants::Empty => {
597 self.walk_value(v)
600 }
601 }
602 }
603 }
604
605 fn visit_union(
606 &mut self,
607 _v: &MPlaceTy<'tcx>,
608 _fields: NonZero<usize>,
609 ) -> InterpResult<'tcx> {
610 bug!("we should have already handled unions in `visit_value`")
611 }
612 }
613 }
614
615 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
619 if !self.eval_context_ref().machine.communicate() {
620 self.reject_in_isolation(name, RejectOpWith::Abort)?;
621 }
622 interp_ok(())
623 }
624
625 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
628 let this = self.eval_context_ref();
629 match reject_with {
630 RejectOpWith::Abort => isolation_abort_error(op_name),
631 RejectOpWith::WarningWithoutBacktrace => {
632 static DEDUP: Mutex<FxHashSet<String>> =
634 Mutex::new(FxHashSet::with_hasher(FxBuildHasher));
635 let mut emitted_warnings = DEDUP.lock().unwrap();
636 if !emitted_warnings.contains(op_name) {
637 emitted_warnings.insert(op_name.to_owned());
639 this.tcx
640 .dcx()
641 .warn(format!("{op_name} was made to return an error due to isolation"));
642 }
643
644 interp_ok(())
645 }
646 RejectOpWith::Warning => {
647 this.emit_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
648 interp_ok(())
649 }
650 RejectOpWith::NoWarning => interp_ok(()), }
652 }
653
654 fn assert_target_os(&self, target_os: Os, name: &str) {
658 assert_eq!(
659 self.eval_context_ref().tcx.sess.target.os,
660 target_os,
661 "`{name}` is only available on the `{target_os}` target OS",
662 )
663 }
664
665 fn check_target_os(&self, target_oses: &[Os], name: Symbol) -> InterpResult<'tcx> {
669 let target_os = &self.eval_context_ref().tcx.sess.target.os;
670 if !target_oses.contains(target_os) {
671 throw_unsup_format!("`{name}` is not supported on {target_os}");
672 }
673 interp_ok(())
674 }
675
676 fn assert_target_os_is_unix(&self, name: &str) {
680 assert!(self.target_os_is_unix(), "`{name}` is only available for unix targets",);
681 }
682
683 fn target_os_is_unix(&self) -> bool {
684 self.eval_context_ref().tcx.sess.target.families.iter().any(|f| f == "unix")
685 }
686
687 fn deref_pointer_as(
689 &self,
690 op: &impl Projectable<'tcx, Provenance>,
691 layout: TyAndLayout<'tcx>,
692 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
693 let this = self.eval_context_ref();
694 let ptr = this.read_pointer(op)?;
695 interp_ok(this.ptr_to_mplace(ptr, layout))
696 }
697
698 fn deref_pointer_and_offset(
700 &self,
701 op: &impl Projectable<'tcx, Provenance>,
702 offset: u64,
703 base_layout: TyAndLayout<'tcx>,
704 value_layout: TyAndLayout<'tcx>,
705 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
706 let this = self.eval_context_ref();
707 let op_place = this.deref_pointer_as(op, base_layout)?;
708 let offset = Size::from_bytes(offset);
709
710 assert!(base_layout.size >= offset + value_layout.size);
712 let value_place = op_place.offset(offset, value_layout, this)?;
713 interp_ok(value_place)
714 }
715
716 fn deref_pointer_and_read(
717 &self,
718 op: &impl Projectable<'tcx, Provenance>,
719 offset: u64,
720 base_layout: TyAndLayout<'tcx>,
721 value_layout: TyAndLayout<'tcx>,
722 ) -> InterpResult<'tcx, Scalar> {
723 let this = self.eval_context_ref();
724 let value_place = this.deref_pointer_and_offset(op, offset, base_layout, value_layout)?;
725 this.read_scalar(&value_place)
726 }
727
728 fn deref_pointer_and_write(
729 &mut self,
730 op: &impl Projectable<'tcx, Provenance>,
731 offset: u64,
732 value: impl Into<Scalar>,
733 base_layout: TyAndLayout<'tcx>,
734 value_layout: TyAndLayout<'tcx>,
735 ) -> InterpResult<'tcx, ()> {
736 let this = self.eval_context_mut();
737 let value_place = this.deref_pointer_and_offset(op, offset, base_layout, value_layout)?;
738 this.write_scalar(value, &value_place)
739 }
740
741 fn read_byte_slice<'a>(&'a self, slice: &ImmTy<'tcx>) -> InterpResult<'tcx, &'a [u8]>
743 where
744 'tcx: 'a,
745 {
746 let this = self.eval_context_ref();
747 let (ptr, len) = slice.to_scalar_pair();
748 let ptr = ptr.to_pointer(this);
749 let len = len.to_target_usize(this)?;
750 let bytes = this.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
751 interp_ok(bytes)
752 }
753
754 fn read_c_str<'a>(&'a self, ptr: Pointer) -> InterpResult<'tcx, &'a [u8]>
756 where
757 'tcx: 'a,
758 {
759 let this = self.eval_context_ref();
760 let size1 = Size::from_bytes(1);
761
762 let mut len = Size::ZERO;
764 loop {
765 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()?;
769 if byte == 0 {
770 break;
771 } else {
772 len += size1;
773 }
774 }
775
776 this.read_bytes_ptr_strip_provenance(ptr, len)
778 }
779
780 fn write_c_str(
786 &mut self,
787 c_str: &[u8],
788 ptr: Pointer,
789 size: u64,
790 ) -> InterpResult<'tcx, (bool, u64)> {
791 let string_length = u64::try_from(c_str.len()).unwrap();
794 let string_length = string_length.strict_add(1);
795 if size < string_length {
796 return interp_ok((false, string_length));
797 }
798 self.eval_context_mut()
799 .write_bytes_ptr(ptr, c_str.iter().copied().chain(iter::once(0u8)))?;
800 interp_ok((true, string_length))
801 }
802
803 fn read_c_str_with_char_size<T>(
806 &self,
807 mut ptr: Pointer,
808 size: Size,
809 align: Align,
810 ) -> InterpResult<'tcx, Vec<T>>
811 where
812 T: TryFrom<u128>,
813 <T as TryFrom<u128>>::Error: std::fmt::Debug,
814 {
815 assert_ne!(size, Size::ZERO);
816
817 let this = self.eval_context_ref();
818
819 this.check_ptr_align(ptr, align)?;
820
821 let mut wchars = Vec::new();
822 loop {
823 let alloc = this.get_ptr_alloc(ptr, size)?.unwrap(); let wchar_int = alloc.read_integer(alloc_range(Size::ZERO, size))?.to_bits(size)?;
827 if wchar_int == 0 {
828 break;
829 } else {
830 wchars.push(wchar_int.try_into().unwrap());
831 ptr = ptr.wrapping_offset(size, this);
832 }
833 }
834
835 interp_ok(wchars)
836 }
837
838 fn read_wide_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u16>> {
840 self.read_c_str_with_char_size(ptr, Size::from_bytes(2), Align::from_bytes(2).unwrap())
841 }
842
843 fn write_wide_str(
850 &mut self,
851 wide_str: &[u16],
852 ptr: Pointer,
853 size: u64,
854 ) -> InterpResult<'tcx, (bool, u64)> {
855 let string_length = u64::try_from(wide_str.len()).unwrap();
858 let string_length = string_length.strict_add(1);
859 if size < string_length {
860 return interp_ok((false, string_length));
861 }
862
863 let size2 = Size::from_bytes(2);
865 let this = self.eval_context_mut();
866 this.check_ptr_align(ptr, Align::from_bytes(2).unwrap())?;
867 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() {
869 let offset = u64::try_from(offset).unwrap();
870 alloc.write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar))?;
871 }
872 interp_ok((true, string_length))
873 }
874
875 fn read_wchar_t_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u32>> {
878 let this = self.eval_context_ref();
879 let wchar_t = if this.tcx.sess.target.os == Os::Windows {
880 this.machine.layouts.u16
882 } else {
883 this.libc_ty_layout("wchar_t")
884 };
885 self.read_c_str_with_char_size(ptr, wchar_t.size, wchar_t.align.abi)
886 }
887
888 fn frame_in_std(&self) -> bool {
889 let this = self.eval_context_ref();
890 let frame = this.frame();
891 let instance: Option<_> = try {
893 let scope = frame.current_source_info()?.scope;
894 let inlined_parent = frame.body().source_scopes[scope].inlined_parent_scope?;
895 let source = &frame.body().source_scopes[inlined_parent];
896 source.inlined.expect("inlined_parent_scope points to scope without inline info").0
897 };
898 let instance = instance.unwrap_or(frame.instance());
900 let frame_crate = this.tcx.def_path(instance.def_id()).krate;
905 let crate_name = this.tcx.crate_name(frame_crate);
906 let crate_name = crate_name.as_str();
907 crate_name == "std"
908 }
909
910 fn mark_immutable(&mut self, mplace: &MPlaceTy<'tcx>) {
912 let this = self.eval_context_mut();
913 let provenance = mplace.ptr().into_pointer_or_addr().unwrap().provenance;
915 this.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
916 }
917
918 fn get_twice_wide_int_ty(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
920 let this = self.eval_context_ref();
921 match ty.kind() {
922 ty::Uint(UintTy::U8) => this.tcx.types.u16,
924 ty::Uint(UintTy::U16) => this.tcx.types.u32,
925 ty::Uint(UintTy::U32) => this.tcx.types.u64,
926 ty::Uint(UintTy::U64) => this.tcx.types.u128,
927 ty::Int(IntTy::I8) => this.tcx.types.i16,
929 ty::Int(IntTy::I16) => this.tcx.types.i32,
930 ty::Int(IntTy::I32) => this.tcx.types.i64,
931 ty::Int(IntTy::I64) => this.tcx.types.i128,
932 _ => span_bug!(this.cur_span(), "unexpected type: {ty:?}"),
933 }
934 }
935
936 fn expect_target_feature_for_intrinsic(
941 &self,
942 intrinsic: Symbol,
943 target_feature: &str,
944 ) -> InterpResult<'tcx, ()> {
945 let this = self.eval_context_ref();
946 if !this.tcx.sess.internal_target_features.contains(&Symbol::intern(target_feature)) {
947 throw_ub_format!(
948 "attempted to call intrinsic `{intrinsic}` that requires missing target feature {target_feature}"
949 );
950 }
951 interp_ok(())
952 }
953
954 fn lookup_link_section(
957 &mut self,
958 include_name: impl Fn(&str) -> bool,
959 ) -> InterpResult<'tcx, Vec<(ImmTy<'tcx>, Span)>> {
960 let this = self.eval_context_mut();
961 let tcx = this.tcx.tcx;
962
963 let mut array = vec![];
964
965 iter_exported_symbols(tcx, |_cnum, def_id, used| {
966 let attrs = tcx.codegen_fn_attrs(def_id);
967 if !used {
968 return interp_ok(());
971 }
972 let Some(link_section) = attrs.link_section else {
973 return interp_ok(());
974 };
975 if include_name(link_section.as_str()) {
976 let instance = ty::Instance::mono(tcx, def_id);
977 let span = tcx.def_span(def_id);
978 let const_val = this.eval_global(instance).unwrap_or_else(|err| {
979 panic!(
980 "failed to evaluate static in required link_section: {def_id:?}\n{err:?}"
981 )
982 });
983 match const_val.layout.ty.kind() {
984 ty::FnPtr(..) => {
985 array.push((this.read_immediate(&const_val)?, span));
986 }
987 ty::Array(elem_ty, _) if matches!(elem_ty.kind(), ty::FnPtr(..)) => {
988 let mut elems = this.project_array_fields(&const_val)?;
989 while let Some((_idx, elem)) = elems.next(this)? {
990 array.push((this.read_immediate(&elem)?, span));
991 }
992 }
993 _ =>
994 throw_unsup_format!(
995 "only function pointers and arrays of function pointers are supported in well-known linker sections"
996 ),
997 }
998 }
999 interp_ok(())
1000 })?;
1001
1002 interp_ok(array)
1003 }
1004
1005 fn mangle_internal_symbol<'a>(&'a mut self, name: &'static str) -> &'a str
1006 where
1007 'tcx: 'a,
1008 {
1009 let this = self.eval_context_mut();
1010 let tcx = *this.tcx;
1011 this.machine
1012 .mangle_internal_symbol_cache
1013 .entry(name)
1014 .or_insert_with(|| mangle_internal_symbol(tcx, name))
1015 }
1016}
1017
1018impl<'tcx> MiriMachine<'tcx> {
1019 pub fn current_user_relevant_span(&self) -> Span {
1024 self.threads.active_thread_ref().current_user_relevant_span()
1025 }
1026
1027 pub fn caller_span(&self) -> Span {
1033 let frame_idx = self.top_user_relevant_frame().unwrap();
1036 let frame_idx = cmp::min(frame_idx, self.stack().len().saturating_sub(2));
1037 self.stack()[frame_idx].current_span()
1038 }
1039
1040 fn stack(&self) -> &[Frame<'tcx, Provenance, machine::FrameExtra<'tcx>>] {
1041 self.threads.active_thread_stack()
1042 }
1043
1044 fn top_user_relevant_frame(&self) -> Option<usize> {
1045 self.threads.active_thread_ref().top_user_relevant_frame()
1046 }
1047
1048 pub fn user_relevance(&self, frame: &Frame<'tcx, Provenance>) -> u8 {
1050 if frame.instance().def.requires_caller_location(self.tcx) {
1051 return 0;
1052 }
1053 if self.is_local(frame.instance()) {
1054 u8::MAX
1055 } else {
1056 1
1059 }
1060 }
1061}
1062
1063pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
1064 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
1065 "{name} not available when isolation is enabled",
1066 )))
1067}
1068
1069pub(crate) fn bool_to_simd_element(b: bool, size: Size) -> Scalar {
1070 let val = if b { -1 } else { 0 };
1074 Scalar::from_int(val, size)
1075}
1076
1077pub(crate) fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
1081 if success {
1082 u32::try_from(len.strict_sub(1)).unwrap()
1085 } else {
1086 u32::try_from(len).unwrap()
1089 }
1090}
1091
1092pub fn is_no_core(tcx: TyCtxt<'_>) -> bool {
1094 rustc_attr_ir::find_attr!(tcx, crate, NoCore)
1095}
1096
1097pub trait ToUsize {
1099 fn to_usize(self) -> usize;
1100}
1101
1102impl ToUsize for u32 {
1103 fn to_usize(self) -> usize {
1104 self.try_into().unwrap()
1105 }
1106}
1107
1108pub trait ToU64 {
1111 fn to_u64(self) -> u64;
1112}
1113
1114impl ToU64 for usize {
1115 fn to_u64(self) -> u64 {
1116 self.try_into().unwrap()
1117 }
1118}
1119
1120#[macro_export]
1126macro_rules! enter_trace_span {
1127 ($($tt:tt)*) => {
1128 rustc_const_eval::enter_trace_span!($crate::MiriMachine<'static>, $($tt)*)
1129 };
1130}