1 use std::{iter, convert::TryInto};
4 use rustc::ty::layout::{Align, LayoutOf, Size};
5 use rustc::hir::def_id::DefId;
6 use rustc_apfloat::Float;
9 use syntax::symbol::sym;
13 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
14 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
15 /// Returns the minimum alignment for the target architecture for allocations of the given size.
16 fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
17 let this = self.eval_context_ref();
18 // List taken from `libstd/sys_common/alloc.rs`.
19 let min_align = match this.tcx.tcx.sess.target.target.arch.as_str() {
20 "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
21 "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
22 arch => bug!("Unsupported target architecture: {}", arch),
24 // Windows always aligns, even small allocations.
25 // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
26 // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
27 if kind == MiriMemoryKind::WinHeap || size >= min_align {
28 return Align::from_bytes(min_align).unwrap();
30 // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
31 fn prev_power_of_two(x: u64) -> u64 {
32 let next_pow2 = x.next_power_of_two();
34 // x *is* a power of two, just use that.
37 // x is between two powers, so next = 2*prev.
41 Align::from_bytes(prev_power_of_two(size)).unwrap()
44 fn malloc(&mut self, size: u64, zero_init: bool, kind: MiriMemoryKind) -> Scalar<Tag> {
45 let this = self.eval_context_mut();
47 Scalar::from_int(0, this.pointer_size())
49 let align = this.min_align(size, kind);
52 .allocate(Size::from_bytes(size), align, kind.into());
54 // We just allocated this, the access is definitely in-bounds.
56 .write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize))
63 fn free(&mut self, ptr: Scalar<Tag>, kind: MiriMemoryKind) -> InterpResult<'tcx> {
64 let this = self.eval_context_mut();
65 if !this.is_null(ptr)? {
66 let ptr = this.force_ptr(ptr)?;
67 this.memory.deallocate(ptr, None, kind.into())?;
77 ) -> InterpResult<'tcx, Scalar<Tag>> {
78 let this = self.eval_context_mut();
79 let new_align = this.min_align(new_size, kind);
80 if this.is_null(old_ptr)? {
82 Ok(Scalar::from_int(0, this.pointer_size()))
86 .allocate(Size::from_bytes(new_size), new_align, kind.into());
87 Ok(Scalar::Ptr(new_ptr))
90 let old_ptr = this.force_ptr(old_ptr)?;
92 this.memory.deallocate(old_ptr, None, kind.into())?;
93 Ok(Scalar::from_int(0, this.pointer_size()))
95 let new_ptr = this.memory.reallocate(
98 Size::from_bytes(new_size),
102 Ok(Scalar::Ptr(new_ptr))
107 /// Emulates calling a foreign item, failing if the item is not supported.
108 /// This function will handle `goto_block` if needed.
109 /// Returns Ok(None) if the foreign item was completely handled
110 /// by this function.
111 /// Returns Ok(Some(body)) if processing the foreign item
112 /// is delegated to another function.
113 fn emulate_foreign_item(
116 args: &[OpTy<'tcx, Tag>],
117 dest: Option<PlaceTy<'tcx, Tag>>,
118 ret: Option<mir::BasicBlock>,
119 _unwind: Option<mir::BasicBlock>
120 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
121 let this = self.eval_context_mut();
122 let attrs = this.tcx.get_attrs(def_id);
123 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
124 Some(name) => name.as_str(),
125 None => this.tcx.item_name(def_id).as_str(),
127 // Strip linker suffixes (seen on 32-bit macOS).
128 let link_name = link_name.trim_end_matches("$UNIX2003");
129 let tcx = &{ this.tcx.tcx };
131 // First: functions that diverge.
133 // Note that this matches calls to the *foreign* item `__rust_start_panic* -
134 // that is, calls to `extern "Rust" { fn __rust_start_panic(...) }`.
135 // We forward this to the underlying *implementation* in "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)?));
140 // Similarly, we forward calls to the `panic_impl` foreign item to its implementation.
141 // The implementation is provided by the function with the `#[panic_handler]` attribute.
143 let panic_impl_id = this.tcx.lang_items().panic_impl().unwrap();
144 let panic_impl_instance = ty::Instance::mono(*this.tcx, panic_impl_id);
145 return Ok(Some(this.load_mir(panic_impl_instance.def, None)?));
148 "exit" | "ExitProcess" => {
149 // it's really u32 for ExitProcess, but we have to put it into the `Exit` error variant anyway
150 let code = this.read_scalar(args[0])?.to_i32()?;
151 return Err(InterpError::Exit(code).into());
155 throw_unsup_format!("can't call (diverging) foreign function: {}", link_name);
160 // Next: functions that assume a ret and dest.
161 let dest = dest.expect("we already checked for a dest");
162 let ret = ret.expect("dest is `Some` but ret is `None`");
165 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
166 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
167 this.write_scalar(res, dest)?;
170 let items = this.read_scalar(args[0])?.to_machine_usize(this)?;
171 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
174 .ok_or_else(|| err_panic!(Overflow(mir::BinOp::Mul)))?;
175 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
176 this.write_scalar(res, dest)?;
178 "posix_memalign" => {
179 let ret = this.deref_operand(args[0])?;
180 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
181 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
182 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
183 if !align.is_power_of_two() {
184 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
186 if align < this.pointer_size().bytes() {
188 "posix_memalign: alignment must be at least the size of a pointer, but is {}",
194 this.write_null(ret.into())?;
196 let ptr = this.memory.allocate(
197 Size::from_bytes(size),
198 Align::from_bytes(align).unwrap(),
199 MiriMemoryKind::C.into(),
201 this.write_scalar(Scalar::Ptr(ptr), ret.into())?;
203 this.write_null(dest)?;
206 let ptr = this.read_scalar(args[0])?.not_undef()?;
207 this.free(ptr, MiriMemoryKind::C)?;
210 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
211 let new_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
212 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
213 this.write_scalar(res, dest)?;
217 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
218 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
220 throw_unsup!(HeapAllocZeroBytes);
222 if !align.is_power_of_two() {
223 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
225 let ptr = this.memory.allocate(
226 Size::from_bytes(size),
227 Align::from_bytes(align).unwrap(),
228 MiriMemoryKind::Rust.into(),
230 this.write_scalar(Scalar::Ptr(ptr), dest)?;
232 "__rust_alloc_zeroed" => {
233 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
234 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
236 throw_unsup!(HeapAllocZeroBytes);
238 if !align.is_power_of_two() {
239 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
241 let ptr = this.memory.allocate(
242 Size::from_bytes(size),
243 Align::from_bytes(align).unwrap(),
244 MiriMemoryKind::Rust.into(),
246 // We just allocated this, the access is definitely in-bounds.
248 .write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize))
250 this.write_scalar(Scalar::Ptr(ptr), dest)?;
252 "__rust_dealloc" => {
253 let ptr = this.read_scalar(args[0])?.not_undef()?;
254 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
255 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
257 throw_unsup!(HeapAllocZeroBytes);
259 if !align.is_power_of_two() {
260 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
262 let ptr = this.force_ptr(ptr)?;
263 this.memory.deallocate(
266 Size::from_bytes(old_size),
267 Align::from_bytes(align).unwrap(),
269 MiriMemoryKind::Rust.into(),
272 "__rust_realloc" => {
273 let ptr = this.read_scalar(args[0])?.to_ptr()?;
274 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
275 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
276 let new_size = this.read_scalar(args[3])?.to_machine_usize(this)?;
277 if old_size == 0 || new_size == 0 {
278 throw_unsup!(HeapAllocZeroBytes);
280 if !align.is_power_of_two() {
281 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
283 let align = Align::from_bytes(align).unwrap();
284 let new_ptr = this.memory.reallocate(
286 Some((Size::from_bytes(old_size), align)),
287 Size::from_bytes(new_size),
289 MiriMemoryKind::Rust.into(),
291 this.write_scalar(Scalar::Ptr(new_ptr), dest)?;
295 let sys_getrandom = this
296 .eval_path_scalar(&["libc", "SYS_getrandom"])?
297 .expect("Failed to get libc::SYS_getrandom")
298 .to_machine_usize(this)?;
300 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
301 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
302 match this.read_scalar(args[0])?.to_machine_usize(this)? {
303 id if id == sys_getrandom => {
304 // The first argument is the syscall id,
306 linux_getrandom(this, &args[1..], dest)?;
308 id => throw_unsup_format!("miri does not support syscall ID {}", id),
313 linux_getrandom(this, args, dest)?;
317 let _handle = this.read_scalar(args[0])?;
318 let symbol = this.read_scalar(args[1])?.not_undef()?;
319 let symbol_name = this.memory.read_c_str(symbol)?;
320 let err = format!("bad c unicode symbol: {:?}", symbol_name);
321 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
322 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
323 let ptr = this.memory.create_fn_alloc(FnVal::Other(dlsym));
324 this.write_scalar(Scalar::from(ptr), dest)?;
326 this.write_null(dest)?;
330 "__rust_maybe_catch_panic" => {
331 this.handle_catch_panic(args, dest, ret)?;
336 let left = this.read_scalar(args[0])?.not_undef()?;
337 let right = this.read_scalar(args[1])?.not_undef()?;
338 let n = Size::from_bytes(this.read_scalar(args[2])?.to_machine_usize(this)?);
341 let left_bytes = this.memory.read_bytes(left, n)?;
342 let right_bytes = this.memory.read_bytes(right, n)?;
344 use std::cmp::Ordering::*;
345 match left_bytes.cmp(right_bytes) {
352 this.write_scalar(Scalar::from_int(result, Size::from_bits(32)), dest)?;
356 let ptr = this.read_scalar(args[0])?.not_undef()?;
357 let val = this.read_scalar(args[1])?.to_i32()? as u8;
358 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
359 if let Some(idx) = this
361 .read_bytes(ptr, Size::from_bytes(num))?
364 .position(|&c| c == val)
366 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
367 this.write_scalar(new_ptr, dest)?;
369 this.write_null(dest)?;
374 let ptr = this.read_scalar(args[0])?.not_undef()?;
375 let val = this.read_scalar(args[1])?.to_i32()? as u8;
376 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
379 .read_bytes(ptr, Size::from_bytes(num))?
381 .position(|&c| c == val);
382 if let Some(idx) = idx {
383 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
384 this.write_scalar(new_ptr, dest)?;
386 this.write_null(dest)?;
390 "__errno_location" | "__error" => {
391 let errno_place = this.machine.last_error.unwrap();
392 this.write_scalar(errno_place.to_ref().to_scalar()?, dest)?;
396 let result = this.getenv(args[0])?;
397 this.write_scalar(result, dest)?;
401 let result = this.unsetenv(args[0])?;
402 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
406 let result = this.setenv(args[0], args[1])?;
407 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
411 let result = this.getcwd(args[0], args[1])?;
412 this.write_scalar(result, dest)?;
416 let result = this.chdir(args[0])?;
417 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
420 "open" | "open64" => {
421 let result = this.open(args[0], args[1])?;
422 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
426 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
427 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
430 "close" | "close$NOCANCEL" => {
431 let result = this.close(args[0])?;
432 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
436 let result = this.read(args[0], args[1], args[2])?;
437 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
441 let fd = this.read_scalar(args[0])?.to_i32()?;
442 let buf = this.read_scalar(args[1])?.not_undef()?;
443 let n = this.read_scalar(args[2])?.to_machine_usize(tcx)?;
444 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
445 let result = if fd == 1 || fd == 2 {
447 use std::io::{self, Write};
449 let buf_cont = this.memory.read_bytes(buf, Size::from_bytes(n))?;
450 // We need to flush to make sure this actually appears on the screen
451 let res = if fd == 1 {
452 // Stdout is buffered, flush to make sure it appears on the screen.
453 // This is the write() syscall of the interpreted program, we want it
454 // to correspond to a write() syscall on the host -- there is no good
455 // in adding extra buffering here.
456 let res = io::stdout().write(buf_cont);
457 io::stdout().flush().unwrap();
460 // No need to flush, stderr is not buffered.
461 io::stderr().write(buf_cont)
468 this.write(args[0], args[1], args[2])?
470 // Now, `result` is the value we return back to the program.
471 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
475 let result = this.unlink(args[0])?;
476 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
480 let result = this.clock_gettime(args[0], args[1])?;
481 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
485 let result = this.gettimeofday(args[0], args[1])?;
486 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
490 let ptr = this.read_scalar(args[0])?.not_undef()?;
491 let n = this.memory.read_c_str(ptr)?.len();
492 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
496 "cbrtf" | "coshf" | "sinhf" | "tanf" => {
497 // FIXME: Using host floats.
498 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
499 let f = match link_name {
506 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
508 // underscore case for windows
509 "_hypotf" | "hypotf" | "atan2f" => {
510 // FIXME: Using host floats.
511 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
512 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
513 let n = match link_name {
514 "_hypotf" | "hypotf" => f1.hypot(f2),
515 "atan2f" => f1.atan2(f2),
518 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
521 "cbrt" | "cosh" | "sinh" | "tan" => {
522 // FIXME: Using host floats.
523 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
524 let f = match link_name {
531 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
533 // underscore case for windows, here and below
534 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
535 "_hypot" | "hypot" | "atan2" => {
536 // FIXME: Using host floats.
537 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
538 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
539 let n = match link_name {
540 "_hypot" | "hypot" => f1.hypot(f2),
541 "atan2" => f1.atan2(f2),
544 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
546 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
547 "_ldexp" | "ldexp" | "scalbn" => {
548 let x = this.read_scalar(args[0])?.to_f64()?;
549 let exp = this.read_scalar(args[1])?.to_i32()?;
551 // Saturating cast to i16. Even those are outside the valid exponent range to
552 // `scalbn` below will do its over/underflow handling.
553 let exp = if exp > i16::max_value() as i32 {
555 } else if exp < i16::min_value() as i32 {
558 exp.try_into().unwrap()
561 let res = x.scalbn(exp);
562 this.write_scalar(Scalar::from_f64(res), dest)?;
565 // Some things needed for `sys::thread` initialization to go through.
566 "signal" | "sigaction" | "sigaltstack" => {
567 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
571 let name = this.read_scalar(args[0])?.to_i32()?;
573 trace!("sysconf() called with name {}", name);
574 // TODO: Cache the sysconf integers via Miri's global cache.
577 &["libc", "_SC_PAGESIZE"],
578 Scalar::from_int(PAGE_SIZE, dest.layout.size),
581 &["libc", "_SC_GETPW_R_SIZE_MAX"],
582 Scalar::from_int(-1, dest.layout.size),
585 &["libc", "_SC_NPROCESSORS_ONLN"],
586 Scalar::from_int(NUM_CPUS, dest.layout.size),
589 let mut result = None;
590 for &(path, path_value) in paths {
591 if let Some(val) = this.eval_path_scalar(path)? {
592 let val = val.to_i32()?;
594 result = Some(path_value);
599 if let Some(result) = result {
600 this.write_scalar(result, dest)?;
602 throw_unsup_format!("Unimplemented sysconf name: {}", name)
606 "sched_getaffinity" => {
607 // Return an error; `num_cpus` then falls back to `sysconf`.
608 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
612 this.write_null(dest)?;
615 // Hook pthread calls that go to the thread-local storage memory subsystem.
616 "pthread_key_create" => {
617 let key_place = this.deref_operand(args[0])?;
619 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
620 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
621 Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
625 // Figure out how large a pthread TLS key actually is.
626 // This is `libc::pthread_key_t`.
627 let key_type = args[0].layout.ty
629 .ok_or_else(|| err_ub_format!(
630 "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
633 let key_layout = this.layout_of(key_type)?;
635 // Create key and write it into the memory where `key_ptr` wants it.
636 let key = this.machine.tls.create_tls_key(dtor) as u128;
637 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
639 throw_unsup!(OutOfTls);
642 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
644 // Return success (`0`).
645 this.write_null(dest)?;
647 "pthread_key_delete" => {
648 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
649 this.machine.tls.delete_tls_key(key)?;
650 // Return success (0)
651 this.write_null(dest)?;
653 "pthread_getspecific" => {
654 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
655 let ptr = this.machine.tls.load_tls(key, tcx)?;
656 this.write_scalar(ptr, dest)?;
658 "pthread_setspecific" => {
659 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
660 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
661 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
663 // Return success (`0`).
664 this.write_null(dest)?;
667 // Stack size/address stuff.
669 | "pthread_attr_destroy"
671 | "pthread_attr_setstacksize" => {
672 this.write_null(dest)?;
674 "pthread_attr_getstack" => {
675 let addr_place = this.deref_operand(args[1])?;
676 let size_place = this.deref_operand(args[2])?;
679 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
683 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
687 // Return success (`0`).
688 this.write_null(dest)?;
691 // We don't support threading. (Also for Windows.)
692 "pthread_create" | "CreateThread" => {
693 throw_unsup_format!("Miri does not support threading");
696 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
697 "pthread_mutexattr_init"
698 | "pthread_mutexattr_settype"
699 | "pthread_mutex_init"
700 | "pthread_mutexattr_destroy"
701 | "pthread_mutex_lock"
702 | "pthread_mutex_unlock"
703 | "pthread_mutex_destroy"
704 | "pthread_rwlock_rdlock"
705 | "pthread_rwlock_unlock"
706 | "pthread_rwlock_wrlock"
707 | "pthread_rwlock_destroy"
708 | "pthread_condattr_init"
709 | "pthread_condattr_setclock"
710 | "pthread_cond_init"
711 | "pthread_condattr_destroy"
712 | "pthread_cond_destroy" => {
713 this.write_null(dest)?;
716 // We don't support fork so we don't have to do anything for atfork.
717 "pthread_atfork" => {
718 this.write_null(dest)?;
722 // 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.
723 let addr = this.read_scalar(args[0])?.not_undef()?;
724 this.write_scalar(addr, dest)?;
727 this.write_null(dest)?;
731 "pthread_attr_get_np" | "pthread_getattr_np" => {
732 this.write_null(dest)?;
734 "pthread_get_stackaddr_np" => {
735 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
736 this.write_scalar(stack_addr, dest)?;
738 "pthread_get_stacksize_np" => {
739 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
740 this.write_scalar(stack_size, dest)?;
743 // FIXME: register the destructor.
746 this.write_scalar(this.machine.argc.expect("machine must be initialized"), dest)?;
749 this.write_scalar(this.machine.argv.expect("machine must be initialized"), dest)?;
751 "SecRandomCopyBytes" => {
752 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
753 let ptr = this.read_scalar(args[2])?.not_undef()?;
754 this.gen_random(ptr, len as usize)?;
755 this.write_null(dest)?;
758 // Windows API stubs.
760 // DWORD = ULONG = u32
762 "GetProcessHeap" => {
763 // Just fake a HANDLE
764 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
767 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
768 let flags = this.read_scalar(args[1])?.to_u32()?;
769 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
770 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
771 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
772 this.write_scalar(res, dest)?;
775 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
776 let _flags = this.read_scalar(args[1])?.to_u32()?;
777 let ptr = this.read_scalar(args[2])?.not_undef()?;
778 this.free(ptr, MiriMemoryKind::WinHeap)?;
779 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
782 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
783 let _flags = this.read_scalar(args[1])?.to_u32()?;
784 let ptr = this.read_scalar(args[2])?.not_undef()?;
785 let size = this.read_scalar(args[3])?.to_machine_usize(this)?;
786 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
787 this.write_scalar(res, dest)?;
791 this.set_last_error(this.read_scalar(args[0])?.not_undef()?)?;
794 let last_error = this.get_last_error()?;
795 this.write_scalar(last_error, dest)?;
798 "AddVectoredExceptionHandler" => {
799 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
800 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
802 "InitializeCriticalSection"
803 | "EnterCriticalSection"
804 | "LeaveCriticalSection"
805 | "DeleteCriticalSection" => {
806 // Nothing to do, not even a return value.
810 | "TryEnterCriticalSection"
811 | "GetConsoleScreenBufferInfo"
812 | "SetConsoleTextAttribute" => {
813 // Pretend these do not exist / nothing happened, by returning zero.
814 this.write_null(dest)?;
817 let system_info = this.deref_operand(args[0])?;
818 // Initialize with `0`.
820 .write_bytes(system_info.ptr, iter::repeat(0u8).take(system_info.layout.size.bytes() as usize))?;
821 // Set number of processors.
822 let dword_size = Size::from_bytes(4);
823 let num_cpus = this.mplace_field(system_info, 6)?;
825 Scalar::from_int(NUM_CPUS, dword_size),
831 // This just creates a key; Windows does not natively support TLS destructors.
833 // Create key and return it.
834 let key = this.machine.tls.create_tls_key(None) as u128;
836 // Figure out how large a TLS key actually is. This is `c::DWORD`.
837 if dest.layout.size.bits() < 128
838 && key >= (1u128 << dest.layout.size.bits() as u128)
840 throw_unsup!(OutOfTls);
842 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
845 let key = this.read_scalar(args[0])?.to_u32()? as u128;
846 let ptr = this.machine.tls.load_tls(key, tcx)?;
847 this.write_scalar(ptr, dest)?;
850 let key = this.read_scalar(args[0])?.to_u32()? as u128;
851 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
852 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
854 // Return success (`1`).
855 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
858 let which = this.read_scalar(args[0])?.to_i32()?;
859 // We just make this the identity function, so we know later in `WriteFile`
861 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
864 let handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
865 let buf = this.read_scalar(args[1])?.not_undef()?;
866 let n = this.read_scalar(args[2])?.to_u32()?;
867 let written_place = this.deref_operand(args[3])?;
868 // Spec says to always write `0` first.
869 this.write_null(written_place.into())?;
870 let written = if handle == -11 || handle == -12 {
872 use std::io::{self, Write};
876 .read_bytes(buf, Size::from_bytes(u64::from(n)))?;
877 let res = if handle == -11 {
878 io::stdout().write(buf_cont)
880 io::stderr().write(buf_cont)
882 res.ok().map(|n| n as u32)
884 eprintln!("Miri: Ignored output to handle {}", handle);
885 // Pretend it all went well.
888 // If there was no error, write back how much was written.
889 if let Some(n) = written {
890 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
892 // Return whether this was a success.
894 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
898 "GetConsoleMode" => {
899 // Everything is a pipe.
900 this.write_null(dest)?;
902 "GetEnvironmentVariableW" => {
903 // This is not the env var you are looking for.
904 this.set_last_error(Scalar::from_u32(203))?; // ERROR_ENVVAR_NOT_FOUND
905 this.write_null(dest)?;
907 "GetCommandLineW" => {
908 this.write_scalar(this.machine.cmd_line.expect("machine must be initialized"), dest)?;
910 // The actual name of 'RtlGenRandom'
911 "SystemFunction036" => {
912 let ptr = this.read_scalar(args[0])?.not_undef()?;
913 let len = this.read_scalar(args[1])?.to_u32()?;
914 this.gen_random(ptr, len as usize)?;
915 this.write_scalar(Scalar::from_bool(true), dest)?;
918 // We can't execute anything else.
919 _ => throw_unsup_format!("can't call foreign function: {}", link_name),
922 this.goto_block(Some(ret))?;
923 this.dump_place(*dest);
927 /// Evaluates the scalar at the specified path. Returns Some(val)
928 /// if the path could be resolved, and None otherwise
932 ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
933 let this = self.eval_context_mut();
934 if let Ok(instance) = this.resolve_path(path) {
939 let const_val = this.const_eval_raw(cid)?;
940 let const_val = this.read_scalar(const_val.into())?;
941 return Ok(Some(const_val));
947 // Shims the linux 'getrandom()' syscall.
948 fn linux_getrandom<'tcx>(
949 this: &mut MiriEvalContext<'_, 'tcx>,
950 args: &[OpTy<'tcx, Tag>],
951 dest: PlaceTy<'tcx, Tag>,
952 ) -> InterpResult<'tcx> {
953 let ptr = this.read_scalar(args[0])?.not_undef()?;
954 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
956 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
957 // neither of which have any effect on our current PRNG.
958 let _flags = this.read_scalar(args[2])?.to_i32()?;
960 this.gen_random(ptr, len as usize)?;
961 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;