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