link_dyn_lib.py 11 KB

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