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 let ti = Box::new(TerminationInfo::Exit(code.into()));
158 return Err(InterpError::MachineStop(ti).into());
161 if let Some(p) = ret {
164 throw_unsup_format!("can't call (diverging) foreign function: {}", link_name);
169 // Next: functions that return.
172 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
173 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
174 this.write_scalar(res, dest)?;
177 let items = this.read_scalar(args[0])?.to_machine_usize(this)?;
178 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
181 .ok_or_else(|| err_panic!(Overflow(mir::BinOp::Mul)))?;
182 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
183 this.write_scalar(res, dest)?;
185 "posix_memalign" => {
186 let ret = this.deref_operand(args[0])?;
187 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
188 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
189 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
190 if !align.is_power_of_two() {
191 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
193 if align < this.pointer_size().bytes() {
195 "posix_memalign: alignment must be at least the size of a pointer, but is {}",
201 this.write_null(ret.into())?;
203 let ptr = this.memory.allocate(
204 Size::from_bytes(size),
205 Align::from_bytes(align).unwrap(),
206 MiriMemoryKind::C.into(),
208 this.write_scalar(ptr, ret.into())?;
210 this.write_null(dest)?;
213 let ptr = this.read_scalar(args[0])?.not_undef()?;
214 this.free(ptr, MiriMemoryKind::C)?;
217 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
218 let new_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
219 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
220 this.write_scalar(res, dest)?;
224 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
225 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
227 throw_unsup!(HeapAllocZeroBytes);
229 if !align.is_power_of_two() {
230 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
232 let ptr = this.memory.allocate(
233 Size::from_bytes(size),
234 Align::from_bytes(align).unwrap(),
235 MiriMemoryKind::Rust.into(),
237 this.write_scalar(ptr, dest)?;
239 "__rust_alloc_zeroed" => {
240 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
241 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
243 throw_unsup!(HeapAllocZeroBytes);
245 if !align.is_power_of_two() {
246 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
248 let ptr = this.memory.allocate(
249 Size::from_bytes(size),
250 Align::from_bytes(align).unwrap(),
251 MiriMemoryKind::Rust.into(),
253 // We just allocated this, the access is definitely in-bounds.
255 .write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize))
257 this.write_scalar(ptr, dest)?;
259 "__rust_dealloc" => {
260 let ptr = this.read_scalar(args[0])?.not_undef()?;
261 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
262 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
264 throw_unsup!(HeapAllocZeroBytes);
266 if !align.is_power_of_two() {
267 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
269 let ptr = this.force_ptr(ptr)?;
270 this.memory.deallocate(
273 Size::from_bytes(old_size),
274 Align::from_bytes(align).unwrap(),
276 MiriMemoryKind::Rust.into(),
279 "__rust_realloc" => {
280 let ptr = this.read_scalar(args[0])?.to_ptr()?;
281 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
282 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
283 let new_size = this.read_scalar(args[3])?.to_machine_usize(this)?;
284 if old_size == 0 || new_size == 0 {
285 throw_unsup!(HeapAllocZeroBytes);
287 if !align.is_power_of_two() {
288 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
290 let align = Align::from_bytes(align).unwrap();
291 let new_ptr = this.memory.reallocate(
293 Some((Size::from_bytes(old_size), align)),
294 Size::from_bytes(new_size),
296 MiriMemoryKind::Rust.into(),
298 this.write_scalar(new_ptr, dest)?;
302 let sys_getrandom = this
303 .eval_path_scalar(&["libc", "SYS_getrandom"])?
304 .expect("Failed to get libc::SYS_getrandom")
305 .to_machine_usize(this)?;
307 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
308 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
309 match this.read_scalar(args[0])?.to_machine_usize(this)? {
310 id if id == sys_getrandom => {
311 // The first argument is the syscall id,
313 linux_getrandom(this, &args[1..], dest)?;
315 id => throw_unsup_format!("miri does not support syscall ID {}", id),
320 linux_getrandom(this, args, dest)?;
324 let _handle = this.read_scalar(args[0])?;
325 let symbol = this.read_scalar(args[1])?.not_undef()?;
326 let symbol_name = this.memory.read_c_str(symbol)?;
327 let err = format!("bad c unicode symbol: {:?}", symbol_name);
328 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
329 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
330 let ptr = this.memory.create_fn_alloc(FnVal::Other(dlsym));
331 this.write_scalar(Scalar::from(ptr), dest)?;
333 this.write_null(dest)?;
337 "__rust_maybe_catch_panic" => {
338 this.handle_catch_panic(args, dest, ret)?;
343 let left = this.read_scalar(args[0])?.not_undef()?;
344 let right = this.read_scalar(args[1])?.not_undef()?;
345 let n = Size::from_bytes(this.read_scalar(args[2])?.to_machine_usize(this)?);
348 let left_bytes = this.memory.read_bytes(left, n)?;
349 let right_bytes = this.memory.read_bytes(right, n)?;
351 use std::cmp::Ordering::*;
352 match left_bytes.cmp(right_bytes) {
359 this.write_scalar(Scalar::from_int(result, Size::from_bits(32)), dest)?;
363 let ptr = this.read_scalar(args[0])?.not_undef()?;
364 let val = this.read_scalar(args[1])?.to_i32()? as u8;
365 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
366 if let Some(idx) = this
368 .read_bytes(ptr, Size::from_bytes(num))?
371 .position(|&c| c == val)
373 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
374 this.write_scalar(new_ptr, dest)?;
376 this.write_null(dest)?;
381 let ptr = this.read_scalar(args[0])?.not_undef()?;
382 let val = this.read_scalar(args[1])?.to_i32()? as u8;
383 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
386 .read_bytes(ptr, Size::from_bytes(num))?
388 .position(|&c| c == val);
389 if let Some(idx) = idx {
390 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
391 this.write_scalar(new_ptr, dest)?;
393 this.write_null(dest)?;
397 "__errno_location" | "__error" => {
398 let errno_place = this.machine.last_error.unwrap();
399 this.write_scalar(errno_place.to_ref().to_scalar()?, dest)?;
403 let result = this.getenv(args[0])?;
404 this.write_scalar(result, dest)?;
408 let result = this.unsetenv(args[0])?;
409 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
413 let result = this.setenv(args[0], args[1])?;
414 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
418 let result = this.getcwd(args[0], args[1])?;
419 this.write_scalar(result, dest)?;
423 let result = this.chdir(args[0])?;
424 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
427 "open" | "open64" => {
428 let result = this.open(args[0], args[1])?;
429 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
433 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
434 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
437 "close" | "close$NOCANCEL" => {
438 let result = this.close(args[0])?;
439 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
443 let result = this.read(args[0], args[1], args[2])?;
444 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
448 let fd = this.read_scalar(args[0])?.to_i32()?;
449 let buf = this.read_scalar(args[1])?.not_undef()?;
450 let n = this.read_scalar(args[2])?.to_machine_usize(tcx)?;
451 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
452 let result = if fd == 1 || fd == 2 {
454 use std::io::{self, Write};
456 let buf_cont = this.memory.read_bytes(buf, Size::from_bytes(n))?;
457 // We need to flush to make sure this actually appears on the screen
458 let res = if fd == 1 {
459 // Stdout is buffered, flush to make sure it appears on the screen.
460 // This is the write() syscall of the interpreted program, we want it
461 // to correspond to a write() syscall on the host -- there is no good
462 // in adding extra buffering here.
463 let res = io::stdout().write(buf_cont);
464 io::stdout().flush().unwrap();
467 // No need to flush, stderr is not buffered.
468 io::stderr().write(buf_cont)
475 this.write(args[0], args[1], args[2])?
477 // Now, `result` is the value we return back to the program.
478 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
482 let result = this.unlink(args[0])?;
483 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
487 let result = this.clock_gettime(args[0], args[1])?;
488 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
492 let result = this.gettimeofday(args[0], args[1])?;
493 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
497 let ptr = this.read_scalar(args[0])?.not_undef()?;
498 let n = this.memory.read_c_str(ptr)?.len();
499 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
503 "cbrtf" | "coshf" | "sinhf" | "tanf" | "acosf" | "asinf" | "atanf" => {
504 // FIXME: Using host floats.
505 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
506 let f = match link_name {
516 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
518 // underscore case for windows
519 "_hypotf" | "hypotf" | "atan2f" => {
520 // FIXME: Using host floats.
521 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
522 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
523 let n = match link_name {
524 "_hypotf" | "hypotf" => f1.hypot(f2),
525 "atan2f" => f1.atan2(f2),
528 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
531 "cbrt" | "cosh" | "sinh" | "tan" | "acos" | "asin" | "atan" => {
532 // FIXME: Using host floats.
533 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
534 let f = match link_name {
544 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
546 // underscore case for windows, here and below
547 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
548 "_hypot" | "hypot" | "atan2" => {
549 // FIXME: Using host floats.
550 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
551 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
552 let n = match link_name {
553 "_hypot" | "hypot" => f1.hypot(f2),
554 "atan2" => f1.atan2(f2),
557 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
559 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
560 "_ldexp" | "ldexp" | "scalbn" => {
561 let x = this.read_scalar(args[0])?.to_f64()?;
562 let exp = this.read_scalar(args[1])?.to_i32()?;
564 // Saturating cast to i16. Even those are outside the valid exponent range to
565 // `scalbn` below will do its over/underflow handling.
566 let exp = if exp > i16::max_value() as i32 {
568 } else if exp < i16::min_value() as i32 {
571 exp.try_into().unwrap()
574 let res = x.scalbn(exp);
575 this.write_scalar(Scalar::from_f64(res), dest)?;
578 // Some things needed for `sys::thread` initialization to go through.
579 "signal" | "sigaction" | "sigaltstack" => {
580 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
584 let name = this.read_scalar(args[0])?.to_i32()?;
586 trace!("sysconf() called with name {}", name);
587 // TODO: Cache the sysconf integers via Miri's global cache.
590 &["libc", "_SC_PAGESIZE"],
591 Scalar::from_int(PAGE_SIZE, dest.layout.size),
594 &["libc", "_SC_GETPW_R_SIZE_MAX"],
595 Scalar::from_int(-1, dest.layout.size),
598 &["libc", "_SC_NPROCESSORS_ONLN"],
599 Scalar::from_int(NUM_CPUS, dest.layout.size),
602 let mut result = None;
603 for &(path, path_value) in paths {
604 if let Some(val) = this.eval_path_scalar(path)? {
605 let val = val.to_i32()?;
607 result = Some(path_value);
612 if let Some(result) = result {
613 this.write_scalar(result, dest)?;
615 throw_unsup_format!("Unimplemented sysconf name: {}", name)
619 "sched_getaffinity" => {
620 // Return an error; `num_cpus` then falls back to `sysconf`.
621 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
625 this.write_null(dest)?;
628 // Hook pthread calls that go to the thread-local storage memory subsystem.
629 "pthread_key_create" => {
630 let key_place = this.deref_operand(args[0])?;
632 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
633 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
634 Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
638 // Figure out how large a pthread TLS key actually is.
639 // This is `libc::pthread_key_t`.
640 let key_type = args[0].layout.ty
642 .ok_or_else(|| err_ub_format!(
643 "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
646 let key_layout = this.layout_of(key_type)?;
648 // Create key and write it into the memory where `key_ptr` wants it.
649 let key = this.machine.tls.create_tls_key(dtor) as u128;
650 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
652 throw_unsup!(OutOfTls);
655 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
657 // Return success (`0`).
658 this.write_null(dest)?;
660 "pthread_key_delete" => {
661 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
662 this.machine.tls.delete_tls_key(key)?;
663 // Return success (0)
664 this.write_null(dest)?;
666 "pthread_getspecific" => {
667 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
668 let ptr = this.machine.tls.load_tls(key, tcx)?;
669 this.write_scalar(ptr, dest)?;
671 "pthread_setspecific" => {
672 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
673 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
674 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
676 // Return success (`0`).
677 this.write_null(dest)?;
680 // Stack size/address stuff.
682 | "pthread_attr_destroy"
684 | "pthread_attr_setstacksize" => {
685 this.write_null(dest)?;
687 "pthread_attr_getstack" => {
688 let addr_place = this.deref_operand(args[1])?;
689 let size_place = this.deref_operand(args[2])?;
692 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
696 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
700 // Return success (`0`).
701 this.write_null(dest)?;
704 // We don't support threading. (Also for Windows.)
705 "pthread_create" | "CreateThread" => {
706 throw_unsup_format!("Miri does not support threading");
709 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
710 "pthread_mutexattr_init"
711 | "pthread_mutexattr_settype"
712 | "pthread_mutex_init"
713 | "pthread_mutexattr_destroy"
714 | "pthread_mutex_lock"
715 | "pthread_mutex_unlock"
716 | "pthread_mutex_destroy"
717 | "pthread_rwlock_rdlock"
718 | "pthread_rwlock_unlock"
719 | "pthread_rwlock_wrlock"
720 | "pthread_rwlock_destroy"
721 | "pthread_condattr_init"
722 | "pthread_condattr_setclock"
723 | "pthread_cond_init"
724 | "pthread_condattr_destroy"
725 | "pthread_cond_destroy" => {
726 this.write_null(dest)?;
729 // We don't support fork so we don't have to do anything for atfork.
730 "pthread_atfork" => {
731 this.write_null(dest)?;
735 // 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.
736 let addr = this.read_scalar(args[0])?.not_undef()?;
737 this.write_scalar(addr, dest)?;
740 this.write_null(dest)?;
744 "pthread_attr_get_np" | "pthread_getattr_np" => {
745 this.write_null(dest)?;
747 "pthread_get_stackaddr_np" => {
748 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
749 this.write_scalar(stack_addr, dest)?;
751 "pthread_get_stacksize_np" => {
752 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
753 this.write_scalar(stack_size, dest)?;
756 // FIXME: register the destructor.
759 this.write_scalar(this.machine.argc.expect("machine must be initialized"), dest)?;
762 this.write_scalar(this.machine.argv.expect("machine must be initialized"), dest)?;
764 "SecRandomCopyBytes" => {
765 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
766 let ptr = this.read_scalar(args[2])?.not_undef()?;
767 this.gen_random(ptr, len as usize)?;
768 this.write_null(dest)?;
771 // Windows API stubs.
773 // DWORD = ULONG = u32
775 "GetProcessHeap" => {
776 // Just fake a HANDLE
777 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
780 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
781 let flags = this.read_scalar(args[1])?.to_u32()?;
782 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
783 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
784 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
785 this.write_scalar(res, 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 this.free(ptr, MiriMemoryKind::WinHeap)?;
792 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
795 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
796 let _flags = this.read_scalar(args[1])?.to_u32()?;
797 let ptr = this.read_scalar(args[2])?.not_undef()?;
798 let size = this.read_scalar(args[3])?.to_machine_usize(this)?;
799 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
800 this.write_scalar(res, dest)?;
804 this.set_last_error(this.read_scalar(args[0])?.not_undef()?)?;
807 let last_error = this.get_last_error()?;
808 this.write_scalar(last_error, dest)?;
811 "AddVectoredExceptionHandler" => {
812 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
813 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
815 "InitializeCriticalSection"
816 | "EnterCriticalSection"
817 | "LeaveCriticalSection"
818 | "DeleteCriticalSection" => {
819 // Nothing to do, not even a return value.
823 | "TryEnterCriticalSection"
824 | "GetConsoleScreenBufferInfo"
825 | "SetConsoleTextAttribute" => {
826 // Pretend these do not exist / nothing happened, by returning zero.
827 this.write_null(dest)?;
830 let system_info = this.deref_operand(args[0])?;
831 // Initialize with `0`.
833 .write_bytes(system_info.ptr, iter::repeat(0u8).take(system_info.layout.size.bytes() as usize))?;
834 // Set number of processors.
835 let dword_size = Size::from_bytes(4);
836 let num_cpus = this.mplace_field(system_info, 6)?;
838 Scalar::from_int(NUM_CPUS, dword_size),
844 // This just creates a key; Windows does not natively support TLS destructors.
846 // Create key and return it.
847 let key = this.machine.tls.create_tls_key(None) as u128;
849 // Figure out how large a TLS key actually is. This is `c::DWORD`.
850 if dest.layout.size.bits() < 128
851 && key >= (1u128 << dest.layout.size.bits() as u128)
853 throw_unsup!(OutOfTls);
855 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
858 let key = this.read_scalar(args[0])?.to_u32()? as u128;
859 let ptr = this.machine.tls.load_tls(key, tcx)?;
860 this.write_scalar(ptr, dest)?;
863 let key = this.read_scalar(args[0])?.to_u32()? as u128;
864 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
865 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
867 // Return success (`1`).
868 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
871 let which = this.read_scalar(args[0])?.to_i32()?;
872 // We just make this the identity function, so we know later in `WriteFile`
874 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
877 let handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
878 let buf = this.read_scalar(args[1])?.not_undef()?;
879 let n = this.read_scalar(args[2])?.to_u32()?;
880 let written_place = this.deref_operand(args[3])?;
881 // Spec says to always write `0` first.
882 this.write_null(written_place.into())?;
883 let written = if handle == -11 || handle == -12 {
885 use std::io::{self, Write};
889 .read_bytes(buf, Size::from_bytes(u64::from(n)))?;
890 let res = if handle == -11 {
891 io::stdout().write(buf_cont)
893 io::stderr().write(buf_cont)
895 res.ok().map(|n| n as u32)
897 eprintln!("Miri: Ignored output to handle {}", handle);
898 // Pretend it all went well.
901 // If there was no error, write back how much was written.
902 if let Some(n) = written {
903 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
905 // Return whether this was a success.
907 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
911 "GetConsoleMode" => {
912 // Everything is a pipe.
913 this.write_null(dest)?;
915 "GetEnvironmentVariableW" => {
916 // This is not the env var you are looking for.
917 this.set_last_error(Scalar::from_u32(203))?; // ERROR_ENVVAR_NOT_FOUND
918 this.write_null(dest)?;
920 "GetCommandLineW" => {
921 this.write_scalar(this.machine.cmd_line.expect("machine must be initialized"), dest)?;
923 // The actual name of 'RtlGenRandom'
924 "SystemFunction036" => {
925 let ptr = this.read_scalar(args[0])?.not_undef()?;
926 let len = this.read_scalar(args[1])?.to_u32()?;
927 this.gen_random(ptr, len as usize)?;
928 this.write_scalar(Scalar::from_bool(true), dest)?;
931 // We can't execute anything else.
932 _ => throw_unsup_format!("can't call foreign function: {}", link_name),
935 this.dump_place(*dest);
936 this.go_to_block(ret);
940 /// Evaluates the scalar at the specified path. Returns Some(val)
941 /// if the path could be resolved, and None otherwise
945 ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
946 let this = self.eval_context_mut();
947 if let Ok(instance) = this.resolve_path(path) {
952 let const_val = this.const_eval_raw(cid)?;
953 let const_val = this.read_scalar(const_val.into())?;
954 return Ok(Some(const_val));
960 // Shims the linux 'getrandom()' syscall.
961 fn linux_getrandom<'tcx>(
962 this: &mut MiriEvalContext<'_, 'tcx>,
963 args: &[OpTy<'tcx, Tag>],
964 dest: PlaceTy<'tcx, Tag>,
965 ) -> InterpResult<'tcx> {
966 let ptr = this.read_scalar(args[0])?.not_undef()?;
967 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
969 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
970 // neither of which have any effect on our current PRNG.
971 let _flags = this.read_scalar(args[2])?.to_i32()?;
973 this.gen_random(ptr, len as usize)?;
974 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;