How to recover Python function from memory address?
>> def spam():
... print("top secret function")
...
>>> print(spam)
<function spam at 0x7feccc97fb78>
>>> spam = "spam"
So, I am losing the link to the function spam
. Can I return it from this memory address: 0x7feccc97fb78?
>>> orig_spam_function = get_orig_func_from_memory_address("0x7feccc97fb78")
Edit (answer to the question):
Sorry for the lousy question, consider this case:
>>> from collections import defaultdict
>>> d = defaultdict(spam)
>>> d
defaultdict(<function spam at 0x7f597572c270>, {})
Thus, the function is not yet garbage collected. Can I restore it? Of course, in this case you can use the attribute default_factory
.
>>> d.default_factory
<function spam at 0x7f597572c270>
But imagine defaultdict
without an attribute default_factory
.
@thethetheourourtheye brings up a good point about the garbage collection function.
But if for some reason the function does not collect garbage, you can search for it in all existing objects:
def spam():
pass
spam2 = spam # keep a reference
print spam
=> <function spam at 0x56d69b0>
import gc
[ obj for obj in gc.get_objects() if id(obj) == 0x56d69b0 ]
=> [<function __main__.spam>]
( ), .
From the point of view of forensics, you could probably if you had to freeze execution immediately after the assignment operation and then check this location in memory (knowing how to analyze the memory structure of python), if you were careful, you could go back to some op code instructions, and from those that you could probably rewrite a function or something like that manually.