Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/utils/misc.py

raw
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 # Copyright 2020-2024 NXP
4 #
5 # SPDX-License-Identifier: BSD-3-Clause
6
7 """Miscellaneous functions used throughout the SPSDK."""
8
9 import re
10 from enum import Enum
11 from math import ceil
12 from secrets import token_bytes
13 from typing import List, Optional, Union
14
15 from ..exceptions import SPSDKError, SPSDKValueError
16
17
18 class Endianness(str, Enum):
19 """Endianness enum."""
20
21 BIG = "big"
22 LITTLE = "little"
23
24 @classmethod
25 def values(cls) -> List[str]:
26 """Get enumeration values."""
27 return [mem.value for mem in Endianness.__members__.values()]
28
29
30 class BinaryPattern:
31 """Binary pattern class.
32
33 Supported patterns:
34 - rand: Random Pattern
35 - zeros: Filled with zeros
36 - ones: Filled with all ones
37 - inc: Filled with repeated numbers incremented by one 0-0xff
38 - any kind of number, that will be repeated to fill up whole image.
39 The format could be decimal, hexadecimal, bytes.
40 """
41
42 SPECIAL_PATTERNS = ["rand", "zeros", "ones", "inc"]
43
44 def __init__(self, pattern: str) -> None:
45 """Constructor of pattern class.
46
47 :param pattern: Supported patterns:
48 - rand: Random Pattern
49 - zeros: Filled with zeros
50 - ones: Filled with all ones
51 - inc: Filled with repeated numbers incremented by one 0-0xff
52 - any kind of number, that will be repeated to fill up whole image.
53 The format could be decimal, hexadecimal, bytes.
54 :raises SPSDKValueError: Unsupported pattern detected.
55 """
56 try:
57 value_to_int(pattern)
58 except SPSDKError as e:
59 if pattern not in BinaryPattern.SPECIAL_PATTERNS:
60 raise SPSDKValueError( # pylint: disable=raise-missing-from
61 f"Unsupported input pattern {pattern}"
62 ) from e
63
64 self._pattern = pattern
65
66 def get_block(self, size: int) -> bytes:
67 """Get block filled with pattern.
68
69 :param size: Size of block to return.
70 :return: Filled up block with specified pattern.
71 """
72 if self._pattern == "zeros":
73 return bytes(size)
74
75 if self._pattern == "ones":
76 return bytes(b"\xff" * size)
77
78 if self._pattern == "rand":
79 return token_bytes(size)
80
81 if self._pattern == "inc":
82 return bytes((x & 0xFF for x in range(size)))
83
84 pattern = value_to_bytes(self._pattern, align_to_2n=False)
85 block = bytes(pattern * (int((size / len(pattern))) + 1))
86 return block[:size]
87
88 @property
89 def pattern(self) -> str:
90 """Get the pattern.
91
92 :return: Pattern in string representation.
93 """
94 try:
95 return hex(value_to_int(self._pattern))
96 except SPSDKError:
97 return self._pattern
98
99
100 def align(number: int, alignment: int = 4) -> int:
101 """Align number (size or address) size to specified alignment, typically 4, 8 or 16 bytes boundary.
102
103 :param number: input to be aligned
104 :param alignment: the boundary to align; typical value is power of 2
105 :return: aligned number; result is always >= size (e.g. aligned up)
106 :raises SPSDKError: When there is wrong alignment
107 """
108 if alignment <= 0 or number < 0:
109 raise SPSDKError("Wrong alignment")
110
111 return (number + (alignment - 1)) // alignment * alignment
112
113
114 def align_block(
115 data: Union[bytes, bytearray],
116 alignment: int = 4,
117 padding: Optional[Union[int, str, BinaryPattern]] = None,
118 ) -> bytes:
119 """Align binary data block length to specified boundary by adding padding bytes to the end.
120
121 :param data: to be aligned
122 :param alignment: boundary alignment (typically 2, 4, 16, 64 or 256 boundary)
123 :param padding: byte to be added or BinaryPattern
124 :return: aligned block
125 :raises SPSDKError: When there is wrong alignment
126 """
127 assert isinstance(data, (bytes, bytearray))
128
129 if alignment < 0:
130 raise SPSDKError("Wrong alignment")
131 current_size = len(data)
132 num_padding = align(current_size, alignment) - current_size
133 if not num_padding:
134 return bytes(data)
135 if not padding:
136 padding = BinaryPattern("zeros")
137 elif not isinstance(padding, BinaryPattern):
138 padding = BinaryPattern(str(padding))
139 return bytes(data + padding.get_block(num_padding))
140
141
142 def align_block_fill_random(data: bytes, alignment: int = 4) -> bytes:
143 """Same as `align_block`, just parameter `padding` is fixed to `-1` to fill with random data."""
144 return align_block(data, alignment, BinaryPattern("rand"))
145
146
147 def get_bytes_cnt_of_int(
148 value: int, align_to_2n: bool = True, byte_cnt: Optional[int] = None
149 ) -> int:
150 """Returns count of bytes needed to store handled integer.
151
152 :param value: Input integer value.
153 :param align_to_2n: The result will be aligned to standard sizes 1,2,4,8,12,16,20.
154 :param byte_cnt: The result count of bytes.
155 :raises SPSDKValueError: The integer input value doesn't fit into byte_cnt.
156 :return: Number of bytes needed to store integer.
157 """
158 cnt = 0
159 if value == 0:
160 return byte_cnt or 1
161
162 while value != 0:
163 value >>= 8
164 cnt += 1
165
166 if align_to_2n and cnt > 2:
167 cnt = int(ceil(cnt / 4)) * 4
168
169 if byte_cnt and cnt > byte_cnt:
170 raise SPSDKValueError(
171 f"Value takes more bytes than required byte count {byte_cnt} after align."
172 )
173
174 cnt = byte_cnt or cnt
175
176 return cnt
177
178
179 def value_to_int(value: Union[bytes, bytearray, int, str], default: Optional[int] = None) -> int:
180 """Function loads value from lot of formats to integer.
181
182 :param value: Input value.
183 :param default: Default Value in case of invalid input.
184 :return: Value in Integer.
185 :raises SPSDKError: Unsupported input type.
186 """
187 if isinstance(value, int):
188 return value
189
190 if isinstance(value, (bytes, bytearray)):
191 return int.from_bytes(value, Endianness.BIG.value)
192
193 if isinstance(value, str) and value != "":
194 match = re.match(
195 r"(?P<prefix>0[box])?(?P<number>[0-9a-f_]+)(?P<suffix>[ul]{0,3})$",
196 value.strip().lower(),
197 )
198 if match:
199 base = {"0b": 2, "0o": 8, "0": 10, "0x": 16, None: 10}[match.group("prefix")]
200 try:
201 return int(match.group("number"), base=base)
202 except ValueError:
203 pass
204
205 if default is not None:
206 return default
207 raise SPSDKError(f"Invalid input number type({type(value)}) with value ({value})")
208
209
210 def value_to_bytes(
211 value: Union[bytes, bytearray, int, str],
212 align_to_2n: bool = True,
213 byte_cnt: Optional[int] = None,
214 endianness: Endianness = Endianness.BIG,
215 ) -> bytes:
216 """Function loads value from lot of formats.
217
218 :param value: Input value.
219 :param align_to_2n: When is set, the function aligns length of return array to 1,2,4,8,12 etc.
220 :param byte_cnt: The result count of bytes.
221 :param endianness: The result bytes endianness ['big', 'little'].
222 :return: Value in bytes.
223 """
224 if isinstance(value, bytes):
225 return value
226
227 if isinstance(value, bytearray):
228 return bytes(value)
229
230 value = value_to_int(value)
231 return value.to_bytes(
232 get_bytes_cnt_of_int(value, align_to_2n, byte_cnt=byte_cnt), endianness.value
233 )
234
235
236 def size_fmt(num: Union[float, int], use_kibibyte: bool = True) -> str:
237 """Size format."""
238 base, suffix = [(1000.0, "B"), (1024.0, "iB")][use_kibibyte]
239 i = "B"
240 for i in ["B"] + [i + suffix for i in list("kMGTP")]: # noqa: B007
241 if num < base:
242 break
243 num /= base
244
245 return f"{int(num)} {i}" if i == "B" else f"{num:3.1f} {i}"
246
247
248 def swap16(x: int) -> int:
249 """Swap bytes in half word (16bit).
250
251 :param x: Original number
252 :return: Number with swapped bytes
253 :raises SPSDKError: When incorrect number to be swapped is provided
254 """
255 if x < 0 or x > 0xFFFF:
256 raise SPSDKError("Incorrect number to be swapped")
257 return ((x << 8) & 0xFF00) | ((x >> 8) & 0x00FF)