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