1 use std::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();
45 let tcx = &{ this.tcx.tcx };
47 Scalar::from_int(0, this.pointer_size())
49 let align = this.min_align(size, kind);
52 .allocate(Size::from_bytes(size), align, kind.into());
54 // We just allocated this, the access cannot fail
56 .get_mut(ptr.alloc_id)
58 .write_repeat(tcx, ptr, 0, Size::from_bytes(size))
65 fn free(&mut self, ptr: Scalar<Tag>, kind: MiriMemoryKind) -> InterpResult<'tcx> {
66 let this = self.eval_context_mut();
67 if !this.is_null(ptr)? {
68 let ptr = this.force_ptr(ptr)?;
69 this.memory_mut().deallocate(ptr, None, kind.into())?;
79 ) -> InterpResult<'tcx, Scalar<Tag>> {
80 let this = self.eval_context_mut();
81 let new_align = this.min_align(new_size, kind);
82 if this.is_null(old_ptr)? {
84 Ok(Scalar::from_int(0, this.pointer_size()))
88 .allocate(Size::from_bytes(new_size), new_align, kind.into());
89 Ok(Scalar::Ptr(new_ptr))
92 let old_ptr = this.force_ptr(old_ptr)?;
93 let memory = this.memory_mut();
95 memory.deallocate(old_ptr, None, kind.into())?;
96 Ok(Scalar::from_int(0, this.pointer_size()))
98 let new_ptr = memory.reallocate(
101 Size::from_bytes(new_size),
105 Ok(Scalar::Ptr(new_ptr))
110 /// Emulates calling a foreign item, failing if the item is not supported.
111 /// This function will handle `goto_block` if needed.
112 fn emulate_foreign_item(
115 args: &[OpTy<'tcx, Tag>],
116 dest: Option<PlaceTy<'tcx, Tag>>,
117 ret: Option<mir::BasicBlock>,
118 ) -> InterpResult<'tcx> {
119 let this = self.eval_context_mut();
120 let attrs = this.tcx.get_attrs(def_id);
121 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
122 Some(name) => name.as_str(),
123 None => this.tcx.item_name(def_id).as_str(),
125 // Strip linker suffixes (seen on 32-bit macOS).
126 let link_name = link_name.trim_end_matches("$UNIX2003");
127 let tcx = &{ this.tcx.tcx };
129 // First: functions that diverge.
131 "__rust_start_panic" | "panic_impl" => {
132 throw_unsup_format!("the evaluated program panicked");
134 "exit" | "ExitProcess" => {
135 // it's really u32 for ExitProcess, but we have to put it into the `Exit` error variant anyway
136 let code = this.read_scalar(args[0])?.to_i32()?;
137 return Err(InterpError::Exit(code).into());
141 throw_unsup_format!("can't call (diverging) foreign function: {}", link_name);
146 // Next: functions that assume a ret and dest.
147 let dest = dest.expect("we already checked for a dest");
148 let ret = ret.expect("dest is `Some` but ret is `None`");
151 let size = this.read_scalar(args[0])?.to_usize(this)?;
152 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
153 this.write_scalar(res, dest)?;
156 let items = this.read_scalar(args[0])?.to_usize(this)?;
157 let len = this.read_scalar(args[1])?.to_usize(this)?;
160 .ok_or_else(|| err_panic!(Overflow(mir::BinOp::Mul)))?;
161 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
162 this.write_scalar(res, dest)?;
164 "posix_memalign" => {
165 let ret = this.deref_operand(args[0])?;
166 let align = this.read_scalar(args[1])?.to_usize(this)?;
167 let size = this.read_scalar(args[2])?.to_usize(this)?;
168 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
169 if !align.is_power_of_two() {
170 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
172 if align < this.pointer_size().bytes() {
174 "posix_memalign: alignment must be at least the size of a pointer, but is {}",
180 this.write_null(ret.into())?;
182 let ptr = this.memory_mut().allocate(
183 Size::from_bytes(size),
184 Align::from_bytes(align).unwrap(),
185 MiriMemoryKind::C.into(),
187 this.write_scalar(Scalar::Ptr(ptr), ret.into())?;
189 this.write_null(dest)?;
192 let ptr = this.read_scalar(args[0])?.not_undef()?;
193 this.free(ptr, MiriMemoryKind::C)?;
196 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
197 let new_size = this.read_scalar(args[1])?.to_usize(this)?;
198 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
199 this.write_scalar(res, dest)?;
203 let size = this.read_scalar(args[0])?.to_usize(this)?;
204 let align = this.read_scalar(args[1])?.to_usize(this)?;
206 throw_unsup!(HeapAllocZeroBytes);
208 if !align.is_power_of_two() {
209 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
211 let ptr = this.memory_mut().allocate(
212 Size::from_bytes(size),
213 Align::from_bytes(align).unwrap(),
214 MiriMemoryKind::Rust.into(),
216 this.write_scalar(Scalar::Ptr(ptr), dest)?;
218 "__rust_alloc_zeroed" => {
219 let size = this.read_scalar(args[0])?.to_usize(this)?;
220 let align = this.read_scalar(args[1])?.to_usize(this)?;
222 throw_unsup!(HeapAllocZeroBytes);
224 if !align.is_power_of_two() {
225 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
227 let ptr = this.memory_mut().allocate(
228 Size::from_bytes(size),
229 Align::from_bytes(align).unwrap(),
230 MiriMemoryKind::Rust.into(),
232 // We just allocated this, the access cannot fail
234 .get_mut(ptr.alloc_id)
236 .write_repeat(tcx, ptr, 0, Size::from_bytes(size))
238 this.write_scalar(Scalar::Ptr(ptr), dest)?;
240 "__rust_dealloc" => {
241 let ptr = this.read_scalar(args[0])?.not_undef()?;
242 let old_size = this.read_scalar(args[1])?.to_usize(this)?;
243 let align = this.read_scalar(args[2])?.to_usize(this)?;
245 throw_unsup!(HeapAllocZeroBytes);
247 if !align.is_power_of_two() {
248 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
250 let ptr = this.force_ptr(ptr)?;
251 this.memory_mut().deallocate(
254 Size::from_bytes(old_size),
255 Align::from_bytes(align).unwrap(),
257 MiriMemoryKind::Rust.into(),
260 "__rust_realloc" => {
261 let ptr = this.read_scalar(args[0])?.to_ptr()?;
262 let old_size = this.read_scalar(args[1])?.to_usize(this)?;
263 let align = this.read_scalar(args[2])?.to_usize(this)?;
264 let new_size = this.read_scalar(args[3])?.to_usize(this)?;
265 if old_size == 0 || new_size == 0 {
266 throw_unsup!(HeapAllocZeroBytes);
268 if !align.is_power_of_two() {
269 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
271 let align = Align::from_bytes(align).unwrap();
272 let new_ptr = this.memory_mut().reallocate(
274 Some((Size::from_bytes(old_size), align)),
275 Size::from_bytes(new_size),
277 MiriMemoryKind::Rust.into(),
279 this.write_scalar(Scalar::Ptr(new_ptr), dest)?;
283 let sys_getrandom = this
284 .eval_path_scalar(&["libc", "SYS_getrandom"])?
285 .expect("Failed to get libc::SYS_getrandom")
288 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
289 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
290 match this.read_scalar(args[0])?.to_usize(this)? {
291 id if id == sys_getrandom => {
292 // The first argument is the syscall id,
294 linux_getrandom(this, &args[1..], dest)?;
296 id => throw_unsup_format!("miri does not support syscall ID {}", id),
301 linux_getrandom(this, args, dest)?;
305 let _handle = this.read_scalar(args[0])?;
306 let symbol = this.read_scalar(args[1])?.not_undef()?;
307 let symbol_name = this.memory().read_c_str(symbol)?;
308 let err = format!("bad c unicode symbol: {:?}", symbol_name);
309 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
310 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
311 let ptr = this.memory_mut().create_fn_alloc(FnVal::Other(dlsym));
312 this.write_scalar(Scalar::from(ptr), dest)?;
314 this.write_null(dest)?;
318 "__rust_maybe_catch_panic" => {
319 // fn __rust_maybe_catch_panic(
322 // data_ptr: *mut usize,
323 // vtable_ptr: *mut usize,
325 // We abort on panic, so not much is going on here, but we still have to call the closure.
326 let f = this.read_scalar(args[0])?.not_undef()?;
327 let data = this.read_scalar(args[1])?.not_undef()?;
328 let f_instance = this.memory().get_fn(f)?.as_instance()?;
329 this.write_null(dest)?;
330 trace!("__rust_maybe_catch_panic: {:?}", f_instance);
332 // Now we make a function call.
333 // TODO: consider making this reusable? `InterpCx::step` does something similar
334 // for the TLS destructors, and of course `eval_main`.
335 let mir = this.load_mir(f_instance.def, None)?;
337 MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
338 this.push_stack_frame(
343 // Directly return to caller.
344 StackPopCleanup::Goto(Some(ret)),
346 let mut args = this.frame().body.args_iter();
350 .expect("Argument to __rust_maybe_catch_panic does not take enough arguments.");
351 let arg_dest = this.local_place(arg_local)?;
352 this.write_scalar(data, arg_dest)?;
355 args.next().is_none(),
356 "__rust_maybe_catch_panic argument has more arguments than expected"
359 // We ourselves will return `0`, eventually (because we will not return if we paniced).
360 this.write_null(dest)?;
362 // Don't fall through, we do *not* want to `goto_block`!
367 let left = this.read_scalar(args[0])?.not_undef()?;
368 let right = this.read_scalar(args[1])?.not_undef()?;
369 let n = Size::from_bytes(this.read_scalar(args[2])?.to_usize(this)?);
372 let left_bytes = this.memory().read_bytes(left, n)?;
373 let right_bytes = this.memory().read_bytes(right, n)?;
375 use std::cmp::Ordering::*;
376 match left_bytes.cmp(right_bytes) {
383 this.write_scalar(Scalar::from_int(result, Size::from_bits(32)), dest)?;
387 let ptr = this.read_scalar(args[0])?.not_undef()?;
388 let val = this.read_scalar(args[1])?.to_i32()? as u8;
389 let num = this.read_scalar(args[2])?.to_usize(this)?;
390 if let Some(idx) = this
392 .read_bytes(ptr, Size::from_bytes(num))?
395 .position(|&c| c == val)
397 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
398 this.write_scalar(new_ptr, dest)?;
400 this.write_null(dest)?;
405 let ptr = this.read_scalar(args[0])?.not_undef()?;
406 let val = this.read_scalar(args[1])?.to_i32()? as u8;
407 let num = this.read_scalar(args[2])?.to_usize(this)?;
410 .read_bytes(ptr, Size::from_bytes(num))?
412 .position(|&c| c == val);
413 if let Some(idx) = idx {
414 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
415 this.write_scalar(new_ptr, dest)?;
417 this.write_null(dest)?;
421 "__errno_location" | "__error" => {
422 let errno_scalar: Scalar<Tag> = this.machine.last_error.unwrap().into();
423 this.write_scalar(errno_scalar, dest)?;
427 let result = this.getenv(args[0])?;
428 this.write_scalar(result, dest)?;
432 let result = this.unsetenv(args[0])?;
433 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
437 let result = this.setenv(args[0], args[1])?;
438 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
442 let result = this.getcwd(args[0], args[1])?;
443 this.write_scalar(result, dest)?;
447 let result = this.chdir(args[0])?;
448 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
451 "open" | "open64" => {
452 let result = this.open(args[0], args[1])?;
453 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
457 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
458 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
461 "close" | "close$NOCANCEL" => {
462 let result = this.close(args[0])?;
463 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
467 let result = this.read(args[0], args[1], args[2])?;
468 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
472 let fd = this.read_scalar(args[0])?.to_i32()?;
473 let buf = this.read_scalar(args[1])?.not_undef()?;
474 let n = this.read_scalar(args[2])?.to_usize(&*this.tcx)?;
475 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
476 let result = if fd == 1 || fd == 2 {
478 use std::io::{self, Write};
480 let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(n))?;
481 // We need to flush to make sure this actually appears on the screen
482 let res = if fd == 1 {
483 // Stdout is buffered, flush to make sure it appears on the screen.
484 // This is the write() syscall of the interpreted program, we want it
485 // to correspond to a write() syscall on the host -- there is no good
486 // in adding extra buffering here.
487 let res = io::stdout().write(buf_cont);
488 io::stdout().flush().unwrap();
491 // No need to flush, stderr is not buffered.
492 io::stderr().write(buf_cont)
499 this.write(args[0], args[1], args[2])?
501 // Now, `result` is the value we return back to the program.
502 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
506 let result = this.unlink(args[0])?;
507 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
511 if !this.machine.communicate {
512 throw_unsup_format!("`clock_gettime` not available when isolation is enabled")
514 let clk_id = this.read_scalar(args[0])?.to_i32()?;
516 if clk_id != this.eval_libc_i32("CLOCK_REALTIME")? {
517 let einval = this.eval_libc("EINVAL")?;
518 this.set_last_error(einval)?;
519 this.write_scalar(Scalar::from_int(-1i32, dest.layout.size), dest)?;
521 let tp = this.force_ptr(this.read_scalar(args[1])?.not_undef()?)?;
525 let duration = std::time::SystemTime::now()
526 .duration_since(std::time::SystemTime::UNIX_EPOCH)
527 .unwrap_or_else(|e| {
532 let tv_sec = sign * (duration.as_secs() as i128);
533 let tv_nsec = duration.subsec_nanos() as i128;
535 this.write_c_ints(&tp, &[tv_sec, tv_nsec], &["time_t", "c_long"])?;
537 this.write_scalar(Scalar::from_int(0i32, dest.layout.size), dest)?;
543 if !this.machine.communicate {
544 throw_unsup_format!("`gettimeofday` not available when isolation is enabled")
546 let tz = this.read_scalar(args[1])?.not_undef()?;
547 // Using tz is obsolete and should always be null
548 if !this.is_null(tz)? {
549 let einval = this.eval_libc("EINVAL")?;
550 this.set_last_error(einval)?;
551 this.write_scalar(Scalar::from_int(-1i32, dest.layout.size), dest)?;
553 let tv = this.force_ptr(this.read_scalar(args[0])?.not_undef()?)?;
557 let duration = std::time::SystemTime::now()
558 .duration_since(std::time::SystemTime::UNIX_EPOCH)
559 .unwrap_or_else(|e| {
564 let tv_sec = sign * (duration.as_secs() as i128);
565 let tv_usec = duration.subsec_micros() as i128;
567 this.write_c_ints(&tv, &[tv_sec, tv_usec], &["time_t", "suseconds_t"])?;
569 this.write_scalar(Scalar::from_int(0i32, dest.layout.size), dest)?;
575 let ptr = this.read_scalar(args[0])?.not_undef()?;
576 let n = this.memory().read_c_str(ptr)?.len();
577 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
581 "cbrtf" | "coshf" | "sinhf" | "tanf" => {
582 // FIXME: Using host floats.
583 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
584 let f = match link_name {
591 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
593 // underscore case for windows
594 "_hypotf" | "hypotf" | "atan2f" => {
595 // FIXME: Using host floats.
596 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
597 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
598 let n = match link_name {
599 "_hypotf" | "hypotf" => f1.hypot(f2),
600 "atan2f" => f1.atan2(f2),
603 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
606 "cbrt" | "cosh" | "sinh" | "tan" => {
607 // FIXME: Using host floats.
608 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
609 let f = match link_name {
616 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
618 // underscore case for windows, here and below
619 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
620 "_hypot" | "hypot" | "atan2" => {
621 // FIXME: Using host floats.
622 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
623 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
624 let n = match link_name {
625 "_hypot" | "hypot" => f1.hypot(f2),
626 "atan2" => f1.atan2(f2),
629 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
631 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
632 "_ldexp" | "ldexp" | "scalbn" => {
633 let x = this.read_scalar(args[0])?.to_f64()?;
634 let exp = this.read_scalar(args[1])?.to_i32()?;
636 // Saturating cast to i16. Even those are outside the valid exponent range to
637 // `scalbn` below will do its over/underflow handling.
638 let exp = if exp > i16::max_value() as i32 {
640 } else if exp < i16::min_value() as i32 {
643 exp.try_into().unwrap()
646 let res = x.scalbn(exp);
647 this.write_scalar(Scalar::from_f64(res), dest)?;
650 // Some things needed for `sys::thread` initialization to go through.
651 "signal" | "sigaction" | "sigaltstack" => {
652 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
656 let name = this.read_scalar(args[0])?.to_i32()?;
658 trace!("sysconf() called with name {}", name);
659 // TODO: Cache the sysconf integers via Miri's global cache.
662 &["libc", "_SC_PAGESIZE"],
663 Scalar::from_int(PAGE_SIZE, dest.layout.size),
666 &["libc", "_SC_GETPW_R_SIZE_MAX"],
667 Scalar::from_int(-1, dest.layout.size),
670 &["libc", "_SC_NPROCESSORS_ONLN"],
671 Scalar::from_int(NUM_CPUS, dest.layout.size),
674 let mut result = None;
675 for &(path, path_value) in paths {
676 if let Some(val) = this.eval_path_scalar(path)? {
677 let val = val.to_i32()?;
679 result = Some(path_value);
684 if let Some(result) = result {
685 this.write_scalar(result, dest)?;
687 throw_unsup_format!("Unimplemented sysconf name: {}", name)
691 "sched_getaffinity" => {
692 // Return an error; `num_cpus` then falls back to `sysconf`.
693 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
697 this.write_null(dest)?;
700 // Hook pthread calls that go to the thread-local storage memory subsystem.
701 "pthread_key_create" => {
702 let key_ptr = this.read_scalar(args[0])?.not_undef()?;
704 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
705 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
706 Some(dtor_ptr) => Some(this.memory().get_fn(dtor_ptr)?.as_instance()?),
710 // Figure out how large a pthread TLS key actually is.
711 // This is `libc::pthread_key_t`.
712 let key_type = args[0].layout.ty
714 .ok_or_else(|| err_ub_format!(
715 "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
718 let key_layout = this.layout_of(key_type)?;
720 // Create key and write it into the memory where `key_ptr` wants it.
721 let key = this.machine.tls.create_tls_key(dtor) as u128;
722 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
724 throw_unsup!(OutOfTls);
729 .check_ptr_access(key_ptr, key_layout.size, key_layout.align.abi)?
730 .expect("cannot be a ZST");
731 this.memory_mut().get_mut(key_ptr.alloc_id)?.write_scalar(
734 Scalar::from_uint(key, key_layout.size).into(),
738 // Return success (`0`).
739 this.write_null(dest)?;
741 "pthread_key_delete" => {
742 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
743 this.machine.tls.delete_tls_key(key)?;
744 // Return success (0)
745 this.write_null(dest)?;
747 "pthread_getspecific" => {
748 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
749 let ptr = this.machine.tls.load_tls(key, tcx)?;
750 this.write_scalar(ptr, dest)?;
752 "pthread_setspecific" => {
753 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
754 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
755 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
757 // Return success (`0`).
758 this.write_null(dest)?;
761 // Stack size/address stuff.
763 | "pthread_attr_destroy"
765 | "pthread_attr_setstacksize" => {
766 this.write_null(dest)?;
768 "pthread_attr_getstack" => {
769 let addr_place = this.deref_operand(args[1])?;
770 let size_place = this.deref_operand(args[2])?;
773 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
777 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
781 // Return success (`0`).
782 this.write_null(dest)?;
785 // We don't support threading. (Also for Windows.)
786 "pthread_create" | "CreateThread" => {
787 throw_unsup_format!("Miri does not support threading");
790 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
791 "pthread_mutexattr_init"
792 | "pthread_mutexattr_settype"
793 | "pthread_mutex_init"
794 | "pthread_mutexattr_destroy"
795 | "pthread_mutex_lock"
796 | "pthread_mutex_unlock"
797 | "pthread_mutex_destroy"
798 | "pthread_rwlock_rdlock"
799 | "pthread_rwlock_unlock"
800 | "pthread_rwlock_wrlock"
801 | "pthread_rwlock_destroy"
802 | "pthread_condattr_init"
803 | "pthread_condattr_setclock"
804 | "pthread_cond_init"
805 | "pthread_condattr_destroy"
806 | "pthread_cond_destroy" => {
807 this.write_null(dest)?;
810 // We don't support fork so we don't have to do anything for atfork.
811 "pthread_atfork" => {
812 this.write_null(dest)?;
816 // 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.
817 let addr = this.read_scalar(args[0])?.not_undef()?;
818 this.write_scalar(addr, dest)?;
821 this.write_null(dest)?;
825 "pthread_attr_get_np" | "pthread_getattr_np" => {
826 this.write_null(dest)?;
828 "pthread_get_stackaddr_np" => {
829 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
830 this.write_scalar(stack_addr, dest)?;
832 "pthread_get_stacksize_np" => {
833 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
834 this.write_scalar(stack_size, dest)?;
837 // FIXME: register the destructor.
840 this.write_scalar(Scalar::Ptr(this.machine.argc.unwrap()), dest)?;
843 this.write_scalar(Scalar::Ptr(this.machine.argv.unwrap()), dest)?;
845 "SecRandomCopyBytes" => {
846 let len = this.read_scalar(args[1])?.to_usize(this)?;
847 let ptr = this.read_scalar(args[2])?.not_undef()?;
848 this.gen_random(ptr, len as usize)?;
849 this.write_null(dest)?;
852 // Windows API stubs.
854 // DWORD = ULONG = u32
856 "GetProcessHeap" => {
857 // Just fake a HANDLE
858 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
861 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
862 let flags = this.read_scalar(args[1])?.to_u32()?;
863 let size = this.read_scalar(args[2])?.to_usize(this)?;
864 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
865 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
866 this.write_scalar(res, dest)?;
869 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
870 let _flags = this.read_scalar(args[1])?.to_u32()?;
871 let ptr = this.read_scalar(args[2])?.not_undef()?;
872 this.free(ptr, MiriMemoryKind::WinHeap)?;
873 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
876 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
877 let _flags = this.read_scalar(args[1])?.to_u32()?;
878 let ptr = this.read_scalar(args[2])?.not_undef()?;
879 let size = this.read_scalar(args[3])?.to_usize(this)?;
880 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
881 this.write_scalar(res, dest)?;
885 this.set_last_error(this.read_scalar(args[0])?.not_undef()?)?;
888 let last_error = this.get_last_error()?;
889 this.write_scalar(last_error, dest)?;
892 "AddVectoredExceptionHandler" => {
893 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
894 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
896 "InitializeCriticalSection"
897 | "EnterCriticalSection"
898 | "LeaveCriticalSection"
899 | "DeleteCriticalSection" => {
900 // Nothing to do, not even a return value.
904 | "TryEnterCriticalSection"
905 | "GetConsoleScreenBufferInfo"
906 | "SetConsoleTextAttribute" => {
907 // Pretend these do not exist / nothing happened, by returning zero.
908 this.write_null(dest)?;
911 let system_info = this.deref_operand(args[0])?;
912 let system_info_ptr = this
913 .check_mplace_access(system_info, None)?
914 .expect("cannot be a ZST");
915 // Initialize with `0`.
917 .get_mut(system_info_ptr.alloc_id)?
918 .write_repeat(tcx, system_info_ptr, 0, system_info.layout.size)?;
919 // Set number of processors.
920 let dword_size = Size::from_bytes(4);
921 let offset = 2 * dword_size + 3 * tcx.pointer_size();
923 .get_mut(system_info_ptr.alloc_id)?
926 system_info_ptr.offset(offset, tcx)?,
927 Scalar::from_int(NUM_CPUS, dword_size).into(),
933 // This just creates a key; Windows does not natively support TLS destructors.
935 // Create key and return it.
936 let key = this.machine.tls.create_tls_key(None) as u128;
938 // Figure out how large a TLS key actually is. This is `c::DWORD`.
939 if dest.layout.size.bits() < 128
940 && key >= (1u128 << dest.layout.size.bits() as u128)
942 throw_unsup!(OutOfTls);
944 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
947 let key = this.read_scalar(args[0])?.to_u32()? as u128;
948 let ptr = this.machine.tls.load_tls(key, tcx)?;
949 this.write_scalar(ptr, dest)?;
952 let key = this.read_scalar(args[0])?.to_u32()? as u128;
953 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
954 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
956 // Return success (`1`).
957 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
960 let which = this.read_scalar(args[0])?.to_i32()?;
961 // We just make this the identity function, so we know later in `WriteFile`
963 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
966 let handle = this.read_scalar(args[0])?.to_isize(this)?;
967 let buf = this.read_scalar(args[1])?.not_undef()?;
968 let n = this.read_scalar(args[2])?.to_u32()?;
969 let written_place = this.deref_operand(args[3])?;
970 // Spec says to always write `0` first.
971 this.write_null(written_place.into())?;
972 let written = if handle == -11 || handle == -12 {
974 use std::io::{self, Write};
978 .read_bytes(buf, Size::from_bytes(u64::from(n)))?;
979 let res = if handle == -11 {
980 io::stdout().write(buf_cont)
982 io::stderr().write(buf_cont)
984 res.ok().map(|n| n as u32)
986 eprintln!("Miri: Ignored output to handle {}", handle);
987 // Pretend it all went well.
990 // If there was no error, write back how much was written.
991 if let Some(n) = written {
992 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
994 // Return whether this was a success.
996 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
1000 "GetConsoleMode" => {
1001 // Everything is a pipe.
1002 this.write_null(dest)?;
1004 "GetEnvironmentVariableW" => {
1005 // This is not the env var you are looking for.
1006 this.set_last_error(Scalar::from_u32(203))?; // ERROR_ENVVAR_NOT_FOUND
1007 this.write_null(dest)?;
1009 "GetCommandLineW" => {
1010 this.write_scalar(Scalar::Ptr(this.machine.cmd_line.unwrap()), dest)?;
1012 // The actual name of 'RtlGenRandom'
1013 "SystemFunction036" => {
1014 let ptr = this.read_scalar(args[0])?.not_undef()?;
1015 let len = this.read_scalar(args[1])?.to_u32()?;
1016 this.gen_random(ptr, len as usize)?;
1017 this.write_scalar(Scalar::from_bool(true), dest)?;
1020 // We can't execute anything else.
1021 _ => throw_unsup_format!("can't call foreign function: {}", link_name),
1024 this.goto_block(Some(ret))?;
1025 this.dump_place(*dest);
1029 /// Evaluates the scalar at the specified path. Returns Some(val)
1030 /// if the path could be resolved, and None otherwise
1031 fn eval_path_scalar(
1034 ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
1035 let this = self.eval_context_mut();
1036 if let Ok(instance) = this.resolve_path(path) {
1037 let cid = GlobalId {
1041 let const_val = this.const_eval_raw(cid)?;
1042 let const_val = this.read_scalar(const_val.into())?;
1043 return Ok(Some(const_val));
1048 fn set_last_error(&mut self, scalar: Scalar<Tag>) -> InterpResult<'tcx> {
1049 let this = self.eval_context_mut();
1050 let tcx = &{ this.tcx.tcx };
1051 let errno_ptr = this.machine.last_error.unwrap();
1052 this.memory_mut().get_mut(errno_ptr.alloc_id)?.write_scalar(
1056 Size::from_bits(32),
1060 fn get_last_error(&mut self) -> InterpResult<'tcx, Scalar<Tag>> {
1061 let this = self.eval_context_mut();
1062 let tcx = &{ this.tcx.tcx };
1063 let errno_ptr = this.machine.last_error.unwrap();
1065 .get(errno_ptr.alloc_id)?
1066 .read_scalar(tcx, errno_ptr, Size::from_bits(32))?
1070 fn consume_io_error(&mut self, e: std::io::Error) -> InterpResult<'tcx> {
1071 self.eval_context_mut().set_last_error(Scalar::from_int(
1072 e.raw_os_error().unwrap(),
1073 Size::from_bits(32),
1078 // Shims the linux 'getrandom()' syscall.
1079 fn linux_getrandom<'tcx>(
1080 this: &mut MiriEvalContext<'_, 'tcx>,
1081 args: &[OpTy<'tcx, Tag>],
1082 dest: PlaceTy<'tcx, Tag>,
1083 ) -> InterpResult<'tcx> {
1084 let ptr = this.read_scalar(args[0])?.not_undef()?;
1085 let len = this.read_scalar(args[1])?.to_usize(this)?;
1087 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
1088 // neither of which have any effect on our current PRNG.
1089 let _flags = this.read_scalar(args[2])?.to_i32()?;
1091 this.gen_random(ptr, len as usize)?;
1092 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;