如何使用 GDB 修改内存内容?

我知道我们可以使用几个命令来访问和读取内存: 例如,print、 p、 x..。

但是如何在任何特定位置(在 GDB 中调试时)更改内存的内容呢?

178082 次浏览

The easiest is setting a program variable (see GDB: assignment):

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

Or you can just update arbitrary (writable) location by address:

(gdb) set {int}0x83040 = 4

There's more. Read the manual.

As Nikolai has said you can use the gdb 'set' command to change the value of a variable.

You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10


(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20

This should work for any valid pointer, and can be cast to any appropriate data type.

Expanding on the answers provided here.

You can just do set idx = 1 to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1 would not be valid.

This means that you should prefer the syntax: set variable idx = 1 or set var idx = 1.

Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.

(gdb) p idx = 1
$1 = 1

You can read more about gdb here.

One of the most useful things is to change the value of Registers directly.

 0x000000000800088e <+67>:    lea    rdi,[rip+0x118]        # 0x80009ad

To change the value of rdi register:

 set $rdi = 0x8201010

Writing memory:

(gdb) set *0x20001234 = 0xABABABAB

Reading memory:

(gdb) x 0x20001234
0x20001234:     0xabababab