link_dyn_lib.py 12 KB

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