Writing GDB scripts to collect data

1.4k views Asked by At

I need to print addresses of all local variables in C, and for that I am trying to use a GDB script.

I am using the following gdb script. First I set a breakpoint at main, and once that is encountered, I set a breakpoint at the next line and then step into it at each line of the program.

Even next can be used instead of step to execute till the next line. But I need to use step to step into functions as next does not do that.

b main
 commands 1
     while 1
        info locals      //some code needed to print addresses
        b 
        step
     end
 end

run    

However, the command "step", steps into library functions too. Is there a way to run "step" command conditionally such that it does not step into library functions? I will have a list of functions and variables used in the program as it is returned by my GCC Plugin. Can I use an if statement which executes step only if a user defined function is encountered, and next otherwise?

commands 1
    while 1
       info locals
       b
       if   //function name belongs to a predefined set
         step
       else
         next
       end
    end
end

I want to learn more about the GDB Scripting Language but I am not able to find sufficient material about it. I also need to know if we can declare arrays,strings and perform comparisons and other operations on them.

1

There are 1 answers

1
user2213232 On

I will have a list of functions and variables used in the program as it is returned by my GCC Plugin.

As you have a list of function names you have declared, in the start of script add breakpoint on each function in your list, now run it, and after each break run your logic to print addresses, then continue.

For example:

prog:

void fn1()
{
  int j = 0;
  printf("I am in fn 1");
}

void fn2()
{
  int k = 0;
  printf("I am in fn 2");
}

int main()
{
  int i = 0;
  fn1();
  printf("I am in main");
  fn2();
}

gdb transcript:

(gdb) b main
Breakpoint 1 at 0x400575: file surya.c, line 15.
(gdb) b fn1
Breakpoint 2 at 0x400535: file surya.c, line 3.
(gdb) b fn2
Breakpoint 3 at 0x400555: file surya.c, line 9.
(gdb) r
Starting program: /home/mohit/test/a.out 
warning: the debug information found in "/lib64/ld-2.19.so" does not match "/lib64/ld-linux-x86-64.so.2" (CRC mismatch).


Breakpoint 1, main () at surya.c:15
15    int i = 0;
(gdb) p &i
$1 = (int *) 0x7fffffffdf7c
(gdb) c
Continuing.

Breakpoint 2, fn1 () at surya.c:3
3     int j = 0;
(gdb) p &j
$2 = (int *) 0x7fffffffdf5c
(gdb) c
Continuing.

Breakpoint 3, fn2 () at surya.c:9
9     int k = 0;
(gdb) p &k
$3 = (int *) 0x7fffffffdf5c
(gdb)