blob: 0eb1b7631a76a449470843e7abed3244d072f503 [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
22import sys
23from xml.dom import minidom
24
25
26from manifest import android_ns
27from manifest import get_children_with_tag
28from manifest import parse_manifest
29from manifest import write_xml
30
31
32class ManifestMismatchError(Exception):
33 pass
34
35
36def parse_args():
37 """Parse commandline arguments."""
38
39 parser = argparse.ArgumentParser()
40 parser.add_argument('--uses-library', dest='uses_libraries',
41 action='append',
42 help='specify uses-library entries known to the build system')
43 parser.add_argument('--optional-uses-library',
44 dest='optional_uses_libraries',
45 action='append',
46 help='specify uses-library entries known to the build system with required:false')
47 parser.add_argument('--enforce-uses-libraries',
48 dest='enforce_uses_libraries',
49 action='store_true',
50 help='check the uses-library entries known to the build system against the manifest')
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +000051 parser.add_argument('--enforce-uses-libraries-relax',
52 dest='enforce_uses_libraries_relax',
53 action='store_true',
54 help='do not fail immediately, just save the error message to file')
55 parser.add_argument('--enforce-uses-libraries-status',
56 dest='enforce_uses_libraries_status',
57 help='output file to store check status (error message)')
Colin Cross72119102019-05-20 13:14:18 -070058 parser.add_argument('--extract-target-sdk-version',
59 dest='extract_target_sdk_version',
60 action='store_true',
61 help='print the targetSdkVersion from the manifest')
62 parser.add_argument('--output', '-o', dest='output', help='output AndroidManifest.xml file')
63 parser.add_argument('input', help='input AndroidManifest.xml file')
64 return parser.parse_args()
65
66
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +000067def enforce_uses_libraries(doc, uses_libraries, optional_uses_libraries, relax):
Colin Cross72119102019-05-20 13:14:18 -070068 """Verify that the <uses-library> tags in the manifest match those provided by the build system.
69
70 Args:
71 doc: The XML document.
72 uses_libraries: The names of <uses-library> tags known to the build system
73 optional_uses_libraries: The names of <uses-library> tags with required:fals
74 known to the build system
75 Raises:
76 RuntimeError: Invalid manifest
77 ManifestMismatchError: Manifest does not match
78 """
79
80 manifest = parse_manifest(doc)
81 elems = get_children_with_tag(manifest, 'application')
82 application = elems[0] if len(elems) == 1 else None
83 if len(elems) > 1:
84 raise RuntimeError('found multiple <application> tags')
85 elif not elems:
86 if uses_libraries or optional_uses_libraries:
87 raise ManifestMismatchError('no <application> tag found')
88 return
89
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +000090 return verify_uses_library(application, uses_libraries, optional_uses_libraries, relax)
Colin Cross72119102019-05-20 13:14:18 -070091
92
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +000093def verify_uses_library(application, uses_libraries, optional_uses_libraries, relax):
Colin Cross72119102019-05-20 13:14:18 -070094 """Verify that the uses-library values known to the build system match the manifest.
95
96 Args:
97 application: the <application> tag in the manifest.
98 uses_libraries: the names of expected <uses-library> tags.
99 optional_uses_libraries: the names of expected <uses-library> tags with required="false".
100 Raises:
101 ManifestMismatchError: Manifest does not match
102 """
103
104 if uses_libraries is None:
105 uses_libraries = []
106
107 if optional_uses_libraries is None:
108 optional_uses_libraries = []
109
110 manifest_uses_libraries, manifest_optional_uses_libraries = parse_uses_library(application)
111
112 err = []
113 if manifest_uses_libraries != uses_libraries:
114 err.append('Expected required <uses-library> tags "%s", got "%s"' %
115 (', '.join(uses_libraries), ', '.join(manifest_uses_libraries)))
116
117 if manifest_optional_uses_libraries != optional_uses_libraries:
118 err.append('Expected optional <uses-library> tags "%s", got "%s"' %
119 (', '.join(optional_uses_libraries), ', '.join(manifest_optional_uses_libraries)))
120
121 if err:
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000122 errmsg = '\n'.join(err)
123 if not relax:
124 raise ManifestMismatchError(errmsg)
125 return errmsg
Colin Cross72119102019-05-20 13:14:18 -0700126
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000127 return None
Colin Cross72119102019-05-20 13:14:18 -0700128
129def parse_uses_library(application):
130 """Extract uses-library tags from the manifest.
131
132 Args:
133 application: the <application> tag in the manifest.
134 """
135
136 libs = get_children_with_tag(application, 'uses-library')
137
138 uses_libraries = [uses_library_name(x) for x in libs if uses_library_required(x)]
139 optional_uses_libraries = [uses_library_name(x) for x in libs if not uses_library_required(x)]
140
141 return first_unique_elements(uses_libraries), first_unique_elements(optional_uses_libraries)
142
143
144def first_unique_elements(l):
145 result = []
146 [result.append(x) for x in l if x not in result]
147 return result
148
149
150def uses_library_name(lib):
151 """Extract the name attribute of a uses-library tag.
152
153 Args:
154 lib: a <uses-library> tag.
155 """
156 name = lib.getAttributeNodeNS(android_ns, 'name')
157 return name.value if name is not None else ""
158
159
160def uses_library_required(lib):
161 """Extract the required attribute of a uses-library tag.
162
163 Args:
164 lib: a <uses-library> tag.
165 """
166 required = lib.getAttributeNodeNS(android_ns, 'required')
167 return (required.value == 'true') if required is not None else True
168
169
170def extract_target_sdk_version(doc):
171 """Returns the targetSdkVersion from the manifest.
172
173 Args:
174 doc: The XML document.
175 Raises:
176 RuntimeError: invalid manifest
177 """
178
179 manifest = parse_manifest(doc)
180
181 # Get or insert the uses-sdk element
182 uses_sdk = get_children_with_tag(manifest, 'uses-sdk')
183 if len(uses_sdk) > 1:
184 raise RuntimeError('found multiple uses-sdk elements')
185 elif len(uses_sdk) == 0:
186 raise RuntimeError('missing uses-sdk element')
187
188 uses_sdk = uses_sdk[0]
189
190 min_attr = uses_sdk.getAttributeNodeNS(android_ns, 'minSdkVersion')
191 if min_attr is None:
192 raise RuntimeError('minSdkVersion is not specified')
193
194 target_attr = uses_sdk.getAttributeNodeNS(android_ns, 'targetSdkVersion')
195 if target_attr is None:
196 target_attr = min_attr
197
198 return target_attr.value
199
200
201def main():
202 """Program entry point."""
203 try:
204 args = parse_args()
205
206 doc = minidom.parse(args.input)
207
208 if args.enforce_uses_libraries:
Ulya Trafimovich8c35fcf2021-02-17 16:23:28 +0000209 # Check if the <uses-library> lists in the build system agree with those
210 # in the manifest. Raise an exception on mismatch, unless the script was
211 # passed a special parameter to suppress exceptions.
212 errmsg = enforce_uses_libraries(doc, args.uses_libraries,
213 args.optional_uses_libraries, args.enforce_uses_libraries_relax)
214
215 # Create a status file that is empty on success, or contains an error
216 # message on failure. When exceptions are suppressed, dexpreopt command
217 # command will check file size to determine if the check has failed.
218 if args.enforce_uses_libraries_status:
219 with open(args.enforce_uses_libraries_status, 'w') as f:
220 if not errmsg == None:
221 f.write("%s\n" % errmsg)
Colin Cross72119102019-05-20 13:14:18 -0700222
223 if args.extract_target_sdk_version:
224 print(extract_target_sdk_version(doc))
225
226 if args.output:
227 with open(args.output, 'wb') as f:
228 write_xml(f, doc)
229
230 # pylint: disable=broad-except
231 except Exception as err:
232 print('error: ' + str(err), file=sys.stderr)
233 sys.exit(-1)
234
235if __name__ == '__main__':
236 main()