Let’s suppose I have a function:
int f1(int x){
// some more or less complicated operations on x
return x;
}
And that I have another function
int f2(int x){
// we simply return x
return x;
}
I would like to be able to do something like the following:
char* _f1 = (char*)f1;
char* _f2 = (char*)f2;
int i;
for (i=0; i<FUN_LENGTH; ++i){
f1[i] = f2[i];
}
I.e. I would like to interpret f1 and f2 as raw byte arrays and “overwrite f1 byte by byte” and thus, replace it by f2.
I know that usually callable code is write-protected, however, in my particular situation, you can simply overwrite the memory location where f1 is located. That is, I can copy the bytes over onto f1, but afterwards, if I call f1, the whole thing crashes.
So, is my approach possible in principle? Or are there some machine/implementation/whatsoever-dependent issues I have to take into consideration?
It would be easier to replace the first few bytes of
f1with a machinejumpinstruction to the beginning off2. That way, you won’t have to deal with any possible code relocation issues.Also, the information about how many bytes a function occupies (
FUN_LENGTHin your question) is normally not available at runtime. Using ajumpwould avoid that problem too.For x86, the relative jump instruction opcode you need is
E9(according to here). This is a 32-bit relative jump, which means you need to calculate the relative offset betweenf2andf1. This code might do it:The offset is taken from the end of the JMP instruction, so that’s why there is 5 added to the address of
f1in the offset calculation.It’s a good idea to step through the result with an assembly level debugger to make sure you’re poking the correct bytes. Of course, this is all not standards compliant so if it breaks you get to keep both pieces.