-
Notifications
You must be signed in to change notification settings - Fork 38
/
mgbdis.py
executable file
·1189 lines (923 loc) · 40.9 KB
/
mgbdis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Disassemble a Game Boy ROM into RGBDS compatible assembly code"""
__author__ = 'Matt Currie and contributors'
__credits__ = ['mattcurrie', 'kemenaran', 'bnzis', 'ISSOtm']
__version__ = '2.0'
__copyright__ = 'Copyright 2018 by Matt Currie'
__license__ = 'MIT'
import argparse
import glob
import hashlib
import os
import png
from shutil import copyfile
from instruction_set import instructions, cb_instructions, instruction_variants
default_symbols = [
'00:0000 RST_00',
'00:0000 .code:8',
'00:0008 RST_08',
'00:0008 .code:8',
'00:0010 RST_10',
'00:0010 .code:8',
'00:0018 RST_18',
'00:0018 .code:8',
'00:0020 RST_20',
'00:0020 .code:8',
'00:0028 RST_28',
'00:0028 .code:8',
'00:0030 RST_30',
'00:0030 .code:8',
'00:0038 RST_38',
'00:0038 .code:8',
'00:0040 VBlankInterrupt',
'00:0040 .code:8',
'00:0048 LCDCInterrupt',
'00:0048 .code:8',
'00:0050 TimerOverflowInterrupt',
'00:0050 .code:8',
'00:0058 SerialTransferCompleteInterrupt',
'00:0058 .code:8',
'00:0060 JoypadTransitionInterrupt',
'00:0060 .code:8',
'00:0100 Boot',
'00:0100 .code:4',
'00:0104 HeaderLogo',
'00:0104 .data:30',
'00:0134 HeaderTitle',
'00:0134 .text:10',
'00:0144 .data:c',
'00:0144 HeaderNewLicenseeCode',
'00:0146 HeaderSGBFlag',
'00:0147 HeaderCartridgeType',
'00:0148 HeaderROMSize',
'00:0149 HeaderRAMSize',
'00:014a HeaderDestinationCode',
'00:014b HeaderOldLicenseeCode',
'00:014c HeaderMaskROMVersion',
'00:014d HeaderComplementCheck',
'00:014e HeaderGlobalChecksum',
]
gbc_symbols = [
'00:0134 .text:b',
'00:013f HeaderManufacturerCode',
'00:013f .text:4',
'00:0143 HeaderCGBFlag',
'00:0143 .data:1'
]
hardware_labels = {
0xFF00: 'rP1',
0xFF01: 'rSB',
0xFF02: 'rSC',
0xFF04: 'rDIV',
0xFF05: 'rTIMA',
0xFF06: 'rTMA',
0xFF07: 'rTAC',
0xFF0F: 'rIF',
0xFF40: 'rLCDC',
0xFF41: 'rSTAT',
0xFF42: 'rSCY',
0xFF43: 'rSCX',
0xFF44: 'rLY',
0xFF45: 'rLYC',
0xFF46: 'rDMA',
0xFF47: 'rBGP',
0xFF48: 'rOBP0',
0xFF49: 'rOBP1',
0xFF4A: 'rWY',
0xFF4B: 'rWX',
0xFF4D: 'rKEY1',
0xFF4F: 'rVBK',
0xFF51: 'rHDMA1',
0xFF52: 'rHDMA2',
0xFF53: 'rHDMA3',
0xFF54: 'rHDMA4',
0xFF55: 'rHDMA5',
0xFF56: 'rRP',
0xFF68: 'rBCPS',
0xFF69: 'rBCPD',
0xFF6A: 'rOCPS',
0xFF6B: 'rOCPD',
0xFF70: 'rSVBK',
0xFFFF: 'rIE',
0xFF24: 'rNR50',
0xFF25: 'rNR51',
0xFF26: 'rNR52',
0xFF10: 'rNR10',
0xFF11: 'rNR11',
0xFF12: 'rNR12',
0xFF13: 'rNR13',
0xFF14: 'rNR14',
0xFF16: 'rNR21',
0xFF17: 'rNR22',
0xFF18: 'rNR23',
0xFF19: 'rNR24',
0xFF1A: 'rNR30',
0xFF1B: 'rNR31',
0xFF1C: 'rNR32',
0xFF1D: 'rNR33',
0xFF1E: 'rNR34',
0xFF20: 'rNR41',
0xFF21: 'rNR42',
0xFF22: 'rNR43',
0xFF23: 'rNR44',
0xFF76: 'rPCM12',
0xFF77: 'rPCM34',
}
ldh_a8_formatters = {
'ldh_a8': lambda value: '[{0}]'.format(hex_byte(value)),
'ld_ff00_a8': lambda value: '[{0}+{1}]'.format(hex_word(0xff00), hex_byte(value)),
'ldh_ffa8': lambda value: '[{0}]'.format(hex_word(0xff00 + value)),
}
def warn(*args, **kwargs):
print("WARNING: ", *args, **kwargs)
def abort(message):
print("FATAL: ", message)
os._exit(1)
def hex_word(value):
if style['uppercase_hex']:
return f'${value:04X}'
else:
return f'${value:04x}'
def hex_byte(value):
if style['uppercase_hex']:
return f'${value:02X}'
else:
return f'${value:02x}'
def format_hex(hex_string):
if style['uppercase_hex']:
return hex_string.upper()
else:
return hex_string.lower()
def bytes_to_string(data):
return ' '.join(hex_byte(byte) for byte in data)
def rom_address_to_mem_address(address):
if address < 0x4000:
return address
else:
return ((address % 0x4000) + 0x4000)
def to_signed(value):
if value > 127:
return (256 - value) * -1
return value
def apply_style_to_instructions(style, instructions):
# set undefined opcodes to use db/DB
for opcode, instruction in instructions.items():
if instruction.startswith('db '):
instructions[opcode] = style['db'] + ' ' + hex_byte(opcode)
# set instruction variants
for variant_name, variants in instruction_variants.items():
for opcode, instruction in variants[style[variant_name]].items():
instructions[opcode] = instruction
return instructions
class Bank:
def __init__(self, number, symbols, style, bank0, size):
self.style = style
self.bank_number = number
self.blocks = {}
self.disassembled_addresses = set()
self.symbols = symbols
self.size = size
self.bank0 = bank0
if number == 0:
self.memory_base_address = 0
self.rom_base_address = 0
else:
self.memory_base_address = 0x4000
self.rom_base_address = (number - 1) * 0x4000
self.target_addresses = dict({
'call': set(),
'jp': set(),
'jr': set()
})
self.instruction_label_prefixes = dict({
'call': 'Call',
'jp': 'Jump',
'jr': 'jr'
})
self.disassemble_block_range = dict({
'code': self.process_code_in_range,
'data': self.process_data_in_range,
'text': self.process_text_in_range,
'image': self.process_image_in_range
})
def add_target_address(self, instruction_name, address):
if address not in self.target_addresses[instruction_name]:
self.target_addresses[instruction_name].add(address)
def resolve_blocks(self):
blocks = self.symbols.get_blocks(self.bank_number, self.size)
block_start_addresses = sorted(blocks.keys())
resolved_blocks = {}
for index in range(len(block_start_addresses)):
start_address = block_start_addresses[index]
block = blocks[start_address]
end_address = start_address + block['length']
# check if there is another block after this block
next_start_address = None
if index < len(block_start_addresses) - 1:
next_start_address = block_start_addresses[index + 1]
# if the next block starts before this one finishes, then adjust end address
if next_start_address < end_address:
end_address = next_start_address
resolved_blocks[start_address] = {
'type': block['type'],
'length': end_address - start_address,
'arguments': block['arguments'],
}
if next_start_address is None and (end_address != self.memory_base_address + self.size):
# no more blocks and didn't finish at the end of the block, so finish up with a code block
resolved_blocks[end_address] = {
'type': 'code',
'length': (self.memory_base_address + self.size) - end_address,
'arguments': None
}
if next_start_address is not None and end_address < next_start_address:
# we have another block, but there is a gap until the next block, so fill in the gap with a code block
resolved_blocks[end_address] = {
'type': 'code',
'length': next_start_address - end_address,
'arguments': None
}
self.blocks = resolved_blocks
def get_label(self, address):
if self.bank_number != 0 and address < 0x4000:
return self.bank0.symbols.get_label(0, address)
return self.symbols.get_label(self.bank_number, address)
def get_label_for_instruction_operand(self, value):
# an operand value lower than $100 is more probably an actual value than an address:
# don't lookup symbols for it
if value <= 0x100:
return None
return self.get_label(value)
def get_label_for_jump_target(self, instruction_name, address):
if self.bank_number == 0:
if address not in self.disassembled_addresses:
return None
else:
is_in_switchable_bank = 0x4000 <= address < 0x8000
# if target address is in bank 0 then check if that address has been
# disassembled in bank 0
if not is_in_switchable_bank:
return self.bank0.get_label_for_jump_target(instruction_name, address)
if address not in self.disassembled_addresses:
return None
label = self.get_label(address)
if label is not None:
# if the address has a specific label then just use that
return label
if address in self.target_addresses[instruction_name]:
return self.format_label(instruction_name, address)
return None
def get_labels_for_non_code_address(self, address):
labels = []
label = self.get_label(address)
if label is not None:
is_local = label.startswith('.')
if is_local:
labels.append(label + ':')
else:
labels.append(label + '::')
return labels
def get_labels_for_address(self, address):
labels = []
label = self.get_label(address)
if label is not None:
# if the address has a specific label then just use that
is_local = label.startswith('.')
if is_local:
labels.append(label + ':')
else:
labels.append(label + '::')
else:
# otherwise, if the address was marked as a target address, generate a label
for instruction_name in ['call', 'jp', 'jr']:
if address in self.target_addresses[instruction_name]:
labels.append(self.format_label(instruction_name, address) + ':')
return labels
def format_label(self, instruction_name, address):
formatted_bank = format_hex(f'{self.bank_number:03x}')
formatted_address = format_hex(f'{address:04x}')
return f'{self.instruction_label_prefixes[instruction_name]}_{formatted_bank}_{formatted_address}'
def format_image_label(self, address):
return 'image_{0:03x}_{1:04x}'.format(self.bank_number, address)
def format_instruction(self, instruction_name, operands, address = None, source_bytes = None):
instruction = f"{self.style['indentation']}{instruction_name:<{self.style['operand_padding']}} {', '.join(operands)}"
if self.style['print_hex'] and address is not None and source_bytes is not None:
return f"{instruction:<50}; {hex_word(address)}: {bytes_to_string(source_bytes)}"
else:
return instruction.rstrip()
def format_data(self, data):
return self.format_instruction(self.style['db'], data)
def append_output(self, text):
self.output.append(text)
def append_labels_to_output(self, labels):
self.append_empty_line_if_none_already()
self.append_output('\n'.join(labels))
def append_empty_line_if_none_already(self):
if len(self.output) > 0 and self.output[len(self.output) - 1] != '':
self.append_output('')
def disassemble(self, rom, first_pass = False):
self.first_pass = first_pass
if first_pass:
self.resolve_blocks()
self.output = []
if self.bank_number == 0:
self.append_output('SECTION "ROM Bank ${0:03x}", ROM0[$0]'.format(self.bank_number))
else:
self.append_output('SECTION "ROM Bank ${0:03x}", ROMX[$4000], BANK[${0:x}]'.format(self.bank_number))
self.append_output('')
block_start_addresses = sorted(self.blocks.keys())
for index in range(len(block_start_addresses)):
start_address = block_start_addresses[index]
block = self.blocks[start_address]
end_address = start_address + block['length']
self.disassemble_block_range[block['type']](rom, self.rom_base_address + start_address, self.rom_base_address + end_address, block['arguments'])
self.append_empty_line_if_none_already()
return '\n'.join(self.output)
def process_code_in_range(self, rom, start_address, end_address, arguments = None):
if not self.first_pass and debug:
print('Disassembling code in range: {} - {}'.format(hex_word(start_address), hex_word(end_address)))
self.pc = start_address
while self.pc < end_address:
instruction = self.disassemble_at_pc(rom, end_address)
def disassemble_at_pc(self, rom, end_address):
pc = self.pc
pc_mem_address = rom_address_to_mem_address(pc)
length = 1
opcode = rom.data[pc]
comment = None
operands = None
operand_values = []
if opcode not in instructions:
abort('Unhandled opcode: {} at {}'.format(hex_byte(opcode), hex_word(pc)))
if opcode == 0xCB:
cb_opcode = rom.data[pc + 1]
length += 1
instruction_name = rom.cb_instruction_name[cb_opcode]
operands = rom.cb_instruction_operands[cb_opcode]
else:
instruction_name = rom.instruction_names[opcode]
operands = rom.instruction_operands[opcode]
if instruction_name == 'stop' or (instruction_name == 'halt' and not self.style['disable_halt_nops']):
if rom.data[pc + 1] == 0x00:
# rgbds adds a nop instruction after a stop/halt, so if that instruction
# exists then we can insert it as a stop/halt command with length 2
length += 1
else:
# otherwise handle it as a data byte
instruction_name = self.style['db']
operands = [hex_byte(opcode)]
# figure out the operand values for each operand
for operand in operands:
value = None
if operand == 'a16':
length += 2
value = rom.data[pc + 1] + rom.data[pc + 2] * 256
operand_values.append(hex_word(value))
elif operand == '[a16]':
length += 2
value = rom.data[pc + 1] + rom.data[pc + 2] * 256
label = self.get_label_for_instruction_operand(value)
if label:
operand_values.append('[' + label + ']')
else:
operand_values.append('[' + hex_word(value) + ']')
elif operand == '[$ff00+a8]' or operand == '[a8]' or operand == '[$ffa8]':
length += 1
value = rom.data[pc + 1]
full_value = 0xff00 + value
label = self.get_label_for_instruction_operand(full_value)
if label is not None:
# when referencing a label, we need to explicitely tell rgbds to use the short load opcode
instruction_name = 'ldh'
operand_values.append('[{}]'.format(label))
elif full_value in hardware_labels:
operand_values.append('[{}]'.format(hardware_labels[full_value]))
else:
# use one of the ldh_a8_formatters formatters
operand_values.append(ldh_a8_formatters[self.style['ldh_a8']](value))
elif operand == 'd8':
length += 1
value = rom.data[pc + 1]
operand_values.append(hex_byte(value))
elif operand == 'd16':
length += 2
value = rom.data[pc + 1] + rom.data[pc + 2] * 256
label = self.get_label_for_instruction_operand(value)
if label is not None:
operand_values.append(label)
else:
operand_values.append(hex_word(value))
elif operand == 'r8':
length += 1
value = to_signed(rom.data[pc + 1])
if value < 0:
operand_values.append('-' + hex_byte(abs(value)))
else:
operand_values.append(hex_byte(value))
elif operand == 'pc+r8':
length += 1
value = to_signed(rom.data[pc + 1])
# calculate the absolute address for the jump
rom_address = pc + 2 + value
relative_value = rom_address - pc
if relative_value >= 0:
operand_values.append('@+' + hex_byte(relative_value))
else:
operand_values.append('@-' + hex_byte(relative_value * -1))
# convert to banked value so it can be used as a label
value = rom_address_to_mem_address(rom_address)
# is the jump target is in this bank?
if (rom_address >= self.rom_base_address + self.memory_base_address and
rom_address < self.rom_base_address + self.memory_base_address + self.size):
# yep!
pass
else:
# don't use labels for relative jumps across banks
value = None
if rom_address < self.rom_base_address + self.memory_base_address:
# output as data, otherwise RGBDS will complain
instruction_name = self.style['db']
operand_values = [hex_byte(opcode), hex_byte(rom.data[pc + 1])]
# exit the loop to avoid processing the operands any further
break
elif operand == 'sp+r8':
length += 1
value = to_signed(rom.data[pc + 1])
if value < 0:
operand_values.append('sp-' + hex_byte(abs(value)))
else:
operand_values.append('sp+' + hex_byte(value))
elif operand == '[$ff00+c]':
operand_values.append('[{0}+c]'.format(hex_word(0xff00)))
elif type(operand) is str:
operand_values.append(operand)
else:
operand_values.append(hex_byte(operand))
if instruction_name in ['jr', 'jp', 'call'] and value is not None and value < 0x8000:
mem_address = rom_address_to_mem_address(value)
if self.first_pass:
# add the label
if mem_address >= self.memory_base_address and mem_address < self.memory_base_address + self.size:
# label in cur bank
self.add_target_address(instruction_name, mem_address)
elif mem_address < 0x4000 and self.bank0:
# label in fixed bank
self.bank0.add_target_address(instruction_name, mem_address)
else:
# fetch the label name
label = self.get_label_for_jump_target(instruction_name, mem_address)
if label is not None:
# remove the address from operand values and use the label instead
operand_values.pop()
operand_values.append(label)
# check the instruction is not spanning 2 banks
if pc + length - 1 >= end_address:
# must handle it as data
length = 1
instruction_name = self.style['db']
operand_values = [hex_byte(opcode)]
self.pc += length
if self.first_pass:
self.disassembled_addresses.add(pc_mem_address)
else:
labels = self.get_labels_for_address(pc_mem_address)
if len(labels):
self.append_labels_to_output(labels)
if comment is not None:
self.append_output(comment)
instruction_bytes = rom.data[pc:pc + length]
self.append_output(self.format_instruction(instruction_name, operand_values, pc_mem_address, instruction_bytes))
# add some empty lines after returns and jumps to break up the code blocks
if instruction_name in ['ret', 'reti', 'jr', 'jp']:
if (
instruction_name == 'jr' or
(instruction_name == 'jp' and len(operand_values) > 1) or
(instruction_name == 'ret' and len(operand_values) > 0)
):
# conditional or jr
self.append_output('')
else:
# always executes
self.append_output('')
self.append_output('')
def process_data_in_range(self, rom, start_address, end_address, arguments = None):
if not self.first_pass and debug:
print('Outputting data in range: {} - {}'.format(hex_word(start_address), hex_word(end_address)))
values = []
for address in range(start_address, end_address):
mem_address = rom_address_to_mem_address(address)
labels = self.get_labels_for_non_code_address(mem_address)
if len(labels):
# add any existing values to the output and reset the list
if len(values) > 0:
self.append_output(self.format_data(values))
values = []
self.append_labels_to_output(labels)
values.append(hex_byte(rom.data[address]))
# output max of 16 bytes per line, and ensure any remaining values are output
if len(values) == 16 or (address == end_address - 1 and len(values)):
self.append_output(self.format_data(values))
values = []
def process_text_in_range(self, rom, start_address, end_address, arguments = None):
if not self.first_pass and debug:
print('Outputting text in range: {} - {}'.format(hex_word(start_address), hex_word(end_address)))
values = []
text = ''
for address in range(start_address, end_address):
mem_address = rom_address_to_mem_address(address)
labels = self.get_labels_for_non_code_address(mem_address)
if len(labels):
# add any existing values to the output and reset the list
if len(text):
values.append('"{}"'.format(text))
text = ''
if len(values):
self.append_output(self.format_data(values))
values = []
self.append_labels_to_output(labels)
byte = rom.data[address]
if byte >= 0x20 and byte < 0x7F:
if chr(byte) in {'"', '\\', '{', '}'}:
text += '\\'
text += chr(byte)
else:
if len(text):
values.append('"{}"'.format(text))
text = ''
values.append(hex_byte(byte))
if len(text):
values.append('"{}"'.format(text))
if len(values):
self.append_output(self.format_data(values))
def process_image_in_range(self, rom, start_address, end_address, arguments = None):
if not self.first_pass and debug:
print('Outputting image in range: {} - {}'.format(hex_word(start_address), hex_word(end_address)))
if self.first_pass:
return
mem_address = rom_address_to_mem_address(start_address)
labels = self.get_labels_for_non_code_address(mem_address)
if len(labels):
self.append_labels_to_output(labels)
basename = labels[0].rstrip(':')
else:
basename = self.format_image_label(mem_address)
full_filename = rom.write_image(basename, arguments, rom.data[start_address:end_address])
self.append_output(self.format_instruction('INCBIN', ['\"' + full_filename + '\"']))
class Symbols:
def __init__(self, bank_size):
self.symbols = {}
self.blocks = {}
self.bank_size = bank_size
def load_sym_file(self, symbols_path):
f = open(symbols_path, 'r')
for line in f:
# ignore comments and empty lines
if line[0] != ';' and len(line.strip()):
self.add_symbol_definition(line)
f.close()
def add_symbol_definition(self, symbol_def):
try:
location, label = symbol_def.split()
bank, address = location.split(':')
bank = int(bank, 16)
address = int(address, 16)
except:
print("Ignored invalid symbol definition: {}\n".format(symbol_def))
else:
label_parts = label.split(':')
is_block_definition = label[0] == '.' and len(label_parts) >= 2
if is_block_definition:
# add a block
block_type = label_parts[0].lower()
data_length = int(label_parts[1], 16)
if block_type in ['.byt', '.data']:
block_type = 'data'
elif block_type in ['.asc', '.text']:
block_type = 'text'
elif block_type in ['.code']:
block_type = 'code'
elif block_type in ['.image']:
block_type = 'image'
else:
return
if len(label_parts) == 3:
arguments = label_parts[2]
else:
arguments = None
self.add_block(bank, address, block_type, data_length, arguments)
else:
# add the label
self.add_label(bank, address, label)
def add_block(self, bank, address, block_type, length, arguments = None):
memory_base_address = 0x0000 if bank == 0 else 0x4000
if address >= memory_base_address:
blocks = self.get_blocks(bank, self.bank_size)
blocks[address] = {
'type': block_type,
'length': length,
'arguments': arguments
}
def add_label(self, bank, address, label):
if bank not in self.symbols:
self.symbols[bank] = {}
is_symbol_banked = self.bank_size <= address < 0x8000
if is_symbol_banked:
self.symbols[bank][address] = label
else:
self.symbols[0][address] = label
def get_label(self, bank, address):
# attempt to find a banked symbol
is_symbol_banked = self.bank_size <= address < 0x8000
if is_symbol_banked and bank in self.symbols and address in self.symbols[bank]:
return self.symbols[bank][address]
# attempt to find a symbol in non-banked space (stored as bank 0)
if 0 in self.symbols and address in self.symbols[0]:
return self.symbols[0][address]
return None
def get_blocks(self, bank, size):
memory_base_address = 0x0000 if bank == 0 else 0x4000
if bank not in self.blocks:
self.blocks[bank] = {}
# each bank defaults to having a single code block
self.add_block(bank, memory_base_address, 'code', self.bank_size)
return self.blocks[bank]
class ROM:
def __init__(self, rom_path, style, tiny):
self.style = style
self.script_dir = os.path.dirname(os.path.realpath(__file__))
self.rom_path = rom_path
self.load(tiny)
self.split_instructions()
self.tiny = tiny
self.image_output_directory = 'gfx'
self.image_dependencies = []
print('ROM MD5 hash:', hashlib.md5(self.data).hexdigest())
self.symbols = self.load_symbols()
# add some bytes to avoid an index out of range error
# when processing last few instructions in the rom
self.data += b'\x00\x00'
size = self.rom_size
if tiny:
self.banks = [Bank(0, self.symbols, style, None, min(size, 0x8000))]
else:
self.banks = [Bank(0, self.symbols, style, None, min(size, 0x4000))]
for bank in range(1, self.num_banks):
size -= 0x4000
self.banks.append(Bank(bank, self.symbols, style, self.banks[0], min(size, 0x4000)))
def load(self, tiny):
if os.path.isfile(self.rom_path):
print('Loading "{}"...'.format(self.rom_path))
self.data = open(self.rom_path, 'rb').read()
self.rom_size = len(self.data)
if self.rom_size < 0x150:
abort("ROM is too small, doesn't even contain a header!")
self.num_banks = self.rom_size // 0x4000
if self.rom_size % 0x4000 != 0:
warn(f"ROM size (${self.rom_size:04x}) is not a multiple of $4000!")
self.num_banks += 1 # Count that incomplete bank
if tiny:
if self.num_banks > 2:
abort(f"ROM is ${self.rom_size:04x} bytes large, tiny ROMs can only be $8000 at most")
self.num_banks = 1
else:
abort('"{}" not found'.format(self.rom_path))
def split_instructions(self):
# split the instructions and operands
self.instruction_names = {}
self.instruction_operands = {}
self.cb_instruction_name = {}
self.cb_instruction_operands = {}
for opcode in instructions:
instruction_parts = instructions[opcode].split()
self.instruction_names[opcode] = instruction_parts[0]
if len(instruction_parts) > 1:
self.instruction_operands[opcode] = instruction_parts[1].split(',')
else:
self.instruction_operands[opcode] = []
for cb_opcode in cb_instructions:
instruction_parts = cb_instructions[cb_opcode].split()
self.cb_instruction_name[cb_opcode] = instruction_parts[0]
if len(instruction_parts) > 1:
self.cb_instruction_operands[cb_opcode] = instruction_parts[1].split(',')
else:
self.cb_instruction_operands[cb_opcode] = []
def load_symbols(self):
symbols = Symbols(0x8000 if self.tiny else 0x4000)
for symbol_def in default_symbols:
symbols.add_symbol_definition(symbol_def)
if self.supports_gbc():
for symbol_def in gbc_symbols:
symbols.add_symbol_definition(symbol_def)
symbols_path = os.path.splitext(self.rom_path)[0] + '.sym'
if os.path.isfile(symbols_path):
print('Processing symbol file "{}"...'.format(symbols_path))
symbols.load_sym_file(symbols_path)
return symbols
def supports_gbc(self):
return ((self.data[0x143] & 0x80) == 0x80)
def disassemble(self, output_dir):
self.output_directory = os.path.abspath(output_dir.rstrip(os.sep))
if os.path.exists(self.output_directory):
if not args.overwrite:
abort('Output directory "{}" already exists!'.format(self.output_directory))
if not os.path.isdir(self.output_directory):
abort('Output path "{}" already exists and is not a directory!'.format(self.output_directory))
else:
os.makedirs(self.output_directory)
print('Generating labels...')
self.generate_labels()
self.image_dependencies = []
print('Generating disassembly', end='')
if debug:
print('')
for bank in range(0, self.num_banks):
self.write_bank_asm(bank)
self.copy_hardware_inc()
self.write_game_asm()
self.write_makefile()
print('\nDisassembly generated in "{}"'.format(self.output_directory))
def generate_labels(self):
for bank in range(0, self.num_banks):
self.banks[bank].disassemble(rom, True)
def write_bank_asm(self, bank):
if not debug:
# progress indicator
print('.', end='', flush=True)
path = os.path.join(self.output_directory, 'bank_{0:03x}.asm'.format(bank))
f = open(path, 'w')
self.write_header(f)
f.write(self.banks[bank].disassemble(rom))
f.close()
def write_header(self, f):
f.write('; Disassembly of "{}"\n'.format(os.path.basename(self.rom_path)))
f.write('; This file was created with:\n')
f.write('; {}\n'.format(app_name))
f.write('; https://github.com/mattcurrie/mgbdis\n\n')
def copy_hardware_inc(self):
src = os.path.join(self.script_dir, 'hardware.inc')
dest = os.path.join(self.output_directory, 'hardware.inc')
copyfile(src, dest)
def write_game_asm(self):
path = os.path.join(self.output_directory, 'game.asm')
f = open(path, 'w')
self.write_header(f)
f.write('INCLUDE "hardware.inc"')
for bank in range(0, self.num_banks):
f.write('\nINCLUDE "bank_{0:03x}.asm"'.format(bank))
f.close()
def write_image(self, basename, arguments, data):
# defaults
width = 128
palette = 0xe4
bpp = 2
# process arguments
if arguments is not None:
for argument in arguments.split(','):