Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flow control in GDB based on local variable existence

Tags:

c++

c

gdb

I'm trying to write a GDB script (legacy, not Python) that will print information on members of a local variable (a C or C++ struct), but only if that local variable exists. Something like:

# 'magic' should be evaluate to "if 'info locals' has a variable named foo, then
# evaluate to true, otherwise evaluate to false.
if (magic)
    print foo->member
end

I know this is somewhat contrived, because the locals are dependent on the stack frame (so I'm probably better off making it conditional on the frame), but I'd still like to know if something along these lines is possible.

like image 926
Rob Avatar asked Apr 01 '14 08:04

Rob


1 Answers

First -- Python is just far superior for this kind of thing. That's why we added it to gdb!

However, this can still be done with an older gdb. However, it's awful, and after doing it I think you'll appreciate the Python approach even more. What you do is: first, use the various "set logging" commands to redirect the output to a temporary file . Then use gdb commands to print the information you need, in this case something like "info local". Then, use the "shell" command to shell out to rewrite the temporary file into a file that is itself a gdb script. For example, use "sed" to detect that the variable exists in your output, and then emit "set $var_exists=1". Finally, "source" the result of this scripting and test the convenience variable that was set.

Eww. But it works.

like image 118
Tom Tromey Avatar answered Nov 18 '22 02:11

Tom Tromey