1use std::collections::hash_map::Entry;
2use std::io::Write;
3use std::path::Path;
4
5use rustc_abi::{Align, CanonAbi, ExternAbi, Size};
6use rustc_ast::expand::allocator::NO_ALLOC_SHIM_IS_UNSTABLE;
7use rustc_data_structures::either::Either;
8use rustc_hir::attrs::Linkage;
9use rustc_hir::def::DefKind;
10use rustc_hir::def_id::CrateNum;
11use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
12use rustc_middle::mir::interpret::AllocInit;
13use rustc_middle::ty::{Instance, Ty};
14use rustc_middle::{mir, ty};
15use rustc_span::Symbol;
16use rustc_target::callconv::FnAbi;
17use rustc_target::spec::Os;
18
19use super::alloc::EvalContextExt as _;
20use super::backtrace::EvalContextExt as _;
21use crate::concurrency::GenmcEvalContextExt as _;
22use crate::helpers::EvalContextExt as _;
23use crate::*;
24
25#[derive(Debug, Copy, Clone)]
27pub struct DynSym(Symbol);
28
29#[expect(clippy::should_implement_trait)]
30impl DynSym {
31 pub fn from_str(name: &str) -> Self {
32 DynSym(Symbol::intern(name))
33 }
34}
35
36impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
37pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
38 fn emulate_foreign_item(
45 &mut self,
46 link_name: Symbol,
47 abi: &FnAbi<'tcx, Ty<'tcx>>,
48 args: &[OpTy<'tcx>],
49 dest: &PlaceTy<'tcx>,
50 ret: Option<mir::BasicBlock>,
51 unwind: mir::UnwindAction,
52 ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
53 let this = self.eval_context_mut();
54
55 if let Some(shim) = this.machine.allocator_shim_symbols.get(&link_name) {
57 match *shim {
58 Either::Left(other_fn) => {
59 let handler = this
60 .lookup_exported_fn(other_fn)?
61 .expect("missing alloc error handler symbol");
62 return interp_ok(Some(handler));
63 }
64 Either::Right(special) => {
65 this.rust_special_allocator_method(special, link_name, abi, args, dest)?;
66 this.return_to_block(ret)?;
67 return interp_ok(None);
68 }
69 }
70 }
71
72 let dest = this.force_allocation(dest)?;
74
75 let res = this.emulate_foreign_item_inner(link_name, abi, args, &dest)?;
77 res.jump_to_next_block(this, &dest.clone().into(), ret, Some(unwind), |this| {
78 if let Some(body) = this.lookup_exported_fn(link_name)? {
79 return interp_ok(Some(body));
80 }
81
82 throw_machine_stop!(TerminationInfo::UnsupportedForeignItem(format!(
83 "can't call foreign function `{link_name}` on OS `{os}`",
84 os = this.tcx.sess.target.os,
85 )));
86 })
87 }
88
89 fn is_dyn_sym(&self, name: &str) -> bool {
90 let this = self.eval_context_ref();
91 match &this.tcx.sess.target.os {
92 os if this.target_os_is_unix() => shims::unix::foreign_items::is_dyn_sym(name, os),
93 Os::Windows => shims::windows::foreign_items::is_dyn_sym(name),
94 _ => false,
95 }
96 }
97
98 fn emulate_dyn_sym(
100 &mut self,
101 sym: DynSym,
102 abi: &FnAbi<'tcx, Ty<'tcx>>,
103 args: &[OpTy<'tcx>],
104 dest: &PlaceTy<'tcx>,
105 ret: Option<mir::BasicBlock>,
106 unwind: mir::UnwindAction,
107 ) -> InterpResult<'tcx> {
108 let res = self.emulate_foreign_item(sym.0, abi, args, dest, ret, unwind)?;
109 assert!(res.is_none(), "DynSyms that delegate are not supported");
110 interp_ok(())
111 }
112
113 fn lookup_exported_symbol(
115 &self,
116 link_name: Symbol,
117 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
118 let this = self.eval_context_ref();
119 let tcx = this.tcx.tcx;
120
121 let mut cache = this.machine.exported_symbols_cache.borrow_mut();
124 let entry = cache.entry(link_name);
125 let instance = *match entry {
126 Entry::Occupied(e) => e.into_mut(),
127 Entry::Vacant(e) => {
128 struct SymbolTarget<'tcx> {
131 instance: ty::Instance<'tcx>,
132 cnum: CrateNum,
133 is_weak: bool,
134 }
135 let mut symbol_target: Option<SymbolTarget<'tcx>> = None;
136 helpers::iter_exported_symbols(tcx, |cnum, def_id, _used| {
137 let attrs = tcx.codegen_fn_attrs(def_id);
138 if !(attrs.symbol_name.is_some()
140 || attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
141 || attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL))
142 {
143 return interp_ok(());
144 }
145
146 let instance = Instance::mono(tcx, def_id);
147 let symbol_name = tcx.symbol_name(instance).name;
148 let is_weak = attrs.linkage == Some(Linkage::WeakAny);
149 if symbol_name == link_name.as_str() {
150 if let Some(original) = &symbol_target {
151 match (is_weak, original.is_weak) {
154 (false, true) => {
155 symbol_target = Some(SymbolTarget {
158 instance: ty::Instance::mono(tcx, def_id),
159 cnum,
160 is_weak,
161 });
162 }
163 (true, false) => {
164 }
166 (true, true) | (false, false) => {
167 let original_span =
174 tcx.def_span(original.instance.def_id()).data();
175 let span = tcx.def_span(def_id).data();
176 if original_span < span {
177 throw_machine_stop!(
178 TerminationInfo::MultipleSymbolDefinitions {
179 link_name,
180 first: original_span,
181 first_crate: tcx.crate_name(original.cnum),
182 second: span,
183 second_crate: tcx.crate_name(cnum),
184 }
185 );
186 } else {
187 throw_machine_stop!(
188 TerminationInfo::MultipleSymbolDefinitions {
189 link_name,
190 first: span,
191 first_crate: tcx.crate_name(cnum),
192 second: original_span,
193 second_crate: tcx.crate_name(original.cnum),
194 }
195 );
196 }
197 }
198 }
199 } else {
200 symbol_target = Some(SymbolTarget {
201 instance: ty::Instance::mono(tcx, def_id),
202 cnum,
203 is_weak,
204 });
205 }
206 }
207 interp_ok(())
208 })?;
209
210 e.insert(symbol_target.map(|SymbolTarget { instance, .. }| instance))
211 }
212 };
213 drop(cache);
214 interp_ok(instance)
215 }
216
217 fn lookup_exported_fn(
219 &self,
220 link_name: Symbol,
221 ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
222 let this = self.eval_context_ref();
223 let instance = this.lookup_exported_symbol(link_name)?;
224 if let Some(instance) = &instance {
225 if !matches!(this.tcx.def_kind(instance.def_id()), DefKind::Fn | DefKind::AssocFn) {
226 throw_ub_format!(
227 "attempt to call an exported symbol that is not defined as a function"
228 );
229 }
230 }
231 match instance {
232 None => interp_ok(None),
233 Some(instance) => interp_ok(Some((this.load_mir(instance.def, None)?, instance))),
234 }
235 }
236
237 fn lookup_exported_static(
239 &self,
240 link_name: Symbol,
241 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
242 let this = self.eval_context_ref();
243 let instance = this.lookup_exported_symbol(link_name)?;
244 if let Some(instance) = &instance {
245 if !matches!(this.tcx.def_kind(instance.def_id()), DefKind::Static { .. }) {
246 throw_ub_format!(
247 "attempt to access an exported symbol `{link_name}` that is not defined as a static"
248 );
249 }
250 }
251 interp_ok(instance)
252 }
253}
254
255impl<'tcx> EvalContextExtPriv<'tcx> for crate::MiriInterpCx<'tcx> {}
256trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> {
257 fn emulate_foreign_item_inner(
258 &mut self,
259 link_name: Symbol,
260 abi: &FnAbi<'tcx, Ty<'tcx>>,
261 args: &[OpTy<'tcx>],
262 dest: &MPlaceTy<'tcx>,
263 ) -> InterpResult<'tcx, EmulateItemResult> {
264 let this = self.eval_context_mut();
265
266 #[cfg(all(feature = "native-lib", unix))]
268 if !this.machine.native_lib.is_empty() {
269 use crate::shims::native_lib::EvalContextExt as _;
270 if this.call_native_fn(link_name, dest, args)? {
274 return interp_ok(EmulateItemResult::NeedsReturn);
275 }
276 }
277 match link_name.as_str() {
316 name if name == this.mangle_internal_symbol(NO_ALLOC_SHIM_IS_UNSTABLE) => {
318 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
321 }
322
323 "miri_alloc" => {
325 let [size, align] =
326 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
327 let size = this.read_target_usize(size)?;
328 let align = this.read_target_usize(align)?;
329
330 this.check_rust_alloc_request(size, align)?;
331
332 let ptr = this.allocate_ptr(
333 Size::from_bytes(size),
334 Align::from_bytes(align).unwrap(),
335 MiriMemoryKind::Miri.into(),
336 AllocInit::Uninit,
337 )?;
338
339 this.write_pointer(ptr, dest)?;
340 }
341 "miri_dealloc" => {
342 let [ptr, old_size, align] =
343 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
344 let ptr = this.read_pointer(ptr)?;
345 let old_size = this.read_target_usize(old_size)?;
346 let align = this.read_target_usize(align)?;
347
348 this.deallocate_ptr(
350 ptr,
351 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
352 MiriMemoryKind::Miri.into(),
353 )?;
354 }
355 "miri_track_alloc" => {
356 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
357 let ptr = this.read_pointer(ptr)?;
358 let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr, 0).map_err_kind(|_e| {
359 err_machine_stop!(TerminationInfo::Abort(format!(
360 "pointer passed to `miri_get_alloc_id` must not be dangling, got {ptr:?}"
361 )))
362 })?;
363 if this.machine.tracked_alloc_ids.insert(alloc_id) {
364 let info = this.get_alloc_info(alloc_id);
365 this.emit_diagnostic(NonHaltingDiagnostic::TrackingAlloc(
366 alloc_id, info.size, info.align,
367 ));
368 }
369 }
370 "miri_start_unwind" => {
371 let [payload] =
372 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
373 this.handle_miri_start_unwind(payload)?;
374 return interp_ok(EmulateItemResult::NeedsUnwind);
375 }
376 "miri_run_provenance_gc" => {
377 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
378 this.run_provenance_gc();
379 }
380 "miri_get_alloc_id" => {
381 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
382 let ptr = this.read_pointer(ptr)?;
383 let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr, 0).map_err_kind(|_e| {
384 err_machine_stop!(TerminationInfo::Abort(format!(
385 "pointer passed to `miri_get_alloc_id` must not be dangling, got {ptr:?}"
386 )))
387 })?;
388 this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?;
389 }
390 "miri_print_borrow_state" => {
391 let [id, show_unnamed] =
392 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
393 let id = this.read_scalar(id)?.to_u64()?;
394 let show_unnamed = this.read_scalar(show_unnamed)?.to_bool()?;
395 if let Some(id) = std::num::NonZero::new(id).map(AllocId)
396 && this.get_alloc_info(id).kind == AllocKind::LiveData
397 {
398 this.print_borrow_state(id, show_unnamed)?;
399 } else {
400 eprintln!("{id} is not the ID of a live data allocation");
401 }
402 }
403 "miri_pointer_name" => {
404 let [ptr, nth_parent, name] =
407 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
408 let ptr = this.read_pointer(ptr)?;
409 let nth_parent = this.read_scalar(nth_parent)?.to_u8()?;
410 let name = this.read_immediate(name)?;
411
412 let name = this.read_byte_slice(&name)?;
413 let name = String::from_utf8_lossy(name).into_owned();
417 this.give_pointer_debug_name(ptr, nth_parent, &name)?;
418 }
419 "miri_static_root" => {
420 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
421 let ptr = this.read_pointer(ptr)?;
422 let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr, 0)?;
423 if offset != Size::ZERO {
424 throw_unsup_format!(
425 "pointer passed to `miri_static_root` must point to beginning of an allocated block"
426 );
427 }
428 this.machine.static_roots.push(alloc_id);
429 }
430 "miri_host_to_target_path" => {
431 let [ptr, out, out_size] =
432 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
433 let ptr = this.read_pointer(ptr)?;
434 let out = this.read_pointer(out)?;
435 let out_size = this.read_scalar(out_size)?.to_target_usize(this)?;
436
437 this.check_no_isolation("`miri_host_to_target_path`")?;
439
440 let path = this.read_os_str_from_c_str(ptr)?.to_owned();
442 let (success, needed_size) =
443 this.write_path_to_c_str(Path::new(&path), out, out_size)?;
444 this.write_int(if success { 0 } else { needed_size }, dest)?;
446 }
447 "miri_thread_spawn" => {
448 let [start_routine, func_arg] =
450 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
451 let start_routine = this.read_pointer(start_routine)?;
452 let func_arg = this.read_immediate(func_arg)?;
453
454 this.start_regular_thread(
455 Some(dest.clone()),
456 start_routine,
457 ExternAbi::Rust,
458 func_arg,
459 this.machine.layouts.unit,
460 )?;
461 }
462 "miri_thread_join" => {
463 let [thread_id] = this.check_shim_sig(
464 shim_sig!(extern "Rust" fn(usize) -> bool),
465 link_name,
466 abi,
467 args,
468 )?;
469
470 let thread = this.read_target_usize(thread_id)?;
471 use crate::concurrency::thread::ThreadLookupError;
473 let thread = match this.thread_id_try_from(thread) {
474 Ok(id) | Err(ThreadLookupError::Terminated(id)) => Some(id),
475 Err(ThreadLookupError::InvalidId) => None,
476 };
477 if let Some(thread) = thread {
478 this.join_thread_exclusive(
479 thread,
480 Scalar::from_bool(true),
481 dest,
482 )?;
483 } else {
484 this.write_scalar(Scalar::from_bool(false), dest)?;
485 }
486 }
487 "miri_spin_loop" => {
489 let [] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
490
491 this.yield_active_thread();
493 }
494 "miri_backtrace_size" => {
496 this.handle_miri_backtrace_size(abi, link_name, args, dest)?;
497 }
498 "miri_get_backtrace" => {
500 this.handle_miri_get_backtrace(abi, link_name, args)?;
502 }
503 "miri_resolve_frame" => {
505 this.handle_miri_resolve_frame(abi, link_name, args, dest)?;
507 }
508 "miri_resolve_frame_names" => {
510 this.handle_miri_resolve_frame_names(abi, link_name, args)?;
511 }
512 "miri_write_to_stdout" | "miri_write_to_stderr" => {
515 let [msg] = this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
516 let msg = this.read_immediate(msg)?;
517 let msg = this.read_byte_slice(&msg)?;
518 let _ignore = match link_name.as_str() {
520 "miri_write_to_stdout" => std::io::stdout().write_all(msg),
521 "miri_write_to_stderr" => std::io::stderr().write_all(msg),
522 _ => unreachable!(),
523 };
524 }
525 "miri_promise_symbolic_alignment" => {
527 use rustc_abi::AlignFromBytesError;
528
529 let [ptr, align] =
530 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
531 let ptr = this.read_pointer(ptr)?;
532 let align = this.read_target_usize(align)?;
533 if !align.is_power_of_two() {
534 throw_unsup_format!(
535 "`miri_promise_symbolic_alignment`: alignment must be a power of 2, got {align}"
536 );
537 }
538 let align = Align::from_bytes(align).unwrap_or_else(|err| {
539 match err {
540 AlignFromBytesError::NotPowerOfTwo(_) => unreachable!(),
541 AlignFromBytesError::TooLarge(_) => Align::MAX,
543 }
544 });
545 let addr = ptr.addr();
546 if addr.bytes().strict_rem(align.bytes()) != 0 {
548 throw_unsup_format!(
549 "`miri_promise_symbolic_alignment`: pointer is not actually aligned"
550 );
551 }
552 if let Ok((alloc_id, offset, ..)) = this.ptr_try_get_alloc_id(ptr, 0) {
553 let alloc_align = this.get_alloc_info(alloc_id).align;
554 if align > alloc_align
557 && this
558 .machine
559 .symbolic_alignment
560 .get_mut()
561 .get(&alloc_id)
562 .is_none_or(|&(_, old_align)| align > old_align)
563 {
564 this.machine.symbolic_alignment.get_mut().insert(alloc_id, (offset, align));
565 }
566 }
567 }
568 "miri_genmc_assume" => {
570 let [condition] =
571 this.check_shim_sig_lenient(abi, CanonAbi::Rust, link_name, args)?;
572 if this.machine.data_race.as_genmc_ref().is_some() {
573 this.handle_genmc_verifier_assume(condition)?;
574 } else {
575 throw_unsup_format!("miri_genmc_assume is only supported in GenMC mode")
576 }
577 }
578
579 "exit" => {
581 let [code] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
583 let code = this.read_scalar(code)?.to_i32()?;
584 if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
585 genmc_ctx.handle_exit(
587 this.machine.threads.active_thread(),
588 code,
589 crate::concurrency::ExitType::ExitCalled,
590 )?;
591 return interp_ok(EmulateItemResult::AlreadyJumped);
592 }
593 throw_machine_stop!(TerminationInfo::Exit { code, leak_check: false });
594 }
595 "abort" => {
596 let [] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
598 throw_machine_stop!(TerminationInfo::Abort(
599 "the program aborted execution".to_owned()
600 ));
601 }
602
603 "malloc" => {
605 let [size] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
606 let size = this.read_target_usize(size)?;
607 if size <= this.max_size_of_val().bytes() {
608 let res = this.malloc(size, AllocInit::Uninit)?;
609 this.write_pointer(res, dest)?;
610 } else {
611 if this.target_os_is_unix() {
613 this.set_last_error(LibcError("ENOMEM"))?;
614 }
615 this.write_null(dest)?;
616 }
617 }
618 "calloc" => {
619 let [items, elem_size] =
620 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
621 let items = this.read_target_usize(items)?;
622 let elem_size = this.read_target_usize(elem_size)?;
623 if let Some(size) = this.compute_size_in_bytes(Size::from_bytes(elem_size), items) {
624 let res = this.malloc(size.bytes(), AllocInit::Zero)?;
625 this.write_pointer(res, dest)?;
626 } else {
627 if this.target_os_is_unix() {
629 this.set_last_error(LibcError("ENOMEM"))?;
630 }
631 this.write_null(dest)?;
632 }
633 }
634 "free" => {
635 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
636 let ptr = this.read_pointer(ptr)?;
637 this.free(ptr)?;
638 }
639 "realloc" => {
640 let [old_ptr, new_size] =
641 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
642 let old_ptr = this.read_pointer(old_ptr)?;
643 let new_size = this.read_target_usize(new_size)?;
644 if new_size <= this.max_size_of_val().bytes() {
645 let res = this.realloc(old_ptr, new_size)?;
646 this.write_pointer(res, dest)?;
647 } else {
648 if this.target_os_is_unix() {
650 this.set_last_error(LibcError("ENOMEM"))?;
651 }
652 this.write_null(dest)?;
653 }
654 }
655
656 "memcmp" => {
658 let [left, right, n] =
659 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
660 let left = this.read_pointer(left)?;
661 let right = this.read_pointer(right)?;
662 let n = Size::from_bytes(this.read_target_usize(n)?);
663
664 this.ptr_get_alloc_id(left, 0)?;
666 this.ptr_get_alloc_id(right, 0)?;
667
668 let result = {
673 let left_bytes = this.read_bytes_ptr_strip_provenance(left, n)?;
674 let right_bytes = this.read_bytes_ptr_strip_provenance(right, n)?;
675
676 use std::cmp::Ordering::*;
677 match left_bytes.cmp(right_bytes) {
678 Less => -1i32,
679 Equal => 0,
680 Greater => 1,
681 }
682 };
683
684 this.write_scalar(Scalar::from_i32(result), dest)?;
685 }
686 "memchr" => {
687 let [ptr, val, num] =
688 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
689 let ptr = this.read_pointer(ptr)?;
690 let val = this.read_scalar(val)?.to_i32()?;
691 let num = this.read_target_usize(num)?;
692 #[expect(clippy::as_conversions)]
694 let val = val as u8;
695
696 this.ptr_get_alloc_id(ptr, 0)?;
698
699 let needle_ptr = this.memchr(ptr, 0..num, val)?.map(|(_idx, ptr)| ptr);
702
703 if let Some(needle_ptr) = needle_ptr {
704 this.write_pointer(needle_ptr, dest)?;
705 } else {
706 this.write_null(dest)?;
707 }
708 }
709 "memrchr" => {
710 this.check_target_os(&[Os::Linux, Os::Android, Os::FreeBsd], link_name)?;
711
712 let [ptr, val, num] =
713 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
714 let ptr = this.read_pointer(ptr)?;
715 let val = this.read_scalar(val)?.to_i32()?;
716 let num = this.read_target_usize(num)?;
717 #[expect(clippy::as_conversions)]
719 let val = val as u8;
720
721 this.ptr_get_alloc_id(ptr, 0)?;
723
724 let needle_ptr = this.memchr(ptr, (0..num).rev(), val)?.map(|(_idx, ptr)| ptr);
726
727 if let Some(needle_ptr) = needle_ptr {
728 this.write_pointer(needle_ptr, dest)?;
729 } else {
730 this.write_null(dest)?;
731 }
732 }
733 "strlen" => {
734 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
735 let ptr = this.read_pointer(ptr)?;
736 let n = this.read_c_str(ptr)?.len();
738 this.write_scalar(
739 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
740 dest,
741 )?;
742 }
743 "strnlen" => {
744 let [ptr, num] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
745 let ptr = this.read_pointer(ptr)?;
746 let num = this.read_target_usize(num)?;
747
748 this.ptr_get_alloc_id(ptr, 0)?;
750
751 let idx = this.memchr(ptr, 0..num, 0)?.map(|(idx, _ptr)| idx).unwrap_or(num);
754 this.write_scalar(Scalar::from_target_usize(idx, this), dest)?;
755 }
756 "wcslen" => {
757 let [ptr] = this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
758 let ptr = this.read_pointer(ptr)?;
759 let n = this.read_wchar_t_str(ptr)?.len();
761 this.write_scalar(
762 Scalar::from_target_usize(u64::try_from(n).unwrap(), this),
763 dest,
764 )?;
765 }
766 "memcpy" => {
767 let [ptr_dest, ptr_src, n] =
768 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
769 let ptr_dest = this.read_pointer(ptr_dest)?;
770 let ptr_src = this.read_pointer(ptr_src)?;
771 let n = this.read_target_usize(n)?;
772
773 this.ptr_get_alloc_id(ptr_dest, 0)?;
776 this.ptr_get_alloc_id(ptr_src, 0)?;
777
778 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
779 this.write_pointer(ptr_dest, dest)?;
780 }
781 "strcpy" => {
782 let [ptr_dest, ptr_src] =
783 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
784 let ptr_dest = this.read_pointer(ptr_dest)?;
785 let ptr_src = this.read_pointer(ptr_src)?;
786
787 let n = this.read_c_str(ptr_src)?.len().strict_add(1);
794 this.mem_copy(ptr_src, ptr_dest, Size::from_bytes(n), true)?;
795 this.write_pointer(ptr_dest, dest)?;
796 }
797 "memset" => {
798 let [ptr_dest, val, n] =
799 this.check_shim_sig_lenient(abi, CanonAbi::C, link_name, args)?;
800 let ptr_dest = this.read_pointer(ptr_dest)?;
801 let val = this.read_scalar(val)?.to_i32()?;
802 let n = this.read_target_usize(n)?;
803 #[expect(clippy::as_conversions)]
805 let val = val as u8;
806
807 this.ptr_get_alloc_id(ptr_dest, 0)?;
809
810 let bytes = std::iter::repeat_n(val, n.try_into().unwrap());
811 this.write_bytes_ptr(ptr_dest, bytes)?;
812 this.write_pointer(ptr_dest, dest)?;
813 }
814
815 _ => {
817 if let res = shims::math::EvalContextExt::emulate_foreign_item_inner(
819 this, link_name, abi, args, dest,
820 )? && !matches!(res, EmulateItemResult::NotSupported)
821 {
822 return interp_ok(res);
823 }
824
825 return match &this.tcx.sess.target.os {
827 _ if this.target_os_is_unix() =>
828 shims::unix::foreign_items::EvalContextExt::emulate_foreign_item_inner(
829 this, link_name, abi, args, dest,
830 ),
831 Os::Windows =>
832 shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_inner(
833 this, link_name, abi, args, dest,
834 ),
835 _ => interp_ok(EmulateItemResult::NotSupported),
836 };
837 }
838 };
839 interp_ok(EmulateItemResult::NeedsReturn)
842 }
843
844 fn memchr(
847 &self,
848 ptr: Pointer,
849 idxs: impl Iterator<Item = u64>,
850 needle: u8,
851 ) -> InterpResult<'tcx, Option<(u64, Pointer)>> {
852 let this = self.eval_context_ref();
853 for idx in idxs {
854 let ptr = ptr.wrapping_offset(Size::from_bytes(idx), this);
855 let place = this.ptr_to_mplace(ptr, this.machine.layouts.u8);
856 let val = this.read_scalar(&place)?.to_u8()?;
857 if val == needle {
858 return interp_ok(Some((idx, ptr)));
859 }
860 }
861 interp_ok(None)
862 }
863}