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