]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items.rs
clamp ldexp exponent to i16
[rust.git] / src / shims / foreign_items.rs
1 use std::convert::TryInto;
2
3 use rustc_apfloat::Float;
4 use rustc::ty::layout::{Align, LayoutOf, Size};
5 use rustc::hir::def_id::DefId;
6 use rustc::mir;
7 use syntax::attr;
8 use syntax::symbol::sym;
9
10 use crate::*;
11
12 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
13 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
14     /// Returns the minimum alignment for the target architecture for allocations of the given size.
15     fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
16         let this = self.eval_context_ref();
17         // List taken from `libstd/sys_common/alloc.rs`.
18         let min_align = match this.tcx.tcx.sess.target.target.arch.as_str() {
19             "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
20             "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
21             arch => bug!("Unsupported target architecture: {}", arch),
22         };
23         // Windows always aligns, even small allocations.
24         // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
25         // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
26         if kind == MiriMemoryKind::WinHeap || size >= min_align {
27             return Align::from_bytes(min_align).unwrap();
28         }
29         // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
30         fn prev_power_of_two(x: u64) -> u64 {
31             let next_pow2 = x.next_power_of_two();
32             if next_pow2 == x {
33                 // x *is* a power of two, just use that.
34                 x
35             } else {
36                 // x is between two powers, so next = 2*prev.
37                 next_pow2 / 2
38             }
39         }
40         Align::from_bytes(prev_power_of_two(size)).unwrap()
41     }
42
43     fn malloc(
44         &mut self,
45         size: u64,
46         zero_init: bool,
47         kind: MiriMemoryKind,
48     ) -> Scalar<Tag> {
49         let this = self.eval_context_mut();
50         let tcx = &{this.tcx.tcx};
51         if size == 0 {
52             Scalar::from_int(0, this.pointer_size())
53         } else {
54             let align = this.min_align(size, kind);
55             let ptr = this.memory_mut().allocate(Size::from_bytes(size), align, kind.into());
56             if zero_init {
57                 // We just allocated this, the access cannot fail
58                 this.memory_mut()
59                     .get_mut(ptr.alloc_id).unwrap()
60                     .write_repeat(tcx, ptr, 0, Size::from_bytes(size)).unwrap();
61             }
62             Scalar::Ptr(ptr)
63         }
64     }
65
66     fn free(
67         &mut self,
68         ptr: Scalar<Tag>,
69         kind: MiriMemoryKind,
70     ) -> InterpResult<'tcx> {
71         let this = self.eval_context_mut();
72         if !this.is_null(ptr)? {
73             let ptr = this.force_ptr(ptr)?;
74             this.memory_mut().deallocate(
75                 ptr,
76                 None,
77                 kind.into(),
78             )?;
79         }
80         Ok(())
81     }
82
83     fn realloc(
84         &mut self,
85         old_ptr: Scalar<Tag>,
86         new_size: u64,
87         kind: MiriMemoryKind,
88     ) -> InterpResult<'tcx, Scalar<Tag>> {
89         let this = self.eval_context_mut();
90         let new_align = this.min_align(new_size, kind);
91         if this.is_null(old_ptr)? {
92             if new_size == 0 {
93                 Ok(Scalar::from_int(0, this.pointer_size()))
94             } else {
95                 let new_ptr = this.memory_mut().allocate(
96                     Size::from_bytes(new_size),
97                     new_align,
98                     kind.into()
99                 );
100                 Ok(Scalar::Ptr(new_ptr))
101             }
102         } else {
103             let old_ptr = this.force_ptr(old_ptr)?;
104             let memory = this.memory_mut();
105             if new_size == 0 {
106                 memory.deallocate(
107                     old_ptr,
108                     None,
109                     kind.into(),
110                 )?;
111                 Ok(Scalar::from_int(0, this.pointer_size()))
112             } else {
113                 let new_ptr = memory.reallocate(
114                     old_ptr,
115                     None,
116                     Size::from_bytes(new_size),
117                     new_align,
118                     kind.into(),
119                 )?;
120                 Ok(Scalar::Ptr(new_ptr))
121             }
122         }
123     }
124
125     /// Emulates calling a foreign item, failing if the item is not supported.
126     /// This function will handle `goto_block` if needed.
127     fn emulate_foreign_item(
128         &mut self,
129         def_id: DefId,
130         args: &[OpTy<'tcx, Tag>],
131         dest: Option<PlaceTy<'tcx, Tag>>,
132         ret: Option<mir::BasicBlock>,
133     ) -> InterpResult<'tcx> {
134         let this = self.eval_context_mut();
135         let attrs = this.tcx.get_attrs(def_id);
136         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
137             Some(name) => name.as_str(),
138             None => this.tcx.item_name(def_id).as_str(),
139         };
140         // Strip linker suffixes (seen on 32-bit macOS).
141         let link_name = link_name.get().trim_end_matches("$UNIX2003");
142         let tcx = &{this.tcx.tcx};
143
144         // First: functions that diverge.
145         match link_name {
146             "__rust_start_panic" | "panic_impl" => {
147                 throw_unsup_format!("the evaluated program panicked");
148             }
149             "exit" | "ExitProcess" => {
150                 // it's really u32 for ExitProcess, but we have to put it into the `Exit` error variant anyway
151                 let code = this.read_scalar(args[0])?.to_i32()?;
152                 return Err(InterpError::Exit(code).into());
153             }
154             _ => if dest.is_none() {
155                 throw_unsup_format!("can't call (diverging) foreign function: {}", link_name);
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(|| err_panic!(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                     throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
182                 }
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                         // The first argument is the syscall id,
300                         // so skip over it.
301                         linux_getrandom(this, &args[1..], dest)?;
302                     }
303                     id => {
304                         throw_unsup_format!("miri does not support syscall ID {}", id)
305                     }
306                 }
307             }
308
309             "getrandom" => {
310                 linux_getrandom(this, args, dest)?;
311             }
312
313             "dlsym" => {
314                 let _handle = this.read_scalar(args[0])?;
315                 let symbol = this.read_scalar(args[1])?.not_undef()?;
316                 let symbol_name = this.memory().read_c_str(symbol)?;
317                 let err = format!("bad c unicode symbol: {:?}", symbol_name);
318                 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
319                 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
320                     let ptr = this.memory_mut().create_fn_alloc(FnVal::Other(dlsym));
321                     this.write_scalar(Scalar::from(ptr), dest)?;
322                 } else {
323                     this.write_null(dest)?;
324                 }
325             }
326
327             "__rust_maybe_catch_panic" => {
328                 // fn __rust_maybe_catch_panic(
329                 //     f: fn(*mut u8),
330                 //     data: *mut u8,
331                 //     data_ptr: *mut usize,
332                 //     vtable_ptr: *mut usize,
333                 // ) -> u32
334                 // We abort on panic, so not much is going on here, but we still have to call the closure.
335                 let f = this.read_scalar(args[0])?.not_undef()?;
336                 let data = this.read_scalar(args[1])?.not_undef()?;
337                 let f_instance = this.memory().get_fn(f)?.as_instance()?;
338                 this.write_null(dest)?;
339                 trace!("__rust_maybe_catch_panic: {:?}", f_instance);
340
341                 // Now we make a function call.
342                 // TODO: consider making this reusable? `InterpCx::step` does something similar
343                 // for the TLS destructors, and of course `eval_main`.
344                 let mir = this.load_mir(f_instance.def)?;
345                 let ret_place = MPlaceTy::dangling(this.layout_of(this.tcx.mk_unit())?, this).into();
346                 this.push_stack_frame(
347                     f_instance,
348                     mir.span,
349                     mir,
350                     Some(ret_place),
351                     // Directly return to caller.
352                     StackPopCleanup::Goto(Some(ret)),
353                 )?;
354                 let mut args = this.frame().body.args_iter();
355
356                 let arg_local = args.next()
357                     .expect("Argument to __rust_maybe_catch_panic does not take enough arguments.");
358                 let arg_dest = this.local_place(arg_local)?;
359                 this.write_scalar(data, arg_dest)?;
360
361                 assert!(args.next().is_none(), "__rust_maybe_catch_panic argument has more arguments than expected");
362
363                 // We ourselves will return `0`, eventually (because we will not return if we paniced).
364                 this.write_null(dest)?;
365
366                 // Don't fall through, we do *not* want to `goto_block`!
367                 return Ok(());
368             }
369
370             "memcmp" => {
371                 let left = this.read_scalar(args[0])?.not_undef()?;
372                 let right = this.read_scalar(args[1])?.not_undef()?;
373                 let n = Size::from_bytes(this.read_scalar(args[2])?.to_usize(this)?);
374
375                 let result = {
376                     let left_bytes = this.memory().read_bytes(left, n)?;
377                     let right_bytes = this.memory().read_bytes(right, n)?;
378
379                     use std::cmp::Ordering::*;
380                     match left_bytes.cmp(right_bytes) {
381                         Less => -1i32,
382                         Equal => 0,
383                         Greater => 1,
384                     }
385                 };
386
387                 this.write_scalar(
388                     Scalar::from_int(result, Size::from_bits(32)),
389                     dest,
390                 )?;
391             }
392
393             "memrchr" => {
394                 let ptr = this.read_scalar(args[0])?.not_undef()?;
395                 let val = this.read_scalar(args[1])?.to_i32()? as u8;
396                 let num = this.read_scalar(args[2])?.to_usize(this)?;
397                 if let Some(idx) = this.memory().read_bytes(ptr, Size::from_bytes(num))?
398                     .iter().rev().position(|&c| c == val)
399                 {
400                     let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
401                     this.write_scalar(new_ptr, dest)?;
402                 } else {
403                     this.write_null(dest)?;
404                 }
405             }
406
407             "memchr" => {
408                 let ptr = this.read_scalar(args[0])?.not_undef()?;
409                 let val = this.read_scalar(args[1])?.to_i32()? as u8;
410                 let num = this.read_scalar(args[2])?.to_usize(this)?;
411                 let idx = this
412                     .memory()
413                     .read_bytes(ptr, Size::from_bytes(num))?
414                     .iter()
415                     .position(|&c| c == val);
416                 if let Some(idx) = idx {
417                     let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
418                     this.write_scalar(new_ptr, dest)?;
419                 } else {
420                     this.write_null(dest)?;
421                 }
422             }
423
424             "getenv" => {
425                 let result = {
426                     let name_ptr = this.read_scalar(args[0])?.not_undef()?;
427                     let name = this.memory().read_c_str(name_ptr)?;
428                     match this.machine.env_vars.get(name) {
429                         Some(&var) => Scalar::Ptr(var),
430                         None => Scalar::ptr_null(&*this.tcx),
431                     }
432                 };
433                 this.write_scalar(result, dest)?;
434             }
435
436             "unsetenv" => {
437                 let mut success = None;
438                 {
439                     let name_ptr = this.read_scalar(args[0])?.not_undef()?;
440                     if !this.is_null(name_ptr)? {
441                         let name = this.memory().read_c_str(name_ptr)?.to_owned();
442                         if !name.is_empty() && !name.contains(&b'=') {
443                             success = Some(this.machine.env_vars.remove(&name));
444                         }
445                     }
446                 }
447                 if let Some(old) = success {
448                     if let Some(var) = old {
449                         this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
450                     }
451                     this.write_null(dest)?;
452                 } else {
453                     this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
454                 }
455             }
456
457             "setenv" => {
458                 let mut new = None;
459                 {
460                     let name_ptr = this.read_scalar(args[0])?.not_undef()?;
461                     let value_ptr = this.read_scalar(args[1])?.not_undef()?;
462                     let value = this.memory().read_c_str(value_ptr)?;
463                     if !this.is_null(name_ptr)? {
464                         let name = this.memory().read_c_str(name_ptr)?;
465                         if !name.is_empty() && !name.contains(&b'=') {
466                             new = Some((name.to_owned(), value.to_owned()));
467                         }
468                     }
469                 }
470                 if let Some((name, value)) = new {
471                     // `+1` for the null terminator.
472                     let value_copy = this.memory_mut().allocate(
473                         Size::from_bytes((value.len() + 1) as u64),
474                         Align::from_bytes(1).unwrap(),
475                         MiriMemoryKind::Env.into(),
476                     );
477                     // We just allocated these, so the write cannot fail.
478                     let alloc = this.memory_mut().get_mut(value_copy.alloc_id).unwrap();
479                     alloc.write_bytes(tcx, value_copy, &value).unwrap();
480                     let trailing_zero_ptr = value_copy.offset(
481                         Size::from_bytes(value.len() as u64),
482                         tcx,
483                     ).unwrap();
484                     alloc.write_bytes(tcx, trailing_zero_ptr, &[0]).unwrap();
485
486                     if let Some(var) = this.machine.env_vars.insert(
487                         name.to_owned(),
488                         value_copy,
489                     )
490                     {
491                         this.memory_mut().deallocate(var, None, MiriMemoryKind::Env.into())?;
492                     }
493                     this.write_null(dest)?;
494                 } else {
495                     this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
496                 }
497             }
498
499             "write" => {
500                 let fd = this.read_scalar(args[0])?.to_i32()?;
501                 let buf = this.read_scalar(args[1])?.not_undef()?;
502                 let n = this.read_scalar(args[2])?.to_usize(&*this.tcx)?;
503                 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
504                 let result = if fd == 1 || fd == 2 {
505                     // stdout/stderr
506                     use std::io::{self, Write};
507
508                     let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(n))?;
509                     // We need to flush to make sure this actually appears on the screen
510                     let res = if fd == 1 {
511                         // Stdout is buffered, flush to make sure it appears on the screen.
512                         // This is the write() syscall of the interpreted program, we want it
513                         // to correspond to a write() syscall on the host -- there is no good
514                         // in adding extra buffering here.
515                         let res = io::stdout().write(buf_cont);
516                         io::stdout().flush().unwrap();
517                         res
518                     } else {
519                         // No need to flush, stderr is not buffered.
520                         io::stderr().write(buf_cont)
521                     };
522                     match res {
523                         Ok(n) => n as i64,
524                         Err(_) => -1,
525                     }
526                 } else {
527                     eprintln!("Miri: Ignored output to FD {}", fd);
528                     // Pretend it all went well.
529                     n as i64
530                 };
531                 // Now, `result` is the value we return back to the program.
532                 this.write_scalar(
533                     Scalar::from_int(result, dest.layout.size),
534                     dest,
535                 )?;
536             }
537
538             "strlen" => {
539                 let ptr = this.read_scalar(args[0])?.not_undef()?;
540                 let n = this.memory().read_c_str(ptr)?.len();
541                 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
542             }
543
544             // math functions
545
546             "cbrtf" | "coshf" | "sinhf" |"tanf" => {
547                 // FIXME: Using host floats.
548                 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
549                 let f = match link_name {
550                     "cbrtf" => f.cbrt(),
551                     "coshf" => f.cosh(),
552                     "sinhf" => f.sinh(),
553                     "tanf" => f.tan(),
554                     _ => bug!(),
555                 };
556                 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
557             }
558             // underscore case for windows
559             "_hypotf" | "hypotf" | "atan2f" => {
560                 // FIXME: Using host floats.
561                 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
562                 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
563                 let n = match link_name {
564                     "_hypotf" | "hypotf" => f1.hypot(f2),
565                     "atan2f" => f1.atan2(f2),
566                     _ => bug!(),
567                 };
568                 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
569             }
570
571             "cbrt" | "cosh" | "sinh" | "tan" => {
572                 // FIXME: Using host floats.
573                 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
574                 let f = match link_name {
575                     "cbrt" => f.cbrt(),
576                     "cosh" => f.cosh(),
577                     "sinh" => f.sinh(),
578                     "tan" => f.tan(),
579                     _ => bug!(),
580                 };
581                 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
582             }
583             // underscore case for windows, here and below
584             // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
585             "_hypot" | "hypot" | "atan2" => {
586                 // FIXME: Using host floats.
587                 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
588                 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
589                 let n = match link_name {
590                     "_hypot" | "hypot" => f1.hypot(f2),
591                     "atan2" => f1.atan2(f2),
592                     _ => bug!(),
593                 };
594                 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
595             }
596             // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
597             "_ldexp" | "ldexp" | "scalbn" => {
598                 let x = this.read_scalar(args[0])?.to_f64()?;
599                 let exp = this.read_scalar(args[1])?.to_i32()?;
600                 // Saturating cast to i16. Even those are outside the valid exponent range to
601                 // `scalbn` below will to its over/underflow handling.
602                 let exp = if exp > i16::max_value() as i32 {
603                     i16::max_value()
604                 } else if exp < i16::min_value() as i32 {
605                     i16::min_value()
606                 } else {
607                     exp.try_into().unwrap()
608                 };
609                 let res = x.scalbn(exp);
610                 this.write_scalar(Scalar::from_f64(res), dest)?;
611             }
612
613             // Some things needed for `sys::thread` initialization to go through.
614             "signal" | "sigaction" | "sigaltstack" => {
615                 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
616             }
617
618             "sysconf" => {
619                 let name = this.read_scalar(args[0])?.to_i32()?;
620
621                 trace!("sysconf() called with name {}", name);
622                 // TODO: Cache the sysconf integers via Miri's global cache.
623                 let paths = &[
624                     (&["libc", "_SC_PAGESIZE"], Scalar::from_int(PAGE_SIZE, dest.layout.size)),
625                     (&["libc", "_SC_GETPW_R_SIZE_MAX"], Scalar::from_int(-1, dest.layout.size)),
626                     (&["libc", "_SC_NPROCESSORS_ONLN"], Scalar::from_int(NUM_CPUS, dest.layout.size)),
627                 ];
628                 let mut result = None;
629                 for &(path, path_value) in paths {
630                     if let Some(val) = this.eval_path_scalar(path)? {
631                         let val = val.to_i32()?;
632                         if val == name {
633                             result = Some(path_value);
634                             break;
635                         }
636
637                     }
638                 }
639                 if let Some(result) = result {
640                     this.write_scalar(result, dest)?;
641                 } else {
642                     throw_unsup_format!("Unimplemented sysconf name: {}", name)
643                 }
644             }
645
646             "sched_getaffinity" => {
647                 // Return an error; `num_cpus` then falls back to `sysconf`.
648                 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
649             }
650
651             "isatty" => {
652                 this.write_null(dest)?;
653             }
654
655             // Hook pthread calls that go to the thread-local storage memory subsystem.
656             "pthread_key_create" => {
657                 let key_ptr = this.read_scalar(args[0])?.not_undef()?;
658
659                 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
660                 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
661                     Some(dtor_ptr) => Some(this.memory().get_fn(dtor_ptr)?.as_instance()?),
662                     None => None,
663                 };
664
665                 // Figure out how large a pthread TLS key actually is.
666                 // This is `libc::pthread_key_t`.
667                 let key_type = args[0].layout.ty
668                     .builtin_deref(true)
669                     .ok_or_else(|| err_ub_format!(
670                         "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
671                     ))?
672                     .ty;
673                 let key_layout = this.layout_of(key_type)?;
674
675                 // Create key and write it into the memory where `key_ptr` wants it.
676                 let key = this.machine.tls.create_tls_key(dtor) as u128;
677                 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128) {
678                     throw_unsup!(OutOfTls);
679                 }
680
681                 let key_ptr = this.memory().check_ptr_access(key_ptr, key_layout.size, key_layout.align.abi)?
682                     .expect("cannot be a ZST");
683                 this.memory_mut().get_mut(key_ptr.alloc_id)?.write_scalar(
684                     tcx,
685                     key_ptr,
686                     Scalar::from_uint(key, key_layout.size).into(),
687                     key_layout.size,
688                 )?;
689
690                 // Return success (`0`).
691                 this.write_null(dest)?;
692             }
693             "pthread_key_delete" => {
694                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
695                 this.machine.tls.delete_tls_key(key)?;
696                 // Return success (0)
697                 this.write_null(dest)?;
698             }
699             "pthread_getspecific" => {
700                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
701                 let ptr = this.machine.tls.load_tls(key, tcx)?;
702                 this.write_scalar(ptr, dest)?;
703             }
704             "pthread_setspecific" => {
705                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
706                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
707                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
708
709                 // Return success (`0`).
710                 this.write_null(dest)?;
711             }
712
713             // Stack size/address stuff.
714             "pthread_attr_init" | "pthread_attr_destroy" | "pthread_self" |
715             "pthread_attr_setstacksize" => {
716                 this.write_null(dest)?;
717             }
718             "pthread_attr_getstack" => {
719                 let addr_place = this.deref_operand(args[1])?;
720                 let size_place = this.deref_operand(args[2])?;
721
722                 this.write_scalar(
723                     Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
724                     addr_place.into(),
725                 )?;
726                 this.write_scalar(
727                     Scalar::from_uint(STACK_SIZE, size_place.layout.size),
728                     size_place.into(),
729                 )?;
730
731                 // Return success (`0`).
732                 this.write_null(dest)?;
733             }
734
735             // We don't support threading. (Also for Windows.)
736             "pthread_create" | "CreateThread" => {
737                 throw_unsup_format!("Miri does not support threading");
738             }
739
740             // Stub out calls for condvar, mutex and rwlock, to just return `0`.
741             "pthread_mutexattr_init" | "pthread_mutexattr_settype" | "pthread_mutex_init" |
742             "pthread_mutexattr_destroy" | "pthread_mutex_lock" | "pthread_mutex_unlock" |
743             "pthread_mutex_destroy" | "pthread_rwlock_rdlock" | "pthread_rwlock_unlock" |
744             "pthread_rwlock_wrlock" | "pthread_rwlock_destroy" | "pthread_condattr_init" |
745             "pthread_condattr_setclock" | "pthread_cond_init" | "pthread_condattr_destroy" |
746             "pthread_cond_destroy" => {
747                 this.write_null(dest)?;
748             }
749
750             // We don't support fork so we don't have to do anything for atfork.
751             "pthread_atfork" => {
752                 this.write_null(dest)?;
753             }
754
755             "mmap" => {
756                 // 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.
757                 let addr = this.read_scalar(args[0])?.not_undef()?;
758                 this.write_scalar(addr, dest)?;
759             }
760             "mprotect" => {
761                 this.write_null(dest)?;
762             }
763
764             // macOS API stubs.
765             "pthread_attr_get_np" | "pthread_getattr_np" => {
766                 this.write_null(dest)?;
767             }
768             "pthread_get_stackaddr_np" => {
769                 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
770                 this.write_scalar(stack_addr, dest)?;
771             }
772             "pthread_get_stacksize_np" => {
773                 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
774                 this.write_scalar(stack_size, dest)?;
775             }
776             "_tlv_atexit" => {
777                 // FIXME: register the destructor.
778             },
779             "_NSGetArgc" => {
780                 this.write_scalar(Scalar::Ptr(this.machine.argc.unwrap()), dest)?;
781             },
782             "_NSGetArgv" => {
783                 this.write_scalar(Scalar::Ptr(this.machine.argv.unwrap()), dest)?;
784             },
785             "SecRandomCopyBytes" => {
786                 let len = this.read_scalar(args[1])?.to_usize(this)?;
787                 let ptr = this.read_scalar(args[2])?.not_undef()?;
788                 this.gen_random(ptr, len as usize)?;
789                 this.write_null(dest)?;
790             }
791
792             // Windows API stubs.
793             // HANDLE = isize
794             // DWORD = ULONG = u32
795             // BOOL = i32
796             "GetProcessHeap" => {
797                 // Just fake a HANDLE
798                 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
799             }
800             "HeapAlloc" => {
801                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
802                 let flags = this.read_scalar(args[1])?.to_u32()?;
803                 let size = this.read_scalar(args[2])?.to_usize(this)?;
804                 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
805                 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
806                 this.write_scalar(res, dest)?;
807             }
808             "HeapFree" => {
809                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
810                 let _flags = this.read_scalar(args[1])?.to_u32()?;
811                 let ptr = this.read_scalar(args[2])?.not_undef()?;
812                 this.free(ptr, MiriMemoryKind::WinHeap)?;
813                 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
814             }
815             "HeapReAlloc" => {
816                 let _handle = this.read_scalar(args[0])?.to_isize(this)?;
817                 let _flags = this.read_scalar(args[1])?.to_u32()?;
818                 let ptr = this.read_scalar(args[2])?.not_undef()?;
819                 let size = this.read_scalar(args[3])?.to_usize(this)?;
820                 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
821                 this.write_scalar(res, dest)?;
822             }
823
824             "SetLastError" => {
825                 let err = this.read_scalar(args[0])?.to_u32()?;
826                 this.machine.last_error = err;
827             }
828             "GetLastError" => {
829                 this.write_scalar(Scalar::from_u32(this.machine.last_error), dest)?;
830             }
831
832             "AddVectoredExceptionHandler" => {
833                 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
834                 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
835             },
836             "InitializeCriticalSection" |
837             "EnterCriticalSection" |
838             "LeaveCriticalSection" |
839             "DeleteCriticalSection" => {
840                 // Nothing to do, not even a return value.
841             },
842             "GetModuleHandleW" |
843             "GetProcAddress" |
844             "TryEnterCriticalSection" |
845             "GetConsoleScreenBufferInfo" |
846             "SetConsoleTextAttribute" => {
847                 // Pretend these do not exist / nothing happened, by returning zero.
848                 this.write_null(dest)?;
849             },
850             "GetSystemInfo" => {
851                 let system_info = this.deref_operand(args[0])?;
852                 let system_info_ptr = this.check_mplace_access(system_info, None)?
853                     .expect("cannot be a ZST");
854                 // Initialize with `0`.
855                 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
856                     .write_repeat(tcx, system_info_ptr, 0, system_info.layout.size)?;
857                 // Set number of processors.
858                 let dword_size = Size::from_bytes(4);
859                 let offset = 2*dword_size + 3*tcx.pointer_size();
860                 this.memory_mut().get_mut(system_info_ptr.alloc_id)?
861                     .write_scalar(
862                         tcx,
863                         system_info_ptr.offset(offset, tcx)?,
864                         Scalar::from_int(NUM_CPUS, dword_size).into(),
865                         dword_size,
866                     )?;
867             }
868
869             "TlsAlloc" => {
870                 // This just creates a key; Windows does not natively support TLS destructors.
871
872                 // Create key and return it.
873                 let key = this.machine.tls.create_tls_key(None) as u128;
874
875                 // Figure out how large a TLS key actually is. This is `c::DWORD`.
876                 if dest.layout.size.bits() < 128
877                         && key >= (1u128 << dest.layout.size.bits() as u128) {
878                     throw_unsup!(OutOfTls);
879                 }
880                 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
881             }
882             "TlsGetValue" => {
883                 let key = this.read_scalar(args[0])?.to_u32()? as u128;
884                 let ptr = this.machine.tls.load_tls(key, tcx)?;
885                 this.write_scalar(ptr, dest)?;
886             }
887             "TlsSetValue" => {
888                 let key = this.read_scalar(args[0])?.to_u32()? as u128;
889                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
890                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
891
892                 // Return success (`1`).
893                 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
894             }
895             "GetStdHandle" => {
896                 let which = this.read_scalar(args[0])?.to_i32()?;
897                 // We just make this the identity function, so we know later in `WriteFile`
898                 // which one it is.
899                 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
900             }
901             "WriteFile" => {
902                 let handle = this.read_scalar(args[0])?.to_isize(this)?;
903                 let buf = this.read_scalar(args[1])?.not_undef()?;
904                 let n = this.read_scalar(args[2])?.to_u32()?;
905                 let written_place = this.deref_operand(args[3])?;
906                 // Spec says to always write `0` first.
907                 this.write_null(written_place.into())?;
908                 let written = if handle == -11 || handle == -12 {
909                     // stdout/stderr
910                     use std::io::{self, Write};
911
912                     let buf_cont = this.memory().read_bytes(buf, Size::from_bytes(u64::from(n)))?;
913                     let res = if handle == -11 {
914                         io::stdout().write(buf_cont)
915                     } else {
916                         io::stderr().write(buf_cont)
917                     };
918                     res.ok().map(|n| n as u32)
919                 } else {
920                     eprintln!("Miri: Ignored output to handle {}", handle);
921                     // Pretend it all went well.
922                     Some(n)
923                 };
924                 // If there was no error, write back how much was written.
925                 if let Some(n) = written {
926                     this.write_scalar(Scalar::from_u32(n), written_place.into())?;
927                 }
928                 // Return whether this was a success.
929                 this.write_scalar(
930                     Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
931                     dest,
932                 )?;
933             }
934             "GetConsoleMode" => {
935                 // Everything is a pipe.
936                 this.write_null(dest)?;
937             }
938             "GetEnvironmentVariableW" => {
939                 // This is not the env var you are looking for.
940                 this.machine.last_error = 203; // ERROR_ENVVAR_NOT_FOUND
941                 this.write_null(dest)?;
942             }
943             "GetCommandLineW" => {
944                 this.write_scalar(Scalar::Ptr(this.machine.cmd_line.unwrap()), dest)?;
945             }
946             // The actual name of 'RtlGenRandom'
947             "SystemFunction036" => {
948                 let ptr = this.read_scalar(args[0])?.not_undef()?;
949                 let len = this.read_scalar(args[1])?.to_u32()?;
950                 this.gen_random(ptr, len as usize)?;
951                 this.write_scalar(Scalar::from_bool(true), dest)?;
952             }
953
954             // We can't execute anything else.
955             _ => {
956                 throw_unsup_format!("can't call foreign function: {}", link_name)
957             }
958         }
959
960         this.goto_block(Some(ret))?;
961         this.dump_place(*dest);
962         Ok(())
963     }
964
965     /// Evaluates the scalar at the specified path. Returns Some(val)
966     /// if the path could be resolved, and None otherwise
967     fn eval_path_scalar(&mut self, path: &[&str]) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
968         let this = self.eval_context_mut();
969         if let Ok(instance) = this.resolve_path(path) {
970             let cid = GlobalId {
971                 instance,
972                 promoted: None,
973             };
974             let const_val = this.const_eval_raw(cid)?;
975             let const_val = this.read_scalar(const_val.into())?;
976             return Ok(Some(const_val));
977         }
978         return Ok(None);
979     }
980 }
981
982 // Shims the linux 'getrandom()' syscall.
983 fn linux_getrandom<'tcx>(
984     this: &mut MiriEvalContext<'_, 'tcx>,
985     args: &[OpTy<'tcx, Tag>],
986     dest: PlaceTy<'tcx, Tag>,
987 ) -> InterpResult<'tcx> {
988     let ptr = this.read_scalar(args[0])?.not_undef()?;
989     let len = this.read_scalar(args[1])?.to_usize(this)?;
990
991     // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
992     // neither of which have any effect on our current PRNG.
993     let _flags = this.read_scalar(args[2])?.to_i32()?;
994
995     this.gen_random(ptr, len as usize)?;
996     this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;
997     Ok(())
998 }