From c5be6485fb545894f64a8c000fa1f096413f45f2 Mon Sep 17 00:00:00 2001 From: Paul Mucur Date: Mon, 29 Mar 2021 11:56:53 +0100 Subject: [PATCH] Fix crash when scanning invalid regexp GitHub: https://github.com/mudge/re2/issues/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. --- ext/re2/re2.cc | 8 +++++++- spec/re2/scanner_spec.rb | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/ext/re2/re2.cc b/ext/re2/re2.cc index 41d5341..7372d85 100644 --- a/ext/re2/re2.cc +++ b/ext/re2/re2.cc @@ -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; diff --git a/spec/re2/scanner_spec.rb b/spec/re2/scanner_spec.rb index 89fddf1..b0d1744 100644 --- a/spec/re2/scanner_spec.rb +++ b/spec/re2/scanner_spec.rb @@ -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("")