2021-09-09 11:42:37 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
"""
|
|
|
|
This script is for comparing the size of the library files from two
|
|
|
|
different Git revisions within an Mbed TLS repository.
|
|
|
|
The results of the comparison is formatted as csv and stored at a
|
|
|
|
configurable location.
|
|
|
|
Note: must be run from Mbed TLS root.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Copyright The Mbed TLS Contributors
|
2023-11-02 20:47:20 +01:00
|
|
|
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
|
2021-09-09 11:42:37 +02:00
|
|
|
|
|
|
|
import argparse
|
2023-07-19 06:09:45 +02:00
|
|
|
import logging
|
2021-09-09 11:42:37 +02:00
|
|
|
import os
|
2023-05-30 12:10:20 +02:00
|
|
|
import re
|
2023-07-21 10:09:00 +02:00
|
|
|
import shutil
|
2021-09-09 11:42:37 +02:00
|
|
|
import subprocess
|
|
|
|
import sys
|
2023-05-30 12:10:20 +02:00
|
|
|
import typing
|
2023-05-24 05:03:59 +02:00
|
|
|
from enum import Enum
|
2021-09-09 11:42:37 +02:00
|
|
|
|
2022-09-18 21:17:09 +02:00
|
|
|
from mbedtls_dev import build_tree
|
2023-07-19 06:09:45 +02:00
|
|
|
from mbedtls_dev import logging_util
|
|
|
|
from mbedtls_dev import typing_util
|
2022-09-18 21:17:09 +02:00
|
|
|
|
2023-05-24 05:03:59 +02:00
|
|
|
class SupportedArch(Enum):
|
|
|
|
"""Supported architecture for code size measurement."""
|
|
|
|
AARCH64 = 'aarch64'
|
|
|
|
AARCH32 = 'aarch32'
|
2023-05-29 10:45:56 +02:00
|
|
|
ARMV8_M = 'armv8-m'
|
2023-05-24 05:03:59 +02:00
|
|
|
X86_64 = 'x86_64'
|
|
|
|
X86 = 'x86'
|
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
|
2023-05-24 06:24:38 +02:00
|
|
|
class SupportedConfig(Enum):
|
|
|
|
"""Supported configuration for code size measurement."""
|
|
|
|
DEFAULT = 'default'
|
|
|
|
TFM_MEDIUM = 'tfm-medium'
|
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
|
2023-05-30 12:10:20 +02:00
|
|
|
# Static library
|
|
|
|
MBEDTLS_STATIC_LIB = {
|
|
|
|
'CRYPTO': 'library/libmbedcrypto.a',
|
|
|
|
'X509': 'library/libmbedx509.a',
|
|
|
|
'TLS': 'library/libmbedtls.a',
|
|
|
|
}
|
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
class CodeSizeDistinctInfo: # pylint: disable=too-few-public-methods
|
|
|
|
"""Data structure to store possibly distinct information for code size
|
|
|
|
comparison."""
|
|
|
|
def __init__( #pylint: disable=too-many-arguments
|
|
|
|
self,
|
|
|
|
version: str,
|
|
|
|
git_rev: str,
|
|
|
|
arch: str,
|
|
|
|
config: str,
|
2023-07-21 10:09:00 +02:00
|
|
|
compiler: str,
|
|
|
|
opt_level: str,
|
2023-07-21 06:08:27 +02:00
|
|
|
) -> None:
|
|
|
|
"""
|
|
|
|
:param: version: which version to compare with for code size.
|
|
|
|
:param: git_rev: Git revision to calculate code size.
|
|
|
|
:param: arch: architecture to measure code size on.
|
|
|
|
:param: config: Configuration type to calculate code size.
|
|
|
|
(See SupportedConfig)
|
2023-07-21 10:09:00 +02:00
|
|
|
:param: compiler: compiler used to build library/*.o.
|
|
|
|
:param: opt_level: Options that control optimization. (E.g. -Os)
|
2023-07-21 06:08:27 +02:00
|
|
|
"""
|
|
|
|
self.version = version
|
|
|
|
self.git_rev = git_rev
|
|
|
|
self.arch = arch
|
|
|
|
self.config = config
|
2023-07-21 10:09:00 +02:00
|
|
|
self.compiler = compiler
|
|
|
|
self.opt_level = opt_level
|
|
|
|
# Note: Variables below are not initialized by class instantiation.
|
|
|
|
self.pre_make_cmd = [] #type: typing.List[str]
|
|
|
|
self.make_cmd = ''
|
2023-07-21 06:08:27 +02:00
|
|
|
|
2023-07-24 09:20:42 +02:00
|
|
|
def get_info_indication(self):
|
|
|
|
"""Return a unique string to indicate Code Size Distinct Information."""
|
2023-07-26 08:59:37 +02:00
|
|
|
return '{git_rev}-{arch}-{config}-{compiler}'.format(**self.__dict__)
|
2023-07-24 09:20:42 +02:00
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
|
|
|
|
class CodeSizeCommonInfo: # pylint: disable=too-few-public-methods
|
|
|
|
"""Data structure to store common information for code size comparison."""
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
host_arch: str,
|
|
|
|
measure_cmd: str,
|
|
|
|
) -> None:
|
|
|
|
"""
|
|
|
|
:param host_arch: host architecture.
|
|
|
|
:param measure_cmd: command to measure code size for library/*.o.
|
|
|
|
"""
|
|
|
|
self.host_arch = host_arch
|
|
|
|
self.measure_cmd = measure_cmd
|
|
|
|
|
2023-07-24 09:20:42 +02:00
|
|
|
def get_info_indication(self):
|
|
|
|
"""Return a unique string to indicate Code Size Common Information."""
|
2023-07-25 04:37:11 +02:00
|
|
|
return '{measure_tool}'\
|
|
|
|
.format(measure_tool=self.measure_cmd.strip().split(' ')[0])
|
2023-07-21 06:08:27 +02:00
|
|
|
|
|
|
|
class CodeSizeResultInfo: # pylint: disable=too-few-public-methods
|
|
|
|
"""Data structure to store result options for code size comparison."""
|
2023-07-28 10:34:05 +02:00
|
|
|
def __init__( #pylint: disable=too-many-arguments
|
2023-07-21 06:08:27 +02:00
|
|
|
self,
|
|
|
|
record_dir: str,
|
|
|
|
comp_dir: str,
|
|
|
|
with_markdown=False,
|
|
|
|
stdout=False,
|
2023-07-28 10:34:05 +02:00
|
|
|
show_all=False,
|
2023-07-21 06:08:27 +02:00
|
|
|
) -> None:
|
|
|
|
"""
|
|
|
|
:param record_dir: directory to store code size record.
|
|
|
|
:param comp_dir: directory to store results of code size comparision.
|
|
|
|
:param with_markdown: write comparision result into a markdown table.
|
|
|
|
(Default: False)
|
|
|
|
:param stdout: direct comparison result into sys.stdout.
|
|
|
|
(Default False)
|
2023-07-28 10:34:05 +02:00
|
|
|
:param show_all: show all objects in comparison result. (Default False)
|
2023-07-21 06:08:27 +02:00
|
|
|
"""
|
|
|
|
self.record_dir = record_dir
|
|
|
|
self.comp_dir = comp_dir
|
|
|
|
self.with_markdown = with_markdown
|
|
|
|
self.stdout = stdout
|
2023-07-28 10:34:05 +02:00
|
|
|
self.show_all = show_all
|
2023-07-21 06:08:27 +02:00
|
|
|
|
|
|
|
|
2023-05-24 05:03:59 +02:00
|
|
|
DETECT_ARCH_CMD = "cc -dM -E - < /dev/null"
|
|
|
|
def detect_arch() -> str:
|
|
|
|
"""Auto-detect host architecture."""
|
|
|
|
cc_output = subprocess.check_output(DETECT_ARCH_CMD, shell=True).decode()
|
2023-07-20 09:32:15 +02:00
|
|
|
if '__aarch64__' in cc_output:
|
2023-05-24 05:03:59 +02:00
|
|
|
return SupportedArch.AARCH64.value
|
2023-07-20 09:32:15 +02:00
|
|
|
if '__arm__' in cc_output:
|
2023-05-24 05:03:59 +02:00
|
|
|
return SupportedArch.AARCH32.value
|
2023-07-20 09:32:15 +02:00
|
|
|
if '__x86_64__' in cc_output:
|
2023-05-24 05:03:59 +02:00
|
|
|
return SupportedArch.X86_64.value
|
2023-07-26 11:16:29 +02:00
|
|
|
if '__i386__' in cc_output:
|
2023-05-24 05:03:59 +02:00
|
|
|
return SupportedArch.X86.value
|
|
|
|
else:
|
|
|
|
print("Unknown host architecture, cannot auto-detect arch.")
|
|
|
|
sys.exit(1)
|
2022-09-18 21:17:09 +02:00
|
|
|
|
2023-09-06 05:50:45 +02:00
|
|
|
TFM_MEDIUM_CONFIG_H = 'configs/ext/tfm_mbedcrypto_config_profile_medium.h'
|
|
|
|
TFM_MEDIUM_CRYPTO_CONFIG_H = 'configs/ext/crypto_config_profile_medium.h'
|
2023-07-21 10:09:00 +02:00
|
|
|
|
|
|
|
CONFIG_H = 'include/mbedtls/mbedtls_config.h'
|
|
|
|
CRYPTO_CONFIG_H = 'include/psa/crypto_config.h'
|
|
|
|
BACKUP_SUFFIX = '.code_size.bak'
|
|
|
|
|
2023-07-17 06:43:00 +02:00
|
|
|
class CodeSizeBuildInfo: # pylint: disable=too-few-public-methods
|
2023-05-24 06:24:38 +02:00
|
|
|
"""Gather information used to measure code size.
|
|
|
|
|
|
|
|
It collects information about architecture, configuration in order to
|
|
|
|
infer build command for code size measurement.
|
|
|
|
"""
|
|
|
|
|
2023-05-31 05:08:04 +02:00
|
|
|
SupportedArchConfig = [
|
2023-07-20 09:32:15 +02:00
|
|
|
'-a ' + SupportedArch.AARCH64.value + ' -c ' + SupportedConfig.DEFAULT.value,
|
|
|
|
'-a ' + SupportedArch.AARCH32.value + ' -c ' + SupportedConfig.DEFAULT.value,
|
|
|
|
'-a ' + SupportedArch.X86_64.value + ' -c ' + SupportedConfig.DEFAULT.value,
|
|
|
|
'-a ' + SupportedArch.X86.value + ' -c ' + SupportedConfig.DEFAULT.value,
|
|
|
|
'-a ' + SupportedArch.ARMV8_M.value + ' -c ' + SupportedConfig.TFM_MEDIUM.value,
|
2023-05-31 05:08:04 +02:00
|
|
|
]
|
|
|
|
|
2023-07-17 08:04:30 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
2023-07-21 06:08:27 +02:00
|
|
|
size_dist_info: CodeSizeDistinctInfo,
|
2023-07-19 06:09:45 +02:00
|
|
|
host_arch: str,
|
|
|
|
logger: logging.Logger,
|
2023-07-17 08:04:30 +02:00
|
|
|
) -> None:
|
2023-05-24 06:24:38 +02:00
|
|
|
"""
|
2023-07-21 06:08:27 +02:00
|
|
|
:param size_dist_info:
|
|
|
|
CodeSizeDistinctInfo containing info for code size measurement.
|
|
|
|
- size_dist_info.arch: architecture to measure code size on.
|
|
|
|
- size_dist_info.config: configuration type to measure
|
|
|
|
code size with.
|
2023-07-21 10:09:00 +02:00
|
|
|
- size_dist_info.compiler: compiler used to build library/*.o.
|
|
|
|
- size_dist_info.opt_level: Options that control optimization.
|
|
|
|
(E.g. -Os)
|
2023-07-20 09:09:51 +02:00
|
|
|
:param host_arch: host architecture.
|
|
|
|
:param logger: logging module
|
2023-05-24 06:24:38 +02:00
|
|
|
"""
|
2023-07-21 10:09:00 +02:00
|
|
|
self.arch = size_dist_info.arch
|
|
|
|
self.config = size_dist_info.config
|
|
|
|
self.compiler = size_dist_info.compiler
|
|
|
|
self.opt_level = size_dist_info.opt_level
|
|
|
|
|
|
|
|
self.make_cmd = ['make', '-j', 'lib']
|
|
|
|
|
2023-07-17 08:04:30 +02:00
|
|
|
self.host_arch = host_arch
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger = logger
|
2023-05-24 06:24:38 +02:00
|
|
|
|
2023-07-21 10:09:00 +02:00
|
|
|
def check_correctness(self) -> bool:
|
|
|
|
"""Check whether we are using proper / supported combination
|
|
|
|
of information to build library/*.o."""
|
|
|
|
|
|
|
|
# default config
|
|
|
|
if self.config == SupportedConfig.DEFAULT.value and \
|
|
|
|
self.arch == self.host_arch:
|
|
|
|
return True
|
|
|
|
# TF-M
|
|
|
|
elif self.arch == SupportedArch.ARMV8_M.value and \
|
|
|
|
self.config == SupportedConfig.TFM_MEDIUM.value:
|
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
def infer_pre_make_command(self) -> typing.List[str]:
|
|
|
|
"""Infer command to set up proper configuration before running make."""
|
|
|
|
pre_make_cmd = [] #type: typing.List[str]
|
|
|
|
if self.config == SupportedConfig.TFM_MEDIUM.value:
|
2023-07-26 09:01:10 +02:00
|
|
|
pre_make_cmd.append('cp {src} {dest}'
|
2023-07-25 04:37:11 +02:00
|
|
|
.format(src=TFM_MEDIUM_CONFIG_H, dest=CONFIG_H))
|
2023-07-26 09:01:10 +02:00
|
|
|
pre_make_cmd.append('cp {src} {dest}'
|
2023-07-25 04:37:11 +02:00
|
|
|
.format(src=TFM_MEDIUM_CRYPTO_CONFIG_H,
|
|
|
|
dest=CRYPTO_CONFIG_H))
|
2023-07-21 10:09:00 +02:00
|
|
|
|
|
|
|
return pre_make_cmd
|
|
|
|
|
|
|
|
def infer_make_cflags(self) -> str:
|
|
|
|
"""Infer CFLAGS by instance attributes in CodeSizeDistinctInfo."""
|
|
|
|
cflags = [] #type: typing.List[str]
|
|
|
|
|
|
|
|
# set optimization level
|
|
|
|
cflags.append(self.opt_level)
|
|
|
|
# set compiler by config
|
|
|
|
if self.config == SupportedConfig.TFM_MEDIUM.value:
|
|
|
|
self.compiler = 'armclang'
|
|
|
|
cflags.append('-mcpu=cortex-m33')
|
|
|
|
# set target
|
|
|
|
if self.compiler == 'armclang':
|
|
|
|
cflags.append('--target=arm-arm-none-eabi')
|
|
|
|
|
|
|
|
return ' '.join(cflags)
|
|
|
|
|
2023-07-17 06:43:00 +02:00
|
|
|
def infer_make_command(self) -> str:
|
2023-07-21 10:09:00 +02:00
|
|
|
"""Infer make command by CFLAGS and CC."""
|
|
|
|
|
|
|
|
if self.check_correctness():
|
|
|
|
# set CFLAGS=
|
|
|
|
self.make_cmd.append('CFLAGS=\'{}\''.format(self.infer_make_cflags()))
|
|
|
|
# set CC=
|
|
|
|
self.make_cmd.append('CC={}'.format(self.compiler))
|
|
|
|
return ' '.join(self.make_cmd)
|
2023-05-24 06:24:38 +02:00
|
|
|
else:
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger.error("Unsupported combination of architecture: {} " \
|
|
|
|
"and configuration: {}.\n"
|
2023-07-21 10:09:00 +02:00
|
|
|
.format(self.arch,
|
|
|
|
self.config))
|
2023-07-26 04:11:31 +02:00
|
|
|
self.logger.error("Please use supported combination of " \
|
2023-07-19 06:09:45 +02:00
|
|
|
"architecture and configuration:")
|
2023-07-17 06:43:00 +02:00
|
|
|
for comb in CodeSizeBuildInfo.SupportedArchConfig:
|
2023-07-26 04:11:31 +02:00
|
|
|
self.logger.error(comb)
|
|
|
|
self.logger.error("")
|
|
|
|
self.logger.error("For your system, please use:")
|
2023-07-17 06:43:00 +02:00
|
|
|
for comb in CodeSizeBuildInfo.SupportedArchConfig:
|
2023-07-17 08:04:30 +02:00
|
|
|
if "default" in comb and self.host_arch not in comb:
|
2023-06-01 05:29:06 +02:00
|
|
|
continue
|
2023-07-26 04:11:31 +02:00
|
|
|
self.logger.error(comb)
|
2023-05-24 06:24:38 +02:00
|
|
|
sys.exit(1)
|
|
|
|
|
2023-07-14 11:33:09 +02:00
|
|
|
|
2023-07-14 11:37:45 +02:00
|
|
|
class CodeSizeCalculator:
|
2023-07-20 09:09:51 +02:00
|
|
|
""" A calculator to calculate code size of library/*.o based on
|
2023-07-14 11:37:45 +02:00
|
|
|
Git revision and code size measurement tool.
|
|
|
|
"""
|
|
|
|
|
2023-07-21 10:09:00 +02:00
|
|
|
def __init__( #pylint: disable=too-many-arguments
|
2023-07-14 11:37:45 +02:00
|
|
|
self,
|
2023-07-21 06:08:27 +02:00
|
|
|
git_rev: str,
|
2023-07-21 10:09:00 +02:00
|
|
|
pre_make_cmd: typing.List[str],
|
2023-07-14 11:37:45 +02:00
|
|
|
make_cmd: str,
|
2023-07-19 06:09:45 +02:00
|
|
|
measure_cmd: str,
|
|
|
|
logger: logging.Logger,
|
2023-07-14 11:37:45 +02:00
|
|
|
) -> None:
|
|
|
|
"""
|
2023-07-21 06:08:27 +02:00
|
|
|
:param git_rev: Git revision. (E.g: commit)
|
2023-07-21 10:09:00 +02:00
|
|
|
:param pre_make_cmd: command to set up proper config before running make.
|
2023-07-20 09:09:51 +02:00
|
|
|
:param make_cmd: command to build library/*.o.
|
|
|
|
:param measure_cmd: command to measure code size for library/*.o.
|
|
|
|
:param logger: logging module
|
2023-07-14 11:37:45 +02:00
|
|
|
"""
|
|
|
|
self.repo_path = "."
|
|
|
|
self.git_command = "git"
|
|
|
|
self.make_clean = 'make clean'
|
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
self.git_rev = git_rev
|
2023-07-21 10:09:00 +02:00
|
|
|
self.pre_make_cmd = pre_make_cmd
|
2023-07-14 11:37:45 +02:00
|
|
|
self.make_cmd = make_cmd
|
2023-07-17 08:04:30 +02:00
|
|
|
self.measure_cmd = measure_cmd
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger = logger
|
2023-07-14 11:37:45 +02:00
|
|
|
|
|
|
|
@staticmethod
|
2023-07-21 06:08:27 +02:00
|
|
|
def validate_git_revision(git_rev: str) -> str:
|
2023-07-14 11:37:45 +02:00
|
|
|
result = subprocess.check_output(["git", "rev-parse", "--verify",
|
2023-07-21 06:08:27 +02:00
|
|
|
git_rev + "^{commit}"],
|
|
|
|
shell=False, universal_newlines=True)
|
2023-07-20 09:32:15 +02:00
|
|
|
return result[:7]
|
2023-07-14 11:37:45 +02:00
|
|
|
|
2023-07-19 06:09:45 +02:00
|
|
|
def _create_git_worktree(self) -> str:
|
2023-07-21 06:08:27 +02:00
|
|
|
"""Create a separate worktree for Git revision.
|
|
|
|
If Git revision is current, use current worktree instead."""
|
2023-07-14 11:37:45 +02:00
|
|
|
|
2023-07-21 10:09:00 +02:00
|
|
|
if self.git_rev == 'current':
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger.debug("Using current work directory.")
|
2023-07-14 11:37:45 +02:00
|
|
|
git_worktree_path = self.repo_path
|
|
|
|
else:
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger.debug("Creating git worktree for {}."
|
2023-07-21 06:08:27 +02:00
|
|
|
.format(self.git_rev))
|
2023-07-19 06:09:45 +02:00
|
|
|
git_worktree_path = os.path.join(self.repo_path,
|
2023-07-21 06:08:27 +02:00
|
|
|
"temp-" + self.git_rev)
|
2023-07-14 11:37:45 +02:00
|
|
|
subprocess.check_output(
|
|
|
|
[self.git_command, "worktree", "add", "--detach",
|
2023-07-21 06:08:27 +02:00
|
|
|
git_worktree_path, self.git_rev], cwd=self.repo_path,
|
2023-07-14 11:37:45 +02:00
|
|
|
stderr=subprocess.STDOUT
|
|
|
|
)
|
|
|
|
|
|
|
|
return git_worktree_path
|
|
|
|
|
2023-07-21 10:09:00 +02:00
|
|
|
@staticmethod
|
|
|
|
def backup_config_files(restore: bool) -> None:
|
|
|
|
"""Backup / Restore config files."""
|
|
|
|
if restore:
|
|
|
|
shutil.move(CONFIG_H + BACKUP_SUFFIX, CONFIG_H)
|
|
|
|
shutil.move(CRYPTO_CONFIG_H + BACKUP_SUFFIX, CRYPTO_CONFIG_H)
|
|
|
|
else:
|
|
|
|
shutil.copy(CONFIG_H, CONFIG_H + BACKUP_SUFFIX)
|
|
|
|
shutil.copy(CRYPTO_CONFIG_H, CRYPTO_CONFIG_H + BACKUP_SUFFIX)
|
|
|
|
|
2023-07-14 11:37:45 +02:00
|
|
|
def _build_libraries(self, git_worktree_path: str) -> None:
|
2023-07-20 09:09:51 +02:00
|
|
|
"""Build library/*.o in the specified worktree."""
|
2023-07-14 11:37:45 +02:00
|
|
|
|
2023-07-20 09:09:51 +02:00
|
|
|
self.logger.debug("Building library/*.o for {}."
|
2023-07-21 06:08:27 +02:00
|
|
|
.format(self.git_rev))
|
2023-07-14 11:37:45 +02:00
|
|
|
my_environment = os.environ.copy()
|
|
|
|
try:
|
2023-07-21 10:09:00 +02:00
|
|
|
if self.git_rev == 'current':
|
|
|
|
self.backup_config_files(restore=False)
|
|
|
|
for pre_cmd in self.pre_make_cmd:
|
|
|
|
subprocess.check_output(
|
|
|
|
pre_cmd, env=my_environment, shell=True,
|
|
|
|
cwd=git_worktree_path, stderr=subprocess.STDOUT,
|
|
|
|
universal_newlines=True
|
|
|
|
)
|
2023-07-14 11:37:45 +02:00
|
|
|
subprocess.check_output(
|
|
|
|
self.make_clean, env=my_environment, shell=True,
|
|
|
|
cwd=git_worktree_path, stderr=subprocess.STDOUT,
|
2023-07-20 09:32:15 +02:00
|
|
|
universal_newlines=True
|
2023-07-14 11:37:45 +02:00
|
|
|
)
|
|
|
|
subprocess.check_output(
|
|
|
|
self.make_cmd, env=my_environment, shell=True,
|
|
|
|
cwd=git_worktree_path, stderr=subprocess.STDOUT,
|
2023-07-20 09:32:15 +02:00
|
|
|
universal_newlines=True
|
2023-07-14 11:37:45 +02:00
|
|
|
)
|
2023-07-21 10:09:00 +02:00
|
|
|
if self.git_rev == 'current':
|
|
|
|
self.backup_config_files(restore=True)
|
2023-07-14 11:37:45 +02:00
|
|
|
except subprocess.CalledProcessError as e:
|
|
|
|
self._handle_called_process_error(e, git_worktree_path)
|
|
|
|
|
2023-07-20 09:32:15 +02:00
|
|
|
def _gen_raw_code_size(self, git_worktree_path: str) -> typing.Dict[str, str]:
|
2023-07-20 09:09:51 +02:00
|
|
|
"""Measure code size by a tool and return in UTF-8 encoding."""
|
2023-07-19 06:09:45 +02:00
|
|
|
|
|
|
|
self.logger.debug("Measuring code size for {} by `{}`."
|
2023-07-21 06:08:27 +02:00
|
|
|
.format(self.git_rev,
|
2023-07-19 06:09:45 +02:00
|
|
|
self.measure_cmd.strip().split(' ')[0]))
|
2023-07-14 11:37:45 +02:00
|
|
|
|
|
|
|
res = {}
|
|
|
|
for mod, st_lib in MBEDTLS_STATIC_LIB.items():
|
|
|
|
try:
|
|
|
|
result = subprocess.check_output(
|
2023-07-17 08:04:30 +02:00
|
|
|
[self.measure_cmd + ' ' + st_lib], cwd=git_worktree_path,
|
|
|
|
shell=True, universal_newlines=True
|
2023-07-14 11:37:45 +02:00
|
|
|
)
|
|
|
|
res[mod] = result
|
|
|
|
except subprocess.CalledProcessError as e:
|
|
|
|
self._handle_called_process_error(e, git_worktree_path)
|
|
|
|
|
|
|
|
return res
|
|
|
|
|
|
|
|
def _remove_worktree(self, git_worktree_path: str) -> None:
|
|
|
|
"""Remove temporary worktree."""
|
|
|
|
if git_worktree_path != self.repo_path:
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger.debug("Removing temporary worktree {}."
|
|
|
|
.format(git_worktree_path))
|
2023-07-14 11:37:45 +02:00
|
|
|
subprocess.check_output(
|
|
|
|
[self.git_command, "worktree", "remove", "--force",
|
|
|
|
git_worktree_path], cwd=self.repo_path,
|
|
|
|
stderr=subprocess.STDOUT
|
|
|
|
)
|
|
|
|
|
|
|
|
def _handle_called_process_error(self, e: subprocess.CalledProcessError,
|
|
|
|
git_worktree_path: str) -> None:
|
|
|
|
"""Handle a CalledProcessError and quit the program gracefully.
|
|
|
|
Remove any extra worktrees so that the script may be called again."""
|
|
|
|
|
|
|
|
# Tell the user what went wrong
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger.error(e, exc_info=True)
|
2023-07-20 09:32:15 +02:00
|
|
|
self.logger.error("Process output:\n {}".format(e.output))
|
2023-07-14 11:37:45 +02:00
|
|
|
|
|
|
|
# Quit gracefully by removing the existing worktree
|
|
|
|
self._remove_worktree(git_worktree_path)
|
|
|
|
sys.exit(-1)
|
|
|
|
|
2023-07-20 09:32:15 +02:00
|
|
|
def cal_libraries_code_size(self) -> typing.Dict[str, str]:
|
2023-07-20 09:09:51 +02:00
|
|
|
"""Do a complete round to calculate code size of library/*.o
|
|
|
|
by measurement tool.
|
|
|
|
|
|
|
|
:return A dictionary of measured code size
|
|
|
|
- typing.Dict[mod: str]
|
|
|
|
"""
|
2023-07-14 11:37:45 +02:00
|
|
|
|
2023-07-19 06:09:45 +02:00
|
|
|
git_worktree_path = self._create_git_worktree()
|
2023-07-26 11:12:57 +02:00
|
|
|
try:
|
|
|
|
self._build_libraries(git_worktree_path)
|
|
|
|
res = self._gen_raw_code_size(git_worktree_path)
|
|
|
|
finally:
|
|
|
|
self._remove_worktree(git_worktree_path)
|
2023-07-14 11:37:45 +02:00
|
|
|
|
|
|
|
return res
|
|
|
|
|
|
|
|
|
2023-07-17 05:17:12 +02:00
|
|
|
class CodeSizeGenerator:
|
2023-07-20 09:09:51 +02:00
|
|
|
""" A generator based on size measurement tool for library/*.o.
|
2023-07-17 05:17:12 +02:00
|
|
|
|
|
|
|
This is an abstract class. To use it, derive a class that implements
|
2023-07-24 06:29:22 +02:00
|
|
|
write_record and write_comparison methods, then call both of them with
|
|
|
|
proper arguments.
|
2023-07-17 05:17:12 +02:00
|
|
|
"""
|
2023-07-19 06:09:45 +02:00
|
|
|
def __init__(self, logger: logging.Logger) -> None:
|
2023-07-20 09:09:51 +02:00
|
|
|
"""
|
|
|
|
:param logger: logging module
|
|
|
|
"""
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger = logger
|
|
|
|
|
2023-07-24 06:29:22 +02:00
|
|
|
def write_record(
|
2023-07-17 05:17:12 +02:00
|
|
|
self,
|
2023-07-21 06:08:27 +02:00
|
|
|
git_rev: str,
|
2023-07-24 06:29:22 +02:00
|
|
|
code_size_text: typing.Dict[str, str],
|
|
|
|
output: typing_util.Writable
|
2023-07-17 05:17:12 +02:00
|
|
|
) -> None:
|
|
|
|
"""Write size record into a file.
|
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
:param git_rev: Git revision. (E.g: commit)
|
2023-07-20 09:09:51 +02:00
|
|
|
:param code_size_text:
|
|
|
|
string output (utf-8) from measurement tool of code size.
|
|
|
|
- typing.Dict[mod: str]
|
2023-07-24 06:29:22 +02:00
|
|
|
:param output: output stream which the code size record is written to.
|
|
|
|
(Note: Normally write code size record into File)
|
2023-07-17 05:17:12 +02:00
|
|
|
"""
|
|
|
|
raise NotImplementedError
|
|
|
|
|
2023-07-28 10:34:05 +02:00
|
|
|
def write_comparison( #pylint: disable=too-many-arguments
|
2023-07-17 05:17:12 +02:00
|
|
|
self,
|
|
|
|
old_rev: str,
|
|
|
|
new_rev: str,
|
2023-07-24 06:29:22 +02:00
|
|
|
output: typing_util.Writable,
|
2023-07-28 10:34:05 +02:00
|
|
|
with_markdown=False,
|
|
|
|
show_all=False
|
2023-07-17 05:17:12 +02:00
|
|
|
) -> None:
|
2023-07-21 06:08:27 +02:00
|
|
|
"""Write a comparision result into a stream between two Git revisions.
|
2023-07-17 05:17:12 +02:00
|
|
|
|
2023-07-20 09:09:51 +02:00
|
|
|
:param old_rev: old Git revision to compared with.
|
|
|
|
:param new_rev: new Git revision to compared with.
|
2023-07-24 06:29:22 +02:00
|
|
|
:param output: output stream which the code size record is written to.
|
|
|
|
(File / sys.stdout)
|
|
|
|
:param with_markdown: write comparision result in a markdown table.
|
|
|
|
(Default: False)
|
2023-07-28 10:34:05 +02:00
|
|
|
:param show_all: show all objects in comparison result. (Default False)
|
2023-07-17 05:17:12 +02:00
|
|
|
"""
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
|
|
|
|
class CodeSizeGeneratorWithSize(CodeSizeGenerator):
|
2023-05-30 12:10:20 +02:00
|
|
|
"""Code Size Base Class for size record saving and writing."""
|
|
|
|
|
2023-07-14 11:33:09 +02:00
|
|
|
class SizeEntry: # pylint: disable=too-few-public-methods
|
|
|
|
"""Data Structure to only store information of code size."""
|
2023-07-27 09:28:20 +02:00
|
|
|
def __init__(self, text: int, data: int, bss: int, dec: int):
|
2023-07-14 11:33:09 +02:00
|
|
|
self.text = text
|
|
|
|
self.data = data
|
|
|
|
self.bss = bss
|
|
|
|
self.total = dec # total <=> dec
|
|
|
|
|
2023-07-19 06:09:45 +02:00
|
|
|
def __init__(self, logger: logging.Logger) -> None:
|
2023-07-21 06:08:27 +02:00
|
|
|
""" Variable code_size is used to store size info for any Git revisions.
|
2023-07-20 09:09:51 +02:00
|
|
|
:param code_size:
|
|
|
|
Data Format as following:
|
2023-07-27 09:28:20 +02:00
|
|
|
code_size = {
|
|
|
|
git_rev: {
|
|
|
|
module: {
|
|
|
|
file_name: SizeEntry,
|
|
|
|
...
|
|
|
|
},
|
|
|
|
...
|
|
|
|
},
|
|
|
|
...
|
|
|
|
}
|
2023-05-30 12:10:20 +02:00
|
|
|
"""
|
2023-07-19 06:09:45 +02:00
|
|
|
super().__init__(logger)
|
2023-05-30 12:10:20 +02:00
|
|
|
self.code_size = {} #type: typing.Dict[str, typing.Dict]
|
2023-07-27 09:28:20 +02:00
|
|
|
self.mod_total_suffix = '-' + 'TOTALS'
|
2023-05-30 12:10:20 +02:00
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
def _set_size_record(self, git_rev: str, mod: str, size_text: str) -> None:
|
|
|
|
"""Store size information for target Git revision and high-level module.
|
2023-05-30 12:10:20 +02:00
|
|
|
|
|
|
|
size_text Format: text data bss dec hex filename
|
|
|
|
"""
|
|
|
|
size_record = {}
|
|
|
|
for line in size_text.splitlines()[1:]:
|
|
|
|
data = line.split()
|
2023-07-27 09:28:20 +02:00
|
|
|
if re.match(r'\s*\(TOTALS\)', data[5]):
|
|
|
|
data[5] = mod + self.mod_total_suffix
|
2023-07-17 11:59:53 +02:00
|
|
|
# file_name: SizeEntry(text, data, bss, dec)
|
|
|
|
size_record[data[5]] = CodeSizeGeneratorWithSize.SizeEntry(
|
2023-07-27 09:28:20 +02:00
|
|
|
int(data[0]), int(data[1]), int(data[2]), int(data[3]))
|
2023-07-26 08:59:37 +02:00
|
|
|
self.code_size.setdefault(git_rev, {}).update({mod: size_record})
|
2023-05-30 12:10:20 +02:00
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
def read_size_record(self, git_rev: str, fname: str) -> None:
|
2023-05-30 12:10:20 +02:00
|
|
|
"""Read size information from csv file and write it into code_size.
|
|
|
|
|
|
|
|
fname Format: filename text data bss dec
|
|
|
|
"""
|
|
|
|
mod = ""
|
|
|
|
size_record = {}
|
|
|
|
with open(fname, 'r') as csv_file:
|
|
|
|
for line in csv_file:
|
|
|
|
data = line.strip().split()
|
|
|
|
# check if we find the beginning of a module
|
|
|
|
if data and data[0] in MBEDTLS_STATIC_LIB:
|
|
|
|
mod = data[0]
|
|
|
|
continue
|
2023-05-24 06:24:38 +02:00
|
|
|
|
2023-05-30 12:10:20 +02:00
|
|
|
if mod:
|
2023-07-17 11:59:53 +02:00
|
|
|
# file_name: SizeEntry(text, data, bss, dec)
|
|
|
|
size_record[data[0]] = CodeSizeGeneratorWithSize.SizeEntry(
|
2023-07-27 09:28:20 +02:00
|
|
|
int(data[1]), int(data[2]), int(data[3]), int(data[4]))
|
2023-05-30 12:10:20 +02:00
|
|
|
|
|
|
|
# check if we hit record for the end of a module
|
2023-07-27 09:28:20 +02:00
|
|
|
m = re.match(r'\w+' + self.mod_total_suffix, line)
|
2023-05-30 12:10:20 +02:00
|
|
|
if m:
|
2023-07-21 06:08:27 +02:00
|
|
|
if git_rev in self.code_size:
|
|
|
|
self.code_size[git_rev].update({mod: size_record})
|
2023-05-30 12:10:20 +02:00
|
|
|
else:
|
2023-07-21 06:08:27 +02:00
|
|
|
self.code_size[git_rev] = {mod: size_record}
|
2023-05-30 12:10:20 +02:00
|
|
|
mod = ""
|
|
|
|
size_record = {}
|
|
|
|
|
2023-07-24 06:29:22 +02:00
|
|
|
def write_record(
|
2023-05-30 12:10:20 +02:00
|
|
|
self,
|
2023-07-21 06:08:27 +02:00
|
|
|
git_rev: str,
|
2023-07-24 06:29:22 +02:00
|
|
|
code_size_text: typing.Dict[str, str],
|
2023-05-30 12:10:20 +02:00
|
|
|
output: typing_util.Writable
|
|
|
|
) -> None:
|
|
|
|
"""Write size information to a file.
|
|
|
|
|
2023-07-27 09:28:20 +02:00
|
|
|
Writing Format: filename text data bss total(dec)
|
2023-05-30 12:10:20 +02:00
|
|
|
"""
|
2023-07-24 06:29:22 +02:00
|
|
|
for mod, size_text in code_size_text.items():
|
|
|
|
self._set_size_record(git_rev, mod, size_text)
|
|
|
|
|
2023-07-18 06:28:35 +02:00
|
|
|
format_string = "{:<30} {:>7} {:>7} {:>7} {:>7}\n"
|
|
|
|
output.write(format_string.format("filename",
|
|
|
|
"text", "data", "bss", "total"))
|
2023-05-30 12:10:20 +02:00
|
|
|
|
2023-07-27 09:28:20 +02:00
|
|
|
for mod, f_size in self.code_size[git_rev].items():
|
|
|
|
output.write("\n" + mod + "\n")
|
|
|
|
for fname, size_entry in f_size.items():
|
|
|
|
output.write(format_string
|
|
|
|
.format(fname,
|
|
|
|
size_entry.text, size_entry.data,
|
|
|
|
size_entry.bss, size_entry.total))
|
|
|
|
|
2023-07-28 10:34:05 +02:00
|
|
|
def write_comparison( #pylint: disable=too-many-arguments
|
2023-05-30 12:10:20 +02:00
|
|
|
self,
|
|
|
|
old_rev: str,
|
|
|
|
new_rev: str,
|
2023-07-18 06:28:35 +02:00
|
|
|
output: typing_util.Writable,
|
2023-07-28 10:34:05 +02:00
|
|
|
with_markdown=False,
|
|
|
|
show_all=False
|
2023-05-30 12:10:20 +02:00
|
|
|
) -> None:
|
2023-07-28 10:34:05 +02:00
|
|
|
# pylint: disable=too-many-locals
|
2023-05-30 12:10:20 +02:00
|
|
|
"""Write comparison result into a file.
|
|
|
|
|
2023-08-14 08:38:36 +02:00
|
|
|
Writing Format:
|
|
|
|
Markdown Output:
|
|
|
|
filename new(text) new(data) change(text) change(data)
|
|
|
|
CSV Output:
|
|
|
|
filename new(text) new(data) old(text) old(data) change(text) change(data)
|
2023-05-30 12:10:20 +02:00
|
|
|
"""
|
2023-08-14 08:38:36 +02:00
|
|
|
header_line = ["filename", "new(text)", "old(text)", "change(text)",
|
|
|
|
"new(data)", "old(data)", "change(data)"]
|
2023-07-18 06:28:35 +02:00
|
|
|
if with_markdown:
|
2023-08-14 08:38:36 +02:00
|
|
|
dash_line = [":----", "----:", "----:", "----:",
|
|
|
|
"----:", "----:", "----:"]
|
|
|
|
# | filename | new(text) | new(data) | change(text) | change(data) |
|
|
|
|
line_format = "| {0:<30} | {1:>9} | {4:>9} | {3:>12} | {6:>12} |\n"
|
2023-07-27 09:28:20 +02:00
|
|
|
bold_text = lambda x: '**' + str(x) + '**'
|
2023-07-18 06:28:35 +02:00
|
|
|
else:
|
2023-08-14 08:38:36 +02:00
|
|
|
# filename new(text) new(data) old(text) old(data) change(text) change(data)
|
|
|
|
line_format = "{0:<30} {1:>9} {4:>9} {2:>10} {5:>10} {3:>12} {6:>12}\n"
|
2023-07-27 09:28:20 +02:00
|
|
|
|
|
|
|
def cal_sect_change(
|
|
|
|
old_size: typing.Optional[CodeSizeGeneratorWithSize.SizeEntry],
|
|
|
|
new_size: typing.Optional[CodeSizeGeneratorWithSize.SizeEntry],
|
|
|
|
sect: str
|
|
|
|
) -> typing.List:
|
|
|
|
"""Inner helper function to calculate size change for a section.
|
|
|
|
|
|
|
|
Convention for special cases:
|
|
|
|
- If the object has been removed in new Git revision,
|
|
|
|
the size is minus code size of old Git revision;
|
|
|
|
the size change is marked as `Removed`,
|
|
|
|
- If the object only exists in new Git revision,
|
|
|
|
the size is code size of new Git revision;
|
|
|
|
the size change is marked as `None`,
|
|
|
|
|
|
|
|
:param: old_size: code size for objects in old Git revision.
|
|
|
|
:param: new_size: code size for objects in new Git revision.
|
|
|
|
:param: sect: section to calculate from `size` tool. This could be
|
|
|
|
any instance variable in SizeEntry.
|
|
|
|
:return: List of [section size of objects for new Git revision,
|
2023-08-14 08:38:36 +02:00
|
|
|
section size of objects for old Git revision,
|
2023-07-27 09:28:20 +02:00
|
|
|
section size change of objects between two Git revisions]
|
|
|
|
"""
|
|
|
|
if old_size and new_size:
|
|
|
|
new_attr = new_size.__dict__[sect]
|
2023-08-14 08:38:36 +02:00
|
|
|
old_attr = old_size.__dict__[sect]
|
|
|
|
delta = new_attr - old_attr
|
2023-08-14 05:54:47 +02:00
|
|
|
change_attr = '{0:{1}}'.format(delta, '+' if delta else '')
|
2023-07-27 09:28:20 +02:00
|
|
|
elif old_size:
|
2023-08-16 09:59:55 +02:00
|
|
|
new_attr = 'Removed'
|
2023-08-14 08:38:36 +02:00
|
|
|
old_attr = old_size.__dict__[sect]
|
2023-08-16 09:59:55 +02:00
|
|
|
delta = - old_attr
|
|
|
|
change_attr = '{0:{1}}'.format(delta, '+' if delta else '')
|
2023-07-27 09:28:20 +02:00
|
|
|
elif new_size:
|
|
|
|
new_attr = new_size.__dict__[sect]
|
2023-08-14 08:38:36 +02:00
|
|
|
old_attr = 'NotCreated'
|
2023-08-16 09:59:55 +02:00
|
|
|
delta = new_attr
|
|
|
|
change_attr = '{0:{1}}'.format(delta, '+' if delta else '')
|
2023-07-27 09:28:20 +02:00
|
|
|
else:
|
|
|
|
# Should never happen
|
|
|
|
new_attr = 'Error'
|
2023-08-14 08:38:36 +02:00
|
|
|
old_attr = 'Error'
|
2023-07-27 09:28:20 +02:00
|
|
|
change_attr = 'Error'
|
2023-08-14 08:38:36 +02:00
|
|
|
return [new_attr, old_attr, change_attr]
|
2023-07-27 09:28:20 +02:00
|
|
|
|
|
|
|
# sort dictionary by key
|
|
|
|
sort_by_k = lambda item: item[0].lower()
|
|
|
|
def get_results(
|
|
|
|
f_rev_size:
|
|
|
|
typing.Dict[str,
|
|
|
|
typing.Dict[str,
|
|
|
|
CodeSizeGeneratorWithSize.SizeEntry]]
|
|
|
|
) -> typing.List:
|
|
|
|
"""Return List of results in the format of:
|
2023-08-14 08:38:36 +02:00
|
|
|
[filename, new(text), old(text), change(text),
|
|
|
|
new(data), old(data), change(data)]
|
2023-07-27 09:28:20 +02:00
|
|
|
"""
|
|
|
|
res = []
|
|
|
|
for fname, revs_size in sorted(f_rev_size.items(), key=sort_by_k):
|
|
|
|
old_size = revs_size.get(old_rev)
|
|
|
|
new_size = revs_size.get(new_rev)
|
|
|
|
|
|
|
|
text_sect = cal_sect_change(old_size, new_size, 'text')
|
|
|
|
data_sect = cal_sect_change(old_size, new_size, 'data')
|
|
|
|
# skip the files that haven't changed in code size
|
2023-08-14 08:38:36 +02:00
|
|
|
if not show_all and text_sect[-1] == '0' and data_sect[-1] == '0':
|
2023-07-27 09:28:20 +02:00
|
|
|
continue
|
2023-07-18 06:28:35 +02:00
|
|
|
|
2023-07-27 09:28:20 +02:00
|
|
|
res.append([fname, *text_sect, *data_sect])
|
|
|
|
return res
|
|
|
|
|
|
|
|
# write header
|
|
|
|
output.write(line_format.format(*header_line))
|
2023-07-18 06:28:35 +02:00
|
|
|
if with_markdown:
|
2023-07-27 09:28:20 +02:00
|
|
|
output.write(line_format.format(*dash_line))
|
|
|
|
for mod in MBEDTLS_STATIC_LIB:
|
|
|
|
# convert self.code_size to:
|
|
|
|
# {
|
|
|
|
# file_name: {
|
|
|
|
# old_rev: SizeEntry,
|
|
|
|
# new_rev: SizeEntry
|
|
|
|
# },
|
|
|
|
# ...
|
|
|
|
# }
|
|
|
|
f_rev_size = {} #type: typing.Dict[str, typing.Dict]
|
|
|
|
for fname, size_entry in self.code_size[old_rev][mod].items():
|
|
|
|
f_rev_size.setdefault(fname, {}).update({old_rev: size_entry})
|
|
|
|
for fname, size_entry in self.code_size[new_rev][mod].items():
|
|
|
|
f_rev_size.setdefault(fname, {}).update({new_rev: size_entry})
|
|
|
|
|
|
|
|
mod_total_sz = f_rev_size.pop(mod + self.mod_total_suffix)
|
|
|
|
res = get_results(f_rev_size)
|
|
|
|
total_clm = get_results({mod + self.mod_total_suffix: mod_total_sz})
|
|
|
|
if with_markdown:
|
|
|
|
# bold row of mod-TOTALS in markdown table
|
|
|
|
total_clm = [[bold_text(j) for j in i] for i in total_clm]
|
|
|
|
res += total_clm
|
|
|
|
|
|
|
|
# write comparison result
|
|
|
|
for line in res:
|
|
|
|
output.write(line_format.format(*line))
|
2023-05-30 12:10:20 +02:00
|
|
|
|
|
|
|
|
2023-07-14 11:33:09 +02:00
|
|
|
class CodeSizeComparison:
|
2021-10-21 14:22:58 +02:00
|
|
|
"""Compare code size between two Git revisions."""
|
2021-09-09 11:42:37 +02:00
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
def __init__( #pylint: disable=too-many-arguments
|
2023-05-31 09:20:39 +02:00
|
|
|
self,
|
2023-07-21 06:08:27 +02:00
|
|
|
old_size_dist_info: CodeSizeDistinctInfo,
|
|
|
|
new_size_dist_info: CodeSizeDistinctInfo,
|
|
|
|
size_common_info: CodeSizeCommonInfo,
|
|
|
|
result_options: CodeSizeResultInfo,
|
2023-07-19 06:09:45 +02:00
|
|
|
logger: logging.Logger,
|
2023-05-31 09:20:39 +02:00
|
|
|
) -> None:
|
2021-09-09 11:42:37 +02:00
|
|
|
"""
|
2023-07-21 06:08:27 +02:00
|
|
|
:param old_size_dist_info: CodeSizeDistinctInfo containing old distinct
|
|
|
|
info to compare code size with.
|
|
|
|
:param new_size_dist_info: CodeSizeDistinctInfo containing new distinct
|
|
|
|
info to take as comparision base.
|
|
|
|
:param size_common_info: CodeSizeCommonInfo containing common info for
|
|
|
|
both old and new size distinct info and
|
|
|
|
measurement tool.
|
|
|
|
:param result_options: CodeSizeResultInfo containing results options for
|
|
|
|
code size record and comparision.
|
2023-07-20 09:09:51 +02:00
|
|
|
:param logger: logging module
|
2021-09-09 11:42:37 +02:00
|
|
|
"""
|
|
|
|
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger = logger
|
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
self.old_size_dist_info = old_size_dist_info
|
|
|
|
self.new_size_dist_info = new_size_dist_info
|
|
|
|
self.size_common_info = size_common_info
|
2023-07-21 10:09:00 +02:00
|
|
|
# infer pre make command
|
|
|
|
self.old_size_dist_info.pre_make_cmd = CodeSizeBuildInfo(
|
|
|
|
self.old_size_dist_info, self.size_common_info.host_arch,
|
|
|
|
self.logger).infer_pre_make_command()
|
|
|
|
self.new_size_dist_info.pre_make_cmd = CodeSizeBuildInfo(
|
|
|
|
self.new_size_dist_info, self.size_common_info.host_arch,
|
|
|
|
self.logger).infer_pre_make_command()
|
2023-07-20 09:32:15 +02:00
|
|
|
# infer make command
|
2023-07-21 06:08:27 +02:00
|
|
|
self.old_size_dist_info.make_cmd = CodeSizeBuildInfo(
|
|
|
|
self.old_size_dist_info, self.size_common_info.host_arch,
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger).infer_make_command()
|
2023-07-21 06:08:27 +02:00
|
|
|
self.new_size_dist_info.make_cmd = CodeSizeBuildInfo(
|
|
|
|
self.new_size_dist_info, self.size_common_info.host_arch,
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger).infer_make_command()
|
2023-07-20 09:32:15 +02:00
|
|
|
# initialize size parser with corresponding measurement tool
|
2023-07-19 06:09:45 +02:00
|
|
|
self.code_size_generator = self.__generate_size_parser()
|
2021-09-09 11:42:37 +02:00
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
self.result_options = result_options
|
|
|
|
self.csv_dir = os.path.abspath(self.result_options.record_dir)
|
|
|
|
os.makedirs(self.csv_dir, exist_ok=True)
|
|
|
|
self.comp_dir = os.path.abspath(self.result_options.comp_dir)
|
|
|
|
os.makedirs(self.comp_dir, exist_ok=True)
|
|
|
|
|
2023-07-19 06:09:45 +02:00
|
|
|
def __generate_size_parser(self):
|
2023-07-20 09:09:51 +02:00
|
|
|
"""Generate a parser for the corresponding measurement tool."""
|
2023-07-21 06:08:27 +02:00
|
|
|
if re.match(r'size', self.size_common_info.measure_cmd.strip()):
|
2023-07-19 06:09:45 +02:00
|
|
|
return CodeSizeGeneratorWithSize(self.logger)
|
2023-07-17 08:04:30 +02:00
|
|
|
else:
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger.error("Unsupported measurement tool: `{}`."
|
2023-07-21 06:08:27 +02:00
|
|
|
.format(self.size_common_info.measure_cmd
|
2023-07-19 06:09:45 +02:00
|
|
|
.strip().split(' ')[0]))
|
2023-07-17 08:04:30 +02:00
|
|
|
sys.exit(1)
|
|
|
|
|
2023-07-20 09:32:15 +02:00
|
|
|
def cal_code_size(
|
|
|
|
self,
|
2023-07-21 06:08:27 +02:00
|
|
|
size_dist_info: CodeSizeDistinctInfo
|
2023-07-20 09:32:15 +02:00
|
|
|
) -> typing.Dict[str, str]:
|
2023-07-20 09:09:51 +02:00
|
|
|
"""Calculate code size of library/*.o in a UTF-8 encoding"""
|
2021-09-09 11:42:37 +02:00
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
return CodeSizeCalculator(size_dist_info.git_rev,
|
2023-07-21 10:09:00 +02:00
|
|
|
size_dist_info.pre_make_cmd,
|
2023-07-21 06:08:27 +02:00
|
|
|
size_dist_info.make_cmd,
|
|
|
|
self.size_common_info.measure_cmd,
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger).cal_libraries_code_size()
|
2023-05-30 12:18:18 +02:00
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
def gen_code_size_report(self, size_dist_info: CodeSizeDistinctInfo) -> None:
|
2023-07-17 05:55:54 +02:00
|
|
|
"""Generate code size record and write it into a file."""
|
2021-09-09 11:42:37 +02:00
|
|
|
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger.info("Start to generate code size record for {}."
|
2023-07-21 06:08:27 +02:00
|
|
|
.format(size_dist_info.git_rev))
|
2023-07-24 09:20:42 +02:00
|
|
|
output_file = os.path.join(
|
|
|
|
self.csv_dir,
|
|
|
|
'{}-{}.csv'
|
|
|
|
.format(size_dist_info.get_info_indication(),
|
|
|
|
self.size_common_info.get_info_indication()))
|
2021-09-09 11:42:37 +02:00
|
|
|
# Check if the corresponding record exists
|
2023-07-21 06:08:27 +02:00
|
|
|
if size_dist_info.git_rev != "current" and \
|
2023-07-19 06:09:45 +02:00
|
|
|
os.path.exists(output_file):
|
|
|
|
self.logger.debug("Code size csv file for {} already exists."
|
2023-07-21 06:08:27 +02:00
|
|
|
.format(size_dist_info.git_rev))
|
2023-07-19 06:09:45 +02:00
|
|
|
self.code_size_generator.read_size_record(
|
2023-07-21 06:08:27 +02:00
|
|
|
size_dist_info.git_rev, output_file)
|
2021-09-09 11:42:37 +02:00
|
|
|
else:
|
2023-07-24 06:29:22 +02:00
|
|
|
# measure code size
|
|
|
|
code_size_text = self.cal_code_size(size_dist_info)
|
|
|
|
|
|
|
|
self.logger.debug("Generating code size csv for {}."
|
|
|
|
.format(size_dist_info.git_rev))
|
|
|
|
output = open(output_file, "w")
|
|
|
|
self.code_size_generator.write_record(
|
|
|
|
size_dist_info.git_rev, code_size_text, output)
|
2021-09-09 11:42:37 +02:00
|
|
|
|
2023-07-20 09:32:15 +02:00
|
|
|
def gen_code_size_comparison(self) -> None:
|
2023-07-21 06:08:27 +02:00
|
|
|
"""Generate results of code size changes between two Git revisions,
|
2023-07-20 09:09:51 +02:00
|
|
|
old and new.
|
|
|
|
|
2023-07-21 06:08:27 +02:00
|
|
|
- Measured code size result of these two Git revisions must be available.
|
2023-07-20 09:09:51 +02:00
|
|
|
- The result is directed into either file / stdout depending on
|
2023-07-21 06:08:27 +02:00
|
|
|
the option, size_common_info.result_options.stdout. (Default: file)
|
2023-07-20 09:09:51 +02:00
|
|
|
"""
|
2021-10-21 14:22:58 +02:00
|
|
|
|
2023-07-19 06:09:45 +02:00
|
|
|
self.logger.info("Start to generate comparision result between "\
|
|
|
|
"{} and {}."
|
2023-07-21 06:08:27 +02:00
|
|
|
.format(self.old_size_dist_info.git_rev,
|
|
|
|
self.new_size_dist_info.git_rev))
|
2023-07-24 06:29:22 +02:00
|
|
|
if self.result_options.stdout:
|
|
|
|
output = sys.stdout
|
|
|
|
else:
|
2023-07-24 09:20:42 +02:00
|
|
|
output_file = os.path.join(
|
|
|
|
self.comp_dir,
|
2023-07-28 07:47:19 +02:00
|
|
|
'{}-{}-{}.{}'
|
2023-07-24 09:20:42 +02:00
|
|
|
.format(self.old_size_dist_info.get_info_indication(),
|
|
|
|
self.new_size_dist_info.get_info_indication(),
|
2023-07-28 07:47:19 +02:00
|
|
|
self.size_common_info.get_info_indication(),
|
|
|
|
'md' if self.result_options.with_markdown else 'csv'))
|
2023-07-24 06:29:22 +02:00
|
|
|
output = open(output_file, "w")
|
2023-07-24 09:20:42 +02:00
|
|
|
|
|
|
|
self.logger.debug("Generating comparison results between {} and {}."
|
|
|
|
.format(self.old_size_dist_info.git_rev,
|
|
|
|
self.new_size_dist_info.git_rev))
|
2023-07-26 04:34:39 +02:00
|
|
|
if self.result_options.with_markdown or self.result_options.stdout:
|
|
|
|
print("Measure code size between {} and {} by `{}`."
|
|
|
|
.format(self.old_size_dist_info.get_info_indication(),
|
|
|
|
self.new_size_dist_info.get_info_indication(),
|
|
|
|
self.size_common_info.get_info_indication()),
|
|
|
|
file=output)
|
2023-07-24 06:29:22 +02:00
|
|
|
self.code_size_generator.write_comparison(
|
2023-07-21 06:08:27 +02:00
|
|
|
self.old_size_dist_info.git_rev,
|
|
|
|
self.new_size_dist_info.git_rev,
|
2023-07-28 10:34:05 +02:00
|
|
|
output, self.result_options.with_markdown,
|
|
|
|
self.result_options.show_all)
|
2021-10-26 11:23:42 +02:00
|
|
|
|
2023-07-20 09:32:15 +02:00
|
|
|
def get_comparision_results(self) -> None:
|
2023-07-21 06:08:27 +02:00
|
|
|
"""Compare size of library/*.o between self.old_size_dist_info and
|
|
|
|
self.old_size_dist_info and generate the result file."""
|
2022-09-18 21:17:09 +02:00
|
|
|
build_tree.check_repo_path()
|
2023-07-21 06:08:27 +02:00
|
|
|
self.gen_code_size_report(self.old_size_dist_info)
|
|
|
|
self.gen_code_size_report(self.new_size_dist_info)
|
2023-07-20 09:32:15 +02:00
|
|
|
self.gen_code_size_comparison()
|
2021-09-09 11:42:37 +02:00
|
|
|
|
2021-10-21 14:22:58 +02:00
|
|
|
def main():
|
2023-05-31 05:41:36 +02:00
|
|
|
parser = argparse.ArgumentParser(description=(__doc__))
|
|
|
|
group_required = parser.add_argument_group(
|
|
|
|
'required arguments',
|
|
|
|
'required arguments to parse for running ' + os.path.basename(__file__))
|
|
|
|
group_required.add_argument(
|
2023-07-20 09:09:51 +02:00
|
|
|
'-o', '--old-rev', type=str, required=True,
|
2023-07-21 06:08:27 +02:00
|
|
|
help='old Git revision for comparison.')
|
2023-05-31 05:41:36 +02:00
|
|
|
|
|
|
|
group_optional = parser.add_argument_group(
|
|
|
|
'optional arguments',
|
|
|
|
'optional arguments to parse for running ' + os.path.basename(__file__))
|
|
|
|
group_optional.add_argument(
|
2023-07-26 09:37:26 +02:00
|
|
|
'--record-dir', type=str, default='code_size_records',
|
2023-07-21 06:08:27 +02:00
|
|
|
help='directory where code size record is stored. '
|
|
|
|
'(Default: code_size_records)')
|
|
|
|
group_optional.add_argument(
|
2023-07-26 09:37:26 +02:00
|
|
|
'--comp-dir', type=str, default='comparison',
|
2023-07-20 09:09:51 +02:00
|
|
|
help='directory where comparison result is stored. '
|
|
|
|
'(Default: comparison)')
|
2023-05-31 05:41:36 +02:00
|
|
|
group_optional.add_argument(
|
2023-07-26 08:44:52 +02:00
|
|
|
'-n', '--new-rev', type=str, default='current',
|
2023-07-21 06:08:27 +02:00
|
|
|
help='new Git revision as comparison base. '
|
2023-07-20 09:09:51 +02:00
|
|
|
'(Default is the current work directory, including uncommitted '
|
|
|
|
'changes.)')
|
2023-05-31 05:41:36 +02:00
|
|
|
group_optional.add_argument(
|
2023-07-20 09:09:51 +02:00
|
|
|
'-a', '--arch', type=str, default=detect_arch(),
|
2023-05-24 05:03:59 +02:00
|
|
|
choices=list(map(lambda s: s.value, SupportedArch)),
|
2023-07-20 09:09:51 +02:00
|
|
|
help='Specify architecture for code size comparison. '
|
|
|
|
'(Default is the host architecture.)')
|
2023-05-31 05:41:36 +02:00
|
|
|
group_optional.add_argument(
|
2023-07-20 09:09:51 +02:00
|
|
|
'-c', '--config', type=str, default=SupportedConfig.DEFAULT.value,
|
2023-05-24 06:24:38 +02:00
|
|
|
choices=list(map(lambda s: s.value, SupportedConfig)),
|
2023-07-20 09:09:51 +02:00
|
|
|
help='Specify configuration type for code size comparison. '
|
2023-10-06 18:07:24 +02:00
|
|
|
'(Default is the current Mbed TLS configuration.)')
|
2023-07-18 06:28:35 +02:00
|
|
|
group_optional.add_argument(
|
|
|
|
'--markdown', action='store_true', dest='markdown',
|
2023-07-20 09:09:51 +02:00
|
|
|
help='Show comparision of code size in a markdown table. '
|
|
|
|
'(Only show the files that have changed).')
|
2023-07-18 08:35:05 +02:00
|
|
|
group_optional.add_argument(
|
|
|
|
'--stdout', action='store_true', dest='stdout',
|
2023-07-20 09:09:51 +02:00
|
|
|
help='Set this option to direct comparison result into sys.stdout. '
|
|
|
|
'(Default: file)')
|
2023-07-28 10:34:05 +02:00
|
|
|
group_optional.add_argument(
|
|
|
|
'--show-all', action='store_true', dest='show_all',
|
|
|
|
help='Show all the objects in comparison result, including the ones '
|
|
|
|
'that haven\'t changed in code size. (Default: False)')
|
2023-07-19 06:09:45 +02:00
|
|
|
group_optional.add_argument(
|
|
|
|
'--verbose', action='store_true', dest='verbose',
|
2023-07-20 09:09:51 +02:00
|
|
|
help='Show logs in detail for code size measurement. '
|
|
|
|
'(Default: False)')
|
2021-09-09 11:42:37 +02:00
|
|
|
comp_args = parser.parse_args()
|
|
|
|
|
2023-07-19 06:09:45 +02:00
|
|
|
logger = logging.getLogger()
|
2023-08-14 04:33:37 +02:00
|
|
|
logging_util.configure_logger(logger, split_level=logging.NOTSET)
|
|
|
|
logger.setLevel(logging.DEBUG if comp_args.verbose else logging.INFO)
|
2023-07-19 06:09:45 +02:00
|
|
|
|
2023-07-26 09:37:26 +02:00
|
|
|
if os.path.isfile(comp_args.record_dir):
|
|
|
|
logger.error("record directory: {} is not a directory"
|
|
|
|
.format(comp_args.record_dir))
|
|
|
|
sys.exit(1)
|
2023-07-21 06:08:27 +02:00
|
|
|
if os.path.isfile(comp_args.comp_dir):
|
2023-07-26 09:37:26 +02:00
|
|
|
logger.error("comparison directory: {} is not a directory"
|
|
|
|
.format(comp_args.comp_dir))
|
|
|
|
sys.exit(1)
|
2021-09-09 11:42:37 +02:00
|
|
|
|
2023-07-26 08:44:52 +02:00
|
|
|
comp_args.old_rev = CodeSizeCalculator.validate_git_revision(
|
|
|
|
comp_args.old_rev)
|
|
|
|
if comp_args.new_rev != 'current':
|
|
|
|
comp_args.new_rev = CodeSizeCalculator.validate_git_revision(
|
2023-07-21 06:08:27 +02:00
|
|
|
comp_args.new_rev)
|
2021-10-21 14:22:58 +02:00
|
|
|
|
2023-07-21 10:09:00 +02:00
|
|
|
# version, git_rev, arch, config, compiler, opt_level
|
2023-07-21 06:08:27 +02:00
|
|
|
old_size_dist_info = CodeSizeDistinctInfo(
|
2023-07-26 08:44:52 +02:00
|
|
|
'old', comp_args.old_rev, comp_args.arch, comp_args.config, 'cc', '-Os')
|
2023-07-21 06:08:27 +02:00
|
|
|
new_size_dist_info = CodeSizeDistinctInfo(
|
2023-07-26 08:44:52 +02:00
|
|
|
'new', comp_args.new_rev, comp_args.arch, comp_args.config, 'cc', '-Os')
|
2023-07-21 10:09:00 +02:00
|
|
|
# host_arch, measure_cmd
|
2023-07-21 06:08:27 +02:00
|
|
|
size_common_info = CodeSizeCommonInfo(
|
|
|
|
detect_arch(), 'size -t')
|
2023-07-28 10:34:05 +02:00
|
|
|
# record_dir, comp_dir, with_markdown, stdout, show_all
|
2023-07-21 06:08:27 +02:00
|
|
|
result_options = CodeSizeResultInfo(
|
|
|
|
comp_args.record_dir, comp_args.comp_dir,
|
2023-07-28 10:34:05 +02:00
|
|
|
comp_args.markdown, comp_args.stdout, comp_args.show_all)
|
2023-07-17 06:43:00 +02:00
|
|
|
|
2023-07-24 09:20:42 +02:00
|
|
|
logger.info("Measure code size between {} and {} by `{}`."
|
|
|
|
.format(old_size_dist_info.get_info_indication(),
|
|
|
|
new_size_dist_info.get_info_indication(),
|
|
|
|
size_common_info.get_info_indication()))
|
2023-07-21 06:08:27 +02:00
|
|
|
CodeSizeComparison(old_size_dist_info, new_size_dist_info,
|
|
|
|
size_common_info, result_options,
|
|
|
|
logger).get_comparision_results()
|
2021-09-09 11:42:37 +02:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2021-10-21 14:22:58 +02:00
|
|
|
main()
|