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