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