manifest_fixer.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2018 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. """A tool for inserting values from the build system into a manifest."""
  18. from __future__ import print_function
  19. import argparse
  20. import sys
  21. from xml.dom import minidom
  22. from manifest import android_ns
  23. from manifest import compare_version_gt
  24. from manifest import ensure_manifest_android_ns
  25. from manifest import find_child_with_attribute
  26. from manifest import get_children_with_tag
  27. from manifest import get_indent
  28. from manifest import parse_manifest
  29. from manifest import write_xml
  30. def parse_args():
  31. """Parse commandline arguments."""
  32. parser = argparse.ArgumentParser()
  33. parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
  34. help='specify minSdkVersion used by the build system')
  35. parser.add_argument('--replaceMaxSdkVersionPlaceholder', default='', dest='max_sdk_version',
  36. help='specify maxSdkVersion used by the build system')
  37. parser.add_argument('--targetSdkVersion', default='', dest='target_sdk_version',
  38. help='specify targetSdkVersion used by the build system')
  39. parser.add_argument('--raise-min-sdk-version', dest='raise_min_sdk_version', action='store_true',
  40. help='raise the minimum sdk version in the manifest if necessary')
  41. parser.add_argument('--library', dest='library', action='store_true',
  42. help='manifest is for a static library')
  43. parser.add_argument('--uses-library', dest='uses_libraries', action='append',
  44. help='specify additional <uses-library> tag to add. android:requred is set to true')
  45. parser.add_argument('--optional-uses-library', dest='optional_uses_libraries', action='append',
  46. help='specify additional <uses-library> tag to add. android:requred is set to false')
  47. parser.add_argument('--uses-non-sdk-api', dest='uses_non_sdk_api', action='store_true',
  48. help='manifest is for a package built against the platform')
  49. parser.add_argument('--logging-parent', dest='logging_parent', default='',
  50. help=('specify logging parent as an additional <meta-data> tag. '
  51. 'This value is ignored if the logging_parent meta-data tag is present.'))
  52. parser.add_argument('--use-embedded-dex', dest='use_embedded_dex', action='store_true',
  53. help=('specify if the app wants to use embedded dex and avoid extracted,'
  54. 'locally compiled code. Must not conflict if already declared '
  55. 'in the manifest.'))
  56. parser.add_argument('--extract-native-libs', dest='extract_native_libs',
  57. default=None, type=lambda x: (str(x).lower() == 'true'),
  58. help=('specify if the app wants to use embedded native libraries. Must not conflict '
  59. 'if already declared in the manifest.'))
  60. parser.add_argument('--has-no-code', dest='has_no_code', action='store_true',
  61. help=('adds hasCode="false" attribute to application. Ignored if application elem '
  62. 'already has a hasCode attribute.'))
  63. parser.add_argument('--test-only', dest='test_only', action='store_true',
  64. help=('adds testOnly="true" attribute to application. Assign true value if application elem '
  65. 'already has a testOnly attribute.'))
  66. parser.add_argument('--override-placeholder-version', dest='new_version',
  67. help='Overrides the versionCode if it\'s set to the placeholder value of 0')
  68. parser.add_argument('input', help='input AndroidManifest.xml file')
  69. parser.add_argument('output', help='output AndroidManifest.xml file')
  70. return parser.parse_args()
  71. def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
  72. """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
  73. Args:
  74. doc: The XML document. May be modified by this function.
  75. min_sdk_version: The requested minSdkVersion attribute.
  76. target_sdk_version: The requested targetSdkVersion attribute.
  77. library: True if the manifest is for a library.
  78. Raises:
  79. RuntimeError: invalid manifest
  80. """
  81. manifest = parse_manifest(doc)
  82. # Get or insert the uses-sdk element
  83. uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
  84. if len(uses_sdk) > 1:
  85. raise RuntimeError('found multiple uses-sdk elements')
  86. elif len(uses_sdk) == 1:
  87. element = uses_sdk[0]
  88. else:
  89. element = doc.createElement('uses-sdk')
  90. indent = get_indent(manifest.firstChild, 1)
  91. manifest.insertBefore(element, manifest.firstChild)
  92. # Insert an indent before uses-sdk to line it up with the indentation of the
  93. # other children of the <manifest> tag.
  94. manifest.insertBefore(doc.createTextNode(indent), manifest.firstChild)
  95. # Get or insert the minSdkVersion attribute. If it is already present, make
  96. # sure it as least the requested value.
  97. min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
  98. if min_attr is None:
  99. min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
  100. min_attr.value = min_sdk_version
  101. element.setAttributeNode(min_attr)
  102. else:
  103. if compare_version_gt(min_sdk_version, min_attr.value):
  104. min_attr.value = min_sdk_version
  105. # Insert the targetSdkVersion attribute if it is missing. If it is already
  106. # present leave it as is.
  107. target_attr = element.getAttributeNodeNS(android_ns, 'targetSdkVersion')
  108. if target_attr is None:
  109. target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
  110. if library:
  111. # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but
  112. # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it
  113. # is empty. Set it to something low so that it will be overriden by the
  114. # main manifest, but high enough that it doesn't cause implicit
  115. # permissions grants.
  116. target_attr.value = '16'
  117. else:
  118. target_attr.value = target_sdk_version
  119. element.setAttributeNode(target_attr)
  120. def add_logging_parent(doc, logging_parent_value):
  121. """Add logging parent as an additional <meta-data> tag.
  122. Args:
  123. doc: The XML document. May be modified by this function.
  124. logging_parent_value: A string representing the logging
  125. parent value.
  126. Raises:
  127. RuntimeError: Invalid manifest
  128. """
  129. manifest = parse_manifest(doc)
  130. logging_parent_key = 'android.content.pm.LOGGING_PARENT'
  131. elems = get_children_with_tag(manifest, 'application')
  132. application = elems[0] if len(elems) == 1 else None
  133. if len(elems) > 1:
  134. raise RuntimeError('found multiple <application> tags')
  135. elif not elems:
  136. application = doc.createElement('application')
  137. indent = get_indent(manifest.firstChild, 1)
  138. first = manifest.firstChild
  139. manifest.insertBefore(doc.createTextNode(indent), first)
  140. manifest.insertBefore(application, first)
  141. indent = get_indent(application.firstChild, 2)
  142. last = application.lastChild
  143. if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
  144. last = None
  145. if not find_child_with_attribute(application, 'meta-data', android_ns,
  146. 'name', logging_parent_key):
  147. ul = doc.createElement('meta-data')
  148. ul.setAttributeNS(android_ns, 'android:name', logging_parent_key)
  149. ul.setAttributeNS(android_ns, 'android:value', logging_parent_value)
  150. application.insertBefore(doc.createTextNode(indent), last)
  151. application.insertBefore(ul, last)
  152. last = application.lastChild
  153. # align the closing tag with the opening tag if it's not
  154. # indented
  155. if last and last.nodeType != minidom.Node.TEXT_NODE:
  156. indent = get_indent(application.previousSibling, 1)
  157. application.appendChild(doc.createTextNode(indent))
  158. def add_uses_libraries(doc, new_uses_libraries, required):
  159. """Add additional <uses-library> tags
  160. Args:
  161. doc: The XML document. May be modified by this function.
  162. new_uses_libraries: The names of libraries to be added by this function.
  163. required: The value of android:required attribute. Can be true or false.
  164. Raises:
  165. RuntimeError: Invalid manifest
  166. """
  167. manifest = parse_manifest(doc)
  168. elems = get_children_with_tag(manifest, 'application')
  169. application = elems[0] if len(elems) == 1 else None
  170. if len(elems) > 1:
  171. raise RuntimeError('found multiple <application> tags')
  172. elif not elems:
  173. application = doc.createElement('application')
  174. indent = get_indent(manifest.firstChild, 1)
  175. first = manifest.firstChild
  176. manifest.insertBefore(doc.createTextNode(indent), first)
  177. manifest.insertBefore(application, first)
  178. indent = get_indent(application.firstChild, 2)
  179. last = application.lastChild
  180. if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
  181. last = None
  182. for name in new_uses_libraries:
  183. if find_child_with_attribute(application, 'uses-library', android_ns,
  184. 'name', name) is not None:
  185. # If the uses-library tag of the same 'name' attribute value exists,
  186. # respect it.
  187. continue
  188. ul = doc.createElement('uses-library')
  189. ul.setAttributeNS(android_ns, 'android:name', name)
  190. ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
  191. application.insertBefore(doc.createTextNode(indent), last)
  192. application.insertBefore(ul, last)
  193. # align the closing tag with the opening tag if it's not
  194. # indented
  195. if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
  196. indent = get_indent(application.previousSibling, 1)
  197. application.appendChild(doc.createTextNode(indent))
  198. def add_uses_non_sdk_api(doc):
  199. """Add android:usesNonSdkApi=true attribute to <application>.
  200. Args:
  201. doc: The XML document. May be modified by this function.
  202. Raises:
  203. RuntimeError: Invalid manifest
  204. """
  205. manifest = parse_manifest(doc)
  206. elems = get_children_with_tag(manifest, 'application')
  207. application = elems[0] if len(elems) == 1 else None
  208. if len(elems) > 1:
  209. raise RuntimeError('found multiple <application> tags')
  210. elif not elems:
  211. application = doc.createElement('application')
  212. indent = get_indent(manifest.firstChild, 1)
  213. first = manifest.firstChild
  214. manifest.insertBefore(doc.createTextNode(indent), first)
  215. manifest.insertBefore(application, first)
  216. attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
  217. if attr is None:
  218. attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
  219. attr.value = 'true'
  220. application.setAttributeNode(attr)
  221. def add_use_embedded_dex(doc):
  222. manifest = parse_manifest(doc)
  223. elems = get_children_with_tag(manifest, 'application')
  224. application = elems[0] if len(elems) == 1 else None
  225. if len(elems) > 1:
  226. raise RuntimeError('found multiple <application> tags')
  227. elif not elems:
  228. application = doc.createElement('application')
  229. indent = get_indent(manifest.firstChild, 1)
  230. first = manifest.firstChild
  231. manifest.insertBefore(doc.createTextNode(indent), first)
  232. manifest.insertBefore(application, first)
  233. attr = application.getAttributeNodeNS(android_ns, 'useEmbeddedDex')
  234. if attr is None:
  235. attr = doc.createAttributeNS(android_ns, 'android:useEmbeddedDex')
  236. attr.value = 'true'
  237. application.setAttributeNode(attr)
  238. elif attr.value != 'true':
  239. raise RuntimeError('existing attribute mismatches the option of --use-embedded-dex')
  240. def add_extract_native_libs(doc, extract_native_libs):
  241. manifest = parse_manifest(doc)
  242. elems = get_children_with_tag(manifest, 'application')
  243. application = elems[0] if len(elems) == 1 else None
  244. if len(elems) > 1:
  245. raise RuntimeError('found multiple <application> tags')
  246. elif not elems:
  247. application = doc.createElement('application')
  248. indent = get_indent(manifest.firstChild, 1)
  249. first = manifest.firstChild
  250. manifest.insertBefore(doc.createTextNode(indent), first)
  251. manifest.insertBefore(application, first)
  252. value = str(extract_native_libs).lower()
  253. attr = application.getAttributeNodeNS(android_ns, 'extractNativeLibs')
  254. if attr is None:
  255. attr = doc.createAttributeNS(android_ns, 'android:extractNativeLibs')
  256. attr.value = value
  257. application.setAttributeNode(attr)
  258. elif attr.value != value:
  259. raise RuntimeError('existing attribute extractNativeLibs="%s" conflicts with --extract-native-libs="%s"' %
  260. (attr.value, value))
  261. def set_has_code_to_false(doc):
  262. manifest = parse_manifest(doc)
  263. elems = get_children_with_tag(manifest, 'application')
  264. application = elems[0] if len(elems) == 1 else None
  265. if len(elems) > 1:
  266. raise RuntimeError('found multiple <application> tags')
  267. elif not elems:
  268. application = doc.createElement('application')
  269. indent = get_indent(manifest.firstChild, 1)
  270. first = manifest.firstChild
  271. manifest.insertBefore(doc.createTextNode(indent), first)
  272. manifest.insertBefore(application, first)
  273. attr = application.getAttributeNodeNS(android_ns, 'hasCode')
  274. if attr is not None:
  275. # Do nothing if the application already has a hasCode attribute.
  276. return
  277. attr = doc.createAttributeNS(android_ns, 'android:hasCode')
  278. attr.value = 'false'
  279. application.setAttributeNode(attr)
  280. def set_test_only_flag_to_true(doc):
  281. manifest = parse_manifest(doc)
  282. elems = get_children_with_tag(manifest, 'application')
  283. application = elems[0] if len(elems) == 1 else None
  284. if len(elems) > 1:
  285. raise RuntimeError('found multiple <application> tags')
  286. elif not elems:
  287. application = doc.createElement('application')
  288. indent = get_indent(manifest.firstChild, 1)
  289. first = manifest.firstChild
  290. manifest.insertBefore(doc.createTextNode(indent), first)
  291. manifest.insertBefore(application, first)
  292. attr = application.getAttributeNodeNS(android_ns, 'testOnly')
  293. if attr is not None:
  294. # Do nothing If the application already has a testOnly attribute.
  295. return
  296. attr = doc.createAttributeNS(android_ns, 'android:testOnly')
  297. attr.value = 'true'
  298. application.setAttributeNode(attr)
  299. def set_max_sdk_version(doc, max_sdk_version):
  300. """Replace the maxSdkVersion attribute value for permission and
  301. uses-permission tags if the value was originally set to 'current'.
  302. Used for cts test cases where the maxSdkVersion should equal to
  303. Build.SDK_INT.
  304. Args:
  305. doc: The XML document. May be modified by this function.
  306. max_sdk_version: The requested maxSdkVersion attribute.
  307. """
  308. manifest = parse_manifest(doc)
  309. for tag in ['permission', 'uses-permission']:
  310. children = get_children_with_tag(manifest, tag)
  311. for child in children:
  312. max_attr = child.getAttributeNodeNS(android_ns, 'maxSdkVersion')
  313. if max_attr and max_attr.value == 'current':
  314. max_attr.value = max_sdk_version
  315. def override_placeholder_version(doc, new_version):
  316. """Replace the versionCode attribute value if it\'s currently
  317. set to the placeholder version of 0.
  318. Args:
  319. doc: The XML document. May be modified by this function.
  320. new_version: The new version to set if versionCode is equal to 0.
  321. """
  322. manifest = parse_manifest(doc)
  323. version = manifest.getAttribute("android:versionCode")
  324. if (version == '0'):
  325. manifest.setAttribute("android:versionCode", new_version)
  326. def main():
  327. """Program entry point."""
  328. try:
  329. args = parse_args()
  330. doc = minidom.parse(args.input)
  331. ensure_manifest_android_ns(doc)
  332. if args.raise_min_sdk_version:
  333. raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
  334. if args.max_sdk_version:
  335. set_max_sdk_version(doc, args.max_sdk_version)
  336. if args.uses_libraries:
  337. add_uses_libraries(doc, args.uses_libraries, True)
  338. if args.optional_uses_libraries:
  339. add_uses_libraries(doc, args.optional_uses_libraries, False)
  340. if args.uses_non_sdk_api:
  341. add_uses_non_sdk_api(doc)
  342. if args.logging_parent:
  343. add_logging_parent(doc, args.logging_parent)
  344. if args.use_embedded_dex:
  345. add_use_embedded_dex(doc)
  346. if args.has_no_code:
  347. set_has_code_to_false(doc)
  348. if args.test_only:
  349. set_test_only_flag_to_true(doc)
  350. if args.extract_native_libs is not None:
  351. add_extract_native_libs(doc, args.extract_native_libs)
  352. if args.new_version:
  353. override_placeholder_version(doc, args.new_version)
  354. with open(args.output, 'w') as f:
  355. write_xml(f, doc)
  356. # pylint: disable=broad-except
  357. except Exception as err:
  358. print('error: ' + str(err), file=sys.stderr)
  359. sys.exit(-1)
  360. if __name__ == '__main__':
  361. main()