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