1
votes

I defined a convenience function for GDB using the Python API,

import gdb

verbose = True

class HCall(gdb.Function):
    def __init__(self, funcname):
        super(HCall,self).__init__(funcname)

    def log_call(cmd):
        if verbose:
            print(cmd)
        try:
            gdb.execute(cmd)
        except Exception, e:
            print (e)
            import traceback
            # traceback.print_stack()
            traceback.format_exc()


class NewCVar(HCall):
   """ allocates a c variable in heap """
   def __init__(self):
       super(NewCVar,self).__init__("newcvar")

   def invoke(self, name, oftype):
       cmd = "call gdb.execute(set $" + name + " = malloc(sizeof(" + oftype + "))"
       log_call(cmd)
       return "$" + name

NewCVar()

I can load this file with "source usefunction.py", and print the help text with "function newcvar". Nevertheless GDB does not know about $newcvar, as I would expect (https://sourceware.org/gdb/onlinedocs/gdb/Functions-In-Python.html).

Does anyone have a clue what can I be doing wrong?

Thanks in advance!

1
You have, ultimately, gdb.execute("call gdb.execute(set $" + name + " = malloc(sizeof(" + oftype + "))"). But the gdb call command is used to call a function in the target that is being debugged. What sort of target is gdb debugging when you run this? - Mark Plotnick
A standard C program. For some reason, I need to allocate variables and call functions on them. That is the motivation for NewCVar. But that is not the issue. When I try to call it, GDB says, it does not know about $newcvar, even though the command function knows about it. - gramuc

1 Answers

0
votes

You should probably post exactly what happens, and what you expect to happen.

I tried your program in gdb and gdb does see the function; but since there is a bug in the function, it doesn't actually work. For example I tried:

(gdb) p $newcvar("x", "int")
Traceback (most recent call last):
  File "/tmp/q.py", line 23, in invoke
    cmd = "call gdb.execute(set $" + name + " = malloc(sizeof(" + oftype + "))"
gdb.error: Argument to arithmetic operation not a number or boolean.
Error occurred in Python convenience function: Argument to arithmetic operation not a number or boolean.

The bug is that ou're trying to gdb.execute a string that looks like call gdb.execute(...). This is weird. call evaluates an expression in the inferior, so using it with an argument containing gdb.execute is incorrect. Instead NewCVar.invoke should make a string like set variable $mumble = ....

Returning a string here is also strange.

I wonder why you want this to be a function rather than a new gdb command.