Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | """ |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 4 | This script is for comparing the size of the library files from two |
| 5 | different Git revisions within an Mbed TLS repository. |
| 6 | The results of the comparison is formatted as csv and stored at a |
| 7 | configurable location. |
| 8 | Note: must be run from Mbed TLS root. |
| 9 | """ |
| 10 | |
| 11 | # Copyright The Mbed TLS Contributors |
| 12 | # SPDX-License-Identifier: Apache-2.0 |
| 13 | # |
| 14 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 15 | # not use this file except in compliance with the License. |
| 16 | # You may obtain a copy of the License at |
| 17 | # |
| 18 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 19 | # |
| 20 | # Unless required by applicable law or agreed to in writing, software |
| 21 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 22 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 23 | # See the License for the specific language governing permissions and |
| 24 | # limitations under the License. |
| 25 | |
| 26 | import argparse |
| 27 | import os |
Yanray Wang | 16ebc57 | 2023-05-30 18:10:20 +0800 | [diff] [blame] | 28 | import re |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 29 | import subprocess |
| 30 | import sys |
Yanray Wang | 16ebc57 | 2023-05-30 18:10:20 +0800 | [diff] [blame] | 31 | import typing |
Yanray Wang | 23bd532 | 2023-05-24 11:03:59 +0800 | [diff] [blame] | 32 | from enum import Enum |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 33 | |
Yanray Wang | 16ebc57 | 2023-05-30 18:10:20 +0800 | [diff] [blame] | 34 | from mbedtls_dev import typing_util |
Gilles Peskine | d9071e7 | 2022-09-18 21:17:09 +0200 | [diff] [blame] | 35 | from mbedtls_dev import build_tree |
| 36 | |
Yanray Wang | 23bd532 | 2023-05-24 11:03:59 +0800 | [diff] [blame] | 37 | class SupportedArch(Enum): |
| 38 | """Supported architecture for code size measurement.""" |
| 39 | AARCH64 = 'aarch64' |
| 40 | AARCH32 = 'aarch32' |
Yanray Wang | aba7158 | 2023-05-29 16:45:56 +0800 | [diff] [blame] | 41 | ARMV8_M = 'armv8-m' |
Yanray Wang | 23bd532 | 2023-05-24 11:03:59 +0800 | [diff] [blame] | 42 | X86_64 = 'x86_64' |
| 43 | X86 = 'x86' |
| 44 | |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 45 | CONFIG_TFM_MEDIUM_MBEDCRYPTO_H = "../configs/tfm_mbedcrypto_config_profile_medium.h" |
| 46 | CONFIG_TFM_MEDIUM_PSA_CRYPTO_H = "../configs/crypto_config_profile_medium.h" |
| 47 | class SupportedConfig(Enum): |
| 48 | """Supported configuration for code size measurement.""" |
| 49 | DEFAULT = 'default' |
| 50 | TFM_MEDIUM = 'tfm-medium' |
| 51 | |
Yanray Wang | 16ebc57 | 2023-05-30 18:10:20 +0800 | [diff] [blame] | 52 | # Static library |
| 53 | MBEDTLS_STATIC_LIB = { |
| 54 | 'CRYPTO': 'library/libmbedcrypto.a', |
| 55 | 'X509': 'library/libmbedx509.a', |
| 56 | 'TLS': 'library/libmbedtls.a', |
| 57 | } |
| 58 | |
Yanray Wang | 23bd532 | 2023-05-24 11:03:59 +0800 | [diff] [blame] | 59 | DETECT_ARCH_CMD = "cc -dM -E - < /dev/null" |
| 60 | def detect_arch() -> str: |
| 61 | """Auto-detect host architecture.""" |
| 62 | cc_output = subprocess.check_output(DETECT_ARCH_CMD, shell=True).decode() |
| 63 | if "__aarch64__" in cc_output: |
| 64 | return SupportedArch.AARCH64.value |
| 65 | if "__arm__" in cc_output: |
| 66 | return SupportedArch.AARCH32.value |
| 67 | if "__x86_64__" in cc_output: |
| 68 | return SupportedArch.X86_64.value |
| 69 | if "__x86__" in cc_output: |
| 70 | return SupportedArch.X86.value |
| 71 | else: |
| 72 | print("Unknown host architecture, cannot auto-detect arch.") |
| 73 | sys.exit(1) |
Gilles Peskine | d9071e7 | 2022-09-18 21:17:09 +0200 | [diff] [blame] | 74 | |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 75 | class CodeSizeInfo: # pylint: disable=too-few-public-methods |
| 76 | """Gather information used to measure code size. |
| 77 | |
| 78 | It collects information about architecture, configuration in order to |
| 79 | infer build command for code size measurement. |
| 80 | """ |
| 81 | |
Yanray Wang | c18cd89 | 2023-05-31 11:08:04 +0800 | [diff] [blame] | 82 | SupportedArchConfig = [ |
| 83 | "-a " + SupportedArch.AARCH64.value + " -c " + SupportedConfig.DEFAULT.value, |
| 84 | "-a " + SupportedArch.AARCH32.value + " -c " + SupportedConfig.DEFAULT.value, |
| 85 | "-a " + SupportedArch.X86_64.value + " -c " + SupportedConfig.DEFAULT.value, |
| 86 | "-a " + SupportedArch.X86.value + " -c " + SupportedConfig.DEFAULT.value, |
| 87 | "-a " + SupportedArch.ARMV8_M.value + " -c " + SupportedConfig.TFM_MEDIUM.value, |
| 88 | ] |
| 89 | |
Yanray Wang | 21f1744 | 2023-06-01 11:29:06 +0800 | [diff] [blame] | 90 | def __init__(self, arch: str, config: str, sys_arch: str) -> None: |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 91 | """ |
| 92 | arch: architecture to measure code size on. |
| 93 | config: configuration type to measure code size with. |
Yanray Wang | 699a6c8 | 2023-07-04 17:21:28 +0800 | [diff] [blame^] | 94 | sys_arch: host architecture. |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 95 | make_command: command to build library (Inferred from arch and config). |
| 96 | """ |
| 97 | self.arch = arch |
| 98 | self.config = config |
Yanray Wang | 21f1744 | 2023-06-01 11:29:06 +0800 | [diff] [blame] | 99 | self.sys_arch = sys_arch |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 100 | self.make_command = self.set_make_command() |
| 101 | |
| 102 | def set_make_command(self) -> str: |
| 103 | """Infer build command based on architecture and configuration.""" |
| 104 | |
Yanray Wang | 21f1744 | 2023-06-01 11:29:06 +0800 | [diff] [blame] | 105 | if self.config == SupportedConfig.DEFAULT.value and \ |
| 106 | self.arch == self.sys_arch: |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 107 | return 'make -j lib CFLAGS=\'-Os \' ' |
Yanray Wang | aba7158 | 2023-05-29 16:45:56 +0800 | [diff] [blame] | 108 | elif self.arch == SupportedArch.ARMV8_M.value and \ |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 109 | self.config == SupportedConfig.TFM_MEDIUM.value: |
| 110 | return \ |
Yanray Wang | 60430bd | 2023-05-29 14:48:18 +0800 | [diff] [blame] | 111 | 'make -j lib CC=armclang \ |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 112 | CFLAGS=\'--target=arm-arm-none-eabi -mcpu=cortex-m33 -Os \ |
| 113 | -DMBEDTLS_CONFIG_FILE=\\\"' + CONFIG_TFM_MEDIUM_MBEDCRYPTO_H + '\\\" \ |
| 114 | -DMBEDTLS_PSA_CRYPTO_CONFIG_FILE=\\\"' + CONFIG_TFM_MEDIUM_PSA_CRYPTO_H + '\\\" \'' |
| 115 | else: |
Yanray Wang | 21f1744 | 2023-06-01 11:29:06 +0800 | [diff] [blame] | 116 | print("Unsupported combination of architecture: {} and configuration: {}" |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 117 | .format(self.arch, self.config)) |
Yanray Wang | c18cd89 | 2023-05-31 11:08:04 +0800 | [diff] [blame] | 118 | print("\nPlease use supported combination of architecture and configuration:") |
| 119 | for comb in CodeSizeInfo.SupportedArchConfig: |
| 120 | print(comb) |
Yanray Wang | 21f1744 | 2023-06-01 11:29:06 +0800 | [diff] [blame] | 121 | print("\nFor your system, please use:") |
| 122 | for comb in CodeSizeInfo.SupportedArchConfig: |
| 123 | if "default" in comb and self.sys_arch not in comb: |
| 124 | continue |
| 125 | print(comb) |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 126 | sys.exit(1) |
| 127 | |
Yanray Wang | 16ebc57 | 2023-05-30 18:10:20 +0800 | [diff] [blame] | 128 | class SizeEntry: # pylint: disable=too-few-public-methods |
| 129 | """Data Structure to only store information of code size.""" |
| 130 | def __init__(self, text, data, bss, dec): |
| 131 | self.text = text |
| 132 | self.data = data |
| 133 | self.bss = bss |
| 134 | self.total = dec # total <=> dec |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 135 | |
Yanray Wang | 16ebc57 | 2023-05-30 18:10:20 +0800 | [diff] [blame] | 136 | class CodeSizeBase: |
| 137 | """Code Size Base Class for size record saving and writing.""" |
| 138 | |
| 139 | def __init__(self) -> None: |
| 140 | """ Variable code_size is used to store size info for any revisions. |
| 141 | code_size: (data format) |
| 142 | {revision: {module: {file_name: SizeEntry, |
| 143 | etc ... |
| 144 | }, |
| 145 | etc ... |
| 146 | }, |
| 147 | etc ... |
| 148 | } |
| 149 | """ |
| 150 | self.code_size = {} #type: typing.Dict[str, typing.Dict] |
| 151 | |
| 152 | def set_size_record(self, revision: str, mod: str, size_text: str) -> None: |
| 153 | """Store size information for target revision and high-level module. |
| 154 | |
| 155 | size_text Format: text data bss dec hex filename |
| 156 | """ |
| 157 | size_record = {} |
| 158 | for line in size_text.splitlines()[1:]: |
| 159 | data = line.split() |
| 160 | size_record[data[5]] = SizeEntry(data[0], data[1], data[2], data[3]) |
| 161 | if revision in self.code_size: |
| 162 | self.code_size[revision].update({mod: size_record}) |
| 163 | else: |
| 164 | self.code_size[revision] = {mod: size_record} |
| 165 | |
| 166 | def read_size_record(self, revision: str, fname: str) -> None: |
| 167 | """Read size information from csv file and write it into code_size. |
| 168 | |
| 169 | fname Format: filename text data bss dec |
| 170 | """ |
| 171 | mod = "" |
| 172 | size_record = {} |
| 173 | with open(fname, 'r') as csv_file: |
| 174 | for line in csv_file: |
| 175 | data = line.strip().split() |
| 176 | # check if we find the beginning of a module |
| 177 | if data and data[0] in MBEDTLS_STATIC_LIB: |
| 178 | mod = data[0] |
| 179 | continue |
| 180 | |
| 181 | if mod: |
| 182 | size_record[data[0]] = \ |
| 183 | SizeEntry(data[1], data[2], data[3], data[4]) |
| 184 | |
| 185 | # check if we hit record for the end of a module |
| 186 | m = re.match(r'.?TOTALS', line) |
| 187 | if m: |
| 188 | if revision in self.code_size: |
| 189 | self.code_size[revision].update({mod: size_record}) |
| 190 | else: |
| 191 | self.code_size[revision] = {mod: size_record} |
| 192 | mod = "" |
| 193 | size_record = {} |
| 194 | |
| 195 | def _size_reader_helper( |
| 196 | self, |
| 197 | revision: str, |
| 198 | output: typing_util.Writable |
| 199 | ) -> typing.Iterator[tuple]: |
| 200 | """A helper function to peel code_size based on revision.""" |
| 201 | for mod, file_size in self.code_size[revision].items(): |
| 202 | output.write("\n" + mod + "\n") |
| 203 | for fname, size_entry in file_size.items(): |
| 204 | yield mod, fname, size_entry |
| 205 | |
| 206 | def write_size_record( |
| 207 | self, |
| 208 | revision: str, |
| 209 | output: typing_util.Writable |
| 210 | ) -> None: |
| 211 | """Write size information to a file. |
| 212 | |
| 213 | Writing Format: file_name text data bss total(dec) |
| 214 | """ |
| 215 | output.write("{:<30} {:>7} {:>7} {:>7} {:>7}\n" |
| 216 | .format("filename", "text", "data", "bss", "total")) |
| 217 | for _, fname, size_entry in self._size_reader_helper(revision, output): |
| 218 | output.write("{:<30} {:>7} {:>7} {:>7} {:>7}\n" |
| 219 | .format(fname, size_entry.text, size_entry.data,\ |
| 220 | size_entry.bss, size_entry.total)) |
| 221 | |
| 222 | def write_comparison( |
| 223 | self, |
| 224 | old_rev: str, |
| 225 | new_rev: str, |
| 226 | output: typing_util.Writable |
| 227 | ) -> None: |
| 228 | """Write comparison result into a file. |
| 229 | |
| 230 | Writing Format: file_name current(total) old(total) change(Byte) change_pct(%) |
| 231 | """ |
| 232 | output.write("{:<30} {:>7} {:>7} {:>7} {:>7}\n" |
| 233 | .format("filename", "current", "old", "change", "change%")) |
| 234 | for mod, fname, size_entry in self._size_reader_helper(new_rev, output): |
| 235 | new_size = int(size_entry.total) |
| 236 | # check if we have the file in old revision |
| 237 | if fname in self.code_size[old_rev][mod]: |
| 238 | old_size = int(self.code_size[old_rev][mod][fname].total) |
| 239 | change = new_size - old_size |
| 240 | if old_size != 0: |
| 241 | change_pct = change / old_size |
| 242 | else: |
| 243 | change_pct = 0 |
| 244 | output.write("{:<30} {:>7} {:>7} {:>7} {:>7.2%}\n" |
| 245 | .format(fname, new_size, old_size, change, change_pct)) |
| 246 | else: |
| 247 | output.write("{} {}\n".format(fname, new_size)) |
| 248 | |
| 249 | |
| 250 | class CodeSizeComparison(CodeSizeBase): |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 251 | """Compare code size between two Git revisions.""" |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 252 | |
Yanray Wang | 72b105f | 2023-05-31 15:20:39 +0800 | [diff] [blame] | 253 | def __init__( |
| 254 | self, |
| 255 | old_revision: str, |
| 256 | new_revision: str, |
| 257 | result_dir: str, |
| 258 | code_size_info: CodeSizeInfo |
| 259 | ) -> None: |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 260 | """ |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 261 | old_revision: revision to compare against. |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 262 | new_revision: |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 263 | result_dir: directory for comparison result. |
| 264 | code_size_info: an object containing information to build library. |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 265 | """ |
Yanray Wang | 8804db9 | 2023-05-30 18:18:18 +0800 | [diff] [blame] | 266 | super().__init__() |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 267 | self.repo_path = "." |
| 268 | self.result_dir = os.path.abspath(result_dir) |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 269 | os.makedirs(self.result_dir, exist_ok=True) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 270 | |
| 271 | self.csv_dir = os.path.abspath("code_size_records/") |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 272 | os.makedirs(self.csv_dir, exist_ok=True) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 273 | |
| 274 | self.old_rev = old_revision |
| 275 | self.new_rev = new_revision |
| 276 | self.git_command = "git" |
Yanray Wang | 4c26db0 | 2023-07-04 16:49:04 +0800 | [diff] [blame] | 277 | self.make_clean = 'make clean' |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 278 | self.make_command = code_size_info.make_command |
Yanray Wang | 369cd96 | 2023-05-24 17:13:29 +0800 | [diff] [blame] | 279 | self.fname_suffix = "-" + code_size_info.arch + "-" +\ |
| 280 | code_size_info.config |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 281 | |
| 282 | @staticmethod |
Yanray Wang | 72b105f | 2023-05-31 15:20:39 +0800 | [diff] [blame] | 283 | def validate_revision(revision: str) -> bytes: |
Xiaofei Bai | ccd738b | 2021-11-03 07:12:31 +0000 | [diff] [blame] | 284 | result = subprocess.check_output(["git", "rev-parse", "--verify", |
| 285 | revision + "^{commit}"], shell=False) |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 286 | return result |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 287 | |
Yanray Wang | 72b105f | 2023-05-31 15:20:39 +0800 | [diff] [blame] | 288 | def _create_git_worktree(self, revision: str) -> str: |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 289 | """Make a separate worktree for revision. |
| 290 | Do not modify the current worktree.""" |
| 291 | |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 292 | if revision == "current": |
Yanray Wang | c7a2a6d | 2023-05-31 15:47:25 +0800 | [diff] [blame] | 293 | print("Using current work directory") |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 294 | git_worktree_path = self.repo_path |
| 295 | else: |
| 296 | print("Creating git worktree for", revision) |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 297 | git_worktree_path = os.path.join(self.repo_path, "temp-" + revision) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 298 | subprocess.check_output( |
| 299 | [self.git_command, "worktree", "add", "--detach", |
| 300 | git_worktree_path, revision], cwd=self.repo_path, |
| 301 | stderr=subprocess.STDOUT |
| 302 | ) |
Aditya Deshpande | 41a0aad | 2023-04-13 16:32:21 +0100 | [diff] [blame] | 303 | |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 304 | return git_worktree_path |
| 305 | |
Yanray Wang | 72b105f | 2023-05-31 15:20:39 +0800 | [diff] [blame] | 306 | def _build_libraries(self, git_worktree_path: str) -> None: |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 307 | """Build libraries in the specified worktree.""" |
| 308 | |
| 309 | my_environment = os.environ.copy() |
Aditya Deshpande | 41a0aad | 2023-04-13 16:32:21 +0100 | [diff] [blame] | 310 | try: |
| 311 | subprocess.check_output( |
Yanray Wang | 4c26db0 | 2023-07-04 16:49:04 +0800 | [diff] [blame] | 312 | self.make_clean, env=my_environment, shell=True, |
| 313 | cwd=git_worktree_path, stderr=subprocess.STDOUT, |
| 314 | ) |
| 315 | subprocess.check_output( |
Aditya Deshpande | 41a0aad | 2023-04-13 16:32:21 +0100 | [diff] [blame] | 316 | self.make_command, env=my_environment, shell=True, |
| 317 | cwd=git_worktree_path, stderr=subprocess.STDOUT, |
| 318 | ) |
| 319 | except subprocess.CalledProcessError as e: |
| 320 | self._handle_called_process_error(e, git_worktree_path) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 321 | |
Yanray Wang | 72b105f | 2023-05-31 15:20:39 +0800 | [diff] [blame] | 322 | def _gen_code_size_csv(self, revision: str, git_worktree_path: str) -> None: |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 323 | """Generate code size csv file.""" |
| 324 | |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 325 | if revision == "current": |
Yanray Wang | c7a2a6d | 2023-05-31 15:47:25 +0800 | [diff] [blame] | 326 | print("Measuring code size in current work directory") |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 327 | else: |
| 328 | print("Measuring code size for", revision) |
Yanray Wang | 8804db9 | 2023-05-30 18:18:18 +0800 | [diff] [blame] | 329 | |
| 330 | for mod, st_lib in MBEDTLS_STATIC_LIB.items(): |
| 331 | try: |
| 332 | result = subprocess.check_output( |
| 333 | ["size", st_lib, "-t"], cwd=git_worktree_path |
| 334 | ) |
| 335 | except subprocess.CalledProcessError as e: |
| 336 | self._handle_called_process_error(e, git_worktree_path) |
| 337 | size_text = result.decode("utf-8") |
| 338 | |
| 339 | self.set_size_record(revision, mod, size_text) |
| 340 | |
| 341 | print("Generating code size csv for", revision) |
| 342 | csv_file = open(os.path.join(self.csv_dir, revision + |
| 343 | self.fname_suffix + ".csv"), "w") |
| 344 | self.write_size_record(revision, csv_file) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 345 | |
Yanray Wang | 72b105f | 2023-05-31 15:20:39 +0800 | [diff] [blame] | 346 | def _remove_worktree(self, git_worktree_path: str) -> None: |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 347 | """Remove temporary worktree.""" |
| 348 | if git_worktree_path != self.repo_path: |
| 349 | print("Removing temporary worktree", git_worktree_path) |
| 350 | subprocess.check_output( |
| 351 | [self.git_command, "worktree", "remove", "--force", |
| 352 | git_worktree_path], cwd=self.repo_path, |
| 353 | stderr=subprocess.STDOUT |
| 354 | ) |
| 355 | |
Yanray Wang | 72b105f | 2023-05-31 15:20:39 +0800 | [diff] [blame] | 356 | def _get_code_size_for_rev(self, revision: str) -> None: |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 357 | """Generate code size csv file for the specified git revision.""" |
| 358 | |
| 359 | # Check if the corresponding record exists |
Yanray Wang | 369cd96 | 2023-05-24 17:13:29 +0800 | [diff] [blame] | 360 | csv_fname = revision + self.fname_suffix + ".csv" |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 361 | if (revision != "current") and \ |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 362 | os.path.exists(os.path.join(self.csv_dir, csv_fname)): |
| 363 | print("Code size csv file for", revision, "already exists.") |
Yanray Wang | 8804db9 | 2023-05-30 18:18:18 +0800 | [diff] [blame] | 364 | self.read_size_record(revision, os.path.join(self.csv_dir, csv_fname)) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 365 | else: |
| 366 | git_worktree_path = self._create_git_worktree(revision) |
| 367 | self._build_libraries(git_worktree_path) |
| 368 | self._gen_code_size_csv(revision, git_worktree_path) |
| 369 | self._remove_worktree(git_worktree_path) |
| 370 | |
Yanray Wang | 72b105f | 2023-05-31 15:20:39 +0800 | [diff] [blame] | 371 | def _gen_code_size_comparison(self) -> int: |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 372 | """Generate results of the size changes between two revisions, |
| 373 | old and new. Measured code size results of these two revisions |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 374 | must be available.""" |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 375 | |
Yanray Wang | 369cd96 | 2023-05-24 17:13:29 +0800 | [diff] [blame] | 376 | res_file = open(os.path.join(self.result_dir, "compare-" + |
| 377 | self.old_rev + "-" + self.new_rev + |
| 378 | self.fname_suffix + |
| 379 | ".csv"), "w") |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 380 | |
Yanray Wang | c7a2a6d | 2023-05-31 15:47:25 +0800 | [diff] [blame] | 381 | print("\nGenerating comparison results between",\ |
| 382 | self.old_rev, "and", self.new_rev) |
Yanray Wang | 8804db9 | 2023-05-30 18:18:18 +0800 | [diff] [blame] | 383 | self.write_comparison(self.old_rev, self.new_rev, res_file) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 384 | |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 385 | return 0 |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 386 | |
Yanray Wang | 72b105f | 2023-05-31 15:20:39 +0800 | [diff] [blame] | 387 | def get_comparision_results(self) -> int: |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 388 | """Compare size of library/*.o between self.old_rev and self.new_rev, |
| 389 | and generate the result file.""" |
Gilles Peskine | d9071e7 | 2022-09-18 21:17:09 +0200 | [diff] [blame] | 390 | build_tree.check_repo_path() |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 391 | self._get_code_size_for_rev(self.old_rev) |
| 392 | self._get_code_size_for_rev(self.new_rev) |
Yanray Wang | 8804db9 | 2023-05-30 18:18:18 +0800 | [diff] [blame] | 393 | return self._gen_code_size_comparison() |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 394 | |
Aditya Deshpande | 41a0aad | 2023-04-13 16:32:21 +0100 | [diff] [blame] | 395 | def _handle_called_process_error(self, e: subprocess.CalledProcessError, |
Yanray Wang | 72b105f | 2023-05-31 15:20:39 +0800 | [diff] [blame] | 396 | git_worktree_path: str) -> None: |
Aditya Deshpande | 41a0aad | 2023-04-13 16:32:21 +0100 | [diff] [blame] | 397 | """Handle a CalledProcessError and quit the program gracefully. |
| 398 | Remove any extra worktrees so that the script may be called again.""" |
| 399 | |
| 400 | # Tell the user what went wrong |
| 401 | print("The following command: {} failed and exited with code {}" |
| 402 | .format(e.cmd, e.returncode)) |
| 403 | print("Process output:\n {}".format(str(e.output, "utf-8"))) |
| 404 | |
| 405 | # Quit gracefully by removing the existing worktree |
| 406 | self._remove_worktree(git_worktree_path) |
| 407 | sys.exit(-1) |
| 408 | |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 409 | def main(): |
Yanray Wang | 502c54f | 2023-05-31 11:41:36 +0800 | [diff] [blame] | 410 | parser = argparse.ArgumentParser(description=(__doc__)) |
| 411 | group_required = parser.add_argument_group( |
| 412 | 'required arguments', |
| 413 | 'required arguments to parse for running ' + os.path.basename(__file__)) |
| 414 | group_required.add_argument( |
| 415 | "-o", "--old-rev", type=str, required=True, |
| 416 | help="old revision for comparison.") |
| 417 | |
| 418 | group_optional = parser.add_argument_group( |
| 419 | 'optional arguments', |
| 420 | 'optional arguments to parse for running ' + os.path.basename(__file__)) |
| 421 | group_optional.add_argument( |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 422 | "-r", "--result-dir", type=str, default="comparison", |
| 423 | help="directory where comparison result is stored, \ |
Yanray Wang | 502c54f | 2023-05-31 11:41:36 +0800 | [diff] [blame] | 424 | default is comparison") |
| 425 | group_optional.add_argument( |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 426 | "-n", "--new-rev", type=str, default=None, |
| 427 | help="new revision for comparison, default is the current work \ |
Yanray Wang | 502c54f | 2023-05-31 11:41:36 +0800 | [diff] [blame] | 428 | directory, including uncommitted changes.") |
| 429 | group_optional.add_argument( |
Yanray Wang | 23bd532 | 2023-05-24 11:03:59 +0800 | [diff] [blame] | 430 | "-a", "--arch", type=str, default=detect_arch(), |
| 431 | choices=list(map(lambda s: s.value, SupportedArch)), |
| 432 | help="specify architecture for code size comparison, default is the\ |
Yanray Wang | 502c54f | 2023-05-31 11:41:36 +0800 | [diff] [blame] | 433 | host architecture.") |
| 434 | group_optional.add_argument( |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 435 | "-c", "--config", type=str, default=SupportedConfig.DEFAULT.value, |
| 436 | choices=list(map(lambda s: s.value, SupportedConfig)), |
| 437 | help="specify configuration type for code size comparison,\ |
Yanray Wang | 502c54f | 2023-05-31 11:41:36 +0800 | [diff] [blame] | 438 | default is the current MbedTLS configuration.") |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 439 | comp_args = parser.parse_args() |
| 440 | |
| 441 | if os.path.isfile(comp_args.result_dir): |
| 442 | print("Error: {} is not a directory".format(comp_args.result_dir)) |
| 443 | parser.exit() |
| 444 | |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 445 | validate_res = CodeSizeComparison.validate_revision(comp_args.old_rev) |
Xiaofei Bai | ccd738b | 2021-11-03 07:12:31 +0000 | [diff] [blame] | 446 | old_revision = validate_res.decode().replace("\n", "") |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 447 | |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 448 | if comp_args.new_rev is not None: |
| 449 | validate_res = CodeSizeComparison.validate_revision(comp_args.new_rev) |
Xiaofei Bai | ccd738b | 2021-11-03 07:12:31 +0000 | [diff] [blame] | 450 | new_revision = validate_res.decode().replace("\n", "") |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 451 | else: |
| 452 | new_revision = "current" |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 453 | |
Yanray Wang | 21f1744 | 2023-06-01 11:29:06 +0800 | [diff] [blame] | 454 | code_size_info = CodeSizeInfo(comp_args.arch, comp_args.config, |
| 455 | detect_arch()) |
Yanray Wang | c7a2a6d | 2023-05-31 15:47:25 +0800 | [diff] [blame] | 456 | print("Measure code size for architecture: {}, configuration: {}\n" |
Yanray Wang | aba7158 | 2023-05-29 16:45:56 +0800 | [diff] [blame] | 457 | .format(code_size_info.arch, code_size_info.config)) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 458 | result_dir = comp_args.result_dir |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 459 | size_compare = CodeSizeComparison(old_revision, new_revision, result_dir, |
| 460 | code_size_info) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 461 | return_code = size_compare.get_comparision_results() |
| 462 | sys.exit(return_code) |
| 463 | |
| 464 | |
| 465 | if __name__ == "__main__": |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 466 | main() |