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