blob: 9847ad5bbce957c8b81b14a7c54b3534b8117c15 [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 Crosse1ab8492024-09-11 13:28:16 -070026from manifest import *
Jiyong Parkc08f46f2018-06-18 11:01:00 +090027
Colin Cross8bb10e82018-06-07 16:46:02 -070028def parse_args():
29 """Parse commandline arguments."""
30
31 parser = argparse.ArgumentParser()
32 parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
33 help='specify minSdkVersion used by the build system')
William Loh5a082f92022-05-17 20:21:50 +000034 parser.add_argument('--replaceMaxSdkVersionPlaceholder', default='', dest='max_sdk_version',
35 help='specify maxSdkVersion used by the build system')
Colin Cross7b59e7b2018-09-10 13:35:13 -070036 parser.add_argument('--targetSdkVersion', default='', dest='target_sdk_version',
37 help='specify targetSdkVersion used by the build system')
38 parser.add_argument('--raise-min-sdk-version', dest='raise_min_sdk_version', action='store_true',
39 help='raise the minimum sdk version in the manifest if necessary')
Colin Cross1b6a3cf2018-07-24 14:51:30 -070040 parser.add_argument('--library', dest='library', action='store_true',
41 help='manifest is for a static library')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090042 parser.add_argument('--uses-library', dest='uses_libraries', action='append',
Colin Cross6cb462b2024-09-11 11:34:35 -070043 help='specify additional <uses-library> tag to add. android:required is set to true')
Jiyong Parkfa17afe2018-10-16 11:00:04 +090044 parser.add_argument('--optional-uses-library', dest='optional_uses_libraries', action='append',
Colin Cross6cb462b2024-09-11 11:34:35 -070045 help='specify additional <uses-library> tag to add. android:required is set to false')
David Brazdild5b74992018-08-28 12:41:01 +010046 parser.add_argument('--uses-non-sdk-api', dest='uses_non_sdk_api', action='store_true',
47 help='manifest is for a package built against the platform')
Baligh Uddin5b16dfb2020-02-11 17:27:19 -080048 parser.add_argument('--logging-parent', dest='logging_parent', default='',
49 help=('specify logging parent as an additional <meta-data> tag. '
50 'This value is ignored if the logging_parent meta-data tag is present.'))
Victor Hsiehd181c8b2019-01-29 13:00:33 -080051 parser.add_argument('--use-embedded-dex', dest='use_embedded_dex', action='store_true',
52 help=('specify if the app wants to use embedded dex and avoid extracted,'
Colin Crosse4246ab2019-02-05 21:55:21 -080053 'locally compiled code. Must not conflict if already declared '
Victor Hsiehd181c8b2019-01-29 13:00:33 -080054 'in the manifest.'))
Colin Crosse4246ab2019-02-05 21:55:21 -080055 parser.add_argument('--extract-native-libs', dest='extract_native_libs',
56 default=None, type=lambda x: (str(x).lower() == 'true'),
Jiyong Parkd044bb42024-05-15 02:09:54 +090057 help=('specify if the app wants to use embedded native libraries. Must not conflict '
58 'if already declared in the manifest.'))
Jaewoong Jungc27ab662019-05-30 15:51:14 -070059 parser.add_argument('--has-no-code', dest='has_no_code', action='store_true',
60 help=('adds hasCode="false" attribute to application. Ignored if application elem '
61 'already has a hasCode attribute.'))
Gurpreet Singh75d65f32022-01-24 17:44:05 +000062 parser.add_argument('--test-only', dest='test_only', action='store_true',
63 help=('adds testOnly="true" attribute to application. Assign true value if application elem '
64 'already has a testOnly attribute.'))
Alexei Nicoara69cf0f32022-07-27 14:59:18 +010065 parser.add_argument('--override-placeholder-version', dest='new_version',
66 help='Overrides the versionCode if it\'s set to the placeholder value of 0')
Colin Cross8bb10e82018-06-07 16:46:02 -070067 parser.add_argument('input', help='input AndroidManifest.xml file')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090068 parser.add_argument('output', help='output AndroidManifest.xml file')
Colin Cross8bb10e82018-06-07 16:46:02 -070069 return parser.parse_args()
70
71
Colin Cross7b59e7b2018-09-10 13:35:13 -070072def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
Colin Cross8bb10e82018-06-07 16:46:02 -070073 """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
74
75 Args:
76 doc: The XML document. May be modified by this function.
Colin Cross7b59e7b2018-09-10 13:35:13 -070077 min_sdk_version: The requested minSdkVersion attribute.
78 target_sdk_version: The requested targetSdkVersion attribute.
Colin Cross72119102019-05-20 13:14:18 -070079 library: True if the manifest is for a library.
Colin Cross8bb10e82018-06-07 16:46:02 -070080 Raises:
81 RuntimeError: invalid manifest
82 """
83
84 manifest = parse_manifest(doc)
85
Colin Crosse1ab8492024-09-11 13:28:16 -070086 for uses_sdk in get_or_create_uses_sdks(doc, manifest):
87 # Get or insert the minSdkVersion attribute. If it is already present, make
88 # sure it as least the requested value.
89 min_attr = uses_sdk.getAttributeNodeNS(android_ns, 'minSdkVersion')
90 if min_attr is None:
91 min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
Colin Cross7b59e7b2018-09-10 13:35:13 -070092 min_attr.value = min_sdk_version
Colin Crosse1ab8492024-09-11 13:28:16 -070093 uses_sdk.setAttributeNode(min_attr)
Colin Cross1b6a3cf2018-07-24 14:51:30 -070094 else:
Colin Crosse1ab8492024-09-11 13:28:16 -070095 if compare_version_gt(min_sdk_version, min_attr.value):
96 min_attr.value = min_sdk_version
97
98 # Insert the targetSdkVersion attribute if it is missing. If it is already
99 # present leave it as is.
100 target_attr = uses_sdk.getAttributeNodeNS(android_ns, 'targetSdkVersion')
101 if target_attr is None:
102 target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
103 if library:
104 # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but
105 # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it
106 # is empty. Set it to something low so that it will be overridden by the
107 # main manifest, but high enough that it doesn't cause implicit
108 # permissions grants.
109 target_attr.value = '16'
110 else:
111 target_attr.value = target_sdk_version
112 uses_sdk.setAttributeNode(target_attr)
Colin Cross8bb10e82018-06-07 16:46:02 -0700113
114
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800115def add_logging_parent(doc, logging_parent_value):
116 """Add logging parent as an additional <meta-data> tag.
117
118 Args:
119 doc: The XML document. May be modified by this function.
120 logging_parent_value: A string representing the logging
121 parent value.
122 Raises:
123 RuntimeError: Invalid manifest
124 """
125 manifest = parse_manifest(doc)
126
127 logging_parent_key = 'android.content.pm.LOGGING_PARENT'
Colin Crosse1ab8492024-09-11 13:28:16 -0700128 for application in get_or_create_applications(doc, manifest):
129 indent = get_indent(application.firstChild, 2)
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800130
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800131 last = application.lastChild
Colin Crosse1ab8492024-09-11 13:28:16 -0700132 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
133 last = None
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800134
Colin Crosse1ab8492024-09-11 13:28:16 -0700135 if not find_child_with_attribute(application, 'meta-data', android_ns,
136 'name', logging_parent_key):
137 ul = doc.createElement('meta-data')
138 ul.setAttributeNS(android_ns, 'android:name', logging_parent_key)
139 ul.setAttributeNS(android_ns, 'android:value', logging_parent_value)
140 application.insertBefore(doc.createTextNode(indent), last)
141 application.insertBefore(ul, last)
142 last = application.lastChild
143
144 # align the closing tag with the opening tag if it's not
145 # indented
146 if last and last.nodeType != minidom.Node.TEXT_NODE:
147 indent = get_indent(application.previousSibling, 1)
148 application.appendChild(doc.createTextNode(indent))
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800149
150
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900151def add_uses_libraries(doc, new_uses_libraries, required):
152 """Add additional <uses-library> tags
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900153
154 Args:
155 doc: The XML document. May be modified by this function.
156 new_uses_libraries: The names of libraries to be added by this function.
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900157 required: The value of android:required attribute. Can be true or false.
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900158 Raises:
159 RuntimeError: Invalid manifest
160 """
161
162 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700163 for application in get_or_create_applications(doc, manifest):
164 indent = get_indent(application.firstChild, 2)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900165
Colin Crosse1ab8492024-09-11 13:28:16 -0700166 last = application.lastChild
167 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
168 last = None
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900169
Colin Crosse1ab8492024-09-11 13:28:16 -0700170 for name in new_uses_libraries:
171 if find_child_with_attribute(application, 'uses-library', android_ns,
172 'name', name) is not None:
173 # If the uses-library tag of the same 'name' attribute value exists,
174 # respect it.
175 continue
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900176
Colin Crosse1ab8492024-09-11 13:28:16 -0700177 ul = doc.createElement('uses-library')
178 ul.setAttributeNS(android_ns, 'android:name', name)
179 ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900180
Colin Crosse1ab8492024-09-11 13:28:16 -0700181 application.insertBefore(doc.createTextNode(indent), last)
182 application.insertBefore(ul, last)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900183
Colin Crosse1ab8492024-09-11 13:28:16 -0700184 # align the closing tag with the opening tag if it's not
185 # indented
186 if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
187 indent = get_indent(application.previousSibling, 1)
188 application.appendChild(doc.createTextNode(indent))
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900189
Colin Cross72119102019-05-20 13:14:18 -0700190
David Brazdild5b74992018-08-28 12:41:01 +0100191def add_uses_non_sdk_api(doc):
192 """Add android:usesNonSdkApi=true attribute to <application>.
193
194 Args:
195 doc: The XML document. May be modified by this function.
196 Raises:
197 RuntimeError: Invalid manifest
198 """
199
200 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700201 for application in get_or_create_applications(doc, manifest):
202 attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
203 if attr is None:
204 attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
205 attr.value = 'true'
206 application.setAttributeNode(attr)
David Brazdild5b74992018-08-28 12:41:01 +0100207
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900208
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800209def add_use_embedded_dex(doc):
Victor Hsiehce7818e2018-10-22 11:16:25 -0700210 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700211 for application in get_or_create_applications(doc, manifest):
212 attr = application.getAttributeNodeNS(android_ns, 'useEmbeddedDex')
213 if attr is None:
214 attr = doc.createAttributeNS(android_ns, 'android:useEmbeddedDex')
215 attr.value = 'true'
216 application.setAttributeNode(attr)
217 elif attr.value != 'true':
218 raise RuntimeError('existing attribute mismatches the option of --use-embedded-dex')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700219
220
Colin Crosse4246ab2019-02-05 21:55:21 -0800221def add_extract_native_libs(doc, extract_native_libs):
222 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700223 for application in get_or_create_applications(doc, manifest):
224 value = str(extract_native_libs).lower()
225 attr = application.getAttributeNodeNS(android_ns, 'extractNativeLibs')
226 if attr is None:
227 attr = doc.createAttributeNS(android_ns, 'android:extractNativeLibs')
228 attr.value = value
229 application.setAttributeNode(attr)
230 elif attr.value != value:
231 raise RuntimeError('existing attribute extractNativeLibs="%s" conflicts with --extract-native-libs="%s"' %
232 (attr.value, value))
Colin Crosse4246ab2019-02-05 21:55:21 -0800233
234
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700235def set_has_code_to_false(doc):
236 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700237 for application in get_or_create_applications(doc, manifest):
238 attr = application.getAttributeNodeNS(android_ns, 'hasCode')
239 if attr is not None:
240 # Do nothing if the application already has a hasCode attribute.
241 continue
242 attr = doc.createAttributeNS(android_ns, 'android:hasCode')
243 attr.value = 'false'
244 application.setAttributeNode(attr)
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700245
Colin Cross6cb462b2024-09-11 11:34:35 -0700246
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000247def set_test_only_flag_to_true(doc):
248 manifest = parse_manifest(doc)
Colin Crosse1ab8492024-09-11 13:28:16 -0700249 for application in get_or_create_applications(doc, manifest):
250 attr = application.getAttributeNodeNS(android_ns, 'testOnly')
251 if attr is not None:
252 # Do nothing If the application already has a testOnly attribute.
253 continue
254 attr = doc.createAttributeNS(android_ns, 'android:testOnly')
255 attr.value = 'true'
256 application.setAttributeNode(attr)
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700257
Colin Cross6cb462b2024-09-11 11:34:35 -0700258
William Loh5a082f92022-05-17 20:21:50 +0000259def set_max_sdk_version(doc, max_sdk_version):
260 """Replace the maxSdkVersion attribute value for permission and
261 uses-permission tags if the value was originally set to 'current'.
262 Used for cts test cases where the maxSdkVersion should equal to
263 Build.SDK_INT.
264
265 Args:
266 doc: The XML document. May be modified by this function.
267 max_sdk_version: The requested maxSdkVersion attribute.
268 """
269 manifest = parse_manifest(doc)
270 for tag in ['permission', 'uses-permission']:
271 children = get_children_with_tag(manifest, tag)
272 for child in children:
273 max_attr = child.getAttributeNodeNS(android_ns, 'maxSdkVersion')
274 if max_attr and max_attr.value == 'current':
275 max_attr.value = max_sdk_version
276
Colin Cross6cb462b2024-09-11 11:34:35 -0700277
Alexei Nicoara69cf0f32022-07-27 14:59:18 +0100278def override_placeholder_version(doc, new_version):
279 """Replace the versionCode attribute value if it\'s currently
280 set to the placeholder version of 0.
281
282 Args:
283 doc: The XML document. May be modified by this function.
284 new_version: The new version to set if versionCode is equal to 0.
285 """
286 manifest = parse_manifest(doc)
287 version = manifest.getAttribute("android:versionCode")
Colin Cross6cb462b2024-09-11 11:34:35 -0700288 if version == '0':
Alexei Nicoara69cf0f32022-07-27 14:59:18 +0100289 manifest.setAttribute("android:versionCode", new_version)
290
Colin Cross6cb462b2024-09-11 11:34:35 -0700291
Colin Cross8bb10e82018-06-07 16:46:02 -0700292def main():
293 """Program entry point."""
294 try:
295 args = parse_args()
296
297 doc = minidom.parse(args.input)
298
299 ensure_manifest_android_ns(doc)
300
Colin Cross7b59e7b2018-09-10 13:35:13 -0700301 if args.raise_min_sdk_version:
302 raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
Colin Cross8bb10e82018-06-07 16:46:02 -0700303
William Loh5a082f92022-05-17 20:21:50 +0000304 if args.max_sdk_version:
305 set_max_sdk_version(doc, args.max_sdk_version)
306
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900307 if args.uses_libraries:
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900308 add_uses_libraries(doc, args.uses_libraries, True)
309
310 if args.optional_uses_libraries:
311 add_uses_libraries(doc, args.optional_uses_libraries, False)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900312
David Brazdild5b74992018-08-28 12:41:01 +0100313 if args.uses_non_sdk_api:
314 add_uses_non_sdk_api(doc)
315
Baligh Uddin5b16dfb2020-02-11 17:27:19 -0800316 if args.logging_parent:
317 add_logging_parent(doc, args.logging_parent)
318
Victor Hsiehd181c8b2019-01-29 13:00:33 -0800319 if args.use_embedded_dex:
320 add_use_embedded_dex(doc)
Victor Hsiehce7818e2018-10-22 11:16:25 -0700321
Jaewoong Jungc27ab662019-05-30 15:51:14 -0700322 if args.has_no_code:
323 set_has_code_to_false(doc)
324
Gurpreet Singh75d65f32022-01-24 17:44:05 +0000325 if args.test_only:
326 set_test_only_flag_to_true(doc)
327
Colin Crosse4246ab2019-02-05 21:55:21 -0800328 if args.extract_native_libs is not None:
329 add_extract_native_libs(doc, args.extract_native_libs)
330
Alexei Nicoara69cf0f32022-07-27 14:59:18 +0100331 if args.new_version:
332 override_placeholder_version(doc, args.new_version)
333
Cole Faustc41dd722021-11-09 15:08:26 -0800334 with open(args.output, 'w') as f:
Colin Cross8bb10e82018-06-07 16:46:02 -0700335 write_xml(f, doc)
336
337 # pylint: disable=broad-except
338 except Exception as err:
339 print('error: ' + str(err), file=sys.stderr)
340 sys.exit(-1)
341
Colin Cross6cb462b2024-09-11 11:34:35 -0700342
Colin Cross8bb10e82018-06-07 16:46:02 -0700343if __name__ == '__main__':
344 main()