【问题标题】:Print file contents opened with fopen in GDB?打印在 GDB 中用 fopen 打开的文件内容?
【发布时间】:2021-12-16 23:02:24
【问题描述】:

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

以如下C代码为例:

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

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

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

【问题讨论】:

  • 你试过什么?那是怎么工作的?怎么没用?

标签: c gdb fopen


【解决方案1】:

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

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

参数是函数名和参数,记号为 当前的工作语言。结果被打印并保存在 价值历史,如果它不是无效的。

当然,在该函数中,您应该保留文件位置 -- 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)

【讨论】:

  • 这根本不能回答问题。
  • @EmployedRussian 然而,这是 C 编程中的常用方法。当然,不是专门打印文件的内容,而是打印不同的内部。但是,是的,如果你从你的陈述中删去完全,那可能是真的。
  • @alinsoar 您能否在 gdb 中提供一个与我提供的代码相同/相似的示例?
【解决方案2】:

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

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

#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
$1 = {_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-&gt;_IO_read_ptr指向,整个缓冲区被file-&gt;_IO_read_base指向。

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

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多