blob: c33b104bd6c31690664ff8700df31c829652ccf6 [file] [log] [blame]
Colin Cross72119102019-05-20 13:14:18 -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 checking that a manifest agrees with the build system."""
18
19from __future__ import print_function
20
21import argparse
Ulya Trafimovich3c902e72021-03-04 18:06:27 +000022import json
Ulya Trafimovich0aba2522021-03-03 16:38:37 +000023import re
24import subprocess
Colin Cross72119102019-05-20 13:14:18 -070025import sys
26from xml.dom import minidom
27
Colin Cross72119102019-05-20 13:14:18 -070028from manifest import android_ns
29from manifest import get_children_with_tag
30from manifest import parse_manifest
31from manifest import write_xml
32
33
34class ManifestMismatchError(Exception):
Spandan Dasf8807422021-08-25 20:01:17 +000035 pass
Colin Cross72119102019-05-20 13:14:18 -070036
37
38def parse_args():
Spandan Dasf8807422021-08-25 20:01:17 +000039 """Parse commandline arguments."""
Colin Cross72119102019-05-20 13:14:18 -070040
Spandan Dasf8807422021-08-25 20:01:17 +000041 parser = argparse.ArgumentParser()
42 parser.add_argument(
43 '--uses-library',
44 dest='uses_libraries',
45 action='append',
46 help='specify uses-library entries known to the build system')
47 parser.add_argument(
48 '--optional-uses-library',
49 dest='optional_uses_libraries',
50 action='append',
51 help='specify uses-library entries known to the build system with '
52 'required:false'
53 )
54 parser.add_argument(
55 '--enforce-uses-libraries',
56 dest='enforce_uses_libraries',
57 action='store_true',
58 help='check the uses-library entries known to the build system against '
59 'the manifest'
60 )
61 parser.add_argument(
62 '--enforce-uses-libraries-relax',
63 dest='enforce_uses_libraries_relax',
64 action='store_true',
65 help='do not fail immediately, just save the error message to file')
66 parser.add_argument(
67 '--enforce-uses-libraries-status',
68 dest='enforce_uses_libraries_status',
69 help='output file to store check status (error message)')
70 parser.add_argument(
71 '--extract-target-sdk-version',
72 dest='extract_target_sdk_version',
73 action='store_true',
74 help='print the targetSdkVersion from the manifest')
75 parser.add_argument(
76 '--dexpreopt-config',
Ulya Trofimovichc68b2892022-06-13 09:04:49 +000077 dest='dexpreopt_configs',
Spandan Dasf8807422021-08-25 20:01:17 +000078 action='append',
Ulya Trofimovichc68b2892022-06-13 09:04:49 +000079 help='a paths to a dexpreopt.config of some library')
Spandan Dasf8807422021-08-25 20:01:17 +000080 parser.add_argument('--aapt', dest='aapt', help='path to aapt executable')
81 parser.add_argument(
82 '--output', '-o', dest='output', help='output AndroidManifest.xml file')
83 parser.add_argument('input', help='input AndroidManifest.xml file')
84 return parser.parse_args()
Colin Cross72119102019-05-20 13:14:18 -070085
86
Ulya Trafimovichb4c19f82021-11-01 12:57:59 +000087C_RED = "\033[1;31m"
88C_GREEN = "\033[1;32m"
89C_BLUE = "\033[1;34m"
90C_OFF = "\033[0m"
91C_BOLD = "\033[1m"
92
93
Ulya Trafimovichbb7513d2021-03-30 17:15:16 +010094def enforce_uses_libraries(manifest, required, optional, relax, is_apk, path):
Spandan Dasf8807422021-08-25 20:01:17 +000095 """Verify that the <uses-library> tags in the manifest match those provided
96
Ulya Trafimovich0aba2522021-03-03 16:38:37 +000097 by the build system.
Colin Cross72119102019-05-20 13:14:18 -070098
99 Args:
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000100 manifest: manifest (either parsed XML or aapt dump of APK)
101 required: required libs known to the build system
102 optional: optional libs known to the build system
103 relax: if true, suppress error on mismatch and just write it to file
104 is_apk: if the manifest comes from an APK or an XML file
Spandan Dasf8807422021-08-25 20:01:17 +0000105 """
106 if is_apk:
107 manifest_required, manifest_optional, tags = extract_uses_libs_apk(
108 manifest)
109 else:
110 manifest_required, manifest_optional, tags = extract_uses_libs_xml(
111 manifest)
Colin Cross72119102019-05-20 13:14:18 -0700112
Spandan Dasf8807422021-08-25 20:01:17 +0000113 # Trim namespace component. Normally Soong does that automatically when it
114 # handles module names specified in Android.bp properties. However not all
115 # <uses-library> entries in the manifest correspond to real modules: some of
116 # the optional libraries may be missing at build time. Therefor this script
117 # accepts raw module names as spelled in Android.bp/Amdroid.mk and trims the
118 # optional namespace part manually.
119 required = trim_namespace_parts(required)
120 optional = trim_namespace_parts(optional)
Ulya Trafimovich1b513452021-07-20 14:27:32 +0100121
Spandan Dasf8807422021-08-25 20:01:17 +0000122 if manifest_required == required and manifest_optional == optional:
123 return None
Colin Cross72119102019-05-20 13:14:18 -0700124
Spandan Dasf8807422021-08-25 20:01:17 +0000125 #pylint: disable=line-too-long
126 errmsg = ''.join([
127 'mismatch in the <uses-library> tags between the build system and the '
128 'manifest:\n',
Ulya Trafimovichb4c19f82021-11-01 12:57:59 +0000129 '\t- required libraries in build system: %s[%s]%s\n' % (C_RED, ', '.join(required), C_OFF),
130 '\t vs. in the manifest: %s[%s]%s\n' % (C_RED, ', '.join(manifest_required), C_OFF),
131 '\t- optional libraries in build system: %s[%s]%s\n' % (C_RED, ', '.join(optional), C_OFF),
132 '\t vs. in the manifest: %s[%s]%s\n' % (C_RED, ', '.join(manifest_optional), C_OFF),
Spandan Dasf8807422021-08-25 20:01:17 +0000133 '\t- tags in the manifest (%s):\n' % path,
134 '\t\t%s\n' % '\t\t'.join(tags),
Ulya Trafimovichb4c19f82021-11-01 12:57:59 +0000135 '%snote:%s the following options are available:\n' % (C_BLUE, C_OFF),
Spandan Dasf8807422021-08-25 20:01:17 +0000136 '\t- to temporarily disable the check on command line, rebuild with ',
Ulya Trafimovichb4c19f82021-11-01 12:57:59 +0000137 '%sRELAX_USES_LIBRARY_CHECK=true%s' % (C_BOLD, C_OFF),
138 ' (this will set compiler filter "verify" and disable AOT-compilation in dexpreopt)\n',
Spandan Dasf8807422021-08-25 20:01:17 +0000139 '\t- to temporarily disable the check for the whole product, set ',
Ulya Trafimovichb4c19f82021-11-01 12:57:59 +0000140 '%sPRODUCT_BROKEN_VERIFY_USES_LIBRARIES := true%s in the product makefiles\n' % (C_BOLD, C_OFF),
141 '\t- to fix the check, make build system properties coherent with the manifest\n',
142 '\t- for details, see %sbuild/make/Changes.md%s' % (C_GREEN, C_OFF),
143 ' and %shttps://source.android.com/devices/tech/dalvik/art-class-loader-context%s\n' % (C_GREEN, C_OFF)
Spandan Dasf8807422021-08-25 20:01:17 +0000144 ])
145 #pylint: enable=line-too-long
Colin Cross72119102019-05-20 13:14:18 -0700146
Spandan Dasf8807422021-08-25 20:01:17 +0000147 if not relax:
148 raise ManifestMismatchError(errmsg)
Colin Cross72119102019-05-20 13:14:18 -0700149
Spandan Dasf8807422021-08-25 20:01:17 +0000150 return errmsg
Colin Cross72119102019-05-20 13:14:18 -0700151
Colin Cross72119102019-05-20 13:14:18 -0700152
Spandan Dasf8807422021-08-25 20:01:17 +0000153MODULE_NAMESPACE = re.compile('^//[^:]+:')
154
Ulya Trafimovich1b513452021-07-20 14:27:32 +0100155
156def trim_namespace_parts(modules):
Spandan Dasf8807422021-08-25 20:01:17 +0000157 """Trim the namespace part of each module, if present.
Ulya Trafimovich1b513452021-07-20 14:27:32 +0100158
Spandan Dasf8807422021-08-25 20:01:17 +0000159 Leave only the name.
160 """
161
162 trimmed = []
163 for module in modules:
164 trimmed.append(MODULE_NAMESPACE.sub('', module))
165 return trimmed
Ulya Trafimovich1b513452021-07-20 14:27:32 +0100166
167
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000168def extract_uses_libs_apk(badging):
Spandan Dasf8807422021-08-25 20:01:17 +0000169 """Extract <uses-library> tags from the manifest of an APK."""
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000170
Spandan Dasf8807422021-08-25 20:01:17 +0000171 pattern = re.compile("^uses-library(-not-required)?:'(.*)'$", re.MULTILINE)
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000172
Spandan Dasf8807422021-08-25 20:01:17 +0000173 required = []
174 optional = []
175 lines = []
176 for match in re.finditer(pattern, badging):
177 lines.append(match.group(0))
178 libname = match.group(2)
179 if match.group(1) is None:
180 required.append(libname)
181 else:
182 optional.append(libname)
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000183
Spandan Dasf8807422021-08-25 20:01:17 +0000184 required = first_unique_elements(required)
185 optional = first_unique_elements(optional)
186 tags = first_unique_elements(lines)
187 return required, optional, tags
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000188
189
Colin Crossc00fa152023-10-06 13:10:52 -0700190def extract_uses_libs_xml(xml):
Spandan Dasf8807422021-08-25 20:01:17 +0000191 """Extract <uses-library> tags from the manifest."""
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000192
Spandan Dasf8807422021-08-25 20:01:17 +0000193 manifest = parse_manifest(xml)
194 elems = get_children_with_tag(manifest, 'application')
Colin Crossc00fa152023-10-06 13:10:52 -0700195 if len(elems) > 1:
Spandan Dasf8807422021-08-25 20:01:17 +0000196 raise RuntimeError('found multiple <application> tags')
Colin Crossc00fa152023-10-06 13:10:52 -0700197 if not elems:
198 return [], [], []
199
200 application = elems[0]
Colin Cross72119102019-05-20 13:14:18 -0700201
Spandan Dasf8807422021-08-25 20:01:17 +0000202 libs = get_children_with_tag(application, 'uses-library')
Colin Cross72119102019-05-20 13:14:18 -0700203
Spandan Dasf8807422021-08-25 20:01:17 +0000204 required = [uses_library_name(x) for x in libs if uses_library_required(x)]
205 optional = [
206 uses_library_name(x) for x in libs if not uses_library_required(x)
207 ]
Colin Cross72119102019-05-20 13:14:18 -0700208
Spandan Dasf8807422021-08-25 20:01:17 +0000209 # render <uses-library> tags as XML for a pretty error message
210 tags = []
211 for lib in libs:
212 tags.append(lib.toprettyxml())
Ulya Trafimovichbb7513d2021-03-30 17:15:16 +0100213
Spandan Dasf8807422021-08-25 20:01:17 +0000214 required = first_unique_elements(required)
215 optional = first_unique_elements(optional)
216 tags = first_unique_elements(tags)
217 return required, optional, tags
Colin Cross72119102019-05-20 13:14:18 -0700218
219
220def first_unique_elements(l):
Spandan Dasf8807422021-08-25 20:01:17 +0000221 result = []
222 for x in l:
223 if x not in result:
224 result.append(x)
225 return result
Colin Cross72119102019-05-20 13:14:18 -0700226
227
228def uses_library_name(lib):
Spandan Dasf8807422021-08-25 20:01:17 +0000229 """Extract the name attribute of a uses-library tag.
Colin Cross72119102019-05-20 13:14:18 -0700230
231 Args:
232 lib: a <uses-library> tag.
Spandan Dasf8807422021-08-25 20:01:17 +0000233 """
234 name = lib.getAttributeNodeNS(android_ns, 'name')
235 return name.value if name is not None else ''
Colin Cross72119102019-05-20 13:14:18 -0700236
237
238def uses_library_required(lib):
Spandan Dasf8807422021-08-25 20:01:17 +0000239 """Extract the required attribute of a uses-library tag.
Colin Cross72119102019-05-20 13:14:18 -0700240
241 Args:
242 lib: a <uses-library> tag.
Spandan Dasf8807422021-08-25 20:01:17 +0000243 """
244 required = lib.getAttributeNodeNS(android_ns, 'required')
245 return (required.value == 'true') if required is not None else True
Colin Cross72119102019-05-20 13:14:18 -0700246
247
Spandan Dasf8807422021-08-25 20:01:17 +0000248def extract_target_sdk_version(manifest, is_apk=False):
249 """Returns the targetSdkVersion from the manifest.
Colin Cross72119102019-05-20 13:14:18 -0700250
251 Args:
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000252 manifest: manifest (either parsed XML or aapt dump of APK)
253 is_apk: if the manifest comes from an APK or an XML file
Spandan Dasf8807422021-08-25 20:01:17 +0000254 """
255 if is_apk: #pylint: disable=no-else-return
256 return extract_target_sdk_version_apk(manifest)
257 else:
258 return extract_target_sdk_version_xml(manifest)
Colin Cross72119102019-05-20 13:14:18 -0700259
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000260
261def extract_target_sdk_version_apk(badging):
Spandan Dasf8807422021-08-25 20:01:17 +0000262 """Extract targetSdkVersion tags from the manifest of an APK."""
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000263
Spandan Dasf8807422021-08-25 20:01:17 +0000264 pattern = re.compile("^targetSdkVersion?:'(.*)'$", re.MULTILINE)
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000265
Spandan Dasf8807422021-08-25 20:01:17 +0000266 for match in re.finditer(pattern, badging):
267 return match.group(1)
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000268
Spandan Dasf8807422021-08-25 20:01:17 +0000269 raise RuntimeError('cannot find targetSdkVersion in the manifest')
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000270
271
272def extract_target_sdk_version_xml(xml):
Spandan Dasf8807422021-08-25 20:01:17 +0000273 """Extract targetSdkVersion tags from the manifest."""
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000274
Spandan Dasf8807422021-08-25 20:01:17 +0000275 manifest = parse_manifest(xml)
Colin Cross72119102019-05-20 13:14:18 -0700276
Spandan Dasf8807422021-08-25 20:01:17 +0000277 # Get or insert the uses-sdk element
278 uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
279 if len(uses_sdk) > 1: #pylint: disable=no-else-raise
280 raise RuntimeError('found multiple uses-sdk elements')
281 elif len(uses_sdk) == 0:
282 raise RuntimeError('missing uses-sdk element')
Colin Cross72119102019-05-20 13:14:18 -0700283
Spandan Dasf8807422021-08-25 20:01:17 +0000284 uses_sdk = uses_sdk[0]
Colin Cross72119102019-05-20 13:14:18 -0700285
Spandan Dasf8807422021-08-25 20:01:17 +0000286 min_attr = uses_sdk.getAttributeNodeNS(android_ns, 'minSdkVersion')
287 if min_attr is None:
288 raise RuntimeError('minSdkVersion is not specified')
Colin Cross72119102019-05-20 13:14:18 -0700289
Spandan Dasf8807422021-08-25 20:01:17 +0000290 target_attr = uses_sdk.getAttributeNodeNS(android_ns, 'targetSdkVersion')
291 if target_attr is None:
292 target_attr = min_attr
Colin Cross72119102019-05-20 13:14:18 -0700293
Spandan Dasf8807422021-08-25 20:01:17 +0000294 return target_attr.value
Colin Cross72119102019-05-20 13:14:18 -0700295
296
Ulya Trofimovichc68b2892022-06-13 09:04:49 +0000297def load_dexpreopt_configs(configs):
Spandan Dasf8807422021-08-25 20:01:17 +0000298 """Load dexpreopt.config files and map module names to library names."""
299 module_to_libname = {}
Ulya Trafimovich3c902e72021-03-04 18:06:27 +0000300
Ulya Trofimovichc68b2892022-06-13 09:04:49 +0000301 if configs is None:
302 configs = []
Ulya Trafimovich3c902e72021-03-04 18:06:27 +0000303
Ulya Trofimovichc68b2892022-06-13 09:04:49 +0000304 for config in configs:
305 with open(config, 'r') as f:
Spandan Dasf8807422021-08-25 20:01:17 +0000306 contents = json.load(f)
Ulya Trofimovichc68b2892022-06-13 09:04:49 +0000307 module_to_libname[contents['Name']] = contents['ProvidesUsesLibrary']
Ulya Trafimovich3c902e72021-03-04 18:06:27 +0000308
Ulya Trofimovichc68b2892022-06-13 09:04:49 +0000309 return module_to_libname
Ulya Trafimovich3c902e72021-03-04 18:06:27 +0000310
311
312def translate_libnames(modules, module_to_libname):
Spandan Dasf8807422021-08-25 20:01:17 +0000313 """Translate module names into library names using the mapping."""
Ulya Trofimovichc68b2892022-06-13 09:04:49 +0000314 if modules is None:
315 modules = []
Ulya Trafimovich3c902e72021-03-04 18:06:27 +0000316
Spandan Dasf8807422021-08-25 20:01:17 +0000317 libnames = []
318 for name in modules:
319 if name in module_to_libname:
320 name = module_to_libname[name]
321 libnames.append(name)
Ulya Trafimovich3c902e72021-03-04 18:06:27 +0000322
Spandan Dasf8807422021-08-25 20:01:17 +0000323 return libnames
Ulya Trafimovich3c902e72021-03-04 18:06:27 +0000324
325
Colin Cross72119102019-05-20 13:14:18 -0700326def main():
Spandan Dasf8807422021-08-25 20:01:17 +0000327 """Program entry point."""
328 try:
329 args = parse_args()
Colin Cross72119102019-05-20 13:14:18 -0700330
Spandan Dasf8807422021-08-25 20:01:17 +0000331 # The input can be either an XML manifest or an APK, they are parsed and
332 # processed in different ways.
333 is_apk = args.input.endswith('.apk')
334 if is_apk:
335 aapt = args.aapt if args.aapt is not None else 'aapt'
336 manifest = subprocess.check_output(
Cole Faustc41dd722021-11-09 15:08:26 -0800337 [aapt, 'dump', 'badging', args.input]).decode('utf-8')
Spandan Dasf8807422021-08-25 20:01:17 +0000338 else:
339 manifest = minidom.parse(args.input)
Colin Cross72119102019-05-20 13:14:18 -0700340
Spandan Dasf8807422021-08-25 20:01:17 +0000341 if args.enforce_uses_libraries:
342 # Load dexpreopt.config files and build a mapping from module
343 # names to library names. This is necessary because build system
344 # addresses libraries by their module name (`uses_libs`,
345 # `optional_uses_libs`, `LOCAL_USES_LIBRARIES`,
346 # `LOCAL_OPTIONAL_LIBRARY_NAMES` all contain module names), while
347 # the manifest addresses libraries by their name.
Ulya Trofimovichc68b2892022-06-13 09:04:49 +0000348 mod_to_lib = load_dexpreopt_configs(args.dexpreopt_configs)
349 required = translate_libnames(args.uses_libraries, mod_to_lib)
350 optional = translate_libnames(args.optional_uses_libraries,
351 mod_to_lib)
Ulya Trafimovich3c902e72021-03-04 18:06:27 +0000352
Spandan Dasf8807422021-08-25 20:01:17 +0000353 # Check if the <uses-library> lists in the build system agree with
354 # those in the manifest. Raise an exception on mismatch, unless the
355 # script was passed a special parameter to suppress exceptions.
356 errmsg = enforce_uses_libraries(manifest, required, optional,
357 args.enforce_uses_libraries_relax,
358 is_apk, args.input)
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000359
Spandan Dasf8807422021-08-25 20:01:17 +0000360 # Create a status file that is empty on success, or contains an
361 # error message on failure. When exceptions are suppressed,
362 # dexpreopt command command will check file size to determine if
363 # the check has failed.
364 if args.enforce_uses_libraries_status:
365 with open(args.enforce_uses_libraries_status, 'w') as f:
Spandan Das3d5cd4d2021-09-20 18:24:56 +0000366 if errmsg is not None:
Spandan Dasf8807422021-08-25 20:01:17 +0000367 f.write('%s\n' % errmsg)
Colin Cross72119102019-05-20 13:14:18 -0700368
Spandan Dasf8807422021-08-25 20:01:17 +0000369 if args.extract_target_sdk_version:
370 try:
371 print(extract_target_sdk_version(manifest, is_apk))
372 except: #pylint: disable=bare-except
373 # Failed; don't crash, return "any" SDK version. This will
374 # result in dexpreopt not adding any compatibility libraries.
375 print(10000)
Colin Cross72119102019-05-20 13:14:18 -0700376
Spandan Dasf8807422021-08-25 20:01:17 +0000377 if args.output:
378 # XML output is supposed to be written only when this script is
379 # invoked with XML input manifest, not with an APK.
380 if is_apk:
381 raise RuntimeError('cannot save APK manifest as XML')
Ulya Trafimovich0aba2522021-03-03 16:38:37 +0000382
Cole Faustc41dd722021-11-09 15:08:26 -0800383 with open(args.output, 'w') as f:
Spandan Dasf8807422021-08-25 20:01:17 +0000384 write_xml(f, manifest)
Colin Cross72119102019-05-20 13:14:18 -0700385
Spandan Dasf8807422021-08-25 20:01:17 +0000386 # pylint: disable=broad-except
387 except Exception as err:
Ulya Trafimovichb4c19f82021-11-01 12:57:59 +0000388 print('%serror:%s ' % (C_RED, C_OFF) + str(err), file=sys.stderr)
Spandan Dasf8807422021-08-25 20:01:17 +0000389 sys.exit(-1)
390
Colin Cross72119102019-05-20 13:14:18 -0700391
392if __name__ == '__main__':
Spandan Dasf8807422021-08-25 20:01:17 +0000393 main()