Skip to content

Commit 52efe55

Browse files
committed
Handle overflow properly in core::slice
core::slice was originally written to tolerate overflow (notably, with slices of zero-sized elements), but it was never updated to use wrapping arithmetic when overflow traps were added. Also correctly handle the case of calling .nth() on an Iter with a zero-sized element type. The iterator was assuming that the pointer value of the returned reference was meaningful, but that's not true for zero-sized elements. Fixes rust-lang#25016.
1 parent 7334518 commit 52efe55

File tree

2 files changed

+46
-39
lines changed

2 files changed

+46
-39
lines changed

src/libcore/slice.rs

+12-39
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ impl<T> SliceExt for [T] {
140140
assume(!p.is_null());
141141
if mem::size_of::<T>() == 0 {
142142
Iter {ptr: p,
143-
end: (p as usize + self.len()) as *const T,
143+
end: ((p as usize).wrapping_add(self.len())) as *const T,
144144
_marker: marker::PhantomData}
145145
} else {
146146
Iter {ptr: p,
@@ -277,7 +277,7 @@ impl<T> SliceExt for [T] {
277277
assume(!p.is_null());
278278
if mem::size_of::<T>() == 0 {
279279
IterMut {ptr: p,
280-
end: (p as usize + self.len()) as *mut T,
280+
end: ((p as usize).wrapping_add(self.len())) as *mut T,
281281
_marker: marker::PhantomData}
282282
} else {
283283
IterMut {ptr: p,
@@ -632,35 +632,17 @@ fn size_from_ptr<T>(_: *const T) -> usize {
632632

633633

634634
// Use macros to be generic over const/mut
635-
//
636-
// They require non-negative `$by` because otherwise the expression
637-
// `(ptr as usize + $by)` would interpret `-1` as `usize::MAX` (and
638-
// thus trigger a panic when overflow checks are on).
639-
640-
// Use this to do `$ptr + $by`, where `$by` is non-negative.
641-
macro_rules! slice_add_offset {
635+
macro_rules! slice_offset {
642636
($ptr:expr, $by:expr) => {{
643637
let ptr = $ptr;
644638
if size_from_ptr(ptr) == 0 {
645-
transmute(ptr as usize + $by)
639+
transmute((ptr as isize).wrapping_add($by))
646640
} else {
647641
ptr.offset($by)
648642
}
649643
}};
650644
}
651645

652-
// Use this to do `$ptr - $by`, where `$by` is non-negative.
653-
macro_rules! slice_sub_offset {
654-
($ptr:expr, $by:expr) => {{
655-
let ptr = $ptr;
656-
if size_from_ptr(ptr) == 0 {
657-
transmute(ptr as usize - $by)
658-
} else {
659-
ptr.offset(-$by)
660-
}
661-
}};
662-
}
663-
664646
macro_rules! slice_ref {
665647
($ptr:expr) => {{
666648
let ptr = $ptr;
@@ -684,21 +666,19 @@ macro_rules! iterator {
684666
fn next(&mut self) -> Option<$elem> {
685667
// could be implemented with slices, but this avoids bounds checks
686668
unsafe {
687-
::intrinsics::assume(!self.ptr.is_null());
688-
::intrinsics::assume(!self.end.is_null());
689669
if self.ptr == self.end {
690670
None
691671
} else {
692672
let old = self.ptr;
693-
self.ptr = slice_add_offset!(self.ptr, 1);
673+
self.ptr = slice_offset!(self.ptr, 1);
694674
Some(slice_ref!(old))
695675
}
696676
}
697677
}
698678

699679
#[inline]
700680
fn size_hint(&self) -> (usize, Option<usize>) {
701-
let diff = (self.end as usize) - (self.ptr as usize);
681+
let diff = (self.end as usize).wrapping_sub(self.ptr as usize);
702682
let size = mem::size_of::<T>();
703683
let exact = diff / (if size == 0 {1} else {size});
704684
(exact, Some(exact))
@@ -727,12 +707,10 @@ macro_rules! iterator {
727707
fn next_back(&mut self) -> Option<$elem> {
728708
// could be implemented with slices, but this avoids bounds checks
729709
unsafe {
730-
::intrinsics::assume(!self.ptr.is_null());
731-
::intrinsics::assume(!self.end.is_null());
732710
if self.end == self.ptr {
733711
None
734712
} else {
735-
self.end = slice_sub_offset!(self.end, 1);
713+
self.end = slice_offset!(self.end, -1);
736714
Some(slice_ref!(self.end))
737715
}
738716
}
@@ -743,7 +721,7 @@ macro_rules! iterator {
743721

744722
macro_rules! make_slice {
745723
($t: ty => $result: ty: $start: expr, $end: expr) => {{
746-
let diff = $end as usize - $start as usize;
724+
let diff = ($end as usize).wrapping_sub($start as usize);
747725
let len = if mem::size_of::<T>() == 0 {
748726
diff
749727
} else {
@@ -757,7 +735,7 @@ macro_rules! make_slice {
757735

758736
macro_rules! make_mut_slice {
759737
($t: ty => $result: ty: $start: expr, $end: expr) => {{
760-
let diff = $end as usize - $start as usize;
738+
let diff = ($end as usize).wrapping_sub($start as usize);
761739
let len = if mem::size_of::<T>() == 0 {
762740
diff
763741
} else {
@@ -794,7 +772,7 @@ impl<'a, T> Iter<'a, T> {
794772
fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
795773
match self.as_slice().get(n) {
796774
Some(elem_ref) => unsafe {
797-
self.ptr = slice_add_offset!(elem_ref as *const _, 1);
775+
self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
798776
Some(slice_ref!(elem_ref))
799777
},
800778
None => {
@@ -827,12 +805,7 @@ impl<'a, T> RandomAccessIterator for Iter<'a, T> {
827805
fn idx(&mut self, index: usize) -> Option<&'a T> {
828806
unsafe {
829807
if index < self.indexable() {
830-
if mem::size_of::<T>() == 0 {
831-
// Use a non-null pointer value
832-
Some(&mut *(1 as *mut _))
833-
} else {
834-
Some(transmute(self.ptr.offset(index as isize)))
835-
}
808+
Some(slice_ref!(self.ptr.offset(index as isize)))
836809
} else {
837810
None
838811
}
@@ -867,7 +840,7 @@ impl<'a, T> IterMut<'a, T> {
867840
fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
868841
match make_mut_slice!(T => &'a mut [T]: self.ptr, self.end).get_mut(n) {
869842
Some(elem_ref) => unsafe {
870-
self.ptr = slice_add_offset!(elem_ref as *mut _, 1);
843+
self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
871844
Some(slice_ref!(elem_ref))
872845
},
873846
None => {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// compile-flags: -C debug-assertions
12+
13+
use std::slice;
14+
15+
pub fn main() {
16+
// In a slice of zero-size elements the pointer is meaningless.
17+
// Ensure iteration still works even if the pointer is at the end of the address space.
18+
let slice: &[()] = unsafe { slice::from_raw_parts(-5isize as *const (), 10) };
19+
assert_eq!(slice.len(), 10);
20+
assert_eq!(slice.iter().count(), 10);
21+
22+
// .nth() on the iterator should also behave correctly
23+
let mut it = slice.iter();
24+
assert!(it.nth(5).is_some());
25+
assert_eq!(it.count(), 4);
26+
27+
let slice: &mut [()] = unsafe { slice::from_raw_parts_mut(-5isize as *mut (), 10) };
28+
assert_eq!(slice.len(), 10);
29+
assert_eq!(slice.iter_mut().count(), 10);
30+
31+
let mut it = slice.iter_mut();
32+
assert!(it.nth(5).is_some());
33+
assert_eq!(it.count(), 4);
34+
}

0 commit comments

Comments
 (0)