link_dyn_lib.py 11 KB

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