Repository navigation
Expand file tree
/
Copy pathexetext.py
More file actions
1871 lines (1704 loc) · 98 KB
/
Copy pathexetext.py
File metadata and controls
1871 lines (1704 loc) · 98 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
"""exetext.py — the strings inside the executables (the boot ELF, OV01.OVL, OV02.OVL), in place.
Borrowed from Xenosaga1PythonExtractor/ovltext.py (2026-10-15): the reference
scan (pointer words in data, ``lui``/``addiu|ori|load`` pairs in code) and the
slot rule come from there. Re-targeted to Episode II, and in place only: no
string is ever moved. The boot ELF has a bss after its data, and how the
Episode II overlays could grow has not been studied, so this module never
relocates.
Episode II keeps most of its UI words in ``.txd`` menus and ``batdat.us``,
which ``text-export`` already lists. A few displayed strings are still C
literals in the code (read from SLUS_208.92 on 2026-11-20): ``Saving...``
at 0x0068B678, drawn by the save screen FUN_00237830 under
``$init;$bg0;$zoom13;$han1;$prop1;...``; ``No items to sell.`` at
0x0068D430; ``Total Exp``, ``Class Lv``, ``Next Lv``, ``Zone``; the
memory-card and disc-change prompts in the boot ELF and OV02. They go
through the same print function as all other text (FUN_00197bb8, the byte
reading of ``font.us_two_byte``), so the tree uses the kit's USA codec.
**What is listed.** A string is a NUL-terminated run of at least 2 bytes,
each 0x20-0x7E, 0x09, 0x0A or from 0x80 up, with an ASCII letter, digit or
sign in it or reading as Japanese (EUC-JP / Shift-JIS developer strings,
marked); bytes 0x80-0x9F only in a Japanese reading, other control bytes
only in a run with three ASCII letters (the title overlay's memory-card
prompts carry 0x19 0x03 and 0x0C codes). And the code points at it:
* a 32-bit word in a data part equal to the string's address (a pointer in a
table or a struct);
* a ``lui rX,hi`` and then an ``addiu``, ``ori``, ``daddiu`` or byte
load/store with base rX whose address is the string's. The ``lui`` is
followed down the straight path: through the delay slot and the
fall-through of a conditional branch, saved registers (s0-s8) across
calls, until rX is written or an unconditional jump or ``jr`` ends the
path. As a fallback (Episode I's ``last_lui``), a ``lui`` reached only
through a label (switch arms sharing one ``lui``, a ``lui`` in a likely
branch's slot) makes a string only when the address is exactly a string's
start; any other address it forms in the NUL padding after a string ends
that string's slot (Disc 1: the 80-byte block FUN_001a5ff8 copies from
0x0063F730, right after ``cdrom0:\``);
* an ``addiu``/byte load with base ``$gp`` (gp read from the boot ELF's
``.reginfo``, 0x006A2DF0 on the USA build): ``Next Lv`` and ``Zone`` live in
``.sdata``.
Word and float loads and stores form addresses too: those end slots but do
not make a string.
**Accesses through a whole address.** After ``lui rX,hi; addiu rX,rX,lo``
the scan keeps the address in rX (on the same straight path) and reads
``sb v,k(rX)``, ``lbu v,k(rX)``, ``addiu rY,rX,k`` as accesses at address+k:
* a store into a string's own bytes is a stamp: the code writes there at run
time (Disc 1: FUN_0022e9e0 writes the path number into bytes +9 and +10 of
``Path No. 01 achievement level...`` before printing it; ``sc0000.sb``
gets a scene number in +2..+5). The tree names them and an edit must keep
the same bytes at those offsets;
* loads that reach the terminator are a copy of a known size (an inlined
``strcpy``: ``ldl``/``ldr``, ``lw``, ``lb`` up to the NUL; OV01's
``$han1;$prop1;$zoom15,10;...`` and ``(Player)``): ``max`` is then that
size minus the terminator, not the NUL padding, or the copy would arrive
without one;
* any access past a string's terminator is another object and ends its slot.
**Conversions.** Many strings are printf formats passed to a varargs
formatter with a fixed set of arguments (Disc 1: FUN_00286d20 calls
FUN_002aa5d8 with ``$han1;%s`` and one argument). Import compares the
%-conversions of an edit with the exported string, by the argument each one
reads (``%d`` and ``%x`` read the same; ``%s`` and ``%d`` do not; ``%%``
reads nothing), and refuses any change. Which strings actually reach a
formatter has not been traced, so every string is held to this. A segment flagged executable and not writable is code, one
not executable is data. The overlays are one RWX segment each (one section,
code then data): their code is taken to end after the last ``jr ra``. A
function's first instruction (``addiu sp,sp,-N``) and ``jal`` targets are
never strings. A data word or an instruction can still look like a reference
by chance: such a false hit only adds a listed string, ends a neighbour's
slot early or holds bytes in place, never the other way round. A fallback
address inside a string's own bytes is ignored (no object starts inside
text; the fallback misreads walking pointers there).
**Control codes.** A run with a control byte (below 0x20, not tab or line
feed) is read the way the print function FUN_00197bb8 reads it
(``print_tokens``): a zero byte ends the string only in a character
position, a control code is followed by its parameters (``CTRL_PARAMS``),
which may be zero. The save prompts start ``0B 0E 01 01 00 00 00 0D 03 19
03``, so a NUL-split scan saw only their first four bytes. Such a run is
taken when it parses to a terminator, has no address-carrying code (0x16,
0x17) and has three ASCII letters or reads as EUC-JP Japanese with at least
three kana or kanji (the HDD installer prompts; the field-debug label
``0D 02`` + ``ハシゴ`` at 0x006899D0). The tree writes every code and its parameters as
escapes (``show``); import re-reads an edit with the same grammar
(``print_check``).
**Another path's lui.** A ``lui`` whose register is rewritten on the
straight path but that reaches a use through a branch, within its function
(OV02 0x00A80350 ``addiu a1,s1,0x3348`` forms ``Start game?`` from ``lui
s1,0xa8`` at 0x00A80294; s1 is rewritten at 0x00A802B4 on another arm), makes
a string only at an 8-byte-aligned start after a NUL with three ASCII letters
or Japanese text (``_literal_start``), and never ends a slot.
Cross-checked 2026-11-20 against the Ghidra listing of the boot ELF (1,106
strings): before the rule above 24 were not found, developer error messages
whose ``lui`` sits on another path with the register reused in between; the
ones named in docs/MODDING.md are now listed. Every string of the OV01 and
OV02 listings is found.
**Which file owns an address.** OV01.OVL and OV02.OVL both load at
0x00A80000, and the boot ELF carries a third segment at the same address (its
bytes equal OV02.OVL's, compared 2026-11-20): the copy resident at boot. So
a reference from the boot ELF's main code into that range cannot say which
overlay it means, and is ignored. Overlay code may point into the boot ELF's
main data, and those strings are the boot ELF's. A string of the resident
segment that also sits, byte for byte, at the same address of an overlay file
is listed in both trees; an edit must give both the same text (which copy a
given screen draws from has not been read).
**The slot** of a string runs from its first byte to the earliest of the
next non-zero byte, the next address any code or pointer forms, the start of
a font table the kit reads (``region.US``: ASCII table, extra-kanji list,
width table), and the end of the segment's file bytes. ``max N`` in the tree
is that length minus the terminator. The NUL padding after a string is taken
to be free; a variable reached only through a base address below it would
not be seen by the scan.
**Tree.** ``xs2-exe-export.json`` and one block file per executable::
# exetext 1 file=SLUS_208.92 role=boot sha256=1f978e64...
### @0x0068b678 max 15 bytes
# refs 1 (hilo 0x002379c4)
Saving...
``BOOT.exe.txt`` is the boot ELF whatever its serial, so a Disc 1 tree
applies to Disc 2 (byte-identical executable). Blocks are the
``textpack.parse_blocks`` form: every block back once, in order.
**Import** writes each changed string over its own bytes and fills the rest
of the slot with NUL; the file size never changes. The disc's file must be
the one the tree was exported from (manifest sha256). ``--retail`` takes the
base bytes from a retail disc instead and applies every edited string of the
tree to them, so an image that is already exe-patched can be done again.
A tree may hold only the files it changes: a file it leaves out keeps the
disc's bytes, or with ``--retail`` is reset to the retail bytes, so the
result always equals an import of the tree into a fresh retail copy.
After an import the boot ELF is no longer the retail one, so every command
that reads its tables (text-import, font-extract, lang-scan) refuses the
image: exe-import is the last step.
python exetext.py export DISC.iso OUTDIR
python exetext.py import DISC.iso OUTDIR OUT.iso [--retail RETAIL.iso]
python exetext.py --self-test
"""
from __future__ import annotations
import bisect
import hashlib
import json
import os
import re
import struct
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Tuple
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import region # noqa: E402
import textcodec # noqa: E402
from iso9660 import IsoImage # noqa: E402
from textcodec import TextError # noqa: E402
from textpack import keyed_bodies, parse_blocks # noqa: E402
MANIFEST = "xs2-exe-export.json"
FORMAT = 2 # 2: strings read by the print function's grammar (control codes)
BOOT_TREE = "BOOT.exe.txt"
MIN_LEN = 2
PT_LOAD = 1
PT_MIPS_REGINFO = 0x70000000
PF_X, PF_W = 1, 2
GP = 28
# sha256 of the retail USA overlays (Disc 1, read 2026-11-20); --retail accepts these
RETAIL_OVERLAYS = {
"OV01.OVL": "420e78108c3d1fdb2a44be6f74b632fd88e436e6b854b6e7e0929d17183fe9b0",
"OV02.OVL": "709c09c4ab27770e0e84bf360aeb5990d7e89d90bd52a0bd3adb787087f36bd3",
}
class ExeError(ValueError):
pass
# ------------------------------------------------------------------ MIPS bits
_USE_OPS = {0x09, 0x0D, 0x19, 0x1A, 0x1B, 0x1E, 0x1F, 0x31, 0x35, 0x36, 0x39, 0x3D, 0x3E, 0x3F} \
| set(range(0x20, 0x30)) | {0x37}
_RT_WRITERS = set(range(0x08, 0x10)) | {0x18, 0x19, 0x1A, 0x1B, 0x1E, 0x37} | set(range(0x20, 0x28))
_TEMPS = tuple(range(1, 16)) + (24, 25, 31)
_TEXT_OPS = {0x09, 0x0D, 0x19, 0x20, 0x24, 0x28} # addiu, ori, daddiu, lb, lbu, sb
WEAK_REACH = 0x1000 # bytes from a lui to a use reached only through a label
# bytes a store writes, by opcode: sb sh swl sw sdl sdr swr sq swc1 sdc1 sqc2 sd
# where a load at offset k ends (k + bytes; lwl/ldl name the last byte of their word)
_LOAD_END = {0x20: 1, 0x24: 1, 0x21: 2, 0x25: 2, 0x23: 4, 0x27: 4, 0x31: 4, 0x37: 8, 0x35: 8, 0x1E: 16,
0x36: 16, 0x22: 1, 0x1A: 1, 0x26: 4, 0x1B: 8}
_STORE_WIDTH = {0x28: 1, 0x29: 2, 0x2A: 4, 0x2B: 4, 0x2C: 8, 0x2D: 8, 0x2E: 4, 0x1F: 16,
0x39: 4, 0x3D: 8, 0x3E: 16, 0x3F: 8}
def _branch_kind(w: int) -> Optional[str]:
"""None, or what happens after this instruction's delay slot: "cond" (the fall-through
continues), "likely" (the slot runs only when taken), "jump", "call" or "ret"."""
op, rs, rt = w >> 26, (w >> 21) & 31, (w >> 16) & 31
if op == 0:
f = w & 0x3F
if f == 0x08:
return "ret" if rs == 31 else "jump"
return "call" if f == 0x09 else None
if op == 0x02:
return "jump"
if op == 0x03:
return "call"
if op == 0x01:
if 0x10 <= rt <= 0x13:
return "call"
if rt in (0x01, 0x03) and rs == 0: # bgez $0: b
return "jump"
return "likely" if rt in (0x02, 0x03, 0x12, 0x13) else "cond"
if op == 0x04 and rs == 0 and rt == 0: # beq $0,$0: b
return "jump"
if op in (0x04, 0x05, 0x06, 0x07):
return "cond"
if op in (0x14, 0x15, 0x16, 0x17):
return "likely"
if op in (0x10, 0x11, 0x12) and rs == 8: # bc0/bc1/bc2 (t, f, tl, fl)
return "likely" if rt & 2 else "cond"
return None
def _writes(w: int) -> Optional[int]:
"""The general register an instruction writes, as far as the scan cares."""
op, rs, rt, rd = w >> 26, (w >> 21) & 31, (w >> 16) & 31, (w >> 11) & 31
if op == 0:
return None if (w & 0x3F) == 0x08 else rd
if op == 0x1C: # MMI
return rd
if op in _RT_WRITERS:
return rt
if op == 0x03 or (op == 0x01 and 0x10 <= rt <= 0x13): # jal, bltzal & co
return 31
if op in (0x10, 0x11, 0x12) and rs in (0, 1, 2): # mfc/dmfc/cfc
return rt
return None
# FUN_00195760 (USA): the debug print. It draws only when (DAT_008DAD04 & 3) == 3, a debug switch;
# its format is the third argument (a2), its varargs after it.
DEBUG_PRINT = 0x00195760
DEBUG_REACH = 48 # instructions from forming the address to the call
def _debug_call(exe: "Exe", at: int) -> bool:
"""The address the instruction at ``at`` forms goes, on the straight path, into an argument
register of a call to FUN_00195760 (the debug print), and nowhere else first."""
try:
w = struct.unpack_from("<I", exe.data, exe.off_of(at))[0]
except ExeError:
return False
op, rt = w >> 26, (w >> 16) & 31
if op not in (0x09, 0x0D, 0x19) or not 4 <= rt <= 11:
return False
jal = (3 << 26) | ((DEBUG_PRINT >> 2) & 0x3FFFFFF)
try:
prev = struct.unpack_from("<I", exe.data, exe.off_of(at - 4))[0]
except ExeError:
prev = 0
if prev == jal: # formed in the call's delay slot
return True
va = at + 4
for _ in range(DEBUG_REACH):
try:
w = struct.unpack_from("<I", exe.data, exe.off_of(va))[0]
except ExeError:
return False
kind = _branch_kind(w)
if kind is not None:
if w != jal:
return False
try:
slot = struct.unpack_from("<I", exe.data, exe.off_of(va + 4))[0]
except ExeError:
return False
return _writes(slot) != rt
if _writes(w) == rt:
return False
va += 4
return False
def _addr(hi: int, w: int) -> int:
imm = w & 0xFFFF
if (w >> 26) == 0x0D: # ori: zero-extended
return ((hi << 16) | imm) & 0xFFFFFFFF
return ((hi << 16) + (imm - 0x10000 if imm & 0x8000 else imm)) & 0xFFFFFFFF
# ------------------------------------------------------------------ one ELF
@dataclass
class Seg:
va: int
off: int
filesz: int
flags: int
resident: bool = False # the boot ELF's copy of an overlay's address range
code_end: int = 0 # VA where the code part ends (see Exe.__init__)
def has(self, va: int) -> bool:
return self.va <= va < self.va + self.filesz
@dataclass
class Ref:
kind: str # "hilo" | "gp" | "ptr" | "call" (a jal target: code, never a string)
at: int # VA of the use instruction or the pointer word
file: str # the file the reference is in
weak: bool = False # a lui reached only through a label: makes a string only at its start
text: bool = True # forms the address or reads a byte; False for word/float loads and stores
base: Optional[int] = None # an access through a register already holding a full address (lui+addiu)
store: int = 0 # bytes the instruction writes there (0: not a store)
load: int = 0 # for a load: where it ends, counted from its address
op: str = "" # the mnemonic, for the tree's comments
hist: bool = False # an earlier lui of the same function on another path: a string start or nothing
@dataclass
class ExeString:
va: int
off: int
raw: bytes
max: int # bytes of text the slot holds (the terminator not counted)
refs: List[Ref] = field(default_factory=list)
twins: List[Tuple[str, int]] = field(default_factory=list) # (file, va): the same bytes elsewhere
stamps: List[Tuple[int, int, Ref]] = field(default_factory=list) # (offset, bytes, ref): code writes there
copied: int = 0 # bytes the code copies at fixed offsets, terminator included (0: not seen)
copy_refs: List[Ref] = field(default_factory=list)
slot: int = 0 # max before the copy limit
class Exe:
"""One ELF file: its loaded segments and every address its code and data form."""
def __init__(self, name: str, data: bytes, role: str, gp: Optional[int] = None):
self.name, self.data, self.role = name, bytes(data), role
try:
region.elf_segments(self.data) # validates the headers
except region.ElfError as e:
raise ExeError(f"{name}: {e}")
phoff = struct.unpack_from("<I", self.data, 0x1C)[0]
phentsize, phnum = struct.unpack_from("<HH", self.data, 0x2A)
self.segs: List[Seg] = []
self.gp = gp
for i in range(phnum):
p_type, p_off, p_va, _pa, p_filesz, _mem, p_flags = struct.unpack_from("<7I", self.data,
phoff + phentsize * i)
if p_type == PT_LOAD and p_filesz:
seg = Seg(p_va, p_off, p_filesz, p_flags)
seg.code_end = self._code_end(seg)
self.segs.append(seg)
elif p_type == PT_MIPS_REGINFO and p_filesz >= 24 and gp is None:
self.gp = struct.unpack_from("<I", self.data, p_off + 20)[0]
self.sha256 = hashlib.sha256(self.data).hexdigest()
def _code_end(self, seg: Seg) -> int:
"""A segment flagged executable and not writable is all code, one not executable is
all data. The overlays are one RWX segment each, code first and data after (their
single section ``ov01``/``ov02``): the code is taken to end after the last
``jr ra`` and its delay slot."""
if not seg.flags & PF_X:
return seg.va
if not seg.flags & PF_W:
return seg.va + seg.filesz
i = seg.off + seg.filesz - 4
i -= (seg.va + i - seg.off) % 4
while i >= seg.off:
if struct.unpack_from("<I", self.data, i)[0] == 0x03E00008:
return min(seg.va + i - seg.off + 8, seg.va + seg.filesz)
i -= 4
return seg.va
def seg_of(self, va: int) -> Optional[Seg]:
return next((s for s in self.segs if s.has(va)), None)
def off_of(self, va: int) -> int:
s = self.seg_of(va)
if s is None:
raise ExeError(f"{self.name}: {va:#010x} is not in the file bytes of a loaded segment")
return s.off + va - s.va
def scan(self) -> List[Tuple[int, Ref, Seg]]:
"""(address formed, reference, segment the reference sits in), every one."""
out: List[Tuple[int, Ref, Seg]] = []
d = self.data
for seg in self.segs:
start = seg.off + (-seg.va % 4)
end = seg.off + seg.filesz - 3
split = seg.off + seg.code_end - seg.va
for off in range(max(start, split + (-seg.code_end % 4)), end, 4): # data: pointer words
out.append((struct.unpack_from("<I", d, off)[0],
Ref("ptr", seg.va + off - seg.off, self.name), seg))
end = min(end, split)
pending: Dict[int, int] = {} # reg -> hi16 on the straight path (strong)
last: Dict[int, Tuple[int, int]] = {} # reg -> (hi16, lui VA): the fallback (weak)
held = set() # regs whose straight-path value is hi+lo, not hi
full: Dict[int, int] = {} # reg -> a whole address (lui+addiu, gp+addiu), straight path
seen: Dict[int, List[Tuple[int, int]]] = {} # reg -> every (hi16, lui VA) of this function
after = None # what the branch before this instruction does
for off in range(start, end, 4):
w = struct.unpack_from("<I", d, off)[0]
va = seg.va + off - seg.off
op, rs, rt = w >> 26, (w >> 21) & 31, (w >> 16) & 31
if op == 0x03:
out.append((((va + 4) & 0xF0000000) | ((w & 0x3FFFFFF) << 2),
Ref("call", va, self.name, text=False), seg))
newfull = None
if op in _USE_OPS:
text = op in _TEXT_OPS
simm = ((w & 0xFFFF) ^ 0x8000) - 0x8000
if rs in pending:
t = _addr(pending[rs], w)
out.append((t, Ref("hilo", va, self.name, text=text), seg))
if op in (0x09, 0x0D, 0x19):
newfull = t
elif rs in full and op != 0x0D:
# rX already holds a whole address: an access at a fixed offset from it
# (``sb v1,9(a2)`` stamping a digit into a string, a field after it)
t = (full[rs] + simm) & 0xFFFFFFFF
out.append((t, Ref("hilo", va, self.name, text=False, base=full[rs],
store=_STORE_WIDTH.get(op, 0), load=_LOAD_END.get(op, 0),
op=_mnemonic(op)), seg))
if op in (0x09, 0x19):
newfull = t
elif rs == GP and self.gp is not None and op != 0x0D:
t = (self.gp + simm) & 0xFFFFFFFF
out.append((t, Ref("gp", va, self.name, text=text), seg))
if op in (0x09, 0x19):
newfull = t
elif rs in last and rs not in held and va - last[rs][1] <= WEAK_REACH and text:
out.append((_addr(last[rs][0], w), Ref("hilo", va, self.name, weak=True), seg))
if text and rs not in pending and rs not in full and rs != GP:
# an earlier lui of this function into the same register, overwritten on the
# straight path but reached through a branch (OV02 0x00A80350 ``addiu a1,s1,
# 0x3348`` after ``lui s1,0xa8`` at 0x00A80294 and ``b 0x00A8031C``; s1 is
# rewritten at 0x00A802B4 on another arm): a string's only at its start
cur = last[rs][0] if rs in last and rs not in held else None
for hi in sorted({h for h, at in seen.get(rs, ()) if va - at <= WEAK_REACH} - {cur}):
out.append((_addr(hi, w), Ref("hilo", va, self.name, weak=True, hist=True), seg))
wr = rt if op == 0x0F else _writes(w)
if wr:
full.pop(wr, None)
if newfull is not None and wr == rt and after != "likely":
full[wr] = newfull
lo_add = op in (0x09, 0x0D) and rs == rt
if op == 0x0F:
if after != "likely": # a likely slot runs only on the taken path
pending[rt] = w & 0xFFFF
else:
pending.pop(rt, None)
last[rt] = (w & 0xFFFF, va)
seen.setdefault(rt, []).append((w & 0xFFFF, va))
held.discard(rt)
else:
pending.pop(wr, None)
# after ``addiu rX,rX,lo`` rX holds hi+lo on this path: until a jump
# leads to a label (where another arm's lui may arrive), a later
# ``lbu k(rX)`` is an access through the whole address, not a lui pair
if lo_add and wr in last:
held.add(wr)
else:
last.pop(wr, None)
held.discard(wr)
if after == "jump": # the delay slot ran; what follows is a label
pending.clear()
full.clear()
held.clear()
elif after == "call": # the callee clobbers the temporaries
for r in _TEMPS:
pending.pop(r, None)
full.pop(r, None)
elif after == "ret": # end of a function
pending.clear()
full.clear()
last.clear()
held.clear()
seen.clear()
after = _branch_kind(w)
return out
_MNEMONIC = {0x09: "addiu", 0x19: "daddiu", 0x20: "lb", 0x21: "lh", 0x22: "lwl", 0x23: "lw", 0x24: "lbu",
0x25: "lhu", 0x26: "lwr", 0x27: "lwu", 0x28: "sb", 0x29: "sh", 0x2A: "swl", 0x2B: "sw",
0x2C: "sdl", 0x2D: "sdr", 0x2E: "swr", 0x1A: "ldl", 0x1B: "ldr", 0x1E: "lq", 0x1F: "sq",
0x31: "lwc1", 0x35: "ldc1", 0x36: "lqc2", 0x37: "ld", 0x39: "swc1", 0x3D: "sdc1", 0x3E: "sqc2",
0x3F: "sd"}
def _mnemonic(op: int) -> str:
return _MNEMONIC.get(op, f"op{op:#x}")
def _textlike(raw: bytes) -> bool:
"""At least 2 bytes, each 0x20-0x7E, 0x09, 0x0A or from 0x80 up; and either one printable
ASCII byte or the whole run reading as EUC-JP with kana or kanji (a developer string),
so float constants and code bytes are not taken for text."""
if len(raw) < MIN_LEN:
return False
if not all(0x20 <= b <= 0x7E or b in (0x09, 0x0A) or b >= 0x80 for b in raw):
# other control bytes: the title and memory-card screens (OV02) carry 0x19 0x03 and
# 0x0C codes in their prompts; taken only with three ASCII letters in the run
if 0x7F in raw or sum(0x41 <= (b | 0x20) - 0x20 <= 0x5A for b in raw if b < 0x80) < 3:
return False
if any(0x80 <= b <= 0x9F for b in raw): # never text on the USA build, but Shift-JIS leads
return bool(_euc_hint(raw))
return any(0x21 <= b <= 0x7E for b in raw) or bool(_euc_hint(raw))
# ---- the print function's reading of a string (FUN_00197bb8, USA SLUS_208.92) ---------------
#
# At each character position the loop stops at 0x00. A byte below 0x20 is a control code
# followed by a fixed number of parameter bytes, and a parameter may be any byte, 0x00
# included (the save prompts start 0B 0E 01 01 00 00 00 0D 03 19 03). The counts are the
# ones the switch in FUN_00197bb8 steps over; the table at 0x0063EA40 that FUN_00195178
# (the ruby code's copy loop) reads gives the same numbers, with 0xFF for the two whose
# length depends on a parameter: 0x08 (one flags byte, then 2, 2, 3, 2, 2 bytes for flag
# bits 0-4, the bytes at 0x0069DE48) and 0x15 (one length byte n, then n bytes).
# 0x14, 0x1A and 0x1C-0x1F are cases that break without moving the pointer: the loop would
# read the same byte forever. 0x16 and 0x17 carry a 32-bit address (a string to print, a
# function to call). A byte from 0x80 up is one character, or two when font.us_two_byte
# (FUN_00194dd0) accepts the pair. '$' starts a $code (FUN_001970e0: the names at
# 0x0063EAA0, each handler reading ASCII digits up to ';'); its bytes are ordinary
# characters here, and a handler that does not find its ';' prints the '$' as a character.
CTRL_PARAMS = {0x01: 1, 0x02: 1, 0x03: 1, 0x04: 1, 0x05: 1, 0x06: 3, 0x07: 0, 0x09: 0, 0x0A: 0, 0x0B: 0,
0x0C: 3, 0x0D: 1, 0x0E: 5, 0x0F: 3, 0x10: 5, 0x11: 6, 0x12: 2, 0x13: 2, 0x16: 4, 0x17: 7,
0x18: 1, 0x19: 1, 0x1B: 1}
CTRL_08_BITS = (2, 2, 3, 2, 2)
CTRL_HANG = (0x14, 0x1A, 0x1C, 0x1D, 0x1E, 0x1F)
CTRL_ADDRESS = (0x16, 0x17)
DOLLAR_CODES = ("ax", "ay", "az", "rx", "ry", "init", "save", "load", "col", "bg", "shadow", "alpha",
"zoom", "xx", "ruby", "prop", "han", "mark")
MAX_PRINT = 0x1000 # longest run the scan follows as one string
class PrintError(ValueError):
def __init__(self, msg: str, pos: int):
super().__init__(msg)
self.pos = pos
def print_tokens(data: bytes, i: int, end: int) -> Tuple[List[Tuple[str, int, int]], int]:
"""The print function's reading of ``data[i:]`` up to ``end``: ([(kind, start, stop)], index
of the terminating 0x00). ``kind`` is "ctl" (a control code with its parameters) or "char".
PrintError when a code would hang the loop or the bytes end before a terminator or inside
a code's parameters."""
import font
toks: List[Tuple[str, int, int]] = []
start = i
while True:
if i >= end:
raise PrintError("no terminator: the string runs off its end", i)
b = data[i]
if b == 0:
return toks, i
if b < 0x20:
if b in CTRL_HANG:
raise PrintError(f"control byte \u27e6{b:02X}\u27e7: the print function (FUN_00197bb8) never moves "
f"past it, the game would hang", i)
if b == 0x08:
if i + 1 >= end:
raise PrintError("the string ends inside the parameters of code \u27e608\u27e7", i)
n = 1 + sum(w for k, w in enumerate(CTRL_08_BITS) if data[i + 1] >> k & 1)
elif b == 0x15:
if i + 1 >= end:
raise PrintError("the string ends inside the parameters of code \u27e615\u27e7", i)
n = data[i + 1] + 1
else:
n = CTRL_PARAMS[b]
if i + 1 + n >= end:
raise PrintError(f"the string ends inside the {n} parameter byte(s) of code \u27e6{b:02X}\u27e7",
i)
toks.append(("ctl", i, i + 1 + n))
i += 1 + n
elif b >= 0x80 and i + 1 < end and font.us_two_byte(b, data[i + 1]):
toks.append(("char", i, i + 2))
i += 2
else:
toks.append(("char", i, i + 1))
i += 1
if i - start > MAX_PRINT:
raise PrintError("longer than any string of the game", i)
def print_check(raw: bytes) -> Optional[str]:
"""None when the print function reads ``raw`` (a string without its terminator) as one
string ending exactly at its end; else why not."""
data = raw + b"\0"
try:
toks, term = print_tokens(data, 0, len(data))
except PrintError as e:
return str(e)
if term != len(raw):
return ("a NUL byte (\u27e600\u27e7) inside a string where a character belongs; the game would stop "
f"there (byte +{term})")
text = bytes(b for k, a, z in toks if k == "char" for b in raw[a:z])
for m in re.finditer(rb"\$([a-z]+)", text):
name = m.group(1).decode()
if any(name.startswith(c) for c in DOLLAR_CODES) and b";" not in text[m.end():]:
return (f"'${name}' has no ';' after it: the $code reader (FUN_001970e0) would read past the "
f"end of the string")
return None
def _print_text_ok(raw: bytes, toks: List[Tuple[str, int, int]]) -> bool:
"""A run the code points at, read by the print function's grammar, is taken for text when
it has a control code, at least three ASCII letters in character positions (or characters
that read as EUC-JP Japanese), no lone byte
0x80-0x9F as a character and no address-carrying code (0x16/0x17: never in a prompt)."""
letters = 0
ctl = False
chars = bytearray()
for k, a, z in toks:
if k == "ctl":
if raw[a] in CTRL_ADDRESS:
return False
ctl = True
continue
chars += raw[a:z]
if z - a == 1:
b = raw[a]
if 0x80 <= b <= 0x9F or b == 0x7F:
return False
letters += 0x41 <= (b | 0x20) - 0x20 <= 0x5A if b < 0x80 else 0
# Japanese between the codes (the HDD installer's EUC-JP prompts in OV02) counts as text too; with
# a control code in front, three kana are enough (the field-debug label 0D 02 'ハシゴ' at 0x006899D0,
# printed by FUN_00195760; on the retail executables this adds that run and nothing else)
return ctl and (letters >= 3 or _euc_japanese(bytes(chars), min_kana=3))
def _print_chars(raw: bytes) -> bytes:
"""The character bytes of a string, its control codes and their parameters left out."""
data = raw + b"\0"
try:
toks, _ = print_tokens(data, 0, len(data))
except PrintError:
return bytes(c for c in raw if c >= 0x20)
return b"".join(raw[a:z] for k, a, z in toks if k == "char" and raw[a] >= 0x20)
def _euc_japanese(raw: bytes, min_kana: int = 4) -> bool:
"""The bytes read as EUC-JP, at least ``min_kana`` kana or kanji, nearly all of the characters
full-width kana, kanji or full-width signs and letters (not half-width katakana, which a binary
table's 0xA1-0xDF bytes read as in Shift-JIS)."""
try:
t = raw.decode("euc_jp")
except UnicodeDecodeError:
return False
kana = sum(0x3040 <= ord(c) <= 0x30FF or 0x4E00 <= ord(c) <= 0x9FFF for c in t)
wide = sum(0x3000 <= ord(c) <= 0x303F or 0xFF01 <= ord(c) <= 0xFF5E or c in "\u2015\u2018\u2019\u201c\u201d"
for c in t)
return kana >= min_kana and 3 * (kana + wide) >= 2 * len(t.replace(" ", "").replace("\n", ""))
def _print_string(data: bytes, off: int, end: int) -> Optional[bytes]:
"""The string at ``off`` as the print function reads it, when it is one (see _print_text_ok)."""
try:
toks, term = print_tokens(data, off, end)
except PrintError:
return None
raw = data[off:term]
return raw if _print_text_ok(raw, [(k, a - off, z - off) for k, a, z in toks]) else None
def system_font_chars(raw: bytes) -> str:
"""The ASCII letters, digits and signs of a string that its own codes put in the state where
the print function draws ASCII from the 8x8 system font rather than the font file: after
0x0B (which clears the mode bits), 0x19 with parameter bit 1 clear, or ``$han0;``/``$han2;``,
and before 0x19 with bit 1 set or ``$han1;`` (the handler at 0x00196FA0 sets bit 4 for
$han1; FUN_00197bb8 takes the font file's table only with bit 4 set). The state at the string's
start is the caller's and is not counted."""
data = raw + b"\0"
try:
toks, _ = print_tokens(data, 0, len(data))
except PrintError:
return ""
han: Optional[bool] = None
out = []
for k, a, z in toks:
if k == "ctl":
if raw[a] == 0x0B:
han = False
elif raw[a] == 0x19:
han = bool(raw[a + 1] & 2)
continue
c = raw[a]
if c == 0x24:
m = re.match(rb"\$han([0-2]);", raw[a:])
if m:
han = m.group(1) == b"1"
if han is False and z - a == 1 and 0x21 <= c <= 0x7E:
out.append(chr(c))
return "".join(out)
def _address_codes(raw: bytes) -> List[bytes]:
"""The 0x16/0x17 codes of a string with their parameters, in order ([] when it does not parse)."""
data = raw + b"\0"
try:
toks, _ = print_tokens(data, 0, len(data))
except PrintError:
return []
return [raw[a:z] for k, a, z in toks if k == "ctl" and raw[a] in CTRL_ADDRESS]
def has_controls(raw: bytes) -> bool:
"""A control byte other than tab and line feed: the string is shown by the grammar."""
return any(b < 0x20 and b not in (0x09, 0x0A) for b in raw)
def show(codec, raw: bytes) -> str:
"""The tree form of a string. With control codes, each code and its parameters are \u27e6XX\u27e7
escapes (a parameter 0x20 is not a space a translator could delete); characters as the
codec writes them. Exact: codec.from_text(show(raw)) == raw."""
if not has_controls(raw):
return codec.to_text(raw)
data = raw + b"\0"
try:
toks, term = print_tokens(data, 0, len(data))
except PrintError:
return codec.to_text(raw)
if term != len(raw):
return codec.to_text(raw)
out, run = [], bytearray()
for k, a, z in toks:
if k == "ctl":
if run:
out.append(codec._decode(bytes(run), False))
run.clear()
out.append("".join(f"\u27e6{b:02X}\u27e7" for b in raw[a:z]))
else:
run += raw[a:z]
if run:
out.append(codec._decode(bytes(run), False))
t = "".join(out)
return "\u27e623\u27e7" + t[1:] if t.startswith("#") else t
def _string_at(exe: "Exe", seg: "Seg", va: int) -> Optional[bytes]:
"""The string starting at ``va``, or None: never in a code-only segment, never at a
function's first instruction (``addiu sp,sp,-N``), and it must look like text. A run
with control codes is read by the print function's grammar (``print_tokens``): its end is
the first 0x00 in a character position, not the first 0x00 (a parameter may be one)."""
if va < seg.code_end:
return None
off = seg.off + va - seg.va
if va % 4 == 0 and off + 4 <= len(exe.data):
w = struct.unpack_from("<I", exe.data, off)[0]
if w >> 16 == 0x27BD and w & 0x8000:
return None
seg_end = seg.off + seg.filesz
j = exe.data.find(b"\0", off, seg_end)
first = exe.data[off:j] if j >= 0 else exe.data[off:seg_end]
if (j >= 0 and has_controls(first)) or (off < seg_end and 0 < exe.data[off] < 0x20
and exe.data[off] not in (0x09, 0x0A)):
g = _print_string(exe.data, off, seg_end)
if g is not None:
return g
if j < 0:
return None
raw = first
return raw if _textlike(raw) else None
def _literal_start(exe: "Exe", seg: "Seg", va: int) -> bool:
"""A string start as the compiler lays literals out: 8-byte aligned, after a NUL (or at the
segment start), text by ``_string_at`` with three ASCII letters
(or Japanese, ``_euc_japanese``). The test for an address only another path's
``lui`` forms (Ref.hist), so a stray hi/lo pair cannot land in the middle of a message."""
raw = _string_at(exe, seg, va) if va % 8 == 0 else None
if raw is None or (sum(0x41 <= (c | 0x20) - 0x20 <= 0x5A for c in raw if c < 0x80) < 3
and not _euc_japanese(_print_chars(raw))):
return False
off = seg.off + va - seg.va
return off == seg.off or exe.data[off - 1] == 0
def font_table_ranges(boot: bytes, prof) -> List[Tuple[int, int]]:
"""VA ranges of the font tables the kit reads from the boot ELF (``region`` profile)."""
out = []
if prof.ascii_table_va is not None:
out.append((prof.ascii_table_va, prof.ascii_table_va + 0x200))
if prof.sys_width_va is not None:
out.append((prof.sys_width_va, prof.sys_width_va + 4 * 0x80))
if prof.kanji_list_va is not None:
va = prof.kanji_list_va
try:
while region.read_va(boot, va, 2)[0] != 0 and va < prof.kanji_list_va + 0x4000:
va += 2
except region.ElfError:
pass
out.append((prof.kanji_list_va, va + 2))
return out
class ExeSet:
"""The executables of one disc, scanned together: which strings each owns."""
def __init__(self, files: List[Tuple[str, bytes, str]], prof=None):
"""``files``: (name, bytes, role) with role "boot" or "overlay"; at most one boot."""
self.prof = prof or region.US
boot = [f for f in files if f[2] == "boot"]
self.boot: Optional[Exe] = Exe(*boot[0]) if boot else None
gp = self.boot.gp if self.boot else None
self.exes: Dict[str, Exe] = {}
if self.boot:
self.exes[self.boot.name] = self.boot
for name, data, role in files:
if role != "boot":
self.exes[name] = Exe(name, data, role, gp=gp)
overlays = [e for e in self.exes.values() if e.role != "boot"]
if self.boot:
for s in self.boot.segs:
s.resident = any(o.va < s.va + s.filesz and s.va < o.va + o.filesz
for ov in overlays for o in ov.segs)
self.tables = font_table_ranges(self.boot.data, self.prof) if self.boot else []
self.strings: Dict[str, Dict[int, ExeString]] = {}
self._build()
def _owner(self, target: int, exe: Exe, seg: Seg) -> Optional[Tuple[Exe, Seg]]:
boot = self.boot
main = (lambda va: next((s for s in boot.segs if not s.resident and s.has(va)), None)) if boot else \
(lambda va: None)
if exe.role != "boot":
own = exe.seg_of(target)
if own is not None:
return exe, own
m = main(target)
return (boot, m) if m else None
if seg.resident:
if seg.has(target):
return exe, seg
m = main(target)
return (exe, m) if m else None
m = main(target)
return (exe, m) if m else None
def _build(self) -> None:
targets: Dict[str, Dict[int, List[Ref]]] = {n: {} for n in self.exes}
extra: Dict[str, set] = {n: set() for n in self.exes} # addresses that only end slots
weak: Dict[str, set] = {n: set() for n in self.exes} # fallback addresses, not strings
derived: Dict[str, List[Tuple[int, Ref]]] = {n: [] for n in self.exes}
for exe in self.exes.values():
for target, ref, seg in exe.scan():
own = self._owner(target, exe, seg)
if own is None:
continue
if ref.base is not None:
derived[own[0].name].append((target, ref))
continue
if ref.hist and not _literal_start(own[0], own[1], target):
continue # another path's lui: an aligned string start, or nothing at all
if ref.weak and _string_at(own[0], own[1], target) is None:
# the fallback lui is a string's only when it lands on a string start; any other
# address it forms past a string's terminator still ends that string's slot
weak[own[0].name].add(target)
continue
targets[own[0].name].setdefault(target, []).append(ref)
for name, exe in self.exes.items():
tabs = self.tables if exe is self.boot else []
cands: Dict[int, Tuple[Seg, bytes]] = {}
for va, refs in sorted(targets[name].items()):
if any(a <= va < b for a, b in tabs):
continue
if not any(r.text for r in refs) or any(r.kind == "call" for r in refs):
continue
seg = exe.seg_of(va)
raw = _string_at(exe, seg, va)
if raw is not None:
cands[va] = (seg, raw)
# accesses at a fixed offset from a register that holds a whole address: a store into
# a string's own bytes (terminator included) is a stamp the edit must keep; a load there
# is a read; anything else (past the terminator, or an address formed inside) is an
# object of its own and ends the slot
starts = sorted(cands)
def inside(t: int) -> Optional[int]:
i = bisect.bisect_right(starts, t) - 1
return starts[i] if i >= 0 and t <= starts[i] + len(cands[starts[i]][1]) else None
# a fallback address inside a string's own bytes is not another object (the fallback
# misreads some accesses); one in the NUL padding after it is (Disc 1: 0x0063F730, the
# 80 bytes FUN_001a5ff8 copies, after 'cdrom0:\'; 0x00645190 after 'pfs1:/Your Saves')
extra[name] |= {t for t in weak[name] if inside(t) is None}
stamps: Dict[int, List[Tuple[int, int, Ref]]] = {}
reads: Dict[int, List[Tuple[int, Ref]]] = {}
for t, ref in derived[name]:
st = inside(t)
if st is not None and ref.store:
stamps.setdefault(st, []).append((t - st, ref.store, ref))
elif st is not None:
if ref.load:
reads.setdefault(st, []).append((t - st + ref.load, ref))
continue # a read, or a pointer walking the string (``addiu a0,a0,1``)
else:
extra[name].add(t)
bounds = sorted(set(targets[name]) | extra[name] | {a for a, _ in tabs})
found: Dict[int, ExeString] = {}
for va, (seg, raw) in cands.items():
refs = targets[name][va]
off = seg.off + va - seg.va
seg_end = seg.off + seg.filesz
k = off + len(raw)
while k < seg_end and exe.data[k] == 0:
k += 1
end = k
i = bisect.bisect_right(bounds, va)
if i < len(bounds) and bounds[i] < seg.va + seg.filesz:
end = min(end, seg.off + bounds[i] - seg.va)
slot = end - off - 1
# loads at fixed offsets that reach the terminator: the code copies the string
# with a size it knows (an inlined strcpy: ldl/ldr, lw, lb ... up to the NUL), so
# a longer text would arrive without its terminator. max is then the copy's size
rd = reads.get(va, [])
copied = max((e for e, _ in rd), default=0)
if copied < len(raw) + 1:
copied = 0
found[va] = ExeString(va, off, raw, min(slot, copied - 1) if copied else slot,
sorted((r for r in refs if r.text),
key=lambda r: (r.file != name, r.at, r.kind)),
stamps=sorted(stamps.get(va, []), key=lambda x: (x[0], x[2].at)),
copied=copied, copy_refs=sorted({r.at: r for _, r in rd}.values(),
key=lambda r: r.at) if copied else [],
slot=slot)
self.strings[name] = found
# the boot ELF's resident overlay copy and the overlay file: the same string twice
if self.boot:
for va, s in self.strings[self.boot.name].items():
seg = self.boot.seg_of(va)
if not seg.resident:
continue
for name, strs in self.strings.items():
t = strs.get(va)
if name != self.boot.name and t is not None and t.raw == s.raw:
s.twins.append((name, va))
t.twins.append((self.boot.name, va))
def debug_only(self, s: "ExeString") -> bool:
"""Every reference to the string forms its address for FUN_00195760, the debug print."""
refs = [r for r in s.refs if r.text]
return bool(refs) and all(r.kind == "hilo" and not r.weak and r.file in self.exes
and _debug_call(self.exes[r.file], r.at) for r in refs)
# -- text ------------------------------------------------------------
def tree_text(self, name: str) -> str:
exe = self.exes[name]
codec = textcodec.UsCodec()
lines = [f"# exetext 1 file={name} role={exe.role} sha256={exe.sha256}",
"# Each '### @ADDRESS max N bytes' block is one string the code points at. Edit the line under",
"# it, in place: at most N bytes as the game stores them (one byte per ASCII or Latin-1",
"# letter, one per escape). A real line break is \u27e60A\u27e7. Keep every block, in order.",
"# Keep every %-conversion (%s, %d, %x, ...) in the same order: many of these strings go to a",
"# printf-style formatter with a fixed set of arguments. Keep $codes; and where a block says the",
"# code writes bytes at run time, keep those bytes where they are.",
"# exe-import must be the last step: afterwards this disc's executable is not the retail one."]
for va, s in sorted(self.strings[name].items()):
lines.append(f"### @0x{va:08x} max {s.max} bytes")
shown = ", ".join(f"{r.kind} {'' if r.file == name else r.file + ' '}0x{r.at:08x}" for r in s.refs[:4])
more = ", ..." if len(s.refs) > 4 else ""
lines.append(f"# refs {len(s.refs)} ({shown}{more})")
if s.max < len(s.raw):
lines.append(f"# the code also points inside this string, {s.max} bytes in: the slot ends there")
for f, a in s.twins:
lines.append(f"# the same string is in {f} at 0x{a:08x}: give both the same text")
if s.copied and s.max < s.slot:
cr = ", ".join(f"{r.op} 0x{r.at:08x}" for r in s.copy_refs[:4]) + (", ..." if len(s.copy_refs) > 4 else "")
lines.append(f"# the code copies the first {s.copied} bytes of this string at fixed offsets ({cr}): "
f"max is {s.max}, not the {s.slot} bytes of NUL padding, or the copy loses its terminator")
if s.stamps:
lines.append(f"# the code writes {_stamp_text(s)} of this string at run time: keep "
f"those bytes where they are (as exported, counting from +0)")
conv = [c for c in _conversions(s.raw) if c[0] != "?"]
if conv:
lines.append("# conversions: " + " ".join(c[3] for c in conv) + " (keep them, in this order)")
if len(s.raw) == 3 and va % 4 == 0 and exe.seg_of(struct.unpack_from("<I", exe.data, s.off)[0]):
lines.append("# probably not text: these 4 bytes are also an address in this file (a pointer)")
sysf = system_font_chars(s.raw)
if sysf:
lines.append(f"# its codes draw {len(sysf)} ASCII character(s) here with the 8x8 system font (no $han1), "
f"not the font file: font-extract does not cover that font, and its glyphs have not "
f"been read")
if self.debug_only(s):
lines.append("# debug (FUN_00195760 only): drawn only by the debug print, behind a debug switch")