diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py index 08b0714da02..8f20d969661 100644 --- a/Lib/test/test_mmap.py +++ b/Lib/test/test_mmap.py @@ -334,6 +334,19 @@ class MmapTests(unittest.TestCase): with mmap.mmap(f.fileno(), 0, offset=65536, access=mmap.ACCESS_READ) as mf: self.assertRaises(IndexError, mf.__getitem__, 80000) + def test_length_0_large_offset(self): + # Issue #10959: test mapping of a file by passing 0 for + # map length with a large offset doesn't cause a segfault. + if not hasattr(os, "stat"): + self.skipTest("needs os.stat") + + with open(TESTFN, "wb") as f: + f.write(115699 * b'm') # Arbitrary character + + with open(TESTFN, "w+b") as f: + self.assertRaises(ValueError, mmap.mmap, f.fileno(), 0, + offset=2147418112) + def test_move(self): # make move works everywhere (64-bit format problem earlier) f = open(TESTFN, 'wb+') diff --git a/Misc/NEWS b/Misc/NEWS index 03912b3cff1..44d39cf71d1 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -16,6 +16,9 @@ Core and Builtins Library ------- +- Issue #10955: Fix a potential crash when trying to mmap() a file past its + length. Initial patch by Ross Lagerwall. + - Issue #10898: Allow compiling the posix module when the C library defines a symbol named FSTAT. diff --git a/Modules/mmapmodule.c b/Modules/mmapmodule.c index f3b2f503dfd..a9049ed1cf9 100644 --- a/Modules/mmapmodule.c +++ b/Modules/mmapmodule.c @@ -1116,6 +1116,11 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict) # endif if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) { if (map_size == 0) { + if (offset >= st.st_size) { + PyErr_SetString(PyExc_ValueError, + "mmap offset is greater than file size"); + return NULL; + } map_size = st.st_size - offset; } else if ((size_t)offset + (size_t)map_size > st.st_size) { PyErr_SetString(PyExc_ValueError, @@ -1300,6 +1305,12 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict) else m_obj->size = low; #endif + if (offset >= m_obj->size) { + PyErr_SetString(PyExc_ValueError, + "mmap offset is greater than file size"); + Py_DECREF(m_obj); + return NULL; + } m_obj->size -= offset; } else { m_obj->size = map_size;