Skip to content

Commit 1250a99

Browse files
committed
Raise re2.error instead of crashing.
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>
1 parent db46d1e commit 1250a99

3 files changed

Lines changed: 17 additions & 2 deletions

File tree

python/_re2.cc

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,10 @@ class Filter {
219219
}
220220

221221
std::vector<int> Match(py::buffer buffer, bool potential) const {
222+
if (set_ == nullptr) {
223+
py::pybind11_fail("Match() called before compiling");
224+
}
225+
222226
auto bytes = buffer.request();
223227
auto text = FromBytes(bytes);
224228
std::vector<int> atoms;
@@ -243,6 +247,9 @@ class Filter {
243247
};
244248

245249
PYBIND11_MODULE(_re2, module) {
250+
// Translate exceptions thrown by py::pybind11_fail() into Python.
251+
py::register_local_exception<std::runtime_error>(module, "Error");
252+
246253
module.def("CharLenToBytes", &CharLenToBytes);
247254
module.def("BytesToCharLen", &BytesToCharLen);
248255

python/re2.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,9 @@
3333
import _re2
3434

3535

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

3940

4041
class Options(_re2.RE2.Options):

python/re2_test.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,13 @@ def test_match(self):
477477
# Verify whether the underlying RE2 object is usable.
478478
self.assertEqual(0, f.re(2).groups)
479479

480+
def test_issue_484(self):
481+
# Previously, the shim would dereference a null pointer and crash.
482+
f = re2.Filter()
483+
with self.assertRaisesRegex(re2.error,
484+
r'Match\(\) called before compiling'):
485+
f.Match('')
486+
480487

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

0 commit comments

Comments
 (0)