I'm new to binary and assembly, and I'm curious about how to directly edit binary executables. I tried to remove an instruction from a binary file (according to disassembled instructions provided by objdump
), but after doing that the "executable" seems no longer in an executable format (segmentation fault when running; gdb
cannot recognize). I heard that this is due to instruction alignment issue. (Is it?)
So, is it possible to add/remove single x86 instructions directly in linux executables? If so, how? Thanks in advance.
Yes. Just replace it with a
NOP
instruction (0x90
) - or multiple ones if the instruction spans across multiple bytes. This is an old trick.If you remove a chunk of binary file without adjusting file headers accordingly, it will become invalid.
Fortunately, you can replace instructions with
NOP
without actually removing them. File size remains the same, and if there is no checksum or signature (or if it's not actually checked), there is nothing more to do.There is no universal way to insert the instructions, but generally you overwrite the original code with a
JMP
to another location, where you reproduce what the original code did, do your own things as you wanted, thenJMP
back. Finding room for your new code might be impossible without changing the size of the binary, so I would instead patch the code after executable is loaded (perhaps using a specialLD_PRELOAD
ed library).