Skip to content
Closed
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
18 changes: 12 additions & 6 deletions src/rules_and_declarations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ where
return Some(result.map_err(|e| {
(
e,
self.input.slice_from(start.position()),
self.input.slice_from_unchecked(start.position()),
start.source_location(),
)
}));
Expand All @@ -325,7 +325,7 @@ where
return Some(result.map_err(|e| {
(
e,
self.input.slice_from(start.position()),
self.input.slice_from_unchecked(start.position()),
start.source_location(),
)
}));
Expand Down Expand Up @@ -415,7 +415,7 @@ where
return Some(result.map_err(|e| {
(
e,
self.input.slice_from(start.position()),
self.input.slice_from_unchecked(start.position()),
start.source_location(),
)
}));
Expand All @@ -440,7 +440,13 @@ where
input.expect_colon()?;
parser.parse_value(name, input, &start)
})
.map_err(|e| (e, input.slice_from(start_position), start.source_location()))
.map_err(|e| {
(
e,
input.slice_from_unchecked(start_position),
start.source_location(),
)
})
}

/// Parse a single rule, such as for CSSOM’s `CSSStyleSheet.insertRule`.
Expand Down Expand Up @@ -500,7 +506,7 @@ where
result.map_err(|e| {
(
e,
input.slice_from(start.position()),
input.slice_from_unchecked(start.position()),
start.source_location(),
)
})
Expand All @@ -513,7 +519,7 @@ where
};
Err((
error,
input.slice(start.position()..end_position),
input.slice_unchecked(start.position()..end_position),
start.source_location(),
))
}
Expand Down
28 changes: 28 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1384,3 +1384,31 @@ fn servo_define_css_keyword_enum() {

assert_eq!(UserZoom::from_ident("fixed"), Ok(UserZoom::Fixed));
}

/// https://github.com/servo/rust-cssparser/issues/459
/// `Parser::slice` is a safe, public method, so it must not be able to trigger
/// undefined behavior. A valid range returns the expected substring.
#[test]
fn parser_slice_valid_range() {
let mut parser = Parser::new("abc def");
let start = parser.position();
parser.next().unwrap(); // consume `abc`
let end = parser.position();
assert_eq!(parser.slice(start..end), "abc");
// `slice_from` goes from the given position to the current one.
assert_eq!(parser.slice_from(start), "abc");
}
Comment on lines +1388 to +1400

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think this test is useful?


/// https://github.com/servo/rust-cssparser/issues/459
/// An inverted range used to reach `get_unchecked` and was undefined behavior
/// from safe code. It now goes through checked string indexing, so it panics
/// instead of invoking UB.
#[test]
Comment on lines +1403 to +1406

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The "used to" part of the comment also seems useless.

#[should_panic]
fn parser_slice_inverted_range_panics_instead_of_ub() {
let mut parser = Parser::new("abc");
let start = parser.position();
parser.next().unwrap(); // advance past `abc`
let end = parser.position();
let _ = parser.slice(end..start);
}
55 changes: 38 additions & 17 deletions src/tokenizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,27 @@ impl<'a> Parser<'a> {
/// Return a slice of the CSS input
#[inline]
pub fn slice(&self, range: Range<SourcePosition>) -> &'a str {
&self.input[range.start.0..range.end.0]
}

/// Like `slice_from`, but skips the bounds and char-boundary checks.
///
/// The caller must guarantee that `start_pos` is a char boundary that is
/// `<= self.position()`, which is always true for positions produced by the
/// tokenizer for the current input.
#[inline]
pub(crate) fn slice_from_unchecked(&self, start_pos: SourcePosition) -> &'a str {
self.slice_unchecked(start_pos..self.position())
}

/// Like `slice`, but skips the bounds and char-boundary checks.
///
/// The caller must guarantee that `range.start.0 <= range.end.0 <=
/// self.input.len()` and that both ends are char boundaries, which is always
/// true for positions produced by the tokenizer for the current input.
#[inline]
pub(crate) fn slice_unchecked(&self, range: Range<SourcePosition>) -> &'a str {
debug_assert!(range.start.0 <= range.end.0);
debug_assert!(self.input.is_char_boundary(range.start.0));
debug_assert!(self.input.is_char_boundary(range.end.0));
unsafe { self.input.get_unchecked(range.start.0..range.end.0) }
Expand Down Expand Up @@ -741,7 +762,7 @@ fn consume_whitespace<'a>(parser: &mut Parser<'a>, newline: bool) -> Token<'a> {
}
}
}
WhiteSpace(parser.slice_from(start_position))
WhiteSpace(parser.slice_from_unchecked(start_position))
}

// Check for sourceMappingURL or sourceURL comments and update the
Expand Down Expand Up @@ -776,7 +797,7 @@ fn consume_comment<'a>(parser: &mut Parser<'a>) -> &'a str {
parser.advance(1);
if parser.next_byte() == Some(b'/') {
parser.advance(1);
let contents = parser.slice(start_position..end_position);
let contents = parser.slice_unchecked(start_position..end_position);
check_for_source_map(parser, contents);
return contents
}
Expand All @@ -792,7 +813,7 @@ fn consume_comment<'a>(parser: &mut Parser<'a>) -> &'a str {
}
}
}
let contents = parser.slice_from(start_position);
let contents = parser.slice_from_unchecked(start_position);
check_for_source_map(parser, contents);
contents
}
Expand All @@ -815,20 +836,20 @@ fn consume_quoted_string<'a>(
let mut string_bytes;
loop {
if parser.is_eof() {
return Ok(parser.slice_from(start_pos).into());
return Ok(parser.slice_from_unchecked(start_pos).into());
}
match_byte! { parser.next_byte_unchecked(),
b'"' => {
if !single_quote {
let value = parser.slice_from(start_pos);
let value = parser.slice_from_unchecked(start_pos);
parser.advance(1);
return Ok(value.into())
}
parser.advance(1);
}
b'\'' => {
if single_quote {
let value = parser.slice_from(start_pos);
let value = parser.slice_from_unchecked(start_pos);
parser.advance(1);
return Ok(value.into())
}
Expand All @@ -840,11 +861,11 @@ fn consume_quoted_string<'a>(
// * so is the current position (which is before '\\' or '\0'
//
// So `string_bytes` is well-formed UTF-8.
string_bytes = parser.slice_from(start_pos).as_bytes().to_owned();
string_bytes = parser.slice_from_unchecked(start_pos).as_bytes().to_owned();
break
}
b'\n' | b'\r' | b'\x0C' => {
return Err(parser.slice_from(start_pos).into())
return Err(parser.slice_from_unchecked(start_pos).into())
},
b'\x80'..=b'\xBF' => { parser.consume_continuation_byte(); }
b'\xF0'..=b'\xFF' => { parser.consume_4byte_intro(); }
Expand Down Expand Up @@ -971,7 +992,7 @@ fn consume_name<'a>(parser: &mut Parser<'a>) -> CowRcStr<'a> {
loop {
parser.advance_while(|b| IS_SIMPLE_NAME_BYTE[b as usize]);
if parser.is_eof() {
return parser.slice_from(start_pos).into();
return parser.slice_from_unchecked(start_pos).into();
}
match_byte! { parser.next_byte_unchecked(),
b'\\' | b'\0' => {
Expand All @@ -980,13 +1001,13 @@ fn consume_name<'a>(parser: &mut Parser<'a>) -> CowRcStr<'a> {
// * so is the current position (which is before '\\' or '\0'
//
// So `value_bytes` is well-formed UTF-8.
value_bytes = parser.slice_from(start_pos).as_bytes().to_owned();
value_bytes = parser.slice_from_unchecked(start_pos).as_bytes().to_owned();
break
}
b'\x80'..=b'\xBF' => { parser.consume_continuation_byte(); }
b'\xF0'..=b'\xFF' => { parser.consume_4byte_intro(); }
_b => {
return parser.slice_from(start_pos).into();
return parser.slice_from_unchecked(start_pos).into();
}
}
}
Expand Down Expand Up @@ -1235,15 +1256,15 @@ fn consume_unquoted_url<'a>(parser: &mut Parser<'a>) -> Result<Token<'a>, ()> {
let mut string_bytes: Vec<u8>;
loop {
if parser.is_eof() {
return UnquotedUrl(parser.slice_from(start_pos).into());
return UnquotedUrl(parser.slice_from_unchecked(start_pos).into());
}
match_byte! { parser.next_byte_unchecked(),
b' ' | b'\t' | b'\n' | b'\r' | b'\x0C' => {
let value = parser.slice_from(start_pos);
let value = parser.slice_from_unchecked(start_pos);
return consume_url_end(parser, start_pos, value.into())
}
b')' => {
let value = parser.slice_from(start_pos);
let value = parser.slice_from_unchecked(start_pos);
parser.advance(1);
return UnquotedUrl(value.into())
}
Expand All @@ -1258,7 +1279,7 @@ fn consume_unquoted_url<'a>(parser: &mut Parser<'a>) -> Result<Token<'a>, ()> {
// * so is the current position (which is before '\\' or '\0'
//
// So `string_bytes` is well-formed UTF-8.
string_bytes = parser.slice_from(start_pos).as_bytes().to_owned();
string_bytes = parser.slice_from_unchecked(start_pos).as_bytes().to_owned();
break
}
b'\x80'..=b'\xBF' => { parser.consume_continuation_byte(); }
Expand Down Expand Up @@ -1353,7 +1374,7 @@ fn consume_unquoted_url<'a>(parser: &mut Parser<'a>) -> Result<Token<'a>, ()> {
while !parser.is_eof() {
match_byte! { parser.next_byte_unchecked(),
b')' => {
let contents = parser.slice_from(start_pos).into();
let contents = parser.slice_from_unchecked(start_pos).into();
parser.advance(1);
return BadUrl(contents)
}
Expand All @@ -1371,7 +1392,7 @@ fn consume_unquoted_url<'a>(parser: &mut Parser<'a>) -> Result<Token<'a>, ()> {
}
}
}
BadUrl(parser.slice_from(start_pos).into())
BadUrl(parser.slice_from_unchecked(start_pos).into())
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/unicode_range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl UnicodeRange {
// This deviates from the spec in case there are CSS comments
// between tokens in the middle of one <unicode-range>,
// but oh well…
let concatenated_tokens = input.slice_from(after_u);
let concatenated_tokens = input.slice_from_unchecked(after_u);

let range = match parse_concatenated(concatenated_tokens.as_bytes()) {
Ok(range) => range,
Expand Down