问题
I'm debugging with a core-file, so I have no active process in which to run anything.
I'm using gdb user-defined commands to inspect a bunch of data from the core file, and attempting to simplify the process using user-defined commands.
However, I cannot find a way to make the user-defined commands return values which could be used in other commands.
For example:
(note the comment on the "return" line)
define dump_linked_list
set $node = global_list->head
set $count = 1
while $node != 0
printf "%p -->", $node
set $node = $node->next
set $count = $count + 1
end
return $count ## GDB doesn't understand this return
end
Ideally, my dump_linked_list command would return the number of nodes found in the list, so that it could be used in another defined command:
define higher_function
set $total_nodes = dump_linked_list
printf "Total Nodes is %d\n", $total_nodes
end
Is such a thing possible in gdb commands?
I feel it must be, but I've been searching documentation and cannot find a mention of it, or any examples.
回答1:
As far as I know GDB does not have such a functionality. You can set a variable of some name that you know and use it as a "return" value. For example always set the variable retval like this:
set $retval = <whatever value>
Then all your newly defined functions can use it as a return value from previously called functions. I know this is only workaround, but it is relatively simple and it works.
回答2:
I found out gdb seems to pass by name which can be used to pass back a return value. A little more flexible that just using a single global variable.
(gdb) define foo
Type commands for definition of "foo".
End with a line saying just "end".
>set $arg0 = 1
>end
(gdb) set $retval = 0
(gdb) p $retval
$3 = 0
(gdb) foo $retval
(gdb) p $retval
$4 = 1
来源:https://stackoverflow.com/questions/12572631/return-a-value-via-a-gdb-user-defined-command