nim-gdb.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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. ##### GDB Commands to invoke common nim tools.
  134. ################################################################################
  135. import subprocess, os
  136. class KochCmd (gdb.Command):
  137. """Command that invokes ``koch'', the build tool for the compiler."""
  138. def __init__ (self):
  139. super (KochCmd, self).__init__ ("koch",
  140. gdb.COMMAND_USER, gdb.COMPLETE_FILENAME)
  141. self.binary = os.path.join(
  142. os.path.dirname(os.path.dirname(__file__)), "koch")
  143. def invoke(self, argument, from_tty):
  144. import os
  145. subprocess.run([self.binary] + gdb.string_to_argv(argument))
  146. KochCmd()
  147. class NimCmd (gdb.Command):
  148. """Command that invokes ``nim'', the nim compiler."""
  149. def __init__ (self):
  150. super (NimCmd, self).__init__ ("nim",
  151. gdb.COMMAND_USER, gdb.COMPLETE_FILENAME)
  152. self.binary = os.path.join(
  153. os.path.dirname(os.path.dirname(__file__)), "bin/nim")
  154. def invoke(self, argument, from_tty):
  155. subprocess.run([self.binary] + gdb.string_to_argv(argument))
  156. NimCmd()
  157. class NimbleCmd (gdb.Command):
  158. """Command that invokes ``nimble'', the nim package manager and build tool."""
  159. def __init__ (self):
  160. super (NimbleCmd, self).__init__ ("nimble",
  161. gdb.COMMAND_USER, gdb.COMPLETE_FILENAME)
  162. self.binary = os.path.join(
  163. os.path.dirname(os.path.dirname(__file__)), "bin/nimble")
  164. def invoke(self, argument, from_tty):
  165. subprocess.run([self.binary] + gdb.string_to_argv(argument))
  166. NimbleCmd()
  167. ################################################################################
  168. ##### Value pretty printers
  169. ################################################################################
  170. class NimBoolPrinter:
  171. pattern = re.compile(r'^NIM_BOOL$')
  172. def __init__(self, val):
  173. self.val = val
  174. def to_string(self):
  175. if self.val == 0:
  176. return "false"
  177. else:
  178. return "true"
  179. ################################################################################
  180. class NimStringPrinter:
  181. pattern = re.compile(r'^NimStringDesc \*$')
  182. def __init__(self, val):
  183. self.val = val
  184. def display_hint(self):
  185. return 'string'
  186. def to_string(self):
  187. if self.val:
  188. l = int(self.val['Sup']['len'])
  189. return self.val['data'][0].address.string("utf-8", "ignore", l)
  190. else:
  191. return ""
  192. class NimRopePrinter:
  193. pattern = re.compile(r'^tyObject_RopeObj_OFzf0kSiPTcNreUIeJgWVA \*$')
  194. def __init__(self, val):
  195. self.val = val
  196. def display_hint(self):
  197. return 'string'
  198. def to_string(self):
  199. if self.val:
  200. left = NimRopePrinter(self.val["left"]).to_string()
  201. data = NimStringPrinter(self.val["data"]).to_string()
  202. right = NimRopePrinter(self.val["right"]).to_string()
  203. return left + data + right
  204. else:
  205. return ""
  206. ################################################################################
  207. # proc reprEnum(e: int, typ: PNimType): string {.compilerRtl.} =
  208. # ## Return string representation for enumeration values
  209. # var n = typ.node
  210. # if ntfEnumHole notin typ.flags:
  211. # let o = e - n.sons[0].offset
  212. # if o >= 0 and o <% typ.node.len:
  213. # return $n.sons[o].name
  214. # else:
  215. # # ugh we need a slow linear search:
  216. # var s = n.sons
  217. # for i in 0 .. n.len-1:
  218. # if s[i].offset == e:
  219. # return $s[i].name
  220. # result = $e & " (invalid data!)"
  221. def reprEnum(e, typ):
  222. """ this is a port of the nim runtime function `reprEnum` to python """
  223. e = int(e)
  224. n = typ["node"]
  225. flags = int(typ["flags"])
  226. # 1 << 2 is {ntfEnumHole}
  227. if ((1 << 2) & flags) == 0:
  228. o = e - int(n["sons"][0]["offset"])
  229. if o >= 0 and 0 < int(n["len"]):
  230. return n["sons"][o]["name"].string("utf-8", "ignore")
  231. else:
  232. # ugh we need a slow linear search:
  233. s = n["sons"]
  234. for i in range(0, int(n["len"])):
  235. if int(s[i]["offset"]) == e:
  236. return s[i]["name"].string("utf-8", "ignore")
  237. return str(e) + " (invalid data!)"
  238. class NimEnumPrinter:
  239. pattern = re.compile(r'^tyEnum_(\w*)_([A-Za-z0-9]*)$')
  240. def __init__(self, val):
  241. self.val = val
  242. match = self.pattern.match(self.val.type.name)
  243. self.typeNimName = match.group(1)
  244. typeInfoName = "NTI_" + match.group(2) + "_"
  245. self.nti = gdb.lookup_global_symbol(typeInfoName)
  246. if self.nti is None:
  247. printErrorOnce(typeInfoName, "NimEnumPrinter: lookup global symbol '" + typeInfoName + " failed for " + self.val.type.name + ".\n")
  248. def to_string(self):
  249. if self.nti:
  250. arg0 = self.val
  251. arg1 = self.nti.value(gdb.newest_frame())
  252. return reprEnum(arg0, arg1)
  253. else:
  254. return self.typeNimName + "(" + str(int(self.val)) + ")"
  255. ################################################################################
  256. class NimSetPrinter:
  257. ## the set printer is limited to sets that fit in an integer. Other
  258. ## sets are compiled to `NU8 *` (ptr uint8) and are invisible to
  259. ## gdb (currently).
  260. pattern = re.compile(r'^tySet_tyEnum_(\w*)_([A-Za-z0-9]*)$')
  261. def __init__(self, val):
  262. self.val = val
  263. match = self.pattern.match(self.val.type.name)
  264. self.typeNimName = match.group(1)
  265. typeInfoName = "NTI_" + match.group(2) + "_"
  266. self.nti = gdb.lookup_global_symbol(typeInfoName)
  267. if self.nti is None:
  268. printErrorOnce(typeInfoName, "NimSetPrinter: lookup global symbol '"+ typeInfoName +" failed for " + self.val.type.name + ".\n")
  269. def to_string(self):
  270. if self.nti:
  271. nti = self.nti.value(gdb.newest_frame())
  272. enumStrings = []
  273. val = int(self.val)
  274. i = 0
  275. while val > 0:
  276. if (val & 1) == 1:
  277. enumStrings.append(reprEnum(i, nti))
  278. val = val >> 1
  279. i += 1
  280. return '{' + ', '.join(enumStrings) + '}'
  281. else:
  282. return str(int(self.val))
  283. ################################################################################
  284. class NimHashSetPrinter:
  285. pattern = re.compile(r'^tyObject_(HashSet)_([A-Za-z0-9]*)$')
  286. def __init__(self, val):
  287. self.val = val
  288. def display_hint(self):
  289. return 'array'
  290. def to_string(self):
  291. counter = 0
  292. capacity = 0
  293. if self.val:
  294. counter = int(self.val['counter'])
  295. if self.val['data']:
  296. capacity = int(self.val['data']['Sup']['len'])
  297. return 'HashSet({0}, {1})'.format(counter, capacity)
  298. def children(self):
  299. if self.val:
  300. data = NimSeqPrinter(self.val['data'])
  301. for idxStr, entry in data.children():
  302. if int(entry['Field0']) > 0:
  303. yield ("data." + idxStr + ".Field1", str(entry['Field1']))
  304. ################################################################################
  305. class NimSeqPrinter:
  306. # the pointer is explicity part of the type. So it is part of
  307. # ``pattern``.
  308. pattern = re.compile(r'^tySequence_\w* \*$')
  309. def __init__(self, val):
  310. self.val = val
  311. def display_hint(self):
  312. return 'array'
  313. def to_string(self):
  314. len = 0
  315. cap = 0
  316. if self.val:
  317. len = int(self.val['Sup']['len'])
  318. cap = int(self.val['Sup']['reserved'])
  319. return 'seq({0}, {1})'.format(len, cap)
  320. def children(self):
  321. if self.val:
  322. length = int(self.val['Sup']['len'])
  323. #align = len(str(length - 1))
  324. for i in range(length):
  325. yield ("data[{0}]".format(i), self.val["data"][i])
  326. ################################################################################
  327. class NimArrayPrinter:
  328. pattern = re.compile(r'^tyArray_\w*$')
  329. def __init__(self, val):
  330. self.val = val
  331. def display_hint(self):
  332. return 'array'
  333. def to_string(self):
  334. return 'array'
  335. def children(self):
  336. length = self.val.type.sizeof // self.val[0].type.sizeof
  337. align = len(str(length-1))
  338. for i in range(length):
  339. yield ("[{0:>{1}}]".format(i, align), self.val[i])
  340. ################################################################################
  341. class NimStringTablePrinter:
  342. pattern = re.compile(r'^tyObject_(StringTableObj)_([A-Za-z0-9]*)(:? \*)?$')
  343. def __init__(self, val):
  344. self.val = val
  345. def display_hint(self):
  346. return 'map'
  347. def to_string(self):
  348. counter = 0
  349. capacity = 0
  350. if self.val:
  351. counter = int(self.val['counter'])
  352. if self.val['data']:
  353. capacity = int(self.val['data']['Sup']['len'])
  354. return 'StringTableObj({0}, {1})'.format(counter, capacity)
  355. def children(self):
  356. if self.val:
  357. data = NimSeqPrinter(self.val['data'])
  358. for idxStr, entry in data.children():
  359. if int(entry['Field2']) > 0:
  360. yield (idxStr + ".Field0", entry['Field0'])
  361. yield (idxStr + ".Field1", entry['Field1'])
  362. ################################################################
  363. class NimTablePrinter:
  364. pattern = re.compile(r'^tyObject_(Table)_([A-Za-z0-9]*)(:? \*)?$')
  365. def __init__(self, val):
  366. self.val = val
  367. # match = self.pattern.match(self.val.type.name)
  368. def display_hint(self):
  369. return 'map'
  370. def to_string(self):
  371. counter = 0
  372. capacity = 0
  373. if self.val:
  374. counter = int(self.val['counter'])
  375. if self.val['data']:
  376. capacity = int(self.val['data']['Sup']['len'])
  377. return 'Table({0}, {1})'.format(counter, capacity)
  378. def children(self):
  379. if self.val:
  380. data = NimSeqPrinter(self.val['data'])
  381. for idxStr, entry in data.children():
  382. if int(entry['Field0']) > 0:
  383. yield (idxStr + '.Field1', entry['Field1'])
  384. yield (idxStr + '.Field2', entry['Field2'])
  385. ################################################################
  386. # this is untested, therefore disabled
  387. # class NimObjectPrinter:
  388. # pattern = re.compile(r'^tyObject_.*$')
  389. # def __init__(self, val):
  390. # self.val = val
  391. # def display_hint(self):
  392. # return 'object'
  393. # def to_string(self):
  394. # return str(self.val.type)
  395. # def children(self):
  396. # if not self.val:
  397. # yield "object", "<nil>"
  398. # raise StopIteration
  399. # for (i, field) in enumerate(self.val.type.fields()):
  400. # if field.type.code == gdb.TYPE_CODE_UNION:
  401. # yield _union_field
  402. # else:
  403. # yield (field.name, self.val[field])
  404. # def _union_field(self, i, field):
  405. # rti = getNimRti(self.val.type.name)
  406. # if rti is None:
  407. # return (field.name, "UNION field can't be displayed without RTI")
  408. # node_sons = rti['node'].dereference()['sons']
  409. # prev_field = self.val.type.fields()[i - 1]
  410. # descriminant_node = None
  411. # for i in range(int(node['len'])):
  412. # son = node_sons[i].dereference()
  413. # if son['name'].string("utf-8", "ignore") == str(prev_field.name):
  414. # descriminant_node = son
  415. # break
  416. # if descriminant_node is None:
  417. # raise ValueError("Can't find union descriminant field in object RTI")
  418. # if descriminant_node is None: raise ValueError("Can't find union field in object RTI")
  419. # union_node = descriminant_node['sons'][int(self.val[prev_field])].dereference()
  420. # union_val = self.val[field]
  421. # for f1 in union_val.type.fields():
  422. # for f2 in union_val[f1].type.fields():
  423. # if str(f2.name) == union_node['name'].string("utf-8", "ignore"):
  424. # return (str(f2.name), union_val[f1][f2])
  425. # raise ValueError("RTI is absent or incomplete, can't find union definition in RTI")
  426. ################################################################################
  427. def makematcher(klass):
  428. def matcher(val):
  429. typeName = str(val.type)
  430. try:
  431. if hasattr(klass, 'pattern') and hasattr(klass, '__name__'):
  432. # print(typeName + " <> " + klass.__name__)
  433. if klass.pattern.match(typeName):
  434. return klass(val)
  435. except Exception as e:
  436. print(klass)
  437. printErrorOnce(typeName, "No matcher for type '" + typeName + "': " + str(e) + "\n")
  438. return matcher
  439. def register_nim_pretty_printers_for_object(objfile):
  440. nimMainSym = gdb.lookup_global_symbol("NimMain", gdb.SYMBOL_FUNCTIONS_DOMAIN)
  441. if nimMainSym and nimMainSym.symtab.objfile == objfile:
  442. print("set Nim pretty printers for ", objfile.filename)
  443. objfile.type_printers = [NimTypePrinter()]
  444. objfile.pretty_printers = [makematcher(var) for var in list(globals().values()) if hasattr(var, 'pattern')]
  445. # Register pretty printers for all objfiles that are already loaded.
  446. for old_objfile in gdb.objfiles():
  447. register_nim_pretty_printers_for_object(old_objfile)
  448. # Register an event handler to register nim pretty printers for all future objfiles.
  449. def new_object_handler(event):
  450. register_nim_pretty_printers_for_object(event.new_objfile)
  451. gdb.events.new_objfile.connect(new_object_handler)