1use std::num::NonZero;
2use std::time::Duration;
3use std::{cmp, iter};
4
5use rand::RngCore;
6use rustc_abi::{Align, ExternAbi, FieldIdx, FieldsShape, Size, Variants};
7use rustc_apfloat::Float;
8use rustc_apfloat::ieee::{Double, Half, Quad, Single};
9use rustc_hir::Safety;
10use rustc_hir::def::{DefKind, Namespace};
11use rustc_hir::def_id::{CRATE_DEF_INDEX, CrateNum, DefId, LOCAL_CRATE};
12use rustc_index::IndexVec;
13use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
14use rustc_middle::middle::dependency_format::Linkage;
15use rustc_middle::middle::exported_symbols::ExportedSymbol;
16use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, MaybeResult, TyAndLayout};
17use rustc_middle::ty::{self, Binder, FloatTy, FnSig, IntTy, Ty, TyCtxt, UintTy};
18use rustc_session::config::CrateType;
19use rustc_span::{Span, Symbol};
20use rustc_symbol_mangling::mangle_internal_symbol;
21use rustc_target::callconv::{Conv, FnAbi};
22
23use crate::*;
24
25#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
27pub enum AccessKind {
28 Read,
29 Write,
30}
31
32fn try_resolve_did(tcx: TyCtxt<'_>, path: &[&str], namespace: Option<Namespace>) -> Option<DefId> {
36 fn find_children<'tcx: 'a, 'a>(
38 tcx: TyCtxt<'tcx>,
39 item: DefId,
40 name: &'a str,
41 ) -> impl Iterator<Item = DefId> + 'a {
42 let name = Symbol::intern(name);
43 tcx.module_children(item)
44 .iter()
45 .filter(move |item| item.ident.name == name)
46 .map(move |item| item.res.def_id())
47 }
48
49 let (&crate_name, path) = path.split_first().expect("paths must have at least one segment");
51 let (modules, item) = if let Some(namespace) = namespace {
52 let (&item_name, modules) =
53 path.split_last().expect("non-module paths must have at least 2 segments");
54 (modules, Some((item_name, namespace)))
55 } else {
56 (path, None)
57 };
58
59 'crates: for krate in
64 tcx.crates(()).iter().filter(|&&krate| tcx.crate_name(krate).as_str() == crate_name)
65 {
66 let mut cur_item = DefId { krate: *krate, index: CRATE_DEF_INDEX };
67 for &segment in modules {
69 let Some(next_item) = find_children(tcx, cur_item, segment)
70 .find(|item| tcx.def_kind(item) == DefKind::Mod)
71 else {
72 continue 'crates;
73 };
74 cur_item = next_item;
75 }
76 match item {
78 Some((item_name, namespace)) => {
79 let Some(item) = find_children(tcx, cur_item, item_name)
80 .find(|item| tcx.def_kind(item).ns() == Some(namespace))
81 else {
82 continue 'crates;
83 };
84 return Some(item);
85 }
86 None => {
87 return Some(cur_item);
89 }
90 }
91 }
92 None
94}
95
96pub fn try_resolve_path<'tcx>(
98 tcx: TyCtxt<'tcx>,
99 path: &[&str],
100 namespace: Namespace,
101) -> Option<ty::Instance<'tcx>> {
102 let did = try_resolve_did(tcx, path, Some(namespace))?;
103 Some(ty::Instance::mono(tcx, did))
104}
105
106#[track_caller]
108pub fn resolve_path<'tcx>(
109 tcx: TyCtxt<'tcx>,
110 path: &[&str],
111 namespace: Namespace,
112) -> ty::Instance<'tcx> {
113 try_resolve_path(tcx, path, namespace)
114 .unwrap_or_else(|| panic!("failed to find required Rust item: {path:?}"))
115}
116
117#[track_caller]
119pub fn path_ty_layout<'tcx>(cx: &impl LayoutOf<'tcx>, path: &[&str]) -> TyAndLayout<'tcx> {
120 let ty = resolve_path(cx.tcx(), path, Namespace::TypeNS).ty(cx.tcx(), cx.typing_env());
121 cx.layout_of(ty).to_result().ok().unwrap()
122}
123
124pub fn iter_exported_symbols<'tcx>(
126 tcx: TyCtxt<'tcx>,
127 mut f: impl FnMut(CrateNum, DefId) -> InterpResult<'tcx>,
128) -> InterpResult<'tcx> {
129 let crate_items = tcx.hir_crate_items(());
133 for def_id in crate_items.definitions() {
134 let exported = tcx.def_kind(def_id).has_codegen_attrs() && {
135 let codegen_attrs = tcx.codegen_fn_attrs(def_id);
136 codegen_attrs.contains_extern_indicator()
137 || codegen_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
138 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED)
139 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
140 };
141 if exported {
142 f(LOCAL_CRATE, def_id.into())?;
143 }
144 }
145
146 let dependency_formats = tcx.dependency_formats(());
151 let dependency_format = dependency_formats
153 .get(&CrateType::Executable)
154 .expect("interpreting a non-executable crate");
155 for cnum in dependency_format
156 .iter_enumerated()
157 .filter_map(|(num, &linkage)| (linkage != Linkage::NotLinked).then_some(num))
158 {
159 if cnum == LOCAL_CRATE {
160 continue; }
162
163 for &(symbol, _export_info) in tcx.exported_symbols(cnum) {
166 if let ExportedSymbol::NonGeneric(def_id) = symbol {
167 f(cnum, def_id)?;
168 }
169 }
170 }
171 interp_ok(())
172}
173
174pub trait ToHost {
176 type HostFloat;
177 fn to_host(self) -> Self::HostFloat;
178}
179
180pub trait ToSoft {
182 type SoftFloat;
183 fn to_soft(self) -> Self::SoftFloat;
184}
185
186impl ToHost for rustc_apfloat::ieee::Double {
187 type HostFloat = f64;
188
189 fn to_host(self) -> Self::HostFloat {
190 f64::from_bits(self.to_bits().try_into().unwrap())
191 }
192}
193
194impl ToSoft for f64 {
195 type SoftFloat = rustc_apfloat::ieee::Double;
196
197 fn to_soft(self) -> Self::SoftFloat {
198 Float::from_bits(self.to_bits().into())
199 }
200}
201
202impl ToHost for rustc_apfloat::ieee::Single {
203 type HostFloat = f32;
204
205 fn to_host(self) -> Self::HostFloat {
206 f32::from_bits(self.to_bits().try_into().unwrap())
207 }
208}
209
210impl ToSoft for f32 {
211 type SoftFloat = rustc_apfloat::ieee::Single;
212
213 fn to_soft(self) -> Self::SoftFloat {
214 Float::from_bits(self.to_bits().into())
215 }
216}
217
218impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
219pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
220 fn have_module(&self, path: &[&str]) -> bool {
222 try_resolve_did(*self.eval_context_ref().tcx, path, None).is_some()
223 }
224
225 fn eval_path(&self, path: &[&str]) -> MPlaceTy<'tcx> {
227 let this = self.eval_context_ref();
228 let instance = resolve_path(*this.tcx, path, Namespace::ValueNS);
229 this.eval_global(instance).unwrap_or_else(|err| {
231 panic!("failed to evaluate required Rust item: {path:?}\n{err:?}")
232 })
233 }
234 fn eval_path_scalar(&self, path: &[&str]) -> Scalar {
235 let this = self.eval_context_ref();
236 let val = this.eval_path(path);
237 this.read_scalar(&val)
238 .unwrap_or_else(|err| panic!("failed to read required Rust item: {path:?}\n{err:?}"))
239 }
240
241 fn eval_libc(&self, name: &str) -> Scalar {
243 if self.eval_context_ref().tcx.sess.target.os == "windows" {
244 panic!(
245 "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
246 );
247 }
248 self.eval_path_scalar(&["libc", name])
249 }
250
251 fn eval_libc_i32(&self, name: &str) -> i32 {
253 self.eval_libc(name).to_i32().unwrap_or_else(|_err| {
255 panic!("required libc item has unexpected type (not `i32`): {name}")
256 })
257 }
258
259 fn eval_libc_u32(&self, name: &str) -> u32 {
261 self.eval_libc(name).to_u32().unwrap_or_else(|_err| {
263 panic!("required libc item has unexpected type (not `u32`): {name}")
264 })
265 }
266
267 fn eval_libc_u64(&self, name: &str) -> u64 {
269 self.eval_libc(name).to_u64().unwrap_or_else(|_err| {
271 panic!("required libc item has unexpected type (not `u64`): {name}")
272 })
273 }
274
275 fn eval_windows(&self, module: &str, name: &str) -> Scalar {
277 self.eval_context_ref().eval_path_scalar(&["std", "sys", "pal", "windows", module, name])
278 }
279
280 fn eval_windows_u32(&self, module: &str, name: &str) -> u32 {
282 self.eval_windows(module, name).to_u32().unwrap_or_else(|_err| {
284 panic!("required Windows item has unexpected type (not `u32`): {module}::{name}")
285 })
286 }
287
288 fn eval_windows_u64(&self, module: &str, name: &str) -> u64 {
290 self.eval_windows(module, name).to_u64().unwrap_or_else(|_err| {
292 panic!("required Windows item has unexpected type (not `u64`): {module}::{name}")
293 })
294 }
295
296 fn libc_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
298 let this = self.eval_context_ref();
299 if this.tcx.sess.target.os == "windows" {
300 panic!(
301 "`libc` crate is not reliably available on Windows targets; Miri should not use it there"
302 );
303 }
304 path_ty_layout(this, &["libc", name])
305 }
306
307 fn windows_ty_layout(&self, name: &str) -> TyAndLayout<'tcx> {
309 let this = self.eval_context_ref();
310 path_ty_layout(this, &["std", "sys", "pal", "windows", "c", name])
311 }
312
313 fn libc_array_ty_layout(&self, name: &str, size: u64) -> TyAndLayout<'tcx> {
315 let this = self.eval_context_ref();
316 let elem_ty_layout = this.libc_ty_layout(name);
317 let array_ty = Ty::new_array(*this.tcx, elem_ty_layout.ty, size);
318 this.layout_of(array_ty).unwrap()
319 }
320
321 fn try_project_field_named<P: Projectable<'tcx, Provenance>>(
323 &self,
324 base: &P,
325 name: &str,
326 ) -> InterpResult<'tcx, Option<P>> {
327 let this = self.eval_context_ref();
328 let adt = base.layout().ty.ty_adt_def().unwrap();
329 for (idx, field) in adt.non_enum_variant().fields.iter().enumerate() {
330 if field.name.as_str() == name {
331 return interp_ok(Some(this.project_field(base, idx)?));
332 }
333 }
334 interp_ok(None)
335 }
336
337 fn project_field_named<P: Projectable<'tcx, Provenance>>(
339 &self,
340 base: &P,
341 name: &str,
342 ) -> InterpResult<'tcx, P> {
343 interp_ok(
344 self.try_project_field_named(base, name)?
345 .unwrap_or_else(|| bug!("no field named {} in type {}", name, base.layout().ty)),
346 )
347 }
348
349 fn write_int(
353 &mut self,
354 i: impl Into<i128>,
355 dest: &impl Writeable<'tcx, Provenance>,
356 ) -> InterpResult<'tcx> {
357 assert!(
358 dest.layout().backend_repr.is_scalar(),
359 "write_int on non-scalar type {}",
360 dest.layout().ty
361 );
362 let val = if dest.layout().backend_repr.is_signed() {
363 Scalar::from_int(i, dest.layout().size)
364 } else {
365 Scalar::from_uint(u128::try_from(i.into()).unwrap(), dest.layout().size)
367 };
368 self.eval_context_mut().write_scalar(val, dest)
369 }
370
371 fn write_int_fields(
373 &mut self,
374 values: &[i128],
375 dest: &impl Writeable<'tcx, Provenance>,
376 ) -> InterpResult<'tcx> {
377 let this = self.eval_context_mut();
378 for (idx, &val) in values.iter().enumerate() {
379 let field = this.project_field(dest, idx)?;
380 this.write_int(val, &field)?;
381 }
382 interp_ok(())
383 }
384
385 fn write_int_fields_named(
387 &mut self,
388 values: &[(&str, i128)],
389 dest: &impl Writeable<'tcx, Provenance>,
390 ) -> InterpResult<'tcx> {
391 let this = self.eval_context_mut();
392 for &(name, val) in values.iter() {
393 let field = this.project_field_named(dest, name)?;
394 this.write_int(val, &field)?;
395 }
396 interp_ok(())
397 }
398
399 fn write_null(&mut self, dest: &impl Writeable<'tcx, Provenance>) -> InterpResult<'tcx> {
401 self.write_int(0, dest)
402 }
403
404 fn ptr_is_null(&self, ptr: Pointer) -> InterpResult<'tcx, bool> {
406 interp_ok(ptr.addr().bytes() == 0)
407 }
408
409 fn gen_random(&mut self, ptr: Pointer, len: u64) -> InterpResult<'tcx> {
411 if len == 0 {
417 return interp_ok(());
418 }
419 let this = self.eval_context_mut();
420
421 let mut data = vec![0; usize::try_from(len).unwrap()];
422
423 if this.machine.communicate() {
424 getrandom::fill(&mut data)
426 .map_err(|err| err_unsup_format!("host getrandom failed: {}", err))?;
427 } else {
428 let rng = this.machine.rng.get_mut();
429 rng.fill_bytes(&mut data);
430 }
431
432 this.write_bytes_ptr(ptr, data.iter().copied())
433 }
434
435 fn call_function(
441 &mut self,
442 f: ty::Instance<'tcx>,
443 caller_abi: ExternAbi,
444 args: &[ImmTy<'tcx>],
445 dest: Option<&MPlaceTy<'tcx>>,
446 stack_pop: StackPopCleanup,
447 ) -> InterpResult<'tcx> {
448 let this = self.eval_context_mut();
449
450 let mir = this.load_mir(f.def, None)?;
452 let dest = match dest {
453 Some(dest) => dest.clone(),
454 None => MPlaceTy::fake_alloc_zst(this.layout_of(mir.return_ty())?),
455 };
456
457 let sig = this.tcx.mk_fn_sig(
459 args.iter().map(|a| a.layout.ty),
460 dest.layout.ty,
461 false,
462 Safety::Safe,
463 caller_abi,
464 );
465 let caller_fn_abi = this.fn_abi_of_fn_ptr(ty::Binder::dummy(sig), ty::List::empty())?;
466
467 this.init_stack_frame(
468 f,
469 mir,
470 caller_fn_abi,
471 &args.iter().map(|a| FnArg::Copy(a.clone().into())).collect::<Vec<_>>(),
472 false,
473 &dest,
474 stack_pop,
475 )
476 }
477
478 fn visit_freeze_sensitive(
482 &self,
483 place: &MPlaceTy<'tcx>,
484 size: Size,
485 mut action: impl FnMut(AllocRange, bool) -> InterpResult<'tcx>,
486 ) -> InterpResult<'tcx> {
487 let this = self.eval_context_ref();
488 trace!("visit_frozen(place={:?}, size={:?})", *place, size);
489 debug_assert_eq!(
490 size,
491 this.size_and_align_of_mplace(place)?
492 .map(|(size, _)| size)
493 .unwrap_or_else(|| place.layout.size)
494 );
495 let start_addr = place.ptr().addr();
499 let mut cur_addr = start_addr;
500 let mut unsafe_cell_action = |unsafe_cell_ptr: &Pointer, unsafe_cell_size: Size| {
503 let unsafe_cell_addr = unsafe_cell_ptr.addr();
506 assert!(unsafe_cell_addr >= cur_addr);
507 let frozen_size = unsafe_cell_addr - cur_addr;
508 if frozen_size != Size::ZERO {
510 action(alloc_range(cur_addr - start_addr, frozen_size), true)?;
511 }
512 cur_addr += frozen_size;
513 if unsafe_cell_size != Size::ZERO {
515 action(
516 alloc_range(cur_addr - start_addr, unsafe_cell_size),
517 false,
518 )?;
519 }
520 cur_addr += unsafe_cell_size;
521 interp_ok(())
523 };
524 {
526 let mut visitor = UnsafeCellVisitor {
527 ecx: this,
528 unsafe_cell_action: |place| {
529 trace!("unsafe_cell_action on {:?}", place.ptr());
530 let unsafe_cell_size = this
532 .size_and_align_of_mplace(place)?
533 .map(|(size, _)| size)
534 .unwrap_or_else(|| place.layout.size);
536 if unsafe_cell_size != Size::ZERO {
538 unsafe_cell_action(&place.ptr(), unsafe_cell_size)
539 } else {
540 interp_ok(())
541 }
542 },
543 };
544 visitor.visit_value(place)?;
545 }
546 unsafe_cell_action(&place.ptr().wrapping_offset(size, this), Size::ZERO)?;
549 return interp_ok(());
551
552 struct UnsafeCellVisitor<'ecx, 'tcx, F>
555 where
556 F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
557 {
558 ecx: &'ecx MiriInterpCx<'tcx>,
559 unsafe_cell_action: F,
560 }
561
562 impl<'ecx, 'tcx, F> ValueVisitor<'tcx, MiriMachine<'tcx>> for UnsafeCellVisitor<'ecx, 'tcx, F>
563 where
564 F: FnMut(&MPlaceTy<'tcx>) -> InterpResult<'tcx>,
565 {
566 type V = MPlaceTy<'tcx>;
567
568 #[inline(always)]
569 fn ecx(&self) -> &MiriInterpCx<'tcx> {
570 self.ecx
571 }
572
573 fn aggregate_field_iter(
574 memory_index: &IndexVec<FieldIdx, u32>,
575 ) -> impl Iterator<Item = FieldIdx> + 'static {
576 let inverse_memory_index = memory_index.invert_bijective_mapping();
577 inverse_memory_index.into_iter()
578 }
579
580 fn visit_value(&mut self, v: &MPlaceTy<'tcx>) -> InterpResult<'tcx> {
582 trace!("UnsafeCellVisitor: {:?} {:?}", *v, v.layout.ty);
583 let is_unsafe_cell = match v.layout.ty.kind() {
584 ty::Adt(adt, _) =>
585 Some(adt.did()) == self.ecx.tcx.lang_items().unsafe_cell_type(),
586 _ => false,
587 };
588 if is_unsafe_cell {
589 (self.unsafe_cell_action)(v)
591 } else if self.ecx.type_is_freeze(v.layout.ty) {
592 interp_ok(())
594 } else if matches!(v.layout.fields, FieldsShape::Union(..)) {
595 (self.unsafe_cell_action)(v)
597 } else if matches!(v.layout.ty.kind(), ty::Dynamic(_, _, ty::DynStar)) {
598 (self.unsafe_cell_action)(v)
601 } else {
602 match v.layout.variants {
606 Variants::Multiple { .. } => {
607 (self.unsafe_cell_action)(v)
615 }
616 Variants::Single { .. } | Variants::Empty => {
617 self.walk_value(v)
620 }
621 }
622 }
623 }
624
625 fn visit_union(
626 &mut self,
627 _v: &MPlaceTy<'tcx>,
628 _fields: NonZero<usize>,
629 ) -> InterpResult<'tcx> {
630 bug!("we should have already handled unions in `visit_value`")
631 }
632 }
633 }
634
635 fn check_no_isolation(&self, name: &str) -> InterpResult<'tcx> {
639 if !self.eval_context_ref().machine.communicate() {
640 self.reject_in_isolation(name, RejectOpWith::Abort)?;
641 }
642 interp_ok(())
643 }
644
645 fn reject_in_isolation(&self, op_name: &str, reject_with: RejectOpWith) -> InterpResult<'tcx> {
648 let this = self.eval_context_ref();
649 match reject_with {
650 RejectOpWith::Abort => isolation_abort_error(op_name),
651 RejectOpWith::WarningWithoutBacktrace => {
652 let mut emitted_warnings = this.machine.reject_in_isolation_warned.borrow_mut();
653 if !emitted_warnings.contains(op_name) {
654 emitted_warnings.insert(op_name.to_owned());
656 this.tcx
657 .dcx()
658 .warn(format!("{op_name} was made to return an error due to isolation"));
659 }
660
661 interp_ok(())
662 }
663 RejectOpWith::Warning => {
664 this.emit_diagnostic(NonHaltingDiagnostic::RejectedIsolatedOp(op_name.to_string()));
665 interp_ok(())
666 }
667 RejectOpWith::NoWarning => interp_ok(()), }
669 }
670
671 fn assert_target_os(&self, target_os: &str, name: &str) {
675 assert_eq!(
676 self.eval_context_ref().tcx.sess.target.os,
677 target_os,
678 "`{name}` is only available on the `{target_os}` target OS",
679 )
680 }
681
682 fn check_target_os(&self, target_oses: &[&str], name: Symbol) -> InterpResult<'tcx> {
686 let target_os = self.eval_context_ref().tcx.sess.target.os.as_ref();
687 if !target_oses.contains(&target_os) {
688 throw_unsup_format!("`{name}` is not supported on {target_os}");
689 }
690 interp_ok(())
691 }
692
693 fn assert_target_os_is_unix(&self, name: &str) {
697 assert!(self.target_os_is_unix(), "`{name}` is only available for unix targets",);
698 }
699
700 fn target_os_is_unix(&self) -> bool {
701 self.eval_context_ref().tcx.sess.target.families.iter().any(|f| f == "unix")
702 }
703
704 fn deref_pointer_as(
706 &self,
707 op: &impl Projectable<'tcx, Provenance>,
708 layout: TyAndLayout<'tcx>,
709 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
710 let this = self.eval_context_ref();
711 let ptr = this.read_pointer(op)?;
712 interp_ok(this.ptr_to_mplace(ptr, layout))
713 }
714
715 fn deref_pointer_and_offset(
717 &self,
718 op: &impl Projectable<'tcx, Provenance>,
719 offset: u64,
720 base_layout: TyAndLayout<'tcx>,
721 value_layout: TyAndLayout<'tcx>,
722 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
723 let this = self.eval_context_ref();
724 let op_place = this.deref_pointer_as(op, base_layout)?;
725 let offset = Size::from_bytes(offset);
726
727 assert!(base_layout.size >= offset + value_layout.size);
729 let value_place = op_place.offset(offset, value_layout, this)?;
730 interp_ok(value_place)
731 }
732
733 fn deref_pointer_and_read(
734 &self,
735 op: &impl Projectable<'tcx, Provenance>,
736 offset: u64,
737 base_layout: TyAndLayout<'tcx>,
738 value_layout: TyAndLayout<'tcx>,
739 ) -> InterpResult<'tcx, Scalar> {
740 let this = self.eval_context_ref();
741 let value_place = this.deref_pointer_and_offset(op, offset, base_layout, value_layout)?;
742 this.read_scalar(&value_place)
743 }
744
745 fn deref_pointer_and_write(
746 &mut self,
747 op: &impl Projectable<'tcx, Provenance>,
748 offset: u64,
749 value: impl Into<Scalar>,
750 base_layout: TyAndLayout<'tcx>,
751 value_layout: TyAndLayout<'tcx>,
752 ) -> InterpResult<'tcx, ()> {
753 let this = self.eval_context_mut();
754 let value_place = this.deref_pointer_and_offset(op, offset, base_layout, value_layout)?;
755 this.write_scalar(value, &value_place)
756 }
757
758 fn read_timespec(&mut self, tp: &MPlaceTy<'tcx>) -> InterpResult<'tcx, Option<Duration>> {
762 let this = self.eval_context_mut();
763 let seconds_place = this.project_field(tp, 0)?;
764 let seconds_scalar = this.read_scalar(&seconds_place)?;
765 let seconds = seconds_scalar.to_target_isize(this)?;
766 let nanoseconds_place = this.project_field(tp, 1)?;
767 let nanoseconds_scalar = this.read_scalar(&nanoseconds_place)?;
768 let nanoseconds = nanoseconds_scalar.to_target_isize(this)?;
769
770 interp_ok(
771 try {
772 let seconds: u64 = seconds.try_into().ok()?;
774 let nanoseconds: u32 = nanoseconds.try_into().ok()?;
776 if nanoseconds >= 1_000_000_000 {
777 None?
779 }
780 Duration::new(seconds, nanoseconds)
781 },
782 )
783 }
784
785 fn read_byte_slice<'a>(&'a self, slice: &ImmTy<'tcx>) -> InterpResult<'tcx, &'a [u8]>
787 where
788 'tcx: 'a,
789 {
790 let this = self.eval_context_ref();
791 let (ptr, len) = slice.to_scalar_pair();
792 let ptr = ptr.to_pointer(this)?;
793 let len = len.to_target_usize(this)?;
794 let bytes = this.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(len))?;
795 interp_ok(bytes)
796 }
797
798 fn read_c_str<'a>(&'a self, ptr: Pointer) -> InterpResult<'tcx, &'a [u8]>
800 where
801 'tcx: 'a,
802 {
803 let this = self.eval_context_ref();
804 let size1 = Size::from_bytes(1);
805
806 let mut len = Size::ZERO;
808 loop {
809 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()?;
813 if byte == 0 {
814 break;
815 } else {
816 len += size1;
817 }
818 }
819
820 this.read_bytes_ptr_strip_provenance(ptr, len)
822 }
823
824 fn write_c_str(
830 &mut self,
831 c_str: &[u8],
832 ptr: Pointer,
833 size: u64,
834 ) -> InterpResult<'tcx, (bool, u64)> {
835 let string_length = u64::try_from(c_str.len()).unwrap();
838 let string_length = string_length.strict_add(1);
839 if size < string_length {
840 return interp_ok((false, string_length));
841 }
842 self.eval_context_mut()
843 .write_bytes_ptr(ptr, c_str.iter().copied().chain(iter::once(0u8)))?;
844 interp_ok((true, string_length))
845 }
846
847 fn read_c_str_with_char_size<T>(
850 &self,
851 mut ptr: Pointer,
852 size: Size,
853 align: Align,
854 ) -> InterpResult<'tcx, Vec<T>>
855 where
856 T: TryFrom<u128>,
857 <T as TryFrom<u128>>::Error: std::fmt::Debug,
858 {
859 assert_ne!(size, Size::ZERO);
860
861 let this = self.eval_context_ref();
862
863 this.check_ptr_align(ptr, align)?;
864
865 let mut wchars = Vec::new();
866 loop {
867 let alloc = this.get_ptr_alloc(ptr, size)?.unwrap(); let wchar_int = alloc.read_integer(alloc_range(Size::ZERO, size))?.to_bits(size)?;
871 if wchar_int == 0 {
872 break;
873 } else {
874 wchars.push(wchar_int.try_into().unwrap());
875 ptr = ptr.wrapping_offset(size, this);
876 }
877 }
878
879 interp_ok(wchars)
880 }
881
882 fn read_wide_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u16>> {
884 self.read_c_str_with_char_size(ptr, Size::from_bytes(2), Align::from_bytes(2).unwrap())
885 }
886
887 fn write_wide_str(
894 &mut self,
895 wide_str: &[u16],
896 ptr: Pointer,
897 size: u64,
898 ) -> InterpResult<'tcx, (bool, u64)> {
899 let string_length = u64::try_from(wide_str.len()).unwrap();
902 let string_length = string_length.strict_add(1);
903 if size < string_length {
904 return interp_ok((false, string_length));
905 }
906
907 let size2 = Size::from_bytes(2);
909 let this = self.eval_context_mut();
910 this.check_ptr_align(ptr, Align::from_bytes(2).unwrap())?;
911 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() {
913 let offset = u64::try_from(offset).unwrap();
914 alloc.write_scalar(alloc_range(size2 * offset, size2), Scalar::from_u16(wchar))?;
915 }
916 interp_ok((true, string_length))
917 }
918
919 fn read_wchar_t_str(&self, ptr: Pointer) -> InterpResult<'tcx, Vec<u32>> {
922 let this = self.eval_context_ref();
923 let wchar_t = if this.tcx.sess.target.os == "windows" {
924 this.machine.layouts.u16
926 } else {
927 this.libc_ty_layout("wchar_t")
928 };
929 self.read_c_str_with_char_size(ptr, wchar_t.size, wchar_t.align.abi)
930 }
931
932 fn check_abi<'a>(&self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>, exp_abi: Conv) -> InterpResult<'a, ()> {
934 if fn_abi.conv != exp_abi {
935 throw_ub_format!(
936 "calling a function with ABI {:?} using caller ABI {:?}",
937 exp_abi,
938 fn_abi.conv
939 );
940 }
941 interp_ok(())
942 }
943
944 fn frame_in_std(&self) -> bool {
945 let this = self.eval_context_ref();
946 let frame = this.frame();
947 let instance: Option<_> = try {
949 let scope = frame.current_source_info()?.scope;
950 let inlined_parent = frame.body().source_scopes[scope].inlined_parent_scope?;
951 let source = &frame.body().source_scopes[inlined_parent];
952 source.inlined.expect("inlined_parent_scope points to scope without inline info").0
953 };
954 let instance = instance.unwrap_or(frame.instance());
956 let frame_crate = this.tcx.def_path(instance.def_id()).krate;
961 let crate_name = this.tcx.crate_name(frame_crate);
962 let crate_name = crate_name.as_str();
963 crate_name == "std" || crate_name == "std_miri_test"
965 }
966
967 fn check_abi_and_shim_symbol_clash(
968 &mut self,
969 abi: &FnAbi<'tcx, Ty<'tcx>>,
970 exp_abi: Conv,
971 link_name: Symbol,
972 ) -> InterpResult<'tcx, ()> {
973 self.check_abi(abi, exp_abi)?;
974 if let Some((body, instance)) = self.eval_context_mut().lookup_exported_symbol(link_name)? {
975 if self.eval_context_ref().tcx.is_compiler_builtins(instance.def_id().krate) {
981 return interp_ok(());
982 }
983
984 throw_machine_stop!(TerminationInfo::SymbolShimClashing {
985 link_name,
986 span: body.span.data(),
987 })
988 }
989 interp_ok(())
990 }
991
992 fn check_shim<'a, const N: usize>(
993 &mut self,
994 abi: &FnAbi<'tcx, Ty<'tcx>>,
995 exp_abi: Conv,
996 link_name: Symbol,
997 args: &'a [OpTy<'tcx>],
998 ) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]> {
999 self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
1000
1001 if abi.c_variadic {
1002 throw_ub_format!(
1003 "calling a non-variadic function with a variadic caller-side signature"
1004 );
1005 }
1006 if let Ok(ops) = args.try_into() {
1007 return interp_ok(ops);
1008 }
1009 throw_ub_format!(
1010 "incorrect number of arguments for `{link_name}`: got {}, expected {}",
1011 args.len(),
1012 N
1013 )
1014 }
1015
1016 fn check_shim_abi<'a, const N: usize>(
1020 &mut self,
1021 link_name: Symbol,
1022 caller_fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
1023 callee_abi: ExternAbi,
1024 callee_input_tys: [Ty<'tcx>; N],
1025 callee_output_ty: Ty<'tcx>,
1026 caller_args: &'a [OpTy<'tcx>],
1027 ) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]> {
1028 let this = self.eval_context_mut();
1029 let mut inputs_and_output = callee_input_tys.to_vec();
1030 inputs_and_output.push(callee_output_ty);
1031 let fn_sig_binder = Binder::dummy(FnSig {
1032 inputs_and_output: this.machine.tcx.mk_type_list(&inputs_and_output),
1033 c_variadic: false,
1034 safety: Safety::Safe,
1036 abi: callee_abi,
1037 });
1038 let callee_fn_abi = this.fn_abi_of_fn_ptr(fn_sig_binder, Default::default())?;
1039
1040 this.check_abi_and_shim_symbol_clash(caller_fn_abi, callee_fn_abi.conv, link_name)?;
1041
1042 if caller_fn_abi.c_variadic {
1043 throw_ub_format!(
1044 "ABI mismatch: calling a non-variadic function with a variadic caller-side signature"
1045 );
1046 }
1047
1048 if callee_fn_abi.fixed_count != caller_fn_abi.fixed_count {
1049 throw_ub_format!(
1050 "ABI mismatch: expected {} arguments, found {} arguments ",
1051 callee_fn_abi.fixed_count,
1052 caller_fn_abi.fixed_count
1053 );
1054 }
1055
1056 if callee_fn_abi.can_unwind && !caller_fn_abi.can_unwind {
1057 throw_ub_format!(
1058 "ABI mismatch: callee may unwind, but caller-side signature prohibits unwinding",
1059 );
1060 }
1061
1062 if !this.check_argument_compat(&caller_fn_abi.ret, &callee_fn_abi.ret)? {
1063 throw_ub!(AbiMismatchReturn {
1064 caller_ty: caller_fn_abi.ret.layout.ty,
1065 callee_ty: callee_fn_abi.ret.layout.ty
1066 });
1067 }
1068
1069 if let Some(index) = caller_fn_abi
1070 .args
1071 .iter()
1072 .zip(callee_fn_abi.args.iter())
1073 .map(|(caller_arg, callee_arg)| this.check_argument_compat(caller_arg, callee_arg))
1074 .collect::<InterpResult<'tcx, Vec<bool>>>()?
1075 .into_iter()
1076 .position(|b| !b)
1077 {
1078 throw_ub!(AbiMismatchArgument {
1079 caller_ty: caller_fn_abi.args[index].layout.ty,
1080 callee_ty: callee_fn_abi.args[index].layout.ty
1081 });
1082 }
1083
1084 if let Ok(ops) = caller_args.try_into() {
1085 return interp_ok(ops);
1086 }
1087 unreachable!()
1088 }
1089
1090 fn check_shim_variadic<'a, const N: usize>(
1093 &mut self,
1094 abi: &FnAbi<'tcx, Ty<'tcx>>,
1095 exp_abi: Conv,
1096 link_name: Symbol,
1097 args: &'a [OpTy<'tcx>],
1098 ) -> InterpResult<'tcx, (&'a [OpTy<'tcx>; N], &'a [OpTy<'tcx>])>
1099 where
1100 &'a [OpTy<'tcx>; N]: TryFrom<&'a [OpTy<'tcx>]>,
1101 {
1102 self.check_abi_and_shim_symbol_clash(abi, exp_abi, link_name)?;
1103
1104 if !abi.c_variadic {
1105 throw_ub_format!(
1106 "calling a variadic function with a non-variadic caller-side signature"
1107 );
1108 }
1109 if abi.fixed_count != u32::try_from(N).unwrap() {
1110 throw_ub_format!(
1111 "incorrect number of fixed arguments for variadic function `{}`: got {}, expected {N}",
1112 link_name.as_str(),
1113 abi.fixed_count
1114 )
1115 }
1116 if let Some(args) = args.split_first_chunk() {
1117 return interp_ok(args);
1118 }
1119 panic!("mismatch between signature and `args` slice");
1120 }
1121
1122 fn mark_immutable(&mut self, mplace: &MPlaceTy<'tcx>) {
1124 let this = self.eval_context_mut();
1125 let provenance = mplace.ptr().into_pointer_or_addr().unwrap().provenance;
1127 this.alloc_mark_immutable(provenance.get_alloc_id().unwrap()).unwrap();
1128 }
1129
1130 fn float_to_int_checked(
1134 &self,
1135 src: &ImmTy<'tcx>,
1136 cast_to: TyAndLayout<'tcx>,
1137 round: rustc_apfloat::Round,
1138 ) -> InterpResult<'tcx, Option<ImmTy<'tcx>>> {
1139 let this = self.eval_context_ref();
1140
1141 fn float_to_int_inner<'tcx, F: rustc_apfloat::Float>(
1142 ecx: &MiriInterpCx<'tcx>,
1143 src: F,
1144 cast_to: TyAndLayout<'tcx>,
1145 round: rustc_apfloat::Round,
1146 ) -> (Scalar, rustc_apfloat::Status) {
1147 let int_size = cast_to.layout.size;
1148 match cast_to.ty.kind() {
1149 ty::Uint(_) => {
1151 let res = src.to_u128_r(int_size.bits_usize(), round, &mut false);
1152 (Scalar::from_uint(res.value, int_size), res.status)
1153 }
1154 ty::Int(_) => {
1156 let res = src.to_i128_r(int_size.bits_usize(), round, &mut false);
1157 (Scalar::from_int(res.value, int_size), res.status)
1158 }
1159 _ =>
1161 span_bug!(
1162 ecx.cur_span(),
1163 "attempted float-to-int conversion with non-int output type {}",
1164 cast_to.ty,
1165 ),
1166 }
1167 }
1168
1169 let ty::Float(fty) = src.layout.ty.kind() else {
1170 bug!("float_to_int_checked: non-float input type {}", src.layout.ty)
1171 };
1172
1173 let (val, status) = match fty {
1174 FloatTy::F16 =>
1175 float_to_int_inner::<Half>(this, src.to_scalar().to_f16()?, cast_to, round),
1176 FloatTy::F32 =>
1177 float_to_int_inner::<Single>(this, src.to_scalar().to_f32()?, cast_to, round),
1178 FloatTy::F64 =>
1179 float_to_int_inner::<Double>(this, src.to_scalar().to_f64()?, cast_to, round),
1180 FloatTy::F128 =>
1181 float_to_int_inner::<Quad>(this, src.to_scalar().to_f128()?, cast_to, round),
1182 };
1183
1184 if status.intersects(
1185 rustc_apfloat::Status::INVALID_OP
1186 | rustc_apfloat::Status::OVERFLOW
1187 | rustc_apfloat::Status::UNDERFLOW,
1188 ) {
1189 interp_ok(None)
1192 } else {
1193 interp_ok(Some(ImmTy::from_scalar(val, cast_to)))
1196 }
1197 }
1198
1199 fn get_twice_wide_int_ty(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
1201 let this = self.eval_context_ref();
1202 match ty.kind() {
1203 ty::Uint(UintTy::U8) => this.tcx.types.u16,
1205 ty::Uint(UintTy::U16) => this.tcx.types.u32,
1206 ty::Uint(UintTy::U32) => this.tcx.types.u64,
1207 ty::Uint(UintTy::U64) => this.tcx.types.u128,
1208 ty::Int(IntTy::I8) => this.tcx.types.i16,
1210 ty::Int(IntTy::I16) => this.tcx.types.i32,
1211 ty::Int(IntTy::I32) => this.tcx.types.i64,
1212 ty::Int(IntTy::I64) => this.tcx.types.i128,
1213 _ => span_bug!(this.cur_span(), "unexpected type: {ty:?}"),
1214 }
1215 }
1216
1217 fn expect_target_feature_for_intrinsic(
1222 &self,
1223 intrinsic: Symbol,
1224 target_feature: &str,
1225 ) -> InterpResult<'tcx, ()> {
1226 let this = self.eval_context_ref();
1227 if !this.tcx.sess.unstable_target_features.contains(&Symbol::intern(target_feature)) {
1228 throw_ub_format!(
1229 "attempted to call intrinsic `{intrinsic}` that requires missing target feature {target_feature}"
1230 );
1231 }
1232 interp_ok(())
1233 }
1234
1235 fn lookup_link_section(&mut self, name: &str) -> InterpResult<'tcx, Vec<ImmTy<'tcx>>> {
1237 let this = self.eval_context_mut();
1238 let tcx = this.tcx.tcx;
1239
1240 let mut array = vec![];
1241
1242 iter_exported_symbols(tcx, |_cnum, def_id| {
1243 let attrs = tcx.codegen_fn_attrs(def_id);
1244 let Some(link_section) = attrs.link_section else {
1245 return interp_ok(());
1246 };
1247 if link_section.as_str() == name {
1248 let instance = ty::Instance::mono(tcx, def_id);
1249 let const_val = this.eval_global(instance).unwrap_or_else(|err| {
1250 panic!(
1251 "failed to evaluate static in required link_section: {def_id:?}\n{err:?}"
1252 )
1253 });
1254 let val = this.read_immediate(&const_val)?;
1255 array.push(val);
1256 }
1257 interp_ok(())
1258 })?;
1259
1260 interp_ok(array)
1261 }
1262
1263 fn mangle_internal_symbol<'a>(&'a mut self, name: &'static str) -> &'a str
1264 where
1265 'tcx: 'a,
1266 {
1267 let this = self.eval_context_mut();
1268 let tcx = *this.tcx;
1269 this.machine
1270 .mangle_internal_symbol_cache
1271 .entry(name)
1272 .or_insert_with(|| mangle_internal_symbol(tcx, name))
1273 }
1274}
1275
1276impl<'tcx> MiriMachine<'tcx> {
1277 pub fn current_span(&self) -> Span {
1282 self.threads.active_thread_ref().current_span()
1283 }
1284
1285 pub fn caller_span(&self) -> Span {
1291 let frame_idx = self.top_user_relevant_frame().unwrap();
1294 let frame_idx = cmp::min(frame_idx, self.stack().len().saturating_sub(2));
1295 self.stack()[frame_idx].current_span()
1296 }
1297
1298 fn stack(&self) -> &[Frame<'tcx, Provenance, machine::FrameExtra<'tcx>>] {
1299 self.threads.active_thread_stack()
1300 }
1301
1302 fn top_user_relevant_frame(&self) -> Option<usize> {
1303 self.threads.active_thread_ref().top_user_relevant_frame()
1304 }
1305
1306 pub fn is_user_relevant(&self, frame: &Frame<'tcx, Provenance>) -> bool {
1308 let def_id = frame.instance().def_id();
1309 (def_id.is_local() || self.local_crates.contains(&def_id.krate))
1310 && !frame.instance().def.requires_caller_location(self.tcx)
1311 }
1312}
1313
1314pub fn check_intrinsic_arg_count<'a, 'tcx, const N: usize>(
1316 args: &'a [OpTy<'tcx>],
1317) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]>
1318where
1319 &'a [OpTy<'tcx>; N]: TryFrom<&'a [OpTy<'tcx>]>,
1320{
1321 if let Ok(ops) = args.try_into() {
1322 return interp_ok(ops);
1323 }
1324 throw_ub_format!(
1325 "incorrect number of arguments for intrinsic: got {}, expected {}",
1326 args.len(),
1327 N
1328 )
1329}
1330
1331pub fn check_min_vararg_count<'a, 'tcx, const N: usize>(
1335 name: &'a str,
1336 args: &'a [OpTy<'tcx>],
1337) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]> {
1338 if let Some((ops, _)) = args.split_first_chunk() {
1339 return interp_ok(ops);
1340 }
1341 throw_ub_format!(
1342 "not enough variadic arguments for `{name}`: got {}, expected at least {}",
1343 args.len(),
1344 N
1345 )
1346}
1347
1348pub fn isolation_abort_error<'tcx>(name: &str) -> InterpResult<'tcx> {
1349 throw_machine_stop!(TerminationInfo::UnsupportedInIsolation(format!(
1350 "{name} not available when isolation is enabled",
1351 )))
1352}
1353
1354pub fn get_local_crates(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
1357 let local_crate_names = std::env::var("MIRI_LOCAL_CRATES")
1360 .map(|crates| crates.split(',').map(|krate| krate.to_string()).collect::<Vec<_>>())
1361 .unwrap_or_default();
1362 let mut local_crates = Vec::new();
1363 for &crate_num in tcx.crates(()) {
1364 let name = tcx.crate_name(crate_num);
1365 let name = name.as_str();
1366 if local_crate_names.iter().any(|local_name| local_name == name) {
1367 local_crates.push(crate_num);
1368 }
1369 }
1370 local_crates
1371}
1372
1373pub(crate) fn bool_to_simd_element(b: bool, size: Size) -> Scalar {
1374 let val = if b { -1 } else { 0 };
1378 Scalar::from_int(val, size)
1379}
1380
1381pub(crate) fn simd_element_to_bool(elem: ImmTy<'_>) -> InterpResult<'_, bool> {
1382 let val = elem.to_scalar().to_int(elem.layout.size)?;
1383 interp_ok(match val {
1384 0 => false,
1385 -1 => true,
1386 _ => throw_ub_format!("each element of a SIMD mask must be all-0-bits or all-1-bits"),
1387 })
1388}
1389
1390pub(crate) fn windows_check_buffer_size((success, len): (bool, u64)) -> u32 {
1394 if success {
1395 u32::try_from(len.strict_sub(1)).unwrap()
1398 } else {
1399 u32::try_from(len).unwrap()
1402 }
1403}