uppercut-ps2-match 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.
Files changed (30) hide show
  1. uppercut_ps2_match-1.0.0/.gitignore +16 -0
  2. uppercut_ps2_match-1.0.0/LICENSE +21 -0
  3. uppercut_ps2_match-1.0.0/PKG-INFO +155 -0
  4. uppercut_ps2_match-1.0.0/README.md +132 -0
  5. uppercut_ps2_match-1.0.0/pyproject.toml +39 -0
  6. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/__init__.py +18 -0
  7. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/__main__.py +5 -0
  8. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/asmtu.py +107 -0
  9. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/audit.py +248 -0
  10. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/cli.py +123 -0
  11. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/config.py +103 -0
  12. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/csplit.py +121 -0
  13. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/datafrag.py +271 -0
  14. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/elf32.py +169 -0
  15. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/errors.py +19 -0
  16. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/fetch.py +177 -0
  17. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/mips.py +81 -0
  18. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/py.typed +0 -0
  19. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/symbols.py +62 -0
  20. uppercut_ps2_match-1.0.0/src/uppercut_ps2_match/verify.py +449 -0
  21. uppercut_ps2_match-1.0.0/tests/conftest.py +6 -0
  22. uppercut_ps2_match-1.0.0/tests/fake_tool.py +111 -0
  23. uppercut_ps2_match-1.0.0/tests/ps2_support.py +320 -0
  24. uppercut_ps2_match-1.0.0/tests/test_audit.py +167 -0
  25. uppercut_ps2_match-1.0.0/tests/test_cli.py +84 -0
  26. uppercut_ps2_match-1.0.0/tests/test_csplit_asmtu.py +111 -0
  27. uppercut_ps2_match-1.0.0/tests/test_datafrag.py +84 -0
  28. uppercut_ps2_match-1.0.0/tests/test_elf_mips_symbols.py +104 -0
  29. uppercut_ps2_match-1.0.0/tests/test_fetch.py +147 -0
  30. uppercut_ps2_match-1.0.0/tests/test_verify.py +236 -0
@@ -0,0 +1,16 @@
1
+ node_modules/
2
+ dist/
3
+ dist-pack/
4
+ *.tgz
5
+ coverage/
6
+ build/
7
+ build-*/
8
+ *.tar.gz
9
+ .venv/
10
+ __pycache__/
11
+ *.egg-info/
12
+ .pytest_cache/
13
+ uv.lock
14
+ .DS_Store
15
+ .env*
16
+ *.pem
@@ -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,155 @@
1
+ Metadata-Version: 2.5
2
+ Name: uppercut-ps2-match
3
+ Version: 1.0.0
4
+ Summary: Tooling for a PlayStation 2 matching decompilation: compile one function at a time and check its bytes against the original, place data pieces, split C files, fetch a toolchain by SHA-256 pins, audit a public repo.
5
+ Project-URL: Source, https://github.com/uppercut-labs/game-kit/tree/main/packages/uppercut-ps2-match
6
+ Author-email: Uppercut Labs <packages@uppercut-labs.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: decompilation,elf,matching,mips,playstation-2,ps2,r5900,splat
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: Topic :: Software Development :: Disassemblers
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+
24
+ # uppercut-ps2-match
25
+
26
+ Tooling for a PlayStation 2 matching decompilation. It compiles one C file at a time with the compiler you give it, links each function at its original address, and says whether the bytes equal the original's. Around that sit the pieces a matching project keeps rewriting: data-fragment placement, a C file splitter, assembly helpers for splat output, a toolchain fetch pinned by SHA-256, and an audit that a public repository holds no game data. Standard library only.
27
+
28
+ It ships tools only. No compiler or SDK binaries, no game code or data, no SDK headers. Where the compiler comes from, its URLs and its hashes are your configuration.
29
+
30
+ ```sh
31
+ pip install uppercut-ps2-match
32
+ ```
33
+
34
+ ## Commands
35
+
36
+ ```sh
37
+ uppercut-ps2-match verify verify.json src/main/foo.c --work build/verify
38
+ uppercut-ps2-match csplit src/main/foo.c
39
+ uppercut-ps2-match fetch toolchain.json --dest tools/ [--host linux-x86-64] [--dry-run]
40
+ uppercut-ps2-match audit --root . [--config audit.json] [--publish] [--extra DIR=PREFIX] [--out audit.md]
41
+ ```
42
+
43
+ `verify` exits 0 when every function of every file matches, 1 when one does not, and 2 for a usage or configuration error. `audit` exits 1 when any file is a finding. `python -m uppercut_ps2_match` runs the same commands.
44
+
45
+ ## verify
46
+
47
+ For each C file the verifier preprocesses and compiles it, assembles the result, links every function section at its address in the original, and compares. A function matches when its bytes equal the original's and the original's remaining bytes up to the next function are zero padding. The report per function:
48
+
49
+ ```json
50
+ {"name": "f", "addr": "0x100000", "size": 16, "orig_size": 32, "diff_words": 0, "padding_ok": true,
51
+ "data": {".rodata.F0": "0x300010+4"}, "data_ok": true, "status": "match"}
52
+ ```
53
+
54
+ `status` is `match`, `mismatch` or `no-address` (the function has no address in your symbols). A file that does not compile or link gives one `compile-error` or `link-error` result with the tools' output.
55
+
56
+ Data a function uses (literals, switch tables, statics, common variables, externs with no address) is not given addresses by hand. Each is first linked at a probe address, and the original's instructions that refer to it (the same `lui`/`%lo`, `$gp`-relative or `jal` instruction in both builds) say where it really sits. `datafrag` gives every data label its own section so each piece is placed by itself, and data that only other data points at (a table of strings) is solved through those pointers. `data_ok` says whether the object's own initialised data equals the original where it was placed; it is reported, not required for a match.
57
+
58
+ ### Configuration
59
+
60
+ ```json
61
+ {
62
+ "image": "original/main.elf",
63
+ "symbols": ["config/symbol_addrs.txt"],
64
+ "symbols_from_elf": false,
65
+ "function_symbols": [],
66
+ "gp": "0x5d2a70",
67
+ "include_dir": "include",
68
+ "defines": "-DVERSION_A",
69
+ "flags": "-O2 -G8",
70
+ "fragments": true,
71
+ "toolchain": {
72
+ "cpp": "/path/to/cpp -lang-c -Iinclude",
73
+ "cc1": "/path/to/cc1 -quiet -ffunction-sections",
74
+ "assembler": "/path/to/as -EL -mabi=eabi",
75
+ "linker": ["/path/to/ld", "-EL"],
76
+ "runner": ["env"],
77
+ "path_map": []
78
+ }
79
+ }
80
+ ```
81
+
82
+ Relative paths are taken from the file's folder. `symbols` are splat-style `name = 0xADDR;` files, read in order (the first address of a name wins). With `symbols_from_elf`, the image's own symbol table is read first, and the `function_symbols` files add only the lines whose comment says `type:func`. The three compiler commands are strings run with `sh -c` in the folder of the compile, through `runner` (`["docker", "exec", "box"]`, a qemu wrapper, or the default `env` for a compiler that runs here). `path_map` translates host folders into the runner's, as `[host prefix, runner prefix]` pairs. The linker runs on the host.
83
+
84
+ ### Python
85
+
86
+ ```python
87
+ from uppercut_ps2_match import Toolchain, Verifier, read_symbol_file
88
+
89
+ tc = Toolchain(cpp="...", cc1="...", assembler="...", linker=["ld", "-EL"])
90
+ verifier = Verifier("original/main.elf", read_symbol_file("symbol_addrs.txt"), tc, gp=0x5D2A70, include_dir="include")
91
+ for result in verifier.check("src/foo.c", "build/verify/foo", "-O2 -G8"):
92
+ print(result["name"], result["status"])
93
+ ```
94
+
95
+ `check(..., prefer=(lo, hi))` resolves a function name that appears at several addresses (file statics) to the one in that range.
96
+
97
+ ## Pieces
98
+
99
+ | Module | What it does |
100
+ | --- | --- |
101
+ | `elf32` | A dependency-free reader for 32-bit little-endian ELF: sections, symbols, `REL` relocations, program headers (`Elf`, `Image.bytes_at`). |
102
+ | `mips` | `refs(words, base, gp)`: the addresses a function builds (`lui` + offset, `$gp`-relative, `jal`/`j`). |
103
+ | `datafrag` | `split(asm)`: cut compiler assembly at every data label, one section per label; `code_shape(object)`: the instruction stream with relocated fields masked. |
104
+ | `csplit` | `split(text)`: a C file into its prelude and its function definitions; `data_definition`, `prototype`. |
105
+ | `symbols` | Read splat symbol files and an ELF symbol table; function starts and repeated names. |
106
+ | `asmtu` | Helpers for splat assembly: VU0 macro lines to `.word`, drop matched functions from a translation unit, strip attributes and `static`. |
107
+ | `fetch` | `load_packages`, `fetch_toolchain`: download, check every SHA-256, unpack safely. |
108
+ | `audit` | `AuditConfig`, `audit_tree`: find binaries, assets, disc images, disassembly and compiler dumps. |
109
+
110
+ ## fetch
111
+
112
+ A toolchain is a JSON file you keep with your project. This package contains no addresses and no hashes of its own.
113
+
114
+ ```json
115
+ {
116
+ "packages": [
117
+ {"name": "compiler", "url": "https://example.invalid/compiler.tar.xz", "sha256": "<archive digest>",
118
+ "files": {"lib/cc1": "<digest of the file the build runs>", "bin/as": "<digest>"}},
119
+ {"name": "binutils", "hosts": {"linux-x86-64": {"url": "...", "sha256": "..."}, "macos-arm64": {"url": "...", "sha256": "..."}}}
120
+ ]
121
+ }
122
+ ```
123
+
124
+ Each archive is checked against its SHA-256 before it is unpacked, and each file named in `files` after. A package is moved into place only when both pass, so a mismatch leaves nothing of it behind. An archive holding a link or a path outside its folder is refused. A package already in the destination is checked and left alone. `--dry-run` prints the plan and downloads nothing.
125
+
126
+ ## audit
127
+
128
+ Checks every file (git's tracked and untracked-but-not-ignored files in a checkout, or every file of a plain folder) for binaries, assets by type, logos and artwork, assembly and disassembly listings, `INCLUDE_ASM`, long C initialisers and base64 runs, and compiler dumps. Screenshots (a PNG, JPEG or WebP under `screenshots/`, at most 2 MB, not named like artwork) are listed and allowed. A file of your own that trips a check and is not game data goes in `known` with its SHA-256:
129
+
130
+ ```json
131
+ {
132
+ "known": {"assets/ui.ttf": ["<sha256>", "our own UI font"]},
133
+ "publish": ["src/", "include/", "README.md"],
134
+ "publish_exclude": [],
135
+ "screenshot_dir": "screenshots",
136
+ "screenshot_max": 2097152,
137
+ "max_literals": 1024,
138
+ "table_extension": ".tbl",
139
+ "table_row": "^[0-9]+ [A-Za-z_0-9]+$"
140
+ }
141
+ ```
142
+
143
+ `publish` limits the first root to the paths you intend to publish (a path ending in `/` is a folder). `table_extension` and `table_row` check a generator table: every line must match the row pattern.
144
+
145
+ ## Not included
146
+
147
+ - The build driver of a particular project (the `main`/data object steps, splat configuration, progress stamps). Those hold project names and layouts; this package is the part that does not.
148
+ - A compiler, an assembler, a linker or any SDK header. Bring your own.
149
+ - Tests against a real EE-GCC or on Windows: the tests use synthetic object files and stand-in `cpp`, `cc1`, `as` and `ld` programs (`tests/fake_tool.py`), so they run anywhere. The command-running code is plain `subprocess` on a `sh -c` string, which needs a POSIX `sh` on the host or in the runner.
150
+
151
+ ## Tests
152
+
153
+ ```sh
154
+ uv sync --all-packages && uv run pytest packages/uppercut-ps2-match
155
+ ```
@@ -0,0 +1,132 @@
1
+ # uppercut-ps2-match
2
+
3
+ Tooling for a PlayStation 2 matching decompilation. It compiles one C file at a time with the compiler you give it, links each function at its original address, and says whether the bytes equal the original's. Around that sit the pieces a matching project keeps rewriting: data-fragment placement, a C file splitter, assembly helpers for splat output, a toolchain fetch pinned by SHA-256, and an audit that a public repository holds no game data. Standard library only.
4
+
5
+ It ships tools only. No compiler or SDK binaries, no game code or data, no SDK headers. Where the compiler comes from, its URLs and its hashes are your configuration.
6
+
7
+ ```sh
8
+ pip install uppercut-ps2-match
9
+ ```
10
+
11
+ ## Commands
12
+
13
+ ```sh
14
+ uppercut-ps2-match verify verify.json src/main/foo.c --work build/verify
15
+ uppercut-ps2-match csplit src/main/foo.c
16
+ uppercut-ps2-match fetch toolchain.json --dest tools/ [--host linux-x86-64] [--dry-run]
17
+ uppercut-ps2-match audit --root . [--config audit.json] [--publish] [--extra DIR=PREFIX] [--out audit.md]
18
+ ```
19
+
20
+ `verify` exits 0 when every function of every file matches, 1 when one does not, and 2 for a usage or configuration error. `audit` exits 1 when any file is a finding. `python -m uppercut_ps2_match` runs the same commands.
21
+
22
+ ## verify
23
+
24
+ For each C file the verifier preprocesses and compiles it, assembles the result, links every function section at its address in the original, and compares. A function matches when its bytes equal the original's and the original's remaining bytes up to the next function are zero padding. The report per function:
25
+
26
+ ```json
27
+ {"name": "f", "addr": "0x100000", "size": 16, "orig_size": 32, "diff_words": 0, "padding_ok": true,
28
+ "data": {".rodata.F0": "0x300010+4"}, "data_ok": true, "status": "match"}
29
+ ```
30
+
31
+ `status` is `match`, `mismatch` or `no-address` (the function has no address in your symbols). A file that does not compile or link gives one `compile-error` or `link-error` result with the tools' output.
32
+
33
+ Data a function uses (literals, switch tables, statics, common variables, externs with no address) is not given addresses by hand. Each is first linked at a probe address, and the original's instructions that refer to it (the same `lui`/`%lo`, `$gp`-relative or `jal` instruction in both builds) say where it really sits. `datafrag` gives every data label its own section so each piece is placed by itself, and data that only other data points at (a table of strings) is solved through those pointers. `data_ok` says whether the object's own initialised data equals the original where it was placed; it is reported, not required for a match.
34
+
35
+ ### Configuration
36
+
37
+ ```json
38
+ {
39
+ "image": "original/main.elf",
40
+ "symbols": ["config/symbol_addrs.txt"],
41
+ "symbols_from_elf": false,
42
+ "function_symbols": [],
43
+ "gp": "0x5d2a70",
44
+ "include_dir": "include",
45
+ "defines": "-DVERSION_A",
46
+ "flags": "-O2 -G8",
47
+ "fragments": true,
48
+ "toolchain": {
49
+ "cpp": "/path/to/cpp -lang-c -Iinclude",
50
+ "cc1": "/path/to/cc1 -quiet -ffunction-sections",
51
+ "assembler": "/path/to/as -EL -mabi=eabi",
52
+ "linker": ["/path/to/ld", "-EL"],
53
+ "runner": ["env"],
54
+ "path_map": []
55
+ }
56
+ }
57
+ ```
58
+
59
+ Relative paths are taken from the file's folder. `symbols` are splat-style `name = 0xADDR;` files, read in order (the first address of a name wins). With `symbols_from_elf`, the image's own symbol table is read first, and the `function_symbols` files add only the lines whose comment says `type:func`. The three compiler commands are strings run with `sh -c` in the folder of the compile, through `runner` (`["docker", "exec", "box"]`, a qemu wrapper, or the default `env` for a compiler that runs here). `path_map` translates host folders into the runner's, as `[host prefix, runner prefix]` pairs. The linker runs on the host.
60
+
61
+ ### Python
62
+
63
+ ```python
64
+ from uppercut_ps2_match import Toolchain, Verifier, read_symbol_file
65
+
66
+ tc = Toolchain(cpp="...", cc1="...", assembler="...", linker=["ld", "-EL"])
67
+ verifier = Verifier("original/main.elf", read_symbol_file("symbol_addrs.txt"), tc, gp=0x5D2A70, include_dir="include")
68
+ for result in verifier.check("src/foo.c", "build/verify/foo", "-O2 -G8"):
69
+ print(result["name"], result["status"])
70
+ ```
71
+
72
+ `check(..., prefer=(lo, hi))` resolves a function name that appears at several addresses (file statics) to the one in that range.
73
+
74
+ ## Pieces
75
+
76
+ | Module | What it does |
77
+ | --- | --- |
78
+ | `elf32` | A dependency-free reader for 32-bit little-endian ELF: sections, symbols, `REL` relocations, program headers (`Elf`, `Image.bytes_at`). |
79
+ | `mips` | `refs(words, base, gp)`: the addresses a function builds (`lui` + offset, `$gp`-relative, `jal`/`j`). |
80
+ | `datafrag` | `split(asm)`: cut compiler assembly at every data label, one section per label; `code_shape(object)`: the instruction stream with relocated fields masked. |
81
+ | `csplit` | `split(text)`: a C file into its prelude and its function definitions; `data_definition`, `prototype`. |
82
+ | `symbols` | Read splat symbol files and an ELF symbol table; function starts and repeated names. |
83
+ | `asmtu` | Helpers for splat assembly: VU0 macro lines to `.word`, drop matched functions from a translation unit, strip attributes and `static`. |
84
+ | `fetch` | `load_packages`, `fetch_toolchain`: download, check every SHA-256, unpack safely. |
85
+ | `audit` | `AuditConfig`, `audit_tree`: find binaries, assets, disc images, disassembly and compiler dumps. |
86
+
87
+ ## fetch
88
+
89
+ A toolchain is a JSON file you keep with your project. This package contains no addresses and no hashes of its own.
90
+
91
+ ```json
92
+ {
93
+ "packages": [
94
+ {"name": "compiler", "url": "https://example.invalid/compiler.tar.xz", "sha256": "<archive digest>",
95
+ "files": {"lib/cc1": "<digest of the file the build runs>", "bin/as": "<digest>"}},
96
+ {"name": "binutils", "hosts": {"linux-x86-64": {"url": "...", "sha256": "..."}, "macos-arm64": {"url": "...", "sha256": "..."}}}
97
+ ]
98
+ }
99
+ ```
100
+
101
+ Each archive is checked against its SHA-256 before it is unpacked, and each file named in `files` after. A package is moved into place only when both pass, so a mismatch leaves nothing of it behind. An archive holding a link or a path outside its folder is refused. A package already in the destination is checked and left alone. `--dry-run` prints the plan and downloads nothing.
102
+
103
+ ## audit
104
+
105
+ Checks every file (git's tracked and untracked-but-not-ignored files in a checkout, or every file of a plain folder) for binaries, assets by type, logos and artwork, assembly and disassembly listings, `INCLUDE_ASM`, long C initialisers and base64 runs, and compiler dumps. Screenshots (a PNG, JPEG or WebP under `screenshots/`, at most 2 MB, not named like artwork) are listed and allowed. A file of your own that trips a check and is not game data goes in `known` with its SHA-256:
106
+
107
+ ```json
108
+ {
109
+ "known": {"assets/ui.ttf": ["<sha256>", "our own UI font"]},
110
+ "publish": ["src/", "include/", "README.md"],
111
+ "publish_exclude": [],
112
+ "screenshot_dir": "screenshots",
113
+ "screenshot_max": 2097152,
114
+ "max_literals": 1024,
115
+ "table_extension": ".tbl",
116
+ "table_row": "^[0-9]+ [A-Za-z_0-9]+$"
117
+ }
118
+ ```
119
+
120
+ `publish` limits the first root to the paths you intend to publish (a path ending in `/` is a folder). `table_extension` and `table_row` check a generator table: every line must match the row pattern.
121
+
122
+ ## Not included
123
+
124
+ - The build driver of a particular project (the `main`/data object steps, splat configuration, progress stamps). Those hold project names and layouts; this package is the part that does not.
125
+ - A compiler, an assembler, a linker or any SDK header. Bring your own.
126
+ - Tests against a real EE-GCC or on Windows: the tests use synthetic object files and stand-in `cpp`, `cc1`, `as` and `ld` programs (`tests/fake_tool.py`), so they run anywhere. The command-running code is plain `subprocess` on a `sh -c` string, which needs a POSIX `sh` on the host or in the runner.
127
+
128
+ ## Tests
129
+
130
+ ```sh
131
+ uv sync --all-packages && uv run pytest packages/uppercut-ps2-match
132
+ ```
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "uppercut-ps2-match"
7
+ version = "1.0.0"
8
+ description = "Tooling for a PlayStation 2 matching decompilation: compile one function at a time and check its bytes against the original, place data pieces, split C files, fetch a toolchain by SHA-256 pins, audit a public repo."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
13
+ keywords = ["ps2", "playstation-2", "decompilation", "matching", "mips", "r5900", "elf", "splat"]
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
+ "Topic :: Software Development :: Disassemblers",
26
+ "Typing :: Typed",
27
+ ]
28
+
29
+ [project.scripts]
30
+ uppercut-ps2-match = "uppercut_ps2_match.cli:main"
31
+
32
+ [project.urls]
33
+ Source = "https://github.com/uppercut-labs/game-kit/tree/main/packages/uppercut-ps2-match"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["src/uppercut_ps2_match"]
37
+
38
+ [tool.hatch.build.targets.sdist]
39
+ include = ["src", "tests", "README.md"]
@@ -0,0 +1,18 @@
1
+ """Tooling for a PlayStation 2 matching decompilation."""
2
+
3
+ __version__ = "1.0.0"
4
+
5
+ from . import asmtu, csplit, datafrag, mips, symbols # noqa: E402
6
+ from .audit import AuditConfig, AuditReport, audit_file, audit_tree # noqa: E402
7
+ from .config import VerifyConfig, load_verify_config, parse_toolchain # noqa: E402
8
+ from .elf32 import Elf, Image # noqa: E402
9
+ from .errors import ConfigError, ElfError, FetchError, MatchError # noqa: E402
10
+ from .fetch import Package, fetch_toolchain, load_packages # noqa: E402
11
+ from .symbols import read_symbol_file, symbols_from_elf # noqa: E402
12
+ from .verify import ObjectInfo, Toolchain, Verifier # noqa: E402
13
+
14
+ __all__ = [
15
+ "AuditConfig", "AuditReport", "ConfigError", "Elf", "ElfError", "FetchError", "Image", "MatchError", "ObjectInfo", "Package",
16
+ "Toolchain", "Verifier", "VerifyConfig", "asmtu", "audit_file", "audit_tree", "csplit", "datafrag", "fetch_toolchain",
17
+ "load_packages", "load_verify_config", "mips", "parse_toolchain", "read_symbol_file", "symbols", "symbols_from_elf",
18
+ ]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,107 @@
1
+ """Helpers for the assembly a splat project writes: one file per translation unit, with a `nonmatching` line before each function.
2
+
3
+ `split_tu` takes the functions you have matched out of a unit's assembly, so the rest can still be assembled and linked around
4
+ the C you compiled. These work on text: they run no tool.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from pathlib import Path
11
+ from typing import Any, List, Sequence, Set, Tuple
12
+
13
+ COP2_LINE = re.compile(r"^(\s*/\* [0-9A-F]+ [0-9A-F]+ ([0-9A-F]{8}) \*/[ \t]+)(v[a-z0-9.]+[ \t].*|vnop|vwaitq)[ \t]*$", re.M)
14
+
15
+
16
+ def fix_cop2(text: str) -> str:
17
+ """The assembler rejects the VU0 macro-mode operand syntax a disassembler writes; each such instruction becomes the `.word` it is
18
+ (the original text stays in a comment)."""
19
+ return COP2_LINE.sub(
20
+ lambda m: f"{m.group(1)}.word 0x{bytes.fromhex(m.group(2))[::-1].hex().upper()} /* {m.group(3)} */", text
21
+ )
22
+
23
+
24
+ def split_tu(text: str, drop: Set[str], keep_pad: bool = False) -> Tuple[str, List[str]]:
25
+ """Drop the functions named in `drop` from a translation unit's assembly; each run of kept functions goes in its own section
26
+ `.text.p<k>`. Returns `(assembly, order)`, where `order` lists the section names and the dropped function names in address order.
27
+
28
+ `keep_pad`: the padding after a dropped function's end label stays as assembly (for objects whose padding is part of the
29
+ object: padding to 16 or more, and objects that start 4 mod 8)."""
30
+ lines = text.splitlines(keepends=True)
31
+ head_end = next(i for i, l in enumerate(lines) if l.startswith(".section .text"))
32
+ starts: List[Tuple[int, str]] = []
33
+ for i, l in enumerate(lines):
34
+ m = re.match(r"nonmatching (\S+),", l)
35
+ if m:
36
+ j = i - 1 if i > 0 and lines[i - 1].startswith(".align") else i
37
+ starts.append((j, m.group(1)))
38
+ out: List[str] = lines[:head_end]
39
+ order: List[str] = []
40
+ part, open_part = 0, False
41
+ out += lines[head_end + 1 : starts[0][0]] if starts else lines[head_end + 1 :]
42
+ for k, (j, name) in enumerate(starts):
43
+ end = starts[k + 1][0] if k + 1 < len(starts) else len(lines)
44
+ if name in drop:
45
+ order.append(name)
46
+ open_part = False
47
+ tail = next((i + 1 for i in range(j, end) if lines[i].startswith("endlabel ")), end)
48
+ pad = [l for l in lines[tail:end] if re.match(r"\s*/\* [0-9A-F]+ [0-9A-F]+ [0-9A-F]+ \*/", l)]
49
+ if keep_pad and pad:
50
+ # only the padding words: an .align here belongs to the next function
51
+ out.append(f'\n.section .text.p{part}, "ax"\n')
52
+ order.append(f".text.p{part}")
53
+ part += 1
54
+ open_part = True
55
+ out += pad
56
+ continue
57
+ if not open_part:
58
+ out.append(f'\n.section .text.p{part}, "ax"\n')
59
+ order.append(f".text.p{part}")
60
+ part += 1
61
+ open_part = True
62
+ out += lines[j:end]
63
+ if keep_pad:
64
+ # every word is in place, padding included; an .align would make the linker pad a part that starts 4 mod 8 after a C function
65
+ out = out[:head_end] + [l for l in out[head_end:] if not l.startswith(".align")]
66
+ return "".join(out), order
67
+
68
+
69
+ def strip_attributes(text: str) -> str:
70
+ """Drop every `__attribute__((...))` (balanced parentheses), so that a declaration like
71
+ `int t[4] __attribute__((section(".rodata"))) = {...}` reads as the data definition it is."""
72
+ while True:
73
+ m = re.search(r"__attribute__\s*\(", text)
74
+ if not m:
75
+ return text
76
+ depth, i = 0, m.end() - 1
77
+ while i < len(text):
78
+ depth += {"(": 1, ")": -1}.get(text[i], 0)
79
+ if depth == 0:
80
+ break
81
+ i += 1
82
+ text = text[: m.start()] + text[i + 1 :]
83
+
84
+
85
+ def unstatic(text: str) -> str:
86
+ """Drop a leading `static` (after comments) from a function or a prototype."""
87
+ return re.sub(r"^((?:\s|/\*.*?\*/)*)static\s+", r"\1", text, count=1, flags=re.S)
88
+
89
+
90
+ def is_static_prototype(chunk: str) -> bool:
91
+ body = re.sub(r"/\*.*?\*/|//[^\n]*", "", chunk, flags=re.S).strip()
92
+ return body.startswith("static") and body.endswith(");") and "(" in body and "=" not in body
93
+
94
+
95
+ __all__: Sequence[Any] = ["fix_cop2", "split_tu", "strip_attributes", "unstatic", "is_static_prototype"]
96
+
97
+
98
+ def fix_cop2_tree(folder: "str | Path") -> int:
99
+ """`fix_cop2` on every `.s` file under `folder`, in place. Returns the number of files changed."""
100
+ changed = 0
101
+ for f in Path(folder).rglob("*.s"):
102
+ text = f.read_text()
103
+ new = fix_cop2(text)
104
+ if new != text:
105
+ f.write_text(new)
106
+ changed += 1
107
+ return changed