forked from gbdev/rgbds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
1503 lines (1330 loc) · 40.4 KB
/
main.cpp
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
/* SPDX-License-Identifier: MIT */
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include "extern/getopt.hpp"
#include "helpers.hpp"
#include "platform.hpp"
#include "version.hpp"
static constexpr uint16_t UNSPECIFIED = 0x200;
static_assert(UNSPECIFIED > 0xFF, "UNSPECIFIED should not be in byte range!");
static constexpr off_t BANK_SIZE = 0x4000;
// Short options
static char const *optstring = "Ccf:i:jk:L:l:m:n:Op:r:st:Vv";
/*
* Equivalent long options
* Please keep in the same order as short opts
*
* Also, make sure long opts don't create ambiguity:
* A long opt's name should start with the same letter as its short opt,
* except if it doesn't create any ambiguity (`verbose` versus `version`).
* This is because long opt matching, even to a single char, is prioritized
* over short opt matching
*/
static option const longopts[] = {
{"color-only", no_argument, nullptr, 'C'},
{"color-compatible", no_argument, nullptr, 'c'},
{"fix-spec", required_argument, nullptr, 'f'},
{"game-id", required_argument, nullptr, 'i'},
{"non-japanese", no_argument, nullptr, 'j'},
{"new-licensee", required_argument, nullptr, 'k'},
{"logo", required_argument, nullptr, 'L'},
{"old-licensee", required_argument, nullptr, 'l'},
{"mbc-type", required_argument, nullptr, 'm'},
{"rom-version", required_argument, nullptr, 'n'},
{"overwrite", no_argument, nullptr, 'O'},
{"pad-value", required_argument, nullptr, 'p'},
{"ram-size", required_argument, nullptr, 'r'},
{"sgb-compatible", no_argument, nullptr, 's'},
{"title", required_argument, nullptr, 't'},
{"version", no_argument, nullptr, 'V'},
{"validate", no_argument, nullptr, 'v'},
{nullptr, no_argument, nullptr, 0 }
};
static void printUsage() {
fputs(
"Usage: rgbfix [-jOsVv] [-C | -c] [-f <fix_spec>] [-i <game_id>] [-k <licensee>]\n"
" [-L <logo_file>] [-l <licensee_byte>] [-m <mbc_type>]\n"
" [-n <rom_version>] [-p <pad_value>] [-r <ram_size>] [-t <title_str>]\n"
" <file> ...\n"
"Useful options:\n"
" -m, --mbc-type <value> set the MBC type byte to this value; refer\n"
" to the man page for a list of values\n"
" -p, --pad-value <value> pad to the next valid size using this value\n"
" -r, --ram-size <code> set the cart RAM size byte to this value\n"
" -V, --version print RGBFIX version and exit\n"
" -v, --validate fix the header logo and both checksums (-f lhg)\n"
"\n"
"For help, use `man rgbfix' or go to https://rgbds.gbdev.io/docs/\n",
stderr
);
}
static uint8_t nbErrors;
[[gnu::format(printf, 1, 2)]] static void report(char const *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
if (nbErrors != UINT8_MAX)
nbErrors++;
}
enum MbcType {
ROM = 0x00,
ROM_RAM = 0x08,
ROM_RAM_BATTERY = 0x09,
MBC1 = 0x01,
MBC1_RAM = 0x02,
MBC1_RAM_BATTERY = 0x03,
MBC2 = 0x05,
MBC2_BATTERY = 0x06,
MMM01 = 0x0B,
MMM01_RAM = 0x0C,
MMM01_RAM_BATTERY = 0x0D,
MBC3 = 0x11,
MBC3_TIMER_BATTERY = 0x0F,
MBC3_TIMER_RAM_BATTERY = 0x10,
MBC3_RAM = 0x12,
MBC3_RAM_BATTERY = 0x13,
MBC5 = 0x19,
MBC5_RAM = 0x1A,
MBC5_RAM_BATTERY = 0x1B,
MBC5_RUMBLE = 0x1C,
MBC5_RUMBLE_RAM = 0x1D,
MBC5_RUMBLE_RAM_BATTERY = 0x1E,
MBC6 = 0x20,
MBC7_SENSOR_RUMBLE_RAM_BATTERY = 0x22,
POCKET_CAMERA = 0xFC,
BANDAI_TAMA5 = 0xFD,
HUC3 = 0xFE,
HUC1_RAM_BATTERY = 0xFF,
// "Extended" values (still valid, but not directly actionable)
// A high byte of 0x01 means TPP1, the low byte is the requested features
// This does not include SRAM, which is instead implied by a non-zero SRAM size
// Note: Multiple rumble speeds imply rumble
TPP1 = 0x100,
TPP1_RUMBLE = 0x101,
TPP1_MULTIRUMBLE = 0x102, // Should not be possible
TPP1_MULTIRUMBLE_RUMBLE = 0x103,
TPP1_TIMER = 0x104,
TPP1_TIMER_RUMBLE = 0x105,
TPP1_TIMER_MULTIRUMBLE = 0x106, // Should not be possible
TPP1_TIMER_MULTIRUMBLE_RUMBLE = 0x107,
TPP1_BATTERY = 0x108,
TPP1_BATTERY_RUMBLE = 0x109,
TPP1_BATTERY_MULTIRUMBLE = 0x10A, // Should not be possible
TPP1_BATTERY_MULTIRUMBLE_RUMBLE = 0x10B,
TPP1_BATTERY_TIMER = 0x10C,
TPP1_BATTERY_TIMER_RUMBLE = 0x10D,
TPP1_BATTERY_TIMER_MULTIRUMBLE = 0x10E, // Should not be possible
TPP1_BATTERY_TIMER_MULTIRUMBLE_RUMBLE = 0x10F,
// Error values
MBC_NONE = UNSPECIFIED, // No MBC specified, do not act on it
MBC_BAD, // Specified MBC does not exist / syntax error
MBC_WRONG_FEATURES, // MBC incompatible with specified features
MBC_BAD_RANGE, // MBC number out of range
MBC_BAD_TPP1, // Invalid TPP1 major or minor revision numbers
};
static void printAcceptedMBCNames() {
fputs("\tROM ($00) [aka ROM_ONLY]\n", stderr);
fputs("\tMBC1 ($01), MBC1+RAM ($02), MBC1+RAM+BATTERY ($03)\n", stderr);
fputs("\tMBC2 ($05), MBC2+BATTERY ($06)\n", stderr);
fputs("\tROM+RAM ($08) [deprecated], ROM+RAM+BATTERY ($09) [deprecated]\n", stderr);
fputs("\tMMM01 ($0B), MMM01+RAM ($0C), MMM01+RAM+BATTERY ($0D)\n", stderr);
fputs("\tMBC3+TIMER+BATTERY ($0F), MBC3+TIMER+RAM+BATTERY ($10)\n", stderr);
fputs("\tMBC3 ($11), MBC3+RAM ($12), MBC3+RAM+BATTERY ($13)\n", stderr);
fputs("\tMBC5 ($19), MBC5+RAM ($1A), MBC5+RAM+BATTERY ($1B)\n", stderr);
fputs("\tMBC5+RUMBLE ($1C), MBC5+RUMBLE+RAM ($1D), MBC5+RUMBLE+RAM+BATTERY ($1E)\n", stderr);
fputs("\tMBC6 ($20)\n", stderr);
fputs("\tMBC7+SENSOR+RUMBLE+RAM+BATTERY ($22)\n", stderr);
fputs("\tPOCKET_CAMERA ($FC)\n", stderr);
fputs("\tBANDAI_TAMA5 ($FD) [aka TAMA5]\n", stderr);
fputs("\tHUC3 ($FE)\n", stderr);
fputs("\tHUC1+RAM+BATTERY ($FF)\n", stderr);
fputs("\n\tTPP1_1.0, TPP1_1.0+RUMBLE, TPP1_1.0+MULTIRUMBLE, TPP1_1.0+TIMER,\n", stderr);
fputs("\tTPP1_1.0+TIMER+RUMBLE, TPP1_1.0+TIMER+MULTIRUMBLE, TPP1_1.0+BATTERY,\n", stderr);
fputs("\tTPP1_1.0+BATTERY+RUMBLE, TPP1_1.0+BATTERY+MULTIRUMBLE,\n", stderr);
fputs("\tTPP1_1.0+BATTERY+TIMER, TPP1_1.0+BATTERY+TIMER+RUMBLE,\n", stderr);
fputs("\tTPP1_1.0+BATTERY+TIMER+MULTIRUMBLE\n", stderr);
}
static uint8_t tpp1Rev[2];
/*
* @return False on failure
*/
static bool readMBCSlice(char const *&name, char const *expected) {
while (*expected) {
char c = *name++;
if (c == '\0') // Name too short
return false;
if (c >= 'a' && c <= 'z') // Perform the comparison case-insensitive
c = c - 'a' + 'A';
else if (c == '_') // Treat underscores as spaces
c = ' ';
if (c != *expected++)
return false;
}
return true;
}
static MbcType parseMBC(char const *name) {
if (!strcasecmp(name, "help")) {
fputs("Accepted MBC names:\n", stderr);
printAcceptedMBCNames();
exit(0);
}
if ((name[0] >= '0' && name[0] <= '9') || name[0] == '$') {
int base = 0;
if (name[0] == '$') {
name++;
base = 16;
}
// Parse number, and return it as-is (unless it's too large)
char *endptr;
unsigned long mbc = strtoul(name, &endptr, base);
if (*endptr)
return MBC_BAD;
if (mbc > 0xFF)
return MBC_BAD_RANGE;
return static_cast<MbcType>(mbc);
} else {
// Begin by reading the MBC type:
uint16_t mbc;
char const *ptr = name;
// Trim off leading whitespace
while (*ptr == ' ' || *ptr == '\t')
ptr++;
#define tryReadSlice(expected) \
do { \
if (!readMBCSlice(ptr, expected)) \
return MBC_BAD; \
} while (0)
switch (*ptr++) {
case 'R': // ROM / ROM_ONLY
case 'r':
tryReadSlice("OM");
// Handle optional " ONLY"
while (*ptr == ' ' || *ptr == '\t' || *ptr == '_')
ptr++;
if (*ptr == 'O' || *ptr == 'o') {
ptr++;
tryReadSlice("NLY");
}
mbc = ROM;
break;
case 'M': // MBC{1, 2, 3, 5, 6, 7} / MMM01
case 'm':
switch (*ptr++) {
case 'B':
case 'b':
switch (*ptr++) {
case 'C':
case 'c':
break;
default:
return MBC_BAD;
}
switch (*ptr++) {
case '1':
mbc = MBC1;
break;
case '2':
mbc = MBC2;
break;
case '3':
mbc = MBC3;
break;
case '5':
mbc = MBC5;
break;
case '6':
mbc = MBC6;
break;
case '7':
mbc = MBC7_SENSOR_RUMBLE_RAM_BATTERY;
break;
default:
return MBC_BAD;
}
break;
case 'M':
case 'm':
tryReadSlice("M01");
mbc = MMM01;
break;
default:
return MBC_BAD;
}
break;
case 'P': // POCKET_CAMERA
case 'p':
tryReadSlice("OCKET CAMERA");
mbc = POCKET_CAMERA;
break;
case 'B': // BANDAI_TAMA5
case 'b':
tryReadSlice("ANDAI TAMA5");
mbc = BANDAI_TAMA5;
break;
case 'T': // TAMA5 / TPP1
case 't':
switch (*ptr++) {
case 'A':
tryReadSlice("MA5");
mbc = BANDAI_TAMA5;
break;
case 'P': {
tryReadSlice("P1");
// Parse version
while (*ptr == ' ' || *ptr == '_')
ptr++;
// Major
char *endptr;
unsigned long val = strtoul(ptr, &endptr, 10);
if (endptr == ptr) {
report("error: Failed to parse TPP1 major revision number\n");
return MBC_BAD_TPP1;
}
ptr = endptr;
if (val != 1) {
report("error: RGBFIX only supports TPP1 version 1.0\n");
return MBC_BAD_TPP1;
}
tpp1Rev[0] = val;
tryReadSlice(".");
// Minor
val = strtoul(ptr, &endptr, 10);
if (endptr == ptr) {
report("error: Failed to parse TPP1 minor revision number\n");
return MBC_BAD_TPP1;
}
ptr = endptr;
if (val > 0xFF) {
report("error: TPP1 minor revision number must be 8-bit\n");
return MBC_BAD_TPP1;
}
tpp1Rev[1] = val;
mbc = TPP1;
break;
}
default:
return MBC_BAD;
}
break;
case 'H': // HuC{1, 3}
case 'h':
tryReadSlice("UC");
switch (*ptr++) {
case '1':
mbc = HUC1_RAM_BATTERY;
break;
case '3':
mbc = HUC3;
break;
default:
return MBC_BAD;
}
break;
default:
return MBC_BAD;
}
// Read "additional features"
uint8_t features = 0;
static constexpr uint8_t RAM = 1 << 7;
static constexpr uint8_t BATTERY = 1 << 6;
static constexpr uint8_t TIMER = 1 << 5;
static constexpr uint8_t RUMBLE = 1 << 4;
static constexpr uint8_t SENSOR = 1 << 3;
static constexpr uint8_t MULTIRUMBLE = 1 << 2;
for (;;) {
// Trim off trailing whitespace
while (*ptr == ' ' || *ptr == '\t' || *ptr == '_')
ptr++;
// If done, start processing "features"
if (!*ptr)
break;
// We expect a '+' at this point
if (*ptr++ != '+')
return MBC_BAD;
// Trim off leading whitespace
while (*ptr == ' ' || *ptr == '\t' || *ptr == '_')
ptr++;
switch (*ptr++) {
case 'B': // BATTERY
case 'b':
tryReadSlice("ATTERY");
features |= BATTERY;
break;
case 'M':
case 'm':
tryReadSlice("ULTIRUMBLE");
features |= MULTIRUMBLE;
break;
case 'R': // RAM or RUMBLE
case 'r':
switch (*ptr++) {
case 'U':
case 'u':
tryReadSlice("MBLE");
features |= RUMBLE;
break;
case 'A':
case 'a':
if (*ptr != 'M' && *ptr != 'm')
return MBC_BAD;
ptr++;
features |= RAM;
break;
default:
return MBC_BAD;
}
break;
case 'S': // SENSOR
case 's':
tryReadSlice("ENSOR");
features |= SENSOR;
break;
case 'T': // TIMER
case 't':
tryReadSlice("IMER");
features |= TIMER;
break;
default:
return MBC_BAD;
}
}
#undef tryReadSlice
switch (mbc) {
case ROM:
if (!features)
break;
mbc = ROM_RAM - 1;
static_assert(ROM_RAM + 1 == ROM_RAM_BATTERY, "Enum sanity check failed!");
static_assert(MBC1 + 1 == MBC1_RAM, "Enum sanity check failed!");
static_assert(MBC1 + 2 == MBC1_RAM_BATTERY, "Enum sanity check failed!");
static_assert(MMM01 + 1 == MMM01_RAM, "Enum sanity check failed!");
static_assert(MMM01 + 2 == MMM01_RAM_BATTERY, "Enum sanity check failed!");
[[fallthrough]];
case MBC1:
case MMM01:
if (features == RAM)
mbc++;
else if (features == (RAM | BATTERY))
mbc += 2;
else if (features)
return MBC_WRONG_FEATURES;
break;
case MBC2:
if (features == BATTERY)
mbc = MBC2_BATTERY;
else if (features)
return MBC_WRONG_FEATURES;
break;
case MBC3:
// Handle timer, which also requires battery
if (features & TIMER) {
if (!(features & BATTERY))
fprintf(stderr, "warning: MBC3+TIMER implies BATTERY\n");
features &= ~(TIMER | BATTERY); // Reset those bits
mbc = MBC3_TIMER_BATTERY;
// RAM is handled below
}
static_assert(MBC3 + 1 == MBC3_RAM, "Enum sanity check failed!");
static_assert(MBC3 + 2 == MBC3_RAM_BATTERY, "Enum sanity check failed!");
static_assert(
MBC3_TIMER_BATTERY + 1 == MBC3_TIMER_RAM_BATTERY, "Enum sanity check failed!"
);
if (features == RAM)
mbc++;
else if (features == (RAM | BATTERY))
mbc += 2;
else if (features)
return MBC_WRONG_FEATURES;
break;
case MBC5:
if (features & RUMBLE) {
features &= ~RUMBLE;
mbc = MBC5_RUMBLE;
}
static_assert(MBC5 + 1 == MBC5_RAM, "Enum sanity check failed!");
static_assert(MBC5 + 2 == MBC5_RAM_BATTERY, "Enum sanity check failed!");
static_assert(MBC5_RUMBLE + 1 == MBC5_RUMBLE_RAM, "Enum sanity check failed!");
static_assert(MBC5_RUMBLE + 2 == MBC5_RUMBLE_RAM_BATTERY, "Enum sanity check failed!");
if (features == RAM)
mbc++;
else if (features == (RAM | BATTERY))
mbc += 2;
else if (features)
return MBC_WRONG_FEATURES;
break;
case MBC6:
case POCKET_CAMERA:
case BANDAI_TAMA5:
case HUC3:
// No extra features accepted
if (features)
return MBC_WRONG_FEATURES;
break;
case MBC7_SENSOR_RUMBLE_RAM_BATTERY:
if (features != (SENSOR | RUMBLE | RAM | BATTERY))
return MBC_WRONG_FEATURES;
break;
case HUC1_RAM_BATTERY:
if (features != (RAM | BATTERY)) // HuC1 expects RAM+BATTERY
return MBC_WRONG_FEATURES;
break;
case TPP1:
if (features & RAM)
fprintf(
stderr, "warning: TPP1 requests RAM implicitly if given a non-zero RAM size"
);
if (features & BATTERY)
mbc |= 0x08;
if (features & TIMER)
mbc |= 0x04;
if (features & MULTIRUMBLE)
mbc |= 0x03; // Also set the rumble flag
if (features & RUMBLE)
mbc |= 0x01;
if (features & SENSOR)
return MBC_WRONG_FEATURES;
break;
}
// Trim off trailing whitespace
while (*ptr == ' ' || *ptr == '\t')
ptr++;
// If there is still something past the whitespace, error out
if (*ptr)
return MBC_BAD;
return static_cast<MbcType>(mbc);
}
}
static char const *mbcName(MbcType type) {
switch (type) {
case ROM:
return "ROM";
case ROM_RAM:
return "ROM+RAM";
case ROM_RAM_BATTERY:
return "ROM+RAM+BATTERY";
case MBC1:
return "MBC1";
case MBC1_RAM:
return "MBC1+RAM";
case MBC1_RAM_BATTERY:
return "MBC1+RAM+BATTERY";
case MBC2:
return "MBC2";
case MBC2_BATTERY:
return "MBC2+BATTERY";
case MMM01:
return "MMM01";
case MMM01_RAM:
return "MMM01+RAM";
case MMM01_RAM_BATTERY:
return "MMM01+RAM+BATTERY";
case MBC3:
return "MBC3";
case MBC3_TIMER_BATTERY:
return "MBC3+TIMER+BATTERY";
case MBC3_TIMER_RAM_BATTERY:
return "MBC3+TIMER+RAM+BATTERY";
case MBC3_RAM:
return "MBC3+RAM";
case MBC3_RAM_BATTERY:
return "MBC3+RAM+BATTERY";
case MBC5:
return "MBC5";
case MBC5_RAM:
return "MBC5+RAM";
case MBC5_RAM_BATTERY:
return "MBC5+RAM+BATTERY";
case MBC5_RUMBLE:
return "MBC5+RUMBLE";
case MBC5_RUMBLE_RAM:
return "MBC5+RUMBLE+RAM";
case MBC5_RUMBLE_RAM_BATTERY:
return "MBC5+RUMBLE+RAM+BATTERY";
case MBC6:
return "MBC6";
case MBC7_SENSOR_RUMBLE_RAM_BATTERY:
return "MBC7+SENSOR+RUMBLE+RAM+BATTERY";
case POCKET_CAMERA:
return "POCKET CAMERA";
case BANDAI_TAMA5:
return "BANDAI TAMA5";
case HUC3:
return "HUC3";
case HUC1_RAM_BATTERY:
return "HUC1+RAM+BATTERY";
case TPP1:
return "TPP1";
case TPP1_RUMBLE:
return "TPP1+RUMBLE";
case TPP1_MULTIRUMBLE:
case TPP1_MULTIRUMBLE_RUMBLE:
return "TPP1+MULTIRUMBLE";
case TPP1_TIMER:
return "TPP1+TIMER";
case TPP1_TIMER_RUMBLE:
return "TPP1+TIMER+RUMBLE";
case TPP1_TIMER_MULTIRUMBLE:
case TPP1_TIMER_MULTIRUMBLE_RUMBLE:
return "TPP1+TIMER+MULTIRUMBLE";
case TPP1_BATTERY:
return "TPP1+BATTERY";
case TPP1_BATTERY_RUMBLE:
return "TPP1+BATTERY+RUMBLE";
case TPP1_BATTERY_MULTIRUMBLE:
case TPP1_BATTERY_MULTIRUMBLE_RUMBLE:
return "TPP1+BATTERY+MULTIRUMBLE";
case TPP1_BATTERY_TIMER:
return "TPP1+BATTERY+TIMER";
case TPP1_BATTERY_TIMER_RUMBLE:
return "TPP1+BATTERY+TIMER+RUMBLE";
case TPP1_BATTERY_TIMER_MULTIRUMBLE:
case TPP1_BATTERY_TIMER_MULTIRUMBLE_RUMBLE:
return "TPP1+BATTERY+TIMER+MULTIRUMBLE";
// Error values
case MBC_NONE:
case MBC_BAD:
case MBC_WRONG_FEATURES:
case MBC_BAD_RANGE:
case MBC_BAD_TPP1:
unreachable_();
}
unreachable_();
}
static bool hasRAM(MbcType type) {
switch (type) {
case ROM:
case MBC1:
case MBC2: // Technically has RAM, but not marked as such
case MBC2_BATTERY:
case MMM01:
case MBC3:
case MBC3_TIMER_BATTERY:
case MBC5:
case MBC5_RUMBLE:
case MBC6: // TODO: not sure
case BANDAI_TAMA5: // TODO: not sure
case MBC_NONE:
case MBC_BAD:
case MBC_WRONG_FEATURES:
case MBC_BAD_RANGE:
case MBC_BAD_TPP1:
return false;
case ROM_RAM:
case ROM_RAM_BATTERY:
case MBC1_RAM:
case MBC1_RAM_BATTERY:
case MMM01_RAM:
case MMM01_RAM_BATTERY:
case MBC3_TIMER_RAM_BATTERY:
case MBC3_RAM:
case MBC3_RAM_BATTERY:
case MBC5_RAM:
case MBC5_RAM_BATTERY:
case MBC5_RUMBLE_RAM:
case MBC5_RUMBLE_RAM_BATTERY:
case MBC7_SENSOR_RUMBLE_RAM_BATTERY:
case POCKET_CAMERA:
case HUC3:
case HUC1_RAM_BATTERY:
return true;
// TPP1 may or may not have RAM, don't call this function for it
case TPP1:
case TPP1_RUMBLE:
case TPP1_MULTIRUMBLE:
case TPP1_MULTIRUMBLE_RUMBLE:
case TPP1_TIMER:
case TPP1_TIMER_RUMBLE:
case TPP1_TIMER_MULTIRUMBLE:
case TPP1_TIMER_MULTIRUMBLE_RUMBLE:
case TPP1_BATTERY:
case TPP1_BATTERY_RUMBLE:
case TPP1_BATTERY_MULTIRUMBLE:
case TPP1_BATTERY_MULTIRUMBLE_RUMBLE:
case TPP1_BATTERY_TIMER:
case TPP1_BATTERY_TIMER_RUMBLE:
case TPP1_BATTERY_TIMER_MULTIRUMBLE:
case TPP1_BATTERY_TIMER_MULTIRUMBLE_RUMBLE:
break;
}
unreachable_();
}
static uint8_t const nintendoLogo[] = {
0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B, 0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D,
0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E, 0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99,
0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC, 0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E,
};
static uint8_t fixSpec = 0;
static constexpr uint8_t FIX_LOGO = 1 << 7;
static constexpr uint8_t TRASH_LOGO = 1 << 6;
static constexpr uint8_t FIX_HEADER_SUM = 1 << 5;
static constexpr uint8_t TRASH_HEADER_SUM = 1 << 4;
static constexpr uint8_t FIX_GLOBAL_SUM = 1 << 3;
static constexpr uint8_t TRASH_GLOBAL_SUM = 1 << 2;
static enum { DMG, BOTH, CGB } model = DMG; // If DMG, byte is left alone
static char const *gameID = nullptr;
static uint8_t gameIDLen;
static bool japanese = true;
static char const *logoFilename = nullptr;
static uint8_t logo[sizeof(nintendoLogo)] = {};
static char const *newLicensee = nullptr;
static uint8_t newLicenseeLen;
static uint16_t oldLicensee = UNSPECIFIED;
static MbcType cartridgeType = MBC_NONE;
static uint16_t romVersion = UNSPECIFIED;
static bool overwriteRom = false; // If false, warn when overwriting non-zero non-identical bytes
static uint16_t padValue = UNSPECIFIED;
static uint16_t ramSize = UNSPECIFIED;
static bool sgb = false; // If false, SGB flags are left alone
static char const *title = nullptr;
static uint8_t titleLen;
static uint8_t maxTitleLen() {
return gameID ? 11 : model != DMG ? 15 : 16;
}
static ssize_t readBytes(int fd, uint8_t *buf, size_t len) {
// POSIX specifies that lengths greater than SSIZE_MAX yield implementation-defined results
assume(len <= SSIZE_MAX);
ssize_t total = 0;
while (len) {
ssize_t ret = read(fd, buf, len);
if (ret == -1 && errno != EINTR) // Return errors, unless we only were interrupted
return -1;
// EOF reached
if (ret == 0)
return total;
// If anything was read, accumulate it, and continue
if (ret != -1) {
total += ret;
len -= ret;
buf += ret;
}
}
return total;
}
static ssize_t writeBytes(int fd, uint8_t *buf, size_t len) {
// POSIX specifies that lengths greater than SSIZE_MAX yield implementation-defined results
assume(len <= SSIZE_MAX);
ssize_t total = 0;
while (len) {
ssize_t ret = write(fd, buf, len);
if (ret == -1 && errno != EINTR) // Return errors, unless we only were interrupted
return -1;
// If anything was written, accumulate it, and continue
if (ret != -1) {
total += ret;
len -= ret;
buf += ret;
}
}
return total;
}
/*
* @param rom0 A pointer to rom0
* @param addr What address to check
* @param fixedByte The fixed byte at the address
* @param areaName Name to be displayed in the warning message
*/
static void overwriteByte(uint8_t *rom0, uint16_t addr, uint8_t fixedByte, char const *areaName) {
uint8_t origByte = rom0[addr];
if (!overwriteRom && origByte != 0 && origByte != fixedByte)
fprintf(stderr, "warning: Overwrote a non-zero byte in the %s\n", areaName);
rom0[addr] = fixedByte;
}
/*
* @param rom0 A pointer to rom0
* @param startAddr What address to begin checking from
* @param fixed The fixed bytes at the address
* @param size How many bytes to check
* @param areaName Name to be displayed in the warning message
*/
static void overwriteBytes(
uint8_t *rom0, uint16_t startAddr, uint8_t const *fixed, uint8_t size, char const *areaName
) {
if (!overwriteRom) {
for (uint8_t i = 0; i < size; i++) {
uint8_t origByte = rom0[i + startAddr];
if (origByte != 0 && origByte != fixed[i]) {
fprintf(stderr, "warning: Overwrote a non-zero byte in the %s\n", areaName);
break;
}
}
}
memcpy(&rom0[startAddr], fixed, size);
}
/*
* @param input File descriptor to be used for reading
* @param output File descriptor to be used for writing, may be equal to `input`
* @param name The file's name, to be displayed for error output
* @param fileSize The file's size if known, 0 if not.
*/
static void processFile(int input, int output, char const *name, off_t fileSize) {
// Both of these should be true for seekable files, and neither otherwise
if (input == output)
assume(fileSize != 0);
else
assume(fileSize == 0);
uint8_t rom0[BANK_SIZE];
ssize_t rom0Len = readBytes(input, rom0, sizeof(rom0));
// Also used as how many bytes to write back when fixing in-place
ssize_t headerSize = (cartridgeType & 0xFF00) == TPP1 ? 0x154 : 0x150;
if (rom0Len == -1) {
report("FATAL: Failed to read \"%s\"'s header: %s\n", name, strerror(errno));
return;
} else if (rom0Len < headerSize) {
report(
"FATAL: \"%s\" too short, expected at least %jd ($%jx) bytes, got only %jd\n",
name,
static_cast<intmax_t>(headerSize),
static_cast<intmax_t>(headerSize),
static_cast<intmax_t>(rom0Len)
);
return;
}
// Accept partial reads if the file contains at least the header
if (fixSpec & (FIX_LOGO | TRASH_LOGO))
overwriteBytes(rom0, 0x0104, logo, sizeof(logo), logoFilename ? "logo" : "Nintendo logo");
if (title)
overwriteBytes(rom0, 0x134, reinterpret_cast<uint8_t const *>(title), titleLen, "title");
if (gameID)
overwriteBytes(
rom0, 0x13F, reinterpret_cast<uint8_t const *>(gameID), gameIDLen, "manufacturer code"
);
if (model != DMG)
overwriteByte(rom0, 0x143, model == BOTH ? 0x80 : 0xC0, "CGB flag");
if (newLicensee)
overwriteBytes(
rom0,
0x144,
reinterpret_cast<uint8_t const *>(newLicensee),
newLicenseeLen,
"new licensee code"
);
if (sgb)
overwriteByte(rom0, 0x146, 0x03, "SGB flag");
// If a valid MBC was specified...
if (cartridgeType < MBC_NONE) {
uint8_t byte = cartridgeType;
if ((cartridgeType & 0xFF00) == TPP1) {
// Cartridge type isn't directly actionable, translate it
byte = 0xBC;
// The other TPP1 identification bytes will be written below
}
overwriteByte(rom0, 0x147, byte, "cartridge type");
}
// ROM size will be written last, after evaluating the file's size
if ((cartridgeType & 0xFF00) == TPP1) {
uint8_t const tpp1Code[2] = {0xC1, 0x65};
overwriteBytes(rom0, 0x149, tpp1Code, sizeof(tpp1Code), "TPP1 identification code");
overwriteBytes(rom0, 0x150, tpp1Rev, sizeof(tpp1Rev), "TPP1 revision number");
if (ramSize != UNSPECIFIED)
overwriteByte(rom0, 0x152, ramSize, "RAM size");
overwriteByte(rom0, 0x153, cartridgeType & 0xFF, "TPP1 feature flags");
} else {
// Regular mappers
if (ramSize != UNSPECIFIED)
overwriteByte(rom0, 0x149, ramSize, "RAM size");
if (!japanese)
overwriteByte(rom0, 0x14A, 0x01, "destination code");
}
if (oldLicensee != UNSPECIFIED)
overwriteByte(rom0, 0x14B, oldLicensee, "old licensee code");
else if (sgb && rom0[0x14B] != 0x33)
fprintf(
stderr,
"warning: SGB compatibility enabled, but old licensee was 0x%02x, not 0x33\n",
rom0[0x14B]
);
if (romVersion != UNSPECIFIED)
overwriteByte(rom0, 0x14C, romVersion, "mask ROM version number");
// Remain to be handled the ROM size, and header checksum.
// The latter depends on the former, and so will be handled after it.
// The former requires knowledge of the file's total size, so read that first.
uint16_t globalSum = 0;
// To keep file sizes fairly reasonable, we'll cap the amount of banks at 65536.
// Official mappers only go up to 512 banks, but at least the TPP1 spec allows up to
// 65536 banks = 1 GiB.
// This should be reasonable for the time being, and may be extended later.
std::vector<uint8_t> romx; // Buffer of ROMX bank data
uint32_t nbBanks = 1; // Number of banks *targeted*, including ROM0
size_t totalRomxLen = 0; // *Actual* size of ROMX data
uint8_t bank[BANK_SIZE]; // Temp buffer used to store a whole bank's worth of data
// Handle ROMX
if (input == output) {
if (fileSize >= 0x10000 * BANK_SIZE) {
report("FATAL: \"%s\" has more than 65536 banks\n", name);
return;
}
// This should be guaranteed from the size cap...
static_assert(0x10000 * BANK_SIZE <= SSIZE_MAX, "Max input file size too large for OS");
// Compute number of banks and ROMX len from file size
nbBanks = (fileSize + (BANK_SIZE - 1)) / BANK_SIZE;
// = ceil(totalRomxLen / BANK_SIZE)
totalRomxLen = fileSize >= BANK_SIZE ? fileSize - BANK_SIZE : 0;
} else if (rom0Len == BANK_SIZE) {
// Copy ROMX when reading a pipe, and we're not at EOF yet
for (;;) {
romx.resize(nbBanks * BANK_SIZE);
ssize_t bankLen = readBytes(input, &romx[(nbBanks - 1) * BANK_SIZE], BANK_SIZE);
// Update bank count, ONLY IF at least one byte was read
if (bankLen) {
// We're gonna read another bank, check that it won't be too much