k0n3ru
k0n3ru

Reputation: 703

call/invoke different methods based on datatypes in GDB

I am trying to define a command in gdb which is sort of a wrapper which will call respective method based on the datatype of the argument passed to it. I have tried something like

set $datatype = whatis $arg0 

But it does not seem to work.

I am trying to write something like this

define gprint

    set $datatype = //somehow get the datatype of arg

    if $datatype == *type1
        p print_type1(*$arg0)
    end
    if $datatype == type1
        p print_type1($arg0)
    end
    if $datatype == type2
        p $arg0->print()
    end

    //
    //
    //  Some more datatypes
    //
    //

end

Upvotes: 0

Views: 50

Answers (1)

Tom Tromey
Tom Tromey

Reputation: 22569

There's no convenient way to do this from the gdb command line, because there is no good way to smuggle a type into an expression.

It can be done the hard way using the "standard hack" -- use "set logging" to write the type to a file, then "shell" to rewrite the file to a gdb script, and then "source" to load that script. However, this is very painful.

Instead, it is much simpler to use Python. Here you have several options.

Since it seems like you want to make the display of some values vary by type, I would suggest using the gdb "pretty printing" feature. This feature is designed for exactly this scenario. It integrates nicely with print, bt, and other gdb commands.

However, if you are not doing that, and you'd still rather write your own gprint command, you still have options: you can write the command entirely in Python, which has access to both expressions and types. Or, you can write Python convenience functions that do what you like. You can see an example of the latter in my gdb-helpers repository; in particular see the $_typeof function.

Upvotes: 1

Related Questions