]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items.rs
Support unwinding after a panic
[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         dest: Option<PlaceTy<'tcx, Tag>>,
118         ret: Option<mir::BasicBlock>,
119         _unwind: Option<mir::BasicBlock>
120     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
121         let this = self.eval_context_mut();
122         let attrs = this.tcx.get_attrs(def_id);
123         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
124             Some(name) => name.as_str(),
125             None => this.tcx.item_name(def_id).as_str(),
126         };
127         // Strip linker suffixes (seen on 32-bit macOS).
128         let link_name = link_name.trim_end_matches("$UNIX2003");
129         let tcx = &{ this.tcx.tcx };
130
131         // First: functions that diverge.
132         match link_name {
133             // Note that this matches calls to the *foreign* item "__rust_start_panic" -
134             // that is, calls `extern "Rust" { fn __rust_start_panic(...) }`
135             // We forward this to the underlying *implementation* in "libpanic_unwind"
136             "__rust_start_panic" => {
137                 let start_panic_instance = this.resolve_path(&["panic_unwind", "__rust_start_panic"])?;
138                 return Ok(Some(this.load_mir(start_panic_instance.def, None)?));
139             }
140
141             // During a normal (non-Miri) compilation,
142             // this gets resolved to the '#[panic_handler]` function at link time,
143             // which corresponds to the function with the `#[panic_handler]` attribute.
144             //
145             // Since we're interpreting mir, we forward it to the implementation of `panic_impl`
146             //
147             // This is used by libcore to forward panics to the actual
148             // panic impl
149             "panic_impl" => {
150                 let panic_impl_id = this.tcx.lang_items().panic_impl().unwrap();
151                 let panic_impl_instance = ty::Instance::mono(*this.tcx, panic_impl_id);
152                 return Ok(Some(this.load_mir(panic_impl_instance.def, None)?));
153             }
154             "exit" | "ExitProcess" => {
155                 // it's really u32 for ExitProcess, but we have to put it into the `Exit` error variant anyway
156                 let code = this.read_scalar(args[0])?.to_i32()?;
157                 return Err(InterpError::Exit(code).into());
158             }
159             _ => {
160                 if dest.is_none() {
161                     throw_unsup_format!("can't call (diverging) foreign function: {}", link_name);
162                 }
163             }
164         }
165
166         // Next: functions that assume a ret and dest.
167         let dest = dest.expect("we already checked for a dest");
168         let ret = ret.expect("dest is `Some` but ret is `None`");
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(Scalar::Ptr(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(Scalar::Ptr(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(Scalar::Ptr(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(Scalar::Ptr(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                 // `libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)`
307                 // is called if a `HashMap` is created the regular way (e.g. HashMap<K, V>).
308                 match this.read_scalar(args[0])?.to_machine_usize(this)? {
309                     id if id == sys_getrandom => {
310                         // The first argument is the syscall id,
311                         // so skip over it.
312                         linux_getrandom(this, &args[1..], dest)?;
313                     }
314                     id => throw_unsup_format!("miri does not support syscall ID {}", id),
315                 }
316             }
317
318             "getrandom" => {
319                 linux_getrandom(this, args, dest)?;
320             }
321
322             "dlsym" => {
323                 let _handle = this.read_scalar(args[0])?;
324                 let symbol = this.read_scalar(args[1])?.not_undef()?;
325                 let symbol_name = this.memory.read_c_str(symbol)?;
326                 let err = format!("bad c unicode symbol: {:?}", symbol_name);
327                 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
328                 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
329                     let ptr = this.memory.create_fn_alloc(FnVal::Other(dlsym));
330                     this.write_scalar(Scalar::from(ptr), dest)?;
331                 } else {
332                     this.write_null(dest)?;
333                 }
334             }
335
336             "__rust_maybe_catch_panic" => {
337                 this.handle_catch_panic(args, dest, ret)?;
338                 return Ok(None)
339             }
340
341             "memcmp" => {
342                 let left = this.read_scalar(args[0])?.not_undef()?;
343                 let right = this.read_scalar(args[1])?.not_undef()?;
344                 let n = Size::from_bytes(this.read_scalar(args[2])?.to_machine_usize(this)?);
345
346                 let result = {
347                     let left_bytes = this.memory.read_bytes(left, n)?;
348                     let right_bytes = this.memory.read_bytes(right, n)?;
349
350                     use std::cmp::Ordering::*;
351                     match left_bytes.cmp(right_bytes) {
352                         Less => -1i32,
353                         Equal => 0,
354                         Greater => 1,
355                     }
356                 };
357
358                 this.write_scalar(Scalar::from_int(result, Size::from_bits(32)), dest)?;
359             }
360
361             "memrchr" => {
362                 let ptr = this.read_scalar(args[0])?.not_undef()?;
363                 let val = this.read_scalar(args[1])?.to_i32()? as u8;
364                 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
365                 if let Some(idx) = this
366                     .memory
367                     .read_bytes(ptr, Size::from_bytes(num))?
368                     .iter()
369                     .rev()
370                     .position(|&c| c == val)
371                 {
372                     let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
373                     this.write_scalar(new_ptr, dest)?;
374                 } else {
375                     this.write_null(dest)?;
376                 }
377             }
378
379             "memchr" => {
380                 let ptr = this.read_scalar(args[0])?.not_undef()?;
381                 let val = this.read_scalar(args[1])?.to_i32()? as u8;
382                 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
383                 let idx = this
384                     .memory
385                     .read_bytes(ptr, Size::from_bytes(num))?
386                     .iter()
387                     .position(|&c| c == val);
388                 if let Some(idx) = idx {
389                     let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
390                     this.write_scalar(new_ptr, dest)?;
391                 } else {
392                     this.write_null(dest)?;
393                 }
394             }
395
396             "__errno_location" | "__error" => {
397                 let errno_place = this.machine.last_error.unwrap();
398                 this.write_scalar(errno_place.to_ref().to_scalar()?, dest)?;
399             }
400
401             "getenv" => {
402                 let result = this.getenv(args[0])?;
403                 this.write_scalar(result, dest)?;
404             }
405
406             "unsetenv" => {
407                 let result = this.unsetenv(args[0])?;
408                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
409             }
410
411             "setenv" => {
412                 let result = this.setenv(args[0], args[1])?;
413                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
414             }
415
416             "getcwd" => {
417                 let result = this.getcwd(args[0], args[1])?;
418                 this.write_scalar(result, dest)?;
419             }
420
421             "chdir" => {
422                 let result = this.chdir(args[0])?;
423                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
424             }
425
426             "open" | "open64" => {
427                 let result = this.open(args[0], args[1])?;
428                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
429             }
430
431             "fcntl" => {
432                 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
433                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
434             }
435
436             "close" | "close$NOCANCEL" => {
437                 let result = this.close(args[0])?;
438                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
439             }
440
441             "read" => {
442                 let result = this.read(args[0], args[1], args[2])?;
443                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
444             }
445
446             "write" => {
447                 let fd = this.read_scalar(args[0])?.to_i32()?;
448                 let buf = this.read_scalar(args[1])?.not_undef()?;
449                 let n = this.read_scalar(args[2])?.to_machine_usize(tcx)?;
450                 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
451                 let result = if fd == 1 || fd == 2 {
452                     // stdout/stderr
453                     use std::io::{self, Write};
454
455                     let buf_cont = this.memory.read_bytes(buf, Size::from_bytes(n))?;
456                     // We need to flush to make sure this actually appears on the screen
457                     let res = if fd == 1 {
458                         // Stdout is buffered, flush to make sure it appears on the screen.
459                         // This is the write() syscall of the interpreted program, we want it
460                         // to correspond to a write() syscall on the host -- there is no good
461                         // in adding extra buffering here.
462                         let res = io::stdout().write(buf_cont);
463                         io::stdout().flush().unwrap();
464                         res
465                     } else {
466                         // No need to flush, stderr is not buffered.
467                         io::stderr().write(buf_cont)
468                     };
469                     match res {
470                         Ok(n) => n as i64,
471                         Err(_) => -1,
472                     }
473                 } else {
474                     this.write(args[0], args[1], args[2])?
475                 };
476                 // Now, `result` is the value we return back to the program.
477                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
478             }
479
480             "unlink" => {
481                 let result = this.unlink(args[0])?;
482                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
483             }
484
485             "clock_gettime" => {
486                 let result = this.clock_gettime(args[0], args[1])?;
487                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
488             }
489
490             "gettimeofday" => {
491                 let result = this.gettimeofday(args[0], args[1])?;
492                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
493             }
494
495             "strlen" => {
496                 let ptr = this.read_scalar(args[0])?.not_undef()?;
497                 let n = this.memory.read_c_str(ptr)?.len();
498                 this.write_scalar(Scalar::from_uint(n as u64, dest.layout.size), dest)?;
499             }
500
501             // math functions
502             "cbrtf" | "coshf" | "sinhf" | "tanf" => {
503                 // FIXME: Using host floats.
504                 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
505                 let f = match link_name {
506                     "cbrtf" => f.cbrt(),
507                     "coshf" => f.cosh(),
508                     "sinhf" => f.sinh(),
509                     "tanf" => f.tan(),
510                     _ => bug!(),
511                 };
512                 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
513             }
514             // underscore case for windows
515             "_hypotf" | "hypotf" | "atan2f" => {
516                 // FIXME: Using host floats.
517                 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
518                 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
519                 let n = match link_name {
520                     "_hypotf" | "hypotf" => f1.hypot(f2),
521                     "atan2f" => f1.atan2(f2),
522                     _ => bug!(),
523                 };
524                 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
525             }
526
527             "cbrt" | "cosh" | "sinh" | "tan" => {
528                 // FIXME: Using host floats.
529                 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
530                 let f = match link_name {
531                     "cbrt" => f.cbrt(),
532                     "cosh" => f.cosh(),
533                     "sinh" => f.sinh(),
534                     "tan" => f.tan(),
535                     _ => bug!(),
536                 };
537                 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
538             }
539             // underscore case for windows, here and below
540             // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
541             "_hypot" | "hypot" | "atan2" => {
542                 // FIXME: Using host floats.
543                 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
544                 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
545                 let n = match link_name {
546                     "_hypot" | "hypot" => f1.hypot(f2),
547                     "atan2" => f1.atan2(f2),
548                     _ => bug!(),
549                 };
550                 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
551             }
552             // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
553             "_ldexp" | "ldexp" | "scalbn" => {
554                 let x = this.read_scalar(args[0])?.to_f64()?;
555                 let exp = this.read_scalar(args[1])?.to_i32()?;
556
557                 // Saturating cast to i16. Even those are outside the valid exponent range to
558                 // `scalbn` below will do its over/underflow handling.
559                 let exp = if exp > i16::max_value() as i32 {
560                     i16::max_value()
561                 } else if exp < i16::min_value() as i32 {
562                     i16::min_value()
563                 } else {
564                     exp.try_into().unwrap()
565                 };
566
567                 let res = x.scalbn(exp);
568                 this.write_scalar(Scalar::from_f64(res), dest)?;
569             }
570
571             // Some things needed for `sys::thread` initialization to go through.
572             "signal" | "sigaction" | "sigaltstack" => {
573                 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
574             }
575
576             "sysconf" => {
577                 let name = this.read_scalar(args[0])?.to_i32()?;
578
579                 trace!("sysconf() called with name {}", name);
580                 // TODO: Cache the sysconf integers via Miri's global cache.
581                 let paths = &[
582                     (
583                         &["libc", "_SC_PAGESIZE"],
584                         Scalar::from_int(PAGE_SIZE, dest.layout.size),
585                     ),
586                     (
587                         &["libc", "_SC_GETPW_R_SIZE_MAX"],
588                         Scalar::from_int(-1, dest.layout.size),
589                     ),
590                     (
591                         &["libc", "_SC_NPROCESSORS_ONLN"],
592                         Scalar::from_int(NUM_CPUS, dest.layout.size),
593                     ),
594                 ];
595                 let mut result = None;
596                 for &(path, path_value) in paths {
597                     if let Some(val) = this.eval_path_scalar(path)? {
598                         let val = val.to_i32()?;
599                         if val == name {
600                             result = Some(path_value);
601                             break;
602                         }
603                     }
604                 }
605                 if let Some(result) = result {
606                     this.write_scalar(result, dest)?;
607                 } else {
608                     throw_unsup_format!("Unimplemented sysconf name: {}", name)
609                 }
610             }
611
612             "sched_getaffinity" => {
613                 // Return an error; `num_cpus` then falls back to `sysconf`.
614                 this.write_scalar(Scalar::from_int(-1, dest.layout.size), dest)?;
615             }
616
617             "isatty" => {
618                 this.write_null(dest)?;
619             }
620
621             // Hook pthread calls that go to the thread-local storage memory subsystem.
622             "pthread_key_create" => {
623                 let key_place = this.deref_operand(args[0])?;
624
625                 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
626                 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
627                     Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
628                     None => None,
629                 };
630
631                 // Figure out how large a pthread TLS key actually is.
632                 // This is `libc::pthread_key_t`.
633                 let key_type = args[0].layout.ty
634                     .builtin_deref(true)
635                     .ok_or_else(|| err_ub_format!(
636                         "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
637                     ))?
638                     .ty;
639                 let key_layout = this.layout_of(key_type)?;
640
641                 // Create key and write it into the memory where `key_ptr` wants it.
642                 let key = this.machine.tls.create_tls_key(dtor) as u128;
643                 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
644                 {
645                     throw_unsup!(OutOfTls);
646                 }
647
648                 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
649
650                 // Return success (`0`).
651                 this.write_null(dest)?;
652             }
653             "pthread_key_delete" => {
654                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
655                 this.machine.tls.delete_tls_key(key)?;
656                 // Return success (0)
657                 this.write_null(dest)?;
658             }
659             "pthread_getspecific" => {
660                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
661                 let ptr = this.machine.tls.load_tls(key, tcx)?;
662                 this.write_scalar(ptr, dest)?;
663             }
664             "pthread_setspecific" => {
665                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
666                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
667                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
668
669                 // Return success (`0`).
670                 this.write_null(dest)?;
671             }
672
673             // Stack size/address stuff.
674             "pthread_attr_init"
675             | "pthread_attr_destroy"
676             | "pthread_self"
677             | "pthread_attr_setstacksize" => {
678                 this.write_null(dest)?;
679             }
680             "pthread_attr_getstack" => {
681                 let addr_place = this.deref_operand(args[1])?;
682                 let size_place = this.deref_operand(args[2])?;
683
684                 this.write_scalar(
685                     Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
686                     addr_place.into(),
687                 )?;
688                 this.write_scalar(
689                     Scalar::from_uint(STACK_SIZE, size_place.layout.size),
690                     size_place.into(),
691                 )?;
692
693                 // Return success (`0`).
694                 this.write_null(dest)?;
695             }
696
697             // We don't support threading. (Also for Windows.)
698             "pthread_create" | "CreateThread" => {
699                 throw_unsup_format!("Miri does not support threading");
700             }
701
702             // Stub out calls for condvar, mutex and rwlock, to just return `0`.
703             "pthread_mutexattr_init"
704             | "pthread_mutexattr_settype"
705             | "pthread_mutex_init"
706             | "pthread_mutexattr_destroy"
707             | "pthread_mutex_lock"
708             | "pthread_mutex_unlock"
709             | "pthread_mutex_destroy"
710             | "pthread_rwlock_rdlock"
711             | "pthread_rwlock_unlock"
712             | "pthread_rwlock_wrlock"
713             | "pthread_rwlock_destroy"
714             | "pthread_condattr_init"
715             | "pthread_condattr_setclock"
716             | "pthread_cond_init"
717             | "pthread_condattr_destroy"
718             | "pthread_cond_destroy" => {
719                 this.write_null(dest)?;
720             }
721
722             // We don't support fork so we don't have to do anything for atfork.
723             "pthread_atfork" => {
724                 this.write_null(dest)?;
725             }
726
727             "mmap" => {
728                 // 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.
729                 let addr = this.read_scalar(args[0])?.not_undef()?;
730                 this.write_scalar(addr, dest)?;
731             }
732             "mprotect" => {
733                 this.write_null(dest)?;
734             }
735
736             // macOS API stubs.
737             "pthread_attr_get_np" | "pthread_getattr_np" => {
738                 this.write_null(dest)?;
739             }
740             "pthread_get_stackaddr_np" => {
741                 let stack_addr = Scalar::from_uint(STACK_ADDR, dest.layout.size);
742                 this.write_scalar(stack_addr, dest)?;
743             }
744             "pthread_get_stacksize_np" => {
745                 let stack_size = Scalar::from_uint(STACK_SIZE, dest.layout.size);
746                 this.write_scalar(stack_size, dest)?;
747             }
748             "_tlv_atexit" => {
749                 // FIXME: register the destructor.
750             }
751             "_NSGetArgc" => {
752                 this.write_scalar(this.machine.argc.expect("machine must be initialized"), dest)?;
753             }
754             "_NSGetArgv" => {
755                 this.write_scalar(this.machine.argv.expect("machine must be initialized"), dest)?;
756             }
757             "SecRandomCopyBytes" => {
758                 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
759                 let ptr = this.read_scalar(args[2])?.not_undef()?;
760                 this.gen_random(ptr, len as usize)?;
761                 this.write_null(dest)?;
762             }
763
764             // Windows API stubs.
765             // HANDLE = isize
766             // DWORD = ULONG = u32
767             // BOOL = i32
768             "GetProcessHeap" => {
769                 // Just fake a HANDLE
770                 this.write_scalar(Scalar::from_int(1, this.pointer_size()), dest)?;
771             }
772             "HeapAlloc" => {
773                 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
774                 let flags = this.read_scalar(args[1])?.to_u32()?;
775                 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
776                 let zero_init = (flags & 0x00000008) != 0; // HEAP_ZERO_MEMORY
777                 let res = this.malloc(size, zero_init, MiriMemoryKind::WinHeap);
778                 this.write_scalar(res, dest)?;
779             }
780             "HeapFree" => {
781                 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
782                 let _flags = this.read_scalar(args[1])?.to_u32()?;
783                 let ptr = this.read_scalar(args[2])?.not_undef()?;
784                 this.free(ptr, MiriMemoryKind::WinHeap)?;
785                 this.write_scalar(Scalar::from_int(1, Size::from_bytes(4)), dest)?;
786             }
787             "HeapReAlloc" => {
788                 let _handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
789                 let _flags = this.read_scalar(args[1])?.to_u32()?;
790                 let ptr = this.read_scalar(args[2])?.not_undef()?;
791                 let size = this.read_scalar(args[3])?.to_machine_usize(this)?;
792                 let res = this.realloc(ptr, size, MiriMemoryKind::WinHeap)?;
793                 this.write_scalar(res, dest)?;
794             }
795
796             "SetLastError" => {
797                 this.set_last_error(this.read_scalar(args[0])?.not_undef()?)?;
798             }
799             "GetLastError" => {
800                 let last_error = this.get_last_error()?;
801                 this.write_scalar(last_error, dest)?;
802             }
803
804             "AddVectoredExceptionHandler" => {
805                 // Any non zero value works for the stdlib. This is just used for stack overflows anyway.
806                 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
807             }
808             "InitializeCriticalSection"
809             | "EnterCriticalSection"
810             | "LeaveCriticalSection"
811             | "DeleteCriticalSection" => {
812                 // Nothing to do, not even a return value.
813             }
814             "GetModuleHandleW"
815             | "GetProcAddress"
816             | "TryEnterCriticalSection"
817             | "GetConsoleScreenBufferInfo"
818             | "SetConsoleTextAttribute" => {
819                 // Pretend these do not exist / nothing happened, by returning zero.
820                 this.write_null(dest)?;
821             }
822             "GetSystemInfo" => {
823                 let system_info = this.deref_operand(args[0])?;
824                 // Initialize with `0`.
825                 this.memory
826                     .write_bytes(system_info.ptr, iter::repeat(0u8).take(system_info.layout.size.bytes() as usize))?;
827                 // Set number of processors.
828                 let dword_size = Size::from_bytes(4);
829                 let num_cpus = this.mplace_field(system_info, 6)?;
830                 this.write_scalar(
831                     Scalar::from_int(NUM_CPUS, dword_size),
832                     num_cpus.into(),
833                 )?;
834             }
835
836             "TlsAlloc" => {
837                 // This just creates a key; Windows does not natively support TLS destructors.
838
839                 // Create key and return it.
840                 let key = this.machine.tls.create_tls_key(None) as u128;
841
842                 // Figure out how large a TLS key actually is. This is `c::DWORD`.
843                 if dest.layout.size.bits() < 128
844                     && key >= (1u128 << dest.layout.size.bits() as u128)
845                 {
846                     throw_unsup!(OutOfTls);
847                 }
848                 this.write_scalar(Scalar::from_uint(key, dest.layout.size), dest)?;
849             }
850             "TlsGetValue" => {
851                 let key = this.read_scalar(args[0])?.to_u32()? as u128;
852                 let ptr = this.machine.tls.load_tls(key, tcx)?;
853                 this.write_scalar(ptr, dest)?;
854             }
855             "TlsSetValue" => {
856                 let key = this.read_scalar(args[0])?.to_u32()? as u128;
857                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
858                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
859
860                 // Return success (`1`).
861                 this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?;
862             }
863             "GetStdHandle" => {
864                 let which = this.read_scalar(args[0])?.to_i32()?;
865                 // We just make this the identity function, so we know later in `WriteFile`
866                 // which one it is.
867                 this.write_scalar(Scalar::from_int(which, this.pointer_size()), dest)?;
868             }
869             "WriteFile" => {
870                 let handle = this.read_scalar(args[0])?.to_machine_isize(this)?;
871                 let buf = this.read_scalar(args[1])?.not_undef()?;
872                 let n = this.read_scalar(args[2])?.to_u32()?;
873                 let written_place = this.deref_operand(args[3])?;
874                 // Spec says to always write `0` first.
875                 this.write_null(written_place.into())?;
876                 let written = if handle == -11 || handle == -12 {
877                     // stdout/stderr
878                     use std::io::{self, Write};
879
880                     let buf_cont = this
881                         .memory
882                         .read_bytes(buf, Size::from_bytes(u64::from(n)))?;
883                     let res = if handle == -11 {
884                         io::stdout().write(buf_cont)
885                     } else {
886                         io::stderr().write(buf_cont)
887                     };
888                     res.ok().map(|n| n as u32)
889                 } else {
890                     eprintln!("Miri: Ignored output to handle {}", handle);
891                     // Pretend it all went well.
892                     Some(n)
893                 };
894                 // If there was no error, write back how much was written.
895                 if let Some(n) = written {
896                     this.write_scalar(Scalar::from_u32(n), written_place.into())?;
897                 }
898                 // Return whether this was a success.
899                 this.write_scalar(
900                     Scalar::from_int(if written.is_some() { 1 } else { 0 }, dest.layout.size),
901                     dest,
902                 )?;
903             }
904             "GetConsoleMode" => {
905                 // Everything is a pipe.
906                 this.write_null(dest)?;
907             }
908             "GetEnvironmentVariableW" => {
909                 // This is not the env var you are looking for.
910                 this.set_last_error(Scalar::from_u32(203))?; // ERROR_ENVVAR_NOT_FOUND
911                 this.write_null(dest)?;
912             }
913             "GetCommandLineW" => {
914                 this.write_scalar(this.machine.cmd_line.expect("machine must be initialized"), dest)?;
915             }
916             // The actual name of 'RtlGenRandom'
917             "SystemFunction036" => {
918                 let ptr = this.read_scalar(args[0])?.not_undef()?;
919                 let len = this.read_scalar(args[1])?.to_u32()?;
920                 this.gen_random(ptr, len as usize)?;
921                 this.write_scalar(Scalar::from_bool(true), dest)?;
922             }
923
924             // We can't execute anything else.
925             _ => throw_unsup_format!("can't call foreign function: {}", link_name),
926         }
927
928         this.goto_block(Some(ret))?;
929         this.dump_place(*dest);
930         Ok(None)
931     }
932
933     /// Evaluates the scalar at the specified path. Returns Some(val)
934     /// if the path could be resolved, and None otherwise
935     fn eval_path_scalar(
936         &mut self,
937         path: &[&str],
938     ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
939         let this = self.eval_context_mut();
940         if let Ok(instance) = this.resolve_path(path) {
941             let cid = GlobalId {
942                 instance,
943                 promoted: None,
944             };
945             let const_val = this.const_eval_raw(cid)?;
946             let const_val = this.read_scalar(const_val.into())?;
947             return Ok(Some(const_val));
948         }
949         return Ok(None);
950     }
951 }
952
953 // Shims the linux 'getrandom()' syscall.
954 fn linux_getrandom<'tcx>(
955     this: &mut MiriEvalContext<'_, 'tcx>,
956     args: &[OpTy<'tcx, Tag>],
957     dest: PlaceTy<'tcx, Tag>,
958 ) -> InterpResult<'tcx> {
959     let ptr = this.read_scalar(args[0])?.not_undef()?;
960     let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
961
962     // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
963     // neither of which have any effect on our current PRNG.
964     let _flags = this.read_scalar(args[2])?.to_i32()?;
965
966     this.gen_random(ptr, len as usize)?;
967     this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;
968     Ok(())
969 }