Merge pull request #7650 from yanrayw/7360-code-size-tfm-medium

code size measurement support for tfm-medium
This commit is contained in:
Tom Cosgrove 2023-06-02 13:25:26 +01:00 committed by GitHub
commit 32b06f50df
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 901 additions and 39 deletions

View File

@ -0,0 +1,115 @@
/*
* Copyright (c) 2018-2022, Arm Limited. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
/**
* \file psa/crypto_config.h
* \brief PSA crypto configuration options (set of defines)
*
*/
#if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
/**
* When #MBEDTLS_PSA_CRYPTO_CONFIG is enabled in mbedtls_config.h,
* this file determines which cryptographic mechanisms are enabled
* through the PSA Cryptography API (\c psa_xxx() functions).
*
* To enable a cryptographic mechanism, uncomment the definition of
* the corresponding \c PSA_WANT_xxx preprocessor symbol.
* To disable a cryptographic mechanism, comment out the definition of
* the corresponding \c PSA_WANT_xxx preprocessor symbol.
* The names of cryptographic mechanisms correspond to values
* defined in psa/crypto_values.h, with the prefix \c PSA_WANT_ instead
* of \c PSA_.
*
* Note that many cryptographic mechanisms involve two symbols: one for
* the key type (\c PSA_WANT_KEY_TYPE_xxx) and one for the algorithm
* (\c PSA_WANT_ALG_xxx). Mechanisms with additional parameters may involve
* additional symbols.
*/
#else
/**
* When \c MBEDTLS_PSA_CRYPTO_CONFIG is disabled in mbedtls_config.h,
* this file is not used, and cryptographic mechanisms are supported
* through the PSA API if and only if they are supported through the
* mbedtls_xxx API.
*/
#endif
#ifndef PROFILE_M_PSA_CRYPTO_CONFIG_H
#define PROFILE_M_PSA_CRYPTO_CONFIG_H
/*
* CBC-MAC is not yet supported via the PSA API in Mbed TLS.
*/
//#define PSA_WANT_ALG_CBC_MAC 1
//#define PSA_WANT_ALG_CBC_NO_PADDING 1
//#define PSA_WANT_ALG_CBC_PKCS7 1
#define PSA_WANT_ALG_CCM 1
//#define PSA_WANT_ALG_CMAC 1
//#define PSA_WANT_ALG_CFB 1
//#define PSA_WANT_ALG_CHACHA20_POLY1305 1
//#define PSA_WANT_ALG_CTR 1
#define PSA_WANT_ALG_DETERMINISTIC_ECDSA 1
//#define PSA_WANT_ALG_ECB_NO_PADDING 1
#define PSA_WANT_ALG_ECDH 1
#define PSA_WANT_ALG_ECDSA 1
//#define PSA_WANT_ALG_GCM 1
#define PSA_WANT_ALG_HKDF 1
#define PSA_WANT_ALG_HMAC 1
//#define PSA_WANT_ALG_MD5 1
//#define PSA_WANT_ALG_OFB 1
/* PBKDF2-HMAC is not yet supported via the PSA API in Mbed TLS.
* Note: when adding support, also adjust include/mbedtls/config_psa.h */
//#define PSA_WANT_ALG_PBKDF2_HMAC 1
//#define PSA_WANT_ALG_RIPEMD160 1
//#define PSA_WANT_ALG_RSA_OAEP 1
//#define PSA_WANT_ALG_RSA_PKCS1V15_CRYPT 1
//#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN 1
//#define PSA_WANT_ALG_RSA_PSS 1
//#define PSA_WANT_ALG_SHA_1 1
#define PSA_WANT_ALG_SHA_224 1
#define PSA_WANT_ALG_SHA_256 1
//#define PSA_WANT_ALG_SHA_384 1
//#define PSA_WANT_ALG_SHA_512 1
//#define PSA_WANT_ALG_STREAM_CIPHER 1
#define PSA_WANT_ALG_TLS12_PRF 1
#define PSA_WANT_ALG_TLS12_PSK_TO_MS 1
/* PBKDF2-HMAC is not yet supported via the PSA API in Mbed TLS.
* Note: when adding support, also adjust include/mbedtls/config_psa.h */
//#define PSA_WANT_ALG_XTS 1
//#define PSA_WANT_ECC_BRAINPOOL_P_R1_256 1
//#define PSA_WANT_ECC_BRAINPOOL_P_R1_384 1
//#define PSA_WANT_ECC_BRAINPOOL_P_R1_512 1
//#define PSA_WANT_ECC_MONTGOMERY_255 1
//#define PSA_WANT_ECC_MONTGOMERY_448 1
//#define PSA_WANT_ECC_SECP_K1_192 1
/*
* SECP224K1 is buggy via the PSA API in Mbed TLS
* (https://github.com/Mbed-TLS/mbedtls/issues/3541). Thus, do not enable it by
* default.
*/
//#define PSA_WANT_ECC_SECP_K1_224 1
//#define PSA_WANT_ECC_SECP_K1_256 1
//#define PSA_WANT_ECC_SECP_R1_192 1
//#define PSA_WANT_ECC_SECP_R1_224 1
#define PSA_WANT_ECC_SECP_R1_256 1
//#define PSA_WANT_ECC_SECP_R1_384 1
//#define PSA_WANT_ECC_SECP_R1_521 1
#define PSA_WANT_KEY_TYPE_DERIVE 1
#define PSA_WANT_KEY_TYPE_HMAC 1
#define PSA_WANT_KEY_TYPE_AES 1
//#define PSA_WANT_KEY_TYPE_ARIA 1
//#define PSA_WANT_KEY_TYPE_CAMELLIA 1
//#define PSA_WANT_KEY_TYPE_CHACHA20 1
//#define PSA_WANT_KEY_TYPE_DES 1
#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR 1
#define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1
#define PSA_WANT_KEY_TYPE_RAW_DATA 1
//#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR 1
//#define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1
#endif /* PROFILE_M_PSA_CRYPTO_CONFIG_H */

View File

@ -0,0 +1,629 @@
/**
* \file config.h
*
* \brief Configuration options (set of defines)
*
* This set of compile-time options may be used to enable
* or disable features selectively, and reduce the global
* memory footprint.
*/
/*
* Copyright (C) 2006-2022, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#ifndef PROFILE_M_MBEDTLS_CONFIG_H
#define PROFILE_M_MBEDTLS_CONFIG_H
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
#define _CRT_SECURE_NO_DEPRECATE 1
#endif
/**
* \name SECTION: System support
*
* This section sets system specific settings.
* \{
*/
/**
* \def MBEDTLS_HAVE_ASM
*
* The compiler has support for asm().
*
* Requires support for asm() in compiler.
*
* Used in:
* library/aria.c
* library/timing.c
* include/mbedtls/bn_mul.h
*
* Required by:
* MBEDTLS_AESNI_C
* MBEDTLS_PADLOCK_C
*
* Comment to disable the use of assembly code.
*/
#define MBEDTLS_HAVE_ASM
/**
* \def MBEDTLS_PLATFORM_MEMORY
*
* Enable the memory allocation layer.
*
* By default mbed TLS uses the system-provided calloc() and free().
* This allows different allocators (self-implemented or provided) to be
* provided to the platform abstraction layer.
*
* Enabling MBEDTLS_PLATFORM_MEMORY without the
* MBEDTLS_PLATFORM_{FREE,CALLOC}_MACROs will provide
* "mbedtls_platform_set_calloc_free()" allowing you to set an alternative calloc() and
* free() function pointer at runtime.
*
* Enabling MBEDTLS_PLATFORM_MEMORY and specifying
* MBEDTLS_PLATFORM_{CALLOC,FREE}_MACROs will allow you to specify the
* alternate function at compile time.
*
* Requires: MBEDTLS_PLATFORM_C
*
* Enable this layer to allow use of alternative memory allocators.
*/
#define MBEDTLS_PLATFORM_MEMORY
/* \} name SECTION: System support */
/**
* \name SECTION: mbed TLS feature support
*
* This section sets support for features that are or are not needed
* within the modules that are enabled.
* \{
*/
/**
* \def MBEDTLS_MD2_PROCESS_ALT
*
* MBEDTLS__FUNCTION_NAME__ALT: Uncomment a macro to let mbed TLS use you
* alternate core implementation of symmetric crypto or hash function. Keep in
* mind that function prototypes should remain the same.
*
* This replaces only one function. The header file from mbed TLS is still
* used, in contrast to the MBEDTLS__MODULE_NAME__ALT flags.
*
* Example: In case you uncomment MBEDTLS_SHA256_PROCESS_ALT, mbed TLS will
* no longer provide the mbedtls_sha1_process() function, but it will still provide
* the other function (using your mbedtls_sha1_process() function) and the definition
* of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible
* with this definition.
*
* \note Because of a signature change, the core AES encryption and decryption routines are
* currently named mbedtls_aes_internal_encrypt and mbedtls_aes_internal_decrypt,
* respectively. When setting up alternative implementations, these functions should
* be overridden, but the wrapper functions mbedtls_aes_decrypt and mbedtls_aes_encrypt
* must stay untouched.
*
* \note If you use the AES_xxx_ALT macros, then is is recommended to also set
* MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES
* tables.
*
* Uncomment a macro to enable alternate implementation of the corresponding
* function.
*
* \warning MD2, MD4, MD5, DES and SHA-1 are considered weak and their use
* constitutes a security risk. If possible, we recommend avoiding
* dependencies on them, and considering stronger message digests
* and ciphers instead.
*
*/
#define MBEDTLS_AES_SETKEY_DEC_ALT
#define MBEDTLS_AES_DECRYPT_ALT
/**
* \def MBEDTLS_AES_ROM_TABLES
*
* Use precomputed AES tables stored in ROM.
*
* Uncomment this macro to use precomputed AES tables stored in ROM.
* Comment this macro to generate AES tables in RAM at runtime.
*
* Tradeoff: Using precomputed ROM tables reduces RAM usage by ~8kb
* (or ~2kb if \c MBEDTLS_AES_FEWER_TABLES is used) and reduces the
* initialization time before the first AES operation can be performed.
* It comes at the cost of additional ~8kb ROM use (resp. ~2kb if \c
* MBEDTLS_AES_FEWER_TABLES below is used), and potentially degraded
* performance if ROM access is slower than RAM access.
*
* This option is independent of \c MBEDTLS_AES_FEWER_TABLES.
*
*/
#define MBEDTLS_AES_ROM_TABLES
/**
* \def MBEDTLS_AES_FEWER_TABLES
*
* Use less ROM/RAM for AES tables.
*
* Uncommenting this macro omits 75% of the AES tables from
* ROM / RAM (depending on the value of \c MBEDTLS_AES_ROM_TABLES)
* by computing their values on the fly during operations
* (the tables are entry-wise rotations of one another).
*
* Tradeoff: Uncommenting this reduces the RAM / ROM footprint
* by ~6kb but at the cost of more arithmetic operations during
* runtime. Specifically, one has to compare 4 accesses within
* different tables to 4 accesses with additional arithmetic
* operations within the same table. The performance gain/loss
* depends on the system and memory details.
*
* This option is independent of \c MBEDTLS_AES_ROM_TABLES.
*
*/
#define MBEDTLS_AES_FEWER_TABLES
/**
* \def MBEDTLS_ECP_NIST_OPTIM
*
* Enable specific 'modulo p' routines for each NIST prime.
* Depending on the prime and architecture, makes operations 4 to 8 times
* faster on the corresponding curve.
*
* Comment this macro to disable NIST curves optimisation.
*/
#define MBEDTLS_ECP_NIST_OPTIM
/**
* \def MBEDTLS_ERROR_STRERROR_DUMMY
*
* Enable a dummy error function to make use of mbedtls_strerror() in
* third party libraries easier when MBEDTLS_ERROR_C is disabled
* (no effect when MBEDTLS_ERROR_C is enabled).
*
* You can safely disable this if MBEDTLS_ERROR_C is enabled, or if you're
* not using mbedtls_strerror() or error_strerror() in your application.
*
* Disable if you run into name conflicts and want to really remove the
* mbedtls_strerror()
*/
#define MBEDTLS_ERROR_STRERROR_DUMMY
/**
* \def MBEDTLS_NO_PLATFORM_ENTROPY
*
* Do not use built-in platform entropy functions.
* This is useful if your platform does not support
* standards like the /dev/urandom or Windows CryptoAPI.
*
* Uncomment this macro to disable the built-in platform entropy functions.
*/
#define MBEDTLS_NO_PLATFORM_ENTROPY
/**
* \def MBEDTLS_ENTROPY_NV_SEED
*
* Enable the non-volatile (NV) seed file-based entropy source.
* (Also enables the NV seed read/write functions in the platform layer)
*
* This is crucial (if not required) on systems that do not have a
* cryptographic entropy source (in hardware or kernel) available.
*
* Requires: MBEDTLS_ENTROPY_C, MBEDTLS_PLATFORM_C
*
* \note The read/write functions that are used by the entropy source are
* determined in the platform layer, and can be modified at runtime and/or
* compile-time depending on the flags (MBEDTLS_PLATFORM_NV_SEED_*) used.
*
* \note If you use the default implementation functions that read a seedfile
* with regular fopen(), please make sure you make a seedfile with the
* proper name (defined in MBEDTLS_PLATFORM_STD_NV_SEED_FILE) and at
* least MBEDTLS_ENTROPY_BLOCK_SIZE bytes in size that can be read from
* and written to or you will get an entropy source error! The default
* implementation will only use the first MBEDTLS_ENTROPY_BLOCK_SIZE
* bytes from the file.
*
* \note The entropy collector will write to the seed file before entropy is
* given to an external source, to update it.
*/
// This macro is enabled in TFM Medium but is disabled here because it is
// incompatible with baremetal builds in Mbed TLS.
//#define MBEDTLS_ENTROPY_NV_SEED
/* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER
*
* Enable key identifiers that encode a key owner identifier.
*
* This is only meaningful when building the library as part of a
* multi-client service. When you activate this option, you must provide an
* implementation of the type mbedtls_key_owner_id_t and a translation from
* mbedtls_svc_key_id_t to file name in all the storage backends that you
* you wish to support.
*
* Note that while this define has been removed from TF-M's copy of this config
* file, TF-M still passes this option to Mbed TLS during the build via CMake.
* Therefore we keep it in our copy. See discussion on PR #7426 for more info.
*
*/
#define MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER
/**
* \def MBEDTLS_PSA_CRYPTO_SPM
*
* When MBEDTLS_PSA_CRYPTO_SPM is defined, the code is built for SPM (Secure
* Partition Manager) integration which separates the code into two parts: a
* NSPE (Non-Secure Process Environment) and an SPE (Secure Process
* Environment).
*
* Module: library/psa_crypto.c
* Requires: MBEDTLS_PSA_CRYPTO_C
*
*/
#define MBEDTLS_PSA_CRYPTO_SPM
/**
* \def MBEDTLS_SHA256_SMALLER
*
* Enable an implementation of SHA-256 that has lower ROM footprint but also
* lower performance.
*
* The default implementation is meant to be a reasonnable compromise between
* performance and size. This version optimizes more aggressively for size at
* the expense of performance. Eg on Cortex-M4 it reduces the size of
* mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about
* 30%.
*
* Uncomment to enable the smaller implementation of SHA256.
*/
#define MBEDTLS_SHA256_SMALLER
/**
* \def MBEDTLS_PSA_CRYPTO_CONFIG
*
* This setting allows support for cryptographic mechanisms through the PSA
* API to be configured separately from support through the mbedtls API.
*
* When this option is disabled, the PSA API exposes the cryptographic
* mechanisms that can be implemented on top of the `mbedtls_xxx` API
* configured with `MBEDTLS_XXX` symbols.
*
* When this option is enabled, the PSA API exposes the cryptographic
* mechanisms requested by the `PSA_WANT_XXX` symbols defined in
* include/psa/crypto_config.h. The corresponding `MBEDTLS_XXX` settings are
* automatically enabled if required (i.e. if no PSA driver provides the
* mechanism). You may still freely enable additional `MBEDTLS_XXX` symbols
* in mbedtls_config.h.
*
* If the symbol #MBEDTLS_PSA_CRYPTO_CONFIG_FILE is defined, it specifies
* an alternative header to include instead of include/psa/crypto_config.h.
*
* This feature is still experimental and is not ready for production since
* it is not completed.
*/
#define MBEDTLS_PSA_CRYPTO_CONFIG
/* \} name SECTION: mbed TLS feature support */
/**
* \name SECTION: mbed TLS modules
*
* This section enables or disables entire modules in mbed TLS
* \{
*/
/**
* \def MBEDTLS_AES_C
*
* Enable the AES block cipher.
*
* Module: library/aes.c
* Caller: library/cipher.c
* library/pem.c
* library/ctr_drbg.c
*
* This module is required to support the TLS ciphersuites that use the AES
* cipher.
*
* PEM_PARSE uses AES for decrypting encrypted keys.
*/
#define MBEDTLS_AES_C
/**
* \def MBEDTLS_CIPHER_C
*
* Enable the generic cipher layer.
*
* Module: library/cipher.c
*
* Uncomment to enable generic cipher wrappers.
*/
#define MBEDTLS_CIPHER_C
/**
* \def MBEDTLS_CTR_DRBG_C
*
* Enable the CTR_DRBG AES-based random generator.
* The CTR_DRBG generator uses AES-256 by default.
* To use AES-128 instead, enable MBEDTLS_CTR_DRBG_USE_128_BIT_KEY below.
*
* Module: library/ctr_drbg.c
* Caller:
*
* Requires: MBEDTLS_AES_C
*
* This module provides the CTR_DRBG AES random number generator.
*/
#define MBEDTLS_CTR_DRBG_C
/**
* \def MBEDTLS_ENTROPY_C
*
* Enable the platform-specific entropy code.
*
* Module: library/entropy.c
* Caller:
*
* Requires: MBEDTLS_SHA512_C or MBEDTLS_SHA256_C
*
* This module provides a generic entropy pool
*/
#define MBEDTLS_ENTROPY_C
/**
* \def MBEDTLS_ERROR_C
*
* Enable error code to error string conversion.
*
* Module: library/error.c
* Caller:
*
* This module enables mbedtls_strerror().
*/
#define MBEDTLS_ERROR_C
/**
* \def MBEDTLS_HKDF_C
*
* Enable the HKDF algorithm (RFC 5869).
*
* Module: library/hkdf.c
* Caller:
*
* Requires: MBEDTLS_MD_C
*
* This module adds support for the Hashed Message Authentication Code
* (HMAC)-based key derivation function (HKDF).
*/
#define MBEDTLS_HKDF_C /* Used for HUK deriviation */
/**
* \def MBEDTLS_MEMORY_BUFFER_ALLOC_C
*
* Enable the buffer allocator implementation that makes use of a (stack)
* based buffer to 'allocate' dynamic memory. (replaces calloc() and free()
* calls)
*
* Module: library/memory_buffer_alloc.c
*
* Requires: MBEDTLS_PLATFORM_C
* MBEDTLS_PLATFORM_MEMORY (to use it within mbed TLS)
*
* Enable this module to enable the buffer memory allocator.
*/
#define MBEDTLS_MEMORY_BUFFER_ALLOC_C
/**
* \def MBEDTLS_PK_C
*
* Enable the generic public (asymetric) key layer.
*
* Module: library/pk.c
*
* Requires: MBEDTLS_RSA_C or MBEDTLS_ECP_C
*
* Uncomment to enable generic public key wrappers.
*/
#define MBEDTLS_PK_C
/**
* \def MBEDTLS_PK_PARSE_C
*
* Enable the generic public (asymetric) key parser.
*
* Module: library/pkparse.c
*
* Requires: MBEDTLS_PK_C
*
* Uncomment to enable generic public key parse functions.
*/
#define MBEDTLS_PK_PARSE_C
/**
* \def MBEDTLS_PK_WRITE_C
*
* Enable the generic public (asymetric) key writer.
*
* Module: library/pkwrite.c
*
* Requires: MBEDTLS_PK_C
*
* Uncomment to enable generic public key write functions.
*/
#define MBEDTLS_PK_WRITE_C
/**
* \def MBEDTLS_PLATFORM_C
*
* Enable the platform abstraction layer that allows you to re-assign
* functions like calloc(), free(), snprintf(), printf(), fprintf(), exit().
*
* Enabling MBEDTLS_PLATFORM_C enables to use of MBEDTLS_PLATFORM_XXX_ALT
* or MBEDTLS_PLATFORM_XXX_MACRO directives, allowing the functions mentioned
* above to be specified at runtime or compile time respectively.
*
* \note This abstraction layer must be enabled on Windows (including MSYS2)
* as other module rely on it for a fixed snprintf implementation.
*
* Module: library/platform.c
* Caller: Most other .c files
*
* This module enables abstraction of common (libc) functions.
*/
#define MBEDTLS_PLATFORM_C
/**
* \def MBEDTLS_PSA_CRYPTO_C
*
* Enable the Platform Security Architecture cryptography API.
*
* Module: library/psa_crypto.c
*
* Requires: MBEDTLS_CTR_DRBG_C, MBEDTLS_ENTROPY_C
*
*/
#define MBEDTLS_PSA_CRYPTO_C
/**
* \def MBEDTLS_PSA_CRYPTO_STORAGE_C
*
* Enable the Platform Security Architecture persistent key storage.
*
* Module: library/psa_crypto_storage.c
*
* Requires: MBEDTLS_PSA_CRYPTO_C,
* either MBEDTLS_PSA_ITS_FILE_C or a native implementation of
* the PSA ITS interface
*/
// This macro is enabled in TFM Medium but is disabled here because it is
// incompatible with baremetal builds in Mbed TLS.
//#define MBEDTLS_PSA_CRYPTO_STORAGE_C
/* \} name SECTION: mbed TLS modules */
/**
* \name SECTION: General configuration options
*
* This section contains Mbed TLS build settings that are not associated
* with a particular module.
*
* \{
*/
/**
* \def MBEDTLS_CONFIG_FILE
*
* If defined, this is a header which will be included instead of
* `"mbedtls/mbedtls_config.h"`.
* This header file specifies the compile-time configuration of Mbed TLS.
* Unlike other configuration options, this one must be defined on the
* compiler command line: a definition in `mbedtls_config.h` would have
* no effect.
*
* This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
* non-standard feature of the C language, so this feature is only available
* with compilers that perform macro expansion on an <tt>\#include</tt> line.
*
* The value of this symbol is typically a path in double quotes, either
* absolute or relative to a directory on the include search path.
*/
//#define MBEDTLS_CONFIG_FILE "mbedtls/mbedtls_config.h"
/**
* \def MBEDTLS_USER_CONFIG_FILE
*
* If defined, this is a header which will be included after
* `"mbedtls/mbedtls_config.h"` or #MBEDTLS_CONFIG_FILE.
* This allows you to modify the default configuration, including the ability
* to undefine options that are enabled by default.
*
* This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
* non-standard feature of the C language, so this feature is only available
* with compilers that perform macro expansion on an <tt>\#include</tt> line.
*
* The value of this symbol is typically a path in double quotes, either
* absolute or relative to a directory on the include search path.
*/
//#define MBEDTLS_USER_CONFIG_FILE "/dev/null"
/**
* \def MBEDTLS_PSA_CRYPTO_CONFIG_FILE
*
* If defined, this is a header which will be included instead of
* `"psa/crypto_config.h"`.
* This header file specifies which cryptographic mechanisms are available
* through the PSA API when #MBEDTLS_PSA_CRYPTO_CONFIG is enabled, and
* is not used when #MBEDTLS_PSA_CRYPTO_CONFIG is disabled.
*
* This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
* non-standard feature of the C language, so this feature is only available
* with compilers that perform macro expansion on an <tt>\#include</tt> line.
*
* The value of this symbol is typically a path in double quotes, either
* absolute or relative to a directory on the include search path.
*/
//#define MBEDTLS_PSA_CRYPTO_CONFIG_FILE "psa/crypto_config.h"
/**
* \def MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE
*
* If defined, this is a header which will be included after
* `"psa/crypto_config.h"` or #MBEDTLS_PSA_CRYPTO_CONFIG_FILE.
* This allows you to modify the default configuration, including the ability
* to undefine options that are enabled by default.
*
* This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
* non-standard feature of the C language, so this feature is only available
* with compilers that perform macro expansion on an <tt>\#include</tt> line.
*
* The value of this symbol is typically a path in double quotes, either
* absolute or relative to a directory on the include search path.
*/
//#define MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE "/dev/null"
/** \} name SECTION: General configuration options */
/**
* \name SECTION: Module configuration options
*
* This section allows for the setting of module specific sizes and
* configuration options. The default values are already present in the
* relevant header files and should suffice for the regular use cases.
*
* Our advice is to enable options and change their values here
* only if you have a good reason and know the consequences.
*
* Please check the respective header file for documentation on these
* parameters (to prevent duplicate documentation).
* \{
*/
/* ECP options */
#define MBEDTLS_ECP_FIXED_POINT_OPTIM 0 /**< Disable fixed-point speed-up */
/* \} name SECTION: Customisation configuration options */
#if CRYPTO_NV_SEED
#include "tfm_mbedcrypto_config_extra_nv_seed.h"
#endif /* CRYPTO_NV_SEED */
#if !defined(CRYPTO_HW_ACCELERATOR) && defined(MBEDTLS_ENTROPY_NV_SEED)
#include "mbedtls_entropy_nv_seed_config.h"
#endif
#ifdef CRYPTO_HW_ACCELERATOR
#include "mbedtls_accelerator_config.h"
#endif
#endif /* PROFILE_M_MBEDTLS_CONFIG_H */

View File

@ -83,7 +83,7 @@ static inline int mbedtls_key_owner_id_equal(mbedtls_key_owner_id_t id1,
*/
#if defined(MBEDTLS_PSA_CRYPTO_SPM)
#define PSA_CRYPTO_SECURE 1
#include "crypto_spe.h"
#include "../tests/include/spe/crypto_spe.h"
#endif // MBEDTLS_PSA_CRYPTO_SPM
#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)

View File

@ -1,8 +1,6 @@
#!/usr/bin/env python3
"""
Purpose
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
@ -29,18 +27,103 @@ import argparse
import os
import subprocess
import sys
from enum import Enum
from mbedtls_dev import build_tree
class SupportedArch(Enum):
"""Supported architecture for code size measurement."""
AARCH64 = 'aarch64'
AARCH32 = 'aarch32'
ARMV8_M = 'armv8-m'
X86_64 = 'x86_64'
X86 = 'x86'
CONFIG_TFM_MEDIUM_MBEDCRYPTO_H = "../configs/tfm_mbedcrypto_config_profile_medium.h"
CONFIG_TFM_MEDIUM_PSA_CRYPTO_H = "../configs/crypto_config_profile_medium.h"
class SupportedConfig(Enum):
"""Supported configuration for code size measurement."""
DEFAULT = 'default'
TFM_MEDIUM = 'tfm-medium'
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()
if "__aarch64__" in cc_output:
return SupportedArch.AARCH64.value
if "__arm__" in cc_output:
return SupportedArch.AARCH32.value
if "__x86_64__" in cc_output:
return SupportedArch.X86_64.value
if "__x86__" in cc_output:
return SupportedArch.X86.value
else:
print("Unknown host architecture, cannot auto-detect arch.")
sys.exit(1)
class CodeSizeInfo: # pylint: disable=too-few-public-methods
"""Gather information used to measure code size.
It collects information about architecture, configuration in order to
infer build command for code size measurement.
"""
SupportedArchConfig = [
"-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,
]
def __init__(self, arch: str, config: str, sys_arch: str) -> None:
"""
arch: architecture to measure code size on.
config: configuration type to measure code size with.
make_command: command to build library (Inferred from arch and config).
"""
self.arch = arch
self.config = config
self.sys_arch = sys_arch
self.make_command = self.set_make_command()
def set_make_command(self) -> str:
"""Infer build command based on architecture and configuration."""
if self.config == SupportedConfig.DEFAULT.value and \
self.arch == self.sys_arch:
return 'make -j lib CFLAGS=\'-Os \' '
elif self.arch == SupportedArch.ARMV8_M.value and \
self.config == SupportedConfig.TFM_MEDIUM.value:
return \
'make -j lib CC=armclang \
CFLAGS=\'--target=arm-arm-none-eabi -mcpu=cortex-m33 -Os \
-DMBEDTLS_CONFIG_FILE=\\\"' + CONFIG_TFM_MEDIUM_MBEDCRYPTO_H + '\\\" \
-DMBEDTLS_PSA_CRYPTO_CONFIG_FILE=\\\"' + CONFIG_TFM_MEDIUM_PSA_CRYPTO_H + '\\\" \''
else:
print("Unsupported combination of architecture: {} and configuration: {}"
.format(self.arch, self.config))
print("\nPlease use supported combination of architecture and configuration:")
for comb in CodeSizeInfo.SupportedArchConfig:
print(comb)
print("\nFor your system, please use:")
for comb in CodeSizeInfo.SupportedArchConfig:
if "default" in comb and self.sys_arch not in comb:
continue
print(comb)
sys.exit(1)
class CodeSizeComparison:
"""Compare code size between two Git revisions."""
def __init__(self, old_revision, new_revision, result_dir):
def __init__(self, old_revision, new_revision, result_dir, code_size_info):
"""
old_revision: revision to compare against
old_revision: revision to compare against.
new_revision:
result_dir: directory for comparison result
result_dir: directory for comparison result.
code_size_info: an object containing information to build library.
"""
self.repo_path = "."
self.result_dir = os.path.abspath(result_dir)
@ -52,7 +135,9 @@ class CodeSizeComparison:
self.old_rev = old_revision
self.new_rev = new_revision
self.git_command = "git"
self.make_command = "make"
self.make_command = code_size_info.make_command
self.fname_suffix = "-" + code_size_info.arch + "-" +\
code_size_info.config
@staticmethod
def validate_revision(revision):
@ -75,21 +160,25 @@ class CodeSizeComparison:
git_worktree_path, revision], cwd=self.repo_path,
stderr=subprocess.STDOUT
)
return git_worktree_path
def _build_libraries(self, git_worktree_path):
"""Build libraries in the specified worktree."""
my_environment = os.environ.copy()
try:
subprocess.check_output(
[self.make_command, "-j", "lib"], env=my_environment,
self.make_command, env=my_environment, shell=True,
cwd=git_worktree_path, stderr=subprocess.STDOUT,
)
except subprocess.CalledProcessError as e:
self._handle_called_process_error(e, git_worktree_path)
def _gen_code_size_csv(self, revision, git_worktree_path):
"""Generate code size csv file."""
csv_fname = revision + ".csv"
csv_fname = revision + self.fname_suffix + ".csv"
if revision == "current":
print("Measuring code size in current work directory.")
else:
@ -117,7 +206,7 @@ class CodeSizeComparison:
"""Generate code size csv file for the specified git revision."""
# Check if the corresponding record exists
csv_fname = revision + ".csv"
csv_fname = revision + self.fname_suffix + ".csv"
if (revision != "current") and \
os.path.exists(os.path.join(self.csv_dir, csv_fname)):
print("Code size csv file for", revision, "already exists.")
@ -132,16 +221,20 @@ class CodeSizeComparison:
old and new. Measured code size results of these two revisions
must be available."""
old_file = open(os.path.join(self.csv_dir, self.old_rev + ".csv"), "r")
new_file = open(os.path.join(self.csv_dir, self.new_rev + ".csv"), "r")
res_file = open(os.path.join(self.result_dir, "compare-" + self.old_rev
+ "-" + self.new_rev + ".csv"), "w")
old_file = open(os.path.join(self.csv_dir, self.old_rev +
self.fname_suffix + ".csv"), "r")
new_file = open(os.path.join(self.csv_dir, self.new_rev +
self.fname_suffix + ".csv"), "r")
res_file = open(os.path.join(self.result_dir, "compare-" +
self.old_rev + "-" + self.new_rev +
self.fname_suffix +
".csv"), "w")
res_file.write("file_name, this_size, old_size, change, change %\n")
print("Generating comparison results.")
old_ds = {}
for line in old_file.readlines()[1:]:
for line in old_file.readlines():
cols = line.split(", ")
fname = cols[0]
size = int(cols[1])
@ -149,7 +242,7 @@ class CodeSizeComparison:
old_ds[fname] = size
new_ds = {}
for line in new_file.readlines()[1:]:
for line in new_file.readlines():
cols = line.split(", ")
fname = cols[0]
size = int(cols[1])
@ -175,30 +268,50 @@ class CodeSizeComparison:
self._get_code_size_for_rev(self.new_rev)
return self.compare_code_size()
def _handle_called_process_error(self, e: subprocess.CalledProcessError,
git_worktree_path):
"""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
print("The following command: {} failed and exited with code {}"
.format(e.cmd, e.returncode))
print("Process output:\n {}".format(str(e.output, "utf-8")))
# Quit gracefully by removing the existing worktree
self._remove_worktree(git_worktree_path)
sys.exit(-1)
def main():
parser = argparse.ArgumentParser(
description=(
"""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."""
)
)
parser.add_argument(
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(
"-o", "--old-rev", type=str, required=True,
help="old revision for comparison.")
group_optional = parser.add_argument_group(
'optional arguments',
'optional arguments to parse for running ' + os.path.basename(__file__))
group_optional.add_argument(
"-r", "--result-dir", type=str, default="comparison",
help="directory where comparison result is stored, \
default is comparison",
)
parser.add_argument(
"-o", "--old-rev", type=str, help="old revision for comparison.",
required=True,
)
parser.add_argument(
default is comparison")
group_optional.add_argument(
"-n", "--new-rev", type=str, default=None,
help="new revision for comparison, default is the current work \
directory, including uncommitted changes."
)
directory, including uncommitted changes.")
group_optional.add_argument(
"-a", "--arch", type=str, default=detect_arch(),
choices=list(map(lambda s: s.value, SupportedArch)),
help="specify architecture for code size comparison, default is the\
host architecture.")
group_optional.add_argument(
"-c", "--config", type=str, default=SupportedConfig.DEFAULT.value,
choices=list(map(lambda s: s.value, SupportedConfig)),
help="specify configuration type for code size comparison,\
default is the current MbedTLS configuration.")
comp_args = parser.parse_args()
if os.path.isfile(comp_args.result_dir):
@ -214,8 +327,13 @@ def main():
else:
new_revision = "current"
code_size_info = CodeSizeInfo(comp_args.arch, comp_args.config,
detect_arch())
print("Measure code size for architecture: {}, configuration: {}"
.format(code_size_info.arch, code_size_info.config))
result_dir = comp_args.result_dir
size_compare = CodeSizeComparison(old_revision, new_revision, result_dir)
size_compare = CodeSizeComparison(old_revision, new_revision, result_dir,
code_size_info)
return_code = size_compare.get_comparision_results()
sys.exit(return_code)