1 use rustc::ty::layout::{Align, LayoutOf, Size};
2 use rustc::hir::def_id::DefId;
5 use syntax::symbol::sym;
11 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
12 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
13 /// Returns the minimum alignment for the target architecture for allocations of the given size.
14 fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
15 let this = self.eval_context_ref();
16 // List taken from `libstd/sys_common/alloc.rs`.
17 let min_align = match this.tcx.tcx.sess.target.target.arch.as_str() {
18 "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
19 "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
20 arch => bug!("Unsupported target architecture: {}", arch),
22 // Windows always aligns, even small allocations.
23 // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
24 // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
25 if kind == MiriMemoryKind::WinHeap || size >= min_align {
26 return Align::from_bytes(min_align).unwrap();
28 // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
29 fn prev_power_of_two(x: u64) -> u64 {
30 let next_pow2 = x.next_power_of_two();
32 // x *is* a power of two, just use that.
35 // x is between two powers, so next = 2*prev.
39 Align::from_bytes(prev_power_of_two(size)).unwrap()
48 let this = self.eval_context_mut();
49 let tcx = &{this.tcx.tcx};
51 Scalar::from_int(0, this.pointer_size())
53 let align = this.min_align(size, kind);
54 let ptr = this.memory_mut().allocate(Size::from_bytes(size), align, kind.into());
56 // We just allocated this, the access cannot fail
58 .get_mut(ptr.alloc_id).unwrap()
59 .write_repeat(tcx, ptr, 0, Size::from_bytes(size)).unwrap();
69 ) -> InterpResult<'tcx> {
70 let this = self.eval_context_mut();
71 if !this.is_null(ptr)? {
72 let ptr = this.force_ptr(ptr)?;
73 this.memory_mut().deallocate(
87 ) -> InterpResult<'tcx, Scalar<Tag>> {
88 let this = self.eval_context_mut();
89 let new_align = this.min_align(new_size, kind);
90 if this.is_null(old_ptr)? {
92 Ok(Scalar::from_int(0, this.pointer_size()))
94 let new_ptr = this.memory_mut().allocate(
95 Size::from_bytes(new_size),
99 Ok(Scalar::Ptr(new_ptr))
102 let old_ptr = this.force_ptr(old_ptr)?;
103 let memory = this.memory_mut();
110 Ok(Scalar::from_int(0, this.pointer_size()))
112 let new_ptr = memory.reallocate(
115 Size::from_bytes(new_size),
119 Ok(Scalar::Ptr(new_ptr))
124 /// Emulates calling a foreign item, failing if the item is not supported.
125 /// This function will handle `goto_block` if needed.
126 fn emulate_foreign_item(
129 args: &[OpTy<'tcx, Tag>],
130 dest: Option<PlaceTy<'tcx, Tag>>,
131 ret: Option<mir::BasicBlock>,
132 ) -> InterpResult<'tcx> {
133 let this = self.eval_context_mut();
134 let attrs = this.tcx.get_attrs(def_id);
135 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
136 Some(name) => name.as_str(),
137 None => this.tcx.item_name(def_id).as_str(),
139 // Strip linker suffixes (seen on 32-bit macOS).
140 let link_name = link_name.get().trim_end_matches("$UNIX2003");
141 let tcx = &{this.tcx.tcx};
143 // First: functions that diverge.
145 "__rust_start_panic" | "panic_impl" => {
146 return err!(MachineError("the evaluated program panicked".to_string()));
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!(Exit(code));
153 _ => if dest.is_none() {
154 return err!(Unimplemented(
155 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_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_usize(this)?;
171 let len = this.read_scalar(args[1])?.to_usize(this)?;
172 let size = items.checked_mul(len).ok_or_else(|| InterpError::Overflow(mir::BinOp::Mul))?;
173 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
174 this.write_scalar(res, dest)?;
176 "posix_memalign" => {
177 let ret = this.deref_operand(args[0])?;
178 let align = this.read_scalar(args[1])?.to_usize(this)?;
179 let size = this.read_scalar(args[2])?.to_usize(this)?;
180 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
181 if !align.is_power_of_two() {
182 return err!(HeapAllocNonPowerOfTwoAlignment(align));
185 FIXME: This check is disabled because rustc violates it.
186 See <https://github.com/rust-lang/rust/issues/62251>.
187 if align < this.pointer_size().bytes() {
188 return err!(MachineError(format!(
189 "posix_memalign: alignment must be at least the size of a pointer, but is {}",
195 this.write_null(ret.into())?;
197 let ptr = this.memory_mut().allocate(
198 Size::from_bytes(size),
199 Align::from_bytes(align).unwrap(),
200 MiriMemoryKind::C.into()
202 this.write_scalar(Scalar::Ptr(ptr), ret.into())?;
204 this.write_null(dest)?;
207 let ptr = this.read_scalar(args[0])?.not_undef()?;
208 this.free(ptr, MiriMemoryKind::C)?;
211 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
212 let new_size = this.read_scalar(args[1])?.to_usize(this)?;
213 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
214 this.write_scalar(res, dest)?;
218 let size = this.read_scalar(args[0])?.to_usize(this)?;
219 let align = this.read_scalar(args[1])?.to_usize(this)?;
221 return err!(HeapAllocZeroBytes);
223 if !align.is_power_of_two() {
224 return err!(HeapAllocNonPowerOfTwoAlignment(align));
226 let ptr = this.memory_mut()
228 Size::from_bytes(size),
229 Align::from_bytes(align).unwrap(),
230 MiriMemoryKind::Rust.into()
232 this.write_scalar(Scalar::Ptr(ptr), dest)?;
234 "__rust_alloc_zeroed" => {
235 let size = this.read_scalar(args[0])?.to_usize(this)?;
236 let align = this.read_scalar(args[1])?.to_usize(this)?;
238 return err!(HeapAllocZeroBytes);
240 if !align.is_power_of_two() {
241 return err!(HeapAllocNonPowerOfTwoAlignment(align));
243 let ptr = this.memory_mut()
245 Size::from_bytes(size),
246 Align::from_bytes(align).unwrap(),
247 MiriMemoryKind::Rust.into()
249 // We just allocated this, the access cannot fail
251 .get_mut(ptr.alloc_id).unwrap()
252 .write_repeat(tcx, ptr, 0, Size::from_bytes(size)).unwrap();
253 this.write_scalar(Scalar::Ptr(ptr), dest)?;
255 "__rust_dealloc" => {
256 let ptr = this.read_scalar(args[0])?.not_undef()?;
257 let old_size = this.read_scalar(args[1])?.to_usize(this)?;
258 let align = this.read_scalar(args[2])?.to_usize(this)?;
260 return err!(HeapAllocZeroBytes);
262 if !align.is_power_of_two() {
263 return err!(HeapAllocNonPowerOfTwoAlignment(align));
265 let ptr = this.force_ptr(ptr)?;
266 this.memory_mut().deallocate(
268 Some((Size::from_bytes(old_size), 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_usize(this)?;
275 let align = this.read_scalar(args[2])?.to_usize(this)?;
276 let new_size = this.read_scalar(args[3])?.to_usize(this)?;
277 if old_size == 0 || new_size == 0 {
278 return err!(HeapAllocZeroBytes);
280 if !align.is_power_of_two() {
281 return err!(HeapAllocNonPowerOfTwoAlignment(align));
283 let align = Align::from_bytes(align).unwrap();
284 let new_ptr = this.memory_mut().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.eval_path_scalar(&["libc", "SYS_getrandom"])?
296 .expect("Failed to get libc::SYS_getrandom")
299 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
300 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
301 match this.read_scalar(args[0])?.to_usize(this)? {
302 id if id == sys_getrandom => {
303 let ptr = this.read_scalar(args[1])?.not_undef()?;
304 let len = this.read_scalar(args[2])?.to_usize(this)?;
306 // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
307 // neither of which have any effect on our current PRNG
308 let _flags = this.read_scalar(args[3])?.to_i32()?;
310 this.gen_random(len as usize, ptr)?;
311 this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;
314 return err!(Unimplemented(
315 format!("miri does not support syscall ID {}", id),
322 let _handle = this.read_scalar(args[0])?;
323 let symbol = this.read_scalar(args[1])?.to_ptr()?;
324 let symbol_name = this.memory().get(symbol.alloc_id)?.read_c_str(tcx, symbol)?;
325 let err = format!("bad c unicode symbol: {:?}", symbol_name);
326 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
327 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
328 let ptr = this.memory_mut().create_fn_alloc(FnVal::Other(dlsym));
329 this.write_scalar(Scalar::from(ptr), dest)?;
331 this.write_null(dest)?;
335 "__rust_maybe_catch_panic" => {
336 // fn __rust_maybe_catch_panic(
339 // data_ptr: *mut usize,
340 // vtable_ptr: *mut usize,
342 // We abort on panic, so not much is going on here, but we still have to call the closure.
343 let f = this.read_scalar(args[0])?.to_ptr()?;
344 let data = this.read_scalar(args[1])?.not_undef()?;
345 let f_instance = this.memory().get_fn(f)?.as_instance()?;
346 this.write_null(dest)?;
347 trace!("__rust_maybe_catch_panic: {:?}", f_instance);
349 // Now we make a function call.
350 // TODO: consider making this reusable? `InterpCx::step` does something similar
351 // for the TLS destructors, and of course `eval_main`.
352 let mir = this.load_mir(f_instance.def)?;
353 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
354 this.push_stack_frame(
359 // Directly return to caller.
360 StackPopCleanup::Goto(Some(ret)),
362 let mut args = this.frame().body.args_iter();
364 let arg_local = args.next().ok_or_else(||
365 InterpError::AbiViolation(
366 "Argument to __rust_maybe_catch_panic does not take enough arguments."
370 let arg_dest = this.eval_place(&mir::Place::Base(mir::PlaceBase::Local(arg_local)))?;
371 this.write_scalar(data, arg_dest)?;
373 assert!(args.next().is_none(), "__rust_maybe_catch_panic argument has more arguments than expected");
375 // We ourselves will return `0`, eventually (because we will not return if we paniced).
376 this.write_null(dest)?;
378 // Don't fall through, we do *not* want to `goto_block`!
383 let left = this.read_scalar(args[0])?.not_undef()?;
384 let right = this.read_scalar(args[1])?.not_undef()?;
385 let n = Size::from_bytes(this.read_scalar(args[2])?.to_usize(this)?);
388 let left_bytes = this.memory().read_bytes(left, n)?;
389 let right_bytes = this.memory().read_bytes(right, n)?;
391 use std::cmp::Ordering::*;
392 match left_bytes.cmp(right_bytes) {
400 Scalar::from_int(result, Size::from_bits(32)),
406 let ptr = this.read_scalar(args[0])?.not_undef()?;
407 let val = this.read_scalar(args[1])?.to_i32()? as u8;
408 let num = this.read_scalar(args[2])?.to_usize(this)?;
409 if let Some(idx) = this.memory().read_bytes(ptr, Size::from_bytes(num))?
410 .iter().rev().position(|&c| c == val)
412 let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
413 this.write_scalar(new_ptr, dest)?;
415 this.write_null(dest)?;
420 let ptr = this.read_scalar(args[0])?.not_undef()?;
421 let val = this.read_scalar(args[1])?.to_i32()? as u8;
422 let num = this.read_scalar(args[2])?.to_usize(this)?;
425 .read_bytes(ptr, Size::from_bytes(num))?
427 .position(|&c| c == val);
428 if let Some(idx) = idx {
429 let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
430 this.write_scalar(new_ptr, dest)?;
432 this.write_null(dest)?;
438 let name_ptr = this.read_scalar(args[0])?.to_ptr()?;
439 let name = this.memory().get(name_ptr.alloc_id)?.read_c_str(tcx, name_ptr)?;
440 match this.machine.env_vars.get(name) {
441 Some(&var) => Scalar::Ptr(var),
442 None => Scalar::ptr_null(&*this.tcx),
445 this.write_scalar(result, dest)?;
449 let mut success = None;
451 let name_ptr = this.read_scalar(args[0])?.not_undef()?;
452 if !this.is_null(name_ptr)? {
453 let name_ptr = name_ptr.to_ptr()?;
456 .get(name_ptr.alloc_id)?
457 .read_c_str(tcx, name_ptr)?
459 if !name.is_empty() && !name.contains(&b'=') {
460 success = Some(this.machine.env_vars.remove(&name));
464 if let Some(old) = success {
465 if let Some(var) = old {
466 this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
468 this.write_null(dest)?;
470 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
477 let name_ptr = this.read_scalar(args[0])?.not_undef()?;
478 let value_ptr = this.read_scalar(args[1])?.to_ptr()?;
479 let value = this.memory().get(value_ptr.alloc_id)?.read_c_str(tcx, value_ptr)?;
480 if !this.is_null(name_ptr)? {
481 let name_ptr = name_ptr.to_ptr()?;
482 let name = this.memory().get(name_ptr.alloc_id)?.read_c_str(tcx, name_ptr)?;
483 if !name.is_empty() && !name.contains(&b'=') {
484 new = Some((name.to_owned(), value.to_owned()));
488 if let Some((name, value)) = new {
489 // `+1` for the null terminator.
490 let value_copy = this.memory_mut().allocate(
491 Size::from_bytes((value.len() + 1) as u64),
492 Align::from_bytes(1).unwrap(),
493 MiriMemoryKind::Env.into(),
495 // We just allocated these, so the write cannot fail.
496 let alloc = this.memory_mut().get_mut(value_copy.alloc_id).unwrap();
497 alloc.write_bytes(tcx, value_copy, &value).unwrap();
498 let trailing_zero_ptr = value_copy.offset(
499 Size::from_bytes(value.len() as u64),
502 alloc.write_bytes(tcx, trailing_zero_ptr, &[0]).unwrap();
504 if let Some(var) = this.machine.env_vars.insert(
509 this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
511 this.write_null(dest)?;
513 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
518 let fd = this.read_scalar(args[0])?.to_i32()?;
519 let buf = this.read_scalar(args[1])?.not_undef()?;
520 let n = this.read_scalar(args[2])?.to_usize(&*this.tcx)?;
521 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
522 let result = if fd == 1 || fd == 2 {
524 use std::io::{self, Write};
526 let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(n))?;
527 // We need to flush to make sure this actually appears on the screen
528 let res = if fd == 1 {
529 // Stdout is buffered, flush to make sure it appears on the screen.
530 // This is the write() syscall of the interpreted program, we want it
531 // to correspond to a write() syscall on the host -- there is no good
532 // in adding extra buffering here.
533 let res = io::stdout().write(buf_cont);
534 io::stdout().flush().unwrap();
537 // No need to flush, stderr is not buffered.
538 io::stderr().write(buf_cont)
545 eprintln!("Miri: Ignored output to FD {}", fd);
546 // Pretend it all went well.
549 // Now, `result` is the value we return back to the program.
551 Scalar::from_int(result, dest.layout.size),
557 let ptr = this.read_scalar(args[0])?.to_ptr()?;
558 let n = this.memory().get(ptr.alloc_id)?.read_c_str(tcx, ptr)?.len();
559 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
564 "cbrtf" | "coshf" | "sinhf" |"tanf" => {
565 // FIXME: Using host floats.
566 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
567 let f = match link_name {
574 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
576 // underscore case for windows
577 "_hypotf" | "hypotf" | "atan2f" => {
578 // FIXME: Using host floats.
579 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
580 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
581 let n = match link_name {
582 "_hypotf" | "hypotf" => f1.hypot(f2),
583 "atan2f" => f1.atan2(f2),
586 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
589 "cbrt" | "cosh" | "sinh" | "tan" => {
590 // FIXME: Using host floats.
591 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
592 let f = match link_name {
599 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
601 // underscore case for windows
602 "_hypot" | "hypot" | "atan2" => {
603 // FIXME: Using host floats.
604 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
605 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
606 let n = match link_name {
607 "_hypot" | "hypot" => f1.hypot(f2),
608 "atan2" => f1.atan2(f2),
611 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
614 // Some things needed for `sys::thread` initialization to go through.
615 "signal" | "sigaction" | "sigaltstack" => {
616 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
620 let name = this.read_scalar(args[0])?.to_i32()?;
622 trace!("sysconf() called with name {}", name);
623 // TODO: Cache the sysconf integers via Miri's global cache.
625 (&["libc", "_SC_PAGESIZE"], Scalar::from_int(PAGE_SIZE, dest.layout.size)),
626 (&["libc", "_SC_GETPW_R_SIZE_MAX"], Scalar::from_int(-1, dest.layout.size)),
627 (&["libc", "_SC_NPROCESSORS_ONLN"], Scalar::from_int(NUM_CPUS, dest.layout.size)),
629 let mut result = None;
630 for &(path, path_value) in paths {
631 if let Some(val) = this.eval_path_scalar(path)? {
632 let val = val.to_i32()?;
634 result = Some(path_value);
640 if let Some(result) = result {
641 this.write_scalar(result, dest)?;
643 return err!(Unimplemented(
644 format!("Unimplemented sysconf name: {}", name),
649 "sched_getaffinity" => {
650 // Return an error; `num_cpus` then falls back to `sysconf`.
651 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
655 this.write_null(dest)?;
658 // Hook pthread calls that go to the thread-local storage memory subsystem.
659 "pthread_key_create" => {
660 let key_ptr = this.read_scalar(args[0])?.not_undef()?;
662 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
663 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
664 Some(dtor_ptr) => Some(this.memory().get_fn(dtor_ptr)?.as_instance()?),
668 // Figure out how large a pthread TLS key actually is.
669 // This is `libc::pthread_key_t`.
670 let key_type = args[0].layout.ty
672 .ok_or_else(|| InterpError::AbiViolation("wrong signature used for `pthread_key_create`: first argument must be a raw pointer.".to_owned()))?
674 let key_layout = this.layout_of(key_type)?;
676 // Create key and write it into the memory where `key_ptr` wants it.
677 let key = this.machine.tls.create_tls_key(dtor) as u128;
678 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128) {
679 return err!(OutOfTls);
682 let key_ptr = this.memory().check_ptr_access(key_ptr, key_layout.size, key_layout.align.abi)?
683 .expect("cannot be a ZST");
684 this.memory_mut().get_mut(key_ptr.alloc_id)?.write_scalar(
687 Scalar::from_uint(key, key_layout.size).into(),
691 // Return success (`0`).
692 this.write_null(dest)?;
694 "pthread_key_delete" => {
695 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
696 this.machine.tls.delete_tls_key(key)?;
697 // Return success (0)
698 this.write_null(dest)?;
700 "pthread_getspecific" => {
701 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
702 let ptr = this.machine.tls.load_tls(key, tcx)?;
703 this.write_scalar(ptr, dest)?;
705 "pthread_setspecific" => {
706 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
707 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
708 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
710 // Return success (`0`).
711 this.write_null(dest)?;
714 // Stack size/address stuff.
715 "pthread_attr_init" | "pthread_attr_destroy" | "pthread_self" |
716 "pthread_attr_setstacksize" => {
717 this.write_null(dest)?;
719 "pthread_attr_getstack" => {
720 let addr_place = this.deref_operand(args[1])?;
721 let size_place = this.deref_operand(args[2])?;
724 Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
728 Scalar::from_uint(STACK_SIZE, size_place.layout.size),
732 // Return success (`0`).
733 this.write_null(dest)?;
736 // We don't support threading.
737 "pthread_create" => {
738 return err!(Unimplemented(format!("Miri does not support threading")));
741 // Stub out calls for condvar, mutex and rwlock, to just return `0`.
742 "pthread_mutexattr_init" | "pthread_mutexattr_settype" | "pthread_mutex_init" |
743 "pthread_mutexattr_destroy" | "pthread_mutex_lock" | "pthread_mutex_unlock" |
744 "pthread_mutex_destroy" | "pthread_rwlock_rdlock" | "pthread_rwlock_unlock" |
745 "pthread_rwlock_wrlock" | "pthread_rwlock_destroy" | "pthread_condattr_init" |
746 "pthread_condattr_setclock" | "pthread_cond_init" | "pthread_condattr_destroy" |
747 "pthread_cond_destroy" => {
748 this.write_null(dest)?;
751 // We don't support fork so we don't have to do anything for atfork.
752 "pthread_atfork" => {
753 this.write_null(dest)?;
757 // 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.
758 let addr = this.read_scalar(args[0])?.not_undef()?;
759 this.write_scalar(addr, dest)?;
762 this.write_null(dest)?;
766 "pthread_attr_get_np" | "pthread_getattr_np" => {
767 this.write_null(dest)?;
769 "pthread_get_stackaddr_np" => {
770 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
771 this.write_scalar(stack_addr, dest)?;
773 "pthread_get_stacksize_np" => {
774 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
775 this.write_scalar(stack_size, dest)?;
778 // FIXME: register the destructor.
781 this.write_scalar(Scalar::Ptr(this.machine.argc.unwrap()), dest)?;
784 this.write_scalar(Scalar::Ptr(this.machine.argv.unwrap()), dest)?;
786 "SecRandomCopyBytes" => {
787 let len = this.read_scalar(args[1])?.to_usize(this)?;
788 let ptr = this.read_scalar(args[2])?.not_undef()?;
789 this.gen_random(len as usize, ptr)?;
790 this.write_null(dest)?;
793 // Windows API stubs.
795 // DWORD = ULONG = u32
797 "GetProcessHeap" => {
798 // Just fake a HANDLE
799 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
802 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
803 let flags = this.read_scalar(args[1])?.to_u32()?;
804 let size = this.read_scalar(args[2])?.to_usize(this)?;
805 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
806 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
807 this.write_scalar(res, 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 this.free(ptr, MiriMemoryKind::WinHeap)?;
814 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
817 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
818 let _flags = this.read_scalar(args[1])?.to_u32()?;
819 let ptr = this.read_scalar(args[2])?.not_undef()?;
820 let size = this.read_scalar(args[3])?.to_usize(this)?;
821 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
822 this.write_scalar(res, dest)?;
826 let err = this.read_scalar(args[0])?.to_u32()?;
827 this.machine.last_error = err;
830 this.write_scalar(Scalar::from_u32(this.machine.last_error), dest)?;
833 "AddVectoredExceptionHandler" => {
834 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
835 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
837 "InitializeCriticalSection" |
838 "EnterCriticalSection" |
839 "LeaveCriticalSection" |
840 "DeleteCriticalSection" => {
841 // Nothing to do, not even a return value.
845 "TryEnterCriticalSection" |
846 "GetConsoleScreenBufferInfo" |
847 "SetConsoleTextAttribute" => {
848 // Pretend these do not exist / nothing happened, by returning zero.
849 this.write_null(dest)?;
852 let system_info = this.deref_operand(args[0])?;
853 let (system_info_ptr, align) = system_info.to_scalar_ptr_align();
854 let system_info_ptr = this.memory()
857 system_info.layout.size,
860 .expect("cannot be a ZST");
861 // Initialize with `0`.
862 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
863 .write_repeat(tcx, system_info_ptr, 0, system_info.layout.size)?;
864 // Set number of processors.
865 let dword_size = Size::from_bytes(4);
866 let offset = 2*dword_size + 3*tcx.pointer_size();
867 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
870 system_info_ptr.offset(offset, tcx)?,
871 Scalar::from_int(NUM_CPUS, dword_size).into(),
877 // This just creates a key; Windows does not natively support TLS destructors.
879 // Create key and return it.
880 let key = this.machine.tls.create_tls_key(None) as u128;
882 // Figure out how large a TLS key actually is. This is `c::DWORD`.
883 if dest.layout.size.bits() < 128
884 && key >= (1u128 << dest.layout.size.bits() as u128) {
885 return err!(OutOfTls);
887 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
890 let key = this.read_scalar(args[0])?.to_u32()? as u128;
891 let ptr = this.machine.tls.load_tls(key, tcx)?;
892 this.write_scalar(ptr, dest)?;
895 let key = this.read_scalar(args[0])?.to_u32()? as u128;
896 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
897 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
899 // Return success (`1`).
900 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
903 let which = this.read_scalar(args[0])?.to_i32()?;
904 // We just make this the identity function, so we know later in `WriteFile`
906 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
909 let handle = this.read_scalar(args[0])?.to_isize(this)?;
910 let buf = this.read_scalar(args[1])?.not_undef()?;
911 let n = this.read_scalar(args[2])?.to_u32()?;
912 let written_place = this.deref_operand(args[3])?;
913 // Spec says to always write `0` first.
914 this.write_null(written_place.into())?;
915 let written = if handle == -11 || handle == -12 {
917 use std::io::{self, Write};
919 let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(u64::from(n)))?;
920 let res = if handle == -11 {
921 io::stdout().write(buf_cont)
923 io::stderr().write(buf_cont)
925 res.ok().map(|n| n as u32)
927 eprintln!("Miri: Ignored output to handle {}", handle);
928 // Pretend it all went well.
931 // If there was no error, write back how much was written.
932 if let Some(n) = written {
933 this.write_scalar(Scalar::from_u32(n), written_place.into())?;
935 // Return whether this was a success.
937 Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
941 "GetConsoleMode" => {
942 // Everything is a pipe.
943 this.write_null(dest)?;
945 "GetEnvironmentVariableW" => {
946 // This is not the env var you are looking for.
947 this.machine.last_error = 203; // ERROR_ENVVAR_NOT_FOUND
948 this.write_null(dest)?;
950 "GetCommandLineW" => {
951 this.write_scalar(Scalar::Ptr(this.machine.cmd_line.unwrap()), dest)?;
953 // The actual name of 'RtlGenRandom'
954 "SystemFunction036" => {
955 let ptr = this.read_scalar(args[0])?.not_undef()?;
956 let len = this.read_scalar(args[1])?.to_u32()?;
957 this.gen_random(len as usize, ptr)?;
958 this.write_scalar(Scalar::from_bool(true), dest)?;
961 // We can't execute anything else.
963 return err!(Unimplemented(
964 format!("can't call foreign function: {}", link_name),
969 this.goto_block(Some(ret))?;
970 this.dump_place(*dest);
974 /// Evaluates the scalar at the specified path. Returns Some(val)
975 /// if the path could be resolved, and None otherwise
976 fn eval_path_scalar(&mut self, path: &[&str]) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
977 let this = self.eval_context_mut();
978 if let Ok(instance) = this.resolve_path(path) {
983 let const_val = this.const_eval_raw(cid)?;
984 let const_val = this.read_scalar(const_val.into())?;
985 return Ok(Some(const_val));
994 ) -> InterpResult<'tcx> {
999 let this = self.eval_context_mut();
1000 let ptr = dest.to_ptr()?;
1002 let data = match &mut this.memory_mut().extra.rng {
1004 let mut rng = rng.borrow_mut();
1005 let mut data = vec![0; len];
1006 rng.fill_bytes(&mut data);
1010 return err!(Unimplemented(
1011 "miri does not support gathering system entropy in deterministic mode!
1012 Use '-Zmiri-seed=<seed>' to enable random number generation.
1013 WARNING: Miri does *not* generate cryptographically secure entropy -
1014 do not use Miri to run any program that needs secure random number generation".to_owned(),
1018 let tcx = &{this.tcx.tcx};
1019 this.memory_mut().get_mut(ptr.alloc_id)?
1020 .write_bytes(tcx, ptr, &data)