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