13

我正在尝试开发一个简单的基于文本的用户界面,它运行一些 gdb 命令。我希望用户能够在代码的某个区域设置和中断/跟踪点并运行一些调试命令。

我想让用户输入需要调试的功能。然后我取这个函数名并打印出函数的源代码,然后让用户选择在哪一行代码设置断点/跟踪点。目前,使用反汇编命令我可以打印出用户的内存地址,但我想打印实际的源代码。

这可以在gdb中完成吗?

目前:

Dump of assembler code for function test_function:
   0x03800f70 <test_function+0>:  push   %ebp
   0x03800f71 <test_function+1>:  mov    %esp,%ebp
   0x03800f73 <test_function+3>:  sub    $0x48,%esp

我想要的是:

void main()
{
  printf("Hello World\n");
}

谢谢!

编辑:我得到这个:

(gdb) list myFunction
941     directory/directory_etc/sourcefile.c: No such file or directory.
        in directory/directory_etc/sourcefile.c

然后我尝试指定linenum:

(gdb) list directory/directory_etc/sourcefile.c:941
936     in directory/directory_etc/sourcefile.c

所以行为类似于你所描述的,但“列表文件名:linenum”仍然不起作用

谢谢!

4

2 回答 2

13

利用:

(gdb) list FUNCTION

详见命令在线帮助list

(gdb) help list
List specified function or line.
With no argument, lists ten more lines after or around previous listing.
"list -" lists the ten lines before a previous ten-line listing.
One argument specifies a line, and ten lines are listed around that line.
Two arguments with comma between specify starting and ending lines to list.
Lines can be specified in these ways:
  LINENUM, to list around that line in current file,
  FILE:LINENUM, to list around that line in that file,
  FUNCTION, to list around beginning of that function,
  FILE:FUNCTION, to distinguish among like-named static functions.
  *ADDRESS, to list around the line containing that address.
With two args if one is empty it stands for ten lines away from the other arg.

对于任何非玩具项目,您可能会遇到这样的情况:

$ gdb /bin/true
<...>
(gdb) start
<...>
(gdb) list printf
file: "/usr/include/bits/stdio2.h", line number: 104
file: "printf.c", line number: 29

其中列出了代码库中函数的多个定义。在printf()上面的例子中,非重载的纯 C 函数有两个定义。一个定义在stdio2.h. 然后,您可以使用list FILE:LINENUM表格指定要列出的内容:

(gdb) list printf.c:29
24  
25  /* Write formatted output to stdout from the format string FORMAT.  */
26  /* VARARGS1 */
27  int
28  __printf (const char *format, ...)
29  {
30    va_list arg;
31    int done;
32  
33    va_start (arg, format);

对于您看到的“sourcefile.c: No such file or directory”错误,您需要告诉 GDB 在哪里查找源代码。请参阅GDB 手册:源路径。显然,您需要实际拥有要在您的机器上列出的功能的源代码。

于 2013-05-08T21:45:19.317 回答
1

对于 gcc

在编译源代码时添加调试选项标志 -g:

gcc -g test.c

要测试,请使用:

gdb ./a.out
(gdb) list

如需更多功能,请查看手册页:

man gcc
man gdb
于 2018-12-30T21:30:21.403 回答