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)?;
307 .eval_path_scalar(&["libc", "SYS_statx"])?
308 .expect("Failed to get libc::SYS_statx")
309 .to_machine_usize(this)?;
311 match this.read_scalar(args[0])?.to_machine_usize(this)? {
312 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
313 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
314 id if id == sys_getrandom => {
315 // The first argument is the syscall id,
317 linux_getrandom(this, &args[1..], dest)?;
319 id if id == sys_statx => {
320 // The first argument is the syscall id,
322 let result = this.statx(args[1], args[2], args[3], args[4], args[5])?;
323 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
325 id => throw_unsup_format!("miri does not support syscall ID {}", id),
330 linux_getrandom(this, args, dest)?;
334 let _handle = this.read_scalar(args[0])?;
335 let symbol = this.read_scalar(args[1])?.not_undef()?;
336 let symbol_name = this.memory.read_c_str(symbol)?;
337 let err = format!("bad c unicode symbol: {:?}", symbol_name);
338 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
339 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
340 let ptr = this.memory.create_fn_alloc(FnVal::Other(dlsym));
341 this.write_scalar(Scalar::from(ptr), dest)?;
343 this.write_null(dest)?;
347 "__rust_maybe_catch_panic" => {
348 this.handle_catch_panic(args, dest, ret)?;
353 let left = this.read_scalar(args[0])?.not_undef()?;
354 let right = this.read_scalar(args[1])?.not_undef()?;
355 let n = Size::from_bytes(this.read_scalar(args[2])?.to_machine_usize(this)?);
358 let left_bytes = this.memory.read_bytes(left, n)?;
359 let right_bytes = this.memory.read_bytes(right, n)?;
361 use std::cmp::Ordering::*;
362 match left_bytes.cmp(right_bytes) {
369 this.write_scalar(Scalar::from_int(result, Size::from_bits(32)), dest)?;
373 let ptr = this.read_scalar(args[0])?.not_undef()?;
374 let val = this.read_scalar(args[1])?.to_i32()? as u8;
375 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
376 if let Some(idx) = this
378 .read_bytes(ptr, Size::from_bytes(num))?
381 .position(|&c| c == val)
383 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
384 this.write_scalar(new_ptr, dest)?;
386 this.write_null(dest)?;
391 let ptr = this.read_scalar(args[0])?.not_undef()?;
392 let val = this.read_scalar(args[1])?.to_i32()? as u8;
393 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
396 .read_bytes(ptr, Size::from_bytes(num))?
398 .position(|&c| c == val);
399 if let Some(idx) = idx {
400 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
401 this.write_scalar(new_ptr, dest)?;
403 this.write_null(dest)?;
407 "__errno_location" | "__error" => {
408 let errno_place = this.machine.last_error.unwrap();
409 this.write_scalar(errno_place.to_ref().to_scalar()?, dest)?;
413 let result = this.getenv(args[0])?;
414 this.write_scalar(result, dest)?;
418 let result = this.unsetenv(args[0])?;
419 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
423 let result = this.setenv(args[0], args[1])?;
424 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
428 let result = this.getcwd(args[0], args[1])?;
429 this.write_scalar(result, dest)?;
433 let result = this.chdir(args[0])?;
434 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
437 "open" | "open64" => {
438 let result = this.open(args[0], args[1])?;
439 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
443 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
444 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
447 "close" | "close$NOCANCEL" => {
448 let result = this.close(args[0])?;
449 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
453 let result = this.read(args[0], args[1], args[2])?;
454 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
458 let fd = this.read_scalar(args[0])?.to_i32()?;
459 let buf = this.read_scalar(args[1])?.not_undef()?;
460 let n = this.read_scalar(args[2])?.to_machine_usize(tcx)?;
461 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
462 let result = if fd == 1 || fd == 2 {
464 use std::io::{self, Write};
466 let buf_cont = this.memory.read_bytes(buf, Size::from_bytes(n))?;
467 // We need to flush to make sure this actually appears on the screen
468 let res = if fd == 1 {
469 // Stdout is buffered, flush to make sure it appears on the screen.
470 // This is the write() syscall of the interpreted program, we want it
471 // to correspond to a write() syscall on the host -- there is no good
472 // in adding extra buffering here.
473 let res = io::stdout().write(buf_cont);
474 io::stdout().flush().unwrap();
477 // No need to flush, stderr is not buffered.
478 io::stderr().write(buf_cont)
485 this.write(args[0], args[1], args[2])?
487 // Now, `result` is the value we return back to the program.
488 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
492 let result = this.unlink(args[0])?;
493 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
497 let result = this.clock_gettime(args[0], args[1])?;
498 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
502 let result = this.gettimeofday(args[0], args[1])?;
503 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
507 let ptr = this.read_scalar(args[0])?.not_undef()?;
508 let n = this.memory.read_c_str(ptr)?.len();
509 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
513 "cbrtf" | "coshf" | "sinhf" | "tanf" | "acosf" | "asinf" | "atanf" => {
514 // FIXME: Using host floats.
515 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
516 let f = match link_name {
526 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
528 // underscore case for windows
529 "_hypotf" | "hypotf" | "atan2f" => {
530 // FIXME: Using host floats.
531 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
532 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
533 let n = match link_name {
534 "_hypotf" | "hypotf" => f1.hypot(f2),
535 "atan2f" => f1.atan2(f2),
538 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
541 "cbrt" | "cosh" | "sinh" | "tan" | "acos" | "asin" | "atan" => {
542 // FIXME: Using host floats.
543 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
544 let f = match link_name {
554 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
556 // underscore case for windows, here and below
557 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
558 "_hypot" | "hypot" | "atan2" => {
559 // FIXME: Using host floats.
560 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
561 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
562 let n = match link_name {
563 "_hypot" | "hypot" => f1.hypot(f2),
564 "atan2" => f1.atan2(f2),
567 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
569 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
570 "_ldexp" | "ldexp" | "scalbn" => {
571 let x = this.read_scalar(args[0])?.to_f64()?;
572 let exp = this.read_scalar(args[1])?.to_i32()?;
574 // Saturating cast to i16. Even those are outside the valid exponent range to
575 // `scalbn` below will do its over/underflow handling.
576 let exp = if exp > i16::max_value() as i32 {
578 } else if exp < i16::min_value() as i32 {
581 exp.try_into().unwrap()
584 let res = x.scalbn(exp);
585 this.write_scalar(Scalar::from_f64(res), dest)?;
588 // Some things needed for `sys::thread` initialization to go through.
589 "signal" | "sigaction" | "sigaltstack" => {
590 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
594 let name = this.read_scalar(args[0])?.to_i32()?;
596 trace!("sysconf() called with name {}", name);
597 // TODO: Cache the sysconf integers via Miri's global cache.
600 &["libc", "_SC_PAGESIZE"],
601 Scalar::from_int(PAGE_SIZE, dest.layout.size),
604 &["libc", "_SC_GETPW_R_SIZE_MAX"],
605 Scalar::from_int(-1, dest.layout.size),
608 &["libc", "_SC_NPROCESSORS_ONLN"],
609 Scalar::from_int(NUM_CPUS, dest.layout.size),
612 let mut result = None;
613 for &(path, path_value) in paths {
614 if let Some(val) = this.eval_path_scalar(path)? {
615 let val = val.to_i32()?;
617 result = Some(path_value);
622 if let Some(result) = result {
623 this.write_scalar(result, dest)?;
625 throw_unsup_format!("Unimplemented sysconf name: {}", name)
629 "sched_getaffinity" => {
630 // Return an error; `num_cpus` then falls back to `sysconf`.
631 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
635 this.write_null(dest)?;
638 // Hook pthread calls that go to the thread-local storage memory subsystem.
639 "pthread_key_create" => {
640 let key_place = this.deref_operand(args[0])?;
642 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
643 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
644 Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
648 // Figure out how large a pthread TLS key actually is.
649 // This is `libc::pthread_key_t`.
650 let key_type = args[0].layout.ty
652 .ok_or_else(|| err_ub_format!(
653 "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
656 let key_layout = this.layout_of(key_type)?;
658 // Create key and write it into the memory where `key_ptr` wants it.
659 let key = this.machine.tls.create_tls_key(dtor) as u128;
660 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
662 throw_unsup!(OutOfTls);
665 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
667 // Return success (`0`).
668 this.write_null(dest)?;
670 "pthread_key_delete" => {
671 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
672 this.machine.tls.delete_tls_key(key)?;
673 // Return success (0)
674 this.write_null(dest)?;
676 "pthread_getspecific" => {
677 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
678 let ptr = this.machine.tls.load_tls(key, tcx)?;
679 this.write_scalar(ptr, dest)?;
681 "pthread_setspecific" => {
682 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
683 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
684 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
686 // Return success (`0`).
687 this.write_null(dest)?;
690 // Stack size/address stuff.
692 | "pthread_attr_destroy"
694 | "pthread_attr_setstacksize" => {
695 this.write_null(dest)?;
697 "pthread_attr_getstack" => {
698 let addr_place = this.deref_operand(args[1])?;
699 let size_place = this.deref_operand(args[2])?;
702 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
706 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
710 // Return success (`0`).
711 this.write_null(dest)?;
714 // We don't support threading. (Also for Windows.)
715 "pthread_create" | "CreateThread" => {
716 throw_unsup_format!("Miri does not support threading");
719 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
720 "pthread_mutexattr_init"
721 | "pthread_mutexattr_settype"
722 | "pthread_mutex_init"
723 | "pthread_mutexattr_destroy"
724 | "pthread_mutex_lock"
725 | "pthread_mutex_unlock"
726 | "pthread_mutex_destroy"
727 | "pthread_rwlock_rdlock"
728 | "pthread_rwlock_unlock"
729 | "pthread_rwlock_wrlock"
730 | "pthread_rwlock_destroy"
731 | "pthread_condattr_init"
732 | "pthread_condattr_setclock"
733 | "pthread_cond_init"
734 | "pthread_condattr_destroy"
735 | "pthread_cond_destroy" => {
736 this.write_null(dest)?;
739 // We don't support fork so we don't have to do anything for atfork.
740 "pthread_atfork" => {
741 this.write_null(dest)?;
745 // 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.
746 let addr = this.read_scalar(args[0])?.not_undef()?;
747 this.write_scalar(addr, dest)?;
750 this.write_null(dest)?;
754 "pthread_attr_get_np" | "pthread_getattr_np" => {
755 this.write_null(dest)?;
757 "pthread_get_stackaddr_np" => {
758 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
759 this.write_scalar(stack_addr, dest)?;
761 "pthread_get_stacksize_np" => {
762 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
763 this.write_scalar(stack_size, dest)?;
766 // FIXME: register the destructor.
769 this.write_scalar(this.machine.argc.expect("machine must be initialized"), dest)?;
772 this.write_scalar(this.machine.argv.expect("machine must be initialized"), dest)?;
774 "SecRandomCopyBytes" => {
775 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
776 let ptr = this.read_scalar(args[2])?.not_undef()?;
777 this.gen_random(ptr, len as usize)?;
778 this.write_null(dest)?;
781 // Windows API stubs.
783 // DWORD = ULONG = u32
785 "GetProcessHeap" => {
786 // Just fake a HANDLE
787 this.write_scalar(Scalar::from_int(1, this.pointer_size()), 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 size = this.read_scalar(args[2])?.to_machine_usize(this)?;
793 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
794 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
795 this.write_scalar(res, dest)?;
798 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
799 let _flags = this.read_scalar(args[1])?.to_u32()?;
800 let ptr = this.read_scalar(args[2])?.not_undef()?;
801 this.free(ptr, MiriMemoryKind::WinHeap)?;
802 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
805 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
806 let _flags = this.read_scalar(args[1])?.to_u32()?;
807 let ptr = this.read_scalar(args[2])?.not_undef()?;
808 let size = this.read_scalar(args[3])?.to_machine_usize(this)?;
809 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
810 this.write_scalar(res, dest)?;
814 this.set_last_error(this.read_scalar(args[0])?.not_undef()?)?;
817 let last_error = this.get_last_error()?;
818 this.write_scalar(last_error, dest)?;
821 "AddVectoredExceptionHandler" => {
822 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
823 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
825 "InitializeCriticalSection"
826 | "EnterCriticalSection"
827 | "LeaveCriticalSection"
828 | "DeleteCriticalSection" => {
829 // Nothing to do, not even a return value.
833 | "TryEnterCriticalSection"
834 | "GetConsoleScreenBufferInfo"
835 | "SetConsoleTextAttribute" => {
836 // Pretend these do not exist / nothing happened, by returning zero.
837 this.write_null(dest)?;
840 let system_info = this.deref_operand(args[0])?;
841 // Initialize with `0`.
843 .write_bytes(system_info.ptr, iter::repeat(0u8).take(system_info.layout.size.bytes() as usize))?;
844 // Set number of processors.
845 let dword_size = Size::from_bytes(4);
846 let num_cpus = this.mplace_field(system_info, 6)?;
848 Scalar::from_int(NUM_CPUS, dword_size),
854 // This just creates a key; Windows does not natively support TLS destructors.
856 // Create key and return it.
857 let key = this.machine.tls.create_tls_key(None) as u128;
859 // Figure out how large a TLS key actually is. This is `c::DWORD`.
860 if dest.layout.size.bits() < 128
861 && key >= (1u128 << dest.layout.size.bits() as u128)
863 throw_unsup!(OutOfTls);
865 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
868 let key = this.read_scalar(args[0])?.to_u32()? as u128;
869 let ptr = this.machine.tls.load_tls(key, tcx)?;
870 this.write_scalar(ptr, dest)?;
873 let key = this.read_scalar(args[0])?.to_u32()? as u128;
874 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
875 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
877 // Return success (`1`).
878 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
881 let which = this.read_scalar(args[0])?.to_i32()?;
882 // We just make this the identity function, so we know later in `WriteFile`
884 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
887 let handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
888 let buf = this.read_scalar(args[1])?.not_undef()?;
889 let n = this.read_scalar(args[2])?.to_u32()?;
890 let written_place = this.deref_operand(args[3])?;
891 // Spec says to always write `0` first.
892 this.write_null(written_place.into())?;
893 let written = if handle == -11 || handle == -12 {
895 use std::io::{self, Write};
899 .read_bytes(buf, Size::from_bytes(u64::from(n)))?;
900 let res = if handle == -11 {
901 io::stdout().write(buf_cont)
903 io::stderr().write(buf_cont)
905 res.ok().map(|n| n as u32)
907 eprintln!("Miri: Ignored output to handle {}", handle);
908 // Pretend it all went well.
911 // If there was no error, write back how much was written.
912 if let Some(n) = written {
913 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
915 // Return whether this was a success.
917 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
921 "GetConsoleMode" => {
922 // Everything is a pipe.
923 this.write_null(dest)?;
925 "GetEnvironmentVariableW" => {
926 // This is not the env var you are looking for.
927 this.set_last_error(Scalar::from_u32(203))?; // ERROR_ENVVAR_NOT_FOUND
928 this.write_null(dest)?;
930 "GetCommandLineW" => {
931 this.write_scalar(this.machine.cmd_line.expect("machine must be initialized"), dest)?;
933 // The actual name of 'RtlGenRandom'
934 "SystemFunction036" => {
935 let ptr = this.read_scalar(args[0])?.not_undef()?;
936 let len = this.read_scalar(args[1])?.to_u32()?;
937 this.gen_random(ptr, len as usize)?;
938 this.write_scalar(Scalar::from_bool(true), dest)?;
941 // We can't execute anything else.
942 _ => throw_unsup_format!("can't call foreign function: {}", link_name),
945 this.dump_place(*dest);
946 this.go_to_block(ret);
950 /// Evaluates the scalar at the specified path. Returns Some(val)
951 /// if the path could be resolved, and None otherwise
955 ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
956 let this = self.eval_context_mut();
957 if let Ok(instance) = this.resolve_path(path) {
962 let const_val = this.const_eval_raw(cid)?;
963 let const_val = this.read_scalar(const_val.into())?;
964 return Ok(Some(const_val));
970 // Shims the linux 'getrandom()' syscall.
971 fn linux_getrandom<'tcx>(
972 this: &mut MiriEvalContext<'_, 'tcx>,
973 args: &[OpTy<'tcx, Tag>],
974 dest: PlaceTy<'tcx, Tag>,
975 ) -> InterpResult<'tcx> {
976 let ptr = this.read_scalar(args[0])?.not_undef()?;
977 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
979 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
980 // neither of which have any effect on our current PRNG.
981 let _flags = this.read_scalar(args[2])?.to_i32()?;
983 this.gen_random(ptr, len as usize)?;
984 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;