[New-bugs-announce] [issue3999] Real segmentation fault handler

STINNER Victor report at bugs.python.org
Tue Sep 30 03:10:12 CEST 2008


New submission from STINNER Victor <victor.stinner at haypocalc.com>:

I would like to be able to catch SIGSEGV in my Python code! So I 
started to hack Python trunk to support this feature. The idea is to 
use a signal handler which call longjmp(), and add setjmp() at 
Py_EvalFrameEx() enter.

See attached ("small") patch: segfault.patch

Example read.py with the *evil* ctypes module of invalid memory read:
------------------- 8< --------------
from ctypes import string_at

def fault():
    text = string_at(1, 10)
    print("text = {0!r}".format(text))

def test():
    print("test: 1")
    try:
        fault()
    except MemoryError, err:
        print "ooops!"
        print err

    print("test: 2")
    try:
        fault()
    except MemoryError, err:
        print "ooops!"
        print err

    print("test: end")

def main():
    test()

if __name__ == "__main__":
    main()
------------------- 8< --------------

Result:
------------------- 8< --------------
$ python read.py
test: 1
sizeof()=160
ooops!
segmentation fault
test: 2
sizeof()=160
ooops!
segmentation fault
test: end
------------------- 8< --------------

Example bug1.py of a stack overflow:
----------
loop = None,
for i in xrange(10**5):
    loop = loop, None
----------

Result:
----------
$ python -i bug1.py

(((((((((...Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError: segmentation fault

----------

Python is able to restore a valid state (stack/heap) after a 
segmentation fault and raise a classical Python exception (I choosed 
MemoryError, but it could be a specific exception).

On my computer (Ubuntu Gutsy/i386), each segfault_frame takes 
sizeof(sigjmpbuf) + sizeof(void*) = 160 bytes, allocated on the stack. 
I don't know if it's huge or not, but that will limit the number of 
recursive calls. The feature can be optional if we add a configure 
option and some #ifdef/#endif. A dedicated stack is needed to be call 
the signal handler on stack overflow error. I choosed 4 KB, but since 
I only call longjmp(), smaller stack might also works.

Does other VM support such feature? JVM, Mono, .NET, etc. ?

I had the idea of catching SIGSEGV after reading the issue 1069092 
(stack overflow because of too many recursive calls).

----------
files: segfault.patch
keywords: patch
messages: 74060
nosy: haypo
severity: normal
status: open
title: Real segmentation fault handler
Added file: http://bugs.python.org/file11659/segfault.patch

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


More information about the New-bugs-announce mailing list