gdb.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import gdb
  2. import re
  3. import gdb.printing
  4. class PuTTYMpintPrettyPrinter(gdb.printing.PrettyPrinter):
  5. "Pretty-print PuTTY's mp_int type."
  6. name = "mp_int"
  7. def __init__(self, val):
  8. super(PuTTYMpintPrettyPrinter, self).__init__(self.name)
  9. self.val = val
  10. def to_string(self):
  11. type_BignumInt = gdb.lookup_type("BignumInt")
  12. type_BignumIntPtr = type_BignumInt.pointer()
  13. BIGNUM_INT_BITS = 8 * type_BignumInt.sizeof
  14. array = self.val["w"]
  15. aget = lambda i: int(array[i]) & ((1 << BIGNUM_INT_BITS)-1)
  16. try:
  17. length = int(self.val["nw"])
  18. value = 0
  19. for i in range(length):
  20. value |= aget(i) << (BIGNUM_INT_BITS * i)
  21. return "mp_int({:#x})".format(value)
  22. except gdb.MemoryError:
  23. address = int(self.val)
  24. if address == 0:
  25. return "mp_int(NULL)".format(address)
  26. return "mp_int(invalid @ {:#x})".format(address)
  27. class PuTTYPtrlenPrettyPrinter(gdb.printing.PrettyPrinter):
  28. "Pretty-print strings in PuTTY's ptrlen type."
  29. name = "ptrlen"
  30. def __init__(self, val):
  31. super(PuTTYPtrlenPrettyPrinter, self).__init__(self.name)
  32. self.val = val
  33. def to_string(self):
  34. length = int(self.val["len"])
  35. char_array_ptr_type = gdb.lookup_type(
  36. "char").const().array(length).pointer()
  37. line = self.val["ptr"].cast(char_array_ptr_type).dereference()
  38. return repr(bytes(int(line[i]) for i in range(length))).lstrip('b')
  39. class PuTTYPrinterSelector(gdb.printing.PrettyPrinter):
  40. def __init__(self):
  41. super(PuTTYPrinterSelector, self).__init__("PuTTY")
  42. def __call__(self, val):
  43. if str(val.type) == "mp_int *":
  44. return PuTTYMpintPrettyPrinter(val)
  45. if str(val.type) == "ptrlen":
  46. return PuTTYPtrlenPrettyPrinter(val)
  47. return None
  48. gdb.printing.register_pretty_printer(None, PuTTYPrinterSelector())
  49. class MemDumpCommand(gdb.Command):
  50. """Print a hex+ASCII dump of object EXP.
  51. EXP must be an expression whose value resides in memory. The
  52. contents of the memory it occupies are printed in a standard hex
  53. dump format, with each line showing an offset relative to the
  54. address of EXP, then the hex byte values of the memory at that
  55. offset, and then a translation into ASCII of the same bytes (with
  56. values outside the printable ASCII range translated as '.').
  57. To dump a number of bytes from a particular address, it's useful
  58. to use the gdb expression extensions {TYPE} and @LENGTH. For
  59. example, if 'ptr' and 'len' are variables giving an address and a
  60. length in bytes, then the command
  61. memdump {char} ptr @ len
  62. will dump the range of memory described by those two variables."""
  63. def __init__(self):
  64. super(MemDumpCommand, self).__init__(
  65. "memdump", gdb.COMMAND_DATA, gdb.COMPLETE_EXPRESSION)
  66. def invoke(self, cmdline, from_tty):
  67. expr = gdb.parse_and_eval(cmdline)
  68. try:
  69. start, size = int(expr.address), expr.type.sizeof
  70. except gdb.error as e:
  71. raise gdb.GdbError(str(e))
  72. except (TypeError, AttributeError):
  73. raise gdb.GdbError("expression must identify an object in memory")
  74. return
  75. width = 16
  76. line_ptr_type = gdb.lookup_type(
  77. "unsigned char").const().array(width).pointer()
  78. dumpaddr = 0
  79. while size > 0:
  80. line = gdb.Value(start).cast(line_ptr_type).dereference()
  81. thislinelen = min(size, width)
  82. start += thislinelen
  83. size -= thislinelen
  84. dumpline = [None, " "] + [" "] * width + [" "] + [""] * width
  85. dumpline[0] = "{:08x}".format(dumpaddr)
  86. dumpaddr += thislinelen
  87. for i in range(thislinelen):
  88. ch = int(line[i]) & 0xFF
  89. dumpline[2+i] = " {:02x}".format(ch)
  90. dumpline[3+width+i] = chr(ch) if 0x20 <= ch < 0x7F else "."
  91. sys.stdout.write("".join(dumpline) + "\n")
  92. MemDumpCommand()
  93. class ContainerOf(gdb.Function):
  94. """Implement the container_of macro from PuTTY's defs.h.
  95. Arguments are an object or pointer to object; a type to convert it
  96. to; and, optionally the name of the structure member in the
  97. destination type that the pointer points to. (If the member name
  98. is not provided, then the default is whichever member of the
  99. destination structure type has the same type as the input object,
  100. provided there's only one.)
  101. Due to limitations of GDB's convenience function syntax, the type
  102. and member names must be provided as strings.
  103. """
  104. def __init__(self):
  105. super(ContainerOf, self).__init__("container_of")
  106. def match_type(self, obj, typ):
  107. if obj.type == typ:
  108. return obj
  109. try:
  110. ref = obj.referenced_value()
  111. if ref.type == typ:
  112. return ref
  113. except gdb.error:
  114. pass
  115. return None
  116. def invoke(self, obj, dest_type_name_val, member_name_val=None):
  117. try:
  118. dest_type_name = dest_type_name_val.string()
  119. except gdb.error:
  120. raise gdb.GdbError("destination type name must be a string")
  121. try:
  122. dest_type = gdb.lookup_type(dest_type_name)
  123. except gdb.error:
  124. raise gdb.GdbError("no such type '{dt}'".format(dt=dest_type_name))
  125. if member_name_val is not None:
  126. try:
  127. member_name = member_name_val.string()
  128. except gdb.error:
  129. raise gdb.GdbError("member name must be a string")
  130. for field in dest_type.fields():
  131. if field.name == member_name:
  132. break
  133. else:
  134. raise gdb.GdbError(
  135. "type '{dt}' has no member called '{memb}'"
  136. .format(dt=dest_type_name, memb=member_name))
  137. match_obj = self.match_type(obj, field.type)
  138. else:
  139. matches = []
  140. for field in dest_type.fields():
  141. this_match_obj = self.match_type(obj, field.type)
  142. if this_match_obj is not None:
  143. match_obj = this_match_obj
  144. matches.append(field)
  145. if len(matches) == 0:
  146. raise gdb.GdbError(
  147. "type '{dt}' has no member matching type '{ot}'"
  148. .format(dt=dest_type_name, ot=obj.type))
  149. if len(matches) > 1:
  150. raise gdb.GdbError(
  151. "type '{dt}' has multiple members matching type '{ot}'"
  152. " ({memberlist})"
  153. .format(dt=dest_type_name, ot=obj.type,
  154. memberlist=", ".join(f.name for f in matches)))
  155. field = matches[0]
  156. if field.bitpos % 8 != 0:
  157. raise gdb.GdbError(
  158. "offset of field '{memb}' is a fractional number of bytes"
  159. .format(dt=dest_type_name, memb=member_name))
  160. offset = field.bitpos // 8
  161. if match_obj.type != field.type:
  162. raise gdb.GdbError(
  163. "value to convert does not have type '{ft}'"
  164. .format(ft=field.type))
  165. try:
  166. addr = int(match_obj.address)
  167. except gdb.error:
  168. raise gdb.GdbError("cannot take address of value to convert")
  169. return gdb.Value(addr - offset).cast(dest_type.pointer())
  170. ContainerOf()
  171. class List234(gdb.Function):
  172. """List the elements currently stored in a tree234.
  173. Arguments are a tree234, and optionally a value type. If no value
  174. type is given, the result is a list of the raw void * pointers
  175. stored in the tree. Otherwise, each one is cast to a pointer to the
  176. value type and dereferenced.
  177. Due to limitations of GDB's convenience function syntax, the value
  178. type must be provided as a string.
  179. """
  180. def __init__(self):
  181. super(List234, self).__init__("list234")
  182. def add_elements(self, node, destlist):
  183. kids = node["kids"]
  184. elems = node["elems"]
  185. for i in range(4):
  186. if int(kids[i]) != 0:
  187. add_elements(self, kids[i].dereference(), destlist)
  188. if i < 3 and int(elems[i]) != 0:
  189. destlist.append(elems[i])
  190. def invoke(self, tree, value_type_name_val=None):
  191. if value_type_name_val is not None:
  192. try:
  193. value_type_name = value_type_name_val.string()
  194. except gdb.error:
  195. raise gdb.GdbError("value type name must be a string")
  196. try:
  197. value_type = gdb.lookup_type(value_type_name)
  198. except gdb.error:
  199. raise gdb.GdbError("no such type '{dt}'"
  200. .format(dt=value_type_name))
  201. else:
  202. value_type = None
  203. try:
  204. tree = tree.dereference()
  205. except gdb.error:
  206. pass
  207. if tree.type == gdb.lookup_type("tree234"):
  208. tree = tree["root"].dereference()
  209. if tree.type != gdb.lookup_type("node234"):
  210. raise gdb.GdbError(
  211. "input value is not a tree234")
  212. if int(tree.address) == 0:
  213. # If you try to return {} for the empty list, gdb gives
  214. # the cryptic error "bad array bounds (0, -1)"! We return
  215. # NULL as the best approximation to 'sorry, list is
  216. # empty'.
  217. return gdb.parse_and_eval("((void *)0)")
  218. elems = []
  219. self.add_elements(tree, elems)
  220. if value_type is not None:
  221. value_ptr_type_name = str(value_type.pointer())
  222. elem_fmt = lambda p: "*({}){}".format(value_ptr_type_name, int(p))
  223. else:
  224. elem_fmt = lambda p: "(void *){}".format(int(p))
  225. elems_str = "{" + ",".join(elem_fmt(elem) for elem in elems) + "}"
  226. return gdb.parse_and_eval(elems_str)
  227. List234()