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

StackOverflow https://stackoverflow.com/questions/4183871

Question

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

Was it helpful?

Solution

You can use strcmp:

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

20 is line number, x can be any filename and y can be any variable.

OTHER TIPS

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!

Since GDB 7.5 you can use these handy Convenience Functions:

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

Seems quite less problematic than having to execute a "foreign" strcmp() on the process' stack each time the breakpoint is hit.

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 configuration inside 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)

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")

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top