]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items.rs
Auto merge of #1101 - christianpoveda:stat-shim, r=RalfJung
[rust.git] / src / shims / foreign_items.rs
1 use std::{iter, convert::TryInto};
2
3 use rustc::mir;
4 use rustc::ty::layout::{Align, LayoutOf, Size};
5 use rustc::hir::def_id::DefId;
6 use rustc_apfloat::Float;
7 use rustc::ty;
8 use syntax::attr;
9 use syntax::symbol::sym;
10
11 use crate::*;
12
13 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
14 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
15     /// Returns the minimum alignment for the target architecture for allocations of the given size.
16     fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
17         let this = self.eval_context_ref();
18         // List taken from `libstd/sys_common/alloc.rs`.
19         let min_align = match this.tcx.tcx.sess.target.target.arch.as_str() {
20             "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
21             "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
22             arch => bug!("Unsupported target architecture: {}", arch),
23         };
24         // Windows always aligns, even small allocations.
25         // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
26         // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
27         if kind == MiriMemoryKind::WinHeap || size >= min_align {
28             return Align::from_bytes(min_align).unwrap();
29         }
30         // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
31         fn prev_power_of_two(x: u64) -> u64 {
32             let next_pow2 = x.next_power_of_two();
33             if next_pow2 == x {
34                 // x *is* a power of two, just use that.
35                 x
36             } else {
37                 // x is between two powers, so next = 2*prev.
38                 next_pow2 / 2
39             }
40         }
41         Align::from_bytes(prev_power_of_two(size)).unwrap()
42     }
43
44     fn malloc(&mut self, size: u64, zero_init: bool, kind: MiriMemoryKind) -> Scalar<Tag> {
45         let this = self.eval_context_mut();
46         if size == 0 {
47             Scalar::from_int(0, this.pointer_size())
48         } else {
49             let align = this.min_align(size, kind);
50             let ptr = this
51                 .memory
52                 .allocate(Size::from_bytes(size), align, kind.into());
53             if zero_init {
54                 // We just allocated this, the access is definitely in-bounds.
55                 this.memory
56                     .write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize))
57                     .unwrap();
58             }
59             Scalar::Ptr(ptr)
60         }
61     }
62
63     fn free(&mut self, ptr: Scalar<Tag>, kind: MiriMemoryKind) -> InterpResult<'tcx> {
64         let this = self.eval_context_mut();
65         if !this.is_null(ptr)? {
66             let ptr = this.force_ptr(ptr)?;
67             this.memory.deallocate(ptr, None, kind.into())?;
68         }
69         Ok(())
70     }
71
72     fn realloc(
73         &mut self,
74         old_ptr: Scalar<Tag>,
75         new_size: u64,
76         kind: MiriMemoryKind,
77     ) -> InterpResult<'tcx, Scalar<Tag>> {
78         let this = self.eval_context_mut();
79         let new_align = this.min_align(new_size, kind);
80         if this.is_null(old_ptr)? {
81             if new_size == 0 {
82                 Ok(Scalar::from_int(0, this.pointer_size()))
83             } else {
84                 let new_ptr =
85                     this.memory
86                         .allocate(Size::from_bytes(new_size), new_align, kind.into());
87                 Ok(Scalar::Ptr(new_ptr))
88             }
89         } else {
90             let old_ptr = this.force_ptr(old_ptr)?;
91             if new_size == 0 {
92                 this.memory.deallocate(old_ptr, None, kind.into())?;
93                 Ok(Scalar::from_int(0, this.pointer_size()))
94             } else {
95                 let new_ptr = this.memory.reallocate(
96                     old_ptr,
97                     None,
98                     Size::from_bytes(new_size),
99                     new_align,
100                     kind.into(),
101                 )?;
102                 Ok(Scalar::Ptr(new_ptr))
103             }
104         }
105     }
106
107     /// Emulates calling a foreign item, failing if the item is not supported.
108     /// This function will handle `goto_block` if needed.
109     /// Returns Ok(None) if the foreign item was completely handled
110     /// by this function.
111     /// Returns Ok(Some(body)) if processing the foreign item
112     /// is delegated to another function.
113     fn emulate_foreign_item(
114         &mut self,
115         def_id: DefId,
116         args: &[OpTy<'tcx, Tag>],
117         ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
118         _unwind: Option<mir::BasicBlock>
119     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
120         let this = self.eval_context_mut();
121         let attrs = this.tcx.get_attrs(def_id);
122         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
123             Some(name) => name.as_str(),
124             None => this.tcx.item_name(def_id).as_str(),
125         };
126         // Strip linker suffixes (seen on 32-bit macOS).
127         let link_name = link_name.trim_end_matches("$UNIX2003");
128         let tcx = &{ this.tcx.tcx };
129
130         // First: functions that diverge.
131         let (dest, ret) = match link_name {
132             // Note that this matches calls to the *foreign* item `__rust_start_panic* -
133             // that is, calls to `extern "Rust" { fn __rust_start_panic(...) }`.
134             // We forward this to the underlying *implementation* in the panic runtime crate.
135             // Normally, this will be either `libpanic_unwind` or `libpanic_abort`, but it could
136             // also be a custom user-provided implementation via `#![feature(panic_runtime)]`
137             "__rust_start_panic" => {
138                 // FIXME we might want to cache this... but it's not really performance-critical.
139                 let panic_runtime = tcx.crates().iter()
140                     .find(|cnum| tcx.is_panic_runtime(**cnum))
141                     .expect("No panic runtime found!");
142                 let panic_runtime = tcx.crate_name(*panic_runtime);
143                 let start_panic_instance = this.resolve_path(&[&*panic_runtime.as_str(), "__rust_start_panic"])?;
144                 return Ok(Some(&*this.load_mir(start_panic_instance.def, None)?));
145             }
146             // Similarly, we forward calls to the `panic_impl` foreign item to its implementation.
147             // The implementation is provided by the function with the `#[panic_handler]` attribute.
148             "panic_impl" => {
149                 let panic_impl_id = this.tcx.lang_items().panic_impl().unwrap();
150                 let panic_impl_instance = ty::Instance::mono(*this.tcx, panic_impl_id);
151                 return Ok(Some(&*this.load_mir(panic_impl_instance.def, None)?));
152             }
153
154             "exit" | "ExitProcess" => {
155                 // it's really u32 for ExitProcess, but we have to put it into the `Exit` variant anyway
156                 let code = this.read_scalar(args[0])?.to_i32()?;
157                 throw_machine_stop!(TerminationInfo::Exit(code.into()));
158             }
159             _ => {
160                 if let Some(p) = ret {
161                     p
162                 } else {
163                     throw_unsup_format!("can't call (diverging) foreign function: {}", link_name);
164                 }
165             }
166         };
167
168         // Next: functions that return.
169         match link_name {
170             "malloc" => {
171                 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
172                 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
173                 this.write_scalar(res, dest)?;
174             }
175             "calloc" => {
176                 let items = this.read_scalar(args[0])?.to_machine_usize(this)?;
177                 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
178                 let size = items
179                     .checked_mul(len)
180                     .ok_or_else(|| err_panic!(Overflow(mir::BinOp::Mul)))?;
181                 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
182                 this.write_scalar(res, dest)?;
183             }
184             "posix_memalign" => {
185                 let ret = this.deref_operand(args[0])?;
186                 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
187                 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
188                 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
189                 if !align.is_power_of_two() {
190                     throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
191                 }
192                 if align < this.pointer_size().bytes() {
193                     throw_ub_format!(
194                         "posix_memalign: alignment must be at least the size of a pointer, but is {}",
195                         align,
196                     );
197                 }
198
199                 if size == 0 {
200                     this.write_null(ret.into())?;
201                 } else {
202                     let ptr = this.memory.allocate(
203                         Size::from_bytes(size),
204                         Align::from_bytes(align).unwrap(),
205                         MiriMemoryKind::C.into(),
206                     );
207                     this.write_scalar(ptr, ret.into())?;
208                 }
209                 this.write_null(dest)?;
210             }
211             "free" => {
212                 let ptr = this.read_scalar(args[0])?.not_undef()?;
213                 this.free(ptr, MiriMemoryKind::C)?;
214             }
215             "realloc" => {
216                 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
217                 let new_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
218                 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
219                 this.write_scalar(res, dest)?;
220             }
221
222             "__rust_alloc" => {
223                 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
224                 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
225                 if size == 0 {
226                     throw_unsup!(HeapAllocZeroBytes);
227                 }
228                 if !align.is_power_of_two() {
229                     throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
230                 }
231                 let ptr = this.memory.allocate(
232                     Size::from_bytes(size),
233                     Align::from_bytes(align).unwrap(),
234                     MiriMemoryKind::Rust.into(),
235                 );
236                 this.write_scalar(ptr, dest)?;
237             }
238             "__rust_alloc_zeroed" => {
239                 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
240                 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
241                 if size == 0 {
242                     throw_unsup!(HeapAllocZeroBytes);
243                 }
244                 if !align.is_power_of_two() {
245                     throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
246                 }
247                 let ptr = this.memory.allocate(
248                     Size::from_bytes(size),
249                     Align::from_bytes(align).unwrap(),
250                     MiriMemoryKind::Rust.into(),
251                 );
252                 // We just allocated this, the access is definitely in-bounds.
253                 this.memory
254                     .write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize))
255                     .unwrap();
256                 this.write_scalar(ptr, dest)?;
257             }
258             "__rust_dealloc" => {
259                 let ptr = this.read_scalar(args[0])?.not_undef()?;
260                 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
261                 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
262                 if old_size == 0 {
263                     throw_unsup!(HeapAllocZeroBytes);
264                 }
265                 if !align.is_power_of_two() {
266                     throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
267                 }
268                 let ptr = this.force_ptr(ptr)?;
269                 this.memory.deallocate(
270                     ptr,
271                     Some((
272                         Size::from_bytes(old_size),
273                         Align::from_bytes(align).unwrap(),
274                     )),
275                     MiriMemoryKind::Rust.into(),
276                 )?;
277             }
278             "__rust_realloc" => {
279                 let ptr = this.read_scalar(args[0])?.to_ptr()?;
280                 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
281                 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
282                 let new_size = this.read_scalar(args[3])?.to_machine_usize(this)?;
283                 if old_size == 0 || new_size == 0 {
284                     throw_unsup!(HeapAllocZeroBytes);
285                 }
286                 if !align.is_power_of_two() {
287                     throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
288                 }
289                 let align = Align::from_bytes(align).unwrap();
290                 let new_ptr = this.memory.reallocate(
291                     ptr,
292                     Some((Size::from_bytes(old_size), align)),
293                     Size::from_bytes(new_size),
294                     align,
295                     MiriMemoryKind::Rust.into(),
296                 )?;
297                 this.write_scalar(new_ptr, dest)?;
298             }
299
300             "syscall" => {
301                 let sys_getrandom = this
302                     .eval_path_scalar(&["libc", "SYS_getrandom"])?
303                     .expect("Failed to get libc::SYS_getrandom")
304                     .to_machine_usize(this)?;
305
306                 let sys_statx = this
307                     .eval_path_scalar(&["libc", "SYS_statx"])?
308                     .expect("Failed to get libc::SYS_statx")
309                     .to_machine_usize(this)?;
310
311                 match this.read_scalar(args[0])?.to_machine_usize(this)? {
312                     // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
313                     // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
314                     id if id == sys_getrandom => {
315                         // The first argument is the syscall id,
316                         // so skip over it.
317                         linux_getrandom(this, &args[1..], dest)?;
318                     }
319                     id if id == sys_statx => {
320                         // The first argument is the syscall id,
321                         // so skip over it.
322                         let result = this.statx(args[1], args[2], args[3], args[4], args[5])?;
323                         this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
324                     }
325                     id => throw_unsup_format!("miri does not support syscall ID {}", id),
326                 }
327             }
328
329             "getrandom" => {
330                 linux_getrandom(this, args, dest)?;
331             }
332
333             "dlsym" => {
334                 let _handle = this.read_scalar(args[0])?;
335                 let symbol = this.read_scalar(args[1])?.not_undef()?;
336                 let symbol_name = this.memory.read_c_str(symbol)?;
337                 let err = format!("bad c unicode symbol: {:?}", symbol_name);
338                 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
339                 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
340                     let ptr = this.memory.create_fn_alloc(FnVal::Other(dlsym));
341                     this.write_scalar(Scalar::from(ptr), dest)?;
342                 } else {
343                     this.write_null(dest)?;
344                 }
345             }
346
347             "__rust_maybe_catch_panic" => {
348                 this.handle_catch_panic(args, dest, ret)?;
349                 return Ok(None)
350             }
351
352             "memcmp" => {
353                 let left = this.read_scalar(args[0])?.not_undef()?;
354                 let right = this.read_scalar(args[1])?.not_undef()?;
355                 let n = Size::from_bytes(this.read_scalar(args[2])?.to_machine_usize(this)?);
356
357                 let result = {
358                     let left_bytes = this.memory.read_bytes(left, n)?;
359                     let right_bytes = this.memory.read_bytes(right, n)?;
360
361                     use std::cmp::Ordering::*;
362                     match left_bytes.cmp(right_bytes) {
363                         Less => -1i32,
364                         Equal => 0,
365                         Greater => 1,
366                     }
367                 };
368
369                 this.write_scalar(Scalar::from_int(result, Size::from_bits(32)), dest)?;
370             }
371
372             "memrchr" => {
373                 let ptr = this.read_scalar(args[0])?.not_undef()?;
374                 let val = this.read_scalar(args[1])?.to_i32()? as u8;
375                 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
376                 if let Some(idx) = this
377                     .memory
378                     .read_bytes(ptr, Size::from_bytes(num))?
379                     .iter()
380                     .rev()
381                     .position(|&c| c == val)
382                 {
383                     let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
384                     this.write_scalar(new_ptr, dest)?;
385                 } else {
386                     this.write_null(dest)?;
387                 }
388             }
389
390             "memchr" => {
391                 let ptr = this.read_scalar(args[0])?.not_undef()?;
392                 let val = this.read_scalar(args[1])?.to_i32()? as u8;
393                 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
394                 let idx = this
395                     .memory
396                     .read_bytes(ptr, Size::from_bytes(num))?
397                     .iter()
398                     .position(|&c| c == val);
399                 if let Some(idx) = idx {
400                     let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
401                     this.write_scalar(new_ptr, dest)?;
402                 } else {
403                     this.write_null(dest)?;
404                 }
405             }
406
407             "__errno_location" | "__error" => {
408                 let errno_place = this.machine.last_error.unwrap();
409                 this.write_scalar(errno_place.to_ref().to_scalar()?, dest)?;
410             }
411
412             "getenv" => {
413                 let result = this.getenv(args[0])?;
414                 this.write_scalar(result, dest)?;
415             }
416
417             "unsetenv" => {
418                 let result = this.unsetenv(args[0])?;
419                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
420             }
421
422             "setenv" => {
423                 let result = this.setenv(args[0], args[1])?;
424                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
425             }
426
427             "getcwd" => {
428                 let result = this.getcwd(args[0], args[1])?;
429                 this.write_scalar(result, dest)?;
430             }
431
432             "chdir" => {
433                 let result = this.chdir(args[0])?;
434                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
435             }
436
437             "open" | "open64" => {
438                 let result = this.open(args[0], args[1])?;
439                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
440             }
441
442             "fcntl" => {
443                 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
444                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
445             }
446
447             "close" | "close$NOCANCEL" => {
448                 let result = this.close(args[0])?;
449                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
450             }
451
452             "read" => {
453                 let result = this.read(args[0], args[1], args[2])?;
454                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
455             }
456
457             "write" => {
458                 let fd = this.read_scalar(args[0])?.to_i32()?;
459                 let buf = this.read_scalar(args[1])?.not_undef()?;
460                 let n = this.read_scalar(args[2])?.to_machine_usize(tcx)?;
461                 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
462                 let result = if fd == 1 || fd == 2 {
463                     // stdout/stderr
464                     use std::io::{self, Write};
465
466                     let buf_cont = this.memory.read_bytes(buf, Size::from_bytes(n))?;
467                     // We need to flush to make sure this actually appears on the screen
468                     let res = if fd == 1 {
469                         // Stdout is buffered, flush to make sure it appears on the screen.
470                         // This is the write() syscall of the interpreted program, we want it
471                         // to correspond to a write() syscall on the host -- there is no good
472                         // in adding extra buffering here.
473                         let res = io::stdout().write(buf_cont);
474                         io::stdout().flush().unwrap();
475                         res
476                     } else {
477                         // No need to flush, stderr is not buffered.
478                         io::stderr().write(buf_cont)
479                     };
480                     match res {
481                         Ok(n) => n as i64,
482                         Err(_) => -1,
483                     }
484                 } else {
485                     this.write(args[0], args[1], args[2])?
486                 };
487                 // Now, `result` is the value we return back to the program.
488                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
489             }
490
491             "unlink" => {
492                 let result = this.unlink(args[0])?;
493                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
494             }
495
496             "clock_gettime" => {
497                 let result = this.clock_gettime(args[0], args[1])?;
498                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
499             }
500
501             "gettimeofday" => {
502                 let result = this.gettimeofday(args[0], args[1])?;
503                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
504             }
505
506             "strlen" => {
507                 let ptr = this.read_scalar(args[0])?.not_undef()?;
508                 let n = this.memory.read_c_str(ptr)?.len();
509                 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
510             }
511
512             // math functions
513             "cbrtf" | "coshf" | "sinhf" | "tanf" | "acosf" | "asinf" | "atanf" => {
514                 // FIXME: Using host floats.
515                 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
516                 let f = match link_name {
517                     "cbrtf" => f.cbrt(),
518                     "coshf" => f.cosh(),
519                     "sinhf" => f.sinh(),
520                     "tanf" => f.tan(),
521                     "acosf" => f.acos(),
522                     "asinf" => f.asin(),
523                     "atanf" => f.atan(),
524                     _ => bug!(),
525                 };
526                 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
527             }
528             // underscore case for windows
529             "_hypotf" | "hypotf" | "atan2f" => {
530                 // FIXME: Using host floats.
531                 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
532                 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
533                 let n = match link_name {
534                     "_hypotf" | "hypotf" => f1.hypot(f2),
535                     "atan2f" => f1.atan2(f2),
536                     _ => bug!(),
537                 };
538                 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
539             }
540
541             "cbrt" | "cosh" | "sinh" | "tan" | "acos" | "asin" | "atan" => {
542                 // FIXME: Using host floats.
543                 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
544                 let f = match link_name {
545                     "cbrt" => f.cbrt(),
546                     "cosh" => f.cosh(),
547                     "sinh" => f.sinh(),
548                     "tan" => f.tan(),
549                     "acos" => f.acos(),
550                     "asin" => f.asin(),
551                     "atan" => f.atan(),
552                     _ => bug!(),
553                 };
554                 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
555             }
556             // underscore case for windows, here and below
557             // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
558             "_hypot" | "hypot" | "atan2" => {
559                 // FIXME: Using host floats.
560                 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
561                 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
562                 let n = match link_name {
563                     "_hypot" | "hypot" => f1.hypot(f2),
564                     "atan2" => f1.atan2(f2),
565                     _ => bug!(),
566                 };
567                 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
568             }
569             // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
570             "_ldexp" | "ldexp" | "scalbn" => {
571                 let x = this.read_scalar(args[0])?.to_f64()?;
572                 let exp = this.read_scalar(args[1])?.to_i32()?;
573
574                 // Saturating cast to i16. Even those are outside the valid exponent range to
575                 // `scalbn` below will do its over/underflow handling.
576                 let exp = if exp > i16::max_value() as i32 {
577                     i16::max_value()
578                 } else if exp < i16::min_value() as i32 {
579                     i16::min_value()
580                 } else {
581                     exp.try_into().unwrap()
582                 };
583
584                 let res = x.scalbn(exp);
585                 this.write_scalar(Scalar::from_f64(res), dest)?;
586             }
587
588             // Some things needed for `sys::thread` initialization to go through.
589             "signal" | "sigaction" | "sigaltstack" => {
590                 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
591             }
592
593             "sysconf" => {
594                 let name = this.read_scalar(args[0])?.to_i32()?;
595
596                 trace!("sysconf() called with name {}", name);
597                 // TODO: Cache the sysconf integers via Miri's global cache.
598                 let paths = &[
599                     (
600                         &["libc", "_SC_PAGESIZE"],
601                         Scalar::from_int(PAGE_SIZE, dest.layout.size),
602                     ),
603                     (
604                         &["libc", "_SC_GETPW_R_SIZE_MAX"],
605                         Scalar::from_int(-1, dest.layout.size),
606                     ),
607                     (
608                         &["libc", "_SC_NPROCESSORS_ONLN"],
609                         Scalar::from_int(NUM_CPUS, dest.layout.size),
610                     ),
611                 ];
612                 let mut result = None;
613                 for &(path, path_value) in paths {
614                     if let Some(val) = this.eval_path_scalar(path)? {
615                         let val = val.to_i32()?;
616                         if val == name {
617                             result = Some(path_value);
618                             break;
619                         }
620                     }
621                 }
622                 if let Some(result) = result {
623                     this.write_scalar(result, dest)?;
624                 } else {
625                     throw_unsup_format!("Unimplemented sysconf name: {}", name)
626                 }
627             }
628
629             "sched_getaffinity" => {
630                 // Return an error; `num_cpus` then falls back to `sysconf`.
631                 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
632             }
633
634             "isatty" => {
635                 this.write_null(dest)?;
636             }
637
638             // Hook pthread calls that go to the thread-local storage memory subsystem.
639             "pthread_key_create" => {
640                 let key_place = this.deref_operand(args[0])?;
641
642                 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
643                 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
644                     Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
645                     None => None,
646                 };
647
648                 // Figure out how large a pthread TLS key actually is.
649                 // This is `libc::pthread_key_t`.
650                 let key_type = args[0].layout.ty
651                     .builtin_deref(true)
652                     .ok_or_else(|| err_ub_format!(
653                         "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
654                     ))?
655                     .ty;
656                 let key_layout = this.layout_of(key_type)?;
657
658                 // Create key and write it into the memory where `key_ptr` wants it.
659                 let key = this.machine.tls.create_tls_key(dtor) as u128;
660                 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
661                 {
662                     throw_unsup!(OutOfTls);
663                 }
664
665                 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
666
667                 // Return success (`0`).
668                 this.write_null(dest)?;
669             }
670             "pthread_key_delete" => {
671                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
672                 this.machine.tls.delete_tls_key(key)?;
673                 // Return success (0)
674                 this.write_null(dest)?;
675             }
676             "pthread_getspecific" => {
677                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
678                 let ptr = this.machine.tls.load_tls(key, tcx)?;
679                 this.write_scalar(ptr, dest)?;
680             }
681             "pthread_setspecific" => {
682                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
683                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
684                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
685
686                 // Return success (`0`).
687                 this.write_null(dest)?;
688             }
689
690             // Stack size/address stuff.
691             "pthread_attr_init"
692             | "pthread_attr_destroy"
693             | "pthread_self"
694             | "pthread_attr_setstacksize" => {
695                 this.write_null(dest)?;
696             }
697             "pthread_attr_getstack" => {
698                 let addr_place = this.deref_operand(args[1])?;
699                 let size_place = this.deref_operand(args[2])?;
700
701                 this.write_scalar(
702                     Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
703                     addr_place.into(),
704                 )?;
705                 this.write_scalar(
706                     Scalar::from_uint(STACK_SIZE, size_place.layout.size),
707                     size_place.into(),
708                 )?;
709
710                 // Return success (`0`).
711                 this.write_null(dest)?;
712             }
713
714             // We don't support threading. (Also for Windows.)
715             "pthread_create" | "CreateThread" => {
716                 throw_unsup_format!("Miri does not support threading");
717             }
718
719             // Stub out calls for condvar, mutex and rwlock, to just return `0`.
720             "pthread_mutexattr_init"
721             | "pthread_mutexattr_settype"
722             | "pthread_mutex_init"
723             | "pthread_mutexattr_destroy"
724             | "pthread_mutex_lock"
725             | "pthread_mutex_unlock"
726             | "pthread_mutex_destroy"
727             | "pthread_rwlock_rdlock"
728             | "pthread_rwlock_unlock"
729             | "pthread_rwlock_wrlock"
730             | "pthread_rwlock_destroy"
731             | "pthread_condattr_init"
732             | "pthread_condattr_setclock"
733             | "pthread_cond_init"
734             | "pthread_condattr_destroy"
735             | "pthread_cond_destroy" => {
736                 this.write_null(dest)?;
737             }
738
739             // We don't support fork so we don't have to do anything for atfork.
740             "pthread_atfork" => {
741                 this.write_null(dest)?;
742             }
743
744             "mmap" => {
745                 // 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.
746                 let addr = this.read_scalar(args[0])?.not_undef()?;
747                 this.write_scalar(addr, dest)?;
748             }
749             "mprotect" => {
750                 this.write_null(dest)?;
751             }
752
753             // macOS API stubs.
754             "pthread_attr_get_np" | "pthread_getattr_np" => {
755                 this.write_null(dest)?;
756             }
757             "pthread_get_stackaddr_np" => {
758                 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
759                 this.write_scalar(stack_addr, dest)?;
760             }
761             "pthread_get_stacksize_np" => {
762                 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
763                 this.write_scalar(stack_size, dest)?;
764             }
765             "_tlv_atexit" => {
766                 // FIXME: register the destructor.
767             }
768             "_NSGetArgc" => {
769                 this.write_scalar(this.machine.argc.expect("machine must be initialized"), dest)?;
770             }
771             "_NSGetArgv" => {
772                 this.write_scalar(this.machine.argv.expect("machine must be initialized"), dest)?;
773             }
774             "SecRandomCopyBytes" => {
775                 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
776                 let ptr = this.read_scalar(args[2])?.not_undef()?;
777                 this.gen_random(ptr, len as usize)?;
778                 this.write_null(dest)?;
779             }
780
781             // Windows API stubs.
782             // HANDLE = isize
783             // DWORD = ULONG = u32
784             // BOOL = i32
785             "GetProcessHeap" => {
786                 // Just fake a HANDLE
787                 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
788             }
789             "HeapAlloc" => {
790                 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
791                 let flags = this.read_scalar(args[1])?.to_u32()?;
792                 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
793                 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
794                 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
795                 this.write_scalar(res, dest)?;
796             }
797             "HeapFree" => {
798                 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
799                 let _flags = this.read_scalar(args[1])?.to_u32()?;
800                 let ptr = this.read_scalar(args[2])?.not_undef()?;
801                 this.free(ptr, MiriMemoryKind::WinHeap)?;
802                 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
803             }
804             "HeapReAlloc" => {
805                 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
806                 let _flags = this.read_scalar(args[1])?.to_u32()?;
807                 let ptr = this.read_scalar(args[2])?.not_undef()?;
808                 let size = this.read_scalar(args[3])?.to_machine_usize(this)?;
809                 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
810                 this.write_scalar(res, dest)?;
811             }
812
813             "SetLastError" => {
814                 this.set_last_error(this.read_scalar(args[0])?.not_undef()?)?;
815             }
816             "GetLastError" => {
817                 let last_error = this.get_last_error()?;
818                 this.write_scalar(last_error, dest)?;
819             }
820
821             "AddVectoredExceptionHandler" => {
822                 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
823                 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
824             }
825             "InitializeCriticalSection"
826             | "EnterCriticalSection"
827             | "LeaveCriticalSection"
828             | "DeleteCriticalSection" => {
829                 // Nothing to do, not even a return value.
830             }
831             "GetModuleHandleW"
832             | "GetProcAddress"
833             | "TryEnterCriticalSection"
834             | "GetConsoleScreenBufferInfo"
835             | "SetConsoleTextAttribute" => {
836                 // Pretend these do not exist / nothing happened, by returning zero.
837                 this.write_null(dest)?;
838             }
839             "GetSystemInfo" => {
840                 let system_info = this.deref_operand(args[0])?;
841                 // Initialize with `0`.
842                 this.memory
843                     .write_bytes(system_info.ptr, iter::repeat(0u8).take(system_info.layout.size.bytes() as usize))?;
844                 // Set number of processors.
845                 let dword_size = Size::from_bytes(4);
846                 let num_cpus = this.mplace_field(system_info, 6)?;
847                 this.write_scalar(
848                     Scalar::from_int(NUM_CPUS, dword_size),
849                     num_cpus.into(),
850                 )?;
851             }
852
853             "TlsAlloc" => {
854                 // This just creates a key; Windows does not natively support TLS destructors.
855
856                 // Create key and return it.
857                 let key = this.machine.tls.create_tls_key(None) as u128;
858
859                 // Figure out how large a TLS key actually is. This is `c::DWORD`.
860                 if dest.layout.size.bits() < 128
861                     && key >= (1u128 << dest.layout.size.bits() as u128)
862                 {
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_machine_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
898                         .memory
899                         .read_bytes(buf, Size::from_bytes(u64::from(n)))?;
900                     let res = if handle == -11 {
901                         io::stdout().write(buf_cont)
902                     } else {
903                         io::stderr().write(buf_cont)
904                     };
905                     res.ok().map(|n| n as u32)
906                 } else {
907                     eprintln!("Miri: Ignored output to handle {}", handle);
908                     // Pretend it all went well.
909                     Some(n)
910                 };
911                 // If there was no error, write back how much was written.
912                 if let Some(n) = written {
913                     this.write_scalar(Scalar::from_u32(n), written_place.into())?;
914                 }
915                 // Return whether this was a success.
916                 this.write_scalar(
917                     Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
918                     dest,
919                 )?;
920             }
921             "GetConsoleMode" => {
922                 // Everything is a pipe.
923                 this.write_null(dest)?;
924             }
925             "GetEnvironmentVariableW" => {
926                 // This is not the env var you are looking for.
927                 this.set_last_error(Scalar::from_u32(203))?; // ERROR_ENVVAR_NOT_FOUND
928                 this.write_null(dest)?;
929             }
930             "GetCommandLineW" => {
931                 this.write_scalar(this.machine.cmd_line.expect("machine must be initialized"), dest)?;
932             }
933             // The actual name of 'RtlGenRandom'
934             "SystemFunction036" => {
935                 let ptr = this.read_scalar(args[0])?.not_undef()?;
936                 let len = this.read_scalar(args[1])?.to_u32()?;
937                 this.gen_random(ptr, len as usize)?;
938                 this.write_scalar(Scalar::from_bool(true), dest)?;
939             }
940
941             // We can't execute anything else.
942             _ => throw_unsup_format!("can't call foreign function: {}", link_name),
943         }
944
945         this.dump_place(*dest);
946         this.go_to_block(ret);
947         Ok(None)
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(
953         &mut self,
954         path: &[&str],
955     ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
956         let this = self.eval_context_mut();
957         if let Ok(instance) = this.resolve_path(path) {
958             let cid = GlobalId {
959                 instance,
960                 promoted: None,
961             };
962             let const_val = this.const_eval_raw(cid)?;
963             let const_val = this.read_scalar(const_val.into())?;
964             return Ok(Some(const_val));
965         }
966         return Ok(None);
967     }
968 }
969
970 // Shims the linux 'getrandom()' syscall.
971 fn linux_getrandom<'tcx>(
972     this: &mut MiriEvalContext<'_, 'tcx>,
973     args: &[OpTy<'tcx, Tag>],
974     dest: PlaceTy<'tcx, Tag>,
975 ) -> InterpResult<'tcx> {
976     let ptr = this.read_scalar(args[0])?.not_undef()?;
977     let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
978
979     // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
980     // neither of which have any effect on our current PRNG.
981     let _flags = this.read_scalar(args[2])?.to_i32()?;
982
983     this.gen_random(ptr, len as usize)?;
984     this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;
985     Ok(())
986 }