打印在 GDB 中用 fopen 打开的文件内容?

Print file contents opened with fopen in GDB?

我正在尝试打印在 GDB 中用 C 中的 fopen 打开的文件的内容。

例如,取下面的C代码:

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *file;
    file = fopen("/etc/passwd", "r");
    fclose(file);
    return 0;
}

我希望在 GDB 中 运行 编译后的可执行文件时能够查看此文件的内容。谢谢!

您可以使用调用函数。您编写了一个函数来打印文件的内容,然后从 gdb 中调用它。

(gdb) help call
Call a function in the program.
Usage: call EXP

The argument is the function name and arguments, in the notation of the current working language. The result is printed and saved in the value history, if it is not void.

当然,在那个函数中你应该保留文件位置——ftell在开头,fseek在结尾,等等.


#include <stdio.h>
#include <stdlib.h>

void
debug_file(FILE*f)
{
   printf("keep ftell, read, print, restore position\n");
}

int main() { 
    ....
}

% gcc -O0 -g3 gbd.c
% gdb ./a.out
Reading symbols from ./a.out...
(gdb) break main
Breakpoint 1 at 0x118f: file gbd.c, line 12.
(gdb) r
Starting program: /work/stub/a.out

Breakpoint 1, main () at gbd.c:12
12          file = fopen("/etc/passwd", "r");
(gdb) n
13          int ch = fgetc(file);              /* force a read */
(gdb)
14          fclose(file);
(gdb) call debug_file(file)
keep ftell, read, print, restore position
(gdb) c
Continuing.
[Inferior 1 (process 6432) exited normally]
(gdb)

I am attempting to print the contents of a file opened with fopen in C within GDB.

你需要有libc,它是用调试信息编译的。例如,在 Linux 上,使用 GLIBC 并安装了 libc6-dbg,使用您的示例程序,修改为实际读取文件(仅 fopening 并立即 fcloseing 文件不读 任何东西):

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *file;
    file = fopen("/etc/passwd", "r");
    int ch = fgetc(file);              /* force a read */
    fclose(file);
    return 0;
}

(gdb) start
Temporary breakpoint 1 at 0x115d: file t.c, line 6.
Starting program: /tmp/a.out

Temporary breakpoint 1, main () at t.c:6
6           file = fopen("/etc/passwd", "r");
(gdb) n
7           int ch = fgetc(file);
(gdb) n
8           fclose(file);
(gdb) p *file
 = {_flags = -72539000, _IO_read_ptr = 0x555555559481 "oot:x:0:0:root:/root:/bin/bash\n"..., _IO_read_end = 0x55555555a1c6 "", ..., _IO_read_base = 0x555555559480 "root:x:0:0:root:/root:/bin/bash\n"...

这里可以看到file->_IO_read_ptr指向了后续读取返回的数据,file->_IO_read_base指向了整个buffer。

成员将取决于您使用的libc,缓冲数据量(如果有)将取决于打开流时使用的缓冲。