Modify next Instruction in memory with gcc

553 views Asked by At

I want to modify next instruction before it fetches, in best answer of This post in foo function, *p points to the next instruction in main function. I want to modify content of where *p points at. For example I want to change the next instruction to a jump instruction. How to I can do this?

void foo()
{
    void** p = search((void**)&p, __builtin_return_address(0));
    // modify content of where *p points at.
}

int main()
{
    
    foo();
    //next instruction. *p points here
    return 0;
}

I want to do this with gcc compiler, on intel Core-i7 3632QM processor.

2

There are 2 answers

1
kestasx On

Just an idea. As it was already mentioned in comments write and execute [usually] can't be set on the same memory range. But any POSIX system should have interface to dynamic linker (dlopen(), dlclose(), ...). So there is a way to modify process memory layout at runtime, which is used by dynamic linker.

If modifying dynamic linker or using the same interfaces as it is using is acceptable option, it may be possible to dump memory segment (or copy it into another range), modify, free original segment and load modified one into the same range.

6
Pascal Cuoq On

For example I want to change the next instruction to a jump instruction. How to I can do this?

On a desktop system with a modern OS, you cannot, unless the program being executed has taken care to have the code held in read-write memory pages. By default, code is loaded in read-only memory pages.