link_dyn_lib.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import sys
  2. import os
  3. import subprocess
  4. import tempfile
  5. import collections
  6. import optparse
  7. import pipes
  8. import thinlto_cache
  9. import link_exe
  10. from process_whole_archive_option import ProcessWholeArchiveOption
  11. from fix_py2_protobuf import fix_py2
  12. def shlex_join(cmd):
  13. # equivalent to shlex.join() in python 3
  14. return ' '.join(pipes.quote(part) for part in cmd)
  15. def parse_export_file(p):
  16. with open(p, 'r') as f:
  17. for l in f:
  18. l = l.strip()
  19. if l and '#' not in l:
  20. words = l.split()
  21. if len(words) == 2 and words[0] == 'linux_version':
  22. yield {'linux_version': words[1]}
  23. elif len(words) == 2:
  24. yield {'lang': words[0], 'sym': words[1]}
  25. elif len(words) == 1:
  26. yield {'lang': 'C', 'sym': words[0]}
  27. else:
  28. raise Exception('unsupported exports line: ' + l)
  29. def to_c(sym):
  30. symbols = collections.deque(sym.split('::'))
  31. c_prefixes = [ # demangle prefixes for c++ symbols
  32. '_ZN', # namespace
  33. '_ZTIN', # typeinfo for
  34. '_ZTSN', # typeinfo name for
  35. '_ZTTN', # VTT for
  36. '_ZTVN', # vtable for
  37. '_ZNK', # const methods
  38. ]
  39. c_sym = ''
  40. while symbols:
  41. s = symbols.popleft()
  42. if s == '*':
  43. c_sym += '*'
  44. break
  45. if '*' in s and len(s) > 1:
  46. raise Exception('Unsupported format, cannot guess length of symbol: ' + s)
  47. c_sym += str(len(s)) + s
  48. if symbols:
  49. raise Exception('Unsupported format: ' + sym)
  50. if c_sym[-1] != '*':
  51. c_sym += 'E*'
  52. return ['{prefix}{sym}'.format(prefix=prefix, sym=c_sym) for prefix in c_prefixes]
  53. def fix_darwin_param(ex):
  54. for item in ex:
  55. if item.get('linux_version'):
  56. continue
  57. if item['lang'] == 'C':
  58. yield '-Wl,-exported_symbol,_' + item['sym']
  59. elif item['lang'] == 'C++':
  60. for sym in to_c(item['sym']):
  61. yield '-Wl,-exported_symbol,_' + sym
  62. else:
  63. raise Exception('unsupported lang: ' + item['lang'])
  64. def fix_gnu_param(arch, ex):
  65. d = collections.defaultdict(list)
  66. version = None
  67. for item in ex:
  68. if item.get('linux_version'):
  69. if not version:
  70. version = item.get('linux_version')
  71. else:
  72. raise Exception('More than one linux_version defined')
  73. elif item['lang'] == 'C++':
  74. d['C'].extend(to_c(item['sym']))
  75. else:
  76. d[item['lang']].append(item['sym'])
  77. with tempfile.NamedTemporaryFile(mode='wt', delete=False) as f:
  78. if version:
  79. f.write('{} {{\nglobal:\n'.format(version))
  80. else:
  81. f.write('{\nglobal:\n')
  82. for k, v in d.items():
  83. f.write(' extern "' + k + '" {\n')
  84. for x in v:
  85. f.write(' ' + x + ';\n')
  86. f.write(' };\n')
  87. f.write('local: *;\n};\n')
  88. ret = ['-Wl,--version-script=' + f.name]
  89. if arch == 'ANDROID':
  90. ret += ['-Wl,--export-dynamic']
  91. return ret
  92. def fix_windows_param(ex):
  93. with tempfile.NamedTemporaryFile(delete=False) as def_file:
  94. exports = []
  95. for item in ex:
  96. if item.get('lang') == 'C':
  97. exports.append(item.get('sym'))
  98. def_file.write('EXPORTS\n')
  99. for export in exports:
  100. def_file.write(' {}\n'.format(export))
  101. return ['/DEF:{}'.format(def_file.name)]
  102. MUSL_LIBS = '-lc', '-lcrypt', '-ldl', '-lm', '-lpthread', '-lrt', '-lutil'
  103. CUDA_LIBRARIES = {
  104. '-lcublas_static': '-lcublas',
  105. '-lcublasLt_static': '-lcublasLt',
  106. '-lcudart_static': '-lcudart',
  107. '-lcudnn_static': '-lcudnn',
  108. '-lcufft_static_nocallback': '-lcufft',
  109. '-lcurand_static': '-lcurand',
  110. '-lcusolver_static': '-lcusolver',
  111. '-lcusparse_static': '-lcusparse',
  112. '-lmyelin_compiler_static': '-lmyelin',
  113. '-lmyelin_executor_static': '-lnvcaffe_parser',
  114. '-lmyelin_pattern_library_static': '',
  115. '-lmyelin_pattern_runtime_static': '',
  116. '-lnvinfer_static': '-lnvinfer',
  117. '-lnvinfer_plugin_static': '-lnvinfer_plugin',
  118. '-lnvonnxparser_static': '-lnvonnxparser',
  119. '-lnvparsers_static': '-lnvparsers',
  120. }
  121. def fix_cmd(arch, c):
  122. if arch == 'WINDOWS':
  123. prefix = '/DEF:'
  124. f = fix_windows_param
  125. else:
  126. prefix = '-Wl,--version-script='
  127. if arch in ('DARWIN', 'IOS', 'IOSSIM'):
  128. f = fix_darwin_param
  129. else:
  130. f = lambda x: fix_gnu_param(arch, x)
  131. def do_fix(p):
  132. if p.startswith(prefix) and p.endswith('.exports'):
  133. fname = p[len(prefix) :]
  134. return list(f(list(parse_export_file(fname))))
  135. if p.endswith('.supp'):
  136. return []
  137. if p.endswith('.pkg.fake'):
  138. return []
  139. return [p]
  140. return sum((do_fix(x) for x in c), [])
  141. def fix_cmd_for_musl(cmd):
  142. flags = []
  143. for flag in cmd:
  144. if flag not in MUSL_LIBS:
  145. flags.append(flag)
  146. return flags
  147. def fix_cmd_for_dynamic_cuda(cmd):
  148. flags = []
  149. for flag in cmd:
  150. if flag in CUDA_LIBRARIES:
  151. flags.append(CUDA_LIBRARIES[flag])
  152. else:
  153. flags.append(flag)
  154. return flags
  155. def fix_blas_resolving(cmd):
  156. # Intel mkl comes as a precompiled static library and thus can not be recompiled with sanitizer runtime instrumentation.
  157. # That's why we prefer to use cblas instead of Intel mkl as a drop-in replacement under sanitizers.
  158. # But if the library has dependencies on mkl and cblas simultaneously, it will get a linking error.
  159. # Hence we assume that it's probably compiling without sanitizers and we can easily remove cblas to prevent multiple definitions of the same symbol at link time.
  160. for arg in cmd:
  161. if arg.startswith('contrib/libs') and arg.endswith('mkl-lp64.a'):
  162. return [arg for arg in cmd if not arg.endswith('libcontrib-libs-cblas.a')]
  163. return cmd
  164. def parse_args():
  165. parser = optparse.OptionParser()
  166. parser.disable_interspersed_args()
  167. parser.add_option('--arch')
  168. parser.add_option('--target')
  169. parser.add_option('--soname')
  170. parser.add_option('--source-root')
  171. parser.add_option('--build-root')
  172. parser.add_option('--fix-elf')
  173. parser.add_option('--linker-output')
  174. parser.add_option('--musl', action='store_true')
  175. parser.add_option('--dynamic-cuda', action='store_true')
  176. parser.add_option('--cuda-architectures',
  177. help='List of supported CUDA architectures, separated by ":" (e.g. "sm_52:compute_70:lto_90a"')
  178. parser.add_option('--nvprune-exe')
  179. parser.add_option('--objcopy-exe')
  180. parser.add_option('--whole-archive-peers', action='append')
  181. parser.add_option('--whole-archive-libs', action='append')
  182. parser.add_option('--custom-step')
  183. parser.add_option('--python')
  184. thinlto_cache.add_options(parser)
  185. return parser.parse_args()
  186. if __name__ == '__main__':
  187. opts, args = parse_args()
  188. assert opts.arch
  189. assert opts.target
  190. cmd = fix_blas_resolving(args)
  191. cmd = fix_cmd(opts.arch, cmd)
  192. cmd = fix_py2(cmd)
  193. if opts.musl:
  194. cmd = fix_cmd_for_musl(cmd)
  195. if opts.dynamic_cuda:
  196. cmd = fix_cmd_for_dynamic_cuda(cmd)
  197. else:
  198. cuda_manager = link_exe.CUDAManager(opts.cuda_architectures, opts.nvprune_exe)
  199. cmd = link_exe.process_cuda_libraries_by_nvprune(cmd, cuda_manager, opts.build_root)
  200. cmd = link_exe.process_cuda_libraries_by_objcopy(cmd, opts.build_root, opts.objcopy_exe)
  201. cmd = ProcessWholeArchiveOption(opts.arch, opts.whole_archive_peers, opts.whole_archive_libs).construct_cmd(cmd)
  202. thinlto_cache.preprocess(opts, cmd)
  203. if opts.custom_step:
  204. assert opts.python
  205. subprocess.check_call([opts.python] + [opts.custom_step] + cmd)
  206. if opts.linker_output:
  207. stdout = open(opts.linker_output, 'w')
  208. else:
  209. stdout = sys.stdout
  210. proc = subprocess.Popen(cmd, shell=False, stderr=sys.stderr, stdout=stdout)
  211. proc.communicate()
  212. thinlto_cache.postprocess(opts)
  213. if proc.returncode:
  214. print >> sys.stderr, 'linker has failed with retcode:', proc.returncode
  215. print >> sys.stderr, 'linker command:', shlex_join(cmd)
  216. sys.exit(proc.returncode)
  217. if opts.fix_elf:
  218. cmd = [opts.fix_elf, opts.target]
  219. proc = subprocess.Popen(cmd, shell=False, stderr=sys.stderr, stdout=sys.stdout)
  220. proc.communicate()
  221. if proc.returncode:
  222. print >> sys.stderr, 'fix_elf has failed with retcode:', proc.returncode
  223. print >> sys.stderr, 'fix_elf command:', shlex_join(cmd)
  224. sys.exit(proc.returncode)
  225. if opts.soname and opts.soname != opts.target:
  226. if os.path.exists(opts.soname):
  227. os.unlink(opts.soname)
  228. os.link(opts.target, opts.soname)
  229. # -----------------Test---------------- #
  230. def write_temp_file(content):
  231. import yatest.common as yc
  232. filename = yc.output_path('test.exports')
  233. with open(filename, 'w') as f:
  234. f.write(content)
  235. return filename
  236. def test_fix_cmd_darwin():
  237. export_file_content = """
  238. C++ geobase5::details::lookup_impl::*
  239. C++ geobase5::hardcoded_service
  240. """
  241. filename = write_temp_file(export_file_content)
  242. args = ['-Wl,--version-script={}'.format(filename)]
  243. assert fix_cmd('DARWIN', args) == [
  244. '-Wl,-exported_symbol,__ZN8geobase57details11lookup_impl*',
  245. '-Wl,-exported_symbol,__ZTIN8geobase57details11lookup_impl*',
  246. '-Wl,-exported_symbol,__ZTSN8geobase57details11lookup_impl*',
  247. '-Wl,-exported_symbol,__ZTTN8geobase57details11lookup_impl*',
  248. '-Wl,-exported_symbol,__ZTVN8geobase57details11lookup_impl*',
  249. '-Wl,-exported_symbol,__ZNK8geobase57details11lookup_impl*',
  250. '-Wl,-exported_symbol,__ZN8geobase517hardcoded_serviceE*',
  251. '-Wl,-exported_symbol,__ZTIN8geobase517hardcoded_serviceE*',
  252. '-Wl,-exported_symbol,__ZTSN8geobase517hardcoded_serviceE*',
  253. '-Wl,-exported_symbol,__ZTTN8geobase517hardcoded_serviceE*',
  254. '-Wl,-exported_symbol,__ZTVN8geobase517hardcoded_serviceE*',
  255. '-Wl,-exported_symbol,__ZNK8geobase517hardcoded_serviceE*',
  256. ]
  257. def run_fix_gnu_param(export_file_content):
  258. filename = write_temp_file(export_file_content)
  259. result = fix_gnu_param('LINUX', list(parse_export_file(filename)))[0]
  260. version_script_path = result[len('-Wl,--version-script=') :]
  261. with open(version_script_path) as f:
  262. content = f.read()
  263. return content
  264. def test_fix_gnu_param():
  265. export_file_content = """
  266. C++ geobase5::details::lookup_impl::*
  267. C getFactoryMap
  268. """
  269. assert (
  270. run_fix_gnu_param(export_file_content)
  271. == """{
  272. global:
  273. extern "C" {
  274. _ZN8geobase57details11lookup_impl*;
  275. _ZTIN8geobase57details11lookup_impl*;
  276. _ZTSN8geobase57details11lookup_impl*;
  277. _ZTTN8geobase57details11lookup_impl*;
  278. _ZTVN8geobase57details11lookup_impl*;
  279. _ZNK8geobase57details11lookup_impl*;
  280. getFactoryMap;
  281. };
  282. local: *;
  283. };
  284. """
  285. )
  286. def test_fix_gnu_param_with_linux_version():
  287. export_file_content = """
  288. C++ geobase5::details::lookup_impl::*
  289. linux_version ver1.0
  290. C getFactoryMap
  291. """
  292. assert (
  293. run_fix_gnu_param(export_file_content)
  294. == """ver1.0 {
  295. global:
  296. extern "C" {
  297. _ZN8geobase57details11lookup_impl*;
  298. _ZTIN8geobase57details11lookup_impl*;
  299. _ZTSN8geobase57details11lookup_impl*;
  300. _ZTTN8geobase57details11lookup_impl*;
  301. _ZTVN8geobase57details11lookup_impl*;
  302. _ZNK8geobase57details11lookup_impl*;
  303. getFactoryMap;
  304. };
  305. local: *;
  306. };
  307. """
  308. )