]> Shamusworld >> Repos - rln/blob - rln.c
And now we have proper lazy linking of AR (*.a) archives.
[rln] / rln.c
1 //
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
5 //
6
7 #include "rln.h"
8
9 unsigned errflag = 0;                           // Error flag, goes TRUE on error
10 unsigned waitflag = 0;                          // Wait for any keypress flag
11 unsigned versflag = 0;                          // Version banner has been shown flag
12 unsigned aflag = 0;                                     // Absolute linking flag
13 unsigned bflag = 0;                                     // Don't remove mulitply def locals flag
14 unsigned cflag = 0;                                     // COF executable
15 unsigned dflag = 0;                                     // Wait for key after link flag
16 unsigned gflag = 0;                                     // Source level debug include flag
17 unsigned lflag = 0;                                     // Add local symbols to output flag
18 unsigned mflag = 0;                                     // Produce symbol load map flag
19 unsigned oflag = 0;                                     // Output filename specified
20 unsigned rflag = 0;                                     // Segment alignment size flag
21 unsigned sflag = 0;                                     // Output only global symbols
22 unsigned vflag = 0;                                     // Verbose flag
23 unsigned wflag = 0;                                     // Show warnings flag
24 unsigned zflag = 0;                                     // Suppress banner flag
25 unsigned pflag, uflag;                          // Unimplemented flags
26 unsigned hd = 0;                                        // Index of next file handle to fill
27 unsigned secalign = 7;                          // Section Alignment (8=phrase)
28 unsigned tbase = 0;                                     // TEXT base address
29 unsigned dbase = 0;                                     // DATA base address
30 unsigned bbase = 0;                                     // BSS base address
31 unsigned textoffset = 0;                        // COF TEXT segment offset
32 unsigned dataoffset = 0;                        // COF DATA segment offset
33 unsigned bssoffset = 0;                         // COF BSS segment offset
34 unsigned displaybanner = 1;                     // Display version banner
35 unsigned symoffset = 0;                         // Symbol table offset in output file
36 unsigned dosymi = 0;                            // Dosym() processing iterator
37 unsigned dbgsymbase = 0;                        // Debug symbol base address
38 //unsigned symtrunc = 0;                        // Symbol truncation -i and -ii
39 int noheaderflag = 0;                           // No header flag for ABS files
40 int hflags;                                                     // Value of the arg to -h option
41 int ttype, dtype, btype;                        // Type flag: 0, -1, -2, -3, -4
42 int tval, dval, bval;                           // Values of these abs bases
43 int hflag[NHANDLES];                            // True for include files
44 int handle[NHANDLES];                           // Open file handles
45 int textsize, datasize, bsssize;        // Cumulative segment sizes
46 char libdir[FARGSIZE * 3];                      // Library directory to search
47 char ofile[FARGSIZE];                           // Output file name (.o)
48 char * name[NHANDLES];                          // Associated file names
49 char * cmdlnexec = NULL;                        // Executable name - pointer to ARGV[0]
50 char * hsym1[SYMLEN];                           // First symbol for include files
51 char * hsym2[SYMLEN];                           // Second symbol for include files
52 struct OFILE * plist = NULL;            // Object image list pointer
53 struct OFILE * plast;                           // Last object image list pointer
54 struct OFILE * olist = NULL;            // Pointer to first object file in list
55 struct OFILE * olast;                           // Pointer to last object file in list
56 char obj_fname[16384][FNLEN];           // Object file names
57 unsigned obj_segsize[16384][3];         // Object file seg sizes; TEXT,DATA,BSS
58 unsigned obj_index = 0;                         // Object file index/count
59 char * arPtr[512];
60 uint32_t arIndex = 0;
61 struct HREC * htable[NBUCKETS];         // Hash table
62 struct HREC * unresolved = NULL;        // Pointer to unresolved hash list
63 char * ost;                                                     // Output symbol table
64 char * ost_ptr;                                         // Output symbol table; current pointer
65 char * ost_end;                                         // Output symbol table; end pointer
66 char * oststr;                                          // Output string table
67 char * oststr_ptr;                                      // Output string table; current pointer
68 char * oststr_end;                                      // Output string table; end pointer
69 int ost_index = 0;                                      // Index of next ost addition
70 int endian;                                                     // Processor endianess
71 uint8_t nullStr[1] = "\x00";            // Empty string
72 struct HREC * arSymbol = NULL;          // Pointer to AR symbol table
73
74 // Some human readable defines for endianess
75 #define ENDIANNESS_BIG     1
76 #define ENDIANNESS_LITTLE  0
77
78 // Function prototypes
79 struct HREC * LookupHREC(char *);
80 char * path_tail(char *);
81 void display_help(void);
82 void display_version(void);
83
84
85 //
86 // Get a long word from memory
87 //
88 uint32_t getlong(uint8_t * src)
89 {
90         uint32_t temp;
91         uint8_t * out = (uint8_t *)&temp;
92
93         if (endian == ENDIANNESS_BIG)
94         {
95                 *out++ = src[0];
96                 *out++ = src[1];
97                 *out++ = src[2];
98                 *out = src[3];
99         }
100         else
101         {
102                 *out++ = src[3];
103                 *out++ = src[2];
104                 *out++ = src[1];
105                 *out = src[0];
106         }
107
108         return temp;
109 }
110
111
112 //
113 // Put a long word into memory
114 //
115 void putlong(uint8_t * dest, uint32_t val)
116 {
117         *dest++ = (uint8_t)(val >> 24);
118         *dest++ = (uint8_t)(val >> 16);
119         *dest++ = (uint8_t)(val >> 8);
120         *dest = (uint8_t)val;
121 }
122
123
124 //
125 // Get a word from memory
126 //
127 uint16_t getword(uint8_t * src)
128 {
129         uint16_t temp;
130         uint8_t * out = (uint8_t *)&temp;
131
132         if (endian == ENDIANNESS_BIG)
133         {
134                 out[0] = src[0];
135                 out[1] = src[1];
136         }
137         else
138         {
139                 out[0] = src[1];
140                 out[1] = src[0];
141         }
142
143         return temp;
144 }
145
146
147 //
148 // Put a word into memory
149 //
150 void putword(uint8_t * dest, uint16_t val)
151 {
152         *dest++ = (uint8_t)(val >> 8);
153         *dest = (uint8_t)val;
154 }
155
156
157 //
158 // Find passed in file's length in bytes
159 // N.B.: This also resets the file's pointer to the start of the file
160 //
161 long FileSize(int fd)
162 {
163         long size = lseek(fd, 0, SEEK_END);
164         lseek(fd, 0, SEEK_SET);
165
166         return size;
167 }
168
169
170 //
171 // For this object file, add symbols to the output symbol table after
172 // relocating them. Returns TRUE if OSTLookup returns an error (-1).
173 //
174 int DoSymbol(struct OFILE * ofile)
175 {
176         int type;                                       // Symbol type
177         long value;                                     // Symbol value
178         int index;                                      // Symbol index
179         int j;                                          // Iterator
180         struct HREC * hptr;                     // Hash table pointer for globl/extrn
181         char sym[SYMLEN];                       // String for symbol name/hash search
182
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);
189
190         // Point to end of symbol record in the object file
191         char * symend = symptr + ofile->o_header.ssize;
192
193         // Search through object segment size table to accumulated segment sizes to
194         // ensure the correct offsets are used in the resulting COF file.
195         int ssidx = -1;
196         unsigned tsegoffset = 0, dsegoffset = 0, bsegoffset = 0;
197
198         // Search for object file name
199         for(j=0; j<(int)obj_index; j++)
200         {
201                 if (!strcmp(ofile->o_name, obj_fname[j]))
202                 {
203                         // Object file name found
204                         ssidx = j;
205                         break;
206                 }
207
208                 // Accumulate segment sizes
209                 tsegoffset += obj_segsize[j][0];
210                 dsegoffset += obj_segsize[j][1];
211                 bsegoffset += obj_segsize[j][2];
212         }
213
214         if (ssidx == -1)
215         {
216                 printf("DoSymbol(): Cannot get object file segment size: %s\n", ofile->o_name);
217                 return 1;
218         }
219
220         // Process each record in the symbol table
221         for(; symptr!=symend; symptr+=12)
222         {
223                 index = getlong(symptr + 0);    // Obtain symbol string index
224                 type  = getlong(symptr + 4);    // Obtain symbol type
225                 value = getlong(symptr + 8);    // Obtain symbol value
226
227                 // Global/External symbols have a pre-processing stage
228                 if (type & 0x01000000)
229                 {
230                         // Obtain the string table index for the relocation symbol, look
231                         // for it in the globals hash table to obtain information on that
232                         // symbol. For the hash calculation to work correctly it must be
233                         // placed in a 'clean' string before looking it up.
234                         memset(sym, 0, SYMLEN);
235                         strcpy(sym, symend + index);
236                         hptr = LookupHREC(sym);
237
238                         if (hptr == NULL)
239                         {
240                                 printf("DoSymbol() : Cannot determine symbol : %s\n", sym);
241                                 return 1;
242                         }
243
244                         // Search through object segment size table to obtain segment sizes
245                         // for the object that has the required external/global as a local
246                         // symbol. As each object is interrogated the segment sizes are
247                         // accumulated to ensure the correct offsets are used in the
248                         // resulting COF file.  This is effectively 'done again' only as we
249                         // are working with a different object file.
250                         ssidx = -1;
251                         tsegoffset = dsegoffset = bsegoffset = 0;
252
253                         // Search for object filename
254                         for(j=0; j<(int)obj_index; j++)
255                         {
256                                 if (!strcmp(hptr->h_ofile->o_name, obj_fname[j]))
257                                 {
258                                         ssidx = j;      // Symbol object filename
259                                         break;
260                                 }
261
262                                 // Accumulate segment sizes
263                                 tsegoffset += obj_segsize[j][0];
264                                 dsegoffset += obj_segsize[j][1];
265                                 bsegoffset += obj_segsize[j][2];
266                         }
267
268                         if (ssidx == -1)
269                         {
270                                 printf("DoSymbol() : Cannot get object file segment size : %s\n", ofile->o_name);
271                                 return 1;
272                         }
273
274                         // Update type with global type
275                         type = hptr->h_type;
276
277                         // Remove external flag if absolute
278                         if (type == (T_EXT | T_ABS))
279                                 type = T_ABS;
280
281                         // If the global/external has a value then update that value in
282                         // accordance with the segment sizes of the object file it
283                         // originates from
284                         if (hptr->h_value)
285                         {
286                                 switch (hptr->h_type & 0x0E000000)
287                                 {
288                                 case T_ABS:
289                                 case T_TEXT:
290                                         value = hptr->h_value;
291                                         break;
292                                 case T_DATA:
293                                         value = hptr->h_value - hptr->h_ofile->o_header.tsize;
294                                         break;
295                                 case T_BSS:
296                                         value = hptr->h_value
297                                                 - (hptr->h_ofile->o_header.tsize
298                                                 + hptr->h_ofile->o_header.dsize);
299                                         break;
300                                 }
301                         }
302                 }
303
304                 // Process and update the value dependent on whether the symbol is a
305                 // debug symbol or not
306                 // N.B.: These are currently not supported
307                 if (type & 0xF0000000)
308                 {
309                         // DEBUG SYMBOL
310                         // Set the correct debug symbol base address (TEXT segment)
311                         dbgsymbase = 0;
312
313                         for(j=0; (unsigned)j<dosymi; j++)
314                                 dbgsymbase += obj_segsize[j][0];
315
316                         switch (type & 0xFF000000)
317                         {
318                         case 0x64000000:
319                                 value = tval + dbgsymbase;
320                                 break;
321                         case 0x44000000:
322                         case 0x46000000:
323                         case 0x48000000:
324                                 value = tval + dbgsymbase + value;
325                         default:
326                                 break;
327                         }
328
329                         putlong(symptr + 8, value);
330                 }
331                 else
332                 {
333                         // NON-DEBUG SYMBOL
334                         // Now make modifications to the symbol value, local or global,
335                         // based on the segment sizes of the object file currently being
336                         // processed.
337                         switch (type & T_SEG)
338                         {
339                         case T_ABS:
340                                 break;
341                         case T_TEXT:
342                                 value = tbase + tsegoffset + value;
343                                 putlong(symptr + 8, value);
344                                 break;
345                         case T_DATA:
346                                 if (type & T_EXT)
347                                         value = dbase + dsegoffset + value;
348                                 else
349                                         value = dbase + dsegoffset + (value
350                                                 - ofile->o_header.tsize);
351
352                                 putlong(symptr + 8, value);
353                                 break;
354                         case T_BSS:
355                                 if (type & T_EXT)
356                                         value = bbase + bsegoffset + value;
357                                 else
358                                         value = bbase + bsegoffset
359                                                 + (value - (ofile->o_header.tsize
360                                                 + ofile->o_header.dsize));
361
362                                 putlong(symptr + 8, value);
363                                 break;
364                         default:
365                                 break;
366                         }
367                 }
368
369                 // Add to output symbol table if global/extern, or local flag is set
370                 if (lflag || !islocal(type))
371                 {
372                         index = OSTAdd(symend + index, type, value);
373
374                         if (index == -1)
375                                 return 1;
376                 }
377         }
378
379         // Increment DoSymbol() processsing
380         dosymi++;
381
382         return 0;
383 }
384
385
386 //
387 // Free up hash memory
388 //
389 void FreeHashes(void)
390 {
391         int i;
392
393         for(i=0; i<NBUCKETS; i++)
394         {
395                 struct HREC * hptr = htable[i];
396
397                 while (hptr)
398                 {
399                         struct HREC * htemp = hptr->h_next;
400                         free(hptr);
401                         hptr = htemp;
402                 }
403         }
404 }
405
406
407 //
408 // Add all global and external symbols to the output symbol table
409 // [This is confusing--is it adding globals or locals? common == local!
410 //  but then again, we see this in the header:
411 //  #define T_COMMON  (T_GLOBAL | T_EXTERN)]
412 //
413 long DoCommon(void)
414 {
415         struct HREC * hptr;
416         int i;
417
418         for(i=0; i<NBUCKETS; i++)
419         {
420                 for(hptr=htable[i]; hptr!=NULL; hptr=hptr->h_next)
421                 {
422 //NO!                   if (iscommon(hptr->h_type))
423                         if (isglobal(hptr->h_type))// || isextern(hptr->h_type))
424                         {
425 // Skip if in *.a file... (does nothing)
426 //if (hptr->h_ofile->isArchiveFile)
427 //      continue;
428
429                                 if (hptr->h_type == (T_EXT | T_ABS))
430                                         hptr->h_type = T_ABS;   // Absolutes *can't* be externals
431
432                                 if (OSTAdd(hptr->h_sym, hptr->h_type, hptr->h_value) == -1)
433                                         return -1;
434                         }
435                 }
436         }
437
438         return 0;
439 }
440
441
442 //
443 // Add a Symbol's Name, Type, and Value to the OST.
444 // Return the Index of the Symbol in OST, or -1 for Error.
445 //
446 int OSTAdd(char * name, int type, long value)
447 {
448         int ost_offset_p, ost_offset_e = 0;     // OST table offsets for position calcs
449         int slen = 0;                                           // Symbol string length
450         int ostresult;                                          // OST index result
451
452         slen = strlen(name);
453
454         // If the OST or OST String Table has not been initialised then do so
455         if (ost_index == 0)
456         {
457                 if ((ost = malloc(OST_BLOCK)) == NULL)
458                 {
459                         printf("OST memory allocation error (stringtable).\n");
460                         return -1;
461                 }
462
463                 ost_ptr = ost;                                                  // Set OST start pointer
464                 ost_end = ost + OST_BLOCK;                              // Set OST end pointer
465
466                 if ((oststr = malloc(OST_BLOCK)) == NULL)
467                 {
468                         printf("OST memory allocation error (string).\n");
469                         return -1;
470                 }
471
472                 putlong(oststr, 0x00000004);            // Just null long for now
473                 oststr_ptr = oststr + 4;                        // Skip size of str table long (incl null long)
474                 putlong(oststr_ptr, 0x00000000);        // Null terminating long
475                 oststr_end = oststr + OST_BLOCK;
476         }
477         else
478         {
479                 // If next symbol record exceeds current allocation then expand symbol
480                 // table.
481                 ost_offset_p = (ost_ptr - ost);
482                 ost_offset_e = (ost_end - ost);
483
484                 // 3 x int (12)
485                 if ((ost_ptr + 12) > ost_end)
486                 {
487 #warning "!!! Bad logic in realloc call !!!"
488                         if ((ost = realloc(ost, (ost_end + OST_BLOCK))) == NULL)
489                         {
490                                 printf("OST memory reallocation error.\n");
491                                 return -1;
492                         }
493
494                         ost_ptr = ost + ost_offset_p;
495                         ost_end = (ost + ost_offset_e) + OST_BLOCK;
496                 }
497
498                 ost_offset_p = (oststr_ptr - oststr);
499                 ost_offset_e = (oststr_end - oststr);
500
501                 if ((oststr_ptr + (slen + 1 + 4)) > oststr_end)
502                 {
503 #warning "!!! Bad logic in realloc call !!!"
504                         if ((oststr = realloc(oststr, (oststr_end + OST_BLOCK))) == NULL)
505                         {
506                                 printf("OSTSTR memory reallocation error.\n");
507                                 return -1;
508                         }
509
510                         oststr_ptr = oststr + ost_offset_p;
511                         oststr_end = (oststr + ost_offset_e) + OST_BLOCK;
512                 }
513         }
514
515         // If this is a debug symbol and the include debug symbol flag (-g) is not
516         // set then do nothing
517         if ((type & 0xF0000000) && !gflag)
518         {
519                 // Do nothing
520         }
521         else
522         {
523                 ostresult = OSTLookup(name);            // Get symbol index in OST
524
525                 // If the symbol is in the output symbol table and the bflag is set
526                 // (don't remove multiply defined locals) and this is not an
527                 // external/global symbol *** OR *** the symbol is not in the output
528                 // symbol table then add it.
529                 if (((ostresult != -1) && bflag && !(type & 0x01000000))
530                         || ((ostresult != -1) && gflag && (type & 0xF0000000)) || (ostresult == -1))
531                 {
532                         if ((type & 0xF0000000) == 0x40000000)
533                                 putlong(ost_ptr, 0x00000000);   // Zero string table offset for dbg line
534                         else
535                                 putlong(ost_ptr, (oststr_ptr - oststr));        // String table offset of symbol string
536
537                         putlong(ost_ptr + 4, type );
538                         putlong(ost_ptr + 8, value);
539                         ost_ptr += 12;
540
541                         // If the symbol type is anything but a debug line information
542                         // symbol then write the symbol string to the string table
543                         if ((type & 0xF0000000) != 0x40000000)
544                         {
545                                 strcpy(oststr_ptr, name);               // Put symbol name in string table
546                                 *(oststr_ptr + slen) = '\0';    // Add null terminating character
547                                 oststr_ptr += (slen + 1);
548                                 putlong(oststr_ptr, 0x00000000);        // Null terminating long
549                                 putlong(oststr, (oststr_ptr - oststr)); // Update size of string table
550                         }
551
552                         if (vflag > 1)
553                         {
554                                 printf("OSTAdd: (%s), type=$%08X, val=$%08X\n", name, type, value);
555                         }
556
557                         return ost_index++;
558                 }
559         }
560
561         // Not sure about this as it could affect return indices. Needed to stop
562         // return error.
563         return 0;
564 }
565
566
567 //
568 // Return the index of a symbol in the output symbol table
569 //
570 int OSTLookup(char * sym)
571 {
572         int i;
573         int stro = 4;           // Offset in string table
574
575         for(i=0; i<ost_index; i++)
576         {
577                 if (strcmp(oststr + stro, sym) == 0)
578                         return i + 1;
579
580                 stro += strlen(oststr + stro) + 1;
581         }
582
583         return -1;
584 }
585
586
587 //
588 // Add unresolved externs to the output symbol table
589 //
590 int DoUnresolved(void)
591 {
592         struct HREC * hptr = unresolved;
593
594         // Add to OST while unresolved list is valid
595         while (hptr != NULL)
596         {
597                 if (OSTAdd(hptr->h_sym, T_EXT, 0L) == -1)
598                         return 1;
599
600                 if (vflag > 1)
601                         printf("DoUnresolved(): added %s\n", hptr->h_sym);
602
603                 struct HREC * htemp = hptr->h_next;
604                 free(hptr);
605                 hptr = htemp;
606         }
607
608         unresolved = NULL;
609         return 0;
610 }
611
612
613 //
614 // Update object file TEXT and DATA segments based on relocation records. Take
615 // in an OFILE header and flag (T_TEXT, T_DATA) to process. Return (0) is
616 // successful or non-zero (1) if failed.
617 //
618 int RelocateSegment(struct OFILE * ofile, int flag)
619 {
620         char * symtab;                                  // Start of symbol table
621         char * symbols;                                 // Start of symbols
622         char * sptr;                                    // Start of segment data
623         char * rptr;                                    // Start of segment relocation records
624         unsigned symidx;                                // Offset to symbol
625         unsigned addr;                                  // Relocation address
626         unsigned rflg;                                  // Relocation flags
627         unsigned olddata;                               // Old segment data at reloc address
628         unsigned newdata = 0;                   // New segment data at reloc address
629         unsigned pad;                                   // Temporary to calculate phrase padding
630         int i;                                                  // Iterator
631         char sym[SYMLEN];                               // String for symbol name/hash search
632         int ssidx;                                              // Segment size table index
633         unsigned glblreloc;                             // Global relocation flag
634         unsigned absreloc;                              // Absolute relocation flag
635         unsigned relreloc;                              // Relative relocation flag
636         unsigned swcond;                                // Switch statement condition
637         unsigned relocsize;                             // Relocation record size
638
639         // If there is no TEXT relocation data for the selected object file segment
640         // then update the COF TEXT segment offset allowing for the phrase padding
641         if ((flag == T_TEXT) && !ofile->o_header.absrel.reloc.tsize)
642         {
643                 // TEXT segment size plus padding
644                 pad = ((ofile->o_header.tsize + secalign) & ~secalign);
645                 textoffset += (ofile->o_header.tsize + (pad - ofile->o_header.tsize));
646
647                 if (vflag > 1)
648                         printf("RelocateSegment(%s, TEXT) : No Relocation Data\n", ofile->o_name);
649
650                 return 0;
651         }
652
653         // If there is no DATA relocation data for the selected object file segment
654         // then update the COF DATA and BSS segment offsets allowing for the phrase
655         // padding
656         if ((flag == T_DATA) && !ofile->o_header.absrel.reloc.dsize)
657         {
658                 // DATA segment size plus padding
659                 pad = ((ofile->o_header.dsize + secalign) & ~secalign);
660                 dataoffset += (ofile->o_header.dsize + (pad - ofile->o_header.dsize));
661                 // BSS segment size plus padding
662                 pad = ((ofile->o_header.bsize + secalign) & ~secalign);
663                 bssoffset += (ofile->o_header.bsize + (pad - ofile->o_header.bsize));
664
665                 if (vflag > 1)
666                         printf("RelocateSegment(%s, DATA) : No Relocation Data\n", ofile->o_name);
667
668                 return 0;
669         }
670
671         // Verbose mode information
672         if (vflag > 1)
673         {
674                 printf("RelocateSegment(%s, %s) : Processing Relocation Data\n",
675                         ofile->o_name, flag == T_DATA ? "DATA" : "TEXT");
676         }
677
678         // Obtain pointer to start of symbol table
679         symtab = (ofile->o_image + 32 + ofile->o_header.tsize
680                 + ofile->o_header.dsize
681                 + ofile->o_header.absrel.reloc.tsize
682                 + ofile->o_header.absrel.reloc.dsize);
683
684         // Obtain pointer to start of symbols
685         symbols = symtab + ofile->o_header.ssize;
686
687         // Obtain pointer to start of TEXT segment
688         sptr = ofile->o_image + 32;
689
690         // Obtain pointer to start of TEXT relocation records
691         rptr = sptr + (ofile->o_header.tsize + ofile->o_header.dsize);
692
693         relocsize = ofile->o_header.absrel.reloc.tsize;
694
695     if (vflag)
696         printf("RELOCSIZE :: %d  Records = %d\n", relocsize, relocsize / 8);
697
698         // Update pointers if DATA relocation records are being processed
699         if (flag == T_DATA)
700         {
701                 sptr += ofile->o_header.tsize;              // Start of DATA segment
702                 rptr += ofile->o_header.absrel.reloc.tsize; // Start of DATA relocation records
703                 relocsize = ofile->o_header.absrel.reloc.dsize;
704         }
705
706         // Process each relocation record for the TEXT segment
707         for(i=0; i<(int)relocsize; i+=8)
708         {
709                 // Obtain both the relocation address and the relocation flags from the
710                 // object file image
711                 addr = getlong(rptr);
712                 rflg = getlong(rptr + 4);
713                 glblreloc = (rflg & 0x00000010 ? 1 : 0);// Set global relocation flag
714                 absreloc = (rflg & 0x00000040 ? 1 : 0); // Set absolute relocation flag
715                 relreloc = (rflg & 0x000000A0 ? 1 : 0); // Set relative relocation flag
716
717                 // Additional processing required for global relocations
718                 if (glblreloc)
719                 {
720                         // Obtain the string table index for the relocation symbol, look
721                         // for it in the globals hash table to obtain information on that
722                         // symbol. For the hash calculation to work correctly it must be
723                         // placed in a 'clean' string before looking it up.
724                         symidx = getlong(symtab + ((rflg >> 8) * 12));
725                         memset(sym, 0, SYMLEN);
726                         strcpy(sym, symbols + symidx);
727                         olddata = newdata = 0;   // Initialise old and new segment data
728                         ssidx = OSTLookup(sym);
729                         newdata = getlong(ost + ((ssidx - 1) * 12) + 8);
730                 }
731
732                 // Obtain the existing long word segment data and flip words if the
733                 // relocation flags indicate it relates to a RISC MOVEI instruction
734                 olddata = getlong(sptr + addr);
735
736                 if (rflg & 0x01)
737                         olddata = _SWAPWORD(olddata);
738
739                 // Process record dependant on segment it relates to; TEXT, DATA or
740                 // BSS. Construct a new relocated segment long word based on the
741                 // required segment base address, the segment data offset in the
742                 // resulting COF file and the offsets from the incoming object file.
743                 swcond = (rflg & 0xFFFFFF00);
744
745                 if (!glblreloc)
746                 {
747                         switch (swcond)
748                         {
749                         case 0x00000200:          // Absolute Value
750                                 break;
751                         case 0x00000400:          // TEXT segment relocation record
752                                 if (flag == T_TEXT)   // Is this a TEXT section record?
753                                         newdata = tbase + textoffset + olddata;
754                                 else
755                                         newdata = tbase + dataoffset + olddata; // Nope, must be DATA section
756
757                                 break;
758                         case 0x00000600:          // DATA segment relocation record
759                                 newdata = dbase + dataoffset
760                                         + (olddata - ofile->o_header.tsize);
761
762                                 break;
763                         case 0x00000800:          // BSS segment relocation record
764                                 newdata = bbase + bssoffset
765                                         + (olddata - (ofile->o_header.tsize
766                                         + ofile->o_header.dsize));
767
768                                 break;
769                         }
770                 }
771                 else
772                 {
773                         if (!relreloc)
774                                 newdata += olddata;
775                 }
776
777                 // Set absolute (long) or relative (word) address of symbol
778                 if (absreloc)
779                 {
780                         // Flip the new long word segment data if the relocation record
781                         // indicated a RISC MOVEI instruction and place the resulting data
782                         // back in the COF segment
783                         if (rflg & 0x01)
784                                 newdata = _SWAPWORD(newdata);
785
786                         putlong(sptr + addr, newdata);
787                 }
788                 else if (relreloc)
789                 {
790                         putword(sptr + addr, newdata - tbase - addr - ofile->o_tbase);
791                 }
792
793                 // Shamus: Let's output some info to aid in debugging this crap
794                 if (vflag > 1)
795                 {
796                         char ssiString[128];
797                         ssiString[0] = 0;
798
799                         if (glblreloc)
800                                 sprintf(ssiString, " [ssi:%i]", ssidx);
801
802                         printf("RelocateSegment($%08X): %s, $%08X: $%08X => $%08X%s\n", rflg, (glblreloc ? sym : "(LOCAL)"), addr, olddata, getlong(sptr + addr), ssiString);
803                 }
804
805                 rptr += 8;     // Point to the next relocation record
806         }
807
808         // Update the COF segment offset allowing for the phrase padding.
809         if (flag == T_TEXT)
810         {
811                 // TEXT segment plus padding
812                 pad = ((ofile->o_header.tsize + secalign) & ~secalign);
813                 textoffset += (ofile->o_header.tsize + (pad - ofile->o_header.tsize));
814         }
815         else
816         {
817                 // DATA segment plus padding
818                 pad = ((ofile->o_header.dsize + secalign) & ~secalign);
819                 dataoffset += (ofile->o_header.dsize + (pad - ofile->o_header.dsize));
820                 // BSS segment plus padding
821                 pad = ((ofile->o_header.bsize + secalign) & ~secalign);
822                 bssoffset += (ofile->o_header.bsize + (pad - ofile->o_header.bsize));
823         }
824
825         // Return value, should always be zero
826         return 0;
827 }
828
829
830 //
831 // Add a path character to the end of string 's' if it doesn't already end with
832 // one. The last occurrance of '/' or '\' in the string is assumed to be the
833 // path character.
834 //
835 // This is fucking shit. We know what the path delimiter is, its FUCKING
836 // DEFINED IN THE FUCKING HEADER. FOR FUCKS SAKE. AND YES, HOPE TO GOD THERE'S
837 // ENOUGH SPACE IN THE PASSED IN BUFFER TO HOLD THE EXTRA CHARACTER!
838 //
839 void AppendPathDelimiter(char * s)
840 {
841 #if 0
842         // And hope to God that there's enough space in the buffer...
843         char pathchar = 0;
844
845         while (*s)
846         {
847                 if (*s == '/' || *s == '\\')
848                         pathchar = *s;
849
850                 s++;
851         }
852
853         s--;
854
855         if (*s == pathchar)
856                 return;
857
858         *++s = pathchar;
859         *++s = 0;
860 #else
861         int length = strlen(s);
862
863         if (s[length - 1] != PATH_DELIMITER)
864         {
865                 s[length] = PATH_DELIMITER;
866                 s[length + 1] = 0;      // BUFFER OVERFLOW!!!! FFFFFFFFUUUUUUUUUUUU
867         }
868 #endif
869 }
870
871
872 //
873 // Try to open "name", "name.o", "${libdir}name", "${libdir}name.o". Return the
874 // handle of the file successfully opened. p_name is updated to point to a
875 // malloc()'ed string which is the name which actually got opened. p_name will
876 // return unchanged if the file can't be found.
877 //
878 int TryOpenFile(char ** p_name)
879 {
880         char * name = *p_name;
881
882         // Note that libdir will be an empty string if there is none specified
883         char * tmpbuf = malloc(strlen(name) + strlen(libdir) + 3);
884
885         if (tmpbuf == NULL)
886         {
887                 printf("TryOpenFile() : out of memory\n");
888                 return -1;
889         }
890
891         strcpy(tmpbuf, name);
892         int hasdot = (strrchr(tmpbuf, '.') > strrchr(tmpbuf, PATH_DELIMITER));
893         // Try to open file as passed first
894         int fd = open(tmpbuf, _OPEN_FLAGS);
895
896         if (fd >= 0)
897                 goto ok;
898
899         if (!hasdot)
900         {
901                 // Try to open file with '.o' added
902                 strcat(tmpbuf, ".o");
903                 fd = open(tmpbuf, _OPEN_FLAGS);
904
905                 if (fd >= 0)
906                         goto ok;
907         }
908
909         // Try the libdir only if the name isn't already anchored
910         // Shamus: WTH, this makes no sense... Why the ':'? Is this a Macintosh??
911 //      if (*name != '/' && *name != '\\' && !strchr(name, ':'))
912         if ((*name != PATH_DELIMITER) && (strchr(name, ':') == NULL))
913         {
914                 strcpy(tmpbuf, libdir);
915                 // Add a trailing path char if there isn't one already
916                 AppendPathDelimiter(tmpbuf);
917                 strcat(tmpbuf, name);
918
919                 if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0)
920                         goto ok;
921
922                 if (!hasdot)
923                 {
924                         strcat(tmpbuf, ".o");
925
926                         if ((fd = open(tmpbuf, _OPEN_FLAGS)) >= 0)
927                                 goto ok;
928                 }
929         }
930
931         // Couldn't open file at all
932         return -1;
933
934 // There are worse things... :-P
935 ok:
936         tmpbuf = realloc(tmpbuf, strlen(tmpbuf) + 1);
937
938         if (tmpbuf == NULL)
939         {
940                 printf("TryOpenFile() : out of memory\n");
941                 return -1;
942         }
943
944         *p_name = tmpbuf;
945         return fd;
946 }
947
948
949 //
950 // Archive File Use, Needs to be Removed [Shamus: NON!]
951 //
952 void put_name(struct OFILE * p)
953 {
954         int flag = *(p->o_arname);
955         printf("%s%s%s", (flag ? (char *)(p->o_arname) : ""), (flag ? ":" : ""), p->o_name);
956 }
957
958
959 //
960 // Collect file names and handles in a buffer so there is less disk activity.
961 // Call DoFile with flag FALSE for normal object files and archives.
962 // Call it with flag TRUE and a symbol name for include files (-i).
963 //
964 int DoFile(char * fname, int incFlag, char * sym)
965 {
966         // Verbose information
967         if (vflag)
968         {
969                 printf("DoFile() : `%s' %s", fname, incFlag ? "INCLUDE" : "NORMAL");
970
971                 if (incFlag)
972                         printf(" symbol %s", sym);
973
974                 printf("\n");
975         }
976
977         // Reached maximum file handles
978         if (hd == NHANDLES)
979         {
980                 if (ProcessFiles())
981                         return 1;
982         }
983
984         // Attempt to open input file
985         int fd = TryOpenFile(&fname);
986
987         if (fd < 0)
988         {
989                 printf("Cannot find input module %s\n", fname);
990                 return 1;
991         }
992
993         // The file is open; save its info in the handle and name arrays
994         handle[hd] = fd;
995         name[hd] = fname;               // This is the name from TryOpenFile()
996         hflag[hd] = incFlag;
997
998         // Include files
999         if (incFlag)
1000         {
1001                 int temp = strlen(sym);         // Get symbol length
1002
1003                 // 100 chars is max length of a symbol
1004                 if (temp > 99)
1005                 {
1006                         sym[99] = '\0';
1007                         temp = 99;
1008                 }
1009
1010                 // Malloc enough space for two symbols, then build the second one.
1011                 // Second one may be one character longer than first
1012                 if ((hsym1[hd] = malloc((long)temp + 1)) == NULL
1013                         || (hsym2[hd] = malloc((long)temp + 2)) == NULL)
1014                 {
1015                         printf("DoFile() : out of memory for include-file symbols\n");
1016                         return 1;
1017                 }
1018
1019                 strcpy(hsym1[hd], sym);
1020                 strcpy(hsym2[hd], sym);
1021
1022                 if (temp == 99)
1023                 {
1024                         if (sym[99] == 'x')
1025                         {
1026                                 printf("Last char of %s is already 'x': choose another name\n", sym);
1027                                 return 1;
1028                         }
1029
1030                         hsym2[hd][99] = 'x';
1031                 }
1032                 else
1033                 {
1034                         hsym2[hd][temp] = 'x';
1035                         hsym2[hd][temp+1] = '\0';
1036                 }
1037         }
1038
1039         // Increment next handle index
1040         hd++;
1041         // No problems
1042         return 0;
1043 }
1044
1045
1046 //
1047 // Pad TEXT or DATA segment to the requested boundary
1048 //
1049 int segmentpad(FILE * fd, long segsize, int value)
1050 {
1051 //      long padsize;                            // Number of pad bytes needed
1052         int i;                                   // Good 'ol iterator
1053         char padarray[32];                       // Array of padding bytes
1054         char * padptr;                           // Pointer to array
1055
1056         // Determine the number of padding bytes that are needed
1057         long padsize = (segsize + secalign) & ~secalign;
1058         padsize = padsize - segsize;
1059
1060         // Fill pad array if padding is required
1061         if (padsize)
1062         {
1063                 padptr = padarray;
1064
1065                 for(i=0; i<16; i++)
1066                 {
1067                         putword(padptr, value);
1068                         padptr += 2;
1069                 }
1070
1071                 symoffset += padsize;
1072
1073                 // Write padding bytes
1074                 if (fwrite(padarray, padsize, 1, fd) != 1)
1075                         return 1;
1076         }
1077
1078         return 0;
1079 }
1080
1081
1082 //
1083 // Write the output file
1084 //
1085 int write_ofile(struct OHEADER * header)
1086 {
1087         FILE * fd;                                                      // File descriptor
1088         unsigned osize;                                         // Object segment size
1089         struct OFILE * otemp;                           // Object file pointer
1090         int i, j;                                                       // Iterators
1091         char himage[0x168];                                     // Header image (COF = 0xA8)
1092         unsigned tsoff, dsoff, bsoff;           // Segment offset values
1093         unsigned index, type, value;            // Symbol table index, type and value
1094         short abstype;                                          // ABS symbol type
1095         char symbol[14];                                        // Symbol record for ABS files
1096         int slen;                                                       // Symbol string length
1097
1098         symoffset = 0;                                          // Initialise symbol offset
1099
1100         // Add correct output extension if none
1101         if (strchr(ofile, '.') == NULL)
1102         {
1103                 if (aflag && cflag)
1104                         strcat(ofile, ".cof");          // COF files
1105                 else if (aflag && !cflag)
1106                         strcat(ofile, ".abs");          // ABS files
1107                 else
1108                         strcat(ofile, ".o");            // Object files (partial linking etc)
1109         }
1110
1111         fd = fopen(ofile, "wb");                        // Attempt to open output file
1112
1113         if (!fd)
1114         {
1115                 printf("Can't open output file %s\n", ofile);   // Error opening output file
1116                 return 1;
1117         }
1118
1119         // Build the output file header
1120         // Absolute (COF) header
1121         if (cflag)
1122         {
1123                 tsoff = dsoff = bsoff = 0xA8;   // Initialises segment offsets
1124
1125                 // Process each object file segment size to obtain a cumulative segment
1126                 // size for both the TEXT and DATA segments
1127                 for(i=0; i<(int)obj_index; i++)
1128                 {
1129                         dsoff += obj_segsize[i][0];     // Adding TEXT segment sizes
1130                         bsoff += obj_segsize[i][0] + obj_segsize[i][1]; // Adding TEXT and DATA segment sizes
1131                 }
1132
1133                 // Currently this only builds a COF absolute file. Conditionals and
1134                 // additional code will need to be added for ABS and partial linking.
1135
1136                 // Build the COF_HDR
1137                 putword(himage + 0,   0x0150               );         // Magic Number (0x0150)
1138                 putword(himage + 2,   0x0003               );         // Sections Number (3)
1139                 putlong(himage + 4,   0x00000000           );         // Date (0L)
1140                 putlong(himage + 8,   dsoff + header->dsize);         // Offset to Symbols Section
1141                 putlong(himage + 12,  ost_index);                     // Number of Symbols
1142                 putword(himage + 16,  0x001C               );         // Size of RUN_HDR (0x1C)
1143                 putword(himage + 18,  0x0003               );         // Executable Flags (3)
1144
1145                 // Build the RUN_HDR
1146                 putlong(himage + 20,  0x00000107           );         // Magic/vstamp
1147                 putlong(himage + 24,  header->tsize        );         // TEXT size in bytes
1148                 putlong(himage + 28,  header->dsize        );         // DATA size in bytes
1149                 putlong(himage + 32,  header->bsize        );         // BSS size in bytes
1150                 putlong(himage + 36,  tbase                );         // Start of executable, normally @TEXT
1151                 putlong(himage + 40,  tbase                );         // @TEXT
1152                 putlong(himage + 44,  dbase                );         // @DATA
1153
1154                 // Build the TEXT SEC_HDR
1155                 putlong(himage + 48,  0x2E746578           );
1156                 putlong(himage + 52,  0x74000000           );         // ".text"
1157                 putlong(himage + 56,  tbase                );         // TEXT START
1158                 putlong(himage + 60,  tbase                );         // TEXT START
1159                 putlong(himage + 64,  header->tsize        );         // TEXT size in bytes
1160                 putlong(himage + 68,  tsoff                );         // Offset to section data in file
1161                 putlong(himage + 72,  0x00000000           );         // Offset to section reloc in file (0L)
1162                 putlong(himage + 76,  0x00000000           );         // Offset to debug lines structures (0L)
1163                 putlong(himage + 80,  0x00000000           );         // Nreloc/nlnno (0L)
1164                 putlong(himage + 84,  0x00000020           );         // SEC_FLAGS: STYP_TEXT
1165
1166                 // Build the DATA SEC_HDR
1167                 putlong(himage + 88,  0x2E646174           );
1168                 putlong(himage + 92,  0x61000000           );         // ".data"
1169                 putlong(himage + 96,  dbase                );         // DATA START
1170                 putlong(himage + 100, dbase                );         // DATA START
1171                 putlong(himage + 104, header->dsize        );         // DATA size in bytes
1172                 putlong(himage + 108, dsoff                );         // Offset to section data in file
1173                 putlong(himage + 112, 0x00000000           );         // Offset to section reloc in file (0L)
1174                 putlong(himage + 116, 0x00000000           );         // Offset to debugging lines structures (0L)
1175                 putlong(himage + 120, 0x00000000           );         // Nreloc/nlnno (0L)
1176                 putlong(himage + 124, 0x00000040           );         // SEC_FLAGS: STYP_DATA
1177
1178                 // Build the BSS SEC_HDR
1179                 putlong(himage + 128, 0x2E627373           );
1180                 putlong(himage + 132, 0x00000000           );         // ".bss"
1181                 putlong(himage + 136, bbase                );         // BSS START
1182                 putlong(himage + 140, bbase                );         // BSS START
1183                 putlong(himage + 144, header->bsize        );         // BSS size in bytes
1184                 putlong(himage + 148, bsoff                );         // Offset to section data in file
1185                 putlong(himage + 152, 0x00000000           );         // Offset to section reloc in file (0L)
1186                 putlong(himage + 156, 0x00000000           );         // Offset to debugging lines structures (0L)
1187                 putlong(himage + 160, 0x00000000           );         // Nreloc/nlnno (0L)
1188                 putlong(himage + 164, 0x00000080           );         // SEC_FLAGS: STYP_BSS
1189
1190                 symoffset = 168;                                      // Update symbol offset
1191         }
1192         // Absolute (ABS) header
1193         else
1194         {
1195                 // Build the ABS header
1196                 putword(himage + 0,   0x601B               );         // Magic Number (0x601B)
1197                 putlong(himage + 2,   header->tsize        );         // TEXT segment size
1198                 putlong(himage + 6,   header->dsize        );         // DATA segment size
1199                 putlong(himage + 10,  header->bsize        );         // BSS segment size
1200                 putlong(himage + 14,  ost_index * 14       );         // Symbol table size (?)
1201                 putlong(himage + 18,  0x00000000           );         //
1202                 putlong(himage + 22,  tbase                );         // TEXT base address
1203                 putword(himage + 26,  0xFFFF               );         // Flags (?)
1204                 putlong(himage + 28,  dbase                );         // DATA base address
1205                 putlong(himage + 32,  bbase                );         // BSS base address
1206
1207                 symoffset = 36;                                       // Update symbol offset
1208         }
1209
1210         // Write the header, but not if noheaderflag
1211         // Absolute (ABS) header
1212         if (!cflag)
1213         {
1214                 if (!noheaderflag)
1215                         if (fwrite(himage, 36, 1, fd) != 1)
1216                                 goto werror;
1217         }
1218         // Absolute (COF) header
1219         else
1220         {
1221                 if (fwrite(himage, 168, 1, fd) != 1)
1222                         goto werror;
1223         }
1224
1225         // Write the TEXT segment of each object file
1226         for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1227         {
1228                 osize = otemp->o_header.tsize;
1229
1230                 // Write only if segment has size
1231                 if (osize)
1232                 {
1233                         if (vflag > 1)
1234                                 printf("Writing TEXT Segment of %s\n", otemp->o_name);
1235
1236                         if (fwrite(otemp->o_image + 32, osize, 1, fd) != 1)
1237                                 goto werror;
1238
1239                         // Pad to required alignment boundary
1240                         if (segmentpad(fd, osize, 0x0000))
1241                                 goto werror;
1242
1243                         symoffset += osize;
1244                 }
1245         }
1246
1247         // Write the DATA segment of each object file
1248         for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1249         {
1250                 osize = otemp->o_header.dsize;
1251
1252                 // Write only if the segment has size
1253                 if (osize)
1254                 {
1255                         if (vflag > 1)
1256                                 printf("Writing DATA Segment of %s\n", otemp->o_name);
1257
1258                         if (fwrite((otemp->o_image + 32 + otemp->o_header.tsize), osize, 1, fd) != 1)
1259                                 goto werror;
1260
1261                         // Pad to required alignment boundary
1262                         if (segmentpad(fd, osize, 0))
1263                                 goto werror;
1264
1265                         symoffset += osize;
1266                 }
1267         }
1268
1269         if (!noheaderflag)
1270         {
1271                 // Write the symbols table and string table
1272                 // Absolute (COF) symbol/string table
1273                 if (cflag)
1274                 {
1275                         if (header->ssize)
1276                         {
1277                                 if (fwrite(ost, (ost_ptr - ost), 1, fd) != 1) goto werror;
1278                                 if (fwrite(oststr, (oststr_ptr - oststr), 1, fd) != 1) goto werror;
1279                         }
1280                 }
1281                 // Absolute (ABS) symbol/string table
1282                 else
1283                 {
1284                         // The symbol and string table have been created as part of the
1285                         // DoSymbol() function and the output symbol and string tables are in
1286                         // COF format. For an ABS file we need to process through this to
1287                         // create the 14 character long combined symbol and string table.
1288                         // Format of symbol table in ABS: AAAAAAAATTVVVV, where (A)=STRING,
1289                         // (T)=TYPE & (V)=VALUE
1290
1291                         for(i=0; i<ost_index; i++)
1292                         {
1293                                 memset(symbol, 0, 14);                          // Initialise symbol record
1294                                 abstype = 0;                                            // Initialise ABS symbol type
1295                                 slen = 0;                                                       // Initialise symbol string length
1296                                 index = getlong(ost + (i * 12));        // Get symbol index
1297                                 type  = getlong((ost + (i * 12)) + 4);  // Get symbol type
1298
1299                                 if (type & 0xF0000000)
1300                                         continue;                    // Not doing debug symbols
1301
1302                                 value = getlong((ost + (i * 12)) + 8);  // Get symbol value
1303                                 slen = strlen(oststr + index);
1304
1305                                 // Get symbol string (maximum 8 chars)
1306                                 if (slen > 8)
1307                                 {
1308                                         for(j=0; j<8; j++)
1309                                                 *(symbol + j) = *(oststr + index + j);
1310                                 }
1311                                 else
1312                                 {
1313                                         for(j=0; j<slen; j++)
1314                                                 *(symbol + j) = *(oststr + index + j);
1315                                 }
1316
1317                                 // Modify to ABS symbol type
1318                                 switch (type)
1319                                 {
1320                                 case 0x02000000: abstype = (short)ABST_DEFINED;                           break;
1321                                 case 0x04000000: abstype = (short)ABST_DEFINED | ABST_TEXT;               break;
1322                                 case 0x05000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_TEXT; break;
1323                                 case 0x06000000: abstype = (short)ABST_DEFINED | ABST_DATA;               break;
1324                                 case 0x07000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_DATA; break;
1325                                 case 0x08000000: abstype = (short)ABST_DEFINED | ABST_BSS;                break;
1326                                 case 0x09000000: abstype = (short)ABST_DEFINED | ABST_GLOBAL | ABST_BSS;  break;
1327                                 default:
1328                                         printf("write_ofile: abs, cannot determine symbol type\n");
1329                                         type = 0;
1330                                         break;
1331                                 }
1332
1333                                 putword(symbol + 8, abstype);           // Write back new ABS type
1334                                 putlong(symbol + 10, value);            // Write back value
1335
1336                                 if (fwrite(symbol, 14, 1, fd) != 1) goto werror;    // Write symbol record
1337                         }
1338                 }
1339         }
1340
1341         // Close the file
1342         if (fclose(fd))
1343         {
1344                 printf("Close error on output file %s\n",ofile);
1345                 return 1;
1346         }
1347
1348         return 0;
1349
1350 werror:
1351         printf("Write error on output file %s\n", ofile);
1352         fclose(fd);                     // Try to close output file anyway
1353         return 1;
1354 }
1355
1356
1357 //
1358 // Display the Symbol Load Map
1359 //
1360 int write_map(struct OHEADER * header)
1361 {
1362         unsigned i, o;                  // Inner and outer loop iterators
1363         unsigned c;                             // Column number
1364         unsigned index;                 // Symbol string index
1365         unsigned type;                  // Symbol type
1366         unsigned value;                 // Symbol value
1367         char * symbol;                  // Symbol string value
1368
1369         if (ost_index == 0)
1370                 return 0;                       // Return if no symbols to map
1371
1372         printf("LOAD MAP\n\n");
1373
1374         // Outer loop for each of the symbol areas to map out;
1375         // 0 = NON-RELOCATABLE SYMBOLS
1376         // 1 = TEXT-SEGMENT RELOCATABLE SYMBOLS
1377         // 2 = DATA-SEGMENT RELOCATABLE SYMBOLS
1378         // 3 = BSS-SEGMENT RELOCATABLE SYMBOLS
1379         for(o=0; o<4; o++)
1380         {
1381                 // Display the correct map header for the symbols being processed
1382                 switch (o)
1383                 {
1384                 case 0: printf("NON-RELOCATABLE SYMBOLS\n\n");          break;
1385                 case 1: printf("TEXT-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1386                 case 2: printf("DATA-SEGMENT RELOCATABLE SYMBOLS\n\n"); break;
1387                 case 3: printf("BSS-SEGMENT RELOCATABLE SYMBOLS\n\n");  break;
1388                 }
1389
1390                 c = 0;                          // Initialise column number
1391
1392                 // Inner loop to process each record in the symbol table
1393                 for(i=0; i<(unsigned)ost_index; i++)
1394                 {
1395                         index  = getlong(ost + (i * 12));               // Get symbol string index
1396                         type   = getlong(ost + (i * 12) + 4);   // Get symbol type
1397                         value  = getlong(ost + (i * 12) + 8);   // Get symbol value
1398                         symbol = oststr + index;                                // Get symbol string
1399
1400                         // Display only three columns
1401                         if (c == 3)
1402                         {
1403                                 printf("\n");
1404                                 c = 0;
1405                         }
1406
1407                         // If local symbols not included and the type is local then go to
1408                         // next symbol record
1409                         if (!lflag & !(type & 0x01000000))
1410                                 continue;
1411
1412                         // Output each symbol to the display, dependant on type
1413                         switch (o)
1414                         {
1415                         case 0:
1416                                 // Non-relocatable symbols
1417                                 if (type == 0x02000000 || type == 0x03000000)
1418                                 {
1419                                         printf("%-8s %c  %08X   ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1420                                         c++;
1421                                 }
1422
1423                                 break;
1424                         case 1:
1425                                 // TEXT segment relocatable symbols
1426                                 if (type == 0x04000000 || type == 0x05000000)
1427                                 {
1428                                         printf("%-8s %c  %08X   ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1429                                         c++;
1430                                 }
1431
1432                                 break;
1433                         case 2:
1434                                 // DATA segment relocatble symbols
1435                                 if (type == 0x06000000 || type == 0x07000000)
1436                                 {
1437                                         printf("%-8s %c  %08X   ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1438                                         c++;
1439                                 }
1440
1441                                 break;
1442                         case 3:
1443                                 // BSS segment relocatable symbols
1444                                 if (type == 0x08000000 || type == 0x09000000)
1445                                 {
1446                                         printf("%-8s %c  %08X   ", symbol, (type & 0x01000000) ? 'G' : 'L', value);
1447                                         c++;
1448                                 }
1449
1450                                 break;
1451                         }
1452                 }
1453
1454                 printf("\n\n");
1455         }
1456
1457         return 0;
1458 }
1459
1460
1461 //
1462 // Convert ASCII to hexadecimal
1463 //
1464 //int atolx(char * string, long * value)
1465 int atolx(char * string, int * value)
1466 {
1467         *value = 0;
1468
1469         while (isxdigit(*string))
1470         {
1471                 if (isdigit(*string))
1472                 {
1473                         *value = (*value << 4) + (*string++ - '0');
1474                 }
1475                 else
1476                 {
1477                         if (isupper(*string))
1478                                 *string = tolower(*string);
1479
1480                         *value = (*value << 4) + ((*string++ - 'a') + 10);
1481                 }
1482         }
1483
1484         if (*string != '\0')
1485         {
1486                 printf("Invalid hexadecimal value");
1487                 return 1;
1488         }
1489
1490         return 0;
1491 }
1492
1493
1494 //
1495 // Stuff the (long) value of a string into the value argument. RETURNS TRUE if
1496 // the string doesn't parse.  Parses only as a hex string.
1497 //
1498 int getval(char * string, int * value)
1499 {
1500         return atolx(string, value);
1501 }
1502
1503
1504 //
1505 // Create one big .o file from the images already in memory, returning a
1506 // pointer to an OHEADER. Note that the oheader is just the header for the
1507 // output (plus some other information). The text, data, and fixups are all
1508 // still in the ofile images hanging off the global `olist'.
1509 //
1510 struct OHEADER * make_ofile()
1511 {
1512         unsigned tptr, dptr, bptr;                                      // Bases in runtime model
1513         int ret = 0;                                                            // Return value
1514         struct OFILE * otemp, * oprev, * ohold;         // Object file list pointers
1515         struct OHEADER * header;                                        // Output header pointer
1516
1517         // Initialize cumulative segment sizes
1518         textsize = datasize = bsssize = 0;
1519
1520         // For each object file, accumulate the sizes of the segments but remove
1521         // those object files which are unused
1522         oprev = NULL;                   // Init previous obj file list ptr
1523         otemp = olist;                  // Set temp pointer to object file list
1524
1525         while (otemp != NULL)
1526         {
1527                 // UNUSED !!!!! (it's !O_ARCHIVE, so this code executes.)
1528                 if (!(otemp->o_flags & O_ARCHIVE))
1529                 {
1530                         if ((otemp->o_flags & O_USED) == 0)
1531                         {
1532                                 if (wflag)
1533                                 {
1534                                         printf("Unused object file ");
1535                                         put_name(otemp);
1536                                         printf(" discarded.\n");
1537                                 }
1538
1539                                 if (oprev == NULL)
1540                                         olist = otemp->o_next;
1541                                 else
1542                                         oprev->o_next = otemp->o_next;
1543
1544                                 ohold = otemp;
1545
1546                                 if (!ohold->isArchiveFile)
1547                                         free(ohold->o_image);
1548
1549                                 free(ohold);
1550                         }
1551                         else
1552                         {
1553                                 // Increment total of segment sizes ensuring requested
1554                                 // alignment
1555                                 textsize += (otemp->o_header.tsize + secalign) & ~secalign;
1556                                 datasize += (otemp->o_header.dsize + secalign) & ~secalign;
1557                                 bsssize  += (otemp->o_header.bsize + secalign) & ~secalign;
1558                                 oprev = otemp;
1559                         }
1560                 }
1561
1562                 // Go to next object file list pointer
1563                 otemp = otemp->o_next;
1564         }
1565
1566         // Update base addresses and create symbols _TEXT_E, _DATA_E and _BSS_E
1567         tbase = tval;
1568         OSTAdd("_TEXT_E", 0x05000000, tval + textsize);
1569
1570         if (!dval)
1571         {
1572                 // DATA follows TEXT
1573                 dbase = tval + textsize;
1574                 OSTAdd("_DATA_E", 0x07000000, tval + textsize + datasize);
1575
1576                 if (!bval)
1577                 {
1578                         // BSS follows DATA
1579                         bbase = tval + textsize + datasize;
1580                         OSTAdd("_BSS_E", 0x09000000, tval + textsize + datasize + bsssize);
1581                 }
1582                 else
1583                 {
1584                         // BSS is independant of DATA
1585                         bbase = bval;
1586                         OSTAdd("_BSS_E", 0x09000000, bval + bsssize);
1587                 }
1588         }
1589         else
1590         {
1591                 // DATA is independant of TEXT
1592                 dbase = dval;
1593                 OSTAdd("_DATA_E", 0x07000000, dval + datasize);
1594
1595                 if (!bval)
1596                 {
1597                         // BSS follows DATA
1598                         bbase = dval + datasize;
1599                         OSTAdd("_BSS_E", 0x09000000, dval + datasize + bsssize);
1600                 }
1601                 else
1602                 {
1603                         // BSS is independant of DATA
1604                         bbase = bval;
1605                         OSTAdd("_BSS_E", 0x09000000, bval + bsssize);
1606                 }
1607         }
1608
1609         // Place each unresolved symbol in the output symbol table
1610         if (DoUnresolved())
1611                 return NULL;
1612
1613         // Initialise base addresses
1614         tptr = dptr = bptr = 0;
1615
1616         // For each file, relocate its symbols and add them to the output symbol
1617         // table
1618         otemp = olist;
1619         oprev = NULL;
1620
1621         while (otemp != NULL)
1622         {
1623                 otemp->o_tbase = tptr;
1624
1625                 // Do rest only for non-ARCHIVE markers
1626                 if (!(otemp->o_flags & O_ARCHIVE))
1627                 {
1628                         otemp->o_dbase = dptr;
1629                         otemp->o_bbase = bptr;
1630                         tptr += (otemp->o_header.tsize + secalign) & ~secalign;
1631                         dptr += (otemp->o_header.dsize + secalign) & ~secalign;
1632                         bptr += (otemp->o_header.bsize + secalign) & ~secalign;
1633                 }
1634
1635                 // For each symbol, (conditionally) add it to the ost
1636                 // For ARCHIVE markers, this adds the symbol for the file & returns
1637                 // (Shamus: N.B. it does no such thing ATM)
1638                 if (DoSymbol(otemp))
1639                         return NULL;
1640
1641                 if (otemp->o_flags & O_ARCHIVE)
1642                 {
1643                         // Now that the archive is marked, remove it from list
1644                         if (oprev == NULL)
1645                                 olist = otemp->o_next;
1646                         else
1647                                 oprev->o_next = otemp->o_next;
1648
1649                         ohold = otemp;
1650
1651                         if (ohold->o_image)
1652                                 if (!ohold->isArchiveFile)
1653                                         free(ohold->o_image);
1654
1655                         free(ohold);
1656                 }
1657                 else
1658                 {
1659                         oprev = otemp;
1660                 }
1661
1662                 otemp = otemp->o_next;
1663         }
1664
1665         // Places all the externs, globals etc into the output symbol table
1666         if (DoCommon() == -1)
1667                 return NULL;
1668
1669         // Create a new output file header
1670         header = new_oheader();
1671
1672         if (header == NULL)
1673         {
1674                 printf("make_ofile: out of memory!\n");
1675                 return NULL;
1676         }
1677
1678         // Fill in the output header. Does not match the actual output but values
1679         // used as reference
1680         header->magic = 0x0150;             // COF magic number
1681         header->tsize = textsize;           // TEXT segment size
1682         header->dsize = datasize;           // DATA segment size
1683         header->bsize = bsssize;            // BSS segment size
1684         header->ssize = (ost_ptr - ost);    // Symbol table size
1685         header->ostbase = ost;              // Output symbol table base address
1686
1687         // For each object file, relocate its TEXT and DATA segments. OR the result
1688         // into ret so all files get moved (and errors reported) before returning
1689         // with the error condition
1690         for(otemp=olist; otemp!=NULL; otemp=otemp->o_next)
1691         {
1692                 if (!(otemp->o_flags & O_ARCHIVE))
1693                 {
1694                         ret |= RelocateSegment(otemp, T_TEXT); // TEXT segment relocations
1695                         ret |= RelocateSegment(otemp, T_DATA); // DATA segment relocations
1696                 }
1697         }
1698
1699         // Done with global symbol hash tables
1700         FreeHashes();
1701
1702         return (ret ? (struct OHEADER *)NULL : header);
1703 }
1704
1705
1706 //
1707 // Add symbol to hash list
1708 //
1709 int AddSymbolToHashList(struct HREC ** hptr, char * sym, struct OFILE * ofile,
1710         long value, int type)
1711 {
1712         struct HREC * htemp = new_hrec();
1713
1714         if (htemp == NULL)
1715         {
1716                 printf("Out of memory\n");
1717                 return 1;
1718         }
1719
1720         // Shamus: Moar testing...
1721         if (vflag > 1)
1722         {
1723                 printf("AddSymbolToHashList(): hptr=$%08X, sym=\"%s\", ofile=$%08X, value=$%X, type=$%X\n", hptr, sym, ofile, value, type);
1724         }
1725
1726         // Populate hash record
1727         memset(htemp->h_sym, 0, SYMLEN);
1728         strcpy(htemp->h_sym, sym);
1729         htemp->h_ofile = ofile;
1730         htemp->h_value = value;
1731         htemp->h_type = type;
1732
1733         // Add new hash to the front of the list (hence the ** for hptr)
1734         htemp->h_next = *hptr;
1735         *hptr = htemp;
1736
1737         return 0;
1738 }
1739
1740
1741 //
1742 // Add symbol to the unresolved symbols hash table (really, it's a linked list)
1743 //
1744 int AddUnresolvedSymbol(char * sym, struct OFILE * ofile)
1745 {
1746         if (vflag > 1)
1747                 printf("AddUnresolvedSymbol(%s, %s)\n", sym, ofile->o_name);
1748
1749         return AddSymbolToHashList(&unresolved, sym, ofile, 0L, 0);
1750 }
1751
1752
1753 //
1754 // Remove the HREC from the unresolved symbol list, and pass back a pointer
1755 // to the spot where the HREC was.
1756 //
1757 struct HREC * RemoveUnresolvedSymbol(struct HREC * hrec)
1758 {
1759         struct HREC * ptr = unresolved;
1760         struct HREC * previous = NULL;
1761
1762         while ((ptr != hrec) && (ptr != NULL))
1763         {
1764                 previous = ptr;
1765                 ptr = ptr->h_next;
1766         }
1767
1768         // Not found...!
1769         if (ptr == NULL)
1770                 return NULL;
1771
1772         struct HREC * next = ptr->h_next;
1773
1774         // Remove the head if nothing previous, otherwise, remove what we found
1775         if (previous == NULL)
1776                 unresolved = next;
1777         else
1778                 previous->h_next = next;
1779
1780         free(ptr);
1781         return next;
1782 }
1783
1784
1785 //
1786 // Add symbol to the unresolved symbols hash table
1787 //
1788 int AddARSymbol(char * sym, struct OFILE * ofile)
1789 {
1790         if (vflag > 1)
1791                 printf("AddARSymbol(%s, %s)\n", sym, ofile->o_name);
1792
1793         return AddSymbolToHashList(&arSymbol, sym, ofile, 0L, 0);
1794 }
1795
1796
1797 //
1798 // Generate hash value from the 1st 15 characters of the symbol modulo the
1799 // number of buckets in the hash.
1800 //
1801 int GetHash(char * s)
1802 {
1803         // For this to be consistent, the symbol MUST be zeroed out beforehand!
1804         char c[SYMLEN];
1805         memset(c, 0, SYMLEN);
1806         strcpy(c, s);
1807
1808         int i = (c[0] + c[1] + c[2] + c[3] + c[4] + c[5] + c[6] + c[7] + c[8]
1809                 + c[9] + c[10] + c[11] + c[12] + c[13] + c[14]) % NBUCKETS;
1810         return i;
1811 }
1812
1813
1814 //
1815 // Lookup a symbol in the hash table.
1816 // Returns either a pointer to the HREC or NULL if not found.
1817 //
1818 struct HREC * LookupHREC(char * symbol)
1819 {
1820         struct HREC * hptr = htable[GetHash(symbol)];
1821
1822         while (hptr != NULL)
1823         {
1824 //This is utter failure...
1825 //              if (symcmp(symbol, hptr->h_sym))  <-- left here for giggles :D  - LinkoVitch
1826                 // Return hash record pointer if found
1827                 if (strcmp(symbol, hptr->h_sym) == 0)
1828                         return hptr;
1829
1830                 hptr = hptr->h_next;
1831         }
1832
1833         return NULL;
1834 }
1835
1836
1837 //
1838 // Lookup a symbol in the AR symbol table.
1839 // Returns either a pointer to the HREC or NULL if not found.
1840 //
1841 struct HREC * LookupARHREC(char * symbol)
1842 {
1843         struct HREC * hptr = arSymbol;//htable[GetHash(symbol)];
1844
1845         while (hptr != NULL)
1846         {
1847                 // Return hash record pointer if found
1848                 if (strcmp(symbol, hptr->h_sym) == 0)
1849                         return hptr;
1850
1851                 hptr = hptr->h_next;
1852         }
1853
1854         return NULL;
1855 }
1856
1857
1858 //
1859 // Add symbol to the hash table if it doesn't already exist, otherwise decide
1860 // what to do since it's already defined in another unit.
1861 //
1862 int DealWithSymbol(char * sym, long type, long value, struct OFILE * ofile)
1863 {
1864         if (vflag > 1)
1865         {
1866                 printf("DealWithSymbol(%s,%s,%lx,", sym, ofile->o_name, value);
1867                 printf("%x,%s)\n", (unsigned int)type, (isglobal(type) ? "GLOBAL" : "COMMON"));
1868         }
1869
1870         struct HREC * hptr = LookupHREC(sym);
1871
1872         if (hptr == NULL)
1873                 return AddSymbolToHashList(&htable[GetHash(sym)], sym, ofile, value, type);
1874
1875         // Symbol is already in table... Figure out how to handle!
1876         if (iscommon(type) && !iscommon(hptr->h_type))
1877         {
1878                 // Mismatch: global came first; warn and keep the global one
1879                 if (wflag)
1880                 {
1881                         printf("Warning: %s: global from ", sym);
1882                         put_name(hptr->h_ofile);
1883                         printf(" used, common from ");
1884                         put_name(ofile);
1885                         printf(" discarded.\n");
1886                 }
1887
1888                 putword(sym + 8, ABST_EXTERN);
1889                 putlong(sym + 10, 0L);
1890         }
1891         else if (iscommon(hptr->h_type) && !iscommon(type))
1892         {
1893                 // Mismatch: common came first; warn and keep the global one
1894                 if (wflag)
1895                 {
1896                         printf("Warning: %s: global from ", sym);
1897                         put_name(ofile);
1898                         printf(" used, common from ");
1899                         put_name(hptr->h_ofile);
1900                         printf(" discarded.\n");
1901                 }
1902
1903                 hptr->h_type = type;
1904                 hptr->h_ofile = ofile;
1905                 hptr->h_value = value;
1906         }
1907         // They're both global [WRONG! Passed in one is global]
1908 //      else if (!iscommon(type))
1909 //is this now right??
1910         else if (!iscommon(type) && !iscommon(hptr->h_type))
1911         {
1912                 // Global exported by another ofile; warn and make this one extern
1913                 if (wflag)
1914                 {
1915                         printf("Duplicate symbol %s: ", sym);
1916                         put_name(hptr->h_ofile);
1917                         printf(" used, ");
1918                         put_name(ofile);
1919                         printf(" discarded\n");
1920                 }
1921
1922                 putword(sym + 8, ABST_EXTERN);
1923         }
1924         // They're both common
1925         else
1926         {
1927                 if (hptr->h_value < value)
1928                 {
1929                         hptr->h_value = value;
1930                         hptr->h_ofile = ofile;
1931                 }
1932         }
1933
1934         return 0;
1935 }
1936
1937
1938 //
1939 // Add the imported symbols from this file to unresolved, and the global and
1940 // common (???) symbols to the exported hash table.
1941 //
1942 // Change old-style commons (type == T_EXTERN, value != 0) to new-style ones
1943 // (type == (T_GLOBAL | T_EXTERN)). [??? O_o]
1944 //
1945 int AddSymbols(struct OFILE * Ofile)
1946 {
1947         struct HREC * hptr;                     // Hash record pointer
1948         char symbol[SYMLEN];
1949
1950         if (vflag > 1)
1951                 printf("Add symbols for file %s\n", Ofile->o_name);
1952
1953         // Get base pointer, start of sym fixups
1954         char * ptr = Ofile->o_image + 32
1955                 + Ofile->o_header.tsize
1956                 + Ofile->o_header.dsize
1957                 + Ofile->o_header.absrel.reloc.tsize
1958                 + Ofile->o_header.absrel.reloc.dsize;
1959         char * sfix = ptr;                                                      // Set symbol fixup pointer
1960         char * sstr = sfix + Ofile->o_header.ssize;     // Set symbol table pointer
1961         long nsymbols = Ofile->o_header.ssize / 12;     // Obtain number of symbols
1962
1963         while (nsymbols)
1964         {
1965                 long index = getlong(sfix);                             // Get symbol string index
1966                 long type  = getlong(sfix + 4);                 // Get symbol type
1967                 long value = getlong(sfix + 8);                 // Get symbol value
1968                 memset(symbol, 0, SYMLEN);
1969                 strcpy(symbol, sstr + index);
1970
1971                 if ((Ofile->isArchiveFile) && !(Ofile->o_flags & O_USED))
1972                 {
1973                         if ((type & T_EXT) && (type & (T_SEG | T_ABS)))
1974                                 if (AddARSymbol(symbol, Ofile))
1975                                         return 1;
1976                 }
1977                 else if (type == T_EXT)
1978                 {
1979                         // External symbal that is *not* in the current unit
1980                         hptr = LookupHREC(symbol);
1981
1982                         if (hptr != NULL)
1983                                 hptr->h_ofile->o_flags |= O_USED;       // Mark .o file as used
1984                         // Otherwise add to unresolved list
1985                         else if (AddUnresolvedSymbol(symbol, Ofile))
1986                                 return 1;                               // Error if addition failed
1987                 }
1988                 else if ((type & T_EXT) && (type & (T_SEG | T_ABS)))
1989                 {
1990                         // Symbol in the current unit that is also EXPORTED
1991                         if (DealWithSymbol(symbol, type, value, Ofile))
1992                                 return 1;                               // Error if addition failed
1993                 }
1994
1995                 sfix += 12;                     // Increment symbol fixup pointer
1996                 nsymbols--;                     // Decrement num of symbols to process
1997         }
1998
1999         // Success loading symbols
2000         return 0;
2001 }
2002
2003
2004 //
2005 // Process object file for symbols
2006 //
2007 int DoItem(struct OFILE * obj)
2008 {
2009         // Allocate memory for object record ptr
2010         struct OFILE * Ofile = new_ofile();
2011
2012         if (Ofile == NULL)
2013         {
2014                 printf("Out of memory while processing %s\n", obj->o_name);
2015                 return 1;
2016         }
2017
2018         // Starting after all pathnames, etc., copy .o file name to Ofile
2019         char * temp = path_tail(obj->o_name);
2020
2021         // Check filename length
2022         if (strlen(temp) > FNLEN - 1)
2023         {
2024                 printf("File name too long: %s\n", temp);
2025                 return 1;
2026         }
2027
2028         // Check archive name length
2029         if (strlen(obj->o_arname) > FNLEN - 1)
2030         {
2031                 printf("Archive name too long: %s\n", obj->o_arname);
2032                 return 1;
2033         }
2034
2035         strcpy(Ofile->o_name, temp);            // Store filename
2036         strcpy(Ofile->o_arname, obj->o_arname); // Store archive name
2037
2038         // Initialise object record information
2039         Ofile->o_next  = NULL;
2040         Ofile->o_tbase = 0;
2041         Ofile->o_dbase = 0;
2042         Ofile->o_bbase = 0;
2043         Ofile->o_flags = obj->o_flags;
2044         Ofile->o_image = obj->o_image;
2045         Ofile->isArchiveFile = obj->isArchiveFile;
2046         char * ptr = obj->o_image;
2047
2048         // Don't do anything if this is just an ARCHIVE marker, just add the file
2049         // to the olist
2050         // (Shamus: N.B. it does no such ARCHIVE thing ATM)
2051         if (!(obj->o_flags & O_ARCHIVE))
2052         {
2053                 Ofile->o_header.magic = getlong(ptr);
2054                 Ofile->o_header.tsize = getlong(ptr + 4);
2055                 Ofile->o_header.dsize = getlong(ptr + 8);
2056                 Ofile->o_header.bsize = getlong(ptr + 12);
2057                 Ofile->o_header.ssize = getlong(ptr + 16);
2058                 Ofile->o_header.absrel.reloc.tsize = getlong(ptr + 24);
2059                 Ofile->o_header.absrel.reloc.dsize = getlong(ptr + 28);
2060
2061                 // Round BSS off to alignment boundary
2062                 Ofile->o_header.bsize = (Ofile->o_header.bsize + secalign) & ~secalign;
2063
2064                 if ((Ofile->o_header.dsize & 7) && wflag)
2065                 {
2066                         printf("Warning: data segment size of ");
2067                         put_name(Ofile);
2068                         printf(" is not a phrase multiple\n");
2069                 }
2070
2071                 // Check for odd segment sizes
2072                 if ((Ofile->o_header.tsize & 1) || (Ofile->o_header.dsize & 1)
2073                         || (Ofile->o_header.bsize & 1))
2074                 {
2075                         printf("Error: odd-sized segment in ");
2076                         put_name(Ofile);
2077                         printf("; link aborted.\n");
2078                         return 1;
2079                 }
2080
2081                 if (AddSymbols(Ofile))
2082                         return 1;
2083         }
2084
2085         // Add this file to the olist
2086         if (olist == NULL)
2087                 olist = Ofile;
2088         else
2089                 olast->o_next = Ofile;
2090
2091         olast = Ofile;
2092         return 0;
2093 }
2094
2095
2096 //
2097 // Handle items in processing list.
2098 //
2099 // After loading all objects, archives & include files, we now go and process
2100 // each item on the processing list (plist). Once this is done, we go through
2101 // any unresolved symbols left and see if they have shown up.
2102 //
2103 int ProcessLists(void)
2104 {
2105         // Process object file list first (adds symbols from each unit & creates
2106         // the olist)
2107         while (plist != NULL)
2108         {
2109                 if (DoItem(plist))
2110                         return 1;
2111
2112                 struct OFILE * ptemp = plist;
2113                 plist = plist->o_next;
2114                 free(ptemp);
2115         }
2116
2117         struct HREC * uptr;
2118
2119         // Process the unresolved symbols list. This may involve pulling in symbols
2120         // from any included .a units. Such units are lazy linked by default; we
2121         // generally don't want everything they provide, just what's refenced.
2122         for(uptr=unresolved; uptr!=NULL; )
2123         {
2124                 if (vflag > 1)
2125                         printf("LookupHREC(%s) => ", uptr->h_sym);
2126
2127                 struct HREC * htemp = LookupHREC(uptr->h_sym);
2128
2129                 if (htemp != NULL)
2130                 {
2131                         // Found it in the symbol table!
2132                         if (vflag > 1)
2133                                 printf("%s in %s (=$%06X)\n", (isglobal(htemp->h_type) ? "global" : "common"), htemp->h_ofile->o_name, htemp->h_value);
2134
2135                         // Mark the .o unit that the symbol is in as seen & remove from the
2136                         // unresolved list
2137                         htemp->h_ofile->o_flags |= O_USED;
2138                         uptr = RemoveUnresolvedSymbol(uptr);
2139                 }
2140                 else
2141                 {
2142                         if (vflag > 1)
2143                                 printf("NULL\n");
2144
2145                         // Check to see if the unresolved symbol is on the AR symbol list.
2146                         htemp = LookupARHREC(uptr->h_sym);
2147
2148                         // If the unresolved symbol is in a .o unit that is unused, we can
2149                         // drop it; same if the unresolved symbol is in the exported AR
2150                         // symbol list. Otherwise, go to the next unresolved symbol.
2151                         if (!(uptr->h_ofile->o_flags & O_USED) || (htemp != NULL))
2152                                 uptr = RemoveUnresolvedSymbol(uptr);
2153                         else
2154                                 uptr = uptr->h_next;
2155
2156                         // Now that we've possibly deleted the symbol from unresolved list
2157                         // that was also in the AR list, we add the symbols from this .o
2158                         // unit to the symbol table, mark the .o unit as used, and restart
2159                         // scanning the unresolved list as there is a good possibility that
2160                         // the symbols in the unit we're adding has unresolved symbols as
2161                         // well.
2162                         if (htemp != NULL)
2163                         {
2164                                 htemp->h_ofile->o_flags |= O_USED;
2165                                 AddSymbols(htemp->h_ofile);
2166                                 uptr = unresolved;
2167                         }
2168                 }
2169         }
2170
2171         // Show files used if the user requests it.
2172         if (vflag > 1)
2173         {
2174                 printf("Files used:\n");
2175                 struct OFILE * filePtr = olist;
2176
2177                 while (filePtr != NULL)
2178                 {
2179                         if (filePtr->o_flags & O_USED)
2180                         {
2181                                 printf("   %s%s%s\n", filePtr->o_name, (filePtr->isArchiveFile ? ":" : ""), (filePtr->isArchiveFile ? filePtr->o_arname : nullStr));
2182                         }
2183
2184                         filePtr = filePtr->o_next;
2185                 }
2186         }
2187
2188         return 0;
2189 }
2190
2191
2192 //
2193 // Extract filename from path
2194 //
2195 char * path_tail(char * name)
2196 {
2197         char * temp = strrchr(name, PATH_DELIMITER);
2198
2199         // Return what was passed in if path delimiter was not found
2200         if (temp == NULL)
2201                 return name;
2202
2203         return temp + 1;
2204 }
2205
2206
2207 //
2208 // Add input file to processing list
2209 //
2210 int AddToProcessingList(char * ptr, char * fname, char * arname, uint8_t arFile)
2211 {
2212         if (plist == NULL)
2213         {
2214                 // First time object record allocation
2215                 plist = new_ofile();
2216                 plast = plist;
2217         }
2218         else
2219         {
2220                 // Next object record allocation
2221                 plast->o_next = new_ofile();
2222                 plast = plast->o_next;
2223         }
2224
2225         if (plast == NULL)
2226         {
2227                 printf("Out of memory.\n");             // Error if memory allocation fails
2228                 return 1;
2229         }
2230
2231         fname = path_tail(fname);
2232         arname = path_tail(arname);
2233
2234         if (strlen(fname) > FNLEN - 1)
2235         {
2236                 // Error on excessive filename length
2237                 printf("File name too long: %s (sorry!)\n", fname);
2238                 return 1;
2239         }
2240
2241         if (strlen(arname) > FNLEN - 1)
2242         {
2243                 // Error on excessive filename length
2244                 printf("AR file name too long: %s (sorry!)\n", arname);
2245                 return 1;
2246         }
2247
2248         strcpy(plast->o_name, fname);           // Store filename sans path
2249         strcpy(plast->o_arname, arname);        // Store archive name sans path
2250         plast->o_image = ptr;                           // Store data pointer
2251         plast->o_flags = (arFile ? 0 : O_USED); // File is used if NOT in archive
2252         plast->o_next = NULL;                           // Initialise next record pointer
2253         plast->isArchiveFile = arFile;          // Shamus: Temp until can sort it out
2254
2255         return 0;                                                       // Return without errors
2256 }
2257
2258
2259 //
2260 // Process in binary include files and add them to the processing list. This
2261 // routine takes in the binary file and creates an 'object' file in memory.
2262 // Sym1/Sym2 point to the start and end of data.
2263 //
2264 // Image size for include files is:
2265 // Header ....... 32 bytes
2266 // Data ......... dsize
2267 // Sym Fixups ... 2 * 12 bytes
2268 // Symbol Size .. 4 bytes (Value to include symbols and terminating null)
2269 // Symbols ...... (strlen(sym1) + 1) + (strlen(sym2) + 1)
2270 // Terminate .... 4 bytes (0x00000000)
2271 //
2272 int LoadInclude(char * fname, int handle, char * sym1, char * sym2, int segment)
2273 {
2274         long fsize, dsize, size;              // File, DATA segment and image sizes
2275         char * ptr, * sptr;                   // Data pointers
2276         int i;                                // Iterators
2277         int sym1len = 0;                      // Symbol 1 length
2278         int sym2len = 0;                      // Symbol 2 length
2279         unsigned symtype = 0;
2280
2281         fsize = FileSize(handle);             // Get size of include file
2282         dsize = (fsize + secalign) & ~secalign; // Round up to a alignment boundary
2283
2284         sym1len = strlen(sym1) + 1;           // Get sym1 length + null termination
2285         sym2len = strlen(sym2) + 1;           // Get sym2 length + null termination
2286
2287         size = 32 + dsize + 24 + 4 + sym1len + sym2len + 4;
2288
2289         // Use calloc so the header & fixups initialize to zero
2290         // Allocate object image memory
2291         if ((ptr = calloc(size, 1)) == NULL)
2292         {
2293                 printf("Out of memory while including %s\n", fname);
2294                 close(handle);
2295                 return 1;
2296         }
2297
2298         // Read in binary data
2299         if (read(handle, ptr + 32, fsize) != fsize)
2300         {
2301                 printf("File read error on %s\n", fname);
2302                 close(handle);
2303                 free(ptr);
2304                 return 1;
2305         }
2306
2307         close(handle);
2308
2309         strcpy(obj_fname[obj_index], path_tail(fname));
2310
2311         // Build this image's dummy header
2312         putlong(ptr, 0x00000107);              // Magic number
2313
2314         if (segment)
2315         {
2316                 putlong(ptr+4, dsize);             // Text size
2317                 putlong(ptr+8, 0L);                // Data size
2318                 symtype = 0x05000000;
2319                 obj_segsize[obj_index][0] = dsize;
2320                 obj_segsize[obj_index][1] = 0;
2321                 obj_segsize[obj_index][2] = 0;
2322         }
2323         else
2324         {
2325                 putlong(ptr+4, 0L);                // Text size
2326                 putlong(ptr+8, dsize);             // Data size
2327                 symtype = 0x07000000;
2328                 obj_segsize[obj_index][0] = 0;
2329                 obj_segsize[obj_index][1] = dsize;
2330                 obj_segsize[obj_index][2] = 0;
2331         }
2332
2333         obj_index++;                           // Increment object count
2334
2335         putlong(ptr+12, 0L);                   // BSS size
2336         putlong(ptr+16, 24);                   // Symbol table size
2337         putlong(ptr+20, 0L);                   // Entry point
2338         putlong(ptr+24, 0L);                   // TEXT relocation size
2339         putlong(ptr+28, 0L);                   // DATA relocation size
2340
2341         sptr = ptr + 32 + dsize;               // Set sptr to symbol table location
2342
2343         putlong(sptr,    4L);                  // String offset of symbol1
2344         putlong(sptr+4,  symtype);             // Symbol type
2345         putlong(sptr+8,  0x00000000);          // Symbol has no value (START)
2346         putlong(sptr+12, 4L + (sym2len - 1));  // String offset of symbol2
2347         putlong(sptr+16, symtype);             // Symbol type
2348         putlong(sptr+20, dsize);               // Symbol is data size (END)
2349
2350         sptr = ptr + 32 + dsize + 24;          // Set sptr to symbol table size loc
2351
2352         putlong(sptr, sym1len + 4L);           // Size of symbol table
2353
2354         sptr = ptr + 32 + dsize + 24 + 4;      // Set sptr to symbol table location
2355
2356         for(i=0; i<(sym1len-1); i++)           // Write symbol1 to string table
2357                 sptr[i] = *sym1++;
2358
2359         sptr += (sym1len - 1);                 // Step past symbol string
2360         *sptr = '\0';                          // Terminate symbol string
2361         sptr += 1;                             // Step past termination
2362
2363         for(i=0; i<(sym2len-1); i++)           // Write symbol2 to string table
2364                 sptr[i] = *sym2++;
2365
2366         sptr += (sym2len - 1);                 // Step past symbol string
2367         *sptr = '\0';                          // Terminate symbol string
2368         sptr += 1;                             // Step past termination
2369
2370         putlong(sptr, 0L);                     // Terminating long for object file
2371
2372         return AddToProcessingList(ptr, fname, nullStr, 0);
2373 }
2374
2375
2376 //
2377 // Takes a file name, gets in its image, puts it on plist. The image may
2378 // already be in memory: If so, the ptr arg is non-null.  If so, the file is
2379 // already closed. Note that the file is already open (from DoFile()). RETURNS
2380 // a pointer to the OFILE structure for this file, so you can diddle its flags
2381 // (DoFile sets O_USED for files on the command line).
2382 //
2383 int LoadObject(char * fname, int fd, char * ptr)
2384 {
2385         if (ptr == NULL)
2386         {
2387                 long size = FileSize(fd);
2388
2389                 // Allocate memory for file data
2390                 ptr = malloc(size);
2391
2392                 if (ptr == NULL)
2393                 {
2394                         printf("Out of memory while processing %s\n", fname);
2395                         close(fd);
2396                         return 1;
2397                 }
2398
2399                 // Read in file data
2400                 if (read(fd, ptr, size) != size)
2401                 {
2402                         printf("File read error on %s\n", fname);
2403                         close(fd);
2404                         free(ptr);
2405                         return 1;
2406                 }
2407
2408                 // SCPCD : get the name of the file instead of all pathname
2409                 strcpy(obj_fname[obj_index], path_tail(fname));
2410                 obj_segsize[obj_index][0] = (getlong(ptr + 4) + secalign) & ~secalign;
2411                 obj_segsize[obj_index][1] = (getlong(ptr + 8) + secalign) & ~secalign;
2412                 obj_segsize[obj_index][2] = (getlong(ptr + 12) + secalign) & ~secalign;
2413                 obj_index++;
2414
2415                 close(fd);                                            // Close file
2416         }
2417
2418         // Now add this image to the list of pending ofiles (plist)
2419         // This routine is shared by LoadInclude after it builds the image
2420         return AddToProcessingList(ptr, fname, nullStr, 0);
2421 }
2422
2423
2424 //
2425 // What it says on the tin: check for a .o suffix on the passed in string
2426 //
2427 uint8_t HasDotOSuffix(char * s)
2428 {
2429         char * temp = strrchr(s, '.');
2430
2431         if ((temp == NULL) || (strncmp(temp, ".o", 2) != 0))
2432                 return 0;
2433
2434         return 1;
2435 }
2436
2437
2438 //
2439 // Process an ar archive file (*.a)
2440 //
2441 int LoadArchive(char * fname, int fd)
2442 {
2443         // Read in the archive file to memory and process
2444         long size = FileSize(fd);
2445         char * ptr = malloc(size);
2446         char * endPtr = ptr + size;
2447         char * longFilenames = NULL;
2448
2449         if (ptr == NULL)
2450         {
2451                 printf("Out of memory while processing %s\n", fname);
2452                 close(fd);
2453                 return 1;
2454         }
2455
2456         if (read(fd, ptr, size) != size)
2457         {
2458                 printf("File read error on %s\n", fname);
2459                 close(fd);
2460                 free(ptr);
2461                 return 1;
2462         }
2463
2464         close(fd);
2465
2466         // Save the pointer for later...
2467         arPtr[arIndex++] = ptr;
2468         char objName[FNLEN];
2469         char objSize[11];
2470         int i;
2471 //printf("\nProcessing AR file \"%s\"...\n", fname);
2472         ptr += 8;
2473
2474         // Loop through all objects in the archive and process them
2475         do
2476         {
2477                 memset(objName, 0, 17);
2478                 objSize[10] = 0;
2479
2480                 for(i=0; i<16; i++)
2481                 {
2482 //                      if ((ptr[i] == '/') || (ptr[i] == ' '))
2483                         if ((ptr[i] == ' ') && (i != 0))
2484                         {
2485                                 objName[i] = 0;
2486                                 break;
2487                         }
2488
2489                         objName[i] = ptr[i];
2490                 }
2491
2492                 for(i=0; i<10; i++)
2493                 {
2494                         if (ptr[48 + i] == ' ')
2495                         {
2496                                 objSize[i] = 0;
2497                                 break;
2498                         }
2499
2500                         objSize[i] = ptr[48 + i];
2501                 }
2502
2503                 // Check to see if a long filename was requested
2504                 if (objName[0] == 0x20)
2505                 {
2506                         uint32_t fnSize = atoi(objName + 1);
2507
2508                         if (longFilenames != NULL)
2509                         {
2510                                 i = 0;
2511                                 char * currentFilename = longFilenames + fnSize;
2512
2513                                 while (*currentFilename != 0x0A)
2514                                         objName[i++] = *currentFilename++;
2515
2516                                 objName[i] = 0;
2517                         }
2518                 }
2519
2520                 if ((strncmp(objName, "ARFILENAMES/", 12) == 0) || (strncmp(objName, "//", 2) == 0))
2521                 {
2522                         longFilenames = ptr + 60;
2523                 }
2524                 else if (HasDotOSuffix(objName))
2525                 {
2526 //printf("Processing object \"%s\" (size == %i, obj_index == %i)...\n", objName, atoi(objSize), obj_index);
2527                         strcpy(obj_fname[obj_index], objName);
2528                         obj_segsize[obj_index][0] = (getlong(ptr + 60 + 4) + secalign) & ~secalign;
2529                         obj_segsize[obj_index][1] = (getlong(ptr + 60  + 8) + secalign) & ~secalign;
2530                         obj_segsize[obj_index][2] = (getlong(ptr + 60  + 12) + secalign) & ~secalign;
2531                         obj_index++;
2532
2533                         if (AddToProcessingList(ptr + 60, objName, fname, 1))
2534                                 return 1;
2535                 }
2536
2537                 uint32_t size = atoi(objSize);
2538                 size += (size & 0x01 ? 1 : 0);
2539                 ptr += 60 + size;
2540         }
2541         while (ptr < endPtr);
2542
2543         return 0;
2544 }
2545
2546
2547 //
2548 // Process files (*.o, *.a) passed in on the command line
2549 //
2550 int ProcessFiles(void)
2551 {
2552         int i;
2553         char magic[8];          // Magic header number (4 bytes for *.o, 8 for *.a)
2554
2555         // Process all file handles
2556         for(i=0; i<(int)hd; i++)
2557         {
2558                 // Verbose mode information
2559                 if (vflag == 1)
2560                         printf("Read file %s%s\n", name[i], (hflag[i] ? " (include)" : ""));
2561
2562                 if (!hflag[i])
2563                 {
2564                         // Attempt to read file magic number (OBJECT/ARCHIVE FILES)
2565                         if (read(handle[i], magic, 8) != 8)
2566                         {
2567                                 printf("Error reading file %s\n", name[i]);
2568                                 close(handle[i]);
2569                                 return 1;
2570                         }
2571
2572                         lseek(handle[i], 0L, 0);        // Reset to start of input file
2573
2574                         // Look for RMAC/MAC/GCC ($20107) object files
2575                         if ((getlong(magic) == 0x00000107) || (getlong(magic) == 0x00020107))
2576                         {
2577                                 // Process input object file
2578                                 if (LoadObject(name[i], handle[i], 0L))
2579                                         return 1;
2580                         }
2581                         // Otherwise, look for an object archive file
2582                         else if (strncmp(magic, "!<arch>\x0A", 8) == 0)
2583                         {
2584                                 if (LoadArchive(name[i], handle[i]))
2585                                         return 1;
2586                         }
2587                         else
2588                         {
2589                                 // Close file and error
2590                                 printf("%s is not a supported object or archive file\n", name[i]);
2591                                 close(handle[i]);
2592                                 return 1;
2593                         }
2594                 }
2595                 else
2596                 {
2597                         // INCLUDE FILES
2598                         // If hflag[i] is 1, include this in the data segment; if 2, put it
2599                         // in text segment
2600                         if (LoadInclude(name[i], handle[i], hsym1[i], hsym2[i], hflag[i] - 1))
2601                                 return 1;
2602                 }
2603         }
2604
2605         // Free include, symbol & object handles
2606         for(i=0; i<(int)hd; i++)
2607         {
2608                 free(name[i]);
2609
2610                 if (hflag[i])
2611                 {
2612                         free(hsym1[i]);
2613                         free(hsym2[i]);
2614                 }
2615         }
2616
2617         // Reset next handle indicator
2618         hd = 0;
2619         return 0;
2620 }
2621
2622
2623 //
2624 // Load newargv with pointers to arguments found in the buffer
2625 //
2626 int parse(char * buf, char * newargv[])
2627 {
2628         int i = 1;
2629
2630         if (vflag)
2631                 printf("begin parsing\n");
2632
2633         while (1)
2634         {
2635                 while (*buf && strchr(",\t\n\r\14 ", *buf))
2636                         buf++;
2637
2638                 /* test for eof */
2639                 if (*buf == '\0' || *buf == 26)
2640                 {
2641                         if (i == 0)
2642                         {
2643                                 printf("No commands in command file\n");
2644                                 return -1;
2645                         }
2646                         else
2647                         {
2648                                 return i;
2649                         }
2650                 }
2651
2652                 /* test for comment */
2653                 if (*buf == '#')
2654                 {
2655                         /* found a comment; skip to next \n and start over */
2656                         while (*buf && *buf != '\n')
2657                                 buf++;
2658
2659                         continue;
2660                 }
2661
2662                 if (i == MAXARGS)
2663                 {
2664                         printf("Too many arguments in command file\n");
2665                         return -1;
2666                 }
2667
2668                 newargv[i] = buf;
2669
2670                 while (!strchr(",\t\n\r\14 ", *buf))
2671                 {
2672                         if (*buf == '\0' || *buf == 26)
2673                         {
2674                                 printf("Finished parsing %d args\n", i);
2675                                 return i;
2676                         }
2677
2678                         buf++;
2679                 }
2680
2681                 *buf++ = '\0';
2682
2683                 if (vflag)
2684                         printf("argv[%d] = \"%s\"\n", i, newargv[i]);
2685
2686                 i++;
2687         }
2688 }
2689
2690
2691 //
2692 // Process in a Link Command File
2693 //
2694 int docmdfile(char * fname)
2695 {
2696         int fd;                                     // File descriptor
2697         unsigned size;                              // Command file size
2698         char * ptr;                                 // Pointer
2699         int newargc;                                // New argument count
2700         char * (*newargv)[];                        // New argument value array
2701
2702         // Verbose information
2703         if (vflag > 1)
2704                 printf("docmdfile(%s)\n", fname);
2705
2706         // Allocate memory for new argument values
2707         newargv = malloc((long)(sizeof(char *) * MAXARGS));
2708
2709         if (!newargv)
2710         {
2711                 printf("Out of memory.\n");
2712                 return 1;
2713         }
2714
2715         // Attempt to open and read in the command file
2716         if (fname)
2717         {
2718                 if ((fd = open(fname, _OPEN_FLAGS)) < 0)
2719                 {
2720                         printf("Cannot open command file %s.\n", fname);
2721                         return 1;
2722                 }
2723
2724                 size = FileSize(fd);
2725
2726                 if ((ptr = malloc(size + 1)) == NULL)
2727                 {
2728                         printf("Out of memory.\n");
2729                         close(fd);
2730                         return 1;
2731                 }
2732
2733                 if (read(fd, ptr, size) != (int)size)
2734                 {
2735                         printf("Read error on command file %s.\n", fname);
2736                         close(fd);
2737                         return 1;
2738                 }
2739
2740                 *(ptr + size) = 0;                      // Null terminate the buffer
2741                 close(fd);
2742         }
2743         else
2744         {
2745                 printf("No command filename specified\n");
2746                 return 1;
2747         }
2748
2749         // Parse the command file
2750         if ((newargc = parse(ptr, *newargv)) == -1)
2751         {
2752                 return 1;
2753         }
2754
2755         // Process the inputted flags
2756         if (doargs(newargc, *newargv))
2757         {
2758                 printf("docmdfile: doargs returns TRUE\n");
2759                 return 1;
2760         }
2761
2762         free(ptr);
2763         free(newargv);
2764
2765         return 0;
2766 }
2767
2768
2769 //
2770 // Take an Argument List and Parse the Command Line
2771 //
2772 int doargs(int argc, char * argv[])
2773 {
2774         int i = 1;                                      // Iterator
2775         int c;                                          // Command line character
2776         char * ifile, * isym;           // File name and symbol name for -i
2777
2778         // Parse through option switches & files
2779         while (i < argc)
2780         {
2781                 // Process command line switches
2782                 if (argv[i][0] == '-')
2783                 {
2784                         if (!argv[i][1])
2785                         {
2786                                 printf("Illegal option argument: %s\n\n", argv[i]);
2787                                 display_help();
2788                                 return 1;
2789                         }
2790
2791                         c = argv[i++][1];                       // Get next character in command line
2792
2793                         // Process command line switch
2794                         switch (c)
2795                         {
2796                         case '?':                                       // Display usage information
2797                         case 'h':
2798                         case 'H':
2799                                 display_version();
2800                                 display_help();
2801                                 return 1;
2802                         case 'a':
2803                         case 'A':                                       // Set absolute linking on
2804                                 if (aflag)
2805                                         warn('a', 1);
2806
2807                                 if (i + 2 >= argc)
2808                                 {
2809                                         printf("Not enough arguments to -a\n");
2810                                         return 1;
2811                                 }
2812
2813                                 aflag = 1;                              // Set abs link flag
2814                                 // Segment order is TEXT, DATA, BSS
2815                                 // Text segment can be 'r', 'x' or a value
2816                                 ttype = 0;
2817
2818                                 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2819                                 {
2820                                         ttype = -1;                     // TEXT segment is relocatable
2821                                 }
2822                                 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2823                                 {
2824                                         printf("Error in text-segment address: cannot be contiguous\n");
2825                                         return 1;
2826                                 }
2827                                 else if ((ttype = 0), getval(argv[i], &tval))
2828                                 {
2829                                         printf("Error in text-segment address: %s is not 'r', 'x' or an address.", argv[i]);
2830                                         return 1;
2831                                 }
2832
2833                                 i++;
2834                                 // Data segment can be 'r', 'x' or a value
2835                                 dtype = 0;
2836
2837                                 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2838                                 {
2839                                         dtype = -1;                     // DATA segment is relocatable
2840                                 }
2841                                 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2842                                 {
2843                                         dtype = -2;                     // DATA follows TEXT
2844                                 }
2845                                 else if ((dtype = 0), getval(argv[i],&dval))
2846                                 {
2847                                         printf("Error in data-segment address: %s is not 'r', 'x' or an address.", argv[i]);
2848                                         return 1;
2849                                 }
2850
2851                                 i++;
2852                                 btype = 0;
2853
2854                                 // BSS segment can be 'r', 'x' or a value
2855                                 if ((*argv[i] == 'r' || *argv[i] == 'R') && !argv[i][1])
2856                                 {
2857                                         btype = -1;                     // BSS segment is relocatable
2858                                 }
2859                                 else if ((*argv[i] == 'x' || *argv[i] == 'X'))
2860                                 {
2861                                         btype = -3;                     // BSS follows DATA
2862                                 }
2863                                 else if ((btype = 0), getval(argv[i],&bval))
2864                                 {
2865                                         printf("Error in bss-segment address: %s is not 'r', 'x[td]', or an address.", argv[i]);
2866                                         return 1;
2867                                 }
2868
2869                                 i++;
2870                                 break;
2871                         case 'b':
2872                         case 'B':                                       // Don't remove muliply defined locals
2873                                 if (bflag)
2874                                         warn('b', 1);
2875
2876                                 bflag = 1;
2877                                 break;
2878                         case 'c':
2879                         case 'C':                                       // Process a command file
2880                                 if (i == argc)
2881                                 {
2882                                         printf("Not enough arguments to -c\n");
2883                                         return 1;
2884                                 }
2885
2886                                 if (docmdfile(argv[i++]))
2887                                 {
2888                                         return 1;
2889                                 }
2890
2891                                 break;
2892                         case 'd':
2893                         case 'D':                                       // Wait for "return" before exiting
2894                                 if (dflag)
2895                                         warn('d', 0);
2896
2897                                 dflag = 1;
2898                                 waitflag = 1;
2899                                 break;
2900                         case 'e':
2901                         case 'E':                                       // Output COFF (absolute only)
2902                                 cflag = 1;
2903                                 break;
2904                         case 'g':
2905                         case 'G':                                       // Output source level debugging
2906                                 printf("\'g\' flag not currently implemented\n");
2907                                 gflag = 0;
2908                                 /*
2909                                 if (gflag) warn('g', 1);
2910                                 gflag = 1;
2911                                 */
2912                                 break;
2913                         case 'i':
2914                         case 'I':                                       // Include binary file
2915                                 if (i + 2 > argc)
2916                                 {
2917                                         printf("Not enough arguments to -i\n");
2918                                         return 1;
2919                                 }
2920
2921                                 ifile = argv[i++];
2922                                 isym = argv[i++];
2923
2924                                 // handle -ii (No truncation)
2925                                 if ((argv[i-3][2] == 'i') || (argv[i-3][2] == 'I'))
2926                                 {
2927                                         if (!cflag)
2928                                                 printf("warning: (-ii) COFF format output not specified\n");
2929                                 }
2930                                 // handle -i (Truncation)
2931                                 else
2932                                 {
2933                                         if (strlen(isym) > 7)
2934                                                 isym[7] = '\0';
2935                                 }
2936
2937                                 // Place include files in the DATA segment only
2938                                 if (DoFile(ifile, DSTSEG_D, isym))
2939                                         return 1;
2940
2941                                 break;
2942                         case 'l':
2943                         case 'L':                                       // Add local symbols
2944                                 if (lflag)
2945                                         warn('l', 1);
2946
2947                                 lflag = 1;
2948                                 break;
2949                         case 'm':
2950                         case 'M':                                       // Produce load symbol map
2951                                 if (mflag)
2952                                         warn('m', 1);
2953
2954                                 mflag = 1;
2955                                 break;
2956                         case 'n':
2957                         case 'N':                                       // Output no header to .abs file
2958                                 if (noheaderflag)
2959                                         warn('n', 1);
2960
2961                                 noheaderflag = 1;
2962                                 break;
2963                         case 'o':
2964                         case 'O':                                       // Specify an output file
2965                                 if (oflag)
2966                                         warn('o', 1);
2967
2968                                 oflag = 1;
2969
2970                                 if (i >= argc)
2971                                 {
2972                                         printf("No output filename following -o switch\n");
2973                                         return 1;
2974                                 }
2975
2976                                 if (strlen(argv[i]) > FARGSIZE - 5)
2977                                 {
2978                                         printf("Output file name too long (sorry!)\n");
2979                                         return 1;
2980                                 }
2981
2982                                 strcpy(ofile, argv[i++]);
2983                                 break;
2984                         case 'r':
2985                         case 'R':                                       // Section alignment size
2986                                 if (rflag)
2987                                         warn('r', 1);
2988
2989                                 rflag = 1;
2990
2991                                 switch (argv[i-1][2])
2992                                 {
2993                                         case 'w': case 'W': secalign = 1;  break; // Word alignment
2994                                         case 'l': case 'L': secalign = 3;  break; // Long alignment
2995                                         case 'p': case 'P': secalign = 7;  break; // Phrase alignment
2996                                         case 'd': case 'D': secalign = 15; break; // Double phrase alignment
2997                                         case 'q': case 'Q': secalign = 31; break; // Quad phrase alignment
2998                                         default:            secalign = 7;  break; // Default phrase alignment
2999                                 }
3000
3001                                 break;
3002                         case 's':
3003                         case 'S':                                       // Output only global symbols
3004                                 if (sflag)
3005                                         warn('s', 1);
3006
3007                                 sflag = 1;
3008                                 break;
3009                         case 'v':
3010                         case 'V':                                       // Verbose information
3011                                 if (!vflag && !versflag)
3012                                 {
3013                                         display_version();
3014                                 }
3015
3016                                 vflag++;
3017                                 break;
3018                         case 'w':
3019                         case 'W':                                       // Show warnings flag
3020                                 if (wflag)
3021                                         warn('w', 1);
3022
3023                                 wflag = 1;
3024                                 break;
3025                         case 'z':
3026                         case 'Z':                                       // Suppress banner flag
3027                                 if (zflag)
3028                                         warn('z', 1);
3029
3030                                 zflag = 1;
3031                                 break;
3032                         default:
3033                                 printf("unknown option argument `%c'\n", c);
3034                                 return 1;
3035                         }
3036                 }
3037                 else
3038                 {
3039                         // Not a switch, then process as a file
3040                         if (DoFile(argv[i++], 0, NULL))
3041                                 return 1;
3042                 }
3043         }
3044
3045         if (!oflag && vflag)
3046         {
3047                 strcpy(ofile, "output");
3048                 printf("Output file is %s[.ext]\n", ofile);
3049         }
3050
3051         if (oflag && vflag)
3052                 printf("Output file is %s\n", ofile);
3053
3054         if (sflag)
3055                 lflag = 0;
3056
3057         // No problems encountered
3058         return 0;
3059 }
3060
3061
3062 //
3063 // Display Version Information
3064 //
3065 void display_version(void)
3066 {
3067         if (displaybanner)// && vflag)
3068         {
3069                 printf("\nReboot's Linker for Atari Jaguar\n");
3070                 printf("Copyright (c) 199x Allan K. Pratt, 2014 Reboot\n");
3071                 printf("V%i.%i.%i %s (%s)\n\n", MAJOR, MINOR, PATCH, __DATE__, PLATFORM);
3072         }
3073 }
3074
3075
3076 //
3077 // Display Command Line Help
3078 //
3079 void display_help(void)
3080 {
3081         printf("Usage:\n");
3082         printf("    %s [-options] file(s)\n", cmdlnexec);
3083         printf("\n");
3084         printf("Options:\n");
3085         printf("   -? or -h                display usage information\n");
3086         printf("   -a <text> <data> <bss>  output absolute file\n");
3087         printf("                           hex value: segment address\n");
3088         printf("                           r: relocatable segment\n");
3089         printf("                           x: contiguous segment\n");
3090         printf("   -b                      don't remove multiply defined local labels\n");
3091         printf("   -c <fname>              add contents of <fname> to command line\n");
3092         printf("   -d                      wait for key after link\n");
3093         printf("   -e                      output COF absolute file\n");
3094         printf("   -g                      output source-level debugging\n");
3095         printf("   -i <fname> <label>      incbin <fname> and set <label>\n");
3096         printf("   -l                      add local symbols\n");
3097         printf("   -m                      produce load symbols map\n");
3098         printf("   -n                      output no file header to .abs file\n");
3099         printf("   -o <fname>              set output name\n");
3100         printf("   -r<size>                section alignment size\n");
3101         printf("                           w: word (2 bytes)\n");
3102         printf("                           l: long (4 bytes)\n");
3103         printf("                           p: phrase (8 bytes, default alignment)\n");
3104         printf("                           d: double phrase (16 bytes)\n");
3105         printf("                           q: quad phrase (32 bytes)\n");
3106         printf("   -s                      output only global symbols\n");
3107         printf("   -v                      set verbose mode\n");
3108         printf("   -w                      show linker warnings\n");
3109         printf("   -z                      suppress banner\n");
3110         printf("\n");
3111 }
3112
3113
3114 //
3115 // Application Exit
3116 //
3117 void rln_exit(void)
3118 {
3119         char tempbuf[128];
3120
3121         // Display link status if verbose mode
3122         if (vflag)
3123                 printf("Link %s.\n", errflag ? "aborted" : "complete");
3124
3125         // Wait for return key if requested
3126         if (waitflag)
3127         {
3128                 printf("\nPress the [RETURN] key to continue. ");
3129                 fgets(tempbuf, 128, stdin);
3130         }
3131
3132         exit(errflag);
3133 }
3134
3135
3136 //
3137 // Determine Processor Endianess
3138 //
3139 int get_endianess(void)
3140 {
3141         int i = 1;
3142         char * p = (char *)&i;
3143
3144         if (p[0] == 1)
3145                 return ENDIANNESS_LITTLE;
3146
3147         return ENDIANNESS_BIG;
3148 }
3149
3150
3151 //
3152 // Application Code Starts Here
3153 //
3154 int main(int argc, char * argv[])
3155 {
3156         char * s = NULL;                                // String pointer for "getenv"
3157         struct HREC * utemp;                    // Temporary hash record pointer
3158         struct OHEADER * header;                // Pointer to output header structure
3159
3160         endian = get_endianess();               // Get processor endianess
3161         cmdlnexec = argv[0];                    // Obtain executable name
3162         s = getenv("RLNPATH");
3163
3164         if (s)                                                  // Attempt to obtain env variable
3165                 strcpy(libdir, s);                      // Store it if found
3166
3167         // Parse the command line
3168         if (doargs(argc, argv))
3169         {
3170                 errflag = 1;
3171                 rln_exit();
3172         }
3173
3174         if (!zflag && !vflag)
3175         {
3176                 display_version();                      // Display version information
3177                 versflag = 1;                           // We've dumped the version banner
3178         }
3179
3180         // Load in specified files/objects and add to processing list
3181         if (ProcessFiles())
3182         {
3183                 errflag = 1;
3184                 rln_exit();
3185         }
3186
3187         // Work in items in processing list & deal with unresolved list
3188         if (ProcessLists())
3189         {
3190                 errflag = 1;
3191                 rln_exit();
3192         }
3193
3194         // Check that there is something to link
3195         if (olist == NULL)
3196         {
3197                 display_help();
3198                 rln_exit();
3199         }
3200
3201         // Report unresolved externals
3202         if (unresolved != NULL)
3203         {
3204                 printf("UNRESOLVED SYMBOLS\n");
3205
3206                 // Don't list them if two -u's or more
3207                 if (uflag < 2)
3208                 {
3209                         utemp = unresolved;
3210
3211                         while (utemp != NULL)
3212                         {
3213                                 printf("\t%s (",utemp->h_sym);
3214                                 put_name(utemp->h_ofile);
3215                                 printf(")\n");
3216                                 utemp = utemp->h_next;
3217                         }
3218                 }
3219
3220                 if (!uflag)
3221                 {
3222                         errflag = 1;
3223                         rln_exit();
3224                 }
3225         }
3226
3227         // Make one output file from input objs
3228         header = make_ofile();
3229
3230         if (header == NULL)
3231         {
3232                 errflag = 1;
3233                 rln_exit();
3234         }
3235
3236         // Partial linking
3237         if (pflag)
3238         {
3239                 printf("TO DO:Partial linking\n");
3240                 errflag = 1;
3241         }
3242         // Relocatable linking
3243         else if (!aflag)
3244         {
3245                 printf("TO DO:Relocatable linking\n");
3246                 errflag = 1;
3247         }
3248         // Absolute linking
3249         else
3250         {
3251                 if (vflag)
3252                 {
3253                         printf("Absolute linking ");
3254
3255                         if (cflag)
3256                                 printf("(COF)\n"); 
3257                         else
3258                                 printf("(ABS)\n");
3259                 }
3260
3261                 if (vflag > 1)
3262                         printf("Header magic is 0x%04X\n", (unsigned int)header->magic);
3263
3264                 if (write_ofile(header))
3265                         errflag = 1;
3266         }
3267
3268         // Display the loaded symbols map
3269         if (mflag)
3270                 if (write_map(header))
3271                         errflag = 1;
3272
3273         // Display segment size summary
3274         if (vflag)
3275         {
3276                 printf("\n");
3277                 printf("+---------+----------+----------+----------+\n");
3278                 printf("| Segment |     TEXT |     DATA |      BSS |\n");
3279                 printf("| Sizes   |----------+----------+----------|\n");
3280                 printf("| (Hex)   | %8X | %8X | %8X |\n", (unsigned int)header->tsize, (unsigned int)header->dsize, (unsigned int)header->bsize);
3281                 printf("+---------+----------+----------+----------+\n\n");
3282         }
3283
3284 //printf("BIG_ENDIAN = %i, LITTLE_ENDIAN = %i\n", BIG_ENDIAN, LITTLE_ENDIAN);
3285
3286         free(header);
3287         rln_exit();
3288 }
3289