如何在 GDB 中使用管道和 awk 设置变量?

How to set variable using pipe and awk in GDB?

我想将当前下级的可执行文件名存储在一个变量中。我在 gdb CLI 中获取可执行文件名称的方法如下:

 pipe info inferiors | awk '{ if ( == "*") { print } }'

但我无法将此表达式的输出存储在变量中。该表达式使用单引号和双引号,如果它与 seteval.

结合使用,这会使 gdb 报错
(gdb) set $exec="pipe info inferiors | awk '{ if ( == "*") { print } }'"
Argument to arithmetic operation not a number or boolean.
(gdb) eval "!echo %s", "pipe info inferiors | awk '{ if ( == "*") { print } }'"
Argument to arithmetic operation not a number or boolean.

那么,如何将可执行文件名称存储在变量中?我的目标是将可执行文件名称传递给 file 命令,以便在使用 Autotools 时重新加载可执行文件(参见 using libtool e gdb)。

您最好的选择是使用嵌入式 Python。示例:

gdb -q ./a.out
Reading symbols from ./a.out...

(gdb) start
Temporary breakpoint 1 at 0x1129: file foo.c, line 3.
Starting program: /tmp/a.out 

Temporary breakpoint 1, main () at foo.c:3
3         int v1 = 1, v2 = 2, v3 = 42;
(gdb) info inferiors
  Num  Description       Connection           Executable        
* 1    process 217200    1 (native)           /tmp/a.out        

(gdb) python gdb.execute('set $pid = ' + str(gdb.selected_inferior().pid))
(gdb) p $pid
 = 217200

更新:

原始问题要求字段 4,即 pid,但似乎 Gorka 实际上对文件名感兴趣,可以通过以下方式找到:

(gdb) python gdb.execute('set $f = "' + str(gdb.selected_inferior().progspace.filename) + '"')
(gdb) p $f
 = "/tmp/a.out"

文档:Inferiors, Progspaces

更新二:

Now I get the file name again with the field 4... but I was obtaining the pid as you said. I cannot figure why this is happening.

你得到 pid 或 name 取决于劣质者是否是 运行(这是为人类解析数据的危险)。

当inferior不是运行时,info inferiors打印:

(gdb) info inferiors
  Num  Description       Connection           Executable
* 1    <null>                                 /bin/date

当下级当前处于活动状态时,它会打印:

(gdb) info inferiors
  Num  Description       Connection           Executable
* 1    process 118431    2 (native)           /bin/date

尽管@EmployedRussian 的回答是最适合问题中出现的用例的解决方案,但我认为如何使用 pipe 和 awk 设置变量的问题尚未得到解答。这可以使用 python 并将管道分成两部分来完成:

python res = gdb.execute('info inferiors', to_string=True);
python gdb.execute ('set $exec = "' + str(res.strip().split()[6]) + '"');

如果首选类似 awk 的命令,请尝试使用 python 提供的工具,例如,将 res 转换为 pandas DataFrame。

请注意,此方法可能是灾难性的,正如此处列选择问题所见。