sonic_maniac
sonic_maniac

Reputation: 59

Track all variables for execution of function in gdb

I want to track the state of all the variables in a function in C.

I know I can use info commands in gdb to get all the variables state at the current context.

And I can use gdbinit to automate the gdb.

But what I want to do is set a breakpoint at the function and then after executing each line print execute the info command.

Basically, I want to set 2 breakpoints: one at the start of a function and one at the end of the same function(I don't know how to this) and execute line-by-line between these 2 points.

I want something like this in my gdbinit:

b <func_name>
commands
while <inside the function>:
   info locals
   next
end
run

Is there a way to have the while loop shown above?

Upvotes: 2

Views: 662

Answers (1)

Employed Russian
Employed Russian

Reputation: 213955

Basically, I want to set 2 breakpoints: one at the start of a function and one at the end of the same function(I don't know how to this) and execute line-by-line between these 2 points.

You can find how to set the breakpoint at the end of the function here. However, that isn't necessary here.

You can use $_caller_is() GDB convenience function to finish executing current routine, and stop after it has returned.

Example:

int fn()
{
  int sum = 0;
  for (int j = 0; j < 5; j++) {
    sum += j;
  }
  return sum;
}

int main()
{
  return fn() - 10;
}

And now GDB session:

gdb -q ./a.out
Reading symbols from ./a.out...
(gdb) b 4
Breakpoint 1 at 0x1130: file t.c, line 4.
(gdb) run
Starting program: /tmp/a.out

Breakpoint 1, fn () at t.c:4
4     for (int j = 0; j < 5; j++) {
(gdb) while $_caller_is("main")
 >info locals
 >next
 >end
j = 1431654464
sum = 0
5       sum += j;
j = 0
sum = 0
4     for (int j = 0; j < 5; j++) {
j = 0
sum = 0
5       sum += j;
j = 1
sum = 0
4     for (int j = 0; j < 5; j++) {
j = 1
sum = 1
5       sum += j;
j = 2
sum = 1
4     for (int j = 0; j < 5; j++) {
j = 2
sum = 3
5       sum += j;
j = 3
sum = 3
4     for (int j = 0; j < 5; j++) {
j = 3
sum = 6
5       sum += j;
j = 4
sum = 6
4     for (int j = 0; j < 5; j++) {
j = 4
sum = 10
7     return sum;
sum = 10
8   }
sum = 10
main () at t.c:12
12    return fn() - 10;
(gdb) q

P.S. For all but toy problems, this method of debugging will be both grossly inefficient and insufficient (it is rare for the interesting state to be captured entirely by local variables).

Upvotes: 3

Related Questions