Skip to content

Commit

Permalink
Raise re2.error instead of crashing.
Browse files Browse the repository at this point in the history
Fixes #484.

Change-Id: I152b5ed8a6358d2d74f553bde2e66f2e50cfba1d
Reviewed-on: https://code-review.googlesource.com/c/re2/+/62890
Reviewed-by: Alex Chernyakhovsky <achernya@google.com>
Reviewed-by: Paul Wankadia <junyer@google.com>
  • Loading branch information
junyer committed Mar 18, 2024
1 parent db46d1e commit 1250a99
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
7 changes: 7 additions & 0 deletions python/_re2.cc
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,10 @@ class Filter {
}

std::vector<int> Match(py::buffer buffer, bool potential) const {
if (set_ == nullptr) {
py::pybind11_fail("Match() called before compiling");
}

auto bytes = buffer.request();
auto text = FromBytes(bytes);
std::vector<int> atoms;
Expand All @@ -243,6 +247,9 @@ class Filter {
};

PYBIND11_MODULE(_re2, module) {
// Translate exceptions thrown by py::pybind11_fail() into Python.
py::register_local_exception<std::runtime_error>(module, "Error");

module.def("CharLenToBytes", &CharLenToBytes);
module.def("BytesToCharLen", &BytesToCharLen);

Expand Down
5 changes: 3 additions & 2 deletions python/re2.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@
import _re2


class error(Exception):
pass
# pybind11 translates C++ exceptions to Python exceptions.
# We use that same Python exception class for consistency.
error = _re2.Error


class Options(_re2.RE2.Options):
Expand Down
7 changes: 7 additions & 0 deletions python/re2_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,13 @@ def test_match(self):
# Verify whether the underlying RE2 object is usable.
self.assertEqual(0, f.re(2).groups)

def test_issue_484(self):
# Previously, the shim would dereference a null pointer and crash.
f = re2.Filter()
with self.assertRaisesRegex(re2.error,
r'Match\(\) called before compiling'):
f.Match('')


if __name__ == '__main__':
absltest.main()

0 comments on commit 1250a99

Please sign in to comment.