Debian Codegraph @

src/nitrokey/trussed/_bootloader/lpc55_upload/mboot/properties.py

raw
1 #!/usr/bin/env python
2 # -*- coding: UTF-8 -*-
3 #
4 # Copyright 2016-2018 Martin Olejar
5 # Copyright 2019-2024 NXP
6 #
7 # SPDX-License-Identifier: BSD-3-Clause
8
9 """Helper module for more human-friendly interpretation of the target device properties."""
10
11 import ctypes
12 from copy import deepcopy
13 from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
14
15 from ..exceptions import SPSDKKeyError
16 from ..mboot.exceptions import McuBootError
17 from ..utils.misc import Endianness
18 from ..utils.spsdk_enum import SpsdkEnum
19 from .commands import CommandTag
20 from .error_codes import StatusCode
21 from .memories import ExtMemPropTags, MemoryRegion
22
23
24 ########################################################################################################################
25 # McuBoot helper functions
26 ########################################################################################################################
27 def size_fmt(value: Union[int, float], kibibyte: bool = True) -> str:
28 """Convert size value into string format.
29
30 :param value: The raw value
31 :param kibibyte: True if 1024 Bytes represent 1kB or False if 1000 Bytes represent 1kB
32 :return: Stringified value
33 """
34 base, suffix = [(1000.0, "B"), (1024.0, "iB")][kibibyte]
35 x = "B"
36 for x in ["B"] + [prefix + suffix for prefix in list("kMGTP")]: # noqa: B007
37 if -base < value < base:
38 break
39 value /= base
40
41 return f"{value} {x}" if x == "B" else f"{value:3.1f} {x}"
42
43
44 ########################################################################################################################
45 # McuBoot helper classes
46 ########################################################################################################################
47
48
49 class Version:
50 """McuBoot current and target version type."""
51
52 def __init__(self, *args: Union[str, int], **kwargs: int) -> None:
53 """Initialize the Version object.
54
55 :raises McuBootError: Argument passed the not str not int
56 """
57 self.mark = kwargs.get("mark", "K")
58 self.major = kwargs.get("major", 0)
59 self.minor = kwargs.get("minor", 0)
60 self.fixation = kwargs.get("fixation", 0)
61 if args:
62 if isinstance(args[0], int):
63 self.from_int(args[0])
64 elif isinstance(args[0], str):
65 self.from_str(args[0])
66 else:
67 raise McuBootError("Value must be 'str' or 'int' type !")
68
69 def __eq__(self, obj: object) -> bool:
70 return isinstance(obj, Version) and vars(obj) == vars(self)
71
72 def __ne__(self, obj: object) -> bool:
73 return not self.__eq__(obj)
74
75 def __lt__(self, obj: "Version") -> bool:
76 return self.to_int(True) < obj.to_int(True)
77
78 def __le__(self, obj: "Version") -> bool:
79 return self.to_int(True) <= obj.to_int(True)
80
81 def __gt__(self, obj: "Version") -> bool:
82 return self.to_int(True) > obj.to_int(True)
83
84 def __ge__(self, obj: "Version") -> bool:
85 return self.to_int(True) >= obj.to_int(True)
86
87 def __repr__(self) -> str:
88 return f"<Version(mark={self.mark}, major={self.major}, minor={self.minor}, fixation={self.fixation})>"
89
90 def __str__(self) -> str:
91 return self.to_str()
92
93 def from_int(self, value: int) -> None:
94 """Parse version data from raw int value.
95
96 :param value: Raw integer input
97 """
98 mark = (value >> 24) & 0xFF
99 self.mark = chr(mark) if 64 < mark < 91 else None # type: ignore
100 self.major = (value >> 16) & 0xFF
101 self.minor = (value >> 8) & 0xFF
102 self.fixation = value & 0xFF
103
104 def from_str(self, value: str) -> None:
105 """Parse version data from string value.
106
107 :param value: String representation input
108 """
109 mark_major, minor, fixation = value.split(".")
110 if len(mark_major) > 1 and mark_major[0] not in "0123456789":
111 self.mark = mark_major[0]
112 self.major = int(mark_major[1:])
113 else:
114 self.major = int(mark_major)
115 self.minor = int(minor)
116 self.fixation = int(fixation)
117
118 def to_int(self, no_mark: bool = False) -> int:
119 """Get version value in raw integer format.
120
121 :param no_mark: If True, return value without mark
122 :return: Integer representation
123 """
124 value = self.major << 16 | self.minor << 8 | self.fixation
125 mark = 0 if no_mark or self.mark is None else ord(self.mark) << 24 # type: ignore
126 return value | mark
127
128 def to_str(self, no_mark: bool = False) -> str:
129 """Get version value in readable string format.
130
131 :param no_mark: If True, return value without mark
132 :return: String representation
133 """
134 value = f"{self.major}.{self.minor}.{self.fixation}"
135 mark = "" if no_mark or self.mark is None else self.mark
136 return f"{mark}{value}"
137
138
139 ########################################################################################################################
140 # McuBoot Properties
141 ########################################################################################################################
142
143
144 # fmt: off
145 class PropertyTag(SpsdkEnum):
146 """McuBoot Properties."""
147
148 LIST_PROPERTIES = (0x00, 'ListProperties', 'List Properties')
149 CURRENT_VERSION = (0x01, "CurrentVersion", "Current Version")
150 AVAILABLE_PERIPHERALS = (0x02, "AvailablePeripherals", "Available Peripherals")
151 FLASH_START_ADDRESS = (0x03, "FlashStartAddress", "Flash Start Address")
152 FLASH_SIZE = (0x04, "FlashSize", "Flash Size")
153 FLASH_SECTOR_SIZE = (0x05, "FlashSectorSize", "Flash Sector Size")
154 FLASH_BLOCK_COUNT = (0x06, "FlashBlockCount", "Flash Block Count")
155 AVAILABLE_COMMANDS = (0x07, "AvailableCommands", "Available Commands")
156 CRC_CHECK_STATUS = (0x08, "CrcCheckStatus", "CRC Check Status")
157 LAST_ERROR = (0x09, "LastError", "Last Error Value")
158 VERIFY_WRITES = (0x0A, "VerifyWrites", "Verify Writes")
159 MAX_PACKET_SIZE = (0x0B, "MaxPacketSize", "Max Packet Size")
160 RESERVED_REGIONS = (0x0C, "ReservedRegions", "Reserved Regions")
161 VALIDATE_REGIONS = (0x0D, "ValidateRegions", "Validate Regions")
162 RAM_START_ADDRESS = (0x0E, "RamStartAddress", "RAM Start Address")
163 RAM_SIZE = (0x0F, "RamSize", "RAM Size")
164 SYSTEM_DEVICE_IDENT = (0x10, "SystemDeviceIdent", "System Device Identification")
165 FLASH_SECURITY_STATE = (0x11, "FlashSecurityState", "Security State")
166 UNIQUE_DEVICE_IDENT = (0x12, "UniqueDeviceIdent", "Unique Device Identification")
167 FLASH_FAC_SUPPORT = (0x13, "FlashFacSupport", "Flash Fac. Support")
168 FLASH_ACCESS_SEGMENT_SIZE = (0x14, "FlashAccessSegmentSize", "Flash Access Segment Size",)
169 FLASH_ACCESS_SEGMENT_COUNT = (0x15, "FlashAccessSegmentCount", "Flash Access Segment Count",)
170 FLASH_READ_MARGIN = (0x16, "FlashReadMargin", "Flash Read Margin")
171 QSPI_INIT_STATUS = (0x17, "QspiInitStatus", "QuadSPI Initialization Status")
172 TARGET_VERSION = (0x18, "TargetVersion", "Target Version")
173 EXTERNAL_MEMORY_ATTRIBUTES = (0x19, "ExternalMemoryAttributes", "External Memory Attributes",)
174 RELIABLE_UPDATE_STATUS = (0x1A, "ReliableUpdateStatus", "Reliable Update Status")
175 FLASH_PAGE_SIZE = (0x1B, "FlashPageSize", "Flash Page Size")
176 IRQ_NOTIFIER_PIN = (0x1C, "IrqNotifierPin", "Irq Notifier Pin")
177 PFR_KEYSTORE_UPDATE_OPT = (0x1D, "PfrKeystoreUpdateOpt", "PFR Keystore Update Opt")
178 BYTE_WRITE_TIMEOUT_MS = (0x1E, "ByteWriteTimeoutMs", "Byte Write Timeout in ms")
179 FUSE_LOCKED_STATUS = (0x1F, "FuseLockedStatus", "Fuse Locked Status")
180 UNKNOWN = (0xFF, "Unknown", "Unknown property")
181
182
183 class PropertyTagKw45xx(SpsdkEnum):
184 """McuBoot Properties."""
185
186 VERIFY_ERASE = (0x0A, "VerifyErase", "Verify Erase")
187 BOOT_STATUS_REGISTER = (0x14, "BootStatusRegister", "Boot Status Register",)
188 FIRMWARE_VERSION = (0x15, "FirmwareVersion", "Firmware Version",)
189 FUSE_PROGRAM_VOLTAGE = (0x16, "FuseProgramVoltage", "Fuse Program Voltage")
190
191
192 class PeripheryTag(SpsdkEnum):
193 """Tags representing peripherals."""
194
195 UART = (0x01, "UART", "UART Interface")
196 I2C_SLAVE = (0x02, "I2C-Slave", "I2C Slave Interface")
197 SPI_SLAVE = (0x04, "SPI-Slave", "SPI Slave Interface")
198 CAN = (0x08, "CAN", "CAN Interface")
199 USB_HID = (0x10, "USB-HID", "USB HID-Class Interface")
200 USB_CDC = (0x20, "USB-CDC", "USB CDC-Class Interface")
201 USB_DFU = (0x40, "USB-DFU", "USB DFU-Class Interface")
202 LIN = (0x80, "LIN", "LIN Interface")
203
204
205 class FlashReadMargin(SpsdkEnum):
206 """Scopes for flash read."""
207
208 NORMAL = (0, "NORMAL")
209 USER = (1, "USER")
210 FACTORY = (2, "FACTORY")
211
212
213 class PfrKeystoreUpdateOpt(SpsdkEnum):
214 """Options for PFR updating."""
215
216 KEY_PROVISIONING = (0, "KEY_PROVISIONING", "KeyProvisioning")
217 WRITE_MEMORY = (1, "WRITE_MEMORY", "WriteMemory")
218 # fmt: on
219
220 ########################################################################################################################
221 # McuBoot Properties Values
222 ########################################################################################################################
223
224
225 class PropertyValueBase:
226 """Base class for property value."""
227
228 __slots__ = ("tag", "name", "desc")
229
230 def __init__(self, tag: int, name: Optional[str] = None, desc: Optional[str] = None) -> None:
231 """Initialize the base of property.
232
233 :param tag: Property tag, see: `PropertyTag`
234 :param name: Optional name for the property
235 :param desc: Optional description for the property
236 """
237 self.tag = tag
238 self.name = name or PropertyTag.get_label(tag) or ""
239 self.desc = desc or PropertyTag.get_description(tag, "")
240
241 def __str__(self) -> str:
242 return f"{self.desc} = {self.to_str()}"
243
244 def to_str(self) -> str:
245 """Stringified representation of a property.
246
247 Derived classes should implement this function.
248
249 :return: String representation
250 :raises NotImplementedError: Derived class has to implement this method
251 """
252 raise NotImplementedError("Derived class has to implement this method.")
253
254
255 class IntValue(PropertyValueBase):
256 """Integer-based value property."""
257
258 __slots__ = ("value", "_fmt")
259
260 def __init__(self, tag: int, raw_values: List[int], str_format: str = "dec") -> None:
261 """Initialize the integer-based property object.
262
263 :param tag: Property tag, see: `PropertyTag`
264 :param raw_values: List of integers representing the property
265 :param str_format: Format to display the value ('dec', 'hex', 'size')
266 """
267 super().__init__(tag)
268 self._fmt = str_format
269 self.value = raw_values[0]
270
271 def to_int(self) -> int:
272 """Get the raw integer property representation."""
273 return self.value
274
275 def to_str(self) -> str:
276 """Get stringified property representation."""
277 if self._fmt == "size":
278 str_value = size_fmt(self.value)
279 elif self._fmt == "hex":
280 str_value = f"0x{self.value:08X}"
281 elif self._fmt == "dec":
282 str_value = str(self.value)
283 elif self._fmt == "int32":
284 str_value = str(ctypes.c_int32(self.value).value)
285 else:
286 str_value = self._fmt.format(self.value)
287 return str_value
288
289
290 class BoolValue(PropertyValueBase):
291 """Boolean-based value property."""
292
293 __slots__ = ("value", "_true_values", "_false_values", "_true_string", "_false_string")
294
295 def __init__(
296 self,
297 tag: int,
298 raw_values: List[int],
299 true_values: Tuple[int] = (1,),
300 true_string: str = "YES",
301 false_values: Tuple[int] = (0,),
302 false_string: str = "NO",
303 ) -> None:
304 """Initialize the Boolean-based property object.
305
306 :param tag: Property tag, see: `PropertyTag`
307 :param raw_values: List of integers representing the property
308 :param true_values: Values representing 'True', defaults to (1,)
309 :param true_string: String representing 'True, defaults to 'YES'
310 :param false_values: Values representing 'False', defaults to (0,)
311 :param false_string: String representing 'False, defaults to 'NO'
312 """
313 super().__init__(tag)
314 self._true_values = true_values
315 self._true_string = true_string
316 self._false_values = false_values
317 self._false_string = false_string
318 self.value = raw_values[0]
319
320 def __bool__(self) -> bool:
321 return self.value in self._true_values
322
323 def to_int(self) -> int:
324 """Get the raw integer portion of the property."""
325 return self.value
326
327 def to_str(self) -> str:
328 """Get stringified property representation."""
329 return self._true_string if self.value in self._true_values else self._false_string
330
331
332 class EnumValue(PropertyValueBase):
333 """Enumeration value property."""
334
335 __slots__ = ("value", "enum", "_na_msg")
336
337 def __init__(
338 self, tag: int, raw_values: List[int], enum: Type[SpsdkEnum], na_msg: str = "Unknown Item"
339 ) -> None:
340 """Initialize the enumeration-based property object.
341
342 :param tag: Property tag, see: `PropertyTag`
343 :param raw_values: List of integers representing the property
344 :param enum: Enumeration to pick from
345 :param na_msg: Message to display if an item is not found in the enum
346 """
347 super().__init__(tag)
348 self._na_msg = na_msg
349 self.enum = enum
350 self.value = raw_values[0]
351
352 def to_int(self) -> int:
353 """Get the raw integer portion of the property."""
354 return self.value
355
356 def to_str(self) -> str:
357 """Get stringified property representation."""
358 try:
359 return self.enum.get_label(self.value)
360 except SPSDKKeyError:
361 return f"{self._na_msg}: {self.value}"
362
363
364 class VersionValue(PropertyValueBase):
365 """Version property class."""
366
367 __slots__ = ("value",)
368
369 def __init__(self, tag: int, raw_values: List[int]) -> None:
370 """Initialize the Version-based property object.
371
372 :param tag: Property tag, see: `PropertyTag`
373 :param raw_values: List of integers representing the property
374 """
375 super().__init__(tag)
376 self.value = Version(raw_values[0])
377
378 def to_int(self) -> int:
379 """Get the raw integer portion of the property."""
380 return self.value.to_int()
381
382 def to_str(self) -> str:
383 """Get stringified property representation."""
384 return self.value.to_str()
385
386
387 class DeviceUidValue(PropertyValueBase):
388 """Device UID value property."""
389
390 __slots__ = ("value",)
391
392 def __init__(self, tag: int, raw_values: List[int]) -> None:
393 """Initialize the Version-based property object.
394
395 :param tag: Property tag, see: `PropertyTag`
396 :param raw_values: List of integers representing the property
397 """
398 super().__init__(tag)
399 self.value = b"".join(
400 [int.to_bytes(val, length=4, byteorder=Endianness.LITTLE.value) for val in raw_values]
401 )
402
403 def to_int(self) -> int:
404 """Get the raw integer portion of the property."""
405 return int.from_bytes(self.value, byteorder=Endianness.BIG.value)
406
407 def to_str(self) -> str:
408 """Get stringified property representation."""
409 return " ".join(f"{item:02X}" for item in self.value)
410
411
412 class ReservedRegionsValue(PropertyValueBase):
413 """Reserver Regions property."""
414
415 __slots__ = ("regions",)
416
417 def __init__(self, tag: int, raw_values: List[int]) -> None:
418 """Initialize the ReserverRegion-based property object.
419
420 :param tag: Property tag, see: `PropertyTag`
421 :param raw_values: List of integers representing the property
422 """
423 super().__init__(tag)
424 self.regions: List[MemoryRegion] = []
425 for i in range(0, len(raw_values), 2):
426 if raw_values[i + 1] == 0:
427 continue
428 self.regions.append(MemoryRegion(raw_values[i], raw_values[i + 1]))
429
430 def __str__(self) -> str:
431 return f"{self.desc} =\n{self.to_str()}"
432
433 def to_str(self) -> str:
434 """Get stringified property representation."""
435 return "\n".join([f" Region {i}: {region}" for i, region in enumerate(self.regions)])
436
437
438 class AvailablePeripheralsValue(PropertyValueBase):
439 """Available Peripherals property."""
440
441 __slots__ = ("value",)
442
443 def __init__(self, tag: int, raw_values: List[int]) -> None:
444 """Initialize the AvailablePeripherals-based property object.
445
446 :param tag: Property tag, see: `PropertyTag`
447 :param raw_values: List of integers representing the property
448 """
449 super().__init__(tag)
450 self.value = raw_values[0]
451
452 def to_int(self) -> int:
453 """Get the raw integer portion of the property."""
454 return self.value
455
456 def to_str(self) -> str:
457 """Get stringified property representation."""
458 return ", ".join(
459 [
460 peripheral_tag.label
461 for peripheral_tag in PeripheryTag
462 if peripheral_tag.tag & self.value
463 ]
464 )
465
466
467 class AvailableCommandsValue(PropertyValueBase):
468 """Available commands property."""
469
470 __slots__ = ("value",)
471
472 @property
473 def tags(self) -> List[int]:
474 """List of tags representing Available commands."""
475 return [
476 cmd_tag.tag
477 for cmd_tag in CommandTag
478 if cmd_tag.tag > 0 and (1 << cmd_tag.tag - 1) & self.value
479 ]
480
481 def __init__(self, tag: int, raw_values: List[int]) -> None:
482 """Initialize the AvailableCommands-based property object.
483
484 :param tag: Property tag, see: `PropertyTag`
485 :param raw_values: List of integers representing the property
486 """
487 super().__init__(tag)
488 self.value = raw_values[0]
489
490 def __contains__(self, item: int) -> bool:
491 return isinstance(item, int) and bool((1 << item - 1) & self.value)
492
493 def to_str(self) -> str:
494 """Get stringified property representation."""
495 return ", ".join(
496 [
497 cmd_tag.label
498 for cmd_tag in CommandTag
499 if cmd_tag.tag > 0 and (1 << cmd_tag.tag - 1) & self.value
500 ]
501 )
502
503
504 class IrqNotifierPinValue(PropertyValueBase):
505 """IRQ notifier pin property."""
506
507 __slots__ = ("value",)
508
509 @property
510 def pin(self) -> int:
511 """Number of the pin used for reporting IRQ."""
512 return self.value & 0xFF
513
514 @property
515 def port(self) -> int:
516 """Number of the port used for reporting IRQ."""
517 return (self.value >> 8) & 0xFF
518
519 @property
520 def enabled(self) -> bool:
521 """Indicates whether IRQ reporting is enabled."""
522 return bool(self.value & (1 << 32))
523
524 def __init__(self, tag: int, raw_values: List[int]) -> None:
525 """Initialize the IrqNotifierPin-based property object.
526
527 :param tag: Property tag, see: `PropertyTag`
528 :param raw_values: List of integers representing the property
529 """
530 super().__init__(tag)
531 self.value = raw_values[0]
532
533 def __bool__(self) -> bool:
534 return self.enabled
535
536 def to_str(self) -> str:
537 """Get stringified property representation."""
538 return (
539 f"IRQ Port[{self.port}], Pin[{self.pin}] is {'enabled' if self.enabled else 'disabled'}"
540 )
541
542
543 class ExternalMemoryAttributesValue(PropertyValueBase):
544 """Attributes for external memories."""
545
546 __slots__ = (
547 "value",
548 "mem_id",
549 "start_address",
550 "total_size",
551 "page_size",
552 "sector_size",
553 "block_size",
554 )
555
556 def __init__(self, tag: int, raw_values: List[int], mem_id: int = 0) -> None:
557 """Initialize the ExternalMemoryAttributes-based property object.
558
559 :param tag: Property tag, see: `PropertyTag`
560 :param raw_values: List of integers representing the property
561 :param mem_id: ID of the external memory
562 """
563 super().__init__(tag)
564 self.mem_id = mem_id
565 self.start_address = (
566 raw_values[1] if raw_values[0] & ExtMemPropTags.START_ADDRESS.tag else None
567 )
568 self.total_size = (
569 raw_values[2] * 1024 if raw_values[0] & ExtMemPropTags.SIZE_IN_KBYTES.tag else None
570 )
571 self.page_size = raw_values[3] if raw_values[0] & ExtMemPropTags.PAGE_SIZE.tag else None
572 self.sector_size = raw_values[4] if raw_values[0] & ExtMemPropTags.SECTOR_SIZE.tag else None
573 self.block_size = raw_values[5] if raw_values[0] & ExtMemPropTags.BLOCK_SIZE.tag else None
574 self.value = raw_values[0]
575
576 def to_str(self) -> str:
577 """Get stringified property representation."""
578 str_values = []
579 if self.start_address is not None:
580 str_values.append(f"Start Address: 0x{self.start_address:08X}")
581 if self.total_size is not None:
582 str_values.append(f"Total Size: {size_fmt(self.total_size)}")
583 if self.page_size is not None:
584 str_values.append(f"Page Size: {size_fmt(self.page_size)}")
585 if self.sector_size is not None:
586 str_values.append(f"Sector Size: {size_fmt(self.sector_size)}")
587 if self.block_size is not None:
588 str_values.append(f"Block Size: {size_fmt(self.block_size)}")
589 return ", ".join(str_values)
590
591
592 class FuseLock:
593 """Fuse Lock."""
594
595 def __init__(self, index: int, locked: bool) -> None:
596 """Initialize object representing information about fuse lock.
597
598 :param index: value of OTP index
599 :param locked: status of the lock, true if locked
600 """
601 self.index = index
602 self.locked = locked
603
604 def __str__(self) -> str:
605 status = "LOCKED" if self.locked else "UNLOCKED"
606 return f" FUSE{(self.index):03d}: {status}\r\n"
607
608
609 class FuseLockRegister:
610 """Fuse Lock Register."""
611
612 def __init__(self, value: int, index: int, start: int = 0) -> None:
613 """Initialize object representing the OTP Controller Program Locked Status.
614
615 :param value: value of the register
616 :param index: index of the fuse
617 :param start: shift to the start of the register
618
619 """
620 self.value = value
621 self.index = index
622 self.msg = ""
623 self.bitfields: List[FuseLock] = []
624
625 shift = 0
626 for _ in range(start, 32):
627 locked = (value >> shift) & 1
628 self.bitfields.append(FuseLock(index + shift, bool(locked)))
629 shift += 1
630
631 def __str__(self) -> str:
632 """Get stringified property representation."""
633 if self.bitfields:
634 for bitfield in self.bitfields:
635 self.msg += str(bitfield)
636 return f"\r\n{self.msg}"
637
638
639 class FuseLockedStatus(PropertyValueBase):
640 """Class representing FuseLocked registers."""
641
642 __slots__ = ("fuses",)
643
644 def __init__(self, tag: int, raw_values: List[int]) -> None:
645 """Initialize the FuseLockedStatus property object.
646
647 :param tag: Property tag, see: `PropertyTag`
648 :param raw_values: List of integers representing the property
649 """
650 super().__init__(tag)
651 self.fuses: List[FuseLockRegister] = []
652 idx = 0
653 for count, val in enumerate(raw_values):
654 start = 0
655 if count == 0:
656 start = 16
657 self.fuses.append(FuseLockRegister(val, idx, start))
658 idx += 32
659 if count == 0:
660 idx -= 16
661
662 def to_str(self) -> str:
663 """Get stringified property representation."""
664 msg = "\r\n"
665 for count, register in enumerate(self.fuses):
666 msg += f"OTP Controller Program Locked Status {count} Register: {register}"
667 return msg
668
669 def get_fuses(self) -> List[FuseLock]:
670 """Get list of fuses bitfield objects.
671
672 :return: list of FuseLockBitfield objects
673 """
674 fuses = []
675 for registers in self.fuses:
676 fuses.extend(registers.bitfields)
677 return fuses
678
679
680 ########################################################################################################################
681 # McuBoot property response parser
682 ########################################################################################################################
683
684 PROPERTIES: Dict[PropertyTag, Dict[Any, Any]] = {
685 PropertyTag.CURRENT_VERSION: {"class": VersionValue, "kwargs": {}},
686 PropertyTag.AVAILABLE_PERIPHERALS: {"class": AvailablePeripheralsValue, "kwargs": {}},
687 PropertyTag.FLASH_START_ADDRESS: {"class": IntValue, "kwargs": {"str_format": "hex"}},
688 PropertyTag.FLASH_SIZE: {"class": IntValue, "kwargs": {"str_format": "size"}},
689 PropertyTag.FLASH_SECTOR_SIZE: {"class": IntValue, "kwargs": {"str_format": "size"}},
690 PropertyTag.FLASH_BLOCK_COUNT: {"class": IntValue, "kwargs": {"str_format": "dec"}},
691 PropertyTag.AVAILABLE_COMMANDS: {"class": AvailableCommandsValue, "kwargs": {}},
692 PropertyTag.CRC_CHECK_STATUS: {
693 "class": EnumValue,
694 "kwargs": {"enum": StatusCode, "na_msg": "Unknown CRC Status code"},
695 },
696 PropertyTag.VERIFY_WRITES: {
697 "class": BoolValue,
698 "kwargs": {"true_string": "ON", "false_string": "OFF"},
699 },
700 PropertyTag.LAST_ERROR: {
701 "class": EnumValue,
702 "kwargs": {"enum": StatusCode, "na_msg": "Unknown Error"},
703 },
704 PropertyTag.MAX_PACKET_SIZE: {"class": IntValue, "kwargs": {"str_format": "size"}},
705 PropertyTag.RESERVED_REGIONS: {"class": ReservedRegionsValue, "kwargs": {}},
706 PropertyTag.VALIDATE_REGIONS: {
707 "class": BoolValue,
708 "kwargs": {"true_string": "ON", "false_string": "OFF"},
709 },
710 PropertyTag.RAM_START_ADDRESS: {"class": IntValue, "kwargs": {"str_format": "hex"}},
711 PropertyTag.RAM_SIZE: {"class": IntValue, "kwargs": {"str_format": "size"}},
712 PropertyTag.SYSTEM_DEVICE_IDENT: {"class": IntValue, "kwargs": {"str_format": "hex"}},
713 PropertyTag.FLASH_SECURITY_STATE: {
714 "class": BoolValue,
715 "kwargs": {
716 "true_values": (0x00000000, 0x5AA55AA5),
717 "true_string": "UNSECURE",
718 "false_values": (0x00000001, 0xC33CC33C),
719 "false_string": "SECURE",
720 },
721 },
722 PropertyTag.UNIQUE_DEVICE_IDENT: {"class": DeviceUidValue, "kwargs": {}},
723 PropertyTag.FLASH_FAC_SUPPORT: {
724 "class": BoolValue,
725 "kwargs": {"true_string": "ON", "false_string": "OFF"},
726 },
727 PropertyTag.FLASH_ACCESS_SEGMENT_SIZE: {"class": IntValue, "kwargs": {"str_format": "size"}},
728 PropertyTag.FLASH_ACCESS_SEGMENT_COUNT: {"class": IntValue, "kwargs": {"str_format": "int32"}},
729 PropertyTag.FLASH_READ_MARGIN: {
730 "class": EnumValue,
731 "kwargs": {"enum": FlashReadMargin, "na_msg": "Unknown Margin"},
732 },
733 PropertyTag.QSPI_INIT_STATUS: {
734 "class": EnumValue,
735 "kwargs": {"enum": StatusCode, "na_msg": "Unknown Error"},
736 },
737 PropertyTag.TARGET_VERSION: {"class": VersionValue, "kwargs": {}},
738 PropertyTag.EXTERNAL_MEMORY_ATTRIBUTES: {
739 "class": ExternalMemoryAttributesValue,
740 "kwargs": {"mem_id": None},
741 },
742 PropertyTag.RELIABLE_UPDATE_STATUS: {
743 "class": EnumValue,
744 "kwargs": {"enum": StatusCode, "na_msg": "Unknown Error"},
745 },
746 PropertyTag.FLASH_PAGE_SIZE: {"class": IntValue, "kwargs": {"str_format": "size"}},
747 PropertyTag.IRQ_NOTIFIER_PIN: {"class": IrqNotifierPinValue, "kwargs": {}},
748 PropertyTag.PFR_KEYSTORE_UPDATE_OPT: {
749 "class": EnumValue,
750 "kwargs": {"enum": PfrKeystoreUpdateOpt, "na_msg": "Unknown"},
751 },
752 PropertyTag.BYTE_WRITE_TIMEOUT_MS: {"class": IntValue, "kwargs": {"str_format": "dec"}},
753 PropertyTag.FUSE_LOCKED_STATUS: {"class": FuseLockedStatus, "kwargs": {}},
754 }
755
756 PROPERTIES_KW45XX = {
757 PropertyTagKw45xx.VERIFY_ERASE: {
758 "class": BoolValue,
759 "kwargs": {"true_string": "ENABLE", "false_string": "DISABLE"},
760 },
761 PropertyTagKw45xx.BOOT_STATUS_REGISTER: {"class": IntValue, "kwargs": {"str_format": "int32"}},
762 PropertyTagKw45xx.FIRMWARE_VERSION: {"class": IntValue, "kwargs": {"str_format": "int32"}},
763 PropertyTagKw45xx.FUSE_PROGRAM_VOLTAGE: {
764 "class": BoolValue,
765 "kwargs": {
766 "true_string": "Over Drive Voltage (2.5 V)",
767 "false_string": "Normal Voltage (1.8 V)",
768 },
769 },
770 }
771
772 PROPERTIES_OVERRIDE = {"kw45xx": PROPERTIES_KW45XX, "k32w1xx": PROPERTIES_KW45XX}
773 PROPERTY_TAG_OVERRIDE = {"kw45xx": PropertyTagKw45xx, "k32w1xx": PropertyTagKw45xx}
774
775
776 def parse_property_value(
777 property_tag: int,
778 raw_values: List[int],
779 ext_mem_id: Optional[int] = None,
780 family: Optional[str] = None,
781 ) -> Optional[PropertyValueBase]:
782 """Parse the property value received from the device.
783
784 :param property_tag: Tag representing the property
785 :param raw_values: Data received from the device
786 :param ext_mem_id: ID of the external memory used to read the property, defaults to None
787 :param family: supported family
788 :return: Object representing the property
789 """
790 assert isinstance(property_tag, int)
791 assert isinstance(raw_values, list)
792 properties_dict = deepcopy(PROPERTIES)
793 if family:
794 properties_dict.update(PROPERTIES_OVERRIDE[family]) # type: ignore
795 if property_tag not in list(properties_dict.keys()):
796 return None
797 property_value = next(
798 value for key, value in properties_dict.items() if key.tag == property_tag
799 )
800 cls: Callable = property_value["class"] # type: ignore[type-arg]
801 kwargs: dict[str, Any] = property_value["kwargs"]
802 if "mem_id" in kwargs:
803 kwargs["mem_id"] = ext_mem_id
804 obj = cls(property_tag, raw_values, **kwargs)
805 if family:
806 property_tag_override = PROPERTY_TAG_OVERRIDE[family].from_tag(property_tag)
807 obj.name = property_tag_override.label
808 obj.desc = property_tag_override.description
809 assert isinstance(obj, PropertyValueBase)
810 return obj