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