转自: http://my.oschina.net/alphajay/blog/49941
下面我向大家介绍一下使用gdb修改可执行文件中的代码和变量的方法。
另,在GDB文档中介绍这个方法也 能修改CORE文件的内容,本人未验证。
在 一般情况下GDB是以只读方式打开可执行文件的,如果需要改变可执行文件,需要在读入文件以前,用GDB启动参数“–write”或者命令“set write on”用可读写方式打开可执行文件。如果文件已经打开了可执行文件,就需要使用exec-file重新以读写方式打开可执行文件,注意如果你还没打开可执行文件,就一定要使用file命令读入,因为exec-file不会重新读入符号信息。
还有要注意的是,因为修改只能修改section的内容,所以能修改的变量只能是非0的全局变量,内容是O的变量会被放入bss。
1.c:
1 2 3 4 5 6 7 8 |
#include <stdio.h> int a = 1; int main(int argc,char *argv[],char *envp[]) { printf ("%d\n", a); return 0; } |
gcc -g 1.c
./a.out
1
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#gdb GNU gdb 6.8-debian Copyright (C) 2008 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". (gdb) set write on #打开功能 (gdb) file ./a.out #打开文件 Reading symbols from /home/teawater/gdb/a.out...done. (gdb) p a = 100 #修改变量的文件中的值 $1 = 100 |
./a.out
100
下面举例修改代码内容:
1.c:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <stdio.h> void cool (void) { printf ("Call function cool.\n"); } int main(int argc,char *argv[],char *envp[]) { cool (); return 0; } |
#gcc -g 1.c
#./a.out
1 |
Call function cool. |
修改代码内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
gdb --write ./a.out #使用--write直接打开可写功能 GNU gdb 6.8-debian Copyright (C) 2008 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu"... (gdb) disas cool Dump of assembler code for function cool: 0x000000000040050c <cool+0>: push %rbp #注意改之前这条指令 0x000000000040050d <cool+1>: mov %rsp,%rbp 0x0000000000400510 <cool+4>: mov $0x40062c,%edi 0x0000000000400515 <cool+9>: callq 0x4003f8 <puts@plt> 0x000000000040051a <cool+14>: leaveq 0x000000000040051b <cool+15>: retq End of assembler dump. (gdb) set *(unsigned char *)(0x000000000040050c) = 0xc3 #修改指令 (gdb) disas cool Dump of assembler code for function cool: 0x000000000040050c <cool+0>: retq #改之后这指令发生了变化 0x000000000040050d <cool+1>: mov %rsp,%rbp 0x0000000000400510 <cool+4>: mov $0x40062c,%edi 0x0000000000400515 <cool+9>: callq 0x4003f8 <puts@plt> 0x000000000040051a <cool+14>: leaveq 0x000000000040051b <cool+15>: retq End of assembler dump. |
. /a.out #现在没有输出了 因为cool函数直接返回了