-
Notifications
You must be signed in to change notification settings - Fork 3
/
obj2bin.pl
1297 lines (1060 loc) · 41.5 KB
/
obj2bin.pl
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/perl -w
#!/usr/local/bin/perl -w
# Copyright (c) 2005-2023 Don North
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# o Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# o Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# o Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
require 5.008;
=head1 NAME
obj2bin.pl - Convert a Macro-11 program image to PROM/load format
=head1 SYNOPSIS
obj2bin.pl
S<[--help]>
S<[--debug]>
S<[--verbose]>
S<[--boot]>
S<[--console]>
S<[--binary]>
S<[--raw]>
S<[--ascii]>
S<[--rt11]>
S<[--rsx11]>
S<[--bytes=N]>
S<[--nocrc]>
S<[--logfile=LOGFILE]>
S<--outfile=BINFILE>
S<OBJFILE>
=head1 DESCRIPTION
Converts a Macro-11 object files to various output formats,
including M9312 boot and console PROM, straight binary records,
ASCII format for M9312 console load commands, and loadable absolute
binary program images (.BIN) files.
Multiple .psect/.asect ops are supported, as well as all local
(non-global) relocation directory entries.
Supports either RT-11 or RSX-11 format object files.
=head1 OPTIONS
The following options are available:
=over
=item B<--help>
Output this manpage and exit the program.
=item B<--debug>
Enable debug mode; print input file records as parsed.
=item B<--verbose>
Verbose status; output status messages during processing.
=item B<--boot>
Generate a hex PROM file image suitable for programming into
an M9312 boot prom (512x4 geometry, only low half used).
=item B<--console>
Generate a hex PROM file image suitable for programming into
an M9312 console/diagnostic prom (1024x4 geometry).
=item B<--ascii>
Generate a a sequence of 'L addr' / 'D data' commands for downloading
a program via a terminal emulator thru the M9312 user command interface.
Suitable only for really small test programs.
=item B<--binary>
Generate binary format load records of the program image (paper
tape format) for loading into SIMH or compatible simulators.
These files can also be copied onto XXDP filesystems to generate
runnable program images (used to write custom diaqnostics).
Binary format is the default if no other option is specified.
If more than one option is specified the last one takes effect.
=item B<--raw>
Generate raw data format file.
=item B<--rt11>
Read input object files in RT-11 format.
=item B<--rsx11>
Read input object files in RSX-11 format.
RSX-11 object file format is the default if no other option is specified.
If more than one option is specified the last one takes effect.
=item B<--bytes=N>
For hex format output files, output N bytes per line (default 16).
=item B<--nocrc>
For hex format output files, don't automatically stuff the computed
CRC-16 as the last word in the ROM.
=item B<--logfile=FILENAME>
Generate debug output into this file.
=item B<--outfile=FILENAME>
Output binary file in format selected by user option.
=item B<OBJFILE...>
Input object file(s) in .obj format.
=back
=head1 ERRORS
The following diagnostic error messages can be produced on STDERR.
The meaning should be fairly self explanatory.
C<Aborted due to command line errors> -- bad option or missing file(s)
C<Can't open input file '$file'> -- bad filename or unreadable file
C<Error: Improper object file format (1)> -- valid RT-11 record must start with 0x01
C<Error: Improper object file format (2)> -- second RT-11 byte must be 0x00
C<Error: Improper object file format (3)> -- third byte is low byte of record length
C<Error: Improper object file format (4)> -- fourth byte is high byte of record length
C<Error: Improper object file format (5)> -- bytes five thru end-1 are data bytes
C<Error: Improper object file format (6)> -- last RT-11 byte is checksum
C<Error: Bad checksum exp=0x%02X rcv=0x%02X> -- compare rcv'ed checksum vs exp'ed checksum
=head1 EXAMPLES
Some examples of common usage:
obj2bin.pl --help
obj2bin.pl --verbose --boot --out 23-751A9.hex 23-751A9.obj
obj2bin.pl --verbose --binary --rt11 --out memtest.bin memtest.obj
obj2bin.pl --verbose --binary --rsx11 --out prftst.bin prftst.obj mac/printf.obj
=head1 AUTHOR
Don North - donorth <ak6dn _at_ mindspring _dot_ com>
=head1 HISTORY
Modification history:
2005-05-05 v1.0 donorth - Initial version.
2016-01-15 v1.1 donorth - Added RLD(IR) processing, moved sub's to end.
2016-01-18 v1.2 donorth - Added GSD processing, improved debug output.
2016-01-20 v1.3 donorth - Initial support for linking multiple PSECTs.
2016-01-22 v1.4 donorth - Added objfile/outfile/logfile switches vs stdio.
2016-01-28 v1.5 donorth - Added RLD processing, especially complex.
2017-04-01 v1.9 donorth - Renamed from obj2hex.pl to obj2bin.pl
2017-05-04 v1.95 donorth - Updated capability to read multiple input .obj files.
2020-03-06 v2.0 donorth - Updated help documentation and README.md file.
2020-03-10 v2.1 donorth - Broke down and added RSX-11 input format option.
2023-07-06 v2.2 donorth - Added binmode($fh) on object input and binary output files.
2024-03-22 v2.3 MattisLind/donorth - Added raw data format output via --raw option.
=cut
# options
use strict;
# external standard modules
use Getopt::Long;
use Pod::Text;
use FindBin;
use FileHandle;
# external local modules search path
BEGIN { unshift(@INC, $FindBin::Bin);
unshift(@INC, $ENV{PERL5LIB}) if defined($ENV{PERL5LIB}); # cygwin bugfix
unshift(@INC, '.'); }
# external local modules
# generic defaults
my $VERSION = 'v2.3'; # version of code
my $HELP = 0; # set to 1 for man page output
my $DEBUG = 0; # set to 1 for debug messages
my $VERBOSE = 0; # set to 1 for verbose messages
# specific defaults
my $crctype = 'CRC-16'; # type of crc calc to do
my $memsize; # number of instruction bytes allowed
my $memfill; # memory fill pattern
my %excaddr; # words to be skipped in rom crc calc
my $rombase; # base address of rom image
my $romsize; # number of rom addresses
my $romfill; # rom fill pattern
my $romtype = 'BINA'; # default rom type is BINARY
my $objtype = 'RSX11'; # default object file format is RSX11
my $bytesper = -1; # bytes per block in output file
my $nocrc = 0; # output CRC16 as last word unless set
my $outfile = undef; # output filename
my $logfile = undef; # log filename
# process command line arguments
my $NOERROR = GetOptions( "help" => \$HELP,
"debug" => \$DEBUG,
"verbose" => \$VERBOSE,
"boot" => sub { $romtype = 'BOOT'; },
"console" => sub { $romtype = 'DIAG'; },
"binary" => sub { $romtype = 'BINA'; },
"raw" => sub { $romtype = 'RAWA'; },
"ascii" => sub { $romtype = 'ASC9'; },
"rt11" => sub { $objtype = 'RT11'; },
"rsx11" => sub { $objtype = 'RSX11'; },
"bytes=i" => \$bytesper,
"nocrc" => \$nocrc,
"outfile=s" => \$outfile,
"logfile=s" => \$logfile,
);
# init
$VERBOSE = 1 if $DEBUG; # debug implies verbose messages
# output the documentation
if ($HELP) {
# output a man page if we can
if (ref(Pod::Text->can('new')) eq 'CODE') {
# try the new way if appears to exist
my $parser = Pod::Text->new(sentence=>0, width=>78);
printf STDOUT "\n"; $parser->parse_from_file($0);
} else {
# else must use the old way
printf STDOUT "\n"; Pod::Text::pod2text(-78, $0);
};
exit(1);
}
# check for correct arguments present, print usage if errors
unless ($NOERROR
&& scalar(@ARGV) >= 1
&& defined($outfile)
&& $romtype ne 'NONE'
) {
printf STDERR "obj2bin.pl %s by Don North (perl %g)\n", $VERSION, $];
print STDERR "Usage: $0 [options...] arguments\n";
print STDERR <<"EOF";
--help output manpage and exit
--debug enable debug mode
--verbose verbose status reporting
--boot M9312 boot prom .hex
--console M9312 console/diagnostic prom .hex
--binary binary program load image .bin [default]
--raw raw binary data output
--ascii ascii m9312 program load image .txt
--rt11 read .obj files in RT11 format
--rsx11 read .obj files in RSX11 format [default]
--bytes=N bytes per block on output hex format
--nocrc inhibit output of CRC-16 in hex format
--logfile=LOGFILE logging message file
--outfile=OUTFILE output .hex/.txt/.bin file
OBJFILE... macro11 object .obj file(s)
EOF
# exit if errors...
die "Aborted due to command line errors.\n";
}
# setup log file as a file, defaults to STDERR if not supplied
my $LOG = defined($logfile) ? FileHandle->new("> ".$logfile) : FileHandle->new_from_fd(fileno(STDERR),"w");
#----------------------------------------------------------------------------------------------------
# subroutine prototypes
sub trim ($);
sub chksum (@);
sub rad2asc (@);
sub crc (%);
sub sym2psect ($$);
sub read_rec ($);
sub get_global ($);
sub parse_rec ($$$);
#----------------------------------------------------------------------------------------------------
# fill in the parameters of the device
if ($romtype eq 'BOOT') {
# M9312 512x4 boot prom
%excaddr = ( 024=>1, 025=>1 ); # bytes to be skipped in rom crc calc
$memsize = 128; # number of instruction bytes allowed
$memfill = 0x00; # memory fill pattern
$romsize = 512; # number of rom addresses (must be a power of two)
$romfill = 0x00; # rom fill pattern
$rombase = 0173000; # base address of rom
} elsif ($romtype eq 'DIAG') {
# M9312 1024x4 diagnostic/console prom
%excaddr = ( ); # bytes to be skipped in rom crc calc
$memsize = 512; # number of instruction bytes allowed
$memfill = 0x00; # memory fill pattern
$romsize = 1024; # number of rom addresses (must be a power of two)
$romfill = 0x00; # rom fill pattern
$rombase = 0165000; # base address of rom
} elsif ($romtype eq 'BINA' || $romtype eq 'ASC9' || $romtype eq 'RAWA') {
# program load image ... 56KB address space maximum
%excaddr = ( ); # bytes to be skipped in rom crc calc
$memsize = 7*8192; # number of instruction bytes allowed
$memfill = 0x00; # memory fill pattern
$romsize = 8*8192; # number of rom addresses (must be a power of two)
$romfill = 0x00; # image fill pattern
$rombase = 0; # base address of binary image
} else {
# unknown ROM type code
die "ROM type '$romtype' is not supported!\n";
}
if ($VERBOSE) {
printf $LOG "ROM type is '%s'\n", $romtype;
printf $LOG "ROM space is %d. bytes\n", $memsize;
printf $LOG "ROM length is %d. addresses\n", $romsize;
printf $LOG "ROM base address is 0%06o\n", $rombase;
}
#----------------------------------------------------------------------------------------------------
# read/process the input object file records
# real pdp11 memory data words in boot prom
my @mem = ((0) x $memsize);
# min/max address limits in object file
my ($adrmin,$adrmax) = ('','');
# state variables in processing object records
my $rommsk = ($romsize-1)>>1; # address bit mask
my $adrmsk = 0xFFFF; # 16b addr mask
my $datmsk = 0xFFFF; # 16b data mask
my $memmsk = 0xFF; # 8b memory data mask
# databases
my %gblsym = ();
my %psect = ();
my @psect = ();
my %program = ();
my $psectname = sprintf("%02d:%s",1,'. ABS.');
my $psectaddr = 0;
my $psectnumb = -1;
my $textaddr = 0;
# program defaults
$program{START}{ADDRESS} = 1;
$program{START}{VALUE} = 1;
$program{START}{PSECT} = $psectname;
# two passes, first is headers, second is data records
foreach my $pass (1..2) {
foreach my $numb (0..$#ARGV) {
my $objfile = $ARGV[$numb];
my $OBJ = FileHandle->new("< ".$objfile);
die "Error: can't open input object file '$objfile'\n" unless defined $OBJ;
printf $LOG "\n\nPROCESS PASS %d FILE %d '%s'\n\n", $pass, $numb+1, $objfile if $DEBUG;
binmode($OBJ);
while (my @rec = &read_rec($OBJ)) { &parse_rec($numb+1, $pass, \@rec); }
$OBJ->close;
}
}
#----------------------------------------------------------------------------------------------------
# compute CRC if required, copy memory image to output buffer
my @buf = ($romfill) x $romsize; # physical PROM data bytes, filled background pattern
# only compute CRC on M9312 ROMs
if ($romtype eq 'BOOT' || $romtype eq 'DIAG') {
# compute CRC-16 of the prom contents (except exception words) and store at last location
my $crctab = &crc(-name=>$crctype, -new=>1);
my $crc = &crc(-name=>$crctype, -init=>1);
for (my $adr = 0; $adr < $memsize-2; $adr += 1) {
next if exists($excaddr{$adr}); # skip these addresses
$mem[$rombase+$adr] = $memfill unless defined($mem[$rombase+$adr]);
$crc = &crc(-name=>$crctype, -table=>$crctab, -crc=>$crc, -byte=>$mem[$rombase+$adr]);
}
$crc = &crc(-name=>$crctype, -crc=>$crc, -last=>1);
unless ($nocrc) {
# output computed CRC-16 as last word in the ROM file
$mem[$rombase+$memsize-2] = ($crc>>0)&0xFF;
$mem[$rombase+$memsize-1] = ($crc>>8)&0xFF;
}
printf $LOG "ROM %s is %06o (0x%04X)\n", $crctype, ($crc) x 2 if $VERBOSE;
# process data words to actual PROM byte data
# put 4bit nibble in low 4b of each 8b data byte, zero the upper 4b
# only copy the above instruction portion over
for (my $idx = 0; $idx < $memsize<<1; $idx += 4) {
my $dat = ($mem[$rombase+($idx>>1)+1]<<8) | ($mem[$rombase+($idx>>1)+0]<<0);
$buf[$idx+0] = ($dat&0xE)|(($dat>>8)&0x1); # bits 3 2 1 8
$buf[$idx+1] = ($dat>>4)&0xF; # bits 7 6 5 4
$buf[$idx+2] = ((($dat>>8)&0xE)|($dat&0x1))^0xC; # bits ~11 ~10 9 0
$buf[$idx+3] = (($dat>>12)&0xF)^0x1; # bits 15 14 13 ~12
}
} elsif ($romtype eq 'BINA' || $romtype eq 'ASC9' || $romtype eq 'RAWA') {
# only copy the above instruction portion over
for (my $adr = 0; $adr < $memsize; $adr += 1) {
$mem[$rombase+$adr] = $memfill unless defined($mem[$rombase+$adr]);
$buf[$adr] = $mem[$rombase+$adr];
}
}
if ($VERBOSE) {
# print checksum of entire device
my $chksum = 0; map($chksum += $_, @buf);
printf $LOG "ROM checksum is %06o (0x%04X)\n", $chksum, $chksum;
}
#----------------------------------------------------------------------------------------------------
# output the linked/processed binary file image in the desired format
my $OUT = FileHandle->new("> ".$outfile);
die "Error: can't open output file '$outfile'\n" unless defined $OUT;
if ($romtype eq 'BOOT' || $romtype eq 'DIAG') {
# output the entire PROM buffer as an intel hex file
$bytesper = 16 if $bytesper <= 0;
for (my $idx = 0; $idx < $romsize; $idx += $bytesper) {
my $cnt = $idx+$bytesper <= $romsize ? $bytesper : $romsize-$idx; # N bytes or whatever is left
my @dat = @buf[$idx..($idx+$cnt-1)]; # get the data
my $dat = join('', map(sprintf("%02X",$_),@dat)); # map to ascii text
printf $OUT ":%02X%04X%02X%s%02X\n", $cnt, $idx, 0x00, $dat, &chksum($cnt, $idx>>0, $idx>>8, 0x00, @dat);
}
printf $OUT ":%02X%04X%02X%s%02X\n", 0x00, 0x0000, 0x01, '', &chksum(0x0, 0x0000>>0, 0x0000>>8, 0x01);
} elsif ($romtype eq 'BINA') {
# Loader format consists of blocks, optionally preceded, separated, and
# followed by zeroes. Each block consists of:
#
# 001 ---
# 000 |
# lo(length) |
# hi(length) |
# lo(address) > 'length' bytes
# hi(address) |
# databyte1 |
# : |
# databyteN ---
# checksum
#
# If the byte length is exactly six, the block is the last on the tape, and
# there is no checksum. If the origin is not 000001, then the origin is
# the PC at which to start the program.
binmode($OUT);
$bytesper = 128 if $bytesper <= 0;
my $start = $program{START}{ADDRESS};
sub m ($) { $_[0] & 0xFF; }
# output the entire PROM buffer as a binary loader file
for (my $idx = $adrmin; $idx < $adrmax+1; $idx += $bytesper) {
my $cnt = $idx+$bytesper <= $adrmax+1 ? $bytesper : $adrmax+1-$idx; # N bytes or whatever is left
my @dat = @buf[$idx..($idx+$cnt-1)]; # get the data
my $len = $cnt+6;
my @rec = (0x01, 0x00, &m($len>>0), &m($len>>8), &m($idx>>0), &m($idx>>8), @dat);
print $OUT pack("C*", @rec, &chksum(@rec));
}
my @end = (0x01, 0x00, 0x06, 0x00, &m($start>>0), &m($start>>8));
print $OUT pack("C*", @end, &chksum(@end));
} elsif ($romtype eq 'ASC9') {
# ascii interface to M9312 console emulator
sub n ($) { $_[0] & 0xFF; }
# start program load here
printf $OUT "L %o\r\n", $adrmin;
# output the PROM buffer as an ascii load file
for (my $idx = $adrmin; $idx < $adrmax+1; $idx += 2) {
printf $OUT "D %06o\r\n", (&n($buf[$idx+1])<<8) | &n($buf[$idx+0]);
}
# start program exec here
printf $OUT "L %o\r\nS\r\n", $adrmin;
} elsif ($romtype eq 'RAWA') {
# raw format data output as just data bytes
binmode($OUT);
$bytesper = 128 if $bytesper <= 0;
# output the entire PROM buffer as a binary loader file
for (my $idx = $adrmin; $idx < $adrmax+1; $idx += $bytesper) {
my $cnt = $idx+$bytesper <= $adrmax+1 ? $bytesper : $adrmax+1-$idx; # N bytes or whatever is left
my @dat = @buf[$idx..($idx+$cnt-1)]; # get the data
print $OUT pack("C*", @dat);
}
}
# all done
$OUT->close;
#----------------------------------------------------------------------------------------------------
# really done
$LOG->close;
exit;
#----------------------------------------------------------------------------------------------------
#----------------------------------------------------------------------------------------------------
# trim leading/trailing spaces on a string
sub trim ($) {
my ($str) = @_;
$str =~ s/\s+$//;
$str =~ s/^\s+//;
return $str;
}
#----------------------------------------------------------------------------------------------------
# compute checksum (twos complement of the sum of bytes)
sub chksum (@) {
my $sum = 0;
map($sum += $_, @_);
return (-$sum) & 0xFF;
}
#----------------------------------------------------------------------------------------------------
# RAD50 to ASCII decode
sub rad2asc (@) {
my @str = split(//, ' ABCDEFGHIJKLMNOPQRSTUVWXYZ$.%0123456789'); # RAD50 character subset
my $ascii = "";
foreach my $rad50 (@_) {
$ascii .= $str[int($rad50/1600)%40] . $str[int($rad50/40)%40] . $str[$rad50%40];
}
return $ascii;
}
#----------------------------------------------------------------------------------------------------
# symbol to psect name converter
sub sym2psect ($$) {
return sprintf("%02d:%-6s", @_);
}
#----------------------------------------------------------------------------------------------------
# crc computation routine
sub crc (%) {
# pass all args by name
my %args = @_;
# all the crcs we know how to compute
my %crcdat = ( 'CRC-16' => [ 0xA001, 2, 0x0000, 0x0000 ],
'CRC-32' => [ 0xEDB88320, 4, 0xFFFFFFFF, 0xFFFFFFFF ] );
# run next byte thru crc computation, return updated crc
return $args{-table}[($args{-crc}^$args{-byte}) & 0xFF]^($args{-crc}>>8) if exists($args{-byte});
# return initial crc value
return $crcdat{$args{-name}}->[2] if exists($args{-init});
# return final crc value xored with xorout
return $args{-crc} ^ $crcdat{$args{-name}}->[3] if exists($args{-last});
# compute the crc lookup table, return a pointer to it
if (exists($args{-new})) {
my $crctab = [];
my $poly = $crcdat{$args{-name}}->[0];
foreach my $byte (0..255) {
my $data = $byte;
foreach (1..8) { $data = ($data>>1) ^ ($data&1 ? $poly : 0); }
$$crctab[$byte] = $data;
}
return $crctab;
}
}
#----------------------------------------------------------------------------------------------------
# read a record from the object file
sub read_rec ($) {
my ($fh) = @_;
my ($buf, $cnt, $len, $err) = (0,0,0,0);
my @pre = ();
my @dat = ();
my @suf = ();
if ($objtype eq 'RT11') {
# RT-11 object file format consists of blocks, optionally preceded, separated, and
# followed by zeroes. Each block consists of:
#
# 001 ---
# 000 |
# lo(length) |
# hi(length) > 'length' bytes
# databyte1 |
# : |
# databyteN ---
# checksum
#
# skip over strings of 0x00; exit OK if hit EOF
do { return () unless $cnt = read($fh, $buf, 1); } while (ord($buf) == 0);
# valid record starts with (1)
$err = 1 unless $cnt == 1 && ord($buf) == 1;
push(@pre, ord($buf));
# second byte must be (0)
$cnt = read($fh, $buf, 1);
$err = 2 unless $cnt == 1 && ord($buf) == 0;
push(@pre, ord($buf));
# third byte is low byte of record length
$cnt = read($fh, $buf, 1);
$err = 3 unless $cnt == 1;
$len = ord($buf);
push(@pre, ord($buf));
# fourth byte is high byte of record length
$cnt = read($fh, $buf, 1);
$err = 4 unless $cnt == 1;
$len += ord($buf)<<8;
push(@pre, ord($buf));
# bytes five thru end-1 are data bytes
$cnt = read($fh, $buf, $len-4);
$err = 5 unless $cnt == $len-4 && $len >= 4;
@dat = unpack("C*", $buf);
# last byte is checksum
$cnt = read($fh, $buf, 1);
$err = 6 unless $cnt == 1;
my $rcv = ord($buf);
push(@suf, ord($buf));
# compare rcv'ed checksum vs exp'ed checksum
my $exp = &chksum(0x01, $len>>0, $len>>8, @dat);
warn sprintf("Warning: Bad checksum exp=0x%02X rcv=0x%02X", $exp, $rcv) unless $exp == $rcv;
} elsif ($objtype eq 'RSX11') {
# RSX-11 object file format consists of blocks of data in the following format.
# Each block consists of:
#
# lo(length)
# hi(length)
# databyte1 ---
# : |
# : > 'length' bytes
# : |
# databyteN ---
# zeroFill present if length is ODD; else not present
#
# first byte is low byte of record length
$cnt = read($fh, $buf, 1);
# but exit OK if hit EOF
return () if $cnt == 0;
$err = 10 unless $cnt == 1;
$len = ord($buf);
push(@pre, ord($buf));
# second byte is high byte of record length
$cnt = read($fh, $buf, 1);
$err = 11 unless $cnt == 1;
$len += ord($buf)<<8;
push(@pre, ord($buf));
# bytes three thru end are data bytes
$cnt = read($fh, $buf, $len);
$err = 12 unless $cnt == $len && $len >= 0;
@dat = unpack("C*", $buf);
# optional pad byte if length is odd
$cnt = ($len & 1) ? read($fh, $buf, 1) : 2;
$err = 13 unless $cnt == 1 && ord($buf) == 0 || $cnt == 2;
}
# output the record if debugging
if ($DEBUG >= 2) {
my $fmt = "%03o";
my $n = 16;
my $pre = sprintf("RECORD: [%s] ",join(" ",map(sprintf($fmt,$_),@pre)));
printf $LOG "\n\n%s", $pre;
my $k = length($pre);
my @tmp = @dat;
while (@tmp > $n) {
printf $LOG "%s\n%*s", join(" ",map(sprintf($fmt,$_),splice(@tmp,0,$n))), $k, '';
}
printf $LOG "%s", join(" ",map(sprintf($fmt,$_),@tmp)) if @tmp;
printf $LOG " [%s]\n\n", join(" ",map(sprintf($fmt,$_),@suf));
}
# check we have a well formatted record
warn sprintf("Warning: invalid %s object file record format (%d)", $objtype, $err) if $err;
# all is well, return the record
return @dat;
}
#----------------------------------------------------------------------------------------------------
# get a global symbol target value
sub get_global ($) {
my ($sym) = @_;
# return target value if exists
return $gblsym{$sym}{DEF}{ADDRESS} if exists $gblsym{$sym}{DEF}{ADDRESS};
# issue a warning for multiple definition with a different address
warn sprintf("Warning: global symbol undefined: symbol=%s, assuming value of 000000\n", $sym);
# and return nil
return 0;
}
#----------------------------------------------------------------------------------------------------
# parse an input object file record, update data structures
sub parse_rec ($$$) {
my ($file,$pass,$rec) = (@_);
# type is first byte of record
my $key = $rec->[0];
if ($key == 001 && $pass == 1) { # GSD
# iterate over GSD subrecords
for (my $i = 2; $i < scalar(@$rec); ) {
# GSD records are fixed 8B length all in the same format
my $sym = &rad2asc(($rec->[$i+1]<<8)|($rec->[$i+0]<<0),($rec->[$i+3]<<8)|($rec->[$i+2]<<0));
my $flg = $rec->[$i+4];
my $ent = $rec->[$i+5];
my $val = ($rec->[$i+7]<<8)|($rec->[$i+6]<<0);
my @ent = ('MODULE','CSECT','INTSYM','XFRADR','GBLSYM','PSECT','IDENT','VSECT');
my $def = undef;
if ($ent == 3) {
# XFRADR
$program{START}{PSECT} = &sym2psect($file,$sym);
$program{START}{VALUE} = $val;
if ($DEBUG) {
printf $LOG "..GSD: type='%-6s'(%03o) name='%s' value=%06o\n",
$ent[$ent], $ent, $program{START}{PSECT}, $program{START}{VALUE};
}
} elsif ($ent == 4) {
# GBLSYM flags
my $adr = $val + $psect{$psectname}{START};
$def = $flg&(1<<3) ? "DEF" : "REF";
if ($def eq "DEF" && exists $gblsym{$sym}{$def} && $adr != $gblsym{$sym}{$def}{ADDRESS}) {
# issue a warning for multiple definition with a different address
warn sprintf("Warning: global symbol redefinition: symbol=%s (address/psect) old=%06o/%s new=%06o/%s -- IGNORING\n",
&trim($sym), $gblsym{$sym}{$def}{ADDRESS}, &trim($gblsym{$sym}{$def}{PSECT}), $adr, &trim($psectname));
} else {
# define first time only ... ignore any redefinition attempt
$gblsym{$sym}{$def}{FLG}{$flg&(1<<0) ? "WEA" : "STR"}++;
$gblsym{$sym}{$def}{FLG}{$flg&(1<<3) ? "DEF" : "REF"}++;
$gblsym{$sym}{$def}{FLG}{$flg&(1<<5) ? "REL" : "ABS"}++;
$gblsym{$sym}{$def}{PSECT} = $psectname;
$gblsym{$sym}{$def}{VALUE} = $val;
$gblsym{$sym}{$def}{ADDRESS} = $adr;
}
if ($DEBUG) {
printf $LOG "..GSD: type='%-6s'(%03o) name='%s' value=%06o", $ent[$ent], $ent, $sym, $val;
printf $LOG " psect='%s' value=%06o", $gblsym{$sym}{$def}{PSECT}, $gblsym{$sym}{$def}{VALUE};
printf $LOG " flags=%s\n", join(",", sort(keys(%{$gblsym{$sym}{$def}{FLG}})));
}
} elsif ($ent == 5) {
# PSECT flags
my $nam = &sym2psect($file,$sym);
$psect[++$psectnumb] = $nam;
$psect{$nam}{FILE} = $file;
$psect{$nam}{NUMBER} = $psectnumb;
$psect{$nam}{FLG}{$flg&(1<<0) ? "GBL" : $flg&(1<<6) ? "GBL" : "LCL"}++;
$psect{$nam}{FLG}{$flg&(1<<2) ? "OVR" : "CON"}++;
$psect{$nam}{FLG}{$flg&(1<<4) ? "R/O" : "R/W"}++;
$psect{$nam}{FLG}{$flg&(1<<5) ? "REL" : "ABS"}++;
$psect{$nam}{FLG}{$flg&(1<<7) ? "D" : "I/D"}++;
$psectname = $nam;
if ($psect{$nam}{FLG}{ABS}) {
# absolute
if ($psect{$nam}{FLG}{CON}) {
# concatenated
warn sprintf("Warning: psect ABS,CON is not supported, psect='%s'\n", $psectname);
} elsif ($psect{$nam}{FLG}{OVR}) {
# overlaid
$psect{$nam}{LENGTH} = $val;
$psect{$nam}{START} = 0;
}
} elsif ($psect{$nam}{FLG}{REL}) {
# relative
if ($psect{$nam}{FLG}{CON}) {
# concatenated
$psect{$nam}{LENGTH} = $val;
$psect{$nam}{START} = $psectaddr & 1 ? ++$psectaddr : $psectaddr;
$psectaddr += $val;
} elsif ($psect{$nam}{FLG}{OVR}) {
# overlaid
warn sprintf("Warning: psect REL,OVR is not supported, psect='%s'\n", $psectname);
}
}
if ($DEBUG) {
printf $LOG "..GSD: type='%-6s'(%03o) name='%s' value=%06o", $ent[$ent], $ent, $nam, $val;
printf $LOG " length=%06o start=%06o", $psect{$nam}{LENGTH}, $psect{$nam}{START};
printf $LOG " flags=%s\n", join(",", sort(keys(%{$psect{$nam}{FLG}})));
}
}
$i += 8;
}
} elsif ($key == 002 && $pass == 1) { # ENDGSD
# just say we saw it
printf $LOG "..ENDGSD\n\n" if $DEBUG;
$program{END}{ADDRESS} = 0;
foreach my $nam (sort({$psect{$a}{START} == $psect{$b}{START} ? $psect{$a}{NUMBER} <=> $psect{$b}{NUMBER} : $psect{$a}{START} <=> $psect{$b}{START}} keys(%psect))) {
my $start = $psect{$nam}{START};
my $length = $psect{$nam}{LENGTH};
my $end = $length ? $start + $length - 1 : $start;
$program{END}{ADDRESS} = $end if $end > $program{END}{ADDRESS};
printf $LOG "....PSECT[%02d](%s) START=%06o END=%06o LENGTH=%06o\n",
$psect{$nam}{NUMBER}, $nam, $start, $end, $length if $length && $DEBUG;
}
printf $LOG "\n" if $DEBUG;
foreach my $nam (sort(keys(%gblsym))) {
if (exists $gblsym{$nam}{DEF}) {
printf $LOG "....GBLSYM(%s) PSECT='%s' VALUE=%06o : ADDRESS=%06o\n",
$nam, $gblsym{$nam}{DEF}{PSECT}, $gblsym{$nam}{DEF}{VALUE}, $gblsym{$nam}{DEF}{ADDRESS} if $DEBUG;
}
}
if ($program{START}{ADDRESS} == 1) {
$program{START}{ADDRESS} = $program{START}{VALUE} + $psect{$program{START}{PSECT}}{START};
}
printf $LOG "\n....PROG(ADDRESS) START=%06o END=%06o\n",
$program{START}{ADDRESS}, $program{END}{ADDRESS} if $DEBUG;
} elsif ($key == 003 && $pass == 2) { # TXT
# process text record
my $off = ($rec->[3]<<8)|($rec->[2]<<0);
my $len = scalar(@$rec)-4;
my $base = $psect{$psectname}{START};
my $adr = ($base + $off) & $adrmsk;
foreach my $i (1..$len) { $mem[$adr+$i-1] = $rec->[4+$i-1]; }
if ($DEBUG) {
printf $LOG "..TXT OFFSET=%06o LENGTH=%o BASE=%06o PSECTNAME='%s'\n", $off, $len, $base, $psectname;
for (my $i = 0; $i < $len; $i += 2) {
printf $LOG " %06o: ", ($adr+$i)&~1 if $i%8 == 0;
printf $LOG " %03o...", $mem[$adr+$i++] if ($adr+$i)&1;
printf $LOG " %06o", ($mem[$adr+$i+1]<<8)|($mem[$adr+$i+0]<<0) if $i < $len-1;
printf $LOG " ...%03o", $mem[$adr+$i] if $i == $len-1;
printf $LOG "\n" if $i%8 >= 6 && $i < $len-2;
}
printf $LOG "\n";
}
$adrmin = $adr if $adrmin eq '' || $adr < $adrmin;
$adrmax = $adr+$len-1 if $adrmax eq '' || $adr+$len-1 > $adrmax;
$textaddr = $adr;
} elsif ($key == 004 && $pass == 2) { # RLD
# iterate over RLD subrecords
for (my $i = 2; $i < scalar(@$rec); ) {
# first byte is entry type and flags
my $ent = $rec->[$i+0] & 0x7F; # entry type
my $flg = $rec->[$i+0] & 0x80; # modification flag (0=word, 1=byte)
# process an entry
if ($ent == 001) {
# internal relocation ... OK
my $dis = $rec->[$i+1];
my $con = ($rec->[$i+3]<<8)|($rec->[$i+2]<<0);
# process
my $adr = $adrmsk & ($textaddr + $dis - 4);
my $val = $datmsk & ($psect{$psectname}{START} + $con);
# store
$mem[($adr+0)&$adrmsk] = $memmsk & ($val>>0);
$mem[($adr+1)&$adrmsk] = $memmsk & ($val>>8);
# print
printf $LOG "..RLD(IR): adr=%06o val=%06o ; dis=%06o con=%06o\n",
$adr, $val, $dis, $con if $DEBUG;
$i += 4;
} elsif ($ent == 003) {
# internal displaced relocation ... OK
my $dis = $rec->[$i+1];
my $con = ($rec->[$i+3]<<8)|($rec->[$i+2]<<0);
# process
my $adr = $adrmsk & ($textaddr + $dis - 4);
my $val = $datmsk & ($con - ($adr+2));
# store
$mem[($adr+0)&$adrmsk] = $memmsk & ($val>>0);
$mem[($adr+1)&$adrmsk] = $memmsk & ($val>>8);
# print
printf $LOG "..RLD(IDR): adr=%06o val=%06o ; dis=%06o con=%06o\n",
$adr, $val, $dis, $con if $DEBUG;
$i += 4;
} elsif ($ent == 012) {
# psect relocation ... OK
my $dis = $rec->[$i+1];
my $nam = &sym2psect($file,&rad2asc(($rec->[$i+3]<<8)|($rec->[$i+2]<<0),($rec->[$i+5]<<8)|($rec->[$i+4]<<0)));
# process
my $adr = $adrmsk & ($textaddr + $dis - 4);
my $val = $datmsk & ($psect{$nam}{START});