Repository navigation
Expand file tree
/
Copy pathrom.go
More file actions
600 lines (560 loc) · 17.1 KB
/
Copy pathrom.go
File metadata and controls
600 lines (560 loc) · 17.1 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
package dash
// Reference game pages used to verify this detector:
// https://randomyoshiyt.itch.io/binary-land
// .nes
// https://kininia.itch.io/gb-dungeon
// .gb
// https://coffeevalenbat.itch.io/pizza-delivery-re-heated
// .gbc
// https://walfie.itch.io/walfies-nonograms
// Analogue Pocket .pocket pushed with butler
// https://thalamusdigital.itch.io/cave-dave-game-boy-color
// Analogue Pocket .pocket, color
// https://bbbbbr.itch.io/gb-wordyl
// zip of .pocket files, one per language
// https://joyrider3774.itch.io/waternet
// .pocket next to the README and box art
// https://pyro-pyro.itch.io/sekhmets-playground
// homebrew .gba
// https://panelix.itch.io/panelix
// homebrew .gba
// https://poolo.itch.io/hamster-blaster-3000
// homebrew .nds with the logo
// https://digitaldesigndude.itch.io/fishing-the-deep
// homebrew .nds without logo or title, entry points only
// https://goodboygalaxy.itch.io/goodboy-galaxy-demo
// 3DS .cia packages (upload 4360172, all eight languages)
// https://team-disposable.itch.io/angelsong
// .sfc
// https://salvatoretosti.itch.io/runic-64
// homebrew .z64
// https://teamultrarare.itch.io/styx
// homebrew .z64
// https://geese-bumps.itch.io/the-weave
// Mega Drive .bin with SEGA header
// https://bonaf.itch.io/master-system-brawl
// .bin carrying a SEGA header, reported as md
// https://dilshan2k14.itch.io/regulate-3x3-demo
// PC .iso, correctly not a ROM
import (
"bytes"
"encoding/binary"
"regexp"
"strings"
)
// romDetector finds console ROMs and disc images by extension, then checks
// the system's header where the format has one. Formats without a header
// are trusted on extension alone, flagged, and capped at the largest
// cartridge the system ever shipped. ".md" is only accepted with the SEGA
// header, since it is also Markdown; ".bin" only with a Sega header.
//
// Details: "system" (nes, snes, gb, gbc, pocket, gba, nds, 3ds, md, 32x,
// sms, gg, pce, lynx, ngp, a26, c64, zx, amiga, n64, psx, ps2, psp, saturn,
// segacd, dreamcast, or "" for a disc image whose system could not be read),
// "confidence" ("ext" when the header was absent or not checked),
// "format" (for disc images: "cue", "iso", "chd"; for 3DS: "cia", "3dsx",
// "3ds", "cci"), "color" (pocket only: the ROM asks for Game Boy Color
// mode).
type romDetector struct{}
// romCheck inspects a file and returns the system, whether the header
// confirmed it, and whether the file is a ROM at all.
type romCheck func(s *scan, index int, ext string) (system string, confirmed bool, ok bool)
var romExts = map[string]romCheck{
".nes": checkNES,
".sfc": checkSNES,
".smc": checkSNES,
".gb": checkGameBoy,
".gbc": checkGameBoy,
".pocket": checkGameBoy,
".gba": checkGBA,
".nds": checkNDS,
".cia": checkCIA,
".3dsx": check3DSX,
".3ds": checkCCI,
".cci": checkCCI,
".md": checkMegaDrive,
".gen": checkMegaDrive,
".32x": checkMegaDrive,
".bin": checkSegaBin,
".sms": checkMasterSystem,
".gg": checkMasterSystem,
".pce": extOnly("pce"),
".lnx": checkLynx,
".ngp": checkNeoGeoPocket,
".ngc": checkNeoGeoPocket,
".a26": extOnly("a26"),
".d64": checkD64,
".prg": extOnly("c64"),
".t64": checkT64,
".tap": checkTAP,
".tzx": checkTZX,
".z80": checkZ80,
".sna": checkSNA,
".szx": checkSZX,
".adf": checkADF,
".z64": checkN64,
".n64": checkN64,
".v64": checkN64,
".cue": checkCue,
".iso": checkISO,
".chd": checkCHD,
}
func (romDetector) detect(s *scan) error {
for index, lower := range s.lowerFiles {
ext := getExt(lower)
check, ok := romExts[ext]
if !ok {
continue
}
system, confirmed, isROM := check(s, index, ext)
if !isROM {
continue
}
info := &EngineInfo{Engine: EngineROM}
info.detail("system", system)
if !confirmed {
info.detail("confidence", "ext")
}
if system == "pocket" && gameBoyColor(s, index) {
info.detail("color", true)
}
switch ext {
case ".cue", ".iso", ".chd", ".cia", ".3dsx", ".3ds", ".cci":
info.detail("format", ext[1:])
}
s.addFileCandidate(index, FlavorROM, info)
}
return nil
}
// extOnlyMaxSize caps extension-only ROMs so a stray file with the same
// extension is not mistaken for a cartridge.
var extOnlyMaxSize = map[string]int64{
"pce": 4 << 20,
"a26": 64 << 10,
"c64": 256 << 10,
"snes": 8 << 20,
"md": 8 << 20,
"32x": 8 << 20,
"sms": 1 << 20,
"gg": 1 << 20,
"lynx": 2 << 20,
"amiga": 2 << 20,
}
func extOnlyOK(s *scan, index int, system string) bool {
max, ok := extOnlyMaxSize[system]
return !ok || s.container.Files[index].Size <= max
}
func extOnly(system string) romCheck {
return func(s *scan, index int, _ string) (string, bool, bool) {
return system, false, extOnlyOK(s, index, system)
}
}
func checkNES(s *scan, index int, _ string) (string, bool, bool) {
head := s.readHead(index, 4)
if string(head) == "NES\x1a" {
return "nes", true, true
}
return "", false, false
}
// checkSNES looks for the checksum complement at the LoROM or HiROM header
// location, skipping a 512-byte copier header when the size betrays one.
func checkSNES(s *scan, index int, _ string) (string, bool, bool) {
size := s.container.Files[index].Size
var skip int64
if size%1024 == 512 {
skip = 512
}
r, err := s.open(index)
if err != nil {
return "", false, false
}
for _, off := range []int64{0x7fdc, 0xffdc} {
b := r.readAt(skip+off, 4)
if b == nil {
continue
}
complement := uint16(b[0]) | uint16(b[1])<<8
checksum := uint16(b[2]) | uint16(b[3])<<8
if complement^checksum == 0xffff {
return "snes", true, true
}
}
return "snes", false, extOnlyOK(s, index, "snes")
}
var nintendoLogoHead = []byte{0xce, 0xed, 0x66, 0x66, 0xcc, 0x0d, 0x00, 0x0b}
// analogueLogoHead replaces the Nintendo logo in Game Boy ROMs built for
// the Analogue Pocket (GB Studio and GBDK's "ap" port). The hardware
// registers are remapped too, so these only run on a Pocket core.
var analogueLogoHead = []byte{0x01, 0x10, 0xce, 0xef, 0x00, 0x00, 0x44, 0xaa}
// checkGameBoy goes by the logo rather than the extension, so a .pocket
// carrying the Nintendo logo is a plain Game Boy ROM and a .gb carrying the
// Analogue logo is a Pocket ROM.
func checkGameBoy(s *scan, index int, ext string) (string, bool, bool) {
r, err := s.open(index)
if err != nil {
return "", false, false
}
switch logo := r.readAt(0x104, 8); {
case bytes.Equal(logo, analogueLogoHead):
return "pocket", true, true
case !bytes.Equal(logo, nintendoLogoHead):
return "", false, false
case ext == ".gbc" || gameBoyColor(s, index):
return "gbc", true, true
}
return "gb", true, true
}
// gameBoyColor reads the CGB flag of a Game Boy header.
func gameBoyColor(s *scan, index int) bool {
r, err := s.open(index)
if err != nil {
return false
}
flag := r.readAt(0x143, 1)
return flag != nil && flag[0]&0x80 != 0
}
var gbaLogoHead = []byte{0x24, 0xff, 0xae, 0x51, 0x69, 0x9a, 0xa2, 0x21}
func checkGBA(s *scan, index int, _ string) (string, bool, bool) {
r, err := s.open(index)
if err != nil {
return "", false, false
}
if bytes.Equal(r.readAt(0x04, 8), gbaLogoHead) {
return "gba", true, true
}
return "", false, false
}
// checkNDS accepts the Nintendo logo, or, for homebrew that leaves the
// logo and title blank, ARM9 and ARM7 entry points inside main RAM (or
// shared WRAM for the ARM7).
func checkNDS(s *scan, index int, _ string) (string, bool, bool) {
r, err := s.open(index)
if err != nil {
return "", false, false
}
if bytes.Equal(r.readAt(0xc0, 8), gbaLogoHead) {
return "nds", true, true
}
hdr := r.readAt(0x20, 0x18)
if hdr == nil {
return "", false, false
}
arm9Entry := binary.LittleEndian.Uint32(hdr[4:8])
arm7Entry := binary.LittleEndian.Uint32(hdr[0x14:0x18])
inMainRAM := func(a uint32) bool { return a >= 0x02000000 && a < 0x02400000 }
inSharedWRAM := func(a uint32) bool { return a >= 0x03780000 && a < 0x03808000 }
if inMainRAM(arm9Entry) && (inMainRAM(arm7Entry) || inSharedWRAM(arm7Entry)) {
return "nds", true, true
}
return "", false, false
}
// CIA has no magic, so check that the header and aligned section sizes fit
// the file. https://www.3dbrew.org/wiki/CIA
func checkCIA(s *scan, index int, _ string) (string, bool, bool) {
h := s.readHead(index, 0x20)
if len(h) != 0x20 || binary.LittleEndian.Uint32(h) != 0x2020 ||
binary.LittleEndian.Uint16(h[4:]) != 0 {
return "", false, false
}
sizes := []uint64{
uint64(binary.LittleEndian.Uint32(h[8:])),
uint64(binary.LittleEndian.Uint32(h[12:])),
uint64(binary.LittleEndian.Uint32(h[16:])),
binary.LittleEndian.Uint64(h[24:]),
uint64(binary.LittleEndian.Uint32(h[20:])),
}
size := uint64(s.container.Files[index].Size)
var end uint64 = 0x2020
for i, sectionSize := range sizes {
if sectionSize == 0 {
if i == 4 {
break // metadata is optional
}
return "", false, false
}
start := (end + 63) &^ uint64(63)
if start > size || sectionSize > size-start {
return "", false, false
}
end = start + sectionSize
}
return "3ds", true, true
}
func check3DSX(s *scan, index int, _ string) (string, bool, bool) {
h := s.readHead(index, 0x20)
if len(h) != 0x20 || string(h[:4]) != "3DSX" {
return "", false, false
}
headerSize := int64(binary.LittleEndian.Uint16(h[4:]))
if headerSize < 0x20 || headerSize > s.container.Files[index].Size {
return "", false, false
}
return "3ds", true, true
}
// .3ds is also a 3D Studio model extension, so require the NCSD header.
func checkCCI(s *scan, index int, _ string) (string, bool, bool) {
r, err := s.open(index)
if err != nil || s.container.Files[index].Size < 0x200 {
return "", false, false
}
if string(r.readAt(0x100, 4)) == "NCSD" {
return "3ds", true, true
}
return "", false, false
}
func checkMegaDrive(s *scan, index int, ext string) (string, bool, bool) {
system := "md"
if ext == ".32x" {
system = "32x"
}
r, err := s.open(index)
if err != nil {
return "", false, false
}
hdr := r.readAt(0x100, 16)
if hdr == nil || !bytes.HasPrefix(hdr, []byte("SEGA")) {
if ext == ".md" {
return "", false, false
}
return system, false, extOnlyOK(s, index, system)
}
if bytes.Contains(hdr, []byte("32X")) {
system = "32x"
}
return system, true, true
}
// checkSegaBin accepts a .bin only when it carries a Mega Drive or Master
// System header; the extension alone means nothing.
func checkSegaBin(s *scan, index int, _ string) (string, bool, bool) {
if system, ok, _ := checkMegaDrive(s, index, ".bin"); ok {
return system, true, true
}
if system, ok, _ := checkMasterSystem(s, index, ".bin"); ok {
return system, true, true
}
return "", false, false
}
func checkMasterSystem(s *scan, index int, ext string) (string, bool, bool) {
system := "sms"
if ext == ".gg" {
system = "gg"
}
r, err := s.open(index)
if err != nil {
return "", false, false
}
for _, off := range []int64{0x7ff0, 0x3ff0, 0x1ff0} {
if string(r.readAt(off, 8)) == "TMR SEGA" {
return system, true, true
}
}
if ext == ".bin" {
return "", false, false
}
return system, false, extOnlyOK(s, index, system)
}
func checkLynx(s *scan, index int, _ string) (string, bool, bool) {
if string(s.readHead(index, 4)) == "LYNX" {
return "lynx", true, true
}
return "lynx", false, extOnlyOK(s, index, "lynx")
}
func checkNeoGeoPocket(s *scan, index int, _ string) (string, bool, bool) {
head := s.readHead(index, 28)
if bytes.HasSuffix(head, []byte("SNK CORPORATION")) {
return "ngp", true, true
}
return "", false, false
}
// checkD64 accepts the standard 35 and 40 track disk sizes, with and
// without error bytes.
func checkD64(s *scan, index int, _ string) (string, bool, bool) {
switch s.container.Files[index].Size {
case 174848, 175531, 196608, 197376:
return "c64", true, true
}
return "c64", false, extOnlyOK(s, index, "c64")
}
func checkT64(s *scan, index int, _ string) (string, bool, bool) {
head := s.readHead(index, 32)
if bytes.HasPrefix(head, []byte("C64")) {
return "c64", true, true
}
return "", false, false
}
// checkTAP tells the two tape formats that share the extension apart: a
// C64 tape has a signature, a ZX Spectrum one is a run of blocks, each a
// length and that many bytes that XOR to zero.
func checkTAP(s *scan, index int, _ string) (string, bool, bool) {
head := s.readHead(index, 12)
if string(head) == "C64-TAPE-RAW" {
return "c64", true, true
}
if len(head) < 4 {
return "", false, false
}
size := int(binary.LittleEndian.Uint16(head))
if size < 2 {
return "", false, false
}
block := s.readHead(index, 2+size)
if len(block) != 2+size {
return "", false, false
}
var sum byte
for _, b := range block[2:] {
sum ^= b
}
if sum != 0 {
return "", false, false
}
return "zx", true, true
}
func checkTZX(s *scan, index int, _ string) (string, bool, bool) {
head := s.readHead(index, 8)
if string(head) == "ZXTape!\x1a" {
return "zx", true, true
}
return "", false, false
}
// checkZ80 reads the snapshot's version from its header. Versions 2 and 3
// leave the first header's PC at zero and say how long the extra header
// after it is. Version 1 is the header and 48K of memory, or compressed
// memory closed by an end marker.
func checkZ80(s *scan, index int, _ string) (string, bool, bool) {
head := s.readHead(index, 32)
if len(head) < 32 {
return "", false, false
}
size := s.container.Files[index].Size
if head[6] == 0 && head[7] == 0 {
extra := binary.LittleEndian.Uint16(head[30:])
switch extra {
case 23, 54, 55:
if size >= 32+int64(extra) {
return "zx", true, true
}
}
return "", false, false
}
flags := head[12]
if flags == 0xff {
flags = 1
}
if flags&0x20 == 0 {
if size == 30+48<<10 {
return "zx", true, true
}
return "", false, false
}
if string(s.readTail(index, 4)) == "\x00\xed\xed\x00" {
return "zx", true, true
}
return "", false, false
}
// checkSNA accepts the sizes of a 48K snapshot and the two 128K ones.
func checkSNA(s *scan, index int, _ string) (string, bool, bool) {
switch s.container.Files[index].Size {
case 49179, 131103, 147487:
return "zx", true, true
}
return "", false, false
}
func checkSZX(s *scan, index int, _ string) (string, bool, bool) {
head := s.readHead(index, 4)
if string(head) == "ZXST" {
return "zx", true, true
}
return "", false, false
}
// checkADF looks for an AmigaDOS boot block; NDOS or blank disks have none.
func checkADF(s *scan, index int, _ string) (string, bool, bool) {
head := s.readHead(index, 4)
if len(head) == 4 && string(head[:3]) == "DOS" && head[3] < 8 {
return "amiga", true, true
}
return "amiga", false, extOnlyOK(s, index, "amiga")
}
func checkN64(s *scan, index int, _ string) (string, bool, bool) {
head := s.readHead(index, 4)
switch string(head) {
case "\x80\x37\x12\x40", "\x37\x80\x40\x12", "\x40\x12\x37\x80", "\x12\x40\x80\x37":
return "n64", true, true
}
return "", false, false
}
var cueFilePattern = regexp.MustCompile(`(?im)^\s*FILE\s+"([^"]+)"|^\s*FILE\s+(\S+)`)
// checkCue reads the first FILE entry of a cue sheet and identifies the
// system from the first sector of that track.
func checkCue(s *scan, index int, _ string) (string, bool, bool) {
head := s.readHead(index, 4096)
m := cueFilePattern.FindSubmatch(head)
if m == nil {
return "", false, false
}
name := string(m[1])
if name == "" {
name = string(m[2])
}
name = strings.ToLower(strings.ReplaceAll(name, "\\", "/"))
binIndex, ok := s.file(joinPath(parentDir(s.lowerFiles[index]), name))
if !ok {
return "", false, false
}
r, err := s.open(binIndex)
if err != nil {
return "", false, false
}
// raw 2352-byte sectors: 12 sync + 4 header, then 8 more for mode 2
for _, off := range []int64{16, 24, 0} {
if system := discSystem(r.readAt(off, 64)); system != "" {
return system, true, true
}
}
return "", false, false
}
func checkISO(s *scan, index int, _ string) (string, bool, bool) {
r, err := s.open(index)
if err != nil {
return "", false, false
}
if system := discSystem(r.readAt(0, 64)); system != "" {
return system, true, true
}
// primary volume descriptor at sector 16
pvd := r.readAt(0x8000, 40)
if pvd == nil || string(pvd[1:6]) != "CD001" {
return "", false, false
}
sysID := strings.TrimSpace(string(pvd[8:40]))
switch {
case strings.HasPrefix(sysID, "PSP GAME"):
return "psp", true, true
case strings.HasPrefix(sysID, "PLAYSTATION"):
// PS1 discs carry the license text in the system area, checked above
return "ps2", true, true
}
return "", false, false
}
// discSystem recognizes the system area text at the start of a disc.
func discSystem(sector []byte) string {
switch {
case bytes.Contains(sector, []byte("Sony Computer Entertainment")):
return "psx"
case bytes.HasPrefix(sector, []byte("SEGA SEGASATURN")):
return "saturn"
case bytes.HasPrefix(sector, []byte("SEGADISCSYSTEM")):
return "segacd"
case bytes.HasPrefix(sector, []byte("SEGA SEGAKATANA")):
return "dreamcast"
}
return ""
}
// checkCHD accepts the container without opening it: hunks are compressed
// and the system would need a decompression pass.
func checkCHD(s *scan, index int, _ string) (string, bool, bool) {
if string(s.readHead(index, 8)) == "MComprHD" {
return "", false, true
}
return "", false, false
}