Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Guard against overflow in codemap::span_to_lines. #25013

Merged
merged 2 commits into from
May 7, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions src/libcore/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -631,8 +631,14 @@ fn size_from_ptr<T>(_: *const T) -> usize {
}


// Use macro to be generic over const/mut
macro_rules! slice_offset {
// Use macros to be generic over const/mut
//
// They require non-negative `$by` because otherwise the expression
// `(ptr as usize + $by)` would interpret `-1` as `usize::MAX` (and
// thus trigger a panic when overflow checks are on).

// Use this to do `$ptr + $by`, where `$by` is non-negative.
macro_rules! slice_add_offset {
($ptr:expr, $by:expr) => {{
let ptr = $ptr;
if size_from_ptr(ptr) == 0 {
Expand All @@ -643,6 +649,18 @@ macro_rules! slice_offset {
}};
}

// Use this to do `$ptr - $by`, where `$by` is non-negative.
macro_rules! slice_sub_offset {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a comment about why one can't just use slice_offset!/slice_add_offset! with -1?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will do.

($ptr:expr, $by:expr) => {{
let ptr = $ptr;
if size_from_ptr(ptr) == 0 {
transmute(ptr as usize - $by)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GitHub seems to have lost my previous comment about this. It may have been a commit comment instead of a diff comment but I thought GitHub still preserved those. In the interests of making the discussion actually make sense, what I had suggested was that we don't need a separate macro at all, we just need wrapping arithmetic, like

macro_rules! slice_offset {
    ($ptr:expr, $by:expr) => {{
        let ptr = $ptr;
        if size_from_ptr(ptr) == 0 {
            transmute((ptr as isize).wrapping_add($by))
        } else {
            ptr.offset($by)
        }
    }};
}

And FWIW I still believe this is the better approach. It more closely mimics the actual pointer arithmetic used for non-zero-sized types, it means none of the callers of the macro have to be updated, and it more closely matches the required changes for #25016 (I think we need to use wrapping addition in more places in this module in order to restore the pre-overflow-check behavior).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have kept the changes in the form presented here because I still believe this code is easier to read than that change that you suggest. (It is an entirely subjective opinion.)

I freely admit that I have not done the full review of the core::slice code, and thus I have no argument against the point you make about hypothetical fixes to #25016. If it comes to that, then we can revert back to a macro of the form you suggest when #25016 gets fixed.

For now, however, my main concern is getting make check working again on --enable-debug builds, and this was the most obviously correct way for me to go about doing it.

} else {
ptr.offset(-$by)
}
}};
}

macro_rules! slice_ref {
($ptr:expr) => {{
let ptr = $ptr;
Expand Down Expand Up @@ -672,7 +690,7 @@ macro_rules! iterator {
None
} else {
let old = self.ptr;
self.ptr = slice_offset!(self.ptr, 1);
self.ptr = slice_add_offset!(self.ptr, 1);
Some(slice_ref!(old))
}
}
Expand Down Expand Up @@ -714,7 +732,7 @@ macro_rules! iterator {
if self.end == self.ptr {
None
} else {
self.end = slice_offset!(self.end, -1);
self.end = slice_sub_offset!(self.end, 1);
Some(slice_ref!(self.end))
}
}
Expand Down Expand Up @@ -816,7 +834,7 @@ impl<'a, T> Iter<'a, T> {
fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
match self.as_slice().get(n) {
Some(elem_ref) => unsafe {
self.ptr = slice_offset!(elem_ref as *const _, 1);
self.ptr = slice_add_offset!(elem_ref as *const _, 1);
Some(slice_ref!(elem_ref))
},
None => {
Expand Down Expand Up @@ -959,7 +977,7 @@ impl<'a, T> IterMut<'a, T> {
fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
match make_mut_slice!(T => &'a mut [T]: self.ptr, self.end).get_mut(n) {
Some(elem_ref) => unsafe {
self.ptr = slice_offset!(elem_ref as *mut _, 1);
self.ptr = slice_add_offset!(elem_ref as *mut _, 1);
Some(slice_ref!(elem_ref))
},
None => {
Expand Down
31 changes: 26 additions & 5 deletions src/libsyntax/codemap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -667,9 +667,22 @@ impl CodeMap {
self.lookup_char_pos(sp.lo).file.name.to_string()
}

pub fn span_to_lines(&self, sp: Span) -> FileLines {
pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
if sp.lo > sp.hi {
return Err(SpanLinesError::IllFormedSpan(sp));
}

let lo = self.lookup_char_pos(sp.lo);
let hi = self.lookup_char_pos(sp.hi);

if lo.file.start_pos != hi.file.start_pos {
return Err(SpanLinesError::DistinctSources(DistinctSources {
begin: (lo.file.name.clone(), lo.file.start_pos),
end: (hi.file.name.clone(), hi.file.start_pos),
}));
}
assert!(hi.line >= lo.line);

let mut lines = Vec::with_capacity(hi.line - lo.line + 1);

// The span starts partway through the first line,
Expand All @@ -693,7 +706,7 @@ impl CodeMap {
start_col: start_col,
end_col: hi.col });

FileLines {file: lo.file, lines: lines}
Ok(FileLines {file: lo.file, lines: lines})
}

pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
Expand Down Expand Up @@ -918,9 +931,17 @@ impl CodeMap {
}

// _____________________________________________________________________________
// SpanSnippetError, DistinctSources, MalformedCodemapPositions
// SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
//

pub type FileLinesResult = Result<FileLines, SpanLinesError>;

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SpanLinesError {
IllFormedSpan(Span),
DistinctSources(DistinctSources),
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SpanSnippetError {
IllFormedSpan(Span),
Expand Down Expand Up @@ -1086,7 +1107,7 @@ mod tests {
// Test span_to_lines for a span ending at the end of filemap
let cm = init_code_map();
let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
let file_lines = cm.span_to_lines(span);
let file_lines = cm.span_to_lines(span).unwrap();

assert_eq!(file_lines.file.name, "blork.rs");
assert_eq!(file_lines.lines.len(), 1);
Expand Down Expand Up @@ -1131,7 +1152,7 @@ mod tests {
assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");

// check that span_to_lines gives us the complete result with the lines/cols we expected
let lines = cm.span_to_lines(span);
let lines = cm.span_to_lines(span).unwrap();
let expected = vec![
LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
Expand Down
22 changes: 19 additions & 3 deletions src/libsyntax/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ fn highlight_suggestion(err: &mut EmitterWriter,
suggestion: &str)
-> io::Result<()>
{
let lines = cm.span_to_lines(sp);
let lines = cm.span_to_lines(sp).unwrap();
assert!(!lines.lines.is_empty());

// To build up the result, we want to take the snippet from the first
Expand Down Expand Up @@ -567,9 +567,17 @@ fn highlight_lines(err: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span,
lvl: Level,
lines: codemap::FileLines)
lines: codemap::FileLinesResult)
-> io::Result<()>
{
let lines = match lines {
Ok(lines) => lines,
Err(_) => {
try!(write!(&mut err.dst, "(internal compiler error: unprintable span)\n"));
return Ok(());
}
};

let fm = &*lines.file;

let line_strings: Option<Vec<&str>> =
Expand Down Expand Up @@ -690,8 +698,16 @@ fn end_highlight_lines(w: &mut EmitterWriter,
cm: &codemap::CodeMap,
sp: Span,
lvl: Level,
lines: codemap::FileLines)
lines: codemap::FileLinesResult)
-> io::Result<()> {
let lines = match lines {
Ok(lines) => lines,
Err(_) => {
try!(write!(&mut w.dst, "(internal compiler error: unprintable span)\n"));
return Ok(());
}
};

let fm = &*lines.file;

let lines = &lines.lines[..];
Expand Down