Nick.D
Nick.D

Reputation: 356

GDB conditional break on function parameter

I'm wanting to set a breakpoint on a function parameter if it is greater than a certain value. Dummy code below:

int main(void)
{
    uint64_t num = 123456;
    uint64_t x   = 847534;

    uint64_t other = (num*x) - (x/num);

    .... other stuff here (multithreaded stuff)

    calc(other);
}

void calc(uint64_t size)
{
    ...do some stuff with size
}

I've tried to set a breakpoint by:

(gdb) b calc if size == 852479

but it does not know what size is since it is a parameter I'm guessing. How would I break if the parameter equals a certain number. It is NOT an option to break on all the calls to this function because it gets called a billion times in the multithreaded environment.

Upvotes: 17

Views: 13788

Answers (3)

WGH
WGH

Reputation: 3499

If break foo if arg1 == 14 doesn't work for some reason (I've encountered some functions/binaries where it does, and where it doesn't), you can try to substitute it with commands.

commands allows you to set some gdb commands that will be run each time breakpoint is hit. To achieve desired effect - a conditional breakpoint - you can do the following:

(gdb) b foo
Breakpoint 1 at 0x400633: file test.c, line 6.
(gdb) commands 1
Type commands for breakpoint(s) 1, one per line.
End with a line saying just "end".
>silent
>if arg1 != 14
 >cont
 >end
>end

The execution will stop at breakpoint only if arg1 == 14.

The only drawback is that silent suppresses typical "breakpoint hit" message. You can remove silent, but then gdb will print the message even if breakpoint is skipped by commands script, which is undesireable if breakpoint is hit very often.

You can add some custom notification inside command script, though.

Upvotes: 5

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37914

Assuming x86-64 calling conventions on GNU/Linux platform you could examine %rdi (64-bit) register directly to check function's first parameter:

b calc if $rdi == 852479

This allows you to break on function calc even if you don't have debugging symbols loaded (thus no code listing, i.e. by list calc).

Note that this method would fail if function is inlined by optimizing compiler.

Upvotes: 9

bph
bph

Reputation: 11258

from the gdb prompt:

break "file.c":100 if (size=852479)

or

break "file.c":100 if (size>852479)

here i am assuming you want the conditional breakpoint on line 100 and your src file is file.c

i.e if you want to break on the line that calls calc, then that would be line 100 - modify as appropriate (you would also have to substitute size with other in this instance)

if you used a line no. that was one of the 1st statements in the calc function then you would stick with size

Upvotes: 8

Related Questions