dl + getenv (without arguments) = segfault (python2.p2, python2.3)

Thomas Heller theller at python.net
Thu Aug 7 03:19:18 EDT 2003


Carl Banks <imbosol at aerojockey.com> writes:

> Skip Montanaro wrote:
>> 
>>    Xavier> Do note that my previous e-mail was not implying my possible
>>    Xavier> ignorance to the 'dl' module's functionality, but instead
>>    Xavier> inquiring wether there is or may be a solution in the future for
>>    Xavier> Python to handle such an erronous outcome.  And plus, segfaults
>>    Xavier> are ugly and make me cry.
>> 
>> I understand.  Given the nature of the problem here, I suspect the segfault
>> occurred in getenv() (I can't check to be sure, as I don't have the dl
>> module).  It's kind of hard for Python to gracefully recover when it doesn't
>> control the program counter.
>
> Theoretically, it could trap SIGSEGV and have the handler return
> control to Python.  (You'd probably have to wrap the dl call with
> setjmp, and use longjmp in the handler.)  I wouldn't count on the
> Python process being in great shape afterwards, though.

ctypes (but only when run under windows) handles this with win32
structured exception handling (c_char_p is the ctypes way to specify
'char *'):

  c:\test>python
  Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32
  Type "help", "copyright", "credits" or "license" for more information.
  >>> from ctypes import *
  >>> cdll.msvcrt.getenv.restype = c_char_p
  >>> cdll.msvcrt.getenv("windir")
  'C:\\WINDOWS'
  >>> cdll.msvcrt.getenv(32)
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  WindowsError: exception: access violation
  >>>

ctypes is cross platform, but it doesn't trap SIGSEGV as Carl
suggested. I wonder if someone comes up with a patch <wink>.

Having said that, it is possible to specify the arguments that getenv
accepts, and so at least make it somewhat harder to crash it:

  >>> cdll.msvcrt.getenv.argtypes = [c_char_p]
  >>> cdll.msvcrt.getenv(32)
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  TypeError: while constructing argument 1:
  string expected instead of int instance
  >>> cdll.msvcrt.getenv("PATH")
  'C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;.....'
  >>>

ctypes lives at <http://starship.python.net/crew/theller/ctypes/>

Thomas




More information about the Python-list mailing list