nim-gdb.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. import gdb
  2. import re
  3. import sys
  4. # some feedback that the nim runtime support is loading, isn't a bad
  5. # thing at all.
  6. gdb.write("Loading Nim Runtime support.\n", gdb.STDERR)
  7. # When error occure they occur regularly. This 'caches' known errors
  8. # and prevents them from being reprinted over and over again.
  9. errorSet = set()
  10. def printErrorOnce(id, message):
  11. global errorSet
  12. if id not in errorSet:
  13. errorSet.add(id)
  14. gdb.write(message, gdb.STDERR)
  15. ################################################################################
  16. ##### Type pretty printers
  17. ################################################################################
  18. type_hash_regex = re.compile("^\w*_([A-Za-z0-9]*)$")
  19. def getNimRti(type_name):
  20. """ Return a ``gdb.Value`` object for the Nim Runtime Information of ``type_name``. """
  21. # Get static const TNimType variable. This should be available for
  22. # every non trivial Nim type.
  23. m = type_hash_regex.match(type_name)
  24. if m:
  25. try:
  26. return gdb.parse_and_eval("NTI_" + m.group(1) + "_")
  27. except:
  28. return None
  29. class NimTypeRecognizer:
  30. # this type map maps from types that are generated in the C files to
  31. # how they are called in nim. To not mix up the name ``int`` from
  32. # system.nim with the name ``int`` that could still appear in
  33. # generated code, ``NI`` is mapped to ``system.int`` and not just
  34. # ``int``.
  35. type_map_static = {
  36. 'NI': 'system.int', 'NI8': 'int8', 'NI16': 'int16', 'NI32': 'int32', 'NI64': 'int64',
  37. 'NU': 'uint', 'NU8': 'uint8','NU16': 'uint16', 'NU32': 'uint32', 'NU64': 'uint64',
  38. 'NF': 'float', 'NF32': 'float32', 'NF64': 'float64',
  39. 'NIM_BOOL': 'bool', 'NIM_CHAR': 'char', 'NCSTRING': 'cstring',
  40. 'NimStringDesc': 'string'
  41. }
  42. # Normally gdb distinguishes between the command `ptype` and
  43. # `whatis`. `ptype` prints a very detailed view of the type, and
  44. # `whatis` a very brief representation of the type. I haven't
  45. # figured out a way to know from the type printer that is
  46. # implemented here how to know if a type printer should print the
  47. # short representation or the long representation. As a hacky
  48. # workaround I just say I am not resposible for printing pointer
  49. # types (seq and string are exception as they are semantically
  50. # values). this way the default type printer will handle pointer
  51. # types and dive into the members of that type. So I can still
  52. # control with `ptype myval` and `ptype *myval` if I want to have
  53. # detail or not. I this this method stinks but I could not figure
  54. # out a better solution.
  55. object_type_pattern = re.compile("^(\w*):ObjectType$")
  56. def recognize(self, type_obj):
  57. tname = None
  58. if type_obj.tag is not None:
  59. tname = type_obj.tag
  60. elif type_obj.name is not None:
  61. tname = type_obj.name
  62. # handle pointer types
  63. if not tname:
  64. if type_obj.code == gdb.TYPE_CODE_PTR:
  65. target_type = type_obj.target()
  66. target_type_name = target_type.name
  67. if target_type_name:
  68. # visualize 'string' as non pointer type (unpack pointer type).
  69. if target_type_name == "NimStringDesc":
  70. tname = target_type_name # could also just return 'string'
  71. # visualize 'seq[T]' as non pointer type.
  72. if target_type_name.find('tySequence_') == 0:
  73. tname = target_type_name
  74. if not tname:
  75. # We are not resposible for this type printing.
  76. # Basically this means we don't print pointer types.
  77. return None
  78. result = self.type_map_static.get(tname, None)
  79. if result:
  80. return result
  81. rti = getNimRti(tname)
  82. if rti:
  83. return rti['name'].string("utf-8", "ignore")
  84. else:
  85. return None
  86. class NimTypePrinter:
  87. """Nim type printer. One printer for all Nim types."""
  88. # enabling and disabling of type printers can be done with the
  89. # following gdb commands:
  90. #
  91. # enable type-printer NimTypePrinter
  92. # disable type-printer NimTypePrinter
  93. name = "NimTypePrinter"
  94. def __init__ (self):
  95. self.enabled = True
  96. def instantiate(self):
  97. return NimTypeRecognizer()
  98. ################################################################################
  99. ##### GDB Function, equivalent of Nim's $ operator
  100. ################################################################################
  101. class DollarPrintFunction (gdb.Function):
  102. "Nim's equivalent of $ operator as a gdb function, available in expressions `print $dollar(myvalue)"
  103. _gdb_dollar_functions = gdb.execute("info functions dollar__", True, True)
  104. dollar_functions = re.findall('NimStringDesc \*(dollar__[A-z0-9_]+?)\(([^,)]*)\);', _gdb_dollar_functions)
  105. def __init__ (self):
  106. super (DollarPrintFunction, self).__init__("dollar")
  107. @staticmethod
  108. def invoke_static(arg):
  109. for func, arg_typ in DollarPrintFunction.dollar_functions:
  110. if arg.type.name == arg_typ:
  111. func_value = gdb.lookup_global_symbol(func, gdb.SYMBOL_FUNCTIONS_DOMAIN).value()
  112. return func_value(arg)
  113. if arg.type.name + " *" == arg_typ:
  114. func_value = gdb.lookup_global_symbol(func, gdb.SYMBOL_FUNCTIONS_DOMAIN).value()
  115. return func_value(arg.address)
  116. typeName = arg.type.name
  117. printErrorOnce(typeName, "No suitable Nim $ operator found for type: " + typeName + ".\n")
  118. def invoke(self, arg):
  119. return self.invoke_static(arg)
  120. DollarPrintFunction()
  121. ################################################################################
  122. ##### GDB Command, equivalent of Nim's $ operator
  123. ################################################################################
  124. class DollarPrintCmd (gdb.Command):
  125. """Dollar print command for Nim, `$ expr` will invoke Nim's $ operator"""
  126. def __init__ (self):
  127. super (DollarPrintCmd, self).__init__ ("$", gdb.COMMAND_DATA, gdb.COMPLETE_EXPRESSION)
  128. def invoke (self, arg, from_tty):
  129. param = gdb.parse_and_eval(arg)
  130. gdb.write(str(DollarPrintFunction.invoke_static(param)) + "\n", gdb.STDOUT)
  131. DollarPrintCmd()
  132. ################################################################################
  133. ##### Value pretty printers
  134. ################################################################################
  135. class NimBoolPrinter:
  136. pattern = re.compile(r'^NIM_BOOL$')
  137. def __init__(self, val):
  138. self.val = val
  139. def to_string(self):
  140. if self.val == 0:
  141. return "false"
  142. else:
  143. return "true"
  144. ################################################################################
  145. class NimStringPrinter:
  146. pattern = re.compile(r'^NimStringDesc \*$')
  147. def __init__(self, val):
  148. self.val = val
  149. def display_hint(self):
  150. return 'string'
  151. def to_string(self):
  152. if self.val:
  153. l = int(self.val['Sup']['len'])
  154. return self.val['data'][0].address.string("utf-8", "ignore", l)
  155. else:
  156. return ""
  157. class NimRopePrinter:
  158. pattern = re.compile(r'^tyObject_RopeObj_OFzf0kSiPTcNreUIeJgWVA \*$')
  159. def __init__(self, val):
  160. self.val = val
  161. def display_hint(self):
  162. return 'string'
  163. def to_string(self):
  164. if self.val:
  165. left = NimRopePrinter(self.val["left"]).to_string()
  166. data = NimStringPrinter(self.val["data"]).to_string()
  167. right = NimRopePrinter(self.val["right"]).to_string()
  168. return left + data + right
  169. else:
  170. return ""
  171. ################################################################################
  172. # proc reprEnum(e: int, typ: PNimType): string {.compilerRtl.} =
  173. # ## Return string representation for enumeration values
  174. # var n = typ.node
  175. # if ntfEnumHole notin typ.flags:
  176. # let o = e - n.sons[0].offset
  177. # if o >= 0 and o <% typ.node.len:
  178. # return $n.sons[o].name
  179. # else:
  180. # # ugh we need a slow linear search:
  181. # var s = n.sons
  182. # for i in 0 .. n.len-1:
  183. # if s[i].offset == e:
  184. # return $s[i].name
  185. # result = $e & " (invalid data!)"
  186. def reprEnum(e, typ):
  187. """ this is a port of the nim runtime function `reprEnum` to python """
  188. e = int(e)
  189. n = typ["node"]
  190. flags = int(typ["flags"])
  191. # 1 << 2 is {ntfEnumHole}
  192. if ((1 << 2) & flags) == 0:
  193. o = e - int(n["sons"][0]["offset"])
  194. if o >= 0 and 0 < int(n["len"]):
  195. return n["sons"][o]["name"].string("utf-8", "ignore")
  196. else:
  197. # ugh we need a slow linear search:
  198. s = n["sons"]
  199. for i in range(0, int(n["len"])):
  200. if int(s[i]["offset"]) == e:
  201. return s[i]["name"].string("utf-8", "ignore")
  202. return str(e) + " (invalid data!)"
  203. class NimEnumPrinter:
  204. pattern = re.compile(r'^tyEnum_(\w*)_([A-Za-z0-9]*)$')
  205. def __init__(self, val):
  206. self.val = val
  207. match = self.pattern.match(self.val.type.name)
  208. self.typeNimName = match.group(1)
  209. typeInfoName = "NTI_" + match.group(2) + "_"
  210. self.nti = gdb.lookup_global_symbol(typeInfoName)
  211. if self.nti is None:
  212. printErrorOnce(typeInfoName, "NimEnumPrinter: lookup global symbol '" + typeInfoName + " failed for " + self.val.type.name + ".\n")
  213. def to_string(self):
  214. if self.nti:
  215. arg0 = self.val
  216. arg1 = self.nti.value(gdb.newest_frame())
  217. return reprEnum(arg0, arg1)
  218. else:
  219. return self.typeNimName + "(" + str(int(self.val)) + ")"
  220. ################################################################################
  221. class NimSetPrinter:
  222. ## the set printer is limited to sets that fit in an integer. Other
  223. ## sets are compiled to `NU8 *` (ptr uint8) and are invisible to
  224. ## gdb (currently).
  225. pattern = re.compile(r'^tySet_tyEnum_(\w*)_([A-Za-z0-9]*)$')
  226. def __init__(self, val):
  227. self.val = val
  228. match = self.pattern.match(self.val.type.name)
  229. self.typeNimName = match.group(1)
  230. typeInfoName = "NTI_" + match.group(2) + "_"
  231. self.nti = gdb.lookup_global_symbol(typeInfoName)
  232. if self.nti is None:
  233. printErrorOnce(typeInfoName, "NimSetPrinter: lookup global symbol '"+ typeInfoName +" failed for " + self.val.type.name + ".\n")
  234. def to_string(self):
  235. if self.nti:
  236. nti = self.nti.value(gdb.newest_frame())
  237. enumStrings = []
  238. val = int(self.val)
  239. i = 0
  240. while val > 0:
  241. if (val & 1) == 1:
  242. enumStrings.append(reprEnum(i, nti))
  243. val = val >> 1
  244. i += 1
  245. return '{' + ', '.join(enumStrings) + '}'
  246. else:
  247. return str(int(self.val))
  248. ################################################################################
  249. class NimHashSetPrinter:
  250. pattern = re.compile(r'^tyObject_(HashSet)_([A-Za-z0-9]*)$')
  251. def __init__(self, val):
  252. self.val = val
  253. def display_hint(self):
  254. return 'array'
  255. def to_string(self):
  256. counter = 0
  257. capacity = 0
  258. if self.val:
  259. counter = int(self.val['counter'])
  260. if self.val['data']:
  261. capacity = int(self.val['data']['Sup']['len'])
  262. return 'HashSet({0}, {1})'.format(counter, capacity)
  263. def children(self):
  264. if self.val:
  265. data = NimSeqPrinter(self.val['data'])
  266. for idxStr, entry in data.children():
  267. if int(entry['Field0']) > 0:
  268. yield ("data." + idxStr + ".Field1", str(entry['Field1']))
  269. ################################################################################
  270. class NimSeqPrinter:
  271. # the pointer is explicity part of the type. So it is part of
  272. # ``pattern``.
  273. pattern = re.compile(r'^tySequence_\w* \*$')
  274. def __init__(self, val):
  275. self.val = val
  276. def display_hint(self):
  277. return 'array'
  278. def to_string(self):
  279. len = 0
  280. cap = 0
  281. if self.val:
  282. len = int(self.val['Sup']['len'])
  283. cap = int(self.val['Sup']['reserved'])
  284. return 'seq({0}, {1})'.format(len, cap)
  285. def children(self):
  286. if self.val:
  287. length = int(self.val['Sup']['len'])
  288. #align = len(str(length - 1))
  289. for i in range(length):
  290. yield ("data[{0}]".format(i), self.val["data"][i])
  291. ################################################################################
  292. class NimArrayPrinter:
  293. pattern = re.compile(r'^tyArray_\w*$')
  294. def __init__(self, val):
  295. self.val = val
  296. def display_hint(self):
  297. return 'array'
  298. def to_string(self):
  299. return 'array'
  300. def children(self):
  301. length = self.val.type.sizeof // self.val[0].type.sizeof
  302. align = len(str(length-1))
  303. for i in range(length):
  304. yield ("[{0:>{1}}]".format(i, align), self.val[i])
  305. ################################################################################
  306. class NimStringTablePrinter:
  307. pattern = re.compile(r'^tyObject_(StringTableObj)_([A-Za-z0-9]*)(:? \*)?$')
  308. def __init__(self, val):
  309. self.val = val
  310. def display_hint(self):
  311. return 'map'
  312. def to_string(self):
  313. counter = 0
  314. capacity = 0
  315. if self.val:
  316. counter = int(self.val['counter'])
  317. if self.val['data']:
  318. capacity = int(self.val['data']['Sup']['len'])
  319. return 'StringTableObj({0}, {1})'.format(counter, capacity)
  320. def children(self):
  321. if self.val:
  322. data = NimSeqPrinter(self.val['data'])
  323. for idxStr, entry in data.children():
  324. if int(entry['Field2']) > 0:
  325. yield (idxStr + ".Field0", entry['Field0'])
  326. yield (idxStr + ".Field1", entry['Field1'])
  327. ################################################################
  328. class NimTablePrinter:
  329. pattern = re.compile(r'^tyObject_(Table)_([A-Za-z0-9]*)(:? \*)?$')
  330. def __init__(self, val):
  331. self.val = val
  332. # match = self.pattern.match(self.val.type.name)
  333. def display_hint(self):
  334. return 'map'
  335. def to_string(self):
  336. counter = 0
  337. capacity = 0
  338. if self.val:
  339. counter = int(self.val['counter'])
  340. if self.val['data']:
  341. capacity = int(self.val['data']['Sup']['len'])
  342. return 'Table({0}, {1})'.format(counter, capacity)
  343. def children(self):
  344. if self.val:
  345. data = NimSeqPrinter(self.val['data'])
  346. for idxStr, entry in data.children():
  347. if int(entry['Field0']) > 0:
  348. yield (idxStr + '.Field1', entry['Field1'])
  349. yield (idxStr + '.Field2', entry['Field2'])
  350. ################################################################
  351. # this is untested, therefore disabled
  352. # class NimObjectPrinter:
  353. # pattern = re.compile(r'^tyObject_.*$')
  354. # def __init__(self, val):
  355. # self.val = val
  356. # def display_hint(self):
  357. # return 'object'
  358. # def to_string(self):
  359. # return str(self.val.type)
  360. # def children(self):
  361. # if not self.val:
  362. # yield "object", "<nil>"
  363. # raise StopIteration
  364. # for (i, field) in enumerate(self.val.type.fields()):
  365. # if field.type.code == gdb.TYPE_CODE_UNION:
  366. # yield _union_field
  367. # else:
  368. # yield (field.name, self.val[field])
  369. # def _union_field(self, i, field):
  370. # rti = getNimRti(self.val.type.name)
  371. # if rti is None:
  372. # return (field.name, "UNION field can't be displayed without RTI")
  373. # node_sons = rti['node'].dereference()['sons']
  374. # prev_field = self.val.type.fields()[i - 1]
  375. # descriminant_node = None
  376. # for i in range(int(node['len'])):
  377. # son = node_sons[i].dereference()
  378. # if son['name'].string("utf-8", "ignore") == str(prev_field.name):
  379. # descriminant_node = son
  380. # break
  381. # if descriminant_node is None:
  382. # raise ValueError("Can't find union descriminant field in object RTI")
  383. # if descriminant_node is None: raise ValueError("Can't find union field in object RTI")
  384. # union_node = descriminant_node['sons'][int(self.val[prev_field])].dereference()
  385. # union_val = self.val[field]
  386. # for f1 in union_val.type.fields():
  387. # for f2 in union_val[f1].type.fields():
  388. # if str(f2.name) == union_node['name'].string("utf-8", "ignore"):
  389. # return (str(f2.name), union_val[f1][f2])
  390. # raise ValueError("RTI is absent or incomplete, can't find union definition in RTI")
  391. ################################################################################
  392. def makematcher(klass):
  393. def matcher(val):
  394. typeName = str(val.type)
  395. try:
  396. if hasattr(klass, 'pattern') and hasattr(klass, '__name__'):
  397. # print(typeName + " <> " + klass.__name__)
  398. if klass.pattern.match(typeName):
  399. return klass(val)
  400. except Exception as e:
  401. print(klass)
  402. printErrorOnce(typeName, "No matcher for type '" + typeName + "': " + str(e) + "\n")
  403. return matcher
  404. def register_nim_pretty_printers_for_object(objfile):
  405. nimMainSym = gdb.lookup_global_symbol("NimMain", gdb.SYMBOL_FUNCTIONS_DOMAIN)
  406. if nimMainSym and nimMainSym.symtab.objfile == objfile:
  407. print("set Nim pretty printers for ", objfile.filename)
  408. objfile.type_printers = [NimTypePrinter()]
  409. objfile.pretty_printers = [makematcher(var) for var in list(globals().values()) if hasattr(var, 'pattern')]
  410. # Register pretty printers for all objfiles that are already loaded.
  411. for old_objfile in gdb.objfiles():
  412. register_nim_pretty_printers_for_object(old_objfile)
  413. # Register an event handler to register nim pretty printers for all future objfiles.
  414. def new_object_handler(event):
  415. register_nim_pretty_printers_for_object(event.new_objfile)
  416. gdb.events.new_objfile.connect(new_object_handler)