[Python-Dev] Trap SIGSEGV and SIGFPE

Victor Stinner victor.stinner at haypocalc.com
Wed Dec 10 12:06:49 CET 2008


Hi,
I published a new version of my fault handler: it installs an handler for 
signals SIGFPE and SIGSEGV. Using it, it's possible to catch them and 
continue the execution of your Python program. Example:
 try:
 call_evil_code()
 except MemoryError:
 print "A segfault? Haha, I don't care!"
 print "continue the execution"
(yes, it's possible to continue the execution after a segmentation fault!)
Handled errors:
 - Segmentation fault:
 * invalid memory read
 * invalid memory write
 * stack overflow (stack pointer outside the stack memory)
 - SIGFPE
 * division by zero
 * floating point error?
Such errors may occurs from external libraries (written in C)... or Python 
builtin libraries (eg. imageop). The handler is now only used in 
Py_EvalFrameEx(), but it could be used anywhere.
The patch uses sigsetjmp() in Py_EvalFrameEx() to set a "check point", and 
siglongjmp() in the signal handler to go back to the check point. It also 
uses a separated stack for the signal handler, because on stack overflow you 
can not use the stack (ex: unable to call any function!). With MAXDEPTH=100, 
the memory footprint is ~20 KB. If you call Py_EvalFrameEx() more than 
MAXDEPTH times, the handler will go back to the frame #MAXDEPTH on error (you 
loose the last entries in the Python traceback).
sigsetjmp()/siglongjmp() should be available on many OS. I just know that it 
works perfectly on Linux. sigaltstack() is needed to recover after a stack 
overflow, but other errors can be catched without it.
I didn't run any benchmark yet, but it would be interresting ;-) Changing 
MAXDEPTH constant may changes the speed with many recursive calls (eg. 
MAXDEPTH=1 only set a check for the first call to Py_EvalFrameEx()).
I would appreciate a review, especially for the patch in Python/ceval.c.
-- 
Victor Stinner aka haypo
http://www.haypocalc.com/blog/


More information about the Python-Dev mailing list

AltStyle によって変換されたページ (->オリジナル) /