blob: 58079aa5d9b0a84f4ad73de4a08a91c1afe2afb7 [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 Parkd044bb42024-05-15 02:09:54 +090065 help=('specify if the app wants to use embedded native libraries. Must not conflict '
66 'if already declared in the manifest.'))
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 Parkd044bb42024-05-15 02:09:54 +0900302 elif attr.value != value:
Colin Crosse4246ab2019-02-05 21:55:21 -0800303 raise RuntimeError('existing attribute extractNativeLibs="%s" conflicts with --extract-native-libs="%s"' %
304 (attr.value, value))
305
306
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700307def set_has_code_to_false(doc):
308 manifest = parse_manifest(doc)
309 elems = get_children_with_tag(manifest, 'application')
310 application = elems[0] if len(elems) == 1 else None
311 if len(elems) > 1:
312 raise RuntimeError('found multiple <application> tags')
313 elif not elems:
314 application = doc.createElement('application')
315 indent = get_indent(manifest.firstChild, 1)
316 first = manifest.firstChild
317 manifest.insertBefore(doc.createTextNode(indent), first)
318 manifest.insertBefore(application, first)
319
320 attr = application.getAttributeNodeNS(android_ns, 'hasCode')
321 if attr is not None:
322 # Do nothing if the application already has a hasCode attribute.
323 return
324 attr = doc.createAttributeNS(android_ns, 'android:hasCode')
325 attr.value = 'false'
326 application.setAttributeNode(attr)
327
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000328def set_test_only_flag_to_true(doc):
329 manifest = parse_manifest(doc)
330 elems = get_children_with_tag(manifest, 'application')
331 application = elems[0] if len(elems) == 1 else None
332 if len(elems) > 1:
333 raise RuntimeError('found multiple <application> tags')
334 elif not elems:
335 application = doc.createElement('application')
336 indent = get_indent(manifest.firstChild, 1)
337 first = manifest.firstChild
338 manifest.insertBefore(doc.createTextNode(indent), first)
339 manifest.insertBefore(application, first)
340
341 attr = application.getAttributeNodeNS(android_ns, 'testOnly')
342 if attr is not None:
343 # Do nothing If the application already has a testOnly attribute.
344 return
345 attr = doc.createAttributeNS(android_ns, 'android:testOnly')
346 attr.value = 'true'
347 application.setAttributeNode(attr)
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700348
William Loh5a082f92022-05-17 20:21:50 +0000349def set_max_sdk_version(doc, max_sdk_version):
350 """Replace the maxSdkVersion attribute value for permission and
351 uses-permission tags if the value was originally set to 'current'.
352 Used for cts test cases where the maxSdkVersion should equal to
353 Build.SDK_INT.
354
355 Args:
356 doc: The XML document. May be modified by this function.
357 max_sdk_version: The requested maxSdkVersion attribute.
358 """
359 manifest = parse_manifest(doc)
360 for tag in ['permission', 'uses-permission']:
361 children = get_children_with_tag(manifest, tag)
362 for child in children:
363 max_attr = child.getAttributeNodeNS(android_ns, 'maxSdkVersion')
364 if max_attr and max_attr.value == 'current':
365 max_attr.value = max_sdk_version
366
Alexei Nicoara69cf0f32022-07-27 14:59:18 +0100367def override_placeholder_version(doc, new_version):
368 """Replace the versionCode attribute value if it\'s currently
369 set to the placeholder version of 0.
370
371 Args:
372 doc: The XML document. May be modified by this function.
373 new_version: The new version to set if versionCode is equal to 0.
374 """
375 manifest = parse_manifest(doc)
376 version = manifest.getAttribute("android:versionCode")
377 if (version == '0'):
378 manifest.setAttribute("android:versionCode", new_version)
379
Colin Cross8bb10e82018-06-07 16:46:02 -0700380def main():
381 """Program entry point."""
382 try:
383 args = parse_args()
384
385 doc = minidom.parse(args.input)
386
387 ensure_manifest_android_ns(doc)
388
Colin Cross7b59e7b2018-09-10 13:35:13 -0700389 if args.raise_min_sdk_version:
390 raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
Colin Cross8bb10e82018-06-07 16:46:02 -0700391
William Loh5a082f92022-05-17 20:21:50 +0000392 if args.max_sdk_version:
393 set_max_sdk_version(doc, args.max_sdk_version)
394
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900395 if args.uses_libraries:
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900396 add_uses_libraries(doc, args.uses_libraries, True)
397
398 if args.optional_uses_libraries:
399 add_uses_libraries(doc, args.optional_uses_libraries, False)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900400
David Brazdild5b74992018-08-28 12:41:01 +0100401 if args.uses_non_sdk_api:
402 add_uses_non_sdk_api(doc)
403
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800404 if args.logging_parent:
405 add_logging_parent(doc, args.logging_parent)
406
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800407 if args.use_embedded_dex:
408 add_use_embedded_dex(doc)
Victor Hsiehce7818e2018-10-22 11:16:25 -0700409
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700410 if args.has_no_code:
411 set_has_code_to_false(doc)
412
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000413 if args.test_only:
414 set_test_only_flag_to_true(doc)
415
Colin Crosse4246ab2019-02-05 21:55:21 -0800416 if args.extract_native_libs is not None:
417 add_extract_native_libs(doc, args.extract_native_libs)
418
Alexei Nicoara69cf0f32022-07-27 14:59:18 +0100419 if args.new_version:
420 override_placeholder_version(doc, args.new_version)
421
Cole Faustc41dd722021-11-09 15:08:26 -0800422 with open(args.output, 'w') as f:
Colin Cross8bb10e82018-06-07 16:46:02 -0700423 write_xml(f, doc)
424
425 # pylint: disable=broad-except
426 except Exception as err:
427 print('error: ' + str(err), file=sys.stderr)
428 sys.exit(-1)
429
430if __name__ == '__main__':
431 main()