utils.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #
  2. # gdb helper commands and functions for Linux kernel debugging
  3. #
  4. # common utilities
  5. #
  6. # Copyright (c) Siemens AG, 2011-2013
  7. #
  8. # Authors:
  9. # Jan Kiszka <jan.kiszka@siemens.com>
  10. #
  11. # This work is licensed under the terms of the GNU GPL version 2.
  12. #
  13. import gdb
  14. class CachedType:
  15. def __init__(self, name):
  16. self._type = None
  17. self._name = name
  18. def _new_objfile_handler(self, event):
  19. self._type = None
  20. gdb.events.new_objfile.disconnect(self._new_objfile_handler)
  21. def get_type(self):
  22. if self._type is None:
  23. self._type = gdb.lookup_type(self._name)
  24. if self._type is None:
  25. raise gdb.GdbError(
  26. "cannot resolve type '{0}'".format(self._name))
  27. if hasattr(gdb, 'events') and hasattr(gdb.events, 'new_objfile'):
  28. gdb.events.new_objfile.connect(self._new_objfile_handler)
  29. return self._type
  30. long_type = CachedType("long")
  31. def get_long_type():
  32. global long_type
  33. return long_type.get_type()
  34. def offset_of(typeobj, field):
  35. element = gdb.Value(0).cast(typeobj)
  36. return int(str(element[field].address).split()[0], 16)
  37. def container_of(ptr, typeobj, member):
  38. return (ptr.cast(get_long_type()) -
  39. offset_of(typeobj, member)).cast(typeobj)
  40. class ContainerOf(gdb.Function):
  41. """Return pointer to containing data structure.
  42. $container_of(PTR, "TYPE", "ELEMENT"): Given PTR, return a pointer to the
  43. data structure of the type TYPE in which PTR is the address of ELEMENT.
  44. Note that TYPE and ELEMENT have to be quoted as strings."""
  45. def __init__(self):
  46. super(ContainerOf, self).__init__("container_of")
  47. def invoke(self, ptr, typename, elementname):
  48. return container_of(ptr, gdb.lookup_type(typename.string()).pointer(),
  49. elementname.string())
  50. ContainerOf()