1#!/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 dynamic partition sizes. 19 20usage: check_partition_sizes [info.txt] 21 22Check dump-super-partitions-info procedure for expected keys in info.txt. In 23addition, *_image (e.g. system_image, vendor_image, etc.) must be defined for 24each partition in dynamic_partition_list. 25 26Exit code is 0 if successful and non-zero if any failures. 27""" 28 29from __future__ import print_function 30 31import logging 32import sys 33 34import common 35import sparse_img 36 37if sys.hexversion < 0x02070000: 38 print("Python 2.7 or newer is required.", file=sys.stderr) 39 sys.exit(1) 40 41logger = logging.getLogger(__name__) 42 43 44class Expression(object): 45 def __init__(self, desc, expr, value=None): 46 # Human-readable description 47 self.desc = str(desc) 48 # Numeric expression 49 self.expr = str(expr) 50 # Value of expression 51 self.value = int(expr) if value is None else value 52 53 def CheckLe(self, other, level=logging.ERROR): 54 format_args = (self.desc, other.desc, self.expr, self.value, 55 other.expr, other.value) 56 if self.value <= other.value: 57 logger.info("%s is less than or equal to %s:\n%s == %d <= %s == %d", 58 *format_args) 59 else: 60 msg = "{} is greater than {}:\n{} == {} > {} == {}".format(*format_args) 61 if "SOONG_RUSTC_INCREMENTAL" in os.environ: 62 msg = ("If setting \"SOONG_RUSTC_INCREMENTAL\" try building without it. " 63 + msg) 64 if level == logging.ERROR: 65 raise RuntimeError(msg) 66 else: 67 logger.log(level, msg) 68 69 def CheckLt(self, other, level=logging.ERROR): 70 format_args = (self.desc, other.desc, self.expr, self.value, 71 other.expr, other.value) 72 if self.value < other.value: 73 logger.info("%s is less than %s:\n%s == %d < %s == %d", 74 *format_args) 75 else: 76 msg = "{} is greater than or equal to {}:\n{} == {} >= {} == {}".format( 77 *format_args) 78 if level == logging.ERROR: 79 raise RuntimeError(msg) 80 else: 81 logger.log(level, msg) 82 83 def CheckEq(self, other): 84 format_args = (self.desc, other.desc, self.expr, self.value, 85 other.expr, other.value) 86 if self.value == other.value: 87 logger.info("%s equals %s:\n%s == %d == %s == %d", *format_args) 88 else: 89 raise RuntimeError("{} does not equal {}:\n{} == {} != {} == {}".format( 90 *format_args)) 91 92 93# A/B feature flags 94class DeviceType(object): 95 NONE = 0 96 AB = 1 97 RVAB = 2 # retrofit Virtual-A/B 98 VAB = 3 99 100 @staticmethod 101 def Get(info_dict): 102 if info_dict.get("ab_update") != "true": 103 return DeviceType.NONE 104 if info_dict.get("virtual_ab_retrofit") == "true": 105 return DeviceType.RVAB 106 if info_dict.get("virtual_ab") == "true": 107 return DeviceType.VAB 108 return DeviceType.AB 109 110 111# Dynamic partition feature flags 112class Dap(object): 113 NONE = 0 114 RDAP = 1 115 DAP = 2 116 117 @staticmethod 118 def Get(info_dict): 119 if info_dict.get("use_dynamic_partitions") != "true": 120 return Dap.NONE 121 if info_dict.get("dynamic_partition_retrofit") == "true": 122 return Dap.RDAP 123 return Dap.DAP 124 125 126class DynamicPartitionSizeChecker(object): 127 def __init__(self, info_dict): 128 if "super_partition_size" in info_dict: 129 if "super_partition_warn_limit" not in info_dict: 130 info_dict["super_partition_warn_limit"] = \ 131 int(info_dict["super_partition_size"]) * 95 // 100 132 if "super_partition_error_limit" not in info_dict: 133 info_dict["super_partition_error_limit"] = \ 134 int(info_dict["super_partition_size"]) 135 self.info_dict = info_dict 136 137 def _ReadSizeOfPartition(self, name): 138 # Tests uses *_image_size instead (to avoid creating empty sparse images 139 # on disk) 140 if name + "_image_size" in self.info_dict: 141 return int(self.info_dict[name + "_image_size"]) 142 return sparse_img.GetImagePartitionSize(self.info_dict[name + "_image"]) 143 144 # Round result to BOARD_SUPER_PARTITION_ALIGNMENT 145 def _RoundPartitionSize(self, size): 146 alignment = self.info_dict.get("super_partition_alignment") 147 if alignment is None: 148 return size 149 return (size + alignment - 1) // alignment * alignment 150 151 def _CheckSuperPartitionSize(self): 152 info_dict = self.info_dict 153 super_block_devices = \ 154 info_dict.get("super_block_devices", "").strip().split() 155 size_list = [int(info_dict.get("super_{}_device_size".format(b), "0")) 156 for b in super_block_devices] 157 sum_size = Expression("sum of super partition block device sizes", 158 "+".join(str(size) for size in size_list), 159 sum(size_list)) 160 super_partition_size = Expression("BOARD_SUPER_PARTITION_SIZE", 161 info_dict["super_partition_size"]) 162 sum_size.CheckEq(super_partition_size) 163 164 def _CheckSumOfPartitionSizes(self, max_size, partition_names, 165 warn_size=None, error_size=None): 166 partition_size_list = [self._RoundPartitionSize( 167 self._ReadSizeOfPartition(p)) for p in partition_names] 168 sum_size = Expression("sum of sizes of {}".format(partition_names), 169 "+".join(str(size) for size in partition_size_list), 170 sum(partition_size_list)) 171 sum_size.CheckLe(max_size) 172 if error_size: 173 sum_size.CheckLe(error_size) 174 if warn_size: 175 sum_size.CheckLe(warn_size, level=logging.WARNING) 176 177 def _NumDeviceTypesInSuper(self): 178 slot = DeviceType.Get(self.info_dict) 179 dap = Dap.Get(self.info_dict) 180 181 if dap == Dap.NONE: 182 raise RuntimeError("check_partition_sizes should only be executed on " 183 "builds with dynamic partitions enabled") 184 185 # Retrofit dynamic partitions: 1 slot per "super", 2 "super"s on the device 186 if dap == Dap.RDAP: 187 if slot != DeviceType.AB: 188 raise RuntimeError("Device with retrofit dynamic partitions must use " 189 "regular (non-Virtual) A/B") 190 return 1 191 192 # Launch DAP: 1 super on the device 193 assert dap == Dap.DAP 194 195 # DAP + A/B: 2 slots in super 196 if slot == DeviceType.AB: 197 return 2 198 199 # DAP + retrofit Virtual A/B: same as A/B 200 if slot == DeviceType.RVAB: 201 return 2 202 203 # DAP + Launch Virtual A/B: 1 *real* slot in super (2 virtual slots) 204 if slot == DeviceType.VAB: 205 return 1 206 207 # DAP + non-A/B: 1 slot in super 208 assert slot == DeviceType.NONE 209 return 1 210 211 def _CheckAllPartitionSizes(self): 212 info_dict = self.info_dict 213 num_slots = self._NumDeviceTypesInSuper() 214 size_limit_suffix = (" / %d" % num_slots) if num_slots > 1 else "" 215 216 # Check sum(all partitions) <= super partition (/ 2 for A/B devices launched 217 # with dynamic partitions) 218 if "super_partition_size" in info_dict and \ 219 "dynamic_partition_list" in info_dict: 220 max_size = Expression( 221 "BOARD_SUPER_PARTITION_SIZE{}".format(size_limit_suffix), 222 int(info_dict["super_partition_size"]) // num_slots) 223 warn_limit = Expression( 224 "BOARD_SUPER_PARTITION_WARN_LIMIT{}".format(size_limit_suffix), 225 int(info_dict["super_partition_warn_limit"]) // num_slots) 226 error_limit = Expression( 227 "BOARD_SUPER_PARTITION_ERROR_LIMIT{}".format(size_limit_suffix), 228 int(info_dict["super_partition_error_limit"]) // num_slots) 229 partitions_in_super = info_dict["dynamic_partition_list"].strip().split() 230 # In the vab case, factory OTA will allocate space on super to install 231 # the system_other partition. So add system_other to the partition list. 232 if DeviceType.Get(self.info_dict) == DeviceType.VAB and ( 233 "system_other_image" in info_dict or 234 "system_other_image_size" in info_dict): 235 partitions_in_super.append("system_other") 236 self._CheckSumOfPartitionSizes(max_size, partitions_in_super, 237 warn_limit, error_limit) 238 239 groups = info_dict.get("super_partition_groups", "").strip().split() 240 241 # For each group, check sum(partitions in group) <= group size 242 for group in groups: 243 if "super_{}_group_size".format(group) in info_dict and \ 244 "super_{}_partition_list".format(group) in info_dict: 245 group_size = Expression( 246 "BOARD_{}_SIZE".format(group), 247 int(info_dict["super_{}_group_size".format(group)])) 248 self._CheckSumOfPartitionSizes( 249 group_size, 250 info_dict["super_{}_partition_list".format(group)].strip().split()) 251 252 # Check sum(all group sizes) <= super partition (/ 2 for A/B devices 253 # launched with dynamic partitions) 254 if "super_partition_size" in info_dict: 255 group_size_list = [int(info_dict.get( 256 "super_{}_group_size".format(group), 0)) for group in groups] 257 sum_size = Expression("sum of sizes of {}".format(groups), 258 "+".join(str(size) for size in group_size_list), 259 sum(group_size_list)) 260 max_size = Expression( 261 "BOARD_SUPER_PARTITION_SIZE{}".format(size_limit_suffix), 262 int(info_dict["super_partition_size"]) // num_slots) 263 # Retrofit DAP will build metadata as part of super image. 264 if Dap.Get(info_dict) == Dap.RDAP: 265 sum_size.CheckLe(max_size) 266 return 267 268 sum_size.CheckLt(max_size) 269 # Display a warning if group size + 1M >= super size 270 minimal_metadata_size = 1024 * 1024 # 1MiB 271 sum_size_plus_metadata = Expression( 272 "sum of sizes of {} plus 1M metadata".format(groups), 273 "+".join(str(size) for size in 274 group_size_list + [minimal_metadata_size]), 275 sum(group_size_list) + minimal_metadata_size) 276 sum_size_plus_metadata.CheckLe(max_size, level=logging.WARNING) 277 278 def Run(self): 279 self._CheckAllPartitionSizes() 280 if self.info_dict.get("dynamic_partition_retrofit") == "true": 281 self._CheckSuperPartitionSize() 282 283 284def CheckPartitionSizes(inp): 285 if isinstance(inp, str): 286 info_dict = common.LoadDictionaryFromFile(inp) 287 return DynamicPartitionSizeChecker(info_dict).Run() 288 if isinstance(inp, dict): 289 return DynamicPartitionSizeChecker(inp).Run() 290 raise ValueError("{} is not a dictionary or a valid path".format(inp)) 291 292 293def main(argv): 294 args = common.ParseOptions(argv, __doc__) 295 if len(args) != 1: 296 common.Usage(__doc__) 297 sys.exit(1) 298 common.InitLogging() 299 CheckPartitionSizes(args[0]) 300 301 302if __name__ == "__main__": 303 try: 304 common.CloseInheritedPipes() 305 main(sys.argv[1:]) 306 finally: 307 common.Cleanup() 308