link_dyn_lib.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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(
  12. pipes.quote(part)
  13. for part in cmd
  14. )
  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. def fix_cmd(arch, musl, c):
  104. if arch == 'WINDOWS':
  105. prefix = '/DEF:'
  106. f = fix_windows_param
  107. else:
  108. prefix = '-Wl,--version-script='
  109. if arch in ('DARWIN', 'IOS'):
  110. f = fix_darwin_param
  111. else:
  112. f = lambda x: fix_gnu_param(arch, x)
  113. def do_fix(p):
  114. if musl and p in musl_libs:
  115. return []
  116. if p.startswith(prefix) and p.endswith('.exports'):
  117. fname = p[len(prefix):]
  118. return list(f(list(parse_export_file(fname))))
  119. if p.endswith('.supp'):
  120. return []
  121. if p.endswith('.pkg.fake'):
  122. return []
  123. return [p]
  124. return sum((do_fix(x) for x in c), [])
  125. def parse_args():
  126. parser = optparse.OptionParser()
  127. parser.disable_interspersed_args()
  128. parser.add_option('--arch')
  129. parser.add_option('--target')
  130. parser.add_option('--soname')
  131. parser.add_option('--fix-elf')
  132. parser.add_option('--linker-output')
  133. parser.add_option('--musl', action='store_true')
  134. parser.add_option('--whole-archive-peers', action='append')
  135. parser.add_option('--whole-archive-libs', action='append')
  136. return parser.parse_args()
  137. if __name__ == '__main__':
  138. opts, args = parse_args()
  139. assert opts.arch
  140. assert opts.target
  141. cmd = fix_cmd(opts.arch, opts.musl, args)
  142. cmd = ProcessWholeArchiveOption(opts.arch, opts.whole_archive_peers, opts.whole_archive_libs).construct_cmd(cmd)
  143. if opts.linker_output:
  144. stdout = open(opts.linker_output, 'w')
  145. else:
  146. stdout = sys.stdout
  147. proc = subprocess.Popen(cmd, shell=False, stderr=sys.stderr, stdout=stdout)
  148. proc.communicate()
  149. if proc.returncode:
  150. print >>sys.stderr, 'linker has failed with retcode:', proc.returncode
  151. print >>sys.stderr, 'linker command:', shlex_join(cmd)
  152. sys.exit(proc.returncode)
  153. if opts.fix_elf:
  154. cmd = [opts.fix_elf, opts.target]
  155. proc = subprocess.Popen(cmd, shell=False, stderr=sys.stderr, stdout=sys.stdout)
  156. proc.communicate()
  157. if proc.returncode:
  158. print >>sys.stderr, 'fix_elf has failed with retcode:', proc.returncode
  159. print >>sys.stderr, 'fix_elf command:', shlex_join(cmd)
  160. sys.exit(proc.returncode)
  161. if opts.soname and opts.soname != opts.target:
  162. if os.path.exists(opts.soname):
  163. os.unlink(opts.soname)
  164. os.link(opts.target, opts.soname)
  165. # -----------------Test---------------- #
  166. def write_temp_file(content):
  167. import yatest.common as yc
  168. filename = yc.output_path('test.exports')
  169. with open(filename, 'w') as f:
  170. f.write(content)
  171. return filename
  172. def test_fix_cmd_darwin():
  173. export_file_content = """
  174. C++ geobase5::details::lookup_impl::*
  175. C++ geobase5::hardcoded_service
  176. """
  177. filename = write_temp_file(export_file_content)
  178. args = ['-Wl,--version-script={}'.format(filename)]
  179. assert fix_cmd('DARWIN', False, args) == [
  180. '-Wl,-exported_symbol,__ZN8geobase57details11lookup_impl*',
  181. '-Wl,-exported_symbol,__ZTIN8geobase57details11lookup_impl*',
  182. '-Wl,-exported_symbol,__ZTSN8geobase57details11lookup_impl*',
  183. '-Wl,-exported_symbol,__ZTTN8geobase57details11lookup_impl*',
  184. '-Wl,-exported_symbol,__ZTVN8geobase57details11lookup_impl*',
  185. '-Wl,-exported_symbol,__ZNK8geobase57details11lookup_impl*',
  186. '-Wl,-exported_symbol,__ZN8geobase517hardcoded_serviceE*',
  187. '-Wl,-exported_symbol,__ZTIN8geobase517hardcoded_serviceE*',
  188. '-Wl,-exported_symbol,__ZTSN8geobase517hardcoded_serviceE*',
  189. '-Wl,-exported_symbol,__ZTTN8geobase517hardcoded_serviceE*',
  190. '-Wl,-exported_symbol,__ZTVN8geobase517hardcoded_serviceE*',
  191. '-Wl,-exported_symbol,__ZNK8geobase517hardcoded_serviceE*',
  192. ]
  193. def run_fix_gnu_param(export_file_content):
  194. filename = write_temp_file(export_file_content)
  195. result = fix_gnu_param('LINUX', list(parse_export_file(filename)))[0]
  196. version_script_path = result[len('-Wl,--version-script='):]
  197. with open(version_script_path) as f:
  198. content = f.read()
  199. return content
  200. def test_fix_gnu_param():
  201. export_file_content = """
  202. C++ geobase5::details::lookup_impl::*
  203. C getFactoryMap
  204. """
  205. assert run_fix_gnu_param(export_file_content) == """{
  206. global:
  207. extern "C" {
  208. _ZN8geobase57details11lookup_impl*;
  209. _ZTIN8geobase57details11lookup_impl*;
  210. _ZTSN8geobase57details11lookup_impl*;
  211. _ZTTN8geobase57details11lookup_impl*;
  212. _ZTVN8geobase57details11lookup_impl*;
  213. _ZNK8geobase57details11lookup_impl*;
  214. getFactoryMap;
  215. };
  216. local: *;
  217. };
  218. """
  219. def test_fix_gnu_param_with_linux_version():
  220. export_file_content = """
  221. C++ geobase5::details::lookup_impl::*
  222. linux_version ver1.0
  223. C getFactoryMap
  224. """
  225. assert run_fix_gnu_param(export_file_content) == """ver1.0 {
  226. global:
  227. extern "C" {
  228. _ZN8geobase57details11lookup_impl*;
  229. _ZTIN8geobase57details11lookup_impl*;
  230. _ZTSN8geobase57details11lookup_impl*;
  231. _ZTTN8geobase57details11lookup_impl*;
  232. _ZTVN8geobase57details11lookup_impl*;
  233. _ZNK8geobase57details11lookup_impl*;
  234. getFactoryMap;
  235. };
  236. local: *;
  237. };
  238. """