container_of equivalent in gdb-python script

Jan Kiszka jan.kiszka@web.de
Wed Jun 10 20:10:00 GMT 2009


Tom Tromey wrote:
>>>>>> "Jan" == Jan Kiszka <jan.kiszka@siemens.com> writes:
> 
> Jan> I'm at the point where I would apply a standard container_of()
> Jan> macro in C: convert the list entry into a gdb.Value that
> Jan> describes the containing object.
> 
> Jan> Of course, I can implement container_of as a gdb expression, print the
> Jan> result and drag it in via gdb.history(). Done that already, basically
> Jan> works. But it is fairly ugly as the print output will flood the screen.
> 
> I would say that the usual approach would be to reimplement the macro
> in Python.  The Python Value API is reasonably robust and can usually
> be used for this.  If you post the macro definition maybe I could help
> with that.  More details wouldn't hurt, either... are you writing a
> pretty-printer?  A new command?  A convenience function?

I want to automate 'add-symbol-file linux_module.ko 0xff...' that you
have to run for loading the symbols of dynamically loaded kernel
modules. Before that you also have to look up the module base address,
typically by cat'ing /proc/modules on the target. With a proper python
script, this will be trivial to do automatically. You just have to walk
the module list of the kernel you are attached to, extract names and
base addresses, search for the corresponding module binaries (also easy
with python) and issue the proper add-symbol-file commands.

But now back to the core problems, starting with the exercise to
implement offset_of(type, field):

def offset_of(type, field):
	container_type = gdb.lookup_type(type)
	dummy_obj = gdb.selected_frame().read_var('modules')
	container_obj = dummy_obj.cast(container_type)
	field_obj = container_obj[field]
	return int(str(field_obj.address), 16) - \
	       int(str(container_obj.address), 16)

I meanwhile discovered (reading testcases and python-*.c)
gdb.lookup_type() and Value.cast() to make this real. But you see, I
still need an ugly synthetic Value object which must have a non-'None'
address to do this calculation. Is there a cleaner, more generic way?

Jan

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 257 bytes
Desc: OpenPGP digital signature
URL: <http://sourceware.org/pipermail/gdb/attachments/20090610/c3af38f5/attachment.sig>


More information about the Gdb mailing list