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 use rustc::mir::interpret::InterpError::Panic;
132 let this = self.eval_context_mut();
133 let attrs = this.tcx.get_attrs(def_id);
134 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
135 Some(name) => name.as_str(),
136 None => this.tcx.item_name(def_id).as_str(),
138 // Strip linker suffixes (seen on 32-bit macOS).
139 let link_name = link_name.get().trim_end_matches("$UNIX2003");
140 let tcx = &{this.tcx.tcx};
142 // First: functions that diverge.
144 "__rust_start_panic" | "panic_impl" => {
145 return err!(MachineError("the evaluated program panicked".to_string()));
147 "exit" | "ExitProcess" => {
148 // it's really u32 for ExitProcess, but we have to put it into the `Exit` error variant anyway
149 let code = this.read_scalar(args[0])?.to_i32()?;
150 return err!(Exit(code));
152 _ => if dest.is_none() {
153 return err!(Unimplemented(
154 format!("can't call diverging foreign function: {}", link_name),
159 // Next: functions that assume a ret and dest.
160 let dest = dest.expect("we already checked for a dest");
161 let ret = ret.expect("dest is `Some` but ret is `None`");
164 let size = this.read_scalar(args[0])?.to_usize(this)?;
165 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
166 this.write_scalar(res, dest)?;
169 let items = this.read_scalar(args[0])?.to_usize(this)?;
170 let len = this.read_scalar(args[1])?.to_usize(this)?;
171 let size = items.checked_mul(len).ok_or_else(|| Panic(PanicMessage::Overflow(mir::BinOp::Mul)))?;
172 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
173 this.write_scalar(res, dest)?;
175 "posix_memalign" => {
176 let ret = this.deref_operand(args[0])?;
177 let align = this.read_scalar(args[1])?.to_usize(this)?;
178 let size = this.read_scalar(args[2])?.to_usize(this)?;
179 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
180 if !align.is_power_of_two() {
181 return err!(HeapAllocNonPowerOfTwoAlignment(align));
184 FIXME: This check is disabled because rustc violates it.
185 See <https://github.com/rust-lang/rust/issues/62251>.
186 if align < this.pointer_size().bytes() {
187 return err!(MachineError(format!(
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_mut().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_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_usize(this)?;
218 let align = this.read_scalar(args[1])?.to_usize(this)?;
220 return err!(HeapAllocZeroBytes);
222 if !align.is_power_of_two() {
223 return err!(HeapAllocNonPowerOfTwoAlignment(align));
225 let ptr = this.memory_mut()
227 Size::from_bytes(size),
228 Align::from_bytes(align).unwrap(),
229 MiriMemoryKind::Rust.into()
231 this.write_scalar(Scalar::Ptr(ptr), dest)?;
233 "__rust_alloc_zeroed" => {
234 let size = this.read_scalar(args[0])?.to_usize(this)?;
235 let align = this.read_scalar(args[1])?.to_usize(this)?;
237 return err!(HeapAllocZeroBytes);
239 if !align.is_power_of_two() {
240 return err!(HeapAllocNonPowerOfTwoAlignment(align));
242 let ptr = this.memory_mut()
244 Size::from_bytes(size),
245 Align::from_bytes(align).unwrap(),
246 MiriMemoryKind::Rust.into()
248 // We just allocated this, the access cannot fail
250 .get_mut(ptr.alloc_id).unwrap()
251 .write_repeat(tcx, ptr, 0, Size::from_bytes(size)).unwrap();
252 this.write_scalar(Scalar::Ptr(ptr), dest)?;
254 "__rust_dealloc" => {
255 let ptr = this.read_scalar(args[0])?.not_undef()?;
256 let old_size = this.read_scalar(args[1])?.to_usize(this)?;
257 let align = this.read_scalar(args[2])?.to_usize(this)?;
259 return err!(HeapAllocZeroBytes);
261 if !align.is_power_of_two() {
262 return err!(HeapAllocNonPowerOfTwoAlignment(align));
264 let ptr = this.force_ptr(ptr)?;
265 this.memory_mut().deallocate(
267 Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
268 MiriMemoryKind::Rust.into(),
271 "__rust_realloc" => {
272 let ptr = this.read_scalar(args[0])?.to_ptr()?;
273 let old_size = this.read_scalar(args[1])?.to_usize(this)?;
274 let align = this.read_scalar(args[2])?.to_usize(this)?;
275 let new_size = this.read_scalar(args[3])?.to_usize(this)?;
276 if old_size == 0 || new_size == 0 {
277 return err!(HeapAllocZeroBytes);
279 if !align.is_power_of_two() {
280 return err!(HeapAllocNonPowerOfTwoAlignment(align));
282 let align = Align::from_bytes(align).unwrap();
283 let new_ptr = this.memory_mut().reallocate(
285 Some((Size::from_bytes(old_size), align)),
286 Size::from_bytes(new_size),
288 MiriMemoryKind::Rust.into(),
290 this.write_scalar(Scalar::Ptr(new_ptr), dest)?;
294 let sys_getrandom = this.eval_path_scalar(&["libc", "SYS_getrandom"])?
295 .expect("Failed to get libc::SYS_getrandom")
298 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
299 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
300 match this.read_scalar(args[0])?.to_usize(this)? {
301 id if id == sys_getrandom => {
302 let ptr = this.read_scalar(args[1])?.not_undef()?;
303 let len = this.read_scalar(args[2])?.to_usize(this)?;
305 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
306 // neither of which have any effect on our current PRNG
307 let _flags = this.read_scalar(args[3])?.to_i32()?;
309 this.gen_random(len as usize, ptr)?;
310 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;
313 return err!(Unimplemented(
314 format!("miri does not support syscall ID {}", id),
321 let _handle = this.read_scalar(args[0])?;
322 let symbol = this.read_scalar(args[1])?.not_undef()?;
323 let symbol_name = this.memory().read_c_str(symbol)?;
324 let err = format!("bad c unicode symbol: {:?}", symbol_name);
325 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
326 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
327 let ptr = this.memory_mut().create_fn_alloc(FnVal::Other(dlsym));
328 this.write_scalar(Scalar::from(ptr), dest)?;
330 this.write_null(dest)?;
334 "__rust_maybe_catch_panic" => {
335 // fn __rust_maybe_catch_panic(
338 // data_ptr: *mut usize,
339 // vtable_ptr: *mut usize,
341 // We abort on panic, so not much is going on here, but we still have to call the closure.
342 let f = this.read_scalar(args[0])?.not_undef()?;
343 let data = this.read_scalar(args[1])?.not_undef()?;
344 let f_instance = this.memory().get_fn(f)?.as_instance()?;
345 this.write_null(dest)?;
346 trace!("__rust_maybe_catch_panic: {:?}", f_instance);
348 // Now we make a function call.
349 // TODO: consider making this reusable? `InterpCx::step` does something similar
350 // for the TLS destructors, and of course `eval_main`.
351 let mir = this.load_mir(f_instance.def)?;
352 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
353 this.push_stack_frame(
358 // Directly return to caller.
359 StackPopCleanup::Goto(Some(ret)),
361 let mut args = this.frame().body.args_iter();
363 let arg_local = args.next().ok_or_else(||
364 InterpError::AbiViolation(
365 "Argument to __rust_maybe_catch_panic does not take enough arguments."
369 let arg_dest = this.local_place(arg_local)?;
370 this.write_scalar(data, arg_dest)?;
372 assert!(args.next().is_none(), "__rust_maybe_catch_panic argument has more arguments than expected");
374 // We ourselves will return `0`, eventually (because we will not return if we paniced).
375 this.write_null(dest)?;
377 // Don't fall through, we do *not* want to `goto_block`!
382 let left = this.read_scalar(args[0])?.not_undef()?;
383 let right = this.read_scalar(args[1])?.not_undef()?;
384 let n = Size::from_bytes(this.read_scalar(args[2])?.to_usize(this)?);
387 let left_bytes = this.memory().read_bytes(left, n)?;
388 let right_bytes = this.memory().read_bytes(right, n)?;
390 use std::cmp::Ordering::*;
391 match left_bytes.cmp(right_bytes) {
399 Scalar::from_int(result, Size::from_bits(32)),
405 let ptr = this.read_scalar(args[0])?.not_undef()?;
406 let val = this.read_scalar(args[1])?.to_i32()? as u8;
407 let num = this.read_scalar(args[2])?.to_usize(this)?;
408 if let Some(idx) = this.memory().read_bytes(ptr, Size::from_bytes(num))?
409 .iter().rev().position(|&c| c == val)
411 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
412 this.write_scalar(new_ptr, dest)?;
414 this.write_null(dest)?;
419 let ptr = this.read_scalar(args[0])?.not_undef()?;
420 let val = this.read_scalar(args[1])?.to_i32()? as u8;
421 let num = this.read_scalar(args[2])?.to_usize(this)?;
424 .read_bytes(ptr, Size::from_bytes(num))?
426 .position(|&c| c == val);
427 if let Some(idx) = idx {
428 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
429 this.write_scalar(new_ptr, dest)?;
431 this.write_null(dest)?;
437 let name_ptr = this.read_scalar(args[0])?.not_undef()?;
438 let name = this.memory().read_c_str(name_ptr)?;
439 match this.machine.env_vars.get(name) {
440 Some(&var) => Scalar::Ptr(var),
441 None => Scalar::ptr_null(&*this.tcx),
444 this.write_scalar(result, dest)?;
448 let mut success = None;
450 let name_ptr = this.read_scalar(args[0])?.not_undef()?;
451 if !this.is_null(name_ptr)? {
452 let name = this.memory().read_c_str(name_ptr)?.to_owned();
453 if !name.is_empty() && !name.contains(&b'=') {
454 success = Some(this.machine.env_vars.remove(&name));
458 if let Some(old) = success {
459 if let Some(var) = old {
460 this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
462 this.write_null(dest)?;
464 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
471 let name_ptr = this.read_scalar(args[0])?.not_undef()?;
472 let value_ptr = this.read_scalar(args[1])?.not_undef()?;
473 let value = this.memory().read_c_str(value_ptr)?;
474 if !this.is_null(name_ptr)? {
475 let name = this.memory().read_c_str(name_ptr)?;
476 if !name.is_empty() && !name.contains(&b'=') {
477 new = Some((name.to_owned(), value.to_owned()));
481 if let Some((name, value)) = new {
482 // `+1` for the null terminator.
483 let value_copy = this.memory_mut().allocate(
484 Size::from_bytes((value.len() + 1) as u64),
485 Align::from_bytes(1).unwrap(),
486 MiriMemoryKind::Env.into(),
488 // We just allocated these, so the write cannot fail.
489 let alloc = this.memory_mut().get_mut(value_copy.alloc_id).unwrap();
490 alloc.write_bytes(tcx, value_copy, &value).unwrap();
491 let trailing_zero_ptr = value_copy.offset(
492 Size::from_bytes(value.len() as u64),
495 alloc.write_bytes(tcx, trailing_zero_ptr, &[0]).unwrap();
497 if let Some(var) = this.machine.env_vars.insert(
502 this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
504 this.write_null(dest)?;
506 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
511 let fd = this.read_scalar(args[0])?.to_i32()?;
512 let buf = this.read_scalar(args[1])?.not_undef()?;
513 let n = this.read_scalar(args[2])?.to_usize(&*this.tcx)?;
514 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
515 let result = if fd == 1 || fd == 2 {
517 use std::io::{self, Write};
519 let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(n))?;
520 // We need to flush to make sure this actually appears on the screen
521 let res = if fd == 1 {
522 // Stdout is buffered, flush to make sure it appears on the screen.
523 // This is the write() syscall of the interpreted program, we want it
524 // to correspond to a write() syscall on the host -- there is no good
525 // in adding extra buffering here.
526 let res = io::stdout().write(buf_cont);
527 io::stdout().flush().unwrap();
530 // No need to flush, stderr is not buffered.
531 io::stderr().write(buf_cont)
538 eprintln!("Miri: Ignored output to FD {}", fd);
539 // Pretend it all went well.
542 // Now, `result` is the value we return back to the program.
544 Scalar::from_int(result, dest.layout.size),
550 let ptr = this.read_scalar(args[0])?.not_undef()?;
551 let n = this.memory().read_c_str(ptr)?.len();
552 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
557 "cbrtf" | "coshf" | "sinhf" |"tanf" => {
558 // FIXME: Using host floats.
559 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
560 let f = match link_name {
567 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
569 // underscore case for windows
570 "_hypotf" | "hypotf" | "atan2f" => {
571 // FIXME: Using host floats.
572 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
573 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
574 let n = match link_name {
575 "_hypotf" | "hypotf" => f1.hypot(f2),
576 "atan2f" => f1.atan2(f2),
579 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
582 "cbrt" | "cosh" | "sinh" | "tan" => {
583 // FIXME: Using host floats.
584 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
585 let f = match link_name {
592 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
594 // underscore case for windows
595 "_hypot" | "hypot" | "atan2" => {
596 // FIXME: Using host floats.
597 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
598 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
599 let n = match link_name {
600 "_hypot" | "hypot" => f1.hypot(f2),
601 "atan2" => f1.atan2(f2),
604 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
607 // Some things needed for `sys::thread` initialization to go through.
608 "signal" | "sigaction" | "sigaltstack" => {
609 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
613 let name = this.read_scalar(args[0])?.to_i32()?;
615 trace!("sysconf() called with name {}", name);
616 // TODO: Cache the sysconf integers via Miri's global cache.
618 (&["libc", "_SC_PAGESIZE"], Scalar::from_int(PAGE_SIZE, dest.layout.size)),
619 (&["libc", "_SC_GETPW_R_SIZE_MAX"], Scalar::from_int(-1, dest.layout.size)),
620 (&["libc", "_SC_NPROCESSORS_ONLN"], Scalar::from_int(NUM_CPUS, dest.layout.size)),
622 let mut result = None;
623 for &(path, path_value) in paths {
624 if let Some(val) = this.eval_path_scalar(path)? {
625 let val = val.to_i32()?;
627 result = Some(path_value);
633 if let Some(result) = result {
634 this.write_scalar(result, dest)?;
636 return err!(Unimplemented(
637 format!("Unimplemented sysconf name: {}", name),
642 "sched_getaffinity" => {
643 // Return an error; `num_cpus` then falls back to `sysconf`.
644 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
648 this.write_null(dest)?;
651 // Hook pthread calls that go to the thread-local storage memory subsystem.
652 "pthread_key_create" => {
653 let key_ptr = this.read_scalar(args[0])?.not_undef()?;
655 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
656 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
657 Some(dtor_ptr) => Some(this.memory().get_fn(dtor_ptr)?.as_instance()?),
661 // Figure out how large a pthread TLS key actually is.
662 // This is `libc::pthread_key_t`.
663 let key_type = args[0].layout.ty
665 .ok_or_else(|| InterpError::AbiViolation("wrong signature used for `pthread_key_create`: first argument must be a raw pointer.".to_owned()))?
667 let key_layout = this.layout_of(key_type)?;
669 // Create key and write it into the memory where `key_ptr` wants it.
670 let key = this.machine.tls.create_tls_key(dtor) as u128;
671 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128) {
672 return err!(OutOfTls);
675 let key_ptr = this.memory().check_ptr_access(key_ptr, key_layout.size, key_layout.align.abi)?
676 .expect("cannot be a ZST");
677 this.memory_mut().get_mut(key_ptr.alloc_id)?.write_scalar(
680 Scalar::from_uint(key, key_layout.size).into(),
684 // Return success (`0`).
685 this.write_null(dest)?;
687 "pthread_key_delete" => {
688 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
689 this.machine.tls.delete_tls_key(key)?;
690 // Return success (0)
691 this.write_null(dest)?;
693 "pthread_getspecific" => {
694 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
695 let ptr = this.machine.tls.load_tls(key, tcx)?;
696 this.write_scalar(ptr, dest)?;
698 "pthread_setspecific" => {
699 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
700 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
701 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
703 // Return success (`0`).
704 this.write_null(dest)?;
707 // Stack size/address stuff.
708 "pthread_attr_init" | "pthread_attr_destroy" | "pthread_self" |
709 "pthread_attr_setstacksize" => {
710 this.write_null(dest)?;
712 "pthread_attr_getstack" => {
713 let addr_place = this.deref_operand(args[1])?;
714 let size_place = this.deref_operand(args[2])?;
717 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
721 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
725 // Return success (`0`).
726 this.write_null(dest)?;
729 // We don't support threading. (Also for Windows.)
730 "pthread_create" | "CreateThread" => {
731 return err!(Unimplemented(format!("Miri does not support threading")));
734 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
735 "pthread_mutexattr_init" | "pthread_mutexattr_settype" | "pthread_mutex_init" |
736 "pthread_mutexattr_destroy" | "pthread_mutex_lock" | "pthread_mutex_unlock" |
737 "pthread_mutex_destroy" | "pthread_rwlock_rdlock" | "pthread_rwlock_unlock" |
738 "pthread_rwlock_wrlock" | "pthread_rwlock_destroy" | "pthread_condattr_init" |
739 "pthread_condattr_setclock" | "pthread_cond_init" | "pthread_condattr_destroy" |
740 "pthread_cond_destroy" => {
741 this.write_null(dest)?;
744 // We don't support fork so we don't have to do anything for atfork.
745 "pthread_atfork" => {
746 this.write_null(dest)?;
750 // 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.
751 let addr = this.read_scalar(args[0])?.not_undef()?;
752 this.write_scalar(addr, dest)?;
755 this.write_null(dest)?;
759 "pthread_attr_get_np" | "pthread_getattr_np" => {
760 this.write_null(dest)?;
762 "pthread_get_stackaddr_np" => {
763 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
764 this.write_scalar(stack_addr, dest)?;
766 "pthread_get_stacksize_np" => {
767 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
768 this.write_scalar(stack_size, dest)?;
771 // FIXME: register the destructor.
774 this.write_scalar(Scalar::Ptr(this.machine.argc.unwrap()), dest)?;
777 this.write_scalar(Scalar::Ptr(this.machine.argv.unwrap()), dest)?;
779 "SecRandomCopyBytes" => {
780 let len = this.read_scalar(args[1])?.to_usize(this)?;
781 let ptr = this.read_scalar(args[2])?.not_undef()?;
782 this.gen_random(len as usize, ptr)?;
783 this.write_null(dest)?;
786 // Windows API stubs.
788 // DWORD = ULONG = u32
790 "GetProcessHeap" => {
791 // Just fake a HANDLE
792 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
795 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
796 let flags = this.read_scalar(args[1])?.to_u32()?;
797 let size = this.read_scalar(args[2])?.to_usize(this)?;
798 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
799 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
800 this.write_scalar(res, dest)?;
803 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
804 let _flags = this.read_scalar(args[1])?.to_u32()?;
805 let ptr = this.read_scalar(args[2])?.not_undef()?;
806 this.free(ptr, MiriMemoryKind::WinHeap)?;
807 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
810 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
811 let _flags = this.read_scalar(args[1])?.to_u32()?;
812 let ptr = this.read_scalar(args[2])?.not_undef()?;
813 let size = this.read_scalar(args[3])?.to_usize(this)?;
814 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
815 this.write_scalar(res, dest)?;
819 let err = this.read_scalar(args[0])?.to_u32()?;
820 this.machine.last_error = err;
823 this.write_scalar(Scalar::from_u32(this.machine.last_error), dest)?;
826 "AddVectoredExceptionHandler" => {
827 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
828 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
830 "InitializeCriticalSection" |
831 "EnterCriticalSection" |
832 "LeaveCriticalSection" |
833 "DeleteCriticalSection" => {
834 // Nothing to do, not even a return value.
838 "TryEnterCriticalSection" |
839 "GetConsoleScreenBufferInfo" |
840 "SetConsoleTextAttribute" => {
841 // Pretend these do not exist / nothing happened, by returning zero.
842 this.write_null(dest)?;
845 let system_info = this.deref_operand(args[0])?;
846 let system_info_ptr = this.check_mplace_access(system_info, None)?
847 .expect("cannot be a ZST");
848 // Initialize with `0`.
849 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
850 .write_repeat(tcx, system_info_ptr, 0, system_info.layout.size)?;
851 // Set number of processors.
852 let dword_size = Size::from_bytes(4);
853 let offset = 2*dword_size + 3*tcx.pointer_size();
854 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
857 system_info_ptr.offset(offset, tcx)?,
858 Scalar::from_int(NUM_CPUS, dword_size).into(),
864 // This just creates a key; Windows does not natively support TLS destructors.
866 // Create key and return it.
867 let key = this.machine.tls.create_tls_key(None) as u128;
869 // Figure out how large a TLS key actually is. This is `c::DWORD`.
870 if dest.layout.size.bits() < 128
871 && key >= (1u128 << dest.layout.size.bits() as u128) {
872 return err!(OutOfTls);
874 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
877 let key = this.read_scalar(args[0])?.to_u32()? as u128;
878 let ptr = this.machine.tls.load_tls(key, tcx)?;
879 this.write_scalar(ptr, dest)?;
882 let key = this.read_scalar(args[0])?.to_u32()? as u128;
883 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
884 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
886 // Return success (`1`).
887 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
890 let which = this.read_scalar(args[0])?.to_i32()?;
891 // We just make this the identity function, so we know later in `WriteFile`
893 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
896 let handle = this.read_scalar(args[0])?.to_isize(this)?;
897 let buf = this.read_scalar(args[1])?.not_undef()?;
898 let n = this.read_scalar(args[2])?.to_u32()?;
899 let written_place = this.deref_operand(args[3])?;
900 // Spec says to always write `0` first.
901 this.write_null(written_place.into())?;
902 let written = if handle == -11 || handle == -12 {
904 use std::io::{self, Write};
906 let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(u64::from(n)))?;
907 let res = if handle == -11 {
908 io::stdout().write(buf_cont)
910 io::stderr().write(buf_cont)
912 res.ok().map(|n| n as u32)
914 eprintln!("Miri: Ignored output to handle {}", handle);
915 // Pretend it all went well.
918 // If there was no error, write back how much was written.
919 if let Some(n) = written {
920 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
922 // Return whether this was a success.
924 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
928 "GetConsoleMode" => {
929 // Everything is a pipe.
930 this.write_null(dest)?;
932 "GetEnvironmentVariableW" => {
933 // This is not the env var you are looking for.
934 this.machine.last_error = 203; // ERROR_ENVVAR_NOT_FOUND
935 this.write_null(dest)?;
937 "GetCommandLineW" => {
938 this.write_scalar(Scalar::Ptr(this.machine.cmd_line.unwrap()), dest)?;
940 // The actual name of 'RtlGenRandom'
941 "SystemFunction036" => {
942 let ptr = this.read_scalar(args[0])?.not_undef()?;
943 let len = this.read_scalar(args[1])?.to_u32()?;
944 this.gen_random(len as usize, ptr)?;
945 this.write_scalar(Scalar::from_bool(true), dest)?;
948 // We can't execute anything else.
950 return err!(Unimplemented(
951 format!("can't call foreign function: {}", link_name),
956 this.goto_block(Some(ret))?;
957 this.dump_place(*dest);
961 /// Evaluates the scalar at the specified path. Returns Some(val)
962 /// if the path could be resolved, and None otherwise
963 fn eval_path_scalar(&mut self, path: &[&str]) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
964 let this = self.eval_context_mut();
965 if let Ok(instance) = this.resolve_path(path) {
970 let const_val = this.const_eval_raw(cid)?;
971 let const_val = this.read_scalar(const_val.into())?;
972 return Ok(Some(const_val));