uppercut-rom-headers 1.0.0__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.
- uppercut_rom_headers-1.0.0/.gitignore +16 -0
- uppercut_rom_headers-1.0.0/LICENSE +21 -0
- uppercut_rom_headers-1.0.0/PKG-INFO +86 -0
- uppercut_rom_headers-1.0.0/README.md +64 -0
- uppercut_rom_headers-1.0.0/pyproject.toml +38 -0
- uppercut_rom_headers-1.0.0/src/uppercut_rom_headers/__init__.py +24 -0
- uppercut_rom_headers-1.0.0/src/uppercut_rom_headers/__main__.py +5 -0
- uppercut_rom_headers-1.0.0/src/uppercut_rom_headers/_checks.py +37 -0
- uppercut_rom_headers-1.0.0/src/uppercut_rom_headers/cli.py +85 -0
- uppercut_rom_headers-1.0.0/src/uppercut_rom_headers/gba.py +28 -0
- uppercut_rom_headers-1.0.0/src/uppercut_rom_headers/megadrive.py +32 -0
- uppercut_rom_headers-1.0.0/src/uppercut_rom_headers/n64.py +70 -0
- uppercut_rom_headers-1.0.0/src/uppercut_rom_headers/py.typed +0 -0
- uppercut_rom_headers-1.0.0/tests/conftest.py +6 -0
- uppercut_rom_headers-1.0.0/tests/rom_images.py +34 -0
- uppercut_rom_headers-1.0.0/tests/test_cli.py +87 -0
- uppercut_rom_headers-1.0.0/tests/test_gba.py +64 -0
- uppercut_rom_headers-1.0.0/tests/test_megadrive.py +68 -0
- uppercut_rom_headers-1.0.0/tests/test_n64.py +120 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Uppercut Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: uppercut-rom-headers
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Compute, fix and verify the header checksums of Nintendo 64, Mega Drive and 32X, and Game Boy Advance ROM images.
|
|
5
|
+
Project-URL: Source, https://github.com/uppercut-labs/game-kit/tree/main/packages/uppercut-rom-headers
|
|
6
|
+
Author-email: Uppercut Labs <packages@uppercut-labs.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: 32x,checksum,gba,header,homebrew,mega-drive,n64,rom
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Games/Entertainment
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# uppercut-rom-headers
|
|
24
|
+
|
|
25
|
+
Computes, writes and checks the header checksums that homebrew ROM builds have to get right: the two CRCs of a Nintendo 64 image (CIC-6102), the word checksum of a Mega Drive or 32X image, and the header complement byte of a Game Boy Advance image. Each format has a `compute_`, a `fix_` and a `verify_` function, and there is a small command line. Standard library only.
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pip install uppercut-rom-headers
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Python
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from uppercut_rom_headers import fix_n64_checksums, verify_n64_checksums
|
|
35
|
+
|
|
36
|
+
image = bytearray(open("game.z64", "rb").read())
|
|
37
|
+
crcs = fix_n64_checksums(image) # writes CRC1 and CRC2 at 0x10 and 0x14
|
|
38
|
+
print(hex(crcs.crc1), hex(crcs.crc2))
|
|
39
|
+
assert verify_n64_checksums(image).ok
|
|
40
|
+
open("game.z64", "wb").write(image)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
| Format | Compute | Fix (writes into a `bytearray`, returns the value) | Verify (returns `Verification`) |
|
|
44
|
+
| --- | --- | --- | --- |
|
|
45
|
+
| Nintendo 64, CIC-6102 | `compute_n64_checksums(rom)` returns `N64Checksums(crc1, crc2)` | `fix_n64_checksums(rom, preserve_zero_header=False)` | `verify_n64_checksums(rom)` |
|
|
46
|
+
| Mega Drive and 32X | `compute_megadrive_checksum(rom)` | `fix_megadrive_checksum(rom)` | `verify_megadrive_checksum(rom)` |
|
|
47
|
+
| Game Boy Advance | `compute_gba_complement(rom)` | `fix_gba_complement(rom)` | `verify_gba_complement(rom)` |
|
|
48
|
+
|
|
49
|
+
`Verification` has `ok`, `expected` (what the contents give) and `found` (what the header holds), each a tuple of integers. The `compute_` and `verify_` functions take `bytes`, `bytearray` or `memoryview`; the `fix_` functions need a `bytearray`. An image that is too short for its checksum raises `RomHeaderError`, a `ValueError`.
|
|
50
|
+
|
|
51
|
+
| Format | What is summed | Where it goes | Smallest image |
|
|
52
|
+
| --- | --- | --- | --- |
|
|
53
|
+
| Nintendo 64 | the 1 MiB at 0x1000 to 0x101000, as big-endian 32-bit words, with the CIC-6102 seed | CRC1 at 0x10 and CRC2 at 0x14, big-endian | 0x101000 bytes |
|
|
54
|
+
| Mega Drive and 32X | every big-endian 16-bit word from 0x200 to the end of the image, modulo 65536; a trailing odd byte is not counted | 0x18E, big-endian | 0x200 bytes |
|
|
55
|
+
| Game Boy Advance | bytes 0xA0 to 0xBC: the complement is `-(sum + 0x19)` modulo 256 | 0xBD | 0xC0 bytes |
|
|
56
|
+
|
|
57
|
+
`preserve_zero_header=True` leaves a Nintendo 64 image alone when both header words are already zero, for toolchains that leave them zero on purpose; the result then has `skipped=True`.
|
|
58
|
+
|
|
59
|
+
## Command line
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
uppercut-rom-headers fix n64 game.z64
|
|
63
|
+
uppercut-rom-headers verify megadrive game.32x
|
|
64
|
+
python -m uppercut_rom_headers verify gba game.gba
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`fix` rewrites the file in place. `verify` prints `PASS ...` to stdout or `FAIL ...` to stderr with the expected and found values. The exit code is 0 for success, 1 when a verification fails and 2 for a missing, unreadable or too short file.
|
|
68
|
+
|
|
69
|
+
## Notes
|
|
70
|
+
|
|
71
|
+
- The Nintendo 64 CRC is the CIC-6102 algorithm, which CIC-6101 shares. The final values are `t6 ^ t4 ^ t3` and `t5 ^ t2 ^ t1`. Some code combines them with `+` as CIC-6103 does, while keeping the 6102 seed; that gives CRCs that a 6102 boot check does not accept. CIC-6103, 6105 and 6106 are not implemented.
|
|
72
|
+
- The header complement of a Game Boy Advance image is the same one that `uppercut-gba-rom-verify` checks. This package fixes and verifies the byte alone; that package checks the whole header, the ELF and the SHA-256. The tests compare the two when both are installed.
|
|
73
|
+
- Only the checksums are here. Logos, security blocks, licence data and boot code are not, and a checksum alone does not make an image bootable.
|
|
74
|
+
- The tests use synthetic images from a fixed pseudo-random stream. The expected checksums were written by an independent implementation of the same algorithms.
|
|
75
|
+
|
|
76
|
+
## Working on it
|
|
77
|
+
|
|
78
|
+
From the repository root:
|
|
79
|
+
|
|
80
|
+
```sh
|
|
81
|
+
uv sync --all-packages && uv run pytest packages/uppercut-rom-headers
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
MIT
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# uppercut-rom-headers
|
|
2
|
+
|
|
3
|
+
Computes, writes and checks the header checksums that homebrew ROM builds have to get right: the two CRCs of a Nintendo 64 image (CIC-6102), the word checksum of a Mega Drive or 32X image, and the header complement byte of a Game Boy Advance image. Each format has a `compute_`, a `fix_` and a `verify_` function, and there is a small command line. Standard library only.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install uppercut-rom-headers
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Python
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from uppercut_rom_headers import fix_n64_checksums, verify_n64_checksums
|
|
13
|
+
|
|
14
|
+
image = bytearray(open("game.z64", "rb").read())
|
|
15
|
+
crcs = fix_n64_checksums(image) # writes CRC1 and CRC2 at 0x10 and 0x14
|
|
16
|
+
print(hex(crcs.crc1), hex(crcs.crc2))
|
|
17
|
+
assert verify_n64_checksums(image).ok
|
|
18
|
+
open("game.z64", "wb").write(image)
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
| Format | Compute | Fix (writes into a `bytearray`, returns the value) | Verify (returns `Verification`) |
|
|
22
|
+
| --- | --- | --- | --- |
|
|
23
|
+
| Nintendo 64, CIC-6102 | `compute_n64_checksums(rom)` returns `N64Checksums(crc1, crc2)` | `fix_n64_checksums(rom, preserve_zero_header=False)` | `verify_n64_checksums(rom)` |
|
|
24
|
+
| Mega Drive and 32X | `compute_megadrive_checksum(rom)` | `fix_megadrive_checksum(rom)` | `verify_megadrive_checksum(rom)` |
|
|
25
|
+
| Game Boy Advance | `compute_gba_complement(rom)` | `fix_gba_complement(rom)` | `verify_gba_complement(rom)` |
|
|
26
|
+
|
|
27
|
+
`Verification` has `ok`, `expected` (what the contents give) and `found` (what the header holds), each a tuple of integers. The `compute_` and `verify_` functions take `bytes`, `bytearray` or `memoryview`; the `fix_` functions need a `bytearray`. An image that is too short for its checksum raises `RomHeaderError`, a `ValueError`.
|
|
28
|
+
|
|
29
|
+
| Format | What is summed | Where it goes | Smallest image |
|
|
30
|
+
| --- | --- | --- | --- |
|
|
31
|
+
| Nintendo 64 | the 1 MiB at 0x1000 to 0x101000, as big-endian 32-bit words, with the CIC-6102 seed | CRC1 at 0x10 and CRC2 at 0x14, big-endian | 0x101000 bytes |
|
|
32
|
+
| Mega Drive and 32X | every big-endian 16-bit word from 0x200 to the end of the image, modulo 65536; a trailing odd byte is not counted | 0x18E, big-endian | 0x200 bytes |
|
|
33
|
+
| Game Boy Advance | bytes 0xA0 to 0xBC: the complement is `-(sum + 0x19)` modulo 256 | 0xBD | 0xC0 bytes |
|
|
34
|
+
|
|
35
|
+
`preserve_zero_header=True` leaves a Nintendo 64 image alone when both header words are already zero, for toolchains that leave them zero on purpose; the result then has `skipped=True`.
|
|
36
|
+
|
|
37
|
+
## Command line
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
uppercut-rom-headers fix n64 game.z64
|
|
41
|
+
uppercut-rom-headers verify megadrive game.32x
|
|
42
|
+
python -m uppercut_rom_headers verify gba game.gba
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`fix` rewrites the file in place. `verify` prints `PASS ...` to stdout or `FAIL ...` to stderr with the expected and found values. The exit code is 0 for success, 1 when a verification fails and 2 for a missing, unreadable or too short file.
|
|
46
|
+
|
|
47
|
+
## Notes
|
|
48
|
+
|
|
49
|
+
- The Nintendo 64 CRC is the CIC-6102 algorithm, which CIC-6101 shares. The final values are `t6 ^ t4 ^ t3` and `t5 ^ t2 ^ t1`. Some code combines them with `+` as CIC-6103 does, while keeping the 6102 seed; that gives CRCs that a 6102 boot check does not accept. CIC-6103, 6105 and 6106 are not implemented.
|
|
50
|
+
- The header complement of a Game Boy Advance image is the same one that `uppercut-gba-rom-verify` checks. This package fixes and verifies the byte alone; that package checks the whole header, the ELF and the SHA-256. The tests compare the two when both are installed.
|
|
51
|
+
- Only the checksums are here. Logos, security blocks, licence data and boot code are not, and a checksum alone does not make an image bootable.
|
|
52
|
+
- The tests use synthetic images from a fixed pseudo-random stream. The expected checksums were written by an independent implementation of the same algorithms.
|
|
53
|
+
|
|
54
|
+
## Working on it
|
|
55
|
+
|
|
56
|
+
From the repository root:
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
uv sync --all-packages && uv run pytest packages/uppercut-rom-headers
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## License
|
|
63
|
+
|
|
64
|
+
MIT
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "uppercut-rom-headers"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Compute, fix and verify the header checksums of Nintendo 64, Mega Drive and 32X, and Game Boy Advance ROM images."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
|
|
13
|
+
keywords = ["rom", "header", "checksum", "n64", "mega-drive", "32x", "gba", "homebrew"]
|
|
14
|
+
dependencies = []
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 5 - Production/Stable",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Topic :: Games/Entertainment",
|
|
25
|
+
"Typing :: Typed",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
uppercut-rom-headers = "uppercut_rom_headers.cli:main"
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Source = "https://github.com/uppercut-labs/game-kit/tree/main/packages/uppercut-rom-headers"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/uppercut_rom_headers"]
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.sdist]
|
|
38
|
+
include = ["src", "tests", "README.md"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Compute, fix and verify the header checksums of Nintendo 64, Mega Drive and 32X, and Game Boy Advance ROM images."""
|
|
2
|
+
|
|
3
|
+
from ._checks import RomHeaderError, Verification
|
|
4
|
+
from .cli import main
|
|
5
|
+
from .gba import compute_gba_complement, fix_gba_complement, verify_gba_complement
|
|
6
|
+
from .megadrive import compute_megadrive_checksum, fix_megadrive_checksum, verify_megadrive_checksum
|
|
7
|
+
from .n64 import N64Checksums, compute_n64_checksums, fix_n64_checksums, verify_n64_checksums
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"N64Checksums",
|
|
11
|
+
"RomHeaderError",
|
|
12
|
+
"Verification",
|
|
13
|
+
"compute_gba_complement",
|
|
14
|
+
"compute_megadrive_checksum",
|
|
15
|
+
"compute_n64_checksums",
|
|
16
|
+
"fix_gba_complement",
|
|
17
|
+
"fix_megadrive_checksum",
|
|
18
|
+
"fix_n64_checksums",
|
|
19
|
+
"main",
|
|
20
|
+
"verify_gba_complement",
|
|
21
|
+
"verify_megadrive_checksum",
|
|
22
|
+
"verify_n64_checksums",
|
|
23
|
+
]
|
|
24
|
+
__version__ = "1.0.0"
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Shared types: the error, the verification result and the input checks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Tuple, Union
|
|
7
|
+
|
|
8
|
+
ByteString = Union[bytes, bytearray, memoryview]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class RomHeaderError(ValueError):
|
|
12
|
+
"""Raised when a ROM image is too short for the checksum, or is not a byte buffer."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Verification:
|
|
17
|
+
"""The outcome of a ``verify_*`` call.
|
|
18
|
+
|
|
19
|
+
``expected`` is what the image's contents give, ``found`` is what its header holds. Each is a tuple of
|
|
20
|
+
integers: ``(crc1, crc2)`` for Nintendo 64, one value for Mega Drive and Game Boy Advance.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
ok: bool
|
|
24
|
+
expected: Tuple[int, ...]
|
|
25
|
+
found: Tuple[int, ...]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def require_length(rom: ByteString, minimum: int, what: str) -> None:
|
|
29
|
+
if not isinstance(rom, (bytes, bytearray, memoryview)):
|
|
30
|
+
raise RomHeaderError(f"{what} must be bytes, bytearray or memoryview, not {type(rom).__name__}")
|
|
31
|
+
if len(rom) < minimum:
|
|
32
|
+
raise RomHeaderError(f"{what} is too short for its checksum: {len(rom)} bytes, need at least {minimum}")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def require_writable(rom: ByteString) -> None:
|
|
36
|
+
if not isinstance(rom, bytearray):
|
|
37
|
+
raise RomHeaderError(f"fixing a checksum writes into the image, so it must be a bytearray, not {type(rom).__name__}")
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Command line: fix or verify the header checksum of a ROM file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Callable, Optional, Sequence
|
|
9
|
+
|
|
10
|
+
from ._checks import RomHeaderError, Verification
|
|
11
|
+
from .gba import fix_gba_complement, verify_gba_complement
|
|
12
|
+
from .megadrive import fix_megadrive_checksum, verify_megadrive_checksum
|
|
13
|
+
from .n64 import fix_n64_checksums, verify_n64_checksums
|
|
14
|
+
|
|
15
|
+
# For each format: the verifier and the number of hex digits to show per value.
|
|
16
|
+
_VERIFIERS: dict[str, tuple[Callable[[bytearray], Verification], int]] = {
|
|
17
|
+
"n64": (verify_n64_checksums, 8),
|
|
18
|
+
"megadrive": (verify_megadrive_checksum, 4),
|
|
19
|
+
"gba": (verify_gba_complement, 2),
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
24
|
+
parser = argparse.ArgumentParser(
|
|
25
|
+
prog="uppercut-rom-headers",
|
|
26
|
+
description="Fix or verify the header checksum of a Nintendo 64, Mega Drive or 32X, or Game Boy Advance ROM.",
|
|
27
|
+
)
|
|
28
|
+
parser.add_argument("action", choices=("fix", "verify"), help="write the checksum into the file, or check it")
|
|
29
|
+
parser.add_argument(
|
|
30
|
+
"format",
|
|
31
|
+
choices=tuple(_VERIFIERS),
|
|
32
|
+
help="n64 (CIC-6102 CRC1 and CRC2), megadrive (also 32X) or gba (header complement)",
|
|
33
|
+
)
|
|
34
|
+
parser.add_argument("rom", help="path to the ROM file")
|
|
35
|
+
parser.add_argument(
|
|
36
|
+
"--preserve-zero-header",
|
|
37
|
+
action="store_true",
|
|
38
|
+
help="n64 fix only: leave an image whose two CRC words are both zero as it is",
|
|
39
|
+
)
|
|
40
|
+
return parser
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _show(values: Sequence[int], digits: int) -> str:
|
|
44
|
+
return ", ".join(f"0x{value:0{digits}X}" for value in values)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
48
|
+
"""Run the command line. Returns 0 on success, 1 when a verification fails and 2 for a file or usage error."""
|
|
49
|
+
args = build_parser().parse_args(argv)
|
|
50
|
+
path = Path(args.rom)
|
|
51
|
+
verifier, digits = _VERIFIERS[args.format]
|
|
52
|
+
try:
|
|
53
|
+
image = bytearray(path.read_bytes())
|
|
54
|
+
except OSError as error:
|
|
55
|
+
print(f"cannot read {path}: {error.strerror or error}", file=sys.stderr)
|
|
56
|
+
return 2
|
|
57
|
+
try:
|
|
58
|
+
if args.action == "verify":
|
|
59
|
+
result = verifier(image)
|
|
60
|
+
text = f"{args.format} header: expected {_show(result.expected, digits)}, found {_show(result.found, digits)}"
|
|
61
|
+
if result.ok:
|
|
62
|
+
print(f"PASS {text}")
|
|
63
|
+
return 0
|
|
64
|
+
print(f"FAIL {text}", file=sys.stderr)
|
|
65
|
+
return 1
|
|
66
|
+
if args.format == "n64":
|
|
67
|
+
fixed = fix_n64_checksums(image, preserve_zero_header=args.preserve_zero_header)
|
|
68
|
+
if fixed.skipped:
|
|
69
|
+
print(f"left {path} as it is: both n64 CRC words are zero")
|
|
70
|
+
return 0
|
|
71
|
+
elif args.format == "megadrive":
|
|
72
|
+
fix_megadrive_checksum(image)
|
|
73
|
+
else:
|
|
74
|
+
fix_gba_complement(image)
|
|
75
|
+
written = verifier(image).expected
|
|
76
|
+
except RomHeaderError as error:
|
|
77
|
+
print(f"{path}: {error}", file=sys.stderr)
|
|
78
|
+
return 2
|
|
79
|
+
try:
|
|
80
|
+
path.write_bytes(image)
|
|
81
|
+
except OSError as error:
|
|
82
|
+
print(f"cannot write {path}: {error.strerror or error}", file=sys.stderr)
|
|
83
|
+
return 2
|
|
84
|
+
print(f"fixed {args.format} header of {path}: {_show(written, digits)}")
|
|
85
|
+
return 0
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""The Game Boy Advance header complement byte at 0xBD."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ._checks import ByteString, Verification, require_length, require_writable
|
|
6
|
+
|
|
7
|
+
HEADER_SIZE = 0xC0
|
|
8
|
+
COMPLEMENT_OFFSET = 0xBD
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def compute_gba_complement(rom: ByteString) -> int:
|
|
12
|
+
"""The complement of the header bytes 0xA0 to 0xBC: ``-(sum + 0x19)`` modulo 256."""
|
|
13
|
+
require_length(rom, HEADER_SIZE, "GBA ROM")
|
|
14
|
+
return (-sum(rom[0xA0:COMPLEMENT_OFFSET]) - 0x19) & 0xFF
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def fix_gba_complement(rom: bytearray) -> int:
|
|
18
|
+
"""Write the complement byte at 0xBD and return it."""
|
|
19
|
+
require_writable(rom)
|
|
20
|
+
complement = compute_gba_complement(rom)
|
|
21
|
+
rom[COMPLEMENT_OFFSET] = complement
|
|
22
|
+
return complement
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def verify_gba_complement(rom: ByteString) -> Verification:
|
|
26
|
+
"""Compare the header's complement byte with the one its header bytes give."""
|
|
27
|
+
expected = compute_gba_complement(rom)
|
|
28
|
+
return Verification(ok=rom[COMPLEMENT_OFFSET] == expected, expected=(expected,), found=(rom[COMPLEMENT_OFFSET],))
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""The Mega Drive and 32X header checksum: the sum of every 16-bit word from 0x200 to the end of the image."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import struct
|
|
6
|
+
|
|
7
|
+
from ._checks import ByteString, Verification, require_length, require_writable
|
|
8
|
+
|
|
9
|
+
SUM_START = 0x200
|
|
10
|
+
CHECKSUM_OFFSET = 0x18E
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def compute_megadrive_checksum(rom: ByteString) -> int:
|
|
14
|
+
"""The big-endian 16-bit word sum of the image from 0x200, modulo 65536. A trailing odd byte is not counted."""
|
|
15
|
+
require_length(rom, SUM_START, "Mega Drive ROM")
|
|
16
|
+
words = (len(rom) - SUM_START) // 2
|
|
17
|
+
return sum(struct.unpack_from(f">{words}H", rom, SUM_START)) & 0xFFFF
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def fix_megadrive_checksum(rom: bytearray) -> int:
|
|
21
|
+
"""Write the checksum big-endian at 0x18E and return it."""
|
|
22
|
+
require_writable(rom)
|
|
23
|
+
checksum = compute_megadrive_checksum(rom)
|
|
24
|
+
struct.pack_into(">H", rom, CHECKSUM_OFFSET, checksum)
|
|
25
|
+
return checksum
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def verify_megadrive_checksum(rom: ByteString) -> Verification:
|
|
29
|
+
"""Compare the header's checksum word with the image's word sum."""
|
|
30
|
+
expected = compute_megadrive_checksum(rom)
|
|
31
|
+
(found,) = struct.unpack_from(">H", rom, CHECKSUM_OFFSET)
|
|
32
|
+
return Verification(ok=found == expected, expected=(expected,), found=(found,))
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Nintendo 64 header CRCs for the CIC-6102 boot code (and its 6101 sibling, which uses the same seed and formula)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import struct
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from ._checks import ByteString, Verification, require_length, require_writable
|
|
9
|
+
|
|
10
|
+
CRC_RANGE_START = 0x1000
|
|
11
|
+
CRC_RANGE_END = 0x101000
|
|
12
|
+
CRC1_OFFSET = 0x10
|
|
13
|
+
CRC2_OFFSET = 0x14
|
|
14
|
+
CIC_6102_SEED = 0xF8CA4DDC
|
|
15
|
+
|
|
16
|
+
_WORDS = (CRC_RANGE_END - CRC_RANGE_START) // 4
|
|
17
|
+
_MASK = 0xFFFFFFFF
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class N64Checksums:
|
|
22
|
+
"""The two header CRCs. ``skipped`` is set when ``preserve_zero_header`` left an all-zero header alone."""
|
|
23
|
+
|
|
24
|
+
crc1: int
|
|
25
|
+
crc2: int
|
|
26
|
+
skipped: bool = False
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def compute_n64_checksums(rom: ByteString) -> N64Checksums:
|
|
30
|
+
"""CRC1 and CRC2 of the 1 MiB at 0x1000, for CIC-6102. The image must reach 0x101000."""
|
|
31
|
+
require_length(rom, CRC_RANGE_END, "N64 ROM")
|
|
32
|
+
words = struct.unpack_from(f">{_WORDS}I", rom, CRC_RANGE_START)
|
|
33
|
+
t1 = t2 = t3 = t4 = t5 = t6 = CIC_6102_SEED
|
|
34
|
+
for d in words:
|
|
35
|
+
total = t6 + d
|
|
36
|
+
if total > _MASK:
|
|
37
|
+
t4 = (t4 + 1) & _MASK
|
|
38
|
+
t6 = total & _MASK
|
|
39
|
+
t3 ^= d
|
|
40
|
+
shift = d & 0x1F
|
|
41
|
+
rotated = ((d << shift) | (d >> (32 - shift))) & _MASK if shift else d
|
|
42
|
+
t5 = (t5 + rotated) & _MASK
|
|
43
|
+
if t2 > d:
|
|
44
|
+
t2 ^= rotated
|
|
45
|
+
else:
|
|
46
|
+
t2 ^= t6 ^ d
|
|
47
|
+
t1 = (t1 + (t5 ^ d)) & _MASK
|
|
48
|
+
return N64Checksums(crc1=t6 ^ t4 ^ t3, crc2=t5 ^ t2 ^ t1)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def fix_n64_checksums(rom: bytearray, *, preserve_zero_header: bool = False) -> N64Checksums:
|
|
52
|
+
"""Write CRC1 and CRC2 big-endian at 0x10 and 0x14 and return them.
|
|
53
|
+
|
|
54
|
+
With ``preserve_zero_header`` an image whose two header words are both zero is left as it is (some toolchains
|
|
55
|
+
leave them zero on purpose) and ``N64Checksums(0, 0, skipped=True)`` is returned.
|
|
56
|
+
"""
|
|
57
|
+
require_writable(rom)
|
|
58
|
+
require_length(rom, CRC_RANGE_END, "N64 ROM")
|
|
59
|
+
if preserve_zero_header and struct.unpack_from(">II", rom, CRC1_OFFSET) == (0, 0):
|
|
60
|
+
return N64Checksums(0, 0, skipped=True)
|
|
61
|
+
checksums = compute_n64_checksums(rom)
|
|
62
|
+
struct.pack_into(">II", rom, CRC1_OFFSET, checksums.crc1, checksums.crc2)
|
|
63
|
+
return checksums
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def verify_n64_checksums(rom: ByteString) -> Verification:
|
|
67
|
+
"""Compare the header's CRC1 and CRC2 with what the image's contents give."""
|
|
68
|
+
expected = compute_n64_checksums(rom)
|
|
69
|
+
found = struct.unpack_from(">II", rom, CRC1_OFFSET)
|
|
70
|
+
return Verification(ok=found == (expected.crc1, expected.crc2), expected=(expected.crc1, expected.crc2), found=found)
|
|
File without changes
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Synthetic ROM images for the tests. The bytes come from a fixed xorshift stream, so they are the same on every run."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import struct
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def stream(seed: int, size: int) -> bytearray:
|
|
9
|
+
"""``size`` pseudo-random bytes from a xorshift32 stream seeded with ``seed``."""
|
|
10
|
+
state = seed & 0xFFFFFFFF or 1
|
|
11
|
+
words = []
|
|
12
|
+
for _ in range((size + 3) // 4):
|
|
13
|
+
state ^= (state << 13) & 0xFFFFFFFF
|
|
14
|
+
state ^= state >> 17
|
|
15
|
+
state ^= (state << 5) & 0xFFFFFFFF
|
|
16
|
+
words.append(state)
|
|
17
|
+
return bytearray(struct.pack(f">{len(words)}I", *words)[:size])
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
N64_SIZE = 0x101000
|
|
21
|
+
|
|
22
|
+
# CRC1 and CRC2 of four images, as written by an independent implementation of the same algorithm: the JavaScript
|
|
23
|
+
# fixer this package was ported from, with its final combine corrected to XOR (see the README).
|
|
24
|
+
N64_GOLDEN = {
|
|
25
|
+
"stream-1": (stream(1, N64_SIZE), 0x4126D6C9, 0x1BB5D2FE),
|
|
26
|
+
"stream-7-longer": (stream(7, N64_SIZE + 0x2000), 0x77B0A014, 0x1DA127E4),
|
|
27
|
+
"zeros": (bytearray(N64_SIZE), 0xF8CA4DDC, 0x303A4DDC),
|
|
28
|
+
"ones": (bytearray(b"\xff" * N64_SIZE), 0xF8C24DDC, 0xC1544DDC),
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
MEGADRIVE_GOLDEN = {
|
|
32
|
+
"stream-3-odd-length": (stream(3, 0x1203), 0xF936),
|
|
33
|
+
"stream-4": (stream(4, 0x4000), 0x7BC4),
|
|
34
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import subprocess
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from uppercut_rom_headers import compute_gba_complement, compute_megadrive_checksum, compute_n64_checksums, main
|
|
7
|
+
from rom_images import N64_SIZE, stream
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_fix_then_verify_for_every_format(tmp_path, capsys):
|
|
11
|
+
images = {"n64": stream(1, N64_SIZE), "megadrive": stream(2, 0x1000), "gba": stream(3, 0x400)}
|
|
12
|
+
for name, image in images.items():
|
|
13
|
+
path = tmp_path / f"{name}.rom"
|
|
14
|
+
path.write_bytes(bytes(image))
|
|
15
|
+
assert main(["verify", name, str(path)]) == 1
|
|
16
|
+
assert main(["fix", name, str(path)]) == 0
|
|
17
|
+
assert main(["verify", name, str(path)]) == 0
|
|
18
|
+
out = capsys.readouterr()
|
|
19
|
+
assert out.out.count("PASS") == 3
|
|
20
|
+
assert out.err.count("FAIL") == 3
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_fix_writes_what_the_library_computes(tmp_path):
|
|
24
|
+
n64 = stream(4, N64_SIZE)
|
|
25
|
+
path = tmp_path / "game.n64"
|
|
26
|
+
path.write_bytes(bytes(n64))
|
|
27
|
+
main(["fix", "n64", str(path)])
|
|
28
|
+
expected = compute_n64_checksums(n64)
|
|
29
|
+
assert path.read_bytes()[0x10:0x18] == expected.crc1.to_bytes(4, "big") + expected.crc2.to_bytes(4, "big")
|
|
30
|
+
|
|
31
|
+
md = stream(5, 0x800)
|
|
32
|
+
path = tmp_path / "game.md"
|
|
33
|
+
path.write_bytes(bytes(md))
|
|
34
|
+
main(["fix", "megadrive", str(path)])
|
|
35
|
+
assert path.read_bytes()[0x18E:0x190] == compute_megadrive_checksum(md).to_bytes(2, "big")
|
|
36
|
+
|
|
37
|
+
gba = stream(6, 0x200)
|
|
38
|
+
path = tmp_path / "game.gba"
|
|
39
|
+
path.write_bytes(bytes(gba))
|
|
40
|
+
main(["fix", "gba", str(path)])
|
|
41
|
+
assert path.read_bytes()[0xBD] == compute_gba_complement(gba)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_verify_prints_expected_and_found(tmp_path, capsys):
|
|
45
|
+
path = tmp_path / "game.gba"
|
|
46
|
+
image = stream(7, 0xC0)
|
|
47
|
+
image[0xBD] = 0x00
|
|
48
|
+
path.write_bytes(bytes(image))
|
|
49
|
+
assert main(["verify", "gba", str(path)]) in (0, 1)
|
|
50
|
+
out = capsys.readouterr()
|
|
51
|
+
assert "gba header: expected 0x" in out.out + out.err
|
|
52
|
+
assert "found 0x00" in out.out + out.err
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_preserve_zero_header_leaves_the_file_untouched(tmp_path, capsys):
|
|
56
|
+
image = stream(8, N64_SIZE)
|
|
57
|
+
image[0x10:0x18] = bytes(8)
|
|
58
|
+
path = tmp_path / "zero.n64"
|
|
59
|
+
path.write_bytes(bytes(image))
|
|
60
|
+
assert main(["fix", "n64", str(path), "--preserve-zero-header"]) == 0
|
|
61
|
+
assert path.read_bytes() == bytes(image)
|
|
62
|
+
assert "left" in capsys.readouterr().out
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_a_missing_or_short_file_exits_2_and_changes_nothing(tmp_path, capsys):
|
|
66
|
+
assert main(["verify", "gba", str(tmp_path / "missing.gba")]) == 2
|
|
67
|
+
short = tmp_path / "short.n64"
|
|
68
|
+
short.write_bytes(b"abc")
|
|
69
|
+
assert main(["fix", "n64", str(short)]) == 2
|
|
70
|
+
assert short.read_bytes() == b"abc"
|
|
71
|
+
err = capsys.readouterr().err
|
|
72
|
+
assert "cannot read" in err
|
|
73
|
+
assert "too short" in err
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_python_dash_m_runs_the_command(tmp_path):
|
|
77
|
+
path = tmp_path / "game.gba"
|
|
78
|
+
path.write_bytes(bytes(stream(9, 0xC0)))
|
|
79
|
+
done = subprocess.run([sys.executable, "-m", "uppercut_rom_headers", "fix", "gba", str(path)], capture_output=True, text=True)
|
|
80
|
+
assert done.returncode == 0
|
|
81
|
+
assert "fixed gba header" in done.stdout
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_an_unknown_format_is_a_usage_error(tmp_path):
|
|
85
|
+
with pytest.raises(SystemExit) as raised:
|
|
86
|
+
main(["verify", "snes", str(tmp_path / "x")])
|
|
87
|
+
assert raised.value.code == 2
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from uppercut_rom_headers import RomHeaderError, compute_gba_complement, fix_gba_complement, verify_gba_complement
|
|
4
|
+
from rom_images import stream
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_the_complement_of_a_small_header():
|
|
8
|
+
rom = bytearray(0xC0)
|
|
9
|
+
rom[0xA0] = 0x10
|
|
10
|
+
rom[0xBC] = 0x05
|
|
11
|
+
assert fix_gba_complement(rom) == (-0x10 - 0x05 - 0x19) & 0xFF
|
|
12
|
+
assert rom[0xBD] == (-0x10 - 0x05 - 0x19) & 0xFF
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_the_bios_rule_holds_after_a_fix():
|
|
16
|
+
for seed in range(1, 40):
|
|
17
|
+
rom = stream(seed, 0x200)
|
|
18
|
+
fix_gba_complement(rom)
|
|
19
|
+
assert (sum(rom[0xA0:0xBE]) + 0x19) & 0xFF == 0
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_only_bytes_0xa0_to_0xbc_matter():
|
|
23
|
+
rom = stream(3, 0x400)
|
|
24
|
+
expected = compute_gba_complement(rom)
|
|
25
|
+
for offset in (0, 0x9F, 0xBD, 0xBE, 0xBF, 0xC0, 0x3FF):
|
|
26
|
+
changed = bytearray(rom)
|
|
27
|
+
changed[offset] ^= 0xFF
|
|
28
|
+
assert compute_gba_complement(changed) == expected
|
|
29
|
+
for offset in (0xA0, 0xAC, 0xBC):
|
|
30
|
+
changed = bytearray(rom)
|
|
31
|
+
changed[offset] ^= 0x01
|
|
32
|
+
assert compute_gba_complement(changed) != expected
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_fix_changes_only_the_complement_byte_and_is_idempotent():
|
|
36
|
+
original = stream(4, 0x300)
|
|
37
|
+
rom = bytearray(original)
|
|
38
|
+
value = fix_gba_complement(rom)
|
|
39
|
+
assert [i for i in range(len(rom)) if rom[i] != original[i]] in ([], [0xBD])
|
|
40
|
+
assert fix_gba_complement(rom) == value
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_verify_reports_expected_and_found():
|
|
44
|
+
rom = stream(5, 0xC0)
|
|
45
|
+
rom[0xBD] = (compute_gba_complement(rom) + 1) & 0xFF
|
|
46
|
+
bad = verify_gba_complement(rom)
|
|
47
|
+
assert bad.ok is False
|
|
48
|
+
assert bad.found == (rom[0xBD],)
|
|
49
|
+
fix_gba_complement(rom)
|
|
50
|
+
assert verify_gba_complement(rom).ok is True
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_agrees_with_uppercut_gba_rom_verify_when_it_is_installed():
|
|
54
|
+
verify = pytest.importorskip("uppercut_gba_rom_verify")
|
|
55
|
+
for seed in range(1, 60):
|
|
56
|
+
rom = stream(seed, 0xC0 + seed)
|
|
57
|
+
assert compute_gba_complement(rom) == verify.calculate_header_complement(bytes(rom))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_a_shorter_header_or_a_read_only_buffer_is_refused():
|
|
61
|
+
with pytest.raises(RomHeaderError, match="too short"):
|
|
62
|
+
compute_gba_complement(bytes(0xBF))
|
|
63
|
+
with pytest.raises(RomHeaderError, match="bytearray"):
|
|
64
|
+
fix_gba_complement(bytes(0xC0)) # type: ignore[arg-type]
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
from uppercut_rom_headers import RomHeaderError, compute_megadrive_checksum, fix_megadrive_checksum, verify_megadrive_checksum
|
|
4
|
+
from rom_images import MEGADRIVE_GOLDEN, stream
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_adds_the_big_endian_words_from_0x200():
|
|
8
|
+
rom = bytearray(0x400)
|
|
9
|
+
rom[0x200:0x204] = bytes.fromhex("12340002")
|
|
10
|
+
assert fix_megadrive_checksum(rom) == 0x1236
|
|
11
|
+
assert rom[0x18E:0x190] == bytes.fromhex("1236")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.mark.parametrize("name", sorted(MEGADRIVE_GOLDEN))
|
|
15
|
+
def test_matches_the_independent_implementation(name):
|
|
16
|
+
image, expected = MEGADRIVE_GOLDEN[name]
|
|
17
|
+
assert compute_megadrive_checksum(image) == expected
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_a_trailing_odd_byte_is_not_counted():
|
|
21
|
+
even = bytearray(0x202)
|
|
22
|
+
even[0x200:0x202] = bytes.fromhex("0102")
|
|
23
|
+
odd = bytearray(even) + b"\xff"
|
|
24
|
+
assert compute_megadrive_checksum(even) == compute_megadrive_checksum(odd) == 0x0102
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_the_sum_wraps_at_16_bits():
|
|
28
|
+
rom = bytearray(b"\xff" * (0x200 + 4))
|
|
29
|
+
assert compute_megadrive_checksum(rom) == 0xFFFE
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_the_header_before_0x200_is_not_summed_and_the_checksum_word_does_not_feed_itself():
|
|
33
|
+
rom = stream(10, 0x800)
|
|
34
|
+
expected = compute_megadrive_checksum(rom)
|
|
35
|
+
for offset in (0, 0x100, 0x18E, 0x18F, 0x1FF):
|
|
36
|
+
changed = bytearray(rom)
|
|
37
|
+
changed[offset] ^= 0xFF
|
|
38
|
+
assert compute_megadrive_checksum(changed) == expected
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_fix_changes_only_the_two_checksum_bytes_and_is_idempotent():
|
|
42
|
+
original = stream(11, 0x1000)
|
|
43
|
+
rom = bytearray(original)
|
|
44
|
+
value = fix_megadrive_checksum(rom)
|
|
45
|
+
assert [i for i in range(len(rom)) if rom[i] != original[i]] == [i for i in (0x18E, 0x18F) if original[i] != rom[i]]
|
|
46
|
+
assert fix_megadrive_checksum(rom) == value
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_verify_reports_expected_and_found():
|
|
50
|
+
rom = stream(12, 0x1000)
|
|
51
|
+
before = verify_megadrive_checksum(rom)
|
|
52
|
+
assert before.ok is False
|
|
53
|
+
fix_megadrive_checksum(rom)
|
|
54
|
+
after = verify_megadrive_checksum(rom)
|
|
55
|
+
assert after.ok is True
|
|
56
|
+
assert after.expected == after.found == before.expected
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_the_smallest_image_is_0x200_bytes_and_sums_to_zero():
|
|
60
|
+
rom = bytearray(0x200)
|
|
61
|
+
assert fix_megadrive_checksum(rom) == 0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_a_shorter_image_or_a_read_only_buffer_is_refused():
|
|
65
|
+
with pytest.raises(RomHeaderError, match="too short"):
|
|
66
|
+
compute_megadrive_checksum(bytes(0x1FF))
|
|
67
|
+
with pytest.raises(RomHeaderError, match="bytearray"):
|
|
68
|
+
fix_megadrive_checksum(bytes(0x400)) # type: ignore[arg-type]
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import struct
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from uppercut_rom_headers import RomHeaderError, compute_n64_checksums, fix_n64_checksums, verify_n64_checksums
|
|
6
|
+
from rom_images import N64_GOLDEN, N64_SIZE, stream
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@pytest.mark.parametrize("name", sorted(N64_GOLDEN))
|
|
10
|
+
def test_matches_the_independent_implementation(name):
|
|
11
|
+
image, crc1, crc2 = N64_GOLDEN[name]
|
|
12
|
+
result = compute_n64_checksums(image)
|
|
13
|
+
assert (result.crc1, result.crc2) == (crc1, crc2)
|
|
14
|
+
assert result.skipped is False
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_compute_leaves_the_image_alone_and_accepts_any_byte_buffer():
|
|
18
|
+
image = stream(5, N64_SIZE)
|
|
19
|
+
before = bytes(image)
|
|
20
|
+
from_bytearray = compute_n64_checksums(image)
|
|
21
|
+
assert bytes(image) == before
|
|
22
|
+
assert compute_n64_checksums(bytes(image)) == from_bytearray
|
|
23
|
+
assert compute_n64_checksums(memoryview(image)) == from_bytearray
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_fix_writes_both_crcs_big_endian_at_0x10_and_0x14():
|
|
27
|
+
image = stream(1, N64_SIZE)
|
|
28
|
+
result = fix_n64_checksums(image)
|
|
29
|
+
assert image[0x10:0x18] == bytes.fromhex("4126d6c91bb5d2fe")
|
|
30
|
+
assert (result.crc1, result.crc2) == (0x4126D6C9, 0x1BB5D2FE)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_fix_changes_only_the_eight_header_bytes_and_is_idempotent():
|
|
34
|
+
original = stream(2, N64_SIZE)
|
|
35
|
+
image = bytearray(original)
|
|
36
|
+
first = fix_n64_checksums(image)
|
|
37
|
+
changed = [offset for offset in range(len(image)) if image[offset] != original[offset]]
|
|
38
|
+
assert all(0x10 <= offset < 0x18 for offset in changed)
|
|
39
|
+
assert fix_n64_checksums(image) == first
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_the_checksum_ignores_its_own_header_words_and_everything_outside_the_range():
|
|
43
|
+
image = stream(3, N64_SIZE + 64)
|
|
44
|
+
expected = compute_n64_checksums(image)
|
|
45
|
+
for offset in (0x10, 0x17, 0x20, 0xFFF, N64_SIZE, N64_SIZE + 63):
|
|
46
|
+
changed = bytearray(image)
|
|
47
|
+
changed[offset] ^= 0xFF
|
|
48
|
+
assert compute_n64_checksums(changed) == expected, hex(offset)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@pytest.mark.parametrize("offset", [0x1000, 0x1003, 0x80000, N64_SIZE - 1])
|
|
52
|
+
def test_a_change_inside_the_range_changes_the_checksum(offset):
|
|
53
|
+
image = stream(4, N64_SIZE)
|
|
54
|
+
expected = compute_n64_checksums(image)
|
|
55
|
+
changed = bytearray(image)
|
|
56
|
+
changed[offset] ^= 0x01
|
|
57
|
+
assert compute_n64_checksums(changed) != expected
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_verify_passes_after_fix_and_reports_both_values_when_it_does_not():
|
|
61
|
+
image = stream(6, N64_SIZE)
|
|
62
|
+
before = verify_n64_checksums(image)
|
|
63
|
+
assert before.ok is False
|
|
64
|
+
assert before.found == struct.unpack_from(">II", image, 0x10)
|
|
65
|
+
fix_n64_checksums(image)
|
|
66
|
+
after = verify_n64_checksums(image)
|
|
67
|
+
assert after.ok is True
|
|
68
|
+
assert after.expected == after.found == before.expected
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_verify_detects_one_wrong_word():
|
|
72
|
+
image = stream(6, N64_SIZE)
|
|
73
|
+
fix_n64_checksums(image)
|
|
74
|
+
image[0x17] ^= 0x01
|
|
75
|
+
result = verify_n64_checksums(image)
|
|
76
|
+
assert result.ok is False
|
|
77
|
+
assert result.expected[0] == result.found[0]
|
|
78
|
+
assert result.expected[1] != result.found[1]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_preserve_zero_header_leaves_an_all_zero_header_alone():
|
|
82
|
+
image = stream(8, N64_SIZE)
|
|
83
|
+
image[0x10:0x18] = bytes(8)
|
|
84
|
+
before = bytes(image)
|
|
85
|
+
result = fix_n64_checksums(image, preserve_zero_header=True)
|
|
86
|
+
assert (result.crc1, result.crc2, result.skipped) == (0, 0, True)
|
|
87
|
+
assert bytes(image) == before
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_preserve_zero_header_still_fixes_anything_else():
|
|
91
|
+
half = stream(8, N64_SIZE)
|
|
92
|
+
half[0x10:0x18] = bytes([0, 0, 0, 0, 0, 0, 0, 1])
|
|
93
|
+
assert fix_n64_checksums(half, preserve_zero_header=True).skipped is False
|
|
94
|
+
assert verify_n64_checksums(half).ok
|
|
95
|
+
|
|
96
|
+
nonzero = stream(9, N64_SIZE)
|
|
97
|
+
assert fix_n64_checksums(nonzero, preserve_zero_header=True).skipped is False
|
|
98
|
+
assert verify_n64_checksums(nonzero).ok
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_without_the_option_a_zero_header_is_fixed():
|
|
102
|
+
image = stream(8, N64_SIZE)
|
|
103
|
+
image[0x10:0x18] = bytes(8)
|
|
104
|
+
assert fix_n64_checksums(image).skipped is False
|
|
105
|
+
assert verify_n64_checksums(image).ok
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_an_image_shorter_than_the_range_is_refused():
|
|
109
|
+
for size in (0, 0x1000, N64_SIZE - 1):
|
|
110
|
+
with pytest.raises(RomHeaderError, match="too short"):
|
|
111
|
+
compute_n64_checksums(bytes(size))
|
|
112
|
+
with pytest.raises(RomHeaderError, match="too short"):
|
|
113
|
+
fix_n64_checksums(bytearray(size))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def test_fix_needs_a_writable_bytearray():
|
|
117
|
+
with pytest.raises(RomHeaderError, match="bytearray"):
|
|
118
|
+
fix_n64_checksums(bytes(N64_SIZE)) # type: ignore[arg-type]
|
|
119
|
+
with pytest.raises(RomHeaderError, match="bytes, bytearray or memoryview"):
|
|
120
|
+
compute_n64_checksums("not bytes") # type: ignore[arg-type]
|