Try using Memory.patchCode to achieve this. Here's a short example.
int test() { return 1024; } int main(int argc, char **argv) { printf("%d\n", test()); return 0; }
When compiled this looks like
[0x00400560]> s sym.test [0x00400656]> pdf ┌ (fcn) sym.test 11 │ sym.test (); │ ; CALL XREF from main @ 0x400670 │ 0x00400656 55 push rbp │ 0x00400657 4889e5 mov rbp, rsp │ 0x0040065a b800040000 mov eax, 0x400 ; 1024 │ 0x0040065f 5d pop rbp └ 0x00400660 c3 ret [0x00400656]> s sym.main [0x00400661]> pdf ┌ (fcn) main 44 │ int main (int argc, char **argv, char **envp); │ ; var char **var_10h @ rbp-0x10 │ ; var int32_t var_4h @ rbp-0x4 │ ; arg int argc @ rdi │ ; arg char **argv @ rsi │ ; DATA XREF from entry0 @ 0x40057d │ 0x00400661 55 push rbp │ 0x00400662 4889e5 mov rbp, rsp │ 0x00400665 4883ec10 sub rsp, 0x10 │ 0x00400669 897dfc mov dword [var_4h], edi ; argc │ 0x0040066c 488975f0 mov qword [var_10h], rsi ; argv │ 0x00400670 e8e1ffffff call sym test() ; sym.test │ 0x00400675 89c6 mov esi, eax │ 0x00400677 bf24084000 mov edi, 0x400824 ; const char *format │ 0x0040067c b800000000 mov eax, 0 │ 0x00400681 e89afeffff call sym.imp.printf ; int printf(const char *format) │ 0x00400686 b800000000 mov eax, 0 │ 0x0040068b c9 leave └ 0x0040068c c3 ret
At 0x0040065a, the constant 1024(0x400) is copied to eax. When run this looks like
$ ./test 1024
This can be patched at runtime by frida using patchCode
var pc = new NativePointer(0x0040065a) Memory.patchCode(pc, 5, function (code) { var cw = new X86Writer(code, { pc: pc }); cw.putMovRegU32('eax', 999); cw.flush(); });
When run
$ frida -q -l patch_code.js -f ./test --no-pause Spawned `./test`. Resuming main thread! 999 Process terminated
Another method of hooking a function is to use an Interceptor with onEnter to access args and onLeave to access the return value.
function hook(address) { Interceptor.attach(address, { onEnter: function (args) { console.log(args[0]) }, onLeave: function (ret) { ret.replace(999) } }) }
Memory.patchCodeorMemory.writeByteArrayto write this instruction or its raw representation.