`Parser::slice` and `Parser::slice_from` can trigger UB in safe Rust via unchecked slicing · Issue #459 · servo/rust-cssparser · GitHub
Skip to content

Parser::slice and Parser::slice_from can trigger UB in safe Rust via unchecked slicing #459

Open

Description

@randy3k

Parser::slice (and Parser::slice_from) in src/tokenizer.rs calls self.input.get_unchecked(range.start.0..range.end.0) without verifying range.start.0 <= range.end.0 or range.end.0 <= self.input.len():

#[inline]
pub fn slice(&self, range: Range<SourcePosition>) -> &'a str {
    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) }
}

Safe callers can trigger undefined behavior without unsafe:

  1. Passing an inverted range p1..p0 where p1 > p0 (both is_char_boundary assertions still pass in debug builds, and end - start underflows in get_unchecked).
  2. Calling parser.reset(&saved_state) to rewind the parser position and then calling parser.slice_from(later_pos).
  3. Passing a SourcePosition obtained from another Parser with a longer input string in release builds where debug_assert! is disabled.

Replacing unsafe { self.input.get_unchecked(range.start.0..range.end.0) } with &self.input[range.start.0..range.end.0] avoids the soundness issue.

Activity

  1. emilio commented on Oct 17, 2026

    @emilio
    Member

    Patch welcome, though I think at least for the internal callers we want to avoid the overhead of checking codepoint boundaries etc, see d320a8e which introduced the unsafe.

    I guess when I wrote that I didn't realize they were exposed via Parser (I made them pub(crate)).

    Calling parser.reset(&saved_state) to rewind the parser position and then calling parser.slice_from(later_pos).

    Can you elaborate why this one is an issue tho?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions