From 881d7afb66c97a98d00a736d9696c762e5866e0e Mon Sep 17 00:00:00 2001 From: Tobias Bucher Date: Sat, 23 Aug 2014 15:04:58 +0200 Subject: [PATCH] Fix a potential overflow in `core::str::Searcher::new` The overflow is mitigated by checking a sufficient condition for the less relation. Given the term `A - B < C` (`A`, `B` and `C` fixed size unsigned integers) one can check whether it holds, by evaluating `A < C || A - B < C`. --- src/libcore/str.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 076eb8bbe6aa3..8c0b278c7f8b2 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -562,7 +562,9 @@ enum Searcher { impl Searcher { fn new(haystack: &[u8], needle: &[u8]) -> Searcher { // FIXME: Tune this. - if needle.len() + 20 > haystack.len() { + // This checks whether mathematically (that is, not constrained by + // wrap-around of uint) `haystack.len() - 20 < needle.len()`. + if haystack.len() < 20 || haystack.len() - 20 < needle.len() { Naive(NaiveSearcher::new()) } else { let searcher = TwoWaySearcher::new(needle);