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