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