From 6d5019244d9a954356b70e81cf9181dbad2b5f84 Mon Sep 17 00:00:00 2001 From: Prince Roshan Date: Sat, 29 Apr 2023 19:53:00 +0530 Subject: [PATCH] gh-103987: fix crash in mmap module --- Lib/test/test_mmap.py | 17 +++++++++++++++++ Modules/mmapmodule.c | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py index 213a44d56f37b3..9ac72d37fdb30c 100644 --- a/Lib/test/test_mmap.py +++ b/Lib/test/test_mmap.py @@ -264,6 +264,23 @@ def test_bad_file_desc(self): # Try opening a bad file descriptor... self.assertRaises(OSError, mmap.mmap, -2, 4096) + def test_if_crash(self): # test for issue gh-103987 + with open("TESTFN", "w+") as f: + f.write("foobar") + f.flush() + + class X(object): + def __index__(self): + m.close() + return 1 + + m = mmap.mmap(f.fileno(), 6, access=mmap.ACCESS_READ) + self.assertEqual(m[1], 111) + with self.assertRaises(ValueError): + m[X()] # should not crash + + m.close() + def test_tougher_find(self): # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2, # searching for data with embedded \0 bytes didn't work. diff --git a/Modules/mmapmodule.c b/Modules/mmapmodule.c index a470dd3c2f3bba..eaacb847eb810b 100644 --- a/Modules/mmapmodule.c +++ b/Modules/mmapmodule.c @@ -933,9 +933,9 @@ mmap_item(mmap_object *self, Py_ssize_t i) static PyObject * mmap_subscript(mmap_object *self, PyObject *item) { - CHECK_VALID(NULL); if (PyIndex_Check(item)) { Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); + CHECK_VALID(NULL); if (i == -1 && PyErr_Occurred()) return NULL; if (i < 0)