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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3305164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:16:46  来源:igfitidea点击:

How to modify memory contents using GDB?

clinuxmemorygdb

提问by bits

I know that we can use several commands to access and read memory: for example, print, p, x...

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

But how can I change the contents of memory at any specific location (while debugging in GDB)?

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

采纳答案by Nikolai Fetissov

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

最简单的方法是设置程序变量(参见GDB: assignment):

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

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

或者您可以按地址更新任意(可写)位置:

(gdb) set {int}0x83040 = 4

There's more. Read the manual.

还有更多。阅读手册

回答by Andrew Edgecombe

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

正如尼古拉所说,您可以使用 gdb 'set' 命令来更改变量的值。

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

您还可以使用“set”命令来更改内存位置。例如。扩展尼古拉的例子:

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

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

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

这应该适用于任何有效的指针,并且可以转换为任何适当的数据类型。

回答by Jo?o Portela

Expanding on the answers provided here.

扩展此处提供的答案。

You can just do set idx = 1to 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=1would not be valid.

您可以只set idx = 1设置变量,但不建议使用该语法,因为变量名称可能与 set 子命令冲突。作为一个例子set w=1将是无效的。

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

这意味着您应该更喜欢语法:set variable idx = 1set 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

You can read more about gdb here.

您可以在此处阅读有关 gdb 的更多信息。