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