8

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.

Tianyi Cai
  • 103
  • 2
  • 9

1 Answers1

14

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
Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • the "immediate quit" thing *might* be the trick. I accidentally modified the binary once, probably due to the "immediate quit". – Tianyi Cai Oct 05 '14 at 07:11
  • 1
    I just verified your "immediate quit" trick. It works. So after finding out where needs to change, QUIT gdb, restart gdb with option "--write", directly and immediately give command "set {some type}0x..=0x..", then immediately quit gdb, then binary is changed!. – Tianyi Cai Oct 05 '14 at 11:14
  • Question. Why `unsigned char` and not `int`? I notice that we manipulate a single byte. Is that somehow depending on the machine code generated? – Peter Oct 08 '20 at 13:04
  • AFAIK all the data byte in the binary is unsigned char and there is anther way to set data to a specific byte location using: set *(char *) 0x ...= 0x ... So, as you can see, no place to use int here. – husin alhaj ahmade Jan 12 '23 at 04:29