1 use std::{iter, convert::TryInto};
4 use rustc::ty::layout::{Align, LayoutOf, Size};
5 use rustc::hir::def_id::DefId;
6 use rustc_apfloat::Float;
9 use syntax::symbol::sym;
13 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
14 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
15 /// Returns the minimum alignment for the target architecture for allocations of the given size.
16 fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
17 let this = self.eval_context_ref();
18 // List taken from `libstd/sys_common/alloc.rs`.
19 let min_align = match this.tcx.tcx.sess.target.target.arch.as_str() {
20 "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
21 "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
22 arch => bug!("Unsupported target architecture: {}", arch),
24 // Windows always aligns, even small allocations.
25 // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
26 // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
27 if kind == MiriMemoryKind::WinHeap || size >= min_align {
28 return Align::from_bytes(min_align).unwrap();
30 // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
31 fn prev_power_of_two(x: u64) -> u64 {
32 let next_pow2 = x.next_power_of_two();
34 // x *is* a power of two, just use that.
37 // x is between two powers, so next = 2*prev.
41 Align::from_bytes(prev_power_of_two(size)).unwrap()
44 fn malloc(&mut self, size: u64, zero_init: bool, kind: MiriMemoryKind) -> Scalar<Tag> {
45 let this = self.eval_context_mut();
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 is definitely in-bounds.
56 .write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize))
63 fn free(&mut self, ptr: Scalar<Tag>, kind: MiriMemoryKind) -> InterpResult<'tcx> {
64 let this = self.eval_context_mut();
65 if !this.is_null(ptr)? {
66 let ptr = this.force_ptr(ptr)?;
67 this.memory.deallocate(ptr, None, kind.into())?;
77 ) -> InterpResult<'tcx, Scalar<Tag>> {
78 let this = self.eval_context_mut();
79 let new_align = this.min_align(new_size, kind);
80 if this.is_null(old_ptr)? {
82 Ok(Scalar::from_int(0, this.pointer_size()))
86 .allocate(Size::from_bytes(new_size), new_align, kind.into());
87 Ok(Scalar::Ptr(new_ptr))
90 let old_ptr = this.force_ptr(old_ptr)?;
92 this.memory.deallocate(old_ptr, None, kind.into())?;
93 Ok(Scalar::from_int(0, this.pointer_size()))
95 let new_ptr = this.memory.reallocate(
98 Size::from_bytes(new_size),
102 Ok(Scalar::Ptr(new_ptr))
107 /// Emulates calling a foreign item, failing if the item is not supported.
108 /// This function will handle `goto_block` if needed.
109 /// Returns Ok(None) if the foreign item was completely handled
110 /// by this function.
111 /// Returns Ok(Some(body)) if processing the foreign item
112 /// is delegated to another function.
113 fn emulate_foreign_item(
116 args: &[OpTy<'tcx, Tag>],
117 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
118 _unwind: Option<mir::BasicBlock>
119 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
120 let this = self.eval_context_mut();
121 let attrs = this.tcx.get_attrs(def_id);
122 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
123 Some(name) => name.as_str(),
124 None => this.tcx.item_name(def_id).as_str(),
126 // Strip linker suffixes (seen on 32-bit macOS).
127 let link_name = link_name.trim_end_matches("$UNIX2003");
128 let tcx = &{ this.tcx.tcx };
130 // First: functions that diverge.
131 let (dest, ret) = match link_name {
132 // Note that this matches calls to the *foreign* item `__rust_start_panic* -
133 // that is, calls to `extern "Rust" { fn __rust_start_panic(...) }`.
134 // We forward this to the underlying *implementation* in the panic runtime crate.
135 // Normally, this will be either `libpanic_unwind` or `libpanic_abort`, but it could
136 // also be a custom user-provided implementation via `#![feature(panic_runtime)]`
137 "__rust_start_panic" => {
138 let panic_runtime = tcx.crate_name(tcx.injected_panic_runtime().expect("No panic runtime found!"));
139 let start_panic_instance = this.resolve_path(&[&*panic_runtime.as_str(), "__rust_start_panic"])?;
140 return Ok(Some(this.load_mir(start_panic_instance.def, None)?));
142 // Similarly, we forward calls to the `panic_impl` foreign item to its implementation.
143 // The implementation is provided by the function with the `#[panic_handler]` attribute.
145 let panic_impl_id = this.tcx.lang_items().panic_impl().unwrap();
146 let panic_impl_instance = ty::Instance::mono(*this.tcx, panic_impl_id);
147 return Ok(Some(this.load_mir(panic_impl_instance.def, None)?));
150 "exit" | "ExitProcess" => {
151 // it's really u32 for ExitProcess, but we have to put it into the `Exit` error variant anyway
152 let code = this.read_scalar(args[0])?.to_i32()?;
153 return Err(InterpError::Exit(code).into());
156 if let Some(p) = ret {
159 throw_unsup_format!("can't call (diverging) foreign function: {}", link_name);
164 // Next: functions that return.
167 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
168 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
169 this.write_scalar(res, dest)?;
172 let items = this.read_scalar(args[0])?.to_machine_usize(this)?;
173 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
176 .ok_or_else(|| err_panic!(Overflow(mir::BinOp::Mul)))?;
177 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
178 this.write_scalar(res, dest)?;
180 "posix_memalign" => {
181 let ret = this.deref_operand(args[0])?;
182 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
183 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
184 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
185 if !align.is_power_of_two() {
186 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
188 if align < this.pointer_size().bytes() {
190 "posix_memalign: alignment must be at least the size of a pointer, but is {}",
196 this.write_null(ret.into())?;
198 let ptr = this.memory.allocate(
199 Size::from_bytes(size),
200 Align::from_bytes(align).unwrap(),
201 MiriMemoryKind::C.into(),
203 this.write_scalar(Scalar::Ptr(ptr), ret.into())?;
205 this.write_null(dest)?;
208 let ptr = this.read_scalar(args[0])?.not_undef()?;
209 this.free(ptr, MiriMemoryKind::C)?;
212 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
213 let new_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
214 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
215 this.write_scalar(res, dest)?;
219 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
220 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
222 throw_unsup!(HeapAllocZeroBytes);
224 if !align.is_power_of_two() {
225 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
227 let ptr = this.memory.allocate(
228 Size::from_bytes(size),
229 Align::from_bytes(align).unwrap(),
230 MiriMemoryKind::Rust.into(),
232 this.write_scalar(Scalar::Ptr(ptr), dest)?;
234 "__rust_alloc_zeroed" => {
235 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
236 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
238 throw_unsup!(HeapAllocZeroBytes);
240 if !align.is_power_of_two() {
241 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
243 let ptr = this.memory.allocate(
244 Size::from_bytes(size),
245 Align::from_bytes(align).unwrap(),
246 MiriMemoryKind::Rust.into(),
248 // We just allocated this, the access is definitely in-bounds.
250 .write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize))
252 this.write_scalar(Scalar::Ptr(ptr), dest)?;
254 "__rust_dealloc" => {
255 let ptr = this.read_scalar(args[0])?.not_undef()?;
256 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
257 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
259 throw_unsup!(HeapAllocZeroBytes);
261 if !align.is_power_of_two() {
262 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
264 let ptr = this.force_ptr(ptr)?;
265 this.memory.deallocate(
268 Size::from_bytes(old_size),
269 Align::from_bytes(align).unwrap(),
271 MiriMemoryKind::Rust.into(),
274 "__rust_realloc" => {
275 let ptr = this.read_scalar(args[0])?.to_ptr()?;
276 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
277 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
278 let new_size = this.read_scalar(args[3])?.to_machine_usize(this)?;
279 if old_size == 0 || new_size == 0 {
280 throw_unsup!(HeapAllocZeroBytes);
282 if !align.is_power_of_two() {
283 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
285 let align = Align::from_bytes(align).unwrap();
286 let new_ptr = this.memory.reallocate(
288 Some((Size::from_bytes(old_size), align)),
289 Size::from_bytes(new_size),
291 MiriMemoryKind::Rust.into(),
293 this.write_scalar(Scalar::Ptr(new_ptr), dest)?;
297 let sys_getrandom = this
298 .eval_path_scalar(&["libc", "SYS_getrandom"])?
299 .expect("Failed to get libc::SYS_getrandom")
300 .to_machine_usize(this)?;
302 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
303 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
304 match this.read_scalar(args[0])?.to_machine_usize(this)? {
305 id if id == sys_getrandom => {
306 // The first argument is the syscall id,
308 linux_getrandom(this, &args[1..], dest)?;
310 id => throw_unsup_format!("miri does not support syscall ID {}", id),
315 linux_getrandom(this, args, dest)?;
319 let _handle = this.read_scalar(args[0])?;
320 let symbol = this.read_scalar(args[1])?.not_undef()?;
321 let symbol_name = this.memory.read_c_str(symbol)?;
322 let err = format!("bad c unicode symbol: {:?}", symbol_name);
323 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
324 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
325 let ptr = this.memory.create_fn_alloc(FnVal::Other(dlsym));
326 this.write_scalar(Scalar::from(ptr), dest)?;
328 this.write_null(dest)?;
332 "__rust_maybe_catch_panic" => {
333 this.handle_catch_panic(args, dest, ret)?;
338 let left = this.read_scalar(args[0])?.not_undef()?;
339 let right = this.read_scalar(args[1])?.not_undef()?;
340 let n = Size::from_bytes(this.read_scalar(args[2])?.to_machine_usize(this)?);
343 let left_bytes = this.memory.read_bytes(left, n)?;
344 let right_bytes = this.memory.read_bytes(right, n)?;
346 use std::cmp::Ordering::*;
347 match left_bytes.cmp(right_bytes) {
354 this.write_scalar(Scalar::from_int(result, Size::from_bits(32)), dest)?;
358 let ptr = this.read_scalar(args[0])?.not_undef()?;
359 let val = this.read_scalar(args[1])?.to_i32()? as u8;
360 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
361 if let Some(idx) = this
363 .read_bytes(ptr, Size::from_bytes(num))?
366 .position(|&c| c == val)
368 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
369 this.write_scalar(new_ptr, dest)?;
371 this.write_null(dest)?;
376 let ptr = this.read_scalar(args[0])?.not_undef()?;
377 let val = this.read_scalar(args[1])?.to_i32()? as u8;
378 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
381 .read_bytes(ptr, Size::from_bytes(num))?
383 .position(|&c| c == val);
384 if let Some(idx) = idx {
385 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
386 this.write_scalar(new_ptr, dest)?;
388 this.write_null(dest)?;
392 "__errno_location" | "__error" => {
393 let errno_place = this.machine.last_error.unwrap();
394 this.write_scalar(errno_place.to_ref().to_scalar()?, dest)?;
398 let result = this.getenv(args[0])?;
399 this.write_scalar(result, dest)?;
403 let result = this.unsetenv(args[0])?;
404 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
408 let result = this.setenv(args[0], args[1])?;
409 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
413 let result = this.getcwd(args[0], args[1])?;
414 this.write_scalar(result, dest)?;
418 let result = this.chdir(args[0])?;
419 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
422 "open" | "open64" => {
423 let result = this.open(args[0], args[1])?;
424 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
428 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
429 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
432 "close" | "close$NOCANCEL" => {
433 let result = this.close(args[0])?;
434 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
438 let result = this.read(args[0], args[1], args[2])?;
439 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
443 let fd = this.read_scalar(args[0])?.to_i32()?;
444 let buf = this.read_scalar(args[1])?.not_undef()?;
445 let n = this.read_scalar(args[2])?.to_machine_usize(tcx)?;
446 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
447 let result = if fd == 1 || fd == 2 {
449 use std::io::{self, Write};
451 let buf_cont = this.memory.read_bytes(buf, Size::from_bytes(n))?;
452 // We need to flush to make sure this actually appears on the screen
453 let res = if fd == 1 {
454 // Stdout is buffered, flush to make sure it appears on the screen.
455 // This is the write() syscall of the interpreted program, we want it
456 // to correspond to a write() syscall on the host -- there is no good
457 // in adding extra buffering here.
458 let res = io::stdout().write(buf_cont);
459 io::stdout().flush().unwrap();
462 // No need to flush, stderr is not buffered.
463 io::stderr().write(buf_cont)
470 this.write(args[0], args[1], args[2])?
472 // Now, `result` is the value we return back to the program.
473 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
477 let result = this.unlink(args[0])?;
478 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
482 let result = this.clock_gettime(args[0], args[1])?;
483 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
487 let result = this.gettimeofday(args[0], args[1])?;
488 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
492 let ptr = this.read_scalar(args[0])?.not_undef()?;
493 let n = this.memory.read_c_str(ptr)?.len();
494 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
498 "cbrtf" | "coshf" | "sinhf" | "tanf" | "acosf" | "asinf" | "atanf" => {
499 // FIXME: Using host floats.
500 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
501 let f = match link_name {
511 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
513 // underscore case for windows
514 "_hypotf" | "hypotf" | "atan2f" => {
515 // FIXME: Using host floats.
516 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
517 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
518 let n = match link_name {
519 "_hypotf" | "hypotf" => f1.hypot(f2),
520 "atan2f" => f1.atan2(f2),
523 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
526 "cbrt" | "cosh" | "sinh" | "tan" | "acos" | "asin" | "atan" => {
527 // FIXME: Using host floats.
528 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
529 let f = match link_name {
539 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
541 // underscore case for windows, here and below
542 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
543 "_hypot" | "hypot" | "atan2" => {
544 // FIXME: Using host floats.
545 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
546 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
547 let n = match link_name {
548 "_hypot" | "hypot" => f1.hypot(f2),
549 "atan2" => f1.atan2(f2),
552 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
554 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
555 "_ldexp" | "ldexp" | "scalbn" => {
556 let x = this.read_scalar(args[0])?.to_f64()?;
557 let exp = this.read_scalar(args[1])?.to_i32()?;
559 // Saturating cast to i16. Even those are outside the valid exponent range to
560 // `scalbn` below will do its over/underflow handling.
561 let exp = if exp > i16::max_value() as i32 {
563 } else if exp < i16::min_value() as i32 {
566 exp.try_into().unwrap()
569 let res = x.scalbn(exp);
570 this.write_scalar(Scalar::from_f64(res), dest)?;
573 // Some things needed for `sys::thread` initialization to go through.
574 "signal" | "sigaction" | "sigaltstack" => {
575 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
579 let name = this.read_scalar(args[0])?.to_i32()?;
581 trace!("sysconf() called with name {}", name);
582 // TODO: Cache the sysconf integers via Miri's global cache.
585 &["libc", "_SC_PAGESIZE"],
586 Scalar::from_int(PAGE_SIZE, dest.layout.size),
589 &["libc", "_SC_GETPW_R_SIZE_MAX"],
590 Scalar::from_int(-1, dest.layout.size),
593 &["libc", "_SC_NPROCESSORS_ONLN"],
594 Scalar::from_int(NUM_CPUS, dest.layout.size),
597 let mut result = None;
598 for &(path, path_value) in paths {
599 if let Some(val) = this.eval_path_scalar(path)? {
600 let val = val.to_i32()?;
602 result = Some(path_value);
607 if let Some(result) = result {
608 this.write_scalar(result, dest)?;
610 throw_unsup_format!("Unimplemented sysconf name: {}", name)
614 "sched_getaffinity" => {
615 // Return an error; `num_cpus` then falls back to `sysconf`.
616 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
620 this.write_null(dest)?;
623 // Hook pthread calls that go to the thread-local storage memory subsystem.
624 "pthread_key_create" => {
625 let key_place = this.deref_operand(args[0])?;
627 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
628 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
629 Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
633 // Figure out how large a pthread TLS key actually is.
634 // This is `libc::pthread_key_t`.
635 let key_type = args[0].layout.ty
637 .ok_or_else(|| err_ub_format!(
638 "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
641 let key_layout = this.layout_of(key_type)?;
643 // Create key and write it into the memory where `key_ptr` wants it.
644 let key = this.machine.tls.create_tls_key(dtor) as u128;
645 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
647 throw_unsup!(OutOfTls);
650 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
652 // Return success (`0`).
653 this.write_null(dest)?;
655 "pthread_key_delete" => {
656 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
657 this.machine.tls.delete_tls_key(key)?;
658 // Return success (0)
659 this.write_null(dest)?;
661 "pthread_getspecific" => {
662 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
663 let ptr = this.machine.tls.load_tls(key, tcx)?;
664 this.write_scalar(ptr, dest)?;
666 "pthread_setspecific" => {
667 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
668 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
669 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
671 // Return success (`0`).
672 this.write_null(dest)?;
675 // Stack size/address stuff.
677 | "pthread_attr_destroy"
679 | "pthread_attr_setstacksize" => {
680 this.write_null(dest)?;
682 "pthread_attr_getstack" => {
683 let addr_place = this.deref_operand(args[1])?;
684 let size_place = this.deref_operand(args[2])?;
687 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
691 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
695 // Return success (`0`).
696 this.write_null(dest)?;
699 // We don't support threading. (Also for Windows.)
700 "pthread_create" | "CreateThread" => {
701 throw_unsup_format!("Miri does not support threading");
704 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
705 "pthread_mutexattr_init"
706 | "pthread_mutexattr_settype"
707 | "pthread_mutex_init"
708 | "pthread_mutexattr_destroy"
709 | "pthread_mutex_lock"
710 | "pthread_mutex_unlock"
711 | "pthread_mutex_destroy"
712 | "pthread_rwlock_rdlock"
713 | "pthread_rwlock_unlock"
714 | "pthread_rwlock_wrlock"
715 | "pthread_rwlock_destroy"
716 | "pthread_condattr_init"
717 | "pthread_condattr_setclock"
718 | "pthread_cond_init"
719 | "pthread_condattr_destroy"
720 | "pthread_cond_destroy" => {
721 this.write_null(dest)?;
724 // We don't support fork so we don't have to do anything for atfork.
725 "pthread_atfork" => {
726 this.write_null(dest)?;
730 // 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.
731 let addr = this.read_scalar(args[0])?.not_undef()?;
732 this.write_scalar(addr, dest)?;
735 this.write_null(dest)?;
739 "pthread_attr_get_np" | "pthread_getattr_np" => {
740 this.write_null(dest)?;
742 "pthread_get_stackaddr_np" => {
743 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
744 this.write_scalar(stack_addr, dest)?;
746 "pthread_get_stacksize_np" => {
747 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
748 this.write_scalar(stack_size, dest)?;
751 // FIXME: register the destructor.
754 this.write_scalar(this.machine.argc.expect("machine must be initialized"), dest)?;
757 this.write_scalar(this.machine.argv.expect("machine must be initialized"), dest)?;
759 "SecRandomCopyBytes" => {
760 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
761 let ptr = this.read_scalar(args[2])?.not_undef()?;
762 this.gen_random(ptr, len as usize)?;
763 this.write_null(dest)?;
766 // Windows API stubs.
768 // DWORD = ULONG = u32
770 "GetProcessHeap" => {
771 // Just fake a HANDLE
772 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
775 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
776 let flags = this.read_scalar(args[1])?.to_u32()?;
777 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
778 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
779 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
780 this.write_scalar(res, dest)?;
783 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
784 let _flags = this.read_scalar(args[1])?.to_u32()?;
785 let ptr = this.read_scalar(args[2])?.not_undef()?;
786 this.free(ptr, MiriMemoryKind::WinHeap)?;
787 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
790 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
791 let _flags = this.read_scalar(args[1])?.to_u32()?;
792 let ptr = this.read_scalar(args[2])?.not_undef()?;
793 let size = this.read_scalar(args[3])?.to_machine_usize(this)?;
794 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
795 this.write_scalar(res, dest)?;
799 this.set_last_error(this.read_scalar(args[0])?.not_undef()?)?;
802 let last_error = this.get_last_error()?;
803 this.write_scalar(last_error, dest)?;
806 "AddVectoredExceptionHandler" => {
807 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
808 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
810 "InitializeCriticalSection"
811 | "EnterCriticalSection"
812 | "LeaveCriticalSection"
813 | "DeleteCriticalSection" => {
814 // Nothing to do, not even a return value.
818 | "TryEnterCriticalSection"
819 | "GetConsoleScreenBufferInfo"
820 | "SetConsoleTextAttribute" => {
821 // Pretend these do not exist / nothing happened, by returning zero.
822 this.write_null(dest)?;
825 let system_info = this.deref_operand(args[0])?;
826 // Initialize with `0`.
828 .write_bytes(system_info.ptr, iter::repeat(0u8).take(system_info.layout.size.bytes() as usize))?;
829 // Set number of processors.
830 let dword_size = Size::from_bytes(4);
831 let num_cpus = this.mplace_field(system_info, 6)?;
833 Scalar::from_int(NUM_CPUS, dword_size),
839 // This just creates a key; Windows does not natively support TLS destructors.
841 // Create key and return it.
842 let key = this.machine.tls.create_tls_key(None) as u128;
844 // Figure out how large a TLS key actually is. This is `c::DWORD`.
845 if dest.layout.size.bits() < 128
846 && key >= (1u128 << dest.layout.size.bits() as u128)
848 throw_unsup!(OutOfTls);
850 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
853 let key = this.read_scalar(args[0])?.to_u32()? as u128;
854 let ptr = this.machine.tls.load_tls(key, tcx)?;
855 this.write_scalar(ptr, dest)?;
858 let key = this.read_scalar(args[0])?.to_u32()? as u128;
859 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
860 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
862 // Return success (`1`).
863 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
866 let which = this.read_scalar(args[0])?.to_i32()?;
867 // We just make this the identity function, so we know later in `WriteFile`
869 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
872 let handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
873 let buf = this.read_scalar(args[1])?.not_undef()?;
874 let n = this.read_scalar(args[2])?.to_u32()?;
875 let written_place = this.deref_operand(args[3])?;
876 // Spec says to always write `0` first.
877 this.write_null(written_place.into())?;
878 let written = if handle == -11 || handle == -12 {
880 use std::io::{self, Write};
884 .read_bytes(buf, Size::from_bytes(u64::from(n)))?;
885 let res = if handle == -11 {
886 io::stdout().write(buf_cont)
888 io::stderr().write(buf_cont)
890 res.ok().map(|n| n as u32)
892 eprintln!("Miri: Ignored output to handle {}", handle);
893 // Pretend it all went well.
896 // If there was no error, write back how much was written.
897 if let Some(n) = written {
898 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
900 // Return whether this was a success.
902 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
906 "GetConsoleMode" => {
907 // Everything is a pipe.
908 this.write_null(dest)?;
910 "GetEnvironmentVariableW" => {
911 // This is not the env var you are looking for.
912 this.set_last_error(Scalar::from_u32(203))?; // ERROR_ENVVAR_NOT_FOUND
913 this.write_null(dest)?;
915 "GetCommandLineW" => {
916 this.write_scalar(this.machine.cmd_line.expect("machine must be initialized"), dest)?;
918 // The actual name of 'RtlGenRandom'
919 "SystemFunction036" => {
920 let ptr = this.read_scalar(args[0])?.not_undef()?;
921 let len = this.read_scalar(args[1])?.to_u32()?;
922 this.gen_random(ptr, len as usize)?;
923 this.write_scalar(Scalar::from_bool(true), dest)?;
926 // We can't execute anything else.
927 _ => throw_unsup_format!("can't call foreign function: {}", link_name),
930 this.dump_place(*dest);
931 this.go_to_block(ret);
935 /// Evaluates the scalar at the specified path. Returns Some(val)
936 /// if the path could be resolved, and None otherwise
940 ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
941 let this = self.eval_context_mut();
942 if let Ok(instance) = this.resolve_path(path) {
947 let const_val = this.const_eval_raw(cid)?;
948 let const_val = this.read_scalar(const_val.into())?;
949 return Ok(Some(const_val));
955 // Shims the linux 'getrandom()' syscall.
956 fn linux_getrandom<'tcx>(
957 this: &mut MiriEvalContext<'_, 'tcx>,
958 args: &[OpTy<'tcx, Tag>],
959 dest: PlaceTy<'tcx, Tag>,
960 ) -> InterpResult<'tcx> {
961 let ptr = this.read_scalar(args[0])?.not_undef()?;
962 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
964 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
965 // neither of which have any effect on our current PRNG.
966 let _flags = this.read_scalar(args[2])?.to_i32()?;
968 this.gen_random(ptr, len as usize)?;
969 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;