Yes, you are trying to write data to the function code, this is not possible because the executable code is not writable.
What are you trying to achieve?
I’m trying to write something similar to minhook that allows me to hook a specific address and inject my own logic.
For example, assume I have 2 functions add and hook:
add: ; int add(int a, int b) { return a + b; }
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], edi
mov DWORD PTR [rbp-8], esi
mov edx, DWORD PTR [rbp-4]
mov eax, DWORD PTR [rbp-8]
add eax, edx
pop rbp
ret
hook: ; int hook(int a, int b) { return 1; }
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], edi
mov DWORD PTR [rbp-8], esi
mov eax, 1
pop rbp
ret
To “hook” add I’d overwrite the first x bytes with an unconditional jump to hook
add:
mov %r10, <address of label
jmp %r10
mov DWORD PTR [rbp-4], edi
mov DWORD PTR [rbp-8], esi
mov edx, DWORD PTR [rbp-4]
mov eax, DWORD PTR [rbp-8]
add eax, edx
pop rbp
ret
That way I can intercept any calls to add with my own logic.
Basically I’m trying to write to the executable code.
Since it seems that you are on Linux, you could use mprotect. This requires a little alignment since you need to pass in a page-aligned address and size.