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