2 // RLN - Reboot's Linker for the Atari Jaguar Console System
3 // RLN.C - Application Code
4 // Copyright (C) 199x, Allan K. Pratt, 2014 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 wflag = 0; // Show warnings flag
24 unsigned zflag = 0; // Suppress banner flag
25 unsigned pflag, uflag; // Unimplemented flags
26 unsigned hd = 0; // Index of next file handle to fill
27 unsigned secalign = 7; // Section Alignment (8=phrase)
28 unsigned tbase = 0; // TEXT base address
29 unsigned dbase = 0; // DATA base address
30 unsigned bbase = 0; // BSS base address
31 unsigned textoffset = 0; // COF TEXT segment offset
32 unsigned dataoffset = 0; // COF DATA segment offset
33 unsigned bssoffset = 0; // COF BSS segment offset
34 unsigned displaybanner = 1; // Display version banner
35 unsigned symoffset = 0; // Symbol table offset in output file
36 unsigned dosymi = 0; // Dosym() processing iterator
37 unsigned dbgsymbase = 0; // Debug symbol base address
38 //unsigned symtrunc = 0; // Symbol truncation -i and -ii
39 int noheaderflag = 0; // No header flag for ABS files
40 int hflags; // Value of the arg to -h option
41 int ttype, dtype, btype; // Type flag: 0, -1, -2, -3, -4
42 int tval, dval, bval; // Values of these abs bases
43 int hflag[NHANDLES]; // True for include files
44 int handle[NHANDLES]; // Open file handles
45 int textsize, datasize, bsssize; // Cumulative segment sizes
46 char libdir[FARGSIZE * 3]; // Library directory to search
47 char ofile[FARGSIZE]; // Output file name (.o)
48 char * name[NHANDLES]; // Associated file names
49 char * cmdlnexec = NULL; // Executable name - pointer to ARGV[0]
50 char * hsym1[SYMLEN]; // First symbol for include files
51 char * hsym2[SYMLEN]; // Second symbol for include files
52 struct OFILE * plist = NULL; // Object image list pointer
53 struct OFILE * plast; // Last object image list pointer
54 struct OFILE * olist = NULL; // Pointer to first object file in list
55 struct OFILE * olast; // Pointer to last object file in list
56 char obj_fname[16384][FNLEN]; // Object file names
57 unsigned obj_segsize[16384][3]; // Object file seg sizes; TEXT,DATA,BSS
58 unsigned obj_index = 0; // Object file index/count
61 struct HREC * htable[NBUCKETS]; // Hash table
62 struct HREC * unresolved = NULL; // Pointer to unresolved hash list
63 char * ost; // Output symbol table
64 char * ost_ptr; // Output symbol table; current pointer
65 char * ost_end; // Output symbol table; end pointer
66 char * oststr; // Output string table
67 char * oststr_ptr; // Output string table; current pointer
68 char * oststr_end; // Output string table; end pointer
69 int ost_index = 0; // Index of next ost addition
70 int endian; // Processor endianess
71 uint8_t nullStr[1] = "\x00"; // Empty string
72 struct HREC * arSymbol = NULL; // Pointer to AR symbol table
74 // Some human readable defines for endianess
75 #define ENDIANNESS_BIG 1
76 #define ENDIANNESS_LITTLE 0
78 // Function prototypes
79 struct HREC * LookupHREC(char *);
80 char * path_tail(char *);
81 void display_help(void);
82 void display_version(void);
86 // Get a long word from memory
88 uint32_t getlong(uint8_t * src)
91 uint8_t * out = (uint8_t *)&temp;
93 if (endian == ENDIANNESS_BIG)
113 // Put a long word into memory
115 void putlong(uint8_t * dest, uint32_t val)
117 *dest++ = (uint8_t)(val >> 24);
118 *dest++ = (uint8_t)(val >> 16);
119 *dest++ = (uint8_t)(val >> 8);
120 *dest = (uint8_t)val;
125 // Get a word from memory
127 uint16_t getword(uint8_t * src)
130 uint8_t * out = (uint8_t *)&temp;
132 if (endian == ENDIANNESS_BIG)
148 // Put a word into memory
150 void putword(uint8_t * dest, uint16_t val)
152 *dest++ = (uint8_t)(val >> 8);
153 *dest = (uint8_t)val;
158 // Find passed in file's length in bytes
159 // N.B.: This also resets the file's pointer to the start of the file
161 long FileSize(int fd)
163 long size = lseek(fd, 0, SEEK_END);
164 lseek(fd, 0, SEEK_SET);
171 // For this object file, add symbols to the output symbol table after
172 // relocating them. Returns TRUE if OSTLookup returns an error (-1).
174 int DoSymbol(struct OFILE * ofile)
176 int type; // Symbol type
177 long value; // Symbol value
178 int index; // Symbol index
180 struct HREC * hptr; // Hash table pointer for globl/extrn
181 char sym[SYMLEN]; // String for symbol name/hash search
183 // Point to first symbol record in the object file
184 char * symptr = (ofile->o_image + 32
185 + ofile->o_header.tsize
186 + ofile->o_header.dsize
187 + ofile->o_header.absrel.reloc.tsize
188 + ofile->o_header.absrel.reloc.dsize);
190 // Point to end of symbol record in the object file
191 char * symend = symptr + ofile->o_header.ssize;
193 // Search through object segment size table to accumulated segment sizes to
194 // ensure the correct offsets are used in the resulting COF file.
196 unsigned tsegoffset = 0, dsegoffset = 0, bsegoffset = 0;
198 // Search for object file name
199 for(j=0; j<(int)obj_index; j++)
201 if (!strcmp(ofile->o_name, obj_fname[j]))
203 // Object file name found
208 // Accumulate segment sizes
209 tsegoffset += obj_segsize[j][0];
210 dsegoffset += obj_segsize[j][1];
211 bsegoffset += obj_segsize[j][2];
216 printf("DoSymbol(): Cannot get object file segment size: %s\n", ofile->o_name);
220 // Process each record in the symbol table
221 for(; symptr!=symend; symptr+=12)
223 index = getlong(symptr + 0); // Obtain symbol string index
224 type = getlong(symptr + 4); // Obtain symbol type
225 value = getlong(symptr + 8); // Obtain symbol value
227 // Global/External symbols have a pre-processing stage
228 if (type & 0x01000000)
230 // Obtain the string table index for the relocation symbol, look
231 // for it in the globals hash table to obtain information on that
234 memset(sym, 0, SYMLEN);
235 strcpy(sym, symend + index);
236 hptr = LookupHREC(sym);
238 hptr = LookupHREC(symend + index);
243 printf("DoSymbol() : Cannot determine symbol : %s\n", sym);
247 // Search through object segment size table to obtain segment sizes
248 // for the object that has the required external/global as a local
249 // symbol. As each object is interrogated the segment sizes are
250 // accumulated to ensure the correct offsets are used in the
251 // resulting COF file. This is effectively 'done again' only as we
252 // are working with a different object file.
254 tsegoffset = dsegoffset = bsegoffset = 0;
256 // Search for object filename
257 for(j=0; j<(int)obj_index; j++)
259 if (!strcmp(hptr->h_ofile->o_name, obj_fname[j]))
261 ssidx = j; // Symbol object filename
265 // Accumulate segment sizes
266 tsegoffset += obj_segsize[j][0];
267 dsegoffset += obj_segsize[j][1];
268 bsegoffset += obj_segsize[j][2];
273 printf("DoSymbol() : Cannot get object file segment size : %s\n", ofile->o_name);
277 // Update type with global type
280 // Remove external flag if absolute
281 if (type == (T_EXT | T_ABS))
284 // If the global/external has a value then update that value in
285 // accordance with the segment sizes of the object file it
289 switch (hptr->h_type & 0x0E000000)
293 value = hptr->h_value;
296 value = hptr->h_value - hptr->h_ofile->o_header.tsize;
299 value = hptr->h_value
300 - (hptr->h_ofile->o_header.tsize
301 + hptr->h_ofile->o_header.dsize);
307 // Process and update the value dependent on whether the symbol is a
308 // debug symbol or not
309 // N.B.: These are currently not supported
310 if (type & 0xF0000000)
313 // Set the correct debug symbol base address (TEXT segment)
316 for(j=0; (unsigned)j<dosymi; j++)
317 dbgsymbase += obj_segsize[j][0];
319 switch (type & 0xFF000000)
322 value = tval + dbgsymbase;
327 value = tval + dbgsymbase + value;
332 putlong(symptr + 8, value);
337 // Now make modifications to the symbol value, local or global,
338 // based on the segment sizes of the object file currently being
340 switch (type & T_SEG)
345 value = tbase + tsegoffset + value;
346 putlong(symptr + 8, value);
350 value = dbase + dsegoffset + value;
352 value = dbase + dsegoffset + (value
353 - ofile->o_header.tsize);
355 putlong(symptr + 8, value);
359 value = bbase + bsegoffset + value;
361 value = bbase + bsegoffset
362 + (value - (ofile->o_header.tsize
363 + ofile->o_header.dsize));
365 putlong(symptr + 8, value);
372 // Add to output symbol table if global/extern, or local flag is set
373 if (lflag || !islocal(type))
375 index = OSTAdd(symend + index, type, value);
382 // Increment dosymi processsing
390 // Free up hash memory
392 void FreeHashes(void)
396 for(i=0; i<NBUCKETS; i++)
398 struct HREC * hptr = htable[i];
402 struct HREC * htemp = hptr->h_next;
411 // Add all global and external symbols to the output symbol table
412 // [This is confusing--is it adding globals or locals? common == local!
413 // but then again, we see this in the header:
414 // #define T_COMMON (T_GLOBAL | T_EXTERN) but that could be just bullshit.]
421 for(i=0; i<NBUCKETS; i++)
423 for(hptr=htable[i]; hptr!=NULL; hptr=hptr->h_next)
425 //NO! if (iscommon(hptr->h_type))
426 if (isglobal(hptr->h_type))// || isextern(hptr->h_type))
428 // Skip if in *.a file... (does nothing)
429 //if (hptr->h_ofile->isArchiveFile)
432 if (hptr->h_type == (T_EXT | T_ABS))
433 hptr->h_type = T_ABS; // Absolutes *can't* be externals
435 if (OSTAdd(hptr->h_sym, hptr->h_type, hptr->h_value) == -1)
446 // Add a Symbol's Name, Type, and Value to the OST.
447 // Return the Index of the Symbol in OST, or -1 for Error.
449 int OSTAdd(char * name, int type, long value)
451 int ost_offset_p, ost_offset_e = 0; // OST table offsets for position calcs
452 int slen = 0; // Symbol string length
453 int ostresult; // OST index result
457 // If the OST or OST String Table has not been initialised then do so
460 if ((ost = malloc(OST_BLOCK)) == NULL)
462 printf("OST memory allocation error (stringtable).\n");
466 ost_ptr = ost; // Set OST start pointer
467 ost_end = ost + OST_BLOCK; // Set OST end pointer
469 if ((oststr = malloc(OST_BLOCK)) == NULL)
471 printf("OST memory allocation error (string).\n");
475 putlong(oststr, 0x00000004); // Just null long for now
476 oststr_ptr = oststr + 4; // Skip size of str table long (incl null long)
477 putlong(oststr_ptr, 0x00000000); // Null terminating long
478 oststr_end = oststr + OST_BLOCK;
482 // If next symbol record exceeds current allocation then expand symbol
484 ost_offset_p = (ost_ptr - ost);
485 ost_offset_e = (ost_end - ost);
488 if ((ost_ptr + 12) > ost_end)
490 #warning "!!! Bad logic in realloc call !!!"
491 if ((ost = realloc(ost, (ost_end + OST_BLOCK))) == NULL)
493 printf("OST memory reallocation error.\n");
497 ost_ptr = ost + ost_offset_p;
498 ost_end = (ost + ost_offset_e) + OST_BLOCK;
501 ost_offset_p = (oststr_ptr - oststr);
502 ost_offset_e = (oststr_end - oststr);
504 if ((oststr_ptr + (slen + 1 + 4)) > oststr_end)
506 #warning "!!! Bad logic in realloc call !!!"
507 if ((oststr = realloc(oststr, (oststr_end + OST_BLOCK))) == NULL)
509 printf("OSTSTR memory reallocation error.\n");
513 oststr_ptr = oststr + ost_offset_p;
514 oststr_end = (oststr + ost_offset_e) + OST_BLOCK;
518 // If this is a debug symbol and the include debug symbol flag (-g) is not
519 // set then do nothing
520 if ((type & 0xF0000000) && !gflag)
526 ostresult = OSTLookup(name); // Get symbol index in OST
528 // If the symbol is in the output symbol table and the bflag is set
529 // (don't remove multiply defined locals) and this is not an
530 // external/global symbol *** OR *** the symbol is not in the output
531 // symbol table then add it.
532 if (((ostresult != -1) && bflag && !(type & 0x01000000))
533 || ((ostresult != -1) && gflag && (type & 0xF0000000)) || (ostresult == -1))
535 if ((type & 0xF0000000) == 0x40000000)
536 putlong(ost_ptr, 0x00000000); // Zero string table offset for dbg line
538 putlong(ost_ptr, (oststr_ptr - oststr)); // String table offset of symbol string
540 putlong(ost_ptr + 4, type );
541 putlong(ost_ptr + 8, value);
544 // If the symbol type is anything but a debug line information
545 // symbol then write the symbol string to the string table
546 if ((type & 0xF0000000) != 0x40000000)
548 strcpy(oststr_ptr, name); // Put symbol name in string table
549 *(oststr_ptr + slen) = '\0'; // Add null terminating character
550 oststr_ptr += (slen + 1);
551 putlong(oststr_ptr, 0x00000000); // Null terminating long
552 putlong(oststr, (oststr_ptr - oststr)); // Update size of string table
557 printf("OSTAdd: (%s), type=$%08X, val=$%08X\n", name, type, value);
564 // Not sure about this as it could affect return indices. Needed to stop
571 // Return the index of a symbol in the output symbol table
573 int OSTLookup(char * sym)
576 int stro = 4; // Offset in string table
578 for(i=0; i<ost_index; i++)
580 if (strcmp(oststr + stro, sym) == 0)
583 stro += strlen(oststr + stro) + 1;
591 // Add unresolved externs to the output symbol table
593 int DoUnresolved(void)
595 struct HREC * hptr = unresolved;
597 // Add to OST while unresolved list is valid
600 if (OSTAdd(hptr->h_sym, T_EXT, 0L) == -1)
604 printf("DoUnresolved(): added %s\n", hptr->h_sym);
606 struct HREC * htemp = hptr->h_next;
617 // Update object file TEXT and DATA segments based on relocation records. Take
618 // in an OFILE header and flag (T_TEXT, T_DATA) to process. Return (0) is
619 // successful or non-zero (1) if failed.
621 int RelocateSegment(struct OFILE * ofile, int flag)
623 char * symtab; // Start of symbol table
624 char * symbols; // Start of symbols
625 char * sptr; // Start of segment data
626 char * rptr; // Start of segment relocation records
627 unsigned symidx; // Offset to symbol
628 unsigned addr; // Relocation address
629 unsigned rflg; // Relocation flags
630 unsigned olddata; // Old segment data at reloc address
631 unsigned newdata = 0; // New segment data at reloc address
632 unsigned pad; // Temporary to calculate phrase padding
634 char sym[SYMLEN]; // String for symbol name/hash search
635 int ssidx; // Segment size table index
636 unsigned glblreloc; // Global relocation flag
637 unsigned absreloc; // Absolute relocation flag
638 unsigned relreloc; // Relative relocation flag
639 unsigned swcond; // Switch statement condition
640 unsigned relocsize; // Relocation record size
642 // If there is no TEXT relocation data for the selected object file segment
643 // then update the COF TEXT segment offset allowing for the phrase padding
644 if ((flag == T_TEXT) && !ofile->o_header.absrel.reloc.tsize)
646 // TEXT segment size plus padding
647 pad = ((ofile->o_header.tsize + secalign) & ~secalign);
648 textoffset += (ofile->o_header.tsize + (pad - ofile->o_header.tsize));
651 printf("RelocateSegment(%s, TEXT) : No Relocation Data\n", ofile->o_name);
656 // If there is no DATA relocation data for the selected object file segment
657 // then update the COF DATA and BSS segment offsets allowing for the phrase
659 if ((flag == T_DATA) && !ofile->o_header.absrel.reloc.dsize)
661 // DATA segment size plus padding
662 pad = ((ofile->o_header.dsize + secalign) & ~secalign);
663 dataoffset += (ofile->o_header.dsize + (pad - ofile->o_header.dsize));
664 // BSS segment size plus padding
665 pad = ((ofile->o_header.bsize + secalign) & ~secalign);
666 bssoffset += (ofile->o_header.bsize + (pad - ofile->o_header.bsize));
669 printf("RelocateSegment(%s, DATA) : No Relocation Data\n", ofile->o_name);
674 // Verbose mode information
677 printf("RelocateSegment(%s, %s) : Processing Relocation Data\n",
678 ofile->o_name, flag == T_DATA ? "DATA" : "TEXT");
681 // Obtain pointer to start of symbol table
682 symtab = (ofile->o_image + 32 + ofile->o_header.tsize
683 + ofile->o_header.dsize
684 + ofile->o_header.absrel.reloc.tsize
685 + ofile->o_header.absrel.reloc.dsize);
687 // Obtain pointer to start of symbols
688 symbols = symtab + ofile->o_header.ssize;
690 // Obtain pointer to start of TEXT segment
691 sptr = ofile->o_image + 32;
693 // Obtain pointer to start of TEXT relocation records
694 rptr = sptr + (ofile->o_header.tsize + ofile->o_header.dsize);
696 relocsize = ofile->o_header.absrel.reloc.tsize;
699 printf("RELOCSIZE :: %d Records = %d\n", relocsize, relocsize / 8);
701 // Update pointers if DATA relocation records are being processed
704 sptr += ofile->o_header.tsize; // Start of DATA segment
705 rptr += ofile->o_header.absrel.reloc.tsize; // Start of DATA relocation records
706 relocsize = ofile->o_header.absrel.reloc.dsize;
709 // Process each relocation record for the TEXT segment
710 for(i=0; i<(int)relocsize; i+=8)
712 // Obtain both the relocation address and the relocation flags from the
714 addr = getlong(rptr);
715 rflg = getlong(rptr + 4);
716 glblreloc = (rflg & 0x00000010 ? 1 : 0);// Set global relocation flag
717 absreloc = (rflg & 0x00000040 ? 1 : 0); // Set absolute relocation flag
718 relreloc = (rflg & 0x000000A0 ? 1 : 0); // Set relative relocation flag
720 // Additional processing required for global relocations
723 // Obtain the string table index for the relocation symbol, look
724 // for it in the globals hash table to obtain information on that
725 // symbol. For the hash calculation to work correctly it must be
726 // placed in a 'clean' string before looking it up.
727 symidx = getlong(symtab + ((rflg >> 8) * 12));
728 memset(sym, 0, SYMLEN);
729 strcpy(sym, symbols + symidx);
730 olddata = newdata = 0; // Initialise old and new segment data
731 ssidx = OSTLookup(sym);
732 newdata = getlong(ost + ((ssidx - 1) * 12) + 8);
735 // Obtain the existing long word segment data and flip words if the
736 // relocation flags indicate it relates to a RISC MOVEI instruction
737 olddata = getlong(sptr + addr);
740 olddata = _SWAPWORD(olddata);
742 // Process record dependant on segment it relates to; TEXT, DATA or
743 // BSS. Construct a new relocated segment long word based on the
744 // required segment base address, the segment data offset in the
745 // resulting COF file and the offsets from the incoming object file.
746 swcond = (rflg & 0xFFFFFF00);
752 case 0x00000200: // Absolute Value
754 case 0x00000400: // TEXT segment relocation record
755 if (flag == T_TEXT) // Is this a TEXT section record?
756 newdata = tbase + textoffset + olddata;
758 newdata = tbase + dataoffset + olddata; // Nope, must be DATA section
761 case 0x00000600: // DATA segment relocation record
762 newdata = dbase + dataoffset
763 + (olddata - ofile->o_header.tsize);
766 case 0x00000800: // BSS segment relocation record
767 newdata = bbase + bssoffset
768 + (olddata - (ofile->o_header.tsize
769 + ofile->o_header.dsize));
780 // Set absolute (long) or relative (word) address of symbol
783 // Flip the new long word segment data if the relocation record
784 // indicated a RISC MOVEI instruction and place the resulting data
785 // back in the COF segment
787 newdata = _SWAPWORD(newdata);
789 putlong(sptr + addr, newdata);
793 putword(sptr + addr, newdata - tbase - addr - ofile->o_tbase);
796 // Shamus: Let's output some info to aid in debugging this crap
803 sprintf(ssiString, " [ssi:%i]", ssidx);
805 printf("RelocateSegment($%08X): %s, $%08X: $%08X => $%08X%s\n", rflg, (glblreloc ? sym : "(LOCAL)"), addr, olddata, getlong(sptr + addr), ssiString);
808 rptr += 8; // Point to the next relocation record
811 // Update the COF segment offset allowing for the phrase padding.
814 // TEXT segment plus padding
815 pad = ((ofile->o_header.tsize + secalign) & ~secalign);
816 textoffset += (ofile->o_header.tsize + (pad - ofile->o_header.tsize));
820 // DATA segment plus padding
821 pad = ((ofile->o_header.dsize + secalign) & ~secalign);
822 dataoffset += (ofile->o_header.dsize + (pad - ofile->o_header.dsize));
823 // BSS segment plus padding
824 pad = ((ofile->o_header.bsize + secalign) & ~secalign);
825 bssoffset += (ofile->o_header.bsize + (pad - ofile->o_header.bsize));
828 // Return value, should always be zero
834 // Add a path character to the end of string 's' if it doesn't already end with
835 // one. The last occurrance of '/' or '\' in the string is assumed to be the
838 // This is fucking shit. We know what the path delimiter is, its FUCKING
839 // DEFINED IN THE FUCKING HEADER. FOR FUCKS SAKE. AND YES, HOPE TO GOD THERE'S
840 // ENOUGH SPACE IN THE PASSED IN BUFFER TO HOLD THE EXTRA CHARACTER!
842 void AppendPathDelimiter(char * s)
845 // And hope to God that there's enough space in the buffer...
850 if (*s == '/' || *s == '\\')
864 int length = strlen(s);
866 if (s[length - 1] != PATH_DELIMITER)
868 s[length] = PATH_DELIMITER;
869 s[length + 1] = 0; // BUFFER OVERFLOW!!!! FFFFFFFFUUUUUUUUUUUU
876 // Try to open "name", "name.o", "${libdir}name", "${libdir}name.o". Return the
877 // handle of the file successfully opened. p_name is updated to point to a
878 // malloc()'ed string which is the name which actually got opened. p_name will
879 // return unchanged if the file can't be found.
881 int TryOpenFile(char ** p_name)
883 char * name = *p_name;
885 // Note that libdir will be an empty string if there is none specified
886 char * tmpbuf = malloc(strlen(name) + strlen(libdir) + 3);
890 printf("TryOpenFile() : out of memory\n");
894 strcpy(tmpbuf, name);
895 int hasdot = (strrchr(tmpbuf, '.') > strrchr(tmpbuf, PATH_DELIMITER));
896 // Try to open file as passed first
897 int fd = open(tmpbuf, _OPEN_FLAGS);
904 // Try to open file with '.o' added
905 strcat(tmpbuf, ".o");
906 fd = open(tmpbuf, _OPEN_FLAGS);
912 // Try the libdir only if the name isn't already anchored
913 // Shamus: WTH, this makes no sense... Why the ':'? Is this a Macintosh??
914 // if (*name != '/' && *name != '\\' && !strchr(name, ':'))
915 if ((*name != PATH_DELIMITER) && (strchr(name, ':') == NULL))
917 strcpy(tmpbuf, libdir);
918 // Add a trailing path char if there isn't one already
919 AppendPathDelimiter(tmpbuf);
920 strcat(tmpbuf, name);
922 if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0)
927 strcat(tmpbuf, ".o");
929 if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0)
934 // Couldn't open file at all
937 // There are worse things... :-P
939 tmpbuf = realloc(tmpbuf, strlen(tmpbuf) + 1);
943 printf("TryOpenFile() : out of memory\n");
953 // Archive File Use, Needs to be Removed [Shamus: NON!]
955 void put_name(struct OFILE * p)
957 int flag = *(p->o_arname);
958 printf("%s%s%s", (flag ? (char *)(p->o_arname) : ""), (flag ? ":" : ""), p->o_name);
963 // Collect file names and handles in a buffer so there is less disk activity.
964 // Call DoFile with flag FALSE for normal object files and archives.
965 // Call it with flag TRUE and a symbol name for include files (-i).
967 int DoFile(char * fname, int incFlag, char * sym)
969 // Verbose information
972 printf("DoFile() : `%s' %s", fname, incFlag ? "INCLUDE" : "NORMAL");
975 printf(" symbol %s", sym);
980 // Reached maximum file handles
987 // Attempt to open input file
988 int fd = TryOpenFile(&fname);
992 printf("Cannot find input module %s\n", fname);
996 // The file is open; save its info in the handle and name arrays
998 name[hd] = fname; // This is the name from TryOpenFile()
1004 int temp = strlen(sym); // Get symbol length
1006 // 100 chars is max length of a symbol
1013 // Malloc enough space for two symbols, then build the second one.
1014 // Second one may be one character longer than first
1015 if ((hsym1[hd] = malloc((long)temp + 1)) == NULL
1016 || (hsym2[hd] = malloc((long)temp + 2)) == NULL)
1018 printf("DoFile() : out of memory for include-file symbols\n");
1022 strcpy(hsym1[hd], sym);
1023 strcpy(hsym2[hd], sym);
1029 printf("Last char of %s is already 'x': choose another name\n", sym);
1033 hsym2[hd][99] = 'x';
1037 hsym2[hd][temp] = 'x';
1038 hsym2[hd][temp+1] = '\0';
1042 // Increment next handle index
1050 // Pad TEXT or DATA segment to the requested boundary
1052 int segmentpad(FILE * fd, long segsize, int value)
1054 // long padsize; // Number of pad bytes needed
1055 int i; // Good 'ol iterator
1056 char padarray[32]; // Array of padding bytes
1057 char * padptr; // Pointer to array
1059 // Determine the number of padding bytes that are needed
1060 long padsize = (segsize + secalign) & ~secalign;
1061 padsize = padsize - segsize;
1063 // Fill pad array if padding is required
1070 putword(padptr, value);
1074 symoffset += padsize;
1076 // Write padding bytes
1077 if (fwrite(padarray, padsize, 1, fd) != 1)
1086 // Write the output file
1088 int write_ofile(struct OHEADER * header)
1090 unsigned osize; // Object segment size
1091 struct OFILE * otemp; // Object file pointer
1092 int i, j; // Iterators
1093 char himage[0x168]; // Header image (COF = 0xA8)
1094 unsigned tsoff, dsoff, bsoff; // Segment offset values
1095 unsigned index, type, value; // Symbol table index, type and value
1096 short abstype; // ABS symbol type
1097 char symbol[14]; // Symbol record for ABS files
1098 int slen; // Symbol string length
1100 symoffset = 0; // Initialise symbol offset
1102 // Add correct output extension if none
1103 if (strchr(ofile, '.') == NULL)
1106 strcat(ofile, ".cof"); // COF files
1107 else if (aflag && !cflag)
1108 strcat(ofile, ".abs"); // ABS files
1110 strcat(ofile, ".o"); // Object files (partial linking etc)
1113 FILE * fd = fopen(ofile, "wb"); // Attempt to open output file
1117 printf("Can't open output file %s\n", ofile);
1121 // Build the output file header
1122 // Absolute (COF) header
1125 tsoff = dsoff = bsoff = 0xA8; // Initialises segment offsets
1127 // Process each object file segment size to obtain a cumulative segment
1128 // size for both the TEXT and DATA segments
1129 for(i=0; i<(int)obj_index; i++)
1131 dsoff += obj_segsize[i][0]; // Adding TEXT segment sizes
1132 bsoff += obj_segsize[i][0] + obj_segsize[i][1]; // Adding TEXT and DATA segment sizes
1135 // Currently this only builds a COF absolute file. Conditionals and
1136 // additional code will need to be added for ABS and partial linking.
1138 // Build the COF_HDR
1139 putword(himage + 0, 0x0150 ); // Magic Number (0x0150)
1140 putword(himage + 2, 0x0003 ); // Sections Number (3)
1141 putlong(himage + 4, 0x00000000 ); // Date (0L)
1142 putlong(himage + 8, dsoff + header->dsize); // Offset to Symbols Section
1143 putlong(himage + 12, ost_index); // Number of Symbols
1144 putword(himage + 16, 0x001C ); // Size of RUN_HDR (0x1C)
1145 putword(himage + 18, 0x0003 ); // Executable Flags (3)
1147 // Build the RUN_HDR
1148 putlong(himage + 20, 0x00000107 ); // Magic/vstamp
1149 putlong(himage + 24, header->tsize ); // TEXT size in bytes
1150 putlong(himage + 28, header->dsize ); // DATA size in bytes
1151 putlong(himage + 32, header->bsize ); // BSS size in bytes
1152 putlong(himage + 36, tbase ); // Start of executable, normally @TEXT
1153 putlong(himage + 40, tbase ); // @TEXT
1154 putlong(himage + 44, dbase ); // @DATA
1156 // Build the TEXT SEC_HDR
1157 putlong(himage + 48, 0x2E746578 );
1158 putlong(himage + 52, 0x74000000 ); // ".text"
1159 putlong(himage + 56, tbase ); // TEXT START
1160 putlong(himage + 60, tbase ); // TEXT START
1161 putlong(himage + 64, header->tsize ); // TEXT size in bytes
1162 putlong(himage + 68, tsoff ); // Offset to section data in file
1163 putlong(himage + 72, 0x00000000 ); // Offset to section reloc in file (0L)
1164 putlong(himage + 76, 0x00000000 ); // Offset to debug lines structures (0L)
1165 putlong(himage + 80, 0x00000000 ); // Nreloc/nlnno (0L)
1166 putlong(himage + 84, 0x00000020 ); // SEC_FLAGS: STYP_TEXT
1168 // Build the DATA SEC_HDR
1169 putlong(himage + 88, 0x2E646174 );
1170 putlong(himage + 92, 0x61000000 ); // ".data"
1171 putlong(himage + 96, dbase ); // DATA START
1172 putlong(himage + 100, dbase ); // DATA START
1173 putlong(himage + 104, header->dsize ); // DATA size in bytes
1174 putlong(himage + 108, dsoff ); // Offset to section data in file
1175 putlong(himage + 112, 0x00000000 ); // Offset to section reloc in file (0L)
1176 putlong(himage + 116, 0x00000000 ); // Offset to debugging lines structures (0L)
1177 putlong(himage + 120, 0x00000000 ); // Nreloc/nlnno (0L)
1178 putlong(himage + 124, 0x00000040 ); // SEC_FLAGS: STYP_DATA
1180 // Build the BSS SEC_HDR
1181 putlong(himage + 128, 0x2E627373 );
1182 putlong(himage + 132, 0x00000000 ); // ".bss"
1183 putlong(himage + 136, bbase ); // BSS START
1184 putlong(himage + 140, bbase ); // BSS START
1185 putlong(himage + 144, header->bsize ); // BSS size in bytes
1186 putlong(himage + 148, bsoff ); // Offset to section data in file
1187 putlong(himage + 152, 0x00000000 ); // Offset to section reloc in file (0L)
1188 putlong(himage + 156, 0x00000000 ); // Offset to debugging lines structures (0L)
1189 putlong(himage + 160, 0x00000000 ); // Nreloc/nlnno (0L)
1190 putlong(himage + 164, 0x00000080 ); // SEC_FLAGS: STYP_BSS
1192 symoffset = 168; // Update symbol offset
1194 // Absolute (ABS) header
1197 // Build the ABS header
1198 putword(himage + 0, 0x601B ); // Magic Number (0x601B)
1199 putlong(himage + 2, header->tsize ); // TEXT segment size
1200 putlong(himage + 6, header->dsize ); // DATA segment size
1201 putlong(himage + 10, header->bsize ); // BSS segment size
1202 putlong(himage + 14, ost_index * 14 ); // Symbol table size (?)
1203 putlong(himage + 18, 0x00000000 ); //
1204 putlong(himage + 22, tbase ); // TEXT base address
1205 putword(himage + 26, 0xFFFF ); // Flags (?)
1206 putlong(himage + 28, dbase ); // DATA base address
1207 putlong(himage + 32, bbase ); // BSS base address
1209 symoffset = 36; // Update symbol offset
1212 // Write the header, but not if noheaderflag
1213 // Absolute (ABS) header
1217 if (fwrite(himage, 36, 1, fd) != 1)
1220 // Absolute (COF) header
1223 if (fwrite(himage, 168, 1, fd) != 1)
1227 // Write the TEXT segment of each object file
1228 for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1230 osize = otemp->o_header.tsize;
1232 // Write only if segment has size
1236 printf("Writing TEXT Segment of %s\n", otemp->o_name);
1238 if (fwrite(otemp->o_image + 32, osize, 1, fd) != 1)
1241 // Pad to required alignment boundary
1242 if (segmentpad(fd, osize, 0x0000))
1249 // Write the DATA segment of each object file
1250 for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1252 osize = otemp->o_header.dsize;
1254 // Write only if the segment has size
1258 printf("Writing DATA Segment of %s\n", otemp->o_name);
1260 if (fwrite((otemp->o_image + 32 + otemp->o_header.tsize), osize, 1, fd) != 1)
1263 // Pad to required alignment boundary
1264 if (segmentpad(fd, osize, 0))
1273 // Write the symbols table and string table
1274 // Absolute (COF) symbol/string table
1279 if (fwrite(ost, (ost_ptr - ost), 1, fd) != 1)
1282 if (fwrite(oststr, (oststr_ptr - oststr), 1, fd) != 1)
1286 // Absolute (ABS) symbol/string table
1289 // The symbol and string table have been created as part of the
1290 // DoSymbol() function and the output symbol and string tables are
1291 // in COF format. For an ABS file we need to process through this
1292 // to create the 14 character long combined symbol and string
1293 // table. Format of symbol table in ABS: AAAAAAAATTVVVV, where
1294 // (A)=STRING, (T)=TYPE & (V)=VALUE
1296 for(i=0; i<ost_index; i++)
1298 memset(symbol, 0, 14); // Initialise symbol record
1299 abstype = 0; // Initialise ABS symbol type
1300 slen = 0; // Initialise symbol string length
1301 index = getlong(ost + (i * 12)); // Get symbol index
1302 type = getlong((ost + (i * 12)) + 4); // Get symbol type
1304 // Not doing debug symbols
1305 if (type & 0xF0000000)
1309 value = getlong((ost + (i * 12)) + 8);
1310 slen = strlen(oststr + index);
1312 // Get symbol string (maximum 8 chars)
1316 *(symbol + j) = *(oststr + index + j);
1320 for(j=0; j<slen; j++)
1321 *(symbol + j) = *(oststr + index + j);
1324 // Modify to ABS symbol type
1327 case 0x02000000: abstype = (short)ABST_DEFINED; break;
1328 case 0x04000000: abstype = (short)ABST_DEFINED | ABST_TEXT; break;
1329 case 0x05000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_TEXT; break;
1330 case 0x06000000: abstype = (short)ABST_DEFINED | ABST_DATA; break;
1331 case 0x07000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_DATA; break;
1332 case 0x08000000: abstype = (short)ABST_DEFINED | ABST_BSS; break;
1333 case 0x09000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_BSS; break;
1335 printf("write_ofile: abs, cannot determine symbol type\n");
1340 putword(symbol + 8, abstype); // Write back new ABS type
1341 putlong(symbol + 10, value); // Write back value
1343 // Write symbol record
1344 if (fwrite(symbol, 14, 1, fd) != 1)
1353 printf("Close error on output file %s\n",ofile);
1360 printf("Write error on output file %s\n", ofile);
1361 fclose(fd); // Try to close output file anyway
1367 // Display the Symbol Load Map
1369 int write_map(struct OHEADER * header)
1371 unsigned i, o; // Inner and outer loop iterators
1372 unsigned c; // Column number
1373 unsigned index; // Symbol string index
1374 unsigned type; // Symbol type
1375 unsigned value; // Symbol value
1376 char * symbol; // Symbol string value
1379 return 0; // Return if no symbols to map
1381 printf("LOAD MAP\n\n");
1383 // Outer loop for each of the symbol areas to map out;
1384 // 0 = NON-RELOCATABLE SYMBOLS
1385 // 1 = TEXT-SEGMENT RELOCATABLE SYMBOLS
1386 // 2 = DATA-SEGMENT RELOCATABLE SYMBOLS
1387 // 3 = BSS-SEGMENT RELOCATABLE SYMBOLS
1390 // Display the correct map header for the symbols being processed
1393 case 0: printf("NON-RELOCATABLE SYMBOLS\n\n"); break;
1394 case 1: printf("TEXT-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1395 case 2: printf("DATA-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1396 case 3: printf("BSS-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1399 c = 0; // Initialise column number
1401 // Inner loop to process each record in the symbol table
1402 for(i=0; i<(unsigned)ost_index; i++)
1404 index = getlong(ost + (i * 12)); // Get symbol string index
1405 type = getlong(ost + (i * 12) + 4); // Get symbol type
1406 value = getlong(ost + (i * 12) + 8); // Get symbol value
1407 symbol = oststr + index; // Get symbol string
1409 // Display only three columns
1416 // If local symbols not included and the type is local then go to
1417 // next symbol record
1418 if (!lflag & !(type & 0x01000000))
1421 // Output each symbol to the display, dependant on type
1425 // Non-relocatable symbols
1426 if (type == 0x02000000 || type == 0x03000000)
1428 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1434 // TEXT segment relocatable symbols
1435 if (type == 0x04000000 || type == 0x05000000)
1437 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1443 // DATA segment relocatble symbols
1444 if (type == 0x06000000 || type == 0x07000000)
1446 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1452 // BSS segment relocatable symbols
1453 if (type == 0x08000000 || type == 0x09000000)
1455 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1471 // Stuff the (long) value of a string into the value argument. RETURNS TRUE if
1472 // the string doesn't parse. Parses only as a hexadecimal string.
1474 int GetHexValue(char * string, int * value)
1478 while (isxdigit(*string))
1480 if (isdigit(*string))
1482 *value = (*value << 4) + (*string++ - '0');
1486 if (isupper(*string))
1487 *string = tolower(*string);
1489 *value = (*value << 4) + ((*string++ - 'a') + 10);
1493 if (*string != '\0')
1495 printf("Invalid hexadecimal value");
1504 // Create one big .o file from the images already in memory, returning a
1505 // pointer to an OHEADER. Note that the oheader is just the header for the
1506 // output (plus some other information). The text, data, and fixups are all
1507 // still in the ofile images hanging off the global `olist'.
1509 struct OHEADER * make_ofile()
1511 unsigned tptr, dptr, bptr; // Bases in runtime model
1512 int ret = 0; // Return value
1513 struct OHEADER * header; // Output header pointer
1515 // Initialize cumulative segment sizes
1516 textsize = datasize = bsssize = 0;
1518 // For each object file, accumulate the sizes of the segments but remove
1519 // those object files which are unused
1520 struct OFILE * oprev = NULL; // Init previous obj file list ptr
1521 struct OFILE * otemp = olist; // Set temp pointer to object file list
1524 while (otemp != NULL)
1526 // UNUSED !!!!! (it's !O_ARCHIVE, so this code executes.)
1527 if (!(otemp->o_flags & O_ARCHIVE))
1529 if ((otemp->o_flags & O_USED) == 0)
1533 printf("Unused object file ");
1535 printf(" discarded.\n");
1539 olist = otemp->o_next;
1541 oprev->o_next = otemp->o_next;
1543 struct OFILE * ohold = otemp;
1545 if (!ohold->isArchiveFile)
1546 free(ohold->o_image);
1550 // Also need to remove them from the obj_* tables too :-P
1551 // N.B.: Would probably be worthwhile to remove crap like this
1552 // and stuff it into the OFILE structure...
1554 printf("»-> removing %s... (index == %i, len == %i)\n", obj_fname[i], i, obj_index - 1);
1558 for(k=i; k<obj_index-1; k++)
1560 memcpy(obj_fname[k], obj_fname[k + 1], FNLEN);
1561 obj_segsize[k][0] = obj_segsize[k + 1][0];
1562 obj_segsize[k][1] = obj_segsize[k + 1][1];
1563 obj_segsize[k][2] = obj_segsize[k + 1][2];
1571 // Increment total of segment sizes ensuring requested
1573 textsize += (otemp->o_header.tsize + secalign) & ~secalign;
1574 datasize += (otemp->o_header.dsize + secalign) & ~secalign;
1575 bsssize += (otemp->o_header.bsize + secalign) & ~secalign;
1580 // Go to next object file list pointer
1581 otemp = otemp->o_next;
1585 // Update base addresses and create symbols _TEXT_E, _DATA_E and _BSS_E
1587 OSTAdd("_TEXT_E", 0x05000000, tval + textsize);
1591 // DATA follows TEXT
1592 dbase = tval + textsize;
1593 OSTAdd("_DATA_E", 0x07000000, tval + textsize + datasize);
1598 bbase = tval + textsize + datasize;
1599 OSTAdd("_BSS_E", 0x09000000, tval + textsize + datasize + bsssize);
1603 // BSS is independent of DATA
1605 OSTAdd("_BSS_E", 0x09000000, bval + bsssize);
1610 // DATA is independant of TEXT
1612 OSTAdd("_DATA_E", 0x07000000, dval + datasize);
1617 bbase = dval + datasize;
1618 OSTAdd("_BSS_E", 0x09000000, dval + datasize + bsssize);
1622 // BSS is independent of DATA
1624 OSTAdd("_BSS_E", 0x09000000, bval + bsssize);
1628 // Place each unresolved symbol in the output symbol table
1632 // Initialise base addresses
1633 tptr = dptr = bptr = 0;
1635 // For each file, relocate its symbols and add them to the output symbol
1640 while (otemp != NULL)
1642 otemp->o_tbase = tptr;
1644 // Do rest only for non-ARCHIVE markers
1645 if (!(otemp->o_flags & O_ARCHIVE))
1647 otemp->o_dbase = dptr;
1648 otemp->o_bbase = bptr;
1649 tptr += (otemp->o_header.tsize + secalign) & ~secalign;
1650 dptr += (otemp->o_header.dsize + secalign) & ~secalign;
1651 bptr += (otemp->o_header.bsize + secalign) & ~secalign;
1654 // For each symbol, (conditionally) add it to the ost
1655 // For ARCHIVE markers, this adds the symbol for the file & returns
1656 // (Shamus: N.B. it does no such thing ATM)
1657 if (DoSymbol(otemp))
1660 if (otemp->o_flags & O_ARCHIVE)
1662 // Now that the archive is marked, remove it from list
1664 olist = otemp->o_next;
1666 oprev->o_next = otemp->o_next;
1668 struct OFILE * ohold = otemp;
1671 if (!ohold->isArchiveFile)
1672 free(ohold->o_image);
1681 otemp = otemp->o_next;
1684 // Places all the externs, globals etc into the output symbol table
1685 if (DoCommon() == -1)
1688 // Create a new output file header
1689 header = new_oheader();
1693 printf("make_ofile: out of memory!\n");
1697 // Fill in the output header. Does not match the actual output but values
1698 // used as reference
1699 header->magic = 0x0150; // COF magic number
1700 header->tsize = textsize; // TEXT segment size
1701 header->dsize = datasize; // DATA segment size
1702 header->bsize = bsssize; // BSS segment size
1703 header->ssize = (ost_ptr - ost); // Symbol table size
1704 header->ostbase = ost; // Output symbol table base address
1706 // For each object file, relocate its TEXT and DATA segments. OR the result
1707 // into ret so all files get moved (and errors reported) before returning
1708 // with the error condition
1709 for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1711 if (!(otemp->o_flags & O_ARCHIVE))
1713 ret |= RelocateSegment(otemp, T_TEXT); // TEXT segment relocations
1714 ret |= RelocateSegment(otemp, T_DATA); // DATA segment relocations
1718 // Done with global symbol hash tables
1721 return (ret ? (struct OHEADER *)NULL : header);
1726 // Add symbol to hash list
1728 int AddSymbolToHashList(struct HREC ** hptr, char * sym, struct OFILE * ofile,
1729 long value, int type)
1731 struct HREC * htemp = new_hrec();
1735 printf("Out of memory\n");
1739 // Shamus: Moar testing...
1742 printf("AddSymbolToHashList(): hptr=$%08X, sym=\"%s\", ofile=$%08X, value=$%X, type=$%X\n", hptr, sym, ofile, value, type);
1745 // Populate hash record
1746 memset(htemp->h_sym, 0, SYMLEN);
1747 strcpy(htemp->h_sym, sym);
1748 htemp->h_ofile = ofile;
1749 htemp->h_value = value;
1750 htemp->h_type = type;
1752 // Add new hash to the front of the list (hence the ** for hptr)
1753 htemp->h_next = *hptr;
1761 // Add symbol to the unresolved symbols hash table (really, it's a linked list)
1763 int AddUnresolvedSymbol(char * sym, struct OFILE * ofile)
1766 printf("AddUnresolvedSymbol(%s, %s)\n", sym, ofile->o_name);
1768 return AddSymbolToHashList(&unresolved, sym, ofile, 0L, 0);
1773 // Remove the HREC from the unresolved symbol list, and pass back a pointer
1774 // to the spot where the HREC was.
1776 struct HREC * RemoveUnresolvedSymbol(struct HREC * hrec)
1778 struct HREC * ptr = unresolved;
1779 struct HREC * previous = NULL;
1781 while ((ptr != hrec) && (ptr != NULL))
1791 struct HREC * next = ptr->h_next;
1793 // Remove the head if nothing previous, otherwise, remove what we found
1794 if (previous == NULL)
1797 previous->h_next = next;
1805 // Add symbol to the unresolved symbols hash table
1807 int AddARSymbol(char * sym, struct OFILE * ofile)
1810 printf("AddARSymbol(%s, %s)\n", sym, ofile->o_name);
1812 return AddSymbolToHashList(&arSymbol, sym, ofile, 0L, 0);
1817 // Generate hash value from the 1st 15 characters of the symbol modulo the
1818 // number of buckets in the hash.
1820 int GetHash(char * s)
1822 // For this to be consistent, the symbol MUST be zeroed out beforehand!
1824 memset(c, 0, SYMLEN);
1827 int i = (c[0] + c[1] + c[2] + c[3] + c[4] + c[5] + c[6] + c[7] + c[8]
1828 + c[9] + c[10] + c[11] + c[12] + c[13] + c[14]) % NBUCKETS;
1834 // Lookup a symbol in the hash table.
1835 // Returns either a pointer to the HREC or NULL if not found.
1837 struct HREC * LookupHREC(char * symbol)
1839 struct HREC * hptr = htable[GetHash(symbol)];
1841 while (hptr != NULL)
1843 //This is utter failure...
1844 // if (symcmp(symbol, hptr->h_sym)) <-- left here for giggles :D - LinkoVitch
1845 // Return hash record pointer if found
1846 if (strcmp(symbol, hptr->h_sym) == 0)
1849 hptr = hptr->h_next;
1857 // Lookup a symbol in the AR symbol table.
1858 // Returns either a pointer to the HREC or NULL if not found.
1860 struct HREC * LookupARHREC(char * symbol)
1862 struct HREC * hptr = arSymbol;//htable[GetHash(symbol)];
1864 while (hptr != NULL)
1866 // Return hash record pointer if found
1867 if (strcmp(symbol, hptr->h_sym) == 0)
1870 hptr = hptr->h_next;
1878 // Add symbol to the hash table if it doesn't already exist, otherwise decide
1879 // what to do since it's already defined in another unit.
1881 int DealWithSymbol(char * sym, long type, long value, struct OFILE * ofile)
1885 printf("DealWithSymbol(%s,%s,%lx,", sym, ofile->o_name, value);
1886 printf("%x,%s)\n", (unsigned int)type, (isglobal(type) ? "GLOBAL" : "COMMON"));
1889 struct HREC * hptr = LookupHREC(sym);
1892 return AddSymbolToHashList(&htable[GetHash(sym)], sym, ofile, value, type);
1894 // Symbol is already in table... Figure out how to handle!
1895 if (iscommon(type) && !iscommon(hptr->h_type))
1897 // Mismatch: global came first; warn and keep the global one
1900 printf("Warning: %s: global from ", sym);
1901 put_name(hptr->h_ofile);
1902 printf(" used, common from ");
1904 printf(" discarded.\n");
1907 putword(sym + 8, ABST_EXTERN);
1908 putlong(sym + 10, 0L);
1910 else if (iscommon(hptr->h_type) && !iscommon(type))
1912 // Mismatch: common came first; warn and keep the global one
1915 printf("Warning: %s: global from ", sym);
1917 printf(" used, common from ");
1918 put_name(hptr->h_ofile);
1919 printf(" discarded.\n");
1922 hptr->h_type = type;
1923 hptr->h_ofile = ofile;
1924 hptr->h_value = value;
1926 // They're both global [WRONG! Passed in one is global]
1927 // else if (!iscommon(type))
1928 //is this now right??
1929 else if (!iscommon(type) && !iscommon(hptr->h_type))
1931 // Global exported by another ofile; warn and make this one extern
1934 printf("Duplicate symbol %s: ", sym);
1935 put_name(hptr->h_ofile);
1938 printf(" discarded\n");
1941 putword(sym + 8, ABST_EXTERN);
1943 // They're both common
1946 if (hptr->h_value < value)
1948 hptr->h_value = value;
1949 hptr->h_ofile = ofile;
1958 // Add the imported symbols from this file to unresolved, and the global and
1959 // common (???) symbols to the exported hash table.
1961 // Change old-style commons (type == T_EXTERN, value != 0) to new-style ones
1962 // (type == (T_GLOBAL | T_EXTERN)). [??? O_o]
1964 int AddSymbols(struct OFILE * Ofile)
1966 struct HREC * hptr; // Hash record pointer
1967 char symbol[SYMLEN];
1970 printf("Add symbols for file %s\n", Ofile->o_name);
1972 // Get base pointer, start of sym fixups
1973 char * ptr = Ofile->o_image + 32
1974 + Ofile->o_header.tsize
1975 + Ofile->o_header.dsize
1976 + Ofile->o_header.absrel.reloc.tsize
1977 + Ofile->o_header.absrel.reloc.dsize;
1978 char * sfix = ptr; // Set symbol fixup pointer
1979 char * sstr = sfix + Ofile->o_header.ssize; // Set symbol table pointer
1980 long nsymbols = Ofile->o_header.ssize / 12; // Obtain number of symbols
1984 long index = getlong(sfix); // Get symbol string index
1985 long type = getlong(sfix + 4); // Get symbol type
1986 long value = getlong(sfix + 8); // Get symbol value
1987 memset(symbol, 0, SYMLEN);
1988 strcpy(symbol, sstr + index);
1990 if ((Ofile->isArchiveFile) && !(Ofile->o_flags & O_USED))
1992 if ((type & T_EXT) && (type & (T_SEG | T_ABS)))
1993 if (AddARSymbol(symbol, Ofile))
1996 else if (type == T_EXT)
1998 // External symbal that is *not* in the current unit
1999 hptr = LookupHREC(symbol);
2002 hptr->h_ofile->o_flags |= O_USED; // Mark .o file as used
2003 // Otherwise add to unresolved list
2004 else if (AddUnresolvedSymbol(symbol, Ofile))
2005 return 1; // Error if addition failed
2007 else if ((type & T_EXT) && (type & (T_SEG | T_ABS)))
2009 // Symbol in the current unit that is also EXPORTED
2010 if (DealWithSymbol(symbol, type, value, Ofile))
2011 return 1; // Error if addition failed
2014 sfix += 12; // Increment symbol fixup pointer
2015 nsymbols--; // Decrement num of symbols to process
2018 // Success loading symbols
2024 // Process object file for symbols
2026 int DoItem(struct OFILE * obj)
2028 // Allocate memory for object record ptr
2029 struct OFILE * Ofile = new_ofile();
2033 printf("Out of memory while processing %s\n", obj->o_name);
2037 // Starting after all pathnames, etc., copy .o file name to Ofile
2038 char * temp = path_tail(obj->o_name);
2040 // Check filename length
2041 if (strlen(temp) > FNLEN - 1)
2043 printf("File name too long: %s\n", temp);
2047 // Check archive name length
2048 if (strlen(obj->o_arname) > FNLEN - 1)
2050 printf("Archive name too long: %s\n", obj->o_arname);
2054 strcpy(Ofile->o_name, temp); // Store filename
2055 strcpy(Ofile->o_arname, obj->o_arname); // Store archive name
2057 // Initialise object record information
2058 Ofile->o_next = NULL;
2062 Ofile->o_flags = obj->o_flags;
2063 Ofile->o_image = obj->o_image;
2064 Ofile->isArchiveFile = obj->isArchiveFile;
2065 char * ptr = obj->o_image;
2067 // Don't do anything if this is just an ARCHIVE marker, just add the file
2069 // (Shamus: N.B.: it does no such ARCHIVE thing ATM)
2070 if (!(obj->o_flags & O_ARCHIVE))
2072 Ofile->o_header.magic = getlong(ptr);
2073 Ofile->o_header.tsize = getlong(ptr + 4);
2074 Ofile->o_header.dsize = getlong(ptr + 8);
2075 Ofile->o_header.bsize = getlong(ptr + 12);
2076 Ofile->o_header.ssize = getlong(ptr + 16);
2077 Ofile->o_header.absrel.reloc.tsize = getlong(ptr + 24);
2078 Ofile->o_header.absrel.reloc.dsize = getlong(ptr + 28);
2080 // Round BSS off to alignment boundary
2081 Ofile->o_header.bsize = (Ofile->o_header.bsize + secalign) & ~secalign;
2083 if ((Ofile->o_header.dsize & 7) && wflag)
2085 printf("Warning: data segment size of ");
2087 printf(" is not a phrase multiple\n");
2090 // Check for odd segment sizes
2091 if ((Ofile->o_header.tsize & 1) || (Ofile->o_header.dsize & 1)
2092 || (Ofile->o_header.bsize & 1))
2094 printf("Error: odd-sized segment in ");
2096 printf("; link aborted.\n");
2100 if (AddSymbols(Ofile))
2104 // Add this file to the olist
2108 olast->o_next = Ofile;
2116 // Handle items in processing list.
2118 // After loading all objects, archives & include files, we now go and process
2119 // each item on the processing list (plist). Once this is done, we go through
2120 // any unresolved symbols left and see if they have shown up.
2122 int ProcessLists(void)
2124 // Process object file list first (adds symbols from each unit & creates
2126 while (plist != NULL)
2131 struct OFILE * ptemp = plist;
2132 plist = plist->o_next;
2138 // Process the unresolved symbols list. This may involve pulling in symbols
2139 // from any included .a units. Such units are lazy linked by default; we
2140 // generally don't want everything they provide, just what's referenced.
2141 for(uptr=unresolved; uptr!=NULL; )
2144 printf("LookupHREC(%s) => ", uptr->h_sym);
2146 struct HREC * htemp = LookupHREC(uptr->h_sym);
2150 // Found it in the symbol table!
2152 printf("%s in %s (=$%06X)\n", (isglobal(htemp->h_type) ? "global" : "common"), htemp->h_ofile->o_name, htemp->h_value);
2154 // Mark the .o unit that the symbol is in as seen & remove from the
2156 htemp->h_ofile->o_flags |= O_USED;
2157 uptr = RemoveUnresolvedSymbol(uptr);
2164 // Check to see if the unresolved symbol is on the AR symbol list.
2165 htemp = LookupARHREC(uptr->h_sym);
2167 // If the unresolved symbol is in a .o unit that is unused, we can
2168 // drop it; same if the unresolved symbol is in the exported AR
2169 // symbol list. Otherwise, go to the next unresolved symbol.
2170 if (!(uptr->h_ofile->o_flags & O_USED) || (htemp != NULL))
2171 uptr = RemoveUnresolvedSymbol(uptr);
2173 uptr = uptr->h_next;
2175 // Now that we've possibly deleted the symbol from unresolved list
2176 // that was also in the AR list, we add the symbols from this .o
2177 // unit to the symbol table, mark the .o unit as used, and restart
2178 // scanning the unresolved list as there is a good possibility that
2179 // the symbols in the unit we're adding has unresolved symbols as
2183 htemp->h_ofile->o_flags |= O_USED;
2184 AddSymbols(htemp->h_ofile);
2190 // Show files used if the user requests it.
2193 printf("Files used:\n");
2194 struct OFILE * filePtr = olist;
2196 while (filePtr != NULL)
2198 if (filePtr->o_flags & O_USED)
2200 printf(" %s%s%s\n", filePtr->o_name, (filePtr->isArchiveFile ? ":" : ""), (filePtr->isArchiveFile ? filePtr->o_arname : nullStr));
2203 filePtr = filePtr->o_next;
2212 // Extract filename from path
2214 char * path_tail(char * name)
2216 char * temp = strrchr(name, PATH_DELIMITER);
2218 // Return what was passed in if path delimiter was not found
2227 // Add input file to processing list
2229 int AddToProcessingList(char * ptr, char * fname, char * arname, uint8_t arFile)
2233 // First time object record allocation
2234 plist = new_ofile();
2239 // Next object record allocation
2240 plast->o_next = new_ofile();
2241 plast = plast->o_next;
2246 printf("Out of memory.\n"); // Error if memory allocation fails
2250 fname = path_tail(fname);
2251 arname = path_tail(arname);
2253 if (strlen(fname) > FNLEN - 1)
2255 // Error on excessive filename length
2256 printf("File name too long: %s (sorry!)\n", fname);
2260 if (strlen(arname) > FNLEN - 1)
2262 // Error on excessive filename length
2263 printf("AR file name too long: %s (sorry!)\n", arname);
2267 strcpy(plast->o_name, fname); // Store filename sans path
2268 strcpy(plast->o_arname, arname); // Store archive name sans path
2269 plast->o_image = ptr; // Store data pointer
2270 plast->o_flags = (arFile ? 0 : O_USED); // File is used if NOT in archive
2271 plast->o_next = NULL; // Initialise next record pointer
2272 plast->isArchiveFile = arFile; // Shamus: Temp until can sort it out
2274 return 0; // Return without errors
2279 // Process in binary include files and add them to the processing list. This
2280 // routine takes in the binary file and creates an 'object' file in memory.
2281 // Sym1/Sym2 point to the start and end of data.
2283 // Image size for include files is:
2284 // Header ....... 32 bytes
2285 // Data ......... dsize
2286 // Sym Fixups ... 2 * 12 bytes
2287 // Symbol Size .. 4 bytes (Value to include symbols and terminating null)
2288 // Symbols ...... (strlen(sym1) + 1) + (strlen(sym2) + 1)
2289 // Terminate .... 4 bytes (0x00000000)
2291 int LoadInclude(char * fname, int handle, char * sym1, char * sym2, int segment)
2293 long fsize, dsize, size; // File, DATA segment and image sizes
2294 char * ptr, * sptr; // Data pointers
2296 int sym1len = 0; // Symbol 1 length
2297 int sym2len = 0; // Symbol 2 length
2298 unsigned symtype = 0;
2300 fsize = FileSize(handle); // Get size of include file
2301 dsize = (fsize + secalign) & ~secalign; // Round up to a alignment boundary
2303 sym1len = strlen(sym1) + 1; // Get sym1 length + null termination
2304 sym2len = strlen(sym2) + 1; // Get sym2 length + null termination
2306 size = 32 + dsize + 24 + 4 + sym1len + sym2len + 4;
2308 // Use calloc so the header & fixups initialize to zero
2309 // Allocate object image memory
2310 if ((ptr = calloc(size, 1)) == NULL)
2312 printf("Out of memory while including %s\n", fname);
2317 // Read in binary data
2318 if (read(handle, ptr + 32, fsize) != fsize)
2320 printf("File read error on %s\n", fname);
2328 strcpy(obj_fname[obj_index], path_tail(fname));
2330 // Build this image's dummy header
2331 putlong(ptr, 0x00000107); // Magic number
2335 putlong(ptr+4, dsize); // Text size
2336 putlong(ptr+8, 0L); // Data size
2337 symtype = 0x05000000;
2338 obj_segsize[obj_index][0] = dsize;
2339 obj_segsize[obj_index][1] = 0;
2340 obj_segsize[obj_index][2] = 0;
2344 putlong(ptr+4, 0L); // Text size
2345 putlong(ptr+8, dsize); // Data size
2346 symtype = 0x07000000;
2347 obj_segsize[obj_index][0] = 0;
2348 obj_segsize[obj_index][1] = dsize;
2349 obj_segsize[obj_index][2] = 0;
2352 obj_index++; // Increment object count
2354 putlong(ptr+12, 0L); // BSS size
2355 putlong(ptr+16, 24); // Symbol table size
2356 putlong(ptr+20, 0L); // Entry point
2357 putlong(ptr+24, 0L); // TEXT relocation size
2358 putlong(ptr+28, 0L); // DATA relocation size
2360 sptr = ptr + 32 + dsize; // Set sptr to symbol table location
2362 putlong(sptr, 4L); // String offset of symbol1
2363 putlong(sptr+4, symtype); // Symbol type
2364 putlong(sptr+8, 0x00000000); // Symbol has no value (START)
2365 putlong(sptr+12, 4L + (sym2len - 1)); // String offset of symbol2
2366 putlong(sptr+16, symtype); // Symbol type
2367 putlong(sptr+20, dsize); // Symbol is data size (END)
2369 sptr = ptr + 32 + dsize + 24; // Set sptr to symbol table size loc
2371 putlong(sptr, sym1len + 4L); // Size of symbol table
2373 sptr = ptr + 32 + dsize + 24 + 4; // Set sptr to symbol table location
2375 for(i=0; i<(sym1len-1); i++) // Write symbol1 to string table
2378 sptr += (sym1len - 1); // Step past symbol string
2379 *sptr = '\0'; // Terminate symbol string
2380 sptr += 1; // Step past termination
2382 for(i=0; i<(sym2len-1); i++) // Write symbol2 to string table
2385 sptr += (sym2len - 1); // Step past symbol string
2386 *sptr = '\0'; // Terminate symbol string
2387 sptr += 1; // Step past termination
2389 putlong(sptr, 0L); // Terminating long for object file
2391 return AddToProcessingList(ptr, fname, nullStr, 0);
2396 // Takes a file name, gets in its image, puts it on plist. The image may
2397 // already be in memory: If so, the ptr arg is non-null. If so, the file is
2398 // already closed. Note that the file is already open (from DoFile()). RETURNS
2399 // a pointer to the OFILE structure for this file, so you can diddle its flags
2400 // (DoFile sets O_USED for files on the command line).
2402 int LoadObject(char * fname, int fd, char * ptr)
2406 long size = FileSize(fd);
2408 // Allocate memory for file data
2413 printf("Out of memory while processing %s\n", fname);
2418 // Read in file data
2419 if (read(fd, ptr, size) != size)
2421 printf("File read error on %s\n", fname);
2427 // SCPCD: get the name of the file instead of all pathname
2428 strcpy(obj_fname[obj_index], path_tail(fname));
2429 obj_segsize[obj_index][0] = (getlong(ptr + 4) + secalign) & ~secalign;
2430 obj_segsize[obj_index][1] = (getlong(ptr + 8) + secalign) & ~secalign;
2431 obj_segsize[obj_index][2] = (getlong(ptr + 12) + secalign) & ~secalign;
2434 close(fd); // Close file
2437 // Now add this image to the list of pending ofiles (plist)
2438 // This routine is shared by LoadInclude after it builds the image
2439 return AddToProcessingList(ptr, fname, nullStr, 0);
2444 // What it says on the tin: check for a .o suffix on the passed in string
2446 uint8_t HasDotOSuffix(char * s)
2448 char * temp = strrchr(s, '.');
2450 if ((temp == NULL) || (strncmp(temp, ".o", 2) != 0))
2458 // Process an ar archive file (*.a)
2460 int LoadArchive(char * fname, int fd)
2462 // Read in the archive file to memory and process
2463 long size = FileSize(fd);
2464 char * ptr = malloc(size);
2465 char * endPtr = ptr + size;
2466 char * longFilenames = NULL;
2470 printf("Out of memory while processing %s\n", fname);
2475 if (read(fd, ptr, size) != size)
2477 printf("File read error on %s\n", fname);
2485 // Save the pointer for later...
2486 arPtr[arIndex++] = ptr;
2487 char objName[FNLEN];
2490 //printf("\nProcessing AR file \"%s\"...\n", fname);
2493 // Loop through all objects in the archive and process them
2496 memset(objName, 0, 17);
2501 // if ((ptr[i] == '/') || (ptr[i] == ' '))
2502 if ((ptr[i] == ' ') && (i != 0))
2508 objName[i] = ptr[i];
2513 if (ptr[48 + i] == ' ')
2519 objSize[i] = ptr[48 + i];
2522 // Check to see if a long filename was requested
2523 if (objName[0] == 0x20)
2525 uint32_t fnSize = atoi(objName + 1);
2527 if (longFilenames != NULL)
2530 char * currentFilename = longFilenames + fnSize;
2532 while (*currentFilename != 0x0A)
2533 objName[i++] = *currentFilename++;
2539 if ((strncmp(objName, "ARFILENAMES/", 12) == 0) || (strncmp(objName, "//", 2) == 0))
2541 longFilenames = ptr + 60;
2543 else if (HasDotOSuffix(objName))
2545 //printf("Processing object \"%s\" (size == %i, obj_index == %i)...\n", objName, atoi(objSize), obj_index);
2546 strcpy(obj_fname[obj_index], objName);
2547 obj_segsize[obj_index][0] = (getlong(ptr + 60 + 4) + secalign) & ~secalign;
2548 obj_segsize[obj_index][1] = (getlong(ptr + 60 + 8) + secalign) & ~secalign;
2549 obj_segsize[obj_index][2] = (getlong(ptr + 60 + 12) + secalign) & ~secalign;
2552 if (AddToProcessingList(ptr + 60, objName, fname, 1))
2556 uint32_t size = atoi(objSize);
2557 size += (size & 0x01 ? 1 : 0);
2560 while (ptr < endPtr);
2567 // Process files (*.o, *.a) passed in on the command line
2569 int ProcessFiles(void)
2572 char magic[8]; // Magic header number (4 bytes for *.o, 8 for *.a)
2574 // Process all file handles
2575 for(i=0; i<(int)hd; i++)
2577 // Verbose mode information
2579 printf("Read file %s%s\n", name[i], (hflag[i] ? " (include)" : ""));
2583 // Attempt to read file magic number (OBJECT/ARCHIVE FILES)
2584 if (read(handle[i], magic, 8) != 8)
2586 printf("Error reading file %s\n", name[i]);
2591 lseek(handle[i], 0L, 0); // Reset to start of input file
2593 // Look for RMAC/MAC/GCC ($20107) object files
2594 if ((getlong(magic) == 0x00000107) || (getlong(magic) == 0x00020107))
2596 // Process input object file
2597 if (LoadObject(name[i], handle[i], 0L))
2600 // Otherwise, look for an object archive file
2601 else if (strncmp(magic, "!<arch>\x0A", 8) == 0)
2603 if (LoadArchive(name[i], handle[i]))
2608 // Close file and error
2609 printf("%s is not a supported object or archive file\n", name[i]);
2617 // If hflag[i] is 1, include this in the data segment; if 2, put it
2619 if (LoadInclude(name[i], handle[i], hsym1[i], hsym2[i], hflag[i] - 1))
2624 // Free include, symbol & object handles
2625 for(i=0; i<(int)hd; i++)
2636 // Reset next handle indicator
2643 // Load newargv with pointers to arguments found in the buffer
2645 int parse(char * buf, char * newargv[])
2650 printf("begin parsing\n");
2654 while (*buf && strchr(",\t\n\r\14 ", *buf))
2658 if (*buf == '\0' || *buf == 26)
2662 printf("No commands in command file\n");
2671 /* test for comment */
2674 /* found a comment; skip to next \n and start over */
2675 while (*buf && *buf != '\n')
2683 printf("Too many arguments in command file\n");
2689 while (!strchr(",\t\n\r\14 ", *buf))
2691 if (*buf == '\0' || *buf == 26)
2693 printf("Finished parsing %d args\n", i);
2703 printf("argv[%d] = \"%s\"\n", i, newargv[i]);
2711 // Process in a Link Command File
2713 int docmdfile(char * fname)
2715 int fd; // File descriptor
2716 unsigned size; // Command file size
2717 char * ptr; // Pointer
2718 int newargc; // New argument count
2719 char * (*newargv)[]; // New argument value array
2721 // Verbose information
2723 printf("docmdfile(%s)\n", fname);
2725 // Allocate memory for new argument values
2726 newargv = malloc((long)(sizeof(char *) * MAXARGS));
2730 printf("Out of memory.\n");
2734 // Attempt to open and read in the command file
2737 if ((fd = open(fname, _OPEN_FLAGS)) < 0)
2739 printf("Cannot open command file %s.\n", fname);
2743 size = FileSize(fd);
2745 if ((ptr = malloc(size + 1)) == NULL)
2747 printf("Out of memory.\n");
2752 if (read(fd, ptr, size) != (int)size)
2754 printf("Read error on command file %s.\n", fname);
2759 *(ptr + size) = 0; // Null terminate the buffer
2764 printf("No command filename specified\n");
2768 // Parse the command file
2769 if ((newargc = parse(ptr, *newargv)) == -1)
2774 // Process the inputted flags
2775 if (doargs(newargc, *newargv))
2777 printf("docmdfile: doargs returns TRUE\n");
2789 // Take an Argument List and Parse the Command Line
2791 int doargs(int argc, char * argv[])
2793 int i = 1; // Iterator
2794 int c; // Command line character
2795 char * ifile, * isym; // File name and symbol name for -i
2797 // Parse through option switches & files
2800 // Process command line switches
2801 if (argv[i][0] == '-')
2805 printf("Illegal option argument: %s\n\n", argv[i]);
2810 c = argv[i++][1]; // Get next character in command line
2812 // Process command line switch
2815 case '?': // Display usage information
2822 case 'A': // Set absolute linking on
2828 printf("Not enough arguments to -a\n");
2832 aflag = 1; // Set abs link flag
2833 // Segment order is TEXT, DATA, BSS
2834 // Text segment can be 'r', 'x' or a value
2837 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2839 ttype = -1; // TEXT segment is relocatable
2841 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2843 printf("Error in text-segment address: cannot be contiguous\n");
2846 else if ((ttype = 0), GetHexValue(argv[i], &tval))
2848 printf("Error in text-segment address: %s is not 'r', 'x' or an address.", argv[i]);
2853 // Data segment can be 'r', 'x' or a value
2856 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2858 dtype = -1; // DATA segment is relocatable
2860 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2862 dtype = -2; // DATA follows TEXT
2864 else if ((dtype = 0), GetHexValue(argv[i], &dval))
2866 printf("Error in data-segment address: %s is not 'r', 'x' or an address.", argv[i]);
2873 // BSS segment can be 'r', 'x' or a value
2874 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2876 btype = -1; // BSS segment is relocatable
2878 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2880 btype = -3; // BSS follows DATA
2882 else if ((btype = 0), GetHexValue(argv[i], &bval))
2884 printf("Error in bss-segment address: %s is not 'r', 'x[td]', or an address.", argv[i]);
2891 case 'B': // Don't remove muliply defined locals
2898 case 'C': // Process a command file
2901 printf("Not enough arguments to -c\n");
2905 if (docmdfile(argv[i++]))
2912 case 'D': // Wait for "return" before exiting
2920 case 'E': // Output COFF (absolute only)
2924 case 'G': // Output source level debugging
2925 printf("\'g\' flag not currently implemented\n");
2928 if (gflag) warn('g', 1);
2933 case 'I': // Include binary file
2936 printf("Not enough arguments to -i\n");
2943 // handle -ii (No truncation)
2944 if ((argv[i-3][2] == 'i') || (argv[i-3][2] == 'I'))
2947 printf("warning: (-ii) COFF format output not specified\n");
2949 // handle -i (Truncation)
2952 if (strlen(isym) > 7)
2956 // Place include files in the DATA segment only
2957 if (DoFile(ifile, DSTSEG_D, isym))
2962 case 'L': // Add local symbols
2969 case 'M': // Produce load symbol map
2976 case 'N': // Output no header to .abs file
2983 case 'O': // Specify an output file
2991 printf("No output filename following -o switch\n");
2995 if (strlen(argv[i]) > FARGSIZE - 5)
2997 printf("Output file name too long (sorry!)\n");
3001 strcpy(ofile, argv[i++]);
3004 case 'R': // Section alignment size
3010 switch (argv[i-1][2])
3012 case 'w': case 'W': secalign = 1; break; // Word alignment
3013 case 'l': case 'L': secalign = 3; break; // Long alignment
3014 case 'p': case 'P': secalign = 7; break; // Phrase alignment
3015 case 'd': case 'D': secalign = 15; break; // Double phrase alignment
3016 case 'q': case 'Q': secalign = 31; break; // Quad phrase alignment
3017 default: secalign = 7; break; // Default phrase alignment
3022 case 'S': // Output only global symbols
3029 case 'V': // Verbose information
3030 if (!vflag && !versflag)
3038 case 'W': // Show warnings flag
3045 case 'Z': // Suppress banner flag
3052 printf("unknown option argument `%c'\n", c);
3058 // Not a switch, then process as a file
3059 if (DoFile(argv[i++], 0, NULL))
3064 if (!oflag && vflag)
3066 strcpy(ofile, "output");
3067 printf("Output file is %s[.ext]\n", ofile);
3071 printf("Output file is %s\n", ofile);
3076 // No problems encountered
3082 // Display Version Information
3084 void display_version(void)
3086 if (displaybanner)// && vflag)
3088 printf("\nReboot's Linker for Atari Jaguar\n");
3089 printf("Copyright (c) 199x Allan K. Pratt, 2014 Reboot\n");
3090 printf("V%i.%i.%i %s (%s)\n\n", MAJOR, MINOR, PATCH, __DATE__, PLATFORM);
3096 // Display Command Line Help
3098 void display_help(void)
3101 printf(" %s [-options] file(s)\n", cmdlnexec);
3103 printf("Options:\n");
3104 printf(" -? or -h display usage information\n");
3105 printf(" -a <text> <data> <bss> output absolute file\n");
3106 printf(" hex value: segment address\n");
3107 printf(" r: relocatable segment\n");
3108 printf(" x: contiguous segment\n");
3109 printf(" -b don't remove multiply defined local labels\n");
3110 printf(" -c <fname> add contents of <fname> to command line\n");
3111 printf(" -d wait for key after link\n");
3112 printf(" -e output COF absolute file\n");
3113 printf(" -g output source-level debugging\n");
3114 printf(" -i <fname> <label> incbin <fname> and set <label>\n");
3115 printf(" -l add local symbols\n");
3116 printf(" -m produce load symbols map\n");
3117 printf(" -n output no file header to .abs file\n");
3118 printf(" -o <fname> set output name\n");
3119 printf(" -r<size> section alignment size\n");
3120 printf(" w: word (2 bytes)\n");
3121 printf(" l: long (4 bytes)\n");
3122 printf(" p: phrase (8 bytes, default alignment)\n");
3123 printf(" d: double phrase (16 bytes)\n");
3124 printf(" q: quad phrase (32 bytes)\n");
3125 printf(" -s output only global symbols\n");
3126 printf(" -v set verbose mode\n");
3127 printf(" -w show linker warnings\n");
3128 printf(" -z suppress banner\n");
3140 // Display link status if verbose mode
3142 printf("Link %s.\n", errflag ? "aborted" : "complete");
3144 // Wait for return key if requested
3147 printf("\nPress the [RETURN] key to continue. ");
3148 fgets(tempbuf, 128, stdin);
3156 // Determine Processor Endianess
3158 int get_endianess(void)
3161 char * p = (char *)&i;
3164 return ENDIANNESS_LITTLE;
3166 return ENDIANNESS_BIG;
3171 // Application Code Starts Here
3173 int main(int argc, char * argv[])
3175 char * s = NULL; // String pointer for "getenv"
3176 struct HREC * utemp; // Temporary hash record pointer
3177 struct OHEADER * header; // Pointer to output header structure
3179 endian = get_endianess(); // Get processor endianess
3180 cmdlnexec = argv[0]; // Obtain executable name
3181 s = getenv("RLNPATH");
3183 if (s) // Attempt to obtain env variable
3184 strcpy(libdir, s); // Store it if found
3186 // Parse the command line
3187 if (doargs(argc, argv))
3193 if (!zflag && !vflag)
3195 display_version(); // Display version information
3196 versflag = 1; // We've dumped the version banner
3199 // Load in specified files/objects and add to processing list
3206 // Work in items in processing list & deal with unresolved list
3213 // Check that there is something to link
3220 // Report unresolved externals
3221 if (unresolved != NULL)
3223 printf("UNRESOLVED SYMBOLS\n");
3225 // Don't list them if two -u's or more
3230 while (utemp != NULL)
3232 printf("\t%s (",utemp->h_sym);
3233 put_name(utemp->h_ofile);
3235 utemp = utemp->h_next;
3246 // Make one output file from input objs
3247 header = make_ofile();
3258 printf("TO DO:Partial linking\n");
3261 // Relocatable linking
3264 printf("TO DO:Relocatable linking\n");
3272 printf("Absolute linking ");
3281 printf("Header magic is 0x%04X\n", (unsigned int)header->magic);
3283 if (write_ofile(header))
3287 // Display the loaded symbols map
3289 if (write_map(header))
3292 // Display segment size summary
3296 printf("+---------+----------+----------+----------+\n");
3297 printf("| Segment | TEXT | DATA | BSS |\n");
3298 printf("| Sizes |----------+----------+----------|\n");
3299 printf("| (Hex) | %8X | %8X | %8X |\n", (unsigned int)header->tsize, (unsigned int)header->dsize, (unsigned int)header->bsize);
3300 printf("+---------+----------+----------+----------+\n\n");
3303 //printf("BIG_ENDIAN = %i, LITTLE_ENDIAN = %i\n", BIG_ENDIAN, LITTLE_ENDIAN);