Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | """ |
| 4 | Purpose |
| 5 | |
| 6 | This script is for comparing the size of the library files from two |
| 7 | different Git revisions within an Mbed TLS repository. |
| 8 | The results of the comparison is formatted as csv and stored at a |
| 9 | configurable location. |
| 10 | Note: must be run from Mbed TLS root. |
| 11 | """ |
| 12 | |
| 13 | # Copyright The Mbed TLS Contributors |
| 14 | # SPDX-License-Identifier: Apache-2.0 |
| 15 | # |
| 16 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 17 | # not use this file except in compliance with the License. |
| 18 | # You may obtain a copy of the License at |
| 19 | # |
| 20 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 21 | # |
| 22 | # Unless required by applicable law or agreed to in writing, software |
| 23 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 24 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 25 | # See the License for the specific language governing permissions and |
| 26 | # limitations under the License. |
| 27 | |
| 28 | import argparse |
| 29 | import os |
| 30 | import subprocess |
| 31 | import sys |
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 | |
Gilles Peskine | d9071e7 | 2022-09-18 21:17:09 +0200 | [diff] [blame] | 34 | from mbedtls_dev import build_tree |
| 35 | |
Yanray Wang | 23bd532 | 2023-05-24 11:03:59 +0800 | [diff] [blame] | 36 | class SupportedArch(Enum): |
| 37 | """Supported architecture for code size measurement.""" |
| 38 | AARCH64 = 'aarch64' |
| 39 | AARCH32 = 'aarch32' |
| 40 | X86_64 = 'x86_64' |
| 41 | X86 = 'x86' |
| 42 | |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 43 | CONFIG_TFM_MEDIUM_MBEDCRYPTO_H = "../configs/tfm_mbedcrypto_config_profile_medium.h" |
| 44 | CONFIG_TFM_MEDIUM_PSA_CRYPTO_H = "../configs/crypto_config_profile_medium.h" |
| 45 | class SupportedConfig(Enum): |
| 46 | """Supported configuration for code size measurement.""" |
| 47 | DEFAULT = 'default' |
| 48 | TFM_MEDIUM = 'tfm-medium' |
| 49 | |
Yanray Wang | 23bd532 | 2023-05-24 11:03:59 +0800 | [diff] [blame] | 50 | DETECT_ARCH_CMD = "cc -dM -E - < /dev/null" |
| 51 | def detect_arch() -> str: |
| 52 | """Auto-detect host architecture.""" |
| 53 | cc_output = subprocess.check_output(DETECT_ARCH_CMD, shell=True).decode() |
| 54 | if "__aarch64__" in cc_output: |
| 55 | return SupportedArch.AARCH64.value |
| 56 | if "__arm__" in cc_output: |
| 57 | return SupportedArch.AARCH32.value |
| 58 | if "__x86_64__" in cc_output: |
| 59 | return SupportedArch.X86_64.value |
| 60 | if "__x86__" in cc_output: |
| 61 | return SupportedArch.X86.value |
| 62 | else: |
| 63 | print("Unknown host architecture, cannot auto-detect arch.") |
| 64 | sys.exit(1) |
Gilles Peskine | d9071e7 | 2022-09-18 21:17:09 +0200 | [diff] [blame] | 65 | |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 66 | class CodeSizeInfo: # pylint: disable=too-few-public-methods |
| 67 | """Gather information used to measure code size. |
| 68 | |
| 69 | It collects information about architecture, configuration in order to |
| 70 | infer build command for code size measurement. |
| 71 | """ |
| 72 | |
| 73 | def __init__(self, arch: str, config: str) -> None: |
| 74 | """ |
| 75 | arch: architecture to measure code size on. |
| 76 | config: configuration type to measure code size with. |
| 77 | make_command: command to build library (Inferred from arch and config). |
| 78 | """ |
| 79 | self.arch = arch |
| 80 | self.config = config |
| 81 | self.make_command = self.set_make_command() |
| 82 | |
| 83 | def set_make_command(self) -> str: |
| 84 | """Infer build command based on architecture and configuration.""" |
| 85 | |
| 86 | if self.config == SupportedConfig.DEFAULT.value: |
| 87 | return 'make -j lib CFLAGS=\'-Os \' ' |
| 88 | elif self.arch == SupportedArch.AARCH32.value and \ |
| 89 | self.config == SupportedConfig.TFM_MEDIUM.value: |
| 90 | return \ |
| 91 | 'make -j lib CC=/usr/local/ArmCompilerforEmbedded6.19/bin/armclang \ |
| 92 | CFLAGS=\'--target=arm-arm-none-eabi -mcpu=cortex-m33 -Os \ |
| 93 | -DMBEDTLS_CONFIG_FILE=\\\"' + CONFIG_TFM_MEDIUM_MBEDCRYPTO_H + '\\\" \ |
| 94 | -DMBEDTLS_PSA_CRYPTO_CONFIG_FILE=\\\"' + CONFIG_TFM_MEDIUM_PSA_CRYPTO_H + '\\\" \'' |
| 95 | else: |
| 96 | print("Unsupported architecture: {} and configurations: {}" |
| 97 | .format(self.arch, self.config)) |
| 98 | sys.exit(1) |
| 99 | |
| 100 | |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 101 | class CodeSizeComparison: |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 102 | """Compare code size between two Git revisions.""" |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 103 | |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 104 | def __init__(self, old_revision, new_revision, result_dir, code_size_info): |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 105 | """ |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 106 | old_revision: revision to compare against. |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 107 | new_revision: |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 108 | result_dir: directory for comparison result. |
| 109 | code_size_info: an object containing information to build library. |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 110 | """ |
| 111 | self.repo_path = "." |
| 112 | self.result_dir = os.path.abspath(result_dir) |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 113 | os.makedirs(self.result_dir, exist_ok=True) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 114 | |
| 115 | self.csv_dir = os.path.abspath("code_size_records/") |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 116 | os.makedirs(self.csv_dir, exist_ok=True) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 117 | |
| 118 | self.old_rev = old_revision |
| 119 | self.new_rev = new_revision |
| 120 | self.git_command = "git" |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 121 | self.make_command = code_size_info.make_command |
Yanray Wang | 369cd96 | 2023-05-24 17:13:29 +0800 | [diff] [blame^] | 122 | self.fname_suffix = "-" + code_size_info.arch + "-" +\ |
| 123 | code_size_info.config |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 124 | |
| 125 | @staticmethod |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 126 | def validate_revision(revision): |
Xiaofei Bai | ccd738b | 2021-11-03 07:12:31 +0000 | [diff] [blame] | 127 | result = subprocess.check_output(["git", "rev-parse", "--verify", |
| 128 | revision + "^{commit}"], shell=False) |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 129 | return result |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 130 | |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 131 | def _create_git_worktree(self, revision): |
| 132 | """Make a separate worktree for revision. |
| 133 | Do not modify the current worktree.""" |
| 134 | |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 135 | if revision == "current": |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 136 | print("Using current work directory.") |
| 137 | git_worktree_path = self.repo_path |
| 138 | else: |
| 139 | print("Creating git worktree for", revision) |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 140 | git_worktree_path = os.path.join(self.repo_path, "temp-" + revision) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 141 | subprocess.check_output( |
| 142 | [self.git_command, "worktree", "add", "--detach", |
| 143 | git_worktree_path, revision], cwd=self.repo_path, |
| 144 | stderr=subprocess.STDOUT |
| 145 | ) |
Aditya Deshpande | 41a0aad | 2023-04-13 16:32:21 +0100 | [diff] [blame] | 146 | |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 147 | return git_worktree_path |
| 148 | |
| 149 | def _build_libraries(self, git_worktree_path): |
| 150 | """Build libraries in the specified worktree.""" |
| 151 | |
| 152 | my_environment = os.environ.copy() |
Aditya Deshpande | 41a0aad | 2023-04-13 16:32:21 +0100 | [diff] [blame] | 153 | try: |
| 154 | subprocess.check_output( |
| 155 | self.make_command, env=my_environment, shell=True, |
| 156 | cwd=git_worktree_path, stderr=subprocess.STDOUT, |
| 157 | ) |
| 158 | except subprocess.CalledProcessError as e: |
| 159 | self._handle_called_process_error(e, git_worktree_path) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 160 | |
| 161 | def _gen_code_size_csv(self, revision, git_worktree_path): |
| 162 | """Generate code size csv file.""" |
| 163 | |
Yanray Wang | 369cd96 | 2023-05-24 17:13:29 +0800 | [diff] [blame^] | 164 | csv_fname = revision + self.fname_suffix + ".csv" |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 165 | if revision == "current": |
| 166 | print("Measuring code size in current work directory.") |
| 167 | else: |
| 168 | print("Measuring code size for", revision) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 169 | result = subprocess.check_output( |
| 170 | ["size library/*.o"], cwd=git_worktree_path, shell=True |
| 171 | ) |
| 172 | size_text = result.decode() |
| 173 | csv_file = open(os.path.join(self.csv_dir, csv_fname), "w") |
| 174 | for line in size_text.splitlines()[1:]: |
| 175 | data = line.split() |
| 176 | csv_file.write("{}, {}\n".format(data[5], data[3])) |
| 177 | |
| 178 | def _remove_worktree(self, git_worktree_path): |
| 179 | """Remove temporary worktree.""" |
| 180 | if git_worktree_path != self.repo_path: |
| 181 | print("Removing temporary worktree", git_worktree_path) |
| 182 | subprocess.check_output( |
| 183 | [self.git_command, "worktree", "remove", "--force", |
| 184 | git_worktree_path], cwd=self.repo_path, |
| 185 | stderr=subprocess.STDOUT |
| 186 | ) |
| 187 | |
| 188 | def _get_code_size_for_rev(self, revision): |
| 189 | """Generate code size csv file for the specified git revision.""" |
| 190 | |
| 191 | # Check if the corresponding record exists |
Yanray Wang | 369cd96 | 2023-05-24 17:13:29 +0800 | [diff] [blame^] | 192 | csv_fname = revision + self.fname_suffix + ".csv" |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 193 | if (revision != "current") and \ |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 194 | os.path.exists(os.path.join(self.csv_dir, csv_fname)): |
| 195 | print("Code size csv file for", revision, "already exists.") |
| 196 | else: |
| 197 | git_worktree_path = self._create_git_worktree(revision) |
| 198 | self._build_libraries(git_worktree_path) |
| 199 | self._gen_code_size_csv(revision, git_worktree_path) |
| 200 | self._remove_worktree(git_worktree_path) |
| 201 | |
| 202 | def compare_code_size(self): |
| 203 | """Generate results of the size changes between two revisions, |
| 204 | old and new. Measured code size results of these two revisions |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 205 | must be available.""" |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 206 | |
Yanray Wang | 369cd96 | 2023-05-24 17:13:29 +0800 | [diff] [blame^] | 207 | old_file = open(os.path.join(self.csv_dir, self.old_rev + |
| 208 | self.fname_suffix + ".csv"), "r") |
| 209 | new_file = open(os.path.join(self.csv_dir, self.new_rev + |
| 210 | self.fname_suffix + ".csv"), "r") |
| 211 | res_file = open(os.path.join(self.result_dir, "compare-" + |
| 212 | self.old_rev + "-" + self.new_rev + |
| 213 | self.fname_suffix + |
| 214 | ".csv"), "w") |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 215 | |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 216 | res_file.write("file_name, this_size, old_size, change, change %\n") |
Shaun Case | 8b0ecbc | 2021-12-20 21:14:10 -0800 | [diff] [blame] | 217 | print("Generating comparison results.") |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 218 | |
| 219 | old_ds = {} |
| 220 | for line in old_file.readlines()[1:]: |
| 221 | cols = line.split(", ") |
| 222 | fname = cols[0] |
| 223 | size = int(cols[1]) |
| 224 | if size != 0: |
| 225 | old_ds[fname] = size |
| 226 | |
| 227 | new_ds = {} |
| 228 | for line in new_file.readlines()[1:]: |
| 229 | cols = line.split(", ") |
| 230 | fname = cols[0] |
| 231 | size = int(cols[1]) |
| 232 | new_ds[fname] = size |
| 233 | |
| 234 | for fname in new_ds: |
| 235 | this_size = new_ds[fname] |
| 236 | if fname in old_ds: |
| 237 | old_size = old_ds[fname] |
| 238 | change = this_size - old_size |
| 239 | change_pct = change / old_size |
| 240 | res_file.write("{}, {}, {}, {}, {:.2%}\n".format(fname, \ |
| 241 | this_size, old_size, change, float(change_pct))) |
| 242 | else: |
| 243 | res_file.write("{}, {}\n".format(fname, this_size)) |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 244 | return 0 |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 245 | |
| 246 | def get_comparision_results(self): |
| 247 | """Compare size of library/*.o between self.old_rev and self.new_rev, |
| 248 | and generate the result file.""" |
Gilles Peskine | d9071e7 | 2022-09-18 21:17:09 +0200 | [diff] [blame] | 249 | build_tree.check_repo_path() |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 250 | self._get_code_size_for_rev(self.old_rev) |
| 251 | self._get_code_size_for_rev(self.new_rev) |
| 252 | return self.compare_code_size() |
| 253 | |
Aditya Deshpande | 41a0aad | 2023-04-13 16:32:21 +0100 | [diff] [blame] | 254 | def _handle_called_process_error(self, e: subprocess.CalledProcessError, |
| 255 | git_worktree_path): |
| 256 | """Handle a CalledProcessError and quit the program gracefully. |
| 257 | Remove any extra worktrees so that the script may be called again.""" |
| 258 | |
| 259 | # Tell the user what went wrong |
| 260 | print("The following command: {} failed and exited with code {}" |
| 261 | .format(e.cmd, e.returncode)) |
| 262 | print("Process output:\n {}".format(str(e.output, "utf-8"))) |
| 263 | |
| 264 | # Quit gracefully by removing the existing worktree |
| 265 | self._remove_worktree(git_worktree_path) |
| 266 | sys.exit(-1) |
| 267 | |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 268 | def main(): |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 269 | parser = argparse.ArgumentParser( |
| 270 | description=( |
| 271 | """This script is for comparing the size of the library files |
| 272 | from two different Git revisions within an Mbed TLS repository. |
| 273 | The results of the comparison is formatted as csv, and stored at |
| 274 | a configurable location. |
| 275 | Note: must be run from Mbed TLS root.""" |
| 276 | ) |
| 277 | ) |
| 278 | parser.add_argument( |
| 279 | "-r", "--result-dir", type=str, default="comparison", |
| 280 | help="directory where comparison result is stored, \ |
| 281 | default is comparison", |
| 282 | ) |
| 283 | parser.add_argument( |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 284 | "-o", "--old-rev", type=str, help="old revision for comparison.", |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 285 | required=True, |
| 286 | ) |
| 287 | parser.add_argument( |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 288 | "-n", "--new-rev", type=str, default=None, |
| 289 | help="new revision for comparison, default is the current work \ |
Shaun Case | 8b0ecbc | 2021-12-20 21:14:10 -0800 | [diff] [blame] | 290 | directory, including uncommitted changes." |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 291 | ) |
Yanray Wang | 23bd532 | 2023-05-24 11:03:59 +0800 | [diff] [blame] | 292 | parser.add_argument( |
| 293 | "-a", "--arch", type=str, default=detect_arch(), |
| 294 | choices=list(map(lambda s: s.value, SupportedArch)), |
| 295 | help="specify architecture for code size comparison, default is the\ |
| 296 | host architecture." |
| 297 | ) |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 298 | parser.add_argument( |
| 299 | "-c", "--config", type=str, default=SupportedConfig.DEFAULT.value, |
| 300 | choices=list(map(lambda s: s.value, SupportedConfig)), |
| 301 | help="specify configuration type for code size comparison,\ |
| 302 | default is the current MbedTLS configuration." |
| 303 | ) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 304 | comp_args = parser.parse_args() |
| 305 | |
| 306 | if os.path.isfile(comp_args.result_dir): |
| 307 | print("Error: {} is not a directory".format(comp_args.result_dir)) |
| 308 | parser.exit() |
| 309 | |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 310 | validate_res = CodeSizeComparison.validate_revision(comp_args.old_rev) |
Xiaofei Bai | ccd738b | 2021-11-03 07:12:31 +0000 | [diff] [blame] | 311 | old_revision = validate_res.decode().replace("\n", "") |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 312 | |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 313 | if comp_args.new_rev is not None: |
| 314 | validate_res = CodeSizeComparison.validate_revision(comp_args.new_rev) |
Xiaofei Bai | ccd738b | 2021-11-03 07:12:31 +0000 | [diff] [blame] | 315 | new_revision = validate_res.decode().replace("\n", "") |
Xiaofei Bai | 184e8b6 | 2021-10-26 09:23:42 +0000 | [diff] [blame] | 316 | else: |
| 317 | new_revision = "current" |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 318 | |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 319 | print("Measure code size for architecture: {}, configuration: {}" |
| 320 | .format(comp_args.arch, comp_args.config)) |
| 321 | code_size_info = CodeSizeInfo(comp_args.arch, comp_args.config) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 322 | result_dir = comp_args.result_dir |
Yanray Wang | 6a86258 | 2023-05-24 12:24:38 +0800 | [diff] [blame] | 323 | size_compare = CodeSizeComparison(old_revision, new_revision, result_dir, |
| 324 | code_size_info) |
Xiaofei Bai | bca03e5 | 2021-09-09 09:42:37 +0000 | [diff] [blame] | 325 | return_code = size_compare.get_comparision_results() |
| 326 | sys.exit(return_code) |
| 327 | |
| 328 | |
| 329 | if __name__ == "__main__": |
Xiaofei Bai | 2400b50 | 2021-10-21 12:22:58 +0000 | [diff] [blame] | 330 | main() |