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