-
Notifications
You must be signed in to change notification settings - Fork 0
/
UEF2ROM.py
executable file
·1505 lines (1155 loc) · 58.1 KB
/
UEF2ROM.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 python
"""
Copyright (C) 2015 David Boddie <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import commands, os, stat, struct, sys, tempfile
from tools import format_data, joystick, patcher, UEFfile
from compressors import distance_pair
header_template_file = "asm/romfs-template.oph"
minimal_header_template_file = "asm/romfs-minimal-template.oph"
# Each compressed file entry is
# trigger address (2) + source address (2) + destination address (2)
# + destination end address (2) + count mask (1) + offset bits (1) = 10
compressed_entry_size = 10
res_dir = os.path.split(__file__)[0]
__usage__ = \
"""Usage: %s [-f <file indices>]
[(-m [-M <custom routine oph file> <custom routine label>]
[-I <custom routine oph file> <custom routine label>])
| ([-p] [-t] [-T] [-w <workspace>] [-l])]
[-p1]
[-s] [-b [-a] [-r|-x] [-B <boot page>]]
[-c <load addresses>] [-cbits <compression bits>]
[-pf <patch file>]
[-P <bank info address> <ROM index>]
<UEF file> <ROM file> [<ROM file>]
"""
__description__ = \
"""The file indices can be given as a colon-separated list and can include
hyphen-separated ranges of indices. Additionally, a special value of 's' can
be used to indicate the end of a ROM, so that files following this will be
added to a new ROM.
The first ROM image can be specified to be a minimal ROM with the -m option.
Otherwise, it will contain code to use a persistent ROM pointer.
The second ROM image will always be minimal, but can be specified to use a
persistent ROM pointer if the -p option is given and the first ROM is not a
minimal ROM.
If a minimal ROM image is not used, the -t option can be used to specify
that code to override *TAPE calls should be used. Additionally, the -T option
can be used to add code to trap filing system checks and always report that
the cassette filing system is in use.
The workspace for the ROM can be given as a hexadecimal value with the -w option
and specifies the address in memory where the persistent ROM pointer will be
stored; also the code and old BYTEV vector address for *TAPE interception (if
used) and the code and old ARGSV vector address is filing system checks are
intercepted. The workspace defaults to a00.
If you specify a pair of addresses separated by a colon (e.g, d3f:ef97) then the
second address will be used for the BYTEV vector address.
The -p1 option causes code to be inserted into the boot sequence that disables
the Plus 1 before loading any files.
The -l option determines whether the first ROM will be read again after the
second ROM has been accessed. By default, the first ROM will not be readable
to ensure that files on the second ROM following a split file can be read.
If the -s option is specified, files may be split between ROMs.
If the -b option is specified, the first ROM will be run when selected.
Additionally, if the -a option is given, the ROM will be made auto-bootable.
If the -B option is also specified, the PAGE for subsequent BASIC programs
can be specified as a hexadecimal number.
The -r option is used to specify that the first file must be executed with *RUN.
The -x option indicates that *EXEC is used to execute the first file.
The -c option is used to indicate that files should be compressed, and is used
to supply information about the location in memory where they should be
decompressed. This is followed by colon-separated lists of load addresses,
themselves separated using slashes.
Additionally, the compression algorithm can be tuned by specifying the number
of bits to use to store offsets in the compression data, using the -cbits option
to do this. The default value of 4 is reasonable for most files.
The -P option causes code to be included that writes to the paging register
at 0xfc00. The code reads from the bank info address specified to obtain a base
page number and adds the specified ROM index (base 10) to it in order to swap
in the ROM from the resulting bank number.
The -M option allows a custom piece of code to be used to respond to the star
command that is otherwise not used for minimal ROMs.
The -I option is like the -M option except that the custom code is not tied to
a star command and will be run before any other initialisation
code that may also be inserted into the ROM by other options.
The -L option allows a custom piece of code to be run after the last file has
been read, accepting the name of the Ophis file to assemble and the name of
the label in the file that is the start of the subroutine to call.
The -pf option allows a set of patches to be applied to files in the UEF before
they are encoded in a ROM.
"""
def _open(file_name):
return open(os.path.join(res_dir, file_name))
def plural_str(n, singular, plural):
if n == 1:
return singular
else:
return plural
class AddressInfo:
def __init__(self, name, addr, src_label, decomp_addr, decomp_end_addr,
offset_bits):
self.name = name
self.addr = addr
self.src_label = src_label
self.decomp_addr = decomp_addr
self.decomp_end_addr = decomp_end_addr
self.offset_bits = offset_bits
class Block:
def __init__(self, data, info):
self.data = data
self.info = info
class Compressed(Block):
def __init__(self, data, info, raw_length, offset_bits, first_block,
short_header):
Block.__init__(self, data, info)
self.raw_length = raw_length
self.offset_bits = offset_bits
self.first_block = first_block
self.short_header = short_header
def format_data(data):
s = ""
i = 0
while i < len(data):
s += ".byte " + ",".join(map(lambda c: "$%02x" % ord(c), data[i:i+16])) + "\n"
i += 16
return s
def read_block(block):
# Read the block
name = ''
a = 1
while 1:
c = block[a]
if ord(c) != 0: # was > 32:
name = name + c
a = a + 1
if ord(c) == 0:
break
load = struct.unpack("<I", block[a:a+4])[0]
exec_addr = struct.unpack("<I", block[a+4:a+8])[0]
block_number = struct.unpack("<H", block[a+8:a+10])[0]
flags = struct.unpack("<B", block[a+12])[0]
data = block[a+19:-2]
if len(data) > 256:
data = data[:256]
return (name, load, exec_addr, data, block_number, flags)
def write_block(u, name, load, exec_, data, n, flags, address):
# Write the alignment character
out = "*"+name[:10]+"\000"
# Load address
out = out + struct.pack("<I", load)
# Execution address
out = out + struct.pack("<I", exec_)
# Block number
out = out + struct.pack("<H", n)
# Block length
out = out + struct.pack("<H", len(data))
# Block flags
out = out + struct.pack("<B", flags)
# Next address
out = out + struct.pack("<I", address)
# Header CRC
out = out + struct.pack("<H", u.crc(out[1:]))
if data:
# Block data
out += data
# Block CRC
out += struct.pack("<H", u.crc(data))
return out
def compress_file_or_blocks(encoded_raw_data, compress_offset_bits, block_size):
if compress_file_blocks:
# Obtain a list of pieces for processing.
new_compressed_pieces = distance_pair.compress_blocks(
encoded_raw_data, block_size)
decoded_raw_data = distance_pair.decompress_blocks(new_compressed_pieces)
else:
if compress_offset_bits != None:
cdata = distance_pair.compress_file(encoded_raw_data,
offset_bits = compress_offset_bits)
else:
# Construct a list of tuples containing the length of compressed
# data, the number of offset bits used to compress it and the data
# itself.
dlength = len(encoded_raw_data)
compression_results = []
# Put a default entry in the list corresponding to uncompressed
# data.
#compression_results.append((dlength, 0, encoded_raw_data))
for compress_offset_bits in range(3, 8):
cdata = distance_pair.compress_file(encoded_raw_data,
offset_bits = compress_offset_bits)
l = len(cdata)
#if l >= dlength:
# continue
compression_results.append((l, compress_offset_bits, cdata))
compression_results.sort()
l, compress_offset_bits, cdata = compression_results[0]
# If returning a compressed file, create a list containing only one
# piece for processing.
new_compressed_pieces = [[compress_offset_bits, encoded_raw_data, cdata]]
if compress_offset_bits == 0:
# If the uncompressed data was shortest then return it instead of
# compressed data. This is currently unused but handled in the
# compress_file function.
decoded_raw_data = encoded_raw_data
else:
decoded_raw_data = distance_pair.decompress(cdata, compress_offset_bits)
return decoded_raw_data, new_compressed_pieces
def compress_file(uef_files, index, decomp_addr, execution_addr, details, roms,
r, address, end_address, file_addresses, data_addresses,
files, triggers):
# When compressing, for all files other than the initial boot file,
# insert a header with no block data into the stream followed by
# compressed data and skip all other blocks in the file.
chunk = uef_files[index][0]
name, load, exec_, block_data, this, flags = info = read_block(chunk)
load = load & 0xffff
if decomp_addr is not None:
load = decomp_addr
if execution_addr is not None:
exec_ = execution_addr
# Concatenate the raw data from all the chunks in the file.
raw_data = ""
for chunk in uef_files[index]:
raw_data += read_block(chunk)[3]
encoded_raw_data = map(ord, raw_data)
this = 0
compressed_pieces = []
blocks = []
while encoded_raw_data or compressed_pieces:
# Compress the raw data.
compress_offset_bits = details[r]["compress offset bits"]
decoded_raw_data, new_compressed_pieces = compress_file_or_blocks(
encoded_raw_data, compress_offset_bits, compress_block_size)
if decoded_raw_data != encoded_raw_data:
sys.stderr.write("Error when compressing file %s. "
"Decompressed data did not match the original data.\n" % name)
sys.exit(1)
# Insert new compressed data before any already queued. This handles
# the case where the end of a ROM was encountered and the remaining
# data needed to be compressed again.
compressed_pieces = new_compressed_pieces + compressed_pieces
print "Attempted to compress %s from %i bytes to %i %s of compressed data:" % (
repr(name)[1:-1], len(encoded_raw_data), len(compressed_pieces),
plural_str(len(compressed_pieces), "piece", "pieces"))
first_block = True
while compressed_pieces:
compress_offset_bits, enc_raw_data, encoded_compressed_data = \
compressed_pieces.pop(0)
clength = len(encoded_compressed_data)
if compress_offset_bits != 0:
print " %02x: %i bytes with %i-bit offset at load address $%x." % (
this, clength, compress_offset_bits, load)
else:
print " %02x: %i bytes of uncompressed data at load address $%x." % (
this, clength, load)
# Create a block with only a header and no data.
if first_block or not compressed_pieces:
info = (name, load, exec_, "", this, 0x0)
header = write_block(u, name, load, exec_, "", this, 0x0, 0)
else:
info = (name, load, exec_, "", this, 0)
header = "\x23"
# Calculate the space between the end of the ROM and the
# current address, leaving room for an end of ROM marker.
remaining = end_address - address - 1
if remaining < len(header) + compressed_entry_size + clength:
# The file won't fit into the current ROM. Either put it in a
# new one, or split it and put the rest of the file there.
print "File %s won't fit in the current ROM - %i bytes too long." % (
repr(name), len(header) + compressed_entry_size + clength - remaining)
# Try to fit the block header, compressed entry and
# part of the compressed file in the remaining space.
has_free_space = (remaining >= compressed_entry_size + len(header) + 256)
if split_files and has_free_space:
# Decompress the truncated compressed data to find out
# how much raw data needs to be moved to the next ROM.
# Avoid truncating the data in the middle of a special
# byte sequence - this can be two bytes in length
# following a special byte.
special = encoded_compressed_data[0]
end = remaining - compressed_entry_size - len(header)
while end > 2 and special in encoded_compressed_data[end-2:end]:
end -= 1
if end == 2:
sys.stderr.write("Failed to split compressed data for %s.\n" % repr(name))
sys.exit(1)
# Truncate the compressed data and find the decompressed
# data that corresponds to it.
encoded_compressed_data = encoded_compressed_data[:end]
raw_data_written = distance_pair.decompress(
encoded_compressed_data, offset_bits = compress_offset_bits)
# Store the raw data that has been handled in a compressed
# block and put the rest back in the byte string for it to
# be compressed again.
encoded_raw_data = enc_raw_data[len(raw_data_written):]
# Also add the raw data from any other compressed blocks
# in the queue.
for piece in compressed_pieces:
encoded_raw_data += piece[1]
compressed_pieces = []
print "Writing %i bytes, leaving %i to be written." % (
len(raw_data_written), len(encoded_raw_data))
cdata = "".join(map(chr, encoded_compressed_data))
compressed_block = Compressed(cdata, info,
len(raw_data_written), compress_offset_bits,
first_block, header == "\x23")
if first_block:
file_addresses.append(address)
# Add information about the truncated block to the list
# of blocks, update the block number and record the
# trigger address.
blocks.append(compressed_block)
this += 1
triggers.append(address + len(header) - 1)
address += len(header)
# Adjust the load address for the rest of the file.
load += len(raw_data_written)
# Add pending blocks to the list of files, add an address
# for the end of ROMFS marker, and clear the list of blocks.
files.append(blocks)
file_addresses.append(address)
blocks = []
first_block = True
roms.append((files, file_addresses, triggers))
# Start a new ROM.
files = []
file_addresses = []
triggers = []
end_address = 0xc000
r += 1
if r >= len(data_addresses):
sys.stderr.write("Not enough ROM files specified.\n")
sys.exit(1)
# Update the data address from the start of the new ROM's
# data area.
address = data_addresses[r]
if split_files and has_free_space:
print "Splitting %s - moving %i bytes to the next ROM." % (
repr(name), len(encoded_raw_data))
break
else:
print "Moving %s to the next ROM." % repr(name)
# No raw data needs to be recompressed.
encoded_raw_data = []
# Requeue the current piece of compressed data.
compressed_pieces.insert(0, [compress_offset_bits,
enc_raw_data, encoded_compressed_data])
else:
# Reserve space for the ROM address, decompression start
# and finish addresses, source address and compressed data.
end_address -= compressed_entry_size + clength
# Update the header if this block is the last in the file.
if not compressed_pieces:
info = (name, load, exec_, "", this, 0x80)
header = write_block(u, name, load, exec_, "", this, 0x80, 0)
cdata = "".join(map(chr, encoded_compressed_data))
compressed_block = Compressed(cdata, info, len(enc_raw_data),
compress_offset_bits, first_block, header == "\x23")
if first_block:
file_addresses.append(address)
if details[r]["decode code"] == "":
sys.stderr.write("Cannot write compressed data for %s to ROM "
"without compression support.\n" % repr(name))
sys.exit(1)
blocks.append(compressed_block)
triggers.append(address + len(header) - 1)
address += len(header)
load += len(enc_raw_data)
encoded_raw_data = []
this += 1
first_block = False
# Append any remaining blocks.
files.append(blocks)
return files, [], r, address, end_address, file_addresses, triggers
def convert_chunks(u, indices, decomp_addrs, data_addresses, headers, details,
rom_files):
uef_files = []
chunks = []
names = []
for n, chunk in u.chunks:
if (n == 0x100 or n == 0x102) and chunk and chunk[0] == "\x2a":
name, load, exec_, block_data, this, flags = info = read_block(chunk)
if this == 0:
names.append(name)
if chunks:
uef_files.append(chunks)
chunks = []
chunks.append(chunk)
if chunks:
uef_files.append(chunks)
# If file indices were not specified, obtain the indices of all files.
if not indices:
indices = range(len(uef_files))
# Insert a !BOOT file at the start.
if bootable:
# Ideally, we could drop the !BOOT file if the first file should be
# *RUN, but it seems that we may need to select the ROM filing system
# again after entering BASIC.
if star_run:
details[0]["boot commands"].append('"*/%s"' % names[indices[0]])
elif star_exec:
details[0]["boot commands"].append('"*EXEC", 34, "%s", 34' % names[indices[0]])
else:
details[0]["boot commands"].append('"CHAIN", 34, "%s", 34' % names[indices[0]])
details[0]["boot commands"] = ", ".join(details[0]["boot commands"])
tof, temp_oph_file = tempfile.mkstemp(suffix=os.extsep+'oph')
tf, temp_boot_file = tempfile.mkstemp(suffix=os.extsep+'boot')
boot_file_text = _open("asm/file_boot_code.oph").read() % details[0]
os.write(tof, boot_file_text)
if os.system("ophis -o " + commands.mkarg(temp_boot_file) + " " + commands.mkarg(temp_oph_file)) != 0:
sys.exit(1)
boot_code = open(temp_boot_file, "rb").read()
os.remove(temp_oph_file)
os.remove(temp_boot_file)
if boot_code:
boot_name = details[0]["boot name"]
uef_files.insert(0, [write_block(u, boot_name, 0x1900, 0x1900, boot_code, 0, 0x80, 0)])
# If we inserted a !BOOT file, increment all the indices by 1 and
# insert the !BOOT file at the start.
new_indices = [0]
for i in indices:
if i == "s":
new_indices.append(i)
else:
new_indices.append(i + 1)
indices = new_indices
if decomp_addrs:
decomp_addrs[0].insert(0, ("x", None))
roms = []
files = []
file_addresses = []
blocks = []
# Start adding files to the first ROM at the address following the code.
r = 0
address = data_addresses[r]
end_address = 0xc000
# Create a list of trigger addresses.
triggers = []
# Examine the files at the given indices in the UEF file.
for i, index in enumerate(indices):
if index == "s":
# Add pending blocks to the list of files, add an address
# for the end of ROMFS marker, and clear the list of blocks.
files.append(blocks)
file_addresses.append(address)
blocks = []
roms.append((files, file_addresses, triggers))
files = []
file_addresses = []
triggers = []
end_address = 0xc000
r += 1
if r >= len(data_addresses):
sys.stderr.write("Not enough ROM files specified.\n")
sys.exit(1)
# Update the data address from the start of the new ROM's
# data area.
address = data_addresses[r]
continue
if r < len(decomp_addrs):
if decomp_addrs[r]:
decomp_addr, execution_addr = decomp_addrs[r].pop(0)
else:
decomp_addr = execution_addr = None
else:
decomp_addr = "x"
execution_addr = None
if decomp_addr != "x":
files, blocks, r, address, end_address, file_addresses, triggers = \
compress_file(uef_files, index, decomp_addr, execution_addr,
details, roms, r, address, end_address,
file_addresses, data_addresses, files, triggers)
# Examine the next file.
continue
# For uncompressed data, handle each chunk from the UEF file separately.
for i, chunk in enumerate(uef_files[index]):
name, load, exec_, block_data, this, flags = info = read_block(chunk)
last = (i == len(uef_files[index]) - 1)
# Encode the full header and data, or continuation byte and data.
if this == 0 or last:
# The next block follows the normal header and block data.
block = chunk
else:
# The next block follows the continuation marker, raw block data
# and the block checksum.
block = "\x23" + block_data + struct.pack("<H", u.crc(block_data))
if this == 0:
file_addresses.append(address)
if address + len(block) > end_address - 1:
# The block won't fit into the current ROM. Start a new one
# and add it there along with the other blocks in the file.
print "Block $%x in %s won't fit in the current ROM." % (this, repr(name))
if split_files:
files.append(blocks)
file_addresses.append(address)
blocks = []
roms.append((files, file_addresses, triggers))
files = []
file_addresses = []
triggers = []
end_address = 0xc000
r += 1
if r >= len(data_addresses):
sys.stderr.write("Not enough ROM files specified.\n")
sys.exit(1)
# Update the data address from the start of the new ROM's data
# area, adding the lengths of the blocks that need to be
# transferred to the next ROM.
address = data_addresses[r]
file_addresses.append(address)
if split_files:
print "Splitting %s - moving block $%x to the next ROM." % (repr(name), this)
# Ensure that the first block in the new ROM has a full
# header.
block = chunk
else:
print "Moving %s to the next ROM." % repr(name)
for old_block_info in blocks:
address += len(old_block_info.data)
address += len(block)
blocks.append(Block(block, info))
files.append(blocks)
blocks = []
end = load + (this * 256) + len(block_data)
if workspace != workspace_end and \
(load <= workspace < end or load < workspace_end <= end):
print "Warning: file %s [$%x,$%x) may overwrite ROM workspace: [$%x,$%x)" % (
repr(name), load, end, workspace, workspace_end)
if blocks:
files.append(blocks)
if files:
# Record the address of the byte after the last file.
file_addresses.append(address)
roms.append((files, file_addresses, triggers))
if len(roms) > len(rom_files):
sys.stderr.write("Not enough ROM files specified.\n")
sys.exit(1)
# Write the source for each ROM file, containing the appropriate ROM header
# and the files it contains in its ROMFS structure.
r = 0
for header, rom_file, rom in zip(headers, rom_files, roms):
tf, temp_file = tempfile.mkstemp(suffix=os.extsep+'oph')
os.write(tf, header)
files, file_addresses, triggers = rom
# Discard the address of the first file.
address = file_addresses.pop(0)
print rom_file
first_block = True
file_details = []
for blocks in files:
file_name = ""
load_addr = 0
length = 0
for b, block_info in enumerate(blocks):
name, load, exec_, block_data, this, flags = block_info.info
length += len(block_data)
last = (b == len(blocks) - 1) and block_info.data[0] != "\x23"
# Potential flag modifications:
#
#if flags & 0x40 and len(block_data) != 0:
# flags = flags & 0xbf
#if flags & 0x80 and not last:
# flags = flags & 0x7f
if isinstance(block_info, Compressed):
os.write(tf, "; %s %x\n" % (repr(name)[1:-1], this))
if block_info.first_block:
next_address = file_addresses.pop(0)
file_details.append((name, load, block_info))
length = 0
if block_info.short_header:
data = "\x23"
else:
data = write_block(u, name, load, exec_, block_data, this, flags, next_address)
os.write(tf, format_data(data))
if block_info.first_block:
print " %s starts at $%x and ends at $%x, next file at $%x" % (
repr(name), address, address + len(data),
next_address)
elif this == 0 or last or first_block:
os.write(tf, "; %s %x\n" % (repr(name)[1:-1], this))
if last:
next_address = file_addresses.pop(0)
block_info.raw_length = length
length = 0
if this == 0:
print " %s starts at $%x and ends at $%x, next file at $%x" % (
repr(name), address, address + len(block_info.data),
next_address)
elif this == 0:
file_name = name
load_addr = load
next_address = file_addresses[0]
print " %s starts at $%x, next file at $%x" % (
repr(name), address, next_address)
else:
next_address = file_addresses[0]
print " %s continues at $%x, next file at $%x" % (
repr(name), address, next_address)
first_block = False
data = write_block(u, name, load, exec_, block_data, this, flags, next_address)
os.write(tf, format_data(data))
else:
os.write(tf, "; %s %x\n" % (repr(name)[1:-1], this))
data = block_info.data
os.write(tf, format_data(data))
address += len(data)
write_end_marker(tf)
# If a list of triggers was compiled, write the compressed data after
# the ROMFS data, and write the associated addresses at the end of the
# ROM file.
if triggers:
os.write(tf, "\n; Compressed data\n")
os.write(tf, ".alias after_triggers %i\n" % (len(triggers) * 2))
addresses = []
for info in file_details:
# Unpack the file information.
name, decomp_addr, block_info = info
src_label = "src_%x" % id(block_info)
if decomp_addr != "x":
addr = triggers.pop(0)
decomp_addr = decomp_addr & 0xffff
addresses.append(AddressInfo(name, addr, src_label, decomp_addr,
decomp_addr + block_info.raw_length, block_info.offset_bits))
os.write(tf, "\n; %s\n" % repr(name)[1:-1])
os.write(tf, src_label + ":\n")
os.write(tf, format_data(block_info.data))
#os.write(tf, "\n.alias debug %i" % (49 + roms.index(rom)))
os.write(tf, "\ntriggers:\n")
for address_info in addresses:
if address_info.decomp_addr != "x":
os.write(tf, ".byte $%02x, $%02x ; %s\n" % (
address_info.addr & 0xff, address_info.addr >> 8,
repr(address_info.name)[1:-1]))
os.write(tf, "\nsrc_addresses:\n")
for address_info in addresses:
if address_info.decomp_addr != "x":
os.write(tf, ".byte <%s, >%s\n" % (address_info.src_label,
address_info.src_label))
os.write(tf, "\ndest_addresses:\n")
for address_info in addresses:
if address_info.decomp_addr != "x":
os.write(tf, ".byte $%02x, $%02x\n" % (
address_info.decomp_addr & 0xff,
address_info.decomp_addr >> 8))
os.write(tf, "\ndest_end_addresses:\n")
for address_info in addresses:
if address_info.decomp_addr != "x":
os.write(tf, ".byte $%02x, $%02x\n" % (
address_info.decomp_end_addr & 0xff,
address_info.decomp_end_addr >> 8))
os.write(tf, "\noffset_bits_and_count_masks:\n")
for address_info in addresses:
if address_info.decomp_addr != "x":
offset_mask = (1 << address_info.offset_bits) - 1
count_mask = 0xff ^ offset_mask
os.write(tf, ".byte $%02x ; count mask\n" % count_mask)
os.write(tf, ".byte %i ; offset bits\n" % address_info.offset_bits)
os.write(tf, "\n")
decomp_addrs = decomp_addrs[len(file_details):]
elif details[r]["compress"]:
# Ideally, we would remove the decompression code and rebuild the ROM.
sys.stderr.write("ROM file %s contains unused decompression code.\n" % rom_file)
os.write(tf, ".alias after_triggers 0\n")
os.write(tf, "triggers:\n")
os.write(tf, "src_addresses:\n")
os.write(tf, "dest_addresses:\n")
os.write(tf, "dest_end_addresses:\n")
os.write(tf, "offset_bits_and_count_masks:\n")
os.close(tf)
if os.system("ophis -o " + commands.mkarg(rom_file) + " " + commands.mkarg(temp_file)) != 0:
sys.exit(1)
os.remove(temp_file)
r += 1
def write_end_marker(tf):
os.write(tf, "end_of_romfs_marker:\n")
os.write(tf, ".byte $2b\n")
def get_data_address(header_file, rom_file):
tf, temp_file = tempfile.mkstemp(suffix=os.extsep+'oph')
os.write(tf, header_file)
# Include placeholder values.
os.write(tf, ".alias after_triggers 0\n")
#os.write(tf, ".alias debug 48\n")
os.write(tf, "triggers:\n")
os.write(tf, "src_addresses:\n")
os.write(tf, "dest_addresses:\n")
os.write(tf, "dest_end_addresses:\n")
os.write(tf, "offset_bits_and_count_masks:\n")
os.write(tf, "end_of_romfs_marker:\n")
os.close(tf)
if os.system("ophis -o " + commands.mkarg(rom_file) + " " + commands.mkarg(temp_file)):
sys.exit(1)
data_address = 0x8000 + os.stat(rom_file)[stat.ST_SIZE]
os.remove(temp_file)
return data_address
class ArgumentError(Exception):
pass
def find_option(args, label, number = 0, missing_value = None):
try:
i = args.index(label)
except ValueError:
if number == 0:
return False
else:
return False, missing_value
values = args[i + 1:i + number + 1]
args[:] = args[:i] + args[i + number + 1:]
if number == 0:
return True
if len(values) < number:
raise ArgumentError, "Not enough values for argument '%s': %s" % (label, repr(values))
if number == 1:
values = values[0]
return True, values
def usage():
sys.stderr.write(__usage__ % sys.argv[0])
sys.stderr.write(__description__)
sys.exit(1)
if __name__ == "__main__":
args = sys.argv[:]
indices = []
details = [
{"title": '.byte "", 0', # '.byte "Test ROM", 0',
"version string": '.byte "", 0', # '.byte "1.0", 0',
"version": ".byte 1",
"copyright": '.byte "(C)", 0', # '.byte "(C) Original author", 0',
"copyright offset": '.byte [copyright_string - rom_start - 1]',
"rom name": '',
"service entry command code": "",
"service command code": "",
"service boot code": "",
"boot name": "!BOOT",
"boot code": "",
"init romfs code": "",
"first rom bank init code": "",
"first rom bank check code": "",
"first rom bank behaviour code": "",
"second rom bank check code": "",
"second rom bank init code": "",