blob: 2da29ee9112e0c0298ae99573a25caa645650f66 [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'),
65 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.'))
Colin Cross8bb10e82018-06-07 16:46:02 -070073 parser.add_argument('input', help='input AndroidManifest.xml file')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090074 parser.add_argument('output', help='output AndroidManifest.xml file')
Colin Cross8bb10e82018-06-07 16:46:02 -070075 return parser.parse_args()
76
77
Colin Cross7b59e7b2018-09-10 13:35:13 -070078def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
Colin Cross8bb10e82018-06-07 16:46:02 -070079 """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
80
81 Args:
82 doc: The XML document. May be modified by this function.
Colin Cross7b59e7b2018-09-10 13:35:13 -070083 min_sdk_version: The requested minSdkVersion attribute.
84 target_sdk_version: The requested targetSdkVersion attribute.
Colin Cross72119102019-05-20 13:14:18 -070085 library: True if the manifest is for a library.
Colin Cross8bb10e82018-06-07 16:46:02 -070086 Raises:
87 RuntimeError: invalid manifest
88 """
89
90 manifest = parse_manifest(doc)
91
92 # Get or insert the uses-sdk element
93 uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
94 if len(uses_sdk) > 1:
95 raise RuntimeError('found multiple uses-sdk elements')
96 elif len(uses_sdk) == 1:
97 element = uses_sdk[0]
98 else:
99 element = doc.createElement('uses-sdk')
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900100 indent = get_indent(manifest.firstChild, 1)
Colin Cross8bb10e82018-06-07 16:46:02 -0700101 manifest.insertBefore(element, manifest.firstChild)
102
103 # Insert an indent before uses-sdk to line it up with the indentation of the
104 # other children of the <manifest> tag.
105 manifest.insertBefore(doc.createTextNode(indent), manifest.firstChild)
106
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700107 # Get or insert the minSdkVersion attribute. If it is already present, make
108 # sure it as least the requested value.
Colin Cross8bb10e82018-06-07 16:46:02 -0700109 min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
110 if min_attr is None:
111 min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
Colin Cross7b59e7b2018-09-10 13:35:13 -0700112 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700113 element.setAttributeNode(min_attr)
114 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700115 if compare_version_gt(min_sdk_version, min_attr.value):
116 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700117
118 # Insert the targetSdkVersion attribute if it is missing. If it is already
119 # present leave it as is.
120 target_attr = element.getAttributeNodeNS(android_ns, 'targetSdkVersion')
121 if target_attr is None:
122 target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
123 if library:
Colin Cross4b176062018-10-01 15:15:51 -0700124 # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but
125 # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it
126 # is empty. Set it to something low so that it will be overriden by the
127 # main manifest, but high enough that it doesn't cause implicit
128 # permissions grants.
Andrew Wheeler18dcd042021-01-12 21:02:03 -0600129 target_attr.value = '16'
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700130 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700131 target_attr.value = target_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700132 element.setAttributeNode(target_attr)
Colin Cross8bb10e82018-06-07 16:46:02 -0700133
134
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800135def add_logging_parent(doc, logging_parent_value):
136 """Add logging parent as an additional <meta-data> tag.
137
138 Args:
139 doc: The XML document. May be modified by this function.
140 logging_parent_value: A string representing the logging
141 parent value.
142 Raises:
143 RuntimeError: Invalid manifest
144 """
145 manifest = parse_manifest(doc)
146
147 logging_parent_key = 'android.content.pm.LOGGING_PARENT'
148 elems = get_children_with_tag(manifest, 'application')
149 application = elems[0] if len(elems) == 1 else None
150 if len(elems) > 1:
151 raise RuntimeError('found multiple <application> tags')
152 elif not elems:
153 application = doc.createElement('application')
154 indent = get_indent(manifest.firstChild, 1)
155 first = manifest.firstChild
156 manifest.insertBefore(doc.createTextNode(indent), first)
157 manifest.insertBefore(application, first)
158
159 indent = get_indent(application.firstChild, 2)
160
161 last = application.lastChild
162 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
163 last = None
164
165 if not find_child_with_attribute(application, 'meta-data', android_ns,
166 'name', logging_parent_key):
167 ul = doc.createElement('meta-data')
168 ul.setAttributeNS(android_ns, 'android:name', logging_parent_key)
169 ul.setAttributeNS(android_ns, 'android:value', logging_parent_value)
170 application.insertBefore(doc.createTextNode(indent), last)
171 application.insertBefore(ul, last)
172 last = application.lastChild
173
174 # align the closing tag with the opening tag if it's not
175 # indented
176 if last and last.nodeType != minidom.Node.TEXT_NODE:
177 indent = get_indent(application.previousSibling, 1)
178 application.appendChild(doc.createTextNode(indent))
179
180
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900181def add_uses_libraries(doc, new_uses_libraries, required):
182 """Add additional <uses-library> tags
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900183
184 Args:
185 doc: The XML document. May be modified by this function.
186 new_uses_libraries: The names of libraries to be added by this function.
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900187 required: The value of android:required attribute. Can be true or false.
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900188 Raises:
189 RuntimeError: Invalid manifest
190 """
191
192 manifest = parse_manifest(doc)
193 elems = get_children_with_tag(manifest, 'application')
194 application = elems[0] if len(elems) == 1 else None
195 if len(elems) > 1:
196 raise RuntimeError('found multiple <application> tags')
197 elif not elems:
198 application = doc.createElement('application')
199 indent = get_indent(manifest.firstChild, 1)
200 first = manifest.firstChild
201 manifest.insertBefore(doc.createTextNode(indent), first)
202 manifest.insertBefore(application, first)
203
204 indent = get_indent(application.firstChild, 2)
205
206 last = application.lastChild
207 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
208 last = None
209
210 for name in new_uses_libraries:
211 if find_child_with_attribute(application, 'uses-library', android_ns,
212 'name', name) is not None:
213 # If the uses-library tag of the same 'name' attribute value exists,
214 # respect it.
215 continue
216
217 ul = doc.createElement('uses-library')
218 ul.setAttributeNS(android_ns, 'android:name', name)
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900219 ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900220
221 application.insertBefore(doc.createTextNode(indent), last)
222 application.insertBefore(ul, last)
223
224 # align the closing tag with the opening tag if it's not
225 # indented
226 if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
227 indent = get_indent(application.previousSibling, 1)
228 application.appendChild(doc.createTextNode(indent))
229
Colin Cross72119102019-05-20 13:14:18 -0700230
David Brazdild5b74992018-08-28 12:41:01 +0100231def add_uses_non_sdk_api(doc):
232 """Add android:usesNonSdkApi=true attribute to <application>.
233
234 Args:
235 doc: The XML document. May be modified by this function.
236 Raises:
237 RuntimeError: Invalid manifest
238 """
239
240 manifest = parse_manifest(doc)
241 elems = get_children_with_tag(manifest, 'application')
242 application = elems[0] if len(elems) == 1 else None
243 if len(elems) > 1:
244 raise RuntimeError('found multiple <application> tags')
245 elif not elems:
246 application = doc.createElement('application')
247 indent = get_indent(manifest.firstChild, 1)
248 first = manifest.firstChild
249 manifest.insertBefore(doc.createTextNode(indent), first)
250 manifest.insertBefore(application, first)
251
252 attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
253 if attr is None:
254 attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
255 attr.value = 'true'
256 application.setAttributeNode(attr)
257
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900258
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800259def add_use_embedded_dex(doc):
Victor Hsiehce7818e2018-10-22 11:16:25 -0700260 manifest = parse_manifest(doc)
261 elems = get_children_with_tag(manifest, 'application')
262 application = elems[0] if len(elems) == 1 else None
263 if len(elems) > 1:
264 raise RuntimeError('found multiple <application> tags')
265 elif not elems:
266 application = doc.createElement('application')
267 indent = get_indent(manifest.firstChild, 1)
268 first = manifest.firstChild
269 manifest.insertBefore(doc.createTextNode(indent), first)
270 manifest.insertBefore(application, first)
271
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800272 attr = application.getAttributeNodeNS(android_ns, 'useEmbeddedDex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700273 if attr is None:
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800274 attr = doc.createAttributeNS(android_ns, 'android:useEmbeddedDex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700275 attr.value = 'true'
276 application.setAttributeNode(attr)
277 elif attr.value != 'true':
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800278 raise RuntimeError('existing attribute mismatches the option of --use-embedded-dex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700279
280
Colin Crosse4246ab2019-02-05 21:55:21 -0800281def add_extract_native_libs(doc, extract_native_libs):
282 manifest = parse_manifest(doc)
283 elems = get_children_with_tag(manifest, 'application')
284 application = elems[0] if len(elems) == 1 else None
285 if len(elems) > 1:
286 raise RuntimeError('found multiple <application> tags')
287 elif not elems:
288 application = doc.createElement('application')
289 indent = get_indent(manifest.firstChild, 1)
290 first = manifest.firstChild
291 manifest.insertBefore(doc.createTextNode(indent), first)
292 manifest.insertBefore(application, first)
293
294 value = str(extract_native_libs).lower()
295 attr = application.getAttributeNodeNS(android_ns, 'extractNativeLibs')
296 if attr is None:
297 attr = doc.createAttributeNS(android_ns, 'android:extractNativeLibs')
298 attr.value = value
299 application.setAttributeNode(attr)
300 elif attr.value != value:
301 raise RuntimeError('existing attribute extractNativeLibs="%s" conflicts with --extract-native-libs="%s"' %
302 (attr.value, value))
303
304
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700305def set_has_code_to_false(doc):
306 manifest = parse_manifest(doc)
307 elems = get_children_with_tag(manifest, 'application')
308 application = elems[0] if len(elems) == 1 else None
309 if len(elems) > 1:
310 raise RuntimeError('found multiple <application> tags')
311 elif not elems:
312 application = doc.createElement('application')
313 indent = get_indent(manifest.firstChild, 1)
314 first = manifest.firstChild
315 manifest.insertBefore(doc.createTextNode(indent), first)
316 manifest.insertBefore(application, first)
317
318 attr = application.getAttributeNodeNS(android_ns, 'hasCode')
319 if attr is not None:
320 # Do nothing if the application already has a hasCode attribute.
321 return
322 attr = doc.createAttributeNS(android_ns, 'android:hasCode')
323 attr.value = 'false'
324 application.setAttributeNode(attr)
325
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000326def set_test_only_flag_to_true(doc):
327 manifest = parse_manifest(doc)
328 elems = get_children_with_tag(manifest, 'application')
329 application = elems[0] if len(elems) == 1 else None
330 if len(elems) > 1:
331 raise RuntimeError('found multiple <application> tags')
332 elif not elems:
333 application = doc.createElement('application')
334 indent = get_indent(manifest.firstChild, 1)
335 first = manifest.firstChild
336 manifest.insertBefore(doc.createTextNode(indent), first)
337 manifest.insertBefore(application, first)
338
339 attr = application.getAttributeNodeNS(android_ns, 'testOnly')
340 if attr is not None:
341 # Do nothing If the application already has a testOnly attribute.
342 return
343 attr = doc.createAttributeNS(android_ns, 'android:testOnly')
344 attr.value = 'true'
345 application.setAttributeNode(attr)
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700346
William Loh5a082f92022-05-17 20:21:50 +0000347def set_max_sdk_version(doc, max_sdk_version):
348 """Replace the maxSdkVersion attribute value for permission and
349 uses-permission tags if the value was originally set to 'current'.
350 Used for cts test cases where the maxSdkVersion should equal to
351 Build.SDK_INT.
352
353 Args:
354 doc: The XML document. May be modified by this function.
355 max_sdk_version: The requested maxSdkVersion attribute.
356 """
357 manifest = parse_manifest(doc)
358 for tag in ['permission', 'uses-permission']:
359 children = get_children_with_tag(manifest, tag)
360 for child in children:
361 max_attr = child.getAttributeNodeNS(android_ns, 'maxSdkVersion')
362 if max_attr and max_attr.value == 'current':
363 max_attr.value = max_sdk_version
364
Colin Cross8bb10e82018-06-07 16:46:02 -0700365def main():
366 """Program entry point."""
367 try:
368 args = parse_args()
369
370 doc = minidom.parse(args.input)
371
372 ensure_manifest_android_ns(doc)
373
Colin Cross7b59e7b2018-09-10 13:35:13 -0700374 if args.raise_min_sdk_version:
375 raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
Colin Cross8bb10e82018-06-07 16:46:02 -0700376
William Loh5a082f92022-05-17 20:21:50 +0000377 if args.max_sdk_version:
378 set_max_sdk_version(doc, args.max_sdk_version)
379
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900380 if args.uses_libraries:
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900381 add_uses_libraries(doc, args.uses_libraries, True)
382
383 if args.optional_uses_libraries:
384 add_uses_libraries(doc, args.optional_uses_libraries, False)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900385
David Brazdild5b74992018-08-28 12:41:01 +0100386 if args.uses_non_sdk_api:
387 add_uses_non_sdk_api(doc)
388
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800389 if args.logging_parent:
390 add_logging_parent(doc, args.logging_parent)
391
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800392 if args.use_embedded_dex:
393 add_use_embedded_dex(doc)
Victor Hsiehce7818e2018-10-22 11:16:25 -0700394
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700395 if args.has_no_code:
396 set_has_code_to_false(doc)
397
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000398 if args.test_only:
399 set_test_only_flag_to_true(doc)
400
Colin Crosse4246ab2019-02-05 21:55:21 -0800401 if args.extract_native_libs is not None:
402 add_extract_native_libs(doc, args.extract_native_libs)
403
Cole Faustc41dd722021-11-09 15:08:26 -0800404 with open(args.output, 'w') as f:
Colin Cross8bb10e82018-06-07 16:46:02 -0700405 write_xml(f, doc)
406
407 # pylint: disable=broad-except
408 except Exception as err:
409 print('error: ' + str(err), file=sys.stderr)
410 sys.exit(-1)
411
412if __name__ == '__main__':
413 main()