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