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, uflag; // 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 DoSymbol(struct OFILE * ofile)
177 int type; // Symbol type
178 long value; // Symbol value
179 int index; // Symbol index
181 struct HREC * hptr; // Hash table pointer for globl/extrn
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",
221 // Process each record in the symbol table
222 for(; symptr!=symend; symptr+=12)
224 index = getlong(symptr + 0); // Obtain symbol string index
225 type = getlong(symptr + 4); // Obtain symbol type
226 value = getlong(symptr + 8); // Obtain symbol value
228 // Global/External symbols have a pre-processing stage
229 if (type & 0x01000000)
231 // Obtain the string table index for the relocation symbol, look
232 // for it in the globals hash table to obtain information on that
234 hptr = LookupHREC(symend + index);
238 printf("DoSymbol(): Cannot determine symbol: '%s' (%s)\n",
239 symend + index, ofile->o_name);
243 // Search through object segment size table to obtain segment sizes
244 // for the object that has the required external/global as a local
245 // symbol. As each object is interrogated the segment sizes are
246 // accumulated to ensure the correct offsets are used in the
247 // resulting COF file. This is effectively 'done again' only as we
248 // are working with a different object file.
250 tsegoffset = dsegoffset = bsegoffset = 0;
252 // Search for object filename
253 for(j=0; j<(int)obj_index; j++)
255 if (!strcmp(hptr->h_ofile->o_name, obj_fname[j]))
257 ssidx = j; // Symbol object filename
261 // Accumulate segment sizes
262 tsegoffset += obj_segsize[j][0];
263 dsegoffset += obj_segsize[j][1];
264 bsegoffset += obj_segsize[j][2];
269 printf("DoSymbol(): Cannot get object file segment size: '%s:%s' symbol: '%s' (%s)\n",
270 hptr->h_ofile->o_name, hptr->h_ofile->o_arname,
271 symend + index, ofile->o_name);
275 // Update type with global type
278 // Remove external flag if absolute
279 if (type == (T_EXT | T_ABS))
282 // If the global/external has a value then update that value in
283 // accordance with the segment sizes of the object file it
287 switch (hptr->h_type & 0x0E000000)
291 value = hptr->h_value;
294 value = hptr->h_value - hptr->h_ofile->o_header.tsize;
297 value = hptr->h_value
298 - (hptr->h_ofile->o_header.tsize
299 + hptr->h_ofile->o_header.dsize);
305 // Process and update the value dependent on whether the symbol is a
306 // debug symbol or not
307 // N.B.: These are currently not supported
308 if (type & 0xF0000000)
311 // Set the correct debug symbol base address (TEXT segment)
314 for(j=0; (unsigned)j<dosymi; j++)
315 dbgsymbase += obj_segsize[j][0];
317 switch (type & 0xFF000000)
320 value = tval + dbgsymbase;
325 value = tval + dbgsymbase + value;
330 putlong(symptr + 8, value);
335 // Now make modifications to the symbol value, local or global,
336 // based on the segment sizes of the object file currently being
338 switch (type & T_SEG)
343 value = tbase + tsegoffset + value;
344 putlong(symptr + 8, value);
348 value = dbase + dsegoffset + value;
350 value = dbase + dsegoffset + (value
351 - ofile->o_header.tsize);
353 putlong(symptr + 8, value);
357 value = bbase + bsegoffset + value;
359 value = bbase + bsegoffset
360 + (value - (ofile->o_header.tsize
361 + ofile->o_header.dsize));
363 putlong(symptr + 8, value);
370 // Add to output symbol table if global/extern, or local flag is set
371 if (lflag || !islocal(type))
373 index = OSTAdd(symend + index, type, value);
377 printf("DoSymbol(): Failed to add symbol '%s' to OST!\n", symend + index);
383 // Increment dosymi processsing
391 // Free up hash memory
393 void FreeHashes(void)
397 for(i=0; i<NBUCKETS; i++)
399 struct HREC * hptr = htable[i];
403 struct HREC * htemp = hptr->h_next;
412 // Add all global and external symbols to the output symbol table
413 // [This is confusing--is it adding globals or locals? common == local!
414 // but then again, we see this in the header:
415 // #define T_COMMON (T_GLOBAL | T_EXTERN) but that could be just bullshit.]
422 for(i=0; i<NBUCKETS; i++)
424 for(hptr=htable[i]; hptr!=NULL; hptr=hptr->h_next)
426 //NO! if (iscommon(hptr->h_type))
427 if (isglobal(hptr->h_type))// || isextern(hptr->h_type))
429 // Skip if in *.a file... (does nothing)
430 //if (hptr->h_ofile->isArchiveFile)
433 //Is this true? Couldn't an absolute be exported???
434 if (hptr->h_type == (T_EXT | T_ABS))
435 hptr->h_type = T_ABS; // Absolutes *can't* be externals
437 if (OSTAdd(hptr->h_sym, hptr->h_type, hptr->h_value) == -1)
448 // Add a symbol's name, type, and value to the OST.
449 // Returns the index of the symbol in OST, or -1 for error.
451 int OSTAdd(char * name, int type, long value)
453 int ost_offset_p, ost_offset_e = 0; // OST table offsets for position calcs
454 int ostresult; // OST index result
455 int slen = strlen(name);
457 // If the OST or OST string table has not been initialised then do so
460 ost = malloc(OST_BLOCK);
461 oststr = malloc(OST_BLOCK);
465 printf("OST memory allocation error.\n");
471 printf("OSTSTR memory allocation error.\n");
475 ost_ptr = ost; // Set OST start pointer
476 ost_end = ost + OST_BLOCK; // Set OST end pointer
478 putlong(oststr, 0x00000004); // Just null long for now
479 oststr_ptr = oststr + 4; // Skip size of str table long (incl null long)
480 putlong(oststr_ptr, 0x00000000); // Null terminating long
481 oststr_end = oststr + OST_BLOCK;
485 // If next symbol record exceeds current allocation then expand symbol
486 // table and/or symbol string table.
487 ost_offset_p = (ost_ptr - ost);
488 ost_offset_e = (ost_end - ost);
490 // 3 x uint32_t (12 bytes)
491 if ((ost_ptr + 12) > ost_end)
493 // We want to allocate the current size of the OST + another block.
494 ost = realloc(ost, ost_offset_e + OST_BLOCK);
498 printf("OST memory reallocation error.\n");
502 ost_ptr = ost + ost_offset_p;
503 ost_end = (ost + ost_offset_e) + OST_BLOCK;
506 ost_offset_p = (oststr_ptr - oststr);
507 ost_offset_e = (oststr_end - oststr);
509 // string length + terminating NULL + uint32_t (terminal long)
510 if ((oststr_ptr + (slen + 1 + 4)) > oststr_end)
512 oststr = realloc(oststr, ost_offset_e + OST_BLOCK);
516 printf("OSTSTR memory reallocation error.\n");
520 oststr_ptr = oststr + ost_offset_p;
521 oststr_end = (oststr + ost_offset_e) + OST_BLOCK;
525 // If this is a debug symbol and the include debug symbol flag (-g) is not
526 // set then do nothing
527 if ((type & 0xF0000000) && !gflag)
533 // Get symbol index in OST, if any (-1 if not found)
534 ostresult = OSTLookup(name);
536 // If the symbol is in the output symbol table and the bflag is set
537 // (don't remove multiply defined locals) and this is not an
538 // external/global symbol *** OR *** the symbol is not in the output
539 // symbol table then add it.
540 if (((ostresult != -1) && bflag && !(type & 0x01000000))
541 || ((ostresult != -1) && gflag && (type & 0xF0000000))
542 || (ostresult == -1))
544 if ((type & 0xF0000000) == 0x40000000)
545 putlong(ost_ptr, 0x00000000); // Zero string table offset for dbg line
547 putlong(ost_ptr, (oststr_ptr - oststr)); // String table offset of symbol string
549 putlong(ost_ptr + 4, type);
550 putlong(ost_ptr + 8, value);
553 // If the symbol type is anything but a debug line information
554 // symbol then write the symbol string to the string table
555 if ((type & 0xF0000000) != 0x40000000)
557 strcpy(oststr_ptr, name); // Put symbol name in string table
558 *(oststr_ptr + slen) = '\0'; // Add null terminating character
559 oststr_ptr += (slen + 1);
560 putlong(oststr_ptr, 0x00000000); // Null terminating long
561 putlong(oststr, (oststr_ptr - oststr)); // Update size of string table
566 printf("OSTAdd: (%s), type=$%08X, val=$%08lX\n", name, type, value);
569 // is ost_index pointing one past?
570 // does this return the same regardless of if its ++n or n++?
571 // no. it returns the value of ost_index *before* it's incremented.
580 // Return the index of a symbol in the output symbol table
581 // N.B.: This is a 1-based index! (though there's no real reason for it to be)
583 int OSTLookup(char * sym)
586 int stro = 4; // Offset in string table
588 for(i=0; i<ost_index; i++)
590 if (strcmp(oststr + stro, sym) == 0)
593 stro += strlen(oststr + stro) + 1;
601 // Add unresolved externs to the output symbol table
603 int DoUnresolved(void)
605 struct HREC * hptr = unresolved;
607 // Add to OST while unresolved list is valid
610 if (OSTAdd(hptr->h_sym, T_EXT, 0L) == -1)
614 printf("DoUnresolved(): added %s\n", hptr->h_sym);
616 struct HREC * htemp = hptr->h_next;
627 // Update object file TEXT and DATA segments based on relocation records. Take
628 // in an OFILE header and flag (T_TEXT, T_DATA) to process. Return (0) is
629 // successful or non-zero (1) if failed.
631 int RelocateSegment(struct OFILE * ofile, int flag)
633 char * symtab; // Start of symbol table
634 char * symbols; // Start of symbols
635 char * sptr; // Start of segment data
636 char * rptr; // Start of segment relocation records
637 unsigned symidx; // Offset to symbol
638 unsigned addr; // Relocation address
639 unsigned rflg; // Relocation flags
640 unsigned olddata; // Old segment data at reloc address
641 unsigned newdata = 0; // New segment data at reloc address
642 unsigned pad; // Temporary to calculate phrase padding
644 char sym[SYMLEN]; // String for symbol name/hash search
645 int ssidx; // Segment size table index
646 unsigned glblreloc; // Global relocation flag
647 unsigned absreloc; // Absolute relocation flag
648 unsigned relreloc; // Relative relocation flag
649 unsigned swcond; // Switch statement condition
650 unsigned relocsize; // Relocation record size
652 // If there is no TEXT relocation data for the selected object file segment
653 // then update the COF TEXT segment offset allowing for the phrase padding
654 if ((flag == T_TEXT) && !ofile->o_header.absrel.reloc.tsize)
656 // TEXT segment size plus padding
657 pad = ((ofile->o_header.tsize + secalign) & ~secalign);
658 textoffset += (ofile->o_header.tsize + (pad - ofile->o_header.tsize));
661 printf("RelocateSegment(%s, TEXT) : No Relocation Data\n", ofile->o_name);
666 // If there is no DATA relocation data for the selected object file segment
667 // then update the COF DATA and BSS segment offsets allowing for the phrase
669 if ((flag == T_DATA) && !ofile->o_header.absrel.reloc.dsize)
671 // DATA segment size plus padding
672 pad = ((ofile->o_header.dsize + secalign) & ~secalign);
673 dataoffset += (ofile->o_header.dsize + (pad - ofile->o_header.dsize));
674 // BSS segment size plus padding
675 pad = ((ofile->o_header.bsize + secalign) & ~secalign);
676 bssoffset += (ofile->o_header.bsize + (pad - ofile->o_header.bsize));
679 printf("RelocateSegment(%s, DATA) : No Relocation Data\n", ofile->o_name);
684 // Verbose mode information
687 printf("RelocateSegment(%s, %s) : Processing Relocation Data\n",
688 ofile->o_name, flag == T_DATA ? "DATA" : "TEXT");
691 // Obtain pointer to start of symbol table
692 symtab = (ofile->o_image + 32 + ofile->o_header.tsize
693 + ofile->o_header.dsize
694 + ofile->o_header.absrel.reloc.tsize
695 + ofile->o_header.absrel.reloc.dsize);
697 // Obtain pointer to start of symbols
698 symbols = symtab + ofile->o_header.ssize;
700 // Obtain pointer to start of TEXT segment
701 sptr = ofile->o_image + 32;
703 // Obtain pointer to start of TEXT relocation records
704 rptr = sptr + (ofile->o_header.tsize + ofile->o_header.dsize);
706 relocsize = ofile->o_header.absrel.reloc.tsize;
709 printf("RELOCSIZE :: %d Records = %d\n", relocsize, relocsize / 8);
711 // Update pointers if DATA relocation records are being processed
714 sptr += ofile->o_header.tsize; // Start of DATA segment
715 rptr += ofile->o_header.absrel.reloc.tsize; // Start of DATA relocation records
716 relocsize = ofile->o_header.absrel.reloc.dsize;
719 // Process each relocation record for the TEXT segment
720 for(i=0; i<(int)relocsize; i+=8)
722 // Obtain both the relocation address and the relocation flags from the
724 addr = getlong(rptr);
725 rflg = getlong(rptr + 4);
726 glblreloc = (rflg & 0x00000010 ? 1 : 0);// Set global relocation flag
727 absreloc = (rflg & 0x00000040 ? 1 : 0); // Set absolute relocation flag
728 relreloc = (rflg & 0x000000A0 ? 1 : 0); // Set relative relocation flag
730 // Additional processing required for global relocations
733 // Obtain the string table index for the relocation symbol, look
734 // for it in the globals hash table to obtain information on that
735 // symbol. For the hash calculation to work correctly it must be
736 // placed in a 'clean' string before looking it up.
737 symidx = getlong(symtab + ((rflg >> 8) * 12));
738 memset(sym, 0, SYMLEN);
739 strcpy(sym, symbols + symidx);
740 olddata = newdata = 0; // Initialise old and new segment data
741 ssidx = OSTLookup(sym);
742 newdata = getlong(ost + ((ssidx - 1) * 12) + 8);
745 // Obtain the existing long word segment data and flip words if the
746 // relocation flags indicate it relates to a RISC MOVEI instruction
747 olddata = getlong(sptr + addr);
750 olddata = _SWAPWORD(olddata);
752 // Process record dependant on segment it relates to; TEXT, DATA or
753 // BSS. Construct a new relocated segment long word based on the
754 // required segment base address, the segment data offset in the
755 // resulting COF file and the offsets from the incoming object file.
756 swcond = (rflg & 0xFFFFFF00);
762 case 0x00000200: // Absolute Value
764 case 0x00000400: // TEXT segment relocation record
765 if (flag == T_TEXT) // Is this a TEXT section record?
766 newdata = tbase + textoffset + olddata;
768 newdata = tbase + dataoffset + olddata; // Nope, must be DATA section
771 case 0x00000600: // DATA segment relocation record
772 newdata = dbase + dataoffset
773 + (olddata - ofile->o_header.tsize);
776 case 0x00000800: // BSS segment relocation record
777 newdata = bbase + bssoffset
778 + (olddata - (ofile->o_header.tsize
779 + ofile->o_header.dsize));
790 // Set absolute (long) or relative (word) address of symbol
793 // Flip the new long word segment data if the relocation record
794 // indicated a RISC MOVEI instruction and place the resulting data
795 // back in the COF segment
797 newdata = _SWAPWORD(newdata);
799 putlong(sptr + addr, newdata);
803 putword(sptr + addr, newdata - tbase - addr - ofile->o_tbase);
806 // Shamus: Let's output some info to aid in debugging this crap
813 sprintf(ssiString, " [ssi:%i]", ssidx);
815 printf("RelocateSegment($%08X): %s, $%08X: $%08X => $%08X%s\n", rflg, (glblreloc ? sym : "(LOCAL)"), addr, olddata, getlong(sptr + addr), ssiString);
818 rptr += 8; // Point to the next relocation record
821 // Update the COF segment offset allowing for the phrase padding.
824 // TEXT segment plus padding
825 pad = ((ofile->o_header.tsize + secalign) & ~secalign);
826 textoffset += (ofile->o_header.tsize + (pad - ofile->o_header.tsize));
830 // DATA segment plus padding
831 pad = ((ofile->o_header.dsize + secalign) & ~secalign);
832 dataoffset += (ofile->o_header.dsize + (pad - ofile->o_header.dsize));
833 // BSS segment plus padding
834 pad = ((ofile->o_header.bsize + secalign) & ~secalign);
835 bssoffset += (ofile->o_header.bsize + (pad - ofile->o_header.bsize));
838 // Return value, should always be zero
844 // Add a path character to the end of string 's' if it doesn't already end with
845 // one. The last occurrance of '/' or '\' in the string is assumed to be the
848 // This is fucking shit. We know what the path delimiter is, its FUCKING
849 // DEFINED IN THE FUCKING HEADER. FOR FUCKS SAKE. AND YES, HOPE TO GOD THERE'S
850 // ENOUGH SPACE IN THE PASSED IN BUFFER TO HOLD THE EXTRA CHARACTER!
852 void AppendPathDelimiter(char * s)
855 // And hope to God that there's enough space in the buffer...
860 if (*s == '/' || *s == '\\')
874 int length = strlen(s);
876 if (s[length - 1] != PATH_DELIMITER)
878 s[length] = PATH_DELIMITER;
879 s[length + 1] = 0; // BUFFER OVERFLOW!!!! FFFFFFFFUUUUUUUUUUUU
886 // Try to open "name", "name.o", "${libdir}name", "${libdir}name.o". Return the
887 // handle of the file successfully opened. p_name is updated to point to a
888 // malloc()'ed string which is the name which actually got opened. p_name will
889 // return unchanged if the file can't be found.
891 int TryOpenFile(char ** p_name)
893 char * name = *p_name;
895 // Note that libdir will be an empty string if there is none specified
896 char * tmpbuf = malloc(strlen(name) + strlen(libdir) + 3);
900 printf("TryOpenFile() : out of memory\n");
904 strcpy(tmpbuf, name);
905 int hasdot = (strrchr(tmpbuf, '.') > strrchr(tmpbuf, PATH_DELIMITER));
906 // Try to open file as passed first
907 int fd = open(tmpbuf, _OPEN_FLAGS);
914 // Try to open file with '.o' added
915 strcat(tmpbuf, ".o");
916 fd = open(tmpbuf, _OPEN_FLAGS);
922 // Try the libdir only if the name isn't already anchored
923 // Shamus: WTH, this makes no sense... Why the ':'? Is this a Macintosh??
924 // if (*name != '/' && *name != '\\' && !strchr(name, ':'))
925 if ((*name != PATH_DELIMITER) && (strchr(name, ':') == NULL))
927 strcpy(tmpbuf, libdir);
928 // Add a trailing path char if there isn't one already
929 AppendPathDelimiter(tmpbuf);
930 strcat(tmpbuf, name);
932 if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0)
937 strcat(tmpbuf, ".o");
939 if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0)
944 // Couldn't open file at all
947 // There are worse things... :-P
949 tmpbuf = realloc(tmpbuf, strlen(tmpbuf) + 1);
953 printf("TryOpenFile() : out of memory\n");
963 // Archive File Use, Needs to be Removed [Shamus: NON!]
965 void put_name(struct OFILE * p)
967 int flag = *(p->o_arname);
968 printf("%s%s%s", (flag ? (char *)(p->o_arname) : ""), (flag ? ":" : ""), p->o_name);
973 // Collect file names and handles in a buffer so there is less disk activity.
974 // Call DoFile with flag FALSE for normal object files and archives.
975 // Call it with flag TRUE and a symbol name for include files (-i).
977 int DoFile(char * fname, int incFlag, char * sym)
979 // Verbose information
982 printf("DoFile() : `%s' %s", fname, incFlag ? "INCLUDE" : "NORMAL");
985 printf(" symbol %s", sym);
990 // Reached maximum file handles
997 // Attempt to open input file
998 int fd = TryOpenFile(&fname);
1002 printf("Cannot find input module %s\n", fname);
1006 // The file is open; save its info in the handle and name arrays
1008 name[hd] = fname; // This is the name from TryOpenFile()
1009 hflag[hd] = incFlag;
1014 int temp = strlen(sym); // Get symbol length
1016 // 100 chars is max length of a symbol
1023 // Malloc enough space for two symbols, then build the second one.
1024 // Second one may be one character longer than first
1025 if ((hsym1[hd] = malloc((long)temp + 1)) == NULL
1026 || (hsym2[hd] = malloc((long)temp + 2)) == NULL)
1028 printf("DoFile() : out of memory for include-file symbols\n");
1032 strcpy(hsym1[hd], sym);
1033 strcpy(hsym2[hd], sym);
1039 printf("Last char of %s is already 'x': choose another name\n", sym);
1043 hsym2[hd][99] = 'x';
1047 hsym2[hd][temp] = 'x';
1048 hsym2[hd][temp+1] = '\0';
1052 // Increment next handle index
1060 // Pad TEXT or DATA segment to the requested boundary
1062 int segmentpad(FILE * fd, long segsize, int value)
1068 // Determine the number of padding bytes that are needed
1069 long padsize = (segsize + secalign) & ~secalign;
1070 padsize = padsize - segsize;
1072 // Fill pad array if padding is required
1079 putword(padptr, value);
1083 symoffset += padsize;
1085 // Write padding bytes
1086 if (fwrite(padarray, padsize, 1, fd) != 1)
1095 // Write the output file
1097 int write_ofile(struct OHEADER * header)
1099 unsigned osize; // Object segment size
1100 struct OFILE * otemp; // Object file pointer
1101 int i, j; // Iterators
1102 char himage[0x168]; // Header image (COF = 0xA8)
1103 unsigned tsoff, dsoff, bsoff; // Segment offset values
1104 unsigned index, type, value; // Symbol table index, type and value
1105 short abstype; // ABS symbol type
1106 char symbol[14]; // Symbol record for ABS files
1107 int slen; // Symbol string length
1109 symoffset = 0; // Initialise symbol offset
1111 // Add correct output extension if none
1112 if (strchr(ofile, '.') == NULL)
1115 strcat(ofile, ".cof"); // COF files
1116 else if (aflag && !cflag)
1117 strcat(ofile, ".abs"); // ABS files
1119 strcat(ofile, ".o"); // Object files (partial linking etc)
1122 FILE * fd = fopen(ofile, "wb"); // Attempt to open output file
1126 printf("Can't open output file %s\n", ofile);
1130 // Build the output file header
1131 // Absolute (COF) header
1134 tsoff = dsoff = bsoff = 0xA8; // Initialises segment offsets
1136 // Process each object file segment size to obtain a cumulative segment
1137 // size for both the TEXT and DATA segments
1138 for(i=0; i<(int)obj_index; i++)
1140 dsoff += obj_segsize[i][0]; // Adding TEXT segment sizes
1141 bsoff += obj_segsize[i][0] + obj_segsize[i][1]; // Adding TEXT and DATA segment sizes
1144 // Currently this only builds a COF absolute file. Conditionals and
1145 // additional code will need to be added for ABS and partial linking.
1147 // Build the COF_HDR
1148 putword(himage + 0, 0x0150 ); // Magic Number (0x0150)
1149 putword(himage + 2, 0x0003 ); // Sections Number (3)
1150 putlong(himage + 4, 0x00000000 ); // Date (0L)
1151 putlong(himage + 8, dsoff + header->dsize); // Offset to Symbols Section
1152 putlong(himage + 12, ost_index); // Number of Symbols
1153 putword(himage + 16, 0x001C ); // Size of RUN_HDR (0x1C)
1154 putword(himage + 18, 0x0003 ); // Executable Flags (3)
1156 // Build the RUN_HDR
1157 putlong(himage + 20, 0x00000107 ); // Magic/vstamp
1158 putlong(himage + 24, header->tsize ); // TEXT size in bytes
1159 putlong(himage + 28, header->dsize ); // DATA size in bytes
1160 putlong(himage + 32, header->bsize ); // BSS size in bytes
1161 putlong(himage + 36, tbase ); // Start of executable, normally @TEXT
1162 putlong(himage + 40, tbase ); // @TEXT
1163 putlong(himage + 44, dbase ); // @DATA
1165 // Build the TEXT SEC_HDR
1166 putlong(himage + 48, 0x2E746578 );
1167 putlong(himage + 52, 0x74000000 ); // ".text"
1168 putlong(himage + 56, tbase ); // TEXT START
1169 putlong(himage + 60, tbase ); // TEXT START
1170 putlong(himage + 64, header->tsize ); // TEXT size in bytes
1171 putlong(himage + 68, tsoff ); // Offset to section data in file
1172 putlong(himage + 72, 0x00000000 ); // Offset to section reloc in file (0L)
1173 putlong(himage + 76, 0x00000000 ); // Offset to debug lines structures (0L)
1174 putlong(himage + 80, 0x00000000 ); // Nreloc/nlnno (0L)
1175 putlong(himage + 84, 0x00000020 ); // SEC_FLAGS: STYP_TEXT
1177 // Build the DATA SEC_HDR
1178 putlong(himage + 88, 0x2E646174 );
1179 putlong(himage + 92, 0x61000000 ); // ".data"
1180 putlong(himage + 96, dbase ); // DATA START
1181 putlong(himage + 100, dbase ); // DATA START
1182 putlong(himage + 104, header->dsize ); // DATA size in bytes
1183 putlong(himage + 108, dsoff ); // Offset to section data in file
1184 putlong(himage + 112, 0x00000000 ); // Offset to section reloc in file (0L)
1185 putlong(himage + 116, 0x00000000 ); // Offset to debugging lines structures (0L)
1186 putlong(himage + 120, 0x00000000 ); // Nreloc/nlnno (0L)
1187 putlong(himage + 124, 0x00000040 ); // SEC_FLAGS: STYP_DATA
1189 // Build the BSS SEC_HDR
1190 putlong(himage + 128, 0x2E627373 );
1191 putlong(himage + 132, 0x00000000 ); // ".bss"
1192 putlong(himage + 136, bbase ); // BSS START
1193 putlong(himage + 140, bbase ); // BSS START
1194 putlong(himage + 144, header->bsize ); // BSS size in bytes
1195 putlong(himage + 148, bsoff ); // Offset to section data in file
1196 putlong(himage + 152, 0x00000000 ); // Offset to section reloc in file (0L)
1197 putlong(himage + 156, 0x00000000 ); // Offset to debugging lines structures (0L)
1198 putlong(himage + 160, 0x00000000 ); // Nreloc/nlnno (0L)
1199 putlong(himage + 164, 0x00000080 ); // SEC_FLAGS: STYP_BSS
1201 symoffset = 168; // Update symbol offset
1203 // Absolute (ABS) header
1206 // Build the ABS header
1207 putword(himage + 0, 0x601B ); // Magic Number (0x601B)
1208 putlong(himage + 2, header->tsize ); // TEXT segment size
1209 putlong(himage + 6, header->dsize ); // DATA segment size
1210 putlong(himage + 10, header->bsize ); // BSS segment size
1211 putlong(himage + 14, ost_index * 14 ); // Symbol table size (?)
1212 putlong(himage + 18, 0x00000000 ); //
1213 putlong(himage + 22, tbase ); // TEXT base address
1214 putword(himage + 26, 0xFFFF ); // Flags (?)
1215 putlong(himage + 28, dbase ); // DATA base address
1216 putlong(himage + 32, bbase ); // BSS base address
1218 symoffset = 36; // Update symbol offset
1221 // Write the header, but not if noheaderflag
1222 // Absolute (ABS) header
1226 if (fwrite(himage, 36, 1, fd) != 1)
1229 // Absolute (COF) header
1232 if (fwrite(himage, 168, 1, fd) != 1)
1236 // Write the TEXT segment of each object file
1237 for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1239 osize = otemp->o_header.tsize;
1241 // Write only if segment has size
1245 printf("Writing TEXT Segment of %s\n", otemp->o_name);
1247 if (fwrite(otemp->o_image + 32, osize, 1, fd) != 1)
1250 // Pad to required alignment boundary
1251 if (segmentpad(fd, osize, 0x0000))
1258 // Write the DATA segment of each object file
1259 for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1261 osize = otemp->o_header.dsize;
1263 // Write only if the segment has size
1267 printf("Writing DATA Segment of %s\n", otemp->o_name);
1269 if (fwrite((otemp->o_image + 32 + otemp->o_header.tsize), osize, 1, fd) != 1)
1272 // Pad to required alignment boundary
1273 if (segmentpad(fd, osize, 0))
1282 // Write the symbols table and string table
1283 // Absolute (COF) symbol/string table
1288 if (fwrite(ost, (ost_ptr - ost), 1, fd) != 1)
1291 if (fwrite(oststr, (oststr_ptr - oststr), 1, fd) != 1)
1295 // Absolute (ABS) symbol/string table
1298 // The symbol and string table have been created as part of the
1299 // DoSymbol() function and the output symbol and string tables are
1300 // in COF format. For an ABS file we need to process through this
1301 // to create the 14 character long combined symbol and string
1302 // table. Format of symbol table in ABS: AAAAAAAATTVVVV, where
1303 // (A)=STRING, (T)=TYPE & (V)=VALUE
1305 for(i=0; i<ost_index; i++)
1307 memset(symbol, 0, 14); // Initialise symbol record
1308 abstype = 0; // Initialise ABS symbol type
1309 slen = 0; // Initialise symbol string length
1310 index = getlong(ost + (i * 12)); // Get symbol index
1311 type = getlong((ost + (i * 12)) + 4); // Get symbol type
1313 // Skip debug symbols
1314 if (type & 0xF0000000)
1318 value = getlong((ost + (i * 12)) + 8);
1319 slen = strlen(oststr + index);
1321 // Get symbol string (maximum 8 chars)
1325 *(symbol + j) = *(oststr + index + j);
1329 for(j=0; j<slen; j++)
1330 *(symbol + j) = *(oststr + index + j);
1333 // Modify to ABS symbol type
1336 case 0x02000000: abstype = (short)ABST_DEFINED; break;
1337 case 0x04000000: abstype = (short)ABST_DEFINED | ABST_TEXT; break;
1338 case 0x05000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_TEXT; break;
1339 case 0x06000000: abstype = (short)ABST_DEFINED | ABST_DATA; break;
1340 case 0x07000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_DATA; break;
1341 case 0x08000000: abstype = (short)ABST_DEFINED | ABST_BSS; break;
1342 case 0x09000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_BSS; break;
1344 printf("write_ofile: abs, cannot determine symbol type\n");
1349 putword(symbol + 8, abstype); // Write back new ABS type
1350 putlong(symbol + 10, value); // Write back value
1352 // Write symbol record
1353 if (fwrite(symbol, 14, 1, fd) != 1)
1362 printf("Close error on output file %s\n",ofile);
1369 printf("Write error on output file %s\n", ofile);
1370 fclose(fd); // Try to close output file anyway
1376 // Display the Symbol Load Map
1378 int write_map(struct OHEADER * header)
1380 unsigned i, o; // Inner and outer loop iterators
1381 unsigned c; // Column number
1382 unsigned index; // Symbol string index
1383 unsigned type; // Symbol type
1384 unsigned value; // Symbol value
1385 char * symbol; // Symbol string value
1388 return 0; // Return if no symbols to map
1390 printf("LOAD MAP\n\n");
1392 // Outer loop for each of the symbol areas to map out;
1393 // 0 = NON-RELOCATABLE SYMBOLS
1394 // 1 = TEXT-SEGMENT RELOCATABLE SYMBOLS
1395 // 2 = DATA-SEGMENT RELOCATABLE SYMBOLS
1396 // 3 = BSS-SEGMENT RELOCATABLE SYMBOLS
1399 // Display the correct map header for the symbols being processed
1402 case 0: printf("NON-RELOCATABLE SYMBOLS\n\n"); break;
1403 case 1: printf("TEXT-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1404 case 2: printf("DATA-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1405 case 3: printf("BSS-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1408 c = 0; // Initialise column number
1410 // Inner loop to process each record in the symbol table
1411 for(i=0; i<(unsigned)ost_index; i++)
1413 index = getlong(ost + (i * 12)); // Get symbol string index
1414 type = getlong(ost + (i * 12) + 4); // Get symbol type
1415 value = getlong(ost + (i * 12) + 8); // Get symbol value
1416 symbol = oststr + index; // Get symbol string
1418 // Display only three columns
1425 // If local symbols not included and the type is local then go to
1426 // next symbol record
1427 if (!lflag & !(type & 0x01000000))
1430 // Output each symbol to the display, dependant on type
1434 // Non-relocatable symbols
1435 if (type == 0x02000000 || type == 0x03000000)
1437 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1443 // TEXT segment relocatable symbols
1444 if (type == 0x04000000 || type == 0x05000000)
1446 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1452 // DATA segment relocatble symbols
1453 if (type == 0x06000000 || type == 0x07000000)
1455 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1461 // BSS segment relocatable symbols
1462 if (type == 0x08000000 || type == 0x09000000)
1464 printf("%-8s %c %08X ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1480 // Stuff the (long) value of a string into the value argument. RETURNS TRUE if
1481 // the string doesn't parse. Parses only as a hexadecimal string.
1483 int GetHexValue(char * string, int * value)
1487 while (isxdigit(*string))
1489 if (isdigit(*string))
1491 *value = (*value << 4) + (*string++ - '0');
1495 if (isupper(*string))
1496 *string = tolower(*string);
1498 *value = (*value << 4) + ((*string++ - 'a') + 10);
1502 if (*string != '\0')
1504 printf("Invalid hexadecimal value");
1513 // Create one big .o file from the images already in memory, returning a
1514 // pointer to an OHEADER. Note that the oheader is just the header for the
1515 // output (plus some other information). The text, data, and fixups are all
1516 // still in the ofile images hanging off the global `olist'.
1518 struct OHEADER * make_ofile()
1520 unsigned tptr, dptr, bptr; // Bases in runtime model
1521 int ret = 0; // Return value
1522 struct OHEADER * header; // Output header pointer
1524 // Initialize cumulative segment sizes
1525 textsize = datasize = bsssize = 0;
1527 // For each object file, accumulate the sizes of the segments but remove
1528 // those object files which are unused
1529 struct OFILE * oprev = NULL; // Init previous obj file list ptr
1530 struct OFILE * otemp = olist; // Set temp pointer to object file list
1533 while (otemp != NULL)
1535 // UNUSED !!!!! (it's !O_ARCHIVE, so this code executes.)
1536 if (!(otemp->o_flags & O_ARCHIVE))
1538 if ((otemp->o_flags & O_USED) == 0)
1542 printf("Unused object file ");
1544 printf(" discarded.\n");
1548 olist = otemp->o_next;
1550 oprev->o_next = otemp->o_next;
1552 struct OFILE * ohold = otemp;
1554 if (!ohold->isArchiveFile)
1555 free(ohold->o_image);
1559 // Also need to remove them from the obj_* tables too :-P
1560 // N.B.: Would probably be worthwhile to remove crap like this
1561 // and stuff it into the OFILE structure...
1563 printf("»-> removing %s... (index == %i, len == %i)\n", obj_fname[i], i, obj_index - 1);
1567 for(k=i; k<obj_index-1; k++)
1569 memcpy(obj_fname[k], obj_fname[k + 1], FNLEN);
1570 obj_segsize[k][0] = obj_segsize[k + 1][0];
1571 obj_segsize[k][1] = obj_segsize[k + 1][1];
1572 obj_segsize[k][2] = obj_segsize[k + 1][2];
1580 // Increment total of segment sizes ensuring requested
1582 textsize += (otemp->o_header.tsize + secalign) & ~secalign;
1583 datasize += (otemp->o_header.dsize + secalign) & ~secalign;
1584 bsssize += (otemp->o_header.bsize + secalign) & ~secalign;
1589 // Go to next object file list pointer
1590 otemp = otemp->o_next;
1594 // Update base addresses and create symbols _TEXT_E, _DATA_E and _BSS_E
1596 OSTAdd("_TEXT_E", 0x05000000, tval + textsize);
1600 // DATA follows TEXT
1601 dbase = tval + textsize;
1602 OSTAdd("_DATA_E", 0x07000000, tval + textsize + datasize);
1607 bbase = tval + textsize + datasize;
1608 OSTAdd("_BSS_E", 0x09000000, tval + textsize + datasize + bsssize);
1612 // BSS is independent of DATA
1614 OSTAdd("_BSS_E", 0x09000000, bval + bsssize);
1619 // DATA is independant of TEXT
1621 OSTAdd("_DATA_E", 0x07000000, dval + datasize);
1626 bbase = dval + datasize;
1627 OSTAdd("_BSS_E", 0x09000000, dval + datasize + bsssize);
1631 // BSS is independent of DATA
1633 OSTAdd("_BSS_E", 0x09000000, bval + bsssize);
1637 // Place each unresolved symbol in the output symbol table
1641 // Initialise base addresses
1642 tptr = dptr = bptr = 0;
1644 // For each file, relocate its symbols and add them to the output symbol
1649 while (otemp != NULL)
1651 otemp->o_tbase = tptr;
1653 // Do rest only for non-ARCHIVE markers
1654 if (!(otemp->o_flags & O_ARCHIVE))
1656 otemp->o_dbase = dptr;
1657 otemp->o_bbase = bptr;
1658 tptr += (otemp->o_header.tsize + secalign) & ~secalign;
1659 dptr += (otemp->o_header.dsize + secalign) & ~secalign;
1660 bptr += (otemp->o_header.bsize + secalign) & ~secalign;
1663 // For each symbol, (conditionally) add it to the ost
1664 // For ARCHIVE markers, this adds the symbol for the file & returns
1665 // (Shamus: N.B. it does no such thing ATM)
1666 if (DoSymbol(otemp))
1669 if (otemp->o_flags & O_ARCHIVE)
1671 // Now that the archive is marked, remove it from list
1673 olist = otemp->o_next;
1675 oprev->o_next = otemp->o_next;
1677 struct OFILE * ohold = otemp;
1680 if (!ohold->isArchiveFile)
1681 free(ohold->o_image);
1690 otemp = otemp->o_next;
1693 // Places all the externs, globals etc into the output symbol table
1694 if (DoCommon() == -1)
1697 // Create a new output file header
1698 header = new_oheader();
1702 printf("make_ofile: out of memory!\n");
1706 // Fill in the output header. Does not match the actual output but values
1707 // used as reference
1708 header->magic = 0x0150; // COF magic number
1709 header->tsize = textsize; // TEXT segment size
1710 header->dsize = datasize; // DATA segment size
1711 header->bsize = bsssize; // BSS segment size
1712 header->ssize = (ost_ptr - ost); // Symbol table size
1713 header->ostbase = ost; // Output symbol table base address
1715 // For each object file, relocate its TEXT and DATA segments. OR the result
1716 // into ret so all files get moved (and errors reported) before returning
1717 // with the error condition
1718 for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1720 if (!(otemp->o_flags & O_ARCHIVE))
1722 ret |= RelocateSegment(otemp, T_TEXT); // TEXT segment relocations
1723 ret |= RelocateSegment(otemp, T_DATA); // DATA segment relocations
1727 // Done with global symbol hash tables
1730 return (ret ? (struct OHEADER *)NULL : header);
1735 // Add symbol to hash list
1737 int AddSymbolToHashList(struct HREC ** hptr, char * sym, struct OFILE * ofile,
1738 long value, int type)
1740 struct HREC * htemp = new_hrec();
1744 printf("Out of memory\n");
1748 // Shamus: Moar testing...
1751 printf("AddSymbolToHashList(): hptr=$%08X, sym=\"%s\", ofile=$%08X, value=$%X, type=$%X\n", hptr, sym, ofile, value, type);
1754 // Populate hash record
1755 memset(htemp->h_sym, 0, SYMLEN);
1756 strcpy(htemp->h_sym, sym);
1757 htemp->h_ofile = ofile;
1758 htemp->h_value = value;
1759 htemp->h_type = type;
1761 // Add new hash to the front of the list (hence the ** for hptr)
1762 htemp->h_next = *hptr;
1770 // Add symbol to the unresolved symbols hash table (really, it's a linked list)
1772 int AddUnresolvedSymbol(char * sym, struct OFILE * ofile)
1775 printf("AddUnresolvedSymbol(%s, %s)\n", sym, ofile->o_name);
1777 return AddSymbolToHashList(&unresolved, sym, ofile, 0L, 0);
1782 // Remove the HREC from the unresolved symbol list, and pass back a pointer
1783 // to the spot where the HREC was.
1785 struct HREC * RemoveUnresolvedSymbol(struct HREC * hrec)
1787 struct HREC * ptr = unresolved;
1788 struct HREC * previous = NULL;
1790 while ((ptr != hrec) && (ptr != NULL))
1800 struct HREC * next = ptr->h_next;
1802 // Remove the head if nothing previous, otherwise, remove what we found
1803 if (previous == NULL)
1806 previous->h_next = next;
1814 // Add symbol to the unresolved symbols hash table
1816 int AddARSymbol(char * sym, struct OFILE * ofile)
1819 printf("AddARSymbol(%s, %s)\n", sym, ofile->o_name);
1821 return AddSymbolToHashList(&arSymbol, sym, ofile, 0L, 0);
1826 // Generate hash value from the 1st 15 characters of the symbol modulo the
1827 // number of buckets in the hash.
1829 int GetHash(char * s)
1831 // For this to be consistent, the symbol MUST be zeroed out beforehand!
1832 // N.B.: strncpy() pads zeroes for us, if the symbol is less than 15 chars.
1836 int i = (c[0] + c[1] + c[2] + c[3] + c[4] + c[5] + c[6] + c[7] + c[8]
1837 + c[9] + c[10] + c[11] + c[12] + c[13] + c[14]) % NBUCKETS;
1843 // Lookup a symbol in the hash table.
1844 // Returns either a pointer to the HREC or NULL if not found.
1846 struct HREC * LookupHREC(char * symbol)
1848 struct HREC * hptr = htable[GetHash(symbol)];
1850 while (hptr != NULL)
1852 //This is utter failure...
1853 // if (symcmp(symbol, hptr->h_sym)) <-- left here for giggles :D - LinkoVitch
1854 // Return hash record pointer if found
1855 if (strcmp(symbol, hptr->h_sym) == 0)
1858 hptr = hptr->h_next;
1866 // Lookup a symbol in the AR symbol table.
1867 // Returns either a pointer to the HREC or NULL if not found.
1869 struct HREC * LookupARHREC(char * symbol)
1871 struct HREC * hptr = arSymbol;//htable[GetHash(symbol)];
1873 while (hptr != NULL)
1875 // Return hash record pointer if found
1876 if (strcmp(symbol, hptr->h_sym) == 0)
1879 hptr = hptr->h_next;
1888 // Add symbol to the hash table if it doesn't already exist, otherwise decide
1889 // what to do since it's already defined in another unit.
1891 int DealWithSymbol(char * sym, long type, long value, struct OFILE * ofile)
1893 // Make sure we have a filename...
1894 assert(ofile->o_name[0] != 0);
1898 printf("DealWithSymbol(%s,%s,%lx,", sym, ofile->o_name, value);
1899 printf("%x,%s)\n", (unsigned int)type, (isglobal(type) ? "GLOBAL" : "COMMON"));
1902 // See if the symbol is already in the symbol table...
1903 struct HREC * hptr = LookupHREC(sym);
1906 return AddSymbolToHashList(&htable[GetHash(sym)], sym, ofile, value, type);
1908 // N.B.: The symbol being passed in is *already* been vetted as an
1909 // external, so we have only *two* cases to look for here.
1911 // Symbol is already in table... Figure out how to handle!
1912 if (iscommon(type) && !iscommon(hptr->h_type))
1914 // Mismatch: global came first; warn and keep the global one
1917 printf("Warning: %s: global from ", sym);
1918 put_name(hptr->h_ofile);
1919 printf(" used, common from ");
1921 printf(" discarded.\n");
1925 #warning "!!! WHERE THE FUCK IS THIS WRITING TO?? !!!"
1926 // Wow, just wow. This is writing to the symbol string table when it apparently
1927 // it thinks it's writing to an ABS symbol. This is so wrong, I don't even know
1928 // where to begin...
1929 putword(sym + 8, ABST_EXTERN);
1930 putlong(sym + 10, 0L);
1932 // ??? write what to where?
1935 else if (iscommon(hptr->h_type) && !iscommon(type))
1937 // Mismatch: common came first; warn and keep the global one
1940 printf("Warning: %s: global from ", sym);
1942 printf(" used, common from ");
1943 put_name(hptr->h_ofile);
1944 printf(" discarded.\n");
1947 hptr->h_type = type;
1948 hptr->h_ofile = ofile;
1949 hptr->h_value = value;
1951 // They're both global [WRONG! Passed in one is global]
1952 // [technically, this is correct, as it failed the 1st two checks...
1953 // but it is unclear, so the latter is preferable.]
1954 // else if (!iscommon(type))
1955 //is this now right?? [YES, see above]
1956 else if (!iscommon(type) && !iscommon(hptr->h_type))
1958 // Global exported by another ofile; warn and make this one extern
1961 printf("Duplicate symbol %s: ", sym);
1962 put_name(hptr->h_ofile);
1965 printf(" discarded\n");
1969 #warning "!!! WHERE THE FUCK IS THIS WRITING TO?? !!!"
1970 putword(sym + 8, ABST_EXTERN);
1972 // ??? write what to where?
1975 // They're both common
1978 if (hptr->h_value < value)
1980 hptr->h_value = value;
1981 hptr->h_ofile = ofile;
1985 if (iscommon(hptr->h_type))
1987 // Mismatch: common came first; warn and keep the global one
1990 printf("Warning: %s: global from ", sym);
1992 printf(" used, common from ");
1993 put_name(hptr->h_ofile);
1994 printf(" discarded.\n");
1997 hptr->h_type = type;
1998 hptr->h_ofile = ofile;
1999 hptr->h_value = value;
2003 // Global exported by another ofile; warn and make this one extern
2006 printf("Duplicate symbol %s: ", sym);
2007 put_name(hptr->h_ofile);
2010 printf(" discarded\n");
2014 #warning "!!! WHERE THE FUCK IS THIS WRITING TO?? !!!"
2015 putword(sym + 8, ABST_EXTERN);
2017 // ??? write what to where?
2028 // Add the imported symbols from this file to unresolved, and the global and
2029 // common (???) symbols to the exported hash table.
2031 // Change old-style commons (type == T_EXTERN, value != 0) to new-style ones
2032 // (type == (T_GLOBAL | T_EXTERN)). [??? O_o]
2034 int AddSymbols(struct OFILE * Ofile)
2036 struct HREC * hptr; // Hash record pointer
2039 printf("Add symbols for file %s\n", Ofile->o_name);
2041 // Get base pointer, start of sym fixups
2042 char * ptr = Ofile->o_image + 32
2043 + Ofile->o_header.tsize
2044 + Ofile->o_header.dsize
2045 + Ofile->o_header.absrel.reloc.tsize
2046 + Ofile->o_header.absrel.reloc.dsize;
2047 char * sfix = ptr; // Set symbol fixup pointer
2048 char * sstr = sfix + Ofile->o_header.ssize; // Set symbol table pointer
2049 long nsymbols = Ofile->o_header.ssize / 12; // Obtain number of symbols
2053 long index = getlong(sfix); // Get symbol string index
2054 long type = getlong(sfix + 4); // Get symbol type
2055 long value = getlong(sfix + 8); // Get symbol value
2057 if ((Ofile->isArchiveFile) && !(Ofile->o_flags & O_USED))
2059 if ((type & T_EXT) && (type & (T_SEG | T_ABS)))
2060 if (AddARSymbol(sstr + index, Ofile))
2063 else if (type == T_EXT)
2065 // External symbol that is *not* in the current unit
2066 hptr = LookupHREC(sstr + index);
2069 hptr->h_ofile->o_flags |= O_USED; // Mark .o file as used
2070 // Otherwise add to unresolved list
2071 else if (AddUnresolvedSymbol(sstr + index, Ofile))
2072 return 1; // Error if addition failed
2074 else if ((type & T_EXT) && (type & (T_SEG | T_ABS)))
2077 // Symbol in the current unit that is also EXPORTED
2078 if (DealWithSymbol(sstr + index, type, value, Ofile))
2079 return 1; // Error if addition failed
2081 hptr = LookupHREC(sstr + index);
2083 // Symbol isn't in the table, so try to add it:
2086 if (AddSymbolToHashList(&htable[GetHash(sstr + index)],
2087 sstr + index, Ofile, value, type))
2092 // Symbol already exists, decide what to do about it
2093 if (iscommon(hptr->h_type))
2095 // Mismatch: common came first; warn and keep the global
2098 printf("Warning: %s: global from ", sstr + index);
2100 printf(" used, common from ");
2101 put_name(hptr->h_ofile);
2102 printf(" discarded.\n");
2105 hptr->h_ofile = Ofile;
2106 hptr->h_type = type;
2107 hptr->h_value = value;
2111 // Global exported by another ofile; warn and make this one
2115 printf("Duplicate symbol %s: ", sstr + index);
2116 put_name(hptr->h_ofile);
2119 printf(" discarded\n");
2122 // Set the global in this unit to pure external
2123 // (is this a good idea? what if the other one is a ref to
2125 putlong(sfix + 4, T_EXT);
2131 sfix += 12; // Increment symbol fixup pointer
2132 nsymbols--; // Decrement num of symbols to process
2135 // Success loading symbols
2141 // Process object file for symbols
2143 int DoItem(struct OFILE * obj)
2145 // Allocate memory for object record ptr
2146 struct OFILE * Ofile = new_ofile();
2150 printf("Out of memory while processing %s\n", obj->o_name);
2154 // Starting after all pathnames, etc., copy .o file name to Ofile
2155 char * temp = path_tail(obj->o_name);
2157 // Check filename length
2158 if (strlen(temp) > FNLEN - 1)
2160 printf("File name too long: %s\n", temp);
2164 // Check archive name length
2165 if (strlen(obj->o_arname) > FNLEN - 1)
2167 printf("Archive name too long: %s\n", obj->o_arname);
2171 strcpy(Ofile->o_name, temp); // Store filename
2172 strcpy(Ofile->o_arname, obj->o_arname); // Store archive name
2174 // Initialise object record information
2175 Ofile->o_next = NULL;
2179 Ofile->o_flags = obj->o_flags;
2180 Ofile->o_image = obj->o_image;
2181 Ofile->isArchiveFile = obj->isArchiveFile;
2182 char * ptr = obj->o_image;
2184 // Don't do anything if this is just an ARCHIVE marker, just add the file
2186 // (Shamus: N.B.: it does no such ARCHIVE thing ATM)
2187 if (!(obj->o_flags & O_ARCHIVE))
2189 Ofile->o_header.magic = getlong(ptr);
2190 Ofile->o_header.tsize = getlong(ptr + 4);
2191 Ofile->o_header.dsize = getlong(ptr + 8);
2192 Ofile->o_header.bsize = getlong(ptr + 12);
2193 Ofile->o_header.ssize = getlong(ptr + 16);
2194 Ofile->o_header.absrel.reloc.tsize = getlong(ptr + 24);
2195 Ofile->o_header.absrel.reloc.dsize = getlong(ptr + 28);
2197 // Round BSS off to alignment boundary
2198 Ofile->o_header.bsize = (Ofile->o_header.bsize + secalign) & ~secalign;
2200 if ((Ofile->o_header.dsize & 7) && wflag)
2202 printf("Warning: data segment size of ");
2204 printf(" is not a phrase multiple\n");
2207 // Check for odd segment sizes
2208 if ((Ofile->o_header.tsize & 1) || (Ofile->o_header.dsize & 1)
2209 || (Ofile->o_header.bsize & 1))
2211 printf("Error: odd-sized segment in ");
2213 printf("; link aborted.\n");
2217 if (AddSymbols(Ofile))
2221 // Add this file to the olist
2225 olast->o_next = Ofile;
2233 // Handle items in processing list.
2235 // After loading all objects, archives & include files, we now go and process
2236 // each item on the processing list (plist). Once this is done, we go through
2237 // any unresolved symbols left and see if they have shown up.
2239 int ProcessLists(void)
2241 // Process object file list first (adds symbols from each unit & creates
2243 while (plist != NULL)
2248 struct OFILE * ptemp = plist;
2249 plist = plist->o_next;
2255 // Process the unresolved symbols list. This may involve pulling in symbols
2256 // from any included .a units. Such units are lazy linked by default; we
2257 // generally don't want everything they provide, just what's referenced.
2258 for(uptr=unresolved; uptr!=NULL; )
2261 printf("LookupHREC(%s) => ", uptr->h_sym);
2263 struct HREC * htemp = LookupHREC(uptr->h_sym);
2267 // Found it in the symbol table!
2269 printf("%s in %s (=$%06X)\n", (isglobal(htemp->h_type) ? "global" : "common"), htemp->h_ofile->o_name, htemp->h_value);
2271 // Mark the .o unit that the symbol is in as seen & remove from the
2273 htemp->h_ofile->o_flags |= O_USED;
2274 uptr = RemoveUnresolvedSymbol(uptr);
2281 // Check to see if the unresolved symbol is on the AR symbol list.
2282 htemp = LookupARHREC(uptr->h_sym);
2284 // If the unresolved symbol is in a .o unit that is unused, we can
2285 // drop it; same if the unresolved symbol is in the exported AR
2286 // symbol list. Otherwise, go to the next unresolved symbol.
2287 if (!(uptr->h_ofile->o_flags & O_USED) || (htemp != NULL))
2288 uptr = RemoveUnresolvedSymbol(uptr);
2290 uptr = uptr->h_next;
2292 // Now that we've possibly deleted the symbol from unresolved list
2293 // that was also in the AR list, we add the symbols from this .o
2294 // unit to the symbol table, mark the .o unit as used, and restart
2295 // scanning the unresolved list as there is a good possibility that
2296 // the symbols in the unit we're adding has unresolved symbols as
2300 htemp->h_ofile->o_flags |= O_USED;
2301 AddSymbols(htemp->h_ofile);
2307 // Show files used if the user requests it.
2310 printf("Files used:\n");
2311 struct OFILE * filePtr = olist;
2313 while (filePtr != NULL)
2315 if (filePtr->o_flags & O_USED)
2317 printf(" %s%s%s\n", filePtr->o_name, (filePtr->isArchiveFile ? ":" : ""), (filePtr->isArchiveFile ? filePtr->o_arname : nullStr));
2320 filePtr = filePtr->o_next;
2329 // Extract filename from path
2331 char * path_tail(char * name)
2333 // Find last occurance of PATH_DELIMETER
2334 char * temp = strrchr(name, PATH_DELIMITER);
2336 // Return what was passed in if path delimiter was not found
2345 // Add input file to processing list
2347 int AddToProcessingList(char * ptr, char * fname, char * arname, uint8_t arFile)
2351 // First time object record allocation
2352 plist = new_ofile();
2357 // Next object record allocation
2358 plast->o_next = new_ofile();
2359 plast = plast->o_next;
2364 printf("Out of memory.\n"); // Error if memory allocation fails
2368 fname = path_tail(fname);
2369 arname = path_tail(arname);
2371 if (strlen(fname) > FNLEN - 1)
2373 // Error on excessive filename length
2374 printf("File name too long: %s (sorry!)\n", fname);
2378 if (strlen(arname) > FNLEN - 1)
2380 // Error on excessive filename length
2381 printf("AR file name too long: %s (sorry!)\n", arname);
2385 strcpy(plast->o_name, fname); // Store filename sans path
2386 strcpy(plast->o_arname, arname); // Store archive name sans path
2387 plast->o_image = ptr; // Store data pointer
2388 plast->o_flags = (arFile ? 0 : O_USED); // File is used if NOT in archive
2389 plast->o_next = NULL; // Initialise next record pointer
2390 plast->isArchiveFile = arFile; // Shamus: Temp until can sort it out
2392 return 0; // Return without errors
2397 // Process in binary include files and add them to the processing list. This
2398 // routine takes in the binary file and creates an 'object' file in memory.
2399 // Sym1/Sym2 point to the start and end of data.
2401 // Image size for include files is:
2402 // Header ....... 32 bytes
2403 // Data ......... dsize
2404 // Sym Fixups ... 2 * 12 bytes
2405 // Symbol Size .. 4 bytes (Value to include symbols and terminating null)
2406 // Symbols ...... (strlen(sym1) + 1) + (strlen(sym2) + 1)
2407 // Terminate .... 4 bytes (0x00000000)
2409 int LoadInclude(char * fname, int handle, char * sym1, char * sym2, int segment)
2411 long fsize, dsize, size; // File, DATA segment and image sizes
2412 char * ptr, * sptr; // Data pointers
2414 int sym1len = 0; // Symbol 1 length
2415 int sym2len = 0; // Symbol 2 length
2416 unsigned symtype = 0;
2418 fsize = FileSize(handle); // Get size of include file
2419 dsize = (fsize + secalign) & ~secalign; // Round up to a alignment boundary
2421 sym1len = strlen(sym1) + 1; // Get sym1 length + null termination
2422 sym2len = strlen(sym2) + 1; // Get sym2 length + null termination
2424 size = 32 + dsize + 24 + 4 + sym1len + sym2len + 4;
2426 // Use calloc so the header & fixups initialize to zero
2427 // Allocate object image memory
2428 if ((ptr = calloc(size, 1)) == NULL)
2430 printf("Out of memory while including %s\n", fname);
2435 // Read in binary data
2436 if (read(handle, ptr + 32, fsize) != fsize)
2438 printf("File read error on %s\n", fname);
2446 strcpy(obj_fname[obj_index], path_tail(fname));
2448 // Build this image's dummy header
2449 putlong(ptr, 0x00000107); // Magic number
2453 putlong(ptr+4, dsize); // Text size
2454 putlong(ptr+8, 0L); // Data size
2455 symtype = 0x05000000;
2456 obj_segsize[obj_index][0] = dsize;
2457 obj_segsize[obj_index][1] = 0;
2458 obj_segsize[obj_index][2] = 0;
2462 putlong(ptr+4, 0L); // Text size
2463 putlong(ptr+8, dsize); // Data size
2464 symtype = 0x07000000;
2465 obj_segsize[obj_index][0] = 0;
2466 obj_segsize[obj_index][1] = dsize;
2467 obj_segsize[obj_index][2] = 0;
2470 obj_index++; // Increment object count
2472 putlong(ptr+12, 0L); // BSS size
2473 putlong(ptr+16, 24); // Symbol table size
2474 putlong(ptr+20, 0L); // Entry point
2475 putlong(ptr+24, 0L); // TEXT relocation size
2476 putlong(ptr+28, 0L); // DATA relocation size
2478 sptr = ptr + 32 + dsize; // Set sptr to symbol table location
2480 putlong(sptr, 4L); // String offset of symbol1
2481 putlong(sptr+4, symtype); // Symbol type
2482 putlong(sptr+8, 0x00000000); // Symbol has no value (START)
2483 putlong(sptr+12, 4L + (sym2len - 1)); // String offset of symbol2
2484 putlong(sptr+16, symtype); // Symbol type
2485 putlong(sptr+20, dsize); // Symbol is data size (END)
2487 sptr = ptr + 32 + dsize + 24; // Set sptr to symbol table size loc
2489 putlong(sptr, sym1len + 4L); // Size of symbol table
2491 sptr = ptr + 32 + dsize + 24 + 4; // Set sptr to symbol table location
2493 for(i=0; i<(sym1len-1); i++) // Write symbol1 to string table
2496 sptr += (sym1len - 1); // Step past symbol string
2497 *sptr = '\0'; // Terminate symbol string
2498 sptr += 1; // Step past termination
2500 for(i=0; i<(sym2len-1); i++) // Write symbol2 to string table
2503 sptr += (sym2len - 1); // Step past symbol string
2504 *sptr = '\0'; // Terminate symbol string
2505 sptr += 1; // Step past termination
2507 putlong(sptr, 0L); // Terminating long for object file
2509 return AddToProcessingList(ptr, fname, nullStr, 0);
2514 // Takes a file name, gets in its image, puts it on plist. The image may
2515 // already be in memory: If so, the ptr arg is non-null. If so, the file is
2516 // already closed. Note that the file is already open (from DoFile()). RETURNS
2517 // a pointer to the OFILE structure for this file, so you can diddle its flags
2518 // (DoFile sets O_USED for files on the command line).
2520 int LoadObject(char * fname, int fd, char * ptr)
2524 long size = FileSize(fd);
2526 // Allocate memory for file data
2531 printf("Out of memory while processing %s\n", fname);
2536 // Read in file data
2537 if (read(fd, ptr, size) != size)
2539 printf("File read error on %s\n", fname);
2545 // SCPCD: get the name of the file instead of all pathname
2546 strcpy(obj_fname[obj_index], path_tail(fname));
2547 obj_segsize[obj_index][0] = (getlong(ptr + 4) + secalign) & ~secalign;
2548 obj_segsize[obj_index][1] = (getlong(ptr + 8) + secalign) & ~secalign;
2549 obj_segsize[obj_index][2] = (getlong(ptr + 12) + secalign) & ~secalign;
2552 close(fd); // Close file
2555 // Now add this image to the list of pending ofiles (plist)
2556 // This routine is shared by LoadInclude after it builds the image
2557 return AddToProcessingList(ptr, fname, nullStr, 0);
2562 // What it says on the tin: check for a .o suffix on the passed in string
2564 uint8_t HasDotOSuffix(char * s)
2566 char * temp = strrchr(s, '.');
2568 if ((temp == NULL) || (strncmp(temp, ".o", 2) != 0))
2576 // Process an ar archive file (*.a)
2578 int LoadArchive(char * fname, int fd)
2580 // Read in the archive file to memory and process
2581 long size = FileSize(fd);
2582 char * ptr = malloc(size);
2583 char * endPtr = ptr + size;
2584 char * longFilenames = NULL;
2588 printf("Out of memory while processing %s\n", fname);
2593 if (read(fd, ptr, size) != size)
2595 printf("File read error on %s\n", fname);
2603 // Save the pointer for later...
2604 arPtr[arIndex++] = ptr;
2605 char objName[FNLEN];
2608 //printf("\nProcessing AR file \"%s\"...\n", fname);
2611 // Loop through all objects in the archive and process them
2614 memset(objName, 0, 17);
2619 // if ((ptr[i] == '/') || (ptr[i] == ' '))
2620 if ((ptr[i] == ' ') && (i != 0))
2626 objName[i] = ptr[i];
2631 if (ptr[48 + i] == ' ')
2637 objSize[i] = ptr[48 + i];
2640 // Check to see if a long filename was requested
2641 if (objName[0] == 0x20)
2643 uint32_t fnSize = atoi(objName + 1);
2645 if (longFilenames != NULL)
2648 char * currentFilename = longFilenames + fnSize;
2650 while (*currentFilename != 0x0A)
2651 objName[i++] = *currentFilename++;
2657 if ((strncmp(objName, "ARFILENAMES/", 12) == 0) || (strncmp(objName, "//", 2) == 0))
2659 longFilenames = ptr + 60;
2661 else if (HasDotOSuffix(objName))
2664 // Strip off any trailing forward slash at end of object name
2665 int lastChar = strlen(objName) - 1;
2667 if (objName[lastChar] == '/')
2668 objName[lastChar] = 0;
2670 //printf("Processing object \"%s\" (size == %i, obj_index == %i)...\n", objName, atoi(objSize), obj_index);
2671 strcpy(obj_fname[obj_index], objName);
2672 obj_segsize[obj_index][0] = (getlong(ptr + 60 + 4) + secalign) & ~secalign;
2673 obj_segsize[obj_index][1] = (getlong(ptr + 60 + 8) + secalign) & ~secalign;
2674 obj_segsize[obj_index][2] = (getlong(ptr + 60 + 12) + secalign) & ~secalign;
2677 if (AddToProcessingList(ptr + 60, objName, fname, 1))
2681 uint32_t size = atoi(objSize);
2682 size += (size & 0x01 ? 1 : 0);
2685 while (ptr < endPtr);
2692 // Process files (*.o, *.a) passed in on the command line
2694 int ProcessFiles(void)
2697 char magic[8]; // Magic header number (4 bytes for *.o, 8 for *.a)
2699 // Process all file handles
2700 for(i=0; i<(int)hd; i++)
2702 // Verbose mode information
2704 printf("Read file %s%s\n", name[i], (hflag[i] ? " (include)" : ""));
2708 // Attempt to read file magic number (OBJECT/ARCHIVE FILES)
2709 if (read(handle[i], magic, 8) != 8)
2711 printf("Error reading file %s\n", name[i]);
2716 lseek(handle[i], 0L, 0); // Reset to start of input file
2718 // Look for RMAC/MAC/GCC (a.out) object files
2719 if ((getlong(magic) & 0xFFFF) == 0x0107)
2721 // Process input object file
2722 if (LoadObject(name[i], handle[i], 0L))
2725 // Otherwise, look for an object archive file
2726 else if (strncmp(magic, "!<arch>\x0A", 8) == 0)
2728 if (LoadArchive(name[i], handle[i]))
2733 // Close file and error
2734 printf("%s is not a supported object or archive file\n", name[i]);
2735 printf("Magic == [%02X][%02X][%02X][%02X]\n", magic[0], magic[1], magic[2], magic[3]);
2743 // If hflag[i] is 1, include this in the data segment; if 2, put it
2745 if (LoadInclude(name[i], handle[i], hsym1[i], hsym2[i], hflag[i] - 1))
2750 // Free include, symbol & object handles
2751 for(i=0; i<(int)hd; i++)
2762 // Reset next handle indicator
2769 // Load newargv with pointers to arguments found in the buffer
2771 int parse(char * buf, char * newargv[])
2776 printf("begin parsing\n");
2780 while (*buf && strchr(",\t\n\r\14 ", *buf))
2784 if (*buf == '\0' || *buf == 26)
2788 printf("No commands in command file\n");
2797 /* test for comment */
2800 /* found a comment; skip to next \n and start over */
2801 while (*buf && *buf != '\n')
2809 printf("Too many arguments in command file\n");
2815 while (!strchr(",\t\n\r\14 ", *buf))
2817 if (*buf == '\0' || *buf == 26)
2819 printf("Finished parsing %d args\n", i);
2829 printf("argv[%d] = \"%s\"\n", i, newargv[i]);
2837 // Process in a Link Command File
2839 int docmdfile(char * fname)
2841 int fd; // File descriptor
2842 unsigned size; // Command file size
2843 char * ptr; // Pointer
2844 int newargc; // New argument count
2845 char * (*newargv)[]; // New argument value array
2847 // Verbose information
2849 printf("docmdfile(%s)\n", fname);
2851 // Allocate memory for new argument values
2852 newargv = malloc((long)(sizeof(char *) * MAXARGS));
2856 printf("Out of memory.\n");
2860 // Attempt to open and read in the command file
2863 if ((fd = open(fname, _OPEN_FLAGS)) < 0)
2865 printf("Cannot open command file %s.\n", fname);
2869 size = FileSize(fd);
2871 if ((ptr = malloc(size + 1)) == NULL)
2873 printf("Out of memory.\n");
2878 if (read(fd, ptr, size) != (int)size)
2880 printf("Read error on command file %s.\n", fname);
2885 *(ptr + size) = 0; // Null terminate the buffer
2890 printf("No command filename specified\n");
2894 // Parse the command file
2895 if ((newargc = parse(ptr, *newargv)) == -1)
2900 // Process the inputted flags
2901 if (doargs(newargc, *newargv))
2903 printf("docmdfile: doargs returns TRUE\n");
2915 // Take an Argument List and Parse the Command Line
2917 int doargs(int argc, char * argv[])
2919 int i = 1; // Iterator
2920 int c; // Command line character
2921 char * ifile, * isym; // File name and symbol name for -i
2923 // Parse through option switches & files
2926 // Process command line switches
2927 if (argv[i][0] == '-')
2931 printf("Illegal option argument: %s\n\n", argv[i]);
2936 c = argv[i++][1]; // Get next character in command line
2938 // Process command line switch
2941 case '?': // Display usage information
2948 case 'A': // Set absolute linking on
2954 printf("Not enough arguments to -a\n");
2958 aflag = 1; // Set abs link flag
2959 // Segment order is TEXT, DATA, BSS
2960 // Text segment can be 'r', 'x' or a value
2963 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2965 ttype = -1; // TEXT segment is relocatable
2967 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2969 printf("Error in text-segment address: cannot be contiguous\n");
2972 else if ((ttype = 0), GetHexValue(argv[i], &tval))
2974 printf("Error in text-segment address: %s is not 'r', 'x' or an address.", argv[i]);
2979 // Data segment can be 'r', 'x' or a value
2982 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2984 dtype = -1; // DATA segment is relocatable
2986 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2988 dtype = -2; // DATA follows TEXT
2990 else if ((dtype = 0), GetHexValue(argv[i], &dval))
2992 printf("Error in data-segment address: %s is not 'r', 'x' or an address.", argv[i]);
2999 // BSS segment can be 'r', 'x' or a value
3000 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
3002 btype = -1; // BSS segment is relocatable
3004 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
3006 btype = -3; // BSS follows DATA
3008 else if ((btype = 0), GetHexValue(argv[i], &bval))
3010 printf("Error in bss-segment address: %s is not 'r', 'x[td]', or an address.", argv[i]);
3017 case 'B': // Don't remove muliply defined locals
3024 case 'C': // Process a command file
3027 printf("Not enough arguments to -c\n");
3031 if (docmdfile(argv[i++]))
3038 case 'D': // Wait for "return" before exiting
3046 case 'E': // Output COFF (absolute only)
3050 case 'G': // Output source level debugging
3051 printf("\'g\' flag not currently implemented\n");
3054 if (gflag) warn('g', 1);
3059 case 'I': // Include binary file
3062 printf("Not enough arguments to -i\n");
3069 // handle -ii (No truncation)
3070 if ((argv[i-3][2] == 'i') || (argv[i-3][2] == 'I'))
3073 printf("warning: (-ii) COFF format output not specified\n");
3075 // handle -i (Truncation)
3078 if (strlen(isym) > 7)
3082 // Place include files in the DATA segment only
3083 if (DoFile(ifile, DSTSEG_D, isym))
3088 case 'L': // Add local symbols
3095 case 'M': // Produce load symbol map
3102 case 'N': // Output no header to .abs file
3109 case 'O': // Specify an output file
3117 printf("No output filename following -o switch\n");
3121 if (strlen(argv[i]) > FARGSIZE - 5)
3123 printf("Output file name too long (sorry!)\n");
3127 strcpy(ofile, argv[i++]);
3130 case 'R': // Section alignment size
3136 switch (argv[i-1][2])
3138 case 'w': case 'W': secalign = 1; break; // Word alignment
3139 case 'l': case 'L': secalign = 3; break; // Long alignment
3140 case 'p': case 'P': secalign = 7; break; // Phrase alignment
3141 case 'd': case 'D': secalign = 15; break; // Double phrase alignment
3142 case 'q': case 'Q': secalign = 31; break; // Quad phrase alignment
3143 default: secalign = 7; break; // Default phrase alignment
3148 case 'S': // Output only global symbols
3155 case 'V': // Verbose information
3156 if (!vflag && !versflag)
3164 case 'W': // Show warnings flag
3171 case 'Z': // Suppress banner flag
3178 printf("unknown option argument `%c'\n", c);
3184 // Not a switch, then process as a file
3185 if (DoFile(argv[i++], 0, NULL))
3190 if (!oflag && vflag)
3192 strcpy(ofile, "output");
3193 printf("Output file is %s[.ext]\n", ofile);
3197 printf("Output file is %s\n", ofile);
3202 // No problems encountered
3208 // Display Version Information
3210 void display_version(void)
3212 if (displaybanner)// && vflag)
3214 printf("\nReboot's Linker for Atari Jaguar\n");
3215 printf("Copyright (c) 199x Allan K. Pratt, 2014 Reboot\n");
3216 printf("V%i.%i.%i %s (%s)\n\n", MAJOR, MINOR, PATCH, __DATE__, PLATFORM);
3222 // Display Command Line Help
3224 void display_help(void)
3227 printf(" %s [-options] file(s)\n", cmdlnexec);
3229 printf("Options:\n");
3230 printf(" -? or -h display usage information\n");
3231 printf(" -a <text> <data> <bss> output absolute file\n");
3232 printf(" hex value: segment address\n");
3233 printf(" r: relocatable segment\n");
3234 printf(" x: contiguous segment\n");
3235 printf(" -b don't remove multiply defined local labels\n");
3236 printf(" -c <fname> add contents of <fname> to command line\n");
3237 printf(" -d wait for key after link\n");
3238 printf(" -e output COF absolute file\n");
3239 printf(" -g output source-level debugging\n");
3240 printf(" -i <fname> <label> incbin <fname> and set <label>\n");
3241 printf(" -l add local symbols\n");
3242 printf(" -m produce load symbols map\n");
3243 printf(" -n output no file header to .abs file\n");
3244 printf(" -o <fname> set output name\n");
3245 printf(" -r<size> section alignment size\n");
3246 printf(" w: word (2 bytes)\n");
3247 printf(" l: long (4 bytes)\n");
3248 printf(" p: phrase (8 bytes, default alignment)\n");
3249 printf(" d: double phrase (16 bytes)\n");
3250 printf(" q: quad phrase (32 bytes)\n");
3251 printf(" -s output only global symbols\n");
3252 printf(" -v set verbose mode\n");
3253 printf(" -w show linker warnings\n");
3254 printf(" -z suppress banner\n");
3267 // Display link status if verbose mode
3269 printf("Link %s.\n", errflag ? "aborted" : "complete");
3271 // Wait for return key if requested
3274 printf("\nPress the [RETURN] key to continue. ");
3275 c = fgets(tempbuf, 128, stdin);
3283 // Determine Processor Endianess
3285 int get_endianess(void)
3288 char * p = (char *)&i;
3291 return ENDIANNESS_LITTLE;
3293 return ENDIANNESS_BIG;
3298 // Application Code Starts Here
3300 int main(int argc, char * argv[])
3302 char * s = NULL; // String pointer for "getenv"
3303 struct HREC * utemp; // Temporary hash record pointer
3304 struct OHEADER * header; // Pointer to output header structure
3306 endian = get_endianess(); // Get processor endianess
3307 cmdlnexec = argv[0]; // Obtain executable name
3308 s = getenv("RLNPATH");
3310 if (s) // Attempt to obtain env variable
3311 strcpy(libdir, s); // Store it if found
3313 // Parse the command line
3314 if (doargs(argc, argv))
3320 if (!zflag && !vflag)
3322 display_version(); // Display version information
3323 versflag = 1; // We've dumped the version banner
3326 // Load in specified files/objects and add to processing list
3333 // Work in items in processing list & deal with unresolved list
3340 // Check that there is something to link
3347 // Report unresolved externals
3348 if (unresolved != NULL)
3350 printf("UNRESOLVED SYMBOLS\n");
3352 // Don't list them if two -u's or more
3357 while (utemp != NULL)
3359 printf("\t%s (",utemp->h_sym);
3360 put_name(utemp->h_ofile);
3362 utemp = utemp->h_next;
3373 // Make one output file from input objs
3374 header = make_ofile();
3385 printf("TO DO:Partial linking\n");
3388 // Relocatable linking
3391 printf("TO DO:Relocatable linking\n");
3399 printf("Absolute linking ");
3408 printf("Header magic is 0x%04X\n", (unsigned int)header->magic);
3410 if (write_ofile(header))
3414 // Display the loaded symbols map
3416 if (write_map(header))
3419 // Display segment size summary
3423 printf("+---------+----------+----------+----------+\n");
3424 printf("| Segment | TEXT | DATA | BSS |\n");
3425 printf("| Sizes |----------+----------+----------|\n");
3426 printf("| (Hex) | %8X | %8X | %8X |\n", (unsigned int)header->tsize, (unsigned int)header->dsize, (unsigned int)header->bsize);
3427 printf("+---------+----------+----------+----------+\n\n");
3430 //printf("BIG_ENDIAN = %i, LITTLE_ENDIAN = %i\n", BIG_ENDIAN, LITTLE_ENDIAN);