-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathpsxrecomp_cli.py
More file actions
executable file
·2182 lines (1994 loc) · 79.6 KB
/
Copy pathpsxrecomp_cli.py
File metadata and controls
executable file
·2182 lines (1994 loc) · 79.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Headless disc → generate / rebuild / optional PGO for psxrecomp games.
Commands:
verify-disc Hash-check a dump against game.toml [prepare_disc]
generate Ensure emitters + prepare disc + run psxrecomp-game → generated/
rebuild cmake --build; if [pgo] enabled, instrument → train → use
pgo-train Standalone PGO train (same as rebuild's PGO phase)
ensure-toolchain Resolve / download cmake-clang-v1 into the shared cache
ensure-emitters Build psxrecomp-game + psxrecomp-bios when missing
Exit codes: 0 ok · 1 runtime · 2 usage · 3 disc verify fail
"""
from __future__ import annotations
import argparse
import hashlib
import os
import re
import shutil
import subprocess
import sys
import time
from pathlib import Path
from typing import Any, Optional
ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT / "tools"))
from sdk_progress import ProgressReporter # noqa: E402
from toolchain_pack import ( # noqa: E402
ensure_toolchain as _ensure_toolchain_pack,
resolve_toolchain_bin,
toolchain_bin_runs,
)
EXIT_OK = 0
EXIT_ERROR = 1
EXIT_USAGE = 2
EXIT_VERIFY = 3
def resolve_embedded_toolchain_bin(project_root: Path) -> Optional[Path]:
"""Return a usable toolchain bin/ (project, env, or shared cache)."""
return resolve_toolchain_bin(project_root)
def activate_embedded_toolchain(
project_root: Path, progress: Optional[ProgressReporter] = None
) -> bool:
"""Prepend resolved toolchain bin/ to PATH for cmake/ninja/clang."""
log = progress.log if progress else None
bin_dir = resolve_toolchain_bin(project_root)
if not bin_dir or not toolchain_bin_runs(bin_dir, log=log):
return False
from toolchain_pack import activate_toolchain_bin
activate_toolchain_bin(bin_dir, log=log)
return True
def ensure_toolchain_for_rebuild(
project_root: Path,
progress: ProgressReporter,
*,
from_zip: str = "",
download: bool = True,
min_version: str = "",
) -> bool:
"""Ensure cmake is available via cache / download / offline zip."""
try:
_ensure_toolchain_pack(
project_root,
from_zip=Path(from_zip) if from_zip else None,
download=download and not from_zip,
min_version=min_version,
log=progress.log,
)
return True
except Exception as exc: # noqa: BLE001 — surface to progress UI
progress.log(f"Toolchain ensure: {exc}")
return False
def prune_after_rebuild(
project_root: Path,
build_dir: Path,
modes: set[str],
progress: ProgressReporter,
) -> None:
"""Free disk after a successful rebuild (wizard / one-shot setup)."""
if not modes:
return
if "toolchain" in modes or "all" in modes:
tc = project_root / "toolchain"
if tc.is_dir():
shutil.rmtree(tc, ignore_errors=True)
progress.log(f"Pruned {tc}")
if "build-intermediates" in modes or "all" in modes:
if build_dir.is_dir():
for name in ("CMakeFiles", ".ninja_deps", ".ninja_log", "CMakeCache.txt",
"cmake_install.cmake", "build.ninja", "compile_commands.json"):
p = build_dir / name
if p.is_dir():
shutil.rmtree(p, ignore_errors=True)
elif p.is_file():
try:
p.unlink()
except OSError:
pass
# Drop object/lib digests but keep the launch binary + assets/.
for p in build_dir.rglob("*"):
if not p.is_file():
continue
if p.suffix in {".o", ".obj", ".a", ".lib", ".pdb", ".ilk", ".exp"}:
try:
p.unlink()
except OSError:
pass
progress.log(f"Pruned build intermediates under {build_dir}")
if "build-tree" in modes:
# Keep only the executable + assets next to it, then wipe the rest of
# the build dir by moving keepers aside — used by aggressive cleanup.
if build_dir.is_dir():
keep_names = set()
for p in build_dir.iterdir():
if p.is_file() and os.access(p, os.X_OK):
keep_names.add(p.name)
if p.name.lower().endswith(".exe"):
keep_names.add(p.name)
assets = build_dir / "assets"
staging = build_dir.parent / f".prune-keep-{build_dir.name}"
if staging.exists():
shutil.rmtree(staging, ignore_errors=True)
staging.mkdir(parents=True, exist_ok=True)
for name in keep_names:
src = build_dir / name
if src.is_file():
shutil.move(str(src), str(staging / name))
if assets.is_dir():
shutil.move(str(assets), str(staging / "assets"))
shutil.rmtree(build_dir, ignore_errors=True)
staging.rename(build_dir)
progress.log(f"Pruned build tree to binary+assets under {build_dir}")
def clamp_future_mtimes(
root: Path,
*,
skip: Optional[Path] = None,
now: Optional[float] = None,
) -> int:
"""Clamp mtimes ahead of *now* so Ninja does not infinite-reconfigure.
Release zips often preserve CI clocks that are slightly ahead of a user's
clock (timezone / skew). Ninja then treats every source as newer than
``build.ninja``, re-runs CMake forever, and fails with
``manifest 'build.ninja' still dirty after 100 tries``.
"""
if not root.is_dir():
return 0
stamp = time.time() if now is None else now
skip_res: Optional[Path] = None
if skip is not None:
try:
skip_res = skip.resolve()
except OSError:
skip_res = skip
n = 0
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
dpath = Path(dirpath)
try:
d_res = dpath.resolve()
except OSError:
d_res = dpath
# Skip the active build tree entirely (outputs are rewritten anyway).
if skip_res is not None and (
d_res == skip_res or skip_res in d_res.parents
):
dirnames[:] = []
continue
# Never descend into VCS metadata; prune the build dir at the parent.
pruned: list[str] = []
for x in dirnames:
if x == ".git":
continue
if skip_res is not None:
try:
if (dpath / x).resolve() == skip_res:
continue
except OSError:
pass
pruned.append(x)
dirnames[:] = pruned
for name in filenames:
p = dpath / name
try:
mtime = p.stat().st_mtime
except OSError:
continue
if mtime > stamp:
try:
os.utime(p, (stamp, stamp), follow_symlinks=False)
n += 1
except OSError:
pass
return n
def _parse_array_items(inner: str) -> list[Any]:
items: list[Any] = []
if not inner.strip():
return items
for part in re.split(r",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", inner):
part = part.strip().rstrip(",").strip()
if not part:
continue
if part.startswith('"') and part.endswith('"'):
items.append(part[1:-1])
else:
try:
items.append(int(part, 0))
except ValueError:
items.append(part)
return items
def parse_toml_simple(text: str) -> dict[str, dict[str, Any]]:
sections: dict[str, dict[str, Any]] = {"": {}}
cur = ""
array_key: Optional[str] = None
array_buf: list[str] = []
for raw in text.splitlines():
line = raw.split("#", 1)[0].strip()
if array_key is not None:
array_buf.append(line)
joined = " ".join(array_buf)
if "]" in joined:
inner = joined.split("]", 1)[0]
if inner.startswith("["):
inner = inner[1:]
sections[cur][array_key] = _parse_array_items(inner)
array_key = None
array_buf = []
continue
if not line:
continue
if line.startswith("[") and line.endswith("]"):
cur = line[1:-1].strip()
sections.setdefault(cur, {})
continue
if "=" not in line:
continue
key, val = line.split("=", 1)
key, val = key.strip(), val.strip()
if val.startswith("["):
if val.endswith("]") and val.count("[") == val.count("]"):
sections[cur][key] = _parse_array_items(val[1:-1])
else:
array_key = key
array_buf = [val[1:]]
continue
if val.startswith('"') and val.endswith('"'):
sections[cur][key] = val[1:-1]
elif val.lower() in ("true", "false"):
sections[cur][key] = val.lower() == "true"
else:
try:
sections[cur][key] = int(val, 0)
except ValueError:
sections[cur][key] = val
return sections
def file_hashes(path: Path) -> tuple[str, str, int]:
h_md5, h_sha1 = hashlib.md5(), hashlib.sha1()
size = 0
with open(path, "rb") as f:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
size += len(chunk)
h_md5.update(chunk)
h_sha1.update(chunk)
return h_md5.hexdigest(), h_sha1.hexdigest(), size
def resolve_cue_bin(cue_path: Path) -> Path:
text = cue_path.read_text(encoding="utf-8", errors="replace")
m = re.search(r'FILE\s+"([^"]+)"\s+BINARY', text, re.I)
if not m:
m = re.search(r"FILE\s+(\S+)\s+BINARY", text, re.I)
if not m:
raise ValueError(f"no BINARY FILE in cue: {cue_path}")
cand = Path(m.group(1))
if not cand.is_absolute():
cand = cue_path.parent / cand
if not cand.is_file():
raise ValueError(f"cue references missing bin: {cand}")
return cand
def _find_recompiler_tool(project_root: Path, basename: str, env_name: str) -> Path:
env = os.environ.get(env_name, "").strip()
if env:
p = Path(env).expanduser()
if p.is_file():
return p.resolve()
names = [basename, f"{basename}.exe"]
search_dirs = [
# The dedicated analyzer tree comes FIRST. ensure_analyzer() builds and
# source-stamps that one, and an older psxrecomp-analyze left behind in
# the shared emitters tree would otherwise shadow every rebuild — the
# tool would be rebuilt correctly and then never used.
project_root / "psxrecomp" / "recompiler" / "build-analyze",
ROOT / "recompiler" / "build-analyze",
project_root / "psxrecomp" / "recompiler" / "build",
project_root / "psxrecomp" / "recompiler" / "build" / "Release",
project_root / "build-recompiler",
ROOT / "recompiler" / "build",
ROOT / "recompiler" / "build" / "Release",
]
for d in search_dirs:
for name in names:
c = d / name
if c.is_file():
return c.resolve()
which = shutil.which(basename)
if which:
return Path(which).resolve()
raise FileNotFoundError(
f"{basename} not found. Build it:\n"
" cmake -S psxrecomp/recompiler -B psxrecomp/recompiler/build -G Ninja\n"
f" cmake --build psxrecomp/recompiler/build --target {basename}\n"
f"Or set {env_name}=/path/to/{basename}"
)
def find_psxrecomp_game(project_root: Path) -> Path:
return _find_recompiler_tool(project_root, "psxrecomp-game", "PSXRECOMP_GAME")
def find_psxrecomp_bios(project_root: Path) -> Path:
return _find_recompiler_tool(project_root, "psxrecomp-bios", "PSXRECOMP_BIOS")
def find_psxrecomp_analyze(project_root: Path) -> Path:
return _find_recompiler_tool(project_root, "psxrecomp-analyze", "PSXRECOMP_ANALYZE")
def find_emitters(project_root: Path) -> tuple[Path, Path]:
"""Return (psxrecomp-game, psxrecomp-bios); raises FileNotFoundError if either missing."""
return find_psxrecomp_game(project_root), find_psxrecomp_bios(project_root)
def recompiler_source_dir(project_root: Path) -> Path:
fw = framework_root(project_root)
src = fw / "recompiler"
if not (src / "CMakeLists.txt").is_file():
raise FileNotFoundError(
f"recompiler sources missing under {src} "
"(need a full psxrecomp checkout / submodule, not a pruned zipball)"
)
return src
def ensure_emitters(
project_root: Path,
progress: ProgressReporter,
*,
download_toolchain: bool = True,
force: bool = False,
) -> tuple[Path, Path]:
"""Return emitter binaries, building them with the portable toolchain if needed.
Matches setup_project.sh / tools/ci/build_emitters.sh so a GitHub fork can
Generate & rebuild without a pre-staged setup-host SDK.
"""
if not force:
try:
game, bios = find_emitters(project_root)
progress.log(f"Emitters ready: {game.name}, {bios.name}")
return game, bios
except FileNotFoundError:
pass
progress.phase(
"emitters",
pct=0.12,
message="Building psxrecomp-game + psxrecomp-bios…",
)
_build_recompiler_targets(
project_root,
progress,
# psxrecomp-analyze is deliberately NOT built here. It has its own
# ensure_analyzer()/build tree, and requesting it from the shared
# emitters build breaks `ensure-emitters` outright on any checkout whose
# recompiler/CMakeLists.txt predates the target ("ninja: error: unknown
# target"). The emitters path must keep working on old framework pins.
("psxrecomp-game", "psxrecomp-bios"),
download_toolchain=download_toolchain,
clean=force,
)
try:
game, bios = find_emitters(project_root)
except FileNotFoundError as exc:
raise RuntimeError(
f"emitters build finished but binaries not found: {exc}"
) from exc
progress.log(f"Emitters built: {game} , {bios}")
return game, bios
# Source files that make up psxrecomp-analyze. Kept in step with the target's
# source list in recompiler/CMakeLists.txt.
ANALYZER_SOURCES = (
"recompiler/src/ps1_exe_parser.cpp",
"recompiler/src/mips_decoder.cpp",
"recompiler/src/function_analysis.cpp",
"recompiler/src/analysis_db.cpp",
"recompiler/src/bios_call_names.cpp",
"recompiler/src/analysis_export.cpp",
"recompiler/src/widescreen_scan.cpp",
"recompiler/src/main_analyze.cpp",
"recompiler/include/analysis_db.h",
"recompiler/src/analysis_export.h",
"recompiler/include/widescreen_scan.h",
"runtime/include/ws_cull_detect.h",
)
def _analyzer_source_hash(project_root: Path) -> str:
"""Digest of the analyzer's sources, or "" if they cannot be read.
The toolchain stamp notices a changed COMPILER; nothing noticed changed
CODE, so a psxrecomp-analyze built before a feature landed kept being reused
and rejected the very options the caller had just learned to pass. This is
the same guard `psxrecomp-game --codegen-hash` provides for the emitters,
computed here rather than baked in so it needs no CMake support.
"""
import hashlib
fw = framework_root(project_root)
h = hashlib.sha256()
for rel in ANALYZER_SOURCES:
p = fw / rel
if not p.is_file():
return ""
h.update(rel.encode("utf-8"))
h.update(p.read_bytes())
return h.hexdigest()
def _analyzer_stamp_path(tool: Path) -> Path:
return tool.parent / (tool.name + ".srcstamp")
def ensure_analyzer(
project_root: Path,
progress: ProgressReporter,
*,
download_toolchain: bool = True,
) -> Path:
"""Return psxrecomp-analyze, building ONLY that target when it is missing.
Every build tree created before this target existed has game+bios but no
analyzer, so `analyze` has to be able to add one. It must not do that by
rebuilding the emitters: they already work, a relink is slow, and on a repo
whose tree was configured with the portable cmake-clang toolchain against a
newer system glibc the psxrecomp-game link fails outright on
``__isoc23_strtoul`` — a pre-existing toolchain mismatch that has nothing to
do with analysis. Building the one target that is actually missing avoids
dragging that failure into an unrelated command.
"""
src = recompiler_source_dir(project_root)
dedicated = src / "build-analyze"
# If this project already has the dedicated tree, always run the build step
# rather than trusting the binary's presence. Ninja is a no-op when nothing
# changed (tens of milliseconds), and it is the only thing that notices an
# analyzer SOURCE edit — the toolchain stamp catches a changed compiler, not
# changed code, so a stale binary would otherwise keep producing old-format
# reports indefinitely.
want = _analyzer_source_hash(project_root)
try:
existing = find_psxrecomp_analyze(project_root)
stamp = _analyzer_stamp_path(existing)
have = stamp.read_text(encoding="utf-8").strip() if stamp.is_file() else ""
if want and have == want:
return existing
progress.log(
"psxrecomp-analyze is stale for the current sources — rebuilding"
if have
else "psxrecomp-analyze has no source stamp — rebuilding once"
)
except FileNotFoundError:
pass
progress.phase("emitters", pct=0.12, message="Building psxrecomp-analyze…")
_build_recompiler_targets(
project_root,
progress,
("psxrecomp-analyze",),
download_toolchain=download_toolchain,
build_dir_override=dedicated,
# The analyzer needs fmt and nothing else. Configuring its own tree with
# libchdr and the test suite off keeps `analyze` independent of whatever
# state the emitters' build directory is in — a half-configured cache, a
# cold FetchContent needing the network, or a project path containing a
# colon, all of which fail the shared configure for reasons that have
# nothing to do with static analysis.
extra_cmake_args=("-DPSXRECOMP_ENABLE_CHD=OFF", "-DBUILD_TESTING=OFF"),
)
try:
tool = find_psxrecomp_analyze(project_root)
except FileNotFoundError as exc:
raise RuntimeError(
f"psxrecomp-analyze build finished but the binary was not found: {exc}"
) from exc
if want:
try:
_analyzer_stamp_path(tool).write_text(want, encoding="utf-8")
except OSError:
pass
progress.log(f"Analyzer built: {tool}")
return tool
def _toolchain_stamp(clang_cxx: Optional[str], cmake_tool: Optional[str]) -> str:
"""Identity of the toolchain that a build directory's objects were made with.
The portable toolchain is addressed through a stable ``latest`` symlink, so
an upgrade behind it leaves CMAKE_CXX_COMPILER unchanged and CMake's
compiler-change detection never fires. Ninja then relinks object files
built by the previous toolchain.
That is not theoretical: cmake-clang-v1 v1.0.10 shipped no sysroot and
compiled against the host's glibc, so `strtoul` became `__isoc23_strtoul`
(glibc >= 2.38). v1.0.14 added a bundled older sysroot that exports no such
symbol, and every build tree from before the upgrade failed to link with
"undefined symbol: __isoc23_strtoul" while nothing looked out of date.
Resolving the symlink puts the concrete version in the stamp, so the
upgrade becomes visible and the tree can be wiped.
"""
parts: list[str] = []
for tool in (clang_cxx, cmake_tool):
if not tool:
continue
real = Path(tool).resolve()
parts.append(str(real))
try:
parts.append(str(real.stat().st_size))
except OSError:
pass
manifest = real.parent.parent / "retcomm-toolchain.json"
if manifest.is_file():
try:
parts.append(manifest.read_text(encoding="utf-8", errors="replace"))
except OSError:
pass
return "\n".join(parts)
def _build_recompiler_targets(
project_root: Path,
progress: ProgressReporter,
targets: tuple[str, ...],
*,
download_toolchain: bool = True,
build_dir_override: Path | None = None,
extra_cmake_args: tuple[str, ...] = (),
clean: bool = False,
) -> Path:
"""Configure recompiler/ and build `targets`. Returns the build directory."""
if not activate_embedded_toolchain(project_root, progress):
if not download_toolchain or not ensure_toolchain_for_rebuild(
project_root, progress, download=True
):
if not (_which_tool("cmake") and _which_tool("ninja")):
raise RuntimeError(
"Cannot build emitters: no portable toolchain and no "
"cmake+ninja on PATH. Finish the launcher toolchain step, "
"or run: python3 psxrecomp/psxrecomp_cli.py ensure-toolchain"
)
progress.log("Using system cmake/ninja on PATH for emitters")
elif not activate_embedded_toolchain(project_root, progress):
raise RuntimeError(
"Toolchain ensure succeeded but bin/ is not usable for emitters"
)
src = recompiler_source_dir(project_root)
# Prefer recompiler/build (packaging / RetComM harvest layout); also keep
# project-root build-recompiler if that is where prior binaries lived.
build_dir = src / "build"
try:
existing_game = find_psxrecomp_game(project_root)
# Rebuild into the directory that already holds a partial install.
if existing_game.parent != build_dir:
alt = project_root / "build-recompiler"
if existing_game.parent.resolve() == alt.resolve():
build_dir = alt
except FileNotFoundError:
pass
if build_dir_override is not None:
build_dir = build_dir_override
build_dir.mkdir(parents=True, exist_ok=True)
toolchain_bin = resolve_embedded_toolchain_bin(project_root)
ninja = _tool_in_dir(toolchain_bin, "ninja") or _which_tool("ninja")
clang_c = _tool_in_dir(toolchain_bin, "clang") or _which_tool("clang")
clang_cxx = _tool_in_dir(toolchain_bin, "clang++") or _which_tool("clang++")
cmake = _tool_in_dir(toolchain_bin, "cmake") or _which_tool("cmake")
if cmake is None:
raise RuntimeError("cmake not found on PATH after toolchain activate")
# Wipe when the caller asked for a clean build, or when the toolchain that
# produced this tree's objects is not the one about to link them.
stamp_file = build_dir / ".retcomm-toolchain-stamp"
stamp = _toolchain_stamp(clang_cxx, cmake)
if clean:
progress.log(f"Clean rebuild requested — removing {build_dir}")
shutil.rmtree(build_dir, ignore_errors=True)
build_dir.mkdir(parents=True, exist_ok=True)
elif stamp and stamp_file.is_file():
try:
previous = stamp_file.read_text(encoding="utf-8", errors="replace")
except OSError:
previous = ""
if previous and previous != stamp:
progress.log(
"Toolchain changed since this build directory was configured — "
f"removing {build_dir} so objects are rebuilt against it"
)
shutil.rmtree(build_dir, ignore_errors=True)
build_dir.mkdir(parents=True, exist_ok=True)
elif stamp and not stamp_file.is_file() and (build_dir / "CMakeCache.txt").is_file():
# A tree configured before stamping existed. Its objects may predate the
# current toolchain with no way to tell, and a mismatch surfaces only as
# an undefined symbol at link time. Rebuild once, then stamp.
progress.log(
f"Unstamped build directory {build_dir} — rebuilding once so its "
"objects are known to match the active toolchain"
)
shutil.rmtree(build_dir, ignore_errors=True)
build_dir.mkdir(parents=True, exist_ok=True)
cache_file = build_dir / "CMakeCache.txt"
gen: list[str] = []
if ninja is not None:
cached_gen = _read_cmake_cache_generator(cache_file)
if cached_gen and cached_gen != "Ninja":
progress.log(f'Replacing emitters cmake generator "{cached_gen}" with Ninja…')
shutil.rmtree(build_dir, ignore_errors=True)
build_dir.mkdir(parents=True, exist_ok=True)
gen = ["-G", "Ninja", f"-DCMAKE_MAKE_PROGRAM={ninja}"]
elif sys.platform == "win32":
progress.log(
"warning: ninja not on PATH — emitters cmake may pick NMake Makefiles"
)
cmake_args = [
str(cmake),
"-S",
str(src),
"-B",
str(build_dir),
*gen,
"-DCMAKE_BUILD_TYPE=Release",
]
if clang_c is not None:
cmake_args.append(f"-DCMAKE_C_COMPILER={clang_c}")
if clang_cxx is not None:
cmake_args.append(f"-DCMAKE_CXX_COMPILER={clang_cxx}")
# Portable llvm-mingw / cmake-clang-v1: static CRT so staged emitters need
# no MSYS2 GCC DLLs (same as tools/ci/build_emitters.sh).
if clang_c is not None or clang_cxx is not None:
cmake_args.append("-DPSXRECOMP_STATIC_CLI=ON")
cmake_args.extend(
_pack_sysroot_cmake_args(clang_c, (*cmake_args, *extra_cmake_args))
)
cmake_args.extend(extra_cmake_args)
progress.log(" ".join(cmake_args))
proc = subprocess.run(
cmake_args, cwd=str(project_root), capture_output=True, text=True
)
for stream in (proc.stdout, proc.stderr):
if stream:
for line in stream.splitlines():
if line.strip():
progress.log(line)
if proc.returncode != 0:
raise RuntimeError(
f"emitters cmake configure failed (exit {proc.returncode})"
)
jobs = os.environ.get("CMAKE_BUILD_PARALLEL_LEVEL") or str(os.cpu_count() or 4)
build_cmd = [str(cmake), "--build", str(build_dir), "--parallel", jobs]
for target in targets:
build_cmd += ["--target", target]
progress.log(" ".join(build_cmd))
proc = subprocess.run(build_cmd, capture_output=True, text=True)
for stream in (proc.stdout, proc.stderr):
if stream:
for line in stream.splitlines():
if line.strip():
progress.log(line)
if proc.returncode != 0:
raise RuntimeError(
f"recompiler cmake build failed (exit {proc.returncode}) for "
+ ", ".join(targets)
)
if stamp:
try:
stamp_file.write_text(stamp, encoding="utf-8")
except OSError:
pass
return build_dir
def framework_root(project_root: Path) -> Path:
"""Directory containing bios/*.toml and recompiler/ (usually …/psxrecomp)."""
cand = project_root / "psxrecomp"
if (cand / "bios" / "OpenBIOS.toml").is_file() or (
(cand / "bios").is_dir() and (cand / "recompiler").is_dir()
):
if (cand / "bios").is_dir():
return cand
if (ROOT / "bios").is_dir() and (ROOT / "recompiler").is_dir():
return ROOT
return cand
def _copy_missing(src: Path, dest: Path) -> None:
if src.is_dir():
dest.mkdir(parents=True, exist_ok=True)
for child in src.iterdir():
_copy_missing(child, dest / child.name)
return
if not src.is_file():
return
if dest.is_file():
return
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dest)
def ensure_framework(
project_root: Path, *, progress: Optional[ProgressReporter] = None
) -> Path:
"""Ensure project_root/psxrecomp has BIOS profiles + seeds for local generate.
GitHub zipballs omit git submodules, so RetComM source trees often lack
psxrecomp/bios. Seed from the SDK pack that ships this CLI (ROOT).
"""
fw = project_root / "psxrecomp"
need_seed = not (fw / "bios" / "OpenBIOS.toml").is_file()
if need_seed and (ROOT / "bios").is_dir():
if progress:
progress.log(
f"Seeding psxrecomp BIOS profiles from SDK -> {fw}"
)
fw.mkdir(parents=True, exist_ok=True)
_copy_missing(ROOT / "bios", fw / "bios")
seeds_src = ROOT / "recompiler" / "seeds"
if seeds_src.is_dir():
_copy_missing(seeds_src, fw / "recompiler" / "seeds")
(fw / "recompiler" / "build").mkdir(parents=True, exist_ok=True)
# psxrecomp-bios walks up from bios/*.toml looking for .gitignore/.git/
# CMakeLists.txt to find the framework root. Zipball trees lack the
# submodule .git — plant a marker so rom = "bios/openbios.bin" resolves.
if (fw / "bios").is_dir() and not any(
(fw / m).exists() for m in (".gitignore", ".git", "CMakeLists.txt")
):
marker = fw / ".gitignore"
if not marker.is_file():
marker.write_text(
"# RetComM SDK seed marker (project-root for psxrecomp-bios)\n",
encoding="utf-8",
)
return framework_root(project_root)
def bios_backend_present(fw: Path, stem: str) -> bool:
dispatch = fw / "generated" / f"{stem}_dispatch.c"
full = fw / "generated" / f"{stem}_full.c"
if not dispatch.is_file() or not full.is_file():
return False
try:
text = dispatch.read_text(encoding="utf-8", errors="ignore")
except OSError:
return False
return f"{stem}_psx_bios_backend" in text
def regen_bios_profile(
project_root: Path,
profile_rel: str,
*,
progress: ProgressReporter,
) -> None:
fw = framework_root(project_root)
profile = fw / profile_rel
if not profile.is_file():
raise FileNotFoundError(f"BIOS profile not found: {profile}")
bios_tool = find_psxrecomp_bios(project_root)
progress.log(f"regen BIOS via {bios_tool.name} --config {profile_rel}")
(fw / "generated").mkdir(parents=True, exist_ok=True)
# Pass a framework-relative config path and cwd=fw so toml paths like
# rom = "bios/openbios.bin" resolve under the framework root (not bios/bios/).
proc = subprocess.run(
[str(bios_tool), "--config", profile_rel],
cwd=str(fw),
capture_output=True,
text=True,
)
for stream in (proc.stdout, proc.stderr):
if not stream:
continue
for line in stream.splitlines():
if line.strip():
progress.log(line)
if proc.returncode != 0:
raise RuntimeError(
f"psxrecomp-bios failed for {profile_rel} (exit {proc.returncode})"
)
def load_sections(config: Path) -> dict[str, dict[str, Any]]:
return parse_toml_simple(config.read_text(encoding="utf-8"))
def verify_disc_path(
disc: Path,
prep: dict[str, Any],
*,
skip_hash: bool,
progress: ProgressReporter,
) -> dict[str, Any]:
path = disc.resolve()
if path.suffix.lower() == ".cue":
path = resolve_cue_bin(path)
md5, sha1, size = file_hashes(path)
identity = {
"path": str(path),
"md5": md5,
"sha1": sha1,
"size": size,
"verified": False,
}
progress.event("disc", **identity)
sizes = [int(s) for s in (prep.get("known_sizes") or [])]
md5s = [str(x).lower() for x in (prep.get("known_md5") or [])]
sha1s = [str(x).lower() for x in (prep.get("known_sha1") or [])]
if not md5s and not sha1s and not sizes:
identity["verified"] = True
return identity
if skip_hash:
return identity
ok = (md5 in md5s) or (sha1 in sha1s)
if not ok and sizes and size in sizes and not md5s and not sha1s:
ok = True
if not ok:
raise DiscVerifyError(
f"disc digests not in prepare_disc.known_* "
f"(size={size} md5={md5} sha1={sha1})"
)
identity["verified"] = True
return identity
class DiscVerifyError(Exception):
pass
def cmd_verify_disc(args: argparse.Namespace, progress: ProgressReporter) -> int:
config = Path(args.config).expanduser().resolve()
if not config.is_file():
progress.error(f"config not found: {config}", code=EXIT_USAGE)
return EXIT_USAGE
project_root = (
Path(args.project_root).expanduser().resolve()
if args.project_root
else config.parent
)
activate_embedded_toolchain(project_root, progress)
disc = Path(args.disc).expanduser()
if not disc.is_absolute():
disc = (project_root / disc).resolve()
else:
disc = disc.resolve()
if not disc.is_file():
progress.error(f"disc not found: {disc}", code=EXIT_USAGE)
return EXIT_USAGE
secs = load_sections(config)
prep = secs.get("prepare_disc") or {}
progress.phase("verify", pct=0.1, message=f"Verifying {disc.name}")
try:
identity = verify_disc_path(
disc, prep, skip_hash=bool(args.skip_hash_check), progress=progress
)
except DiscVerifyError as exc:
progress.error(str(exc), code=EXIT_VERIFY, verify_failed=True)
return EXIT_VERIFY
progress.phase("done", pct=1.0, message="Disc OK")
progress.result(ok=True, **identity)
return EXIT_OK
def run_prepare_disc(
project_root: Path,
config: Path,
source: Path,
progress: ProgressReporter,
) -> Path:
script = ROOT / "tools" / "prepare_disc.py"
if not script.is_file():
raise RuntimeError(f"missing {script}")
progress.phase("prepare_disc", pct=0.15, message="Normalizing disc image...")
cmd = [
sys.executable,
str(script),
"--config",
str(config),
"--project-root",
str(project_root),
str(source),
]
proc = subprocess.run(cmd, cwd=str(project_root), capture_output=True, text=True)
out = (proc.stdout or "") + (proc.stderr or "")
for line in out.splitlines():
if line.strip():
progress.log(line)
if proc.returncode != 0:
raise RuntimeError(f"prepare_disc failed (exit {proc.returncode})")
marker = "RESULT_CUE="
cue = None
for line in out.splitlines():
if line.startswith(marker):
cue = Path(line[len(marker) :].strip())
if not cue or not cue.is_file():
raise RuntimeError("prepare_disc did not print RESULT_CUE=")
return cue.resolve()
def cmd_generate(args: argparse.Namespace, progress: ProgressReporter) -> int:
config = Path(args.config).expanduser().resolve()
if not config.is_file():
progress.error(f"config not found: {config}", code=EXIT_USAGE)
return EXIT_USAGE
project_root = (
Path(args.project_root).expanduser().resolve()
if args.project_root
else config.parent
)
activate_embedded_toolchain(project_root, progress)
secs = load_sections(config)
game = secs.get("game") or {}
prep = secs.get("prepare_disc") or {}
recomp = secs.get("recompiler") or {}
runtime = secs.get("runtime") or {}
openbios_allowed = bool(runtime.get("openbios", True))
disc_arg = args.disc
if not disc_arg:
disc_arg = game.get("disc") or ""
if not disc_arg:
progress.error("no --disc and game.disc empty", code=EXIT_USAGE)
return EXIT_USAGE
disc = Path(str(disc_arg)).expanduser()
if not disc.is_absolute():
disc = (project_root / disc).resolve()
else:
disc = disc.resolve()
progress.log(f"generate --disc {disc}")
progress.phase("verify", pct=0.05, message=f"Checking disc {disc.name}")
try:
if disc.is_file():
verify_disc_path(
disc, prep, skip_hash=bool(args.skip_hash_check), progress=progress
)
except DiscVerifyError as exc:
progress.error(str(exc), code=EXIT_VERIFY, verify_failed=True)
return EXIT_VERIFY
boot = str(prep.get("boot_exe") or Path(str(game.get("exe") or "")).name)
out_rel = str(prep.get("out_dir") or "prepared_disc")
boot_path = project_root / out_rel / boot
working_disc = disc
# Normalize library dumps when boot EXE missing or source looks like ISO/raw.
need_prep = (not boot_path.is_file()) or disc.suffix.lower() in (
".iso",
".ISO",
)
if need_prep or args.force_prepare: