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 dest: Option<PlaceTy<'tcx, Tag>>,
118 ret: Option<mir::BasicBlock>,
119 _unwind: Option<mir::BasicBlock>
120 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
121 let this = self.eval_context_mut();
122 let attrs = this.tcx.get_attrs(def_id);
123 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
124 Some(name) => name.as_str(),
125 None => this.tcx.item_name(def_id).as_str(),
127 // Strip linker suffixes (seen on 32-bit macOS).
128 let link_name = link_name.trim_end_matches("$UNIX2003");
129 let tcx = &{ this.tcx.tcx };
131 // First: functions that diverge.
133 // Note that this matches calls to the *foreign* item `__rust_start_panic* -
134 // that is, calls to `extern "Rust" { fn __rust_start_panic(...) }`.
135 // We forward this to the underlying *implementation* in the panic runtime crate.
136 // Normally, this will be either `libpanic_unwind` or `libpanic_abort`, but it could
137 // also be a custom user-provided implementation via `#![feature(panic_runtime)]`
138 "__rust_start_panic" => {
139 let panic_runtime = tcx.crate_name(tcx.injected_panic_runtime().expect("No panic runtime found!"));
140 let start_panic_instance = this.resolve_path(&[&*panic_runtime.as_str(), "__rust_start_panic"])?;
141 return Ok(Some(this.load_mir(start_panic_instance.def, None)?));
143 // Similarly, we forward calls to the `panic_impl` foreign item to its implementation.
144 // The implementation is provided by the function with the `#[panic_handler]` attribute.
146 let panic_impl_id = this.tcx.lang_items().panic_impl().unwrap();
147 let panic_impl_instance = ty::Instance::mono(*this.tcx, panic_impl_id);
148 return Ok(Some(this.load_mir(panic_impl_instance.def, None)?));
151 "exit" | "ExitProcess" => {
152 // it's really u32 for ExitProcess, but we have to put it into the `Exit` error variant anyway
153 let code = this.read_scalar(args[0])?.to_i32()?;
154 return Err(InterpError::Exit(code).into());
158 throw_unsup_format!("can't call (diverging) foreign function: {}", link_name);
163 // Next: functions that assume a ret and dest.
164 let dest = dest.expect("we already checked for a dest");
165 let ret = ret.expect("dest is `Some` but ret is `None`");
168 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
169 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
170 this.write_scalar(res, dest)?;
173 let items = this.read_scalar(args[0])?.to_machine_usize(this)?;
174 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
177 .ok_or_else(|| err_panic!(Overflow(mir::BinOp::Mul)))?;
178 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
179 this.write_scalar(res, dest)?;
181 "posix_memalign" => {
182 let ret = this.deref_operand(args[0])?;
183 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
184 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
185 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
186 if !align.is_power_of_two() {
187 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
189 if align < this.pointer_size().bytes() {
191 "posix_memalign: alignment must be at least the size of a pointer, but is {}",
197 this.write_null(ret.into())?;
199 let ptr = this.memory.allocate(
200 Size::from_bytes(size),
201 Align::from_bytes(align).unwrap(),
202 MiriMemoryKind::C.into(),
204 this.write_scalar(Scalar::Ptr(ptr), ret.into())?;
206 this.write_null(dest)?;
209 let ptr = this.read_scalar(args[0])?.not_undef()?;
210 this.free(ptr, MiriMemoryKind::C)?;
213 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
214 let new_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
215 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
216 this.write_scalar(res, dest)?;
220 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
221 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
223 throw_unsup!(HeapAllocZeroBytes);
225 if !align.is_power_of_two() {
226 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
228 let ptr = this.memory.allocate(
229 Size::from_bytes(size),
230 Align::from_bytes(align).unwrap(),
231 MiriMemoryKind::Rust.into(),
233 this.write_scalar(Scalar::Ptr(ptr), dest)?;
235 "__rust_alloc_zeroed" => {
236 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
237 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
239 throw_unsup!(HeapAllocZeroBytes);
241 if !align.is_power_of_two() {
242 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
244 let ptr = this.memory.allocate(
245 Size::from_bytes(size),
246 Align::from_bytes(align).unwrap(),
247 MiriMemoryKind::Rust.into(),
249 // We just allocated this, the access is definitely in-bounds.
251 .write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize))
253 this.write_scalar(Scalar::Ptr(ptr), dest)?;
255 "__rust_dealloc" => {
256 let ptr = this.read_scalar(args[0])?.not_undef()?;
257 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
258 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
260 throw_unsup!(HeapAllocZeroBytes);
262 if !align.is_power_of_two() {
263 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
265 let ptr = this.force_ptr(ptr)?;
266 this.memory.deallocate(
269 Size::from_bytes(old_size),
270 Align::from_bytes(align).unwrap(),
272 MiriMemoryKind::Rust.into(),
275 "__rust_realloc" => {
276 let ptr = this.read_scalar(args[0])?.to_ptr()?;
277 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
278 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
279 let new_size = this.read_scalar(args[3])?.to_machine_usize(this)?;
280 if old_size == 0 || new_size == 0 {
281 throw_unsup!(HeapAllocZeroBytes);
283 if !align.is_power_of_two() {
284 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
286 let align = Align::from_bytes(align).unwrap();
287 let new_ptr = this.memory.reallocate(
289 Some((Size::from_bytes(old_size), align)),
290 Size::from_bytes(new_size),
292 MiriMemoryKind::Rust.into(),
294 this.write_scalar(Scalar::Ptr(new_ptr), dest)?;
298 let sys_getrandom = this
299 .eval_path_scalar(&["libc", "SYS_getrandom"])?
300 .expect("Failed to get libc::SYS_getrandom")
301 .to_machine_usize(this)?;
303 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
304 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
305 match this.read_scalar(args[0])?.to_machine_usize(this)? {
306 id if id == sys_getrandom => {
307 // The first argument is the syscall id,
309 linux_getrandom(this, &args[1..], dest)?;
311 id => throw_unsup_format!("miri does not support syscall ID {}", id),
316 linux_getrandom(this, args, dest)?;
320 let _handle = this.read_scalar(args[0])?;
321 let symbol = this.read_scalar(args[1])?.not_undef()?;
322 let symbol_name = this.memory.read_c_str(symbol)?;
323 let err = format!("bad c unicode symbol: {:?}", symbol_name);
324 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
325 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
326 let ptr = this.memory.create_fn_alloc(FnVal::Other(dlsym));
327 this.write_scalar(Scalar::from(ptr), dest)?;
329 this.write_null(dest)?;
333 "__rust_maybe_catch_panic" => {
334 this.handle_catch_panic(args, dest, ret)?;
339 let left = this.read_scalar(args[0])?.not_undef()?;
340 let right = this.read_scalar(args[1])?.not_undef()?;
341 let n = Size::from_bytes(this.read_scalar(args[2])?.to_machine_usize(this)?);
344 let left_bytes = this.memory.read_bytes(left, n)?;
345 let right_bytes = this.memory.read_bytes(right, n)?;
347 use std::cmp::Ordering::*;
348 match left_bytes.cmp(right_bytes) {
355 this.write_scalar(Scalar::from_int(result, Size::from_bits(32)), dest)?;
359 let ptr = this.read_scalar(args[0])?.not_undef()?;
360 let val = this.read_scalar(args[1])?.to_i32()? as u8;
361 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
362 if let Some(idx) = this
364 .read_bytes(ptr, Size::from_bytes(num))?
367 .position(|&c| c == val)
369 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
370 this.write_scalar(new_ptr, dest)?;
372 this.write_null(dest)?;
377 let ptr = this.read_scalar(args[0])?.not_undef()?;
378 let val = this.read_scalar(args[1])?.to_i32()? as u8;
379 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
382 .read_bytes(ptr, Size::from_bytes(num))?
384 .position(|&c| c == val);
385 if let Some(idx) = idx {
386 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
387 this.write_scalar(new_ptr, dest)?;
389 this.write_null(dest)?;
393 "__errno_location" | "__error" => {
394 let errno_place = this.machine.last_error.unwrap();
395 this.write_scalar(errno_place.to_ref().to_scalar()?, dest)?;
399 let result = this.getenv(args[0])?;
400 this.write_scalar(result, dest)?;
404 let result = this.unsetenv(args[0])?;
405 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
409 let result = this.setenv(args[0], args[1])?;
410 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
414 let result = this.getcwd(args[0], args[1])?;
415 this.write_scalar(result, dest)?;
419 let result = this.chdir(args[0])?;
420 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
423 "open" | "open64" => {
424 let result = this.open(args[0], args[1])?;
425 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
429 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
430 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
433 "close" | "close$NOCANCEL" => {
434 let result = this.close(args[0])?;
435 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
439 let result = this.read(args[0], args[1], args[2])?;
440 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
444 let fd = this.read_scalar(args[0])?.to_i32()?;
445 let buf = this.read_scalar(args[1])?.not_undef()?;
446 let n = this.read_scalar(args[2])?.to_machine_usize(tcx)?;
447 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
448 let result = if fd == 1 || fd == 2 {
450 use std::io::{self, Write};
452 let buf_cont = this.memory.read_bytes(buf, Size::from_bytes(n))?;
453 // We need to flush to make sure this actually appears on the screen
454 let res = if fd == 1 {
455 // Stdout is buffered, flush to make sure it appears on the screen.
456 // This is the write() syscall of the interpreted program, we want it
457 // to correspond to a write() syscall on the host -- there is no good
458 // in adding extra buffering here.
459 let res = io::stdout().write(buf_cont);
460 io::stdout().flush().unwrap();
463 // No need to flush, stderr is not buffered.
464 io::stderr().write(buf_cont)
471 this.write(args[0], args[1], args[2])?
473 // Now, `result` is the value we return back to the program.
474 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
478 let result = this.unlink(args[0])?;
479 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
483 let result = this.clock_gettime(args[0], args[1])?;
484 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
488 let result = this.gettimeofday(args[0], args[1])?;
489 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
493 let ptr = this.read_scalar(args[0])?.not_undef()?;
494 let n = this.memory.read_c_str(ptr)?.len();
495 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
499 "cbrtf" | "coshf" | "sinhf" | "tanf" => {
500 // FIXME: Using host floats.
501 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
502 let f = match link_name {
509 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
511 // underscore case for windows
512 "_hypotf" | "hypotf" | "atan2f" => {
513 // FIXME: Using host floats.
514 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
515 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
516 let n = match link_name {
517 "_hypotf" | "hypotf" => f1.hypot(f2),
518 "atan2f" => f1.atan2(f2),
521 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
524 "cbrt" | "cosh" | "sinh" | "tan" => {
525 // FIXME: Using host floats.
526 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
527 let f = match link_name {
534 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
536 // underscore case for windows, here and below
537 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
538 "_hypot" | "hypot" | "atan2" => {
539 // FIXME: Using host floats.
540 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
541 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
542 let n = match link_name {
543 "_hypot" | "hypot" => f1.hypot(f2),
544 "atan2" => f1.atan2(f2),
547 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
549 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
550 "_ldexp" | "ldexp" | "scalbn" => {
551 let x = this.read_scalar(args[0])?.to_f64()?;
552 let exp = this.read_scalar(args[1])?.to_i32()?;
554 // Saturating cast to i16. Even those are outside the valid exponent range to
555 // `scalbn` below will do its over/underflow handling.
556 let exp = if exp > i16::max_value() as i32 {
558 } else if exp < i16::min_value() as i32 {
561 exp.try_into().unwrap()
564 let res = x.scalbn(exp);
565 this.write_scalar(Scalar::from_f64(res), dest)?;
568 // Some things needed for `sys::thread` initialization to go through.
569 "signal" | "sigaction" | "sigaltstack" => {
570 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
574 let name = this.read_scalar(args[0])?.to_i32()?;
576 trace!("sysconf() called with name {}", name);
577 // TODO: Cache the sysconf integers via Miri's global cache.
580 &["libc", "_SC_PAGESIZE"],
581 Scalar::from_int(PAGE_SIZE, dest.layout.size),
584 &["libc", "_SC_GETPW_R_SIZE_MAX"],
585 Scalar::from_int(-1, dest.layout.size),
588 &["libc", "_SC_NPROCESSORS_ONLN"],
589 Scalar::from_int(NUM_CPUS, dest.layout.size),
592 let mut result = None;
593 for &(path, path_value) in paths {
594 if let Some(val) = this.eval_path_scalar(path)? {
595 let val = val.to_i32()?;
597 result = Some(path_value);
602 if let Some(result) = result {
603 this.write_scalar(result, dest)?;
605 throw_unsup_format!("Unimplemented sysconf name: {}", name)
609 "sched_getaffinity" => {
610 // Return an error; `num_cpus` then falls back to `sysconf`.
611 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
615 this.write_null(dest)?;
618 // Hook pthread calls that go to the thread-local storage memory subsystem.
619 "pthread_key_create" => {
620 let key_place = this.deref_operand(args[0])?;
622 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
623 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
624 Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
628 // Figure out how large a pthread TLS key actually is.
629 // This is `libc::pthread_key_t`.
630 let key_type = args[0].layout.ty
632 .ok_or_else(|| err_ub_format!(
633 "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
636 let key_layout = this.layout_of(key_type)?;
638 // Create key and write it into the memory where `key_ptr` wants it.
639 let key = this.machine.tls.create_tls_key(dtor) as u128;
640 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
642 throw_unsup!(OutOfTls);
645 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
647 // Return success (`0`).
648 this.write_null(dest)?;
650 "pthread_key_delete" => {
651 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
652 this.machine.tls.delete_tls_key(key)?;
653 // Return success (0)
654 this.write_null(dest)?;
656 "pthread_getspecific" => {
657 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
658 let ptr = this.machine.tls.load_tls(key, tcx)?;
659 this.write_scalar(ptr, dest)?;
661 "pthread_setspecific" => {
662 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
663 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
664 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
666 // Return success (`0`).
667 this.write_null(dest)?;
670 // Stack size/address stuff.
672 | "pthread_attr_destroy"
674 | "pthread_attr_setstacksize" => {
675 this.write_null(dest)?;
677 "pthread_attr_getstack" => {
678 let addr_place = this.deref_operand(args[1])?;
679 let size_place = this.deref_operand(args[2])?;
682 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
686 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
690 // Return success (`0`).
691 this.write_null(dest)?;
694 // We don't support threading. (Also for Windows.)
695 "pthread_create" | "CreateThread" => {
696 throw_unsup_format!("Miri does not support threading");
699 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
700 "pthread_mutexattr_init"
701 | "pthread_mutexattr_settype"
702 | "pthread_mutex_init"
703 | "pthread_mutexattr_destroy"
704 | "pthread_mutex_lock"
705 | "pthread_mutex_unlock"
706 | "pthread_mutex_destroy"
707 | "pthread_rwlock_rdlock"
708 | "pthread_rwlock_unlock"
709 | "pthread_rwlock_wrlock"
710 | "pthread_rwlock_destroy"
711 | "pthread_condattr_init"
712 | "pthread_condattr_setclock"
713 | "pthread_cond_init"
714 | "pthread_condattr_destroy"
715 | "pthread_cond_destroy" => {
716 this.write_null(dest)?;
719 // We don't support fork so we don't have to do anything for atfork.
720 "pthread_atfork" => {
721 this.write_null(dest)?;
725 // 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.
726 let addr = this.read_scalar(args[0])?.not_undef()?;
727 this.write_scalar(addr, dest)?;
730 this.write_null(dest)?;
734 "pthread_attr_get_np" | "pthread_getattr_np" => {
735 this.write_null(dest)?;
737 "pthread_get_stackaddr_np" => {
738 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
739 this.write_scalar(stack_addr, dest)?;
741 "pthread_get_stacksize_np" => {
742 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
743 this.write_scalar(stack_size, dest)?;
746 // FIXME: register the destructor.
749 this.write_scalar(this.machine.argc.expect("machine must be initialized"), dest)?;
752 this.write_scalar(this.machine.argv.expect("machine must be initialized"), dest)?;
754 "SecRandomCopyBytes" => {
755 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
756 let ptr = this.read_scalar(args[2])?.not_undef()?;
757 this.gen_random(ptr, len as usize)?;
758 this.write_null(dest)?;
761 // Windows API stubs.
763 // DWORD = ULONG = u32
765 "GetProcessHeap" => {
766 // Just fake a HANDLE
767 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
770 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
771 let flags = this.read_scalar(args[1])?.to_u32()?;
772 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
773 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
774 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
775 this.write_scalar(res, dest)?;
778 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
779 let _flags = this.read_scalar(args[1])?.to_u32()?;
780 let ptr = this.read_scalar(args[2])?.not_undef()?;
781 this.free(ptr, MiriMemoryKind::WinHeap)?;
782 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
785 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
786 let _flags = this.read_scalar(args[1])?.to_u32()?;
787 let ptr = this.read_scalar(args[2])?.not_undef()?;
788 let size = this.read_scalar(args[3])?.to_machine_usize(this)?;
789 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
790 this.write_scalar(res, dest)?;
794 this.set_last_error(this.read_scalar(args[0])?.not_undef()?)?;
797 let last_error = this.get_last_error()?;
798 this.write_scalar(last_error, dest)?;
801 "AddVectoredExceptionHandler" => {
802 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
803 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
805 "InitializeCriticalSection"
806 | "EnterCriticalSection"
807 | "LeaveCriticalSection"
808 | "DeleteCriticalSection" => {
809 // Nothing to do, not even a return value.
813 | "TryEnterCriticalSection"
814 | "GetConsoleScreenBufferInfo"
815 | "SetConsoleTextAttribute" => {
816 // Pretend these do not exist / nothing happened, by returning zero.
817 this.write_null(dest)?;
820 let system_info = this.deref_operand(args[0])?;
821 // Initialize with `0`.
823 .write_bytes(system_info.ptr, iter::repeat(0u8).take(system_info.layout.size.bytes() as usize))?;
824 // Set number of processors.
825 let dword_size = Size::from_bytes(4);
826 let num_cpus = this.mplace_field(system_info, 6)?;
828 Scalar::from_int(NUM_CPUS, dword_size),
834 // This just creates a key; Windows does not natively support TLS destructors.
836 // Create key and return it.
837 let key = this.machine.tls.create_tls_key(None) as u128;
839 // Figure out how large a TLS key actually is. This is `c::DWORD`.
840 if dest.layout.size.bits() < 128
841 && key >= (1u128 << dest.layout.size.bits() as u128)
843 throw_unsup!(OutOfTls);
845 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
848 let key = this.read_scalar(args[0])?.to_u32()? as u128;
849 let ptr = this.machine.tls.load_tls(key, tcx)?;
850 this.write_scalar(ptr, dest)?;
853 let key = this.read_scalar(args[0])?.to_u32()? as u128;
854 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
855 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
857 // Return success (`1`).
858 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
861 let which = this.read_scalar(args[0])?.to_i32()?;
862 // We just make this the identity function, so we know later in `WriteFile`
864 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
867 let handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
868 let buf = this.read_scalar(args[1])?.not_undef()?;
869 let n = this.read_scalar(args[2])?.to_u32()?;
870 let written_place = this.deref_operand(args[3])?;
871 // Spec says to always write `0` first.
872 this.write_null(written_place.into())?;
873 let written = if handle == -11 || handle == -12 {
875 use std::io::{self, Write};
879 .read_bytes(buf, Size::from_bytes(u64::from(n)))?;
880 let res = if handle == -11 {
881 io::stdout().write(buf_cont)
883 io::stderr().write(buf_cont)
885 res.ok().map(|n| n as u32)
887 eprintln!("Miri: Ignored output to handle {}", handle);
888 // Pretend it all went well.
891 // If there was no error, write back how much was written.
892 if let Some(n) = written {
893 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
895 // Return whether this was a success.
897 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
901 "GetConsoleMode" => {
902 // Everything is a pipe.
903 this.write_null(dest)?;
905 "GetEnvironmentVariableW" => {
906 // This is not the env var you are looking for.
907 this.set_last_error(Scalar::from_u32(203))?; // ERROR_ENVVAR_NOT_FOUND
908 this.write_null(dest)?;
910 "GetCommandLineW" => {
911 this.write_scalar(this.machine.cmd_line.expect("machine must be initialized"), dest)?;
913 // The actual name of 'RtlGenRandom'
914 "SystemFunction036" => {
915 let ptr = this.read_scalar(args[0])?.not_undef()?;
916 let len = this.read_scalar(args[1])?.to_u32()?;
917 this.gen_random(ptr, len as usize)?;
918 this.write_scalar(Scalar::from_bool(true), dest)?;
921 // We can't execute anything else.
922 _ => throw_unsup_format!("can't call foreign function: {}", link_name),
925 this.goto_block(Some(ret))?;
926 this.dump_place(*dest);
930 /// Evaluates the scalar at the specified path. Returns Some(val)
931 /// if the path could be resolved, and None otherwise
935 ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
936 let this = self.eval_context_mut();
937 if let Ok(instance) = this.resolve_path(path) {
942 let const_val = this.const_eval_raw(cid)?;
943 let const_val = this.read_scalar(const_val.into())?;
944 return Ok(Some(const_val));
950 // Shims the linux 'getrandom()' syscall.
951 fn linux_getrandom<'tcx>(
952 this: &mut MiriEvalContext<'_, 'tcx>,
953 args: &[OpTy<'tcx, Tag>],
954 dest: PlaceTy<'tcx, Tag>,
955 ) -> InterpResult<'tcx> {
956 let ptr = this.read_scalar(args[0])?.not_undef()?;
957 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
959 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
960 // neither of which have any effect on our current PRNG.
961 let _flags = this.read_scalar(args[2])?.to_i32()?;
963 this.gen_random(ptr, len as usize)?;
964 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;