]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items.rs
b4931d36004444f20f79359d90b86b4d296c4fa7
[rust.git] / src / shims / foreign_items.rs
1 mod windows;
2 mod posix;
3
4 use std::{convert::{TryInto, TryFrom}, iter};
5
6 use rustc_hir::def_id::DefId;
7 use rustc::mir;
8 use rustc::ty;
9 use rustc::ty::layout::{Align, Size};
10 use rustc_apfloat::Float;
11 use rustc_span::symbol::sym;
12 use rustc_ast::attr;
13
14 use crate::*;
15
16 impl<'mir, 'tcx> 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.tcx.sess.target.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::from_int(0, this.pointer_size())
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::from_int(0, this.pointer_size()))
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::from_int(0, this.pointer_size()))
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 attr::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                 // This matches calls to the foreign item `panic_impl`.
133                 // The implementation is provided by the function with the `#[panic_handler]` attribute.
134                 "panic_impl" => {
135                     let panic_impl_id = this.tcx.lang_items().panic_impl().unwrap();
136                     let panic_impl_instance = ty::Instance::mono(*this.tcx, panic_impl_id);
137                     return Ok(Some(&*this.load_mir(panic_impl_instance.def, None)?));
138                 }
139                 | "exit"
140                 | "ExitProcess"
141                 => {
142                     // it's really u32 for ExitProcess, but we have to put it into the `Exit` variant anyway
143                     let code = this.read_scalar(args[0])?.to_i32()?;
144                     throw_machine_stop!(TerminationInfo::Exit(code.into()));
145                 }
146                 _ => throw_unsup_format!("can't call (diverging) foreign function: {}", link_name),
147             },
148             Some(p) => p,
149         };
150
151         // Second: some functions that we forward to MIR implementations.
152         match link_name {
153             // This matches calls to the foreign item `__rust_start_panic`, that is,
154             // calls to `extern "Rust" { fn __rust_start_panic(...) }`
155             // (and `__rust_panic_cleanup`, respectively).
156             // We forward this to the underlying *implementation* in the panic runtime crate.
157             // Normally, this will be either `libpanic_unwind` or `libpanic_abort`, but it could
158             // also be a custom user-provided implementation via `#![feature(panic_runtime)]`
159             "__rust_start_panic" | "__rust_panic_cleanup"=> {
160                 // FIXME we might want to cache this... but it's not really performance-critical.
161                 let panic_runtime = tcx
162                     .crates()
163                     .iter()
164                     .find(|cnum| tcx.is_panic_runtime(**cnum))
165                     .expect("No panic runtime found!");
166                 let panic_runtime = tcx.crate_name(*panic_runtime);
167                 let start_panic_instance =
168                     this.resolve_path(&[&*panic_runtime.as_str(), link_name])?;
169                 return Ok(Some(&*this.load_mir(start_panic_instance.def, None)?));
170             }
171             _ => {}
172         }
173
174         // Third: functions that return.
175         if this.emulate_foreign_item_by_name(link_name, args, dest, ret)? {
176             this.dump_place(*dest);
177             this.go_to_block(ret);
178         }
179
180         Ok(None)
181     }
182
183     /// Emulates calling a foreign item using its name, failing if the item is not supported.
184     /// Returns `true` if the caller is expected to jump to the return block, and `false` if
185     /// jumping has already been taken care of.
186     fn emulate_foreign_item_by_name(
187         &mut self,
188         link_name: &str,
189         args: &[OpTy<'tcx, Tag>],
190         dest: PlaceTy<'tcx, Tag>,
191         ret: mir::BasicBlock,
192     ) -> InterpResult<'tcx, bool> {
193         let this = self.eval_context_mut();
194
195         // Here we dispatch all the shims for foreign functions. If you have a platform specific
196         // shim, add it to the corresponding submodule.
197         match link_name {
198             "malloc" => {
199                 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
200                 let res = this.malloc(size, /*zero_init:*/ false, MiriMemoryKind::C);
201                 this.write_scalar(res, dest)?;
202             }
203             "calloc" => {
204                 let items = this.read_scalar(args[0])?.to_machine_usize(this)?;
205                 let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
206                 let size =
207                     items.checked_mul(len).ok_or_else(|| err_ub_format!("overflow during calloc size computation"))?;
208                 let res = this.malloc(size, /*zero_init:*/ true, MiriMemoryKind::C);
209                 this.write_scalar(res, dest)?;
210             }
211             "free" => {
212                 let ptr = this.read_scalar(args[0])?.not_undef()?;
213                 this.free(ptr, MiriMemoryKind::C)?;
214             }
215             "realloc" => {
216                 let old_ptr = this.read_scalar(args[0])?.not_undef()?;
217                 let new_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
218                 let res = this.realloc(old_ptr, new_size, MiriMemoryKind::C)?;
219                 this.write_scalar(res, dest)?;
220             }
221
222             "__rust_alloc" => {
223                 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
224                 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
225                 Self::check_alloc_request(size, align)?;
226                 let ptr = this.memory.allocate(
227                     Size::from_bytes(size),
228                     Align::from_bytes(align).unwrap(),
229                     MiriMemoryKind::Rust.into(),
230                 );
231                 this.write_scalar(ptr, dest)?;
232             }
233             "__rust_alloc_zeroed" => {
234                 let size = this.read_scalar(args[0])?.to_machine_usize(this)?;
235                 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
236                 Self::check_alloc_request(size, align)?;
237                 let ptr = this.memory.allocate(
238                     Size::from_bytes(size),
239                     Align::from_bytes(align).unwrap(),
240                     MiriMemoryKind::Rust.into(),
241                 );
242                 // We just allocated this, the access is definitely in-bounds.
243                 this.memory.write_bytes(ptr.into(), iter::repeat(0u8).take(usize::try_from(size).unwrap())).unwrap();
244                 this.write_scalar(ptr, dest)?;
245             }
246             "__rust_dealloc" => {
247                 let ptr = this.read_scalar(args[0])?.not_undef()?;
248                 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
249                 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
250                 // No need to check old_size/align; we anyway check that they match the allocation.
251                 let ptr = this.force_ptr(ptr)?;
252                 this.memory.deallocate(
253                     ptr,
254                     Some((Size::from_bytes(old_size), Align::from_bytes(align).unwrap())),
255                     MiriMemoryKind::Rust.into(),
256                 )?;
257             }
258             "__rust_realloc" => {
259                 let old_size = this.read_scalar(args[1])?.to_machine_usize(this)?;
260                 let align = this.read_scalar(args[2])?.to_machine_usize(this)?;
261                 let new_size = this.read_scalar(args[3])?.to_machine_usize(this)?;
262                 Self::check_alloc_request(new_size, align)?;
263                 // No need to check old_size; we anyway check that they match the allocation.
264                 let ptr = this.force_ptr(this.read_scalar(args[0])?.not_undef()?)?;
265                 let align = Align::from_bytes(align).unwrap();
266                 let new_ptr = this.memory.reallocate(
267                     ptr,
268                     Some((Size::from_bytes(old_size), align)),
269                     Size::from_bytes(new_size),
270                     align,
271                     MiriMemoryKind::Rust.into(),
272                 )?;
273                 this.write_scalar(new_ptr, dest)?;
274             }
275
276             "memcmp" => {
277                 let left = this.read_scalar(args[0])?.not_undef()?;
278                 let right = this.read_scalar(args[1])?.not_undef()?;
279                 let n = Size::from_bytes(this.read_scalar(args[2])?.to_machine_usize(this)?);
280
281                 let result = {
282                     let left_bytes = this.memory.read_bytes(left, n)?;
283                     let right_bytes = this.memory.read_bytes(right, n)?;
284
285                     use std::cmp::Ordering::*;
286                     match left_bytes.cmp(right_bytes) {
287                         Less => -1i32,
288                         Equal => 0,
289                         Greater => 1,
290                     }
291                 };
292
293                 this.write_scalar(Scalar::from_int(result, Size::from_bits(32)), dest)?;
294             }
295
296             "memrchr" => {
297                 let ptr = this.read_scalar(args[0])?.not_undef()?;
298                 let val = this.read_scalar(args[1])?.to_i32()? as u8;
299                 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
300                 if let Some(idx) = this
301                     .memory
302                     .read_bytes(ptr, Size::from_bytes(num))?
303                     .iter()
304                     .rev()
305                     .position(|&c| c == val)
306                 {
307                     let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
308                     this.write_scalar(new_ptr, dest)?;
309                 } else {
310                     this.write_null(dest)?;
311                 }
312             }
313
314             "memchr" => {
315                 let ptr = this.read_scalar(args[0])?.not_undef()?;
316                 let val = this.read_scalar(args[1])?.to_i32()? as u8;
317                 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
318                 let idx = this
319                     .memory
320                     .read_bytes(ptr, Size::from_bytes(num))?
321                     .iter()
322                     .position(|&c| c == val);
323                 if let Some(idx) = idx {
324                     let new_ptr = ptr.ptr_offset(Size::from_bytes(idx as u64), this)?;
325                     this.write_scalar(new_ptr, dest)?;
326                 } else {
327                     this.write_null(dest)?;
328                 }
329             }
330
331             "strlen" => {
332                 let ptr = this.read_scalar(args[0])?.not_undef()?;
333                 let n = this.memory.read_c_str(ptr)?.len();
334                 this.write_scalar(Scalar::from_uint(u64::try_from(n).unwrap(), dest.layout.size), dest)?;
335             }
336
337             // math functions
338             | "cbrtf"
339             | "coshf"
340             | "sinhf"
341             | "tanf"
342             | "acosf"
343             | "asinf"
344             | "atanf"
345             => {
346                 // FIXME: Using host floats.
347                 let f = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
348                 let f = match link_name {
349                     "cbrtf" => f.cbrt(),
350                     "coshf" => f.cosh(),
351                     "sinhf" => f.sinh(),
352                     "tanf" => f.tan(),
353                     "acosf" => f.acos(),
354                     "asinf" => f.asin(),
355                     "atanf" => f.atan(),
356                     _ => bug!(),
357                 };
358                 this.write_scalar(Scalar::from_u32(f.to_bits()), dest)?;
359             }
360             // underscore case for windows
361             | "_hypotf"
362             | "hypotf"
363             | "atan2f"
364             => {
365                 // FIXME: Using host floats.
366                 let f1 = f32::from_bits(this.read_scalar(args[0])?.to_u32()?);
367                 let f2 = f32::from_bits(this.read_scalar(args[1])?.to_u32()?);
368                 let n = match link_name {
369                     "_hypotf" | "hypotf" => f1.hypot(f2),
370                     "atan2f" => f1.atan2(f2),
371                     _ => bug!(),
372                 };
373                 this.write_scalar(Scalar::from_u32(n.to_bits()), dest)?;
374             }
375
376             | "cbrt"
377             | "cosh"
378             | "sinh"
379             | "tan"
380             | "acos"
381             | "asin"
382             | "atan"
383             => {
384                 // FIXME: Using host floats.
385                 let f = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
386                 let f = match link_name {
387                     "cbrt" => f.cbrt(),
388                     "cosh" => f.cosh(),
389                     "sinh" => f.sinh(),
390                     "tan" => f.tan(),
391                     "acos" => f.acos(),
392                     "asin" => f.asin(),
393                     "atan" => f.atan(),
394                     _ => bug!(),
395                 };
396                 this.write_scalar(Scalar::from_u64(f.to_bits()), dest)?;
397             }
398             // underscore case for windows, here and below
399             // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019)
400             | "_hypot"
401             | "hypot"
402             | "atan2"
403             => {
404                 // FIXME: Using host floats.
405                 let f1 = f64::from_bits(this.read_scalar(args[0])?.to_u64()?);
406                 let f2 = f64::from_bits(this.read_scalar(args[1])?.to_u64()?);
407                 let n = match link_name {
408                     "_hypot" | "hypot" => f1.hypot(f2),
409                     "atan2" => f1.atan2(f2),
410                     _ => bug!(),
411                 };
412                 this.write_scalar(Scalar::from_u64(n.to_bits()), dest)?;
413             }
414             // For radix-2 (binary) systems, `ldexp` and `scalbn` are the same.
415             | "_ldexp"
416             | "ldexp"
417             | "scalbn"
418             => {
419                 let x = this.read_scalar(args[0])?.to_f64()?;
420                 let exp = this.read_scalar(args[1])?.to_i32()?;
421
422                 // Saturating cast to i16. Even those are outside the valid exponent range to
423                 // `scalbn` below will do its over/underflow handling.
424                 let exp = if exp > i32::from(i16::MAX) {
425                     i16::MAX
426                 } else if exp < i32::from(i16::MIN) {
427                     i16::MIN
428                 } else {
429                     exp.try_into().unwrap()
430                 };
431
432                 let res = x.scalbn(exp);
433                 this.write_scalar(Scalar::from_f64(res), dest)?;
434             }
435
436             _ => match this.tcx.sess.target.target.target_os.as_str() {
437                 "linux" | "macos" => return posix::EvalContextExt::emulate_foreign_item_by_name(this, link_name, args, dest, ret),
438                 "windows" => return windows::EvalContextExt::emulate_foreign_item_by_name(this, link_name, args, dest, ret),
439                 target => throw_unsup_format!("the {} target platform is not supported", target),
440             }
441         };
442
443         Ok(true)
444     }
445
446     /// Check some basic requirements for this allocation request:
447     /// non-zero size, power-of-two alignment.
448     fn check_alloc_request(size: u64, align: u64) -> InterpResult<'tcx> {
449         if size == 0 {
450             throw_ub_format!("creating allocation with size 0");
451         }
452         if !align.is_power_of_two() {
453             throw_ub_format!("creating allocation with non-power-of-two alignment {}", align);
454         }
455         Ok(())
456     }
457
458     /// Evaluates the scalar at the specified path. Returns Some(val)
459     /// if the path could be resolved, and None otherwise
460     fn eval_path_scalar(
461         &mut self,
462         path: &[&str],
463     ) -> InterpResult<'tcx, Option<ScalarMaybeUndef<Tag>>> {
464         let this = self.eval_context_mut();
465         if let Ok(instance) = this.resolve_path(path) {
466             let cid = GlobalId { instance, promoted: None };
467             let const_val = this.const_eval_raw(cid)?;
468             let const_val = this.read_scalar(const_val.into())?;
469             return Ok(Some(const_val));
470         }
471         return Ok(None);
472     }
473 }