Search code examples
gdbgdbinit

How to execute commands conditionally in gdbinit functions


I have a gdb function, defined in gdbinit file:

define myfunc 
    set $retval = SOMEHOW_RET_VALUE_OF shell my-shell-command
    if $retval == 0
       load my-output
    else
       echo command not succeeded, not doing anything.\n
    end 
end 

How can I get my-shell-func return status and use it to control loading new binary output?


Solution

  • There are two ways to do this.

    The simplest way is to use gdb's built-in Python scripting capability. For a case like the above, you could write a new convenience function that does what you like. A convenience function is appropriate here because it can be used directly in an expression.

    To write a convenience function, look through the docs for gdb.Function.

    Then you would use it like:

    set $retval = $_shellcommand("shell command")
    

    If you'd rather not dive into Python, there is still a way; although it is somewhat more painful.

    For a simple shell command, the idea would be to write the exit status of the shell command to a gdb script file, which you then source:

    (gdb) shell false; echo "set \$retval = $?" > /tmp/q
    (gdb) source /tmp/q
    (gdb) print $retval
    $1 = 1
    

    This gets somewhat hairier if you want more than just the exit status, or if you want to use output from gdb commands in the computation.