1 use std::{iter, convert::TryInto};
3 use rustc::hir::def_id::DefId;
5 use rustc::ty::layout::{Align, LayoutOf, Size};
6 use rustc_apfloat::Float;
8 use syntax::symbol::sym;
12 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
13 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
14 /// Returns the minimum alignment for the target architecture for allocations of the given size.
15 fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
16 let this = self.eval_context_ref();
17 // List taken from `libstd/sys_common/alloc.rs`.
18 let min_align = match this.tcx.tcx.sess.target.target.arch.as_str() {
19 "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
20 "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
21 arch => bug!("Unsupported target architecture: {}", arch),
23 // Windows always aligns, even small allocations.
24 // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
25 // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
26 if kind == MiriMemoryKind::WinHeap || size >= min_align {
27 return Align::from_bytes(min_align).unwrap();
29 // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
30 fn prev_power_of_two(x: u64) -> u64 {
31 let next_pow2 = x.next_power_of_two();
33 // x *is* a power of two, just use that.
36 // x is between two powers, so next = 2*prev.
40 Align::from_bytes(prev_power_of_two(size)).unwrap()
43 fn malloc(&mut self, size: u64, zero_init: bool, kind: MiriMemoryKind) -> Scalar<Tag> {
44 let this = self.eval_context_mut();
46 Scalar::from_int(0, this.pointer_size())
48 let align = this.min_align(size, kind);
51 .allocate(Size::from_bytes(size), align, kind.into());
53 // We just allocated this, the access is definitely in-bounds.
55 .write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize))
62 fn free(&mut self, ptr: Scalar<Tag>, kind: MiriMemoryKind) -> InterpResult<'tcx> {
63 let this = self.eval_context_mut();
64 if !this.is_null(ptr)? {
65 let ptr = this.force_ptr(ptr)?;
66 this.memory.deallocate(ptr, None, kind.into())?;
76 ) -> InterpResult<'tcx, Scalar<Tag>> {
77 let this = self.eval_context_mut();
78 let new_align = this.min_align(new_size, kind);
79 if this.is_null(old_ptr)? {
81 Ok(Scalar::from_int(0, this.pointer_size()))
85 .allocate(Size::from_bytes(new_size), new_align, kind.into());
86 Ok(Scalar::Ptr(new_ptr))
89 let old_ptr = this.force_ptr(old_ptr)?;
91 this.memory.deallocate(old_ptr, None, kind.into())?;
92 Ok(Scalar::from_int(0, this.pointer_size()))
94 let new_ptr = this.memory.reallocate(
97 Size::from_bytes(new_size),
101 Ok(Scalar::Ptr(new_ptr))
106 /// Emulates calling a foreign item, failing if the item is not supported.
107 /// This function will handle `goto_block` if needed.
108 fn emulate_foreign_item(
111 args: &[OpTy<'tcx, Tag>],
112 dest: Option<PlaceTy<'tcx, Tag>>,
113 ret: Option<mir::BasicBlock>,
114 ) -> InterpResult<'tcx> {
115 let this = self.eval_context_mut();
116 let attrs = this.tcx.get_attrs(def_id);
117 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
118 Some(name) => name.as_str(),
119 None => this.tcx.item_name(def_id).as_str(),
121 // Strip linker suffixes (seen on 32-bit macOS).
122 let link_name = link_name.trim_end_matches("$UNIX2003");
123 let tcx = &{ this.tcx.tcx };
125 // First: functions that diverge.
127 "__rust_start_panic" | "panic_impl" => {
128 throw_unsup_format!("the evaluated program panicked");
130 "exit" | "ExitProcess" => {
131 // it's really u32 for ExitProcess, but we have to put it into the `Exit` error variant anyway
132 let code = this.read_scalar(args[0])?.to_i32()?;
133 return Err(InterpError::Exit(code).into());
137 throw_unsup_format!("can't call (diverging) foreign function: {}", link_name);
142 // Next: functions that assume a ret and dest.
143 let dest = dest.expect("we already checked for a dest");
144 let ret = ret.expect("dest is `Some` but ret is `None`");
147 let size = this.read_scalar(args[0])?.to_usize(this)?;
148 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
149 this.write_scalar(res, dest)?;
152 let items = this.read_scalar(args[0])?.to_usize(this)?;
153 let len = this.read_scalar(args[1])?.to_usize(this)?;
156 .ok_or_else(|| err_panic!(Overflow(mir::BinOp::Mul)))?;
157 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
158 this.write_scalar(res, dest)?;
160 "posix_memalign" => {
161 let ret = this.deref_operand(args[0])?;
162 let align = this.read_scalar(args[1])?.to_usize(this)?;
163 let size = this.read_scalar(args[2])?.to_usize(this)?;
164 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
165 if !align.is_power_of_two() {
166 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
168 if align < this.pointer_size().bytes() {
170 "posix_memalign: alignment must be at least the size of a pointer, but is {}",
176 this.write_null(ret.into())?;
178 let ptr = this.memory.allocate(
179 Size::from_bytes(size),
180 Align::from_bytes(align).unwrap(),
181 MiriMemoryKind::C.into(),
183 this.write_scalar(Scalar::Ptr(ptr), ret.into())?;
185 this.write_null(dest)?;
188 let ptr = this.read_scalar(args[0])?.not_undef()?;
189 this.free(ptr, MiriMemoryKind::C)?;
192 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
193 let new_size = this.read_scalar(args[1])?.to_usize(this)?;
194 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
195 this.write_scalar(res, dest)?;
199 let size = this.read_scalar(args[0])?.to_usize(this)?;
200 let align = this.read_scalar(args[1])?.to_usize(this)?;
202 throw_unsup!(HeapAllocZeroBytes);
204 if !align.is_power_of_two() {
205 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
207 let ptr = this.memory.allocate(
208 Size::from_bytes(size),
209 Align::from_bytes(align).unwrap(),
210 MiriMemoryKind::Rust.into(),
212 this.write_scalar(Scalar::Ptr(ptr), dest)?;
214 "__rust_alloc_zeroed" => {
215 let size = this.read_scalar(args[0])?.to_usize(this)?;
216 let align = this.read_scalar(args[1])?.to_usize(this)?;
218 throw_unsup!(HeapAllocZeroBytes);
220 if !align.is_power_of_two() {
221 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
223 let ptr = this.memory.allocate(
224 Size::from_bytes(size),
225 Align::from_bytes(align).unwrap(),
226 MiriMemoryKind::Rust.into(),
228 // We just allocated this, the access is definitely in-bounds.
230 .write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize))
232 this.write_scalar(Scalar::Ptr(ptr), dest)?;
234 "__rust_dealloc" => {
235 let ptr = this.read_scalar(args[0])?.not_undef()?;
236 let old_size = this.read_scalar(args[1])?.to_usize(this)?;
237 let align = this.read_scalar(args[2])?.to_usize(this)?;
239 throw_unsup!(HeapAllocZeroBytes);
241 if !align.is_power_of_two() {
242 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
244 let ptr = this.force_ptr(ptr)?;
245 this.memory.deallocate(
248 Size::from_bytes(old_size),
249 Align::from_bytes(align).unwrap(),
251 MiriMemoryKind::Rust.into(),
254 "__rust_realloc" => {
255 let ptr = this.read_scalar(args[0])?.to_ptr()?;
256 let old_size = this.read_scalar(args[1])?.to_usize(this)?;
257 let align = this.read_scalar(args[2])?.to_usize(this)?;
258 let new_size = this.read_scalar(args[3])?.to_usize(this)?;
259 if old_size == 0 || new_size == 0 {
260 throw_unsup!(HeapAllocZeroBytes);
262 if !align.is_power_of_two() {
263 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
265 let align = Align::from_bytes(align).unwrap();
266 let new_ptr = this.memory.reallocate(
268 Some((Size::from_bytes(old_size), align)),
269 Size::from_bytes(new_size),
271 MiriMemoryKind::Rust.into(),
273 this.write_scalar(Scalar::Ptr(new_ptr), dest)?;
277 let sys_getrandom = this
278 .eval_path_scalar(&["libc", "SYS_getrandom"])?
279 .expect("Failed to get libc::SYS_getrandom")
282 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
283 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
284 match this.read_scalar(args[0])?.to_usize(this)? {
285 id if id == sys_getrandom => {
286 // The first argument is the syscall id,
288 linux_getrandom(this, &args[1..], dest)?;
290 id => throw_unsup_format!("miri does not support syscall ID {}", id),
295 linux_getrandom(this, args, dest)?;
299 let _handle = this.read_scalar(args[0])?;
300 let symbol = this.read_scalar(args[1])?.not_undef()?;
301 let symbol_name = this.memory.read_c_str(symbol)?;
302 let err = format!("bad c unicode symbol: {:?}", symbol_name);
303 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
304 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
305 let ptr = this.memory.create_fn_alloc(FnVal::Other(dlsym));
306 this.write_scalar(Scalar::from(ptr), dest)?;
308 this.write_null(dest)?;
312 "__rust_maybe_catch_panic" => {
313 // fn __rust_maybe_catch_panic(
316 // data_ptr: *mut usize,
317 // vtable_ptr: *mut usize,
319 // We abort on panic, so not much is going on here, but we still have to call the closure.
320 let f = this.read_scalar(args[0])?.not_undef()?;
321 let data = this.read_scalar(args[1])?.not_undef()?;
322 let f_instance = this.memory.get_fn(f)?.as_instance()?;
323 this.write_null(dest)?;
324 trace!("__rust_maybe_catch_panic: {:?}", f_instance);
326 // Now we make a function call.
327 // TODO: consider making this reusable? `InterpCx::step` does something similar
328 // for the TLS destructors, and of course `eval_main`.
329 let mir = this.load_mir(f_instance.def, None)?;
331 MPlaceTy::dangling(this.layout_of(tcx.mk_unit())?, this).into();
332 this.push_stack_frame(
337 // Directly return to caller.
338 StackPopCleanup::Goto(Some(ret)),
340 let mut args = this.frame().body.args_iter();
344 .expect("Argument to __rust_maybe_catch_panic does not take enough arguments.");
345 let arg_dest = this.local_place(arg_local)?;
346 this.write_scalar(data, arg_dest)?;
348 args.next().expect_none("__rust_maybe_catch_panic argument has more arguments than expected");
350 // We ourselves will return `0`, eventually (because we will not return if we paniced).
351 this.write_null(dest)?;
353 // Don't fall through, we do *not* want to `goto_block`!
358 let left = this.read_scalar(args[0])?.not_undef()?;
359 let right = this.read_scalar(args[1])?.not_undef()?;
360 let n = Size::from_bytes(this.read_scalar(args[2])?.to_usize(this)?);
363 let left_bytes = this.memory.read_bytes(left, n)?;
364 let right_bytes = this.memory.read_bytes(right, n)?;
366 use std::cmp::Ordering::*;
367 match left_bytes.cmp(right_bytes) {
374 this.write_scalar(Scalar::from_int(result, Size::from_bits(32)), dest)?;
378 let ptr = this.read_scalar(args[0])?.not_undef()?;
379 let val = this.read_scalar(args[1])?.to_i32()? as u8;
380 let num = this.read_scalar(args[2])?.to_usize(this)?;
381 if let Some(idx) = this
383 .read_bytes(ptr, Size::from_bytes(num))?
386 .position(|&c| c == val)
388 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
389 this.write_scalar(new_ptr, dest)?;
391 this.write_null(dest)?;
396 let ptr = this.read_scalar(args[0])?.not_undef()?;
397 let val = this.read_scalar(args[1])?.to_i32()? as u8;
398 let num = this.read_scalar(args[2])?.to_usize(this)?;
401 .read_bytes(ptr, Size::from_bytes(num))?
403 .position(|&c| c == val);
404 if let Some(idx) = idx {
405 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
406 this.write_scalar(new_ptr, dest)?;
408 this.write_null(dest)?;
412 "__errno_location" | "__error" => {
413 let errno_place = this.machine.last_error.unwrap();
414 this.write_scalar(errno_place.to_ref().to_scalar()?, dest)?;
418 let result = this.getenv(args[0])?;
419 this.write_scalar(result, dest)?;
423 let result = this.unsetenv(args[0])?;
424 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
428 let result = this.setenv(args[0], args[1])?;
429 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
433 let result = this.getcwd(args[0], args[1])?;
434 this.write_scalar(result, dest)?;
438 let result = this.chdir(args[0])?;
439 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
442 "open" | "open64" => {
443 let result = this.open(args[0], args[1])?;
444 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
448 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
449 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
452 "close" | "close$NOCANCEL" => {
453 let result = this.close(args[0])?;
454 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
458 let result = this.read(args[0], args[1], args[2])?;
459 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
463 let fd = this.read_scalar(args[0])?.to_i32()?;
464 let buf = this.read_scalar(args[1])?.not_undef()?;
465 let n = this.read_scalar(args[2])?.to_usize(tcx)?;
466 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
467 let result = if fd == 1 || fd == 2 {
469 use std::io::{self, Write};
471 let buf_cont = this.memory.read_bytes(buf, Size::from_bytes(n))?;
472 // We need to flush to make sure this actually appears on the screen
473 let res = if fd == 1 {
474 // Stdout is buffered, flush to make sure it appears on the screen.
475 // This is the write() syscall of the interpreted program, we want it
476 // to correspond to a write() syscall on the host -- there is no good
477 // in adding extra buffering here.
478 let res = io::stdout().write(buf_cont);
479 io::stdout().flush().unwrap();
482 // No need to flush, stderr is not buffered.
483 io::stderr().write(buf_cont)
490 this.write(args[0], args[1], args[2])?
492 // Now, `result` is the value we return back to the program.
493 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
497 let result = this.unlink(args[0])?;
498 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
502 let result = this.clock_gettime(args[0], args[1])?;
503 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
507 let result = this.gettimeofday(args[0], args[1])?;
508 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
512 let ptr = this.read_scalar(args[0])?.not_undef()?;
513 let n = this.memory.read_c_str(ptr)?.len();
514 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
518 "cbrtf" | "coshf" | "sinhf" | "tanf" => {
519 // FIXME: Using host floats.
520 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
521 let f = match link_name {
528 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
530 // underscore case for windows
531 "_hypotf" | "hypotf" | "atan2f" => {
532 // FIXME: Using host floats.
533 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
534 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
535 let n = match link_name {
536 "_hypotf" | "hypotf" => f1.hypot(f2),
537 "atan2f" => f1.atan2(f2),
540 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
543 "cbrt" | "cosh" | "sinh" | "tan" => {
544 // FIXME: Using host floats.
545 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
546 let f = match link_name {
553 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
555 // underscore case for windows, here and below
556 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
557 "_hypot" | "hypot" | "atan2" => {
558 // FIXME: Using host floats.
559 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
560 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
561 let n = match link_name {
562 "_hypot" | "hypot" => f1.hypot(f2),
563 "atan2" => f1.atan2(f2),
566 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
568 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
569 "_ldexp" | "ldexp" | "scalbn" => {
570 let x = this.read_scalar(args[0])?.to_f64()?;
571 let exp = this.read_scalar(args[1])?.to_i32()?;
573 // Saturating cast to i16. Even those are outside the valid exponent range to
574 // `scalbn` below will do its over/underflow handling.
575 let exp = if exp > i16::max_value() as i32 {
577 } else if exp < i16::min_value() as i32 {
580 exp.try_into().unwrap()
583 let res = x.scalbn(exp);
584 this.write_scalar(Scalar::from_f64(res), dest)?;
587 // Some things needed for `sys::thread` initialization to go through.
588 "signal" | "sigaction" | "sigaltstack" => {
589 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
593 let name = this.read_scalar(args[0])?.to_i32()?;
595 trace!("sysconf() called with name {}", name);
596 // TODO: Cache the sysconf integers via Miri's global cache.
599 &["libc", "_SC_PAGESIZE"],
600 Scalar::from_int(PAGE_SIZE, dest.layout.size),
603 &["libc", "_SC_GETPW_R_SIZE_MAX"],
604 Scalar::from_int(-1, dest.layout.size),
607 &["libc", "_SC_NPROCESSORS_ONLN"],
608 Scalar::from_int(NUM_CPUS, dest.layout.size),
611 let mut result = None;
612 for &(path, path_value) in paths {
613 if let Some(val) = this.eval_path_scalar(path)? {
614 let val = val.to_i32()?;
616 result = Some(path_value);
621 if let Some(result) = result {
622 this.write_scalar(result, dest)?;
624 throw_unsup_format!("Unimplemented sysconf name: {}", name)
628 "sched_getaffinity" => {
629 // Return an error; `num_cpus` then falls back to `sysconf`.
630 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
634 this.write_null(dest)?;
637 // Hook pthread calls that go to the thread-local storage memory subsystem.
638 "pthread_key_create" => {
639 let key_place = this.deref_operand(args[0])?;
641 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
642 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
643 Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
647 // Figure out how large a pthread TLS key actually is.
648 // This is `libc::pthread_key_t`.
649 let key_type = args[0].layout.ty
651 .ok_or_else(|| err_ub_format!(
652 "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
655 let key_layout = this.layout_of(key_type)?;
657 // Create key and write it into the memory where `key_ptr` wants it.
658 let key = this.machine.tls.create_tls_key(dtor) as u128;
659 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
661 throw_unsup!(OutOfTls);
664 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
666 // Return success (`0`).
667 this.write_null(dest)?;
669 "pthread_key_delete" => {
670 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
671 this.machine.tls.delete_tls_key(key)?;
672 // Return success (0)
673 this.write_null(dest)?;
675 "pthread_getspecific" => {
676 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
677 let ptr = this.machine.tls.load_tls(key, tcx)?;
678 this.write_scalar(ptr, dest)?;
680 "pthread_setspecific" => {
681 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
682 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
683 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
685 // Return success (`0`).
686 this.write_null(dest)?;
689 // Stack size/address stuff.
691 | "pthread_attr_destroy"
693 | "pthread_attr_setstacksize" => {
694 this.write_null(dest)?;
696 "pthread_attr_getstack" => {
697 let addr_place = this.deref_operand(args[1])?;
698 let size_place = this.deref_operand(args[2])?;
701 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
705 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
709 // Return success (`0`).
710 this.write_null(dest)?;
713 // We don't support threading. (Also for Windows.)
714 "pthread_create" | "CreateThread" => {
715 throw_unsup_format!("Miri does not support threading");
718 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
719 "pthread_mutexattr_init"
720 | "pthread_mutexattr_settype"
721 | "pthread_mutex_init"
722 | "pthread_mutexattr_destroy"
723 | "pthread_mutex_lock"
724 | "pthread_mutex_unlock"
725 | "pthread_mutex_destroy"
726 | "pthread_rwlock_rdlock"
727 | "pthread_rwlock_unlock"
728 | "pthread_rwlock_wrlock"
729 | "pthread_rwlock_destroy"
730 | "pthread_condattr_init"
731 | "pthread_condattr_setclock"
732 | "pthread_cond_init"
733 | "pthread_condattr_destroy"
734 | "pthread_cond_destroy" => {
735 this.write_null(dest)?;
738 // We don't support fork so we don't have to do anything for atfork.
739 "pthread_atfork" => {
740 this.write_null(dest)?;
744 // This is a horrible hack, but since the guard page mechanism calls mmap and expects a particular return value, we just give it that value.
745 let addr = this.read_scalar(args[0])?.not_undef()?;
746 this.write_scalar(addr, dest)?;
749 this.write_null(dest)?;
753 "pthread_attr_get_np" | "pthread_getattr_np" => {
754 this.write_null(dest)?;
756 "pthread_get_stackaddr_np" => {
757 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
758 this.write_scalar(stack_addr, dest)?;
760 "pthread_get_stacksize_np" => {
761 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
762 this.write_scalar(stack_size, dest)?;
765 // FIXME: register the destructor.
768 this.write_scalar(Scalar::Ptr(this.machine.argc.unwrap()), dest)?;
771 this.write_scalar(Scalar::Ptr(this.machine.argv.unwrap()), dest)?;
773 "SecRandomCopyBytes" => {
774 let len = this.read_scalar(args[1])?.to_usize(this)?;
775 let ptr = this.read_scalar(args[2])?.not_undef()?;
776 this.gen_random(ptr, len as usize)?;
777 this.write_null(dest)?;
780 // Windows API stubs.
782 // DWORD = ULONG = u32
784 "GetProcessHeap" => {
785 // Just fake a HANDLE
786 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
789 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
790 let flags = this.read_scalar(args[1])?.to_u32()?;
791 let size = this.read_scalar(args[2])?.to_usize(this)?;
792 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
793 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
794 this.write_scalar(res, dest)?;
797 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
798 let _flags = this.read_scalar(args[1])?.to_u32()?;
799 let ptr = this.read_scalar(args[2])?.not_undef()?;
800 this.free(ptr, MiriMemoryKind::WinHeap)?;
801 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
804 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
805 let _flags = this.read_scalar(args[1])?.to_u32()?;
806 let ptr = this.read_scalar(args[2])?.not_undef()?;
807 let size = this.read_scalar(args[3])?.to_usize(this)?;
808 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
809 this.write_scalar(res, dest)?;
813 this.set_last_error(this.read_scalar(args[0])?.not_undef()?)?;
816 let last_error = this.get_last_error()?;
817 this.write_scalar(last_error, dest)?;
820 "AddVectoredExceptionHandler" => {
821 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
822 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
824 "InitializeCriticalSection"
825 | "EnterCriticalSection"
826 | "LeaveCriticalSection"
827 | "DeleteCriticalSection" => {
828 // Nothing to do, not even a return value.
832 | "TryEnterCriticalSection"
833 | "GetConsoleScreenBufferInfo"
834 | "SetConsoleTextAttribute" => {
835 // Pretend these do not exist / nothing happened, by returning zero.
836 this.write_null(dest)?;
839 let system_info = this.deref_operand(args[0])?;
840 // Initialize with `0`.
842 .write_bytes(system_info.ptr, iter::repeat(0u8).take(system_info.layout.size.bytes() as usize))?;
843 // Set number of processors.
844 let dword_size = Size::from_bytes(4);
845 let num_cpus = this.mplace_field(system_info, 6)?;
847 Scalar::from_int(NUM_CPUS, dword_size),
853 // This just creates a key; Windows does not natively support TLS destructors.
855 // Create key and return it.
856 let key = this.machine.tls.create_tls_key(None) as u128;
858 // Figure out how large a TLS key actually is. This is `c::DWORD`.
859 if dest.layout.size.bits() < 128
860 && key >= (1u128 << dest.layout.size.bits() as u128)
862 throw_unsup!(OutOfTls);
864 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
867 let key = this.read_scalar(args[0])?.to_u32()? as u128;
868 let ptr = this.machine.tls.load_tls(key, tcx)?;
869 this.write_scalar(ptr, dest)?;
872 let key = this.read_scalar(args[0])?.to_u32()? as u128;
873 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
874 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
876 // Return success (`1`).
877 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
880 let which = this.read_scalar(args[0])?.to_i32()?;
881 // We just make this the identity function, so we know later in `WriteFile`
883 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
886 let handle = this.read_scalar(args[0])?.to_isize(this)?;
887 let buf = this.read_scalar(args[1])?.not_undef()?;
888 let n = this.read_scalar(args[2])?.to_u32()?;
889 let written_place = this.deref_operand(args[3])?;
890 // Spec says to always write `0` first.
891 this.write_null(written_place.into())?;
892 let written = if handle == -11 || handle == -12 {
894 use std::io::{self, Write};
898 .read_bytes(buf, Size::from_bytes(u64::from(n)))?;
899 let res = if handle == -11 {
900 io::stdout().write(buf_cont)
902 io::stderr().write(buf_cont)
904 res.ok().map(|n| n as u32)
906 eprintln!("Miri: Ignored output to handle {}", handle);
907 // Pretend it all went well.
910 // If there was no error, write back how much was written.
911 if let Some(n) = written {
912 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
914 // Return whether this was a success.
916 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
920 "GetConsoleMode" => {
921 // Everything is a pipe.
922 this.write_null(dest)?;
924 "GetEnvironmentVariableW" => {
925 // This is not the env var you are looking for.
926 this.set_last_error(Scalar::from_u32(203))?; // ERROR_ENVVAR_NOT_FOUND
927 this.write_null(dest)?;
929 "GetCommandLineW" => {
930 this.write_scalar(Scalar::Ptr(this.machine.cmd_line.unwrap()), dest)?;
932 // The actual name of 'RtlGenRandom'
933 "SystemFunction036" => {
934 let ptr = this.read_scalar(args[0])?.not_undef()?;
935 let len = this.read_scalar(args[1])?.to_u32()?;
936 this.gen_random(ptr, len as usize)?;
937 this.write_scalar(Scalar::from_bool(true), dest)?;
940 // We can't execute anything else.
941 _ => throw_unsup_format!("can't call foreign function: {}", link_name),
944 this.goto_block(Some(ret))?;
945 this.dump_place(*dest);
949 /// Evaluates the scalar at the specified path. Returns Some(val)
950 /// if the path could be resolved, and None otherwise
954 ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
955 let this = self.eval_context_mut();
956 if let Ok(instance) = this.resolve_path(path) {
961 let const_val = this.const_eval_raw(cid)?;
962 let const_val = this.read_scalar(const_val.into())?;
963 return Ok(Some(const_val));
969 // Shims the linux 'getrandom()' syscall.
970 fn linux_getrandom<'tcx>(
971 this: &mut MiriEvalContext<'_, 'tcx>,
972 args: &[OpTy<'tcx, Tag>],
973 dest: PlaceTy<'tcx, Tag>,
974 ) -> InterpResult<'tcx> {
975 let ptr = this.read_scalar(args[0])?.not_undef()?;
976 let len = this.read_scalar(args[1])?.to_usize(this)?;
978 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
979 // neither of which have any effect on our current PRNG.
980 let _flags = this.read_scalar(args[2])?.to_i32()?;
982 this.gen_random(ptr, len as usize)?;
983 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;