diff --git a/src/rules_and_declarations.rs b/src/rules_and_declarations.rs index 8a39a54b..d7aeffce 100644 --- a/src/rules_and_declarations.rs +++ b/src/rules_and_declarations.rs @@ -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(), ) })); @@ -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(), ) })); @@ -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(), ) })); @@ -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`. @@ -500,7 +506,7 @@ where result.map_err(|e| { ( e, - input.slice_from(start.position()), + input.slice_from_unchecked(start.position()), start.source_location(), ) }) @@ -513,7 +519,7 @@ where }; Err(( error, - input.slice(start.position()..end_position), + input.slice_unchecked(start.position()..end_position), start.source_location(), )) } diff --git a/src/tests.rs b/src/tests.rs index d2fecbed..a13a665d 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -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"); +} + +/// 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] +#[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); +} diff --git a/src/tokenizer.rs b/src/tokenizer.rs index 07342cf6..b77b0503 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -294,6 +294,27 @@ impl<'a> Parser<'a> { /// Return a slice of the CSS input #[inline] pub fn slice(&self, range: Range) -> &'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) -> &'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) } @@ -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 @@ -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 } @@ -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 } @@ -815,12 +836,12 @@ 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()) } @@ -828,7 +849,7 @@ fn consume_quoted_string<'a>( } 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()) } @@ -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(); } @@ -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' => { @@ -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(); } } } @@ -1235,15 +1256,15 @@ fn consume_unquoted_url<'a>(parser: &mut Parser<'a>) -> Result, ()> { let mut string_bytes: Vec; 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()) } @@ -1258,7 +1279,7 @@ fn consume_unquoted_url<'a>(parser: &mut Parser<'a>) -> Result, ()> { // * 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(); } @@ -1353,7 +1374,7 @@ fn consume_unquoted_url<'a>(parser: &mut Parser<'a>) -> Result, ()> { 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) } @@ -1371,7 +1392,7 @@ fn consume_unquoted_url<'a>(parser: &mut Parser<'a>) -> Result, ()> { } } } - BadUrl(parser.slice_from(start_pos).into()) + BadUrl(parser.slice_from_unchecked(start_pos).into()) } } diff --git a/src/unicode_range.rs b/src/unicode_range.rs index 5d69507e..5de62930 100644 --- a/src/unicode_range.rs +++ b/src/unicode_range.rs @@ -40,7 +40,7 @@ impl UnicodeRange { // This deviates from the spec in case there are CSS comments // between tokens in the middle of one , // 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,