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