link_dyn_lib.py 12 KB

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