0

I'm trying to create a code object (Python 3.11) with modified co_code to another function, but I notice that the CodeType constructor seems to modify the inputted co_code.

For example:

import types
import random

def f(a):
    a = a + 1
    return a

codeobj = f.__code__

new_co_code = bytes([random.randint(0, 255) for _ in range(24)])
new_code = types.CodeType(
    codeobj.co_argcount,
    codeobj.co_posonlyargcount,  
    codeobj.co_kwonlyargcount,
    codeobj.co_nlocals,
    codeobj.co_stacksize,
    codeobj.co_flags,
    new_co_code,
    codeobj.co_consts,
    codeobj.co_names,
    codeobj.co_varnames,
    codeobj.co_filename,
    codeobj.co_name,
    codeobj.co_qualname,
    codeobj.co_firstlineno,
    codeobj.co_lnotab,
    codeobj.co_exceptiontable,
)

print(new_co_code)
print(new_code.co_code)

# this assertion will generally fail
assert new_co_code == new_code.co_code
"""
example output:

b'\xe6\x8f\xdb\xc8\xb8\xb86\xe6&a\x18\xfb\x11&\xbc\xce\xc0A\xedjg\x8a\xa4G'
b'\x00\x8f\x00\xc8\x00\xb86\xe6\x8ca\xab\xfb\x00\x00\x00\x00\x00\x00\x00\x00g\x8a\xa4G'
"""

I would assume the newly created code objects co_code would be the same as the parameter I input, but there seems to be some modification done before hand. The resulting code object if you call it will segfault anyways so I dont understand why any modification is needed.

Why does it modify it, and where can I see more documentation about it, the only documentation I see about CodeType is that its just defined as f.__code__ in types.py.

Abhishek G
  • 90
  • 6
  • CPython source for the constructor is here, if it helps: https://github.com/python/cpython/blob/6e850c30bb7085c80a97982d00c9c20e7d23ff84/Objects/codeobject.c#L545 – slothrop Jul 27 '23 at 08:46
  • Yeah from what I briefly saw it seems like it just memcpy's it with no modification here: https://github.com/python/cpython/blob/6e850c30bb7085c80a97982d00c9c20e7d23ff84/Objects/codeobject.c#L439, which is what confuses me. – Abhishek G Jul 27 '23 at 09:02
  • 1
    Not only: https://github.com/python/cpython/blob/6e850c30bb7085c80a97982d00c9c20e7d23ff84/Python/specialize.c#L275 – STerliakov Jul 27 '23 at 09:08
  • but wait that is in latest cpython, in 3.11, https://github.com/python/cpython/blob/3.11/Objects/codeobject.c its different, do you know wher the optimization is done here? – Abhishek G Jul 27 '23 at 09:30

0 Answers0