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