]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items.rs
Auto merge of #852 - lzutao: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         use rustc::mir::interpret::InterpError::Panic;
132         let this = self.eval_context_mut();
133         let attrs = this.tcx.get_attrs(def_id);
134         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
135             Some(name) => name.as_str(),
136             None => this.tcx.item_name(def_id).as_str(),
137         };
138         // Strip linker suffixes (seen on 32-bit macOS).
139         let link_name = link_name.get().trim_end_matches("$UNIX2003");
140         let tcx = &{this.tcx.tcx};
141
142         // First: functions that diverge.
143         match link_name {
144             "__rust_start_panic" | "panic_impl" => {
145                 return err!(MachineError("the evaluated program panicked".to_string()));
146             }
147             "exit" | "ExitProcess" => {
148                 // it's really u32 for ExitProcess, but we have to put it into the `Exit` error variant anyway
149                 let code = this.read_scalar(args[0])?.to_i32()?;
150                 return err!(Exit(code));
151             }
152             _ => if dest.is_none() {
153                 return err!(Unimplemented(
154                     format!("can't call diverging foreign function: {}", link_name),
155                 ));
156             }
157         }
158
159         // Next: functions that assume a ret and dest.
160         let dest = dest.expect("we already checked for a dest");
161         let ret = ret.expect("dest is `Some` but ret is `None`");
162         match link_name {
163             "malloc" => {
164                 let size = this.read_scalar(args[0])?.to_usize(this)?;
165                 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
166                 this.write_scalar(res, dest)?;
167             }
168             "calloc" => {
169                 let items = this.read_scalar(args[0])?.to_usize(this)?;
170                 let len = this.read_scalar(args[1])?.to_usize(this)?;
171                 let size = items.checked_mul(len).ok_or_else(|| Panic(PanicMessage::Overflow(mir::BinOp::Mul)))?;
172                 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
173                 this.write_scalar(res, dest)?;
174             }
175             "posix_memalign" => {
176                 let ret = this.deref_operand(args[0])?;
177                 let align = this.read_scalar(args[1])?.to_usize(this)?;
178                 let size = this.read_scalar(args[2])?.to_usize(this)?;
179                 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
180                 if !align.is_power_of_two() {
181                     return err!(HeapAllocNonPowerOfTwoAlignment(align));
182                 }
183                 /*
184                 FIXME: This check is disabled because rustc violates it.
185                 See <https://github.com/rust-lang/rust/issues/62251>.
186                 if align < this.pointer_size().bytes() {
187                     return err!(MachineError(format!(
188                         "posix_memalign: alignment must be at least the size of a pointer, but is {}",
189                         align,
190                     )));
191                 }
192                 */
193                 if size == 0 {
194                     this.write_null(ret.into())?;
195                 } else {
196                     let ptr = this.memory_mut().allocate(
197                         Size::from_bytes(size),
198                         Align::from_bytes(align).unwrap(),
199                         MiriMemoryKind::C.into()
200                     );
201                     this.write_scalar(Scalar::Ptr(ptr), ret.into())?;
202                 }
203                 this.write_null(dest)?;
204             }
205             "free" => {
206                 let ptr = this.read_scalar(args[0])?.not_undef()?;
207                 this.free(ptr, MiriMemoryKind::C)?;
208             }
209             "realloc" => {
210                 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
211                 let new_size = this.read_scalar(args[1])?.to_usize(this)?;
212                 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
213                 this.write_scalar(res, dest)?;
214             }
215
216             "__rust_alloc" => {
217                 let size = this.read_scalar(args[0])?.to_usize(this)?;
218                 let align = this.read_scalar(args[1])?.to_usize(this)?;
219                 if size == 0 {
220                     return err!(HeapAllocZeroBytes);
221                 }
222                 if !align.is_power_of_two() {
223                     return err!(HeapAllocNonPowerOfTwoAlignment(align));
224                 }
225                 let ptr = this.memory_mut()
226                     .allocate(
227                         Size::from_bytes(size),
228                         Align::from_bytes(align).unwrap(),
229                         MiriMemoryKind::Rust.into()
230                     );
231                 this.write_scalar(Scalar::Ptr(ptr), dest)?;
232             }
233             "__rust_alloc_zeroed" => {
234                 let size = this.read_scalar(args[0])?.to_usize(this)?;
235                 let align = this.read_scalar(args[1])?.to_usize(this)?;
236                 if size == 0 {
237                     return err!(HeapAllocZeroBytes);
238                 }
239                 if !align.is_power_of_two() {
240                     return err!(HeapAllocNonPowerOfTwoAlignment(align));
241                 }
242                 let ptr = this.memory_mut()
243                     .allocate(
244                         Size::from_bytes(size),
245                         Align::from_bytes(align).unwrap(),
246                         MiriMemoryKind::Rust.into()
247                     );
248                 // We just allocated this, the access cannot fail
249                 this.memory_mut()
250                     .get_mut(ptr.alloc_id).unwrap()
251                     .write_repeat(tcx, ptr, 0, Size::from_bytes(size)).unwrap();
252                 this.write_scalar(Scalar::Ptr(ptr), dest)?;
253             }
254             "__rust_dealloc" => {
255                 let ptr = this.read_scalar(args[0])?.not_undef()?;
256                 let old_size = this.read_scalar(args[1])?.to_usize(this)?;
257                 let align = this.read_scalar(args[2])?.to_usize(this)?;
258                 if old_size == 0 {
259                     return err!(HeapAllocZeroBytes);
260                 }
261                 if !align.is_power_of_two() {
262                     return err!(HeapAllocNonPowerOfTwoAlignment(align));
263                 }
264                 let ptr = this.force_ptr(ptr)?;
265                 this.memory_mut().deallocate(
266                     ptr,
267                     Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
268                     MiriMemoryKind::Rust.into(),
269                 )?;
270             }
271             "__rust_realloc" => {
272                 let ptr = this.read_scalar(args[0])?.to_ptr()?;
273                 let old_size = this.read_scalar(args[1])?.to_usize(this)?;
274                 let align = this.read_scalar(args[2])?.to_usize(this)?;
275                 let new_size = this.read_scalar(args[3])?.to_usize(this)?;
276                 if old_size == 0 || new_size == 0 {
277                     return err!(HeapAllocZeroBytes);
278                 }
279                 if !align.is_power_of_two() {
280                     return err!(HeapAllocNonPowerOfTwoAlignment(align));
281                 }
282                 let align = Align::from_bytes(align).unwrap();
283                 let new_ptr = this.memory_mut().reallocate(
284                     ptr,
285                     Some((Size::from_bytes(old_size), align)),
286                     Size::from_bytes(new_size),
287                     align,
288                     MiriMemoryKind::Rust.into(),
289                 )?;
290                 this.write_scalar(Scalar::Ptr(new_ptr), dest)?;
291             }
292
293             "syscall" => {
294                 let sys_getrandom = this.eval_path_scalar(&["libc", "SYS_getrandom"])?
295                     .expect("Failed to get libc::SYS_getrandom")
296                     .to_usize(this)?;
297
298                 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
299                 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
300                 match this.read_scalar(args[0])?.to_usize(this)? {
301                     id if id == sys_getrandom => {
302                         let ptr = this.read_scalar(args[1])?.not_undef()?;
303                         let len = this.read_scalar(args[2])?.to_usize(this)?;
304
305                         // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
306                         // neither of which have any effect on our current PRNG
307                         let _flags = this.read_scalar(args[3])?.to_i32()?;
308
309                         this.gen_random(len as usize, ptr)?;
310                         this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;
311                     }
312                     id => {
313                         return err!(Unimplemented(
314                             format!("miri does not support syscall ID {}", id),
315                         ))
316                     }
317                 }
318             }
319
320             "dlsym" => {
321                 let _handle = this.read_scalar(args[0])?;
322                 let symbol = this.read_scalar(args[1])?.not_undef()?;
323                 let symbol_name = this.memory().read_c_str(symbol)?;
324                 let err = format!("bad c unicode symbol: {:?}", symbol_name);
325                 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
326                 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
327                     let ptr = this.memory_mut().create_fn_alloc(FnVal::Other(dlsym));
328                     this.write_scalar(Scalar::from(ptr), dest)?;
329                 } else {
330                     this.write_null(dest)?;
331                 }
332             }
333
334             "__rust_maybe_catch_panic" => {
335                 // fn __rust_maybe_catch_panic(
336                 //     f: fn(*mut u8),
337                 //     data: *mut u8,
338                 //     data_ptr: *mut usize,
339                 //     vtable_ptr: *mut usize,
340                 // ) -> u32
341                 // We abort on panic, so not much is going on here, but we still have to call the closure.
342                 let f = this.read_scalar(args[0])?.not_undef()?;
343                 let data = this.read_scalar(args[1])?.not_undef()?;
344                 let f_instance = this.memory().get_fn(f)?.as_instance()?;
345                 this.write_null(dest)?;
346                 trace!("__rust_maybe_catch_panic: {:?}", f_instance);
347
348                 // Now we make a function call.
349                 // TODO: consider making this reusable? `InterpCx::step` does something similar
350                 // for the TLS destructors, and of course `eval_main`.
351                 let mir = this.load_mir(f_instance.def)?;
352                 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
353                 this.push_stack_frame(
354                     f_instance,
355                     mir.span,
356                     mir,
357                     Some(ret_place),
358                     // Directly return to caller.
359                     StackPopCleanup::Goto(Some(ret)),
360                 )?;
361                 let mut args = this.frame().body.args_iter();
362
363                 let arg_local = args.next().ok_or_else(||
364                     InterpError::AbiViolation(
365                         "Argument to __rust_maybe_catch_panic does not take enough arguments."
366                             .to_owned(),
367                     ),
368                 )?;
369                 let arg_dest = this.local_place(arg_local)?;
370                 this.write_scalar(data, arg_dest)?;
371
372                 assert!(args.next().is_none(), "__rust_maybe_catch_panic argument has more arguments than expected");
373
374                 // We ourselves will return `0`, eventually (because we will not return if we paniced).
375                 this.write_null(dest)?;
376
377                 // Don't fall through, we do *not* want to `goto_block`!
378                 return Ok(());
379             }
380
381             "memcmp" => {
382                 let left = this.read_scalar(args[0])?.not_undef()?;
383                 let right = this.read_scalar(args[1])?.not_undef()?;
384                 let n = Size::from_bytes(this.read_scalar(args[2])?.to_usize(this)?);
385
386                 let result = {
387                     let left_bytes = this.memory().read_bytes(left, n)?;
388                     let right_bytes = this.memory().read_bytes(right, n)?;
389
390                     use std::cmp::Ordering::*;
391                     match left_bytes.cmp(right_bytes) {
392                         Less => -1i32,
393                         Equal => 0,
394                         Greater => 1,
395                     }
396                 };
397
398                 this.write_scalar(
399                     Scalar::from_int(result, Size::from_bits(32)),
400                     dest,
401                 )?;
402             }
403
404             "memrchr" => {
405                 let ptr = this.read_scalar(args[0])?.not_undef()?;
406                 let val = this.read_scalar(args[1])?.to_i32()? as u8;
407                 let num = this.read_scalar(args[2])?.to_usize(this)?;
408                 if let Some(idx) = this.memory().read_bytes(ptr, Size::from_bytes(num))?
409                     .iter().rev().position(|&c| c == val)
410                 {
411                     let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
412                     this.write_scalar(new_ptr, dest)?;
413                 } else {
414                     this.write_null(dest)?;
415                 }
416             }
417
418             "memchr" => {
419                 let ptr = this.read_scalar(args[0])?.not_undef()?;
420                 let val = this.read_scalar(args[1])?.to_i32()? as u8;
421                 let num = this.read_scalar(args[2])?.to_usize(this)?;
422                 let idx = this
423                     .memory()
424                     .read_bytes(ptr, Size::from_bytes(num))?
425                     .iter()
426                     .position(|&c| c == val);
427                 if let Some(idx) = idx {
428                     let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
429                     this.write_scalar(new_ptr, dest)?;
430                 } else {
431                     this.write_null(dest)?;
432                 }
433             }
434
435             "getenv" => {
436                 let result = {
437                     let name_ptr = this.read_scalar(args[0])?.not_undef()?;
438                     let name = this.memory().read_c_str(name_ptr)?;
439                     match this.machine.env_vars.get(name) {
440                         Some(&var) => Scalar::Ptr(var),
441                         None => Scalar::ptr_null(&*this.tcx),
442                     }
443                 };
444                 this.write_scalar(result, dest)?;
445             }
446
447             "unsetenv" => {
448                 let mut success = None;
449                 {
450                     let name_ptr = this.read_scalar(args[0])?.not_undef()?;
451                     if !this.is_null(name_ptr)? {
452                         let name = this.memory().read_c_str(name_ptr)?.to_owned();
453                         if !name.is_empty() && !name.contains(&b'=') {
454                             success = Some(this.machine.env_vars.remove(&name));
455                         }
456                     }
457                 }
458                 if let Some(old) = success {
459                     if let Some(var) = old {
460                         this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
461                     }
462                     this.write_null(dest)?;
463                 } else {
464                     this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
465                 }
466             }
467
468             "setenv" => {
469                 let mut new = None;
470                 {
471                     let name_ptr = this.read_scalar(args[0])?.not_undef()?;
472                     let value_ptr = this.read_scalar(args[1])?.not_undef()?;
473                     let value = this.memory().read_c_str(value_ptr)?;
474                     if !this.is_null(name_ptr)? {
475                         let name = this.memory().read_c_str(name_ptr)?;
476                         if !name.is_empty() && !name.contains(&b'=') {
477                             new = Some((name.to_owned(), value.to_owned()));
478                         }
479                     }
480                 }
481                 if let Some((name, value)) = new {
482                     // `+1` for the null terminator.
483                     let value_copy = this.memory_mut().allocate(
484                         Size::from_bytes((value.len() + 1) as u64),
485                         Align::from_bytes(1).unwrap(),
486                         MiriMemoryKind::Env.into(),
487                     );
488                     // We just allocated these, so the write cannot fail.
489                     let alloc = this.memory_mut().get_mut(value_copy.alloc_id).unwrap();
490                     alloc.write_bytes(tcx, value_copy, &value).unwrap();
491                     let trailing_zero_ptr = value_copy.offset(
492                         Size::from_bytes(value.len() as u64),
493                         tcx,
494                     ).unwrap();
495                     alloc.write_bytes(tcx, trailing_zero_ptr, &[0]).unwrap();
496
497                     if let Some(var) = this.machine.env_vars.insert(
498                         name.to_owned(),
499                         value_copy,
500                     )
501                     {
502                         this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
503                     }
504                     this.write_null(dest)?;
505                 } else {
506                     this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
507                 }
508             }
509
510             "write" => {
511                 let fd = this.read_scalar(args[0])?.to_i32()?;
512                 let buf = this.read_scalar(args[1])?.not_undef()?;
513                 let n = this.read_scalar(args[2])?.to_usize(&*this.tcx)?;
514                 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
515                 let result = if fd == 1 || fd == 2 {
516                     // stdout/stderr
517                     use std::io::{self, Write};
518
519                     let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(n))?;
520                     // We need to flush to make sure this actually appears on the screen
521                     let res = if fd == 1 {
522                         // Stdout is buffered, flush to make sure it appears on the screen.
523                         // This is the write() syscall of the interpreted program, we want it
524                         // to correspond to a write() syscall on the host -- there is no good
525                         // in adding extra buffering here.
526                         let res = io::stdout().write(buf_cont);
527                         io::stdout().flush().unwrap();
528                         res
529                     } else {
530                         // No need to flush, stderr is not buffered.
531                         io::stderr().write(buf_cont)
532                     };
533                     match res {
534                         Ok(n) => n as i64,
535                         Err(_) => -1,
536                     }
537                 } else {
538                     eprintln!("Miri: Ignored output to FD {}", fd);
539                     // Pretend it all went well.
540                     n as i64
541                 };
542                 // Now, `result` is the value we return back to the program.
543                 this.write_scalar(
544                     Scalar::from_int(result, dest.layout.size),
545                     dest,
546                 )?;
547             }
548
549             "strlen" => {
550                 let ptr = this.read_scalar(args[0])?.not_undef()?;
551                 let n = this.memory().read_c_str(ptr)?.len();
552                 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
553             }
554
555             // math functions
556
557             "cbrtf" | "coshf" | "sinhf" |"tanf" => {
558                 // FIXME: Using host floats.
559                 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
560                 let f = match link_name {
561                     "cbrtf" => f.cbrt(),
562                     "coshf" => f.cosh(),
563                     "sinhf" => f.sinh(),
564                     "tanf" => f.tan(),
565                     _ => bug!(),
566                 };
567                 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
568             }
569             // underscore case for windows
570             "_hypotf" | "hypotf" | "atan2f" => {
571                 // FIXME: Using host floats.
572                 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
573                 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
574                 let n = match link_name {
575                     "_hypotf" | "hypotf" => f1.hypot(f2),
576                     "atan2f" => f1.atan2(f2),
577                     _ => bug!(),
578                 };
579                 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
580             }
581
582             "cbrt" | "cosh" | "sinh" | "tan" => {
583                 // FIXME: Using host floats.
584                 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
585                 let f = match link_name {
586                     "cbrt" => f.cbrt(),
587                     "cosh" => f.cosh(),
588                     "sinh" => f.sinh(),
589                     "tan" => f.tan(),
590                     _ => bug!(),
591                 };
592                 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
593             }
594             // underscore case for windows
595             "_hypot" | "hypot" | "atan2" => {
596                 // FIXME: Using host floats.
597                 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
598                 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
599                 let n = match link_name {
600                     "_hypot" | "hypot" => f1.hypot(f2),
601                     "atan2" => f1.atan2(f2),
602                     _ => bug!(),
603                 };
604                 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
605             }
606
607             // Some things needed for `sys::thread` initialization to go through.
608             "signal" | "sigaction" | "sigaltstack" => {
609                 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
610             }
611
612             "sysconf" => {
613                 let name = this.read_scalar(args[0])?.to_i32()?;
614
615                 trace!("sysconf() called with name {}", name);
616                 // TODO: Cache the sysconf integers via Miri's global cache.
617                 let paths = &[
618                     (&["libc", "_SC_PAGESIZE"], Scalar::from_int(PAGE_SIZE, dest.layout.size)),
619                     (&["libc", "_SC_GETPW_R_SIZE_MAX"], Scalar::from_int(-1, dest.layout.size)),
620                     (&["libc", "_SC_NPROCESSORS_ONLN"], Scalar::from_int(NUM_CPUS, dest.layout.size)),
621                 ];
622                 let mut result = None;
623                 for &(path, path_value) in paths {
624                     if let Some(val) = this.eval_path_scalar(path)? {
625                         let val = val.to_i32()?;
626                         if val == name {
627                             result = Some(path_value);
628                             break;
629                         }
630
631                     }
632                 }
633                 if let Some(result) = result {
634                     this.write_scalar(result, dest)?;
635                 } else {
636                     return err!(Unimplemented(
637                         format!("Unimplemented sysconf name: {}", name),
638                     ));
639                 }
640             }
641
642             "sched_getaffinity" => {
643                 // Return an error; `num_cpus` then falls back to `sysconf`.
644                 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
645             }
646
647             "isatty" => {
648                 this.write_null(dest)?;
649             }
650
651             // Hook pthread calls that go to the thread-local storage memory subsystem.
652             "pthread_key_create" => {
653                 let key_ptr = this.read_scalar(args[0])?.not_undef()?;
654
655                 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
656                 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
657                     Some(dtor_ptr) => Some(this.memory().get_fn(dtor_ptr)?.as_instance()?),
658                     None => None,
659                 };
660
661                 // Figure out how large a pthread TLS key actually is.
662                 // This is `libc::pthread_key_t`.
663                 let key_type = args[0].layout.ty
664                     .builtin_deref(true)
665                     .ok_or_else(|| InterpError::AbiViolation("wrong signature used for `pthread_key_create`: first argument must be a raw pointer.".to_owned()))?
666                     .ty;
667                 let key_layout = this.layout_of(key_type)?;
668
669                 // Create key and write it into the memory where `key_ptr` wants it.
670                 let key = this.machine.tls.create_tls_key(dtor) as u128;
671                 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128) {
672                     return err!(OutOfTls);
673                 }
674
675                 let key_ptr = this.memory().check_ptr_access(key_ptr, key_layout.size, key_layout.align.abi)?
676                     .expect("cannot be a ZST");
677                 this.memory_mut().get_mut(key_ptr.alloc_id)?.write_scalar(
678                     tcx,
679                     key_ptr,
680                     Scalar::from_uint(key, key_layout.size).into(),
681                     key_layout.size,
682                 )?;
683
684                 // Return success (`0`).
685                 this.write_null(dest)?;
686             }
687             "pthread_key_delete" => {
688                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
689                 this.machine.tls.delete_tls_key(key)?;
690                 // Return success (0)
691                 this.write_null(dest)?;
692             }
693             "pthread_getspecific" => {
694                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
695                 let ptr = this.machine.tls.load_tls(key, tcx)?;
696                 this.write_scalar(ptr, dest)?;
697             }
698             "pthread_setspecific" => {
699                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
700                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
701                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
702
703                 // Return success (`0`).
704                 this.write_null(dest)?;
705             }
706
707             // Stack size/address stuff.
708             "pthread_attr_init" | "pthread_attr_destroy" | "pthread_self" |
709             "pthread_attr_setstacksize" => {
710                 this.write_null(dest)?;
711             }
712             "pthread_attr_getstack" => {
713                 let addr_place = this.deref_operand(args[1])?;
714                 let size_place = this.deref_operand(args[2])?;
715
716                 this.write_scalar(
717                     Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
718                     addr_place.into(),
719                 )?;
720                 this.write_scalar(
721                     Scalar::from_uint(STACK_SIZE, size_place.layout.size),
722                     size_place.into(),
723                 )?;
724
725                 // Return success (`0`).
726                 this.write_null(dest)?;
727             }
728
729             // We don't support threading. (Also for Windows.)
730             "pthread_create" | "CreateThread" => {
731                 return err!(Unimplemented(format!("Miri does not support threading")));
732             }
733
734             // Stub out calls for condvar, mutex and rwlock, to just return `0`.
735             "pthread_mutexattr_init" | "pthread_mutexattr_settype" | "pthread_mutex_init" |
736             "pthread_mutexattr_destroy" | "pthread_mutex_lock" | "pthread_mutex_unlock" |
737             "pthread_mutex_destroy" | "pthread_rwlock_rdlock" | "pthread_rwlock_unlock" |
738             "pthread_rwlock_wrlock" | "pthread_rwlock_destroy" | "pthread_condattr_init" |
739             "pthread_condattr_setclock" | "pthread_cond_init" | "pthread_condattr_destroy" |
740             "pthread_cond_destroy" => {
741                 this.write_null(dest)?;
742             }
743
744             // We don't support fork so we don't have to do anything for atfork.
745             "pthread_atfork" => {
746                 this.write_null(dest)?;
747             }
748
749             "mmap" => {
750                 // This is a horrible hack, but since the guard page mechanism calls mmap and expects a particular return value, we just give it that value.
751                 let addr = this.read_scalar(args[0])?.not_undef()?;
752                 this.write_scalar(addr, dest)?;
753             }
754             "mprotect" => {
755                 this.write_null(dest)?;
756             }
757
758             // macOS API stubs.
759             "pthread_attr_get_np" | "pthread_getattr_np" => {
760                 this.write_null(dest)?;
761             }
762             "pthread_get_stackaddr_np" => {
763                 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
764                 this.write_scalar(stack_addr, dest)?;
765             }
766             "pthread_get_stacksize_np" => {
767                 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
768                 this.write_scalar(stack_size, dest)?;
769             }
770             "_tlv_atexit" => {
771                 // FIXME: register the destructor.
772             },
773             "_NSGetArgc" => {
774                 this.write_scalar(Scalar::Ptr(this.machine.argc.unwrap()), dest)?;
775             },
776             "_NSGetArgv" => {
777                 this.write_scalar(Scalar::Ptr(this.machine.argv.unwrap()), dest)?;
778             },
779             "SecRandomCopyBytes" => {
780                 let len = this.read_scalar(args[1])?.to_usize(this)?;
781                 let ptr = this.read_scalar(args[2])?.not_undef()?;
782                 this.gen_random(len as usize, ptr)?;
783                 this.write_null(dest)?;
784             }
785
786             // Windows API stubs.
787             // HANDLE = isize
788             // DWORD = ULONG = u32
789             // BOOL = i32
790             "GetProcessHeap" => {
791                 // Just fake a HANDLE
792                 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
793             }
794             "HeapAlloc" => {
795                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
796                 let flags = this.read_scalar(args[1])?.to_u32()?;
797                 let size = this.read_scalar(args[2])?.to_usize(this)?;
798                 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
799                 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
800                 this.write_scalar(res, dest)?;
801             }
802             "HeapFree" => {
803                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
804                 let _flags = this.read_scalar(args[1])?.to_u32()?;
805                 let ptr = this.read_scalar(args[2])?.not_undef()?;
806                 this.free(ptr, MiriMemoryKind::WinHeap)?;
807                 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
808             }
809             "HeapReAlloc" => {
810                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
811                 let _flags = this.read_scalar(args[1])?.to_u32()?;
812                 let ptr = this.read_scalar(args[2])?.not_undef()?;
813                 let size = this.read_scalar(args[3])?.to_usize(this)?;
814                 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
815                 this.write_scalar(res, dest)?;
816             }
817
818             "SetLastError" => {
819                 let err = this.read_scalar(args[0])?.to_u32()?;
820                 this.machine.last_error = err;
821             }
822             "GetLastError" => {
823                 this.write_scalar(Scalar::from_u32(this.machine.last_error), dest)?;
824             }
825
826             "AddVectoredExceptionHandler" => {
827                 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
828                 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
829             },
830             "InitializeCriticalSection" |
831             "EnterCriticalSection" |
832             "LeaveCriticalSection" |
833             "DeleteCriticalSection" => {
834                 // Nothing to do, not even a return value.
835             },
836             "GetModuleHandleW" |
837             "GetProcAddress" |
838             "TryEnterCriticalSection" |
839             "GetConsoleScreenBufferInfo" |
840             "SetConsoleTextAttribute" => {
841                 // Pretend these do not exist / nothing happened, by returning zero.
842                 this.write_null(dest)?;
843             },
844             "GetSystemInfo" => {
845                 let system_info = this.deref_operand(args[0])?;
846                 let system_info_ptr = this.check_mplace_access(system_info, None)?
847                     .expect("cannot be a ZST");
848                 // Initialize with `0`.
849                 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
850                     .write_repeat(tcx, system_info_ptr, 0, system_info.layout.size)?;
851                 // Set number of processors.
852                 let dword_size = Size::from_bytes(4);
853                 let offset = 2*dword_size + 3*tcx.pointer_size();
854                 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
855                     .write_scalar(
856                         tcx,
857                         system_info_ptr.offset(offset, tcx)?,
858                         Scalar::from_int(NUM_CPUS, dword_size).into(),
859                         dword_size,
860                     )?;
861             }
862
863             "TlsAlloc" => {
864                 // This just creates a key; Windows does not natively support TLS destructors.
865
866                 // Create key and return it.
867                 let key = this.machine.tls.create_tls_key(None) as u128;
868
869                 // Figure out how large a TLS key actually is. This is `c::DWORD`.
870                 if dest.layout.size.bits() < 128
871                         && key >= (1u128 << dest.layout.size.bits() as u128) {
872                     return err!(OutOfTls);
873                 }
874                 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
875             }
876             "TlsGetValue" => {
877                 let key = this.read_scalar(args[0])?.to_u32()? as u128;
878                 let ptr = this.machine.tls.load_tls(key, tcx)?;
879                 this.write_scalar(ptr, dest)?;
880             }
881             "TlsSetValue" => {
882                 let key = this.read_scalar(args[0])?.to_u32()? as u128;
883                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
884                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
885
886                 // Return success (`1`).
887                 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
888             }
889             "GetStdHandle" => {
890                 let which = this.read_scalar(args[0])?.to_i32()?;
891                 // We just make this the identity function, so we know later in `WriteFile`
892                 // which one it is.
893                 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
894             }
895             "WriteFile" => {
896                 let handle = this.read_scalar(args[0])?.to_isize(this)?;
897                 let buf = this.read_scalar(args[1])?.not_undef()?;
898                 let n = this.read_scalar(args[2])?.to_u32()?;
899                 let written_place = this.deref_operand(args[3])?;
900                 // Spec says to always write `0` first.
901                 this.write_null(written_place.into())?;
902                 let written = if handle == -11 || handle == -12 {
903                     // stdout/stderr
904                     use std::io::{self, Write};
905
906                     let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(u64::from(n)))?;
907                     let res = if handle == -11 {
908                         io::stdout().write(buf_cont)
909                     } else {
910                         io::stderr().write(buf_cont)
911                     };
912                     res.ok().map(|n| n as u32)
913                 } else {
914                     eprintln!("Miri: Ignored output to handle {}", handle);
915                     // Pretend it all went well.
916                     Some(n)
917                 };
918                 // If there was no error, write back how much was written.
919                 if let Some(n) = written {
920                     this.write_scalar(Scalar::from_u32(n), written_place.into())?;
921                 }
922                 // Return whether this was a success.
923                 this.write_scalar(
924                     Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
925                     dest,
926                 )?;
927             }
928             "GetConsoleMode" => {
929                 // Everything is a pipe.
930                 this.write_null(dest)?;
931             }
932             "GetEnvironmentVariableW" => {
933                 // This is not the env var you are looking for.
934                 this.machine.last_error = 203; // ERROR_ENVVAR_NOT_FOUND
935                 this.write_null(dest)?;
936             }
937             "GetCommandLineW" => {
938                 this.write_scalar(Scalar::Ptr(this.machine.cmd_line.unwrap()), dest)?;
939             }
940             // The actual name of 'RtlGenRandom'
941             "SystemFunction036" => {
942                 let ptr = this.read_scalar(args[0])?.not_undef()?;
943                 let len = this.read_scalar(args[1])?.to_u32()?;
944                 this.gen_random(len as usize, ptr)?;
945                 this.write_scalar(Scalar::from_bool(true), dest)?;
946             }
947
948             // We can't execute anything else.
949             _ => {
950                 return err!(Unimplemented(
951                     format!("can't call foreign function: {}", link_name),
952                 ));
953             }
954         }
955
956         this.goto_block(Some(ret))?;
957         this.dump_place(*dest);
958         Ok(())
959     }
960
961     /// Evaluates the scalar at the specified path. Returns Some(val)
962     /// if the path could be resolved, and None otherwise
963     fn eval_path_scalar(&mut self, path: &[&str]) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
964         let this = self.eval_context_mut();
965         if let Ok(instance) = this.resolve_path(path) {
966             let cid = GlobalId {
967                 instance,
968                 promoted: None,
969             };
970             let const_val = this.const_eval_raw(cid)?;
971             let const_val = this.read_scalar(const_val.into())?;
972             return Ok(Some(const_val));
973         }
974         return Ok(None);
975     }
976 }