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