Skip to content

Commit

Permalink
Fix crash when scanning invalid regexp
Browse files Browse the repository at this point in the history
GitHub: #52

As re2 will report the number of capturing groups for an invalid regular
expression as -1, we need to check whether a pattern is OK or not before
using the number to initialize any vectors, etc.

This was causing a crash when using RE2::Scanner#scan with an invalid
regular expression as we would attempt to initialize vectors with a
length of -1. Instead, set the number of capturing groups to 0 and rely
on re2's FindAndConsumeN returning false so we return nil to the user to
indicate no match was made.
  • Loading branch information
mudge committed Mar 29, 2021
1 parent 372b6df commit c5be648
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
8 changes: 7 additions & 1 deletion ext/re2/re2.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1251,7 +1251,13 @@ static VALUE re2_regexp_scan(VALUE self, VALUE text) {
c->input = new(nothrow) re2::StringPiece(StringValuePtr(text));
c->regexp = self;
c->text = text;
c->number_of_capturing_groups = p->pattern->NumberOfCapturingGroups();

if (p->pattern->ok()) {
c->number_of_capturing_groups = p->pattern->NumberOfCapturingGroups();
} else {
c->number_of_capturing_groups = 0;
}

c->eof = false;

return scanner;
Expand Down
6 changes: 6 additions & 0 deletions spec/re2/scanner_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@
expect(scanner.scan).to be_nil
end

it "returns nil if the regexp is invalid" do
r = RE2::Regexp.new('???', :log_errors => false)
scanner = r.scan("Foo bar")
expect(scanner.scan).to be_nil
end

it "returns an empty array if the input is empty" do
r = RE2::Regexp.new("")
scanner = r.scan("")
Expand Down

0 comments on commit c5be648

Please sign in to comment.