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