extract_symbols.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. #!/usr/bin/env python
  2. """A tool for extracting a list of symbols to export
  3. When exporting symbols from a dll or exe we either need to mark the symbols in
  4. the source code as __declspec(dllexport) or supply a list of symbols to the
  5. linker. This program automates the latter by inspecting the symbol tables of a
  6. list of link inputs and deciding which of those symbols need to be exported.
  7. We can't just export all the defined symbols, as there's a limit of 65535
  8. exported symbols and in clang we go way over that, particularly in a debug
  9. build. Therefore a large part of the work is pruning symbols either which can't
  10. be imported, or which we think are things that have definitions in public header
  11. files (i.e. template instantiations) and we would get defined in the thing
  12. importing these symbols anyway.
  13. """
  14. from __future__ import print_function
  15. import sys
  16. import re
  17. import os
  18. import subprocess
  19. import multiprocessing
  20. import argparse
  21. # Define functions which extract a list of symbols from a library using several
  22. # different tools. We use subprocess.Popen and yield a symbol at a time instead
  23. # of using subprocess.check_output and returning a list as, especially on
  24. # Windows, waiting for the entire output to be ready can take a significant
  25. # amount of time.
  26. def dumpbin_get_symbols(lib):
  27. process = subprocess.Popen(['dumpbin','/symbols',lib], bufsize=1,
  28. stdout=subprocess.PIPE, stdin=subprocess.PIPE,
  29. universal_newlines=True)
  30. process.stdin.close()
  31. for line in process.stdout:
  32. # Look for external symbols that are defined in some section
  33. match = re.match("^.+SECT.+External\s+\|\s+(\S+).*$", line)
  34. if match:
  35. yield match.group(1)
  36. process.wait()
  37. def nm_get_symbols(lib):
  38. process = subprocess.Popen(['nm',lib], bufsize=1,
  39. stdout=subprocess.PIPE, stdin=subprocess.PIPE,
  40. universal_newlines=True)
  41. process.stdin.close()
  42. for line in process.stdout:
  43. # Look for external symbols that are defined in some section
  44. match = re.match("^\S+\s+[BDGRSTVW]\s+(\S+)$", line)
  45. if match:
  46. yield match.group(1)
  47. process.wait()
  48. def readobj_get_symbols(lib):
  49. process = subprocess.Popen(['llvm-readobj','-symbols',lib], bufsize=1,
  50. stdout=subprocess.PIPE, stdin=subprocess.PIPE,
  51. universal_newlines=True)
  52. process.stdin.close()
  53. for line in process.stdout:
  54. # When looking through the output of llvm-readobj we expect to see Name,
  55. # Section, then StorageClass, so record Name and Section when we see
  56. # them and decide if this is a defined external symbol when we see
  57. # StorageClass.
  58. match = re.search('Name: (\S+)', line)
  59. if match:
  60. name = match.group(1)
  61. match = re.search('Section: (\S+)', line)
  62. if match:
  63. section = match.group(1)
  64. match = re.search('StorageClass: (\S+)', line)
  65. if match:
  66. storageclass = match.group(1)
  67. if section != 'IMAGE_SYM_ABSOLUTE' and \
  68. section != 'IMAGE_SYM_UNDEFINED' and \
  69. storageclass == 'External':
  70. yield name
  71. process.wait()
  72. # Define functions which determine if the target is 32-bit Windows (as that's
  73. # where calling convention name decoration happens).
  74. def dumpbin_is_32bit_windows(lib):
  75. # dumpbin /headers can output a huge amount of data (>100MB in a debug
  76. # build) so we read only up to the 'machine' line then close the output.
  77. process = subprocess.Popen(['dumpbin','/headers',lib], bufsize=1,
  78. stdout=subprocess.PIPE, stdin=subprocess.PIPE,
  79. universal_newlines=True)
  80. process.stdin.close()
  81. retval = False
  82. for line in process.stdout:
  83. match = re.match('.+machine \((\S+)\)', line)
  84. if match:
  85. retval = (match.group(1) == 'x86')
  86. break
  87. process.stdout.close()
  88. process.wait()
  89. return retval
  90. def objdump_is_32bit_windows(lib):
  91. output = subprocess.check_output(['objdump','-f',lib],
  92. universal_newlines=True)
  93. for line in output:
  94. match = re.match('.+file format (\S+)', line)
  95. if match:
  96. return (match.group(1) == 'pe-i386')
  97. return False
  98. def readobj_is_32bit_windows(lib):
  99. output = subprocess.check_output(['llvm-readobj','-file-headers',lib],
  100. universal_newlines=True)
  101. for line in output:
  102. match = re.match('Format: (\S+)', line)
  103. if match:
  104. return (match.group(1) == 'COFF-i386')
  105. return False
  106. # MSVC mangles names to ?<identifier_mangling>@<type_mangling>. By examining the
  107. # identifier/type mangling we can decide which symbols could possibly be
  108. # required and which we can discard.
  109. def should_keep_microsoft_symbol(symbol, calling_convention_decoration):
  110. # Keep unmangled (i.e. extern "C") names
  111. if not '?' in symbol:
  112. if calling_convention_decoration:
  113. # Remove calling convention decoration from names
  114. match = re.match('[_@]([^@]+)', symbol)
  115. if match:
  116. return match.group(1)
  117. return symbol
  118. # Function template instantiations start with ?$; keep the instantiations of
  119. # clang::Type::getAs, as some of them are explipict specializations that are
  120. # defined in clang's lib/AST/Type.cpp; discard the rest as it's assumed that
  121. # the definition is public
  122. elif re.match('\?\?\$getAs@.+@Type@clang@@', symbol):
  123. return symbol
  124. elif symbol.startswith('??$'):
  125. return None
  126. # Deleting destructors start with ?_G or ?_E and can be discarded because
  127. # link.exe gives you a warning telling you they can't be exported if you
  128. # don't
  129. elif symbol.startswith('??_G') or symbol.startswith('??_E'):
  130. return None
  131. # Constructors (?0) and destructors (?1) of templates (?$) are assumed to be
  132. # defined in headers and not required to be kept
  133. elif symbol.startswith('??0?$') or symbol.startswith('??1?$'):
  134. return None
  135. # An anonymous namespace is mangled as ?A(maybe hex number)@. Any symbol
  136. # that mentions an anonymous namespace can be discarded, as the anonymous
  137. # namespace doesn't exist outside of that translation unit.
  138. elif re.search('\?A(0x\w+)?@', symbol):
  139. return None
  140. # Keep mangled llvm:: and clang:: function symbols. How we detect these is a
  141. # bit of a mess and imprecise, but that avoids having to completely demangle
  142. # the symbol name. The outermost namespace is at the end of the identifier
  143. # mangling, and the identifier mangling is followed by the type mangling, so
  144. # we look for (llvm|clang)@@ followed by something that looks like a
  145. # function type mangling. To spot a function type we use (this is derived
  146. # from clang/lib/AST/MicrosoftMangle.cpp):
  147. # <function-type> ::= <function-class> <this-cvr-qualifiers>
  148. # <calling-convention> <return-type>
  149. # <argument-list> <throw-spec>
  150. # <function-class> ::= [A-Z]
  151. # <this-cvr-qualifiers> ::= [A-Z0-9_]*
  152. # <calling-convention> ::= [A-JQ]
  153. # <return-type> ::= .+
  154. # <argument-list> ::= X (void)
  155. # ::= .+@ (list of types)
  156. # ::= .*Z (list of types, varargs)
  157. # <throw-spec> ::= exceptions are not allowed
  158. elif re.search('(llvm|clang)@@[A-Z][A-Z0-9_]*[A-JQ].+(X|.+@|.*Z)$', symbol):
  159. return symbol
  160. return None
  161. # Itanium manglings are of the form _Z<identifier_mangling><type_mangling>. We
  162. # demangle the identifier mangling to identify symbols that can be safely
  163. # discarded.
  164. def should_keep_itanium_symbol(symbol, calling_convention_decoration):
  165. # Start by removing any calling convention decoration (which we expect to
  166. # see on all symbols, even mangled C++ symbols)
  167. if calling_convention_decoration and symbol.startswith('_'):
  168. symbol = symbol[1:]
  169. # Keep unmangled names
  170. if not symbol.startswith('_') and not symbol.startswith('.'):
  171. return symbol
  172. # Discard manglings that aren't nested names
  173. match = re.match('_Z(T[VTIS])?(N.+)', symbol)
  174. if not match:
  175. return None
  176. # Demangle the name. If the name is too complex then we don't need to keep
  177. # it, but it the demangling fails then keep the symbol just in case.
  178. try:
  179. names, _ = parse_itanium_nested_name(match.group(2))
  180. except TooComplexName:
  181. return None
  182. if not names:
  183. return symbol
  184. # Constructors and destructors of templates classes are assumed to be
  185. # defined in headers and not required to be kept
  186. if re.match('[CD][123]', names[-1][0]) and names[-2][1]:
  187. return None
  188. # Keep the instantiations of clang::Type::getAs, as some of them are
  189. # explipict specializations that are defined in clang's lib/AST/Type.cpp;
  190. # discard any other function template instantiations as it's assumed that
  191. # the definition is public
  192. elif symbol.startswith('_ZNK5clang4Type5getAs'):
  193. return symbol
  194. elif names[-1][1]:
  195. return None
  196. # Keep llvm:: and clang:: names
  197. elif names[0][0] == '4llvm' or names[0][0] == '5clang':
  198. return symbol
  199. # Discard everything else
  200. else:
  201. return None
  202. # Certain kinds of complex manglings we assume cannot be part of a public
  203. # interface, and we handle them by raising an exception.
  204. class TooComplexName(Exception):
  205. pass
  206. # Parse an itanium mangled name from the start of a string and return a
  207. # (name, rest of string) pair.
  208. def parse_itanium_name(arg):
  209. # Check for a normal name
  210. match = re.match('(\d+)(.+)', arg)
  211. if match:
  212. n = int(match.group(1))
  213. name = match.group(1)+match.group(2)[:n]
  214. rest = match.group(2)[n:]
  215. return name, rest
  216. # Check for constructor/destructor names
  217. match = re.match('([CD][123])(.+)', arg)
  218. if match:
  219. return match.group(1), match.group(2)
  220. # Assume that a sequence of characters that doesn't end a nesting is an
  221. # operator (this is very imprecise, but appears to be good enough)
  222. match = re.match('([^E]+)(.+)', arg)
  223. if match:
  224. return match.group(1), match.group(2)
  225. # Anything else: we can't handle it
  226. return None, arg
  227. # Parse an itanium mangled template argument list from the start of a string
  228. # and throw it away, returning the rest of the string.
  229. def skip_itanium_template(arg):
  230. # A template argument list starts with I
  231. assert arg.startswith('I'), arg
  232. tmp = arg[1:]
  233. while tmp:
  234. # Check for names
  235. match = re.match('(\d+)(.+)', tmp)
  236. if match:
  237. n = int(match.group(1))
  238. tmp = match.group(2)[n:]
  239. continue
  240. # Check for substitutions
  241. match = re.match('S[A-Z0-9]*_(.+)', tmp)
  242. if match:
  243. tmp = match.group(1)
  244. # Start of a template
  245. elif tmp.startswith('I'):
  246. tmp = skip_itanium_template(tmp)
  247. # Start of a nested name
  248. elif tmp.startswith('N'):
  249. _, tmp = parse_itanium_nested_name(tmp)
  250. # Start of an expression: assume that it's too complicated
  251. elif tmp.startswith('L') or tmp.startswith('X'):
  252. raise TooComplexName
  253. # End of the template
  254. elif tmp.startswith('E'):
  255. return tmp[1:]
  256. # Something else: probably a type, skip it
  257. else:
  258. tmp = tmp[1:]
  259. return None
  260. # Parse an itanium mangled nested name and transform it into a list of pairs of
  261. # (name, is_template), returning (list, rest of string).
  262. def parse_itanium_nested_name(arg):
  263. # A nested name starts with N
  264. assert arg.startswith('N'), arg
  265. ret = []
  266. # Skip past the N, and possibly a substitution
  267. match = re.match('NS[A-Z0-9]*_(.+)', arg)
  268. if match:
  269. tmp = match.group(1)
  270. else:
  271. tmp = arg[1:]
  272. # Skip past CV-qualifiers and ref qualifiers
  273. match = re.match('[rVKRO]*(.+)', tmp);
  274. if match:
  275. tmp = match.group(1)
  276. # Repeatedly parse names from the string until we reach the end of the
  277. # nested name
  278. while tmp:
  279. # An E ends the nested name
  280. if tmp.startswith('E'):
  281. return ret, tmp[1:]
  282. # Parse a name
  283. name_part, tmp = parse_itanium_name(tmp)
  284. if not name_part:
  285. # If we failed then we don't know how to demangle this
  286. return None, None
  287. is_template = False
  288. # If this name is a template record that, then skip the template
  289. # arguments
  290. if tmp.startswith('I'):
  291. tmp = skip_itanium_template(tmp)
  292. is_template = True
  293. # Add the name to the list
  294. ret.append((name_part, is_template))
  295. # If we get here then something went wrong
  296. return None, None
  297. def extract_symbols(arg):
  298. get_symbols, should_keep_symbol, calling_convention_decoration, lib = arg
  299. symbols = dict()
  300. for symbol in get_symbols(lib):
  301. symbol = should_keep_symbol(symbol, calling_convention_decoration)
  302. if symbol:
  303. symbols[symbol] = 1 + symbols.setdefault(symbol,0)
  304. return symbols
  305. if __name__ == '__main__':
  306. tool_exes = ['dumpbin','nm','objdump','llvm-readobj']
  307. parser = argparse.ArgumentParser(
  308. description='Extract symbols to export from libraries')
  309. parser.add_argument('--mangling', choices=['itanium','microsoft'],
  310. required=True, help='expected symbol mangling scheme')
  311. parser.add_argument('--tools', choices=tool_exes, nargs='*',
  312. help='tools to use to extract symbols and determine the'
  313. ' target')
  314. parser.add_argument('libs', metavar='lib', type=str, nargs='+',
  315. help='libraries to extract symbols from')
  316. parser.add_argument('-o', metavar='file', type=str, help='output to file')
  317. args = parser.parse_args()
  318. # Determine the function to use to get the list of symbols from the inputs,
  319. # and the function to use to determine if the target is 32-bit windows.
  320. tools = { 'dumpbin' : (dumpbin_get_symbols, dumpbin_is_32bit_windows),
  321. 'nm' : (nm_get_symbols, None),
  322. 'objdump' : (None, objdump_is_32bit_windows),
  323. 'llvm-readobj' : (readobj_get_symbols, readobj_is_32bit_windows) }
  324. get_symbols = None
  325. is_32bit_windows = None
  326. # If we have a tools argument then use that for the list of tools to check
  327. if args.tools:
  328. tool_exes = args.tools
  329. # Find a tool to use by trying each in turn until we find one that exists
  330. # (subprocess.call will throw OSError when the program does not exist)
  331. get_symbols = None
  332. for exe in tool_exes:
  333. try:
  334. # Close std streams as we don't want any output and we don't
  335. # want the process to wait for something on stdin.
  336. p = subprocess.Popen([exe], stdout=subprocess.PIPE,
  337. stderr=subprocess.PIPE,
  338. stdin=subprocess.PIPE,
  339. universal_newlines=True)
  340. p.stdout.close()
  341. p.stderr.close()
  342. p.stdin.close()
  343. p.wait()
  344. # Keep going until we have a tool to use for both get_symbols and
  345. # is_32bit_windows
  346. if not get_symbols:
  347. get_symbols = tools[exe][0]
  348. if not is_32bit_windows:
  349. is_32bit_windows = tools[exe][1]
  350. if get_symbols and is_32bit_windows:
  351. break
  352. except OSError:
  353. continue
  354. if not get_symbols:
  355. print("Couldn't find a program to read symbols with", file=sys.stderr)
  356. exit(1)
  357. if not is_32bit_windows:
  358. print("Couldn't find a program to determining the target", file=sys.stderr)
  359. exit(1)
  360. # How we determine which symbols to keep and which to discard depends on
  361. # the mangling scheme
  362. if args.mangling == 'microsoft':
  363. should_keep_symbol = should_keep_microsoft_symbol
  364. else:
  365. should_keep_symbol = should_keep_itanium_symbol
  366. # Get the list of libraries to extract symbols from
  367. libs = list()
  368. for lib in args.libs:
  369. # When invoked by cmake the arguments are the cmake target names of the
  370. # libraries, so we need to add .lib/.a to the end and maybe lib to the
  371. # start to get the filename. Also allow objects.
  372. suffixes = ['.lib','.a','.obj','.o']
  373. if not any([lib.endswith(s) for s in suffixes]):
  374. for s in suffixes:
  375. if os.path.exists(lib+s):
  376. lib = lib+s
  377. break
  378. if os.path.exists('lib'+lib+s):
  379. lib = 'lib'+lib+s
  380. break
  381. if not any([lib.endswith(s) for s in suffixes]):
  382. print("Don't know what to do with argument "+lib, file=sys.stderr)
  383. exit(1)
  384. libs.append(lib)
  385. # Check if calling convention decoration is used by inspecting the first
  386. # library in the list
  387. calling_convention_decoration = is_32bit_windows(libs[0])
  388. # Extract symbols from libraries in parallel. This is a huge time saver when
  389. # doing a debug build, as there are hundreds of thousands of symbols in each
  390. # library.
  391. pool = multiprocessing.Pool()
  392. try:
  393. # Only one argument can be passed to the mapping function, and we can't
  394. # use a lambda or local function definition as that doesn't work on
  395. # windows, so create a list of tuples which duplicates the arguments
  396. # that are the same in all calls.
  397. vals = [(get_symbols, should_keep_symbol, calling_convention_decoration, x) for x in libs]
  398. # Do an async map then wait for the result to make sure that
  399. # KeyboardInterrupt gets caught correctly (see
  400. # http://bugs.python.org/issue8296)
  401. result = pool.map_async(extract_symbols, vals)
  402. pool.close()
  403. libs_symbols = result.get(3600)
  404. except KeyboardInterrupt:
  405. # On Ctrl-C terminate everything and exit
  406. pool.terminate()
  407. pool.join()
  408. exit(1)
  409. # Merge everything into a single dict
  410. symbols = dict()
  411. for this_lib_symbols in libs_symbols:
  412. for k,v in list(this_lib_symbols.items()):
  413. symbols[k] = v + symbols.setdefault(k,0)
  414. # Count instances of member functions of template classes, and map the
  415. # symbol name to the function+class. We do this under the assumption that if
  416. # a member function of a template class is instantiated many times it's
  417. # probably declared in a public header file.
  418. template_function_count = dict()
  419. template_function_mapping = dict()
  420. template_function_count[""] = 0
  421. for k in symbols:
  422. name = None
  423. if args.mangling == 'microsoft':
  424. # Member functions of templates start with
  425. # ?<fn_name>@?$<class_name>@, so we map to <fn_name>@?$<class_name>.
  426. # As manglings go from the innermost scope to the outermost scope
  427. # this means:
  428. # * When we have a function member of a subclass of a template
  429. # class then <fn_name> will actually contain the mangling of
  430. # both the subclass and the function member. This is fine.
  431. # * When we have a function member of a template subclass of a
  432. # (possibly template) class then it's the innermost template
  433. # subclass that becomes <class_name>. This should be OK so long
  434. # as we don't have multiple classes with a template subclass of
  435. # the same name.
  436. match = re.search("^\?(\??\w+\@\?\$\w+)\@", k)
  437. if match:
  438. name = match.group(1)
  439. else:
  440. # Find member functions of templates by demangling the name and
  441. # checking if the second-to-last name in the list is a template.
  442. match = re.match('_Z(T[VTIS])?(N.+)', k)
  443. if match:
  444. try:
  445. names, _ = parse_itanium_nested_name(match.group(2))
  446. if names and names[-2][1]:
  447. name = ''.join([x for x,_ in names])
  448. except TooComplexName:
  449. # Manglings that are too complex should already have been
  450. # filtered out, but if we happen to somehow see one here
  451. # just leave it as-is.
  452. pass
  453. if name:
  454. old_count = template_function_count.setdefault(name,0)
  455. template_function_count[name] = old_count + 1
  456. template_function_mapping[k] = name
  457. else:
  458. template_function_mapping[k] = ""
  459. # Print symbols which both:
  460. # * Appear in exactly one input, as symbols defined in multiple
  461. # objects/libraries are assumed to have public definitions.
  462. # * Aren't instances of member functions of templates which have been
  463. # instantiated 100 times or more, which are assumed to have public
  464. # definitions. (100 is an arbitrary guess here.)
  465. if args.o:
  466. outfile = open(args.o,'w')
  467. else:
  468. outfile = sys.stdout
  469. for k,v in list(symbols.items()):
  470. template_count = template_function_count[template_function_mapping[k]]
  471. if v == 1 and template_count < 100:
  472. print(k, file=outfile)