blob: 51515678f2f90fed17b00db3dc41c57f97d95ec7 [file] [log] [blame]
Yifan Honge3ba82c2019-08-21 13:29:30 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2019 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"""
18Check VINTF compatibility from a target files package.
19
20Usage: check_target_files_vintf target_files
21
22target_files can be a ZIP file or an extracted target files directory.
23"""
24
25import logging
26import subprocess
27import sys
28import os
29import zipfile
30
31import common
32
33logger = logging.getLogger(__name__)
34
35OPTIONS = common.OPTIONS
36
37# Keys are paths that VINTF searches. Must keep in sync with libvintf's search
38# paths (VintfObject.cpp).
39# These paths are stored in different directories in target files package, so
40# we have to search for the correct path and tell checkvintf to remap them.
Yifan Hong2870d1e2019-12-19 13:58:00 -080041# Look for TARGET_COPY_OUT_* variables in board_config.mk for possible paths for
42# each partition.
Yifan Honge3ba82c2019-08-21 13:29:30 -070043DIR_SEARCH_PATHS = {
44 '/system': ('SYSTEM',),
45 '/vendor': ('VENDOR', 'SYSTEM/vendor'),
46 '/product': ('PRODUCT', 'SYSTEM/product'),
Yifan Hong2870d1e2019-12-19 13:58:00 -080047 '/odm': ('ODM', 'VENDOR/odm', 'SYSTEM/vendor/odm'),
Yifan Hong9cbb6242019-12-19 13:56:59 -080048 '/system_ext': ('SYSTEM_EXT', 'SYSTEM/system_ext'),
Yifan Hongc0f187f2020-08-10 16:48:52 -070049 # The following do not have VINTF files:
50 # - vendor_dlkm
51 # - odm_dlkm
52 # - modules
Yifan Honge3ba82c2019-08-21 13:29:30 -070053}
54
55UNZIP_PATTERN = ['META/*', '*/build.prop']
56
57
58def GetDirmap(input_tmp):
59 dirmap = {}
60 for device_path, target_files_rel_paths in DIR_SEARCH_PATHS.items():
61 for target_files_rel_path in target_files_rel_paths:
62 target_files_path = os.path.join(input_tmp, target_files_rel_path)
63 if os.path.isdir(target_files_path):
64 dirmap[device_path] = target_files_path
65 break
66 if device_path not in dirmap:
67 raise ValueError("Can't determine path for device path " + device_path +
68 ". Searched the following:" +
69 ("\n".join(target_files_rel_paths)))
70 return dirmap
71
72
73def GetArgsForSkus(info_dict):
Yifan Hong28ffd732020-03-13 13:11:10 -070074 odm_skus = info_dict.get('vintf_odm_manifest_skus', '').strip().split()
Yifan Hong69430e62020-03-17 15:18:34 -070075 if info_dict.get('vintf_include_empty_odm_sku', '') == "true" or not odm_skus:
Yifan Hong28ffd732020-03-13 13:11:10 -070076 odm_skus += ['']
Yifan Honge3ba82c2019-08-21 13:29:30 -070077
Yifan Hong28ffd732020-03-13 13:11:10 -070078 vendor_skus = info_dict.get('vintf_vendor_manifest_skus', '').strip().split()
Yifan Hong69430e62020-03-17 15:18:34 -070079 if info_dict.get('vintf_include_empty_vendor_sku', '') == "true" or \
80 not vendor_skus:
Yifan Hong28ffd732020-03-13 13:11:10 -070081 vendor_skus += ['']
82
83 return [['--property', 'ro.boot.product.hardware.sku=' + odm_sku,
84 '--property', 'ro.boot.product.vendor.sku=' + vendor_sku]
85 for odm_sku in odm_skus for vendor_sku in vendor_skus]
Yifan Honge3ba82c2019-08-21 13:29:30 -070086
Tianjie Xu0fde41e2020-05-09 05:24:18 +000087
Yifan Honge3ba82c2019-08-21 13:29:30 -070088def GetArgsForShippingApiLevel(info_dict):
Tianjie Xu0fde41e2020-05-09 05:24:18 +000089 shipping_api_level = info_dict['vendor.build.prop'].GetProp(
Yifan Honge3ba82c2019-08-21 13:29:30 -070090 'ro.product.first_api_level')
91 if not shipping_api_level:
92 logger.warning('Cannot determine ro.product.first_api_level')
93 return []
94 return ['--property', 'ro.product.first_api_level=' + shipping_api_level]
95
96
97def GetArgsForKernel(input_tmp):
98 version_path = os.path.join(input_tmp, 'META/kernel_version.txt')
99 config_path = os.path.join(input_tmp, 'META/kernel_configs.txt')
100
101 if not os.path.isfile(version_path) or not os.path.isfile(config_path):
Yifan Hong28ffd732020-03-13 13:11:10 -0700102 logger.info('Skipping kernel config checks because '
Yifan Honge3ba82c2019-08-21 13:29:30 -0700103 'PRODUCT_OTA_ENFORCE_VINTF_KERNEL_REQUIREMENTS is not set')
104 return []
105
106 with open(version_path) as f:
107 version = f.read().strip()
108
109 return ['--kernel', '{}:{}'.format(version, config_path)]
110
111
112def CheckVintfFromExtractedTargetFiles(input_tmp, info_dict=None):
113 """
114 Checks VINTF metadata of an extracted target files directory.
115
116 Args:
117 inp: path to the directory that contains the extracted target files archive.
118 info_dict: The build-time info dict. If None, it will be loaded from inp.
119
120 Returns:
121 True if VINTF check is skipped or compatible, False if incompatible. Raise
122 a RuntimeError if any error occurs.
123 """
124
125 if info_dict is None:
126 info_dict = common.LoadInfoDict(input_tmp)
127
128 if info_dict.get('vintf_enforce') != 'true':
129 logger.warning('PRODUCT_ENFORCE_VINTF_MANIFEST is not set, skipping checks')
130 return True
131
132 dirmap = GetDirmap(input_tmp)
133 args_for_skus = GetArgsForSkus(info_dict)
134 shipping_api_level_args = GetArgsForShippingApiLevel(info_dict)
135 kernel_args = GetArgsForKernel(input_tmp)
136
137 common_command = [
138 'checkvintf',
139 '--check-compat',
140 ]
141 for device_path, real_path in dirmap.items():
142 common_command += ['--dirmap', '{}:{}'.format(device_path, real_path)]
143 common_command += kernel_args
144 common_command += shipping_api_level_args
145
146 success = True
147 for sku_args in args_for_skus:
148 command = common_command + sku_args
149 proc = common.Run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
150 out, err = proc.communicate()
151 if proc.returncode == 0:
152 logger.info("Command `%s` returns 'compatible'", ' '.join(command))
153 elif out.strip() == "INCOMPATIBLE":
154 logger.info("Command `%s` returns 'incompatible'", ' '.join(command))
155 success = False
156 else:
157 raise common.ExternalError(
158 "Failed to run command '{}' (exit code {}):\nstdout:{}\nstderr:{}"
159 .format(' '.join(command), proc.returncode, out, err))
160 logger.info("stdout: %s", out)
161 logger.info("stderr: %s", err)
162
163 return success
164
165
166def GetVintfFileList():
167 """
168 Returns a list of VINTF metadata files that should be read from a target files
169 package before executing checkvintf.
170 """
171 def PathToPatterns(path):
172 if path[-1] == '/':
173 path += '*'
174 for device_path, target_files_rel_paths in DIR_SEARCH_PATHS.items():
175 if path.startswith(device_path):
176 suffix = path[len(device_path):]
177 return [rel_path + suffix for rel_path in target_files_rel_paths]
178 raise RuntimeError('Unrecognized path from checkvintf --dump-file-list: ' +
179 path)
180
181 out = common.RunAndCheckOutput(['checkvintf', '--dump-file-list'])
182 paths = out.strip().split('\n')
183 paths = sum((PathToPatterns(path) for path in paths if path), [])
184 return paths
185
186
187def CheckVintfFromTargetFiles(inp, info_dict=None):
188 """
189 Checks VINTF metadata of a target files zip.
190
191 Args:
192 inp: path to the target files archive.
193 info_dict: The build-time info dict. If None, it will be loaded from inp.
194
195 Returns:
196 True if VINTF check is skipped or compatible, False if incompatible. Raise
197 a RuntimeError if any error occurs.
198 """
199 input_tmp = common.UnzipTemp(inp, GetVintfFileList() + UNZIP_PATTERN)
200 return CheckVintfFromExtractedTargetFiles(input_tmp, info_dict)
201
202
203def CheckVintf(inp, info_dict=None):
204 """
205 Checks VINTF metadata of a target files zip or extracted target files
206 directory.
207
208 Args:
209 inp: path to the (possibly extracted) target files archive.
210 info_dict: The build-time info dict. If None, it will be loaded from inp.
211
212 Returns:
213 True if VINTF check is skipped or compatible, False if incompatible. Raise
214 a RuntimeError if any error occurs.
215 """
216 if os.path.isdir(inp):
217 logger.info('Checking VINTF compatibility extracted target files...')
218 return CheckVintfFromExtractedTargetFiles(inp, info_dict)
219
220 if zipfile.is_zipfile(inp):
221 logger.info('Checking VINTF compatibility target files...')
222 return CheckVintfFromTargetFiles(inp, info_dict)
223
224 raise ValueError('{} is not a valid directory or zip file'.format(inp))
225
Kelvin Zhangcff4d762020-07-29 16:37:51 -0400226def CheckVintfIfTrebleEnabled(target_files, target_info):
227 """Checks compatibility info of the input target files.
228
229 Metadata used for compatibility verification is retrieved from target_zip.
230
231 Compatibility should only be checked for devices that have enabled
232 Treble support.
233
234 Args:
235 target_files: Path to zip file containing the source files to be included
236 for OTA. Can also be the path to extracted directory.
237 target_info: The BuildInfo instance that holds the target build info.
238 """
239
240 # Will only proceed if the target has enabled the Treble support (as well as
241 # having a /vendor partition).
242 if not HasTrebleEnabled(target_files, target_info):
243 return
244
245 # Skip adding the compatibility package as a workaround for b/114240221. The
246 # compatibility will always fail on devices without qualified kernels.
247 if OPTIONS.skip_compatibility_check:
248 return
249
250 if not CheckVintf(target_files, target_info):
251 raise RuntimeError("VINTF compatibility check failed")
252
253def HasTrebleEnabled(target_files, target_info):
254 def HasVendorPartition(target_files):
255 if os.path.isdir(target_files):
256 return os.path.isdir(os.path.join(target_files, "VENDOR"))
257 if zipfile.is_zipfile(target_files):
258 return HasPartition(zipfile.ZipFile(target_files), "vendor")
259 raise ValueError("Unknown target_files argument")
260
261 return (HasVendorPartition(target_files) and
262 target_info.GetBuildProp("ro.treble.enabled") == "true")
263
264
265def HasPartition(target_files_zip, partition):
266 try:
267 target_files_zip.getinfo(partition.upper() + "/")
268 return True
269 except KeyError:
270 return False
271
Yifan Honge3ba82c2019-08-21 13:29:30 -0700272
273def main(argv):
274 args = common.ParseOptions(argv, __doc__)
275 if len(args) != 1:
276 common.Usage(__doc__)
277 sys.exit(1)
278 common.InitLogging()
279 if not CheckVintf(args[0]):
280 sys.exit(1)
281
282
283if __name__ == '__main__':
284 try:
285 common.CloseInheritedPipes()
286 main(sys.argv[1:])
287 except common.ExternalError:
288 logger.exception('\n ERROR:\n')
289 sys.exit(1)
290 finally:
291 common.Cleanup()