Skip to content

Instantly share code, notes, and snippets.

@trillllian
Created June 28, 2025 02:10
Show Gist options
  • Save trillllian/3b50ae8ec75741ef9acd6c0bcab918d5 to your computer and use it in GitHub Desktop.
Save trillllian/3b50ae8ec75741ef9acd6c0bcab918d5 to your computer and use it in GitHub Desktop.
speeding up infinite loops in python
"""
have you ever wanted to make your infinite loops terminate a little
quicker? well, now you can!
python -i fuckery.py
>>> mangle()
>>> while True:
... pass
>>> # finishes instantly!
linux only, cpython 3.9+
note that it only works on code that is parsed after mangle() is
called, i.e. code in the same file as mangle() will not be affected.
"""
import ctypes
def find_data(prot):
maps = open("/proc/self/maps").read()
modname = 'libpython3' if 'libpython3' in maps else '/bin/python3'
for x in maps.splitlines():
row = x.split()
if row[1] == prot and modname in row[-1]:
yield range(*[int(x, 16) for x in row[0].split('-')])
def mangle():
ptr_sz = ctypes.sizeof(ctypes.c_void_p)
data = next(find_data('rw-p'))
rodata = list(find_data('r--p'))
trues, falses = [], []
for x in data[::ptr_sz]:
ptr = ctypes.c_void_p.from_address(x).value
if ptr and any(ptr in r for r in rodata):
if ctypes.string_at(ptr, 5) == b'True\0': trues += [x]
elif ctypes.string_at(ptr, 6) == b'False\0': falses += [x]
[true], [false] = trues, falses
int32_at = ctypes.c_int32.from_address
int32_at(true + ptr_sz).value = int32_at(false + ptr_sz).value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment