gen_stub_libs.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2016 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. """Generates source for stub shared libraries for the NDK."""
  18. import argparse
  19. import json
  20. import logging
  21. import os
  22. import re
  23. import sys
  24. ALL_ARCHITECTURES = (
  25. 'arm',
  26. 'arm64',
  27. 'x86',
  28. 'x86_64',
  29. )
  30. # Arbitrary magic number. We use the same one in api-level.h for this purpose.
  31. FUTURE_API_LEVEL = 10000
  32. def logger():
  33. """Return the main logger for this module."""
  34. return logging.getLogger(__name__)
  35. def get_tags(line):
  36. """Returns a list of all tags on this line."""
  37. _, _, all_tags = line.strip().partition('#')
  38. return [e for e in re.split(r'\s+', all_tags) if e.strip()]
  39. def is_api_level_tag(tag):
  40. """Returns true if this tag has an API level that may need decoding."""
  41. if tag.startswith('introduced='):
  42. return True
  43. if tag.startswith('introduced-'):
  44. return True
  45. if tag.startswith('versioned='):
  46. return True
  47. return False
  48. def decode_api_level_tags(tags, api_map):
  49. """Decodes API level code names in a list of tags.
  50. Raises:
  51. ParseError: An unknown version name was found in a tag.
  52. """
  53. for idx, tag in enumerate(tags):
  54. if not is_api_level_tag(tag):
  55. continue
  56. name, value = split_tag(tag)
  57. try:
  58. decoded = str(decode_api_level(value, api_map))
  59. tags[idx] = '='.join([name, decoded])
  60. except KeyError:
  61. raise ParseError('Unknown version name in tag: {}'.format(tag))
  62. return tags
  63. def split_tag(tag):
  64. """Returns a key/value tuple of the tag.
  65. Raises:
  66. ValueError: Tag is not a key/value type tag.
  67. Returns: Tuple of (key, value) of the tag. Both components are strings.
  68. """
  69. if '=' not in tag:
  70. raise ValueError('Not a key/value tag: ' + tag)
  71. key, _, value = tag.partition('=')
  72. return key, value
  73. def get_tag_value(tag):
  74. """Returns the value of a key/value tag.
  75. Raises:
  76. ValueError: Tag is not a key/value type tag.
  77. Returns: Value part of tag as a string.
  78. """
  79. return split_tag(tag)[1]
  80. def version_is_private(version):
  81. """Returns True if the version name should be treated as private."""
  82. return version.endswith('_PRIVATE') or version.endswith('_PLATFORM')
  83. def should_omit_version(version, arch, api, llndk, apex):
  84. """Returns True if the version section should be ommitted.
  85. We want to omit any sections that do not have any symbols we'll have in the
  86. stub library. Sections that contain entirely future symbols or only symbols
  87. for certain architectures.
  88. """
  89. if version_is_private(version.name):
  90. return True
  91. if 'platform-only' in version.tags:
  92. return True
  93. no_llndk_no_apex = 'llndk' not in version.tags and 'apex' not in version.tags
  94. keep = no_llndk_no_apex or \
  95. ('llndk' in version.tags and llndk) or \
  96. ('apex' in version.tags and apex)
  97. if not keep:
  98. return True
  99. if not symbol_in_arch(version.tags, arch):
  100. return True
  101. if not symbol_in_api(version.tags, arch, api):
  102. return True
  103. return False
  104. def should_omit_symbol(symbol, arch, api, llndk, apex):
  105. """Returns True if the symbol should be omitted."""
  106. no_llndk_no_apex = 'llndk' not in symbol.tags and 'apex' not in symbol.tags
  107. keep = no_llndk_no_apex or \
  108. ('llndk' in symbol.tags and llndk) or \
  109. ('apex' in symbol.tags and apex)
  110. if not keep:
  111. return True
  112. if not symbol_in_arch(symbol.tags, arch):
  113. return True
  114. if not symbol_in_api(symbol.tags, arch, api):
  115. return True
  116. return False
  117. def symbol_in_arch(tags, arch):
  118. """Returns true if the symbol is present for the given architecture."""
  119. has_arch_tags = False
  120. for tag in tags:
  121. if tag == arch:
  122. return True
  123. if tag in ALL_ARCHITECTURES:
  124. has_arch_tags = True
  125. # If there were no arch tags, the symbol is available for all
  126. # architectures. If there were any arch tags, the symbol is only available
  127. # for the tagged architectures.
  128. return not has_arch_tags
  129. def symbol_in_api(tags, arch, api):
  130. """Returns true if the symbol is present for the given API level."""
  131. introduced_tag = None
  132. arch_specific = False
  133. for tag in tags:
  134. # If there is an arch-specific tag, it should override the common one.
  135. if tag.startswith('introduced=') and not arch_specific:
  136. introduced_tag = tag
  137. elif tag.startswith('introduced-' + arch + '='):
  138. introduced_tag = tag
  139. arch_specific = True
  140. elif tag == 'future':
  141. return api == FUTURE_API_LEVEL
  142. if introduced_tag is None:
  143. # We found no "introduced" tags, so the symbol has always been
  144. # available.
  145. return True
  146. return api >= int(get_tag_value(introduced_tag))
  147. def symbol_versioned_in_api(tags, api):
  148. """Returns true if the symbol should be versioned for the given API.
  149. This models the `versioned=API` tag. This should be a very uncommonly
  150. needed tag, and is really only needed to fix versioning mistakes that are
  151. already out in the wild.
  152. For example, some of libc's __aeabi_* functions were originally placed in
  153. the private version, but that was incorrect. They are now in LIBC_N, but
  154. when building against any version prior to N we need the symbol to be
  155. unversioned (otherwise it won't resolve on M where it is private).
  156. """
  157. for tag in tags:
  158. if tag.startswith('versioned='):
  159. return api >= int(get_tag_value(tag))
  160. # If there is no "versioned" tag, the tag has been versioned for as long as
  161. # it was introduced.
  162. return True
  163. class ParseError(RuntimeError):
  164. """An error that occurred while parsing a symbol file."""
  165. pass
  166. class MultiplyDefinedSymbolError(RuntimeError):
  167. """A symbol name was multiply defined."""
  168. def __init__(self, multiply_defined_symbols):
  169. super(MultiplyDefinedSymbolError, self).__init__(
  170. 'Version script contains multiple definitions for: {}'.format(
  171. ', '.join(multiply_defined_symbols)))
  172. self.multiply_defined_symbols = multiply_defined_symbols
  173. class Version(object):
  174. """A version block of a symbol file."""
  175. def __init__(self, name, base, tags, symbols):
  176. self.name = name
  177. self.base = base
  178. self.tags = tags
  179. self.symbols = symbols
  180. def __eq__(self, other):
  181. if self.name != other.name:
  182. return False
  183. if self.base != other.base:
  184. return False
  185. if self.tags != other.tags:
  186. return False
  187. if self.symbols != other.symbols:
  188. return False
  189. return True
  190. class Symbol(object):
  191. """A symbol definition from a symbol file."""
  192. def __init__(self, name, tags):
  193. self.name = name
  194. self.tags = tags
  195. def __eq__(self, other):
  196. return self.name == other.name and set(self.tags) == set(other.tags)
  197. class SymbolFileParser(object):
  198. """Parses NDK symbol files."""
  199. def __init__(self, input_file, api_map, arch, api, llndk, apex):
  200. self.input_file = input_file
  201. self.api_map = api_map
  202. self.arch = arch
  203. self.api = api
  204. self.llndk = llndk
  205. self.apex = apex
  206. self.current_line = None
  207. def parse(self):
  208. """Parses the symbol file and returns a list of Version objects."""
  209. versions = []
  210. while self.next_line() != '':
  211. if '{' in self.current_line:
  212. versions.append(self.parse_version())
  213. else:
  214. raise ParseError(
  215. 'Unexpected contents at top level: ' + self.current_line)
  216. self.check_no_duplicate_symbols(versions)
  217. return versions
  218. def check_no_duplicate_symbols(self, versions):
  219. """Raises errors for multiply defined symbols.
  220. This situation is the normal case when symbol versioning is actually
  221. used, but this script doesn't currently handle that. The error message
  222. will be a not necessarily obvious "error: redefition of 'foo'" from
  223. stub.c, so it's better for us to catch this situation and raise a
  224. better error.
  225. """
  226. symbol_names = set()
  227. multiply_defined_symbols = set()
  228. for version in versions:
  229. if should_omit_version(version, self.arch, self.api, self.llndk, self.apex):
  230. continue
  231. for symbol in version.symbols:
  232. if should_omit_symbol(symbol, self.arch, self.api, self.llndk, self.apex):
  233. continue
  234. if symbol.name in symbol_names:
  235. multiply_defined_symbols.add(symbol.name)
  236. symbol_names.add(symbol.name)
  237. if multiply_defined_symbols:
  238. raise MultiplyDefinedSymbolError(
  239. sorted(list(multiply_defined_symbols)))
  240. def parse_version(self):
  241. """Parses a single version section and returns a Version object."""
  242. name = self.current_line.split('{')[0].strip()
  243. tags = get_tags(self.current_line)
  244. tags = decode_api_level_tags(tags, self.api_map)
  245. symbols = []
  246. global_scope = True
  247. cpp_symbols = False
  248. while self.next_line() != '':
  249. if '}' in self.current_line:
  250. # Line is something like '} BASE; # tags'. Both base and tags
  251. # are optional here.
  252. base = self.current_line.partition('}')[2]
  253. base = base.partition('#')[0].strip()
  254. if not base.endswith(';'):
  255. raise ParseError(
  256. 'Unterminated version/export "C++" block (expected ;).')
  257. if cpp_symbols:
  258. cpp_symbols = False
  259. else:
  260. base = base.rstrip(';').rstrip()
  261. if base == '':
  262. base = None
  263. return Version(name, base, tags, symbols)
  264. elif 'extern "C++" {' in self.current_line:
  265. cpp_symbols = True
  266. elif not cpp_symbols and ':' in self.current_line:
  267. visibility = self.current_line.split(':')[0].strip()
  268. if visibility == 'local':
  269. global_scope = False
  270. elif visibility == 'global':
  271. global_scope = True
  272. else:
  273. raise ParseError('Unknown visiblity label: ' + visibility)
  274. elif global_scope and not cpp_symbols:
  275. symbols.append(self.parse_symbol())
  276. else:
  277. # We're in a hidden scope or in 'extern "C++"' block. Ignore
  278. # everything.
  279. pass
  280. raise ParseError('Unexpected EOF in version block.')
  281. def parse_symbol(self):
  282. """Parses a single symbol line and returns a Symbol object."""
  283. if ';' not in self.current_line:
  284. raise ParseError(
  285. 'Expected ; to terminate symbol: ' + self.current_line)
  286. if '*' in self.current_line:
  287. raise ParseError(
  288. 'Wildcard global symbols are not permitted.')
  289. # Line is now in the format "<symbol-name>; # tags"
  290. name, _, _ = self.current_line.strip().partition(';')
  291. tags = get_tags(self.current_line)
  292. tags = decode_api_level_tags(tags, self.api_map)
  293. return Symbol(name, tags)
  294. def next_line(self):
  295. """Returns the next non-empty non-comment line.
  296. A return value of '' indicates EOF.
  297. """
  298. line = self.input_file.readline()
  299. while line.strip() == '' or line.strip().startswith('#'):
  300. line = self.input_file.readline()
  301. # We want to skip empty lines, but '' indicates EOF.
  302. if line == '':
  303. break
  304. self.current_line = line
  305. return self.current_line
  306. class Generator(object):
  307. """Output generator that writes stub source files and version scripts."""
  308. def __init__(self, src_file, version_script, arch, api, llndk, apex):
  309. self.src_file = src_file
  310. self.version_script = version_script
  311. self.arch = arch
  312. self.api = api
  313. self.llndk = llndk
  314. self.apex = apex
  315. def write(self, versions):
  316. """Writes all symbol data to the output files."""
  317. for version in versions:
  318. self.write_version(version)
  319. def write_version(self, version):
  320. """Writes a single version block's data to the output files."""
  321. if should_omit_version(version, self.arch, self.api, self.llndk, self.apex):
  322. return
  323. section_versioned = symbol_versioned_in_api(version.tags, self.api)
  324. version_empty = True
  325. pruned_symbols = []
  326. for symbol in version.symbols:
  327. if should_omit_symbol(symbol, self.arch, self.api, self.llndk, self.apex):
  328. continue
  329. if symbol_versioned_in_api(symbol.tags, self.api):
  330. version_empty = False
  331. pruned_symbols.append(symbol)
  332. if len(pruned_symbols) > 0:
  333. if not version_empty and section_versioned:
  334. self.version_script.write(version.name + ' {\n')
  335. self.version_script.write(' global:\n')
  336. for symbol in pruned_symbols:
  337. emit_version = symbol_versioned_in_api(symbol.tags, self.api)
  338. if section_versioned and emit_version:
  339. self.version_script.write(' ' + symbol.name + ';\n')
  340. weak = ''
  341. if 'weak' in symbol.tags:
  342. weak = '__attribute__((weak)) '
  343. if 'var' in symbol.tags:
  344. self.src_file.write('{}int {} = 0;\n'.format(
  345. weak, symbol.name))
  346. else:
  347. self.src_file.write('{}void {}() {{}}\n'.format(
  348. weak, symbol.name))
  349. if not version_empty and section_versioned:
  350. base = '' if version.base is None else ' ' + version.base
  351. self.version_script.write('}' + base + ';\n')
  352. def decode_api_level(api, api_map):
  353. """Decodes the API level argument into the API level number.
  354. For the average case, this just decodes the integer value from the string,
  355. but for unreleased APIs we need to translate from the API codename (like
  356. "O") to the future API level for that codename.
  357. """
  358. try:
  359. return int(api)
  360. except ValueError:
  361. pass
  362. if api == "current":
  363. return FUTURE_API_LEVEL
  364. return api_map[api]
  365. def parse_args():
  366. """Parses and returns command line arguments."""
  367. parser = argparse.ArgumentParser()
  368. parser.add_argument('-v', '--verbose', action='count', default=0)
  369. parser.add_argument(
  370. '--api', required=True, help='API level being targeted.')
  371. parser.add_argument(
  372. '--arch', choices=ALL_ARCHITECTURES, required=True,
  373. help='Architecture being targeted.')
  374. parser.add_argument(
  375. '--llndk', action='store_true', help='Use the LLNDK variant.')
  376. parser.add_argument(
  377. '--apex', action='store_true', help='Use the APEX variant.')
  378. parser.add_argument(
  379. '--api-map', type=os.path.realpath, required=True,
  380. help='Path to the API level map JSON file.')
  381. parser.add_argument(
  382. 'symbol_file', type=os.path.realpath, help='Path to symbol file.')
  383. parser.add_argument(
  384. 'stub_src', type=os.path.realpath,
  385. help='Path to output stub source file.')
  386. parser.add_argument(
  387. 'version_script', type=os.path.realpath,
  388. help='Path to output version script.')
  389. return parser.parse_args()
  390. def main():
  391. """Program entry point."""
  392. args = parse_args()
  393. with open(args.api_map) as map_file:
  394. api_map = json.load(map_file)
  395. api = decode_api_level(args.api, api_map)
  396. verbose_map = (logging.WARNING, logging.INFO, logging.DEBUG)
  397. verbosity = args.verbose
  398. if verbosity > 2:
  399. verbosity = 2
  400. logging.basicConfig(level=verbose_map[verbosity])
  401. with open(args.symbol_file) as symbol_file:
  402. try:
  403. versions = SymbolFileParser(symbol_file, api_map, args.arch, api,
  404. args.llndk, args.apex).parse()
  405. except MultiplyDefinedSymbolError as ex:
  406. sys.exit('{}: error: {}'.format(args.symbol_file, ex))
  407. with open(args.stub_src, 'w') as src_file:
  408. with open(args.version_script, 'w') as version_file:
  409. generator = Generator(src_file, version_file, args.arch, api,
  410. args.llndk, args.apex)
  411. generator.write(versions)
  412. if __name__ == '__main__':
  413. main()