generate_breakpad_symbols.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #!/usr/bin/env python
  2. # Copyright (c) 2013 GitHub, Inc.
  3. # Copyright (c) 2013 The Chromium Authors. All rights reserved.
  4. # Use of this source code is governed by a BSD-style license that can be
  5. # found in the LICENSE file.
  6. """A tool to generate symbols for a binary suitable for breakpad.
  7. Currently, the tool only supports Linux, Android, and Mac. Support for other
  8. platforms is planned.
  9. """
  10. import errno
  11. import argparse
  12. import os
  13. import Queue
  14. import re
  15. import shutil
  16. import subprocess
  17. import sys
  18. import threading
  19. CONCURRENT_TASKS=4
  20. def GetCommandOutput(command):
  21. """Runs the command list, returning its output.
  22. Prints the given command (which should be a list of one or more strings),
  23. then runs it and returns its output (stdout) as a string.
  24. From chromium_utils.
  25. """
  26. devnull = open(os.devnull, 'w')
  27. proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=devnull,
  28. bufsize=1)
  29. output = proc.communicate()[0]
  30. return output
  31. def GetDumpSymsBinary(build_dir=None):
  32. """Returns the path to the dump_syms binary."""
  33. DUMP_SYMS = 'dump_syms'
  34. dump_syms_bin = os.path.join(os.path.expanduser(build_dir), DUMP_SYMS)
  35. if not os.access(dump_syms_bin, os.X_OK):
  36. print 'Cannot find %s.' % DUMP_SYMS
  37. sys.exit(1)
  38. return dump_syms_bin
  39. def FindBundlePart(full_path):
  40. if full_path.endswith(('.dylib', '.framework', '.app')):
  41. return os.path.basename(full_path)
  42. elif full_path != '' and full_path != '/':
  43. return FindBundlePart(os.path.dirname(full_path))
  44. else:
  45. return ''
  46. def GetDSYMBundle(options, binary_path):
  47. """Finds the .dSYM bundle to the binary."""
  48. if os.path.isabs(binary_path):
  49. dsym_path = binary_path + '.dSYM'
  50. if os.path.exists(dsym_path):
  51. return dsym_path
  52. filename = FindBundlePart(binary_path)
  53. search_dirs = [options.build_dir, options.libchromiumcontent_dir]
  54. if filename.endswith(('.dylib', '.framework', '.app')):
  55. for directory in search_dirs:
  56. dsym_path = os.path.join(directory, filename) + '.dSYM'
  57. if os.path.exists(dsym_path):
  58. return dsym_path
  59. return binary_path
  60. def GetSymbolPath(options, binary_path):
  61. """Finds the .dbg to the binary."""
  62. filename = os.path.basename(binary_path)
  63. dbg_path = os.path.join(options.libchromiumcontent_dir, filename) + '.dbg'
  64. if os.path.exists(dbg_path):
  65. return dbg_path
  66. return binary_path
  67. def Resolve(path, exe_path, loader_path, rpaths):
  68. """Resolve a dyld path.
  69. @executable_path is replaced with |exe_path|
  70. @loader_path is replaced with |loader_path|
  71. @rpath is replaced with the first path in |rpaths| where the referenced file
  72. is found
  73. """
  74. path = path.replace('@loader_path', loader_path)
  75. path = path.replace('@executable_path', exe_path)
  76. if path.find('@rpath') != -1:
  77. for rpath in rpaths:
  78. new_path = Resolve(path.replace('@rpath', rpath), exe_path, loader_path,
  79. [])
  80. if os.access(new_path, os.F_OK):
  81. return new_path
  82. return ''
  83. return path
  84. def GetSharedLibraryDependenciesLinux(binary):
  85. """Return absolute paths to all shared library dependecies of the binary.
  86. This implementation assumes that we're running on a Linux system."""
  87. ldd = GetCommandOutput(['ldd', binary])
  88. lib_re = re.compile('\t.* => (.+) \(.*\)$')
  89. result = []
  90. for line in ldd.splitlines():
  91. m = lib_re.match(line)
  92. if m:
  93. result.append(os.path.realpath(m.group(1)))
  94. return result
  95. def GetSharedLibraryDependenciesMac(binary, exe_path):
  96. """Return absolute paths to all shared library dependecies of the binary.
  97. This implementation assumes that we're running on a Mac system."""
  98. loader_path = os.path.dirname(binary)
  99. otool = GetCommandOutput(['otool', '-l', binary]).splitlines()
  100. rpaths = []
  101. for idx, line in enumerate(otool):
  102. if line.find('cmd LC_RPATH') != -1:
  103. m = re.match(' *path (.*) \(offset .*\)$', otool[idx+2])
  104. rpaths.append(m.group(1))
  105. otool = GetCommandOutput(['otool', '-L', binary]).splitlines()
  106. lib_re = re.compile('\t(.*) \(compatibility .*\)$')
  107. deps = []
  108. for line in otool:
  109. m = lib_re.match(line)
  110. if m:
  111. dep = Resolve(m.group(1), exe_path, loader_path, rpaths)
  112. if dep:
  113. deps.append(os.path.normpath(dep))
  114. return deps
  115. def GetSharedLibraryDependencies(options, binary, exe_path):
  116. """Return absolute paths to all shared library dependecies of the binary."""
  117. deps = []
  118. if sys.platform.startswith('linux'):
  119. deps = GetSharedLibraryDependenciesLinux(binary)
  120. elif sys.platform == 'darwin':
  121. deps = GetSharedLibraryDependenciesMac(binary, exe_path)
  122. else:
  123. print "Platform not supported."
  124. sys.exit(1)
  125. result = []
  126. build_dir = os.path.abspath(options.build_dir)
  127. for dep in deps:
  128. if (os.access(dep, os.F_OK)):
  129. result.append(dep)
  130. return result
  131. def mkdir_p(path):
  132. """Simulates mkdir -p."""
  133. try:
  134. os.makedirs(path)
  135. except OSError as e:
  136. if e.errno == errno.EEXIST and os.path.isdir(path):
  137. pass
  138. else: raise
  139. def GenerateSymbols(options, binaries):
  140. """Dumps the symbols of binary and places them in the given directory."""
  141. queue = Queue.Queue()
  142. print_lock = threading.Lock()
  143. def _Worker():
  144. while True:
  145. binary = queue.get()
  146. if options.verbose:
  147. with print_lock:
  148. print "Generating symbols for %s" % binary
  149. if sys.platform == 'darwin':
  150. binary = GetDSYMBundle(options, binary)
  151. elif sys.platform == 'linux2':
  152. binary = GetSymbolPath(options, binary)
  153. syms = GetCommandOutput([GetDumpSymsBinary(options.build_dir), '-r', '-c',
  154. binary])
  155. module_line = re.match("MODULE [^ ]+ [^ ]+ ([0-9A-F]+) (.*)\n", syms)
  156. output_path = os.path.join(options.symbols_dir, module_line.group(2),
  157. module_line.group(1))
  158. mkdir_p(output_path)
  159. symbol_file = "%s.sym" % module_line.group(2)
  160. f = open(os.path.join(output_path, symbol_file), 'w')
  161. f.write(syms)
  162. f.close()
  163. queue.task_done()
  164. for binary in binaries:
  165. queue.put(binary)
  166. for _ in range(options.jobs):
  167. t = threading.Thread(target=_Worker)
  168. t.daemon = True
  169. t.start()
  170. queue.join()
  171. def main():
  172. parser = argparse.ArgumentParser(description='Generate Breakpad Symbols Project')
  173. parser.add_argument('--build-dir', required=True,
  174. help='The build output directory.')
  175. parser.add_argument('--symbols-dir', required=True,
  176. help='The directory where to write the symbols file.')
  177. parser.add_argument('--libchromiumcontent-dir', required=True,
  178. help='The directory where libchromiumcontent is downloaded.')
  179. parser.add_argument('--binary', action='append', required=True,
  180. help='The path of the binary to generate symbols for.')
  181. parser.add_argument('--clear', default=False, action='store_true',
  182. help='Clear the symbols directory before writing new '
  183. 'symbols.')
  184. parser.add_argument('-j', '--jobs', default=CONCURRENT_TASKS, action='store',
  185. type=int, help='Number of parallel tasks to run.')
  186. parser.add_argument('-v', '--verbose', action='store_true',
  187. help='Print verbose status output.')
  188. options = parser.parse_args()
  189. for bin_file in options.binary:
  190. if not os.access(bin_file, os.X_OK):
  191. print "Cannot find %s." % options.binary
  192. return 1
  193. if options.clear:
  194. try:
  195. shutil.rmtree(options.symbols_dir)
  196. except:
  197. pass
  198. # Build the transitive closure of all dependencies.
  199. binaries = set(options.binary)
  200. queue = options.binary
  201. while queue:
  202. current_bin = queue.pop(0)
  203. exe_path = os.path.dirname(current_bin)
  204. deps = GetSharedLibraryDependencies(options, current_bin, exe_path)
  205. new_deps = set(deps) - binaries
  206. binaries |= new_deps
  207. queue.extend(list(new_deps))
  208. GenerateSymbols(options, binaries)
  209. return 0
  210. if '__main__' == __name__:
  211. sys.exit(main())