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 `extern "Rust" { fn __rust_start_panic(...) }`
135 // We forward this to the underlying *implementation* in "libpanic_unwind"
136 "__rust_start_panic" => {
137 let start_panic_instance = this.resolve_path(&["panic_unwind", "__rust_start_panic"])?;
138 return Ok(Some(this.load_mir(start_panic_instance.def, None)?));
141 // During a normal (non-Miri) compilation,
142 // this gets resolved to the '#[panic_handler]` function at link time,
143 // which corresponds to the function with the `#[panic_handler]` attribute.
145 // Since we're interpreting mir, we forward it to the implementation of `panic_impl`
147 // This is used by libcore to forward panics to the actual
150 let panic_impl_id = this.tcx.lang_items().panic_impl().unwrap();
151 let panic_impl_instance = ty::Instance::mono(*this.tcx, panic_impl_id);
152 return Ok(Some(this.load_mir(panic_impl_instance.def, None)?));
154 "exit" | "ExitProcess" => {
155 // it's really u32 for ExitProcess, but we have to put it into the `Exit` error variant anyway
156 let code = this.read_scalar(args[0])?.to_i32()?;
157 return Err(InterpError::Exit(code).into());
161 throw_unsup_format!("can't call (diverging) foreign function: {}", link_name);
166 // Next: functions that assume a ret and dest.
167 let dest = dest.expect("we already checked for a dest");
168 let ret = ret.expect("dest is `Some` but ret is `None`");
171 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
172 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
173 this.write_scalar(res, dest)?;
176 let items = this.read_scalar(args[0])?.to_machine_usize(this)?;
177 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
180 .ok_or_else(|| err_panic!(Overflow(mir::BinOp::Mul)))?;
181 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
182 this.write_scalar(res, dest)?;
184 "posix_memalign" => {
185 let ret = this.deref_operand(args[0])?;
186 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
187 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
188 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
189 if !align.is_power_of_two() {
190 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
192 if align < this.pointer_size().bytes() {
194 "posix_memalign: alignment must be at least the size of a pointer, but is {}",
200 this.write_null(ret.into())?;
202 let ptr = this.memory.allocate(
203 Size::from_bytes(size),
204 Align::from_bytes(align).unwrap(),
205 MiriMemoryKind::C.into(),
207 this.write_scalar(Scalar::Ptr(ptr), ret.into())?;
209 this.write_null(dest)?;
212 let ptr = this.read_scalar(args[0])?.not_undef()?;
213 this.free(ptr, MiriMemoryKind::C)?;
216 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
217 let new_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
218 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
219 this.write_scalar(res, dest)?;
223 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
224 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
226 throw_unsup!(HeapAllocZeroBytes);
228 if !align.is_power_of_two() {
229 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
231 let ptr = this.memory.allocate(
232 Size::from_bytes(size),
233 Align::from_bytes(align).unwrap(),
234 MiriMemoryKind::Rust.into(),
236 this.write_scalar(Scalar::Ptr(ptr), dest)?;
238 "__rust_alloc_zeroed" => {
239 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
240 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
242 throw_unsup!(HeapAllocZeroBytes);
244 if !align.is_power_of_two() {
245 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
247 let ptr = this.memory.allocate(
248 Size::from_bytes(size),
249 Align::from_bytes(align).unwrap(),
250 MiriMemoryKind::Rust.into(),
252 // We just allocated this, the access is definitely in-bounds.
254 .write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize))
256 this.write_scalar(Scalar::Ptr(ptr), dest)?;
258 "__rust_dealloc" => {
259 let ptr = this.read_scalar(args[0])?.not_undef()?;
260 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
261 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
263 throw_unsup!(HeapAllocZeroBytes);
265 if !align.is_power_of_two() {
266 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
268 let ptr = this.force_ptr(ptr)?;
269 this.memory.deallocate(
272 Size::from_bytes(old_size),
273 Align::from_bytes(align).unwrap(),
275 MiriMemoryKind::Rust.into(),
278 "__rust_realloc" => {
279 let ptr = this.read_scalar(args[0])?.to_ptr()?;
280 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
281 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
282 let new_size = this.read_scalar(args[3])?.to_machine_usize(this)?;
283 if old_size == 0 || new_size == 0 {
284 throw_unsup!(HeapAllocZeroBytes);
286 if !align.is_power_of_two() {
287 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
289 let align = Align::from_bytes(align).unwrap();
290 let new_ptr = this.memory.reallocate(
292 Some((Size::from_bytes(old_size), align)),
293 Size::from_bytes(new_size),
295 MiriMemoryKind::Rust.into(),
297 this.write_scalar(Scalar::Ptr(new_ptr), dest)?;
301 let sys_getrandom = this
302 .eval_path_scalar(&["libc", "SYS_getrandom"])?
303 .expect("Failed to get libc::SYS_getrandom")
304 .to_machine_usize(this)?;
306 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
307 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
308 match this.read_scalar(args[0])?.to_machine_usize(this)? {
309 id if id == sys_getrandom => {
310 // The first argument is the syscall id,
312 linux_getrandom(this, &args[1..], dest)?;
314 id => throw_unsup_format!("miri does not support syscall ID {}", id),
319 linux_getrandom(this, args, dest)?;
323 let _handle = this.read_scalar(args[0])?;
324 let symbol = this.read_scalar(args[1])?.not_undef()?;
325 let symbol_name = this.memory.read_c_str(symbol)?;
326 let err = format!("bad c unicode symbol: {:?}", symbol_name);
327 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
328 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
329 let ptr = this.memory.create_fn_alloc(FnVal::Other(dlsym));
330 this.write_scalar(Scalar::from(ptr), dest)?;
332 this.write_null(dest)?;
336 "__rust_maybe_catch_panic" => {
337 this.handle_catch_panic(args, dest, ret)?;
342 let left = this.read_scalar(args[0])?.not_undef()?;
343 let right = this.read_scalar(args[1])?.not_undef()?;
344 let n = Size::from_bytes(this.read_scalar(args[2])?.to_machine_usize(this)?);
347 let left_bytes = this.memory.read_bytes(left, n)?;
348 let right_bytes = this.memory.read_bytes(right, n)?;
350 use std::cmp::Ordering::*;
351 match left_bytes.cmp(right_bytes) {
358 this.write_scalar(Scalar::from_int(result, Size::from_bits(32)), dest)?;
362 let ptr = this.read_scalar(args[0])?.not_undef()?;
363 let val = this.read_scalar(args[1])?.to_i32()? as u8;
364 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
365 if let Some(idx) = this
367 .read_bytes(ptr, Size::from_bytes(num))?
370 .position(|&c| c == val)
372 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
373 this.write_scalar(new_ptr, dest)?;
375 this.write_null(dest)?;
380 let ptr = this.read_scalar(args[0])?.not_undef()?;
381 let val = this.read_scalar(args[1])?.to_i32()? as u8;
382 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
385 .read_bytes(ptr, Size::from_bytes(num))?
387 .position(|&c| c == val);
388 if let Some(idx) = idx {
389 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
390 this.write_scalar(new_ptr, dest)?;
392 this.write_null(dest)?;
396 "__errno_location" | "__error" => {
397 let errno_place = this.machine.last_error.unwrap();
398 this.write_scalar(errno_place.to_ref().to_scalar()?, dest)?;
402 let result = this.getenv(args[0])?;
403 this.write_scalar(result, dest)?;
407 let result = this.unsetenv(args[0])?;
408 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
412 let result = this.setenv(args[0], args[1])?;
413 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
417 let result = this.getcwd(args[0], args[1])?;
418 this.write_scalar(result, dest)?;
422 let result = this.chdir(args[0])?;
423 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
426 "open" | "open64" => {
427 let result = this.open(args[0], args[1])?;
428 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
432 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
433 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
436 "close" | "close$NOCANCEL" => {
437 let result = this.close(args[0])?;
438 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
442 let result = this.read(args[0], args[1], args[2])?;
443 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
447 let fd = this.read_scalar(args[0])?.to_i32()?;
448 let buf = this.read_scalar(args[1])?.not_undef()?;
449 let n = this.read_scalar(args[2])?.to_machine_usize(tcx)?;
450 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
451 let result = if fd == 1 || fd == 2 {
453 use std::io::{self, Write};
455 let buf_cont = this.memory.read_bytes(buf, Size::from_bytes(n))?;
456 // We need to flush to make sure this actually appears on the screen
457 let res = if fd == 1 {
458 // Stdout is buffered, flush to make sure it appears on the screen.
459 // This is the write() syscall of the interpreted program, we want it
460 // to correspond to a write() syscall on the host -- there is no good
461 // in adding extra buffering here.
462 let res = io::stdout().write(buf_cont);
463 io::stdout().flush().unwrap();
466 // No need to flush, stderr is not buffered.
467 io::stderr().write(buf_cont)
474 this.write(args[0], args[1], args[2])?
476 // Now, `result` is the value we return back to the program.
477 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
481 let result = this.unlink(args[0])?;
482 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
486 let result = this.clock_gettime(args[0], args[1])?;
487 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
491 let result = this.gettimeofday(args[0], args[1])?;
492 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
496 let ptr = this.read_scalar(args[0])?.not_undef()?;
497 let n = this.memory.read_c_str(ptr)?.len();
498 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
502 "cbrtf" | "coshf" | "sinhf" | "tanf" => {
503 // FIXME: Using host floats.
504 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
505 let f = match link_name {
512 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
514 // underscore case for windows
515 "_hypotf" | "hypotf" | "atan2f" => {
516 // FIXME: Using host floats.
517 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
518 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
519 let n = match link_name {
520 "_hypotf" | "hypotf" => f1.hypot(f2),
521 "atan2f" => f1.atan2(f2),
524 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
527 "cbrt" | "cosh" | "sinh" | "tan" => {
528 // FIXME: Using host floats.
529 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
530 let f = match link_name {
537 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
539 // underscore case for windows, here and below
540 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
541 "_hypot" | "hypot" | "atan2" => {
542 // FIXME: Using host floats.
543 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
544 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
545 let n = match link_name {
546 "_hypot" | "hypot" => f1.hypot(f2),
547 "atan2" => f1.atan2(f2),
550 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
552 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
553 "_ldexp" | "ldexp" | "scalbn" => {
554 let x = this.read_scalar(args[0])?.to_f64()?;
555 let exp = this.read_scalar(args[1])?.to_i32()?;
557 // Saturating cast to i16. Even those are outside the valid exponent range to
558 // `scalbn` below will do its over/underflow handling.
559 let exp = if exp > i16::max_value() as i32 {
561 } else if exp < i16::min_value() as i32 {
564 exp.try_into().unwrap()
567 let res = x.scalbn(exp);
568 this.write_scalar(Scalar::from_f64(res), dest)?;
571 // Some things needed for `sys::thread` initialization to go through.
572 "signal" | "sigaction" | "sigaltstack" => {
573 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
577 let name = this.read_scalar(args[0])?.to_i32()?;
579 trace!("sysconf() called with name {}", name);
580 // TODO: Cache the sysconf integers via Miri's global cache.
583 &["libc", "_SC_PAGESIZE"],
584 Scalar::from_int(PAGE_SIZE, dest.layout.size),
587 &["libc", "_SC_GETPW_R_SIZE_MAX"],
588 Scalar::from_int(-1, dest.layout.size),
591 &["libc", "_SC_NPROCESSORS_ONLN"],
592 Scalar::from_int(NUM_CPUS, dest.layout.size),
595 let mut result = None;
596 for &(path, path_value) in paths {
597 if let Some(val) = this.eval_path_scalar(path)? {
598 let val = val.to_i32()?;
600 result = Some(path_value);
605 if let Some(result) = result {
606 this.write_scalar(result, dest)?;
608 throw_unsup_format!("Unimplemented sysconf name: {}", name)
612 "sched_getaffinity" => {
613 // Return an error; `num_cpus` then falls back to `sysconf`.
614 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
618 this.write_null(dest)?;
621 // Hook pthread calls that go to the thread-local storage memory subsystem.
622 "pthread_key_create" => {
623 let key_place = this.deref_operand(args[0])?;
625 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
626 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
627 Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
631 // Figure out how large a pthread TLS key actually is.
632 // This is `libc::pthread_key_t`.
633 let key_type = args[0].layout.ty
635 .ok_or_else(|| err_ub_format!(
636 "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
639 let key_layout = this.layout_of(key_type)?;
641 // Create key and write it into the memory where `key_ptr` wants it.
642 let key = this.machine.tls.create_tls_key(dtor) as u128;
643 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
645 throw_unsup!(OutOfTls);
648 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
650 // Return success (`0`).
651 this.write_null(dest)?;
653 "pthread_key_delete" => {
654 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
655 this.machine.tls.delete_tls_key(key)?;
656 // Return success (0)
657 this.write_null(dest)?;
659 "pthread_getspecific" => {
660 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
661 let ptr = this.machine.tls.load_tls(key, tcx)?;
662 this.write_scalar(ptr, dest)?;
664 "pthread_setspecific" => {
665 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
666 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
667 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
669 // Return success (`0`).
670 this.write_null(dest)?;
673 // Stack size/address stuff.
675 | "pthread_attr_destroy"
677 | "pthread_attr_setstacksize" => {
678 this.write_null(dest)?;
680 "pthread_attr_getstack" => {
681 let addr_place = this.deref_operand(args[1])?;
682 let size_place = this.deref_operand(args[2])?;
685 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
689 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
693 // Return success (`0`).
694 this.write_null(dest)?;
697 // We don't support threading. (Also for Windows.)
698 "pthread_create" | "CreateThread" => {
699 throw_unsup_format!("Miri does not support threading");
702 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
703 "pthread_mutexattr_init"
704 | "pthread_mutexattr_settype"
705 | "pthread_mutex_init"
706 | "pthread_mutexattr_destroy"
707 | "pthread_mutex_lock"
708 | "pthread_mutex_unlock"
709 | "pthread_mutex_destroy"
710 | "pthread_rwlock_rdlock"
711 | "pthread_rwlock_unlock"
712 | "pthread_rwlock_wrlock"
713 | "pthread_rwlock_destroy"
714 | "pthread_condattr_init"
715 | "pthread_condattr_setclock"
716 | "pthread_cond_init"
717 | "pthread_condattr_destroy"
718 | "pthread_cond_destroy" => {
719 this.write_null(dest)?;
722 // We don't support fork so we don't have to do anything for atfork.
723 "pthread_atfork" => {
724 this.write_null(dest)?;
728 // 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.
729 let addr = this.read_scalar(args[0])?.not_undef()?;
730 this.write_scalar(addr, dest)?;
733 this.write_null(dest)?;
737 "pthread_attr_get_np" | "pthread_getattr_np" => {
738 this.write_null(dest)?;
740 "pthread_get_stackaddr_np" => {
741 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
742 this.write_scalar(stack_addr, dest)?;
744 "pthread_get_stacksize_np" => {
745 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
746 this.write_scalar(stack_size, dest)?;
749 // FIXME: register the destructor.
752 this.write_scalar(this.machine.argc.expect("machine must be initialized"), dest)?;
755 this.write_scalar(this.machine.argv.expect("machine must be initialized"), dest)?;
757 "SecRandomCopyBytes" => {
758 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
759 let ptr = this.read_scalar(args[2])?.not_undef()?;
760 this.gen_random(ptr, len as usize)?;
761 this.write_null(dest)?;
764 // Windows API stubs.
766 // DWORD = ULONG = u32
768 "GetProcessHeap" => {
769 // Just fake a HANDLE
770 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
773 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
774 let flags = this.read_scalar(args[1])?.to_u32()?;
775 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
776 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
777 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
778 this.write_scalar(res, dest)?;
781 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
782 let _flags = this.read_scalar(args[1])?.to_u32()?;
783 let ptr = this.read_scalar(args[2])?.not_undef()?;
784 this.free(ptr, MiriMemoryKind::WinHeap)?;
785 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
788 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
789 let _flags = this.read_scalar(args[1])?.to_u32()?;
790 let ptr = this.read_scalar(args[2])?.not_undef()?;
791 let size = this.read_scalar(args[3])?.to_machine_usize(this)?;
792 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
793 this.write_scalar(res, dest)?;
797 this.set_last_error(this.read_scalar(args[0])?.not_undef()?)?;
800 let last_error = this.get_last_error()?;
801 this.write_scalar(last_error, dest)?;
804 "AddVectoredExceptionHandler" => {
805 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
806 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
808 "InitializeCriticalSection"
809 | "EnterCriticalSection"
810 | "LeaveCriticalSection"
811 | "DeleteCriticalSection" => {
812 // Nothing to do, not even a return value.
816 | "TryEnterCriticalSection"
817 | "GetConsoleScreenBufferInfo"
818 | "SetConsoleTextAttribute" => {
819 // Pretend these do not exist / nothing happened, by returning zero.
820 this.write_null(dest)?;
823 let system_info = this.deref_operand(args[0])?;
824 // Initialize with `0`.
826 .write_bytes(system_info.ptr, iter::repeat(0u8).take(system_info.layout.size.bytes() as usize))?;
827 // Set number of processors.
828 let dword_size = Size::from_bytes(4);
829 let num_cpus = this.mplace_field(system_info, 6)?;
831 Scalar::from_int(NUM_CPUS, dword_size),
837 // This just creates a key; Windows does not natively support TLS destructors.
839 // Create key and return it.
840 let key = this.machine.tls.create_tls_key(None) as u128;
842 // Figure out how large a TLS key actually is. This is `c::DWORD`.
843 if dest.layout.size.bits() < 128
844 && key >= (1u128 << dest.layout.size.bits() as u128)
846 throw_unsup!(OutOfTls);
848 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
851 let key = this.read_scalar(args[0])?.to_u32()? as u128;
852 let ptr = this.machine.tls.load_tls(key, tcx)?;
853 this.write_scalar(ptr, dest)?;
856 let key = this.read_scalar(args[0])?.to_u32()? as u128;
857 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
858 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
860 // Return success (`1`).
861 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
864 let which = this.read_scalar(args[0])?.to_i32()?;
865 // We just make this the identity function, so we know later in `WriteFile`
867 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
870 let handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
871 let buf = this.read_scalar(args[1])?.not_undef()?;
872 let n = this.read_scalar(args[2])?.to_u32()?;
873 let written_place = this.deref_operand(args[3])?;
874 // Spec says to always write `0` first.
875 this.write_null(written_place.into())?;
876 let written = if handle == -11 || handle == -12 {
878 use std::io::{self, Write};
882 .read_bytes(buf, Size::from_bytes(u64::from(n)))?;
883 let res = if handle == -11 {
884 io::stdout().write(buf_cont)
886 io::stderr().write(buf_cont)
888 res.ok().map(|n| n as u32)
890 eprintln!("Miri: Ignored output to handle {}", handle);
891 // Pretend it all went well.
894 // If there was no error, write back how much was written.
895 if let Some(n) = written {
896 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
898 // Return whether this was a success.
900 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
904 "GetConsoleMode" => {
905 // Everything is a pipe.
906 this.write_null(dest)?;
908 "GetEnvironmentVariableW" => {
909 // This is not the env var you are looking for.
910 this.set_last_error(Scalar::from_u32(203))?; // ERROR_ENVVAR_NOT_FOUND
911 this.write_null(dest)?;
913 "GetCommandLineW" => {
914 this.write_scalar(this.machine.cmd_line.expect("machine must be initialized"), dest)?;
916 // The actual name of 'RtlGenRandom'
917 "SystemFunction036" => {
918 let ptr = this.read_scalar(args[0])?.not_undef()?;
919 let len = this.read_scalar(args[1])?.to_u32()?;
920 this.gen_random(ptr, len as usize)?;
921 this.write_scalar(Scalar::from_bool(true), dest)?;
924 // We can't execute anything else.
925 _ => throw_unsup_format!("can't call foreign function: {}", link_name),
928 this.goto_block(Some(ret))?;
929 this.dump_place(*dest);
933 /// Evaluates the scalar at the specified path. Returns Some(val)
934 /// if the path could be resolved, and None otherwise
938 ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
939 let this = self.eval_context_mut();
940 if let Ok(instance) = this.resolve_path(path) {
945 let const_val = this.const_eval_raw(cid)?;
946 let const_val = this.read_scalar(const_val.into())?;
947 return Ok(Some(const_val));
953 // Shims the linux 'getrandom()' syscall.
954 fn linux_getrandom<'tcx>(
955 this: &mut MiriEvalContext<'_, 'tcx>,
956 args: &[OpTy<'tcx, Tag>],
957 dest: PlaceTy<'tcx, Tag>,
958 ) -> InterpResult<'tcx> {
959 let ptr = this.read_scalar(args[0])?.not_undef()?;
960 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
962 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
963 // neither of which have any effect on our current PRNG.
964 let _flags = this.read_scalar(args[2])?.to_i32()?;
966 this.gen_random(ptr, len as usize)?;
967 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;