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