以编程方式在 C 或 C++ 代码中为 Linux 上的 gdb 设置断点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4326414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:56:23  来源:igfitidea点击:

Set breakpoint in C or C++ code programmatically for gdb on Linux

c++clinuxgdb

提问by J. Polfer

How can I set a breakpoint in C or C++ code programatically that will work for gdb on Linux?

如何以编程方式在 C 或 C++ 代码中设置断点,以适用于 Linux 上的 gdb?

I.e.:

IE:

int main(int argc, char** argv)
{
    /* set breakpoint here! */
    int a = 3;
    a++;  /*  In gdb> print a;  expect result to be 3 */
    return 0;
}

采纳答案by H?vard S

One way is to signal an interrupt:

一种方法是发出中断信号:

#include <csignal>

// Generate an interrupt
std::raise(SIGINT);

In C:

在 C 中:

#include <signal.h>
raise(SIGINT);

UPDATE: MSDN statesthat Windows doesn't really support SIGINT, so if portability is a concern, you're probably better off using SIGABRT.

更新MSDN 声明Windows 并不真正支持SIGINT,因此如果考虑可移植性,您可能最好使用SIGABRT.

回答by J. Polfer

By looking here, I found the following way:

通过查看here,我找到了以下方法:

void main(int argc, char** argv)
{
    asm("int ");
    int a = 3;
    a++;  //  In gdb> print a;  expect result to be 3
}

This seems a touch hackish to me. And I think this only works on x86 architecture.

这对我来说似乎有点hackish。而且我认为这仅适用于 x86 架构。

回答by Jason Orendorff

In a project I work on, we do this:

在我从事的一个项目中,我们这样做:

raise(SIGABRT);  /* To continue from here in GDB: "signal 0". */

(In our case we wanted to crash hard if this happened outside the debugger, generating a crash report if possible. That's one reason we used SIGABRT. Doing this portably across Windows, Mac, and Linux took several attempts. We ended up with a few #ifdefs, helpfully commented here: http://hg.mozilla.org/mozilla-central/file/98fa9c0cff7a/js/src/jsutil.cpp#l66.)

(在我们的例子中,如果这发生在调试器之外,我们希望严重崩溃,如果可能,生成一个崩溃报告。这就是我们使用 SIGABRT 的原因之一。在 Windows、Mac 和 Linux 上进行可移植的操作需要多次尝试。我们最终得到了一些#ifdefs,在这里评论很有帮助:http: //hg.mozilla.org/mozilla-central/file/98fa9c0cff7a/js/src/jsutil.cpp#l66。)

回答by hek2mgl

__asm__("int $3");should work:

__asm__("int $3");应该管用:

int main(int argc, char** argv)
{
    /* set breakpoint here! */
    int a = 3;
    __asm__("int ");
    a++;  /*  In gdb> print a;  expect result to be 3 */
    return 0;
}

回答by dacap

On OS X you can just call std::abort()(it might be the same on Linux)

在 OS X 上,您可以调用std::abort()(在 Linux 上可能相同)

回答by Benjamin Crawford Ctrl-Alt-Tut

Disappointing to see so many answers not using the dedicated signal for software breakpoints, SIGTRAP:

令人失望的是,看到这么多答案没有使用软件断点的专用信号,SIGTRAP

#include <signal.h>

raise(SIGTRAP); // At the location of the BP.