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