blob: cc43dc75d7a2c349172471c244160d1a0839f9a3 [file] [log] [blame]
Xiaofei Baibca03e52021-09-09 09:42:37 +00001#!/usr/bin/env python3
2
3"""
Xiaofei Baibca03e52021-09-09 09:42:37 +00004This script is for comparing the size of the library files from two
5different Git revisions within an Mbed TLS repository.
6The results of the comparison is formatted as csv and stored at a
7configurable location.
8Note: 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
26import argparse
Yanray Wang21127f72023-07-19 12:09:45 +080027import logging
Xiaofei Baibca03e52021-09-09 09:42:37 +000028import os
Yanray Wang16ebc572023-05-30 18:10:20 +080029import re
Yanray Wang5605c6f2023-07-21 16:09:00 +080030import shutil
Xiaofei Baibca03e52021-09-09 09:42:37 +000031import subprocess
32import sys
Yanray Wang16ebc572023-05-30 18:10:20 +080033import typing
Yanray Wang23bd5322023-05-24 11:03:59 +080034from enum import Enum
Xiaofei Baibca03e52021-09-09 09:42:37 +000035
Gilles Peskined9071e72022-09-18 21:17:09 +020036from mbedtls_dev import build_tree
Yanray Wang21127f72023-07-19 12:09:45 +080037from mbedtls_dev import logging_util
38from mbedtls_dev import typing_util
Gilles Peskined9071e72022-09-18 21:17:09 +020039
Yanray Wang23bd5322023-05-24 11:03:59 +080040class SupportedArch(Enum):
41 """Supported architecture for code size measurement."""
42 AARCH64 = 'aarch64'
43 AARCH32 = 'aarch32'
Yanray Wangaba71582023-05-29 16:45:56 +080044 ARMV8_M = 'armv8-m'
Yanray Wang23bd5322023-05-24 11:03:59 +080045 X86_64 = 'x86_64'
46 X86 = 'x86'
47
Yanray Wang955671b2023-07-21 12:08:27 +080048
Yanray Wang6a862582023-05-24 12:24:38 +080049class SupportedConfig(Enum):
50 """Supported configuration for code size measurement."""
51 DEFAULT = 'default'
52 TFM_MEDIUM = 'tfm-medium'
53
Yanray Wang955671b2023-07-21 12:08:27 +080054
Yanray Wang16ebc572023-05-30 18:10:20 +080055# Static library
56MBEDTLS_STATIC_LIB = {
57 'CRYPTO': 'library/libmbedcrypto.a',
58 'X509': 'library/libmbedx509.a',
59 'TLS': 'library/libmbedtls.a',
60}
61
Yanray Wang955671b2023-07-21 12:08:27 +080062class CodeSizeDistinctInfo: # pylint: disable=too-few-public-methods
63 """Data structure to store possibly distinct information for code size
64 comparison."""
65 def __init__( #pylint: disable=too-many-arguments
66 self,
67 version: str,
68 git_rev: str,
69 arch: str,
70 config: str,
Yanray Wang5605c6f2023-07-21 16:09:00 +080071 compiler: str,
72 opt_level: str,
Yanray Wang955671b2023-07-21 12:08:27 +080073 ) -> None:
74 """
75 :param: version: which version to compare with for code size.
76 :param: git_rev: Git revision to calculate code size.
77 :param: arch: architecture to measure code size on.
78 :param: config: Configuration type to calculate code size.
79 (See SupportedConfig)
Yanray Wang5605c6f2023-07-21 16:09:00 +080080 :param: compiler: compiler used to build library/*.o.
81 :param: opt_level: Options that control optimization. (E.g. -Os)
Yanray Wang955671b2023-07-21 12:08:27 +080082 """
83 self.version = version
84 self.git_rev = git_rev
85 self.arch = arch
86 self.config = config
Yanray Wang5605c6f2023-07-21 16:09:00 +080087 self.compiler = compiler
88 self.opt_level = opt_level
89 # Note: Variables below are not initialized by class instantiation.
90 self.pre_make_cmd = [] #type: typing.List[str]
91 self.make_cmd = ''
Yanray Wang955671b2023-07-21 12:08:27 +080092
Yanray Wanga6cf6922023-07-24 15:20:42 +080093 def get_info_indication(self):
94 """Return a unique string to indicate Code Size Distinct Information."""
Yanray Wang6ef50492023-07-26 14:59:37 +080095 return '{git_rev}-{arch}-{config}-{compiler}'.format(**self.__dict__)
Yanray Wanga6cf6922023-07-24 15:20:42 +080096
Yanray Wang955671b2023-07-21 12:08:27 +080097
98class CodeSizeCommonInfo: # pylint: disable=too-few-public-methods
99 """Data structure to store common information for code size comparison."""
100 def __init__(
101 self,
102 host_arch: str,
103 measure_cmd: str,
104 ) -> None:
105 """
106 :param host_arch: host architecture.
107 :param measure_cmd: command to measure code size for library/*.o.
108 """
109 self.host_arch = host_arch
110 self.measure_cmd = measure_cmd
111
Yanray Wanga6cf6922023-07-24 15:20:42 +0800112 def get_info_indication(self):
113 """Return a unique string to indicate Code Size Common Information."""
Yanray Wange4a36362023-07-25 10:37:11 +0800114 return '{measure_tool}'\
115 .format(measure_tool=self.measure_cmd.strip().split(' ')[0])
Yanray Wang955671b2023-07-21 12:08:27 +0800116
117class CodeSizeResultInfo: # pylint: disable=too-few-public-methods
118 """Data structure to store result options for code size comparison."""
119 def __init__(
120 self,
121 record_dir: str,
122 comp_dir: str,
123 with_markdown=False,
124 stdout=False,
125 ) -> None:
126 """
127 :param record_dir: directory to store code size record.
128 :param comp_dir: directory to store results of code size comparision.
129 :param with_markdown: write comparision result into a markdown table.
130 (Default: False)
131 :param stdout: direct comparison result into sys.stdout.
132 (Default False)
133 """
134 self.record_dir = record_dir
135 self.comp_dir = comp_dir
136 self.with_markdown = with_markdown
137 self.stdout = stdout
138
139
Yanray Wang23bd5322023-05-24 11:03:59 +0800140DETECT_ARCH_CMD = "cc -dM -E - < /dev/null"
141def detect_arch() -> str:
142 """Auto-detect host architecture."""
143 cc_output = subprocess.check_output(DETECT_ARCH_CMD, shell=True).decode()
Yanray Wang386c2f92023-07-20 15:32:15 +0800144 if '__aarch64__' in cc_output:
Yanray Wang23bd5322023-05-24 11:03:59 +0800145 return SupportedArch.AARCH64.value
Yanray Wang386c2f92023-07-20 15:32:15 +0800146 if '__arm__' in cc_output:
Yanray Wang23bd5322023-05-24 11:03:59 +0800147 return SupportedArch.AARCH32.value
Yanray Wang386c2f92023-07-20 15:32:15 +0800148 if '__x86_64__' in cc_output:
Yanray Wang23bd5322023-05-24 11:03:59 +0800149 return SupportedArch.X86_64.value
Yanray Wang386c2f92023-07-20 15:32:15 +0800150 if '__x86__' in cc_output:
Yanray Wang23bd5322023-05-24 11:03:59 +0800151 return SupportedArch.X86.value
152 else:
153 print("Unknown host architecture, cannot auto-detect arch.")
154 sys.exit(1)
Gilles Peskined9071e72022-09-18 21:17:09 +0200155
Yanray Wang5605c6f2023-07-21 16:09:00 +0800156TFM_MEDIUM_CONFIG_H = 'configs/tfm_mbedcrypto_config_profile_medium.h'
157TFM_MEDIUM_CRYPTO_CONFIG_H = 'configs/crypto_config_profile_medium.h'
158
159CONFIG_H = 'include/mbedtls/mbedtls_config.h'
160CRYPTO_CONFIG_H = 'include/psa/crypto_config.h'
161BACKUP_SUFFIX = '.code_size.bak'
162
Yanray Wang923f9432023-07-17 12:43:00 +0800163class CodeSizeBuildInfo: # pylint: disable=too-few-public-methods
Yanray Wang6a862582023-05-24 12:24:38 +0800164 """Gather information used to measure code size.
165
166 It collects information about architecture, configuration in order to
167 infer build command for code size measurement.
168 """
169
Yanray Wangc18cd892023-05-31 11:08:04 +0800170 SupportedArchConfig = [
Yanray Wang386c2f92023-07-20 15:32:15 +0800171 '-a ' + SupportedArch.AARCH64.value + ' -c ' + SupportedConfig.DEFAULT.value,
172 '-a ' + SupportedArch.AARCH32.value + ' -c ' + SupportedConfig.DEFAULT.value,
173 '-a ' + SupportedArch.X86_64.value + ' -c ' + SupportedConfig.DEFAULT.value,
174 '-a ' + SupportedArch.X86.value + ' -c ' + SupportedConfig.DEFAULT.value,
175 '-a ' + SupportedArch.ARMV8_M.value + ' -c ' + SupportedConfig.TFM_MEDIUM.value,
Yanray Wangc18cd892023-05-31 11:08:04 +0800176 ]
177
Yanray Wang802af162023-07-17 14:04:30 +0800178 def __init__(
179 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800180 size_dist_info: CodeSizeDistinctInfo,
Yanray Wang21127f72023-07-19 12:09:45 +0800181 host_arch: str,
182 logger: logging.Logger,
Yanray Wang802af162023-07-17 14:04:30 +0800183 ) -> None:
Yanray Wang6a862582023-05-24 12:24:38 +0800184 """
Yanray Wang955671b2023-07-21 12:08:27 +0800185 :param size_dist_info:
186 CodeSizeDistinctInfo containing info for code size measurement.
187 - size_dist_info.arch: architecture to measure code size on.
188 - size_dist_info.config: configuration type to measure
189 code size with.
Yanray Wang5605c6f2023-07-21 16:09:00 +0800190 - size_dist_info.compiler: compiler used to build library/*.o.
191 - size_dist_info.opt_level: Options that control optimization.
192 (E.g. -Os)
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800193 :param host_arch: host architecture.
194 :param logger: logging module
Yanray Wang6a862582023-05-24 12:24:38 +0800195 """
Yanray Wang5605c6f2023-07-21 16:09:00 +0800196 self.arch = size_dist_info.arch
197 self.config = size_dist_info.config
198 self.compiler = size_dist_info.compiler
199 self.opt_level = size_dist_info.opt_level
200
201 self.make_cmd = ['make', '-j', 'lib']
202
Yanray Wang802af162023-07-17 14:04:30 +0800203 self.host_arch = host_arch
Yanray Wang21127f72023-07-19 12:09:45 +0800204 self.logger = logger
Yanray Wang6a862582023-05-24 12:24:38 +0800205
Yanray Wang5605c6f2023-07-21 16:09:00 +0800206 def check_correctness(self) -> bool:
207 """Check whether we are using proper / supported combination
208 of information to build library/*.o."""
Yanray Wang6a862582023-05-24 12:24:38 +0800209
Yanray Wang5605c6f2023-07-21 16:09:00 +0800210 # default config
211 if self.config == SupportedConfig.DEFAULT.value and \
212 self.arch == self.host_arch:
213 return True
214 # TF-M
215 elif self.arch == SupportedArch.ARMV8_M.value and \
216 self.config == SupportedConfig.TFM_MEDIUM.value:
217 return True
218
219 return False
220
221 def infer_pre_make_command(self) -> typing.List[str]:
222 """Infer command to set up proper configuration before running make."""
223 pre_make_cmd = [] #type: typing.List[str]
224 if self.config == SupportedConfig.TFM_MEDIUM.value:
Yanray Wanga279ca92023-07-26 15:01:10 +0800225 pre_make_cmd.append('cp {src} {dest}'
Yanray Wange4a36362023-07-25 10:37:11 +0800226 .format(src=TFM_MEDIUM_CONFIG_H, dest=CONFIG_H))
Yanray Wanga279ca92023-07-26 15:01:10 +0800227 pre_make_cmd.append('cp {src} {dest}'
Yanray Wange4a36362023-07-25 10:37:11 +0800228 .format(src=TFM_MEDIUM_CRYPTO_CONFIG_H,
229 dest=CRYPTO_CONFIG_H))
Yanray Wang5605c6f2023-07-21 16:09:00 +0800230
231 return pre_make_cmd
232
233 def infer_make_cflags(self) -> str:
234 """Infer CFLAGS by instance attributes in CodeSizeDistinctInfo."""
235 cflags = [] #type: typing.List[str]
236
237 # set optimization level
238 cflags.append(self.opt_level)
239 # set compiler by config
240 if self.config == SupportedConfig.TFM_MEDIUM.value:
241 self.compiler = 'armclang'
242 cflags.append('-mcpu=cortex-m33')
243 # set target
244 if self.compiler == 'armclang':
245 cflags.append('--target=arm-arm-none-eabi')
246
247 return ' '.join(cflags)
248
249 def infer_make_command(self) -> str:
250 """Infer make command by CFLAGS and CC."""
251
252 if self.check_correctness():
253 # set CFLAGS=
254 self.make_cmd.append('CFLAGS=\'{}\''.format(self.infer_make_cflags()))
255 # set CC=
256 self.make_cmd.append('CC={}'.format(self.compiler))
257 return ' '.join(self.make_cmd)
Yanray Wang6a862582023-05-24 12:24:38 +0800258 else:
Yanray Wang21127f72023-07-19 12:09:45 +0800259 self.logger.error("Unsupported combination of architecture: {} " \
260 "and configuration: {}.\n"
Yanray Wang5605c6f2023-07-21 16:09:00 +0800261 .format(self.arch,
262 self.config))
Yanray Wang2ba9df22023-07-26 10:11:31 +0800263 self.logger.error("Please use supported combination of " \
Yanray Wang21127f72023-07-19 12:09:45 +0800264 "architecture and configuration:")
Yanray Wang923f9432023-07-17 12:43:00 +0800265 for comb in CodeSizeBuildInfo.SupportedArchConfig:
Yanray Wang2ba9df22023-07-26 10:11:31 +0800266 self.logger.error(comb)
267 self.logger.error("")
268 self.logger.error("For your system, please use:")
Yanray Wang923f9432023-07-17 12:43:00 +0800269 for comb in CodeSizeBuildInfo.SupportedArchConfig:
Yanray Wang802af162023-07-17 14:04:30 +0800270 if "default" in comb and self.host_arch not in comb:
Yanray Wang21f17442023-06-01 11:29:06 +0800271 continue
Yanray Wang2ba9df22023-07-26 10:11:31 +0800272 self.logger.error(comb)
Yanray Wang6a862582023-05-24 12:24:38 +0800273 sys.exit(1)
274
275
Yanray Wange0e27602023-07-14 17:37:45 +0800276class CodeSizeCalculator:
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800277 """ A calculator to calculate code size of library/*.o based on
Yanray Wange0e27602023-07-14 17:37:45 +0800278 Git revision and code size measurement tool.
279 """
280
Yanray Wang5605c6f2023-07-21 16:09:00 +0800281 def __init__( #pylint: disable=too-many-arguments
Yanray Wange0e27602023-07-14 17:37:45 +0800282 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800283 git_rev: str,
Yanray Wang5605c6f2023-07-21 16:09:00 +0800284 pre_make_cmd: typing.List[str],
Yanray Wange0e27602023-07-14 17:37:45 +0800285 make_cmd: str,
Yanray Wang21127f72023-07-19 12:09:45 +0800286 measure_cmd: str,
287 logger: logging.Logger,
Yanray Wange0e27602023-07-14 17:37:45 +0800288 ) -> None:
289 """
Yanray Wang955671b2023-07-21 12:08:27 +0800290 :param git_rev: Git revision. (E.g: commit)
Yanray Wang5605c6f2023-07-21 16:09:00 +0800291 :param pre_make_cmd: command to set up proper config before running make.
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800292 :param make_cmd: command to build library/*.o.
293 :param measure_cmd: command to measure code size for library/*.o.
294 :param logger: logging module
Yanray Wange0e27602023-07-14 17:37:45 +0800295 """
296 self.repo_path = "."
297 self.git_command = "git"
298 self.make_clean = 'make clean'
299
Yanray Wang955671b2023-07-21 12:08:27 +0800300 self.git_rev = git_rev
Yanray Wang5605c6f2023-07-21 16:09:00 +0800301 self.pre_make_cmd = pre_make_cmd
Yanray Wange0e27602023-07-14 17:37:45 +0800302 self.make_cmd = make_cmd
Yanray Wang802af162023-07-17 14:04:30 +0800303 self.measure_cmd = measure_cmd
Yanray Wang21127f72023-07-19 12:09:45 +0800304 self.logger = logger
Yanray Wange0e27602023-07-14 17:37:45 +0800305
306 @staticmethod
Yanray Wang955671b2023-07-21 12:08:27 +0800307 def validate_git_revision(git_rev: str) -> str:
Yanray Wange0e27602023-07-14 17:37:45 +0800308 result = subprocess.check_output(["git", "rev-parse", "--verify",
Yanray Wang955671b2023-07-21 12:08:27 +0800309 git_rev + "^{commit}"],
310 shell=False, universal_newlines=True)
Yanray Wang386c2f92023-07-20 15:32:15 +0800311 return result[:7]
Yanray Wange0e27602023-07-14 17:37:45 +0800312
Yanray Wang21127f72023-07-19 12:09:45 +0800313 def _create_git_worktree(self) -> str:
Yanray Wang955671b2023-07-21 12:08:27 +0800314 """Create a separate worktree for Git revision.
315 If Git revision is current, use current worktree instead."""
Yanray Wange0e27602023-07-14 17:37:45 +0800316
Yanray Wang5605c6f2023-07-21 16:09:00 +0800317 if self.git_rev == 'current':
Yanray Wang21127f72023-07-19 12:09:45 +0800318 self.logger.debug("Using current work directory.")
Yanray Wange0e27602023-07-14 17:37:45 +0800319 git_worktree_path = self.repo_path
320 else:
Yanray Wang21127f72023-07-19 12:09:45 +0800321 self.logger.debug("Creating git worktree for {}."
Yanray Wang955671b2023-07-21 12:08:27 +0800322 .format(self.git_rev))
Yanray Wang21127f72023-07-19 12:09:45 +0800323 git_worktree_path = os.path.join(self.repo_path,
Yanray Wang955671b2023-07-21 12:08:27 +0800324 "temp-" + self.git_rev)
Yanray Wange0e27602023-07-14 17:37:45 +0800325 subprocess.check_output(
326 [self.git_command, "worktree", "add", "--detach",
Yanray Wang955671b2023-07-21 12:08:27 +0800327 git_worktree_path, self.git_rev], cwd=self.repo_path,
Yanray Wange0e27602023-07-14 17:37:45 +0800328 stderr=subprocess.STDOUT
329 )
330
331 return git_worktree_path
332
Yanray Wang5605c6f2023-07-21 16:09:00 +0800333 @staticmethod
334 def backup_config_files(restore: bool) -> None:
335 """Backup / Restore config files."""
336 if restore:
337 shutil.move(CONFIG_H + BACKUP_SUFFIX, CONFIG_H)
338 shutil.move(CRYPTO_CONFIG_H + BACKUP_SUFFIX, CRYPTO_CONFIG_H)
339 else:
340 shutil.copy(CONFIG_H, CONFIG_H + BACKUP_SUFFIX)
341 shutil.copy(CRYPTO_CONFIG_H, CRYPTO_CONFIG_H + BACKUP_SUFFIX)
342
Yanray Wange0e27602023-07-14 17:37:45 +0800343 def _build_libraries(self, git_worktree_path: str) -> None:
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800344 """Build library/*.o in the specified worktree."""
Yanray Wange0e27602023-07-14 17:37:45 +0800345
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800346 self.logger.debug("Building library/*.o for {}."
Yanray Wang955671b2023-07-21 12:08:27 +0800347 .format(self.git_rev))
Yanray Wange0e27602023-07-14 17:37:45 +0800348 my_environment = os.environ.copy()
349 try:
Yanray Wang5605c6f2023-07-21 16:09:00 +0800350 if self.git_rev == 'current':
351 self.backup_config_files(restore=False)
352 for pre_cmd in self.pre_make_cmd:
353 subprocess.check_output(
354 pre_cmd, env=my_environment, shell=True,
355 cwd=git_worktree_path, stderr=subprocess.STDOUT,
356 universal_newlines=True
357 )
Yanray Wange0e27602023-07-14 17:37:45 +0800358 subprocess.check_output(
359 self.make_clean, env=my_environment, shell=True,
360 cwd=git_worktree_path, stderr=subprocess.STDOUT,
Yanray Wang386c2f92023-07-20 15:32:15 +0800361 universal_newlines=True
Yanray Wange0e27602023-07-14 17:37:45 +0800362 )
363 subprocess.check_output(
364 self.make_cmd, env=my_environment, shell=True,
365 cwd=git_worktree_path, stderr=subprocess.STDOUT,
Yanray Wang386c2f92023-07-20 15:32:15 +0800366 universal_newlines=True
Yanray Wange0e27602023-07-14 17:37:45 +0800367 )
Yanray Wang5605c6f2023-07-21 16:09:00 +0800368 if self.git_rev == 'current':
369 self.backup_config_files(restore=True)
Yanray Wange0e27602023-07-14 17:37:45 +0800370 except subprocess.CalledProcessError as e:
371 self._handle_called_process_error(e, git_worktree_path)
372
Yanray Wang386c2f92023-07-20 15:32:15 +0800373 def _gen_raw_code_size(self, git_worktree_path: str) -> typing.Dict[str, str]:
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800374 """Measure code size by a tool and return in UTF-8 encoding."""
Yanray Wang21127f72023-07-19 12:09:45 +0800375
376 self.logger.debug("Measuring code size for {} by `{}`."
Yanray Wang955671b2023-07-21 12:08:27 +0800377 .format(self.git_rev,
Yanray Wang21127f72023-07-19 12:09:45 +0800378 self.measure_cmd.strip().split(' ')[0]))
Yanray Wange0e27602023-07-14 17:37:45 +0800379
380 res = {}
381 for mod, st_lib in MBEDTLS_STATIC_LIB.items():
382 try:
383 result = subprocess.check_output(
Yanray Wang802af162023-07-17 14:04:30 +0800384 [self.measure_cmd + ' ' + st_lib], cwd=git_worktree_path,
385 shell=True, universal_newlines=True
Yanray Wange0e27602023-07-14 17:37:45 +0800386 )
387 res[mod] = result
388 except subprocess.CalledProcessError as e:
389 self._handle_called_process_error(e, git_worktree_path)
390
391 return res
392
393 def _remove_worktree(self, git_worktree_path: str) -> None:
394 """Remove temporary worktree."""
395 if git_worktree_path != self.repo_path:
Yanray Wang21127f72023-07-19 12:09:45 +0800396 self.logger.debug("Removing temporary worktree {}."
397 .format(git_worktree_path))
Yanray Wange0e27602023-07-14 17:37:45 +0800398 subprocess.check_output(
399 [self.git_command, "worktree", "remove", "--force",
400 git_worktree_path], cwd=self.repo_path,
401 stderr=subprocess.STDOUT
402 )
403
404 def _handle_called_process_error(self, e: subprocess.CalledProcessError,
405 git_worktree_path: str) -> None:
406 """Handle a CalledProcessError and quit the program gracefully.
407 Remove any extra worktrees so that the script may be called again."""
408
409 # Tell the user what went wrong
Yanray Wang21127f72023-07-19 12:09:45 +0800410 self.logger.error(e, exc_info=True)
Yanray Wang386c2f92023-07-20 15:32:15 +0800411 self.logger.error("Process output:\n {}".format(e.output))
Yanray Wange0e27602023-07-14 17:37:45 +0800412
413 # Quit gracefully by removing the existing worktree
414 self._remove_worktree(git_worktree_path)
415 sys.exit(-1)
416
Yanray Wang386c2f92023-07-20 15:32:15 +0800417 def cal_libraries_code_size(self) -> typing.Dict[str, str]:
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800418 """Do a complete round to calculate code size of library/*.o
419 by measurement tool.
420
421 :return A dictionary of measured code size
422 - typing.Dict[mod: str]
423 """
Yanray Wange0e27602023-07-14 17:37:45 +0800424
Yanray Wang21127f72023-07-19 12:09:45 +0800425 git_worktree_path = self._create_git_worktree()
Yanray Wang6ae94a02023-07-26 17:12:57 +0800426 try:
427 self._build_libraries(git_worktree_path)
428 res = self._gen_raw_code_size(git_worktree_path)
429 finally:
430 self._remove_worktree(git_worktree_path)
Yanray Wange0e27602023-07-14 17:37:45 +0800431
432 return res
433
434
Yanray Wang15c43f32023-07-17 11:17:12 +0800435class CodeSizeGenerator:
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800436 """ A generator based on size measurement tool for library/*.o.
Yanray Wang15c43f32023-07-17 11:17:12 +0800437
438 This is an abstract class. To use it, derive a class that implements
Yanray Wang95059002023-07-24 12:29:22 +0800439 write_record and write_comparison methods, then call both of them with
440 proper arguments.
Yanray Wang15c43f32023-07-17 11:17:12 +0800441 """
Yanray Wang21127f72023-07-19 12:09:45 +0800442 def __init__(self, logger: logging.Logger) -> None:
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800443 """
444 :param logger: logging module
445 """
Yanray Wang21127f72023-07-19 12:09:45 +0800446 self.logger = logger
447
Yanray Wang95059002023-07-24 12:29:22 +0800448 def write_record(
Yanray Wang15c43f32023-07-17 11:17:12 +0800449 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800450 git_rev: str,
Yanray Wang95059002023-07-24 12:29:22 +0800451 code_size_text: typing.Dict[str, str],
452 output: typing_util.Writable
Yanray Wang15c43f32023-07-17 11:17:12 +0800453 ) -> None:
454 """Write size record into a file.
455
Yanray Wang955671b2023-07-21 12:08:27 +0800456 :param git_rev: Git revision. (E.g: commit)
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800457 :param code_size_text:
458 string output (utf-8) from measurement tool of code size.
459 - typing.Dict[mod: str]
Yanray Wang95059002023-07-24 12:29:22 +0800460 :param output: output stream which the code size record is written to.
461 (Note: Normally write code size record into File)
Yanray Wang15c43f32023-07-17 11:17:12 +0800462 """
463 raise NotImplementedError
464
Yanray Wang95059002023-07-24 12:29:22 +0800465 def write_comparison(
Yanray Wang15c43f32023-07-17 11:17:12 +0800466 self,
467 old_rev: str,
468 new_rev: str,
Yanray Wang95059002023-07-24 12:29:22 +0800469 output: typing_util.Writable,
470 with_markdown=False
Yanray Wang15c43f32023-07-17 11:17:12 +0800471 ) -> None:
Yanray Wang955671b2023-07-21 12:08:27 +0800472 """Write a comparision result into a stream between two Git revisions.
Yanray Wang15c43f32023-07-17 11:17:12 +0800473
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800474 :param old_rev: old Git revision to compared with.
475 :param new_rev: new Git revision to compared with.
Yanray Wang95059002023-07-24 12:29:22 +0800476 :param output: output stream which the code size record is written to.
477 (File / sys.stdout)
478 :param with_markdown: write comparision result in a markdown table.
479 (Default: False)
Yanray Wang15c43f32023-07-17 11:17:12 +0800480 """
481 raise NotImplementedError
482
483
484class CodeSizeGeneratorWithSize(CodeSizeGenerator):
Yanray Wang16ebc572023-05-30 18:10:20 +0800485 """Code Size Base Class for size record saving and writing."""
486
Yanray Wangfc6ed4d2023-07-14 17:33:09 +0800487 class SizeEntry: # pylint: disable=too-few-public-methods
488 """Data Structure to only store information of code size."""
489 def __init__(self, text, data, bss, dec):
490 self.text = text
491 self.data = data
492 self.bss = bss
493 self.total = dec # total <=> dec
494
Yanray Wang21127f72023-07-19 12:09:45 +0800495 def __init__(self, logger: logging.Logger) -> None:
Yanray Wang955671b2023-07-21 12:08:27 +0800496 """ Variable code_size is used to store size info for any Git revisions.
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800497 :param code_size:
498 Data Format as following:
Yanray Wang955671b2023-07-21 12:08:27 +0800499 {git_rev: {module: {file_name: [text, data, bss, dec],
500 etc ...
501 },
502 etc ...
503 },
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800504 etc ...
505 }
Yanray Wang16ebc572023-05-30 18:10:20 +0800506 """
Yanray Wang21127f72023-07-19 12:09:45 +0800507 super().__init__(logger)
Yanray Wang16ebc572023-05-30 18:10:20 +0800508 self.code_size = {} #type: typing.Dict[str, typing.Dict]
509
Yanray Wang955671b2023-07-21 12:08:27 +0800510 def _set_size_record(self, git_rev: str, mod: str, size_text: str) -> None:
511 """Store size information for target Git revision and high-level module.
Yanray Wang16ebc572023-05-30 18:10:20 +0800512
513 size_text Format: text data bss dec hex filename
514 """
515 size_record = {}
516 for line in size_text.splitlines()[1:]:
517 data = line.split()
Yanray Wang9b174e92023-07-17 17:59:53 +0800518 # file_name: SizeEntry(text, data, bss, dec)
519 size_record[data[5]] = CodeSizeGeneratorWithSize.SizeEntry(
520 data[0], data[1], data[2], data[3])
Yanray Wang6ef50492023-07-26 14:59:37 +0800521 self.code_size.setdefault(git_rev, {}).update({mod: size_record})
Yanray Wang16ebc572023-05-30 18:10:20 +0800522
Yanray Wang955671b2023-07-21 12:08:27 +0800523 def read_size_record(self, git_rev: str, fname: str) -> None:
Yanray Wang16ebc572023-05-30 18:10:20 +0800524 """Read size information from csv file and write it into code_size.
525
526 fname Format: filename text data bss dec
527 """
528 mod = ""
529 size_record = {}
530 with open(fname, 'r') as csv_file:
531 for line in csv_file:
532 data = line.strip().split()
533 # check if we find the beginning of a module
534 if data and data[0] in MBEDTLS_STATIC_LIB:
535 mod = data[0]
536 continue
537
538 if mod:
Yanray Wang9b174e92023-07-17 17:59:53 +0800539 # file_name: SizeEntry(text, data, bss, dec)
540 size_record[data[0]] = CodeSizeGeneratorWithSize.SizeEntry(
Yanray Wangfc6ed4d2023-07-14 17:33:09 +0800541 data[1], data[2], data[3], data[4])
Yanray Wang16ebc572023-05-30 18:10:20 +0800542
543 # check if we hit record for the end of a module
544 m = re.match(r'.?TOTALS', line)
545 if m:
Yanray Wang955671b2023-07-21 12:08:27 +0800546 if git_rev in self.code_size:
547 self.code_size[git_rev].update({mod: size_record})
Yanray Wang16ebc572023-05-30 18:10:20 +0800548 else:
Yanray Wang955671b2023-07-21 12:08:27 +0800549 self.code_size[git_rev] = {mod: size_record}
Yanray Wang16ebc572023-05-30 18:10:20 +0800550 mod = ""
551 size_record = {}
552
553 def _size_reader_helper(
554 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800555 git_rev: str,
Yanray Wangb664cb72023-07-18 12:28:35 +0800556 output: typing_util.Writable,
557 with_markdown=False
Yanray Wang16ebc572023-05-30 18:10:20 +0800558 ) -> typing.Iterator[tuple]:
Yanray Wang955671b2023-07-21 12:08:27 +0800559 """A helper function to peel code_size based on Git revision."""
560 for mod, file_size in self.code_size[git_rev].items():
Yanray Wangb664cb72023-07-18 12:28:35 +0800561 if not with_markdown:
562 output.write("\n" + mod + "\n")
Yanray Wang16ebc572023-05-30 18:10:20 +0800563 for fname, size_entry in file_size.items():
564 yield mod, fname, size_entry
565
Yanray Wang95059002023-07-24 12:29:22 +0800566 def write_record(
Yanray Wang16ebc572023-05-30 18:10:20 +0800567 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800568 git_rev: str,
Yanray Wang95059002023-07-24 12:29:22 +0800569 code_size_text: typing.Dict[str, str],
Yanray Wang16ebc572023-05-30 18:10:20 +0800570 output: typing_util.Writable
571 ) -> None:
572 """Write size information to a file.
573
574 Writing Format: file_name text data bss total(dec)
575 """
Yanray Wang95059002023-07-24 12:29:22 +0800576 for mod, size_text in code_size_text.items():
577 self._set_size_record(git_rev, mod, size_text)
578
Yanray Wangb664cb72023-07-18 12:28:35 +0800579 format_string = "{:<30} {:>7} {:>7} {:>7} {:>7}\n"
580 output.write(format_string.format("filename",
581 "text", "data", "bss", "total"))
Yanray Wang955671b2023-07-21 12:08:27 +0800582 for _, fname, size_entry in self._size_reader_helper(git_rev, output):
Yanray Wangb664cb72023-07-18 12:28:35 +0800583 output.write(format_string.format(fname,
584 size_entry.text, size_entry.data,
585 size_entry.bss, size_entry.total))
Yanray Wang16ebc572023-05-30 18:10:20 +0800586
Yanray Wang95059002023-07-24 12:29:22 +0800587 def write_comparison(
Yanray Wang16ebc572023-05-30 18:10:20 +0800588 self,
589 old_rev: str,
590 new_rev: str,
Yanray Wangb664cb72023-07-18 12:28:35 +0800591 output: typing_util.Writable,
Yanray Wang95059002023-07-24 12:29:22 +0800592 with_markdown=False
Yanray Wang16ebc572023-05-30 18:10:20 +0800593 ) -> None:
594 """Write comparison result into a file.
595
Yanray Wang9b174e92023-07-17 17:59:53 +0800596 Writing Format: file_name current(text,data) old(text,data)\
597 change(text,data) change_pct%(text,data)
Yanray Wang16ebc572023-05-30 18:10:20 +0800598 """
Yanray Wang9b174e92023-07-17 17:59:53 +0800599
600 def cal_size_section_variation(mod, fname, size_entry, attr):
601 new_size = int(size_entry.__dict__[attr])
Yanray Wang955671b2023-07-21 12:08:27 +0800602 # check if we have the file in old Git revision
Yanray Wang16ebc572023-05-30 18:10:20 +0800603 if fname in self.code_size[old_rev][mod]:
Yanray Wang9b174e92023-07-17 17:59:53 +0800604 old_size = int(self.code_size[old_rev][mod][fname].__dict__[attr])
Yanray Wang16ebc572023-05-30 18:10:20 +0800605 change = new_size - old_size
606 if old_size != 0:
607 change_pct = change / old_size
608 else:
609 change_pct = 0
Yanray Wang9b174e92023-07-17 17:59:53 +0800610 return [new_size, old_size, change, change_pct]
Yanray Wang16ebc572023-05-30 18:10:20 +0800611 else:
Yanray Wang9b174e92023-07-17 17:59:53 +0800612 return [new_size]
613
Yanray Wangb664cb72023-07-18 12:28:35 +0800614 if with_markdown:
615 format_string = "| {:<30} | {:<18} | {:<14} | {:<17} | {:<18} |\n"
616 else:
617 format_string = "{:<30} {:<18} {:<14} {:<17} {:<18}\n"
618
Yanray Wang386c2f92023-07-20 15:32:15 +0800619 output.write(format_string
620 .format("filename",
621 "current(text,data)", "old(text,data)",
622 "change(text,data)", "change%(text,data)"))
Yanray Wangb664cb72023-07-18 12:28:35 +0800623 if with_markdown:
624 output.write(format_string
Yanray Wangbef1acd2023-07-26 10:45:11 +0800625 .format(":----", "----:", "----:", "----:", "----:"))
Yanray Wangb664cb72023-07-18 12:28:35 +0800626
Yanray Wang386c2f92023-07-20 15:32:15 +0800627 for mod, fname, size_entry in \
Yanray Wangb664cb72023-07-18 12:28:35 +0800628 self._size_reader_helper(new_rev, output, with_markdown):
629 text_vari = cal_size_section_variation(mod, fname,
630 size_entry, 'text')
631 data_vari = cal_size_section_variation(mod, fname,
632 size_entry, 'data')
Yanray Wang9b174e92023-07-17 17:59:53 +0800633
634 if len(text_vari) != 1:
Yanray Wangb664cb72023-07-18 12:28:35 +0800635 # skip the files that haven't changed in code size if we write
636 # comparison result in a markdown table.
637 if with_markdown and text_vari[2] == 0 and data_vari[2] == 0:
638 continue
Yanray Wang386c2f92023-07-20 15:32:15 +0800639 output.write(
640 format_string
641 .format(fname,
Yanray Wange4a36362023-07-25 10:37:11 +0800642 # current(text,data)
Yanray Wang386c2f92023-07-20 15:32:15 +0800643 str(text_vari[0]) + "," + str(data_vari[0]),
Yanray Wange4a36362023-07-25 10:37:11 +0800644 # old(text,data)
Yanray Wang386c2f92023-07-20 15:32:15 +0800645 str(text_vari[1]) + "," + str(data_vari[1]),
Yanray Wange4a36362023-07-25 10:37:11 +0800646 # change(text,data)
Yanray Wang386c2f92023-07-20 15:32:15 +0800647 str(text_vari[2]) + "," + str(data_vari[2]),
Yanray Wange4a36362023-07-25 10:37:11 +0800648 # change%(text,data)
Yanray Wang25bd3312023-07-25 10:24:20 +0800649 "{:.0%}".format(text_vari[3]) + ","
650 + "{:.0%}".format(data_vari[3])))
Yanray Wang9b174e92023-07-17 17:59:53 +0800651 else:
Yanray Wangf2cd7172023-07-24 16:56:46 +0800652 output.write(
653 format_string
654 .format(fname,
Yanray Wange4a36362023-07-25 10:37:11 +0800655 # current(text,data)
Yanray Wangf2cd7172023-07-24 16:56:46 +0800656 str(text_vari[0]) + "," + str(data_vari[0]),
657 'None', 'None', 'None'))
Yanray Wang16ebc572023-05-30 18:10:20 +0800658
659
Yanray Wangfc6ed4d2023-07-14 17:33:09 +0800660class CodeSizeComparison:
Xiaofei Bai2400b502021-10-21 12:22:58 +0000661 """Compare code size between two Git revisions."""
Xiaofei Baibca03e52021-09-09 09:42:37 +0000662
Yanray Wang955671b2023-07-21 12:08:27 +0800663 def __init__( #pylint: disable=too-many-arguments
Yanray Wang72b105f2023-05-31 15:20:39 +0800664 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800665 old_size_dist_info: CodeSizeDistinctInfo,
666 new_size_dist_info: CodeSizeDistinctInfo,
667 size_common_info: CodeSizeCommonInfo,
668 result_options: CodeSizeResultInfo,
Yanray Wang21127f72023-07-19 12:09:45 +0800669 logger: logging.Logger,
Yanray Wang72b105f2023-05-31 15:20:39 +0800670 ) -> None:
Xiaofei Baibca03e52021-09-09 09:42:37 +0000671 """
Yanray Wang955671b2023-07-21 12:08:27 +0800672 :param old_size_dist_info: CodeSizeDistinctInfo containing old distinct
673 info to compare code size with.
674 :param new_size_dist_info: CodeSizeDistinctInfo containing new distinct
675 info to take as comparision base.
676 :param size_common_info: CodeSizeCommonInfo containing common info for
677 both old and new size distinct info and
678 measurement tool.
679 :param result_options: CodeSizeResultInfo containing results options for
680 code size record and comparision.
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800681 :param logger: logging module
Xiaofei Baibca03e52021-09-09 09:42:37 +0000682 """
Xiaofei Baibca03e52021-09-09 09:42:37 +0000683
Yanray Wang21127f72023-07-19 12:09:45 +0800684 self.logger = logger
685
Yanray Wang955671b2023-07-21 12:08:27 +0800686 self.old_size_dist_info = old_size_dist_info
687 self.new_size_dist_info = new_size_dist_info
688 self.size_common_info = size_common_info
Yanray Wang5605c6f2023-07-21 16:09:00 +0800689 # infer pre make command
690 self.old_size_dist_info.pre_make_cmd = CodeSizeBuildInfo(
691 self.old_size_dist_info, self.size_common_info.host_arch,
692 self.logger).infer_pre_make_command()
693 self.new_size_dist_info.pre_make_cmd = CodeSizeBuildInfo(
694 self.new_size_dist_info, self.size_common_info.host_arch,
695 self.logger).infer_pre_make_command()
Yanray Wang386c2f92023-07-20 15:32:15 +0800696 # infer make command
Yanray Wang955671b2023-07-21 12:08:27 +0800697 self.old_size_dist_info.make_cmd = CodeSizeBuildInfo(
698 self.old_size_dist_info, self.size_common_info.host_arch,
Yanray Wang21127f72023-07-19 12:09:45 +0800699 self.logger).infer_make_command()
Yanray Wang955671b2023-07-21 12:08:27 +0800700 self.new_size_dist_info.make_cmd = CodeSizeBuildInfo(
701 self.new_size_dist_info, self.size_common_info.host_arch,
Yanray Wang21127f72023-07-19 12:09:45 +0800702 self.logger).infer_make_command()
Yanray Wang386c2f92023-07-20 15:32:15 +0800703 # initialize size parser with corresponding measurement tool
Yanray Wang21127f72023-07-19 12:09:45 +0800704 self.code_size_generator = self.__generate_size_parser()
Xiaofei Baibca03e52021-09-09 09:42:37 +0000705
Yanray Wang955671b2023-07-21 12:08:27 +0800706 self.result_options = result_options
707 self.csv_dir = os.path.abspath(self.result_options.record_dir)
708 os.makedirs(self.csv_dir, exist_ok=True)
709 self.comp_dir = os.path.abspath(self.result_options.comp_dir)
710 os.makedirs(self.comp_dir, exist_ok=True)
711
Yanray Wang21127f72023-07-19 12:09:45 +0800712 def __generate_size_parser(self):
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800713 """Generate a parser for the corresponding measurement tool."""
Yanray Wang955671b2023-07-21 12:08:27 +0800714 if re.match(r'size', self.size_common_info.measure_cmd.strip()):
Yanray Wang21127f72023-07-19 12:09:45 +0800715 return CodeSizeGeneratorWithSize(self.logger)
Yanray Wang802af162023-07-17 14:04:30 +0800716 else:
Yanray Wang21127f72023-07-19 12:09:45 +0800717 self.logger.error("Unsupported measurement tool: `{}`."
Yanray Wang955671b2023-07-21 12:08:27 +0800718 .format(self.size_common_info.measure_cmd
Yanray Wang21127f72023-07-19 12:09:45 +0800719 .strip().split(' ')[0]))
Yanray Wang802af162023-07-17 14:04:30 +0800720 sys.exit(1)
721
Yanray Wang386c2f92023-07-20 15:32:15 +0800722 def cal_code_size(
723 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800724 size_dist_info: CodeSizeDistinctInfo
Yanray Wang386c2f92023-07-20 15:32:15 +0800725 ) -> typing.Dict[str, str]:
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800726 """Calculate code size of library/*.o in a UTF-8 encoding"""
Xiaofei Baibca03e52021-09-09 09:42:37 +0000727
Yanray Wang955671b2023-07-21 12:08:27 +0800728 return CodeSizeCalculator(size_dist_info.git_rev,
Yanray Wang5605c6f2023-07-21 16:09:00 +0800729 size_dist_info.pre_make_cmd,
Yanray Wang955671b2023-07-21 12:08:27 +0800730 size_dist_info.make_cmd,
731 self.size_common_info.measure_cmd,
Yanray Wang21127f72023-07-19 12:09:45 +0800732 self.logger).cal_libraries_code_size()
Yanray Wang8804db92023-05-30 18:18:18 +0800733
Yanray Wang955671b2023-07-21 12:08:27 +0800734 def gen_code_size_report(self, size_dist_info: CodeSizeDistinctInfo) -> None:
Yanray Wang5e9130a2023-07-17 11:55:54 +0800735 """Generate code size record and write it into a file."""
Xiaofei Baibca03e52021-09-09 09:42:37 +0000736
Yanray Wang21127f72023-07-19 12:09:45 +0800737 self.logger.info("Start to generate code size record for {}."
Yanray Wang955671b2023-07-21 12:08:27 +0800738 .format(size_dist_info.git_rev))
Yanray Wanga6cf6922023-07-24 15:20:42 +0800739 output_file = os.path.join(
740 self.csv_dir,
741 '{}-{}.csv'
742 .format(size_dist_info.get_info_indication(),
743 self.size_common_info.get_info_indication()))
Xiaofei Baibca03e52021-09-09 09:42:37 +0000744 # Check if the corresponding record exists
Yanray Wang955671b2023-07-21 12:08:27 +0800745 if size_dist_info.git_rev != "current" and \
Yanray Wang21127f72023-07-19 12:09:45 +0800746 os.path.exists(output_file):
747 self.logger.debug("Code size csv file for {} already exists."
Yanray Wang955671b2023-07-21 12:08:27 +0800748 .format(size_dist_info.git_rev))
Yanray Wang21127f72023-07-19 12:09:45 +0800749 self.code_size_generator.read_size_record(
Yanray Wang955671b2023-07-21 12:08:27 +0800750 size_dist_info.git_rev, output_file)
Xiaofei Baibca03e52021-09-09 09:42:37 +0000751 else:
Yanray Wang95059002023-07-24 12:29:22 +0800752 # measure code size
753 code_size_text = self.cal_code_size(size_dist_info)
754
755 self.logger.debug("Generating code size csv for {}."
756 .format(size_dist_info.git_rev))
757 output = open(output_file, "w")
758 self.code_size_generator.write_record(
759 size_dist_info.git_rev, code_size_text, output)
Xiaofei Baibca03e52021-09-09 09:42:37 +0000760
Yanray Wang386c2f92023-07-20 15:32:15 +0800761 def gen_code_size_comparison(self) -> None:
Yanray Wang955671b2023-07-21 12:08:27 +0800762 """Generate results of code size changes between two Git revisions,
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800763 old and new.
764
Yanray Wang955671b2023-07-21 12:08:27 +0800765 - Measured code size result of these two Git revisions must be available.
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800766 - The result is directed into either file / stdout depending on
Yanray Wang955671b2023-07-21 12:08:27 +0800767 the option, size_common_info.result_options.stdout. (Default: file)
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800768 """
Xiaofei Baibca03e52021-09-09 09:42:37 +0000769
Yanray Wang21127f72023-07-19 12:09:45 +0800770 self.logger.info("Start to generate comparision result between "\
771 "{} and {}."
Yanray Wang955671b2023-07-21 12:08:27 +0800772 .format(self.old_size_dist_info.git_rev,
773 self.new_size_dist_info.git_rev))
Yanray Wanga6cf6922023-07-24 15:20:42 +0800774 if self.result_options.stdout:
775 output = sys.stdout
776 else:
777 output_file = os.path.join(
778 self.comp_dir,
779 '{}-{}-{}.csv'
780 .format(self.old_size_dist_info.get_info_indication(),
781 self.new_size_dist_info.get_info_indication(),
782 self.size_common_info.get_info_indication()))
783 output = open(output_file, "w")
Xiaofei Bai184e8b62021-10-26 09:23:42 +0000784
Yanray Wang95059002023-07-24 12:29:22 +0800785 self.logger.debug("Generating comparison results between {} and {}."
786 .format(self.old_size_dist_info.git_rev,
787 self.new_size_dist_info.git_rev))
Yanray Wangea842e72023-07-26 10:34:39 +0800788 if self.result_options.with_markdown or self.result_options.stdout:
789 print("Measure code size between {} and {} by `{}`."
790 .format(self.old_size_dist_info.get_info_indication(),
791 self.new_size_dist_info.get_info_indication(),
792 self.size_common_info.get_info_indication()),
793 file=output)
Yanray Wang95059002023-07-24 12:29:22 +0800794 self.code_size_generator.write_comparison(
Yanray Wang955671b2023-07-21 12:08:27 +0800795 self.old_size_dist_info.git_rev,
796 self.new_size_dist_info.git_rev,
Yanray Wang95059002023-07-24 12:29:22 +0800797 output, self.result_options.with_markdown)
Yanray Wang21127f72023-07-19 12:09:45 +0800798
Yanray Wang386c2f92023-07-20 15:32:15 +0800799 def get_comparision_results(self) -> None:
Yanray Wang955671b2023-07-21 12:08:27 +0800800 """Compare size of library/*.o between self.old_size_dist_info and
801 self.old_size_dist_info and generate the result file."""
Gilles Peskined9071e72022-09-18 21:17:09 +0200802 build_tree.check_repo_path()
Yanray Wang955671b2023-07-21 12:08:27 +0800803 self.gen_code_size_report(self.old_size_dist_info)
804 self.gen_code_size_report(self.new_size_dist_info)
Yanray Wang386c2f92023-07-20 15:32:15 +0800805 self.gen_code_size_comparison()
Xiaofei Baibca03e52021-09-09 09:42:37 +0000806
Xiaofei Bai2400b502021-10-21 12:22:58 +0000807def main():
Yanray Wang502c54f2023-05-31 11:41:36 +0800808 parser = argparse.ArgumentParser(description=(__doc__))
809 group_required = parser.add_argument_group(
810 'required arguments',
811 'required arguments to parse for running ' + os.path.basename(__file__))
812 group_required.add_argument(
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800813 '-o', '--old-rev', type=str, required=True,
Yanray Wang955671b2023-07-21 12:08:27 +0800814 help='old Git revision for comparison.')
Yanray Wang502c54f2023-05-31 11:41:36 +0800815
816 group_optional = parser.add_argument_group(
817 'optional arguments',
818 'optional arguments to parse for running ' + os.path.basename(__file__))
819 group_optional.add_argument(
Yanray Wang9e8b6712023-07-26 15:37:26 +0800820 '--record-dir', type=str, default='code_size_records',
Yanray Wang955671b2023-07-21 12:08:27 +0800821 help='directory where code size record is stored. '
822 '(Default: code_size_records)')
823 group_optional.add_argument(
Yanray Wang9e8b6712023-07-26 15:37:26 +0800824 '--comp-dir', type=str, default='comparison',
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800825 help='directory where comparison result is stored. '
826 '(Default: comparison)')
Yanray Wang502c54f2023-05-31 11:41:36 +0800827 group_optional.add_argument(
Yanray Wang68265f42023-07-26 14:44:52 +0800828 '-n', '--new-rev', type=str, default='current',
Yanray Wang955671b2023-07-21 12:08:27 +0800829 help='new Git revision as comparison base. '
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800830 '(Default is the current work directory, including uncommitted '
831 'changes.)')
Yanray Wang502c54f2023-05-31 11:41:36 +0800832 group_optional.add_argument(
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800833 '-a', '--arch', type=str, default=detect_arch(),
Yanray Wang23bd5322023-05-24 11:03:59 +0800834 choices=list(map(lambda s: s.value, SupportedArch)),
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800835 help='Specify architecture for code size comparison. '
836 '(Default is the host architecture.)')
Yanray Wang502c54f2023-05-31 11:41:36 +0800837 group_optional.add_argument(
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800838 '-c', '--config', type=str, default=SupportedConfig.DEFAULT.value,
Yanray Wang6a862582023-05-24 12:24:38 +0800839 choices=list(map(lambda s: s.value, SupportedConfig)),
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800840 help='Specify configuration type for code size comparison. '
841 '(Default is the current MbedTLS configuration.)')
Yanray Wangb664cb72023-07-18 12:28:35 +0800842 group_optional.add_argument(
843 '--markdown', action='store_true', dest='markdown',
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800844 help='Show comparision of code size in a markdown table. '
845 '(Only show the files that have changed).')
Yanray Wang227576a2023-07-18 14:35:05 +0800846 group_optional.add_argument(
847 '--stdout', action='store_true', dest='stdout',
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800848 help='Set this option to direct comparison result into sys.stdout. '
849 '(Default: file)')
Yanray Wang21127f72023-07-19 12:09:45 +0800850 group_optional.add_argument(
851 '--verbose', action='store_true', dest='verbose',
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800852 help='Show logs in detail for code size measurement. '
853 '(Default: False)')
Xiaofei Baibca03e52021-09-09 09:42:37 +0000854 comp_args = parser.parse_args()
855
Yanray Wang21127f72023-07-19 12:09:45 +0800856 logger = logging.getLogger()
857 logging_util.configure_logger(logger)
Yanray Wang533cde22023-07-26 10:17:17 +0800858 if comp_args.stdout and not comp_args.verbose:
859 logger.setLevel(logging.ERROR)
860 else:
861 logger.setLevel(logging.DEBUG if comp_args.verbose else logging.INFO)
Yanray Wang21127f72023-07-19 12:09:45 +0800862
Yanray Wang9e8b6712023-07-26 15:37:26 +0800863 if os.path.isfile(comp_args.record_dir):
864 logger.error("record directory: {} is not a directory"
865 .format(comp_args.record_dir))
866 sys.exit(1)
Yanray Wang955671b2023-07-21 12:08:27 +0800867 if os.path.isfile(comp_args.comp_dir):
Yanray Wang9e8b6712023-07-26 15:37:26 +0800868 logger.error("comparison directory: {} is not a directory"
869 .format(comp_args.comp_dir))
870 sys.exit(1)
Xiaofei Baibca03e52021-09-09 09:42:37 +0000871
Yanray Wang68265f42023-07-26 14:44:52 +0800872 comp_args.old_rev = CodeSizeCalculator.validate_git_revision(
873 comp_args.old_rev)
874 if comp_args.new_rev != 'current':
875 comp_args.new_rev = CodeSizeCalculator.validate_git_revision(
Yanray Wang955671b2023-07-21 12:08:27 +0800876 comp_args.new_rev)
Xiaofei Bai2400b502021-10-21 12:22:58 +0000877
Yanray Wang5605c6f2023-07-21 16:09:00 +0800878 # version, git_rev, arch, config, compiler, opt_level
Yanray Wang955671b2023-07-21 12:08:27 +0800879 old_size_dist_info = CodeSizeDistinctInfo(
Yanray Wang68265f42023-07-26 14:44:52 +0800880 'old', comp_args.old_rev, comp_args.arch, comp_args.config, 'cc', '-Os')
Yanray Wang955671b2023-07-21 12:08:27 +0800881 new_size_dist_info = CodeSizeDistinctInfo(
Yanray Wang68265f42023-07-26 14:44:52 +0800882 'new', comp_args.new_rev, comp_args.arch, comp_args.config, 'cc', '-Os')
Yanray Wang5605c6f2023-07-21 16:09:00 +0800883 # host_arch, measure_cmd
Yanray Wang955671b2023-07-21 12:08:27 +0800884 size_common_info = CodeSizeCommonInfo(
885 detect_arch(), 'size -t')
Yanray Wang5605c6f2023-07-21 16:09:00 +0800886 # record_dir, comp_dir, with_markdown, stdout
Yanray Wang955671b2023-07-21 12:08:27 +0800887 result_options = CodeSizeResultInfo(
888 comp_args.record_dir, comp_args.comp_dir,
889 comp_args.markdown, comp_args.stdout)
Yanray Wang923f9432023-07-17 12:43:00 +0800890
Yanray Wanga6cf6922023-07-24 15:20:42 +0800891 logger.info("Measure code size between {} and {} by `{}`."
892 .format(old_size_dist_info.get_info_indication(),
893 new_size_dist_info.get_info_indication(),
894 size_common_info.get_info_indication()))
Yanray Wang955671b2023-07-21 12:08:27 +0800895 CodeSizeComparison(old_size_dist_info, new_size_dist_info,
896 size_common_info, result_options,
897 logger).get_comparision_results()
Xiaofei Baibca03e52021-09-09 09:42:37 +0000898
Xiaofei Baibca03e52021-09-09 09:42:37 +0000899if __name__ == "__main__":
Xiaofei Bai2400b502021-10-21 12:22:58 +0000900 main()