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