I am looking for a way to replace the code / text segment of an ELF executable before executing it. Is this possible? If yes, are there any utilities or libraries that I can use to replace it?
Its possible, but not trivial (I am warning you :) ). ELF contains lots of information about its content in the header files. text is just single section in a ELF file. I am also trying do it but not being successful so far.
I haven't tried objcopy to replace text segment but try this. I had few problem with this so i didn't continue this.
objcopy srcELF--dump-section .text=text.dump
objcopy dstELF --add-section .text=text.dump
My prefered way is to use libelf.
With libelf you can modify an ELF binary (add section, modify data in a section, etc). This tutorial provides a good start.