Skip to content

Commit

Permalink
Fix nullptr-with-nonzero-offset bugs found by UBSan.
Browse files Browse the repository at this point in the history
Change-Id: Ic94c887b3ba4211bec5f7eb096f06fe5bca53b70
Reviewed-on: https://code-review.googlesource.com/c/re2/+/48852
Reviewed-by: Paul Wankadia <[email protected]>
  • Loading branch information
junyer committed Nov 25, 2019
1 parent 4f6e130 commit bb8e777
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
4 changes: 4 additions & 0 deletions re2/bitstate.cc
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,10 @@ bool BitState::Search(const StringPiece& text, const StringPiece& context,
cap_[0] = p;
if (TrySearch(prog_->start(), p)) // Match must be leftmost; done.
return true;
// Avoid invoking undefined behavior (arithmetic on a null pointer)
// by simply not continuing the loop.
if (p == NULL)
break;
}
return false;
}
Expand Down
23 changes: 20 additions & 3 deletions re2/nfa.cc
Original file line number Diff line number Diff line change
Expand Up @@ -382,10 +382,15 @@ int NFA::Step(Threadq* runq, Threadq* nextq, int c, const StringPiece& context,
break;

case kInstMatch: {
// Avoid invoking undefined behavior when p happens
// to be null - and p-1 would be meaningless anyway.
if (p == NULL)
// Avoid invoking undefined behavior (arithmetic on a null pointer)
// by storing p instead of p-1. (What would the latter even mean?!)
// This complements the special case in NFA::Search().
if (p == NULL) {
CopyCapture(match_, t->capture);
match_[1] = p;
matched_ = true;
break;
}

if (endmatch_ && p-1 != etext_)
break;
Expand Down Expand Up @@ -593,6 +598,18 @@ bool NFA::Search(const StringPiece& text, const StringPiece& const_context,
fprintf(stderr, "dead\n");
break;
}

// Avoid invoking undefined behavior (arithmetic on a null pointer)
// by simply not continuing the loop.
// This complements the special case in NFA::Step().
if (p == NULL) {
(void)Step(runq, nextq, p < etext_ ? p[0] & 0xFF : -1, context, p);
DCHECK_EQ(runq->size(), 0);
using std::swap;
swap(nextq, runq);
nextq->clear();
break;
}
}

for (Threadq::iterator i = runq->begin(); i != runq->end(); ++i)
Expand Down
4 changes: 4 additions & 0 deletions re2/testing/backtrack.cc
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ bool Backtracker::Search(const StringPiece& text, const StringPiece& context,
cap_[0] = p;
if (Visit(prog_->start(), p)) // Match must be leftmost; done.
return true;
// Avoid invoking undefined behavior (arithmetic on a null pointer)
// by simply not continuing the loop.
if (p == NULL)
break;
}
return false;
}
Expand Down

0 comments on commit bb8e777

Please sign in to comment.