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