Search code examples
pythoncrashpython-3.5

How can I cause Python 3.5 to crash?


We are using embedded cpython as a scripting language in our app. We are modifying our sys.path at startup to make sure that we don't execute code from outside our app, but a user with a sitecustomize.py in their PYTHONPATH is causing code to execute before we have a chance to fix sys.path, and we believe their code has a hard crash (not an exception, which site.py will catch and handle gracefully).

I believe the correct fix is to simply clear the PYTHONPATH variable from the environment before we initialize python, but I can't test it properly because I can't recreate the problem.

The simplest way I've found is using ctypes to write to memory, such as:

import ctypes
p = (ctypes.c_char).from_address(0)
while True:
  p[0] = 0
  p = p + 1

But in Python 3.5, it doesn't allow me to write to c_char types, giving the error "TypeError: 'c_char' object does not support item assignment".

I've tried a few of the methods available in https://wiki.python.org/moin/CrashingPython to no avail.

Is there a reliable way to crash python 3.5 from pure Python code?


Solution

  • There are plenty of ways through ctypes. For example, a corrected version of your code:

    p = ctypes.pointer(ctypes.c_char.from_address(5))
    p[0] = b'x'
    

    If you don't want to use ctypes, you could trigger a C stack overflow in the dict.__repr__ implementation:

    x = {}
    for i in range(1000000):
        x = {1: x}
    repr(x)
    

    This might get patched in a future Python release, but for now, it should produce a hard crash.

    There are also ways to do it by constructing your own bytecode objects, since Python does almost nothing to make sure that the bytecode it's executing makes sense.