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?
To shut down the computer/PC/laptop by using a Python script, you have to use the os. system() function with the code “ shutdown /s /t 1 ” .
While a lot of effort has gone into making it difficult or impossible to crash the Python interpreter in normal usage, there are lots fairly easy ways to crash the interpreter.
Here is a simple way to crash python:
def crash():
try:
crash()
except:
crash()
crash()
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.
Simply put 0 / 0 on the line of code you want to trigger the crash. You will get a ZeroDivisionError
I think this is the easiest way to force a crash
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With