]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items.rs
Auto merge of #878 - RalfJung:rustup, 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                 throw_unsup!(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(InterpError::Exit(code).into());
150             }
151             _ => if dest.is_none() {
152                 throw_unsup!(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(|| err_panic!(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                     throw_unsup!(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                     throw_unsup!(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                     throw_unsup!(HeapAllocZeroBytes);
220                 }
221                 if !align.is_power_of_two() {
222                     throw_unsup!(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                     throw_unsup!(HeapAllocZeroBytes);
237                 }
238                 if !align.is_power_of_two() {
239                     throw_unsup!(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                     throw_unsup!(HeapAllocZeroBytes);
259                 }
260                 if !align.is_power_of_two() {
261                     throw_unsup!(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                     throw_unsup!(HeapAllocZeroBytes);
277                 }
278                 if !align.is_power_of_two() {
279                     throw_unsup!(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                         throw_unsup!(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                     err_unsup!(AbiViolation(
364                         "Argument to __rust_maybe_catch_panic does not take enough arguments."
365                             .to_owned(),
366                     )),
367                 )?;
368                 let arg_dest = this.local_place(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                     throw_unsup!(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(|| err_unsup!(
665                         AbiViolation("wrong signature used for `pthread_key_create`: first argument must be a raw pointer.".to_owned())
666                     ))?
667                     .ty;
668                 let key_layout = this.layout_of(key_type)?;
669
670                 // Create key and write it into the memory where `key_ptr` wants it.
671                 let key = this.machine.tls.create_tls_key(dtor) as u128;
672                 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128) {
673                     throw_unsup!(OutOfTls);
674                 }
675
676                 let key_ptr = this.memory().check_ptr_access(key_ptr, key_layout.size, key_layout.align.abi)?
677                     .expect("cannot be a ZST");
678                 this.memory_mut().get_mut(key_ptr.alloc_id)?.write_scalar(
679                     tcx,
680                     key_ptr,
681                     Scalar::from_uint(key, key_layout.size).into(),
682                     key_layout.size,
683                 )?;
684
685                 // Return success (`0`).
686                 this.write_null(dest)?;
687             }
688             "pthread_key_delete" => {
689                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
690                 this.machine.tls.delete_tls_key(key)?;
691                 // Return success (0)
692                 this.write_null(dest)?;
693             }
694             "pthread_getspecific" => {
695                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
696                 let ptr = this.machine.tls.load_tls(key, tcx)?;
697                 this.write_scalar(ptr, dest)?;
698             }
699             "pthread_setspecific" => {
700                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
701                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
702                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
703
704                 // Return success (`0`).
705                 this.write_null(dest)?;
706             }
707
708             // Stack size/address stuff.
709             "pthread_attr_init" | "pthread_attr_destroy" | "pthread_self" |
710             "pthread_attr_setstacksize" => {
711                 this.write_null(dest)?;
712             }
713             "pthread_attr_getstack" => {
714                 let addr_place = this.deref_operand(args[1])?;
715                 let size_place = this.deref_operand(args[2])?;
716
717                 this.write_scalar(
718                     Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
719                     addr_place.into(),
720                 )?;
721                 this.write_scalar(
722                     Scalar::from_uint(STACK_SIZE, size_place.layout.size),
723                     size_place.into(),
724                 )?;
725
726                 // Return success (`0`).
727                 this.write_null(dest)?;
728             }
729
730             // We don't support threading. (Also for Windows.)
731             "pthread_create" | "CreateThread" => {
732                 throw_unsup!(Unimplemented(format!("Miri does not support threading")));
733             }
734
735             // Stub out calls for condvar, mutex and rwlock, to just return `0`.
736             "pthread_mutexattr_init" | "pthread_mutexattr_settype" | "pthread_mutex_init" |
737             "pthread_mutexattr_destroy" | "pthread_mutex_lock" | "pthread_mutex_unlock" |
738             "pthread_mutex_destroy" | "pthread_rwlock_rdlock" | "pthread_rwlock_unlock" |
739             "pthread_rwlock_wrlock" | "pthread_rwlock_destroy" | "pthread_condattr_init" |
740             "pthread_condattr_setclock" | "pthread_cond_init" | "pthread_condattr_destroy" |
741             "pthread_cond_destroy" => {
742                 this.write_null(dest)?;
743             }
744
745             // We don't support fork so we don't have to do anything for atfork.
746             "pthread_atfork" => {
747                 this.write_null(dest)?;
748             }
749
750             "mmap" => {
751                 // This is a horrible hack, but since the guard page mechanism calls mmap and expects a particular return value, we just give it that value.
752                 let addr = this.read_scalar(args[0])?.not_undef()?;
753                 this.write_scalar(addr, dest)?;
754             }
755             "mprotect" => {
756                 this.write_null(dest)?;
757             }
758
759             // macOS API stubs.
760             "pthread_attr_get_np" | "pthread_getattr_np" => {
761                 this.write_null(dest)?;
762             }
763             "pthread_get_stackaddr_np" => {
764                 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
765                 this.write_scalar(stack_addr, dest)?;
766             }
767             "pthread_get_stacksize_np" => {
768                 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
769                 this.write_scalar(stack_size, dest)?;
770             }
771             "_tlv_atexit" => {
772                 // FIXME: register the destructor.
773             },
774             "_NSGetArgc" => {
775                 this.write_scalar(Scalar::Ptr(this.machine.argc.unwrap()), dest)?;
776             },
777             "_NSGetArgv" => {
778                 this.write_scalar(Scalar::Ptr(this.machine.argv.unwrap()), dest)?;
779             },
780             "SecRandomCopyBytes" => {
781                 let len = this.read_scalar(args[1])?.to_usize(this)?;
782                 let ptr = this.read_scalar(args[2])?.not_undef()?;
783                 this.gen_random(len as usize, ptr)?;
784                 this.write_null(dest)?;
785             }
786
787             // Windows API stubs.
788             // HANDLE = isize
789             // DWORD = ULONG = u32
790             // BOOL = i32
791             "GetProcessHeap" => {
792                 // Just fake a HANDLE
793                 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
794             }
795             "HeapAlloc" => {
796                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
797                 let flags = this.read_scalar(args[1])?.to_u32()?;
798                 let size = this.read_scalar(args[2])?.to_usize(this)?;
799                 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
800                 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
801                 this.write_scalar(res, dest)?;
802             }
803             "HeapFree" => {
804                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
805                 let _flags = this.read_scalar(args[1])?.to_u32()?;
806                 let ptr = this.read_scalar(args[2])?.not_undef()?;
807                 this.free(ptr, MiriMemoryKind::WinHeap)?;
808                 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
809             }
810             "HeapReAlloc" => {
811                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
812                 let _flags = this.read_scalar(args[1])?.to_u32()?;
813                 let ptr = this.read_scalar(args[2])?.not_undef()?;
814                 let size = this.read_scalar(args[3])?.to_usize(this)?;
815                 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
816                 this.write_scalar(res, dest)?;
817             }
818
819             "SetLastError" => {
820                 let err = this.read_scalar(args[0])?.to_u32()?;
821                 this.machine.last_error = err;
822             }
823             "GetLastError" => {
824                 this.write_scalar(Scalar::from_u32(this.machine.last_error), dest)?;
825             }
826
827             "AddVectoredExceptionHandler" => {
828                 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
829                 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
830             },
831             "InitializeCriticalSection" |
832             "EnterCriticalSection" |
833             "LeaveCriticalSection" |
834             "DeleteCriticalSection" => {
835                 // Nothing to do, not even a return value.
836             },
837             "GetModuleHandleW" |
838             "GetProcAddress" |
839             "TryEnterCriticalSection" |
840             "GetConsoleScreenBufferInfo" |
841             "SetConsoleTextAttribute" => {
842                 // Pretend these do not exist / nothing happened, by returning zero.
843                 this.write_null(dest)?;
844             },
845             "GetSystemInfo" => {
846                 let system_info = this.deref_operand(args[0])?;
847                 let system_info_ptr = this.check_mplace_access(system_info, None)?
848                     .expect("cannot be a ZST");
849                 // Initialize with `0`.
850                 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
851                     .write_repeat(tcx, system_info_ptr, 0, system_info.layout.size)?;
852                 // Set number of processors.
853                 let dword_size = Size::from_bytes(4);
854                 let offset = 2*dword_size + 3*tcx.pointer_size();
855                 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
856                     .write_scalar(
857                         tcx,
858                         system_info_ptr.offset(offset, tcx)?,
859                         Scalar::from_int(NUM_CPUS, dword_size).into(),
860                         dword_size,
861                     )?;
862             }
863
864             "TlsAlloc" => {
865                 // This just creates a key; Windows does not natively support TLS destructors.
866
867                 // Create key and return it.
868                 let key = this.machine.tls.create_tls_key(None) as u128;
869
870                 // Figure out how large a TLS key actually is. This is `c::DWORD`.
871                 if dest.layout.size.bits() < 128
872                         && key >= (1u128 << dest.layout.size.bits() as u128) {
873                     throw_unsup!(OutOfTls);
874                 }
875                 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
876             }
877             "TlsGetValue" => {
878                 let key = this.read_scalar(args[0])?.to_u32()? as u128;
879                 let ptr = this.machine.tls.load_tls(key, tcx)?;
880                 this.write_scalar(ptr, dest)?;
881             }
882             "TlsSetValue" => {
883                 let key = this.read_scalar(args[0])?.to_u32()? as u128;
884                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
885                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
886
887                 // Return success (`1`).
888                 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
889             }
890             "GetStdHandle" => {
891                 let which = this.read_scalar(args[0])?.to_i32()?;
892                 // We just make this the identity function, so we know later in `WriteFile`
893                 // which one it is.
894                 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
895             }
896             "WriteFile" => {
897                 let handle = this.read_scalar(args[0])?.to_isize(this)?;
898                 let buf = this.read_scalar(args[1])?.not_undef()?;
899                 let n = this.read_scalar(args[2])?.to_u32()?;
900                 let written_place = this.deref_operand(args[3])?;
901                 // Spec says to always write `0` first.
902                 this.write_null(written_place.into())?;
903                 let written = if handle == -11 || handle == -12 {
904                     // stdout/stderr
905                     use std::io::{self, Write};
906
907                     let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(u64::from(n)))?;
908                     let res = if handle == -11 {
909                         io::stdout().write(buf_cont)
910                     } else {
911                         io::stderr().write(buf_cont)
912                     };
913                     res.ok().map(|n| n as u32)
914                 } else {
915                     eprintln!("Miri: Ignored output to handle {}", handle);
916                     // Pretend it all went well.
917                     Some(n)
918                 };
919                 // If there was no error, write back how much was written.
920                 if let Some(n) = written {
921                     this.write_scalar(Scalar::from_u32(n), written_place.into())?;
922                 }
923                 // Return whether this was a success.
924                 this.write_scalar(
925                     Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
926                     dest,
927                 )?;
928             }
929             "GetConsoleMode" => {
930                 // Everything is a pipe.
931                 this.write_null(dest)?;
932             }
933             "GetEnvironmentVariableW" => {
934                 // This is not the env var you are looking for.
935                 this.machine.last_error = 203; // ERROR_ENVVAR_NOT_FOUND
936                 this.write_null(dest)?;
937             }
938             "GetCommandLineW" => {
939                 this.write_scalar(Scalar::Ptr(this.machine.cmd_line.unwrap()), dest)?;
940             }
941             // The actual name of 'RtlGenRandom'
942             "SystemFunction036" => {
943                 let ptr = this.read_scalar(args[0])?.not_undef()?;
944                 let len = this.read_scalar(args[1])?.to_u32()?;
945                 this.gen_random(len as usize, ptr)?;
946                 this.write_scalar(Scalar::from_bool(true), dest)?;
947             }
948
949             // We can't execute anything else.
950             _ => {
951                 throw_unsup!(Unimplemented(
952                     format!("can't call foreign function: {}", link_name),
953                 ));
954             }
955         }
956
957         this.goto_block(Some(ret))?;
958         this.dump_place(*dest);
959         Ok(())
960     }
961
962     /// Evaluates the scalar at the specified path. Returns Some(val)
963     /// if the path could be resolved, and None otherwise
964     fn eval_path_scalar(&mut self, path: &[&str]) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
965         let this = self.eval_context_mut();
966         if let Ok(instance) = this.resolve_path(path) {
967             let cid = GlobalId {
968                 instance,
969                 promoted: None,
970             };
971             let const_val = this.const_eval_raw(cid)?;
972             let const_val = this.read_scalar(const_val.into())?;
973             return Ok(Some(const_val));
974         }
975         return Ok(None);
976     }
977 }