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