1 use rustc::ty::layout::{Align, LayoutOf, Size};
2 use rustc::hir::def_id::DefId;
5 use syntax::symbol::sym;
9 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
10 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
11 /// Returns the minimum alignment for the target architecture for allocations of the given size.
12 fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
13 let this = self.eval_context_ref();
14 // List taken from `libstd/sys_common/alloc.rs`.
15 let min_align = match this.tcx.tcx.sess.target.target.arch.as_str() {
16 "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
17 "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
18 arch => bug!("Unsupported target architecture: {}", arch),
20 // Windows always aligns, even small allocations.
21 // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
22 // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
23 if kind == MiriMemoryKind::WinHeap || size >= min_align {
24 return Align::from_bytes(min_align).unwrap();
26 // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
27 fn prev_power_of_two(x: u64) -> u64 {
28 let next_pow2 = x.next_power_of_two();
30 // x *is* a power of two, just use that.
33 // x is between two powers, so next = 2*prev.
37 Align::from_bytes(prev_power_of_two(size)).unwrap()
46 let this = self.eval_context_mut();
47 let tcx = &{this.tcx.tcx};
49 Scalar::from_int(0, this.pointer_size())
51 let align = this.min_align(size, kind);
52 let ptr = this.memory_mut().allocate(Size::from_bytes(size), align, kind.into());
54 // We just allocated this, the access cannot fail
56 .get_mut(ptr.alloc_id).unwrap()
57 .write_repeat(tcx, ptr, 0, Size::from_bytes(size)).unwrap();
67 ) -> InterpResult<'tcx> {
68 let this = self.eval_context_mut();
69 if !this.is_null(ptr)? {
70 let ptr = this.force_ptr(ptr)?;
71 this.memory_mut().deallocate(
85 ) -> InterpResult<'tcx, Scalar<Tag>> {
86 let this = self.eval_context_mut();
87 let new_align = this.min_align(new_size, kind);
88 if this.is_null(old_ptr)? {
90 Ok(Scalar::from_int(0, this.pointer_size()))
92 let new_ptr = this.memory_mut().allocate(
93 Size::from_bytes(new_size),
97 Ok(Scalar::Ptr(new_ptr))
100 let old_ptr = this.force_ptr(old_ptr)?;
101 let memory = this.memory_mut();
108 Ok(Scalar::from_int(0, this.pointer_size()))
110 let new_ptr = memory.reallocate(
113 Size::from_bytes(new_size),
117 Ok(Scalar::Ptr(new_ptr))
122 /// Emulates calling a foreign item, failing if the item is not supported.
123 /// This function will handle `goto_block` if needed.
124 fn emulate_foreign_item(
127 args: &[OpTy<'tcx, Tag>],
128 dest: Option<PlaceTy<'tcx, Tag>>,
129 ret: Option<mir::BasicBlock>,
130 ) -> InterpResult<'tcx> {
131 let this = self.eval_context_mut();
132 let attrs = this.tcx.get_attrs(def_id);
133 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
134 Some(name) => name.as_str(),
135 None => this.tcx.item_name(def_id).as_str(),
137 // Strip linker suffixes (seen on 32-bit macOS).
138 let link_name = link_name.get().trim_end_matches("$UNIX2003");
139 let tcx = &{this.tcx.tcx};
141 // First: functions that diverge.
143 "__rust_start_panic" | "panic_impl" => {
144 throw_unsup!(MachineError("the evaluated program panicked".to_string()));
146 "exit" | "ExitProcess" => {
147 // it's really u32 for ExitProcess, but we have to put it into the `Exit` error variant anyway
148 let code = this.read_scalar(args[0])?.to_i32()?;
149 return Err(InterpError::Exit(code).into());
151 _ => if dest.is_none() {
152 throw_unsup!(Unimplemented(
153 format!("can't call diverging foreign function: {}", link_name),
158 // Next: functions that assume a ret and dest.
159 let dest = dest.expect("we already checked for a dest");
160 let ret = ret.expect("dest is `Some` but ret is `None`");
163 let size = this.read_scalar(args[0])?.to_usize(this)?;
164 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
165 this.write_scalar(res, dest)?;
168 let items = this.read_scalar(args[0])?.to_usize(this)?;
169 let len = this.read_scalar(args[1])?.to_usize(this)?;
170 let size = items.checked_mul(len).ok_or_else(|| err_panic!(Overflow(mir::BinOp::Mul)))?;
171 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
172 this.write_scalar(res, dest)?;
174 "posix_memalign" => {
175 let ret = this.deref_operand(args[0])?;
176 let align = this.read_scalar(args[1])?.to_usize(this)?;
177 let size = this.read_scalar(args[2])?.to_usize(this)?;
178 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
179 if !align.is_power_of_two() {
180 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
183 FIXME: This check is disabled because rustc violates it.
184 See <https://github.com/rust-lang/rust/issues/62251>.
185 if align < this.pointer_size().bytes() {
186 throw_unsup!(MachineError(format!(
187 "posix_memalign: alignment must be at least the size of a pointer, but is {}",
193 this.write_null(ret.into())?;
195 let ptr = this.memory_mut().allocate(
196 Size::from_bytes(size),
197 Align::from_bytes(align).unwrap(),
198 MiriMemoryKind::C.into()
200 this.write_scalar(Scalar::Ptr(ptr), ret.into())?;
202 this.write_null(dest)?;
205 let ptr = this.read_scalar(args[0])?.not_undef()?;
206 this.free(ptr, MiriMemoryKind::C)?;
209 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
210 let new_size = this.read_scalar(args[1])?.to_usize(this)?;
211 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
212 this.write_scalar(res, dest)?;
216 let size = this.read_scalar(args[0])?.to_usize(this)?;
217 let align = this.read_scalar(args[1])?.to_usize(this)?;
219 throw_unsup!(HeapAllocZeroBytes);
221 if !align.is_power_of_two() {
222 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
224 let ptr = this.memory_mut()
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_usize(this)?;
234 let align = this.read_scalar(args[1])?.to_usize(this)?;
236 throw_unsup!(HeapAllocZeroBytes);
238 if !align.is_power_of_two() {
239 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
241 let ptr = this.memory_mut()
243 Size::from_bytes(size),
244 Align::from_bytes(align).unwrap(),
245 MiriMemoryKind::Rust.into()
247 // We just allocated this, the access cannot fail
249 .get_mut(ptr.alloc_id).unwrap()
250 .write_repeat(tcx, ptr, 0, Size::from_bytes(size)).unwrap();
251 this.write_scalar(Scalar::Ptr(ptr), dest)?;
253 "__rust_dealloc" => {
254 let ptr = this.read_scalar(args[0])?.not_undef()?;
255 let old_size = this.read_scalar(args[1])?.to_usize(this)?;
256 let align = this.read_scalar(args[2])?.to_usize(this)?;
258 throw_unsup!(HeapAllocZeroBytes);
260 if !align.is_power_of_two() {
261 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
263 let ptr = this.force_ptr(ptr)?;
264 this.memory_mut().deallocate(
266 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
267 MiriMemoryKind::Rust.into(),
270 "__rust_realloc" => {
271 let ptr = this.read_scalar(args[0])?.to_ptr()?;
272 let old_size = this.read_scalar(args[1])?.to_usize(this)?;
273 let align = this.read_scalar(args[2])?.to_usize(this)?;
274 let new_size = this.read_scalar(args[3])?.to_usize(this)?;
275 if old_size == 0 || new_size == 0 {
276 throw_unsup!(HeapAllocZeroBytes);
278 if !align.is_power_of_two() {
279 throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
281 let align = Align::from_bytes(align).unwrap();
282 let new_ptr = this.memory_mut().reallocate(
284 Some((Size::from_bytes(old_size), align)),
285 Size::from_bytes(new_size),
287 MiriMemoryKind::Rust.into(),
289 this.write_scalar(Scalar::Ptr(new_ptr), dest)?;
293 let sys_getrandom = this.eval_path_scalar(&["libc", "SYS_getrandom"])?
294 .expect("Failed to get libc::SYS_getrandom")
297 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
298 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
299 match this.read_scalar(args[0])?.to_usize(this)? {
300 id if id == sys_getrandom => {
301 let ptr = this.read_scalar(args[1])?.not_undef()?;
302 let len = this.read_scalar(args[2])?.to_usize(this)?;
304 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
305 // neither of which have any effect on our current PRNG
306 let _flags = this.read_scalar(args[3])?.to_i32()?;
308 this.gen_random(len as usize, ptr)?;
309 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;
312 throw_unsup!(Unimplemented(
313 format!("miri does not support syscall ID {}", id),
320 let _handle = this.read_scalar(args[0])?;
321 let symbol = this.read_scalar(args[1])?.not_undef()?;
322 let symbol_name = this.memory().read_c_str(symbol)?;
323 let err = format!("bad c unicode symbol: {:?}", symbol_name);
324 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
325 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
326 let ptr = this.memory_mut().create_fn_alloc(FnVal::Other(dlsym));
327 this.write_scalar(Scalar::from(ptr), dest)?;
329 this.write_null(dest)?;
333 "__rust_maybe_catch_panic" => {
334 // fn __rust_maybe_catch_panic(
337 // data_ptr: *mut usize,
338 // vtable_ptr: *mut usize,
340 // We abort on panic, so not much is going on here, but we still have to call the closure.
341 let f = this.read_scalar(args[0])?.not_undef()?;
342 let data = this.read_scalar(args[1])?.not_undef()?;
343 let f_instance = this.memory().get_fn(f)?.as_instance()?;
344 this.write_null(dest)?;
345 trace!("__rust_maybe_catch_panic: {:?}", f_instance);
347 // Now we make a function call.
348 // TODO: consider making this reusable? `InterpCx::step` does something similar
349 // for the TLS destructors, and of course `eval_main`.
350 let mir = this.load_mir(f_instance.def)?;
351 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
352 this.push_stack_frame(
357 // Directly return to caller.
358 StackPopCleanup::Goto(Some(ret)),
360 let mut args = this.frame().body.args_iter();
362 let arg_local = args.next().ok_or_else(||
363 err_unsup!(AbiViolation(
364 "Argument to __rust_maybe_catch_panic does not take enough arguments."
368 let arg_dest = this.local_place(arg_local)?;
369 this.write_scalar(data, arg_dest)?;
371 assert!(args.next().is_none(), "__rust_maybe_catch_panic argument has more arguments than expected");
373 // We ourselves will return `0`, eventually (because we will not return if we paniced).
374 this.write_null(dest)?;
376 // Don't fall through, we do *not* want to `goto_block`!
381 let left = this.read_scalar(args[0])?.not_undef()?;
382 let right = this.read_scalar(args[1])?.not_undef()?;
383 let n = Size::from_bytes(this.read_scalar(args[2])?.to_usize(this)?);
386 let left_bytes = this.memory().read_bytes(left, n)?;
387 let right_bytes = this.memory().read_bytes(right, n)?;
389 use std::cmp::Ordering::*;
390 match left_bytes.cmp(right_bytes) {
398 Scalar::from_int(result, Size::from_bits(32)),
404 let ptr = this.read_scalar(args[0])?.not_undef()?;
405 let val = this.read_scalar(args[1])?.to_i32()? as u8;
406 let num = this.read_scalar(args[2])?.to_usize(this)?;
407 if let Some(idx) = this.memory().read_bytes(ptr, Size::from_bytes(num))?
408 .iter().rev().position(|&c| c == val)
410 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
411 this.write_scalar(new_ptr, dest)?;
413 this.write_null(dest)?;
418 let ptr = this.read_scalar(args[0])?.not_undef()?;
419 let val = this.read_scalar(args[1])?.to_i32()? as u8;
420 let num = this.read_scalar(args[2])?.to_usize(this)?;
423 .read_bytes(ptr, Size::from_bytes(num))?
425 .position(|&c| c == val);
426 if let Some(idx) = idx {
427 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
428 this.write_scalar(new_ptr, dest)?;
430 this.write_null(dest)?;
436 let name_ptr = this.read_scalar(args[0])?.not_undef()?;
437 let name = this.memory().read_c_str(name_ptr)?;
438 match this.machine.env_vars.get(name) {
439 Some(&var) => Scalar::Ptr(var),
440 None => Scalar::ptr_null(&*this.tcx),
443 this.write_scalar(result, dest)?;
447 let mut success = None;
449 let name_ptr = this.read_scalar(args[0])?.not_undef()?;
450 if !this.is_null(name_ptr)? {
451 let name = this.memory().read_c_str(name_ptr)?.to_owned();
452 if !name.is_empty() && !name.contains(&b'=') {
453 success = Some(this.machine.env_vars.remove(&name));
457 if let Some(old) = success {
458 if let Some(var) = old {
459 this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
461 this.write_null(dest)?;
463 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
470 let name_ptr = this.read_scalar(args[0])?.not_undef()?;
471 let value_ptr = this.read_scalar(args[1])?.not_undef()?;
472 let value = this.memory().read_c_str(value_ptr)?;
473 if !this.is_null(name_ptr)? {
474 let name = this.memory().read_c_str(name_ptr)?;
475 if !name.is_empty() && !name.contains(&b'=') {
476 new = Some((name.to_owned(), value.to_owned()));
480 if let Some((name, value)) = new {
481 // `+1` for the null terminator.
482 let value_copy = this.memory_mut().allocate(
483 Size::from_bytes((value.len() + 1) as u64),
484 Align::from_bytes(1).unwrap(),
485 MiriMemoryKind::Env.into(),
487 // We just allocated these, so the write cannot fail.
488 let alloc = this.memory_mut().get_mut(value_copy.alloc_id).unwrap();
489 alloc.write_bytes(tcx, value_copy, &value).unwrap();
490 let trailing_zero_ptr = value_copy.offset(
491 Size::from_bytes(value.len() as u64),
494 alloc.write_bytes(tcx, trailing_zero_ptr, &[0]).unwrap();
496 if let Some(var) = this.machine.env_vars.insert(
501 this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
503 this.write_null(dest)?;
505 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
510 let fd = this.read_scalar(args[0])?.to_i32()?;
511 let buf = this.read_scalar(args[1])?.not_undef()?;
512 let n = this.read_scalar(args[2])?.to_usize(&*this.tcx)?;
513 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
514 let result = if fd == 1 || fd == 2 {
516 use std::io::{self, Write};
518 let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(n))?;
519 // We need to flush to make sure this actually appears on the screen
520 let res = if fd == 1 {
521 // Stdout is buffered, flush to make sure it appears on the screen.
522 // This is the write() syscall of the interpreted program, we want it
523 // to correspond to a write() syscall on the host -- there is no good
524 // in adding extra buffering here.
525 let res = io::stdout().write(buf_cont);
526 io::stdout().flush().unwrap();
529 // No need to flush, stderr is not buffered.
530 io::stderr().write(buf_cont)
537 eprintln!("Miri: Ignored output to FD {}", fd);
538 // Pretend it all went well.
541 // Now, `result` is the value we return back to the program.
543 Scalar::from_int(result, dest.layout.size),
549 let ptr = this.read_scalar(args[0])?.not_undef()?;
550 let n = this.memory().read_c_str(ptr)?.len();
551 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
556 "cbrtf" | "coshf" | "sinhf" |"tanf" => {
557 // FIXME: Using host floats.
558 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
559 let f = match link_name {
566 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
568 // underscore case for windows
569 "_hypotf" | "hypotf" | "atan2f" => {
570 // FIXME: Using host floats.
571 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
572 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
573 let n = match link_name {
574 "_hypotf" | "hypotf" => f1.hypot(f2),
575 "atan2f" => f1.atan2(f2),
578 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
581 "cbrt" | "cosh" | "sinh" | "tan" => {
582 // FIXME: Using host floats.
583 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
584 let f = match link_name {
591 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
593 // underscore case for windows
594 "_hypot" | "hypot" | "atan2" => {
595 // FIXME: Using host floats.
596 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
597 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
598 let n = match link_name {
599 "_hypot" | "hypot" => f1.hypot(f2),
600 "atan2" => f1.atan2(f2),
603 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
606 // Some things needed for `sys::thread` initialization to go through.
607 "signal" | "sigaction" | "sigaltstack" => {
608 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
612 let name = this.read_scalar(args[0])?.to_i32()?;
614 trace!("sysconf() called with name {}", name);
615 // TODO: Cache the sysconf integers via Miri's global cache.
617 (&["libc", "_SC_PAGESIZE"], Scalar::from_int(PAGE_SIZE, dest.layout.size)),
618 (&["libc", "_SC_GETPW_R_SIZE_MAX"], Scalar::from_int(-1, dest.layout.size)),
619 (&["libc", "_SC_NPROCESSORS_ONLN"], Scalar::from_int(NUM_CPUS, dest.layout.size)),
621 let mut result = None;
622 for &(path, path_value) in paths {
623 if let Some(val) = this.eval_path_scalar(path)? {
624 let val = val.to_i32()?;
626 result = Some(path_value);
632 if let Some(result) = result {
633 this.write_scalar(result, dest)?;
635 throw_unsup!(Unimplemented(
636 format!("Unimplemented sysconf name: {}", name),
641 "sched_getaffinity" => {
642 // Return an error; `num_cpus` then falls back to `sysconf`.
643 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
647 this.write_null(dest)?;
650 // Hook pthread calls that go to the thread-local storage memory subsystem.
651 "pthread_key_create" => {
652 let key_ptr = this.read_scalar(args[0])?.not_undef()?;
654 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
655 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
656 Some(dtor_ptr) => Some(this.memory().get_fn(dtor_ptr)?.as_instance()?),
660 // Figure out how large a pthread TLS key actually is.
661 // This is `libc::pthread_key_t`.
662 let key_type = args[0].layout.ty
664 .ok_or_else(|| err_unsup!(
665 AbiViolation("wrong signature used for `pthread_key_create`: first argument must be a raw pointer.".to_owned())
668 let key_layout = this.layout_of(key_type)?;
670 // Create key and write it into the memory where `key_ptr` wants it.
671 let key = this.machine.tls.create_tls_key(dtor) as u128;
672 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128) {
673 throw_unsup!(OutOfTls);
676 let key_ptr = this.memory().check_ptr_access(key_ptr, key_layout.size, key_layout.align.abi)?
677 .expect("cannot be a ZST");
678 this.memory_mut().get_mut(key_ptr.alloc_id)?.write_scalar(
681 Scalar::from_uint(key, key_layout.size).into(),
685 // Return success (`0`).
686 this.write_null(dest)?;
688 "pthread_key_delete" => {
689 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
690 this.machine.tls.delete_tls_key(key)?;
691 // Return success (0)
692 this.write_null(dest)?;
694 "pthread_getspecific" => {
695 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
696 let ptr = this.machine.tls.load_tls(key, tcx)?;
697 this.write_scalar(ptr, dest)?;
699 "pthread_setspecific" => {
700 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
701 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
702 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
704 // Return success (`0`).
705 this.write_null(dest)?;
708 // Stack size/address stuff.
709 "pthread_attr_init" | "pthread_attr_destroy" | "pthread_self" |
710 "pthread_attr_setstacksize" => {
711 this.write_null(dest)?;
713 "pthread_attr_getstack" => {
714 let addr_place = this.deref_operand(args[1])?;
715 let size_place = this.deref_operand(args[2])?;
718 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
722 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
726 // Return success (`0`).
727 this.write_null(dest)?;
730 // We don't support threading. (Also for Windows.)
731 "pthread_create" | "CreateThread" => {
732 throw_unsup!(Unimplemented(format!("Miri does not support threading")));
735 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
736 "pthread_mutexattr_init" | "pthread_mutexattr_settype" | "pthread_mutex_init" |
737 "pthread_mutexattr_destroy" | "pthread_mutex_lock" | "pthread_mutex_unlock" |
738 "pthread_mutex_destroy" | "pthread_rwlock_rdlock" | "pthread_rwlock_unlock" |
739 "pthread_rwlock_wrlock" | "pthread_rwlock_destroy" | "pthread_condattr_init" |
740 "pthread_condattr_setclock" | "pthread_cond_init" | "pthread_condattr_destroy" |
741 "pthread_cond_destroy" => {
742 this.write_null(dest)?;
745 // We don't support fork so we don't have to do anything for atfork.
746 "pthread_atfork" => {
747 this.write_null(dest)?;
751 // 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.
752 let addr = this.read_scalar(args[0])?.not_undef()?;
753 this.write_scalar(addr, dest)?;
756 this.write_null(dest)?;
760 "pthread_attr_get_np" | "pthread_getattr_np" => {
761 this.write_null(dest)?;
763 "pthread_get_stackaddr_np" => {
764 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
765 this.write_scalar(stack_addr, dest)?;
767 "pthread_get_stacksize_np" => {
768 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
769 this.write_scalar(stack_size, dest)?;
772 // FIXME: register the destructor.
775 this.write_scalar(Scalar::Ptr(this.machine.argc.unwrap()), dest)?;
778 this.write_scalar(Scalar::Ptr(this.machine.argv.unwrap()), dest)?;
780 "SecRandomCopyBytes" => {
781 let len = this.read_scalar(args[1])?.to_usize(this)?;
782 let ptr = this.read_scalar(args[2])?.not_undef()?;
783 this.gen_random(len as usize, ptr)?;
784 this.write_null(dest)?;
787 // Windows API stubs.
789 // DWORD = ULONG = u32
791 "GetProcessHeap" => {
792 // Just fake a HANDLE
793 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
796 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
797 let flags = this.read_scalar(args[1])?.to_u32()?;
798 let size = this.read_scalar(args[2])?.to_usize(this)?;
799 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
800 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
801 this.write_scalar(res, dest)?;
804 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
805 let _flags = this.read_scalar(args[1])?.to_u32()?;
806 let ptr = this.read_scalar(args[2])?.not_undef()?;
807 this.free(ptr, MiriMemoryKind::WinHeap)?;
808 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
811 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
812 let _flags = this.read_scalar(args[1])?.to_u32()?;
813 let ptr = this.read_scalar(args[2])?.not_undef()?;
814 let size = this.read_scalar(args[3])?.to_usize(this)?;
815 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
816 this.write_scalar(res, dest)?;
820 let err = this.read_scalar(args[0])?.to_u32()?;
821 this.machine.last_error = err;
824 this.write_scalar(Scalar::from_u32(this.machine.last_error), dest)?;
827 "AddVectoredExceptionHandler" => {
828 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
829 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
831 "InitializeCriticalSection" |
832 "EnterCriticalSection" |
833 "LeaveCriticalSection" |
834 "DeleteCriticalSection" => {
835 // Nothing to do, not even a return value.
839 "TryEnterCriticalSection" |
840 "GetConsoleScreenBufferInfo" |
841 "SetConsoleTextAttribute" => {
842 // Pretend these do not exist / nothing happened, by returning zero.
843 this.write_null(dest)?;
846 let system_info = this.deref_operand(args[0])?;
847 let system_info_ptr = this.check_mplace_access(system_info, None)?
848 .expect("cannot be a ZST");
849 // Initialize with `0`.
850 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
851 .write_repeat(tcx, system_info_ptr, 0, system_info.layout.size)?;
852 // Set number of processors.
853 let dword_size = Size::from_bytes(4);
854 let offset = 2*dword_size + 3*tcx.pointer_size();
855 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
858 system_info_ptr.offset(offset, tcx)?,
859 Scalar::from_int(NUM_CPUS, dword_size).into(),
865 // This just creates a key; Windows does not natively support TLS destructors.
867 // Create key and return it.
868 let key = this.machine.tls.create_tls_key(None) as u128;
870 // Figure out how large a TLS key actually is. This is `c::DWORD`.
871 if dest.layout.size.bits() < 128
872 && key >= (1u128 << dest.layout.size.bits() as u128) {
873 throw_unsup!(OutOfTls);
875 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
878 let key = this.read_scalar(args[0])?.to_u32()? as u128;
879 let ptr = this.machine.tls.load_tls(key, tcx)?;
880 this.write_scalar(ptr, dest)?;
883 let key = this.read_scalar(args[0])?.to_u32()? as u128;
884 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
885 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
887 // Return success (`1`).
888 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
891 let which = this.read_scalar(args[0])?.to_i32()?;
892 // We just make this the identity function, so we know later in `WriteFile`
894 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
897 let handle = this.read_scalar(args[0])?.to_isize(this)?;
898 let buf = this.read_scalar(args[1])?.not_undef()?;
899 let n = this.read_scalar(args[2])?.to_u32()?;
900 let written_place = this.deref_operand(args[3])?;
901 // Spec says to always write `0` first.
902 this.write_null(written_place.into())?;
903 let written = if handle == -11 || handle == -12 {
905 use std::io::{self, Write};
907 let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(u64::from(n)))?;
908 let res = if handle == -11 {
909 io::stdout().write(buf_cont)
911 io::stderr().write(buf_cont)
913 res.ok().map(|n| n as u32)
915 eprintln!("Miri: Ignored output to handle {}", handle);
916 // Pretend it all went well.
919 // If there was no error, write back how much was written.
920 if let Some(n) = written {
921 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
923 // Return whether this was a success.
925 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
929 "GetConsoleMode" => {
930 // Everything is a pipe.
931 this.write_null(dest)?;
933 "GetEnvironmentVariableW" => {
934 // This is not the env var you are looking for.
935 this.machine.last_error = 203; // ERROR_ENVVAR_NOT_FOUND
936 this.write_null(dest)?;
938 "GetCommandLineW" => {
939 this.write_scalar(Scalar::Ptr(this.machine.cmd_line.unwrap()), dest)?;
941 // The actual name of 'RtlGenRandom'
942 "SystemFunction036" => {
943 let ptr = this.read_scalar(args[0])?.not_undef()?;
944 let len = this.read_scalar(args[1])?.to_u32()?;
945 this.gen_random(len as usize, ptr)?;
946 this.write_scalar(Scalar::from_bool(true), dest)?;
949 // We can't execute anything else.
951 throw_unsup!(Unimplemented(
952 format!("can't call foreign function: {}", link_name),
957 this.goto_block(Some(ret))?;
958 this.dump_place(*dest);
962 /// Evaluates the scalar at the specified path. Returns Some(val)
963 /// if the path could be resolved, and None otherwise
964 fn eval_path_scalar(&mut self, path: &[&str]) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
965 let this = self.eval_context_mut();
966 if let Ok(instance) = this.resolve_path(path) {
971 let const_val = this.const_eval_raw(cid)?;
972 let const_val = this.read_scalar(const_val.into())?;
973 return Ok(Some(const_val));