blob: 35d2a1c819b6d4e8bad4465ba439873242d30121 [file] [log] [blame]
Colin Cross8bb10e82018-06-07 16:46:02 -07001#!/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
19from __future__ import print_function
Colin Cross72119102019-05-20 13:14:18 -070020
Colin Cross8bb10e82018-06-07 16:46:02 -070021import argparse
22import sys
23from xml.dom import minidom
24
25
Colin Cross72119102019-05-20 13:14:18 -070026from manifest import android_ns
27from manifest import compare_version_gt
28from manifest import ensure_manifest_android_ns
29from manifest import find_child_with_attribute
30from manifest import get_children_with_tag
31from manifest import get_indent
32from manifest import parse_manifest
33from manifest import write_xml
Jiyong Parkc08f46f2018-06-18 11:01:00 +090034
35
Colin Cross8bb10e82018-06-07 16:46:02 -070036def parse_args():
37 """Parse commandline arguments."""
38
39 parser = argparse.ArgumentParser()
40 parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
41 help='specify minSdkVersion used by the build system')
William Loh5a082f92022-05-17 20:21:50 +000042 parser.add_argument('--replaceMaxSdkVersionPlaceholder', default='', dest='max_sdk_version',
43 help='specify maxSdkVersion used by the build system')
Colin Cross7b59e7b2018-09-10 13:35:13 -070044 parser.add_argument('--targetSdkVersion', default='', dest='target_sdk_version',
45 help='specify targetSdkVersion used by the build system')
46 parser.add_argument('--raise-min-sdk-version', dest='raise_min_sdk_version', action='store_true',
47 help='raise the minimum sdk version in the manifest if necessary')
Colin Cross1b6a3cf2018-07-24 14:51:30 -070048 parser.add_argument('--library', dest='library', action='store_true',
49 help='manifest is for a static library')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090050 parser.add_argument('--uses-library', dest='uses_libraries', action='append',
Jiyong Parkfa17afe2018-10-16 11:00:04 +090051 help='specify additional <uses-library> tag to add. android:requred is set to true')
52 parser.add_argument('--optional-uses-library', dest='optional_uses_libraries', action='append',
53 help='specify additional <uses-library> tag to add. android:requred is set to false')
David Brazdild5b74992018-08-28 12:41:01 +010054 parser.add_argument('--uses-non-sdk-api', dest='uses_non_sdk_api', action='store_true',
55 help='manifest is for a package built against the platform')
Baligh Uddin5b16dfb2020-02-11 17:27:19 -080056 parser.add_argument('--logging-parent', dest='logging_parent', default='',
57 help=('specify logging parent as an additional <meta-data> tag. '
58 'This value is ignored if the logging_parent meta-data tag is present.'))
Victor Hsiehd181c8b2019-01-29 13:00:33 -080059 parser.add_argument('--use-embedded-dex', dest='use_embedded_dex', action='store_true',
60 help=('specify if the app wants to use embedded dex and avoid extracted,'
Colin Crosse4246ab2019-02-05 21:55:21 -080061 'locally compiled code. Must not conflict if already declared '
Victor Hsiehd181c8b2019-01-29 13:00:33 -080062 'in the manifest.'))
Colin Crosse4246ab2019-02-05 21:55:21 -080063 parser.add_argument('--extract-native-libs', dest='extract_native_libs',
64 default=None, type=lambda x: (str(x).lower() == 'true'),
Jiyong Park20df11e2024-05-08 09:54:22 +000065 help=('specify if the app wants to use embedded native libraries. Must not '
66 'be true if manifest says false.'))
Jaewoong Jungc27ab662019-05-30 15:51:14 -070067 parser.add_argument('--has-no-code', dest='has_no_code', action='store_true',
68 help=('adds hasCode="false" attribute to application. Ignored if application elem '
69 'already has a hasCode attribute.'))
Gurpreet Singh75d65f32022-01-24 17:44:05 +000070 parser.add_argument('--test-only', dest='test_only', action='store_true',
71 help=('adds testOnly="true" attribute to application. Assign true value if application elem '
72 'already has a testOnly attribute.'))
Alexei Nicoara69cf0f32022-07-27 14:59:18 +010073 parser.add_argument('--override-placeholder-version', dest='new_version',
74 help='Overrides the versionCode if it\'s set to the placeholder value of 0')
Colin Cross8bb10e82018-06-07 16:46:02 -070075 parser.add_argument('input', help='input AndroidManifest.xml file')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090076 parser.add_argument('output', help='output AndroidManifest.xml file')
Colin Cross8bb10e82018-06-07 16:46:02 -070077 return parser.parse_args()
78
79
Colin Cross7b59e7b2018-09-10 13:35:13 -070080def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
Colin Cross8bb10e82018-06-07 16:46:02 -070081 """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
82
83 Args:
84 doc: The XML document. May be modified by this function.
Colin Cross7b59e7b2018-09-10 13:35:13 -070085 min_sdk_version: The requested minSdkVersion attribute.
86 target_sdk_version: The requested targetSdkVersion attribute.
Colin Cross72119102019-05-20 13:14:18 -070087 library: True if the manifest is for a library.
Colin Cross8bb10e82018-06-07 16:46:02 -070088 Raises:
89 RuntimeError: invalid manifest
90 """
91
92 manifest = parse_manifest(doc)
93
94 # Get or insert the uses-sdk element
95 uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
96 if len(uses_sdk) > 1:
97 raise RuntimeError('found multiple uses-sdk elements')
98 elif len(uses_sdk) == 1:
99 element = uses_sdk[0]
100 else:
101 element = doc.createElement('uses-sdk')
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900102 indent = get_indent(manifest.firstChild, 1)
Colin Cross8bb10e82018-06-07 16:46:02 -0700103 manifest.insertBefore(element, manifest.firstChild)
104
105 # Insert an indent before uses-sdk to line it up with the indentation of the
106 # other children of the <manifest> tag.
107 manifest.insertBefore(doc.createTextNode(indent), manifest.firstChild)
108
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700109 # Get or insert the minSdkVersion attribute. If it is already present, make
110 # sure it as least the requested value.
Colin Cross8bb10e82018-06-07 16:46:02 -0700111 min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
112 if min_attr is None:
113 min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
Colin Cross7b59e7b2018-09-10 13:35:13 -0700114 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700115 element.setAttributeNode(min_attr)
116 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700117 if compare_version_gt(min_sdk_version, min_attr.value):
118 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700119
120 # Insert the targetSdkVersion attribute if it is missing. If it is already
121 # present leave it as is.
122 target_attr = element.getAttributeNodeNS(android_ns, 'targetSdkVersion')
123 if target_attr is None:
124 target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
125 if library:
Colin Cross4b176062018-10-01 15:15:51 -0700126 # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but
127 # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it
128 # is empty. Set it to something low so that it will be overriden by the
129 # main manifest, but high enough that it doesn't cause implicit
130 # permissions grants.
Andrew Wheeler18dcd042021-01-12 21:02:03 -0600131 target_attr.value = '16'
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700132 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700133 target_attr.value = target_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700134 element.setAttributeNode(target_attr)
Colin Cross8bb10e82018-06-07 16:46:02 -0700135
136
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800137def add_logging_parent(doc, logging_parent_value):
138 """Add logging parent as an additional <meta-data> tag.
139
140 Args:
141 doc: The XML document. May be modified by this function.
142 logging_parent_value: A string representing the logging
143 parent value.
144 Raises:
145 RuntimeError: Invalid manifest
146 """
147 manifest = parse_manifest(doc)
148
149 logging_parent_key = 'android.content.pm.LOGGING_PARENT'
150 elems = get_children_with_tag(manifest, 'application')
151 application = elems[0] if len(elems) == 1 else None
152 if len(elems) > 1:
153 raise RuntimeError('found multiple <application> tags')
154 elif not elems:
155 application = doc.createElement('application')
156 indent = get_indent(manifest.firstChild, 1)
157 first = manifest.firstChild
158 manifest.insertBefore(doc.createTextNode(indent), first)
159 manifest.insertBefore(application, first)
160
161 indent = get_indent(application.firstChild, 2)
162
163 last = application.lastChild
164 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
165 last = None
166
167 if not find_child_with_attribute(application, 'meta-data', android_ns,
168 'name', logging_parent_key):
169 ul = doc.createElement('meta-data')
170 ul.setAttributeNS(android_ns, 'android:name', logging_parent_key)
171 ul.setAttributeNS(android_ns, 'android:value', logging_parent_value)
172 application.insertBefore(doc.createTextNode(indent), last)
173 application.insertBefore(ul, last)
174 last = application.lastChild
175
176 # align the closing tag with the opening tag if it's not
177 # indented
178 if last and last.nodeType != minidom.Node.TEXT_NODE:
179 indent = get_indent(application.previousSibling, 1)
180 application.appendChild(doc.createTextNode(indent))
181
182
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900183def add_uses_libraries(doc, new_uses_libraries, required):
184 """Add additional <uses-library> tags
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900185
186 Args:
187 doc: The XML document. May be modified by this function.
188 new_uses_libraries: The names of libraries to be added by this function.
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900189 required: The value of android:required attribute. Can be true or false.
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900190 Raises:
191 RuntimeError: Invalid manifest
192 """
193
194 manifest = parse_manifest(doc)
195 elems = get_children_with_tag(manifest, 'application')
196 application = elems[0] if len(elems) == 1 else None
197 if len(elems) > 1:
198 raise RuntimeError('found multiple <application> tags')
199 elif not elems:
200 application = doc.createElement('application')
201 indent = get_indent(manifest.firstChild, 1)
202 first = manifest.firstChild
203 manifest.insertBefore(doc.createTextNode(indent), first)
204 manifest.insertBefore(application, first)
205
206 indent = get_indent(application.firstChild, 2)
207
208 last = application.lastChild
209 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
210 last = None
211
212 for name in new_uses_libraries:
213 if find_child_with_attribute(application, 'uses-library', android_ns,
214 'name', name) is not None:
215 # If the uses-library tag of the same 'name' attribute value exists,
216 # respect it.
217 continue
218
219 ul = doc.createElement('uses-library')
220 ul.setAttributeNS(android_ns, 'android:name', name)
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900221 ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900222
223 application.insertBefore(doc.createTextNode(indent), last)
224 application.insertBefore(ul, last)
225
226 # align the closing tag with the opening tag if it's not
227 # indented
228 if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
229 indent = get_indent(application.previousSibling, 1)
230 application.appendChild(doc.createTextNode(indent))
231
Colin Cross72119102019-05-20 13:14:18 -0700232
David Brazdild5b74992018-08-28 12:41:01 +0100233def add_uses_non_sdk_api(doc):
234 """Add android:usesNonSdkApi=true attribute to <application>.
235
236 Args:
237 doc: The XML document. May be modified by this function.
238 Raises:
239 RuntimeError: Invalid manifest
240 """
241
242 manifest = parse_manifest(doc)
243 elems = get_children_with_tag(manifest, 'application')
244 application = elems[0] if len(elems) == 1 else None
245 if len(elems) > 1:
246 raise RuntimeError('found multiple <application> tags')
247 elif not elems:
248 application = doc.createElement('application')
249 indent = get_indent(manifest.firstChild, 1)
250 first = manifest.firstChild
251 manifest.insertBefore(doc.createTextNode(indent), first)
252 manifest.insertBefore(application, first)
253
254 attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
255 if attr is None:
256 attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
257 attr.value = 'true'
258 application.setAttributeNode(attr)
259
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900260
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800261def add_use_embedded_dex(doc):
Victor Hsiehce7818e2018-10-22 11:16:25 -0700262 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
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800274 attr = application.getAttributeNodeNS(android_ns, 'useEmbeddedDex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700275 if attr is None:
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800276 attr = doc.createAttributeNS(android_ns, 'android:useEmbeddedDex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700277 attr.value = 'true'
278 application.setAttributeNode(attr)
279 elif attr.value != 'true':
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800280 raise RuntimeError('existing attribute mismatches the option of --use-embedded-dex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700281
282
Colin Crosse4246ab2019-02-05 21:55:21 -0800283def add_extract_native_libs(doc, extract_native_libs):
284 manifest = parse_manifest(doc)
285 elems = get_children_with_tag(manifest, 'application')
286 application = elems[0] if len(elems) == 1 else None
287 if len(elems) > 1:
288 raise RuntimeError('found multiple <application> tags')
289 elif not elems:
290 application = doc.createElement('application')
291 indent = get_indent(manifest.firstChild, 1)
292 first = manifest.firstChild
293 manifest.insertBefore(doc.createTextNode(indent), first)
294 manifest.insertBefore(application, first)
295
296 value = str(extract_native_libs).lower()
297 attr = application.getAttributeNodeNS(android_ns, 'extractNativeLibs')
298 if attr is None:
299 attr = doc.createAttributeNS(android_ns, 'android:extractNativeLibs')
300 attr.value = value
301 application.setAttributeNode(attr)
Jiyong Park20df11e2024-05-08 09:54:22 +0000302 elif attr.value == "false" and value == "true":
303 # Note that we don't disallow the case of extractNativeLibs="true" in manifest and
304 # --extract-native-libs="false". This is fine because --extract-native-libs="false" means that
305 # the build system didn't compress the JNI libs, which is a fine choice for built-in apps. At
306 # runtime the JNI libs will be extracted to outside of the APK, but everything will still work
307 # okay.
308 #
309 # The opposite (extractNativeLibs="false" && --extract-native-libs="true") should however be
310 # disallowed because otherwise that would make an ill-formed APK; JNI libs are stored compressed
311 # but they won't be extracted. There's no way to execute the JNI libs.
Colin Crosse4246ab2019-02-05 21:55:21 -0800312 raise RuntimeError('existing attribute extractNativeLibs="%s" conflicts with --extract-native-libs="%s"' %
313 (attr.value, value))
314
315
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700316def set_has_code_to_false(doc):
317 manifest = parse_manifest(doc)
318 elems = get_children_with_tag(manifest, 'application')
319 application = elems[0] if len(elems) == 1 else None
320 if len(elems) > 1:
321 raise RuntimeError('found multiple <application> tags')
322 elif not elems:
323 application = doc.createElement('application')
324 indent = get_indent(manifest.firstChild, 1)
325 first = manifest.firstChild
326 manifest.insertBefore(doc.createTextNode(indent), first)
327 manifest.insertBefore(application, first)
328
329 attr = application.getAttributeNodeNS(android_ns, 'hasCode')
330 if attr is not None:
331 # Do nothing if the application already has a hasCode attribute.
332 return
333 attr = doc.createAttributeNS(android_ns, 'android:hasCode')
334 attr.value = 'false'
335 application.setAttributeNode(attr)
336
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000337def set_test_only_flag_to_true(doc):
338 manifest = parse_manifest(doc)
339 elems = get_children_with_tag(manifest, 'application')
340 application = elems[0] if len(elems) == 1 else None
341 if len(elems) > 1:
342 raise RuntimeError('found multiple <application> tags')
343 elif not elems:
344 application = doc.createElement('application')
345 indent = get_indent(manifest.firstChild, 1)
346 first = manifest.firstChild
347 manifest.insertBefore(doc.createTextNode(indent), first)
348 manifest.insertBefore(application, first)
349
350 attr = application.getAttributeNodeNS(android_ns, 'testOnly')
351 if attr is not None:
352 # Do nothing If the application already has a testOnly attribute.
353 return
354 attr = doc.createAttributeNS(android_ns, 'android:testOnly')
355 attr.value = 'true'
356 application.setAttributeNode(attr)
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700357
William Loh5a082f92022-05-17 20:21:50 +0000358def set_max_sdk_version(doc, max_sdk_version):
359 """Replace the maxSdkVersion attribute value for permission and
360 uses-permission tags if the value was originally set to 'current'.
361 Used for cts test cases where the maxSdkVersion should equal to
362 Build.SDK_INT.
363
364 Args:
365 doc: The XML document. May be modified by this function.
366 max_sdk_version: The requested maxSdkVersion attribute.
367 """
368 manifest = parse_manifest(doc)
369 for tag in ['permission', 'uses-permission']:
370 children = get_children_with_tag(manifest, tag)
371 for child in children:
372 max_attr = child.getAttributeNodeNS(android_ns, 'maxSdkVersion')
373 if max_attr and max_attr.value == 'current':
374 max_attr.value = max_sdk_version
375
Alexei Nicoara69cf0f32022-07-27 14:59:18 +0100376def override_placeholder_version(doc, new_version):
377 """Replace the versionCode attribute value if it\'s currently
378 set to the placeholder version of 0.
379
380 Args:
381 doc: The XML document. May be modified by this function.
382 new_version: The new version to set if versionCode is equal to 0.
383 """
384 manifest = parse_manifest(doc)
385 version = manifest.getAttribute("android:versionCode")
386 if (version == '0'):
387 manifest.setAttribute("android:versionCode", new_version)
388
Colin Cross8bb10e82018-06-07 16:46:02 -0700389def main():
390 """Program entry point."""
391 try:
392 args = parse_args()
393
394 doc = minidom.parse(args.input)
395
396 ensure_manifest_android_ns(doc)
397
Colin Cross7b59e7b2018-09-10 13:35:13 -0700398 if args.raise_min_sdk_version:
399 raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
Colin Cross8bb10e82018-06-07 16:46:02 -0700400
William Loh5a082f92022-05-17 20:21:50 +0000401 if args.max_sdk_version:
402 set_max_sdk_version(doc, args.max_sdk_version)
403
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900404 if args.uses_libraries:
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900405 add_uses_libraries(doc, args.uses_libraries, True)
406
407 if args.optional_uses_libraries:
408 add_uses_libraries(doc, args.optional_uses_libraries, False)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900409
David Brazdild5b74992018-08-28 12:41:01 +0100410 if args.uses_non_sdk_api:
411 add_uses_non_sdk_api(doc)
412
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800413 if args.logging_parent:
414 add_logging_parent(doc, args.logging_parent)
415
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800416 if args.use_embedded_dex:
417 add_use_embedded_dex(doc)
Victor Hsiehce7818e2018-10-22 11:16:25 -0700418
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700419 if args.has_no_code:
420 set_has_code_to_false(doc)
421
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000422 if args.test_only:
423 set_test_only_flag_to_true(doc)
424
Colin Crosse4246ab2019-02-05 21:55:21 -0800425 if args.extract_native_libs is not None:
426 add_extract_native_libs(doc, args.extract_native_libs)
427
Alexei Nicoara69cf0f32022-07-27 14:59:18 +0100428 if args.new_version:
429 override_placeholder_version(doc, args.new_version)
430
Cole Faustc41dd722021-11-09 15:08:26 -0800431 with open(args.output, 'w') as f:
Colin Cross8bb10e82018-06-07 16:46:02 -0700432 write_xml(f, doc)
433
434 # pylint: disable=broad-except
435 except Exception as err:
436 print('error: ' + str(err), file=sys.stderr)
437 sys.exit(-1)
438
439if __name__ == '__main__':
440 main()