]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items.rs
Replace target.target with target
[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};
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_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         args: &[OpTy<'tcx, Tag>],
116         ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
117         unwind: Option<mir::BasicBlock>,
118     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
119         let this = self.eval_context_mut();
120         let attrs = this.tcx.get_attrs(def_id);
121         let link_name = match this.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
122             Some(name) => name.as_str(),
123             None => this.tcx.item_name(def_id).as_str(),
124         };
125         // Strip linker suffixes (seen on 32-bit macOS).
126         let link_name = link_name.trim_end_matches("$UNIX2003");
127         let tcx = this.tcx.tcx;
128
129         // First: functions that diverge.
130         let (dest, ret) = match ret {
131             None => match link_name {
132                 "miri_start_panic" => {
133                     this.handle_miri_start_panic(args, unwind)?;
134                     return Ok(None);
135                 }
136                 // This matches calls to the foreign item `panic_impl`.
137                 // The implementation is provided by the function with the `#[panic_handler]` attribute.
138                 "panic_impl" => {
139                     let panic_impl_id = tcx.lang_items().panic_impl().unwrap();
140                     let panic_impl_instance = ty::Instance::mono(tcx, panic_impl_id);
141                     return Ok(Some(&*this.load_mir(panic_impl_instance.def, None)?));
142                 }
143                 | "exit"
144                 | "ExitProcess"
145                 => {
146                     let &[code] = check_arg_count(args)?;
147                     // it's really u32 for ExitProcess, but we have to put it into the `Exit` variant anyway
148                     let code = this.read_scalar(code)?.to_i32()?;
149                     throw_machine_stop!(TerminationInfo::Exit(code.into()));
150                 }
151                 "abort" => {
152                     throw_machine_stop!(TerminationInfo::Abort(None))
153                 }
154                 _ => throw_unsup_format!("can't call (diverging) foreign function: {}", link_name),
155             },
156             Some(p) => p,
157         };
158
159         // Second: some functions that we forward to MIR implementations.
160         match link_name {
161             // This matches calls to the foreign item `__rust_start_panic`, that is,
162             // calls to `extern "Rust" { fn __rust_start_panic(...) }`
163             // (and `__rust_panic_cleanup`, respectively).
164             // We forward this to the underlying *implementation* in the panic runtime crate.
165             // Normally, this will be either `libpanic_unwind` or `libpanic_abort`, but it could
166             // also be a custom user-provided implementation via `#![feature(panic_runtime)]`
167             "__rust_start_panic" | "__rust_panic_cleanup" => {
168                 // This replicates some of the logic in `inject_panic_runtime`.
169                 // FIXME: is there a way to reuse that logic?
170                 let panic_runtime = match this.tcx.sess.panic_strategy() {
171                     PanicStrategy::Unwind => sym::panic_unwind,
172                     PanicStrategy::Abort => sym::panic_abort,
173                 };
174                 let start_panic_instance =
175                     this.resolve_path(&[&*panic_runtime.as_str(), link_name]);
176                 return Ok(Some(&*this.load_mir(start_panic_instance.def, None)?));
177             }
178             _ => {}
179         }
180
181         // Third: functions that return.
182         if this.emulate_foreign_item_by_name(link_name, args, dest, ret)? {
183             trace!("{:?}", this.dump_place(*dest));
184             this.go_to_block(ret);
185         }
186
187         Ok(None)
188     }
189
190     /// Emulates calling a foreign item using its name, failing if the item is not supported.
191     /// Returns `true` if the caller is expected to jump to the return block, and `false` if
192     /// jumping has already been taken care of.
193     fn emulate_foreign_item_by_name(
194         &mut self,
195         link_name: &str,
196         args: &[OpTy<'tcx, Tag>],
197         dest: PlaceTy<'tcx, Tag>,
198         ret: mir::BasicBlock,
199     ) -> InterpResult<'tcx, bool> {
200         let this = self.eval_context_mut();
201
202         // Here we dispatch all the shims for foreign functions. If you have a platform specific
203         // shim, add it to the corresponding submodule.
204         match link_name {
205             // Miri-specific extern functions
206             "miri_static_root" => {
207                 let &[ptr] = check_arg_count(args)?;
208                 let ptr = this.read_scalar(ptr)?.check_init()?;
209                 let ptr = this.force_ptr(ptr)?;
210                 if ptr.offset != Size::ZERO {
211                     throw_unsup_format!("pointer passed to miri_static_root must point to beginning of an allocated block");
212                 }
213                 this.machine.static_roots.push(ptr.alloc_id);
214             }
215
216             // Obtains a Miri backtrace. See the README for details.
217             "miri_get_backtrace" => {
218                 this.handle_miri_get_backtrace(args, dest)?;
219             }
220
221             // Resolves a Miri backtrace frame. See the README for details.
222             "miri_resolve_frame" => {
223                 this.handle_miri_resolve_frame(args, dest)?;
224             }
225
226
227             // Standard C allocation
228             "malloc" => {
229                 let &[size] = check_arg_count(args)?;
230                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
231                 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
232                 this.write_scalar(res, dest)?;
233             }
234             "calloc" => {
235                 let &[items, len] = check_arg_count(args)?;
236                 let items = this.read_scalar(items)?.to_machine_usize(this)?;
237                 let len = this.read_scalar(len)?.to_machine_usize(this)?;
238                 let size =
239                     items.checked_mul(len).ok_or_else(|| err_ub_format!("overflow during calloc size computation"))?;
240                 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
241                 this.write_scalar(res, dest)?;
242             }
243             "free" => {
244                 let &[ptr] = check_arg_count(args)?;
245                 let ptr = this.read_scalar(ptr)?.check_init()?;
246                 this.free(ptr, MiriMemoryKind::C)?;
247             }
248             "realloc" => {
249                 let &[old_ptr, new_size] = check_arg_count(args)?;
250                 let old_ptr = this.read_scalar(old_ptr)?.check_init()?;
251                 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
252                 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
253                 this.write_scalar(res, dest)?;
254             }
255
256             // Rust allocation
257             // (Usually these would be forwarded to to `#[global_allocator]`; we instead implement a generic
258             // allocation that also checks that all conditions are met, such as not permitting zero-sized allocations.)
259             "__rust_alloc" => {
260                 let &[size, align] = check_arg_count(args)?;
261                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
262                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
263                 Self::check_alloc_request(size, align)?;
264                 let ptr = this.memory.allocate(
265                     Size::from_bytes(size),
266                     Align::from_bytes(align).unwrap(),
267                     MiriMemoryKind::Rust.into(),
268                 );
269                 this.write_scalar(ptr, dest)?;
270             }
271             "__rust_alloc_zeroed" => {
272                 let &[size, align] = check_arg_count(args)?;
273                 let size = this.read_scalar(size)?.to_machine_usize(this)?;
274                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
275                 Self::check_alloc_request(size, align)?;
276                 let ptr = this.memory.allocate(
277                     Size::from_bytes(size),
278                     Align::from_bytes(align).unwrap(),
279                     MiriMemoryKind::Rust.into(),
280                 );
281                 // We just allocated this, the access is definitely in-bounds.
282                 this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(usize::try_from(size).unwrap())).unwrap();
283                 this.write_scalar(ptr, dest)?;
284             }
285             "__rust_dealloc" => {
286                 let &[ptr, old_size, align] = check_arg_count(args)?;
287                 let 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                 // No need to check old_size/align; we anyway check that they match the allocation.
291                 let ptr = this.force_ptr(ptr)?;
292                 this.memory.deallocate(
293                     ptr,
294                     Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
295                     MiriMemoryKind::Rust.into(),
296                 )?;
297             }
298             "__rust_realloc" => {
299                 let &[ptr, old_size, align, new_size] = check_arg_count(args)?;
300                 let ptr = this.force_ptr(this.read_scalar(ptr)?.check_init()?)?;
301                 let old_size = this.read_scalar(old_size)?.to_machine_usize(this)?;
302                 let align = this.read_scalar(align)?.to_machine_usize(this)?;
303                 let new_size = this.read_scalar(new_size)?.to_machine_usize(this)?;
304                 Self::check_alloc_request(new_size, align)?;
305                 // No need to check old_size; we anyway check that they match the allocation.
306                 let align = Align::from_bytes(align).unwrap();
307                 let new_ptr = this.memory.reallocate(
308                     ptr,
309                     Some((Size::from_bytes(old_size), align)),
310                     Size::from_bytes(new_size),
311                     align,
312                     MiriMemoryKind::Rust.into(),
313                 )?;
314                 this.write_scalar(new_ptr, dest)?;
315             }
316
317             // C memory handling functions
318             "memcmp" => {
319                 let &[left, right, n] = check_arg_count(args)?;
320                 let left = this.read_scalar(left)?.check_init()?;
321                 let right = this.read_scalar(right)?.check_init()?;
322                 let n = Size::from_bytes(this.read_scalar(n)?.to_machine_usize(this)?);
323
324                 let result = {
325                     let left_bytes = this.memory.read_bytes(left, n)?;
326                     let right_bytes = this.memory.read_bytes(right, n)?;
327
328                     use std::cmp::Ordering::*;
329                     match left_bytes.cmp(right_bytes) {
330                         Less => -1i32,
331                         Equal => 0,
332                         Greater => 1,
333                     }
334                 };
335
336                 this.write_scalar(Scalar::from_i32(result), dest)?;
337             }
338             "memrchr" => {
339                 let &[ptr, val, num] = check_arg_count(args)?;
340                 let ptr = this.read_scalar(ptr)?.check_init()?;
341                 let val = this.read_scalar(val)?.to_i32()? as u8;
342                 let num = this.read_scalar(num)?.to_machine_usize(this)?;
343                 if let Some(idx) = this
344                     .memory
345                     .read_bytes(ptr, Size::from_bytes(num))?
346                     .iter()
347                     .rev()
348                     .position(|&c| c == val)
349                 {
350                     let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
351                     this.write_scalar(new_ptr, dest)?;
352                 } else {
353                     this.write_null(dest)?;
354                 }
355             }
356             "memchr" => {
357                 let &[ptr, val, num] = check_arg_count(args)?;
358                 let ptr = this.read_scalar(ptr)?.check_init()?;
359                 let val = this.read_scalar(val)?.to_i32()? as u8;
360                 let num = this.read_scalar(num)?.to_machine_usize(this)?;
361                 let idx = this
362                     .memory
363                     .read_bytes(ptr, Size::from_bytes(num))?
364                     .iter()
365                     .position(|&c| c == val);
366                 if let Some(idx) = idx {
367                     let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
368                     this.write_scalar(new_ptr, dest)?;
369                 } else {
370                     this.write_null(dest)?;
371                 }
372             }
373             "strlen" => {
374                 let &[ptr] = check_arg_count(args)?;
375                 let ptr = this.read_scalar(ptr)?.check_init()?;
376                 let n = this.memory.read_c_str(ptr)?.len();
377                 this.write_scalar(Scalar::from_machine_usize(u64::try_from(n).unwrap(), this), dest)?;
378             }
379
380             // math functions
381             | "cbrtf"
382             | "coshf"
383             | "sinhf"
384             | "tanf"
385             | "acosf"
386             | "asinf"
387             | "atanf"
388             => {
389                 let &[f] = check_arg_count(args)?;
390                 // FIXME: Using host floats.
391                 let f = f32::from_bits(this.read_scalar(f)?.to_u32()?);
392                 let f = match link_name {
393                     "cbrtf" => f.cbrt(),
394                     "coshf" => f.cosh(),
395                     "sinhf" => f.sinh(),
396                     "tanf" => f.tan(),
397                     "acosf" => f.acos(),
398                     "asinf" => f.asin(),
399                     "atanf" => f.atan(),
400                     _ => bug!(),
401                 };
402                 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
403             }
404             | "_hypotf"
405             | "hypotf"
406             | "atan2f"
407             => {
408                 let &[f1, f2] = check_arg_count(args)?;
409                 // underscore case for windows, here and below
410                 // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
411                 // FIXME: Using host floats.
412                 let f1 = f32::from_bits(this.read_scalar(f1)?.to_u32()?);
413                 let f2 = f32::from_bits(this.read_scalar(f2)?.to_u32()?);
414                 let n = match link_name {
415                     "_hypotf" | "hypotf" => f1.hypot(f2),
416                     "atan2f" => f1.atan2(f2),
417                     _ => bug!(),
418                 };
419                 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
420             }
421             | "cbrt"
422             | "cosh"
423             | "sinh"
424             | "tan"
425             | "acos"
426             | "asin"
427             | "atan"
428             => {
429                 let &[f] = check_arg_count(args)?;
430                 // FIXME: Using host floats.
431                 let f = f64::from_bits(this.read_scalar(f)?.to_u64()?);
432                 let f = match link_name {
433                     "cbrt" => f.cbrt(),
434                     "cosh" => f.cosh(),
435                     "sinh" => f.sinh(),
436                     "tan" => f.tan(),
437                     "acos" => f.acos(),
438                     "asin" => f.asin(),
439                     "atan" => f.atan(),
440                     _ => bug!(),
441                 };
442                 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
443             }
444             | "_hypot"
445             | "hypot"
446             | "atan2"
447             => {
448                 let &[f1, f2] = check_arg_count(args)?;
449                 // FIXME: Using host floats.
450                 let f1 = f64::from_bits(this.read_scalar(f1)?.to_u64()?);
451                 let f2 = f64::from_bits(this.read_scalar(f2)?.to_u64()?);
452                 let n = match link_name {
453                     "_hypot" | "hypot" => f1.hypot(f2),
454                     "atan2" => f1.atan2(f2),
455                     _ => bug!(),
456                 };
457                 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
458             }
459             | "_ldexp"
460             | "ldexp"
461             | "scalbn"
462             => {
463                 let &[x, exp] = check_arg_count(args)?;
464                 // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
465                 let x = this.read_scalar(x)?.to_f64()?;
466                 let exp = this.read_scalar(exp)?.to_i32()?;
467
468                 // Saturating cast to i16. Even those are outside the valid exponent range to
469                 // `scalbn` below will do its over/underflow handling.
470                 let exp = if exp > i32::from(i16::MAX) {
471                     i16::MAX
472                 } else if exp < i32::from(i16::MIN) {
473                     i16::MIN
474                 } else {
475                     exp.try_into().unwrap()
476                 };
477
478                 let res = x.scalbn(exp);
479                 this.write_scalar(Scalar::from_f64(res), dest)?;
480             }
481
482             // Architecture-specific shims
483             "llvm.x86.sse2.pause" if this.tcx.sess.target.arch == "x86" || this.tcx.sess.target.arch == "x86_64" => {
484                 let &[] = check_arg_count(args)?;
485                 this.yield_active_thread();
486             }
487
488             // Platform-specific shims
489             _ => match this.tcx.sess.target.target_os.as_str() {
490                 "linux" | "macos" => return shims::posix::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, args, dest, ret),
491                 "windows" => return shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_by_name(this, link_name, args, dest, ret),
492                 target => throw_unsup_format!("the target `{}` is not supported", target),
493             }
494         };
495
496         Ok(true)
497     }
498
499     /// Check some basic requirements for this allocation request:
500     /// non-zero size, power-of-two alignment.
501     fn check_alloc_request(size: u64, align: u64) -> InterpResult<'tcx> {
502         if size == 0 {
503             throw_ub_format!("creating allocation with size 0");
504         }
505         if !align.is_power_of_two() {
506             throw_ub_format!("creating allocation with non-power-of-two alignment {}", align);
507         }
508         Ok(())
509     }
510 }