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