[issue15994] memoryview to freed memory can cause segfault

Richard Oudkerk report at bugs.python.org
Thu Sep 20 22:37:22 CEST 2012


New submission from Richard Oudkerk:

A memoryview which does not own a reference to its base object can point to freed or reallocated memory.  For instance the following segfaults for me on Windows and Linux.


import io

class File(io.RawIOBase):
    def readinto(self, buf):
        global view
        view = buf
    def readable(self):
        return True

f = io.BufferedReader(File())
f.read(1)                       # get view of buffer used by BufferedReader
del f                           # deallocate buffer
view = view.cast('P')
L = [None] * len(view)          # create list whose array has same size
                                # (this will probably coincide with view)
view[0] = 0                     # overwrite first item with NULL
print(L[0])                     # segfault: dereferencing NULL


I realize there are easier ways to make Python segfault, so maybe this should not be considered a serious issue.  But I think there should be some way of guaranteeing that a memoryview will not try to access memory which has already been freed.

In #15903 skrah proposed exposing memory_release() as PyBuffer_Release().  However, I don't think that would necessarily invalidate all exports of the buffer.

Alternatively, one could incref the buffered reader object and set mview->mbuf->obj to it.  Maybe we could have

    PyMemoryView_FromMemoryEx(char *mem, Py_ssize_t size, int flags, PyObject *obj)

which guarantees that if obj is non-NULL then it will not be garbage collected before the memoryview.  This should *not* expose obj as an attribute of the memoryview.

----------
messages: 170846
nosy: sbt, skrah
priority: normal
severity: normal
status: open
title: memoryview to freed memory can cause segfault
type: crash
versions: Python 3.4

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue15994>
_______________________________________


More information about the Python-bugs-list mailing list