1#!/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
20
21import argparse
22import sys
23from xml.dom import minidom
24
25
26from 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
34
35
36def 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')
42  parser.add_argument('--replaceMaxSdkVersionPlaceholder', default='', dest='max_sdk_version',
43                      help='specify maxSdkVersion used by the build system')
44  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')
48  parser.add_argument('--library', dest='library', action='store_true',
49                      help='manifest is for a static library')
50  parser.add_argument('--uses-library', dest='uses_libraries', action='append',
51                      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')
54  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')
56  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.'))
59  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,'
61                            'locally compiled code. Must not conflict if already declared '
62                            'in the manifest.'))
63  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.'))
67  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.'))
70  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.'))
73  parser.add_argument('--override-placeholder-version', dest='new_version',
74                      help='Overrides the versionCode if it\'s set to the placeholder value of 0')
75  parser.add_argument('input', help='input AndroidManifest.xml file')
76  parser.add_argument('output', help='output AndroidManifest.xml file')
77  return parser.parse_args()
78
79
80def raise_min_sdk_version(doc, min_sdk_version, target_sdk_version, library):
81  """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.
85    min_sdk_version: The requested minSdkVersion attribute.
86    target_sdk_version: The requested targetSdkVersion attribute.
87    library: True if the manifest is for a library.
88  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')
102    indent = get_indent(manifest.firstChild, 1)
103    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
109  # Get or insert the minSdkVersion attribute.  If it is already present, make
110  # sure it as least the requested value.
111  min_attr = element.getAttributeNodeNS(android_ns, 'minSdkVersion')
112  if min_attr is None:
113    min_attr = doc.createAttributeNS(android_ns, 'android:minSdkVersion')
114    min_attr.value = min_sdk_version
115    element.setAttributeNode(min_attr)
116  else:
117    if compare_version_gt(min_sdk_version, min_attr.value):
118      min_attr.value = min_sdk_version
119
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:
126      # 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.
131      target_attr.value = '16'
132    else:
133      target_attr.value = target_sdk_version
134    element.setAttributeNode(target_attr)
135
136
137def 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
183def add_uses_libraries(doc, new_uses_libraries, required):
184  """Add additional <uses-library> tags
185
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.
189    required: The value of android:required attribute. Can be true or false.
190  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)
221    ul.setAttributeNS(android_ns, 'android:required', str(required).lower())
222
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
232
233def 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
260
261def add_use_embedded_dex(doc):
262  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
274  attr = application.getAttributeNodeNS(android_ns, 'useEmbeddedDex')
275  if attr is None:
276    attr = doc.createAttributeNS(android_ns, 'android:useEmbeddedDex')
277    attr.value = 'true'
278    application.setAttributeNode(attr)
279  elif attr.value != 'true':
280    raise RuntimeError('existing attribute mismatches the option of --use-embedded-dex')
281
282
283def 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)
302  elif attr.value != value:
303    raise RuntimeError('existing attribute extractNativeLibs="%s" conflicts with --extract-native-libs="%s"' %
304                       (attr.value, value))
305
306
307def 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
328def 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)
348
349def 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
367def 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
380def 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
389    if args.raise_min_sdk_version:
390      raise_min_sdk_version(doc, args.min_sdk_version, args.target_sdk_version, args.library)
391
392    if args.max_sdk_version:
393      set_max_sdk_version(doc, args.max_sdk_version)
394
395    if args.uses_libraries:
396      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)
400
401    if args.uses_non_sdk_api:
402      add_uses_non_sdk_api(doc)
403
404    if args.logging_parent:
405      add_logging_parent(doc, args.logging_parent)
406
407    if args.use_embedded_dex:
408      add_use_embedded_dex(doc)
409
410    if args.has_no_code:
411      set_has_code_to_false(doc)
412
413    if args.test_only:
414      set_test_only_flag_to_true(doc)
415
416    if args.extract_native_libs is not None:
417      add_extract_native_libs(doc, args.extract_native_libs)
418
419    if args.new_version:
420      override_placeholder_version(doc, args.new_version)
421
422    with open(args.output, 'w') as f:
423      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()
432