我的用例是尝试生成一个编译速度更快的
dprintf
类命令,因为 dprintf
本身与 commands
相比不是很快,请参阅基准测试:dprintf vs break + commands +继续?
我设法在边
printf
中运行compile code
,但问题是注入在执行后立即被删除,根据GDB文档:https://sourceware.org/gdb/current/onlinedocs/gdb#编译和注入代码
需要注意的是,编译后的代码是立即执行的。执行后,编译后的代码将从 GDB 中删除,您定义的任何新类型或变量都将被删除。
有办法吗?例如。作为测试用例:
循环.c
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
uintmax_t i, j, period, max;
if (argc > 1) {
max = strtoumax(argv[1], NULL, 10);
} else {
max = 10;
}
if (argc > 2) {
period = strtoumax(argv[2], NULL, 10);
} else {
period = 1;
}
i = 0;
j = 0;
while (1) {
if (period != 0 && i % period == 0) {
printf("%ju\n", j);
j++;
}
i++; /* line 25 */
if (i == max)
break;
}
}
编译运行:
gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o loop.out loop.c
然后尝试:
time gdb -n -q -batch -ex 'tb 25' -ex run -ex 'compile code printf("hello: %d\n", i)' \
-ex c -args ./loop.out 10000 0
输出:
Temporary breakpoint 1 at 0x122a: file loop.c, line 39.
This GDB supports auto-downloading debuginfo from the following URLs:
https://debuginfod.ubuntu.com
Enable debuginfod for this session? (y or [n]) [answered N; input not from terminal]
Debuginfod has been disabled.
To make this setting permanent, add 'set debuginfod enabled off' to .gdbinit.
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Temporary breakpoint 1, main (argc=3, argv=0x7fffffffcd28) at loop.c:39
39 i++;
gdb command line:1:1: warning: incompatible implicit declaration of built-in function ‘printf’ [-Wbuiltin-declaration-mismatch]
gdb command line:1:1: note: include ‘<stdio.h>’ or provide a declaration of ‘printf’
gdb command line:1:8: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
hello: 0
[Inferior 1 (process 144909) exited normally]
real 0m0.289s
user 0m0.258s
sys 0m0.042s
所以我们确实看到了:
hello: 0
根据需要行,但它只发生一次,我希望它每次都在循环中发生。
我认为我所描述的是所谓的“动态检测”。一些相关项目:
在 Ubuntu 22.10、GDB 12.1 上测试。