Skip to content

Instantly share code, notes, and snippets.

@leo60228
Created April 8, 2022 12:50
Show Gist options
  • Save leo60228/e69df70e7bbb25ff477ead13abd29ff8 to your computer and use it in GitHub Desktop.
Save leo60228/e69df70e7bbb25ff477ead13abd29ff8 to your computer and use it in GitHub Desktop.
# derived from https://github.com/DavidBuchanan314/unsafe-python
nogc = set()
def sizeof(obj):
return type(obj).__sizeof__(obj)
def get_aligned_tuple_and_bytes(prefix):
its_per_size = 4
tuples = []
byteses = []
for size in range(8, 64)[::-1]:
template = range(size)
suffix = b"A" * (size * 8 - len(prefix))
for _ in range(its_per_size):
tuples.append(tuple(template))
byteses.append(prefix + suffix)
bestdist = 9999999999
besttuple = None
bestbytes = None
pairs = [(t, b) for t in tuples for b in byteses]
for t, b in pairs:
dist = id(b) - id(t)
if dist > 0 and dist < bestdist:
bestdist = dist
besttuple = t
bestbytes = b
return (besttuple, bestbytes)
def fakeobj(addr):
ptr = addr.to_bytes(8, 'little')
nogc.add(ptr)
const_tuple, ref = get_aligned_tuple_and_bytes(ptr)
nogc.add(ref)
tuple_start = id(const_tuple) + sizeof(())
ref_addr = id(ref) + sizeof(b"") - 1
offset = (ref_addr - tuple_start) // 8
loader = eval("lambda: list(%s) if None else %s" % (",".join(map(str, range(1, offset))), offset)).__code__
newcode = loader.replace(co_consts=const_tuple)
makemagic = (lambda: None).__class__(newcode, {})
return makemagic()
def write_int(dst, src):
fake_bytearray = (1).to_bytes(8, 'little') + id(bytearray).to_bytes(8, 'little') + ((1<<63)-1).to_bytes(8, 'little') + (0).to_bytes(8, 'little') * 4
mem = fakeobj(id(fake_bytearray) + sizeof(b"") - 1)
for idx in range(sizeof(src)):
mem[id(dst) + idx] = mem[id(src) + idx]
write_int(1, 2)
a = 1
b = 2
print(a + b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment