Tianyi Cai
Tianyi Cai

Reputation: 123

Use gdb to Modify Binary

I tried to modify executable file under gdb. Even though memory has been changed, but corresponding executable does not change, so next time run the program the modification is gone.

I started gdb with -write option. I also tried set write on and then reload exec-file I changed the memory with set {unsigned char}addr = 0xf;

but the corresponding file is not changed.

Upvotes: 10

Views: 9554

Answers (1)

Employed Russian
Employed Russian

Reputation: 213496

but the corresponding file is not changed.

It's hard to say what address you are actually modifying, and so whether your change should actually modify the binary or not.

In the past, I've found that after modifying the binary, I need to immediately quit. If I do anything other than quit (e.g. run), then GDB would discard my change, but if I quit, then the change would "take".

Example:

$ cat t.c
int main()
{
  return 42;
}

$ gcc t.c && ./a.out; echo $?
42

$ gdb --write -q  ./a.out
(gdb) disas/r main
Dump of assembler code for function main:
   0x00000000004004b4 <+0>:     55      push   %rbp
   0x00000000004004b5 <+1>:     48 89 e5        mov    %rsp,%rbp
   0x00000000004004b8 <+4>:     b8 2a 00 00 00  mov    $0x2a,%eax
   0x00000000004004bd <+9>:     5d      pop    %rbp
   0x00000000004004be <+10>:    c3      retq   
End of assembler dump.
(gdb) set {unsigned char}0x00000000004004b9 = 22
(gdb) disas/r main
Dump of assembler code for function main:
   0x00000000004004b4 <+0>:     55      push   %rbp
   0x00000000004004b5 <+1>:     48 89 e5        mov    %rsp,%rbp
   0x00000000004004b8 <+4>:     b8 16 00 00 00  mov    $0x16,%eax  <<< ---changed
   0x00000000004004bd <+9>:     5d      pop    %rbp
   0x00000000004004be <+10>:    c3      retq   
End of assembler dump.
(gdb) q

$ ./a.out; echo $?
22    <<<--- Just as desired

Upvotes: 14

Related Questions