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

Make Input::new guard against incorrect AsRef implementations #1154

Merged
merged 1 commit into from
Jan 21, 2024
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
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
1.10.3 (TBD)
============
This is a new patch release that fixes the feature configuration of optional
dependencies.
dependencies, and fixes an unsound use of bounds check elision.

Bug fixes:

* [BUG #1147](https://github.com/rust-lang/regex/issues/1147):
Set `default-features=false` for the `memchr` and `aho-corasick` dependencies.
* [BUG #1154](https://github.com/rust-lang/regex/pull/1154):
Fix unsound bounds check elision.


1.10.2 (2023-10-16)
Expand Down
28 changes: 26 additions & 2 deletions regex-automata/src/util/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,14 @@ impl<'h> Input<'h> {
/// Create a new search configuration for the given haystack.
#[inline]
pub fn new<H: ?Sized + AsRef<[u8]>>(haystack: &'h H) -> Input<'h> {
// Perform only one call to `haystack.as_ref()` to protect from incorrect
// implementations that return different values from multiple calls.
// This is important because there's code that relies on `span` not being
// out of bounds with respect to the stored `haystack`.
let haystack = haystack.as_ref();
Input {
haystack: haystack.as_ref(),
span: Span { start: 0, end: haystack.as_ref().len() },
haystack,
span: Span { start: 0, end: haystack.len() },
anchored: Anchored::No,
earliest: false,
}
Expand Down Expand Up @@ -1966,4 +1971,23 @@ mod tests {
let expected_size = 3 * core::mem::size_of::<usize>();
assert_eq!(expected_size, core::mem::size_of::<MatchErrorKind>());
}

#[test]
fn incorrect_asref_guard() {
struct Bad(std::cell::Cell<bool>);

impl AsRef<[u8]> for Bad {
fn as_ref(&self) -> &[u8] {
if self.0.replace(false) {
&[]
} else {
&[0; 1000]
}
}
}

let bad = Bad(std::cell::Cell::new(true));
let input = Input::new(&bad);
assert!(input.end() <= input.haystack().len());
}
}