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