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