]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items.rs
Auto merge of #830 - RalfJung:check-place, r=RalfJung
[rust.git] / src / shims / foreign_items.rs
1 use rustc::ty::layout::{Align, LayoutOf, Size};
2 use rustc::hir::def_id::DefId;
3 use rustc::mir;
4 use syntax::attr;
5 use syntax::symbol::sym;
6
7 use crate::*;
8
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),
19         };
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();
25         }
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();
29             if next_pow2 == x {
30                 // x *is* a power of two, just use that.
31                 x
32             } else {
33                 // x is between two powers, so next = 2*prev.
34                 next_pow2 / 2
35             }
36         }
37         Align::from_bytes(prev_power_of_two(size)).unwrap()
38     }
39
40     fn malloc(
41         &mut self,
42         size: u64,
43         zero_init: bool,
44         kind: MiriMemoryKind,
45     ) -> Scalar<Tag> {
46         let this = self.eval_context_mut();
47         let tcx = &{this.tcx.tcx};
48         if size == 0 {
49             Scalar::from_int(0, this.pointer_size())
50         } else {
51             let align = this.min_align(size, kind);
52             let ptr = this.memory_mut().allocate(Size::from_bytes(size), align, kind.into());
53             if zero_init {
54                 // We just allocated this, the access cannot fail
55                 this.memory_mut()
56                     .get_mut(ptr.alloc_id).unwrap()
57                     .write_repeat(tcx, ptr, 0, Size::from_bytes(size)).unwrap();
58             }
59             Scalar::Ptr(ptr)
60         }
61     }
62
63     fn free(
64         &mut self,
65         ptr: Scalar<Tag>,
66         kind: MiriMemoryKind,
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(
72                 ptr,
73                 None,
74                 kind.into(),
75             )?;
76         }
77         Ok(())
78     }
79
80     fn realloc(
81         &mut self,
82         old_ptr: Scalar<Tag>,
83         new_size: u64,
84         kind: MiriMemoryKind,
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)? {
89             if new_size == 0 {
90                 Ok(Scalar::from_int(0, this.pointer_size()))
91             } else {
92                 let new_ptr = this.memory_mut().allocate(
93                     Size::from_bytes(new_size),
94                     new_align,
95                     kind.into()
96                 );
97                 Ok(Scalar::Ptr(new_ptr))
98             }
99         } else {
100             let old_ptr = this.force_ptr(old_ptr)?;
101             let memory = this.memory_mut();
102             if new_size == 0 {
103                 memory.deallocate(
104                     old_ptr,
105                     None,
106                     kind.into(),
107                 )?;
108                 Ok(Scalar::from_int(0, this.pointer_size()))
109             } else {
110                 let new_ptr = memory.reallocate(
111                     old_ptr,
112                     None,
113                     Size::from_bytes(new_size),
114                     new_align,
115                     kind.into(),
116                 )?;
117                 Ok(Scalar::Ptr(new_ptr))
118             }
119         }
120     }
121
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(
125         &mut self,
126         def_id: DefId,
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(),
136         };
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};
140
141         // First: functions that diverge.
142         match link_name {
143             "__rust_start_panic" | "panic_impl" => {
144                 return err!(MachineError("the evaluated program panicked".to_string()));
145             }
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!(Exit(code));
150             }
151             _ => if dest.is_none() {
152                 return err!(Unimplemented(
153                     format!("can't call diverging foreign function: {}", link_name),
154                 ));
155             }
156         }
157
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`");
161         match link_name {
162             "malloc" => {
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)?;
166             }
167             "calloc" => {
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(|| InterpError::Overflow(mir::BinOp::Mul))?;
171                 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
172                 this.write_scalar(res, dest)?;
173             }
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                     return err!(HeapAllocNonPowerOfTwoAlignment(align));
181                 }
182                 /*
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                     return err!(MachineError(format!(
187                         "posix_memalign: alignment must be at least the size of a pointer, but is {}",
188                         align,
189                     )));
190                 }
191                 */
192                 if size == 0 {
193                     this.write_null(ret.into())?;
194                 } else {
195                     let ptr = this.memory_mut().allocate(
196                         Size::from_bytes(size),
197                         Align::from_bytes(align).unwrap(),
198                         MiriMemoryKind::C.into()
199                     );
200                     this.write_scalar(Scalar::Ptr(ptr), ret.into())?;
201                 }
202                 this.write_null(dest)?;
203             }
204             "free" => {
205                 let ptr = this.read_scalar(args[0])?.not_undef()?;
206                 this.free(ptr, MiriMemoryKind::C)?;
207             }
208             "realloc" => {
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)?;
213             }
214
215             "__rust_alloc" => {
216                 let size = this.read_scalar(args[0])?.to_usize(this)?;
217                 let align = this.read_scalar(args[1])?.to_usize(this)?;
218                 if size == 0 {
219                     return err!(HeapAllocZeroBytes);
220                 }
221                 if !align.is_power_of_two() {
222                     return err!(HeapAllocNonPowerOfTwoAlignment(align));
223                 }
224                 let ptr = this.memory_mut()
225                     .allocate(
226                         Size::from_bytes(size),
227                         Align::from_bytes(align).unwrap(),
228                         MiriMemoryKind::Rust.into()
229                     );
230                 this.write_scalar(Scalar::Ptr(ptr), dest)?;
231             }
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)?;
235                 if size == 0 {
236                     return err!(HeapAllocZeroBytes);
237                 }
238                 if !align.is_power_of_two() {
239                     return err!(HeapAllocNonPowerOfTwoAlignment(align));
240                 }
241                 let ptr = this.memory_mut()
242                     .allocate(
243                         Size::from_bytes(size),
244                         Align::from_bytes(align).unwrap(),
245                         MiriMemoryKind::Rust.into()
246                     );
247                 // We just allocated this, the access cannot fail
248                 this.memory_mut()
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)?;
252             }
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)?;
257                 if old_size == 0 {
258                     return err!(HeapAllocZeroBytes);
259                 }
260                 if !align.is_power_of_two() {
261                     return err!(HeapAllocNonPowerOfTwoAlignment(align));
262                 }
263                 let ptr = this.force_ptr(ptr)?;
264                 this.memory_mut().deallocate(
265                     ptr,
266                     Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
267                     MiriMemoryKind::Rust.into(),
268                 )?;
269             }
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                     return err!(HeapAllocZeroBytes);
277                 }
278                 if !align.is_power_of_two() {
279                     return err!(HeapAllocNonPowerOfTwoAlignment(align));
280                 }
281                 let align = Align::from_bytes(align).unwrap();
282                 let new_ptr = this.memory_mut().reallocate(
283                     ptr,
284                     Some((Size::from_bytes(old_size), align)),
285                     Size::from_bytes(new_size),
286                     align,
287                     MiriMemoryKind::Rust.into(),
288                 )?;
289                 this.write_scalar(Scalar::Ptr(new_ptr), dest)?;
290             }
291
292             "syscall" => {
293                 let sys_getrandom = this.eval_path_scalar(&["libc", "SYS_getrandom"])?
294                     .expect("Failed to get libc::SYS_getrandom")
295                     .to_usize(this)?;
296
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)?;
303
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()?;
307
308                         this.gen_random(len as usize, ptr)?;
309                         this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;
310                     }
311                     id => {
312                         return err!(Unimplemented(
313                             format!("miri does not support syscall ID {}", id),
314                         ))
315                     }
316                 }
317             }
318
319             "dlsym" => {
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)?;
328                 } else {
329                     this.write_null(dest)?;
330                 }
331             }
332
333             "__rust_maybe_catch_panic" => {
334                 // fn __rust_maybe_catch_panic(
335                 //     f: fn(*mut u8),
336                 //     data: *mut u8,
337                 //     data_ptr: *mut usize,
338                 //     vtable_ptr: *mut usize,
339                 // ) -> u32
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);
346
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(
353                     f_instance,
354                     mir.span,
355                     mir,
356                     Some(ret_place),
357                     // Directly return to caller.
358                     StackPopCleanup::Goto(Some(ret)),
359                 )?;
360                 let mut args = this.frame().body.args_iter();
361
362                 let arg_local = args.next().ok_or_else(||
363                     InterpError::AbiViolation(
364                         "Argument to __rust_maybe_catch_panic does not take enough arguments."
365                             .to_owned(),
366                     ),
367                 )?;
368                 let arg_dest = this.eval_place(&mir::Place::Base(mir::PlaceBase::Local(arg_local)))?;
369                 this.write_scalar(data, arg_dest)?;
370
371                 assert!(args.next().is_none(), "__rust_maybe_catch_panic argument has more arguments than expected");
372
373                 // We ourselves will return `0`, eventually (because we will not return if we paniced).
374                 this.write_null(dest)?;
375
376                 // Don't fall through, we do *not* want to `goto_block`!
377                 return Ok(());
378             }
379
380             "memcmp" => {
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)?);
384
385                 let result = {
386                     let left_bytes = this.memory().read_bytes(left, n)?;
387                     let right_bytes = this.memory().read_bytes(right, n)?;
388
389                     use std::cmp::Ordering::*;
390                     match left_bytes.cmp(right_bytes) {
391                         Less => -1i32,
392                         Equal => 0,
393                         Greater => 1,
394                     }
395                 };
396
397                 this.write_scalar(
398                     Scalar::from_int(result, Size::from_bits(32)),
399                     dest,
400                 )?;
401             }
402
403             "memrchr" => {
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)
409                 {
410                     let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
411                     this.write_scalar(new_ptr, dest)?;
412                 } else {
413                     this.write_null(dest)?;
414                 }
415             }
416
417             "memchr" => {
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)?;
421                 let idx = this
422                     .memory()
423                     .read_bytes(ptr, Size::from_bytes(num))?
424                     .iter()
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)?;
429                 } else {
430                     this.write_null(dest)?;
431                 }
432             }
433
434             "getenv" => {
435                 let result = {
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),
441                     }
442                 };
443                 this.write_scalar(result, dest)?;
444             }
445
446             "unsetenv" => {
447                 let mut success = None;
448                 {
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));
454                         }
455                     }
456                 }
457                 if let Some(old) = success {
458                     if let Some(var) = old {
459                         this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
460                     }
461                     this.write_null(dest)?;
462                 } else {
463                     this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
464                 }
465             }
466
467             "setenv" => {
468                 let mut new = None;
469                 {
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()));
477                         }
478                     }
479                 }
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(),
486                     );
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),
492                         tcx,
493                     ).unwrap();
494                     alloc.write_bytes(tcx, trailing_zero_ptr, &[0]).unwrap();
495
496                     if let Some(var) = this.machine.env_vars.insert(
497                         name.to_owned(),
498                         value_copy,
499                     )
500                     {
501                         this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
502                     }
503                     this.write_null(dest)?;
504                 } else {
505                     this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
506                 }
507             }
508
509             "write" => {
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 {
515                     // stdout/stderr
516                     use std::io::{self, Write};
517
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();
527                         res
528                     } else {
529                         // No need to flush, stderr is not buffered.
530                         io::stderr().write(buf_cont)
531                     };
532                     match res {
533                         Ok(n) => n as i64,
534                         Err(_) => -1,
535                     }
536                 } else {
537                     eprintln!("Miri: Ignored output to FD {}", fd);
538                     // Pretend it all went well.
539                     n as i64
540                 };
541                 // Now, `result` is the value we return back to the program.
542                 this.write_scalar(
543                     Scalar::from_int(result, dest.layout.size),
544                     dest,
545                 )?;
546             }
547
548             "strlen" => {
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)?;
552             }
553
554             // math functions
555
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 {
560                     "cbrtf" => f.cbrt(),
561                     "coshf" => f.cosh(),
562                     "sinhf" => f.sinh(),
563                     "tanf" => f.tan(),
564                     _ => bug!(),
565                 };
566                 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
567             }
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),
576                     _ => bug!(),
577                 };
578                 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
579             }
580
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 {
585                     "cbrt" => f.cbrt(),
586                     "cosh" => f.cosh(),
587                     "sinh" => f.sinh(),
588                     "tan" => f.tan(),
589                     _ => bug!(),
590                 };
591                 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
592             }
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),
601                     _ => bug!(),
602                 };
603                 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
604             }
605
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)?;
609             }
610
611             "sysconf" => {
612                 let name = this.read_scalar(args[0])?.to_i32()?;
613
614                 trace!("sysconf() called with name {}", name);
615                 // TODO: Cache the sysconf integers via Miri's global cache.
616                 let paths = &[
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)),
620                 ];
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()?;
625                         if val == name {
626                             result = Some(path_value);
627                             break;
628                         }
629
630                     }
631                 }
632                 if let Some(result) = result {
633                     this.write_scalar(result, dest)?;
634                 } else {
635                     return err!(Unimplemented(
636                         format!("Unimplemented sysconf name: {}", name),
637                     ));
638                 }
639             }
640
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)?;
644             }
645
646             "isatty" => {
647                 this.write_null(dest)?;
648             }
649
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()?;
653
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()?),
657                     None => None,
658                 };
659
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
663                     .builtin_deref(true)
664                     .ok_or_else(|| InterpError::AbiViolation("wrong signature used for `pthread_key_create`: first argument must be a raw pointer.".to_owned()))?
665                     .ty;
666                 let key_layout = this.layout_of(key_type)?;
667
668                 // Create key and write it into the memory where `key_ptr` wants it.
669                 let key = this.machine.tls.create_tls_key(dtor) as u128;
670                 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128) {
671                     return err!(OutOfTls);
672                 }
673
674                 let key_ptr = this.memory().check_ptr_access(key_ptr, key_layout.size, key_layout.align.abi)?
675                     .expect("cannot be a ZST");
676                 this.memory_mut().get_mut(key_ptr.alloc_id)?.write_scalar(
677                     tcx,
678                     key_ptr,
679                     Scalar::from_uint(key, key_layout.size).into(),
680                     key_layout.size,
681                 )?;
682
683                 // Return success (`0`).
684                 this.write_null(dest)?;
685             }
686             "pthread_key_delete" => {
687                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
688                 this.machine.tls.delete_tls_key(key)?;
689                 // Return success (0)
690                 this.write_null(dest)?;
691             }
692             "pthread_getspecific" => {
693                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
694                 let ptr = this.machine.tls.load_tls(key, tcx)?;
695                 this.write_scalar(ptr, dest)?;
696             }
697             "pthread_setspecific" => {
698                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
699                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
700                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
701
702                 // Return success (`0`).
703                 this.write_null(dest)?;
704             }
705
706             // Stack size/address stuff.
707             "pthread_attr_init" | "pthread_attr_destroy" | "pthread_self" |
708             "pthread_attr_setstacksize" => {
709                 this.write_null(dest)?;
710             }
711             "pthread_attr_getstack" => {
712                 let addr_place = this.deref_operand(args[1])?;
713                 let size_place = this.deref_operand(args[2])?;
714
715                 this.write_scalar(
716                     Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
717                     addr_place.into(),
718                 )?;
719                 this.write_scalar(
720                     Scalar::from_uint(STACK_SIZE, size_place.layout.size),
721                     size_place.into(),
722                 )?;
723
724                 // Return success (`0`).
725                 this.write_null(dest)?;
726             }
727
728             // We don't support threading.
729             "pthread_create" => {
730                 return err!(Unimplemented(format!("Miri does not support threading")));
731             }
732
733             // Stub out calls for condvar, mutex and rwlock, to just return `0`.
734             "pthread_mutexattr_init" | "pthread_mutexattr_settype" | "pthread_mutex_init" |
735             "pthread_mutexattr_destroy" | "pthread_mutex_lock" | "pthread_mutex_unlock" |
736             "pthread_mutex_destroy" | "pthread_rwlock_rdlock" | "pthread_rwlock_unlock" |
737             "pthread_rwlock_wrlock" | "pthread_rwlock_destroy" | "pthread_condattr_init" |
738             "pthread_condattr_setclock" | "pthread_cond_init" | "pthread_condattr_destroy" |
739             "pthread_cond_destroy" => {
740                 this.write_null(dest)?;
741             }
742
743             // We don't support fork so we don't have to do anything for atfork.
744             "pthread_atfork" => {
745                 this.write_null(dest)?;
746             }
747
748             "mmap" => {
749                 // 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.
750                 let addr = this.read_scalar(args[0])?.not_undef()?;
751                 this.write_scalar(addr, dest)?;
752             }
753             "mprotect" => {
754                 this.write_null(dest)?;
755             }
756
757             // macOS API stubs.
758             "pthread_attr_get_np" | "pthread_getattr_np" => {
759                 this.write_null(dest)?;
760             }
761             "pthread_get_stackaddr_np" => {
762                 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
763                 this.write_scalar(stack_addr, dest)?;
764             }
765             "pthread_get_stacksize_np" => {
766                 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
767                 this.write_scalar(stack_size, dest)?;
768             }
769             "_tlv_atexit" => {
770                 // FIXME: register the destructor.
771             },
772             "_NSGetArgc" => {
773                 this.write_scalar(Scalar::Ptr(this.machine.argc.unwrap()), dest)?;
774             },
775             "_NSGetArgv" => {
776                 this.write_scalar(Scalar::Ptr(this.machine.argv.unwrap()), dest)?;
777             },
778             "SecRandomCopyBytes" => {
779                 let len = this.read_scalar(args[1])?.to_usize(this)?;
780                 let ptr = this.read_scalar(args[2])?.not_undef()?;
781                 this.gen_random(len as usize, ptr)?;
782                 this.write_null(dest)?;
783             }
784
785             // Windows API stubs.
786             // HANDLE = isize
787             // DWORD = ULONG = u32
788             // BOOL = i32
789             "GetProcessHeap" => {
790                 // Just fake a HANDLE
791                 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
792             }
793             "HeapAlloc" => {
794                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
795                 let flags = this.read_scalar(args[1])?.to_u32()?;
796                 let size = this.read_scalar(args[2])?.to_usize(this)?;
797                 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
798                 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
799                 this.write_scalar(res, dest)?;
800             }
801             "HeapFree" => {
802                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
803                 let _flags = this.read_scalar(args[1])?.to_u32()?;
804                 let ptr = this.read_scalar(args[2])?.not_undef()?;
805                 this.free(ptr, MiriMemoryKind::WinHeap)?;
806                 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
807             }
808             "HeapReAlloc" => {
809                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
810                 let _flags = this.read_scalar(args[1])?.to_u32()?;
811                 let ptr = this.read_scalar(args[2])?.not_undef()?;
812                 let size = this.read_scalar(args[3])?.to_usize(this)?;
813                 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
814                 this.write_scalar(res, dest)?;
815             }
816
817             "SetLastError" => {
818                 let err = this.read_scalar(args[0])?.to_u32()?;
819                 this.machine.last_error = err;
820             }
821             "GetLastError" => {
822                 this.write_scalar(Scalar::from_u32(this.machine.last_error), dest)?;
823             }
824
825             "AddVectoredExceptionHandler" => {
826                 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
827                 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
828             },
829             "InitializeCriticalSection" |
830             "EnterCriticalSection" |
831             "LeaveCriticalSection" |
832             "DeleteCriticalSection" => {
833                 // Nothing to do, not even a return value.
834             },
835             "GetModuleHandleW" |
836             "GetProcAddress" |
837             "TryEnterCriticalSection" |
838             "GetConsoleScreenBufferInfo" |
839             "SetConsoleTextAttribute" => {
840                 // Pretend these do not exist / nothing happened, by returning zero.
841                 this.write_null(dest)?;
842             },
843             "GetSystemInfo" => {
844                 let system_info = this.deref_operand(args[0])?;
845                 let system_info_ptr = this.check_mplace_access(system_info, None)?
846                     .expect("cannot be a ZST");
847                 // Initialize with `0`.
848                 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
849                     .write_repeat(tcx, system_info_ptr, 0, system_info.layout.size)?;
850                 // Set number of processors.
851                 let dword_size = Size::from_bytes(4);
852                 let offset = 2*dword_size + 3*tcx.pointer_size();
853                 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
854                     .write_scalar(
855                         tcx,
856                         system_info_ptr.offset(offset, tcx)?,
857                         Scalar::from_int(NUM_CPUS, dword_size).into(),
858                         dword_size,
859                     )?;
860             }
861
862             "TlsAlloc" => {
863                 // This just creates a key; Windows does not natively support TLS destructors.
864
865                 // Create key and return it.
866                 let key = this.machine.tls.create_tls_key(None) as u128;
867
868                 // Figure out how large a TLS key actually is. This is `c::DWORD`.
869                 if dest.layout.size.bits() < 128
870                         && key >= (1u128 << dest.layout.size.bits() as u128) {
871                     return err!(OutOfTls);
872                 }
873                 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
874             }
875             "TlsGetValue" => {
876                 let key = this.read_scalar(args[0])?.to_u32()? as u128;
877                 let ptr = this.machine.tls.load_tls(key, tcx)?;
878                 this.write_scalar(ptr, dest)?;
879             }
880             "TlsSetValue" => {
881                 let key = this.read_scalar(args[0])?.to_u32()? as u128;
882                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
883                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
884
885                 // Return success (`1`).
886                 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
887             }
888             "GetStdHandle" => {
889                 let which = this.read_scalar(args[0])?.to_i32()?;
890                 // We just make this the identity function, so we know later in `WriteFile`
891                 // which one it is.
892                 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
893             }
894             "WriteFile" => {
895                 let handle = this.read_scalar(args[0])?.to_isize(this)?;
896                 let buf = this.read_scalar(args[1])?.not_undef()?;
897                 let n = this.read_scalar(args[2])?.to_u32()?;
898                 let written_place = this.deref_operand(args[3])?;
899                 // Spec says to always write `0` first.
900                 this.write_null(written_place.into())?;
901                 let written = if handle == -11 || handle == -12 {
902                     // stdout/stderr
903                     use std::io::{self, Write};
904
905                     let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(u64::from(n)))?;
906                     let res = if handle == -11 {
907                         io::stdout().write(buf_cont)
908                     } else {
909                         io::stderr().write(buf_cont)
910                     };
911                     res.ok().map(|n| n as u32)
912                 } else {
913                     eprintln!("Miri: Ignored output to handle {}", handle);
914                     // Pretend it all went well.
915                     Some(n)
916                 };
917                 // If there was no error, write back how much was written.
918                 if let Some(n) = written {
919                     this.write_scalar(Scalar::from_u32(n), written_place.into())?;
920                 }
921                 // Return whether this was a success.
922                 this.write_scalar(
923                     Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
924                     dest,
925                 )?;
926             }
927             "GetConsoleMode" => {
928                 // Everything is a pipe.
929                 this.write_null(dest)?;
930             }
931             "GetEnvironmentVariableW" => {
932                 // This is not the env var you are looking for.
933                 this.machine.last_error = 203; // ERROR_ENVVAR_NOT_FOUND
934                 this.write_null(dest)?;
935             }
936             "GetCommandLineW" => {
937                 this.write_scalar(Scalar::Ptr(this.machine.cmd_line.unwrap()), dest)?;
938             }
939             // The actual name of 'RtlGenRandom'
940             "SystemFunction036" => {
941                 let ptr = this.read_scalar(args[0])?.not_undef()?;
942                 let len = this.read_scalar(args[1])?.to_u32()?;
943                 this.gen_random(len as usize, ptr)?;
944                 this.write_scalar(Scalar::from_bool(true), dest)?;
945             }
946
947             // We can't execute anything else.
948             _ => {
949                 return err!(Unimplemented(
950                     format!("can't call foreign function: {}", link_name),
951                 ));
952             }
953         }
954
955         this.goto_block(Some(ret))?;
956         this.dump_place(*dest);
957         Ok(())
958     }
959
960     /// Evaluates the scalar at the specified path. Returns Some(val)
961     /// if the path could be resolved, and None otherwise
962     fn eval_path_scalar(&mut self, path: &[&str]) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
963         let this = self.eval_context_mut();
964         if let Ok(instance) = this.resolve_path(path) {
965             let cid = GlobalId {
966                 instance,
967                 promoted: None,
968             };
969             let const_val = this.const_eval_raw(cid)?;
970             let const_val = this.read_scalar(const_val.into())?;
971             return Ok(Some(const_val));
972         }
973         return Ok(None);
974     }
975 }