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