]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items.rs
Auto merge of #1786 - RalfJung:rustup, r=RalfJung
[rust.git] / src / shims / foreign_items.rs
1 use std::{convert::{TryInto, TryFrom}, iter};
2
3 use log::trace;
4
5 use rustc_hir::def_id::DefId;
6 use rustc_middle::mir;
7 use rustc_target::{abi::{Align, Size}, spec::{PanicStrategy, abi::Abi}};
8 use rustc_middle::ty;
9 use rustc_apfloat::Float;
10 use rustc_span::symbol::sym;
11
12 use crate::*;
13 use super::backtrace::EvalContextExt as _;
14 use helpers::{check_abi, check_arg_count};
15
16 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
17 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
18     /// Returns the minimum alignment for the target architecture for allocations of the given size.
19     fn min_align(&self, size: u64, kind: MiriMemoryKind) -> Align {
20         let this = self.eval_context_ref();
21         // List taken from `libstd/sys_common/alloc.rs`.
22         let min_align = match this.tcx.sess.target.arch.as_str() {
23             "x86" | "arm" | "mips" | "powerpc" | "powerpc64" | "asmjs" | "wasm32" => 8,
24             "x86_64" | "aarch64" | "mips64" | "s390x" | "sparc64" => 16,
25             arch => bug!("Unsupported target architecture: {}", arch),
26         };
27         // Windows always aligns, even small allocations.
28         // Source: <https://support.microsoft.com/en-us/help/286470/how-to-use-pageheap-exe-in-windows-xp-windows-2000-and-windows-server>
29         // But jemalloc does not, so for the C heap we only align if the allocation is sufficiently big.
30         if kind == MiriMemoryKind::WinHeap || size >= min_align {
31             return Align::from_bytes(min_align).unwrap();
32         }
33         // We have `size < min_align`. Round `size` *down* to the next power of two and use that.
34         fn prev_power_of_two(x: u64) -> u64 {
35             let next_pow2 = x.next_power_of_two();
36             if next_pow2 == x {
37                 // x *is* a power of two, just use that.
38                 x
39             } else {
40                 // x is between two powers, so next = 2*prev.
41                 next_pow2 / 2
42             }
43         }
44         Align::from_bytes(prev_power_of_two(size)).unwrap()
45     }
46
47     fn malloc(&mut self, size: u64, zero_init: bool, kind: MiriMemoryKind) -> Scalar<Tag> {
48         let this = self.eval_context_mut();
49         if size == 0 {
50             Scalar::null_ptr(this)
51         } else {
52             let align = this.min_align(size, kind);
53             let ptr = this.memory.allocate(Size::from_bytes(size), align, kind.into());
54             if zero_init {
55                 // We just allocated this, the access is definitely in-bounds.
56                 this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(size as usize)).unwrap();
57             }
58             Scalar::Ptr(ptr)
59         }
60     }
61
62     fn free(&mut self, ptr: Scalar<Tag>, kind: MiriMemoryKind) -> InterpResult<'tcx> {
63         let this = self.eval_context_mut();
64         if !this.is_null(ptr)? {
65             let ptr = this.force_ptr(ptr)?;
66             this.memory.deallocate(ptr, None, kind.into())?;
67         }
68         Ok(())
69     }
70
71     fn realloc(
72         &mut self,
73         old_ptr: Scalar<Tag>,
74         new_size: u64,
75         kind: MiriMemoryKind,
76     ) -> InterpResult<'tcx, Scalar<Tag>> {
77         let this = self.eval_context_mut();
78         let new_align = this.min_align(new_size, kind);
79         if this.is_null(old_ptr)? {
80             if new_size == 0 {
81                 Ok(Scalar::null_ptr(this))
82             } else {
83                 let new_ptr =
84                     this.memory.allocate(Size::from_bytes(new_size), new_align, kind.into());
85                 Ok(Scalar::Ptr(new_ptr))
86             }
87         } else {
88             let old_ptr = this.force_ptr(old_ptr)?;
89             if new_size == 0 {
90                 this.memory.deallocate(old_ptr, None, kind.into())?;
91                 Ok(Scalar::null_ptr(this))
92             } else {
93                 let new_ptr = this.memory.reallocate(
94                     old_ptr,
95                     None,
96                     Size::from_bytes(new_size),
97                     new_align,
98                     kind.into(),
99                 )?;
100                 Ok(Scalar::Ptr(new_ptr))
101             }
102         }
103     }
104
105     /// Emulates calling a foreign item, failing if the item is not supported.
106     /// This function will handle `goto_block` if needed.
107     /// Returns Ok(None) if the foreign item was completely handled
108     /// by this function.
109     /// Returns Ok(Some(body)) if processing the foreign item
110     /// is delegated to another function.
111     #[rustfmt::skip]
112     fn emulate_foreign_item(
113         &mut self,
114         def_id: DefId,
115         abi: Abi,
116         args: &[OpTy<'tcx, Tag>],
117         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
118         unwind: Option<mir::BasicBlock>,
119     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
120         let this = self.eval_context_mut();
121         let attrs = this.tcx.get_attrs(def_id);
122         let link_name = match this.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
123             Some(name) => name.as_str(),
124             None => this.tcx.item_name(def_id).as_str(),
125         };
126         // Strip linker suffixes (seen on 32-bit macOS).
127         let link_name = link_name.trim_end_matches("$UNIX2003");
128         let tcx = this.tcx.tcx;
129
130         // First: functions that diverge.
131         let (dest, ret) = match ret {
132             None => match link_name {
133                 "miri_start_panic" => {
134                     check_abi(abi, Abi::Rust)?;
135                     this.handle_miri_start_panic(args, unwind)?;
136                     return Ok(None);
137                 }
138                 // This matches calls to the foreign item `panic_impl`.
139                 // The implementation is provided by the function with the `#[panic_handler]` attribute.
140                 "panic_impl" => {
141                     check_abi(abi, Abi::Rust)?;
142                     let panic_impl_id = tcx.lang_items().panic_impl().unwrap();
143                     let panic_impl_instance = ty::Instance::mono(tcx, panic_impl_id);
144                     return Ok(Some(&*this.load_mir(panic_impl_instance.def, None)?));
145                 }
146                 | "exit"
147                 | "ExitProcess"
148                 => {
149                     check_abi(abi, if link_name == "exit" { Abi::C { unwind: false } } else { Abi::System { unwind: false } })?;
150                     let &[ref code] = check_arg_count(args)?;
151                     // it's really u32 for ExitProcess, but we have to put it into the `Exit` variant anyway
152                     let code = this.read_scalar(code)?.to_i32()?;
153                     throw_machine_stop!(TerminationInfo::Exit(code.into()));
154                 }
155                 "abort" => {
156                     check_abi(abi, Abi::C { unwind: false })?;
157                     throw_machine_stop!(TerminationInfo::Abort("the program aborted execution".to_owned()))
158                 }
159                 _ => throw_unsup_format!("can't call (diverging) foreign function: {}", link_name),
160             },
161             Some(p) => p,
162         };
163
164         // Second: some functions that we forward to MIR implementations.
165         match link_name {
166             // This matches calls to the foreign item `__rust_start_panic`, that is,
167             // calls to `extern "Rust" { fn __rust_start_panic(...) }`
168             // (and `__rust_panic_cleanup`, respectively).
169             // We forward this to the underlying *implementation* in the panic runtime crate.
170             // Normally, this will be either `libpanic_unwind` or `libpanic_abort`, but it could
171             // also be a custom user-provided implementation via `#![feature(panic_runtime)]`
172             "__rust_start_panic" | "__rust_panic_cleanup" => {
173                 check_abi(abi, Abi::C { unwind: false })?;
174                 // This replicates some of the logic in `inject_panic_runtime`.
175                 // FIXME: is there a way to reuse that logic?
176                 let panic_runtime = match this.tcx.sess.panic_strategy() {
177                     PanicStrategy::Unwind => sym::panic_unwind,
178                     PanicStrategy::Abort => sym::panic_abort,
179                 };
180                 let start_panic_instance =
181                     this.resolve_path(&[&*panic_runtime.as_str(), link_name]);
182                 return Ok(Some(&*this.load_mir(start_panic_instance.def, None)?));
183             }
184             _ => {}
185         }
186
187         // Third: functions that return.
188         if this.emulate_foreign_item_by_name(link_name, abi, args, dest, ret)? {
189             trace!("{:?}", this.dump_place(**dest));
190             this.go_to_block(ret);
191         }
192
193         Ok(None)
194     }
195
196     /// Emulates calling a foreign item using its name, failing if the item is not supported.
197     /// Returns `true` if the caller is expected to jump to the return block, and `false` if
198     /// jumping has already been taken care of.
199     fn emulate_foreign_item_by_name(
200         &mut self,
201         link_name: &str,
202         abi: Abi,
203         args: &[OpTy<'tcx, Tag>],
204         dest: &PlaceTy<'tcx, Tag>,
205         ret: mir::BasicBlock,
206     ) -> InterpResult<'tcx, bool> {
207         let this = self.eval_context_mut();
208
209         // Here we dispatch all the shims for foreign functions. If you have a platform specific
210         // shim, add it to the corresponding submodule.
211         match link_name {
212             // Miri-specific extern functions
213             "miri_static_root" => {
214                 check_abi(abi, Abi::Rust)?;
215                 let &[ref ptr] = check_arg_count(args)?;
216                 let ptr = this.read_scalar(ptr)?.check_init()?;
217                 let ptr = this.force_ptr(ptr)?;
218                 if ptr.offset != Size::ZERO {
219                     throw_unsup_format!("pointer passed to miri_static_root must point to beginning of an allocated block");
220                 }
221                 this.machine.static_roots.push(ptr.alloc_id);
222             }
223
224             // Obtains a Miri backtrace. See the README for details.
225             "miri_get_backtrace" => {
226                 check_abi(abi, Abi::Rust)?;
227                 this.handle_miri_get_backtrace(args, dest)?;
228             }
229
230             // Resolves a Miri backtrace frame. See the README for details.
231             "miri_resolve_frame" => {
232                 check_abi(abi, Abi::Rust)?;
233                 this.handle_miri_resolve_frame(args, dest)?;
234             }
235
236
237             // Standard C allocation
238             "malloc" => {
239                 check_abi(abi, Abi::C { unwind: false })?;
240                 let &[ref size] = check_arg_count(args)?;
241                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
242                 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
243                 this.write_scalar(res, dest)?;
244             }
245             "calloc" => {
246                 check_abi(abi, Abi::C { unwind: false })?;
247                 let &[ref items, ref len] = check_arg_count(args)?;
248                 let items = this.read_scalar(items)?.to_machine_usize(this)?;
249                 let len = this.read_scalar(len)?.to_machine_usize(this)?;
250                 let size =
251                     items.checked_mul(len).ok_or_else(|| err_ub_format!("overflow during calloc size computation"))?;
252                 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
253                 this.write_scalar(res, dest)?;
254             }
255             "free" => {
256                 check_abi(abi, Abi::C { unwind: false })?;
257                 let &[ref ptr] = check_arg_count(args)?;
258                 let ptr = this.read_scalar(ptr)?.check_init()?;
259                 this.free(ptr, MiriMemoryKind::C)?;
260             }
261             "realloc" => {
262                 check_abi(abi, Abi::C { unwind: false })?;
263                 let &[ref old_ptr, ref new_size] = check_arg_count(args)?;
264                 let old_ptr = this.read_scalar(old_ptr)?.check_init()?;
265                 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
266                 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
267                 this.write_scalar(res, dest)?;
268             }
269
270             // Rust allocation
271             // (Usually these would be forwarded to to `#[global_allocator]`; we instead implement a generic
272             // allocation that also checks that all conditions are met, such as not permitting zero-sized allocations.)
273             "__rust_alloc" => {
274                 check_abi(abi, Abi::Rust)?;
275                 let &[ref size, ref align] = check_arg_count(args)?;
276                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
277                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
278                 Self::check_alloc_request(size, align)?;
279                 let ptr = this.memory.allocate(
280                     Size::from_bytes(size),
281                     Align::from_bytes(align).unwrap(),
282                     MiriMemoryKind::Rust.into(),
283                 );
284                 this.write_scalar(ptr, dest)?;
285             }
286             "__rust_alloc_zeroed" => {
287                 check_abi(abi, Abi::Rust)?;
288                 let &[ref size, ref align] = check_arg_count(args)?;
289                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
290                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
291                 Self::check_alloc_request(size, align)?;
292                 let ptr = this.memory.allocate(
293                     Size::from_bytes(size),
294                     Align::from_bytes(align).unwrap(),
295                     MiriMemoryKind::Rust.into(),
296                 );
297                 // We just allocated this, the access is definitely in-bounds.
298                 this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(usize::try_from(size).unwrap())).unwrap();
299                 this.write_scalar(ptr, dest)?;
300             }
301             "__rust_dealloc" => {
302                 check_abi(abi, Abi::Rust)?;
303                 let &[ref ptr, ref old_size, ref align] = check_arg_count(args)?;
304                 let ptr = this.read_scalar(ptr)?.check_init()?;
305                 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
306                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
307                 // No need to check old_size/align; we anyway check that they match the allocation.
308                 let ptr = this.force_ptr(ptr)?;
309                 this.memory.deallocate(
310                     ptr,
311                     Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
312                     MiriMemoryKind::Rust.into(),
313                 )?;
314             }
315             "__rust_realloc" => {
316                 check_abi(abi, Abi::Rust)?;
317                 let &[ref ptr, ref old_size, ref align, ref new_size] = check_arg_count(args)?;
318                 let ptr = this.force_ptr(this.read_scalar(ptr)?.check_init()?)?;
319                 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
320                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
321                 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
322                 Self::check_alloc_request(new_size, align)?;
323                 // No need to check old_size; we anyway check that they match the allocation.
324                 let align = Align::from_bytes(align).unwrap();
325                 let new_ptr = this.memory.reallocate(
326                     ptr,
327                     Some((Size::from_bytes(old_size), align)),
328                     Size::from_bytes(new_size),
329                     align,
330                     MiriMemoryKind::Rust.into(),
331                 )?;
332                 this.write_scalar(new_ptr, dest)?;
333             }
334
335             // C memory handling functions
336             "memcmp" => {
337                 check_abi(abi, Abi::C { unwind: false })?;
338                 let &[ref left, ref right, ref n] = check_arg_count(args)?;
339                 let left = this.read_scalar(left)?.check_init()?;
340                 let right = this.read_scalar(right)?.check_init()?;
341                 let n = Size::from_bytes(this.read_scalar(n)?.to_machine_usize(this)?);
342
343                 let result = {
344                     let left_bytes = this.memory.read_bytes(left, n)?;
345                     let right_bytes = this.memory.read_bytes(right, n)?;
346
347                     use std::cmp::Ordering::*;
348                     match left_bytes.cmp(right_bytes) {
349                         Less => -1i32,
350                         Equal => 0,
351                         Greater => 1,
352                     }
353                 };
354
355                 this.write_scalar(Scalar::from_i32(result), dest)?;
356             }
357             "memrchr" => {
358                 check_abi(abi, Abi::C { unwind: false })?;
359                 let &[ref ptr, ref val, ref num] = check_arg_count(args)?;
360                 let ptr = this.read_scalar(ptr)?.check_init()?;
361                 let val = this.read_scalar(val)?.to_i32()? as u8;
362                 let num = this.read_scalar(num)?.to_machine_usize(this)?;
363                 if let Some(idx) = this
364                     .memory
365                     .read_bytes(ptr, Size::from_bytes(num))?
366                     .iter()
367                     .rev()
368                     .position(|&c| c == val)
369                 {
370                     let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
371                     this.write_scalar(new_ptr, dest)?;
372                 } else {
373                     this.write_null(dest)?;
374                 }
375             }
376             "memchr" => {
377                 check_abi(abi, Abi::C { unwind: false })?;
378                 let &[ref ptr, ref val, ref num] = check_arg_count(args)?;
379                 let ptr = this.read_scalar(ptr)?.check_init()?;
380                 let val = this.read_scalar(val)?.to_i32()? as u8;
381                 let num = this.read_scalar(num)?.to_machine_usize(this)?;
382                 let idx = this
383                     .memory
384                     .read_bytes(ptr, Size::from_bytes(num))?
385                     .iter()
386                     .position(|&c| c == val);
387                 if let Some(idx) = idx {
388                     let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
389                     this.write_scalar(new_ptr, dest)?;
390                 } else {
391                     this.write_null(dest)?;
392                 }
393             }
394             "strlen" => {
395                 check_abi(abi, Abi::C { unwind: false })?;
396                 let &[ref ptr] = check_arg_count(args)?;
397                 let ptr = this.read_scalar(ptr)?.check_init()?;
398                 let n = this.memory.read_c_str(ptr)?.len();
399                 this.write_scalar(Scalar::from_machine_usize(u64::try_from(n).unwrap(), this), dest)?;
400             }
401
402             // math functions
403             | "cbrtf"
404             | "coshf"
405             | "sinhf"
406             | "tanf"
407             | "acosf"
408             | "asinf"
409             | "atanf"
410             => {
411                 check_abi(abi, Abi::C { unwind: false })?;
412                 let &[ref f] = check_arg_count(args)?;
413                 // FIXME: Using host floats.
414                 let f = f32::from_bits(this.read_scalar(f)?.to_u32()?);
415                 let f = match link_name {
416                     "cbrtf" => f.cbrt(),
417                     "coshf" => f.cosh(),
418                     "sinhf" => f.sinh(),
419                     "tanf" => f.tan(),
420                     "acosf" => f.acos(),
421                     "asinf" => f.asin(),
422                     "atanf" => f.atan(),
423                     _ => bug!(),
424                 };
425                 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
426             }
427             | "_hypotf"
428             | "hypotf"
429             | "atan2f"
430             => {
431                 check_abi(abi, Abi::C { unwind: false })?;
432                 let &[ref f1, ref f2] = check_arg_count(args)?;
433                 // underscore case for windows, here and below
434                 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
435                 // FIXME: Using host floats.
436                 let f1 = f32::from_bits(this.read_scalar(f1)?.to_u32()?);
437                 let f2 = f32::from_bits(this.read_scalar(f2)?.to_u32()?);
438                 let n = match link_name {
439                     "_hypotf" | "hypotf" => f1.hypot(f2),
440                     "atan2f" => f1.atan2(f2),
441                     _ => bug!(),
442                 };
443                 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
444             }
445             | "cbrt"
446             | "cosh"
447             | "sinh"
448             | "tan"
449             | "acos"
450             | "asin"
451             | "atan"
452             => {
453                 check_abi(abi, Abi::C { unwind: false })?;
454                 let &[ref f] = check_arg_count(args)?;
455                 // FIXME: Using host floats.
456                 let f = f64::from_bits(this.read_scalar(f)?.to_u64()?);
457                 let f = match link_name {
458                     "cbrt" => f.cbrt(),
459                     "cosh" => f.cosh(),
460                     "sinh" => f.sinh(),
461                     "tan" => f.tan(),
462                     "acos" => f.acos(),
463                     "asin" => f.asin(),
464                     "atan" => f.atan(),
465                     _ => bug!(),
466                 };
467                 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
468             }
469             | "_hypot"
470             | "hypot"
471             | "atan2"
472             => {
473                 check_abi(abi, Abi::C { unwind: false })?;
474                 let &[ref f1, ref f2] = check_arg_count(args)?;
475                 // FIXME: Using host floats.
476                 let f1 = f64::from_bits(this.read_scalar(f1)?.to_u64()?);
477                 let f2 = f64::from_bits(this.read_scalar(f2)?.to_u64()?);
478                 let n = match link_name {
479                     "_hypot" | "hypot" => f1.hypot(f2),
480                     "atan2" => f1.atan2(f2),
481                     _ => bug!(),
482                 };
483                 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
484             }
485             | "_ldexp"
486             | "ldexp"
487             | "scalbn"
488             => {
489                 check_abi(abi, Abi::C { unwind: false })?;
490                 let &[ref x, ref exp] = check_arg_count(args)?;
491                 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
492                 let x = this.read_scalar(x)?.to_f64()?;
493                 let exp = this.read_scalar(exp)?.to_i32()?;
494
495                 // Saturating cast to i16. Even those are outside the valid exponent range to
496                 // `scalbn` below will do its over/underflow handling.
497                 let exp = if exp > i32::from(i16::MAX) {
498                     i16::MAX
499                 } else if exp < i32::from(i16::MIN) {
500                     i16::MIN
501                 } else {
502                     exp.try_into().unwrap()
503                 };
504
505                 let res = x.scalbn(exp);
506                 this.write_scalar(Scalar::from_f64(res), dest)?;
507             }
508
509             // Architecture-specific shims
510             "llvm.x86.sse2.pause" if this.tcx.sess.target.arch == "x86" || this.tcx.sess.target.arch == "x86_64" => {
511                 check_abi(abi, Abi::C { unwind: false })?;
512                 let &[] = check_arg_count(args)?;
513                 this.yield_active_thread();
514             }
515             "llvm.aarch64.isb" if this.tcx.sess.target.arch == "aarch64" => {
516                 check_abi(abi, Abi::C { unwind: false })?;
517                 let &[ref arg] = check_arg_count(args)?;
518                 let arg = this.read_scalar(arg)?.to_i32()?;
519                 match arg {
520                     15 => { // SY ("full system scope")
521                         this.yield_active_thread();
522                     }
523                     _ => {
524                         throw_unsup_format!("unsupported llvm.aarch64.isb argument {}", arg);
525                     }
526                 }
527             }
528
529             // Platform-specific shims
530             _ => match this.tcx.sess.target.os.as_str() {
531                 "linux" | "macos" => return shims::posix::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, abi, args, dest, ret),
532                 "windows" => return shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, abi, args, dest, ret),
533                 target => throw_unsup_format!("the target `{}` is not supported", target),
534             }
535         };
536
537         Ok(true)
538     }
539
540     /// Check some basic requirements for this allocation request:
541     /// non-zero size, power-of-two alignment.
542     fn check_alloc_request(size: u64, align: u64) -> InterpResult<'tcx> {
543         if size == 0 {
544             throw_ub_format!("creating allocation with size 0");
545         }
546         if !align.is_power_of_two() {
547             throw_ub_format!("creating allocation with non-power-of-two alignment {}", align);
548         }
549         Ok(())
550     }
551 }