C语言 当 char* x 指向值等于“hello”的字符串时,如何在 gdb 中设置条件断点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4183871/
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-09-02 07:04:39  来源:igfitidea点击:

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

cdebugginggdbconditional-breakpoint

提问by 341008

Can I specify that I want gdb to break at line x when char* xpoints to a string whose value equals "hello"? If yes, how?

我可以指定我希望 gdb 在char* x指向值等于 的字符串时在第 x 行中断"hello"吗?如果是,如何?

回答by Nathan Fellman

You can use strcmp:

您可以使用strcmp

break x:20 if strcmp(y, "hello") == 0

20is line number, xcan be any filename and ycan be any variable.

20是行号,x可以是任何文件名,y也可以是任何变量。

回答by Tobias Domhan

break x if ((int)strcmp(y, "hello")) == 0

On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!

在某些实现中,gdb 可能不知道 strcmp 的返回类型。这意味着您必须强制转换,否则它将始终评估为 true!

回答by tlwhitec

Since GDB 7.5you can use these native Convenience Functions:

从 GDB 7.5 开始,您可以使用这些原生的便捷功能

$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)

Seems quite less problematic than having to execute a "foreign" strcmp()on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.

strcmp()每次遇到断点时都必须在进程的堆栈上执行“外部” ,这似乎问题要少得多。对于调试多线程进程尤其如此。

Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running show configurationinside GDB and searching for --with-python. This little oneliner does the trick, too:

$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python'
             --with-python=/usr (relocatable)

请注意,您的 GDB 需要使用 Python 支持进行编译,这对于当前的 linux 发行版来说不是问题。可以肯定的是,您可以通过show configuration在 GDB 中运行并搜索--with-python. 这个小单线也可以解决问题:

$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python'
             --with-python=/usr (relocatable)

For your demo case, the usage would be

对于您的演示案例,用法是

break <where> if $_streq(x, "hello")

or, if your breakpoint already exists and you just want to add the condition to it

或者,如果您的断点已经存在并且您只想向其添加条件

condition <breakpoint number> $_streq(x, "hello")

$_streqonly matches the whole string, so if you want something more cunning you should use $_regex, which supports the Python regular expression syntax.

$_streq只匹配整个字符串,所以如果你想要更狡猾的东西,你应该使用$_regex,它支持Python 正则表达式语法