blob: ebfc4d8a0f46edee4ef8dac75c48d8c3091e6227 [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
20import argparse
21import sys
22from xml.dom import minidom
23
24
25android_ns = 'http://schemas.android.com/apk/res/android'
26
27
28def get_children_with_tag(parent, tag_name):
29 children = []
30 for child in parent.childNodes:
31 if child.nodeType == minidom.Node.ELEMENT_NODE and \
32 child.tagName == tag_name:
33 children.append(child)
34 return children
35
36
Jiyong Parkc08f46f2018-06-18 11:01:00 +090037def find_child_with_attribute(element, tag_name, namespace_uri,
38 attr_name, value):
39 for child in get_children_with_tag(element, tag_name):
40 attr = child.getAttributeNodeNS(namespace_uri, attr_name)
41 if attr is not None and attr.value == value:
42 return child
43 return None
44
45
Colin Cross8bb10e82018-06-07 16:46:02 -070046def parse_args():
47 """Parse commandline arguments."""
48
49 parser = argparse.ArgumentParser()
50 parser.add_argument('--minSdkVersion', default='', dest='min_sdk_version',
51 help='specify minSdkVersion used by the build system')
Colin Cross7b59e7b2018-09-10 13:35:13 -070052 parser.add_argument('--targetSdkVersion', default='', dest='target_sdk_version',
53 help='specify targetSdkVersion used by the build system')
54 parser.add_argument('--raise-min-sdk-version', dest='raise_min_sdk_version', action='store_true',
55 help='raise the minimum sdk version in the manifest if necessary')
Colin Cross1b6a3cf2018-07-24 14:51:30 -070056 parser.add_argument('--library', dest='library', action='store_true',
57 help='manifest is for a static library')
Jiyong Parkc08f46f2018-06-18 11:01:00 +090058 parser.add_argument('--uses-library', dest='uses_libraries', action='append',
Jiyong Parkfa17afe2018-10-16 11:00:04 +090059 help='specify additional <uses-library> tag to add. android:requred is set to true')
60 parser.add_argument('--optional-uses-library', dest='optional_uses_libraries', action='append',
61 help='specify additional <uses-library> tag to add. android:requred is set to false')
David Brazdild5b74992018-08-28 12:41:01 +010062 parser.add_argument('--uses-non-sdk-api', dest='uses_non_sdk_api', action='store_true',
63 help='manifest is for a package built against the platform')
Victor Hsieha2c16c12019-01-02 14:50:56 -080064 parser.add_argument('--prefer-code-integrity', dest='prefer_code_integrity', action='store_true',
65 help=('specify if the app prefers strict code integrity. Should not be conflict '
66 'if already declared in the manifest.'))
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
72def parse_manifest(doc):
73 """Get the manifest element."""
74
75 manifest = doc.documentElement
76 if manifest.tagName != 'manifest':
77 raise RuntimeError('expected manifest tag at root')
78 return manifest
79
80
81def ensure_manifest_android_ns(doc):
82 """Make sure the manifest tag defines the android namespace."""
83
84 manifest = parse_manifest(doc)
85
86 ns = manifest.getAttributeNodeNS(minidom.XMLNS_NAMESPACE, 'android')
87 if ns is None:
88 attr = doc.createAttributeNS(minidom.XMLNS_NAMESPACE, 'xmlns:android')
89 attr.value = android_ns
90 manifest.setAttributeNode(attr)
91 elif ns.value != android_ns:
92 raise RuntimeError('manifest tag has incorrect android namespace ' +
93 ns.value)
94
95
96def as_int(s):
97 try:
98 i = int(s)
99 except ValueError:
100 return s, False
101 return i, True
102
103
104def compare_version_gt(a, b):
105 """Compare two SDK versions.
106
107 Compares a and b, treating codenames like 'Q' as higher
108 than numerical versions like '28'.
109
110 Returns True if a > b
111
112 Args:
113 a: value to compare
114 b: value to compare
115 Returns:
116 True if a is a higher version than b
117 """
118
119 a, a_is_int = as_int(a.upper())
120 b, b_is_int = as_int(b.upper())
121
122 if a_is_int == b_is_int:
123 # Both are codenames or both are versions, compare directly
124 return a > b
125 else:
126 # One is a codename, the other is not. Return true if
127 # b is an integer version
128 return b_is_int
129
130
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900131def get_indent(element, default_level):
132 indent = ''
133 if element is not None and element.nodeType == minidom.Node.TEXT_NODE:
134 text = element.nodeValue
135 indent = text[:len(text)-len(text.lstrip())]
136 if not indent or indent == '\n':
137 # 1 indent = 4 space
138 indent = '\n' + (' ' * default_level * 4)
139 return indent
140
141
Colin Cross7b59e7b2018-09-10 13:35:13 -0700142def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
Colin Cross8bb10e82018-06-07 16:46:02 -0700143 """Ensure the manifest contains a <uses-sdk> tag with a minSdkVersion.
144
145 Args:
146 doc: The XML document. May be modified by this function.
Colin Cross7b59e7b2018-09-10 13:35:13 -0700147 min_sdk_version: The requested minSdkVersion attribute.
148 target_sdk_version: The requested targetSdkVersion attribute.
Colin Cross8bb10e82018-06-07 16:46:02 -0700149 Raises:
150 RuntimeError: invalid manifest
151 """
152
153 manifest = parse_manifest(doc)
154
155 # Get or insert the uses-sdk element
156 uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
157 if len(uses_sdk) > 1:
158 raise RuntimeError('found multiple uses-sdk elements')
159 elif len(uses_sdk) == 1:
160 element = uses_sdk[0]
161 else:
162 element = doc.createElement('uses-sdk')
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900163 indent = get_indent(manifest.firstChild, 1)
Colin Cross8bb10e82018-06-07 16:46:02 -0700164 manifest.insertBefore(element, manifest.firstChild)
165
166 # Insert an indent before uses-sdk to line it up with the indentation of the
167 # other children of the <manifest> tag.
168 manifest.insertBefore(doc.createTextNode(indent), manifest.firstChild)
169
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700170 # Get or insert the minSdkVersion attribute. If it is already present, make
171 # sure it as least the requested value.
Colin Cross8bb10e82018-06-07 16:46:02 -0700172 min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
173 if min_attr is None:
174 min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
Colin Cross7b59e7b2018-09-10 13:35:13 -0700175 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700176 element.setAttributeNode(min_attr)
177 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700178 if compare_version_gt(min_sdk_version, min_attr.value):
179 min_attr.value = min_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700180
181 # Insert the targetSdkVersion attribute if it is missing. If it is already
182 # present leave it as is.
183 target_attr = element.getAttributeNodeNS(android_ns, 'targetSdkVersion')
184 if target_attr is None:
185 target_attr = doc.createAttributeNS(android_ns, 'android:targetSdkVersion')
186 if library:
Colin Cross4b176062018-10-01 15:15:51 -0700187 # TODO(b/117122200): libraries shouldn't set targetSdkVersion at all, but
188 # ManifestMerger treats minSdkVersion="Q" as targetSdkVersion="Q" if it
189 # is empty. Set it to something low so that it will be overriden by the
190 # main manifest, but high enough that it doesn't cause implicit
191 # permissions grants.
192 target_attr.value = '15'
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700193 else:
Colin Cross7b59e7b2018-09-10 13:35:13 -0700194 target_attr.value = target_sdk_version
Colin Cross1b6a3cf2018-07-24 14:51:30 -0700195 element.setAttributeNode(target_attr)
Colin Cross8bb10e82018-06-07 16:46:02 -0700196
197
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900198def add_uses_libraries(doc, new_uses_libraries, required):
199 """Add additional <uses-library> tags
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900200
201 Args:
202 doc: The XML document. May be modified by this function.
203 new_uses_libraries: The names of libraries to be added by this function.
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900204 required: The value of android:required attribute. Can be true or false.
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900205 Raises:
206 RuntimeError: Invalid manifest
207 """
208
209 manifest = parse_manifest(doc)
210 elems = get_children_with_tag(manifest, 'application')
211 application = elems[0] if len(elems) == 1 else None
212 if len(elems) > 1:
213 raise RuntimeError('found multiple <application> tags')
214 elif not elems:
215 application = doc.createElement('application')
216 indent = get_indent(manifest.firstChild, 1)
217 first = manifest.firstChild
218 manifest.insertBefore(doc.createTextNode(indent), first)
219 manifest.insertBefore(application, first)
220
221 indent = get_indent(application.firstChild, 2)
222
223 last = application.lastChild
224 if last is not None and last.nodeType != minidom.Node.TEXT_NODE:
225 last = None
226
227 for name in new_uses_libraries:
228 if find_child_with_attribute(application, 'uses-library', android_ns,
229 'name', name) is not None:
230 # If the uses-library tag of the same 'name' attribute value exists,
231 # respect it.
232 continue
233
234 ul = doc.createElement('uses-library')
235 ul.setAttributeNS(android_ns, 'android:name', name)
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900236 ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900237
238 application.insertBefore(doc.createTextNode(indent), last)
239 application.insertBefore(ul, last)
240
241 # align the closing tag with the opening tag if it's not
242 # indented
243 if application.lastChild.nodeType != minidom.Node.TEXT_NODE:
244 indent = get_indent(application.previousSibling, 1)
245 application.appendChild(doc.createTextNode(indent))
246
David Brazdild5b74992018-08-28 12:41:01 +0100247def add_uses_non_sdk_api(doc):
248 """Add android:usesNonSdkApi=true attribute to <application>.
249
250 Args:
251 doc: The XML document. May be modified by this function.
252 Raises:
253 RuntimeError: Invalid manifest
254 """
255
256 manifest = parse_manifest(doc)
257 elems = get_children_with_tag(manifest, 'application')
258 application = elems[0] if len(elems) == 1 else None
259 if len(elems) > 1:
260 raise RuntimeError('found multiple <application> tags')
261 elif not elems:
262 application = doc.createElement('application')
263 indent = get_indent(manifest.firstChild, 1)
264 first = manifest.firstChild
265 manifest.insertBefore(doc.createTextNode(indent), first)
266 manifest.insertBefore(application, first)
267
268 attr = application.getAttributeNodeNS(android_ns, 'usesNonSdkApi')
269 if attr is None:
270 attr = doc.createAttributeNS(android_ns, 'android:usesNonSdkApi')
271 attr.value = 'true'
272 application.setAttributeNode(attr)
273
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900274
Victor Hsieha2c16c12019-01-02 14:50:56 -0800275def add_prefer_code_integrity(doc):
Victor Hsiehce7818e2018-10-22 11:16:25 -0700276 manifest = parse_manifest(doc)
277 elems = get_children_with_tag(manifest, 'application')
278 application = elems[0] if len(elems) == 1 else None
279 if len(elems) > 1:
280 raise RuntimeError('found multiple <application> tags')
281 elif not elems:
282 application = doc.createElement('application')
283 indent = get_indent(manifest.firstChild, 1)
284 first = manifest.firstChild
285 manifest.insertBefore(doc.createTextNode(indent), first)
286 manifest.insertBefore(application, first)
287
Victor Hsieha2c16c12019-01-02 14:50:56 -0800288 attr = application.getAttributeNodeNS(android_ns, 'preferCodeIntegrity')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700289 if attr is None:
Victor Hsieha2c16c12019-01-02 14:50:56 -0800290 attr = doc.createAttributeNS(android_ns, 'android:preferCodeIntegrity')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700291 attr.value = 'true'
292 application.setAttributeNode(attr)
293 elif attr.value != 'true':
Victor Hsieha2c16c12019-01-02 14:50:56 -0800294 raise RuntimeError('existing attribute mismatches the option of --prefer-code-integrity')
Victor Hsiehce7818e2018-10-22 11:16:25 -0700295
296
Colin Cross8bb10e82018-06-07 16:46:02 -0700297def write_xml(f, doc):
298 f.write('<?xml version="1.0" encoding="utf-8"?>\n')
299 for node in doc.childNodes:
300 f.write(node.toxml(encoding='utf-8') + '\n')
301
302
303def main():
304 """Program entry point."""
305 try:
306 args = parse_args()
307
308 doc = minidom.parse(args.input)
309
310 ensure_manifest_android_ns(doc)
311
Colin Cross7b59e7b2018-09-10 13:35:13 -0700312 if args.raise_min_sdk_version:
313 raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
Colin Cross8bb10e82018-06-07 16:46:02 -0700314
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900315 if args.uses_libraries:
Jiyong Parkfa17afe2018-10-16 11:00:04 +0900316 add_uses_libraries(doc, args.uses_libraries, True)
317
318 if args.optional_uses_libraries:
319 add_uses_libraries(doc, args.optional_uses_libraries, False)
Jiyong Parkc08f46f2018-06-18 11:01:00 +0900320
David Brazdild5b74992018-08-28 12:41:01 +0100321 if args.uses_non_sdk_api:
322 add_uses_non_sdk_api(doc)
323
Victor Hsieha2c16c12019-01-02 14:50:56 -0800324 if args.prefer_code_integrity:
325 add_prefer_code_integrity(doc)
Victor Hsiehce7818e2018-10-22 11:16:25 -0700326
Colin Cross8bb10e82018-06-07 16:46:02 -0700327 with open(args.output, 'wb') as f:
328 write_xml(f, doc)
329
330 # pylint: disable=broad-except
331 except Exception as err:
332 print('error: ' + str(err), file=sys.stderr)
333 sys.exit(-1)
334
335if __name__ == '__main__':
336 main()