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