在std :: cerr上打印某些内容时设置gdb断点

时间:2013-01-13 16:25:57

标签: gdb qt-creator stderr

我正在使用qt-creator作为IDE和gdb的前端。如何在运算符<<时设置断点在std :: cerr变量上调用?是否可以从qt-creator或我必须运行gdb standalone?

1 个答案:

答案 0 :(得分:2)

  

如何在std :: cerr

设置断点

您的问题没有意义:std::cerr是全局变量。您只能在函数上设置断点。您还可以在变量上设置观察点,因此GDB会在修改变量时停止,但它可能不是您想要的。

可能提出的问题是:“如果将某些内容写入STDERR_FILENO文件描述符,我怎么能停止?”。

如果是这种情况,catch syscall write可能就是答案(但真正的答案取决于你没有透露的操作系统。)

<强>更新

  

捕捉系统调用不是我认为的选项,因为我经常写文件

您可以在写入STDERR_FILENO(Linux上为2)时使syscall catchpoint成为条件。示例(这将适用于Linux / x86_64,但需要针对Linux / ix86进行调整):

cat t.cc
#include <iostream>
using namespace std;

int main()
{
   cout << "Hello,";
   cerr << "error 1" << endl;
   cout << " World!" << endl;
   cerr << "error 2" << endl;
}

gcc -g t.cc
gdb -q ./a.out
Reading symbols from /tmp/a.out...done.

(gdb) catch syscall write
Catchpoint 2 (syscall 'write' [1])

# Make the catchpoint conditional on writing to stderr:
(gdb) cond 2 $rdi == 2

# By default, "catch syscall" will stop both before and after the actual syscall
# Ignoring the catchpoint once will skip past the "after" stop.
(gdb) command 2 
Type commands for breakpoint(s) 2, one per line.
End with a line saying just "end".
>ignore 2 1
>end

(gdb) r
Starting program: /tmp/a.out 
Hello,
Catchpoint 2 (call to syscall write), 0x00007ffff7383ff0 in __write_nocancel () at ../sysdeps/unix/syscall-template.S:82
82  ../sysdeps/unix/syscall-template.S: No such file or directory.
(gdb) x/s $rsi
0x400a83:   "error 1"    # Good: we caught our first write to std::cerr

(gdb) c
Continuing.
error 1
Catchpoint 2 (call to syscall write), 0x00007ffff7383ff0 in __write_nocancel () at ../sysdeps/unix/syscall-template.S:82
82  in ../sysdeps/unix/syscall-template.S
(gdb) x/s $rsi
0x7ffff76298e3 <_IO_2_1_stderr_+131>:   "\n"  # I didn't know endl gets a separate write syscall.
(gdb) c
Continuing.

 World!

Catchpoint 2 (call to syscall write), 0x00007ffff7383ff0 in __write_nocancel () at ../sysdeps/unix/syscall-template.S:82
82  in ../sysdeps/unix/syscall-template.S
(gdb) x/s $rsi
0x400a93:   "error 2"
(gdb) c
Continuing.
error 2
Catchpoint 2 (call to syscall write), 0x00007ffff7383ff0 in __write_nocancel () at ../sysdeps/unix/syscall-template.S:82
82  in ../sysdeps/unix/syscall-template.S
(gdb) x/s $rsi
0x7ffff76298e3 <_IO_2_1_stderr_+131>:   "\n"
(gdb) c
Continuing.

[Inferior 1 (process 17291) exited normally]