blob: 9b81b82f1d3861f5471b889ae469bd50a5979dc1 [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 Wange4a36362023-07-25 10:37:11 +0800225 pre_make_cmd.append('cp -r {src} {dest}'
226 .format(src=TFM_MEDIUM_CONFIG_H, dest=CONFIG_H))
227 pre_make_cmd.append('cp -r {src} {dest}'
228 .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 Wange0e27602023-07-14 17:37:45 +0800426 self._build_libraries(git_worktree_path)
Yanray Wang21127f72023-07-19 12:09:45 +0800427 res = self._gen_raw_code_size(git_worktree_path)
Yanray Wange0e27602023-07-14 17:37:45 +0800428 self._remove_worktree(git_worktree_path)
429
430 return res
431
432
Yanray Wang15c43f32023-07-17 11:17:12 +0800433class CodeSizeGenerator:
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800434 """ A generator based on size measurement tool for library/*.o.
Yanray Wang15c43f32023-07-17 11:17:12 +0800435
436 This is an abstract class. To use it, derive a class that implements
Yanray Wang95059002023-07-24 12:29:22 +0800437 write_record and write_comparison methods, then call both of them with
438 proper arguments.
Yanray Wang15c43f32023-07-17 11:17:12 +0800439 """
Yanray Wang21127f72023-07-19 12:09:45 +0800440 def __init__(self, logger: logging.Logger) -> None:
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800441 """
442 :param logger: logging module
443 """
Yanray Wang21127f72023-07-19 12:09:45 +0800444 self.logger = logger
445
Yanray Wang95059002023-07-24 12:29:22 +0800446 def write_record(
Yanray Wang15c43f32023-07-17 11:17:12 +0800447 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800448 git_rev: str,
Yanray Wang95059002023-07-24 12:29:22 +0800449 code_size_text: typing.Dict[str, str],
450 output: typing_util.Writable
Yanray Wang15c43f32023-07-17 11:17:12 +0800451 ) -> None:
452 """Write size record into a file.
453
Yanray Wang955671b2023-07-21 12:08:27 +0800454 :param git_rev: Git revision. (E.g: commit)
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800455 :param code_size_text:
456 string output (utf-8) from measurement tool of code size.
457 - typing.Dict[mod: str]
Yanray Wang95059002023-07-24 12:29:22 +0800458 :param output: output stream which the code size record is written to.
459 (Note: Normally write code size record into File)
Yanray Wang15c43f32023-07-17 11:17:12 +0800460 """
461 raise NotImplementedError
462
Yanray Wang95059002023-07-24 12:29:22 +0800463 def write_comparison(
Yanray Wang15c43f32023-07-17 11:17:12 +0800464 self,
465 old_rev: str,
466 new_rev: str,
Yanray Wang95059002023-07-24 12:29:22 +0800467 output: typing_util.Writable,
468 with_markdown=False
Yanray Wang15c43f32023-07-17 11:17:12 +0800469 ) -> None:
Yanray Wang955671b2023-07-21 12:08:27 +0800470 """Write a comparision result into a stream between two Git revisions.
Yanray Wang15c43f32023-07-17 11:17:12 +0800471
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800472 :param old_rev: old Git revision to compared with.
473 :param new_rev: new Git revision to compared with.
Yanray Wang95059002023-07-24 12:29:22 +0800474 :param output: output stream which the code size record is written to.
475 (File / sys.stdout)
476 :param with_markdown: write comparision result in a markdown table.
477 (Default: False)
Yanray Wang15c43f32023-07-17 11:17:12 +0800478 """
479 raise NotImplementedError
480
481
482class CodeSizeGeneratorWithSize(CodeSizeGenerator):
Yanray Wang16ebc572023-05-30 18:10:20 +0800483 """Code Size Base Class for size record saving and writing."""
484
Yanray Wangfc6ed4d2023-07-14 17:33:09 +0800485 class SizeEntry: # pylint: disable=too-few-public-methods
486 """Data Structure to only store information of code size."""
487 def __init__(self, text, data, bss, dec):
488 self.text = text
489 self.data = data
490 self.bss = bss
491 self.total = dec # total <=> dec
492
Yanray Wang21127f72023-07-19 12:09:45 +0800493 def __init__(self, logger: logging.Logger) -> None:
Yanray Wang955671b2023-07-21 12:08:27 +0800494 """ Variable code_size is used to store size info for any Git revisions.
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800495 :param code_size:
496 Data Format as following:
Yanray Wang955671b2023-07-21 12:08:27 +0800497 {git_rev: {module: {file_name: [text, data, bss, dec],
498 etc ...
499 },
500 etc ...
501 },
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800502 etc ...
503 }
Yanray Wang16ebc572023-05-30 18:10:20 +0800504 """
Yanray Wang21127f72023-07-19 12:09:45 +0800505 super().__init__(logger)
Yanray Wang16ebc572023-05-30 18:10:20 +0800506 self.code_size = {} #type: typing.Dict[str, typing.Dict]
507
Yanray Wang955671b2023-07-21 12:08:27 +0800508 def _set_size_record(self, git_rev: str, mod: str, size_text: str) -> None:
509 """Store size information for target Git revision and high-level module.
Yanray Wang16ebc572023-05-30 18:10:20 +0800510
511 size_text Format: text data bss dec hex filename
512 """
513 size_record = {}
514 for line in size_text.splitlines()[1:]:
515 data = line.split()
Yanray Wang9b174e92023-07-17 17:59:53 +0800516 # file_name: SizeEntry(text, data, bss, dec)
517 size_record[data[5]] = CodeSizeGeneratorWithSize.SizeEntry(
518 data[0], data[1], data[2], data[3])
Yanray Wang6ef50492023-07-26 14:59:37 +0800519 self.code_size.setdefault(git_rev, {}).update({mod: size_record})
Yanray Wang16ebc572023-05-30 18:10:20 +0800520
Yanray Wang955671b2023-07-21 12:08:27 +0800521 def read_size_record(self, git_rev: str, fname: str) -> None:
Yanray Wang16ebc572023-05-30 18:10:20 +0800522 """Read size information from csv file and write it into code_size.
523
524 fname Format: filename text data bss dec
525 """
526 mod = ""
527 size_record = {}
528 with open(fname, 'r') as csv_file:
529 for line in csv_file:
530 data = line.strip().split()
531 # check if we find the beginning of a module
532 if data and data[0] in MBEDTLS_STATIC_LIB:
533 mod = data[0]
534 continue
535
536 if mod:
Yanray Wang9b174e92023-07-17 17:59:53 +0800537 # file_name: SizeEntry(text, data, bss, dec)
538 size_record[data[0]] = CodeSizeGeneratorWithSize.SizeEntry(
Yanray Wangfc6ed4d2023-07-14 17:33:09 +0800539 data[1], data[2], data[3], data[4])
Yanray Wang16ebc572023-05-30 18:10:20 +0800540
541 # check if we hit record for the end of a module
542 m = re.match(r'.?TOTALS', line)
543 if m:
Yanray Wang955671b2023-07-21 12:08:27 +0800544 if git_rev in self.code_size:
545 self.code_size[git_rev].update({mod: size_record})
Yanray Wang16ebc572023-05-30 18:10:20 +0800546 else:
Yanray Wang955671b2023-07-21 12:08:27 +0800547 self.code_size[git_rev] = {mod: size_record}
Yanray Wang16ebc572023-05-30 18:10:20 +0800548 mod = ""
549 size_record = {}
550
551 def _size_reader_helper(
552 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800553 git_rev: str,
Yanray Wangb664cb72023-07-18 12:28:35 +0800554 output: typing_util.Writable,
555 with_markdown=False
Yanray Wang16ebc572023-05-30 18:10:20 +0800556 ) -> typing.Iterator[tuple]:
Yanray Wang955671b2023-07-21 12:08:27 +0800557 """A helper function to peel code_size based on Git revision."""
558 for mod, file_size in self.code_size[git_rev].items():
Yanray Wangb664cb72023-07-18 12:28:35 +0800559 if not with_markdown:
560 output.write("\n" + mod + "\n")
Yanray Wang16ebc572023-05-30 18:10:20 +0800561 for fname, size_entry in file_size.items():
562 yield mod, fname, size_entry
563
Yanray Wang95059002023-07-24 12:29:22 +0800564 def write_record(
Yanray Wang16ebc572023-05-30 18:10:20 +0800565 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800566 git_rev: str,
Yanray Wang95059002023-07-24 12:29:22 +0800567 code_size_text: typing.Dict[str, str],
Yanray Wang16ebc572023-05-30 18:10:20 +0800568 output: typing_util.Writable
569 ) -> None:
570 """Write size information to a file.
571
572 Writing Format: file_name text data bss total(dec)
573 """
Yanray Wang95059002023-07-24 12:29:22 +0800574 for mod, size_text in code_size_text.items():
575 self._set_size_record(git_rev, mod, size_text)
576
Yanray Wangb664cb72023-07-18 12:28:35 +0800577 format_string = "{:<30} {:>7} {:>7} {:>7} {:>7}\n"
578 output.write(format_string.format("filename",
579 "text", "data", "bss", "total"))
Yanray Wang955671b2023-07-21 12:08:27 +0800580 for _, fname, size_entry in self._size_reader_helper(git_rev, output):
Yanray Wangb664cb72023-07-18 12:28:35 +0800581 output.write(format_string.format(fname,
582 size_entry.text, size_entry.data,
583 size_entry.bss, size_entry.total))
Yanray Wang16ebc572023-05-30 18:10:20 +0800584
Yanray Wang95059002023-07-24 12:29:22 +0800585 def write_comparison(
Yanray Wang16ebc572023-05-30 18:10:20 +0800586 self,
587 old_rev: str,
588 new_rev: str,
Yanray Wangb664cb72023-07-18 12:28:35 +0800589 output: typing_util.Writable,
Yanray Wang95059002023-07-24 12:29:22 +0800590 with_markdown=False
Yanray Wang16ebc572023-05-30 18:10:20 +0800591 ) -> None:
592 """Write comparison result into a file.
593
Yanray Wang9b174e92023-07-17 17:59:53 +0800594 Writing Format: file_name current(text,data) old(text,data)\
595 change(text,data) change_pct%(text,data)
Yanray Wang16ebc572023-05-30 18:10:20 +0800596 """
Yanray Wang9b174e92023-07-17 17:59:53 +0800597
598 def cal_size_section_variation(mod, fname, size_entry, attr):
599 new_size = int(size_entry.__dict__[attr])
Yanray Wang955671b2023-07-21 12:08:27 +0800600 # check if we have the file in old Git revision
Yanray Wang16ebc572023-05-30 18:10:20 +0800601 if fname in self.code_size[old_rev][mod]:
Yanray Wang9b174e92023-07-17 17:59:53 +0800602 old_size = int(self.code_size[old_rev][mod][fname].__dict__[attr])
Yanray Wang16ebc572023-05-30 18:10:20 +0800603 change = new_size - old_size
604 if old_size != 0:
605 change_pct = change / old_size
606 else:
607 change_pct = 0
Yanray Wang9b174e92023-07-17 17:59:53 +0800608 return [new_size, old_size, change, change_pct]
Yanray Wang16ebc572023-05-30 18:10:20 +0800609 else:
Yanray Wang9b174e92023-07-17 17:59:53 +0800610 return [new_size]
611
Yanray Wangb664cb72023-07-18 12:28:35 +0800612 if with_markdown:
613 format_string = "| {:<30} | {:<18} | {:<14} | {:<17} | {:<18} |\n"
614 else:
615 format_string = "{:<30} {:<18} {:<14} {:<17} {:<18}\n"
616
Yanray Wang386c2f92023-07-20 15:32:15 +0800617 output.write(format_string
618 .format("filename",
619 "current(text,data)", "old(text,data)",
620 "change(text,data)", "change%(text,data)"))
Yanray Wangb664cb72023-07-18 12:28:35 +0800621 if with_markdown:
622 output.write(format_string
Yanray Wangbef1acd2023-07-26 10:45:11 +0800623 .format(":----", "----:", "----:", "----:", "----:"))
Yanray Wangb664cb72023-07-18 12:28:35 +0800624
Yanray Wang386c2f92023-07-20 15:32:15 +0800625 for mod, fname, size_entry in \
Yanray Wangb664cb72023-07-18 12:28:35 +0800626 self._size_reader_helper(new_rev, output, with_markdown):
627 text_vari = cal_size_section_variation(mod, fname,
628 size_entry, 'text')
629 data_vari = cal_size_section_variation(mod, fname,
630 size_entry, 'data')
Yanray Wang9b174e92023-07-17 17:59:53 +0800631
632 if len(text_vari) != 1:
Yanray Wangb664cb72023-07-18 12:28:35 +0800633 # skip the files that haven't changed in code size if we write
634 # comparison result in a markdown table.
635 if with_markdown and text_vari[2] == 0 and data_vari[2] == 0:
636 continue
Yanray Wang386c2f92023-07-20 15:32:15 +0800637 output.write(
638 format_string
639 .format(fname,
Yanray Wange4a36362023-07-25 10:37:11 +0800640 # current(text,data)
Yanray Wang386c2f92023-07-20 15:32:15 +0800641 str(text_vari[0]) + "," + str(data_vari[0]),
Yanray Wange4a36362023-07-25 10:37:11 +0800642 # old(text,data)
Yanray Wang386c2f92023-07-20 15:32:15 +0800643 str(text_vari[1]) + "," + str(data_vari[1]),
Yanray Wange4a36362023-07-25 10:37:11 +0800644 # change(text,data)
Yanray Wang386c2f92023-07-20 15:32:15 +0800645 str(text_vari[2]) + "," + str(data_vari[2]),
Yanray Wange4a36362023-07-25 10:37:11 +0800646 # change%(text,data)
Yanray Wang25bd3312023-07-25 10:24:20 +0800647 "{:.0%}".format(text_vari[3]) + ","
648 + "{:.0%}".format(data_vari[3])))
Yanray Wang9b174e92023-07-17 17:59:53 +0800649 else:
Yanray Wangf2cd7172023-07-24 16:56:46 +0800650 output.write(
651 format_string
652 .format(fname,
Yanray Wange4a36362023-07-25 10:37:11 +0800653 # current(text,data)
Yanray Wangf2cd7172023-07-24 16:56:46 +0800654 str(text_vari[0]) + "," + str(data_vari[0]),
655 'None', 'None', 'None'))
Yanray Wang16ebc572023-05-30 18:10:20 +0800656
657
Yanray Wangfc6ed4d2023-07-14 17:33:09 +0800658class CodeSizeComparison:
Xiaofei Bai2400b502021-10-21 12:22:58 +0000659 """Compare code size between two Git revisions."""
Xiaofei Baibca03e52021-09-09 09:42:37 +0000660
Yanray Wang955671b2023-07-21 12:08:27 +0800661 def __init__( #pylint: disable=too-many-arguments
Yanray Wang72b105f2023-05-31 15:20:39 +0800662 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800663 old_size_dist_info: CodeSizeDistinctInfo,
664 new_size_dist_info: CodeSizeDistinctInfo,
665 size_common_info: CodeSizeCommonInfo,
666 result_options: CodeSizeResultInfo,
Yanray Wang21127f72023-07-19 12:09:45 +0800667 logger: logging.Logger,
Yanray Wang72b105f2023-05-31 15:20:39 +0800668 ) -> None:
Xiaofei Baibca03e52021-09-09 09:42:37 +0000669 """
Yanray Wang955671b2023-07-21 12:08:27 +0800670 :param old_size_dist_info: CodeSizeDistinctInfo containing old distinct
671 info to compare code size with.
672 :param new_size_dist_info: CodeSizeDistinctInfo containing new distinct
673 info to take as comparision base.
674 :param size_common_info: CodeSizeCommonInfo containing common info for
675 both old and new size distinct info and
676 measurement tool.
677 :param result_options: CodeSizeResultInfo containing results options for
678 code size record and comparision.
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800679 :param logger: logging module
Xiaofei Baibca03e52021-09-09 09:42:37 +0000680 """
Xiaofei Baibca03e52021-09-09 09:42:37 +0000681
Yanray Wang21127f72023-07-19 12:09:45 +0800682 self.logger = logger
683
Yanray Wang955671b2023-07-21 12:08:27 +0800684 self.old_size_dist_info = old_size_dist_info
685 self.new_size_dist_info = new_size_dist_info
686 self.size_common_info = size_common_info
Yanray Wang5605c6f2023-07-21 16:09:00 +0800687 # infer pre make command
688 self.old_size_dist_info.pre_make_cmd = CodeSizeBuildInfo(
689 self.old_size_dist_info, self.size_common_info.host_arch,
690 self.logger).infer_pre_make_command()
691 self.new_size_dist_info.pre_make_cmd = CodeSizeBuildInfo(
692 self.new_size_dist_info, self.size_common_info.host_arch,
693 self.logger).infer_pre_make_command()
Yanray Wang386c2f92023-07-20 15:32:15 +0800694 # infer make command
Yanray Wang955671b2023-07-21 12:08:27 +0800695 self.old_size_dist_info.make_cmd = CodeSizeBuildInfo(
696 self.old_size_dist_info, self.size_common_info.host_arch,
Yanray Wang21127f72023-07-19 12:09:45 +0800697 self.logger).infer_make_command()
Yanray Wang955671b2023-07-21 12:08:27 +0800698 self.new_size_dist_info.make_cmd = CodeSizeBuildInfo(
699 self.new_size_dist_info, self.size_common_info.host_arch,
Yanray Wang21127f72023-07-19 12:09:45 +0800700 self.logger).infer_make_command()
Yanray Wang386c2f92023-07-20 15:32:15 +0800701 # initialize size parser with corresponding measurement tool
Yanray Wang21127f72023-07-19 12:09:45 +0800702 self.code_size_generator = self.__generate_size_parser()
Xiaofei Baibca03e52021-09-09 09:42:37 +0000703
Yanray Wang955671b2023-07-21 12:08:27 +0800704 self.result_options = result_options
705 self.csv_dir = os.path.abspath(self.result_options.record_dir)
706 os.makedirs(self.csv_dir, exist_ok=True)
707 self.comp_dir = os.path.abspath(self.result_options.comp_dir)
708 os.makedirs(self.comp_dir, exist_ok=True)
709
Yanray Wang21127f72023-07-19 12:09:45 +0800710 def __generate_size_parser(self):
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800711 """Generate a parser for the corresponding measurement tool."""
Yanray Wang955671b2023-07-21 12:08:27 +0800712 if re.match(r'size', self.size_common_info.measure_cmd.strip()):
Yanray Wang21127f72023-07-19 12:09:45 +0800713 return CodeSizeGeneratorWithSize(self.logger)
Yanray Wang802af162023-07-17 14:04:30 +0800714 else:
Yanray Wang21127f72023-07-19 12:09:45 +0800715 self.logger.error("Unsupported measurement tool: `{}`."
Yanray Wang955671b2023-07-21 12:08:27 +0800716 .format(self.size_common_info.measure_cmd
Yanray Wang21127f72023-07-19 12:09:45 +0800717 .strip().split(' ')[0]))
Yanray Wang802af162023-07-17 14:04:30 +0800718 sys.exit(1)
719
Yanray Wang386c2f92023-07-20 15:32:15 +0800720 def cal_code_size(
721 self,
Yanray Wang955671b2023-07-21 12:08:27 +0800722 size_dist_info: CodeSizeDistinctInfo
Yanray Wang386c2f92023-07-20 15:32:15 +0800723 ) -> typing.Dict[str, str]:
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800724 """Calculate code size of library/*.o in a UTF-8 encoding"""
Xiaofei Baibca03e52021-09-09 09:42:37 +0000725
Yanray Wang955671b2023-07-21 12:08:27 +0800726 return CodeSizeCalculator(size_dist_info.git_rev,
Yanray Wang5605c6f2023-07-21 16:09:00 +0800727 size_dist_info.pre_make_cmd,
Yanray Wang955671b2023-07-21 12:08:27 +0800728 size_dist_info.make_cmd,
729 self.size_common_info.measure_cmd,
Yanray Wang21127f72023-07-19 12:09:45 +0800730 self.logger).cal_libraries_code_size()
Yanray Wang8804db92023-05-30 18:18:18 +0800731
Yanray Wang955671b2023-07-21 12:08:27 +0800732 def gen_code_size_report(self, size_dist_info: CodeSizeDistinctInfo) -> None:
Yanray Wang5e9130a2023-07-17 11:55:54 +0800733 """Generate code size record and write it into a file."""
Xiaofei Baibca03e52021-09-09 09:42:37 +0000734
Yanray Wang21127f72023-07-19 12:09:45 +0800735 self.logger.info("Start to generate code size record for {}."
Yanray Wang955671b2023-07-21 12:08:27 +0800736 .format(size_dist_info.git_rev))
Yanray Wanga6cf6922023-07-24 15:20:42 +0800737 output_file = os.path.join(
738 self.csv_dir,
739 '{}-{}.csv'
740 .format(size_dist_info.get_info_indication(),
741 self.size_common_info.get_info_indication()))
Xiaofei Baibca03e52021-09-09 09:42:37 +0000742 # Check if the corresponding record exists
Yanray Wang955671b2023-07-21 12:08:27 +0800743 if size_dist_info.git_rev != "current" and \
Yanray Wang21127f72023-07-19 12:09:45 +0800744 os.path.exists(output_file):
745 self.logger.debug("Code size csv file for {} already exists."
Yanray Wang955671b2023-07-21 12:08:27 +0800746 .format(size_dist_info.git_rev))
Yanray Wang21127f72023-07-19 12:09:45 +0800747 self.code_size_generator.read_size_record(
Yanray Wang955671b2023-07-21 12:08:27 +0800748 size_dist_info.git_rev, output_file)
Xiaofei Baibca03e52021-09-09 09:42:37 +0000749 else:
Yanray Wang95059002023-07-24 12:29:22 +0800750 # measure code size
751 code_size_text = self.cal_code_size(size_dist_info)
752
753 self.logger.debug("Generating code size csv for {}."
754 .format(size_dist_info.git_rev))
755 output = open(output_file, "w")
756 self.code_size_generator.write_record(
757 size_dist_info.git_rev, code_size_text, output)
Xiaofei Baibca03e52021-09-09 09:42:37 +0000758
Yanray Wang386c2f92023-07-20 15:32:15 +0800759 def gen_code_size_comparison(self) -> None:
Yanray Wang955671b2023-07-21 12:08:27 +0800760 """Generate results of code size changes between two Git revisions,
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800761 old and new.
762
Yanray Wang955671b2023-07-21 12:08:27 +0800763 - Measured code size result of these two Git revisions must be available.
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800764 - The result is directed into either file / stdout depending on
Yanray Wang955671b2023-07-21 12:08:27 +0800765 the option, size_common_info.result_options.stdout. (Default: file)
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800766 """
Xiaofei Baibca03e52021-09-09 09:42:37 +0000767
Yanray Wang21127f72023-07-19 12:09:45 +0800768 self.logger.info("Start to generate comparision result between "\
769 "{} and {}."
Yanray Wang955671b2023-07-21 12:08:27 +0800770 .format(self.old_size_dist_info.git_rev,
771 self.new_size_dist_info.git_rev))
Yanray Wanga6cf6922023-07-24 15:20:42 +0800772 if self.result_options.stdout:
773 output = sys.stdout
774 else:
775 output_file = os.path.join(
776 self.comp_dir,
777 '{}-{}-{}.csv'
778 .format(self.old_size_dist_info.get_info_indication(),
779 self.new_size_dist_info.get_info_indication(),
780 self.size_common_info.get_info_indication()))
781 output = open(output_file, "w")
Xiaofei Bai184e8b62021-10-26 09:23:42 +0000782
Yanray Wang95059002023-07-24 12:29:22 +0800783 self.logger.debug("Generating comparison results between {} and {}."
784 .format(self.old_size_dist_info.git_rev,
785 self.new_size_dist_info.git_rev))
Yanray Wangea842e72023-07-26 10:34:39 +0800786 if self.result_options.with_markdown or self.result_options.stdout:
787 print("Measure code size between {} and {} by `{}`."
788 .format(self.old_size_dist_info.get_info_indication(),
789 self.new_size_dist_info.get_info_indication(),
790 self.size_common_info.get_info_indication()),
791 file=output)
Yanray Wang95059002023-07-24 12:29:22 +0800792 self.code_size_generator.write_comparison(
Yanray Wang955671b2023-07-21 12:08:27 +0800793 self.old_size_dist_info.git_rev,
794 self.new_size_dist_info.git_rev,
Yanray Wang95059002023-07-24 12:29:22 +0800795 output, self.result_options.with_markdown)
Yanray Wang21127f72023-07-19 12:09:45 +0800796
Yanray Wang386c2f92023-07-20 15:32:15 +0800797 def get_comparision_results(self) -> None:
Yanray Wang955671b2023-07-21 12:08:27 +0800798 """Compare size of library/*.o between self.old_size_dist_info and
799 self.old_size_dist_info and generate the result file."""
Gilles Peskined9071e72022-09-18 21:17:09 +0200800 build_tree.check_repo_path()
Yanray Wang955671b2023-07-21 12:08:27 +0800801 self.gen_code_size_report(self.old_size_dist_info)
802 self.gen_code_size_report(self.new_size_dist_info)
Yanray Wang386c2f92023-07-20 15:32:15 +0800803 self.gen_code_size_comparison()
Xiaofei Baibca03e52021-09-09 09:42:37 +0000804
Xiaofei Bai2400b502021-10-21 12:22:58 +0000805def main():
Yanray Wang502c54f2023-05-31 11:41:36 +0800806 parser = argparse.ArgumentParser(description=(__doc__))
807 group_required = parser.add_argument_group(
808 'required arguments',
809 'required arguments to parse for running ' + os.path.basename(__file__))
810 group_required.add_argument(
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800811 '-o', '--old-rev', type=str, required=True,
Yanray Wang955671b2023-07-21 12:08:27 +0800812 help='old Git revision for comparison.')
Yanray Wang502c54f2023-05-31 11:41:36 +0800813
814 group_optional = parser.add_argument_group(
815 'optional arguments',
816 'optional arguments to parse for running ' + os.path.basename(__file__))
817 group_optional.add_argument(
Yanray Wang955671b2023-07-21 12:08:27 +0800818 '--record_dir', type=str, default='code_size_records',
819 help='directory where code size record is stored. '
820 '(Default: code_size_records)')
821 group_optional.add_argument(
822 '-r', '--comp-dir', type=str, default='comparison',
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800823 help='directory where comparison result is stored. '
824 '(Default: comparison)')
Yanray Wang502c54f2023-05-31 11:41:36 +0800825 group_optional.add_argument(
Yanray Wang68265f42023-07-26 14:44:52 +0800826 '-n', '--new-rev', type=str, default='current',
Yanray Wang955671b2023-07-21 12:08:27 +0800827 help='new Git revision as comparison base. '
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800828 '(Default is the current work directory, including uncommitted '
829 'changes.)')
Yanray Wang502c54f2023-05-31 11:41:36 +0800830 group_optional.add_argument(
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800831 '-a', '--arch', type=str, default=detect_arch(),
Yanray Wang23bd5322023-05-24 11:03:59 +0800832 choices=list(map(lambda s: s.value, SupportedArch)),
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800833 help='Specify architecture for code size comparison. '
834 '(Default is the host architecture.)')
Yanray Wang502c54f2023-05-31 11:41:36 +0800835 group_optional.add_argument(
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800836 '-c', '--config', type=str, default=SupportedConfig.DEFAULT.value,
Yanray Wang6a862582023-05-24 12:24:38 +0800837 choices=list(map(lambda s: s.value, SupportedConfig)),
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800838 help='Specify configuration type for code size comparison. '
839 '(Default is the current MbedTLS configuration.)')
Yanray Wangb664cb72023-07-18 12:28:35 +0800840 group_optional.add_argument(
841 '--markdown', action='store_true', dest='markdown',
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800842 help='Show comparision of code size in a markdown table. '
843 '(Only show the files that have changed).')
Yanray Wang227576a2023-07-18 14:35:05 +0800844 group_optional.add_argument(
845 '--stdout', action='store_true', dest='stdout',
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800846 help='Set this option to direct comparison result into sys.stdout. '
847 '(Default: file)')
Yanray Wang21127f72023-07-19 12:09:45 +0800848 group_optional.add_argument(
849 '--verbose', action='store_true', dest='verbose',
Yanray Wang5b64e4c2023-07-20 15:09:51 +0800850 help='Show logs in detail for code size measurement. '
851 '(Default: False)')
Xiaofei Baibca03e52021-09-09 09:42:37 +0000852 comp_args = parser.parse_args()
853
Yanray Wang21127f72023-07-19 12:09:45 +0800854 logger = logging.getLogger()
855 logging_util.configure_logger(logger)
Yanray Wang533cde22023-07-26 10:17:17 +0800856 if comp_args.stdout and not comp_args.verbose:
857 logger.setLevel(logging.ERROR)
858 else:
859 logger.setLevel(logging.DEBUG if comp_args.verbose else logging.INFO)
Yanray Wang21127f72023-07-19 12:09:45 +0800860
Yanray Wang955671b2023-07-21 12:08:27 +0800861 if os.path.isfile(comp_args.comp_dir):
862 logger.error("{} is not a directory".format(comp_args.comp_dir))
Xiaofei Baibca03e52021-09-09 09:42:37 +0000863 parser.exit()
864
Yanray Wang68265f42023-07-26 14:44:52 +0800865 comp_args.old_rev = CodeSizeCalculator.validate_git_revision(
866 comp_args.old_rev)
867 if comp_args.new_rev != 'current':
868 comp_args.new_rev = CodeSizeCalculator.validate_git_revision(
Yanray Wang955671b2023-07-21 12:08:27 +0800869 comp_args.new_rev)
Xiaofei Bai2400b502021-10-21 12:22:58 +0000870
Yanray Wang5605c6f2023-07-21 16:09:00 +0800871 # version, git_rev, arch, config, compiler, opt_level
Yanray Wang955671b2023-07-21 12:08:27 +0800872 old_size_dist_info = CodeSizeDistinctInfo(
Yanray Wang68265f42023-07-26 14:44:52 +0800873 'old', comp_args.old_rev, comp_args.arch, comp_args.config, 'cc', '-Os')
Yanray Wang955671b2023-07-21 12:08:27 +0800874 new_size_dist_info = CodeSizeDistinctInfo(
Yanray Wang68265f42023-07-26 14:44:52 +0800875 'new', comp_args.new_rev, comp_args.arch, comp_args.config, 'cc', '-Os')
Yanray Wang5605c6f2023-07-21 16:09:00 +0800876 # host_arch, measure_cmd
Yanray Wang955671b2023-07-21 12:08:27 +0800877 size_common_info = CodeSizeCommonInfo(
878 detect_arch(), 'size -t')
Yanray Wang5605c6f2023-07-21 16:09:00 +0800879 # record_dir, comp_dir, with_markdown, stdout
Yanray Wang955671b2023-07-21 12:08:27 +0800880 result_options = CodeSizeResultInfo(
881 comp_args.record_dir, comp_args.comp_dir,
882 comp_args.markdown, comp_args.stdout)
Yanray Wang923f9432023-07-17 12:43:00 +0800883
Yanray Wanga6cf6922023-07-24 15:20:42 +0800884 logger.info("Measure code size between {} and {} by `{}`."
885 .format(old_size_dist_info.get_info_indication(),
886 new_size_dist_info.get_info_indication(),
887 size_common_info.get_info_indication()))
Yanray Wang955671b2023-07-21 12:08:27 +0800888 CodeSizeComparison(old_size_dist_info, new_size_dist_info,
889 size_common_info, result_options,
890 logger).get_comparision_results()
Xiaofei Baibca03e52021-09-09 09:42:37 +0000891
Xiaofei Baibca03e52021-09-09 09:42:37 +0000892if __name__ == "__main__":
Xiaofei Bai2400b502021-10-21 12:22:58 +0000893 main()