psptool 3.6__tar.gz → 3.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {psptool-3.6 → psptool-3.7}/.github/workflows/python-tests.yml +2 -0
  2. {psptool-3.6 → psptool-3.7}/PKG-INFO +2 -2
  3. {psptool-3.6 → psptool-3.7}/psptool/blob.py +42 -13
  4. {psptool-3.6 → psptool-3.7}/psptool/directory.py +44 -13
  5. {psptool-3.6 → psptool-3.7}/psptool/entry.py +5 -0
  6. {psptool-3.6 → psptool-3.7}/psptool/header_file.py +4 -0
  7. {psptool-3.6 → psptool-3.7}/psptool/key_store_file.py +13 -8
  8. {psptool-3.6 → psptool-3.7}/psptool/psptool.py +40 -0
  9. psptool-3.7/tests/unit/synthetic_rom.py +122 -0
  10. psptool-3.7/tests/unit/test_key_store_file.py +91 -0
  11. psptool-3.7/tests/unit/test_rom_layouts.py +189 -0
  12. psptool-3.7/tests/unit/test_zen_generation_backfill.py +79 -0
  13. {psptool-3.6 → psptool-3.7}/.github/workflows/publish.yml +0 -0
  14. {psptool-3.6 → psptool-3.7}/.gitignore +0 -0
  15. {psptool-3.6 → psptool-3.7}/.gitmodules +0 -0
  16. {psptool-3.6 → psptool-3.7}/LICENSE +0 -0
  17. {psptool-3.6 → psptool-3.7}/README.md +0 -0
  18. {psptool-3.6 → psptool-3.7}/psptool/__init__.py +0 -0
  19. {psptool-3.6 → psptool-3.7}/psptool/__main__.py +0 -0
  20. {psptool-3.6 → psptool-3.7}/psptool/cert_tree.py +0 -0
  21. {psptool-3.6 → psptool-3.7}/psptool/crypto.py +0 -0
  22. {psptool-3.6 → psptool-3.7}/psptool/errors.py +0 -0
  23. {psptool-3.6 → psptool-3.7}/psptool/fet.py +0 -0
  24. {psptool-3.6 → psptool-3.7}/psptool/file.py +0 -0
  25. {psptool-3.6 → psptool-3.7}/psptool/firmware.py +0 -0
  26. {psptool-3.6 → psptool-3.7}/psptool/microcode_file.py +0 -0
  27. {psptool-3.6 → psptool-3.7}/psptool/pubkey_file.py +0 -0
  28. {psptool-3.6 → psptool-3.7}/psptool/rom.py +0 -0
  29. {psptool-3.6 → psptool-3.7}/psptool/utils.py +0 -0
  30. {psptool-3.6 → psptool-3.7}/pyproject.toml +0 -0
  31. {psptool-3.6 → psptool-3.7}/tests/__init__.py +0 -0
  32. {psptool-3.6 → psptool-3.7}/tests/create_metrics.sh +0 -0
  33. {psptool-3.6 → psptool-3.7}/tests/gha_metrics.py +0 -0
  34. {psptool-3.6 → psptool-3.7}/tests/integration/__init__.py +0 -0
  35. {psptool-3.6 → psptool-3.7}/tests/integration/test_psptrace.py +0 -0
  36. {psptool-3.6 → psptool-3.7}/tests/integration/test_rom_files.py +0 -0
  37. {psptool-3.6 → psptool-3.7}/tests/metrics.txt +0 -0
  38. {psptool-3.6 → psptool-3.7}/tests/unit/__init__.py +0 -0
  39. {psptool-3.6 → psptool-3.7}/tests/unit/test_cli.py +0 -0
@@ -36,6 +36,7 @@ jobs:
36
36
  uses: actions/checkout@v6
37
37
  with:
38
38
  ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || github.sha }}
39
+ allow-unsafe-pr-checkout: true
39
40
 
40
41
  - name: Download fixtures
41
42
  uses: actions/download-artifact@v8
@@ -76,6 +77,7 @@ jobs:
76
77
  uses: actions/checkout@v6
77
78
  with:
78
79
  ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || github.sha }}
80
+ allow-unsafe-pr-checkout: true
79
81
 
80
82
  - name: Download fixtures
81
83
  uses: actions/download-artifact@v8
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: psptool
3
- Version: 3.6
3
+ Version: 3.7
4
4
  Summary: PSPTool is a tool for dealing with AMD binary blobs
5
5
  Author-email: Christian Werling <cwerling@posteo.de>
6
6
  License-File: LICENSE
@@ -30,6 +30,25 @@ class Blob(NestedBuffer):
30
30
  _FIRMWARE_ENTRY_MAGIC = b'\xAA\x55\xAA\x55'
31
31
  # All structures per Rom must be in 16MB windows
32
32
  _MAX_PAGE_SIZE = 16 * 1024 * 1024
33
+ # Assumed only when a file entry points past the ROM size taken from the
34
+ # input size, so a 32 MB ROM inside a bigger file keeps its size
35
+ _BIG_ROM_SIZE = 64 * 1024 * 1024
36
+
37
+ # ROM-relative offsets at which a FET may legitimately appear, in the
38
+ # try-order used by the parser (the loop breaks on first successful
39
+ # FET parse, so order is observable). As seen by a PSPTrace Zen 1
40
+ # boot. The first entry is the canonical position for compact images
41
+ # and is what the synthetic-fixture builder targets via [0].
42
+ POSSIBLE_FET_OFFSETS = (
43
+ 0x020000,
44
+ 0xfa0000,
45
+ 0xf20000,
46
+ 0xe20000,
47
+ 0xc20000,
48
+ 0x820000,
49
+ 0x120000,
50
+ )
51
+
33
52
  class NoFirmwareEntryTableError(Exception):
34
53
  pass
35
54
 
@@ -39,25 +58,15 @@ class Blob(NestedBuffer):
39
58
  self.psptool = psptool
40
59
  self.roms: List[Rom] = []
41
60
 
42
- possible_fet_offsets = [
43
- # as seen by a PSPTrace Zen 1 boot
44
- 0x020000,
45
- 0xfa0000,
46
- 0xf20000,
47
- 0xe20000,
48
- 0xc20000,
49
- 0x820000,
50
- ]
51
-
52
61
  possible_rom_sizes = [32, 16, 8]
53
62
  _rom_size = max(value for value in possible_rom_sizes if value * 1024 * 1024 <= self.buffer_size)
54
63
  rom_size = _rom_size * 1024 * 1024
55
64
  self.psptool.ph.print_warning(f"Input file is {self.buffer_size:#x}, will assume ROM size of {_rom_size}M")
56
65
 
57
- # For each FET, we try to create a 16MB ROM starting at `FET - offset`
66
+ # For each FET, we try to create a ROM starting at `FET - offset`
58
67
  for fet_location in self._find_fets():
59
68
  fet_parsed = False
60
- for fet_offset in possible_fet_offsets:
69
+ for fet_offset in self.POSSIBLE_FET_OFFSETS:
61
70
  if fet_location < fet_offset:
62
71
  # would lead to Blob underflow
63
72
  continue
@@ -69,7 +78,7 @@ class Blob(NestedBuffer):
69
78
  rom_offset = fet_location - fet_offset # e.g. 0x20800 - 0x20000 = 0x0800
70
79
  # W/A for images with single ROMs that have entries crossing 16MB boundary
71
80
  if rom_page == 0:
72
- potential_rom = Rom(self, rom_size, rom_offset, fet_offset, psptool)
81
+ potential_rom = self._create_first_page_rom(rom_size, rom_offset, fet_offset)
73
82
  else:
74
83
  potential_rom = Rom(self, min(rom_size, self._MAX_PAGE_SIZE), rom_offset, fet_offset, psptool)
75
84
  self.roms.append(potential_rom)
@@ -89,6 +98,26 @@ class Blob(NestedBuffer):
89
98
  def __repr__(self):
90
99
  return f'Blob({self.roms=})'
91
100
 
101
+ def _create_first_page_rom(self, rom_size, rom_offset, fet_offset):
102
+ psptool = self.psptool
103
+ directories = dict(psptool.directories_by_offset)
104
+ files = dict(psptool.files_by_offset)
105
+ references = {file: len(file.references) for file in files.values()}
106
+ try:
107
+ return Rom(self, rom_size, rom_offset, fet_offset, psptool)
108
+ except AssertionError as e:
109
+ if 'overflows ROM bounds' not in str(e) or rom_offset + self._BIG_ROM_SIZE > self.buffer_size:
110
+ raise
111
+
112
+ # Drop what the failed attempt registered before parsing again
113
+ psptool.directories_by_offset = directories
114
+ psptool.files_by_offset = files
115
+ for file, count in references.items():
116
+ del file.references[count:]
117
+ psptool.ph.print_warning(f"File offset past {rom_size >> 20}M, will assume ROM size of "
118
+ f"{self._BIG_ROM_SIZE >> 20}M")
119
+ return Rom(self, self._BIG_ROM_SIZE, rom_offset, fet_offset, psptool)
120
+
92
121
  def _construct_range_dict(self):
93
122
  all_files = self.unique_files()
94
123
 
@@ -38,6 +38,22 @@ class Directory(NestedBuffer):
38
38
  'Zen 4/5': [b'\x03\x0D\xBC']
39
39
  }
40
40
 
41
+ # Empirical mapping from PSP_FW_BOOT_LOADER (entry type 0x01) version
42
+ # major byte to Zen generation. Used as a third detection path for
43
+ # single-generation ROMs (e.g. EPYC server BIOSes) that have neither a
44
+ # 2PSP combo directory nor a tertiary self-tag and so hit neither of the
45
+ # existing zen_generation paths. Source for the majors below: the
46
+ # Test-PSPTool corpus and its bootloader_overview.py table, plus the
47
+ # original issue's empirical scrape across 37 EPYC ROMs.
48
+ BOOTLOADER_VERSION_TO_ZEN = {
49
+ 0x07: 'Zen 1', # Naples server (NaplesPI-SP3): H11DSI, MZ31-AR, S8026
50
+ 0x09: 'Zen 1', 0x0A: 'Zen 1', # Naples / Raven Ridge consumer
51
+ 0x0B: 'Zen 2', 0x0C: 'Zen 2', # Rome
52
+ 0x13: 'Zen 3', # Milan
53
+ 0x29: 'Zen 4', # Genoa, Siena (Zen 4c shares the major)
54
+ 0x3D: 'Zen 5', # Turin (Bergamo also lands here per the issue)
55
+ }
56
+
41
57
  @classmethod
42
58
  def get_possible_zen_generation(cls, zen_generation_id):
43
59
  zen_generation = 'unknown'
@@ -73,9 +89,9 @@ class Directory(NestedBuffer):
73
89
  if "Empty entry" in str(e):
74
90
  fet.psptool.ph.print_warning(f"Skipping empty directory entry at offset 0x{offset:x}")
75
91
  return []
76
- else:
77
- # Re-raise other parse errors
78
- raise
92
+ # Some slot headers point at other data, such as an APCB
93
+ fet.psptool.ph.print_warning(f"Skipping non-directory at offset 0x{offset:x}")
94
+ return []
79
95
 
80
96
  # 2. Recursively add secondary directories referenced by the just created directory, if applicable
81
97
  for secondary_directory_offset in directory.secondary_directory_offsets:
@@ -85,17 +101,26 @@ class Directory(NestedBuffer):
85
101
  # 3. Recursively add tertiary directories (double references introduced in Zen 4), if applicable
86
102
  for tertiary_directory_offset in directory.tertiary_directory_offsets:
87
103
  directory_body = fet.rom.get_bytes(tertiary_directory_offset, 32)
104
+
105
+ # Some ROMs point straight at the L2 directory instead of at a
106
+ # header holding its offset, so there is nothing to resolve
107
+ if directory_body[:4] in cls.DIRECTORY_MAGICS + BiosDirectory.DIRECTORY_MAGICS:
108
+ created_directories += cls.create_directories_if_not_exist(
109
+ tertiary_directory_offset, fet, zen_generation)
110
+ continue
111
+
88
112
  actual_tertiary_offset = int.from_bytes(directory_body[16:20], 'little')
89
113
  zen_generation_id = directory_body[21:24]
90
- zen_generation = cls.get_possible_zen_generation(zen_generation_id)
91
- if zen_generation == 'unknown':
114
+ tertiary_zen_generation = cls.get_possible_zen_generation(zen_generation_id)
115
+ if tertiary_zen_generation == 'unknown':
92
116
  fet.psptool.ph.print_warning(f"Unknown {zen_generation_id=}")
93
117
 
94
118
  zen_generation_id = hex(int.from_bytes(directory_body[20:24], 'little'))
95
- zen_generation += f' (PSP ID {zen_generation_id})'
119
+ tertiary_zen_generation += f' (PSP ID {zen_generation_id})'
96
120
 
97
121
  # Resolve one more indirection
98
- tertiary_directories = cls.create_directories_if_not_exist(actual_tertiary_offset, fet, zen_generation)
122
+ tertiary_directories = cls.create_directories_if_not_exist(
123
+ actual_tertiary_offset, fet, tertiary_zen_generation)
99
124
  created_directories += tertiary_directories
100
125
 
101
126
  return created_directories
@@ -241,12 +266,18 @@ class Directory(NestedBuffer):
241
266
  self.update_checksum()
242
267
 
243
268
  def update_zen_generation(self, fet, zen_generation):
244
- if zen_generation is not None:
245
- if zen_generation not in self.zen_generation:
246
- self.zen_generation += '\n' + zen_generation
247
- for offset in self.secondary_directory_offsets:
248
- dir = fet.psptool.directories_by_offset[offset]
249
- dir.update_zen_generation(fet, zen_generation)
269
+ if zen_generation is None:
270
+ return
271
+ # A directory first reached without a generation takes the new one
272
+ if self.zen_generation is None:
273
+ self.zen_generation = zen_generation
274
+ elif zen_generation not in self.zen_generation:
275
+ self.zen_generation += '\n' + zen_generation
276
+ else:
277
+ return
278
+ for offset in self.secondary_directory_offsets:
279
+ dir = fet.psptool.directories_by_offset[offset]
280
+ dir.update_zen_generation(fet, zen_generation)
250
281
 
251
282
 
252
283
  class BiosDirectory(Directory):
@@ -46,6 +46,11 @@ class DirectoryEntry(NestedBuffer):
46
46
  # entry address mode must be taken into account, otherwise ignored.
47
47
  if addr_mode == 2 or addr_mode == 3:
48
48
  addr_mode = self.address_mode
49
+ # coreboot's amdfwtool writes APOB NV entries on older SoCs as an x86
50
+ # physical address (entry address mode 0) in a mode 1 directory. No
51
+ # flash offset reaches 0xff000000.
52
+ elif addr_mode == 1 and self.address_mode == 0 and self.offset >= 0xFF000000:
53
+ addr_mode = 0
49
54
 
50
55
  if addr_mode == 0:
51
56
  # x86 physical address, should be in range 0xff000000 - 0xffffffff
@@ -63,6 +63,10 @@ class HeaderFile(File):
63
63
  if self.has_sha256_checksum and self.has_sha384_checksum:
64
64
  raise File.ParseError('File should not have both sha256 and sha384 checksum bits set!')
65
65
 
66
+ if self.buffer_offset + self.rom_size > self.parent_buffer.buffer_size:
67
+ raise File.ParseError(f'Header size 0x{self.rom_size:x} overflows the parent buffer, '
68
+ f'likely not a PSP header')
69
+
66
70
  if self.rom_size == 0:
67
71
  self.rom_size = self.buffer_size
68
72
  elif self.rom_size > self.buffer_size:
@@ -81,9 +81,13 @@ class KeyStoreFileHeader(NestedBuffer):
81
81
 
82
82
  self.certifying_id = KeyId(self, 0x10, buffer_offset=0x38)
83
83
 
84
- self._unknown_constant_1 = NestedBuffer(self, 0x4, buffer_offset=0x30)
85
- self._unknown_constant_2 = NestedBuffer(self, 0x4, buffer_offset=0x34)
86
- assert self.unknown_constants == (b'\1\0\0\0', b'\2\0\0\0')
84
+ # Same fields as in a HeaderFile. Early Renoir key stores leave the
85
+ # signature type at 0 next to a 0x200 byte signature, so
86
+ # signature_size is derived from the sizes instead.
87
+ self._signed = NestedBuffer(self, 0x4, buffer_offset=0x30)
88
+ self._signature_type = NestedBuffer(self, 0x4, buffer_offset=0x34)
89
+ assert self.signed == 1
90
+ assert self.signature_type in {0, 2}
87
91
 
88
92
  self._keystore_type = NestedBuffer(self, 0x4, buffer_offset=0x7c)
89
93
  assert self.keystore_type in File.KEY_STORE_TYPES or self.keystore_type == 0
@@ -130,11 +134,12 @@ class KeyStoreFileHeader(NestedBuffer):
130
134
  return self.parent_buffer.buffer_size - self.body_size - self.HEADER_SIZE
131
135
 
132
136
  @property
133
- def unknown_constants(self) -> (bytes, bytes, bytes):
134
- return (
135
- self._unknown_constant_1.get_bytes(),
136
- self._unknown_constant_2.get_bytes(),
137
- )
137
+ def signed(self) -> int:
138
+ return int.from_bytes(self._signed.get_bytes(), 'little')
139
+
140
+ @property
141
+ def signature_type(self) -> int:
142
+ return int.from_bytes(self._signature_type.get_bytes(), 'little')
138
143
 
139
144
 
140
145
  class KeyStore(NestedBuffer):
@@ -50,12 +50,52 @@ class PSPTool:
50
50
  self.blob = Blob(rom_bytes, len(rom_bytes), self)
51
51
  self.cert_tree = CertificateTree.from_blob(self.blob, self)
52
52
 
53
+ self._backfill_zen_generation_from_bootloader()
54
+
53
55
  def __repr__(self):
54
56
  if self.filename is not None:
55
57
  return f'PSPTool(filename={self.filename})'
56
58
  else:
57
59
  return f'PSPTool(len(rom_bytes)={self.blob.buffer_size}'
58
60
 
61
+ def _backfill_zen_generation_from_bootloader(self):
62
+ # Single-generation ROMs (notably EPYC server BIOSes) have no 2PSP
63
+ # combo directory and no tertiary self-tag, so neither of the two
64
+ # existing detection paths fires. Fall back to the PSP_FW_BOOT_LOADER
65
+ # version major byte, which is mandatory and stable per PSP firmware
66
+ # generation. Only fires when the entire ROM is unclassified — in a
67
+ # multi-generation combo BIOS the boot loader belongs to one of
68
+ # several $PSP directories and cannot be safely associated with the
69
+ # sibling $BHD directories.
70
+ for rom in self.blob.roms:
71
+ if not all(d.zen_generation is None for d in rom.directories):
72
+ continue
73
+
74
+ bl_major = None
75
+ for directory in rom.directories:
76
+ for f in directory.files:
77
+ if f.type == 0x01 and isinstance(f, HeaderFile):
78
+ # version is reverse-sliced in HeaderFile (header[0x63:0x5f:-1])
79
+ # so the printed-form major byte lives at version[1].
80
+ bl_major = f.version[1]
81
+ break
82
+ if bl_major is not None:
83
+ break
84
+
85
+ if bl_major is None:
86
+ continue
87
+
88
+ gen = Directory.BOOTLOADER_VERSION_TO_ZEN.get(bl_major)
89
+ if gen is None:
90
+ self.ph.print_warning(
91
+ f"PSP_FW_BOOT_LOADER version major 0x{bl_major:02X} not in "
92
+ f"BOOTLOADER_VERSION_TO_ZEN; cannot infer zen_generation"
93
+ )
94
+ continue
95
+
96
+ for directory in rom.directories:
97
+ directory.zen_generation = gen
98
+
59
99
  def to_file(self, filename):
60
100
  with open(filename, 'wb') as f:
61
101
  f.write(self.blob.get_buffer())
@@ -0,0 +1,122 @@
1
+ # PSPTool - Display, extract and manipulate PSP firmware inside UEFI images
2
+ # Copyright (C) 2026 contributors
3
+ #
4
+ # This program is free software: you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation, either version 3 of the License, or
7
+ # (at your option) any later version.
8
+
9
+ """Synthetic ROM builder for unit tests.
10
+
11
+ Constructs an 8 MB ROM-shaped binary that PSPTool.from_file() can parse
12
+ end-to-end: a Firmware Entry Table referencing a single $PSP directory,
13
+ which in turn references one PSP_FW_BOOT_LOADER (type 0x01) HeaderFile.
14
+ Most of the binary is zero padding; only the small windows that PSPTool
15
+ parses are populated.
16
+
17
+ The boot loader's `version` field is the only knob tests need: setting
18
+ the major byte (printed as version[1]) chooses which Zen generation
19
+ PSPTool's back-fill assigns. The mapping itself lives in
20
+ psptool.directory.Directory.BOOTLOADER_VERSION_TO_ZEN.
21
+
22
+ This is intentionally NOT a faithful PSP image; checksums on file
23
+ contents are zero, no signatures, no AGESA strings. It exercises the
24
+ parsing path that drives zen_generation back-fill and nothing more.
25
+ """
26
+
27
+ import struct
28
+
29
+ from psptool.blob import Blob
30
+ from psptool.utils import fletcher32
31
+
32
+ ROM_SIZE = 8 * 1024 * 1024
33
+ # Smallest FET offset PSPTool will probe — every other constant in this
34
+ # module is derived as a small offset above it, so updating the blob's
35
+ # offset table doesn't desync the builder.
36
+ FET_OFFSET = Blob.POSSIBLE_FET_OFFSETS[0]
37
+ PSP_DIR_OFFSET = FET_OFFSET + 0x1000
38
+ BL_FILE_OFFSET = FET_OFFSET + 0x2000
39
+
40
+ FET_MAGIC = Blob._FIRMWARE_ENTRY_MAGIC
41
+ PSP_DIR_MAGIC = b'$PSP'
42
+
43
+ DIRECTORY_HEADER_SIZE = 16
44
+ DIRECTORY_ENTRY_SIZE = 16
45
+ HEADER_FILE_SIZE = 0x100 # HeaderFile.HEADER_LEN; minimal file body
46
+
47
+
48
+ def _build_psp_directory(entry_offset: int, entry_size: int) -> bytes:
49
+ # Header layout:
50
+ # [0:4] magic '$PSP'
51
+ # [4:8] fletcher32(body)
52
+ # [8:12] entry count
53
+ # [12:16] additional_info: bit31=version=1, bits 25:24 = address_mode
54
+ # (1 = flash offset from start of BIOS)
55
+ additional_info = struct.pack('<I', (1 << 31) | (1 << 24))
56
+ count = struct.pack('<I', 1)
57
+
58
+ # One DirectoryEntry: type=0x01 PSP_FW_BOOT_LOADER, subprog=0, flags=0,
59
+ # size, offset, rsv0=0
60
+ entry = struct.pack(
61
+ '<BBHIII',
62
+ 0x01, # type
63
+ 0x00, # subprogram
64
+ 0x0000, # flags
65
+ entry_size, # size
66
+ entry_offset, # offset (raw — directory addr_mode 1 returns this as-is)
67
+ 0x00000000, # rsv0
68
+ )
69
+
70
+ body = count + additional_info + entry # bytes after the checksum field
71
+ checksum = fletcher32(body)
72
+ return PSP_DIR_MAGIC + checksum + body
73
+
74
+
75
+ def _build_header_file(bl_major: int) -> bytes:
76
+ # HeaderFile reads version as header[0x63:0x5f:-1], i.e. bytes at
77
+ # 0x63, 0x62, 0x61, 0x60 in printed order. The major byte that drives
78
+ # zen_generation lives at version[1] = header[0x62].
79
+ header = bytearray(HEADER_FILE_SIZE)
80
+ header[0x60] = 0x00 # version[3] (build, ignored for backfill)
81
+ header[0x61] = 0x00 # version[2] (minor, ignored)
82
+ header[0x62] = bl_major # version[1] (major — drives backfill)
83
+ header[0x63] = 0x00 # version[0] (printed-form leading zero)
84
+ # rom_size (header[0x6c:0x70]) = 0 means "use buffer_size" in HeaderFile
85
+ # All other fields stay zero: not encrypted, not signed, no checksum bits.
86
+ return bytes(header)
87
+
88
+
89
+ def build_synthetic_rom(bl_major: int) -> bytes:
90
+ """Return an 8 MB ROM blob whose PSP_FW_BOOT_LOADER version major
91
+ byte is `bl_major`. Pass a value from
92
+ Directory.BOOTLOADER_VERSION_TO_ZEN to drive a specific Zen
93
+ generation through the back-fill path.
94
+ """
95
+ blob = bytearray(ROM_SIZE)
96
+
97
+ # FET layout. The FET parser walks 4-byte words from FET_OFFSET until
98
+ # it sees 16 bytes of 0xFF. The first word is the FET magic itself
99
+ # (which the parser tries to interpret as a directory pointer and
100
+ # warns about — benign for tests). The next valid pointer points at
101
+ # our $PSP directory.
102
+ blob[FET_OFFSET - 4:FET_OFFSET] = b'\xff\xff\xff\xff' # required by _find_fets regex
103
+ blob[FET_OFFSET:FET_OFFSET + 4] = FET_MAGIC
104
+ blob[FET_OFFSET + 4:FET_OFFSET + 8] = struct.pack('<I', PSP_DIR_OFFSET)
105
+ blob[FET_OFFSET + 8:FET_OFFSET + 24] = b'\xff' * 16 # FET terminator
106
+
107
+ psp_dir = _build_psp_directory(BL_FILE_OFFSET, HEADER_FILE_SIZE)
108
+ blob[PSP_DIR_OFFSET:PSP_DIR_OFFSET + len(psp_dir)] = psp_dir
109
+
110
+ bl_header = _build_header_file(bl_major)
111
+ blob[BL_FILE_OFFSET:BL_FILE_OFFSET + len(bl_header)] = bl_header
112
+
113
+ return bytes(blob)
114
+
115
+
116
+ if __name__ == '__main__':
117
+ # Smoke check: build a Zen 2 ROM and dump its size and the version
118
+ # bytes for sanity.
119
+ data = build_synthetic_rom(0x0C)
120
+ print(f'len={len(data)} fet[0:4]={data[FET_OFFSET:FET_OFFSET+4].hex()} '
121
+ f'psp_dir[0:4]={data[PSP_DIR_OFFSET:PSP_DIR_OFFSET+4]!r} '
122
+ f'bl_version[60:64]={data[BL_FILE_OFFSET+0x60:BL_FILE_OFFSET+0x64].hex()}')
@@ -0,0 +1,91 @@
1
+ # PSPTool - Display, extract and manipulate PSP firmware inside UEFI images
2
+ # Copyright (C) 2026 contributors
3
+ #
4
+ # This program is free software: you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation, either version 3 of the License, or
7
+ # (at your option) any later version.
8
+
9
+ """Synthetic ROMs holding a single 0x50 key store.
10
+
11
+ Key stores in early ThinkPad T14/X13 Gen 1 AMD releases have no $PS1
12
+ magic and signature type 0 next to a 0x200 byte signature.
13
+ """
14
+
15
+ import contextlib
16
+ import io
17
+ import os
18
+ import struct
19
+ import tempfile
20
+ import unittest
21
+
22
+ from psptool import PSPTool
23
+ from psptool.blob import Blob
24
+ from psptool.utils import fletcher32
25
+
26
+ ROM_SIZE = 8 * 1024 * 1024
27
+ FET_OFFSET = Blob.POSSIBLE_FET_OFFSETS[0]
28
+ PSP_DIR_OFFSET = FET_OFFSET + 0x1000
29
+ KEY_STORE_OFFSET = FET_OFFSET + 0x2000
30
+ HEADER_FILE_SIZE = 0x100
31
+
32
+ # Directory additional_info: version bit set, address mode 1 (flash offset)
33
+ FLASH_OFFSET_MODE = (1 << 31) | (1 << 24)
34
+
35
+
36
+ def key_store_file(magic: bytes, signature_type: int) -> bytes:
37
+ modulus_size = 0x100
38
+ key = struct.pack('<IIII', 0x50 + modulus_size, 1, 0, 0x10001)
39
+ key += bytes(0x10) + struct.pack('<I', modulus_size * 8)
40
+ key = key.ljust(0x50, b'\0') + bytes(modulus_size)
41
+ key_store = struct.pack('<II', 0x50 + len(key), 1) + b'$KDB'
42
+ key_store = key_store.ljust(0x50, b'\0') + key
43
+ signature_size = 0x200
44
+ header = bytearray(HEADER_FILE_SIZE)
45
+ header[0x10:0x14] = magic
46
+ header[0x14:0x18] = struct.pack('<I', len(key_store))
47
+ header[0x30:0x38] = struct.pack('<II', 1, signature_type)
48
+ header[0x6c:0x70] = struct.pack('<I', HEADER_FILE_SIZE + len(key_store) + signature_size)
49
+ header[0x7c:0x80] = struct.pack('<I', 0x50)
50
+ return bytes(header) + key_store + bytes(signature_size)
51
+
52
+
53
+ def rom(ksf: bytes) -> bytes:
54
+ blob = bytearray(ROM_SIZE)
55
+ blob[FET_OFFSET - 4:FET_OFFSET] = b'\xff' * 4
56
+ blob[FET_OFFSET:FET_OFFSET + 4] = Blob._FIRMWARE_ENTRY_MAGIC
57
+ blob[FET_OFFSET + 4:FET_OFFSET + 8] = struct.pack('<I', PSP_DIR_OFFSET)
58
+ blob[FET_OFFSET + 8:FET_OFFSET + 24] = b'\xff' * 16
59
+ body = struct.pack('<II', 1, FLASH_OFFSET_MODE)
60
+ body += struct.pack('<BBHIII', 0x50, 0, 0, len(ksf), KEY_STORE_OFFSET, 0)
61
+ psp_dir = b'$PSP' + fletcher32(body) + body
62
+ blob[PSP_DIR_OFFSET:PSP_DIR_OFFSET + len(psp_dir)] = psp_dir
63
+ blob[KEY_STORE_OFFSET:KEY_STORE_OFFSET + len(ksf)] = ksf
64
+ return bytes(blob)
65
+
66
+
67
+ def parse(data: bytes):
68
+ with tempfile.NamedTemporaryFile(suffix='.rom', delete=False) as f:
69
+ f.write(data)
70
+ path = f.name
71
+ try:
72
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
73
+ return PSPTool.from_file(path)
74
+ finally:
75
+ os.unlink(path)
76
+
77
+
78
+ class TestKeyStoreFile(unittest.TestCase):
79
+
80
+ def test_key_store_with_signature_type_0(self):
81
+ for magic, signature_type in ((b'$PS1', 2), (bytes(4), 0)):
82
+ with self.subTest(magic=magic, signature_type=signature_type):
83
+ pt = parse(rom(key_store_file(magic, signature_type)))
84
+ (key_store,) = pt.blob.unique_files()
85
+ self.assertEqual(type(key_store).__name__, 'KeyStoreFile')
86
+ self.assertEqual(key_store.signature.buffer_size, 0x200)
87
+ self.assertEqual(len(key_store.key_store.keys), 1)
88
+
89
+
90
+ if __name__ == '__main__':
91
+ unittest.main()
@@ -0,0 +1,189 @@
1
+ # PSPTool - Display, extract and manipulate PSP firmware inside UEFI images
2
+ # Copyright (C) 2026 contributors
3
+ #
4
+ # This program is free software: you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation, either version 3 of the License, or
7
+ # (at your option) any later version.
8
+
9
+ """Synthetic ROMs for layouts seen in Lenovo ThinkPad client firmware.
10
+
11
+ - A 64 MB flash whose BIOS L2 directory points past 32 MB (Z13 Gen 2),
12
+ and 32 MB ROMs in files of 64 MB that must keep their size.
13
+ - 0x48/0x4a entries pointing straight at a $PL2 directory rather than at
14
+ a header holding its offset (L13 Gen 4).
15
+ - A BIOS directory entry holding a plain PE image, whose bytes at the
16
+ header's size field are text (L13 Gen 4).
17
+ - A 0x4a slot header pointing at an APCB rather than at a $PL2 directory
18
+ (T14 Gen 7 AMD).
19
+ - An x86 physical address with entry address mode 0 in a directory with
20
+ address mode 1, as coreboot writes APOB NV entries (StarBook Mk VI AMD).
21
+ """
22
+
23
+ import contextlib
24
+ import io
25
+ import os
26
+ import struct
27
+ import tempfile
28
+ import unittest
29
+
30
+ from psptool import PSPTool
31
+ from psptool.blob import Blob
32
+ from psptool.utils import fletcher32
33
+
34
+ MB = 1024 * 1024
35
+ FET_OFFSET = Blob.POSSIBLE_FET_OFFSETS[0]
36
+ PSP_DIR_OFFSET = FET_OFFSET + 0x1000
37
+ HEADER_FILE_SIZE = 0x100
38
+
39
+ # Directory additional_info: version bit set, address mode 1 (flash offset)
40
+ FLASH_OFFSET_MODE = (1 << 31) | (1 << 24)
41
+
42
+
43
+ def directory(magic: bytes, entries) -> bytes:
44
+ body = struct.pack('<II', len(entries), FLASH_OFFSET_MODE)
45
+ for type_, size, offset in entries:
46
+ body += struct.pack('<BBHIII', type_, 0, 0, size, offset, 0)
47
+ return magic + fletcher32(body) + body
48
+
49
+
50
+ def header_file(rom_size: int = 0) -> bytes:
51
+ header = bytearray(HEADER_FILE_SIZE)
52
+ header[0x62] = 0x0C # boot loader major in BOOTLOADER_VERSION_TO_ZEN, else PSPTool warns
53
+ header[0x6c:0x70] = struct.pack('<I', rom_size)
54
+ return bytes(header)
55
+
56
+
57
+ def rom(size: int, psp_entries, extra=()) -> bytes:
58
+ blob = bytearray(size)
59
+ blob[FET_OFFSET - 4:FET_OFFSET] = b'\xff' * 4
60
+ blob[FET_OFFSET:FET_OFFSET + 4] = Blob._FIRMWARE_ENTRY_MAGIC
61
+ blob[FET_OFFSET + 4:FET_OFFSET + 8] = struct.pack('<I', PSP_DIR_OFFSET)
62
+ blob[FET_OFFSET + 8:FET_OFFSET + 24] = b'\xff' * 16
63
+ psp_dir = directory(b'$PSP', psp_entries)
64
+ blob[PSP_DIR_OFFSET:PSP_DIR_OFFSET + len(psp_dir)] = psp_dir
65
+ for offset, data in extra:
66
+ blob[offset:offset + len(data)] = data
67
+ return bytes(blob)
68
+
69
+
70
+ def parse(data: bytes):
71
+ with tempfile.NamedTemporaryFile(suffix='.rom', delete=False) as f:
72
+ f.write(data)
73
+ path = f.name
74
+ try:
75
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
76
+ pt = PSPTool.from_file(path)
77
+ return pt, stderr.getvalue()
78
+ finally:
79
+ os.unlink(path)
80
+
81
+
82
+ def files(pt):
83
+ return {(f.type, f.get_address()) for f in pt.blob.unique_files()}
84
+
85
+
86
+ class TestRomLayouts(unittest.TestCase):
87
+
88
+ def test_64mb_rom_reaches_files_past_32mb(self):
89
+ file_offset = 48 * MB
90
+ data = rom(64 * MB, [(0x01, HEADER_FILE_SIZE, file_offset)],
91
+ [(file_offset, header_file())])
92
+ pt, warnings = parse(data)
93
+ self.assertIn('ROM size of 64M', warnings)
94
+ self.assertEqual(pt.blob.roms[0].addr_mask, 64 * MB - 1)
95
+ self.assertIn((0x01, file_offset), files(pt))
96
+
97
+ def test_32mb_rom_in_64mb_file_keeps_its_size(self):
98
+ file_offset = 16 * MB
99
+ data = rom(64 * MB, [(0x01, HEADER_FILE_SIZE, file_offset)],
100
+ [(file_offset, header_file())])
101
+ pt, warnings = parse(data)
102
+ self.assertNotIn('ROM size of 64M', warnings)
103
+ self.assertEqual(pt.blob.roms[0].addr_mask, 32 * MB - 1)
104
+ self.assertIn((0x01, file_offset), files(pt))
105
+
106
+ def test_32mb_rom_at_offset_in_64mb_file(self):
107
+ rom_offset = 0x320
108
+ file_offset = 16 * MB
109
+ data = bytes(rom_offset) + rom(64 * MB - rom_offset, [(0x01, HEADER_FILE_SIZE, file_offset)],
110
+ [(file_offset, header_file())])
111
+ pt, _ = parse(data)
112
+ self.assertEqual(len(pt.blob.roms), 1)
113
+ self.assertEqual(pt.blob.roms[0].addr_mask, 32 * MB - 1)
114
+ self.assertEqual({type_ for type_, _ in files(pt)}, {0x01})
115
+
116
+ def test_l2_pointer_straight_at_directory(self):
117
+ l2_offset = FET_OFFSET + 0x4000
118
+ file_offset = FET_OFFSET + 0x5000
119
+ data = rom(8 * MB, [(0x48, 0x400, l2_offset)], [
120
+ (l2_offset, directory(b'$PL2', [(0x01, HEADER_FILE_SIZE, file_offset)])),
121
+ (file_offset, header_file()),
122
+ ])
123
+ pt, _ = parse(data)
124
+ magics = [d.magic for d in pt.blob.roms[0].directories]
125
+ self.assertEqual(magics, [b'$PSP', b'$PL2'])
126
+ self.assertIn((0x01, file_offset), files(pt))
127
+
128
+ def test_l2_reached_directly_and_through_ish(self):
129
+ l2_offset = FET_OFFSET + 0x4000
130
+ ish_offset = FET_OFFSET + 0x3000
131
+ file_offset = FET_OFFSET + 0x5000
132
+ ish = bytes(16) + struct.pack('<I', l2_offset) + b'\x00\x01\x0C\xBC'
133
+ data = rom(8 * MB, [(0x48, 0x400, l2_offset), (0x4a, 0x20, ish_offset)], [
134
+ (ish_offset, ish),
135
+ (l2_offset, directory(b'$PL2', [(0x01, HEADER_FILE_SIZE, file_offset)])),
136
+ (file_offset, header_file()),
137
+ ])
138
+ pt, _ = parse(data)
139
+ directories = pt.blob.roms[0].directories
140
+ self.assertEqual([d.magic for d in directories], [b'$PSP', b'$PL2'])
141
+ self.assertEqual(directories[1].zen_generation, 'Zen 3 (PSP ID 0xbc0c0100)')
142
+
143
+ def test_header_size_past_rom_skips_file(self):
144
+ bad_offset = FET_OFFSET + 0x4000
145
+ good_offset = FET_OFFSET + 0x5000
146
+ data = rom(8 * MB, [
147
+ (0x01, HEADER_FILE_SIZE, bad_offset),
148
+ (0x73, HEADER_FILE_SIZE, good_offset),
149
+ ], [
150
+ (bad_offset, header_file(rom_size=0x6b20796e)),
151
+ (good_offset, header_file(rom_size=2 * HEADER_FILE_SIZE)),
152
+ ])
153
+ pt, warnings = parse(data)
154
+ self.assertIn('overflows the parent buffer', warnings)
155
+ self.assertEqual(files(pt), {(0x73, good_offset)})
156
+ # A header size past the entry size but inside the ROM still counts
157
+ (good,) = pt.blob.unique_files()
158
+ self.assertEqual(good.buffer_size, 2 * HEADER_FILE_SIZE)
159
+
160
+ def test_slot_header_pointing_at_non_directory_is_skipped(self):
161
+ ish_a = FET_OFFSET + 0x2000
162
+ ish_b = FET_OFFSET + 0x3000
163
+ l2_offset = FET_OFFSET + 0x4000
164
+ apcb_offset = FET_OFFSET + 0x6000
165
+ file_offset = FET_OFFSET + 0x5000
166
+ zen_id = b'\x00\x01\x0C\xBC'
167
+ data = rom(8 * MB, [(0x48, 0x20, ish_a), (0x4a, 0x20, ish_b)], [
168
+ (ish_a, bytes(16) + struct.pack('<I', l2_offset) + zen_id),
169
+ (ish_b, bytes(16) + struct.pack('<I', apcb_offset) + zen_id),
170
+ (l2_offset, directory(b'$PL2', [(0x01, HEADER_FILE_SIZE, file_offset)])),
171
+ (apcb_offset, b'APCB' + bytes(12)),
172
+ (file_offset, header_file()),
173
+ ])
174
+ pt, warnings = parse(data)
175
+ self.assertIn('Unknown directory magic', warnings)
176
+ magics = [d.magic for d in pt.blob.roms[0].directories]
177
+ self.assertEqual(magics, [b'$PSP', b'$PL2'])
178
+ self.assertIn((0x01, file_offset), files(pt))
179
+
180
+ def test_physical_address_in_flash_offset_directory(self):
181
+ file_offset = FET_OFFSET + 0x4000
182
+ data = rom(16 * MB, [(0x01, HEADER_FILE_SIZE, 0xFF000000 + file_offset)],
183
+ [(file_offset, header_file())])
184
+ pt, _ = parse(data)
185
+ self.assertEqual(files(pt), {(0x01, file_offset)})
186
+
187
+
188
+ if __name__ == '__main__':
189
+ unittest.main()
@@ -0,0 +1,79 @@
1
+ # PSPTool - Display, extract and manipulate PSP firmware inside UEFI images
2
+ # Copyright (C) 2026 contributors
3
+ #
4
+ # This program is free software: you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation, either version 3 of the License, or
7
+ # (at your option) any later version.
8
+
9
+ import contextlib
10
+ import io
11
+ import os
12
+ import tempfile
13
+ import unittest
14
+
15
+ from psptool import PSPTool
16
+ from psptool.directory import Directory
17
+
18
+ from .synthetic_rom import build_synthetic_rom
19
+
20
+
21
+ class TestZenGenerationBackfill(unittest.TestCase):
22
+ """Drive the PSP_FW_BOOT_LOADER back-fill path with synthetic ROMs.
23
+
24
+ Each test builds an 8 MB ROM whose only PSP_FW_BOOT_LOADER carries a
25
+ chosen version-major byte, parses it through PSPTool, and asserts
26
+ that the resulting directory.zen_generation matches what
27
+ BOOTLOADER_VERSION_TO_ZEN dictates.
28
+ """
29
+
30
+ def _parse_synthetic(self, bl_major):
31
+ data = build_synthetic_rom(bl_major)
32
+ with tempfile.NamedTemporaryFile(suffix='.rom', delete=False) as f:
33
+ f.write(data)
34
+ path = f.name
35
+ try:
36
+ with io.StringIO() as stderr_buf, contextlib.redirect_stderr(stderr_buf):
37
+ pt = PSPTool.from_file(path)
38
+ warnings = stderr_buf.getvalue()
39
+ return pt, warnings
40
+ finally:
41
+ os.unlink(path)
42
+
43
+ def test_each_known_major_resolves_to_expected_zen(self):
44
+ for bl_major, expected in Directory.BOOTLOADER_VERSION_TO_ZEN.items():
45
+ with self.subTest(f'major=0x{bl_major:02X}'):
46
+ pt, _ = self._parse_synthetic(bl_major)
47
+ gens = [d.zen_generation for r in pt.blob.roms for d in r.directories]
48
+ self.assertEqual(
49
+ gens, [expected],
50
+ f'major=0x{bl_major:02X}: expected one directory tagged {expected!r}, got {gens!r}',
51
+ )
52
+
53
+ def test_unknown_major_leaves_zen_generation_none_and_warns(self):
54
+ # 0x99 is intentionally not in BOOTLOADER_VERSION_TO_ZEN.
55
+ self.assertNotIn(0x99, Directory.BOOTLOADER_VERSION_TO_ZEN)
56
+ pt, warnings = self._parse_synthetic(0x99)
57
+ gens = [d.zen_generation for r in pt.blob.roms for d in r.directories]
58
+ self.assertEqual(gens, [None])
59
+ self.assertIn('0x99', warnings)
60
+ self.assertIn('not in BOOTLOADER_VERSION_TO_ZEN', warnings)
61
+
62
+ def test_back_fill_does_not_overwrite_pre_classified_directories(self):
63
+ # If the directory already has a zen_generation set (would be the
64
+ # case in a combo BIOS where combo_dir classified it), back-fill
65
+ # must not touch it. Verify by mutating the parsed object: pin
66
+ # the directory to a known string, run back-fill again, observe
67
+ # it stays put even though it would otherwise resolve via the
68
+ # 0x0C boot loader.
69
+ pt, _ = self._parse_synthetic(0x0C)
70
+ directory = pt.blob.roms[0].directories[0]
71
+ self.assertEqual(directory.zen_generation, 'Zen 2')
72
+
73
+ directory.zen_generation = 'pre-classified'
74
+ pt._backfill_zen_generation_from_bootloader()
75
+ self.assertEqual(directory.zen_generation, 'pre-classified')
76
+
77
+
78
+ if __name__ == '__main__':
79
+ unittest.main()
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes