]> git.sur5r.net Git - cc65/blob - src/ld65/o65.c
efc7856bc151bf6bada953246244513df99f55a4
[cc65] / src / ld65 / o65.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                   o65.c                                   */
4 /*                                                                           */
5 /*                  Module to handle the o65 binary format                   */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1999-2003 Ullrich von Bassewitz                                       */
10 /*               Römerstraße 52                                              */
11 /*               D-70794 Filderstadt                                         */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdio.h>
37 #include <string.h>
38 #include <limits.h>
39 #include <errno.h>
40 #include <time.h>
41
42 /* common */
43 #include "chartype.h"
44 #include "check.h"
45 #include "print.h"
46 #include "version.h"
47 #include "xmalloc.h"
48
49 /* ld65 */
50 #include "error.h"
51 #include "exports.h"
52 #include "expr.h"
53 #include "fileio.h"
54 #include "global.h"
55 #include "lineinfo.h"
56 #include "o65.h"
57 #include "spool.h"
58
59
60
61 /*****************************************************************************/
62 /*                                   Data                                    */
63 /*****************************************************************************/
64
65
66
67 /* Header mode bits */
68 #define MF_CPU_65816    0x8000          /* Executable is for 65816 */
69 #define MF_CPU_6502     0x0000          /* Executable is for the 6502 */
70 #define MF_CPU_MASK     0x8000          /* Mask to extract CPU type */
71
72 #define MF_RELOC_PAGE   0x4000          /* Page wise relocation */
73 #define MF_RELOC_BYTE   0x0000          /* Byte wise relocation */
74 #define MF_RELOC_MASK   0x4000          /* Mask to extract relocation type */
75
76 #define MF_SIZE_32BIT   0x2000          /* All size words are 32bit */
77 #define MF_SIZE_16BIT   0x0000          /* All size words are 16bit */
78 #define MF_SIZE_MASK    0x2000          /* Mask to extract size */
79
80 #define MF_FTYPE_OBJ    0x1000          /* Object file */
81 #define MF_FTYPE_EXE    0x0000          /* Executable file */
82 #define MF_FTYPE_MASK   0x1000          /* Mask to extract type */
83
84 #define MF_ADDR_SIMPLE  0x0800          /* Simple addressing */
85 #define MF_ADDR_DEFAULT 0x0000          /* Default addressing */
86 #define MF_ADDR_MASK    0x0800          /* Mask to extract addressing */
87
88 #define MF_ALIGN_1      0x0000          /* Bytewise alignment */
89 #define MF_ALIGN_2      0x0001          /* Align words */
90 #define MF_ALIGN_4      0x0002          /* Align longwords */
91 #define MF_ALIGN_256    0x0003          /* Align pages (256 bytes) */
92 #define MF_ALIGN_MASK   0x0003          /* Mask to extract alignment */
93
94 /* The four o65 segment types. Note: These values are identical to the values
95  * needed for the segmentID in the o65 spec.
96  */
97 #define O65SEG_UNDEF    0x00
98 #define O65SEG_ABS      0x01
99 #define O65SEG_TEXT     0x02
100 #define O65SEG_DATA     0x03
101 #define O65SEG_BSS      0x04
102 #define O65SEG_ZP       0x05
103
104 /* Relocation type codes for the o65 format */
105 #define O65RELOC_WORD   0x80
106 #define O65RELOC_HIGH   0x40
107 #define O65RELOC_LOW    0x20
108 #define O65RELOC_SEGADR 0xC0
109 #define O65RELOC_SEG    0xA0
110 #define O65RELOC_MASK   0xE0
111
112 /* O65 executable file header */
113 typedef struct O65Header O65Header;
114 struct O65Header {
115     unsigned        Version;            /* Version number for o65 format */
116     unsigned        Mode;               /* Mode word */
117     unsigned long   TextBase;           /* Base address of text segment */
118     unsigned long   TextSize;           /* Size of text segment */
119     unsigned long   DataBase;           /* Base of data segment */
120     unsigned long   DataSize;           /* Size of data segment */
121     unsigned long   BssBase;            /* Base of bss segment */
122     unsigned long   BssSize;            /* Size of bss segment */
123     unsigned long   ZPBase;             /* Base of zeropage segment */
124     unsigned long   ZPSize;             /* Size of zeropage segment */
125     unsigned long   StackSize;          /* Requested stack size */
126 };
127
128 /* An o65 option */
129 typedef struct O65Option O65Option;
130 struct O65Option {
131     O65Option*      Next;               /* Next in option list */
132     unsigned char   Type;               /* Type of option */
133     unsigned char   Len;                /* Data length */
134     unsigned char   Data [1];           /* Data, dynamically allocated */
135 };
136
137 /* A o65 relocation table */
138 #define RELOC_BLOCKSIZE 4096
139 typedef struct O65RelocTab O65RelocTab;
140 struct O65RelocTab {
141     unsigned        Size;               /* Size of the table */
142     unsigned        Fill;               /* Amount used */
143     unsigned char*  Buf;                /* Buffer, dynamically allocated */
144 };
145
146 /* Structure describing the format */
147 struct O65Desc {
148     O65Header       Header;             /* File header */
149     O65Option*      Options;            /* List of file options */
150     ExtSymTab*      Exports;            /* Table with exported symbols */
151     ExtSymTab*      Imports;            /* Table with imported symbols */
152     unsigned        Undef;              /* Count of undefined symbols */
153     FILE*           F;                  /* The file we're writing to */
154     const char*     Filename;           /* Name of the output file */
155     O65RelocTab*    TextReloc;          /* Relocation table for text segment */
156     O65RelocTab*    DataReloc;          /* Relocation table for data segment */
157
158     unsigned        TextCount;          /* Number of segments assigned to .text */
159     SegDesc**       TextSeg;            /* Array of text segments */
160     unsigned        DataCount;          /* Number of segments assigned to .data */
161     SegDesc**       DataSeg;            /* Array of data segments */
162     unsigned        BssCount;           /* Number of segments assigned to .bss */
163     SegDesc**       BssSeg;             /* Array of bss segments */
164     unsigned        ZPCount;            /* Number of segments assigned to .zp */
165     SegDesc**       ZPSeg;              /* Array of zp segments */
166
167     /* Temporary data for writing segments */
168     unsigned long   SegSize;
169     O65RelocTab*    CurReloc;
170     long            LastOffs;
171 };
172
173 /* Structure for parsing expression trees */
174 typedef struct ExprDesc ExprDesc;
175 struct ExprDesc {
176     O65Desc*        D;                  /* File format descriptor */
177     long            Val;                /* The offset value */
178     int             TooComplex;         /* Expression too complex */
179     Memory*         MemRef;             /* Memory reference if any */
180     Segment*        SegRef;             /* Segment reference if any */
181     Section*        SecRef;             /* Section reference if any */
182     ExtSym*         ExtRef;             /* External reference if any */
183 };
184
185
186
187 /*****************************************************************************/
188 /*                             Helper functions                              */
189 /*****************************************************************************/
190
191
192
193 static ExprDesc* InitExprDesc (ExprDesc* ED, O65Desc* D)
194 /* Initialize an ExprDesc structure for use with O65ParseExpr */
195 {
196     ED->D          = D;
197     ED->Val        = 0;
198     ED->TooComplex = 0;
199     ED->MemRef     = 0;
200     ED->SegRef     = 0;
201     ED->SecRef     = 0;
202     ED->ExtRef     = 0;
203     return ED;
204 }
205
206
207
208 static void WriteSize (const O65Desc* D, unsigned long Val)
209 /* Write a "size" word to the file */
210 {
211     switch (D->Header.Mode & MF_SIZE_MASK) {
212         case MF_SIZE_16BIT:     Write16 (D->F, (unsigned) Val); break;
213         case MF_SIZE_32BIT:     Write32 (D->F, Val);            break;
214         default:                Internal ("Invalid size in header: %04X", D->Header.Mode);
215     }
216 }
217
218
219
220 static unsigned O65SegType (const SegDesc* S)
221 /* Map our own segment types into something o65 compatible */
222 {
223     /* Check the segment type. Readonly segments are assign to the o65
224      * text segment, writeable segments that contain data are assigned
225      * to data, bss and zp segments are handled respectively.
226      * Beware: Zeropage segments have the SF_BSS flag set, so be sure
227      * to check SF_ZP first.
228      */
229     if (S->Flags & SF_RO) {
230         return O65SEG_TEXT;
231     } else if (S->Flags & SF_ZP) {
232         return O65SEG_ZP;
233     } else if (S->Flags & SF_BSS) {
234         return O65SEG_BSS;
235     } else {
236         return O65SEG_DATA;
237     }
238 }
239
240
241
242 static void CvtMemoryToSegment (ExprDesc* ED)
243 /* Convert a memory area into a segment by searching the list of run segments
244  * in this memory area and assigning the nearest one.
245  */
246 {
247     /* Get the memory area from the expression */
248     Memory* M = ED->MemRef;
249
250     /* Get the list of segments in this memory area */
251     MemListNode* N = M->SegList;
252
253     /* Remember the "nearest" segment and its offset */
254     Segment* Nearest   = 0;
255     unsigned long Offs = ULONG_MAX;
256
257     /* Walk over all segments */
258     while (N != 0) {
259
260         /* Get the segment from this node and check if it's a run segment */
261         SegDesc* S = N->Seg;
262         if (S->Run == M) {
263
264             unsigned long O;
265
266             /* Get the segment from the segment descriptor */
267             Segment* Seg = S->Seg;
268
269             /* Check the PC. */
270             if ((long) Seg->PC <= ED->Val && (O = (ED->Val - Seg->PC)) < Offs) {
271                 /* This is the nearest segment for now */
272                 Offs = O;
273                 Nearest = Seg;
274
275                 /* If we found an exact match, don't look further */
276                 if (Offs == 0) {
277                     break;
278                 }
279             }
280         }
281
282         /* Next segment */
283         N = N->Next;
284     }
285
286     /* If we found a segment, use it and adjust the offset */
287     if (Nearest) {
288         ED->SegRef = Nearest;
289         ED->MemRef = 0;
290         ED->Val    -= Nearest->PC;
291     }
292 }
293
294
295
296 static const SegDesc* FindSeg (SegDesc** const List, unsigned Count, const Segment* S)
297 /* Search for a segment in the given list of segment descriptors and return
298  * the descriptor for a segment if we found it, and NULL if not.
299  */
300 {
301     unsigned I;
302
303     for (I = 0; I < Count; ++I) {
304         if (List[I]->Seg == S) {
305             /* Found */
306             return List[I];
307         }
308     }
309
310     /* Not found */
311     return 0;
312 }
313
314
315
316 static const SegDesc* O65FindSeg (const O65Desc* D, const Segment* S)
317 /* Search for a segment in the segment lists and return it's segment descriptor */
318 {
319     const SegDesc* SD;
320
321     if ((SD = FindSeg (D->TextSeg, D->TextCount, S)) != 0) {
322         return SD;
323     }
324     if ((SD = FindSeg (D->DataSeg, D->DataCount, S)) != 0) {
325         return SD;
326     }
327     if ((SD = FindSeg (D->BssSeg, D->BssCount, S)) != 0) {
328         return SD;
329     }
330     if ((SD = FindSeg (D->ZPSeg, D->ZPCount, S)) != 0) {
331         return SD;
332     }
333
334     /* Not found */
335     return 0;
336 }
337
338
339
340 /*****************************************************************************/
341 /*                            Expression handling                            */
342 /*****************************************************************************/
343
344
345
346 static void O65ParseExpr (ExprNode* Expr, ExprDesc* D, int Sign)
347 /* Extract and evaluate all constant factors in an subtree that has only
348  * additions and subtractions. If anything other than additions and
349  * subtractions are found, D->TooComplex is set to true.
350  */
351 {
352     Export* E;
353
354     switch (Expr->Op) {
355
356         case EXPR_LITERAL:
357             D->Val += (Sign * Expr->V.Val);
358             break;
359
360         case EXPR_SYMBOL:
361             /* Get the referenced Export */
362             E = GetExprExport (Expr);
363             /* If this export has a mark set, we've already encountered it.
364              * This means that the export is used to define it's own value,
365              * which in turn means, that we have a circular reference.
366              */
367             if (ExportHasMark (E)) {
368                 CircularRefError (E);
369             } else if (E->Expr == 0) {
370                 /* Dummy export, must be an o65 imported symbol */
371                 ExtSym* S = O65GetImport (D->D, E->Name);
372                 CHECK (S != 0);
373                 if (D->ExtRef) {
374                     /* We cannot have more than one external reference in o65 */
375                     D->TooComplex = 1;
376                 } else {
377                     /* Remember the external reference */
378                     D->ExtRef = S;
379                 }
380             } else {
381                 MarkExport (E);
382                 O65ParseExpr (E->Expr, D, Sign);
383                 UnmarkExport (E);
384             }
385             break;
386
387         case EXPR_SECTION:
388             if (D->SecRef) {
389                 /* We cannot handle more than one segment reference in o65 */
390                 D->TooComplex = 1;
391             } else {
392                 /* Remember the segment reference */
393                 D->SecRef = GetExprSection (Expr);
394                 /* Add the offset of the section to the constant value */
395                 D->Val += Sign * (D->SecRef->Offs + D->SecRef->Seg->PC);
396             }
397             break;
398
399         case EXPR_SEGMENT:
400             if (D->SegRef) {
401                 /* We cannot handle more than one segment reference in o65 */
402                 D->TooComplex = 1;
403             } else {
404                 /* Remember the segment reference */
405                 D->SegRef = Expr->V.Seg;
406                 /* Add the offset of the segment to the constant value */
407                 D->Val += (Sign * D->SegRef->PC);
408             }
409             break;
410
411         case EXPR_MEMAREA:
412             if (D->MemRef) {
413                 /* We cannot handle more than one memory reference in o65 */
414                 D->TooComplex = 1;
415             } else {
416                 /* Remember the memory area reference */
417                 D->MemRef = Expr->V.Mem;
418                 /* Add the start address of the memory area to the constant
419                  * value
420                  */
421                 D->Val += (Sign * D->MemRef->Start);
422             }
423             break;
424
425         case EXPR_PLUS:
426             O65ParseExpr (Expr->Left, D, Sign);
427             O65ParseExpr (Expr->Right, D, Sign);
428             break;
429
430         case EXPR_MINUS:
431             O65ParseExpr (Expr->Left, D, Sign);
432             O65ParseExpr (Expr->Right, D, -Sign);
433             break;
434
435         default:
436             /* Expression contains illegal operators */
437             D->TooComplex = 1;
438             break;
439
440     }
441 }
442
443
444
445 /*****************************************************************************/
446 /*                             Relocation tables                             */
447 /*****************************************************************************/
448
449
450
451 static O65RelocTab* NewO65RelocTab (void)
452 /* Create a new relocation table */
453 {
454     /* Allocate a new structure */
455     O65RelocTab* R = xmalloc (sizeof (O65RelocTab));
456
457     /* Initialize the data */
458     R->Size = 0;
459     R->Fill = 0;
460     R->Buf  = 0;
461
462     /* Return the created struct */
463     return R;
464 }
465
466
467
468 static void FreeO65RelocTab (O65RelocTab* R)
469 /* Free a relocation table */
470 {
471     xfree (R->Buf);
472     xfree (R);
473 }
474
475
476
477 static void O65RelocPutByte (O65RelocTab* R, unsigned B)
478 /* Put the byte into the relocation table */
479 {
480     /* Do we have enough space in the buffer? */
481     if (R->Fill == R->Size) {
482         /* We need to grow the buffer */
483         unsigned char* NewBuf = xmalloc (R->Size + RELOC_BLOCKSIZE);
484         memcpy (NewBuf, R->Buf, R->Size);
485         xfree (R->Buf);
486         R->Buf = NewBuf;
487     }
488
489     /* Put the byte into the buffer */
490     R->Buf [R->Fill++] = (unsigned char) B;
491 }
492
493
494
495 static void O65RelocPutWord (O65RelocTab* R, unsigned W)
496 /* Put a word into the relocation table */
497 {
498     O65RelocPutByte (R, W);
499     O65RelocPutByte (R, W >> 8);
500 }
501
502
503
504 static void O65WriteReloc (O65RelocTab* R, FILE* F)
505 /* Write the relocation table to the given file */
506 {
507     WriteData (F, R->Buf, R->Fill);
508 }
509
510
511
512 /*****************************************************************************/
513 /*                              Option handling                              */
514 /*****************************************************************************/
515
516
517
518 static O65Option* NewO65Option (unsigned Type, const void* Data, unsigned DataLen)
519 /* Allocate and initialize a new option struct */
520 {
521     O65Option* O;
522
523     /* Check the length */
524     CHECK (DataLen <= 253);
525
526     /* Allocate memory */
527     O = xmalloc (sizeof (O65Option) - 1 + DataLen);
528
529     /* Initialize the structure */
530     O->Next     = 0;
531     O->Type     = Type;
532     O->Len      = DataLen;
533     memcpy (O->Data, Data, DataLen);
534
535     /* Return the created struct */
536     return O;
537 }
538
539
540
541 static void FreeO65Option (O65Option* O)
542 /* Free an O65Option struct */
543 {
544     xfree (O);
545 }
546
547
548
549 /*****************************************************************************/
550 /*                     Subroutines to write o65 sections                     */
551 /*****************************************************************************/
552
553
554
555 static void O65WriteHeader (O65Desc* D)
556 /* Write the header of the executable to the given file */
557 {
558     static unsigned char Trailer [5] = {
559         0x01, 0x00, 0x6F, 0x36, 0x35
560     };
561
562     O65Option* O;
563
564     /* Write the fixed header */
565     WriteData (D->F, Trailer, sizeof (Trailer));
566     Write8    (D->F, D->Header.Version);
567     Write16   (D->F, D->Header.Mode);
568     WriteSize (D, D->Header.TextBase);
569     WriteSize (D, D->Header.TextSize);
570     WriteSize (D, D->Header.DataBase);
571     WriteSize (D, D->Header.DataSize);
572     WriteSize (D, D->Header.BssBase);
573     WriteSize (D, D->Header.BssSize);
574     WriteSize (D, D->Header.ZPBase);
575     WriteSize (D, D->Header.ZPSize);
576     WriteSize (D, D->Header.StackSize);
577
578     /* Write the options */
579     O = D->Options;
580     while (O) {
581         Write8 (D->F, O->Len + 2);              /* Account for len and type bytes */
582         Write8 (D->F, O->Type);
583         if (O->Len) {
584             WriteData (D->F, O->Data, O->Len);
585         }
586         O = O->Next;
587     }
588
589     /* Write the end-of-options byte */
590     Write8 (D->F, 0);
591 }
592
593
594
595 static unsigned O65WriteExpr (ExprNode* E, int Signed, unsigned Size,
596                               unsigned long Offs, void* Data)
597 /* Called from SegWrite for an expression. Evaluate the expression, check the
598  * range and write the expression value to the file, update the relocation
599  * table.
600  */
601 {
602     long          Diff;
603     unsigned      RefCount;
604     long          BinVal;
605     ExprNode*     Expr;
606     ExprDesc      ED;
607     unsigned char RelocType;
608
609     /* Cast the Data pointer to its real type, an O65Desc */
610     O65Desc* D = (O65Desc*) Data;
611
612     /* Check for a constant expression */
613     if (IsConstExpr (E)) {
614         /* Write out the constant expression */
615         return SegWriteConstExpr (((O65Desc*)Data)->F, E, Signed, Size);
616     }
617
618     /* We have a relocatable expression that needs a relocation table entry.
619      * Calculate the number of bytes between this entry and the last one, and
620      * setup all necessary intermediate bytes in the relocation table.
621      */
622     Offs += D->SegSize;         /* Calulate full offset */
623     Diff = ((long) Offs) - D->LastOffs;
624     while (Diff > 0xFE) {
625         O65RelocPutByte (D->CurReloc, 0xFF);
626         Diff -= 0xFE;
627     }
628     O65RelocPutByte (D->CurReloc, (unsigned char) Diff);
629
630     /* Remember this offset for the next time */
631     D->LastOffs = Offs;
632
633     /* Determine the expression to relocate */
634     Expr = E;
635     if (E->Op == EXPR_BYTE0 || E->Op == EXPR_BYTE1 ||
636         E->Op == EXPR_BYTE2 || E->Op == EXPR_BYTE3 ||
637         E->Op == EXPR_WORD0 || E->Op == EXPR_WORD1) {
638         /* Use the real expression */
639         Expr = E->Left;
640     }
641
642     /* Recursively collect information about this expression */
643     O65ParseExpr (Expr, InitExprDesc (&ED, D), 1);
644
645     /* We cannot handle more than one external reference */
646     RefCount = (ED.MemRef != 0) + (ED.SegRef != 0) +
647                (ED.SecRef != 0) + (ED.ExtRef != 0);
648     if (RefCount > 1) {
649         ED.TooComplex = 1;
650     }
651
652     /* If we have a memory area reference, we need to convert it into a
653      * segment reference. If we cannot do that, we cannot handle the
654      * expression.
655      */
656     if (ED.MemRef) {
657         CvtMemoryToSegment (&ED);
658         if (ED.SegRef == 0) {
659             return SEG_EXPR_TOO_COMPLEX;
660         }
661     }
662
663     /* Bail out if we cannot handle the expression */
664     if (ED.TooComplex) {
665         return SEG_EXPR_TOO_COMPLEX;
666     }
667
668     /* Safety: Check that we have exactly one reference */
669     CHECK (RefCount == 1);
670
671     /* Write out the offset that goes into the segment. */
672     BinVal = ED.Val;
673     switch (E->Op) {
674         case EXPR_BYTE0:    BinVal &= 0xFF;                     break;
675         case EXPR_BYTE1:    BinVal = (BinVal >>  8) & 0xFF;     break;
676         case EXPR_BYTE2:    BinVal = (BinVal >> 16) & 0xFF;     break;
677         case EXPR_BYTE3:    BinVal = (BinVal >> 24) & 0xFF;     break;
678         case EXPR_WORD0:    BinVal &= 0xFFFF;                   break;
679         case EXPR_WORD1:    BinVal = (BinVal >> 16) & 0xFFFF;   break;
680     }
681     WriteVal (D->F, BinVal, Size);
682
683     /* Determine the actual type of relocation entry needed from the
684      * information gathered about the expression.
685      */
686     if (E->Op == EXPR_BYTE0) {
687         RelocType = O65RELOC_LOW;
688     } else if (E->Op == EXPR_BYTE1) {
689         RelocType = O65RELOC_HIGH;
690     } else if (E->Op == EXPR_BYTE2) {
691         RelocType = O65RELOC_SEG;
692     } else {
693         switch (Size) {
694
695             case 1:
696                 RelocType = O65RELOC_LOW;
697                 break;
698
699             case 2:
700                 RelocType = O65RELOC_WORD;
701                 break;
702
703             case 3:
704                 RelocType = O65RELOC_SEGADR;
705                 break;
706
707             case 4:
708                 /* 4 byte expression not supported by o65 */
709                 return SEG_EXPR_TOO_COMPLEX;
710
711             default:
712                 Internal ("O65WriteExpr: Invalid expression size: %u", Size);
713                 RelocType = 0;          /* Avoid gcc warnings */
714         }
715     }
716
717     /* Determine which segment we're referencing */
718     if (ED.SegRef || ED.SecRef) {
719
720         const SegDesc* Seg;
721
722         /* Segment or section reference. */
723         if (ED.SecRef) {
724             /* Get segment from section */
725             ED.SegRef = ED.SecRef->Seg;
726         }
727
728         /* Search for the segment and map it to it's o65 segmentID */
729         Seg = O65FindSeg (D, ED.SegRef);
730         if (Seg == 0) {
731             /* For some reason, we didn't find this segment in the list of
732              * segments written to the o65 file.
733              */
734             return SEG_EXPR_INVALID;
735         }
736         RelocType |= O65SegType (Seg);
737         O65RelocPutByte (D->CurReloc, RelocType);
738
739         /* Output additional data if needed */
740         switch (RelocType & O65RELOC_MASK) {
741             case O65RELOC_HIGH:
742                 O65RelocPutByte (D->CurReloc, ED.Val & 0xFF);
743                 break;
744             case O65RELOC_SEG:
745                 O65RelocPutWord (D->CurReloc, ED.Val & 0xFFFF);
746                 break;
747         }
748
749     } else if (ED.ExtRef) {
750         /* Imported symbol */
751         RelocType |= O65SEG_UNDEF;
752         O65RelocPutByte (D->CurReloc, RelocType);
753         /* Put the number of the imported symbol into the table */
754         O65RelocPutWord (D->CurReloc, ExtSymNum (ED.ExtRef));
755
756     } else {
757
758         /* OOPS - something bad happened */
759         Internal ("External reference not handled");
760
761     }
762
763     /* Success */
764     return SEG_EXPR_OK;
765 }
766
767
768
769 static void O65WriteSeg (O65Desc* D, SegDesc** Seg, unsigned Count, int DoWrite)
770 /* Write one segment to the o65 output file */
771 {
772     SegDesc* S;
773     unsigned I;
774
775     /* Initialize variables */
776     D->SegSize  = 0;
777     D->LastOffs = -1;
778
779     /* Write out all segments */
780     for (I = 0; I < Count; ++I) {
781
782         /* Get the segment from the list node */
783         S = Seg [I];
784
785         /* Keep the user happy */
786         Print (stdout, 1, "    Writing `%s'\n", GetString (S->Name));
787
788         /* Write this segment */
789         if (DoWrite) {
790             RelocLineInfo (S->Seg);
791             SegWrite (D->F, S->Seg, O65WriteExpr, D);
792         }
793
794         /* Mark the segment as dumped */
795         S->Seg->Dumped = 1;
796
797         /* Calculate the total size */
798         D->SegSize += S->Seg->Size;
799     }
800
801     /* Terminate the relocation table for this segment */
802     if (D->CurReloc) {
803         O65RelocPutByte (D->CurReloc, 0);
804     }
805
806     /* Check the size of the segment for overflow */
807     if ((D->Header.Mode & MF_SIZE_MASK) == MF_SIZE_16BIT && D->SegSize > 0xFFFF) {
808         Error ("Segment overflow in file `%s'", D->Filename);
809     }
810
811 }
812
813
814
815 static void O65WriteTextSeg (O65Desc* D)
816 /* Write the code segment to the o65 output file */
817 {
818     /* Initialize variables */
819     D->CurReloc = D->TextReloc;
820
821     /* Dump all text segments */
822     O65WriteSeg (D, D->TextSeg, D->TextCount, 1);
823
824     /* Set the size of the segment */
825     D->Header.TextSize = D->SegSize;
826 }
827
828
829
830 static void O65WriteDataSeg (O65Desc* D)
831 /* Write the data segment to the o65 output file */
832 {
833     /* Initialize variables */
834     D->CurReloc = D->DataReloc;
835
836     /* Dump all data segments */
837     O65WriteSeg (D, D->DataSeg, D->DataCount, 1);
838
839     /* Set the size of the segment */
840     D->Header.DataSize = D->SegSize;
841 }
842
843
844
845 static void O65WriteBssSeg (O65Desc* D)
846 /* "Write" the bss segments to the o65 output file. This will only update
847  * the relevant header fields.
848  */
849 {
850     /* Initialize variables */
851     D->CurReloc = 0;
852
853     /* Dump all data segments */
854     O65WriteSeg (D, D->BssSeg, D->BssCount, 0);
855
856     /* Set the size of the segment */
857     D->Header.BssSize = D->SegSize;
858 }
859
860
861
862 static void O65WriteZPSeg (O65Desc* D)
863 /* "Write" the zeropage segments to the o65 output file. This will only update
864  * the relevant header fields.
865  */
866 {
867     /* Initialize variables */
868     D->CurReloc = 0;
869
870     /* Dump all data segments */
871     O65WriteSeg (D, D->ZPSeg, D->ZPCount, 0);
872
873     /* Set the size of the segment */
874     D->Header.ZPSize = D->SegSize;
875 }
876
877
878
879 static void O65WriteImports (O65Desc* D)
880 /* Write the list of imported symbols to the O65 file */
881 {
882     const ExtSym* S;
883
884     /* Write the number of imports */
885     WriteSize (D, ExtSymCount (D->Imports));
886
887     /* Write out the symbol names, zero terminated */
888     S = ExtSymList (D->Imports);
889     while (S) {
890         /* Get the name */
891         const char* Name = GetString (ExtSymName (S));
892         /* And write it to the output file */
893         WriteData (D->F, Name, strlen (Name) + 1);
894         /* Next symbol */
895         S = ExtSymNext (S);
896     }
897 }
898
899
900
901 static void O65WriteTextReloc (O65Desc* D)
902 /* Write the relocation for the text segment to the output file */
903 {
904     O65WriteReloc (D->TextReloc, D->F);
905 }
906
907
908
909 static void O65WriteDataReloc (O65Desc* D)
910 /* Write the relocation for the data segment to the output file */
911 {
912     O65WriteReloc (D->DataReloc, D->F);
913 }
914
915
916
917 static void O65WriteExports (O65Desc* D)
918 /* Write the list of exports */
919 {
920     const ExtSym* S;
921
922     /* Write the number of exports */
923     WriteSize (D, ExtSymCount (D->Exports));
924
925     /* Write out the symbol information */
926     S = ExtSymList (D->Exports);
927     while (S) {
928
929         ExprNode* Expr;
930         unsigned char SegmentID;
931         ExprDesc ED;
932
933         /* Get the name */
934         unsigned NameIdx = ExtSymName (S);
935         const char* Name = GetString (NameIdx);
936
937         /* Get the export for this symbol. We've checked before that this
938          * export does really exist, so if it is unresolved, or if we don't
939          * find it, there is an error in the linker code.
940          */
941         Export* E = FindExport (NameIdx);
942         if (E == 0 || IsUnresolvedExport (E)) {
943             Internal ("Unresolved export `%s' found in O65WriteExports", Name);
944         }
945
946         /* Get the expression for the symbol */
947         Expr = E->Expr;
948
949         /* Recursively collect information about this expression */
950         O65ParseExpr (Expr, InitExprDesc (&ED, D), 1);
951
952         /* We cannot handle expressions with imported symbols, or expressions
953          * with more than one segment reference here
954          */
955         if (ED.ExtRef != 0 || (ED.SegRef != 0 && ED.SecRef != 0)) {
956             ED.TooComplex = 1;
957         }
958
959         /* Bail out if we cannot handle the expression */
960         if (ED.TooComplex) {
961             Error ("Expression for symbol `%s' is too complex", Name);
962         }
963
964         /* Determine the segment id for the expression */
965         if (ED.SegRef != 0 || ED.SecRef != 0) {
966
967             const SegDesc* Seg;
968
969             /* Segment or section reference */
970             if (ED.SecRef != 0) {
971                 ED.SegRef = ED.SecRef->Seg;     /* Get segment from section */
972             }
973
974             /* Search for the segment and map it to it's o65 segmentID */
975             Seg = O65FindSeg (D, ED.SegRef);
976             if (Seg == 0) {
977                 /* For some reason, we didn't find this segment in the list of
978                  * segments written to the o65 file.
979                  */
980                 Error ("Segment for symbol `%s' is undefined", Name);
981             }
982             SegmentID = O65SegType (Seg);
983
984         } else {
985
986             /* Absolute value */
987             SegmentID = O65SEG_ABS;
988
989         }
990
991         /* Write the name to the output file */
992         WriteData (D->F, Name, strlen (Name) + 1);
993
994         /* Output the segment id followed by the literal value */
995         Write8 (D->F, SegmentID);
996         WriteSize (D, ED.Val);
997
998         /* Next symbol */
999         S = ExtSymNext (S);
1000     }
1001 }
1002
1003
1004
1005 /*****************************************************************************/
1006 /*                                Public code                                */
1007 /*****************************************************************************/
1008
1009
1010
1011 O65Desc* NewO65Desc (void)
1012 /* Create, initialize and return a new O65 descriptor struct */
1013 {
1014     /* Allocate a new structure */
1015     O65Desc* D = xmalloc (sizeof (O65Desc));
1016
1017     /* Initialize the header */
1018     D->Header.Version   = 0;
1019     D->Header.Mode      = 0;
1020     D->Header.TextBase  = 0;
1021     D->Header.TextSize  = 0;
1022     D->Header.DataBase  = 0;
1023     D->Header.DataSize  = 0;
1024     D->Header.BssBase   = 0;
1025     D->Header.BssSize   = 0;
1026     D->Header.ZPBase    = 0;
1027     D->Header.ZPSize    = 0;
1028     D->Header.StackSize = 0;            /* Let OS choose a good value */
1029
1030     /* Initialize other data */
1031     D->Options          = 0;
1032     D->Exports          = NewExtSymTab ();
1033     D->Imports          = NewExtSymTab ();
1034     D->Undef            = 0;
1035     D->F                = 0;
1036     D->Filename         = 0;
1037     D->TextReloc        = NewO65RelocTab ();
1038     D->DataReloc        = NewO65RelocTab ();
1039     D->TextCount        = 0;
1040     D->TextSeg          = 0;
1041     D->DataCount        = 0;
1042     D->DataSeg          = 0;
1043     D->BssCount         = 0;
1044     D->BssSeg           = 0;
1045     D->ZPCount          = 0;
1046     D->ZPSeg            = 0;
1047
1048     /* Return the created struct */
1049     return D;
1050 }
1051
1052
1053
1054 void FreeO65Desc (O65Desc* D)
1055 /* Delete the descriptor struct with cleanup */
1056 {
1057     /* Free the segment arrays */
1058     xfree (D->ZPSeg);
1059     xfree (D->BssSeg);
1060     xfree (D->DataSeg);
1061     xfree (D->TextSeg);
1062
1063     /* Free the relocation tables */
1064     FreeO65RelocTab (D->DataReloc);
1065     FreeO65RelocTab (D->TextReloc);
1066
1067     /* Free the option list */
1068     while (D->Options) {
1069         O65Option* O = D->Options;
1070         D->Options = D->Options->Next;
1071         FreeO65Option (O);
1072     }
1073
1074     /* Free the external symbol tables */
1075     FreeExtSymTab (D->Exports);
1076     FreeExtSymTab (D->Imports);
1077
1078     /* Free the struct itself */
1079     xfree (D);
1080 }
1081
1082
1083
1084 void O65Set6502 (O65Desc* D)
1085 /* Enable 6502 mode */
1086 {
1087     D->Header.Mode = (D->Header.Mode & ~MF_CPU_MASK) | MF_CPU_6502;
1088 }
1089
1090
1091
1092 void O65Set65816 (O65Desc* D)
1093 /* Enable 816 mode */
1094 {
1095     D->Header.Mode = (D->Header.Mode & ~MF_CPU_MASK) | MF_CPU_65816;
1096 }
1097
1098
1099
1100 void O65SetSmallModel (O65Desc* D)
1101 /* Enable a small memory model executable */
1102 {
1103     D->Header.Mode = (D->Header.Mode & ~MF_SIZE_MASK) | MF_SIZE_16BIT;
1104 }
1105
1106
1107
1108 void O65SetLargeModel (O65Desc* D)
1109 /* Enable a large memory model executable */
1110 {
1111     D->Header.Mode = (D->Header.Mode & ~MF_SIZE_MASK) | MF_SIZE_32BIT;
1112 }
1113
1114
1115
1116 void O65SetAlignment (O65Desc* D, unsigned Align)
1117 /* Set the executable alignment */
1118 {
1119     /* Remove all alignment bits from the mode word */
1120     D->Header.Mode &= ~MF_ALIGN_MASK;
1121
1122     /* Set the alignment bits */
1123     switch (Align) {
1124         case 1:   D->Header.Mode |= MF_ALIGN_1;   break;
1125         case 2:   D->Header.Mode |= MF_ALIGN_2;   break;
1126         case 4:   D->Header.Mode |= MF_ALIGN_4;   break;
1127         case 256: D->Header.Mode |= MF_ALIGN_256; break;
1128         default:  Error ("Invalid alignment for O65 format: %u", Align);
1129     }
1130 }
1131
1132
1133
1134 void O65SetOption (O65Desc* D, unsigned Type, const void* Data, unsigned DataLen)
1135 /* Set an o65 header option */
1136 {
1137     /* Create a new option structure */
1138     O65Option* O = NewO65Option (Type, Data, DataLen);
1139
1140     /* Insert it into the linked list */
1141     O->Next = D->Options;
1142     D->Options = O;
1143 }
1144
1145
1146
1147 void O65SetOS (O65Desc* D, unsigned OS, unsigned Version, unsigned Id)
1148 /* Set an option describing the target operating system */
1149 {
1150     /* Setup the option data */
1151     unsigned char Opt[4];
1152     Opt[0] = OS;
1153     Opt[1] = Version;
1154
1155     /* Write the correct option length */
1156     switch (OS) {
1157         case O65OS_OSA65:
1158         case O65OS_LUNIX:
1159             /* No id for these two */
1160             O65SetOption (D, O65OPT_OS, Opt, 2);
1161             break;
1162
1163         case O65OS_CC65:
1164             /* Set the 16 bit id */
1165             Opt[2] = (unsigned char) Id;
1166             Opt[3] = (unsigned char) (Id >> 8);
1167             O65SetOption (D, O65OPT_OS, Opt, 4);
1168             break;
1169
1170         default:
1171             Internal ("Trying to set invalid O65 operating system: %u", OS);
1172     }
1173 }
1174
1175
1176
1177 ExtSym* O65GetImport (O65Desc* D, unsigned Ident)
1178 /* Return the imported symbol or NULL if not found */
1179 {
1180     /* Retrieve the symbol from the table */
1181     return GetExtSym (D->Imports, Ident);
1182 }
1183
1184
1185
1186 void O65SetImport (O65Desc* D, unsigned Ident)
1187 /* Set an imported identifier */
1188 {
1189     /* Insert the entry into the table */
1190     NewExtSym (D->Imports, Ident);
1191 }
1192
1193
1194
1195 ExtSym* O65GetExport (O65Desc* D, unsigned Ident)
1196 /* Return the exported symbol or NULL if not found */
1197 {
1198     /* Retrieve the symbol from the table */
1199     return GetExtSym (D->Exports, Ident);
1200 }
1201
1202
1203
1204 void O65SetExport (O65Desc* D, unsigned Ident)
1205 /* Set an exported identifier */
1206 {
1207     /* Get the export for this symbol and check if it does exist and is
1208      * a resolved symbol.
1209      */
1210     Export* E = FindExport (Ident);
1211     if (E == 0 || IsUnresolvedExport (E)) {
1212         Error ("Unresolved export: `%s'", GetString (Ident));
1213     }
1214
1215     /* Insert the entry into the table */
1216     NewExtSym (D->Exports, Ident);
1217 }
1218
1219
1220
1221 static void O65SetupSegments (O65Desc* D, File* F)
1222 /* Setup segment assignments */
1223 {
1224     Memory* M;
1225     MemListNode* N;
1226     SegDesc* S;
1227     unsigned TextIdx, DataIdx, BssIdx, ZPIdx;
1228
1229     /* Initialize the counters */
1230     D->TextCount = 0;
1231     D->DataCount = 0;
1232     D->BssCount  = 0;
1233     D->ZPCount   = 0;
1234
1235     /* Walk over the memory list */
1236     M = F->MemList;
1237     while (M) {
1238         /* Walk through the segment list and count the segment types */
1239         N = M->SegList;
1240         while (N) {
1241
1242             /* Get the segment from the list node */
1243             S = N->Seg;
1244
1245             /* Check the segment type. */
1246             switch (O65SegType (S)) {
1247                 case O65SEG_TEXT:   D->TextCount++; break;
1248                 case O65SEG_DATA:   D->DataCount++; break;
1249                 case O65SEG_BSS:    D->BssCount++;  break;
1250                 case O65SEG_ZP:     D->ZPCount++;   break;
1251                 default:            Internal ("Invalid return from O65SegType");
1252             }
1253
1254             /* Next segment node */
1255             N = N->Next;
1256         }
1257         /* Next memory area */
1258         M = M->FNext;
1259     }
1260
1261     /* Allocate memory according to the numbers */
1262     D->TextSeg = xmalloc (D->TextCount * sizeof (SegDesc*));
1263     D->DataSeg = xmalloc (D->DataCount * sizeof (SegDesc*));
1264     D->BssSeg  = xmalloc (D->BssCount  * sizeof (SegDesc*));
1265     D->ZPSeg   = xmalloc (D->ZPCount   * sizeof (SegDesc*));
1266
1267     /* Walk again through the list and setup the segment arrays */
1268     TextIdx = DataIdx = BssIdx = ZPIdx = 0;
1269     M = F->MemList;
1270     while (M) {
1271
1272         N = M->SegList;
1273         while (N) {
1274
1275             /* Get the segment from the list node */
1276             S = N->Seg;
1277
1278             /* Check the segment type. */
1279             switch (O65SegType (S)) {
1280                 case O65SEG_TEXT:   D->TextSeg [TextIdx++] = S; break;
1281                 case O65SEG_DATA:   D->DataSeg [DataIdx++] = S; break;
1282                 case O65SEG_BSS:    D->BssSeg [BssIdx++]   = S; break;
1283                 case O65SEG_ZP:     D->ZPSeg [ZPIdx++]     = S; break;
1284                 default:            Internal ("Invalid return from O65SegType");
1285             }
1286
1287             /* Next segment node */
1288             N = N->Next;
1289         }
1290         /* Next memory area */
1291         M = M->FNext;
1292     }
1293 }
1294
1295
1296
1297 static int O65Unresolved (unsigned Name, void* D)
1298 /* Called if an unresolved symbol is encountered */
1299 {
1300     /* Check if the symbol is an imported o65 symbol */
1301     if (O65GetImport (D, Name) != 0) {
1302         /* This is an external symbol, relax... */
1303         return 1;
1304     } else {
1305         /* This is actually an unresolved external. Bump the counter */
1306         ((O65Desc*) D)->Undef++;
1307         return 0;
1308     }
1309 }
1310
1311
1312
1313 static void O65SetupHeader (O65Desc* D)
1314 /* Set additional stuff in the header */
1315 {
1316     /* Set the base addresses of the segments */
1317     if (D->TextCount > 0) {
1318         SegDesc* FirstSeg  = D->TextSeg [0];
1319         D->Header.TextBase = FirstSeg->Seg->PC;
1320     }
1321     if (D->DataCount > 0) {
1322         SegDesc* FirstSeg  = D->DataSeg [0];
1323         D->Header.DataBase = FirstSeg->Seg->PC;
1324     }
1325     if (D->BssCount > 0) {
1326         SegDesc* FirstSeg  = D->BssSeg [0];
1327         D->Header.BssBase = FirstSeg->Seg->PC;
1328     }
1329     if (D->ZPCount > 0) {
1330         SegDesc* FirstSeg = D->ZPSeg [0];
1331         D->Header.ZPBase  = FirstSeg->Seg->PC;
1332     }
1333
1334     /* If we have byte wise relocation and an alignment of 1, we can set
1335      * the "simple addressing" bit in the header.
1336      */
1337     if ((D->Header.Mode & MF_RELOC_MASK) == MF_RELOC_BYTE &&
1338         (D->Header.Mode & MF_ALIGN_MASK) == MF_ALIGN_1) {
1339         D->Header.Mode = (D->Header.Mode & ~MF_ADDR_MASK) | MF_ADDR_SIMPLE;
1340     }
1341 }
1342
1343
1344
1345 void O65WriteTarget (O65Desc* D, File* F)
1346 /* Write an o65 output file */
1347 {
1348     char        OptBuf [256];   /* Buffer for option strings */
1349     unsigned    OptLen;
1350     time_t      T;
1351
1352     /* Place the filename in the control structure */
1353     D->Filename = GetString (F->Name);
1354
1355     /* Check for unresolved symbols. The function O65Unresolved is called
1356      * if we get an unresolved symbol.
1357      */
1358     D->Undef = 0;               /* Reset the counter */
1359     CheckExports (O65Unresolved, D);
1360     if (D->Undef > 0) {
1361         /* We had unresolved symbols, cannot create output file */
1362         Error ("%u unresolved external(s) found - cannot create output file", D->Undef);
1363     }
1364
1365     /* Setup the segment arrays */
1366     O65SetupSegments (D, F);
1367
1368     /* Setup additional stuff in the header */
1369     O65SetupHeader (D);
1370
1371     /* Open the file */
1372     D->F = fopen (D->Filename, "wb");
1373     if (D->F == 0) {
1374         Error ("Cannot open `%s': %s", D->Filename, strerror (errno));
1375     }
1376
1377     /* Keep the user happy */
1378     Print (stdout, 1, "Opened `%s'...\n", D->Filename);
1379
1380     /* Define some more options: A timestamp and the linker version */
1381     T = time (0);
1382     strcpy (OptBuf, ctime (&T));
1383     OptLen = strlen (OptBuf);
1384     while (OptLen > 0 && IsControl (OptBuf[OptLen-1])) {
1385         --OptLen;
1386     }
1387     OptBuf[OptLen] = '\0';
1388     O65SetOption (D, O65OPT_TIMESTAMP, OptBuf, OptLen + 1);
1389     sprintf (OptBuf, "ld65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
1390     O65SetOption (D, O65OPT_ASM, OptBuf, strlen (OptBuf) + 1);
1391
1392     /* Write the header */
1393     O65WriteHeader (D);
1394
1395     /* Write the text segment */
1396     O65WriteTextSeg (D);
1397
1398     /* Write the data segment */
1399     O65WriteDataSeg (D);
1400
1401     /* "Write" the bss segments */
1402     O65WriteBssSeg (D);
1403
1404     /* "Write" the zeropage segments */
1405     O65WriteZPSeg (D);
1406
1407     /* Write the undefined references list */
1408     O65WriteImports (D);
1409
1410     /* Write the text segment relocation table */
1411     O65WriteTextReloc (D);
1412
1413     /* Write the data segment relocation table */
1414     O65WriteDataReloc (D);
1415
1416     /* Write the list of exports */
1417     O65WriteExports (D);
1418
1419     /* Seek back to the start and write the updated header */
1420     fseek (D->F, 0, SEEK_SET);
1421     O65WriteHeader (D);
1422
1423     /* Close the file */
1424     if (fclose (D->F) != 0) {
1425         Error ("Cannot write to `%s': %s", D->Filename, strerror (errno));
1426     }
1427
1428     /* Reset the file and filename */
1429     D->F        = 0;
1430     D->Filename = 0;
1431 }
1432
1433
1434
1435