2 // RLN - Reboot's Linker for the Atari Jaguar Console System
3 // RLN.C - Application Code
4 // Copyright (C) 199x, Allan K. Pratt, 2011 Reboot & Friends
9 unsigned errflag = 0; // Error flag, goes TRUE on error
10 unsigned waitflag = 0; // Wait for any keypress flag
11 unsigned versflag = 0; // Version banner has been shown flag
12 unsigned aflag = 0; // Absolute linking flag
13 unsigned bflag = 0; // Don't remove mulitply def locals flag
14 unsigned cflag = 0; // COF executable
15 unsigned dflag = 0; // Wait for key after link flag
16 unsigned gflag = 0; // Source level debug include flag
17 unsigned lflag = 0; // Add local symbols to output flag
18 unsigned mflag = 0; // Produce symbol load map flag
19 unsigned oflag = 0; // Output filename specified
20 unsigned rflag = 0; // Segment alignment size flag
21 unsigned sflag = 0; // Output only global symbols
22 unsigned vflag = 0; // Verbose flag
23 unsigned zflag = 0; // Suppress banner flag
24 unsigned pflag, uflag, wflag; // Unimplemented flags
25 unsigned hd = 0; // Index of next file handle to fill
26 unsigned secalign = 7; // Section Alignment (8=phrase)
27 unsigned tbase = 0; // TEXT base address
28 unsigned dbase = 0; // DATA base address
29 unsigned bbase = 0; // BSS base address
30 unsigned textoffset = 0; // COF TEXT segment offset
31 unsigned dataoffset = 0; // COF DATA segment offset
32 unsigned bssoffset = 0; // COF BSS segment offset
33 unsigned displaybanner = 1; // Display version banner
34 unsigned symoffset = 0; // Symbol table offset in output file
35 unsigned dosymi = 0; // Dosym() processing iterator
36 unsigned dbgsymbase = 0; // Debug symbol base address
37 //unsigned symtrunc = 0; // Symbol truncation -i and -ii
38 int noheaderflag = 0; // No header flag for ABS files
39 int hflags; // Value of the arg to -h option
40 int ttype, dtype, btype; // Type flag: 0, -1, -2, -3, -4
41 int tval, dval, bval; // Values of these abs bases
42 int hflag[NHANDLES]; // True for include files
43 int handle[NHANDLES]; // Open file handles
44 int textsize, datasize, bsssize; // Cumulative segment sizes
45 char libdir[FARGSIZE * 3]; // Library directory to search
46 char ofile[FARGSIZE]; // Output file name (.o)
47 char * name[NHANDLES]; // Associated file names
48 char * cmdlnexec = NULL; // Executable name - pointer to ARGV[0]
49 char * hsym1[SYMLEN]; // First symbol for include files
50 char * hsym2[SYMLEN]; // Second symbol for include files
51 struct OFILE * plist = NULL; // Object image list pointer
52 struct OFILE * plast; // Last object image list pointer
53 struct OFILE * olist = NULL; // Pointer to first object file in list
54 struct OFILE * olast; // Pointer to last object file in list
55 char obj_fname[512][FNLEN]; // Object file names
56 unsigned obj_segsize[512][3]; // Object file seg sizes; TEXT,DATA,BSS
57 unsigned obj_index = 0; // Object file index/count
58 struct HREC * htable[NBUCKETS]; // Hash table
59 struct HREC * unresolved = NULL; // Pointer to unresolved hash list
60 struct HREC * lookup(char *); // Hash lookup
61 char * ost; // Output symbol table
62 char * ost_ptr; // Output symbol table; current pointer
63 char * ost_end; // Output symbol table; end pointer
64 char * oststr; // Output string table
65 char * oststr_ptr; // Output string table; current pointer
66 char * oststr_end; // Output string table; end pointer
67 int ost_index = 0; // Index of next ost addition
68 int endian; // Processor endianess
72 // Get a Long Word from Memory
74 unsigned getlong(char * src)
101 // Put a Long Word into Memory
103 void putlong(char * dest, unsigned val)
105 *dest++ = (char)(val >> 24);
106 *dest++ = (char)(val >> 16);
107 *dest++ = (char)(val >> 8);
113 // Get a Word from Memory
115 int getword(char * src)
131 // Put a Word into Memory
133 void putword(char * dest, int val)
135 *dest++ = (char)(val >> 8);
141 // Obtain a File's Size
147 temp = lseek(fd, 0L, SEEK_CUR);
148 hold = lseek(fd, 0L, SEEK_END);
149 lseek(fd, 0L, SEEK_SET);
156 // For this object file, add symbols to the output symbol table after
157 // relocating them. Returns TRUE if ost_lookup returns an error (-1).
159 int dosym(struct OFILE * ofile)
161 char * symptr; // Symbol pointer
162 char * symend; // Symbol end pointer
163 int type; // Symbol type
164 long value; // Symbol value
165 int index; // Symbol index
167 int ssidx; // Segment size table index
168 unsigned tsegoffset; // Cumulative TEXT segment offset
169 unsigned dsegoffset; // Cumulative DATA segment offset
170 unsigned bsegoffset; // Cumulative BSS segment offset
171 struct HREC * hptr; // Hash table pointer for globl/extrn
172 char sym[SYMLEN]; // String for symbol name/hash search
174 // Point to first symbol record in the object file
175 symptr = (ofile->o_image + 32 +
176 ofile->o_header.tsize +
177 ofile->o_header.dsize +
178 ofile->o_header.absrel.reloc.tsize +
179 ofile->o_header.absrel.reloc.dsize);
181 // Point to end of symbol record in the object file
182 symend = symptr + ofile->o_header.ssize;
184 // Search through object segment size table to accumulated segment sizes to ensure
185 // the correct offsets are used in the resulting COF file.
186 ssidx = -1; // Initialise segment index
187 tsegoffset = dsegoffset = bsegoffset = 0; // Initialise segment offsets
189 for(j=0; j<(int)obj_index; j++)
190 { // Search for object file name
191 if (!strcmp(ofile->o_name, obj_fname[j]))
193 ssidx = j; // Object file name found
197 tsegoffset += obj_segsize[j][0]; // Accumulate segment sizes
198 dsegoffset += obj_segsize[j][1];
199 bsegoffset += obj_segsize[j][2];
204 printf("dosym() : Cannot get object file segment size : %s\n", ofile->o_name);
208 // Process each record in the symbol table
209 for(; symptr!=symend ; symptr+=12)
211 index = getlong(symptr + 0); // Obtain symbol string index
212 type = getlong(symptr + 4); // Obtain symbol type
213 value = getlong(symptr + 8); // Obtain symbol value
215 // Global/External symbols have a pre-processing stage
216 if (type & 0x01000000)
218 // Obtain the string table index for the relocation symbol, look for it in the globals
219 // hash table to obtain information on that symbol. For the hash calculation to work
220 // correctly it must be placed in a 'clean' string before looking it up.
221 memset(sym, 0, SYMLEN);
222 strcpy(sym, symend + index);
227 printf("dosym() : Cannot determine symbol : %s\n", sym);
231 // Search through object segment size table to obtain segment sizes for the object
232 // that has the required external/global as a local symbol. As each object is
233 // interrogated the segment sizes are accumulated to ensure the correct offsets are
234 // used in the resulting COF file. This is effectively 'done again' only as we
235 // are working with a different object file.
236 ssidx = -1; // Initialise segment index
237 tsegoffset = dsegoffset = bsegoffset = 0; // Initialise segment offsets
239 for(j=0; j<(int)obj_index; j++)
240 { // Search for object filename
241 if (!strcmp((const char *)hptr->h_ofile, obj_fname[j]))
243 ssidx = j; // Symbol object filename
247 tsegoffset += obj_segsize[j][0]; // Accumulate segment sizes
248 dsegoffset += obj_segsize[j][1];
249 bsegoffset += obj_segsize[j][2];
254 printf("dosym() : Cannot get object file segment size : %s\n",
259 type = hptr->h_type; // Update type with global type
261 if (type == 0x03000000)
262 type = 0x02000000; // Reset external flag if absolute
264 // If the global/external has a value then update that vaule in accordance with the
265 // segment sizes of the object file it originates from
268 switch (hptr->h_type & 0x0E000000)
270 case 0x02000000: // Absolute value
271 case 0x04000000: // TEXT segment
272 value = hptr->h_value;
274 case 0x06000000: // DATA segment
275 value = hptr->h_value - (hptr->h_ofile->o_header.tsize);
277 case 0x08000000: // BSS segment
278 value = hptr->h_value -
279 (hptr->h_ofile->o_header.tsize + hptr->h_ofile->o_header.dsize);
285 // Process and update the value dependant on whether the symbol is a debug symbol or not
286 if (type & 0xF0000000)
288 // Set the correct debug symbol base address (TEXT segment)
291 for(j=0; (unsigned)j<dosymi; j++)
292 dbgsymbase += obj_segsize[j][0];
294 switch (type & 0xFF000000)
297 value = tval + dbgsymbase;
302 value = tval + dbgsymbase + value;
307 putlong(symptr + 8, value);
310 { // NON-DEBUG SYMBOL
311 // Now make modifications to the symbol value, local or global, based on the segment sizes
312 // of the object file currently being processed.
313 switch (type & T_SEG)
315 case 0x02000000: // Absolute value
317 case T_TEXT: // TEXT segment
318 if (type & 0x01000000) value = tbase + tsegoffset + value;
319 else value = tbase + tsegoffset + value;
320 putlong(symptr + 8, value);
322 case T_DATA: // DATA segment
323 if (type & 0x01000000) value = dbase + dsegoffset + value;
324 else value = dbase + dsegoffset + (value - ofile->o_header.tsize);
325 putlong(symptr + 8, value);
327 case T_BSS: // BSS segment
328 if (type & 0x01000000) value = bbase + bsegoffset + value;
329 else value = bbase + bsegoffset +
330 (value - (ofile->o_header.tsize + ofile->o_header.dsize));
331 putlong(symptr + 8, value);
338 // Add to output symbol table
339 if (lflag || !islocal(type))
341 if (islocal(type) || isglobal(type))
343 if ((index = ost_add(symend + index, type, value)) == -1)
348 // Belongs in OST, but don't look it up yet
354 dosymi++; // Increment dosym() processsing
360 // Free Up Hash Records
365 struct HREC * htemp, * hptr;
367 for(i=0; i<NBUCKETS; i++)
373 htemp = hptr->h_next;
382 // Add all Global and External Symbols to the Output Symbol Table
386 struct HREC * hptr; // Hash record pointer
389 for(i=0; i<NBUCKETS; i++)
391 for(hptr=htable[i]; hptr!=NULL; hptr=hptr->h_next)
393 if (iscommon(hptr->h_type))
395 if (hptr->h_type == 0x03000000)
396 hptr->h_type = 0x02000000; // Absolutes can't be externals
398 if (ost_add(hptr->h_sym, hptr->h_type, hptr->h_value) == -1)
409 // Add a Symbol's Name, Type, and Value to the OST.
410 // Return the Index of the Symbol in OST, or -1 for Error.
412 int ost_add(char *name, int type, long value)
414 int ost_offset_p, ost_offset_e = 0; // OST table offsets for position calcs
415 int slen = 0; // Symbol string length
416 int ostresult; // OST index result
420 // If the OST or OST String Table has not been initialised then do so
421 if (ost_index == 0) {
422 if ((ost = malloc(OST_BLOCK)) == NULL) {
423 printf("OST memory allocation error (stringtable).\n");
426 ost_ptr = ost; // Set OST start pointer
427 ost_end = ost + OST_BLOCK; // Set OST end pointer
428 if ((oststr = malloc(OST_BLOCK)) == NULL) {
429 printf("OST memory allocation error (string).\n");
432 putlong(oststr, 0x00000004); // Just null long for now
433 oststr_ptr = oststr + 4; // Skip size of str table long (incl null long)
434 putlong(oststr_ptr, 0x00000000); // Null terminating long
435 oststr_end = oststr + OST_BLOCK;
437 // If next symbol record exceeds current allocation then expand symbol table.
438 ost_offset_p = (ost_ptr - ost);
439 ost_offset_e = (ost_end - ost);
440 if ((ost_ptr + 12) > ost_end) { // 3 x int (12)
441 if ((ost = realloc(ost, (unsigned)(ost_end + OST_BLOCK))) == NULL) {
442 printf("OST memory reallocation error.\n");
445 ost_ptr = ost + ost_offset_p;
446 ost_end = (ost + ost_offset_e) + OST_BLOCK;
448 ost_offset_p = (oststr_ptr - oststr);
449 ost_offset_e = (oststr_end - oststr);
450 if ((oststr_ptr + (slen+1+4)) > oststr_end) {
451 if ((oststr = realloc(oststr, (unsigned)(oststr_end + OST_BLOCK))) == NULL) {
452 printf("OSTSTR memory reallocation error.\n");
455 oststr_ptr = oststr + ost_offset_p;
456 oststr_end = (oststr + ost_offset_e) + OST_BLOCK;
460 // If this is a debug symbol and the include debug symbol flag (-g) is not set then do nothing
461 if ((type & 0xF0000000) && !gflag) {
464 ostresult = ost_lookup(name); // Get symbol index in OST
465 // If the symbol is in the output symbol table and the bflag is set (don't remove multiply
466 // defined locals) and this is not an external/global symbol *** OR *** the symbol is not
467 // in the output symbol table then add it.
468 if (((ostresult != -1) && bflag && !(type & 0x01000000)) ||
469 ((ostresult != -1) && gflag && (type & 0xF0000000)) || (ostresult == -1)) {
470 if ((type & 0xF0000000) == 0x40000000)
471 putlong(ost_ptr, 0x00000000); // Zero string table offset for dbg line
473 putlong(ost_ptr, (oststr_ptr - oststr)); // String table offset of symbol string
474 putlong(ost_ptr + 4, type );
475 putlong(ost_ptr + 8, value);
477 // If the symbol type is anything but a debug line information symbol then write
478 // the symbol string to the string table
479 if ((type & 0xF0000000) != 0x40000000) {
480 strcpy(oststr_ptr, name); // Put symbol name in string table
481 *(oststr_ptr + slen) = '\0'; // Add null terminating character
482 oststr_ptr += (slen + 1);
483 putlong(oststr_ptr, 0x00000000); // Null terminating long
484 putlong(oststr, (oststr_ptr - oststr)); // Update size of string table
486 return(ost_index++); // Return OST index
490 return 0; // not sure about this as it could affect return indices. needed to stop return error.
494 // Return the Index of a Symbol in the Output Symbol Table -------------------------------------
497 int ost_lookup(char *sym) {
499 int stro = 4; // Offset in string table
501 for(i = 0; i < ost_index; i++) {
502 if (!strcmp(oststr+stro, sym)) {
505 stro += strlen(oststr+stro) + 1;
513 // Add Unresolved Externs to the Output Symbol Table -------------------------------------------
516 int dounresolved(void) {
517 struct HREC *hptr, *htemp; // Hash record pointers
519 hptr = unresolved; // Point to unresolved symbols list
521 while (hptr != NULL) { // While unresolved list is valid
522 if (ost_add(hptr->h_sym, T_EXT, 0L) == -1) return 1;
523 htemp = hptr->h_next; // Temporarily get ptr to next record
524 free(hptr); // Free current record
525 hptr = htemp; // Make next record ptr, current
528 unresolved = NULL; // Zero unresolved record list
533 // -------------------------------------------------------------------------------------------------
534 // Update Object File TEXT and DATA Segments Based on Relocation Records. Take in an OFILE header
535 // and flag (T_TEXT, T_DATA) to process. Return (0) is successful or non-zero (1) if failed.
536 // -------------------------------------------------------------------------------------------------
538 int reloc_segment(struct OFILE *ofile, int flag) {
539 char *symtab; // Start of symbol table
540 char *symbols; // Start of symbols
541 char *sptr; // Start of segment data
542 char *rptr; // Start of segment relocation records
543 unsigned symidx; // Offset to symbol
544 unsigned addr; // Relocation address
545 unsigned rflg; // Relocation flags
546 unsigned olddata; // Old segment data at reloc address
547 unsigned newdata = 0; // New segment data at reloc address
548 unsigned pad; // Temporary to calculate phrase padding
550 char sym[SYMLEN]; // String for symbol name/hash search
551 int ssidx; // Segment size table index
552 unsigned glblreloc; // Global relocation flag
553 unsigned absreloc; // Absolute relocation flag
554 unsigned relreloc; // Relative relocation flag
555 unsigned swcond; // Switch statement condition
556 unsigned relocsize; // Relocation record size
558 // If there is no TEXT relocation data for the selected object file segment then update the COF
559 // TEXT segment offset allowing for the phrase padding
560 if ((flag == T_TEXT) && !ofile->o_header.absrel.reloc.tsize) {
561 pad = ((ofile->o_header.tsize+secalign) & ~secalign); // TEXT segment size plus padding
562 textoffset += (ofile->o_header.tsize + (pad - ofile->o_header.tsize));
563 if (vflag > 1) { // Verbose mode information
564 printf("reloc_segment(%s, TEXT) : No Relocation Data\n", ofile->o_name);
569 // If there is no DATA relocation data for the selected object file segment then update the COF
570 // DATA and BSS segment offsets allowing for the phrase padding
571 if ((flag == T_DATA) && !ofile->o_header.absrel.reloc.dsize) {
572 pad = ((ofile->o_header.dsize+secalign) & ~secalign); // DATA segment size plus padding
573 dataoffset += (ofile->o_header.dsize + (pad - ofile->o_header.dsize));
574 pad = ((ofile->o_header.bsize+secalign) & ~secalign); // BSS segment size plus padding
575 bssoffset += (ofile->o_header.bsize + (pad - ofile->o_header.bsize));
576 if (vflag > 1) { // Verbose mode information
577 printf("reloc_segment(%s, DATA) : No Relocation Data\n", ofile->o_name);
582 // Verbose mode information
584 printf("reloc_segment(%s, %s) : Processing Relocation Data\n",
585 ofile->o_name, flag == T_DATA ? "DATA" : "TEXT");
588 // Obtain pointer to start of symbol table
589 symtab = (ofile->o_image + 32 + ofile->o_header.tsize + ofile->o_header.dsize +
590 ofile->o_header.absrel.reloc.tsize + ofile->o_header.absrel.reloc.dsize);
592 // Obtain pointer to start of symbols
593 symbols = symtab + ofile->o_header.ssize;
595 // Obtain pointer to start of TEXT segment
596 sptr = ofile->o_image + 32;
598 // Obtain pointer to start of TEXT relocation records
599 rptr = sptr + (ofile->o_header.tsize + ofile->o_header.dsize);
601 relocsize = ofile->o_header.absrel.reloc.tsize;
603 // Update pointers if DATA relocation records are being processed
604 if (flag == T_DATA) {
605 sptr += ofile->o_header.tsize; // Start of DATA segment
606 rptr += ofile->o_header.absrel.reloc.tsize; // Start of DATA relocation records
607 relocsize = ofile->o_header.absrel.reloc.dsize;
610 // Process each relocation record for the TEXT segment
611 for(i = 0; i < (int)relocsize; i += 8) {
612 // Obtain both the relocation address and the relocation flags from the object file image
613 addr = getlong(rptr);
614 rflg = getlong(rptr + 4);
615 glblreloc = (rflg & 0x00000010) ? 1 : 0; // Set global relocation flag
616 absreloc = (rflg & 0x00000040) ? 1 : 0; // Set absolute relocation flag
617 relreloc = (rflg & 0x000000A0) ? 1 : 0; // Set relative relocation flag
619 // Additional processing required for global relocations
621 // Obtain the string table index for the relocation symbol, look for it in the globals
622 // hash table to obtain information on that symbol. For the hash calculation to work
623 // correctly it must be placed in a 'clean' string before looking it up.
624 symidx = getlong(symtab + ((rflg >> 8) * 12));
625 memset(sym, 0, SYMLEN);
626 strcpy(sym, symbols + symidx);
627 olddata = newdata = 0; // Initialise old and new segment data
628 ssidx = ost_lookup(sym);
629 newdata = getlong(ost + ((ssidx-1) * 12) + 8);
632 // Obtain the existing long word segment data and flip words if the relocation flags
633 // indicate it relates to a RISC MOVEI instruction
634 olddata = getlong(sptr + addr);
635 if (rflg & 0x01) olddata = _SWAPWORD(olddata);
637 // Process record dependant on segment it relates to; TEXT, DATA or BSS. Construct a new
638 // relocated segment long word based on the required segment base address, the segment
639 // data offset in the resulting COF file and the offsets from the incoming object file.
640 //swcond = glblreloc ? ((hptr->h_type & 0x0E000000) >> 16) : (rflg & 0xFFFFFF00);
641 swcond = (rflg & 0xFFFFFF00);
644 case 0x00000200: // Absolute Value
646 case 0x00000400: // TEXT segment relocation record
648 if (flag == T_TEXT) newdata = tbase + textoffset + olddata;
649 else newdata = tbase + dataoffset + olddata;
651 case 0x00000600: // DATA segment relocation record
652 if (!glblreloc) newdata = dbase + dataoffset + (olddata - ofile->o_header.tsize);
654 case 0x00000800: // BSS segment relocation record
655 if (!glblreloc) newdata = bbase + bssoffset +
656 (olddata - (ofile->o_header.tsize + ofile->o_header.dsize));
660 if (!relreloc) newdata += olddata;
662 // Set absolute (long) or relative (word) address of symbol
664 // Flip the new long word segment data if the relocation record indicated a RISC MOVEI
665 // instruction and place the resulting data back in the COF segment
666 if (rflg & 0x01) newdata = _SWAPWORD(newdata);
668 putlong(sptr + addr, newdata);
672 putword(sptr + addr, newdata - tbase - addr - ofile->o_tbase);
675 rptr += 8; // Point to the next relocation record
678 // Update the COF segment offset allowing for the phrase padding.
679 if (flag == T_TEXT) {
680 pad = ((ofile->o_header.tsize+secalign) & ~secalign); // TEXT segment plus padding
681 textoffset += (ofile->o_header.tsize + (pad - ofile->o_header.tsize));
683 pad = ((ofile->o_header.dsize+secalign) & ~secalign); // DATA segment plus padding
684 dataoffset += (ofile->o_header.dsize + (pad - ofile->o_header.dsize));
685 pad = ((ofile->o_header.bsize+secalign) & ~secalign); // BSS segment plus padding
686 bssoffset += (ofile->o_header.bsize + (pad - ofile->o_header.bsize));
689 return 0; // Return value, should always be zero
693 // -------------------------------------------------------------------------------------------------
694 // Add a path character to the end of string 's' if it doesn't already end with one.
695 // The last occurrance of '/' or '\\' in the string is assumed to be the path character.
696 // -------------------------------------------------------------------------------------------------
699 void pathadd(char *s) {
703 if (*s == '/' || *s == '\\') pathchar = *s;
707 if (*s == pathchar) return;
714 // -------------------------------------------------------------------------------------------------
715 // Try to open "name", "name.o", "${libdir}name", "${libdir}name.o". Return the handle of the file
716 // successfully opened. p_name is updated to point to a malloc()'ed string which is the name which
717 // actually got opened. p_name will return unchanged if the file can't be found.
718 // -------------------------------------------------------------------------------------------------
721 int tryopen(char **p_name) {
722 char *name = *p_name; // Filename
723 char *tmpbuf, *lastdot; // Buffer and 'dot' pointers
724 int fd, hasdot; // File descriptor and 'has dot' flag
726 // Note that libdir will be an empty string if there is none specified
727 if ((tmpbuf = malloc((long)strlen(name) + strlen(libdir) + 3)) == NULL) {
728 printf("tryopen() : out of memory\n");
731 strcpy(tmpbuf, name);
733 hasdot = ((lastdot = strrchr(tmpbuf, '.')) > strrchr(tmpbuf, '/')) &&
734 (lastdot > strrchr(tmpbuf, '\\'));
736 if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0) goto ok; // Try to open file as passed first
738 strcat(tmpbuf, ".o"); // Try to open file with '.o' added
739 if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0) goto ok;
742 // Try the libdir only if the name isn't already anchored
743 if (*name != '/' && *name != '\\' && !strchr(name, ':')) {
744 strcpy(tmpbuf,libdir);
745 // Add a trailing path char if there isn't one already
747 strcat(tmpbuf, name);
748 if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0) goto ok;
750 strcat(tmpbuf, ".o");
751 if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0) goto ok;
755 return(-1); // Couldn't open file at all
757 ok: // What more Atari label use - sigh!!!
759 if ((tmpbuf = realloc(tmpbuf, (long)strlen(tmpbuf) + 1)) == NULL) {
760 printf("tryopen() : out of memory\n");
765 return(fd); // Return file descriptor
770 // Archive File Use, Needs to be Removed
772 void put_name(struct OFILE * p)
774 int flag = *(p->o_arname);
775 printf("%s%s%s", flag ? p->o_arname : "", flag ? ":" : "", p->o_name);
780 // Collect file names and handles in a buffer so there is less disk activity.
781 // Call dofile with flag FALSE for normal object files and archives.
782 // Call it with flag TRUE and a symbol name for include files (-i).
784 int dofile(char * fname, int flag, char * sym)
786 int fd; // File descriptor
787 int temp; // Temporary storage
789 // Verbose information
792 printf("dofile() : `%s' %s", fname, flag ? "INCLUDE" : "NORMAL");
795 printf(" symbol %s", sym);
800 // Reached maximum file handles
803 if (flush_handles()) return 1;
806 // Attempt to open input file
807 if ((fd = tryopen(&fname)) < 0)
809 printf("Cannot find input module %s\n", fname);
813 // The file is open; save its info in the handle and name arrays
815 name[hd] = fname; // This is the name from tryopen()
821 temp = strlen(sym); // Get symbol length
823 // 100 chars is max length of a symbol
830 // Malloc enough space for two symbols, then build the second one. Second one may be one
831 // character longer than first
832 if ((hsym1[hd] = malloc((long)temp + 1)) == NULL
833 || (hsym2[hd] = malloc((long)temp + 2)) == NULL)
835 printf("dofile() : out of memory for include-file symbols\n");
839 strcpy(hsym1[hd], sym);
840 strcpy(hsym2[hd], sym);
846 printf("Last char of %s is already 'x': choose another name\n", sym);
854 hsym2[hd][temp] = 'x';
855 hsym2[hd][temp+1] = '\0';
859 hd++; // Increment next handle index
860 return 0; // No problems
865 // Pad TEXT or DATA Segment to the Requested Boundary
867 int segmentpad(FILE * fd, long segsize, int value)
869 long padsize; // Number of pad bytes needed
870 int i; // Good 'ol iterator
871 char padarray[32]; // Array of padding bytes
872 char * padptr; // Pointer to array
874 // Determine the number of padding bytes that are needed
875 padsize = (segsize + secalign) & ~secalign;
876 padsize = padsize - segsize;
878 // Fill pad array if padding is required
885 putword(padptr, value);
889 symoffset += padsize;
891 if (fwrite(padarray, padsize, 1, fd) != 1) // Write padding bytes
895 return 0; // All done
900 // Write the Output File
902 int write_ofile(struct OHEADER * header)
904 FILE * fd; // File descriptor
905 unsigned osize; // Object segment size
906 struct OFILE * otemp; // Object file pointer
907 int i, j; // Iterators
908 char himage[0x168]; // Header image (COF = 0xA8)
909 unsigned tsoff, dsoff, bsoff; // Segment offset values
910 unsigned index, type, value; // Symbol table index, type and value
911 short abstype; // ABS symbol type
912 char symbol[14]; // Symbol record for ABS files
913 int slen; // Symbol string length
915 symoffset = 0; // Initialise symbol offset
917 // Add correct output extension if none
918 if (strchr(ofile, '.') == NULL)
920 if (aflag && cflag) strcat(ofile, ".cof"); // COF files
921 else if (aflag && !cflag) strcat(ofile, ".abs"); // ABS files
922 else strcat(ofile, ".o"); // Object files (partial linking etc)
925 fd = fopen(ofile, "wb"); // Attempt to open output file
929 printf("Can't open output file %s\n", ofile); // Error opening output file
933 // Build the output file header
934 // Absolute (COF) header
937 tsoff = dsoff = bsoff = 0xA8; // Initialises segment offsets
939 // Process each object file segment size to obtain a cumulative segment size for both
940 // the TEXT and DATA segments
941 for(i=0; i<(int)obj_index; i++)
943 dsoff += obj_segsize[i][0]; // Adding TEXT segment sizes
944 bsoff += obj_segsize[i][0] + obj_segsize[i][1]; // Adding TEXT and DATA segment sizes
947 // Currently this only builds a COF absolute file. Conditionals and additional code will
948 // need to be added for ABS and partial linking.
951 putword(himage + 0, 0x0150 ); // Magic Number (0x0150)
952 putword(himage + 2, 0x0003 ); // Sections Number (3)
953 putlong(himage + 4, 0x00000000 ); // Date (0L)
954 putlong(himage + 8, dsoff + header->dsize); // Offset to Symbols Section
955 putlong(himage + 12, ost_index); // Number of Symbols
956 putword(himage + 16, 0x001C ); // Size of RUN_HDR (0x1C)
957 putword(himage + 18, 0x0003 ); // Executable Flags (3)
960 putlong(himage + 20, 0x00000107 ); // Magic/vstamp
961 putlong(himage + 24, header->tsize ); // TEXT size in bytes
962 putlong(himage + 28, header->dsize ); // DATA size in bytes
963 putlong(himage + 32, header->bsize ); // BSS size in bytes
964 putlong(himage + 36, tbase ); // Start of executable, normally @TEXT
965 putlong(himage + 40, tbase ); // @TEXT
966 putlong(himage + 44, dbase ); // @DATA
968 // Build the TEXT SEC_HDR
969 putlong(himage + 48, 0x2E746578 );
970 putlong(himage + 52, 0x74000000 ); // ".text"
971 putlong(himage + 56, tbase ); // TEXT START
972 putlong(himage + 60, tbase ); // TEXT START
973 putlong(himage + 64, header->tsize ); // TEXT size in bytes
974 putlong(himage + 68, tsoff ); // Offset to section data in file
975 putlong(himage + 72, 0x00000000 ); // Offset to section reloc in file (0L)
976 putlong(himage + 76, 0x00000000 ); // Offset to debug lines structures (0L)
977 putlong(himage + 80, 0x00000000 ); // Nreloc/nlnno (0L)
978 putlong(himage + 84, 0x00000020 ); // SEC_FLAGS: STYP_TEXT
980 // Build the DATA SEC_HDR
981 putlong(himage + 88, 0x2E646174 );
982 putlong(himage + 92, 0x61000000 ); // ".data"
983 putlong(himage + 96, dbase ); // DATA START
984 putlong(himage + 100, dbase ); // DATA START
985 putlong(himage + 104, header->dsize ); // DATA size in bytes
986 putlong(himage + 108, dsoff ); // Offset to section data in file
987 putlong(himage + 112, 0x00000000 ); // Offset to section reloc in file (0L)
988 putlong(himage + 116, 0x00000000 ); // Offset to debugging lines structures (0L)
989 putlong(himage + 120, 0x00000000 ); // Nreloc/nlnno (0L)
990 putlong(himage + 124, 0x00000040 ); // SEC_FLAGS: STYP_DATA
992 // Build the BSS SEC_HDR
993 putlong(himage + 128, 0x2E627373 );
994 putlong(himage + 132, 0x00000000 ); // ".bss"
995 putlong(himage + 136, bbase ); // BSS START
996 putlong(himage + 140, bbase ); // BSS START
997 putlong(himage + 144, header->bsize ); // BSS size in bytes
998 putlong(himage + 148, bsoff ); // Offset to section data in file
999 putlong(himage + 152, 0x00000000 ); // Offset to section reloc in file (0L)
1000 putlong(himage + 156, 0x00000000 ); // Offset to debugging lines structures (0L)
1001 putlong(himage + 160, 0x00000000 ); // Nreloc/nlnno (0L)
1002 putlong(himage + 164, 0x00000080 ); // SEC_FLAGS: STYP_BSS
1004 symoffset = 168; // Update symbol offset
1006 // Absolute (ABS) header
1009 // Build the ABS header
1010 putword(himage + 0, 0x601B ); // Magic Number (0x601B)
1011 putlong(himage + 2, header->tsize ); // TEXT segment size
1012 putlong(himage + 6, header->dsize ); // DATA segment size
1013 putlong(himage + 10, header->bsize ); // BSS segment size
1014 putlong(himage + 14, ost_index * 14 ); // Symbol table size (?)
1015 putlong(himage + 18, 0x00000000 ); //
1016 putlong(himage + 22, tbase ); // TEXT base address
1017 putword(himage + 26, 0xFFFF ); // Flags (?)
1018 putlong(himage + 28, dbase ); // DATA base address
1019 putlong(himage + 32, bbase ); // BSS base address
1021 symoffset = 36; // Update symbol offset
1024 // Write the header, but not if noheaderflag
1025 // Absolute (ABS) header
1029 if (fwrite(himage, 36, 1, fd) != 1)
1032 // Absolute (COF) header
1035 if (fwrite(himage, 168, 1, fd) != 1)
1039 // Write the TEXT segment of each object file
1040 for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1042 osize = otemp->o_header.tsize;
1044 // Write only if segment has size
1048 printf("Writing TEXT Segment of %s\n", otemp->o_name);
1050 if (fwrite(otemp->o_image + 32, osize, 1, fd) != 1)
1053 // Pad to required alignment boundary
1054 if (segmentpad(fd, osize, 0x0000))
1061 // Write the DATA segment of each object file
1062 for(otemp = olist; otemp != NULL; otemp = otemp->o_next)
1064 osize = otemp->o_header.dsize;
1066 // Write only if the segment has size
1070 printf("Writing DATA Segment of %s\n", otemp->o_name);
1072 if (fwrite((otemp->o_image + 32 + otemp->o_header.tsize), osize, 1, fd) != 1)
1075 // Pad to required alignment boundary
1076 if (segmentpad(fd, osize, 0))
1085 // Write the symbols table and string table
1086 // Absolute (COF) symbol/string table
1091 if (fwrite(ost, (ost_ptr - ost), 1, fd) != 1) goto werror;
1092 if (fwrite(oststr, (oststr_ptr - oststr), 1, fd) != 1) goto werror;
1095 // Absolute (ABS) symbol/string table
1098 // The symbol and string table have been created as part of the dosym() function and the
1099 // output symbol and string tables are in COF format. For an ABS file we need to process
1100 // through this to create the 14 character long combined symbol and string table.
1101 // Format of symbol table in ABS: AAAAAAAATTVVVV, where (A)=STRING, (T)=TYPE & (V)=VALUE
1103 for(i=0; i<ost_index; i++)
1105 memset(symbol, 0, 14); // Initialise symbol record
1106 abstype = 0; // Initialise ABS symbol type
1107 slen = 0; // Initialise symbol string length
1108 index = getlong(ost + (i * 12)); // Get symbol index
1109 type = getlong((ost + (i * 12)) + 4); // Get symbol type
1111 if (type & 0xF0000000)
1112 continue; // Not doing debug symbols
1114 value = getlong((ost + (i * 12)) + 8); // Get symbol value
1115 slen = strlen(oststr + index);
1117 // Get symbol string (maximum 8 chars)
1121 *(symbol + j) = *(oststr + index + j);
1125 for(j=0; j<slen; j++)
1126 *(symbol + j) = *(oststr + index + j);
1129 // Modify to ABS symbol type
1132 case 0x02000000: abstype = (short)ABST_DEFINED; break;
1133 case 0x04000000: abstype = (short)ABST_DEFINED | ABST_TEXT; break;
1134 case 0x05000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_TEXT; break;
1135 case 0x06000000: abstype = (short)ABST_DEFINED | ABST_DATA; break;
1136 case 0x07000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_DATA; break;
1137 case 0x08000000: abstype = (short)ABST_DEFINED | ABST_BSS; break;
1138 case 0x09000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_BSS; break;
1140 printf("write_ofile: abs, cannot determine symbol type\n");
1145 putword(symbol + 8, abstype); // Write back new ABS type
1146 putlong(symbol + 10, value); // Write back value
1148 if (fwrite(symbol, 14, 1, fd) != 1) goto werror; // Write symbol record
1156 printf("Close error on output file %s\n",ofile);
1162 werror: // OMG! Why did Atari use these :)
1163 printf("Write error on output file %s\n", ofile);
1164 fclose(fd); // Try to close output file anyway
1170 // Display the Symbol Load Map
1172 int write_map(struct OHEADER * header)
1174 unsigned i, o; // Inner and outer loop iterators
1175 unsigned c; // Column number
1176 unsigned index; // Symbol string index
1177 unsigned type; // Symbol type
1178 unsigned value; // Symbol value
1179 char * symbol; // Symbol string value
1182 return 0; // Return if no symbols to map
1184 printf("LOAD MAP\n\n");
1186 // Outer loop for each of the symbol areas to map out;
1187 // 0 = NON-RELOCATABLE SYMBOLS
1188 // 1 = TEXT-SEGMENT RELOCATABLE SYMBOLS
1189 // 2 = DATA-SEGMENT RELOCATABLE SYMBOLS
1190 // 3 = BSS-SEGMENT RELOCATABLE SYMBOLS
1193 // Display the correct map header for the symbols being processed
1196 case 0: printf("NON-RELOCATABLE SYMBOLS\n\n"); break;
1197 case 1: printf("TEXT-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1198 case 2: printf("DATA-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1199 case 3: printf("BSS-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1202 c = 0; // Initialise column number
1204 // Inner loop to process each record in the symbol table
1205 for(i=0; i<(unsigned)ost_index; i++)
1207 index = getlong(ost + (i * 12)); // Get symbol string index
1208 type = getlong(ost + (i * 12) + 4); // Get symbol type
1209 value = getlong(ost + (i * 12) + 8); // Get symbol value
1210 symbol = oststr + index; // Get symbol string
1212 // Display only three columns
1219 // If local symbols not included and the type is local then go to next symbol record
1220 if (!lflag & !(type & 0x01000000))
1223 // Output each symbol to the display, dependant on type
1226 case 0: // Non-relocatable symbols
1227 if (type == 0x02000000 || type == 0x03000000)
1229 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1234 case 1: // TEXT segment relocatable symbols
1235 if (type == 0x04000000 || type == 0x05000000)
1237 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1242 case 2: // DATA segment relocatble symbols
1243 if (type == 0x06000000 || type == 0x07000000)
1245 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1250 case 3: // BSS segment relocatable symbols
1251 if (type == 0x08000000 || type == 0x09000000)
1253 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1264 return 0; // All done
1269 // Convert ASCII to Hexadecimal
1271 //int atolx(char * string, long * value)
1272 int atolx(char * string, int * value)
1276 while (isxdigit(*string))
1278 if (isdigit(*string))
1280 *value = (*value << 4) + (*string++ - '0');
1284 if (isupper(*string))
1285 *string = tolower(*string);
1287 *value = (*value << 4) + ((*string++ - 'a') + 10);
1291 if (*string != '\0')
1293 printf("Invalid hexadecimal value");
1302 // Stuff the (long) value of a string into the value argument. RETURNS TRUE if
1303 // the string doesn't parse. Parses only as a hex string.
1305 //int getval(char * string, long * value)
1306 int getval(char * string, int * value)
1308 return atolx(string, value);
1313 // Create one big .o file from the images already in memory, returning a
1314 // pointer to an OHEADER. Note that the oheader is just the header for the
1315 // output (plus some other information). The text, data, and fixups are all
1316 // still in the ofile images hanging off the global `olist'.
1318 struct OHEADER * make_ofile()
1320 unsigned tptr, dptr, bptr; // Bases in runtime model
1321 int ret = 0; // Return value
1322 struct OFILE * otemp, * oprev, * ohold; // Object file list pointers
1323 struct OHEADER * header; // Output header pointer
1325 textsize = datasize = bsssize = 0; // Initialise cumulative segment sizes
1327 // For each object file, accumulate the sizes of the segments but remove those
1328 // object files which are unused
1329 oprev = NULL; // Init previous obj file list ptr
1330 otemp = olist; // Set temp pointer to object file list
1332 while (otemp != NULL)
1335 if (!(otemp->o_flags & O_ARCHIVE))
1337 if ((otemp->o_flags & O_USED) == 0)
1341 printf("Unused object file ");
1343 printf(" discarded.\n");
1348 olist = otemp->o_next;
1352 oprev -> o_next = otemp->o_next;
1356 free(ohold->o_image);
1361 // Increment total of segment sizes ensuring requested alignment
1362 textsize += (otemp->o_header.tsize+secalign) & ~secalign;
1363 datasize += (otemp->o_header.dsize+secalign) & ~secalign;
1364 bsssize += (otemp->o_header.bsize+secalign) & ~secalign;
1369 otemp = otemp->o_next; // Go to next object file list pointer
1372 // Update base addresses and create symbols _TEXT_E, _DATA_E and _BSS_E
1374 ost_add("_TEXT_E", 0x05000000, tval + textsize);
1378 // DATA follows TEXT
1379 dbase = tval + textsize;
1380 ost_add("_DATA_E", 0x07000000, tval + textsize + datasize);
1385 bbase = tval + textsize + datasize;
1386 ost_add("_BSS_E", 0x09000000, tval + textsize + datasize + bsssize);
1390 // BSS is independant of DATA
1392 ost_add("_BSS_E", 0x09000000, bval + bsssize);
1397 // DATA is independant of TEXT
1399 ost_add("_DATA_E", 0x07000000, dval + datasize);
1404 bbase = dval + datasize;
1405 ost_add("_BSS_E", 0x09000000, dval + datasize + bsssize);
1409 // BSS is independant of DATA
1411 ost_add("_BSS_E", 0x09000000, bval + bsssize);
1415 // Place each unresolved symbol in the output symbol table
1419 tptr = 0; // Initialise base addresses
1423 // For each file, relocate its symbols and add them to the output symbol table
1427 while (otemp != NULL)
1429 otemp->o_tbase = tptr;
1431 // Do rest only for non-ARCHIVE markers
1432 if (!(otemp->o_flags & O_ARCHIVE))
1434 otemp->o_dbase = dptr;
1435 otemp->o_bbase = bptr;
1436 tptr += (otemp->o_header.tsize+secalign) & ~secalign;
1437 dptr += (otemp->o_header.dsize+secalign) & ~secalign;
1438 bptr += (otemp->o_header.bsize+secalign) & ~secalign;
1440 // For each symbol, (conditionally) add it to the ost
1441 // For ARCHIVE markers, this adds the symbol for the file & returns
1445 if (otemp->o_flags & O_ARCHIVE)
1447 // Now that the archive is marked, remove it from list
1450 olist = otemp->o_next;
1454 oprev->o_next = otemp->o_next;
1459 if (ohold->o_image) free(ohold->o_image);
1467 otemp = otemp->o_next;
1470 // Places all the externs, globals etc into the output symbol table
1471 if (docommon() == -1)
1474 // Create a new output file header
1475 if ((header = new_oheader()) == NULL)
1477 printf("make_ofile: out of memory!\n");
1481 // Fill in the output header. Does not match the actual output but values used as reference
1482 header->magic = 0x0150; // COF magic number
1483 header->tsize = textsize; // TEXT segment size
1484 header->dsize = datasize; // DATA segment size
1485 header->bsize = bsssize; // BSS segment size
1486 header->ssize = (ost_ptr - ost); // Symbol table size
1487 header->ostbase = ost; // Output symbol table base address
1489 // For each object file, relocate its TEXT and DATA segments. OR the result into ret so all
1490 // files get moved (and errors reported) before returning with the error condition
1491 for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1493 if (!(otemp->o_flags & O_ARCHIVE))
1495 ret |= reloc_segment(otemp, T_TEXT); // TEXT segment relocations
1496 ret |= reloc_segment(otemp, T_DATA); // DATA segment relocations
1500 hash_free(); // Done with global symbol hash tables
1502 return (ret ? (unsigned)NULL : header);
1507 // Add Symbol to Hash List
1509 int add_to_hlist(struct HREC **hptr, char *sym, struct OFILE *ofile, long value, int type)
1511 struct HREC *htemp; // Temporary hash record pointer
1514 // Attempt to allocate new hash record
1515 if ((htemp = new_hrec()) == NULL)
1517 printf("Out of memory\n");
1521 for(i=0; i<SYMLEN; i++)
1522 htemp->h_sym[i] = '\0';
1524 strcpy(htemp->h_sym, sym); // Populate hash record
1525 htemp->h_ofile = ofile;
1526 htemp->h_value = value;
1527 htemp->h_type = type;
1529 htemp->h_next = *hptr; // Update hash record pointers
1537 // Add Symbol to the Unresolved Symbols Hash Table
1539 add_unresolved(char * sym, struct OFILE * ofile)
1542 printf("add_unresolved(%s,%s)\n", sym, ofile->o_name);
1544 return add_to_hlist(&unresolved, sym, ofile, 0L, 0);
1549 // Generate and Return Hash Value
1551 int dohash(char * s)
1553 int i = (s[0]+s[1]+s[2]+s[3]+s[4]+s[5]+s[6]+s[7] +s[8]+s[9]+s[10]+s[11]+s[12]+s[13]+s[14]) % NBUCKETS;
1559 // Lookup a Symbol in the Hash Table
1561 struct HREC * lookup(char * sym)
1563 struct HREC * hptr = htable[dohash(sym)]; // Hash index to record based on sym
1564 char symbol[SYMLEN]; // Temporary symbol storage
1566 memset(symbol, 0, SYMLEN); // Clean string for comparison
1567 strcpy(symbol, sym);
1569 while (hptr != NULL)
1571 if (symcmp(symbol, hptr->h_sym))
1574 hptr = hptr->h_next; // Return hash pointer if found
1577 return NULL; // Not found in hash table
1582 // Add Symbol to the Hash Table
1584 int hash_add(char * sym, long type, long value, struct OFILE * ofile)
1587 int flag = !iscommon(type);
1591 printf("hash_add(%s,%s,%lx,", sym, ofile->o_name,value);
1592 printf("%x,%s)\n", (unsigned int)type, (flag ? "GLOBAL" : "COMMON"));
1595 if ((hptr = lookup(sym)) == NULL)
1597 return add_to_hlist(&htable[dohash(sym)], sym, ofile, value, type);
1601 if (iscommon(type) && !iscommon(hptr->h_type))
1603 // Mismatch: global came first; warn and keep the global one
1606 printf("Warning: %s: global from ",sym);
1607 put_name(hptr->h_ofile);
1608 printf(" used, common from ");
1610 printf(" discarded.\n");
1613 putword(sym + 8, ABST_EXTERN);
1614 putlong(sym + 10, 0L);
1616 else if (iscommon(hptr->h_type) && !iscommon(type))
1618 // Mismatch: common came first; warn and keep the global one
1621 printf("Warning: %s: global from ", sym);
1623 printf(" used, common from ");
1624 put_name(hptr->h_ofile);
1625 printf(" discarded.\n");
1628 hptr->h_type = type;
1629 hptr->h_ofile = ofile;
1630 hptr->h_value = value;
1633 { // They're both global
1634 // Global exported by another ofile; warn and make this one extern
1637 printf("Duplicate symbol %s: ", sym);
1638 put_name(hptr->h_ofile);
1641 printf(" discarded\n");
1644 putword(sym + 8, ABST_EXTERN);
1647 { // They're both common
1648 if (hptr->h_value < value)
1650 hptr->h_value = value;
1651 hptr->h_ofile = ofile;
1659 // -------------------------------------------------------------------------------------------------
1660 // Add the imported symbols from this file to unresolved, and the global and common symbols to the
1661 // exported hash table.
1663 // Change old-style commons (type == T_EXTERN, value != 0) to new-style ones
1664 // (type == (T_GLOBAL | T_EXTERN)).
1665 // -------------------------------------------------------------------------------------------------
1668 int add_symbols(struct OFILE *Ofile) {
1669 long nsymbols; // Number of symbols in object file
1670 char *ptr; // Object data base pointer
1671 char *sfix; // Symbol fixup table pointer
1672 char *sstr; // Symbol string table pointer
1673 long index; // String index
1674 long type; // Symbol type
1675 long value; // Symbol value
1676 struct HREC *hptr; // Hash record pointer
1677 char symbol[SYMLEN];
1680 printf("Add symbols for file %s\n", Ofile->o_name);
1682 ptr = Ofile->o_image + 32 + // Get base pointer, start of sym fixups
1683 Ofile->o_header.tsize +
1684 Ofile->o_header.dsize +
1685 Ofile->o_header.absrel.reloc.tsize +
1686 Ofile->o_header.absrel.reloc.dsize;
1687 sfix = ptr; // Set symbol fixup pointer
1688 sstr = sfix + Ofile->o_header.ssize; // Set symbol table pointer
1689 nsymbols = Ofile->o_header.ssize / 12; // Obtain number of symbols
1692 index = getlong(sfix); // Get symbol string index
1693 type = getlong(sfix+4); // Get symbol type
1694 value = getlong(sfix+8); // Get symbol value
1695 memset(symbol, 0, SYMLEN);
1696 strcpy(symbol, sstr+index);
1698 if (type & T_EXT) { // If this is a global/external
1699 if ((type - T_EXT)) {
1700 if (hash_add(symbol, type, value, Ofile)) { // Then add to hash table
1701 return 1; // Error if addition failed
1704 if ((hptr = lookup(symbol)) != NULL) { // If value is zero and in hash table
1705 hptr->h_ofile->o_flags |= O_USED; // Mark symbol as used
1706 } else if (add_unresolved(symbol, Ofile)) { // Otherwise add to unresolved list
1707 return 1; // Error if addition failed
1712 sfix += 12; // Increment symbol fixup pointer
1713 nsymbols--; // Decrement num of symbols to process
1716 return 0; // Success loading symbols
1720 // Process Object File for Symbols -------------------------------------------------------------
1723 int doobj(char *fname, char *ptr, char *aname, int flags) {
1724 struct OFILE *Ofile; // Object record pointer
1725 char *temp; // Temporary data pointer
1727 if ((Ofile = new_ofile()) == NULL) { // Allocate memory for object record ptr
1728 printf("Out of memory processing %s\n",fname);
1732 // Starting after all pathnames, etc., copy .o file name to Ofile
1733 temp = path_tail(fname);
1734 if (strlen(temp) > FNLEN - 1) { // Check filename length
1735 printf("File name too long: %s\n", temp);
1738 if (strlen(aname) > FNLEN - 1) { // Check archive name length
1739 printf("Archive name too long: %s\n", aname);
1742 strcpy(Ofile->o_name, temp); // Store filename
1743 strcpy(Ofile->o_arname, aname); // Store archive name
1745 Ofile->o_next = NULL; // Initialise object record information
1749 Ofile->o_flags = flags;
1750 Ofile->o_image = ptr;
1752 // Don't do anything if this is just an ARCHIVE marker, just add the file to the olist
1753 if (!(flags & O_ARCHIVE)) {
1754 Ofile->o_header.magic = getlong(ptr);
1755 Ofile->o_header.tsize = getlong(ptr+4);
1756 Ofile->o_header.dsize = getlong(ptr+8);
1757 Ofile->o_header.bsize = getlong(ptr+12);
1758 Ofile->o_header.ssize = getlong(ptr+16);
1759 Ofile->o_header.absrel.reloc.tsize = getlong(ptr+24);
1760 Ofile->o_header.absrel.reloc.dsize = getlong(ptr+28);
1762 // Round BSS off to alignment boundary
1763 Ofile->o_header.bsize = (Ofile->o_header.bsize + secalign) & ~secalign;
1764 if (Ofile->o_header.dsize & 7) {
1765 printf("Warning: data segment size of ");
1767 printf(" is not a phrase multiple\n");
1770 // Check for odd segment sizes
1771 if ((Ofile->o_header.tsize & 1) || (Ofile->o_header.dsize & 1) || (Ofile->o_header.bsize & 1)) {
1772 printf("Error: odd-sized segment in ");
1774 printf("; link aborted.\n");
1778 if (add_symbols(Ofile)) return 1;
1781 // Add this file to the olist
1785 olast->o_next = Ofile;
1792 // Remove Elements from Unresolved List which are Resolvable
1796 struct HREC * uptr; // Unresolved hash record pointer
1797 struct HREC * prev = NULL; // Previous hash record pointer
1798 struct HREC * htemp; // Temporary hash record pointer
1799 struct OFILE * ptemp; // Temporary object file record pointer
1801 // Process object file list
1802 while (plist != NULL)
1804 if (doobj(plist->o_name, plist->o_image, plist->o_arname, plist->o_flags))
1808 plist = plist->o_next;
1812 // Process unresolved list
1813 for(uptr=unresolved; uptr!=NULL; )
1816 printf("lookup(%s) => ",uptr->h_sym);
1818 if ((htemp = lookup(uptr->h_sym)) != NULL)
1821 printf(" %s in %s\n", isglobal(htemp->h_type) ? "global" : "common", htemp->h_ofile->o_name);
1823 htemp->h_ofile->o_flags |= O_USED;
1827 unresolved = uptr->h_next;
1833 prev->h_next = uptr->h_next;
1835 uptr = prev->h_next;
1842 uptr = uptr->h_next;
1851 // Extract Filename from Path
1853 char * path_tail(char * name)
1855 char * temp = max(strrchr(name,'/'), max(strrchr(name,':'), strrchr(name, 92)));
1865 // Add Input File to Processing List
1867 int pladd(char * ptr, char * fname)
1871 plist = new_ofile(); // First time object record allocation
1872 plast = plist; // Update last object record pointer
1876 plast->o_next = new_ofile(); // Next object record allocation
1877 plast = plast->o_next; // Update last object record pointer
1882 printf("Out of memory.\n"); // Error if memory allocation fails
1886 if (strlen(path_tail(fname)) > FNLEN-1)
1887 { // Error on excessive filename length
1888 printf("File name too long: %s (sorry!)\n",fname);
1892 strcpy(plast->o_name, path_tail(fname)); // Store filename, not path
1893 *plast->o_arname = 0; // No archive name for this file
1894 plast->o_image = ptr; // Store data pointer
1895 plast->o_flags = O_USED; // File is used
1896 plast->o_next = NULL; // Initialise next record pointer
1898 return 0; // Return without errors
1903 // Process in Binary Include Files and Add them to the Processing List. This
1904 // routine takes in the binary file and creates an 'object' file in memory.
1905 // Sym1/Sym2 point to the start and end of data.
1907 // Image size for include files is:
1908 // Header ....... 32 bytes
1909 // Data ......... dsize
1910 // Sym Fixups ... 2 * 12 bytes
1911 // Symbol Size .. 4 bytes (Value to include symbols and terminating null)
1912 // Symbols ...... (strlen(sym1) + 1) + (strlen(sym2) + 1)
1913 // Terminate .... 4 bytes (0x00000000)
1915 int doinclude(char * fname, int handle, char * sym1, char * sym2, int segment)
1917 long fsize, dsize, size; // File, DATA segment and image sizes
1918 char * ptr, * sptr; // Data pointers
1920 int sym1len = 0; // Symbol 1 length
1921 int sym2len = 0; // Symbol 2 length
1922 unsigned symtype = 0;
1924 fsize = FSIZE(handle); // Get size of include file
1925 dsize = (fsize+secalign) & ~secalign; // Round up to a alignment boundary
1927 sym1len = strlen(sym1) + 1; // Get sym1 length + null termination
1928 sym2len = strlen(sym2) + 1; // Get sym2 length + null termination
1930 size = 32 + dsize + 24 + 4 + sym1len + sym2len + 4;
1932 // Use calloc so the header & fixups initialize to zero
1933 // Allocate object image memory
1934 if ((ptr = calloc(size, 1L)) == NULL)
1936 printf("Out of memory while including %s\n", fname);
1941 // Read in binary data
1942 if (read(handle, ptr+32, fsize) != fsize)
1944 printf("File read error on %s\n", fname);
1950 close(handle); // Close file
1952 strcpy(obj_fname[obj_index], path_tail(fname));
1954 // Build this image's dummy header
1955 putlong(ptr, 0x00000107); // Magic number
1959 putlong(ptr+4, dsize); // Text size
1960 putlong(ptr+8, 0L); // Data size
1961 symtype = 0x05000000;
1962 obj_segsize[obj_index][0] = dsize;
1963 obj_segsize[obj_index][1] = 0;
1964 obj_segsize[obj_index][2] = 0;
1968 putlong(ptr+4, 0L); // Text size
1969 putlong(ptr+8, dsize); // Data size
1970 symtype = 0x07000000;
1971 obj_segsize[obj_index][0] = 0;
1972 obj_segsize[obj_index][1] = dsize;
1973 obj_segsize[obj_index][2] = 0;
1976 obj_index++; // Increment object count
1978 putlong(ptr+12, 0L); // BSS size
1979 putlong(ptr+16, 24); // Symbol table size
1980 putlong(ptr+20, 0L); // Entry point
1981 putlong(ptr+24, 0L); // TEXT relocation size
1982 putlong(ptr+28, 0L); // DATA relocation size
1984 sptr = ptr + 32 + dsize; // Set sptr to symbol table location
1986 putlong(sptr, 4L); // String offset of symbol1
1987 putlong(sptr+4, symtype); // Symbol type
1988 putlong(sptr+8, 0x00000000); // Symbol has no value (START)
1989 putlong(sptr+12, 4L + (sym2len-1)); // String offset of symbol2
1990 putlong(sptr+16, symtype); // Symbol type
1991 putlong(sptr+20, dsize); // Symbol is data size (END)
1993 sptr = ptr + 32 + dsize + 24; // Set sptr to symbol table size loc
1995 putlong(sptr, sym1len + 4L); // Size of symbol table
1997 sptr = ptr + 32 + dsize + 24 + 4; // Set sptr to symbol table location
1999 for(i=0; i<(sym1len-1); i++) // Write symbol1 to string table
2002 sptr += (sym1len-1); // Step past symbol string
2003 *sptr = '\0'; // Terminate symbol string
2004 sptr += 1; // Step past termination
2006 for(i=0; i<(sym2len-1); i++) // Write symbol2 to string table
2009 sptr += (sym2len-1); // Step past symbol string
2010 *sptr = '\0'; // Terminate symbol string
2011 sptr += 1; // Step past termination
2013 putlong(sptr, 0L); // Terminating long for object file
2015 return pladd(ptr, fname);
2020 // Takes a file name, gets in its image, puts it on plist. The image may
2021 // already be in memory: If so, the ptr arg is non-null. If so, the file is
2022 // already closed. Note that the file is already open (from dofile()). RETURNS
2023 // a pointer to the OFILE structure for this file, so you can diddle its flags
2024 // (dofile sets O_USED for files on the command line).
2026 int doobject(char * fname, int fd, char * ptr)
2028 long size; // File size
2032 size = FSIZE(fd); // Get size of input object file
2034 // Allocate memory for file data
2035 if ((ptr = malloc(size)) == NULL)
2037 printf("Out of memory while processing %s\n", fname);
2038 close(fd); // Close and error
2042 // Read in file data
2043 if (read(fd, ptr, size) != size)
2045 printf("File read error on %s\n", fname);
2046 close(fd); // Close, free memory and error
2051 strcpy(obj_fname[obj_index], path_tail(fname)); // SCPCD : get the name of the file instead of all pathname
2052 obj_segsize[obj_index][0] = (getlong(ptr + 4) + secalign) & ~secalign;
2053 obj_segsize[obj_index][1] = (getlong(ptr + 8) + secalign) & ~secalign;
2054 obj_segsize[obj_index][2] = (getlong(ptr + 12) + secalign) & ~secalign;
2057 close(fd); // Close file
2060 // Now add this image to the list of pending ofiles (plist)
2061 // This routine is shared by doinclude after it builds the image
2062 return pladd(ptr, fname);
2067 // Process In Outstanding Object Files
2069 int flush_handles(void)
2072 char magic[4]; // Magic header number
2075 for(i = 0; i < (int)hd; i++) { // Process all handles
2076 if (vflag == 1) { // Verbose mode information
2077 printf("Read file %s%s\n", name[i], hflag[i] ? " (include)" : "");
2079 if (!hflag[i]) { // Attempt to read file magic number
2081 if (read(handle[i],magic,4) != 4) {
2082 printf("Error reading file %s\n", name[i]);
2083 close(handle[i]); // Close file and error
2087 lseek(handle[i], 0L, 0); // Reset to start of input file
2088 // test = getlong(magic); printf("Magic Number is 0x%08X\n", test);
2089 if (getlong(magic) == 0x00000107) { // Look for SMAC/MAC object files
2090 if (doobject(name[i], handle[i], 0L)) // Process input object file
2093 printf("%s is not a supported object file\n", name[i]);
2094 close(handle[i]); // Close file and error
2099 // If hflag[i] is 1, include this in the data segment; if 2, put in in text segment
2100 if (doinclude(name[i], handle[i], hsym1[i], hsym2[i], hflag[i]-1))
2105 for(i = 0; i < (int)hd; i++) { // Free include, symbol & object handles
2113 hd = 0; // Reset next handle indicator
2119 // Load newargv with Pointers to Arguments Found in the Buffer ---------------------------------
2122 int parse(char *buf, char *newargv[]) {
2126 printf("begin parsing\n");
2129 while (*buf && strchr(",\t\n\r\14 ", *buf)) buf++;
2132 if (*buf == '\0' || *buf == 26) {
2134 printf("No commands in command file\n");
2141 /* test for comment */
2143 /* found a comment; skip to next \n and start over */
2144 while (*buf && *buf != '\n') buf++;
2149 printf("Too many arguments in command file\n");
2153 while (!strchr(",\t\n\r\14 ", *buf)) {
2154 if (*buf == '\0' || *buf == 26) {
2155 printf("Finished parsing %d args\n", i);
2162 printf("argv[%d] = \"%s\"\n",i,newargv[i]);
2169 // Process in a Link Command File -----------------------------------------
2172 int docmdfile(char * fname)
2174 int fd; // File descriptor
2175 unsigned size; // Command file size
2176 char * ptr; // Pointer
2177 int newargc; // New argument count
2178 char * (*newargv)[]; // New argument value array
2181 printf("docmdfile(%s)\n", fname); // Verbose information
2183 // Allocate memory for new argument values
2184 newargv = malloc((long)(sizeof(char *) * MAXARGS));
2188 printf("Out of memory.\n");
2192 // Attempt to open and read in the command file
2195 if ((fd = open(fname, _OPEN_FLAGS)) < 0)
2197 printf("Cannot open command file %s.\n", fname);
2203 if ((ptr = malloc(size + 1)) == NULL)
2205 printf("Out of memory.\n");
2210 if (read(fd, ptr, size) != (int)size)
2212 printf("Read error on command file %s.\n", fname);
2217 *(ptr + size) = 0; // Null terminate the buffer
2222 printf("No command filename specified\n");
2226 // Parse the command file
2227 if ((newargc = parse(ptr, *newargv)) == -1)
2232 // Process the inputted flags
2233 if (doargs(newargc, *newargv))
2235 printf("docmdfile: doargs returns TRUE\n");
2246 // Take an Argument List and Parse the Command Line -----------------------
2249 int doargs(int argc, char * argv[])
2251 int i = 1; // Iterator
2252 int c; // Command line character
2253 char * ifile, * isym; // File name and symbol name for -i
2256 { // Parse through option switches & files
2257 if (argv[i][0] == '-')
2258 { // Process command line switches
2261 printf("Illegal option argument: %s\n\n", argv[i]);
2266 c = argv[i++][1]; // Get next character in command line
2269 { // Process command line switch
2270 case '?': // Display usage information
2277 case 'A': // Set absolute linking on
2283 printf("Not enough arguments to -a\n");
2287 aflag = 1; // Set abs link flag
2288 // Segment order is TEXT, DATA, BSS
2289 // Text segment can be 'r', 'x' or a value
2292 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2294 ttype = -1; // TEXT segment is relocatable
2296 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2298 printf("Error in text-segment address: cannot be contiguous\n");
2301 else if ((ttype = 0), getval(argv[i], &tval))
2303 printf("Error in text-segment address: %s is not 'r', 'x' or an address.", argv[i]);
2308 // Data segment can be 'r', 'x' or a value
2311 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2313 dtype = -1; // DATA segment is relocatable
2315 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2317 dtype = -2; // DATA follows TEXT
2319 else if ((dtype = 0), getval(argv[i],&dval))
2321 printf("Error in data-segment address: %s is not 'r', 'x' or an address.", argv[i]);
2328 // BSS segment can be 'r', 'x' or a value
2329 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2331 btype = -1; // BSS segment is relocatable
2333 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2335 btype = -3; // BSS follows DATA
2337 else if ((btype = 0), getval(argv[i],&bval))
2339 printf("Error in bss-segment address: %s is not 'r', 'x[td]', or an address.", argv[i]);
2346 case 'B': // Don't remove muliply defined locals
2353 case 'C': // Process a command file
2356 printf("Not enough arguments to -c\n");
2360 if (docmdfile(argv[i++]))
2367 case 'D': // Wait for "return" before exiting
2375 case 'E': // Output COFF (absolute only)
2379 case 'G': // Output source level debugging
2380 printf("\'g\' flag not currently implemented\n");
2383 if (gflag) warn('g', 1);
2388 case 'I': // Include binary file
2391 printf("Not enough arguments to -i\n");
2398 if ((argv[i-3][2] == 'i') || (argv[i-3][2] == 'I'))
2399 { // handle -ii (No truncation)
2401 printf("warning: (-ii) COFF format output not specified\n");
2404 { // handle -i (Truncation)
2405 if (strlen(isym) > 7)
2409 // Place include files in the DATA segment only
2410 if (dofile(ifile, DSTSEG_D, isym))
2415 case 'L': // Add local symbols
2422 case 'M': // Produce load symbol map
2429 case 'N': // Output no header to .abs file
2436 case 'O': // Specify an output file
2444 printf("No output filename following -o switch\n");
2448 if (strlen(argv[i]) > FARGSIZE - 5)
2450 printf("Output file name too long (sorry!)\n");
2454 strcpy(ofile, argv[i++]);
2457 case 'R': // Section alignment size
2463 switch (argv[i-1][2])
2465 case 'w': case 'W': secalign = 1; break; // Word alignment
2466 case 'l': case 'L': secalign = 3; break; // Long alignment
2467 case 'p': case 'P': secalign = 7; break; // Phrase alignment
2468 case 'd': case 'D': secalign = 15; break; // Double phrase alignment
2469 case 'q': case 'Q': secalign = 31; break; // Quad phrase alignment
2470 default: secalign = 7; break; // Default phrase alignment
2475 case 'S': // Output only global symbols
2482 case 'V': // Verbose information
2483 if (!vflag && !versflag)
2491 case 'Z': // Suppress banner flag
2498 printf("unknown option argument `%c'\n", c);
2503 { // Not a switch, then process as a file
2504 if (dofile(argv[i++], 0, NULL))
2510 if (!oflag && vflag)
2512 strcpy(ofile, "output");
2513 printf("Output file is %s[.ext]\n", ofile);
2517 printf("Output file is %s\n", ofile);
2522 return 0; // No problems encountered
2527 // Display Version Information --------------------------------------------
2529 void display_version(void)
2531 if (displaybanner)// && vflag)
2533 printf("\nReboot's Linker for Atari Jaguar\n");
2534 printf("Copyright (c) 199x Allan K. Pratt, 2011 Reboot\n");
2535 printf("V%i.%i.%i %s (%s)\n\n", MAJOR, MINOR, PATCH, __DATE__, PLATFORM);
2541 // Display Command Line Help -----------------------------------------------
2543 void display_help(void)
2546 printf(" %s [-options] file(s)\n", cmdlnexec);
2548 printf("Options:\n");
2549 printf(" -? or -h display usage information\n");
2550 printf(" -a <text> <data> <bss> output absolute file\n");
2551 printf(" hex value: segment address\n");
2552 printf(" r: relocatable segment\n");
2553 printf(" x: contiguous segment\n");
2554 printf(" -b don't remove multiply defined local labels\n");
2555 printf(" -c <fname> add contents of <fname> to command line\n");
2556 printf(" -d wait for key after link\n");
2557 printf(" -e output COF absolute file\n");
2558 printf(" -g output source-level debugging\n");
2559 printf(" -i <fname> <label> incbin <fname> and set <label>\n");
2560 printf(" -l add local symbols\n");
2561 printf(" -m produce load symbols map\n");
2562 printf(" -n output no file header to .abs file\n");
2563 printf(" -o <fname> set output name\n");
2564 printf(" -r<size> section alignment size\n");
2565 printf(" w: word (2 bytes)\n");
2566 printf(" l: long (4 bytes)\n");
2567 printf(" p: phrase (8 bytes, default alignment)\n");
2568 printf(" d: double phrase (16 bytes)\n");
2569 printf(" q: quad phrase (32 bytes)\n");
2570 printf(" -s output only global symbols\n");
2571 printf(" -v set verbose mode\n");
2572 printf(" -z suppress banner\n");
2578 // Application Exit -------------------------------------------------------
2584 // Display link status if verbose mode
2586 printf("Link %s.\n", errflag ? "aborted" : "complete");
2588 // Wait for return key if requested
2591 printf("\nPress the <return> key to continue. ");
2592 fgets(tempbuf, 128, stdin);
2600 // Determine Processor Endianess ------------------------------------------
2602 int get_endianess(void)
2605 char * p = (char *)&i;
2615 // Application Code Starts Here -------------------------------------------
2617 int main(int argc, char * argv[])
2619 char * s = NULL; // String pointer for "getenv"
2620 struct HREC * utemp; // Temporary hash record pointer
2621 struct OHEADER * header; // Pointer to output header structure
2623 endian = get_endianess(); // Get processor endianess
2624 cmdlnexec = argv[0]; // Obtain executable name
2625 s = getenv("RLNPATH");
2627 if (s) // Attempt to obtain env variable
2628 strcpy(libdir, s); // Store it if found
2630 if (doargs(argc, argv))
2631 { // Parse the command line
2636 if (!zflag && !vflag)
2638 display_version(); // Display version information
2639 versflag = 1; // We've dumped the version banner
2642 if (flush_handles())
2643 { // Process in specified files/objects
2649 { // Remove elements from unresolved list
2655 { // Check that there is something to link
2656 // printf("No object files to link.\n\n");
2662 if (unresolved != NULL)
2663 { // Report unresolved externals
2664 printf("UNRESOLVED SYMBOLS\n");
2667 { // Don't list them if two -u's or more
2670 while (utemp != NULL)
2672 printf("\t%s (",utemp->h_sym);
2673 put_name(utemp->h_ofile);
2675 utemp = utemp->h_next;
2686 if ((header = make_ofile()) == NULL)
2687 { // Make one output file from input objs
2693 { // Partial linking
2694 printf("TO DO:Partial linking\n");
2698 { // Relocatable linking
2699 printf("TO DO:Relocatable linking\n");
2703 { // Absolute linking
2706 printf("Absolute linking ");
2715 printf("Header magic is 0x%04X\n", (unsigned int)header->magic);
2717 if (write_ofile(header))
2721 if (mflag) // Display the loaded symbols map
2722 if (write_map(header))
2726 { // Display segment size summary
2728 printf("+---------+----------+----------+----------+\n");
2729 printf("| Segment | TEXT | DATA | BSS |\n");
2730 printf("| Sizes |----------+----------+----------|\n");
2731 printf("| (Hex) | %8X | %8X | %8X |\n", (unsigned int)header->tsize, (unsigned int)header->dsize, (unsigned int)header->bsize);
2732 printf("+---------+----------+----------+----------+\n\n");
2735 free(header); // Free allocated memory
2736 rln_exit(); // Perform application exit