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 // FIXME we might want to cache this... but it's not really performance-critical.
139 let panic_runtime = tcx.crates().iter()
140 .find(|cnum| tcx.is_panic_runtime(**cnum))
141 .expect("No panic runtime found!");
142 let panic_runtime = tcx.crate_name(*panic_runtime);
143 let start_panic_instance = this.resolve_path(&[&*panic_runtime.as_str(), "__rust_start_panic"])?;
144 return Ok(Some(&*this.load_mir(start_panic_instance.def, None)?));
146 // Similarly, we forward calls to the `panic_impl` foreign item to its implementation.
147 // The implementation is provided by the function with the `#[panic_handler]` attribute.
149 let panic_impl_id = this.tcx.lang_items().panic_impl().unwrap();
150 let panic_impl_instance = ty::Instance::mono(*this.tcx, panic_impl_id);
151 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` variant anyway
156 let code = this.read_scalar(args[0])?.to_i32()?;
157 throw_machine_stop!(TerminationInfo::Exit(code.into()));
160 if let Some(p) = ret {
163 throw_unsup_format!("can't call (diverging) foreign function: {}", link_name);
168 // Next: functions that return.
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(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(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(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(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" | "acosf" | "asinf" | "atanf" => {
503 // FIXME: Using host floats.
504 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
505 let f = match link_name {
515 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
517 // underscore case for windows
518 "_hypotf" | "hypotf" | "atan2f" => {
519 // FIXME: Using host floats.
520 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
521 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
522 let n = match link_name {
523 "_hypotf" | "hypotf" => f1.hypot(f2),
524 "atan2f" => f1.atan2(f2),
527 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
530 "cbrt" | "cosh" | "sinh" | "tan" | "acos" | "asin" | "atan" => {
531 // FIXME: Using host floats.
532 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
533 let f = match link_name {
543 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
545 // underscore case for windows, here and below
546 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
547 "_hypot" | "hypot" | "atan2" => {
548 // FIXME: Using host floats.
549 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
550 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
551 let n = match link_name {
552 "_hypot" | "hypot" => f1.hypot(f2),
553 "atan2" => f1.atan2(f2),
556 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
558 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
559 "_ldexp" | "ldexp" | "scalbn" => {
560 let x = this.read_scalar(args[0])?.to_f64()?;
561 let exp = this.read_scalar(args[1])?.to_i32()?;
563 // Saturating cast to i16. Even those are outside the valid exponent range to
564 // `scalbn` below will do its over/underflow handling.
565 let exp = if exp > i16::max_value() as i32 {
567 } else if exp < i16::min_value() as i32 {
570 exp.try_into().unwrap()
573 let res = x.scalbn(exp);
574 this.write_scalar(Scalar::from_f64(res), dest)?;
577 // Some things needed for `sys::thread` initialization to go through.
578 "signal" | "sigaction" | "sigaltstack" => {
579 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
583 let name = this.read_scalar(args[0])?.to_i32()?;
585 trace!("sysconf() called with name {}", name);
586 // TODO: Cache the sysconf integers via Miri's global cache.
589 &["libc", "_SC_PAGESIZE"],
590 Scalar::from_int(PAGE_SIZE, dest.layout.size),
593 &["libc", "_SC_GETPW_R_SIZE_MAX"],
594 Scalar::from_int(-1, dest.layout.size),
597 &["libc", "_SC_NPROCESSORS_ONLN"],
598 Scalar::from_int(NUM_CPUS, dest.layout.size),
601 let mut result = None;
602 for &(path, path_value) in paths {
603 if let Some(val) = this.eval_path_scalar(path)? {
604 let val = val.to_i32()?;
606 result = Some(path_value);
611 if let Some(result) = result {
612 this.write_scalar(result, dest)?;
614 throw_unsup_format!("Unimplemented sysconf name: {}", name)
618 "sched_getaffinity" => {
619 // Return an error; `num_cpus` then falls back to `sysconf`.
620 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
624 this.write_null(dest)?;
627 // Hook pthread calls that go to the thread-local storage memory subsystem.
628 "pthread_key_create" => {
629 let key_place = this.deref_operand(args[0])?;
631 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
632 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
633 Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
637 // Figure out how large a pthread TLS key actually is.
638 // This is `libc::pthread_key_t`.
639 let key_type = args[0].layout.ty
641 .ok_or_else(|| err_ub_format!(
642 "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
645 let key_layout = this.layout_of(key_type)?;
647 // Create key and write it into the memory where `key_ptr` wants it.
648 let key = this.machine.tls.create_tls_key(dtor) as u128;
649 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
651 throw_unsup!(OutOfTls);
654 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
656 // Return success (`0`).
657 this.write_null(dest)?;
659 "pthread_key_delete" => {
660 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
661 this.machine.tls.delete_tls_key(key)?;
662 // Return success (0)
663 this.write_null(dest)?;
665 "pthread_getspecific" => {
666 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
667 let ptr = this.machine.tls.load_tls(key, tcx)?;
668 this.write_scalar(ptr, dest)?;
670 "pthread_setspecific" => {
671 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
672 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
673 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
675 // Return success (`0`).
676 this.write_null(dest)?;
679 // Stack size/address stuff.
681 | "pthread_attr_destroy"
683 | "pthread_attr_setstacksize" => {
684 this.write_null(dest)?;
686 "pthread_attr_getstack" => {
687 let addr_place = this.deref_operand(args[1])?;
688 let size_place = this.deref_operand(args[2])?;
691 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
695 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
699 // Return success (`0`).
700 this.write_null(dest)?;
703 // We don't support threading. (Also for Windows.)
704 "pthread_create" | "CreateThread" => {
705 throw_unsup_format!("Miri does not support threading");
708 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
709 "pthread_mutexattr_init"
710 | "pthread_mutexattr_settype"
711 | "pthread_mutex_init"
712 | "pthread_mutexattr_destroy"
713 | "pthread_mutex_lock"
714 | "pthread_mutex_unlock"
715 | "pthread_mutex_destroy"
716 | "pthread_rwlock_rdlock"
717 | "pthread_rwlock_unlock"
718 | "pthread_rwlock_wrlock"
719 | "pthread_rwlock_destroy"
720 | "pthread_condattr_init"
721 | "pthread_condattr_setclock"
722 | "pthread_cond_init"
723 | "pthread_condattr_destroy"
724 | "pthread_cond_destroy" => {
725 this.write_null(dest)?;
728 // We don't support fork so we don't have to do anything for atfork.
729 "pthread_atfork" => {
730 this.write_null(dest)?;
734 // 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.
735 let addr = this.read_scalar(args[0])?.not_undef()?;
736 this.write_scalar(addr, dest)?;
739 this.write_null(dest)?;
743 "pthread_attr_get_np" | "pthread_getattr_np" => {
744 this.write_null(dest)?;
746 "pthread_get_stackaddr_np" => {
747 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
748 this.write_scalar(stack_addr, dest)?;
750 "pthread_get_stacksize_np" => {
751 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
752 this.write_scalar(stack_size, dest)?;
755 // FIXME: register the destructor.
758 this.write_scalar(this.machine.argc.expect("machine must be initialized"), dest)?;
761 this.write_scalar(this.machine.argv.expect("machine must be initialized"), dest)?;
763 "SecRandomCopyBytes" => {
764 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
765 let ptr = this.read_scalar(args[2])?.not_undef()?;
766 this.gen_random(ptr, len as usize)?;
767 this.write_null(dest)?;
770 // Windows API stubs.
772 // DWORD = ULONG = u32
774 "GetProcessHeap" => {
775 // Just fake a HANDLE
776 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
779 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
780 let flags = this.read_scalar(args[1])?.to_u32()?;
781 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
782 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
783 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
784 this.write_scalar(res, dest)?;
787 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
788 let _flags = this.read_scalar(args[1])?.to_u32()?;
789 let ptr = this.read_scalar(args[2])?.not_undef()?;
790 this.free(ptr, MiriMemoryKind::WinHeap)?;
791 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
794 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
795 let _flags = this.read_scalar(args[1])?.to_u32()?;
796 let ptr = this.read_scalar(args[2])?.not_undef()?;
797 let size = this.read_scalar(args[3])?.to_machine_usize(this)?;
798 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
799 this.write_scalar(res, dest)?;
803 this.set_last_error(this.read_scalar(args[0])?.not_undef()?)?;
806 let last_error = this.get_last_error()?;
807 this.write_scalar(last_error, dest)?;
810 "AddVectoredExceptionHandler" => {
811 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
812 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
814 "InitializeCriticalSection"
815 | "EnterCriticalSection"
816 | "LeaveCriticalSection"
817 | "DeleteCriticalSection" => {
818 // Nothing to do, not even a return value.
822 | "TryEnterCriticalSection"
823 | "GetConsoleScreenBufferInfo"
824 | "SetConsoleTextAttribute" => {
825 // Pretend these do not exist / nothing happened, by returning zero.
826 this.write_null(dest)?;
829 let system_info = this.deref_operand(args[0])?;
830 // Initialize with `0`.
832 .write_bytes(system_info.ptr, iter::repeat(0u8).take(system_info.layout.size.bytes() as usize))?;
833 // Set number of processors.
834 let dword_size = Size::from_bytes(4);
835 let num_cpus = this.mplace_field(system_info, 6)?;
837 Scalar::from_int(NUM_CPUS, dword_size),
843 // This just creates a key; Windows does not natively support TLS destructors.
845 // Create key and return it.
846 let key = this.machine.tls.create_tls_key(None) as u128;
848 // Figure out how large a TLS key actually is. This is `c::DWORD`.
849 if dest.layout.size.bits() < 128
850 && key >= (1u128 << dest.layout.size.bits() as u128)
852 throw_unsup!(OutOfTls);
854 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
857 let key = this.read_scalar(args[0])?.to_u32()? as u128;
858 let ptr = this.machine.tls.load_tls(key, tcx)?;
859 this.write_scalar(ptr, dest)?;
862 let key = this.read_scalar(args[0])?.to_u32()? as u128;
863 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
864 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
866 // Return success (`1`).
867 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
870 let which = this.read_scalar(args[0])?.to_i32()?;
871 // We just make this the identity function, so we know later in `WriteFile`
873 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
876 let handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
877 let buf = this.read_scalar(args[1])?.not_undef()?;
878 let n = this.read_scalar(args[2])?.to_u32()?;
879 let written_place = this.deref_operand(args[3])?;
880 // Spec says to always write `0` first.
881 this.write_null(written_place.into())?;
882 let written = if handle == -11 || handle == -12 {
884 use std::io::{self, Write};
888 .read_bytes(buf, Size::from_bytes(u64::from(n)))?;
889 let res = if handle == -11 {
890 io::stdout().write(buf_cont)
892 io::stderr().write(buf_cont)
894 res.ok().map(|n| n as u32)
896 eprintln!("Miri: Ignored output to handle {}", handle);
897 // Pretend it all went well.
900 // If there was no error, write back how much was written.
901 if let Some(n) = written {
902 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
904 // Return whether this was a success.
906 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
910 "GetConsoleMode" => {
911 // Everything is a pipe.
912 this.write_null(dest)?;
914 "GetEnvironmentVariableW" => {
915 // This is not the env var you are looking for.
916 this.set_last_error(Scalar::from_u32(203))?; // ERROR_ENVVAR_NOT_FOUND
917 this.write_null(dest)?;
919 "GetCommandLineW" => {
920 this.write_scalar(this.machine.cmd_line.expect("machine must be initialized"), dest)?;
922 // The actual name of 'RtlGenRandom'
923 "SystemFunction036" => {
924 let ptr = this.read_scalar(args[0])?.not_undef()?;
925 let len = this.read_scalar(args[1])?.to_u32()?;
926 this.gen_random(ptr, len as usize)?;
927 this.write_scalar(Scalar::from_bool(true), dest)?;
930 // We can't execute anything else.
931 _ => throw_unsup_format!("can't call foreign function: {}", link_name),
934 this.dump_place(*dest);
935 this.go_to_block(ret);
939 /// Evaluates the scalar at the specified path. Returns Some(val)
940 /// if the path could be resolved, and None otherwise
944 ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
945 let this = self.eval_context_mut();
946 if let Ok(instance) = this.resolve_path(path) {
951 let const_val = this.const_eval_raw(cid)?;
952 let const_val = this.read_scalar(const_val.into())?;
953 return Ok(Some(const_val));
959 // Shims the linux 'getrandom()' syscall.
960 fn linux_getrandom<'tcx>(
961 this: &mut MiriEvalContext<'_, 'tcx>,
962 args: &[OpTy<'tcx, Tag>],
963 dest: PlaceTy<'tcx, Tag>,
964 ) -> InterpResult<'tcx> {
965 let ptr = this.read_scalar(args[0])?.not_undef()?;
966 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
968 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
969 // neither of which have any effect on our current PRNG.
970 let _flags = this.read_scalar(args[2])?.to_i32()?;
972 this.gen_random(ptr, len as usize)?;
973 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;