Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replace old patching method by more neat one #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

WolframAlph
Copy link

@WolframAlph WolframAlph commented Dec 6, 2023

Hi, thanks for this package! Current patching approach uses rax register to store hooked_PyEval_EvalFrameEx address. In order to preserve state, rax is pushed right before loading it with hooked_PyEval_EvalFrameEx address. Additionally nop is placed inside hooked_PyEval_EvalFrameEx acting as a placeholder for popping rax. All instructions from the beginning of hooked_PyEval_EvalFrameEx up to the address of nop are shifted by 1 down to insert pop rax as the very first instruction to restore state right after the jump. Instead of that we can skip using registers at all by manipulating stack. Steps are:

  1. Push low 32 bits of hooked_PyEval_EvalFrameEx. Since pushed value is 64 bits, only first 32 bits are correct. Remaining are garbage so far.
  2. Move high 32 bits as 4byte value into address (stack pointer + 4). This inserts missing high 32 bits of hooked_PyEval_EvalFrameEx address (previously garbage).
  3. Perform return from procedure. hooked_PyEval_EvalFrameEx 64bit address on top of the stack is popped by cpu and then it jumps to that address.

As a result: no state saving/restoration is needed and nop approach can be dropped.
This is done in such way because you cannot jump to absolute 64bit immediate address on x86_64 and you cannot push 64bit immediate value either.
You can also push 4 words (16bits) that represents function address and preform return. You cannot push 2x32 however. Matter of preference whether you do it like that or as I did but my way uses less memory.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant