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