]> git.lizzy.rs Git - rust.git/blob - src/operator.rs
a30b11aeb27de6d37b383baa04f425ddd5e1400c
[rust.git] / src / operator.rs
1 use rustc::ty::Ty;
2 use rustc::mir;
3
4 use crate::*;
5
6 pub trait EvalContextExt<'tcx> {
7     fn ptr_op(
8         &self,
9         bin_op: mir::BinOp,
10         left: ImmTy<'tcx, Borrow>,
11         right: ImmTy<'tcx, Borrow>,
12     ) -> EvalResult<'tcx, (Scalar<Borrow>, bool)>;
13
14     fn ptr_int_arithmetic(
15         &self,
16         bin_op: mir::BinOp,
17         left: Pointer<Borrow>,
18         right: u128,
19         signed: bool,
20     ) -> EvalResult<'tcx, (Scalar<Borrow>, bool)>;
21
22     fn ptr_eq(
23         &self,
24         left: Scalar<Borrow>,
25         right: Scalar<Borrow>,
26     ) -> EvalResult<'tcx, bool>;
27
28     fn pointer_offset_inbounds(
29         &self,
30         ptr: Scalar<Borrow>,
31         pointee_ty: Ty<'tcx>,
32         offset: i64,
33     ) -> EvalResult<'tcx, Scalar<Borrow>>;
34 }
35
36 impl<'a, 'mir, 'tcx> EvalContextExt<'tcx> for super::MiriEvalContext<'a, 'mir, 'tcx> {
37     fn ptr_op(
38         &self,
39         bin_op: mir::BinOp,
40         left: ImmTy<'tcx, Borrow>,
41         right: ImmTy<'tcx, Borrow>,
42     ) -> EvalResult<'tcx, (Scalar<Borrow>, bool)> {
43         use rustc::mir::BinOp::*;
44
45         trace!("ptr_op: {:?} {:?} {:?}", *left, bin_op, *right);
46
47         // Operations that support fat pointers
48         match bin_op {
49             Eq | Ne => {
50                 let eq = match (*left, *right) {
51                     (Immediate::Scalar(left), Immediate::Scalar(right)) =>
52                         self.ptr_eq(left.not_undef()?, right.not_undef()?)?,
53                     (Immediate::ScalarPair(left1, left2), Immediate::ScalarPair(right1, right2)) =>
54                         self.ptr_eq(left1.not_undef()?, right1.not_undef()?)? &&
55                         self.ptr_eq(left2.not_undef()?, right2.not_undef()?)?,
56                     _ => bug!("Type system should not allow comparing Scalar with ScalarPair"),
57                 };
58                 return Ok((Scalar::from_bool(if bin_op == Eq { eq } else { !eq }), false));
59             }
60             _ => {},
61         }
62
63         // Now we expect no more fat pointers.
64         let left_layout = left.layout;
65         let left = left.to_scalar()?;
66         let right_layout = right.layout;
67         let right = right.to_scalar()?;
68         debug_assert!(left.is_ptr() || right.is_ptr() || bin_op == Offset);
69
70         match bin_op {
71             Offset => {
72                 let pointee_ty = left_layout.ty
73                     .builtin_deref(true)
74                     .expect("Offset called on non-ptr type")
75                     .ty;
76                 let ptr = self.pointer_offset_inbounds(
77                     left,
78                     pointee_ty,
79                     right.to_isize(self)?,
80                 )?;
81                 Ok((ptr, false))
82             }
83             // These need both to be pointer, and fail if they are not in the same location
84             Lt | Le | Gt | Ge | Sub if left.is_ptr() && right.is_ptr() => {
85                 let left = left.to_ptr().expect("we checked is_ptr");
86                 let right = right.to_ptr().expect("we checked is_ptr");
87                 if left.alloc_id == right.alloc_id {
88                     let res = match bin_op {
89                         Lt => left.offset < right.offset,
90                         Le => left.offset <= right.offset,
91                         Gt => left.offset > right.offset,
92                         Ge => left.offset >= right.offset,
93                         Sub => {
94                             // subtract the offsets
95                             let left_offset = Scalar::from_uint(left.offset.bytes(), self.memory().pointer_size());
96                             let right_offset = Scalar::from_uint(right.offset.bytes(), self.memory().pointer_size());
97                             let layout = self.layout_of(self.tcx.types.usize)?;
98                             return self.binary_op(
99                                 Sub,
100                                 ImmTy::from_scalar(left_offset, layout),
101                                 ImmTy::from_scalar(right_offset, layout),
102                             )
103                         }
104                         _ => bug!("We already established it has to be one of these operators."),
105                     };
106                     Ok((Scalar::from_bool(res), false))
107                 } else {
108                     // Both are pointers, but from different allocations.
109                     err!(InvalidPointerMath)
110                 }
111             }
112             // These work if the left operand is a pointer, and the right an integer
113             Add | BitAnd | Sub | Rem if left.is_ptr() && right.is_bits() => {
114                 // Cast to i128 is fine as we checked the kind to be ptr-sized
115                 self.ptr_int_arithmetic(
116                     bin_op,
117                     left.to_ptr().expect("we checked is_ptr"),
118                     right.to_bits(self.memory().pointer_size()).expect("we checked is_bits"),
119                     right_layout.abi.is_signed(),
120                 )
121             }
122             // Commutative operators also work if the integer is on the left
123             Add | BitAnd if left.is_bits() && right.is_ptr() => {
124                 // This is a commutative operation, just swap the operands
125                 self.ptr_int_arithmetic(
126                     bin_op,
127                     right.to_ptr().expect("we checked is_ptr"),
128                     left.to_bits(self.memory().pointer_size()).expect("we checked is_bits"),
129                     left_layout.abi.is_signed(),
130                 )
131             }
132             // Nothing else works
133             _ => err!(InvalidPointerMath),
134         }
135     }
136
137     fn ptr_eq(
138         &self,
139         left: Scalar<Borrow>,
140         right: Scalar<Borrow>,
141     ) -> EvalResult<'tcx, bool> {
142         let size = self.pointer_size();
143         Ok(match (left, right) {
144             (Scalar::Bits { .. }, Scalar::Bits { .. }) =>
145                 left.to_bits(size)? == right.to_bits(size)?,
146             (Scalar::Ptr(left), Scalar::Ptr(right)) => {
147                 // Comparison illegal if one of them is out-of-bounds, *unless* they
148                 // are in the same allocation.
149                 if left.alloc_id == right.alloc_id {
150                     left.offset == right.offset
151                 } else {
152                     // This accepts one-past-the end. Thus, there is still technically
153                     // some non-determinism that we do not fully rule out when two
154                     // allocations sit right next to each other. The C/C++ standards are
155                     // somewhat fuzzy about this case, so I think for now this check is
156                     // "good enough".
157                     // Dead allocations in miri cannot overlap with live allocations, but
158                     // on read hardware this can easily happen. Thus for comparisons we require
159                     // both pointers to be live.
160                     self.memory().check_bounds_ptr(left, InboundsCheck::Live)?;
161                     self.memory().check_bounds_ptr(right, InboundsCheck::Live)?;
162                     // Two in-bounds pointers, we can compare across allocations.
163                     left == right
164                 }
165             }
166             // Comparing ptr and integer.
167             (Scalar::Ptr(ptr), Scalar::Bits { bits, size }) |
168             (Scalar::Bits { bits, size }, Scalar::Ptr(ptr)) => {
169                 assert_eq!(size as u64, self.pointer_size().bytes());
170                 let bits = bits as u64;
171
172                 // Case I: Comparing with NULL.
173                 if bits == 0 {
174                     // Test if the ptr is in-bounds. Then it cannot be NULL.
175                     // Even dangling pointers cannot be NULL.
176                     if self.memory().check_bounds_ptr(ptr, InboundsCheck::MaybeDead).is_ok() {
177                         return Ok(false);
178                     }
179                 }
180
181                 let (alloc_size, alloc_align) = self.memory()
182                     .get_size_and_align(ptr.alloc_id, InboundsCheck::MaybeDead)
183                     .expect("determining size+align of dead ptr cannot fail");
184
185                 // Case II: Alignment gives it away
186                 if ptr.offset.bytes() % alloc_align.bytes() == 0 {
187                     // The offset maintains the allocation alignment, so we know `base+offset`
188                     // is aligned by `alloc_align`.
189                     // FIXME: We could be even more general, e.g., offset 2 into a 4-aligned
190                     // allocation cannot equal 3.
191                     if bits % alloc_align.bytes() != 0 {
192                         // The integer is *not* aligned. So they cannot be equal.
193                         return Ok(false);
194                     }
195                 }
196                 // Case III: The integer is too big, and the allocation goes on a bit
197                 // without wrapping around the address space.
198                 {
199                     // Compute the highest address at which this allocation could live.
200                     // Substract one more, because it must be possible to add the size
201                     // to the base address without overflowing; that is, the very last address
202                     // of the address space is never dereferencable (but it can be in-bounds, i.e.,
203                     // one-past-the-end).
204                     let max_base_addr =
205                         ((1u128 << self.pointer_size().bits())
206                          - u128::from(alloc_size.bytes())
207                          - 1
208                         ) as u64;
209                     if let Some(max_addr) = max_base_addr.checked_add(ptr.offset.bytes()) {
210                         if bits > max_addr {
211                             // The integer is too big, this cannot possibly be equal.
212                             return Ok(false)
213                         }
214                     }
215                 }
216
217                 // None of the supported cases.
218                 return err!(InvalidPointerMath);
219             }
220         })
221     }
222
223     fn ptr_int_arithmetic(
224         &self,
225         bin_op: mir::BinOp,
226         left: Pointer<Borrow>,
227         right: u128,
228         signed: bool,
229     ) -> EvalResult<'tcx, (Scalar<Borrow>, bool)> {
230         use rustc::mir::BinOp::*;
231
232         fn map_to_primval((res, over): (Pointer<Borrow>, bool)) -> (Scalar<Borrow>, bool) {
233             (Scalar::Ptr(res), over)
234         }
235
236         Ok(match bin_op {
237             Sub =>
238                 // The only way this can overflow is by underflowing, so signdeness of the right
239                 // operands does not matter.
240                 map_to_primval(left.overflowing_signed_offset(-(right as i128), self)),
241             Add if signed =>
242                 map_to_primval(left.overflowing_signed_offset(right as i128, self)),
243             Add if !signed =>
244                 map_to_primval(left.overflowing_offset(Size::from_bytes(right as u64), self)),
245
246             BitAnd if !signed => {
247                 let ptr_base_align = self.memory().get(left.alloc_id)?.align.bytes();
248                 let base_mask = {
249                     // FIXME: use `interpret::truncate`, once that takes a `Size` instead of a `Layout`.
250                     let shift = 128 - self.memory().pointer_size().bits();
251                     let value = !(ptr_base_align as u128 - 1);
252                     // Truncate (shift left to drop out leftover values, shift right to fill with zeroes).
253                     (value << shift) >> shift
254                 };
255                 let ptr_size = self.memory().pointer_size().bytes() as u8;
256                 trace!("ptr BitAnd, align {}, operand {:#010x}, base_mask {:#010x}",
257                     ptr_base_align, right, base_mask);
258                 if right & base_mask == base_mask {
259                     // Case 1: the base address bits are all preserved, i.e., right is all-1 there.
260                     let offset = (left.offset.bytes() as u128 & right) as u64;
261                     (
262                         Scalar::Ptr(Pointer::new_with_tag(
263                             left.alloc_id,
264                             Size::from_bytes(offset),
265                             left.tag,
266                         )),
267                         false,
268                     )
269                 } else if right & base_mask == 0 {
270                     // Case 2: the base address bits are all taken away, i.e., right is all-0 there.
271                     (Scalar::Bits { bits: (left.offset.bytes() as u128) & right, size: ptr_size }, false)
272                 } else {
273                     return err!(ReadPointerAsBytes);
274                 }
275             }
276
277             Rem if !signed => {
278                 // Doing modulo a divisor of the alignment is allowed.
279                 // (Intuition: modulo a divisor leaks less information.)
280                 let ptr_base_align = self.memory().get(left.alloc_id)?.align.bytes();
281                 let right = right as u64;
282                 let ptr_size = self.memory().pointer_size().bytes() as u8;
283                 if right == 1 {
284                     // Modulo 1 is always 0.
285                     (Scalar::Bits { bits: 0, size: ptr_size }, false)
286                 } else if ptr_base_align % right == 0 {
287                     // The base address would be cancelled out by the modulo operation, so we can
288                     // just take the modulo of the offset.
289                     (
290                         Scalar::Bits {
291                             bits: (left.offset.bytes() % right) as u128,
292                             size: ptr_size
293                         },
294                         false,
295                     )
296                 } else {
297                     return err!(ReadPointerAsBytes);
298                 }
299             }
300
301             _ => {
302                 let msg = format!(
303                     "unimplemented binary op on pointer {:?}: {:?}, {:?} ({})",
304                     bin_op,
305                     left,
306                     right,
307                     if signed { "signed" } else { "unsigned" }
308                 );
309                 return err!(Unimplemented(msg));
310             }
311         })
312     }
313
314     /// Raises an error if the offset moves the pointer outside of its allocation.
315     /// We consider ZSTs their own huge allocation that doesn't overlap with anything (and nothing
316     /// moves in there because the size is 0). We also consider the NULL pointer its own separate
317     /// allocation, and all the remaining integers pointers their own allocation.
318     fn pointer_offset_inbounds(
319         &self,
320         ptr: Scalar<Borrow>,
321         pointee_ty: Ty<'tcx>,
322         offset: i64,
323     ) -> EvalResult<'tcx, Scalar<Borrow>> {
324         // FIXME: assuming here that type size is less than `i64::max_value()`.
325         let pointee_size = self.layout_of(pointee_ty)?.size.bytes() as i64;
326         let offset = offset
327             .checked_mul(pointee_size)
328             .ok_or_else(|| InterpError::Overflow(mir::BinOp::Mul))?;
329         // Now let's see what kind of pointer this is.
330         if let Scalar::Ptr(ptr) = ptr {
331             // Both old and new pointer must be in-bounds of a *live* allocation.
332             // (Of the same allocation, but that part is trivial with our representation.)
333             self.memory().check_bounds_ptr(ptr, InboundsCheck::Live)?;
334             let ptr = ptr.signed_offset(offset, self)?;
335             self.memory().check_bounds_ptr(ptr, InboundsCheck::Live)?;
336             Ok(Scalar::Ptr(ptr))
337         } else {
338             // An integer pointer. They can only be offset by 0, and we pretend there
339             // is a little zero-sized allocation here.
340             if offset == 0 {
341                 Ok(ptr)
342             } else {
343                 err!(InvalidPointerMath)
344             }
345         }
346     }
347 }