Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 305bc9e

Browse files
committed
Issue #10955: Fix a potential crash when trying to mmap() a file past its
length. Initial patch by Ross Lagerwall. This fixes a regression introduced by r88022.
1 parent 9ee94de commit 305bc9e

3 files changed

Lines changed: 27 additions & 0 deletions

File tree

Lib/test/test_mmap.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,19 @@ def test_length_0_offset(self):
334334
with mmap.mmap(f.fileno(), 0, offset=65536, access=mmap.ACCESS_READ) as mf:
335335
self.assertRaises(IndexError, mf.__getitem__, 80000)
336336

337+
def test_length_0_large_offset(self):
338+
# Issue #10959: test mapping of a file by passing 0 for
339+
# map length with a large offset doesn't cause a segfault.
340+
if not hasattr(os, "stat"):
341+
self.skipTest("needs os.stat")
342+
343+
with open(TESTFN, "wb") as f:
344+
f.write(115699 * b'm') # Arbitrary character
345+
346+
with open(TESTFN, "w+b") as f:
347+
self.assertRaises(ValueError, mmap.mmap, f.fileno(), 0,
348+
offset=2147418112)
349+
337350
def test_move(self):
338351
# make move works everywhere (64-bit format problem earlier)
339352
f = open(TESTFN, 'wb+')

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ Core and Builtins
1616
Library
1717
-------
1818

19+
- Issue #10955: Fix a potential crash when trying to mmap() a file past its
20+
length. Initial patch by Ross Lagerwall.
21+
1922
- Issue #10898: Allow compiling the posix module when the C library defines
2023
a symbol named FSTAT.
2124

Modules/mmapmodule.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1116,6 +1116,11 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
11161116
# endif
11171117
if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
11181118
if (map_size == 0) {
1119+
if (offset >= st.st_size) {
1120+
PyErr_SetString(PyExc_ValueError,
1121+
"mmap offset is greater than file size");
1122+
return NULL;
1123+
}
11191124
map_size = st.st_size - offset;
11201125
} else if ((size_t)offset + (size_t)map_size > st.st_size) {
11211126
PyErr_SetString(PyExc_ValueError,
@@ -1300,6 +1305,12 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
13001305
else
13011306
m_obj->size = low;
13021307
#endif
1308+
if (offset >= m_obj->size) {
1309+
PyErr_SetString(PyExc_ValueError,
1310+
"mmap offset is greater than file size");
1311+
Py_DECREF(m_obj);
1312+
return NULL;
1313+
}
13031314
m_obj->size -= offset;
13041315
} else {
13051316
m_obj->size = map_size;

0 commit comments

Comments
 (0)