Skip to content

Commit

Permalink
Refuse to rewrite when MaxSubmatch() is too large.
Browse files Browse the repository at this point in the history
Change-Id: I76f1d92586c3e0f4895ceb16fb019951843497f8
Reviewed-on: https://code-review.googlesource.com/c/re2/+/56870
Reviewed-by: Paul Wankadia <[email protected]>
  • Loading branch information
junyer committed May 27, 2020
1 parent 787495f commit aecba11
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
11 changes: 8 additions & 3 deletions re2/re2.cc
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,8 @@ bool RE2::Replace(std::string* str,
const StringPiece& rewrite) {
StringPiece vec[kVecSize];
int nvec = 1 + MaxSubmatch(rewrite);
if (nvec > 1 + re.NumberOfCapturingGroups())
return false;
if (nvec > static_cast<int>(arraysize(vec)))
return false;
if (!re.Match(*str, 0, str->size(), UNANCHORED, vec, nvec))
Expand All @@ -425,6 +427,8 @@ int RE2::GlobalReplace(std::string* str,
const StringPiece& rewrite) {
StringPiece vec[kVecSize];
int nvec = 1 + MaxSubmatch(rewrite);
if (nvec > 1 + re.NumberOfCapturingGroups())
return false;
if (nvec > static_cast<int>(arraysize(vec)))
return false;

Expand Down Expand Up @@ -497,9 +501,10 @@ bool RE2::Extract(const StringPiece& text,
std::string* out) {
StringPiece vec[kVecSize];
int nvec = 1 + MaxSubmatch(rewrite);
if (nvec > 1 + re.NumberOfCapturingGroups())
return false;
if (nvec > static_cast<int>(arraysize(vec)))
return false;

if (!re.Match(text, 0, text.size(), UNANCHORED, vec, nvec))
return false;

Expand Down Expand Up @@ -1012,8 +1017,8 @@ bool RE2::Rewrite(std::string* out,
int n = (c - '0');
if (n >= veclen) {
if (options_.log_errors()) {
LOG(ERROR) << "requested group " << n
<< " in regexp " << rewrite.data();
LOG(ERROR) << "invalid substitution \\" << n
<< " from " << veclen << " groups";
}
return false;
}
Expand Down
9 changes: 9 additions & 0 deletions re2/testing/re2_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,15 @@ TEST(RE2, Extract) {
ASSERT_EQ(s, "'foo'");
}

TEST(RE2, MaxSubmatchTooLarge) {
std::string s;
ASSERT_FALSE(RE2::Extract("foo", "f(o+)", "\\1\\2", &s));
s = "foo";
ASSERT_FALSE(RE2::Replace(&s, "f(o+)", "\\1\\2"));
s = "foo";
ASSERT_FALSE(RE2::GlobalReplace(&s, "f(o+)", "\\1\\2"));
}

TEST(RE2, Consume) {
RE2 r("\\s*(\\w+)"); // matches a word, possibly proceeded by whitespace
std::string word;
Expand Down

0 comments on commit aecba11

Please sign in to comment.