fix_stack_using_bpsyms.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. #!/usr/bin/env python
  2. # This Source Code Form is subject to the terms of the Mozilla Public
  3. # License, v. 2.0. If a copy of the MPL was not distributed with this
  4. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. # This script uses breakpad symbols to post-process the entries produced by
  6. # NS_FormatCodeAddress(), which on TBPL builds often lack a file name and a
  7. # line number (and on Linux even the symbol is often bad).
  8. from __future__ import with_statement
  9. import sys
  10. import os
  11. import re
  12. import subprocess
  13. import bisect
  14. here = os.path.dirname(__file__)
  15. def prettyFileName(name):
  16. if name.startswith("../") or name.startswith("..\\"):
  17. # dom_quickstubs.cpp and many .h files show up with relative paths that are useless
  18. # and/or don't correspond to the layout of the source tree.
  19. return os.path.basename(name) + ":"
  20. elif name.startswith("hg:"):
  21. bits = name.split(":")
  22. if len(bits) == 4:
  23. (junk, repo, path, rev) = bits
  24. # We could construct an hgweb URL with /file/ or /annotate/, like this:
  25. # return "http://%s/annotate/%s/%s#l" % (repo, rev, path)
  26. return path + ":"
  27. return name + ":"
  28. class SymbolFile:
  29. def __init__(self, fn):
  30. addrs = [] # list of addresses, which will be sorted once we're done initializing
  31. funcs = {} # hash: address --> (function name + possible file/line)
  32. files = {} # hash: filenum (string) --> prettified filename ready to have a line number appended
  33. with open(fn) as f:
  34. for line in f:
  35. line = line.rstrip()
  36. # https://chromium.googlesource.com/breakpad/breakpad/+/master/docs/symbol_files.md
  37. if line.startswith("FUNC "):
  38. # FUNC <address> <size> <stack_param_size> <name>
  39. bits = line.split(None, 4)
  40. if len(bits) < 5:
  41. bits.append('unnamed_function')
  42. (junk, rva, size, ss, name) = bits
  43. rva = int(rva,16)
  44. funcs[rva] = name
  45. addrs.append(rva)
  46. lastFuncName = name
  47. elif line.startswith("PUBLIC "):
  48. # PUBLIC <address> <stack_param_size> <name>
  49. (junk, rva, ss, name) = line.split(None, 3)
  50. rva = int(rva,16)
  51. funcs[rva] = name
  52. addrs.append(rva)
  53. elif line.startswith("FILE "):
  54. # FILE <number> <name>
  55. (junk, filenum, name) = line.split(None, 2)
  56. files[filenum] = prettyFileName(name)
  57. elif line[0] in "0123456789abcdef":
  58. # This is one of the "line records" corresponding to the last FUNC record
  59. # <address> <size> <line> <filenum>
  60. (rva, size, line, filenum) = line.split(None)
  61. rva = int(rva,16)
  62. file = files[filenum]
  63. name = lastFuncName + " [" + file + line + "]"
  64. funcs[rva] = name
  65. addrs.append(rva)
  66. # skip everything else
  67. #print "Loaded %d functions from symbol file %s" % (len(funcs), os.path.basename(fn))
  68. self.addrs = sorted(addrs)
  69. self.funcs = funcs
  70. def addrToSymbol(self, address):
  71. i = bisect.bisect(self.addrs, address) - 1
  72. if i > 0:
  73. #offset = address - self.addrs[i]
  74. return self.funcs[self.addrs[i]]
  75. else:
  76. return ""
  77. def findIdForPath(path):
  78. """Finds the breakpad id for the object file at the given path."""
  79. # We should always be packaged with a "fileid" executable.
  80. fileid_exe = os.path.join(here, 'fileid')
  81. if not os.path.isfile(fileid_exe):
  82. fileid_exe = fileid_exe + '.exe'
  83. if not os.path.isfile(fileid_exe):
  84. raise Exception("Could not find fileid executable in %s" % here)
  85. if not os.path.isfile(path):
  86. for suffix in ('.exe', '.dll'):
  87. if os.path.isfile(path + suffix):
  88. path = path + suffix
  89. try:
  90. return subprocess.check_output([fileid_exe, path]).rstrip()
  91. except subprocess.CalledProcessError as e:
  92. raise Exception("Error getting fileid for %s: %s" %
  93. (path, e.output))
  94. def guessSymbolFile(full_path, symbolsDir):
  95. """Guess a symbol file based on an object file's basename, ignoring the path and UUID."""
  96. fn = os.path.basename(full_path)
  97. d1 = os.path.join(symbolsDir, fn)
  98. root, _ = os.path.splitext(fn)
  99. if os.path.exists(os.path.join(symbolsDir, root) + '.pdb'):
  100. d1 = os.path.join(symbolsDir, root) + '.pdb'
  101. fn = root
  102. if not os.path.exists(d1):
  103. return None
  104. uuids = os.listdir(d1)
  105. if len(uuids) == 0:
  106. raise Exception("Missing symbol file for " + fn)
  107. if len(uuids) > 1:
  108. uuid = findIdForPath(full_path)
  109. else:
  110. uuid = uuids[0]
  111. return os.path.join(d1, uuid, fn + ".sym")
  112. parsedSymbolFiles = {}
  113. def getSymbolFile(file, symbolsDir):
  114. p = None
  115. if not file in parsedSymbolFiles:
  116. symfile = guessSymbolFile(file, symbolsDir)
  117. if symfile:
  118. p = SymbolFile(symfile)
  119. else:
  120. p = None
  121. parsedSymbolFiles[file] = p
  122. else:
  123. p = parsedSymbolFiles[file]
  124. return p
  125. def addressToSymbol(file, address, symbolsDir):
  126. p = getSymbolFile(file, symbolsDir)
  127. if p:
  128. return p.addrToSymbol(address)
  129. else:
  130. return ""
  131. # Matches lines produced by NS_FormatCodeAddress().
  132. line_re = re.compile("^(.*#\d+: )(.+)\[(.+) \+(0x[0-9A-Fa-f]+)\](.*)$")
  133. def fixSymbols(line, symbolsDir):
  134. result = line_re.match(line)
  135. if result is not None:
  136. (before, fn, file, address, after) = result.groups()
  137. address = int(address, 16)
  138. symbol = addressToSymbol(file, address, symbolsDir)
  139. if not symbol:
  140. symbol = "%s + 0x%x" % (os.path.basename(file), address)
  141. return before + symbol + after + "\n"
  142. else:
  143. return line
  144. if __name__ == "__main__":
  145. symbolsDir = sys.argv[1]
  146. for line in iter(sys.stdin.readline, ''):
  147. print fixSymbols(line, symbolsDir),