Utils Module API

Contents

Utils Module API#

Module containing various functions/modules used throughout the SPSDK.

Abstract class template#

Module for base abstract classes.

class spsdk.utils.abstract.BaseClass#

Bases: ABC

Abstract Class for Data Classes.

abstract export()#

Serialize object into bytes array.

Return type:

bytes

abstract classmethod parse(data)#

Deserialize object from bytes array.

Return type:

Self

Utils easy enum#

Custom enum extension.

class spsdk.utils.spsdk_enum.SpsdkEnum(tag, label, description=None)#

Bases: SpsdkEnumMember, Enum

SPSDK Enum type.

classmethod contains(obj)#

Check if given member with given tag/label exists in enum.

Parameters:

obj (Union[int, str]) – Label or tag of enum

Return type:

bool

Returns:

True if exists False otherwise

classmethod from_attr(attribute)#

Get enum member with given tag/label attribute.

Parameters:

attribute (Union[int, str]) – Attribute value of enum member

Return type:

Self

Returns:

Found enum member

classmethod from_label(label)#

Get enum member with given label.

Parameters:

label (str) – Label to be used for searching

Raises:

SPSDKKeyError – If enum with given label is not found

Return type:

Self

Returns:

Found enum member

classmethod from_tag(tag)#

Get enum member with given tag.

Parameters:

tag (int) – Tag to be used for searching

Raises:

SPSDKKeyError – If enum with given label is not found

Return type:

Self

Returns:

Found enum member

classmethod get_description(tag, default=None)#

Get description of enum member with given tag.

Parameters:
  • tag (int) – Tag to be used for searching

  • default (Optional[str]) – Default value if member contains no description

Return type:

Optional[str]

Returns:

Description of found enum member

classmethod get_label(tag)#

Get label of enum member with given tag.

Parameters:

tag (int) – Tag to be used for searching

Return type:

str

Returns:

Label of found enum member

classmethod get_tag(label)#

Get tag of enum member with given label.

Parameters:

label (str) – Label to be used for searching

Return type:

int

Returns:

Tag of found enum member

classmethod labels()#

Get list of labels of all enum members.

Return type:

List[str]

Returns:

List of all labels

classmethod tags()#

Get list of tags of all enum members.

Return type:

List[int]

Returns:

List of all tags

class spsdk.utils.spsdk_enum.SpsdkEnumMember(tag, label, description=None)#

Bases: object

SPSDK Enum member.

description: Optional[str] = None#
label: str#
tag: int#
class spsdk.utils.spsdk_enum.SpsdkSoftEnum(tag, label, description=None)#

Bases: SpsdkEnum

SPSDK Soft Enum type.

It has API with default values for labels and descriptions with defaults for non existing members.

Utils crypto - Certification blocks#

Module for handling Certificate block.

class spsdk.utils.crypto.cert_blocks.CertBlock#

Bases: BaseClass

Common general class for various CertBlocks.

abstract create_config(data_path)#

Create configuration of the Certification block Image.

Return type:

str

classmethod find_main_cert_index(config, search_paths=None)#

Go through all certificates and find the index matching to private key.

Parameters:
  • config (Dict[str, Any]) – Configuration to be searched.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

Optional[int]

Returns:

List of root certificates.

abstract classmethod from_config(config, search_paths=None)#

Creates an instance of cert block from configuration.

Return type:

Self

abstract static generate_config_template(family=None)#

Generate configuration for certification block.

Return type:

str

classmethod get_all_supported_families()#

Get supported families for all certification blocks except for SRK.

Return type:

List[str]

classmethod get_cert_block_class(family)#

Get certification block class by family name.

Parameters:

family (str) – Chip family

Raises:

SPSDKError – No certification block class found for given family

Return type:

Type[CertBlock]

classmethod get_cert_block_classes()#

Get list of all cert block classes.

Return type:

List[Type[CertBlock]]

classmethod get_main_cert_index(config, search_paths=None)#

Gets main certificate index from configuration.

Parameters:
  • config (Dict[str, Any]) – Input standard configuration.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

int

Returns:

Certificate index

Raises:
  • SPSDKError – If invalid configuration is provided.

  • SPSDKError – If correct certificate could not be identified.

  • SPSDKValueError – If certificate is not of correct type.

classmethod get_root_private_key_file(config)#

Get main root private key file from config.

Parameters:

config (Dict[str, Any]) – Configuration to be searched.

Return type:

Optional[str]

Returns:

Root private key file path.

abstract classmethod get_supported_families()#

Get supported families for certification block.

Return type:

List[str]

abstract classmethod get_validation_schemas()#

Create the list of validation schemas.

Return type:

List[Dict[str, Any]]

Returns:

List of validation schemas.

property rkth: bytes#

Root Key Table Hash 32-byte hash (SHA-256) of SHA-256 hashes of up to four root public keys.

class spsdk.utils.crypto.cert_blocks.CertBlockHeader(version='1.0', flags=0, build_number=0)#

Bases: BaseClass

Certificate block header.

Constructor.

Parameters:
  • version (str) – Version of the certificate in format n.n

  • flags (int) – Flags for the Certificate Header

  • build_number (int) – of the certificate

Raises:

SPSDKError – When there is invalid version

FORMAT = '<4s2H6I'#
SIGNATURE = b'cert'#
SIZE = 32#
export()#

Certificate block in binary form.

Return type:

bytes

classmethod parse(data)#

Deserialize object from bytes array.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Certificate Header instance

Raises:

SPSDKError – Unexpected size or signature of data

class spsdk.utils.crypto.cert_blocks.CertBlockV1(version='1.0', flags=0, build_number=0)#

Bases: CertBlock

Certificate block.

Shared for SB file 2.1 and for MasterBootImage using RSA keys.

Constructor.

Parameters:
  • version (str) – of the certificate in format n.n

  • flags (int) – Flags for the Certificate Block Header

  • build_number (int) – of the certificate

DEFAULT_ALIGNMENT = 16#
add_certificate(cert)#

Add certificate.

First call adds root certificate. Additional calls add chain certificates.

Parameters:

cert (Union[bytes, Certificate]) – The certificate itself in DER format

Raises:

SPSDKError – If certificate cannot be added

Return type:

None

property alignment: int#

Alignment of the binary output, by default it is DEFAULT_ALIGNMENT but can be customized.

property certificates: List[Certificate]#

List of certificates in header.

First certificate is root certificate and followed by optional chain certificates

create_config(data_path)#

Create configuration of the Certification block Image.

Return type:

str

property expected_size: int#

Expected size of binary block.

export()#

Serialize Certificate Block V1 object.

Return type:

bytes

classmethod from_config(config, search_paths=None)#

Creates an instance of CertBlockV1 from configuration.

Parameters:
  • config (Dict[str, Any]) – Input standard configuration.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

CertBlockV1

Returns:

Instance of CertBlockV1

Raises:

SPSDKError – Invalid certificates detected, Invalid configuration.

static generate_config_template(_family=None)#

Generate configuration for certification block v1.

Return type:

str

get_config(output_folder)#

Create configuration of Certificate V2 from object.

Parameters:

output_folder (str) – Output folder to store possible files.

Return type:

Dict[str, Any]

Returns:

Configuration dictionary.

classmethod get_root_private_key_file(config)#

Get main root private key file from config.

Parameters:

config (Dict[str, Any]) – Configuration to be searched.

Return type:

Optional[str]

Returns:

Root private key file path.

classmethod get_supported_families()#

Get list of supported families.

Return type:

List[str]

classmethod get_validation_schemas()#

Create the list of validation schemas.

Return type:

List[Dict[str, Any]]

Returns:

List of validation schemas.

property header: CertBlockHeader#

Certificate block header.

property image_length: int#

Image length in bytes.

classmethod parse(data)#

Deserialize CertBlockV1 from binary file.

Parameters:

data (bytes) – Binary data

Return type:

Self

Returns:

Certificate Block instance

Raises:

SPSDKError – Length of the data doesn’t match Certificate Block length

property raw_size: int#

Aligned size of the certificate block.

property rkh: List[bytes]#

List of root keys hashes (SHA-256), each hash as 32 bytes.

property rkh_index: int | None#

Index of the Root Key Hash that matches the certificate; None if does not match.

property rkth: bytes#

Root Key Table Hash 32-byte hash (SHA-256) of SHA-256 hashes of up to four root public keys.

property rkth_fuses: List[int]#

List of RKHT fuses, ordered from highest bit to lowest.

Note: Returned values are in format that should be passed for blhost

set_root_key_hash(index, key_hash)#

Add Root Key Hash into RKHT.

Note: Multiple root public keys are supported to allow for key revocation.

Parameters:
  • index (int) – The index of Root Key Hash in the table

  • key_hash (Union[bytes, bytearray, Certificate]) – The Root Key Hash value (32 bytes, SHA-256); or Certificate where the hash can be created from public key

Raises:
  • SPSDKError – When there is invalid index of root key hash in the table

  • SPSDKError – When there is invalid length of key hash

Return type:

None

property signature_size: int#

Size of the signature in bytes.

verify_data(signature, data)#

Signature verification.

Parameters:
  • signature (bytes) – to be verified

  • data (bytes) – that has been signed

Return type:

bool

Returns:

True if the data signature can be confirmed using the certificate; False otherwise

verify_private_key(private_key)#

Verify that given private key matches the public certificate.

Parameters:

private_key (PrivateKeyRsa) – to be tested

Return type:

bool

Returns:

True if yes; False otherwise

class spsdk.utils.crypto.cert_blocks.CertBlockV21(root_certs=None, ca_flag=False, version='2.1', used_root_cert=0, constraints=0, signature_provider=None, isk_cert=None, user_data=None, family=None)#

Bases: CertBlock

Create Certificate block version 2.1.

Used for SB 3.1 and MBI using ECC keys.

The Constructor for Certificate block.

FORMAT_VERSION = '2.1'#
MAGIC = b'chdr'#
calculate()#

Calculate all internal members.

Return type:

None

create_config(data_path)#

Create configuration of the Certification block Image.

Parameters:

data_path (str) – Path to store the data files of configuration.

Return type:

str

Returns:

Configuration in string.

property expected_size: int#

Expected size of binary block.

export()#

Export Certificate block as bytes array.

Return type:

bytes

classmethod from_config(config, search_paths=None)#

Creates an instance of CertBlockV21 from configuration.

Parameters:
  • config (Dict[str, Any]) – Input standard configuration.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

CertBlockV21

Returns:

Instance of CertBlockV21

Raises:

SPSDKError – If found gap in certificates from config file. Invalid configuration.

static generate_config_template(family=None)#

Generate configuration for certification block v21.

Return type:

str

get_config(output_folder)#

Create configuration dictionary of the Certification block Image.

Parameters:

output_folder (str) – Path to store the data files of configuration.

Return type:

Dict[str, Any]

Returns:

Configuration dictionary.

classmethod get_supported_families()#

Get list of supported families.

Return type:

List[str]

classmethod get_validation_schemas()#

Create the list of validation schemas.

Return type:

List[Dict[str, Any]]

Returns:

List of validation schemas.

classmethod parse(data)#

Parse Certificate block from bytes array.This operation is not supported.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKError – Magic do not match

Return type:

Self

property rkth: bytes#

Root Key Table Hash 32-byte hash (SHA-256) of SHA-256 hashes of up to four root public keys.

property signature_size: int#

Size of the signature in bytes.

validate()#

Validate the settings of class members.

Raises:

SPSDKError – Invalid configuration of certification block class members.

Return type:

None

class spsdk.utils.crypto.cert_blocks.CertBlockVx(isk_cert, signature_provider=None, self_signed=True)#

Bases: CertBlock

Create Certificate block for MC56xx.

The Constructor for Certificate block.

ISK_CERT_HASH_LENGTH = 16#
ISK_CERT_LENGTH = 136#
property cert_hash: bytes#

Calculate first half [:127] of certificate hash.

create_config(data_path)#

Create configuration of the Certification block Image.

Return type:

str

property expected_size: int#

Expected size of binary block.

export()#

Export Certificate block as bytes array.

Return type:

bytes

classmethod from_config(config, search_paths=None)#

Creates an instance of CertBlockVx from configuration.

Parameters:
  • config (Dict[str, Any]) – Input standard configuration.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

CertBlockVx

Returns:

CertBlockVx

Raises:

SPSDKError – If found gap in certificates from config file. Invalid configuration.

static generate_config_template(_family=None)#

Generate configuration for certification block vX.

Return type:

str

get_otp_script()#

Return script for writing certificate hash to OTP.

Return type:

str

Returns:

string value of blhost script

classmethod get_supported_families()#

Get list of supported families.

Return type:

List[str]

classmethod get_validation_schemas()#

Create the list of validation schemas.

Return type:

List[Dict[str, Any]]

Returns:

List of validation schemas.

classmethod parse(data)#

Parse Certificate block from bytes array.This operation is not supported.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKValueError – In case of inval

Return type:

Self

validate()#

Validate the settings of class members.

Raises:

SPSDKError – Invalid configuration of certification block class members.

Return type:

None

class spsdk.utils.crypto.cert_blocks.CertificateBlockHeader(format_version='2.1')#

Bases: BaseClass

Create Certificate block header.

Constructor for Certificate block header version 2.1.

Parameters:

format_version (str) – Major = 2, minor = 1

FORMAT = '<4s2HL'#
MAGIC = b'chdr'#
SIZE = 12#
export()#

Export Certificate block header as bytes array.

Return type:

bytes

classmethod parse(data)#

Parse Certificate block header from bytes array.

Parameters:

data (bytes) – Input data as bytes

Raises:
  • SPSDKError – Raised when SIZE is bigger than length of the data without offset

  • SPSDKError – Raised when magic is not equal MAGIC

Return type:

Self

Returns:

CertificateBlockHeader

class spsdk.utils.crypto.cert_blocks.IskCertificate(constraints=0, signature_provider=None, isk_cert=None, user_data=None, offset_present=True, family=None)#

Bases: BaseClass

Create ISK certificate.

Constructor for ISK certificate.

Parameters:
  • constraints (int) – Certificate version

  • signature_provider (Optional[SignatureProvider]) – ISK Signature Provider

  • isk_cert (Union[PublicKeyEcc, bytes, None]) – ISK certificate

  • user_data (Optional[bytes]) – User data

create_isk_signature(key_record_data, force=False)#

Function to create ISK signature.

Raises:

SPSDKError – Signature provider is not specified.

Return type:

None

property expected_size: int#

Binary block expected size.

export()#

Export ISK certificate as bytes array.

Return type:

bytes

classmethod parse(data, signature_size)#

Parse ISK certificate from bytes array.This operation is not supported.

Parameters:
  • data (bytes) – Input data as bytes array

  • signature_size (int) – The signature size of ISK block

Raises:

NotImplementedError – This operation is not supported

Return type:

Self

property signature_offset: int#

Signature offset inside the ISK Certificate.

class spsdk.utils.crypto.cert_blocks.IskCertificateLite(pub_key, constraints=1)#

Bases: BaseClass

ISK certificate lite.

Constructor for ISK certificate.

Parameters:
  • pub_key (Union[PublicKeyEcc, bytes]) – ISK public key

  • constraints (int) – 1 = self signed, 0 = nxp signed

  • user_data – User data

HEADER_FORMAT = '<HHI'#
ISK_PUB_KEY_LENGTH = 64#
ISK_SIGNATURE_SIZE = 64#
MAGIC = 19779#
SIGNATURE_OFFSET = 72#
VERSION = 1#
create_isk_signature(signature_provider, force=False)#

Function to create ISK signature.

Parameters:
  • signature_provider (Optional[SignatureProvider]) – Signature Provider

  • force (bool) – Force resign.

Raises:

SPSDKError – Signature provider is not specified.

Return type:

None

property expected_size: int#

Binary block expected size.

export()#

Export ISK certificate as bytes array.

Return type:

bytes

classmethod parse(data)#

Parse ISK certificate from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

NotImplementedError – This operation is not supported

Return type:

Self

class spsdk.utils.crypto.cert_blocks.RootKeyRecord(ca_flag, root_certs=None, used_root_cert=0)#

Bases: BaseClass

Create Root key record.

Constructor for Root key record.

Parameters:
  • ca_flag (bool) – CA flag

  • root_certs (Union[Sequence[PublicKeyEcc], Sequence[bytes], None]) – Root cert used to ISK/image signature

  • used_root_cert (int) – Used root cert number 0-3

calculate()#

Calculate all internal members.

Raises:

SPSDKError – The RKHT certificates inputs are missing.

Return type:

None

property expected_size: int#

Get expected binary block size.

export()#

Export Root key record as bytes array.

Return type:

bytes

static get_hash_algorithm(flags)#

Get CTRK table hash algorithm.

Parameters:

flags (int) – Root Key Record flags

Return type:

EnumHashAlgorithm

Returns:

Name of hash algorithm

property number_of_certificates: int#

Get number of included certificates.

classmethod parse(data)#

Parse Root key record from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Return type:

Self

Returns:

Root key record object

spsdk.utils.crypto.cert_blocks.convert_to_ecc_key(key)#

Convert key into EccKey instance.

Return type:

PublicKeyEcc

spsdk.utils.crypto.cert_blocks.find_root_certificates(config)#

Find all root certificates in configuration.

Parameters:

config (Dict[str, Any]) – Configuration to be searched.

Raises:

SPSDKError – If invalid configuration is provided.

Return type:

List[str]

Returns:

List of root certificates.

spsdk.utils.crypto.cert_blocks.get_keys_or_rotkh_from_certblock_config(rot, family)#

Get keys or ROTKH value from ROT config.

ROT config might be cert block config or MBI config. There are four cases how cert block might be configured.

  1. MBI with certBlock property pointing to YAML file

  2. MBI with certBlock property pointing to BIN file

  3. YAML configuration of cert block

  4. Binary cert block

Parameters:
  • rot (Optional[str]) – Path to ROT configuration (MBI or cert block) or path to binary cert block

  • family (Optional[str]) – MCU family

Raises:

SPSDKError – In case the ROTKH or keys cannot be parsed

Return type:

Tuple[Optional[Iterable[str]], Optional[bytes]]

Returns:

Tuple containing root of trust (list of paths to keys) or ROTKH in case of binary cert block

Utils crypto - Inline Encryption Engine (IEE)#

The module provides support for IEE for RTxxxx devices.

class spsdk.utils.crypto.iee.Iee#

Bases: object

IEE: Inline Encryption Engine.

Constructor.

IEE_DATA_UNIT = 4096#
IEE_KEY_BLOBS_SIZE = 384#
add_key_blob(key_blob)#

Add key for specified address range.

Parameters:

key_blob (IeeKeyBlob) – to be added

Return type:

None

encrypt_image(image, base_addr)#

Encrypt image with all available keyblobs.

Parameters:
  • image (bytes) – plain image to be encrypted

  • base_addr (int) – where the image will be located in target processor

Return type:

bytes

Returns:

encrypted image

encrypt_key_blobs(ibkek1, ibkek2, keyblob_address)#

Encrypt keyblobs and export them as binary.

Parameters:
  • ibkek1 (Union[bytes, str]) – key encryption key AES-XTS 256 bit

  • ibkek2 (Union[bytes, str]) – key encryption key AES-XTS 256 bit

  • keyblob_address (int) – keyblob base address

Return type:

bytes

Returns:

encrypted keyblobs

get_key_blobs()#

Get key blobs.

Return type:

bytes

Returns:

Binary key blobs joined together

class spsdk.utils.crypto.iee.IeeKeyBlob(attributes, start_addr, end_addr, key1=None, key2=None, page_offset=0, crc=None)#

Bases: object

IEE KeyBlob.

typedef struct _iee_keyblob_
{
uint32_t header; # IEE Key Blob header tag.
uint32_t version; # IEE Key Blob version, upward compatible.
iee_keyblob_attribute_t attribute; # IEE configuration attribute.
uint32_t pageOffset; # IEE page offset.
uint32_t key1[IEE_MAX_AES_KEY_SIZE_IN_BYTE /
sizeof(uint32_t)]; # Encryption key1 for XTS-AES mode, encryption key for AES-CTR mode.
uint32_t key2[IEE_MAX_AES_KEY_SIZE_IN_BYTE /
sizeof(uint32_t)]; # Encryption key2 for XTS-AES mode, initial counter for AES-CTR mode.
uint32_t startAddr; # Physical address of encryption region.
uint32_t endAddr; # Physical address of encryption region.
uint32_t reserved; # Reserved word.
uint32_t crc32; # Entire IEE Key Blob CRC32 value. Must be the last struct member.
} iee_keyblob_t

Constructor.

Parameters:
  • attributes (IeeKeyBlobAttribute) – IEE keyblob attributes

  • start_addr (int) – start address of the region

  • end_addr (int) – end address of the region

  • key1 (Optional[bytes]) – Encryption key1 for XTS-AES mode, encryption key for AES-CTR mode.

  • key2 (Optional[bytes]) – Encryption key2 for XTS-AES mode, initial_counter for AES-CTR mode.

  • crc (Optional[bytes]) – optional value for unused CRC fill (for testing only); None to use calculated value

Raises:
HEADER_TAG = 1229276482#
KEYBLOB_OFFSET = 4096#
KEYBLOB_VERSION = 1442906112#
static calculate_tweak(address)#

Calculate tweak value for AES-XTS encryption based on the address value.

Parameters:

address (int) – start address of encryption

Return type:

bytes

Returns:

16 byte tweak values

contains_addr(addr)#

Whether key blob contains specified address.

Parameters:

addr (int) – to be tested

Return type:

bool

Returns:

True if yes, False otherwise

encrypt_image(base_address, data)#

Encrypt specified data.

Parameters:
  • base_address (int) – of the data in target memory; must be >= self.start_addr

  • data (bytes) – to be encrypted (e.g. plain image); base_address + len(data) must be <= self.end_addr

Return type:

bytes

Returns:

encrypted data

Raises:
  • SPSDKError – If start address is not valid

  • NotImplementedError – AES-CTR is not implemented yet

encrypt_image_ctr(base_address, data)#

Encrypt specified data using AES-CTR.

Parameters:
  • base_address (int) – of the data in target memory; must be >= self.start_addr

  • data (bytes) – to be encrypted (e.g. plain image); base_address + len(data) must be <= self.end_addr

Return type:

bytes

Returns:

encrypted data

encrypt_image_xts(base_address, data)#

Encrypt specified data using AES-XTS.

Parameters:
  • base_address (int) – of the data in target memory; must be >= self.start_addr

  • data (bytes) – to be encrypted (e.g. plain image); base_address + len(data) must be <= self.end_addr

Return type:

bytes

Returns:

encrypted data

matches_range(image_start, image_end)#

Whether key blob matches address range of the image to be encrypted.

Parameters:
  • image_start (int) – start address of the image

  • image_end (int) – last address of the image

Return type:

bool

Returns:

True if yes, False otherwise

plain_data()#

Plain data for selected key range.

Return type:

bytes

Returns:

key blob exported into binary form (serialization)

class spsdk.utils.crypto.iee.IeeKeyBlobAttribute(lock, key_attribute, aes_mode)#

Bases: object

IEE Keyblob Attribute.

typedef struct _iee_keyblob_attribute
{
uint8_t lock; # IEE Region Lock control flag.
uint8_t keySize; # IEE AES key size.
uint8_t aesMode; # IEE AES mode.
uint8_t reserved; # Reserved.
} iee_keyblob_attribute_t;

IEE keyblob constructor.

Parameters:
property ctr_mode: bool#

Return true if AES mode is CTR.

Returns:

True if AES-CTR, false otherwise

export()#

Export binary representation of KeyBlobAttribute.

Return type:

bytes

Returns:

serialized binary data

property key1_size: int#

Return IEE key size based on selected mode.

Returns:

Key size in bytes

property key2_size: int#

Return IEE key size based on selected mode.

Returns:

Key size in bytes

class spsdk.utils.crypto.iee.IeeKeyBlobKeyAttributes(tag, label, description=None)#

Bases: SpsdkEnum

IEE keyblob key attributes.

CTR128XTS256 = (90, 'CTR128XTS256')#
CTR256XTS512 = (165, 'CTR256XTS512')#
class spsdk.utils.crypto.iee.IeeKeyBlobLockAttributes(tag, label, description=None)#

Bases: SpsdkEnum

IEE keyblob lock attributes.

LOCK = (149, 'LOCK')#
UNLOCK = (89, 'UNLOCK')#
class spsdk.utils.crypto.iee.IeeKeyBlobModeAttributes(tag, label, description=None)#

Bases: SpsdkEnum

IEE Keyblob mode attributes.

AesCTRWAddress = (102, 'AesCTRWAddress')#
AesCTRWOAddress = (170, 'AesCTRWOAddress')#
AesCTRkeystream = (25, 'AesCTRkeystream')#
AesXTS = (166, 'AesXTS')#
Bypass = (106, 'Bypass')#
class spsdk.utils.crypto.iee.IeeKeyBlobWritePmsnAttributes(tag, label, description=None)#

Bases: SpsdkEnum

IEE keblob write permission attributes.

DISABLE = (17, 'DISABLE')#
ENABLE = (153, 'ENABLE')#
class spsdk.utils.crypto.iee.IeeNxp(family, keyblob_address, ibkek1, ibkek2, key_blobs=None, binaries=None)#

Bases: Iee

IEE: Inline Encryption Engine.

Constructor.

Parameters:
  • family (str) – Device family

  • ibkek1 (Union[bytes, str]) – 256 bit key to encrypt IEE keyblob

  • ibkek2 (Union[bytes, str]) – 256 bit key to encrypt IEE keyblob

  • key_blobs (Optional[List[IeeKeyBlob]]) – Optional Key blobs to add to IEE, defaults to None

Raises:

SPSDKValueError – Unsupported family

binary_image(plain_data=False, data_alignment=16, keyblob_name='iee_keyblob.bin', image_name='encrypted.bin')#

Get the IEE Binary Image representation.

Parameters:
  • plain_data (bool) – Binary representation in plain format, defaults to False

  • data_alignment (int) – Alignment of data part key blobs.

  • keyblob_name (str) – Filename of the IEE keyblob

  • image_name (str) – Filename of the IEE image

Return type:

BinaryImage

Returns:

IEE in BinaryImage.

export_image()#

Export encrypted image.

Return type:

Optional[BinaryImage]

Returns:

Encrypted image

export_key_blobs()#

Export encrypted keyblobs in binary.

Return type:

bytes

Returns:

Encrypted keyblobs

static generate_config_template(family)#

Generate IEE configuration template.

Parameters:

family (str) – Family for which the template should be generated.

Return type:

Dict[str, Any]

Returns:

Dictionary of individual templates (key is name of template, value is template itself).

get_blhost_script_otp_kek()#

Create BLHOST script to load fuses needed to run IEE with OTP fuses.

Return type:

str

Returns:

BLHOST script that loads the keys into fuses.

static get_supported_families()#

Get all supported families for AHAB container.

Return type:

List[str]

Returns:

List of supported families.

static get_validation_schemas(family)#

Get list of validation schemas.

Parameters:

family (str) – Family for which the template should be generated.

Return type:

List[Dict[str, Any]]

Returns:

Validation list of schemas.

static get_validation_schemas_family()#

Get list of validation schemas for family key.

Return type:

List[Dict[str, Any]]

Returns:

Validation list of schemas.

static load_from_config(config, config_dir, search_paths=None)#

Converts the configuration option into an IEE image object.

“config” content array of containers configurations.

Parameters:
  • config (Dict[str, Any]) – array of IEE configuration dictionaries.

  • config_dir (str) – directory where the config is located

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

IeeNxp

Returns:

initialized IEE object.

Utils crypto - On-the-Fly AES Decryption (OTFAD)#

The module provides support for On-The-Fly encoding for RTxxx devices.

class spsdk.utils.crypto.otfad.KeyBlob(start_addr, end_addr, key=None, counter_iv=None, key_flags=3, zero_fill=None, crc=None)#

Bases: object

OTFAD KeyBlob: The class specifies AES key and counter initial value for specified address range.

typedef struct KeyBlob
{
unsigned char key[kAesKeySizeBytes]; // 16 bytes, 128-bits, KEY[A15…A00]
unsigned char ctr[kCtrSizeBytes]; // 8 bytes, 64-bits, CTR[C7…C0]
unsigned int srtaddr; // region start, SRTADDR[31 - 10]
unsigned int endaddr; // region end, ENDADDR[31 - 10]; lowest three bits are used as flags
// end of 32-byte area covered by CRC
unsigned int zero_fill; // zeros
unsigned int key_blob_crc32; // crc32 over 1st 32-bytes
// end of 40 byte (5*64-bit) key blob data
unsigned char expanded_wrap_data[8]; // 8 bytes, used for wrap expanded data
// end of 48 byte (6*64-bit) wrap data
unsigned char unused_filler[16]; // unused fill to 64 bytes
} keyblob_t;

Constructor.

Parameters:
  • start_addr (int) – start address of the region

  • end_addr (int) – end address of the region

  • key_flags (int) – see KEY_FLAG_xxx constants; default flags: RO = 0, ADE = 1, VLD = 1

  • key (Optional[bytes]) – optional AES key; None to use random value

  • counter_iv (Optional[bytes]) – optional counter init value for AES; None to use random value

  • binaries – optional data chunks of this key blob

  • zero_fill (Optional[bytes]) – optional value for zero_fill (for testing only); None to use random value (recommended)

  • crc (Optional[bytes]) – optional value for unused CRC fill (for testing only); None to use random value (recommended)

Raises:
CTR_SIZE = 8#
KEY_FLAG_ADE = 2#
KEY_FLAG_READ_ONLY = 4#
KEY_FLAG_VLD = 1#
KEY_SIZE = 16#
contains_addr(addr)#

Whether key blob contains specified address.

Parameters:

addr (int) – to be tested

Return type:

bool

Returns:

True if yes, False otherwise

encrypt_image(base_address, data, byte_swap, counter_value=None)#

Encrypt specified data.

Parameters:
  • base_address (int) – of the data in target memory; must be >= self.start_addr

  • data (bytes) – to be encrypted (e.g. plain image); base_address + len(data) must be <= self.end_addr

  • byte_swap (bool) – this probably depends on the flash device, how bytes are organized there

  • counter_value (Optional[int]) – Optional counter value, if not specified start address of keyblob will be used

Return type:

bytes

Returns:

encrypted data

Raises:

SPSDKError – If start address is not valid

export(kek, iv=b'\\xa6\\xa6\\xa6\\xa6\\xa6\\xa6\\xa6\\xa6', byte_swap_cnt=0)#

Creates key wrap for the key blob.

Parameters:
  • kek (Union[bytes, str]) – key to encode; 16 bytes long

  • iv (bytes) – counter initialization vector; 8 bytes; optional, OTFAD uses empty init value

  • byte_swap_cnt (int) – Encrypted keyblob reverse byte count, 0 means NO reversing is enabled

Return type:

bytes

Returns:

Serialized key blob

Raises:
property is_encrypted: bool#

Get the required encryption or not.

Returns:

True if blob is encrypted, False otherwise.

matches_range(image_start, image_end)#

Whether key blob matches address range of the image to be encrypted.

Parameters:
  • image_start (int) – start address of the image

  • image_end (int) – last address of the image

Return type:

bool

Returns:

True if yes, False otherwise

plain_data()#

Plain data for selected key range.

Return type:

bytes

Returns:

key blob exported into binary form (serialization)

Raises:
class spsdk.utils.crypto.otfad.Otfad#

Bases: object

OTFAD: On-the-Fly AES Decryption Module.

Constructor.

OTFAD_DATA_UNIT = 1024#
add_key_blob(key_blob)#

Add key for specified address range.

Parameters:

key_blob (KeyBlob) – to be added

Return type:

None

encrypt_image(image, base_addr, byte_swap)#

Encrypt image with all available keyblobs.

Parameters:
  • image (bytes) – plain image to be encrypted

  • base_addr (int) – where the image will be located in target processor

  • byte_swap (bool) – this probably depends on the flash device, how bytes are organized there

Return type:

bytes

Returns:

encrypted image

encrypt_key_blobs(kek, key_scramble_mask=None, key_scramble_align=None, byte_swap_cnt=0)#

Encrypt key blobs with specified key.

Parameters:
  • kek (Union[bytes, str]) – key to encode key blobs

  • key_scramble_mask (Optional[int]) – 32-bit scramble key, if KEK scrambling is desired.

  • key_scramble_align (Optional[int]) – 8-bit scramble align, if KEK scrambling is desired.

  • byte_swap_cnt (int) – Encrypted keyblob reverse byte count, 0 means NO reversing is enabled

Raises:

SPSDKValueError – Invalid input value.

Return type:

bytes

Returns:

encrypted binary key blobs joined together

get_key_blobs()#

Get key blobs.

Return type:

bytes

Returns:

Binary key blobs joined together

class spsdk.utils.crypto.otfad.OtfadNxp(family, kek, table_address=0, key_blobs=None, key_scramble_mask=None, key_scramble_align=None, binaries=None)#

Bases: Otfad

OTFAD: On-the-Fly AES Decryption Module with reflecting of NXP parts.

Constructor.

Parameters:
  • family (str) – Device family

  • kek (Union[bytes, str]) – KEK to encrypt OTFAD table

  • table_address (int) – Absolute address of OTFAD table.

  • key_blobs (Optional[List[KeyBlob]]) – Optional Key blobs to add to OTFAD, defaults to None

  • key_scramble_mask (Optional[int]) – If defined, the key scrambling algorithm will be applied. (‘key_scramble_align’ must be defined also)

  • key_scramble_align (Optional[int]) – If defined, the key scrambling algorithm will be applied. (‘key_scramble_mask’ must be defined also)

Raises:

SPSDKValueError – Unsupported family

binary_image(plain_data=False, data_alignment=16, otfad_table_name='OTFAD_Table')#

Get the OTFAD Binary Image representation.

Parameters:
  • plain_data (bool) – Binary representation in plain format, defaults to False

  • data_alignment (int) – Alignment of data part key blobs.

  • otfad_table_name (str) – name of the output file that contains OTFAD table

Return type:

BinaryImage

Returns:

OTFAD in BinaryImage.

export_image(plain_data=False, swap_bytes=False, join_sub_images=True, table_address=0)#

Get the OTFAD Key Blob Binary Image representation.

Parameters:
  • plain_data (bool) – Binary representation in plain data format, defaults to False

  • swap_bytes (bool) – For some platforms the swap bytes is needed in encrypted format, defaults to False.

  • join_sub_images (bool) – If it’s True, all the binary sub-images are joined into one, defaults to True.

  • table_address (int) – Absolute address of OTFAD table.

Return type:

Optional[BinaryImage]

Returns:

OTFAD key blob data in BinaryImage.

static generate_config_template(family)#

Generate OTFAD configuration template.

Parameters:

family (str) – Family for which the template should be generated.

Return type:

Dict[str, Any]

Returns:

Dictionary of individual templates (key is name of template, value is template itself).

get_blhost_script_otp_kek(index=1)#

Create BLHOST script to load fuses needed to run OTFAD with OTP fuses just for OTFAD key.

Parameters:

index (int) – Index of OTFAD peripheral [1, 2, …, n].

Return type:

str

Returns:

BLHOST script that loads the keys into fuses.

static get_blhost_script_otp_keys(family, otp_master_key, otfad_key_seed)#

Create BLHOST script to load fuses needed to run OTFAD with OTP fuses.

Parameters:
  • family (str) – Device family.

  • otp_master_key (bytes) – OTP Master Key.

  • otfad_key_seed (bytes) – OTFAD Key Seed.

Return type:

str

Returns:

BLHOST script that loads the keys into fuses.

static get_supported_families()#

Get all supported families for AHAB container.

Return type:

List[str]

Returns:

List of supported families.

static get_validation_schemas(family)#

Get list of validation schemas.

Parameters:

family (str) – Family for which the template should be generated.

Return type:

List[Dict[str, Any]]

Returns:

Validation list of schemas.

static get_validation_schemas_family()#

Get list of validation schemas for family key.

Return type:

List[Dict[str, Any]]

Returns:

Validation list of schemas.

static load_from_config(config, config_dir, search_paths=None)#

Converts the configuration option into an OTFAD image object.

“config” content array of containers configurations.

Parameters:
  • config (Dict[str, Any]) – array of OTFAD configuration dictionaries.

  • config_dir (str) – directory where the config is located

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

OtfadNxp

Returns:

initialized OTFAD object.

Utils crypto - Root Keys Hash Table (RKHT)#

The module provides support for Root Key Hash table.

class spsdk.utils.crypto.rkht.RKHT(rkh_list)#

Bases: object

Root Key Hash Table class.

Initialization of Root Key Hash Table class.

Parameters:

rkh_list (List[bytes]) – List of Root Key Hashes

static convert_key(key, password=None, search_paths=None)#

Convert practically whole input that could hold Public key into public key.

Parameters:
  • key (Union[str, bytes, bytearray, PublicKey, PrivateKey, Certificate]) – Public key in Certificate/Private key, Public key as a path to file, loaded bytes or supported class.

  • password (Optional[str]) – Optional password to open secured private keys, defaults to None.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Raises:

SPSDKError – Invalid kye type.

Return type:

PublicKey

Returns:

Public Key object.

classmethod from_keys(keys, password=None, search_paths=None)#

Create RKHT from list of keys.

Parameters:
  • keys (Sequence[Union[str, bytes, bytearray, PublicKey, PrivateKey, Certificate]]) – List of public keys/certificates/private keys/bytes

  • password (Optional[str]) – Optional password to open secured private keys, defaults to None

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

Self

property hash_algorithm: EnumHashAlgorithm#

Used hash algorithm name.

property hash_algorithm_size: int#

Used hash algorithm size in bites.

abstract rkth()#

Root Key Table Hash.

Return type:

bytes

Returns:

Hash of hashes of public keys.

class spsdk.utils.crypto.rkht.RKHTv1(rkh_list)#

Bases: RKHT

Root Key Hash Table class for cert block v1.

Initialization of Root Key Hash Table class.

Parameters:

rkh_list (List[bytes]) – List of Root Key Hashes

RKHT_SIZE = 4#
RKH_SIZE = 32#
export()#

Export RKHT as bytes.

Return type:

bytes

property hash_algorithm: EnumHashAlgorithm#

Used Hash algorithm name.

classmethod parse(rkht)#

Parse Root Key Hash Table into RKHTv1 object.

Parameters:

rkht (bytes) – Valid RKHT table

Return type:

Self

rkth()#

Root Key Table Hash.

Return type:

bytes

Returns:

Hash of Hashes of public key.

set_rkh(index, rkh)#

Set Root Key Hash with index.

Parameters:
  • index (int) – Index in the hash table

  • rkh (bytes) – Root Key Hash to be set

Return type:

None

class spsdk.utils.crypto.rkht.RKHTv21(rkh_list)#

Bases: RKHT

Root Key Hash Table class for cert block v2.1.

Initialization of Root Key Hash Table class.

Parameters:

rkh_list (List[bytes]) – List of Root Key Hashes

export()#

Export RKHT as bytes.

Return type:

bytes

classmethod parse(rkht, hash_algorithm)#

Parse Root Key Hash Table into RKHTv21 object.

Parameters:
  • rkht (bytes) – Valid RKHT table

  • hash_algorithm (EnumHashAlgorithm) – Hash algorithm to be used

Return type:

Self

rkth()#

Root Key Table Hash.

Return type:

bytes

Returns:

Hash of Hashes of public key.

Utils crypto - Root Of Trust (RoT)#

The module provides support for RoT hash calculation .

class spsdk.utils.crypto.rot.Rot(family, keys_or_certs, password=None, search_paths=None)#

Bases: object

Root of Trust object providing an abstraction over the RoT hash calculation for multiple device families.

Root of Trust initialization.

calculate_hash()#

Calculate RoT hash.

Return type:

bytes

export()#

Export RoT.

Return type:

bytes

classmethod get_rot_class(family)#

Get RoT class.

Return type:

Type[RotBase]

classmethod get_supported_families()#

Get all supported families.

Return type:

List[str]

class spsdk.utils.crypto.rot.RotBase(keys_or_certs, password=None, search_paths=None)#

Bases: object

Root of Trust base class.

Rot initialization.

abstract calculate_hash()#

Calculate ROT hash.

Return type:

bytes

abstract export()#

Calculate ROT table.

Return type:

bytes

rot_type: Optional[str] = None#
class spsdk.utils.crypto.rot.RotCertBlockv1(keys_or_certs, password=None, search_paths=None)#

Bases: RotBase

Root of Trust for certificate block v1 class.

Rot cert block v1 initialization.

calculate_hash()#

Calculate RoT hash.

Return type:

bytes

export()#

Export RoT.

Return type:

bytes

rot_type: Optional[str] = 'cert_block_1'#
class spsdk.utils.crypto.rot.RotCertBlockv21(keys_or_certs, password=None, search_paths=None)#

Bases: RotBase

Root of Trust for certificate block v21 class.

Rot cert block v21 initialization.

calculate_hash()#

Calculate ROT hash.

Return type:

bytes

export()#

Export RoT.

Return type:

bytes

rot_type: Optional[str] = 'cert_block_21'#
class spsdk.utils.crypto.rot.RotSrkTableAhab(keys_or_certs, password=None, search_paths=None)#

Bases: RotBase

Root of Trust for AHAB SrkTable class.

AHAB SRK table initialization.

calculate_hash()#

Calculate ROT hash.

Return type:

bytes

export()#

Export RoT.

Return type:

bytes

rot_type: Optional[str] = 'srk_table_ahab'#
class spsdk.utils.crypto.rot.RotSrkTableHab(keys_or_certs, password=None, search_paths=None)#

Bases: RotBase

Root of Trust for HAB SrkTable class.

HAB SRK table initialization.

calculate_hash()#

Calculate ROT hash.

Return type:

bytes

export()#

Export RoT.

Return type:

bytes

rot_type: Optional[str] = 'srk_table_hab'#

General utils#

Miscellaneous functions used throughout the SPSDK.

class spsdk.utils.misc.BinaryPattern(pattern)#

Bases: object

Binary pattern class.

Supported patterns:
  • rand: Random Pattern

  • zeros: Filled with zeros

  • ones: Filled with all ones

  • inc: Filled with repeated numbers incremented by one 0-0xff

  • any kind of number, that will be repeated to fill up whole image. The format could be decimal, hexadecimal, bytes.

Constructor of pattern class.

Parameters:

pattern (str) – Supported patterns: - rand: Random Pattern - zeros: Filled with zeros - ones: Filled with all ones - inc: Filled with repeated numbers incremented by one 0-0xff - any kind of number, that will be repeated to fill up whole image. The format could be decimal, hexadecimal, bytes.

Raises:

SPSDKValueError – Unsupported pattern detected.

SPECIAL_PATTERNS = ['rand', 'zeros', 'ones', 'inc']#
get_block(size)#

Get block filled with pattern.

Parameters:

size (int) – Size of block to return.

Return type:

bytes

Returns:

Filled up block with specified pattern.

property pattern: str#

Get the pattern.

Returns:

Pattern in string representation.

class spsdk.utils.misc.Endianness(value)#

Bases: str, Enum

Endianness enum.

BIG = 'big'#
LITTLE = 'little'#
classmethod values()#

Get enumeration values.

Return type:

List[str]

class spsdk.utils.misc.SingletonMeta#

Bases: type

Singleton metaclass.

class spsdk.utils.misc.Timeout(timeout, units='s')#

Bases: object

Simple timeout handle class.

Simple timeout class constructor.

Parameters:
  • timeout (int) – Timeout value.

  • units (str) – Timeout units (MUST be from the UNITS list)

Raises:

SPSDKValueError – Invalid input value.

UNITS = {'ms': 1000, 's': 1000000, 'us': 1}#
get_consumed_time()#

Returns consumed time since start of timeout operation.

Return type:

int

Returns:

Consumed time in units as the class was constructed

get_consumed_time_ms()#

Returns consumed time since start of timeouted operation in milliseconds.

Return type:

int

Returns:

Consumed time in milliseconds

get_rest_time(raise_exc=False)#

Returns rest time to timeout overflow.

Parameters:

raise_exc (bool) – If set, the function raise SPSDKTimeoutError in case of overflow.

Return type:

int

Returns:

Rest time in units as the class was constructed

Raises:

SPSDKTimeoutError – In case of overflow

get_rest_time_ms(raise_exc=False)#

Returns rest time to timeout overflow.

Parameters:

raise_exc (bool) – If set, the function raise SPSDKTimeoutError in case of overflow.

Return type:

int

Returns:

Rest time in milliseconds

Raises:

SPSDKTimeoutError – In case of overflow

overflow(raise_exc=False)#

Check the the timer has been overflowed.

Parameters:

raise_exc (bool) – If set, the function raise SPSDKTimeoutError in case of overflow.

Return type:

bool

Returns:

True if timeout overflowed, False otherwise.

Raises:

SPSDKTimeoutError – In case of overflow

spsdk.utils.misc.align(number, alignment=4)#

Align number (size or address) size to specified alignment, typically 4, 8 or 16 bytes boundary.

Parameters:
  • number (int) – input to be aligned

  • alignment (int) – the boundary to align; typical value is power of 2

Return type:

int

Returns:

aligned number; result is always >= size (e.g. aligned up)

Raises:

SPSDKError – When there is wrong alignment

spsdk.utils.misc.align_block(data, alignment=4, padding=None)#

Align binary data block length to specified boundary by adding padding bytes to the end.

Parameters:
  • data (Union[bytes, bytearray]) – to be aligned

  • alignment (int) – boundary alignment (typically 2, 4, 16, 64 or 256 boundary)

  • padding (Union[int, str, BinaryPattern, None]) – byte to be added or BinaryPattern

Return type:

bytes

Returns:

aligned block

Raises:

SPSDKError – When there is wrong alignment

spsdk.utils.misc.align_block_fill_random(data, alignment=4)#

Same as align_block, just parameter padding is fixed to -1 to fill with random data.

Return type:

bytes

spsdk.utils.misc.change_endianness(bin_data)#

Convert binary format used in files to binary used in register object.

Parameters:

bin_data (bytes) – input binary array.

Return type:

bytes

Returns:

Converted array (practically little to big endianness).

Raises:

SPSDKError – Invalid value on input.

spsdk.utils.misc.check_range(x, start=0, end=4294967295)#

Check if the number is in range.

Parameters:
  • x (int) – Number to check.

  • start (int) – Lower border of range, default is 0.

  • end (int) – Upper border of range, default is unsigned 32-bit range.

Return type:

bool

Returns:

True if fits, False otherwise.

spsdk.utils.misc.deep_update(d, u)#

Deep update nested dictionaries.

Parameters:
  • d (Dict) – Dictionary that will be updated

  • u (Dict) – Dictionary with update information

Return type:

Dict

Returns:

Updated dictionary.

spsdk.utils.misc.extend_block(data, length, padding=0)#

Add padding to the binary data block to extend the length to specified value.

Parameters:
  • data (bytes) – block to be extended

  • length (int) – requested block length; the value must be >= current block length

  • padding (int) – 8-bit value value to be used as a padding

Return type:

bytes

Returns:

block extended with padding

Raises:

SPSDKError – When the length is incorrect

spsdk.utils.misc.find_dir(dir_path, use_cwd=True, search_paths=None, raise_exc=True)#

Return a full path to the directory.

search_paths takes precedence over CWD if used (default)

Parameters:
  • dir_path (str) – Directory name, part of directory path or full path

  • use_cwd (bool) – Try current working directory to find the directory, defaults to True

  • search_paths (Optional[List[str]]) – List of paths where to search for the directory, defaults to None

  • raise_exc (bool) – Raise exception if directory is not found, defaults to True

Return type:

str

Returns:

Full path to the directory

Raises:

SPSDKError – File not found

spsdk.utils.misc.find_file(file_path, use_cwd=True, search_paths=None, raise_exc=True)#

Return a full path to the file.

search_paths takes precedence over CWD if used (default)

Parameters:
  • file_path (str) – File name, part of file path or full path

  • use_cwd (bool) – Try current working directory to find the file, defaults to True

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

  • raise_exc (bool) – Raise exception if file is not found, defaults to True

Return type:

str

Returns:

Full path to the file

Raises:

SPSDKError – File not found

spsdk.utils.misc.find_first(iterable, predicate)#

Find first element from the list, that matches the condition.

Parameters:
  • iterable (Iterable[TypeVar(T)]) – list of elements

  • predicate (Callable[[TypeVar(T)], bool]) – function for selection of the element

Return type:

Optional[TypeVar(T)]

Returns:

found element; None if not found

spsdk.utils.misc.format_value(value, size, delimiter='_', use_prefix=True)#

Convert the ‘value’ into either BIN or HEX string, depending on ‘size’.

if ‘size’ is divisible by 8, function returns HEX, BIN otherwise digits in result string are grouped by 4 using ‘delimiter’ (underscore)

Return type:

str

spsdk.utils.misc.get_abs_path(file_path, base_dir=None)#

Return a full path to the file.

param base_dir: Base directory to create absolute path, if not specified the system CWD is used. return: Absolute file path.

Return type:

str

spsdk.utils.misc.get_bytes_cnt_of_int(value, align_to_2n=True, byte_cnt=None)#

Returns count of bytes needed to store handled integer.

Parameters:
  • value (int) – Input integer value.

  • align_to_2n (bool) – The result will be aligned to standard sizes 1,2,4,8,12,16,20.

  • byte_cnt (Optional[int]) – The result count of bytes.

Raises:

SPSDKValueError – The integer input value doesn’t fit into byte_cnt.

Return type:

int

Returns:

Number of bytes needed to store integer.

spsdk.utils.misc.get_hash(text)#

Returns hash of given text.

Return type:

str

spsdk.utils.misc.get_key_by_val(value, dictionary)#

Return key by its value.

Parameters:
  • value (str) – Value to find.

  • dictionary (Dict[str, List[str]]) – Dictionary to find in.

Raises:

SPSDKValueError – Value is not present in dictionary.

Return type:

str

Returns:

Key name

spsdk.utils.misc.load_binary(path, search_paths=None)#

Loads binary file into bytes.

Parameters:
  • path (str) – Path to the file.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

bytes

Returns:

content of the binary file as bytes

spsdk.utils.misc.load_configuration(path, search_paths=None)#

Load configuration from yml/json file.

Parameters:
  • path (str) – Path to configuration file

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Raises:

SPSDKError – When unsupported file is provided

Return type:

Dict

Returns:

Content of configuration as dictionary

spsdk.utils.misc.load_file(path, mode='r', search_paths=None)#

Loads a file into bytes.

Parameters:
  • path (str) – Path to the file.

  • mode (str) – mode for reading the file ‘r’/’rb’

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

Union[str, bytes]

Returns:

content of the binary file as bytes or str (based on mode)

spsdk.utils.misc.load_hex_string(source, expected_size, search_paths=None)#

Get the HEX string from the command line parameter (Keys, digests, etc).

Parameters:
  • source (Union[str, int, bytes, None]) – File path to key file or hexadecimal value. If not specified random value is used.

  • expected_size (int) – Expected size of key in bytes.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Raises:

SPSDKError – Invalid key

Return type:

bytes

Returns:

Key in bytes.

spsdk.utils.misc.load_text(path, search_paths=None)#

Loads text file into string.

Parameters:
  • path (str) – Path to the file.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

str

Returns:

content of the text file as string

spsdk.utils.misc.numberify_version(version, separator='.', valid_numbers=3)#

Turn version string into a number.

Each group is weighted by a multiple of 1000

1.2.3 -> 1 * 1_000_000 + 2 * 1_000 + 3 * 1 = 1_002_003 21.100.9 -> 21 * 1_000_000 + 100 * 1_000 + 9 * 1 = 21_100_009

Parameters:
  • version (str) – Version string numbers separated by separator

  • separator (str) – Separator used in the version string, defaults to “.”

  • valid_numbers (int) – Amount of numbers to sanitize to consider, defaults to 3

Return type:

int

Returns:

Number representing the version

spsdk.utils.misc.reverse_bits_in_bytes(arr)#

The function reverse bits order in input bytes.

Parameters:

arr (bytes) – Input array.

Return type:

bytes

Returns:

New array with reversed bits in bytes.

Raises:

SPSDKError – Raises when invalid value is in input.

spsdk.utils.misc.reverse_bytes_in_longs(arr)#

The function reverse byte order in longs from input bytes.

Parameters:

arr (bytes) – Input array.

Return type:

bytes

Returns:

New array with reversed bytes.

Raises:

SPSDKError – Raises when invalid value is in input.

spsdk.utils.misc.sanitize_version(version, separator='.', valid_numbers=3)#

Sanitize version string.

Append ‘.0’ in case version string has fewer parts than valid_numbers Remove right-most version parts after valid_numbers amount of parts

1.2 -> 1.2.0 1.2.3.4 -> 1.2.3

Parameters:
  • version (str) – Original version string

  • separator (str) – Separator used in the version string, defaults to “.”

  • valid_numbers (int) – Amount of numbers to sanitize, defaults to 3

Return type:

str

Returns:

Sanitized version string

spsdk.utils.misc.size_fmt(num, use_kibibyte=True)#

Size format.

Return type:

str

spsdk.utils.misc.split_data(data, size)#

Split data into chunks of size.

Parameters:
  • data (bytearray) – array of bytes to be split

  • size (int) – size of splitted array

Return Generator[bytes]:

splitted array

Return type:

Generator[bytes, None, None]

spsdk.utils.misc.swap16(x)#

Swap bytes in half word (16bit).

Parameters:

x (int) – Original number

Return type:

int

Returns:

Number with swapped bytes

Raises:

SPSDKError – When incorrect number to be swapped is provided

spsdk.utils.misc.swap32(x)#

Swap 32 bit integer.

Parameters:

x (int) – integer to be swapped

Return type:

int

Returns:

swapped value

Raises:

SPSDKError – When incorrect number to be swapped is provided

spsdk.utils.misc.use_working_directory(path)#

Execute the block in given directory.

Cd into specific directory. Execute the block. Change the directory back into the original one.

Parameters:

path (str) – the path, where the current directory will be changed to

Return type:

Iterator[None]

spsdk.utils.misc.value_to_bool(value)#

Function decode bool value from various formats.

Parameters:

value (Union[bool, int, str]) – Input value.

Return type:

bool

Returns:

Boolean value.

Raises:

SPSDKError – Unsupported input type.

spsdk.utils.misc.value_to_bytes(value, align_to_2n=True, byte_cnt=None, endianness=Endianness.BIG)#

Function loads value from lot of formats.

Parameters:
  • value (Union[bytes, bytearray, int, str]) – Input value.

  • align_to_2n (bool) – When is set, the function aligns length of return array to 1,2,4,8,12 etc.

  • byte_cnt (Optional[int]) – The result count of bytes.

  • endianness (Endianness) – The result bytes endianness [‘big’, ‘little’].

Return type:

bytes

Returns:

Value in bytes.

spsdk.utils.misc.value_to_int(value, default=None)#

Function loads value from lot of formats to integer.

Parameters:
  • value (Union[bytes, bytearray, int, str]) – Input value.

  • default (Optional[int]) – Default Value in case of invalid input.

Return type:

int

Returns:

Value in Integer.

Raises:

SPSDKError – Unsupported input type.

spsdk.utils.misc.wrap_text(text, max_line=100)#

Wrap text in SPSDK standard.

Count with new lines in input string and do wrapping after that.

Parameters:
  • text (str) – Text to wrap

  • max_line (int) – Max line in output, defaults to 100

Return type:

str

Returns:

Wrapped text (added new lines characters on right places)

spsdk.utils.misc.write_file(data, path, mode='w', encoding=None)#

Writes data into a file.

Parameters:
  • data (Union[str, bytes]) – data to write

  • path (str) – Path to the file.

  • mode (str) – writing mode, ‘w’ for text, ‘wb’ for binary data, defaults to ‘w’

  • encoding (Optional[str]) – Encoding of written file (‘ascii’, ‘utf-8’).

Return type:

int

Returns:

number of written elements

Image utils#

Module to keep additional utilities for binary images.

class spsdk.utils.images.BinaryImage(name, size=0, offset=0, description=None, binary=None, pattern=None, alignment=1, parent=None)#

Bases: object

Binary Image class.

Binary Image class constructor.

Parameters:
  • name (str) – Name of Image.

  • size (int) – Image size.

  • offset (int) – Image offset in parent image, defaults to 0

  • description (Optional[str]) – Text description of image, defaults to None

  • binary (Optional[bytes]) – Optional binary content.

  • pattern (Optional[BinaryPattern]) – Optional binary pattern.

  • alignment (int) – Optional alignment of result image

  • parent (Optional[BinaryImage]) – Handle to parent object, defaults to None

MINIMAL_DRAW_WIDTH = 30#
property absolute_address: int#

Image absolute address relative to base parent.

Returns:

Absolute address relative to base parent

add_image(image)#

Add new sub image information.

Parameters:

image (BinaryImage) – Image object.

Return type:

None

aligned_length(alignment=4)#

Returns aligned length for erasing purposes.

Parameters:

alignment (int) – The alignment value, defaults to 4.

Return type:

int

Returns:

Ceil alignment length.

aligned_start(alignment=4)#

Returns aligned start address.

Parameters:

alignment (int) – The alignment value, defaults to 4.

Return type:

int

Returns:

Floor alignment address.

append_image(image)#

Append new sub image at the end of the parent.

This function use the size of the parent as a offset for new appended image.

Parameters:

image (BinaryImage) – Image object.

Return type:

None

draw(include_sub_images=True, width=0, color='', no_color=False)#

Draw the image into the ASCII graphics.

Parameters:
  • include_sub_images (bool) – Include also sub images into, defaults to True

  • width (int) – Fixed width of table, 0 means autosize.

  • color (str) – Color of this block, None means automatic color.

  • no_color (bool) – Disable adding colors into output.

Raises:

SPSDKValueError – In case of invalid width.

Return type:

str

Returns:

ASCII art representation of image.

export()#

Export represented binary image.

Return type:

bytes

Returns:

Byte array of binary image.

find_sub_image(name)#

Find sub image by its name.

Parameters:

name (str) – Name of sub image

Raises:

SPSDKValueError – The sub image with requested name doesn’t exists

Return type:

BinaryImage

Returns:

Sub Image object

static generate_config_template()#

Generate configuration template.

Return type:

str

Returns:

Template to create binary merge..

get_image_by_absolute_address(address)#

Get Binary Image object that contains the provided absolute address.

Parameters:

address (int) – Absolute address to image

Raises:

SPSDKValueError – Exception when the address doesn’t fit into address space

Return type:

BinaryImage

Returns:

Binary image object that contains the data.

get_min_draw_width(include_sub_images=True)#

Get minimal width of table for draw function.

Parameters:

include_sub_images (bool) – Include also sub images into, defaults to True

Return type:

int

Returns:

Minimal width in characters.

static get_validation_schemas()#

Get validation schemas list to check a supported configuration.

Return type:

List[Dict[str, Any]]

Returns:

Validation schemas.

property image_name: str#

Image name including all parents.

Returns:

Full Image name

join_images()#

Join all sub images into main binary block.

Return type:

None

static load_binary_image(path, name=None, size=0, offset=0, description=None, pattern=None, search_paths=None, alignment=1, load_bin=True)#

Load binary data file.

Supported formats are ELF, HEX, SREC and plain binary

Parameters:
  • path (str) – Path to the file.

  • name (Optional[str]) – Name of Image, defaults to file name.

  • size (int) – Image size, defaults to 0.

  • offset (int) – Image offset in parent image, defaults to 0

  • description (Optional[str]) – Text description of image, defaults to None

  • pattern (Optional[BinaryPattern]) – Optional binary pattern.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

  • alignment (int) – Optional alignment of result image

  • load_bin (bool) – Load as binary in case of every other format load fails

Raises:

SPSDKError – The binary file cannot be loaded.

Return type:

BinaryImage

Returns:

Binary data represented in BinaryImage class.

static load_from_config(config, search_paths=None)#

Converts the configuration option into an Binary Image object.

Parameters:
  • config (Dict[str, Any]) – Description of binary image.

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Return type:

BinaryImage

Returns:

Initialized Binary Image.

save_binary_image(path, file_format='BIN')#

Save binary data file.

Parameters:
  • path (str) – Path to the file.

  • file_format (str) – Format of saved file (‘BIN’, ‘HEX’, ‘S19’), defaults to ‘BIN’.

Raises:

SPSDKValueError – The file format is invalid.

Return type:

None

property size: int#

Size property.

update_offsets()#

Update offsets from the sub images into main offset value begin offsets.

Return type:

None

validate()#

Validate if the images doesn’t overlaps each other.

Return type:

None

class spsdk.utils.images.ColorPicker#

Bases: object

Simple class to get each time when ask different color from list.

Constructor of ColorPicker.

COLORS = ['\x1b[90m', '\x1b[34m', '\x1b[32m', '\x1b[36m', '\x1b[33m', '\x1b[35m', '\x1b[37m', '\x1b[94m', '\x1b[96m', '\x1b[92m', '\x1b[95m', '\x1b[97m', '\x1b[93m']#
get_color(unwanted_color=None)#

Get new color from list.

Parameters:

unwanted_color (Optional[str]) – Color that should be omitted.

Return type:

str

Returns:

Color

Interfaces utils#

Device Interfaces.

Serial Proxy#

SerialProxy serves as patch replacement for serial.Serial class.

class spsdk.utils.serial_proxy.SerialProxy(port, timeout, baudrate, write_timeout=None)#

Bases: object

SerialProxy is used to simulate communication with serial device.

It can be used as mock.patch for serial.Serial class. @patch(<your.package>.Serial, SerialProxy.init_proxy(pre_recorded_responses))

Basic initialization for serial.Serial class.

__init__ signature must accommodate instantiation of serial.Serial

Parameters:
  • port (str) – Serial port name

  • timeout (int) – timeout (does nothing)

  • write_timeout (Optional[int]) – does nothing

  • baudrate (int) – Serial port speed (does nothing)

close()#

Simulates closing a serial port.

Return type:

None

flush()#

Simulates flushing input buffer.

Return type:

None

ignore_ack: bool = False#
classmethod init_proxy(data, ignore_ack=False)#

Initialized response dictionary of write and read bytes.

Parameters:
  • data (Dict[bytes, bytes]) – Dictionary of write and read bytes

  • ignore_ack (bool) – Don’t modify internal buffer upon receiving a ACK packet

Return type:

Type[SerialProxy]

Returns:

SerialProxy class with configured data

open()#

Simulates opening a serial port.

Return type:

None

read(length)#

Read portion of pre-configured data.

Parameters:

length (int) – Amount of data to read from buffer

Return type:

bytes

Returns:

Data read

reset_input_buffer()#

Simulates resetting input buffer.

Return type:

None

reset_output_buffer()#

Simulates resetting output buffer.

Return type:

None

responses: Dict[bytes, bytes] = {}#
write(data)#

Simulates a write, currently just pick up response from responses.

Parameters:

data (bytes) – Bytes to write, key in responses

Return type:

None

class spsdk.utils.serial_proxy.SimpleReadSerialProxy(port, timeout, baudrate, write_timeout=None)#

Bases: SerialProxy

SimpleReadSerialProxy is used to simulate communication with serial device.

It simplifies reading method. @patch(<your.package>.Serial, SerialProxy.init_proxy(pre_recorded_responses))

Basic initialization for serial.Serial class.

__init__ signature must accommodate instantiation of serial.Serial

Parameters:
  • port (str) – Serial port name

  • timeout (int) – timeout (does nothing)

  • write_timeout (Optional[int]) – does nothing

  • baudrate (int) – Serial port speed (does nothing)

FULL_BUFFER = b''#
classmethod init_data_proxy(data)#

Initialized response dictionary of write and read bytes.

Parameters:

data (bytes) – Dictionary of write and read bytes

Return type:

Type[SimpleReadSerialProxy]

Returns:

SerialProxy class with configured data

write(data)#

Simulates a write method, but it does nothing.

Parameters:

data (bytes) – Bytes to write, key in responses

Return type:

None

USB Filter#

Module defining a USB filtering class.

class spsdk.utils.usbfilter.NXPUSBDeviceFilter(usb_id=None, nxp_device_names=None)#

Bases: USBDeviceFilter

NXP Device Filtering class.

Extension of the generic USB device filter class to support filtering based on NXP devices. Modifies the way, how single number is handled. By default, if single value is provided, it’s content is expected to be VID. However, legacy tooling were expecting PID, so from this perspective if a single number is provided, we expect that VID is out of range NXP_VIDS.

Initialize the USB Device Filtering.

Parameters:
  • usb_id (Optional[str]) – usb_id string

  • nxp_device_names (Optional[Dict[str, Tuple[int, int]]]) – Dictionary holding NXP device vid/pid {“device_name”: [vid(int), pid(int)]}

NXP_VIDS = [8137, 5538, 1137, 3368]#
compare(usb_device_object)#

Compares the internal usb_id with provided usb_device_object.

Extends the comparison by USB names - dictionary of device name and corresponding VID/PID.

Parameters:

usb_device_object (Any) – lpcusbsio USB HID device object

Return type:

bool

Returns:

True on match, False otherwise

class spsdk.utils.usbfilter.USBDeviceFilter(usb_id=None, search_by_pid=False)#

Bases: object

Generic USB Device Filtering class.

Create a filtering instance. This instance holds the USB ID you are interested in during USB HID device search and allows you to compare, whether provided USB HID object is the one you are interested in. The allowed format of usb_id string is following:

vid or pid - vendor ID or product ID. String holding hex or dec number. Hex number must be preceded by 0x or 0X. Number of characters after 0x is 1 - 4. Mixed upper & lower case letters is allowed. e.g. “0xaB12”, “0XAB12”, “0x1”, “0x0001”. The decimal number is restricted only to have 1 - 5 digits, e.g. “65535” It’s allowed to set the USB filter ID to decimal number “99999”, however, as the USB VID number is four-byte hex number (max value is 65535), this will lead to zero results. Leading zeros are not allowed e.g. 0001. This will result as invalid match.

The user may provide a single number as usb_id. In such a case the number may represent either VID or PID. By default, the filter expects this number to be a VID. In rare cases the user may want to filter based on PID. Initialize the search_by_pid parameter to True in such cases.

vid/pid - string of vendor ID & product ID separated by ‘:’ or ‘,’ Same rules apply to the number format as in VID case, except, that the string consists of two numbers separated by ‘:’ or ‘,’. It’s not allowed to mix hex and dec numbers, e.g. “0xab12:12345” is not allowed. Valid vid/pid strings: “0x12aB:0xabc”, “1,99999”

Windows specific: instance ID - String in following format “HIDVID_<HEX>&PID_<HEX><instance_id>”, see instance ID in device manager under Windows OS.

Linux specific: USB device path - HID API returns path in following form: ‘0003:0002:00’

The first number represents the Bus, the second Device and the third interface. The Bus:Device number is unique so interface is not necessary and Bus:Device should be sufficient.

The Bus:Device can be observed using ‘lsusb’ command. The interface can be observed using ‘lsusb -t’. lsusb returns the Bus and Device as a 3-digit number. It has been agreed, that the expected input is: <Bus in dec>#<Device in dec>, e.g. 3#11

Mac specific: USB device path - HID API returns path in roughly following form: ‘IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/XHC1@14/XHC1@14000000/HS01@14100000/SE Blank RT Family @14100000/IOUSBHostInterface@0/AppleUserUSBHostHIDDevice’

This path can be found using the ‘ioreg’ utility or using ‘IO Hardware Registry Explorer’ tool. However, using the system report from ‘About This MAC -> System Report -> USB’ a partial path can also be gathered. Using the name of USB device from the ‘USB Device Tree’ and appending the ‘Location ID’ should work. The name can be ‘SE Blank RT Family’ and the ‘Location ID’ is in form <hex> / <dec>, e.g. ‘0x14200000 / 18’. So the ‘usb_id’ name should be ‘SE Blank RT Family @14200000’ and the filter should be able to filter out such device.

Initialize the USB Device Filtering.

Parameters:
  • usb_id (Optional[str]) – usb_id string

  • search_by_pid (bool) – if true, expects usb_id to be a PID number, VID otherwise.

compare(usb_device_object)#

Compares the internal usb_id with provided usb_device_object.

The provided USB ID during initialization may be VID or PID, VID/PID pair, or a path. See private methods for details.

Parameters:

usb_device_object (Dict[str, Any]) – Libusbsio/HID_API device object (dictionary)

Return type:

bool

Returns:

True on match, False otherwise

static convert_usb_path(hid_api_usb_path)#

Converts the Libusbsio/HID_API path into string, which can be observed from OS.

DESIGN REMARK: this function is not part of the USBLogicalDevice, as the class intention is to be just a simple container. But to help the class to get the required inputs, this helper method has been provided. Additionally, this method relies on the fact that the provided path comes from the Libusbsio/HID_API. This method will most probably fail or provide improper results in case path from different USB API is provided.

Parameters:

hid_api_usb_path (bytes) – USB device path from Libusbsio/HID_API

Return type:

str

Returns:

Libusbsio/HID_API path converted for given platform

Registers descriptions with support for XML files#

Module to handle registers descriptions with support for XML files.

class spsdk.utils.registers.ConfigProcessor(description='')#

Bases: object

Base class for processing configuration data.

Initialize the processor.

NAME = 'NOP'#
classmethod from_str(config_string)#

Create config processor instance from configuration string.

Return type:

ConfigProcessor

classmethod from_xml(element)#

Create config processor from XML data entry.

Return type:

Optional[ConfigProcessor]

classmethod get_description(config_string)#

Return extra description for config processor.

Return type:

str

classmethod get_method_name(config_string)#

Return config processor method name.

Return type:

str

classmethod get_params(config_string)#

Return config processor method parameters.

Return type:

Dict[str, int]

post_process(value)#

Post-process value going to config file.

Return type:

int

pre_process(value)#

Pre-process value coming from config file.

Return type:

int

width_update(value)#

Update bit-width of value going to config file.

Return type:

int

class spsdk.utils.registers.Registers(device_name, base_endianness=Endianness.BIG)#

Bases: object

SPSDK Class for registers handling.

Initialization of Registers class.

TEMPLATE_NOTE = 'All registers is possible to define also as one value although the bitfields are used. Instead of bitfields: ... field, the value: ... definition works as well.'#
add_register(reg)#

Adds register into register list.

Parameters:

reg (RegsRegister) – Register to add to the class.

Raises:
Return type:

None

export(size=0, pattern=<spsdk.utils.misc.BinaryPattern object>)#

Export Registers into binary.

Parameters:
  • size (int) – Result size of Image, 0 means automatic minimal size.

  • pattern (BinaryPattern) – Pattern of gaps, defaults to “zeros”

Return type:

bytes

find_reg(name, include_group_regs=False)#

Returns the instance of the register by its name.

Parameters:
  • name (str) – The name of the register.

  • include_group_regs (bool) – The algorithm will check also group registers.

Return type:

RegsRegister

Returns:

Instance of the register.

Raises:

SPSDKRegsErrorRegisterNotFound – The register doesn’t exist.

get_config(diff=False)#

Get the whole configuration in dictionary.

Parameters:

diff (bool) – Get only configuration with difference value to reset state.

Return type:

Dict[str, Any]

Returns:

Dictionary of registers values.

get_reg_names(exclude=None, include_group_regs=False)#

Returns list of the register names.

Parameters:
  • exclude (Optional[List[str]]) – Exclude list of register names if needed.

  • include_group_regs (bool) – The algorithm will check also group registers.

Return type:

List[str]

Returns:

List of register names.

get_registers(exclude=None, include_group_regs=False)#

Returns list of the registers.

Method allows exclude some register by their names. :type exclude: Optional[List[str]] :param exclude: Exclude list of register names if needed. :type include_group_regs: bool :param include_group_regs: The algorithm will check also group registers. :rtype: List[RegsRegister] :return: List of register names.

get_validation_schema()#

Get the JSON SCHEMA for registers.

Return type:

Dict

Returns:

JSON SCHEMA.

image_info(size=0, pattern=<spsdk.utils.misc.BinaryPattern object>)#

Export Registers into binary information.

Parameters:
  • size (int) – Result size of Image, 0 means automatic minimal size.

  • pattern (BinaryPattern) – Pattern of gaps, defaults to “zeros”

Return type:

BinaryImage

load_registers_from_xml(xml, filter_reg=None, grouped_regs=None)#

Function loads the registers from the given XML.

Parameters:
  • xml (str) – Input XML data in string format.

  • filter_reg (Optional[List[str]]) – List of register names that should be filtered out.

  • grouped_regs (Optional[List[dict]]) – List of register prefixes names to be grouped into one.

Raises:

SPSDKRegsError – XML parse problem occurs.

Return type:

None

load_yml_config(yml_data)#

The function loads the configuration from YML file.

Parameters:

yml_data (Dict[str, Any]) – The YAML commented data with register values.

Return type:

None

parse(binary)#

Parse the binary data values into loaded registers.

Parameters:

binary (bytes) – Binary data to parse.

Return type:

None

remove_registers()#

Remove all registers.

Return type:

None

reset_values(exclude=None)#

The method reset values in registers.

Parameters:

exclude (Optional[List[str]]) – The list of register names to be excluded.

Return type:

None

write_xml(file_name)#

Write loaded register structures into XML file.

Parameters:

file_name (str) – The name of XML file that should be created.

Return type:

None

class spsdk.utils.registers.RegsBitField(parent, name, offset, width, description=None, reset_val='0', access='RW', hidden=False, config_processor=None)#

Bases: object

Storage for register bitfields.

Constructor of RegsBitField class. Used to store bitfield information.

Parameters:
  • parent (RegsRegister) – Parent register of bitfield.

  • name (str) – Name of bitfield.

  • offset (int) – Bit offset of bitfield.

  • width (int) – Bit width of bitfield.

  • description (Optional[str]) – Text description of bitfield.

  • reset_val (Any) – Reset value of bitfield.

  • access (str) – Access type of bitfield.

  • hidden (bool) – The bitfield will be hidden from standard searches.

add_enum(enum)#

Add bitfield enum.

Parameters:

enum (RegsEnum) – New enumeration value for bitfield.

Return type:

None

add_et_subelement(parent)#

Creates the register XML structure in ElementTree.

Parameters:

parent (Element) – The parent object of ElementTree.

Return type:

None

classmethod from_xml_element(xml_element, parent)#

Initialization register by XML ET element.

Parameters:
  • xml_element (Element) – Input XML subelement with register data.

  • parent (RegsRegister) – Reference to parent RegsRegister object.

Return type:

RegsBitField

Returns:

The instance of this class.

get_enum_constant(enum_name)#

Returns constant representation of enum by its name.

Return type:

int

Returns:

Constant of enum.

Raises:

SPSDKRegsErrorEnumNotFound – The enum has not been found.

get_enum_names()#

Returns list of the enum strings.

Return type:

List[str]

Returns:

List of enum names.

get_enum_value()#

Returns enum value of the bitfield.

Return type:

Union[str, int]

Returns:

Current value of bitfield.

get_enums()#

Returns bitfield enums.

Return type:

List[RegsEnum]

Returns:

List of bitfield enumeration values.

get_hex_value()#

Get the value of register in string hex format.

Return type:

str

Returns:

Hexadecimal value of register.

get_reset_value()#

Returns integer reset value of the bitfield.

Return type:

int

Returns:

Reset value of bitfield.

get_value()#

Returns integer value of the bitfield.

Return type:

int

Returns:

Current value of bitfield.

has_enums()#

Returns if the bitfields has enums.

Return type:

bool

Returns:

True is has enums, False otherwise.

set_enum_value(new_val, raw=False)#

Updates the value of the bitfield by its enum value.

Parameters:
  • new_val (str) – New enum value of bitfield.

  • raw (bool) – If set, no automatic modification of value is applied.

Raises:

SPSDKRegsErrorEnumNotFound – Input value cannot be decoded.

Return type:

None

set_value(new_val, raw=False)#

Updates the value of the bitfield.

Parameters:
  • new_val (Any) – New value of bitfield.

  • raw (bool) – If set, no automatic modification of value is applied.

Raises:

SPSDKValueError – The input value is out of range.

Return type:

None

class spsdk.utils.registers.RegsEnum(name, value, description, max_width=0)#

Bases: object

Storage for register enumerations.

Constructor of RegsEnum class. Used to store enumeration information of bitfield.

Parameters:
  • name (str) – Name of enumeration.

  • value (Any) – Value of enumeration.

  • description (str) – Text description of enumeration.

  • max_width (int) – Maximal width of enum value used to format output

Raises:

SPSDKRegsError – Invalid input value.

add_et_subelement(parent)#

Creates the register XML structure in ElementTree.

Parameters:

parent (Element) – The parent object of ElementTree.

Return type:

None

classmethod from_xml_element(xml_element, maxwidth=0)#

Initialization Enum by XML ET element.

Parameters:
  • xml_element (Element) – Input XML subelement with enumeration data.

  • maxwidth (int) – The maximal width of bitfield for this enum (used for formatting).

Return type:

RegsEnum

Returns:

The instance of this class.

Raises:

SPSDKRegsError – Error during enum XML parsing.

get_value_int()#

Method returns Integer value of enum.

Return type:

int

Returns:

Integer value of Enum.

get_value_str()#

Method returns formatted value.

Return type:

str

Returns:

Formatted string with enum value.

class spsdk.utils.registers.RegsRegister(name, offset, width, description=None, reverse=False, access=None, config_as_hexstring=False, otp_index=None, reverse_subregs_order=False, base_endianness=Endianness.BIG, alt_widths=None)#

Bases: object

Initialization register by input information.

Constructor of RegsRegister class. Used to store register information.

Parameters:
  • name (str) – Name of register.

  • offset (int) – Byte offset of register.

  • width (int) – Bit width of register.

  • description (Optional[str]) – Text description of register.

  • reverse (bool) – Multi byte register value could be printed in reverse order.

  • access (Optional[str]) – Access type of register.

  • config_as_hexstring (bool) – Config is stored as a hex string.

  • otp_index (Optional[int]) – Index of OTP fuse.

  • reverse_subregs_order (bool) – Reverse order of sub registers.

  • base_endianness (Endianness) – Base endianness for bytes import/export of value.

  • alt_widths (Optional[List[int]]) – List of alternative widths.

add_alias(alias)#

Add alias name to register.

Parameters:

alias (str) – Register name alias.

Return type:

None

add_bitfield(bitfield)#

Add register bitfield.

Parameters:

bitfield (RegsBitField) – New bitfield value for register.

Return type:

None

add_et_subelement(parent)#

Creates the register XML structure in ElementTree.

Parameters:

parent (Element) – The parent object of ElementTree.

Return type:

None

add_group_reg(reg)#

Add group element for this register.

Parameters:

reg (RegsRegister) – Register member of this register group.

Raises:

SPSDKRegsErrorRegisterGroupMishmash – When any inconsistency is detected.

Return type:

None

add_setvalue_hook(hook, context=None)#

Set the value hook for write operation.

Parameters:
  • hook (Callable) – Callable hook for set value operation.

  • context (Optional[Any]) – Context data for this hook.

Return type:

None

find_bitfield(name)#

Returns the instance of the bitfield by its name.

Parameters:

name (str) – The name of the bitfield.

Return type:

RegsBitField

Returns:

Instance of the bitfield.

Raises:

SPSDKRegsErrorBitfieldNotFound – The bitfield doesn’t exist.

classmethod from_xml_element(xml_element)#

Initialization register by XML ET element.

Parameters:

xml_element (Element) – Input XML subelement with register data.

Return type:

RegsRegister

Returns:

The instance of this class.

get_alt_width(value)#

Get alternative width of register.

Parameters:

value (int) – Input value to recognize width

Return type:

int

Returns:

Current width

get_bitfield_names(exclude=None)#

Returns list of the bitfield names.

Parameters:

exclude (Optional[List[str]]) – Exclude list of bitfield names if needed.

Return type:

List[str]

Returns:

List of bitfield names.

get_bitfields(exclude=None)#

Returns register bitfields.

Method allows exclude some bitfields by their names. :type exclude: Optional[List[str]] :param exclude: Exclude list of bitfield names if needed. :rtype: List[RegsBitField] :return: Returns List of register bitfields.

get_bytes_value(raw=False)#

Get the bytes value of register.

Parameters:

raw (bool) – Do not use any modification hooks.

Return type:

bytes

Returns:

Register value in bytes.

get_hex_value(raw=False)#

Get the value of register in string hex format.

Parameters:

raw (bool) – Do not use any modification hooks.

Return type:

str

Returns:

Hexadecimal value of register.

get_reset_value()#

Returns reset value of the register.

Return type:

int

Returns:

Reset value of register.

get_value(raw=False)#

Get the value of register.

Parameters:

raw (bool) – Do not use any modification hooks.

Return type:

int

has_group_registers()#

Returns true if register is compounded from sub-registers.

Return type:

bool

Returns:

True if register has sub-registers, False otherwise.

reset_value(raw=False)#

Reset the value of register.

Parameters:

raw (bool) – Do not use any modification hooks.

Return type:

None

set_value(val, raw=False)#

Set the new value of register.

Parameters:
  • val (Any) – The new value to set.

  • raw (bool) – Do not use any modification hooks.

Raises:

SPSDKError – When invalid values is loaded into register

Return type:

None

class spsdk.utils.registers.ShiftRightConfigProcessor(count, description='')#

Bases: ConfigProcessor

Config processor performing the right-shift operation.

Initialize the right-shift config processor.

Parameters:
  • count (int) – Count of bit for shift operation

  • description (str) – Extra description for config processor, defaults to “”

NAME = 'SHIFT_RIGHT'#
classmethod from_str(config_string)#

Create config processor instance from configuration string.

Return type:

ShiftRightConfigProcessor

post_process(value)#

Post-process value going to config file.

Return type:

int

pre_process(value)#

Pre-process value coming from config file.

Return type:

int

width_update(value)#

Update bit-width of value going to config file.

Return type:

int

Register’s configuration#

Module to handle registers configuration.

class spsdk.utils.reg_config.RegConfig(family, feature, revision='latest', db_path=None)#

Bases: object

Class that helps manage the registers configuration.

Initialize the class that handles information regarding register settings.

Parameters:
  • family (str) – Family name

  • feature (str) – Feature name

  • revision (str) – Revision of family

  • db_path (Optional[List[str]]) – Optional database path list of nested information

get_address(alt_read_address=False)#

Get the area address in chip memory.

Parameters:

alt_read_address (bool) – The flag is used if an alternate read address applies.

Return type:

int

Returns:

Base address of registers.

get_antipole_regs()#

Return the list of inverted registers.

Return type:

Dict[str, str]

Returns:

The dictionary of antipole registers.

get_computed_fields()#

Return the list of computed fields (not used in config YML files).

Return type:

Dict[str, Dict[str, str]]

Returns:

The dictionary of computed fields.

get_computed_registers()#

Return the dictionary of computed registers.

Return type:

Dict[str, Any]

Returns:

The dictionary of computed registers.

get_data_file()#

Return the full path to data file (xml).

Raises:

SPSDKValueError – When datafile is not defined in the database

Return type:

str

Returns:

The path to data file.

get_grouped_registers()#

Return the list of grouped registers description.

Return type:

List[dict]

Returns:

The list of grouped registers descriptions.

get_seal_count()#

Return the seal count.

Return type:

Optional[int]

Returns:

The seal count.

Raises:

SPSDKError – When there is invalid seal count

get_seal_start_address()#

Return the seal start address.

Return type:

Optional[str]

Returns:

The seal start register name.

Raises:

SPSDKError – When seal start address has invalid name

get_value(key, default=None)#

Return any parameter by key.

Parameters:
  • key (str) – The Key of the parameter to be returned.

  • default (Optional[Any]) – The default Value in case that is not specified in config file.

Return type:

Any

Returns:

The Value of parameter by handled Key.

USB Device Scanner#

NXP USB Device Scanner API.

spsdk.utils.nxpdevscan.search_libusbsio_devices()#

Returns a list of all LIBUSBSIO devices.

Retval:

list of UartDeviceDescription devices from devicedescription module

Raises:

SPSDKError – In any case of LIBUSBSIO problems.

Return type:

List[SIODeviceDescription]

spsdk.utils.nxpdevscan.search_nxp_sdio_devices()#

Searches all NXP SDIO devices based on their device path.

Return type:

List[SDIODeviceDescription]

Returns:

list of SDIODeviceDescription corresponding to NXP devices

spsdk.utils.nxpdevscan.search_nxp_uart_devices()#

Returns a list of all NXP devices connected via UART.

Retval:

list of UartDeviceDescription devices from devicedescription module

Return type:

List[UartDeviceDescription]

spsdk.utils.nxpdevscan.search_nxp_usb_devices(extend_vid_list=None)#

Searches all NXP USB devices based on their Vendor ID.

Extend_vid_list:

list of VIDs, to extend the default NXP VID list (int)

Return type:

List[USBDeviceDescription]

Returns:

list of USBDeviceDescription corresponding to NXP devices

Device description#

Module for NXP device description classes.

class spsdk.utils.devicedescription.DeviceDescription#

Bases: ABC

Base class for all logical devices.

The intent is to have a generic container for providing info about devices of any type. Thus the class is named as ‘logical’, because it doesn’t allow you to control the device in any way.

This is just a base class and as such shouldn’t be used. If you want to use it, create your own class inheriting from this class and redefining the methods listed in this class!

class spsdk.utils.devicedescription.SDIODeviceDescription(vid, pid, path)#

Bases: DeviceDescription

Simple container holding information about SDIO device.

This container should be used instead of any SDIO API related objects, as this container will be the same all the time compared to specific SDIO API implementations.

Constructor.

Parameters:
  • vid (int) – Vendor ID

  • pid (int) – Product ID

See get_usb_device_name() function to getg the name from VID and PID. See convert_usb_path() function to provide a proper path string.

class spsdk.utils.devicedescription.SIODeviceDescription(info)#

Bases: DeviceDescription

Simple container holding information about LIBUSBSIO device.

This container contains information about LIBUSBSIOdevice.

Constructor.

Parameters:

info (HIDAPI_DEVICE_INFO_T) – LIBUSBSIO device information class.

class spsdk.utils.devicedescription.USBDeviceDescription(vid, pid, path, product_string, manufacturer_string, name, serial, original_path=None)#

Bases: DeviceDescription

Simple container holding information about USB device.

This container should be used instead of any USB API related objects, as this container will be the same all the time compared to specific USB API implementations.

Constructor.

Parameters:
  • vid (int) – Vendor ID

  • pid (int) – Product ID

  • product_string (str) – Product string

  • manufacturer_string (str) – Manufacturer string

  • name (str) – Name(s) of NXP devices as defined under spsdk.mboot.interfaces.usb or spsdk.sdp.interfaces.usb

  • serial (str) – The serial number of device.

See get_usb_device_name() function to get the name from VID and PID. See convert_usb_path() function to provide a proper path string.

class spsdk.utils.devicedescription.UartDeviceDescription(name=None, dev_type=None)#

Bases: DeviceDescription

Simple container holding information about UART device.

This container should be used instead of any USB API related objects, as this container will be the same all the time compared to specific UART API implementations.

Constructor.

The ‘dev_type’ can be in general any string identifying the device type.

Parameters:
  • name (Optional[str]) – COM port name

  • dev_type (Optional[str]) – ‘mboot device’ or ‘SDP device’

spsdk.utils.devicedescription.get_usb_device_name(vid, pid, device_names=None)#

Returns ‘name’ device identifier based on VID/PID, from dicts.

Searches provided dictionary for device name based on VID/PID. If the dict is None, the search happens on USB_DEVICES under mboot/interfaces/usb.py and sdphost/interfaces/usb.py

DESIGN REMARK: this function is not part of the USBLogicalDevice, as the class intention is to be just a simple container. But to help the class to get the required inputs, this helper method has been provided.

Parameters:
  • vid (int) – Vendor ID we are interested in

  • pid (int) – Product ID we are interested in

  • device_names (Optional[Dict[str, Tuple[int, int]]]) – dict where str is device name, first int vid, second int pid

Return type:

List[str]

Returns:

list containing device names with corresponding VID/PID

Module for schema-based configuration validation#

Module for schema-based configuration validation.

class spsdk.utils.schema_validator.CommentedConfig(main_title, schemas, note=None)#

Bases: object

Class for generating commented config templates or custom configurations.

Constructor for Config templates.

Parameters:
  • main_title (str) – Main title of final template.

  • schemas (List[Dict[str, Any]]) – Main description of final template.

  • note (Optional[str]) – Additional Note after title test.

MAX_LINE_LENGTH = 118#
static convert_cm_to_yaml(config)#

Convert Commented Map for into final YAML string.

Parameters:

config (CommentedMap) – Configuration in CM format.

Raises:

SPSDKError – If configuration is empty

Return type:

str

Returns:

YAML string with configuration to use to store in file.

export(config=None)#

Export configuration template into CommentedMap.

Parameters:

config (Optional[Dict[str, Any]]) – Configuration to be applied to template.

Raises:

SPSDKError – Error

Return type:

CommentedMap

Returns:

Configuration template in CM.

get_config(config)#

Export Configuration directly into YAML string format.

Return type:

str

Returns:

YAML string.

static get_property_optional_required(key, block)#

Function to determine if the config property is required or not.

Parameters:
  • key (str) – Name of config record

  • block (Dict[str, Any]) – Source data block

Return type:

PropertyRequired

Returns:

Final description.

get_template()#

Export Configuration template directly into YAML string format.

Return type:

str

Returns:

YAML string.

property max_line: int#

Maximal line with current indent.

class spsdk.utils.schema_validator.PropertyRequired(tag, label, description=None)#

Bases: SpsdkEnum

Enum describing if the property is required or optional.

CONDITIONALLY_REQUIRED = (1, 'CONDITIONALLY_REQUIRED', 'Conditionally required')#
OPTIONAL = (2, 'OPTIONAL', 'Optional')#
REQUIRED = (0, 'REQUIRED', 'Required')#
class spsdk.utils.schema_validator.SPSDKListStrategies(strategy_list)#

Bases: ListStrategies

Extended List Strategies.

static strategy_set(_config, _path, base, nxt)#

Use the set of both as a output.

class spsdk.utils.schema_validator.SPSDKMerger(type_strategies, fallback_strategies, type_conflict_strategies)#

Bases: Merger

Modified Merger to add new list strategy ‘set’.

PROVIDED_TYPE_STRATEGIES = {<class 'list'>: <class 'spsdk.utils.schema_validator.SPSDKListStrategies'>, <class 'dict'>: <class 'deepmerge.strategy.dict.DictStrategies'>, <class 'set'>: <class 'deepmerge.strategy.set.SetStrategies'>}#
spsdk.utils.schema_validator.check_config(config, schemas, extra_formatters=None, search_paths=None)#

Check the configuration by provided list of validation schemas.

Parameters:
  • config (Union[str, Dict[str, Any]]) – Configuration to check

  • schemas (List[Dict[str, Any]]) – List of validation schemas

  • extra_formatters (Optional[Dict[str, Callable[[str], bool]]]) – Additional custom formatters

  • search_paths (Optional[List[str]]) – List of paths where to search for the file, defaults to None

Raises:

SPSDKError – Invalid validation schema or configuration

Return type:

None

spsdk.utils.schema_validator.cmap_update(cmap, updater)#

Update CMap including comments.

Parameters:
  • cmap (CommentedMap) – Original CMap to be updated.

  • updater (CommentedMap) – CMap updater.

Return type:

None

Utils Exceptions#

Module provides exceptions for SPSDK utilities.

exception spsdk.utils.exceptions.SPSDKRegsError(desc=None)#

Bases: SPSDKError

General Error group for utilities SPSDK registers module.

Initialize the base SPSDK Exception.

exception spsdk.utils.exceptions.SPSDKRegsErrorBitfieldNotFound(desc=None)#

Bases: SPSDKRegsError

Bitfield has not been found.

Initialize the base SPSDK Exception.

exception spsdk.utils.exceptions.SPSDKRegsErrorEnumNotFound(desc=None)#

Bases: SPSDKRegsError

Enum has not been found.

Initialize the base SPSDK Exception.

exception spsdk.utils.exceptions.SPSDKRegsErrorRegisterGroupMishmash(desc=None)#

Bases: SPSDKRegsError

Register Group inconsistency problem.

Initialize the base SPSDK Exception.

exception spsdk.utils.exceptions.SPSDKRegsErrorRegisterNotFound(desc=None)#

Bases: SPSDKRegsError

Register has not been found.

Initialize the base SPSDK Exception.

exception spsdk.utils.exceptions.SPSDKTimeoutError#

Bases: TimeoutError, SPSDKError

SPSDK Timeout.

Database#

Module to manage used databases in SPSDK.

class spsdk.utils.database.Database(path)#

Bases: object

Class that helps manage used databases in SPSDK.

Register Configuration class constructor.

Parameters:

path (str) – The path to configuration JSON file.

property devices: Devices#

Get the list of devices stored in the database.

get_defaults(feature)#

Gets feature defaults.

Parameters:

feature (str) – Feature name

Return type:

Dict[str, Any]

Returns:

Dictionary with feature defaults.

get_device_features(device, revision='latest')#

Get device features database.

Parameters:
  • device (str) – The device name.

  • revision (str) – The revision of the silicon.

Raises:

SPSDKValueError – Unsupported feature

Return type:

Features

Returns:

The feature data.

get_devices_with_feature(feature, sub_keys=None)#

Get the list of all device names that supports requested feature.

Parameters:
  • feature (str) – Name of feature

  • sub_keys (Optional[List[str]]) – Optional sub keys to specify the nested dictionaries that feature needs to has to be counted

Return type:

List[str]

Returns:

List of devices that supports requested feature.

get_feature_list(dev_name=None)#

Get features list.

If device is not used, the whole list of SPSDK features is returned

Parameters:

dev_name (Optional[str]) – Device name, defaults to None

Return type:

List[str]

Returns:

List of features.

get_schema_file(feature)#

Get JSON Schema file name for the requested feature.

Parameters:

feature (str) – Requested feature.

Return type:

Dict[str, Any]

Returns:

Loaded dictionary of JSON Schema file.

load_db_cfg_file(filename)#

Return load database config file (JSON/YAML). Use SingleTon behavior.

Parameters:

filename (str) – Path to config file.

Raises:

SPSDKError – Invalid config file.

Return type:

Dict[str, Any]

Returns:

Loaded file in dictionary.

class spsdk.utils.database.DatabaseManager#

Bases: object

Main SPSDK database manager.

Manage SPSDK Database as a singleton class.

Returns:

SPSDK_Database object

AHAB = 'ahab'#
BEE = 'bee'#
BOOTABLE_IMAGE = 'bootable_image'#
CERT_BLOCK = 'cert_block'#
COMM_BUFFER = 'comm_buffer'#
DAT = 'dat'#
DEVHSM = 'devhsm'#
ELE = 'ele'#
FCB = 'fcb'#
HAB = 'hab'#
IEE = 'iee'#
IFR = 'ifr'#
MBI = 'mbi'#
MEMCFG = 'memcfg'#
OTFAD = 'otfad'#
PFR = 'pfr'#
SB21 = 'sb21'#
SB31 = 'sb31'#
SBX = 'sbx'#
SHADOW_REGS = 'shadow_regs'#
SIGNED_MSG = 'signed_msg'#
SIGNING = 'signing'#
TP = 'tp'#
TZ = 'tz'#
WPC = 'wpc'#
XMCD = 'xmcd'#
static clear_cache()#

Clear SPSDK cache.

Return type:

None

property db: Database#

Get Database.

static get_cache_filename()#

Get database cache folder and file name.

Return type:

Tuple[str, str]

Returns:

Tuple of cache path and database file name.

static get_db_hash(path)#

Get the real db hash.

Return type:

bytes

class spsdk.utils.database.Device(name, path, latest_rev, info, device_alias=None, revisions=[])#

Bases: object

Device dataclass represents a single device.

Constructor of SPSDK Device.

Parameters:
  • name (str) – Device name

  • path (str) – Data path

  • latest_rev (str) – latest revision name

  • device_alias (Optional[Device]) – Device alias, defaults to None

  • revisions (Revisions) – Device revisions, defaults to Revisions()

create_file_path(file_name)#

Create File path value for this device.

Parameters:

file_name (str) – File name to be enriched by device path

Return type:

str

Returns:

File path value for the device

property features_list: List[str]#

Get the list of device features.

static load(name, path, defaults, other_devices)#

Loads the device from folder.

Parameters:
  • name (str) – The name of device.

  • path (str) – Device data path.

  • defaults (Dict[str, Any]) – Device data defaults.

  • other_devices (Devices) – Other devices used to allow aliases.

Return type:

Device

Returns:

The Device object.

class spsdk.utils.database.DeviceInfo(purpose, web, memory_map, isp)#

Bases: object

Device information dataclass.

Constructor of device information class.

Parameters:
  • purpose (str) – String description of purpose of MCU (in fact the device group)

  • web (str) – Web page with device info

  • memory_map (Dict[str, Dict[str, Union[int, bool]]]) – Basic memory map of device

  • isp (Dict[str, Any]) – Information regarding ISP mode

static load(config, defaults)#

Loads the device from folder.

Parameters:
  • config (Dict[str, Any]) – The name of device.

  • defaults (Dict[str, Any]) – Device data defaults.

Return type:

DeviceInfo

Returns:

The Device object.

update(config)#

Updates Device info by new configuration.

Parameters:

config (Dict[str, Any]) – The new Device Info configuration

Return type:

None

class spsdk.utils.database.Devices(iterable=(), /)#

Bases: List[Device]

List of devices.

property devices_names: List[str]#

Get the list of devices names.

feature_items(feature, key)#

Iter the whole database for the feature items.

Return type:

Iterator[Tuple[str, str, Any]]

Returns:

Tuple of Device name, revision name and items value.

get(name)#

Return database device structure.

Parameters:

name (str) – String Key with device name.

Raises:

SPSDKErrorMissingDevice – In case the device with given name does not exist

Return type:

Device

Returns:

Dictionary device configuration structure or None:

static load(devices_path, defaults)#

Loads the devices from SPSDK database path.

Parameters:
  • devices_path (str) – Devices data path.

  • defaults (Dict[str, Any]) – Devices defaults data.

Return type:

Devices

Returns:

The Devices object.

class spsdk.utils.database.Features(name, is_latest, device, features)#

Bases: object

Features dataclass represents a single device revision.

Constructor of revision.

Parameters:
  • name (str) – Revision name

  • is_latest (bool) – Mark if this revision is latest.

  • device (Device) – Reference to its device

  • features (Dict[str, Dict[str, Any]]) – Features

check_key(feature, key)#

Check if the key exist in database.

Parameters:
  • feature (str) – Feature name

  • key (Union[List[str], str]) – Item key or key path in list like [‘grp1’, ‘grp2’, ‘key’]

Raises:

SPSDKValueError – Unsupported feature

Return type:

bool

Returns:

True if exist False otherwise

get_bool(feature, key, default=None)#

Get Boolean value.

Parameters:
  • feature (str) – Feature name

  • key (Union[List[str], str]) – Item key or key path in list like [‘grp1’, ‘grp2’, ‘key’]

  • default (Optional[bool]) – Default value in case of missing key

Return type:

bool

Returns:

Boolean value from the feature

get_dict(feature, key, default=None)#

Get Dictionary value.

Parameters:
  • feature (str) – Feature name

  • key (Union[List[str], str]) – Item key or key path in list like [‘grp1’, ‘grp2’, ‘key’]

  • default (Optional[Dict]) – Default value in case of missing key

Return type:

Dict

Returns:

Dictionary value from the feature

get_file_path(feature, key, default=None)#

Get File path value.

Parameters:
  • feature (str) – Feature name

  • key (Union[List[str], str]) – Item key or key path in list like [‘grp1’, ‘grp2’, ‘key’]

  • default (Optional[str]) – Default value in case of missing key

Return type:

str

Returns:

File path value from the feature

get_int(feature, key, default=None)#

Get Integer value.

Parameters:
  • feature (str) – Feature name

  • key (Union[List[str], str]) – Item key or key path in list like [‘grp1’, ‘grp2’, ‘key’]

  • default (Optional[int]) – Default value in case of missing key

Return type:

int

Returns:

Integer value from the feature

get_list(feature, key, default=None)#

Get List value.

Parameters:
  • feature (str) – Feature name

  • key (Union[List[str], str]) – Item key or key path in list like [‘grp1’, ‘grp2’, ‘key’]

  • default (Optional[List]) – Default value in case of missing key

Return type:

List[Any]

Returns:

List value from the feature

get_str(feature, key, default=None)#

Get String value.

Parameters:
  • feature (str) – Feature name

  • key (Union[List[str], str]) – Item key or key path in list like [‘grp1’, ‘grp2’, ‘key’]

  • default (Optional[str]) – Default value in case of missing key

Return type:

str

Returns:

String value from the feature

get_value(feature, key, default=None)#

Get value.

Parameters:
  • feature (str) – Feature name

  • key (Union[List[str], str]) – Item key or key path in list like [‘grp1’, ‘grp2’, ‘key’]

  • default (Optional[Any]) – Default value in case of missing key

Raises:
Return type:

Any

Returns:

Value from the feature

class spsdk.utils.database.Revisions(iterable=(), /)#

Bases: List[Features]

List of device revisions.

get(name=None)#

Get the revision by its name.

If name is not specified, or equal to ‘latest’, then the latest revision is returned.

Parameters:

name (Optional[str]) – The revision name.

Return type:

Features

Returns:

The Revision object.

get_by_name(name)#

Get the required revision.

Parameters:

name (str) – Required revision name

Raises:

SPSDKValueError – Incase of invalid device or revision value.

Return type:

Features

Returns:

The Revision object.

get_latest()#

Get latest revision for device.

Raises:

SPSDKValueError – Incase of there is no latest revision defined.

Return type:

Features

Returns:

The Features object.

revision_names(append_latest=False)#

Get list of revisions.

Parameters:

append_latest (bool) – Add to list also “latest” string

Return type:

List[str]

Returns:

List of all supported device version.

exception spsdk.utils.database.SPSDKErrorMissingDevice(desc=None)#

Bases: SPSDKError

Missing device in database.

Initialize the base SPSDK Exception.

spsdk.utils.database.get_db(device, revision='latest')#

Get device feature database.

Parameters:
  • device (str) – The device name.

  • revision (str) – The revision of the silicon.

Return type:

Features

Returns:

The feature data.

spsdk.utils.database.get_device(device)#

Get device database object.

Parameters:

device (str) – The device name.

Return type:

Device

Returns:

The device data.

spsdk.utils.database.get_families(feature, sub_keys=None)#

Get the list of all family names that supports requested feature.

Parameters:
  • feature (str) – Name of feature

  • sub_keys (Optional[List[str]]) – Optional sub keys to specify the nested dictionaries that feature needs to has to be counted

Return type:

List[str]

Returns:

List of devices that supports requested feature.

spsdk.utils.database.get_schema_file(feature)#

Get JSON Schema file name for the requested feature.

Parameters:

feature (str) – Requested feature.

Return type:

Dict[str, Any]

Returns:

Loaded dictionary of JSON Schema file.

spsdk.utils.database.on_delete()#

Delete method of SPSDK database.

The exit method is used to update cache in case it has been changed.

Return type:

None