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