2

GDB has a reasonably robust API which is exposed to Python at runtime. It allows for inspecting various types, but does not appear to allow creation of types.

However, types can be manually added by loading an object file at runtime (https://stackoverflow.com/q/7272558).

Is there any way to add or create a new gdb.Type object at runtime?

The intent is to then allow inspection of memory via gdb.Value.cast to the type.pointer() and then .dereference()d. This would be much better/easier than manually deserializing data field-by-field.

Alternatively, I thought that I could just load an object file programmatically. It looks like GDB is perfectly happy to load cross-architecture object files for symbol/type purposes. In order to not kill any real/useful symbols, or create misleading ones, a non-existent address should be used. However, loading a .o at an unmapped address requires the user to verify (type y), so when done from gdb.execute(...) it fails outright.

  • You could probably use libdwarf to create an object file that has no symbols, just type information, in it. Then, loading that object file to an existing address probably won't kill any symbols, since it has no mappable sections inside. – Guntram Blohm supports Monica Feb 11 '15 at 12:42
1

So it turns out you can do this in the following way, from within GDB Python. The trick is from_tty=False.

foo = open('foo.cc','w+')
foo.write('struct foobar { int x; }; foobar foo;')
foo.close()

subprocess.check_output('g++ -w -c -g foo.cc -o foo.o', shell=True)

gdb.execute('add-symbol-file foo.o 0', from_tty=False, to_string=True)

You should now be able to view the type in gdb:

gdb $ ptype foobar
type = struct foobar {
    int x;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.