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
10 unsigned errflag = 0; // Error flag, goes TRUE on error
11 unsigned waitflag = 0; // Wait for any keypress flag
12 unsigned versflag = 0; // Version banner has been shown flag
13 unsigned aflag = 0; // Absolute linking flag
14 unsigned bflag = 0; // Don't remove mulitply def locals flag
15 unsigned cflag = 0; // COF executable
16 unsigned dflag = 0; // Wait for key after link flag
17 unsigned gflag = 0; // Source level debug include flag
18 unsigned lflag = 0; // Add local symbols to output flag
19 unsigned mflag = 0; // Produce symbol load map flag
20 unsigned oflag = 0; // Output filename specified
21 unsigned rflag = 0; // Segment alignment size flag
22 unsigned sflag = 0; // Output only global symbols
23 unsigned vflag = 0; // Verbose flag
24 unsigned wflag = 0; // Show warnings flag
25 unsigned zflag = 0; // Suppress banner flag
26 unsigned pflag = 0, uflag = 0; // Unimplemented flags
27 unsigned hd = 0; // Index of next file handle to fill
28 unsigned secalign = 7; // Section Alignment (8=phrase)
29 unsigned tbase = 0; // TEXT base address
30 unsigned dbase = 0; // DATA base address
31 unsigned bbase = 0; // BSS base address
32 unsigned textoffset = 0; // COF TEXT segment offset
33 unsigned dataoffset = 0; // COF DATA segment offset
34 unsigned bssoffset = 0; // COF BSS segment offset
35 unsigned displaybanner = 1; // Display version banner
36 unsigned symoffset = 0; // Symbol table offset in output file
37 unsigned dosymi = 0; // Dosym() processing iterator
38 unsigned dbgsymbase = 0; // Debug symbol base address
39 //unsigned symtrunc = 0; // Symbol truncation -i and -ii
40 int noheaderflag = 0; // No header flag for ABS files
41 int hflags; // Value of the arg to -h option
42 int ttype, dtype, btype; // Type flag: 0, -1, -2, -3, -4
43 int tval, dval, bval; // Values of these abs bases
44 int hflag[NHANDLES]; // True for include files
45 int handle[NHANDLES]; // Open file handles
46 int textsize, datasize, bsssize; // Cumulative segment sizes
47 char libdir[FARGSIZE * 3]; // Library directory to search
48 char ofile[FARGSIZE]; // Output file name (.o)
49 char * name[NHANDLES]; // Associated file names
50 char * cmdlnexec = NULL; // Executable name - pointer to ARGV[0]
51 char * hsym1[SYMLEN]; // First symbol for include files
52 char * hsym2[SYMLEN]; // Second symbol for include files
53 struct OFILE * plist = NULL; // Object image list pointer
54 struct OFILE * plast; // Last object image list pointer
55 struct OFILE * olist = NULL; // Pointer to first object file in list
56 struct OFILE * olast; // Pointer to last object file in list
57 char obj_fname[16384][FNLEN]; // Object file names
58 unsigned obj_segsize[16384][3]; // Object file seg sizes; TEXT,DATA,BSS
59 unsigned obj_index = 0; // Object file index/count
62 struct HREC * htable[NBUCKETS]; // Hash table
63 struct HREC * unresolved = NULL; // Pointer to unresolved hash list
64 char * ost; // Output symbol table
65 char * ost_ptr; // Output symbol table; current pointer
66 char * ost_end; // Output symbol table; end pointer
67 char * oststr; // Output string table
68 char * oststr_ptr; // Output string table; current pointer
69 char * oststr_end; // Output string table; end pointer
70 int ost_index = 0; // Index of next ost addition
71 int endian; // Processor endianess
72 uint8_t nullStr[1] = "\x00"; // Empty string
73 struct HREC * arSymbol = NULL; // Pointer to AR symbol table
75 // Some human readable defines for endianess
76 #define ENDIANNESS_BIG 1
77 #define ENDIANNESS_LITTLE 0
79 // Function prototypes
80 struct HREC * LookupHREC(char *);
81 char * path_tail(char *);
82 void display_help(void);
83 void display_version(void);
87 // Get a long word from memory
89 uint32_t getlong(uint8_t * src)
92 uint8_t * out = (uint8_t *)&temp;
94 if (endian == ENDIANNESS_BIG)
114 // Put a long word into memory
116 void putlong(uint8_t * dest, uint32_t val)
118 *dest++ = (uint8_t)(val >> 24);
119 *dest++ = (uint8_t)(val >> 16);
120 *dest++ = (uint8_t)(val >> 8);
121 *dest = (uint8_t)val;
126 // Get a word from memory
128 uint16_t getword(uint8_t * src)
131 uint8_t * out = (uint8_t *)&temp;
133 if (endian == ENDIANNESS_BIG)
149 // Put a word into memory
151 void putword(uint8_t * dest, uint16_t val)
153 *dest++ = (uint8_t)(val >> 8);
154 *dest = (uint8_t)val;
159 // Find passed in file's length in bytes
160 // N.B.: This also resets the file's pointer to the start of the file
162 long FileSize(int fd)
164 long size = lseek(fd, 0, SEEK_END);
165 lseek(fd, 0, SEEK_SET);
172 // For this object file, add symbols to the output symbol table after
173 // relocating them. Returns TRUE if OSTLookup returns an error (-1).
175 int DoSymbols(struct OFILE * ofile)
182 unsigned tsoSave, dsoSave, bsoSave;
184 // Point to first symbol record in the object file
185 char * symptr = (ofile->o_image + 32
186 + ofile->o_header.tsize
187 + ofile->o_header.dsize
188 + ofile->o_header.absrel.reloc.tsize
189 + ofile->o_header.absrel.reloc.dsize);
191 // Point to end of symbol record in the object file
192 char * symend = symptr + ofile->o_header.ssize;
194 // Search through object segment size table to accumulated segment sizes to
195 // ensure the correct offsets are used in the resulting COF file.
197 unsigned tsegoffset = 0, dsegoffset = 0, bsegoffset = 0;
199 // Search for object file name
200 for(j=0; j<(int)obj_index; j++)
202 if (!strcmp(ofile->o_name, obj_fname[j]))
204 // Object file name found
209 // Accumulate segment sizes
210 tsegoffset += obj_segsize[j][0];
211 dsegoffset += obj_segsize[j][1];
212 bsegoffset += obj_segsize[j][2];
217 printf("DoSymbols(): Object file missing from obj_fname: %s\n",
222 // Save segment vars, so we can restore them if needed
223 tsoSave = tsegoffset, dsoSave = dsegoffset, bsoSave = bsegoffset;
225 // Process each record in the object's symbol table
226 for(; symptr!=symend; symptr+=12)
228 index = getlong(symptr + 0); // Obtain symbol string index
229 type = getlong(symptr + 4); // Obtain symbol type
230 value = getlong(symptr + 8); // Obtain symbol value
232 // Global/External symbols have a pre-processing stage
233 // N.B.: This destroys the t/d/bsegoffset discovered above. So if a
234 // local symbol follows a global/exported one, it gets wrong
235 // info! [Should be FIXED now]
236 if (type & 0x01000000)
238 // Obtain the string table index for the relocation symbol, look
239 // for it in the globals hash table to obtain information on that
241 hptr = LookupHREC(symend + index);
245 // Try to find it in the OST
246 int ostIndex = OSTLookup(symend + index);
250 printf("DoSymbols(): Symbol not found in hash table: '%s' (%s)\n", symend + index, ofile->o_name);
254 // If the symbol is not in any .a or .o units, it must be one
255 // of the injected ones (_TEXT_E, _DATA_E, or _BSS_E), so skip
260 // Search through object segment size table to obtain segment sizes
261 // for the object that has the required external/global as a local
262 // symbol. As each object is interrogated the segment sizes are
263 // accumulated to ensure the correct offsets are used in the
264 // resulting COF file. This is effectively 'done again' only as we
265 // are working with a different object file.
267 tsegoffset = dsegoffset = bsegoffset = 0;
269 // Search for object filename
270 for(j=0; j<(int)obj_index; j++)
272 if (!strcmp(hptr->h_ofile->o_name, obj_fname[j]))
274 ssidx = j; // Symbol object filename
278 // Accumulate segment sizes
279 tsegoffset += obj_segsize[j][0];
280 dsegoffset += obj_segsize[j][1];
281 bsegoffset += obj_segsize[j][2];
286 printf("DoSymbols(): Object file missing from obj_fname: '%s:%s' symbol: '%s' (%s)\n",
287 hptr->h_ofile->o_name, hptr->h_ofile->o_arname,
288 symend + index, ofile->o_name);
292 // Update type with global type
295 // Remove external flag if absolute
296 if (type == (T_EXT | T_ABS))
299 // If the global/external has a value then update that value in
300 // accordance with the segment sizes of the object file it
304 switch (hptr->h_type & 0x0E000000)
308 value = hptr->h_value;
311 value = hptr->h_value - hptr->h_ofile->o_header.tsize;
314 value = hptr->h_value
315 - (hptr->h_ofile->o_header.tsize
316 + hptr->h_ofile->o_header.dsize);
321 // If *not* a global/external, use the info from passed in object
323 tsegoffset = tsoSave, dsegoffset = dsoSave, bsegoffset = bsoSave;
325 // Process and update the value dependent on whether the symbol is a
326 // debug symbol or not
327 // N.B.: These are currently not supported
328 if (type & 0xF0000000)
331 // Set the correct debug symbol base address (TEXT segment)
334 for(j=0; (unsigned)j<dosymi; j++)
335 dbgsymbase += obj_segsize[j][0];
337 switch (type & 0xFF000000)
340 value = tval + dbgsymbase;
345 value = tval + dbgsymbase + value;
350 putlong(symptr + 8, value);
355 // Now make modifications to the symbol value, local or global,
356 // based on the segment sizes of the object file currently being
358 switch (type & T_SEG)
363 value = tbase + tsegoffset + value;
364 putlong(symptr + 8, value);
368 value = dbase + dsegoffset + value;
370 value = dbase + dsegoffset + (value
371 - ofile->o_header.tsize);
373 putlong(symptr + 8, value);
377 value = bbase + bsegoffset + value;
379 value = bbase + bsegoffset
380 + (value - (ofile->o_header.tsize
381 + ofile->o_header.dsize));
383 putlong(symptr + 8, value);
390 // Add to output symbol table if global/extern, or local flag is set
391 if (isglobal(type) || lflag)
393 index = OSTAdd(symend + index, type, value);
397 printf("DoSymbols(): Failed to add symbol '%s' to OST!\n", symend + index);
403 // Increment dosymi processsing
411 // Free up hash memory
413 void FreeHashes(void)
417 for(i=0; i<NBUCKETS; i++)
419 struct HREC * hptr = htable[i];
423 struct HREC * htemp = hptr->h_next;
432 // Add all global and external symbols to the output symbol table
433 // [This is confusing--is it adding globals or locals? common == local!
434 // but then again, we see this in the header:
435 // #define T_COMMON (T_GLOBAL | T_EXTERN) but that could be just bullshit.]
442 for(i=0; i<NBUCKETS; i++)
444 for(hptr=htable[i]; hptr!=NULL; hptr=hptr->h_next)
446 //NO! if (iscommon(hptr->h_type))
447 if (isglobal(hptr->h_type))// || isextern(hptr->h_type))
449 // Skip if in *.a file... (does nothing)
450 //if (hptr->h_ofile->isArchiveFile)
453 //Is this true? Couldn't an absolute be exported???
454 if (hptr->h_type == (T_EXT | T_ABS))
455 hptr->h_type = T_ABS; // Absolutes *can't* be externals
457 if (OSTAdd(hptr->h_sym, hptr->h_type, hptr->h_value) == -1)
468 // Add a symbol's name, type, and value to the OST.
469 // Returns the index of the symbol in OST, or -1 for error.
471 int OSTAdd(char * name, int type, long value)
473 int ost_offset_p, ost_offset_e = 0; // OST table offsets for position calcs
474 int ostresult; // OST index result
475 int slen = strlen(name);
477 // If the OST or OST string table has not been initialised then do so
480 ost = malloc(OST_BLOCK);
481 oststr = malloc(OST_BLOCK);
485 printf("OST memory allocation error.\n");
491 printf("OSTSTR memory allocation error.\n");
495 ost_ptr = ost; // Set OST start pointer
496 ost_end = ost + OST_BLOCK; // Set OST end pointer
498 putlong(oststr, 0x00000004); // Just null long for now
499 oststr_ptr = oststr + 4; // Skip size of str table long (incl null long)
500 putlong(oststr_ptr, 0x00000000); // Null terminating long
501 oststr_end = oststr + OST_BLOCK;
505 // If next symbol record exceeds current allocation then expand symbol
506 // table and/or symbol string table.
507 ost_offset_p = (ost_ptr - ost);
508 ost_offset_e = (ost_end - ost);
510 // 3 x uint32_t (12 bytes)
511 if ((ost_ptr + 12) > ost_end)
513 // We want to allocate the current size of the OST + another block.
514 ost = realloc(ost, ost_offset_e + OST_BLOCK);
518 printf("OST memory reallocation error.\n");
522 ost_ptr = ost + ost_offset_p;
523 ost_end = (ost + ost_offset_e) + OST_BLOCK;
526 ost_offset_p = (oststr_ptr - oststr);
527 ost_offset_e = (oststr_end - oststr);
529 // string length + terminating NULL + uint32_t (terminal long)
530 if ((oststr_ptr + (slen + 1 + 4)) > oststr_end)
532 oststr = realloc(oststr, ost_offset_e + OST_BLOCK);
536 printf("OSTSTR memory reallocation error.\n");
540 oststr_ptr = oststr + ost_offset_p;
541 oststr_end = (oststr + ost_offset_e) + OST_BLOCK;
545 // If this is a debug symbol and the include debug symbol flag (-g) is not
546 // set then do nothing
547 if ((type & 0xF0000000) && !gflag)
553 // Get symbol index in OST, if any (-1 if not found)
554 ostresult = OSTLookup(name);
556 // If the symbol is in the output symbol table and the bflag is set
557 // (don't remove multiply defined locals) and this is not an
558 // external/global symbol *** OR *** the symbol is not in the output
559 // symbol table then add it.
560 if (((ostresult != -1) && bflag && !(type & 0x01000000))
561 || ((ostresult != -1) && gflag && (type & 0xF0000000))
562 || (ostresult == -1))
564 if ((type & 0xF0000000) == 0x40000000)
565 putlong(ost_ptr, 0x00000000); // Zero string table offset for dbg line
567 putlong(ost_ptr, (oststr_ptr - oststr)); // String table offset of symbol string
569 putlong(ost_ptr + 4, type);
570 putlong(ost_ptr + 8, value);
573 // If the symbol type is anything but a debug line information
574 // symbol then write the symbol string to the string table
575 if ((type & 0xF0000000) != 0x40000000)
577 strcpy(oststr_ptr, name); // Put symbol name in string table
578 *(oststr_ptr + slen) = '\0'; // Add null terminating character
579 oststr_ptr += (slen + 1);
580 putlong(oststr_ptr, 0x00000000); // Null terminating long
581 putlong(oststr, (oststr_ptr - oststr)); // Update size of string table
586 printf("OSTAdd: (%s), type=$%08X, val=$%08lX\n", name, type, value);
589 // is ost_index pointing one past?
590 // does this return the same regardless of if its ++n or n++?
591 // no. it returns the value of ost_index *before* it's incremented.
600 // Return the index of a symbol in the output symbol table
601 // N.B.: This is a 1-based index! (though there's no real reason for it to be)
603 int OSTLookup(char * sym)
606 int stro = 4; // Offset in string table
608 for(i=0; i<ost_index; i++)
610 if (strcmp(oststr + stro, sym) == 0)
613 stro += strlen(oststr + stro) + 1;
621 // Add unresolved externs to the output symbol table
622 // N.B.: Only adds unresolved symbols *if* they're not already in the OST
624 int DoUnresolved(void)
626 struct HREC * hptr = unresolved;
628 // Add to OST while unresolved list is valid
631 if (OSTAdd(hptr->h_sym, T_EXT, 0L) == -1)
635 printf("DoUnresolved(): '%s' (%s:$%08X) in OST\n", hptr->h_sym, hptr->h_ofile->o_name, hptr->h_type);
637 struct HREC * htemp = hptr->h_next;
648 // Update object file TEXT and DATA segments based on relocation records. Take
649 // in an OFILE header and flag (T_TEXT, T_DATA) to process. Return (0) is
650 // successful or non-zero (1) if failed.
652 int RelocateSegment(struct OFILE * ofile, int flag)
654 char * symtab; // Start of symbol table
655 char * symbols; // Start of symbols
656 char * sptr; // Start of segment data
657 char * rptr; // Start of segment relocation records
658 unsigned symidx; // Offset to symbol
659 unsigned addr; // Relocation address
660 unsigned rflg; // Relocation flags
661 unsigned olddata; // Old segment data at reloc address
662 unsigned newdata = 0; // New segment data at reloc address
663 unsigned pad; // Temporary to calculate phrase padding
665 char sym[SYMLEN]; // String for symbol name/hash search
666 int ssidx; // Segment size table index
667 unsigned glblreloc; // Global relocation flag
668 unsigned absreloc; // Absolute relocation flag
669 unsigned relreloc; // Relative relocation flag
670 unsigned swcond; // Switch statement condition
671 unsigned relocsize; // Relocation record size
673 // If there is no TEXT relocation data for the selected object file segment
674 // then update the COF TEXT segment offset allowing for the phrase padding
675 if ((flag == T_TEXT) && !ofile->o_header.absrel.reloc.tsize)
677 // TEXT segment size plus padding
678 pad = ((ofile->o_header.tsize + secalign) & ~secalign);
679 textoffset += (ofile->o_header.tsize + (pad - ofile->o_header.tsize));
682 printf("RelocateSegment(%s, TEXT) : No Relocation Data\n", ofile->o_name);
687 // If there is no DATA relocation data for the selected object file segment
688 // then update the COF DATA and BSS segment offsets allowing for the phrase
690 if ((flag == T_DATA) && !ofile->o_header.absrel.reloc.dsize)
692 // DATA segment size plus padding
693 pad = ((ofile->o_header.dsize + secalign) & ~secalign);
694 dataoffset += (ofile->o_header.dsize + (pad - ofile->o_header.dsize));
695 // BSS segment size plus padding
696 pad = ((ofile->o_header.bsize + secalign) & ~secalign);
697 bssoffset += (ofile->o_header.bsize + (pad - ofile->o_header.bsize));
700 printf("RelocateSegment(%s, DATA) : No Relocation Data\n", ofile->o_name);
705 // Verbose mode information
708 printf("RelocateSegment(%s, %s) : Processing Relocation Data\n",
709 ofile->o_name, flag == T_DATA ? "DATA" : "TEXT");
712 // Obtain pointer to start of symbol table
713 symtab = (ofile->o_image + 32 + ofile->o_header.tsize
714 + ofile->o_header.dsize
715 + ofile->o_header.absrel.reloc.tsize
716 + ofile->o_header.absrel.reloc.dsize);
718 // Obtain pointer to start of symbols
719 symbols = symtab + ofile->o_header.ssize;
721 // Obtain pointer to start of TEXT segment
722 sptr = ofile->o_image + 32;
724 // Obtain pointer to start of TEXT relocation records
725 rptr = sptr + (ofile->o_header.tsize + ofile->o_header.dsize);
727 relocsize = ofile->o_header.absrel.reloc.tsize;
730 printf("RELOCSIZE :: %d Records = %d\n", relocsize, relocsize / 8);
732 // Update pointers if DATA relocation records are being processed
735 sptr += ofile->o_header.tsize; // Start of DATA segment
736 rptr += ofile->o_header.absrel.reloc.tsize; // Start of DATA relocation records
737 relocsize = ofile->o_header.absrel.reloc.dsize;
740 // Process each relocation record for the TEXT segment
741 for(i=0; i<(int)relocsize; i+=8)
743 // Obtain both the relocation address and the relocation flags from the
745 addr = getlong(rptr);
746 rflg = getlong(rptr + 4);
747 glblreloc = (rflg & 0x00000010 ? 1 : 0);// Set global relocation flag
748 absreloc = (rflg & 0x00000040 ? 1 : 0); // Set absolute relocation flag
749 relreloc = (rflg & 0x000000A0 ? 1 : 0); // Set relative relocation flag
751 // Additional processing required for global relocations
754 // Obtain the string table index for the relocation symbol, look
755 // for it in the globals hash table to obtain information on that
756 // symbol. For the hash calculation to work correctly it must be
757 // placed in a 'clean' string before looking it up.
758 symidx = getlong(symtab + ((rflg >> 8) * 12));
759 memset(sym, 0, SYMLEN);
760 strcpy(sym, symbols + symidx);
761 olddata = newdata = 0; // Initialise old and new segment data
762 ssidx = OSTLookup(sym);
763 newdata = getlong(ost + ((ssidx - 1) * 12) + 8);
766 // Obtain the existing long word segment data and flip words if the
767 // relocation flags indicate it relates to a RISC MOVEI instruction
768 olddata = getlong(sptr + addr);
771 olddata = _SWAPWORD(olddata);
773 // Process record dependant on segment it relates to; TEXT, DATA or
774 // BSS. Construct a new relocated segment long word based on the
775 // required segment base address, the segment data offset in the
776 // resulting COF file and the offsets from the incoming object file.
777 swcond = (rflg & 0xFFFFFF00);
783 case 0x00000200: // Absolute Value
785 case 0x00000400: // TEXT segment relocation record
786 if (flag == T_TEXT) // Is this a TEXT section record?
787 newdata = tbase + textoffset + olddata;
789 newdata = tbase + dataoffset + olddata; // Nope, must be DATA section
792 case 0x00000600: // DATA segment relocation record
793 newdata = dbase + dataoffset
794 + (olddata - ofile->o_header.tsize);
797 case 0x00000800: // BSS segment relocation record
798 newdata = bbase + bssoffset
799 + (olddata - (ofile->o_header.tsize
800 + ofile->o_header.dsize));
811 // Set absolute (long) or relative (word) address of symbol
814 // Flip the new long word segment data if the relocation record
815 // indicated a RISC MOVEI instruction and place the resulting data
816 // back in the COF segment
818 newdata = _SWAPWORD(newdata);
820 putlong(sptr + addr, newdata);
824 putword(sptr + addr, newdata - tbase - addr - ofile->o_tbase);
827 // Shamus: Let's output some info to aid in debugging this crap
834 sprintf(ssiString, " [ssi:%i]", ssidx);
836 printf("RelocateSegment($%08X): %s, $%08X: $%08X => $%08X%s\n", rflg, (glblreloc ? sym : "(LOCAL)"), addr, olddata, getlong(sptr + addr), ssiString);
839 rptr += 8; // Point to the next relocation record
842 // Update the COF segment offset allowing for the phrase padding.
845 // TEXT segment plus padding
846 pad = ((ofile->o_header.tsize + secalign) & ~secalign);
847 textoffset += (ofile->o_header.tsize + (pad - ofile->o_header.tsize));
851 // DATA segment plus padding
852 pad = ((ofile->o_header.dsize + secalign) & ~secalign);
853 dataoffset += (ofile->o_header.dsize + (pad - ofile->o_header.dsize));
854 // BSS segment plus padding
855 pad = ((ofile->o_header.bsize + secalign) & ~secalign);
856 bssoffset += (ofile->o_header.bsize + (pad - ofile->o_header.bsize));
859 // Return value, should always be zero
865 // Add a path character to the end of string 's' if it doesn't already end with
866 // one. The last occurrance of '/' or '\' in the string is assumed to be the
869 // This is fucking shit. We know what the path delimiter is, its FUCKING
870 // DEFINED IN THE FUCKING HEADER. FOR FUCKS SAKE. AND YES, HOPE TO GOD THERE'S
871 // ENOUGH SPACE IN THE PASSED IN BUFFER TO HOLD THE EXTRA CHARACTER!
873 void AppendPathDelimiter(char * s)
876 // And hope to God that there's enough space in the buffer...
881 if (*s == '/' || *s == '\\')
895 int length = strlen(s);
897 if (s[length - 1] != PATH_DELIMITER)
899 s[length] = PATH_DELIMITER;
900 s[length + 1] = 0; // BUFFER OVERFLOW!!!! FFFFFFFFUUUUUUUUUUUU
907 // Try to open "name", "name.o", "${libdir}name", "${libdir}name.o". Return the
908 // handle of the file successfully opened. p_name is updated to point to a
909 // malloc()'ed string which is the name which actually got opened. p_name will
910 // return unchanged if the file can't be found.
912 int TryOpenFile(char ** p_name)
914 char * name = *p_name;
916 // Note that libdir will be an empty string if there is none specified
917 char * tmpbuf = malloc(strlen(name) + strlen(libdir) + 3);
921 printf("TryOpenFile() : out of memory\n");
925 strcpy(tmpbuf, name);
926 int hasdot = (strrchr(tmpbuf, '.') > strrchr(tmpbuf, PATH_DELIMITER));
927 // Try to open file as passed first
928 int fd = open(tmpbuf, _OPEN_FLAGS);
935 // Try to open file with '.o' added
936 strcat(tmpbuf, ".o");
937 fd = open(tmpbuf, _OPEN_FLAGS);
943 // Try the libdir only if the name isn't already anchored
944 // Shamus: WTH, this makes no sense... Why the ':'? Is this a Macintosh??
945 // if (*name != '/' && *name != '\\' && !strchr(name, ':'))
946 if ((*name != PATH_DELIMITER) && (strchr(name, ':') == NULL))
948 strcpy(tmpbuf, libdir);
949 // Add a trailing path char if there isn't one already
950 AppendPathDelimiter(tmpbuf);
951 strcat(tmpbuf, name);
953 if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0)
958 strcat(tmpbuf, ".o");
960 if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0)
965 // Couldn't open file at all
968 // There are worse things... :-P
970 tmpbuf = realloc(tmpbuf, strlen(tmpbuf) + 1);
974 printf("TryOpenFile() : out of memory\n");
984 // Archive File Use, Needs to be Removed [Shamus: NON!]
986 void put_name(struct OFILE * p)
988 int flag = *(p->o_arname);
989 printf("%s%s%s", (flag ? (char *)(p->o_arname) : ""), (flag ? ":" : ""), p->o_name);
994 // Collect file names and handles in a buffer so there is less disk activity.
995 // Call DoFile with flag FALSE for normal object files and archives.
996 // Call it with flag TRUE and a symbol name for include files (-i).
998 int DoFile(char * fname, int incFlag, char * sym)
1000 // Verbose information
1003 printf("DoFile() : `%s' %s", fname, incFlag ? "INCLUDE" : "NORMAL");
1006 printf(" symbol %s", sym);
1011 // Reached maximum file handles
1018 // Attempt to open input file
1019 int fd = TryOpenFile(&fname);
1023 printf("Cannot find input module %s\n", fname);
1027 // The file is open; save its info in the handle and name arrays
1029 name[hd] = fname; // This is the name from TryOpenFile()
1030 hflag[hd] = incFlag;
1035 int temp = strlen(sym); // Get symbol length
1037 // 100 chars is max length of a symbol
1044 // Malloc enough space for two symbols, then build the second one.
1045 // Second one may be one character longer than first
1046 if ((hsym1[hd] = malloc((long)temp + 1)) == NULL
1047 || (hsym2[hd] = malloc((long)temp + 2)) == NULL)
1049 printf("DoFile() : out of memory for include-file symbols\n");
1053 strcpy(hsym1[hd], sym);
1054 strcpy(hsym2[hd], sym);
1060 printf("Last char of %s is already 'x': choose another name\n", sym);
1064 hsym2[hd][99] = 'x';
1068 hsym2[hd][temp] = 'x';
1069 hsym2[hd][temp+1] = '\0';
1073 // Increment next handle index
1081 // Pad TEXT or DATA segment to the requested boundary
1083 int segmentpad(FILE * fd, long segsize, int value)
1089 // Determine the number of padding bytes that are needed
1090 long padsize = (segsize + secalign) & ~secalign;
1091 padsize = padsize - segsize;
1093 // Fill pad array if padding is required
1100 putword(padptr, value);
1104 symoffset += padsize;
1106 // Write padding bytes
1107 if (fwrite(padarray, padsize, 1, fd) != 1)
1116 // Write the output file
1118 int write_ofile(struct OHEADER * header)
1120 unsigned osize; // Object segment size
1121 struct OFILE * otemp; // Object file pointer
1122 int i, j; // Iterators
1123 char himage[0x168]; // Header image (COF = 0xA8)
1124 unsigned tsoff, dsoff, bsoff; // Segment offset values
1125 unsigned index, type, value; // Symbol table index, type and value
1126 short abstype; // ABS symbol type
1127 char symbol[14]; // Symbol record for ABS files
1128 int slen; // Symbol string length
1130 symoffset = 0; // Initialise symbol offset
1132 // Add correct output extension if none
1133 if (strchr(ofile, '.') == NULL)
1136 strcat(ofile, ".cof"); // COF files
1137 else if (aflag && !cflag)
1138 strcat(ofile, ".abs"); // ABS files
1140 strcat(ofile, ".o"); // Object files (partial linking etc)
1143 FILE * fd = fopen(ofile, "wb"); // Attempt to open output file
1147 printf("Can't open output file %s\n", ofile);
1151 // Build the output file header
1152 // Absolute (COF) header
1155 tsoff = dsoff = bsoff = 0xA8; // Initialises segment offsets
1157 // Process each object file segment size to obtain a cumulative segment
1158 // size for both the TEXT and DATA segments
1159 for(i=0; i<(int)obj_index; i++)
1161 dsoff += obj_segsize[i][0]; // Adding TEXT segment sizes
1162 bsoff += obj_segsize[i][0] + obj_segsize[i][1]; // Adding TEXT and DATA segment sizes
1165 // Currently this only builds a COF absolute file. Conditionals and
1166 // additional code will need to be added for ABS and partial linking.
1168 // Build the COF_HDR
1169 putword(himage + 0, 0x0150 ); // Magic Number (0x0150)
1170 putword(himage + 2, 0x0003 ); // Sections Number (3)
1171 putlong(himage + 4, 0x00000000 ); // Date (0L)
1172 putlong(himage + 8, dsoff + header->dsize); // Offset to Symbols Section
1173 putlong(himage + 12, ost_index); // Number of Symbols
1174 putword(himage + 16, 0x001C ); // Size of RUN_HDR (0x1C)
1175 putword(himage + 18, 0x0003 ); // Executable Flags (3)
1177 // Build the RUN_HDR
1178 putlong(himage + 20, 0x00000107 ); // Magic/vstamp
1179 putlong(himage + 24, header->tsize ); // TEXT size in bytes
1180 putlong(himage + 28, header->dsize ); // DATA size in bytes
1181 putlong(himage + 32, header->bsize ); // BSS size in bytes
1182 putlong(himage + 36, tbase ); // Start of executable, normally @TEXT
1183 putlong(himage + 40, tbase ); // @TEXT
1184 putlong(himage + 44, dbase ); // @DATA
1186 // Build the TEXT SEC_HDR
1187 putlong(himage + 48, 0x2E746578 );
1188 putlong(himage + 52, 0x74000000 ); // ".text"
1189 putlong(himage + 56, tbase ); // TEXT START
1190 putlong(himage + 60, tbase ); // TEXT START
1191 putlong(himage + 64, header->tsize ); // TEXT size in bytes
1192 putlong(himage + 68, tsoff ); // Offset to section data in file
1193 putlong(himage + 72, 0x00000000 ); // Offset to section reloc in file (0L)
1194 putlong(himage + 76, 0x00000000 ); // Offset to debug lines structures (0L)
1195 putlong(himage + 80, 0x00000000 ); // Nreloc/nlnno (0L)
1196 putlong(himage + 84, 0x00000020 ); // SEC_FLAGS: STYP_TEXT
1198 // Build the DATA SEC_HDR
1199 putlong(himage + 88, 0x2E646174 );
1200 putlong(himage + 92, 0x61000000 ); // ".data"
1201 putlong(himage + 96, dbase ); // DATA START
1202 putlong(himage + 100, dbase ); // DATA START
1203 putlong(himage + 104, header->dsize ); // DATA size in bytes
1204 putlong(himage + 108, dsoff ); // Offset to section data in file
1205 putlong(himage + 112, 0x00000000 ); // Offset to section reloc in file (0L)
1206 putlong(himage + 116, 0x00000000 ); // Offset to debugging lines structures (0L)
1207 putlong(himage + 120, 0x00000000 ); // Nreloc/nlnno (0L)
1208 putlong(himage + 124, 0x00000040 ); // SEC_FLAGS: STYP_DATA
1210 // Build the BSS SEC_HDR
1211 putlong(himage + 128, 0x2E627373 );
1212 putlong(himage + 132, 0x00000000 ); // ".bss"
1213 putlong(himage + 136, bbase ); // BSS START
1214 putlong(himage + 140, bbase ); // BSS START
1215 putlong(himage + 144, header->bsize ); // BSS size in bytes
1216 putlong(himage + 148, bsoff ); // Offset to section data in file
1217 putlong(himage + 152, 0x00000000 ); // Offset to section reloc in file (0L)
1218 putlong(himage + 156, 0x00000000 ); // Offset to debugging lines structures (0L)
1219 putlong(himage + 160, 0x00000000 ); // Nreloc/nlnno (0L)
1220 putlong(himage + 164, 0x00000080 ); // SEC_FLAGS: STYP_BSS
1222 symoffset = 168; // Update symbol offset
1224 // Absolute (ABS) header
1227 // Build the ABS header
1228 putword(himage + 0, 0x601B ); // Magic Number (0x601B)
1229 putlong(himage + 2, header->tsize ); // TEXT segment size
1230 putlong(himage + 6, header->dsize ); // DATA segment size
1231 putlong(himage + 10, header->bsize ); // BSS segment size
1232 putlong(himage + 14, ost_index * 14 ); // Symbol table size (?)
1233 putlong(himage + 18, 0x00000000 ); //
1234 putlong(himage + 22, tbase ); // TEXT base address
1235 putword(himage + 26, 0xFFFF ); // Flags (?)
1236 putlong(himage + 28, dbase ); // DATA base address
1237 putlong(himage + 32, bbase ); // BSS base address
1239 symoffset = 36; // Update symbol offset
1242 // Write the header, but not if noheaderflag
1243 // Absolute (ABS) header
1247 if (fwrite(himage, 36, 1, fd) != 1)
1250 // Absolute (COF) header
1253 if (fwrite(himage, 168, 1, fd) != 1)
1257 // Write the TEXT segment of each object file
1258 for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1260 osize = otemp->o_header.tsize;
1262 // Write only if segment has size
1266 printf("Writing TEXT Segment of %s\n", otemp->o_name);
1268 if (fwrite(otemp->o_image + 32, osize, 1, fd) != 1)
1271 // Pad to required alignment boundary
1272 if (segmentpad(fd, osize, 0x0000))
1279 // Write the DATA segment of each object file
1280 for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1282 osize = otemp->o_header.dsize;
1284 // Write only if the segment has size
1288 printf("Writing DATA Segment of %s\n", otemp->o_name);
1290 if (fwrite((otemp->o_image + 32 + otemp->o_header.tsize), osize, 1, fd) != 1)
1293 // Pad to required alignment boundary
1294 if (segmentpad(fd, osize, 0))
1303 // Write the symbols table and string table
1304 // Absolute (COF) symbol/string table
1309 if (fwrite(ost, (ost_ptr - ost), 1, fd) != 1)
1312 if (fwrite(oststr, (oststr_ptr - oststr), 1, fd) != 1)
1316 // Absolute (ABS) symbol/string table
1319 // The symbol and string table have been created as part of the
1320 // DoSymbols() function and the output symbol and string tables are
1321 // in COF format. For an ABS file we need to process through this
1322 // to create the 14 character long combined symbol and string
1323 // table. Format of symbol table in ABS: AAAAAAAATTVVVV, where
1324 // (A)=STRING, (T)=TYPE & (V)=VALUE
1326 for(i=0; i<ost_index; i++)
1328 memset(symbol, 0, 14); // Initialise symbol record
1329 abstype = 0; // Initialise ABS symbol type
1330 slen = 0; // Initialise symbol string length
1331 index = getlong(ost + (i * 12)); // Get symbol index
1332 type = getlong((ost + (i * 12)) + 4); // Get symbol type
1334 // Skip debug symbols
1335 if (type & 0xF0000000)
1339 value = getlong((ost + (i * 12)) + 8);
1340 slen = strlen(oststr + index);
1342 // Get symbol string (maximum 8 chars)
1346 *(symbol + j) = *(oststr + index + j);
1350 for(j=0; j<slen; j++)
1351 *(symbol + j) = *(oststr + index + j);
1354 // Modify to ABS symbol type
1357 case 0x02000000: abstype = (short)ABST_DEFINED; break;
1358 case 0x04000000: abstype = (short)ABST_DEFINED | ABST_TEXT; break;
1359 case 0x05000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_TEXT; break;
1360 case 0x06000000: abstype = (short)ABST_DEFINED | ABST_DATA; break;
1361 case 0x07000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_DATA; break;
1362 case 0x08000000: abstype = (short)ABST_DEFINED | ABST_BSS; break;
1363 case 0x09000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_BSS; break;
1365 printf("warning (write_ofile): ABS, cannot determine symbol type ($%08X)\n", type);
1370 putword(symbol + 8, abstype); // Write back new ABS type
1371 putlong(symbol + 10, value); // Write back value
1373 // Write symbol record
1374 if (fwrite(symbol, 14, 1, fd) != 1)
1383 printf("Close error on output file %s\n",ofile);
1390 printf("Write error on output file %s\n", ofile);
1391 fclose(fd); // Try to close output file anyway
1397 // Display the Symbol Load Map
1399 int write_map(struct OHEADER * header)
1401 unsigned i, o; // Inner and outer loop iterators
1402 unsigned c; // Column number
1403 unsigned index; // Symbol string index
1404 unsigned type; // Symbol type
1405 unsigned value; // Symbol value
1406 char * symbol; // Symbol string value
1409 return 0; // Return if no symbols to map
1411 printf("LOAD MAP\n\n");
1413 // Outer loop for each of the symbol areas to map out;
1414 // 0 = NON-RELOCATABLE SYMBOLS
1415 // 1 = TEXT-SEGMENT RELOCATABLE SYMBOLS
1416 // 2 = DATA-SEGMENT RELOCATABLE SYMBOLS
1417 // 3 = BSS-SEGMENT RELOCATABLE SYMBOLS
1420 // Display the correct map header for the symbols being processed
1423 case 0: printf("NON-RELOCATABLE SYMBOLS\n\n"); break;
1424 case 1: printf("TEXT-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1425 case 2: printf("DATA-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1426 case 3: printf("BSS-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1429 c = 0; // Initialise column number
1431 // Inner loop to process each record in the symbol table
1432 for(i=0; i<(unsigned)ost_index; i++)
1434 index = getlong(ost + (i * 12)); // Get symbol string index
1435 type = getlong(ost + (i * 12) + 4); // Get symbol type
1436 value = getlong(ost + (i * 12) + 8); // Get symbol value
1437 symbol = oststr + index; // Get symbol string
1439 // Display only three columns
1446 // If local symbols not included and the type is local then go to
1447 // next symbol record
1448 if (!lflag & !(type & 0x01000000))
1451 // Output each symbol to the display, dependant on type
1455 // Non-relocatable symbols
1456 if (type == 0x02000000 || type == 0x03000000)
1458 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1464 // TEXT segment relocatable symbols
1465 if (type == 0x04000000 || type == 0x05000000)
1467 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1473 // DATA segment relocatble symbols
1474 if (type == 0x06000000 || type == 0x07000000)
1476 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1482 // BSS segment relocatable symbols
1483 if (type == 0x08000000 || type == 0x09000000)
1485 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1501 // Stuff the (long) value of a string into the value argument. RETURNS TRUE if
1502 // the string doesn't parse. Parses only as a hexadecimal string.
1504 int GetHexValue(char * string, int * value)
1508 while (isxdigit(*string))
1510 if (isdigit(*string))
1512 *value = (*value << 4) + (*string++ - '0');
1516 if (isupper(*string))
1517 *string = tolower(*string);
1519 *value = (*value << 4) + ((*string++ - 'a') + 10);
1523 if (*string != '\0')
1525 printf("Invalid hexadecimal value");
1534 // Create one big .o file from the images already in memory, returning a
1535 // pointer to an OHEADER. Note that the oheader is just the header for the
1536 // output (plus some other information). The text, data, and fixups are all
1537 // still in the ofile images hanging off the global `olist'.
1539 struct OHEADER * make_ofile()
1541 unsigned tptr, dptr, bptr; // Bases in runtime model
1542 int ret = 0; // Return value
1543 struct OHEADER * header; // Output header pointer
1545 // Initialize cumulative segment sizes
1546 textsize = datasize = bsssize = 0;
1548 // For each object file, accumulate the sizes of the segments but remove
1549 // those object files which are unused
1550 struct OFILE * oprev = NULL; // Init previous obj file list ptr
1551 struct OFILE * otemp = olist; // Set temp pointer to object file list
1554 while (otemp != NULL)
1556 // UNUSED !!!!! (it's !O_ARCHIVE, so this code executes.)
1557 if (!(otemp->o_flags & O_ARCHIVE))
1559 if ((otemp->o_flags & O_USED) == 0)
1563 printf("Unused object file ");
1565 printf(" discarded.\n");
1569 olist = otemp->o_next;
1571 oprev->o_next = otemp->o_next;
1573 struct OFILE * ohold = otemp;
1575 if (!ohold->isArchiveFile)
1576 free(ohold->o_image);
1578 // Also need to remove them from the obj_* tables too :-P
1579 // N.B.: Would probably be worthwhile to remove crap like this
1580 // and stuff it into the OFILE structure...
1582 printf("»-> removing %s... (index == %i, len == %i)\n", obj_fname[i], i, obj_index - 1);
1586 for(k=i; k<obj_index-1; k++)
1588 memcpy(obj_fname[k], obj_fname[k + 1], FNLEN);
1589 obj_segsize[k][0] = obj_segsize[k + 1][0];
1590 obj_segsize[k][1] = obj_segsize[k + 1][1];
1591 obj_segsize[k][2] = obj_segsize[k + 1][2];
1599 // Increment total of segment sizes ensuring requested
1601 textsize += (otemp->o_header.tsize + secalign) & ~secalign;
1602 datasize += (otemp->o_header.dsize + secalign) & ~secalign;
1603 bsssize += (otemp->o_header.bsize + secalign) & ~secalign;
1608 // Go to next object file list pointer
1609 otemp = otemp->o_next;
1613 // Update base addresses and create symbols _TEXT_E, _DATA_E and _BSS_E
1618 // DATA follows TEXT
1619 dbase = tval + textsize;
1623 bbase = tval + textsize + datasize;
1625 // BSS is independent of DATA
1630 // DATA is independant of TEXT
1635 bbase = dval + datasize;
1637 // BSS is independent of DATA
1641 OSTAdd("_TEXT_E", 0x05000000, tbase + textsize);
1642 OSTAdd("_DATA_E", 0x07000000, dbase + datasize);
1643 OSTAdd("_BSS_E", 0x09000000, bbase + bsssize);
1645 // Place each unresolved symbol in the output symbol table
1646 // N.B.: It only gets here to do this if user passes in -u flag
1647 // [Only used here, once]
1651 // Initialise base addresses
1652 tptr = dptr = bptr = 0;
1654 // For each file, relocate its symbols and add them to the output symbol
1659 while (otemp != NULL)
1661 otemp->o_tbase = tptr;
1663 // Do rest only for non-ARCHIVE markers
1664 if (!(otemp->o_flags & O_ARCHIVE))
1666 otemp->o_dbase = dptr;
1667 otemp->o_bbase = bptr;
1668 tptr += (otemp->o_header.tsize + secalign) & ~secalign;
1669 dptr += (otemp->o_header.dsize + secalign) & ~secalign;
1670 bptr += (otemp->o_header.bsize + secalign) & ~secalign;
1673 // For each symbol, (conditionally) add it to the ost
1674 // For ARCHIVE markers, this adds the symbol for the file & returns
1675 // (Shamus: N.B. it does no such thing ATM)
1676 // [Only used here, once]
1677 if (DoSymbols(otemp))
1680 if (otemp->o_flags & O_ARCHIVE)
1682 // Now that the archive is marked, remove it from list
1684 olist = otemp->o_next;
1686 oprev->o_next = otemp->o_next;
1688 struct OFILE * ohold = otemp;
1691 if (!ohold->isArchiveFile)
1692 free(ohold->o_image);
1701 otemp = otemp->o_next;
1704 // Places all the externs, globals etc into the output symbol table
1705 if (DoCommon() == -1)
1708 // Create a new output file header
1709 header = new_oheader();
1713 printf("make_ofile: out of memory!\n");
1717 // Fill in the output header. Does not match the actual output but values
1718 // used as reference
1719 header->magic = 0x0150; // COF magic number
1720 header->tsize = textsize; // TEXT segment size
1721 header->dsize = datasize; // DATA segment size
1722 header->bsize = bsssize; // BSS segment size
1723 header->ssize = (ost_ptr - ost); // Symbol table size
1724 header->ostbase = ost; // Output symbol table base address
1726 // For each object file, relocate its TEXT and DATA segments. OR the result
1727 // into ret so all files get moved (and errors reported) before returning
1728 // with the error condition
1729 for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1731 if (!(otemp->o_flags & O_ARCHIVE))
1733 ret |= RelocateSegment(otemp, T_TEXT); // TEXT segment relocations
1734 ret |= RelocateSegment(otemp, T_DATA); // DATA segment relocations
1738 // Done with global symbol hash tables
1741 return (ret ? (struct OHEADER *)NULL : header);
1746 // Add symbol to hash list
1748 int AddSymbolToHashList(struct HREC ** hptr, char * sym, struct OFILE * ofile,
1749 long value, int type)
1751 struct HREC * htemp = new_hrec();
1755 printf("Out of memory\n");
1759 // Shamus: Moar testing...
1762 printf("AddSymbolToHashList(): hptr=$%08X, sym=\"%s\", ofile=$%08X, value=$%X, type=$%X\n", hptr, sym, ofile, value, type);
1765 // Populate hash record
1766 memset(htemp->h_sym, 0, SYMLEN);
1767 strcpy(htemp->h_sym, sym);
1768 htemp->h_ofile = ofile;
1769 htemp->h_value = value;
1770 htemp->h_type = type;
1772 // Add new hash to the front of the list (hence the ** for hptr)
1773 htemp->h_next = *hptr;
1781 // Add symbol to the unresolved symbols hash table (really, it's a linked list)
1783 int AddUnresolvedSymbol(char * sym, struct OFILE * ofile)
1786 printf("AddUnresolvedSymbol(%s, %s)\n", sym, ofile->o_name);
1788 return AddSymbolToHashList(&unresolved, sym, ofile, 0L, 0);
1793 // Remove the HREC from the unresolved symbol list, and pass back a pointer
1794 // to the spot where the HREC was.
1796 struct HREC * RemoveUnresolvedSymbol(struct HREC * hrec)
1798 struct HREC * ptr = unresolved;
1799 struct HREC * previous = NULL;
1801 while ((ptr != hrec) && (ptr != NULL))
1811 struct HREC * next = ptr->h_next;
1813 // Remove the head if nothing previous, otherwise, remove what we found
1814 if (previous == NULL)
1817 previous->h_next = next;
1825 // Add symbol to the unresolved symbols hash table
1827 int AddARSymbol(char * sym, struct OFILE * ofile)
1830 printf("AddARSymbol(%s, %s)\n", sym, ofile->o_name);
1832 return AddSymbolToHashList(&arSymbol, sym, ofile, 0L, 0);
1837 // Generate hash value from the 1st 15 characters of the symbol modulo the
1838 // number of buckets in the hash.
1840 int GetHash(char * s)
1842 // For this to be consistent, the symbol MUST be zeroed out beforehand!
1843 // N.B.: strncpy() pads zeroes for us, if the symbol is less than 15 chars.
1847 int i = (c[0] + c[1] + c[2] + c[3] + c[4] + c[5] + c[6] + c[7] + c[8]
1848 + c[9] + c[10] + c[11] + c[12] + c[13] + c[14]) % NBUCKETS;
1854 // Lookup a symbol in the hash table.
1855 // Returns either a pointer to the HREC or NULL if not found.
1857 struct HREC * LookupHREC(char * symbol)
1859 struct HREC * hptr = htable[GetHash(symbol)];
1861 while (hptr != NULL)
1863 //This is utter failure...
1864 // if (symcmp(symbol, hptr->h_sym)) <-- left here for giggles :D - LinkoVitch
1865 // Return hash record pointer if found
1866 if (strcmp(symbol, hptr->h_sym) == 0)
1869 hptr = hptr->h_next;
1877 // Lookup a symbol in the AR symbol table.
1878 // Returns either a pointer to the HREC or NULL if not found.
1880 struct HREC * LookupARHREC(char * symbol)
1882 struct HREC * hptr = arSymbol;//htable[GetHash(symbol)];
1884 while (hptr != NULL)
1886 // Return hash record pointer if found
1887 if (strcmp(symbol, hptr->h_sym) == 0)
1890 hptr = hptr->h_next;
1898 // Add the imported symbols from this file to unresolved, and the global and
1899 // common (???) symbols to the exported hash table.
1901 // Change old-style commons (type == T_EXTERN, value != 0) to new-style ones
1902 // (type == (T_GLOBAL | T_EXTERN)). [??? O_o]
1904 int AddSymbols(struct OFILE * Ofile)
1906 struct HREC * hptr; // Hash record pointer
1909 printf("Add symbols for file %s\n", Ofile->o_name);
1911 // Get base pointer, start of sym fixups
1912 char * ptr = Ofile->o_image + 32
1913 + Ofile->o_header.tsize
1914 + Ofile->o_header.dsize
1915 + Ofile->o_header.absrel.reloc.tsize
1916 + Ofile->o_header.absrel.reloc.dsize;
1917 char * sfix = ptr; // Set symbol fixup pointer
1918 char * sstr = sfix + Ofile->o_header.ssize; // Set symbol table pointer
1919 long nsymbols = Ofile->o_header.ssize / 12; // Obtain number of symbols
1923 long index = getlong(sfix); // Get symbol string index
1924 long type = getlong(sfix + 4); // Get symbol type
1925 long value = getlong(sfix + 8); // Get symbol value
1927 if ((Ofile->isArchiveFile) && !(Ofile->o_flags & O_USED))
1929 if ((type & T_EXT) && (type & (T_SEG | T_ABS)))
1930 if (AddARSymbol(sstr + index, Ofile))
1933 else if (type == T_EXT)
1935 // External symbol that is *not* in the current unit
1936 hptr = LookupHREC(sstr + index);
1939 hptr->h_ofile->o_flags |= O_USED; // Mark .o file as used
1940 // Otherwise add to unresolved list
1943 // Check for built-in externals...
1944 if ((strcmp(sstr + index, "_TEXT_E") != 0)
1945 && (strcmp(sstr + index, "_DATA_E") != 0)
1946 && (strcmp(sstr + index, "_BSS_E") != 0))
1948 if (AddUnresolvedSymbol(sstr + index, Ofile))
1949 return 1; // Error if addition failed
1953 else if ((type & T_EXT) && (type & (T_SEG | T_ABS)))
1956 // Symbol in the current unit that is also EXPORTED
1957 if (DealWithSymbol(sstr + index, type, value, Ofile))
1958 return 1; // Error if addition failed
1960 hptr = LookupHREC(sstr + index);
1962 // Symbol isn't in the table, so try to add it:
1965 if (AddSymbolToHashList(&htable[GetHash(sstr + index)],
1966 sstr + index, Ofile, value, type))
1971 // Symbol already exists, decide what to do about it
1972 if (iscommon(hptr->h_type))
1974 // Mismatch: common came first; warn and keep the global
1977 printf("Warning: %s: global from ", sstr + index);
1979 printf(" used, common from ");
1980 put_name(hptr->h_ofile);
1981 printf(" discarded.\n");
1984 hptr->h_ofile = Ofile;
1985 hptr->h_type = type;
1986 hptr->h_value = value;
1990 // Global exported by another ofile; warn and make this one
1994 printf("Duplicate symbol %s: ", sstr + index);
1995 put_name(hptr->h_ofile);
1998 printf(" discarded\n");
2001 // Set the global in this unit to pure external
2002 // (is this a good idea? what if the other one is a ref to
2004 putlong(sfix + 4, T_EXT);
2010 sfix += 12; // Increment symbol fixup pointer
2011 nsymbols--; // Decrement num of symbols to process
2014 // Success loading symbols
2020 // Process object file for symbols
2022 int DoItem(struct OFILE * obj)
2024 // Allocate memory for object record ptr
2025 struct OFILE * Ofile = new_ofile();
2029 printf("Out of memory while processing %s\n", obj->o_name);
2033 // Starting after all pathnames, etc., copy .o file name to Ofile
2034 char * temp = path_tail(obj->o_name);
2036 // Check filename length
2037 if (strlen(temp) > FNLEN - 1)
2039 printf("File name too long: %s\n", temp);
2043 // Check archive name length
2044 if (strlen(obj->o_arname) > FNLEN - 1)
2046 printf("Archive name too long: %s\n", obj->o_arname);
2050 strcpy(Ofile->o_name, temp); // Store filename
2051 strcpy(Ofile->o_arname, obj->o_arname); // Store archive name
2053 // Initialise object record information
2054 Ofile->o_next = NULL;
2058 Ofile->o_flags = obj->o_flags;
2059 Ofile->o_image = obj->o_image;
2060 Ofile->isArchiveFile = obj->isArchiveFile;
2061 char * ptr = obj->o_image;
2063 // Don't do anything if this is just an ARCHIVE marker, just add the file
2065 // (Shamus: N.B.: it does no such ARCHIVE thing ATM)
2066 if (!(obj->o_flags & O_ARCHIVE))
2068 Ofile->o_header.magic = getlong(ptr);
2069 Ofile->o_header.tsize = getlong(ptr + 4);
2070 Ofile->o_header.dsize = getlong(ptr + 8);
2071 Ofile->o_header.bsize = getlong(ptr + 12);
2072 Ofile->o_header.ssize = getlong(ptr + 16);
2073 Ofile->o_header.absrel.reloc.tsize = getlong(ptr + 24);
2074 Ofile->o_header.absrel.reloc.dsize = getlong(ptr + 28);
2076 // Round BSS off to alignment boundary
2077 Ofile->o_header.bsize = (Ofile->o_header.bsize + secalign) & ~secalign;
2079 if ((Ofile->o_header.dsize & 7) && wflag)
2081 printf("Warning: data segment size of ");
2083 printf(" is not a phrase multiple\n");
2086 // Check for odd segment sizes
2087 if ((Ofile->o_header.tsize & 1) || (Ofile->o_header.dsize & 1)
2088 || (Ofile->o_header.bsize & 1))
2090 printf("Error: odd-sized segment in ");
2092 printf("; link aborted.\n");
2096 if (AddSymbols(Ofile))
2100 // Add this file to the olist
2104 olast->o_next = Ofile;
2112 // Handle items in processing list.
2114 // After loading all objects, archives & include files, we now go and process
2115 // each item on the processing list (plist). Once this is done, we go through
2116 // any unresolved symbols left and see if they have shown up.
2118 int ProcessLists(void)
2120 // Process object file list first (adds symbols from each unit & creates
2122 while (plist != NULL)
2127 struct OFILE * ptemp = plist;
2128 plist = plist->o_next;
2134 // Process the unresolved symbols list. This may involve pulling in symbols
2135 // from any included .a units. Such units are lazy linked by default; we
2136 // generally don't want everything they provide, just what's referenced.
2137 for(uptr=unresolved; uptr!=NULL; )
2140 printf("LookupHREC(%s) => ", uptr->h_sym);
2142 struct HREC * htemp = LookupHREC(uptr->h_sym);
2146 // Found it in the symbol table!
2148 printf("%s in %s (=$%06X)\n", (isglobal(htemp->h_type) ? "global" : "common"), htemp->h_ofile->o_name, htemp->h_value);
2150 // Mark the .o unit that the symbol is in as seen & remove from the
2152 htemp->h_ofile->o_flags |= O_USED;
2153 uptr = RemoveUnresolvedSymbol(uptr);
2160 // Check to see if the unresolved symbol is on the AR symbol list.
2161 htemp = LookupARHREC(uptr->h_sym);
2163 // If the unresolved symbol is in a .o unit that is unused, we can
2164 // drop it; same if the unresolved symbol is in the exported AR
2165 // symbol list. Otherwise, go to the next unresolved symbol.
2166 if (!(uptr->h_ofile->o_flags & O_USED) || (htemp != NULL))
2167 uptr = RemoveUnresolvedSymbol(uptr);
2169 uptr = uptr->h_next;
2171 // Now that we've possibly deleted the symbol from unresolved list
2172 // that was also in the AR list, we add the symbols from this .o
2173 // unit to the symbol table, mark the .o unit as used, and restart
2174 // scanning the unresolved list as there is a good possibility that
2175 // the symbols in the unit we're adding has unresolved symbols as
2179 htemp->h_ofile->o_flags |= O_USED;
2180 AddSymbols(htemp->h_ofile);
2186 // Show files used if the user requests it.
2189 printf("Files used:\n");
2190 struct OFILE * filePtr = olist;
2192 while (filePtr != NULL)
2194 if (filePtr->o_flags & O_USED)
2196 printf(" %s%s%s\n", filePtr->o_name, (filePtr->isArchiveFile ? ":" : ""), (filePtr->isArchiveFile ? filePtr->o_arname : nullStr));
2199 filePtr = filePtr->o_next;
2208 // Extract filename from path
2210 char * path_tail(char * name)
2212 // Find last occurance of PATH_DELIMETER
2213 char * temp = strrchr(name, PATH_DELIMITER);
2215 // Return what was passed in if path delimiter was not found
2224 // Add input file to processing list
2226 int AddToProcessingList(char * ptr, char * fname, char * arname, uint8_t arFile)
2230 // First time object record allocation
2231 plist = new_ofile();
2236 // Next object record allocation
2237 plast->o_next = new_ofile();
2238 plast = plast->o_next;
2243 printf("Out of memory.\n"); // Error if memory allocation fails
2247 fname = path_tail(fname);
2248 arname = path_tail(arname);
2250 if (strlen(fname) > FNLEN - 1)
2252 // Error on excessive filename length
2253 printf("File name too long: %s (sorry!)\n", fname);
2257 if (strlen(arname) > FNLEN - 1)
2259 // Error on excessive filename length
2260 printf("AR file name too long: %s (sorry!)\n", arname);
2264 strcpy(plast->o_name, fname); // Store filename sans path
2265 strcpy(plast->o_arname, arname); // Store archive name sans path
2266 plast->o_image = ptr; // Store data pointer
2267 plast->o_flags = (arFile ? 0 : O_USED); // File is used if NOT in archive
2268 plast->o_next = NULL; // Initialise next record pointer
2269 plast->isArchiveFile = arFile; // Shamus: Temp until can sort it out
2271 return 0; // Return without errors
2276 // Process in binary include files and add them to the processing list. This
2277 // routine takes in the binary file and creates an 'object' file in memory.
2278 // Sym1/Sym2 point to the start and end of data.
2280 // Image size for include files is:
2281 // Header ....... 32 bytes
2282 // Data ......... dsize
2283 // Sym Fixups ... 2 * 12 bytes
2284 // Symbol Size .. 4 bytes (Value to include symbols and terminating null)
2285 // Symbols ...... (strlen(sym1) + 1) + (strlen(sym2) + 1)
2286 // Terminate .... 4 bytes (0x00000000)
2288 int LoadInclude(char * fname, int handle, char * sym1, char * sym2, int segment)
2292 unsigned symtype = 0;
2294 long fsize = FileSize(handle); // Get size of include file
2295 long dsize = (fsize + secalign) & ~secalign; // Align size to boundary
2296 int sym1len = strlen(sym1) + 1; // Get sym1 length + null termination
2297 int sym2len = strlen(sym2) + 1; // Get sym2 length + null termination
2298 long size = 32 + dsize + 24 + 4 + sym1len + sym2len + 4;
2300 // Use calloc so the header & fixups initialize to zero
2301 // Allocate object image memory
2302 if ((ptr = calloc(size, 1)) == NULL)
2304 printf("Out of memory while including %s\n", fname);
2309 // Read in binary data
2310 if (read(handle, ptr + 32, fsize) != fsize)
2312 printf("File read error on %s\n", fname);
2320 strcpy(obj_fname[obj_index], path_tail(fname));
2322 // Build this image's dummy header
2323 putlong(ptr, 0x00000107); // Magic number
2327 putlong(ptr+4, dsize); // Text size
2328 putlong(ptr+8, 0L); // Data size
2329 symtype = 0x05000000;
2330 obj_segsize[obj_index][0] = dsize;
2331 obj_segsize[obj_index][1] = 0;
2332 obj_segsize[obj_index][2] = 0;
2336 putlong(ptr+4, 0L); // Text size
2337 putlong(ptr+8, dsize); // Data size
2338 symtype = 0x07000000;
2339 obj_segsize[obj_index][0] = 0;
2340 obj_segsize[obj_index][1] = dsize;
2341 obj_segsize[obj_index][2] = 0;
2344 obj_index++; // Increment object count
2346 putlong(ptr+12, 0L); // BSS size
2347 putlong(ptr+16, 24); // Symbol table size
2348 putlong(ptr+20, 0L); // Entry point
2349 putlong(ptr+24, 0L); // TEXT relocation size
2350 putlong(ptr+28, 0L); // DATA relocation size
2352 sptr = ptr + 32 + dsize; // Set sptr to symbol table location
2354 putlong(sptr, 4L); // String offset of symbol1
2355 putlong(sptr+4, symtype); // Symbol type
2356 putlong(sptr+8, 0x00000000); // Symbol has no value (START)
2357 putlong(sptr+12, 4L + (sym2len - 1)); // String offset of symbol2
2358 putlong(sptr+16, symtype); // Symbol type
2359 putlong(sptr+20, dsize); // Symbol is data size (END)
2361 sptr = ptr + 32 + dsize + 24; // Set sptr to symbol table size loc
2363 putlong(sptr, sym1len + 4L); // Size of symbol table
2365 sptr = ptr + 32 + dsize + 24 + 4; // Set sptr to symbol table location
2367 for(i=0; i<(sym1len-1); i++) // Write symbol1 to string table
2370 sptr += (sym1len - 1); // Step past symbol string
2371 *sptr = '\0'; // Terminate symbol string
2372 sptr += 1; // Step past termination
2374 for(i=0; i<(sym2len-1); i++) // Write symbol2 to string table
2377 sptr += (sym2len - 1); // Step past symbol string
2378 *sptr = '\0'; // Terminate symbol string
2379 sptr += 1; // Step past termination
2381 putlong(sptr, 0L); // Terminating long for object file
2383 return AddToProcessingList(ptr, fname, nullStr, 0);
2388 // Takes a file name, gets in its image, puts it on plist. The image may
2389 // already be in memory: If so, the ptr arg is non-null. If so, the file is
2390 // already closed. Note that the file is already open (from DoFile()). RETURNS
2391 // a pointer to the OFILE structure for this file, so you can diddle its flags
2392 // (DoFile sets O_USED for files on the command line).
2394 int LoadObject(char * fname, int fd, char * ptr)
2398 long size = FileSize(fd);
2400 // Allocate memory for file data
2405 printf("Out of memory while processing %s\n", fname);
2410 // Read in file data
2411 if (read(fd, ptr, size) != size)
2413 printf("File read error on %s\n", fname);
2419 // SCPCD: get the name of the file instead of all pathname
2420 strcpy(obj_fname[obj_index], path_tail(fname));
2421 obj_segsize[obj_index][0] = (getlong(ptr + 4) + secalign) & ~secalign;
2422 obj_segsize[obj_index][1] = (getlong(ptr + 8) + secalign) & ~secalign;
2423 obj_segsize[obj_index][2] = (getlong(ptr + 12) + secalign) & ~secalign;
2426 close(fd); // Close file
2429 // Now add this image to the list of pending ofiles (plist)
2430 // This routine is shared by LoadInclude after it builds the image
2431 return AddToProcessingList(ptr, fname, nullStr, 0);
2436 // What it says on the tin: check for a .o suffix on the passed in string
2438 uint8_t HasDotOSuffix(char * s)
2440 char * temp = strrchr(s, '.');
2442 if ((temp == NULL) || (strncmp(temp, ".o", 2) != 0))
2450 // Process an ar archive file (*.a)
2452 int LoadArchive(char * fname, int fd)
2454 // Read in the archive file to memory and process
2455 long size = FileSize(fd);
2456 char * ptr = malloc(size);
2457 char * endPtr = ptr + size;
2458 char * longFilenames = NULL;
2462 printf("Out of memory while processing %s\n", fname);
2467 if (read(fd, ptr, size) != size)
2469 printf("File read error on %s\n", fname);
2477 // Save the pointer for later...
2478 arPtr[arIndex++] = ptr;
2479 char objName[FNLEN];
2482 //printf("\nProcessing AR file \"%s\"...\n", fname);
2485 // Loop through all objects in the archive and process them
2488 memset(objName, 0, 17);
2493 // if ((ptr[i] == '/') || (ptr[i] == ' '))
2494 if ((ptr[i] == ' ') && (i != 0))
2500 objName[i] = ptr[i];
2505 if (ptr[48 + i] == ' ')
2511 objSize[i] = ptr[48 + i];
2514 // Check to see if a long filename was requested
2515 if (objName[0] == 0x20)
2517 uint32_t fnSize = atoi(objName + 1);
2519 if (longFilenames != NULL)
2522 char * currentFilename = longFilenames + fnSize;
2524 while (*currentFilename != 0x0A)
2525 objName[i++] = *currentFilename++;
2531 if ((strncmp(objName, "ARFILENAMES/", 12) == 0) || (strncmp(objName, "//", 2) == 0))
2533 longFilenames = ptr + 60;
2535 else if (HasDotOSuffix(objName))
2538 // Strip off any trailing forward slash at end of object name
2539 int lastChar = strlen(objName) - 1;
2541 if (objName[lastChar] == '/')
2542 objName[lastChar] = 0;
2544 //printf("Processing object \"%s\" (size == %i, obj_index == %i)...\n", objName, atoi(objSize), obj_index);
2545 strcpy(obj_fname[obj_index], objName);
2546 obj_segsize[obj_index][0] = (getlong(ptr + 60 + 4) + secalign) & ~secalign;
2547 obj_segsize[obj_index][1] = (getlong(ptr + 60 + 8) + secalign) & ~secalign;
2548 obj_segsize[obj_index][2] = (getlong(ptr + 60 + 12) + secalign) & ~secalign;
2551 if (AddToProcessingList(ptr + 60, objName, fname, 1))
2555 uint32_t size = atoi(objSize);
2556 size += (size & 0x01 ? 1 : 0);
2559 while (ptr < endPtr);
2566 // Process files (*.o, *.a) passed in on the command line
2568 int ProcessFiles(void)
2571 char magic[8]; // Magic header number (4 bytes for *.o, 8 for *.a)
2573 // Process all file handles
2574 for(i=0; i<(int)hd; i++)
2576 // Verbose mode information
2578 printf("Read file %s%s\n", name[i], (hflag[i] ? " (include)" : ""));
2582 // Attempt to read file magic number (OBJECT/ARCHIVE FILES)
2583 if (read(handle[i], magic, 8) != 8)
2585 printf("Error reading file %s\n", name[i]);
2590 lseek(handle[i], 0L, 0); // Reset to start of input file
2592 // Look for RMAC/MAC/GCC (a.out) object files
2593 if ((getlong(magic) & 0xFFFF) == 0x0107)
2595 // Process input object file
2596 if (LoadObject(name[i], handle[i], 0L))
2599 // Otherwise, look for an object archive file
2600 else if (strncmp(magic, "!<arch>\x0A", 8) == 0)
2602 if (LoadArchive(name[i], handle[i]))
2607 // Close file and error
2608 printf("%s is not a supported object or archive file\n", name[i]);
2609 printf("Magic == [%02X][%02X][%02X][%02X]\n", magic[0], magic[1], magic[2], magic[3]);
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
2834 // Segment order is TEXT, DATA, BSS
2835 // Text segment can be 'r' or a value
2836 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2838 ttype = -1; // TEXT segment is relocatable
2840 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2842 printf("Error in text-segment address: cannot be contiguous\n");
2845 else if (GetHexValue(argv[i], &tval))
2847 printf("Error in text-segment address: %s is not 'r' or an address.", argv[i]);
2853 // Data segment can be 'r', 'x' or a value
2854 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2856 dtype = -1; // DATA segment is relocatable
2858 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2860 dtype = -2; // DATA follows TEXT
2862 else if (GetHexValue(argv[i], &dval))
2864 printf("Error in data-segment address: %s is not 'r', 'x' or an address.", argv[i]);
2870 // BSS segment can be 'r', 'x' or a value
2871 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2873 btype = -1; // BSS segment is relocatable
2875 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2877 btype = -3; // BSS follows DATA
2879 else if (GetHexValue(argv[i], &bval))
2881 printf("Error in bss-segment address: %s is not 'r', 'x[td]', or an address.", argv[i]);
2888 case 'B': // Don't remove muliply defined locals
2895 case 'C': // Process a command file
2898 printf("Not enough arguments to -c\n");
2902 if (docmdfile(argv[i++]))
2909 case 'D': // Wait for "return" before exiting
2917 case 'E': // Output COFF (absolute only)
2921 case 'G': // Output source level debugging
2922 printf("\'g\' flag not currently implemented\n");
2925 if (gflag) warn('g', 1);
2930 case 'I': // Include binary file
2933 printf("Not enough arguments to -i\n");
2940 // handle -ii (No truncation)
2941 if ((argv[i-3][2] == 'i') || (argv[i-3][2] == 'I'))
2944 printf("warning: (-ii) COFF format output not specified\n");
2946 // handle -i (Truncation)
2949 if (strlen(isym) > 7)
2953 // Place include files in the DATA segment only
2954 if (DoFile(ifile, DSTSEG_D, isym))
2959 case 'L': // Add local symbols
2966 case 'M': // Produce load symbol map
2973 case 'N': // Output no header to .abs file
2980 case 'O': // Specify an output file
2988 printf("No output filename following -o switch\n");
2992 if (strlen(argv[i]) > FARGSIZE - 5)
2994 printf("Output file name too long (sorry!)\n");
2998 strcpy(ofile, argv[i++]);
3001 case 'R': // Section alignment size
3007 switch (argv[i-1][2])
3009 case 'w': case 'W': secalign = 1; break; // Word alignment
3010 case 'l': case 'L': secalign = 3; break; // Long alignment
3011 case 'p': case 'P': secalign = 7; break; // Phrase alignment
3012 case 'd': case 'D': secalign = 15; break; // Double phrase alignment
3013 case 'q': case 'Q': secalign = 31; break; // Quad phrase alignment
3014 default: secalign = 7; break; // Default phrase alignment
3019 case 'S': // Output only global symbols
3026 case 'U': // Undefined symbols
3030 case 'V': // Verbose information
3031 if (!vflag && !versflag)
3039 case 'W': // Show warnings flag
3046 case 'Z': // Suppress banner flag
3053 printf("unknown option argument `%c'\n", c);
3059 // Not a switch, then process as a file
3060 if (DoFile(argv[i++], 0, NULL))
3065 if (!oflag && vflag)
3067 strcpy(ofile, "output");
3068 printf("Output file is %s[.ext]\n", ofile);
3072 printf("Output file is %s\n", ofile);
3077 // No problems encountered
3083 // Display Version Information
3085 void display_version(void)
3087 if (displaybanner)// && vflag)
3089 printf("\nReboot's Linker for Atari Jaguar\n");
3090 printf("Copyright (c) 199x Allan K. Pratt, 2014 Reboot\n");
3091 printf("V%i.%i.%i %s (%s)\n\n", MAJOR, MINOR, PATCH, __DATE__, PLATFORM);
3097 // Display Command Line Help
3099 void display_help(void)
3102 printf(" %s [-options] file(s)\n", cmdlnexec);
3104 printf("Options:\n");
3105 printf(" -? or -h display usage information\n");
3106 printf(" -a <text> <data> <bss> output absolute file\n");
3107 printf(" hex value: segment address\n");
3108 printf(" r: relocatable segment\n");
3109 printf(" x: contiguous segment\n");
3110 printf(" -b don't remove multiply defined local labels\n");
3111 printf(" -c <fname> add contents of <fname> to command line\n");
3112 printf(" -d wait for key after link\n");
3113 printf(" -e output COF absolute file\n");
3114 printf(" -g output source-level debugging\n");
3115 printf(" -i <fname> <label> incbin <fname> and set <label>\n");
3116 printf(" -l add local symbols\n");
3117 printf(" -m produce load symbols map\n");
3118 printf(" -n output no file header to .abs file\n");
3119 printf(" -o <fname> set output name\n");
3120 printf(" -r<size> section alignment size\n");
3121 printf(" w: word (2 bytes)\n");
3122 printf(" l: long (4 bytes)\n");
3123 printf(" p: phrase (8 bytes, default alignment)\n");
3124 printf(" d: double phrase (16 bytes)\n");
3125 printf(" q: quad phrase (32 bytes)\n");
3126 printf(" -s output only global symbols\n");
3127 printf(" -u allow unresolved symbols (experimental)\n");
3128 printf(" -v set verbose mode\n");
3129 printf(" -w show linker warnings\n");
3130 printf(" -z suppress banner\n");
3143 // Display link status if verbose mode
3145 printf("Link %s.\n", errflag ? "aborted" : "complete");
3147 // Wait for return key if requested
3150 printf("\nPress the [RETURN] key to continue. ");
3151 c = fgets(tempbuf, 128, stdin);
3159 // Determine Processor Endianess
3161 int get_endianess(void)
3164 char * p = (char *)&i;
3167 return ENDIANNESS_LITTLE;
3169 return ENDIANNESS_BIG;
3174 // Application Code Starts Here
3176 int main(int argc, char * argv[])
3178 char * s = NULL; // String pointer for "getenv"
3179 struct HREC * utemp; // Temporary hash record pointer
3180 struct OHEADER * header; // Pointer to output header structure
3182 endian = get_endianess(); // Get processor endianess
3183 cmdlnexec = argv[0]; // Obtain executable name
3184 s = getenv("RLNPATH");
3186 if (s) // Attempt to obtain env variable
3187 strcpy(libdir, s); // Store it if found
3189 // Initialize some vars
3190 tval = dval = bval = 0;
3191 ttype = dtype = btype = 0;
3193 // Parse the command line
3194 if (doargs(argc, argv))
3200 if (!zflag && !vflag)
3202 display_version(); // Display version information
3203 versflag = 1; // We've dumped the version banner
3206 // Load in specified files/objects and add to processing list
3213 // Work in items in processing list & deal with unresolved list
3220 // Check that there is something to link
3227 // Report unresolved externals
3228 if (unresolved != NULL)
3230 printf("UNRESOLVED SYMBOLS\n");
3232 // Don't list them if two -u's or more
3237 while (utemp != NULL)
3239 printf("\t%s (",utemp->h_sym);
3240 put_name(utemp->h_ofile);
3242 utemp = utemp->h_next;
3253 // Make one output file from input objs
3254 header = make_ofile();
3265 printf("TO DO:Partial linking\n");
3268 // Relocatable linking
3271 printf("TO DO:Relocatable linking\n");
3279 printf("Absolute linking ");
3288 printf("Header magic is 0x%04X\n", (unsigned int)header->magic);
3290 if (write_ofile(header))
3294 // Display the loaded symbols map
3296 if (write_map(header))
3299 // Display segment size summary
3303 printf("+---------+----------+----------+----------+\n");
3304 printf("| Segment | TEXT | DATA | BSS |\n");
3305 printf("| Sizes |----------+----------+----------|\n");
3306 printf("| (Hex) | %8X | %8X | %8X |\n", (unsigned int)header->tsize, (unsigned int)header->dsize, (unsigned int)header->bsize);
3307 printf("+---------+----------+----------+----------+\n\n");
3310 //printf("BIG_ENDIAN = %i, LITTLE_ENDIAN = %i\n", BIG_ENDIAN, LITTLE_ENDIAN);