有没有办法在运行时使用 gdb 编辑 argv?

Is there a way to edit argv during runtime using gdb?

有没有办法在运行时使用 gdb 编辑 argv?

我想获取一个 c 程序的 pid 并将其作为参数 (argv) 传递。

例如:

gdb cProgram
(gdb) b *0x000000000040085b
(gdb) r anyway
(gdb) info inferior
  >Num  Description          Executable
  >* 1    process 2597503    /path/to/file

(gdb) #A command to pass 2597503 as argument (argv)
(gdb) c

谢谢:)

是的,这似乎是可能的,但是,我不知道这样做的含义,其他人需要插话。如果 argv 字符串是字符串文字,那么修改它们就是 undefined behavior. Furthermore, if you write past the length of the original string, that probably invokes UB as well. Nevertheless, I found this answer 详细说明了如何修改 int,并将其适配为字符串。考虑以下程序:

#include <stdio.h>

int main(int argc, char* argv[])
{
  for (int i=1; i<argc; i++)
  {
    printf("%s\n", argv[i]);
  }

  return 0;
}

编译

gcc -Wall -Wextra -g -O0 -std=c99 test.c

然后 运行 gdb:

gdb a.out
// gdb's intro
(gdb) break main
Breakpoint 1 at ...
(gdb) run arg1 arg2 arg3  // pass it 3 arguments
// breakpoint hit at main
(gdb) print argv[1]
 = <address> "arg1"
(gdb) set {char*}(&(argv[1])) = "new4"  // change the value of argv[1]
(gdb) print argv[1]
 = <differentAddress> "new4"
(gdb) delete 1 // deletes the break point
(gdb) continue
Continuing.
new4
arg2
arg3
[... exited normally]
(gdb)

好了。这是否真的安全是另一回事,但这改变了 argv[1] 对我的价值。我至少会确保原始字符串的长度与要替换的字符串的长度相同或更长。