1 /*****************************************************************************/
5 /* Module to handle the o65 binary format */
9 /* (C) 1999-2003 Ullrich von Bassewitz */
10 /* Römerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
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. */
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: */
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 */
32 /*****************************************************************************/
60 /*****************************************************************************/
62 /*****************************************************************************/
66 /* Header mode bits */
67 #define MF_CPU_65816 0x8000 /* Executable is for 65816 */
68 #define MF_CPU_6502 0x0000 /* Executable is for the 6502 */
69 #define MF_CPU_MASK 0x8000 /* Mask to extract CPU type */
71 #define MF_RELOC_PAGE 0x4000 /* Page wise relocation */
72 #define MF_RELOC_BYTE 0x0000 /* Byte wise relocation */
73 #define MF_RELOC_MASK 0x4000 /* Mask to extract relocation type */
75 #define MF_SIZE_32BIT 0x2000 /* All size words are 32bit */
76 #define MF_SIZE_16BIT 0x0000 /* All size words are 16bit */
77 #define MF_SIZE_MASK 0x2000 /* Mask to extract size */
79 #define MF_FTYPE_OBJ 0x1000 /* Object file */
80 #define MF_FTYPE_EXE 0x0000 /* Executable file */
81 #define MF_FTYPE_MASK 0x1000 /* Mask to extract type */
83 #define MF_ADDR_SIMPLE 0x0800 /* Simple addressing */
84 #define MF_ADDR_DEFAULT 0x0000 /* Default addressing */
85 #define MF_ADDR_MASK 0x0800 /* Mask to extract addressing */
87 #define MF_ALIGN_1 0x0000 /* Bytewise alignment */
88 #define MF_ALIGN_2 0x0001 /* Align words */
89 #define MF_ALIGN_4 0x0002 /* Align longwords */
90 #define MF_ALIGN_256 0x0003 /* Align pages (256 bytes) */
91 #define MF_ALIGN_MASK 0x0003 /* Mask to extract alignment */
93 /* The four o65 segment types. Note: These values are identical to the values
94 * needed for the segmentID in the o65 spec.
96 #define O65SEG_UNDEF 0x00
97 #define O65SEG_ABS 0x01
98 #define O65SEG_TEXT 0x02
99 #define O65SEG_DATA 0x03
100 #define O65SEG_BSS 0x04
101 #define O65SEG_ZP 0x05
103 /* Relocation type codes for the o65 format */
104 #define O65RELOC_WORD 0x80
105 #define O65RELOC_HIGH 0x40
106 #define O65RELOC_LOW 0x20
107 #define O65RELOC_SEGADR 0xC0
108 #define O65RELOC_SEG 0xA0
109 #define O65RELOC_MASK 0xE0
111 /* O65 executable file header */
112 typedef struct O65Header O65Header;
114 unsigned Version; /* Version number for o65 format */
115 unsigned Mode; /* Mode word */
116 unsigned long TextBase; /* Base address of text segment */
117 unsigned long TextSize; /* Size of text segment */
118 unsigned long DataBase; /* Base of data segment */
119 unsigned long DataSize; /* Size of data segment */
120 unsigned long BssBase; /* Base of bss segment */
121 unsigned long BssSize; /* Size of bss segment */
122 unsigned long ZPBase; /* Base of zeropage segment */
123 unsigned long ZPSize; /* Size of zeropage segment */
124 unsigned long StackSize; /* Requested stack size */
128 typedef struct O65Option O65Option;
130 O65Option* Next; /* Next in option list */
131 unsigned char Type; /* Type of option */
132 unsigned char Len; /* Data length */
133 unsigned char Data [1]; /* Data, dynamically allocated */
136 /* A o65 relocation table */
137 #define RELOC_BLOCKSIZE 4096
138 typedef struct O65RelocTab O65RelocTab;
140 unsigned Size; /* Size of the table */
141 unsigned Fill; /* Amount used */
142 unsigned char* Buf; /* Buffer, dynamically allocated */
145 /* Structure describing the format */
147 O65Header Header; /* File header */
148 O65Option* Options; /* List of file options */
149 ExtSymTab* Exports; /* Table with exported symbols */
150 ExtSymTab* Imports; /* Table with imported symbols */
151 unsigned Undef; /* Count of undefined symbols */
152 FILE* F; /* The file we're writing to */
153 const char* Filename; /* Name of the output file */
154 O65RelocTab* TextReloc; /* Relocation table for text segment */
155 O65RelocTab* DataReloc; /* Relocation table for data segment */
157 unsigned TextCount; /* Number of segments assigned to .text */
158 SegDesc** TextSeg; /* Array of text segments */
159 unsigned DataCount; /* Number of segments assigned to .data */
160 SegDesc** DataSeg; /* Array of data segments */
161 unsigned BssCount; /* Number of segments assigned to .bss */
162 SegDesc** BssSeg; /* Array of bss segments */
163 unsigned ZPCount; /* Number of segments assigned to .zp */
164 SegDesc** ZPSeg; /* Array of zp segments */
166 /* Temporary data for writing segments */
167 unsigned long SegSize;
168 O65RelocTab* CurReloc;
172 /* Structure for parsing expression trees */
173 typedef struct ExprDesc ExprDesc;
175 O65Desc* D; /* File format descriptor */
176 long Val; /* The offset value */
177 int TooComplex; /* Expression too complex */
178 Segment* SegRef; /* Segment reference if any */
179 Section* SecRef; /* Section reference if any */
180 ExtSym* ExtRef; /* External reference if any */
185 /*****************************************************************************/
186 /* Helper functions */
187 /*****************************************************************************/
191 static ExprDesc* InitExprDesc (ExprDesc* ED, O65Desc* D)
192 /* Initialize an ExprDesc structure for use with O65ParseExpr */
205 static void WriteSize (const O65Desc* D, unsigned long Val)
206 /* Write a "size" word to the file */
208 switch (D->Header.Mode & MF_SIZE_MASK) {
209 case MF_SIZE_16BIT: Write16 (D->F, (unsigned) Val); break;
210 case MF_SIZE_32BIT: Write32 (D->F, Val); break;
211 default: Internal ("Invalid size in header: %04X", D->Header.Mode);
217 static unsigned O65SegType (const SegDesc* S)
218 /* Map our own segment types into something o65 compatible */
220 /* Check the segment type. Readonly segments are assign to the o65
221 * text segment, writeable segments that contain data are assigned
222 * to data, bss and zp segments are handled respectively.
223 * Beware: Zeropage segments have the SF_BSS flag set, so be sure
224 * to check SF_ZP first.
226 if (S->Flags & SF_RO) {
228 } else if (S->Flags & SF_ZP) {
230 } else if (S->Flags & SF_BSS) {
239 static const SegDesc* FindSeg (SegDesc** const List, unsigned Count, const Segment* S)
240 /* Search for a segment in the given list of segment descriptors and return
241 * the descriptor for a segment if we found it, and NULL if not.
246 for (I = 0; I < Count; ++I) {
247 if (List[I]->Seg == S) {
259 static const SegDesc* O65FindSeg (const O65Desc* D, const Segment* S)
260 /* Search for a segment in the segment lists and return it's segment descriptor */
264 if ((SD = FindSeg (D->TextSeg, D->TextCount, S)) != 0) {
267 if ((SD = FindSeg (D->DataSeg, D->DataCount, S)) != 0) {
270 if ((SD = FindSeg (D->BssSeg, D->BssCount, S)) != 0) {
273 if ((SD = FindSeg (D->ZPSeg, D->ZPCount, S)) != 0) {
283 /*****************************************************************************/
284 /* Expression handling */
285 /*****************************************************************************/
289 static void O65ParseExpr (ExprNode* Expr, ExprDesc* D, int Sign)
290 /* Extract and evaluate all constant factors in an subtree that has only
291 * additions and subtractions. If anything other than additions and
292 * subtractions are found, D->TooComplex is set to true.
302 D->Val -= Expr->V.Val;
304 D->Val += Expr->V.Val;
309 /* Get the referenced Export */
310 E = GetExprExport (Expr);
311 /* If this export has a mark set, we've already encountered it.
312 * This means that the export is used to define it's own value,
313 * which in turn means, that we have a circular reference.
315 if (ExportHasMark (E)) {
316 CircularRefError (E);
317 } else if (E->Expr == 0) {
318 /* Dummy export, must be an o65 imported symbol */
319 ExtSym* S = O65GetImport (D->D, E->Name);
322 /* We cannot have more than one external reference in o65 */
325 /* Remember the external reference */
330 O65ParseExpr (E->Expr, D, Sign);
337 /* We cannot handle more than one segment reference in o65 */
340 /* Remember the segment reference */
341 D->SecRef = GetExprSection (Expr);
342 /* Add the offset of the section to the constant value */
343 Val = D->SecRef->Offs + D->SecRef->Seg->PC;
354 /* We cannot handle more than one segment reference in o65 */
357 /* Remember the segment reference */
358 D->SegRef = Expr->V.Seg;
359 /* Add the offset of the segment to the constant value */
370 O65ParseExpr (Expr->Left, D, Sign);
371 O65ParseExpr (Expr->Right, D, Sign);
375 O65ParseExpr (Expr->Left, D, Sign);
376 O65ParseExpr (Expr->Right, D, -Sign);
380 /* Expression contains illegal operators */
389 /*****************************************************************************/
390 /* Relocation tables */
391 /*****************************************************************************/
395 static O65RelocTab* NewO65RelocTab (void)
396 /* Create a new relocation table */
398 /* Allocate a new structure */
399 O65RelocTab* R = xmalloc (sizeof (O65RelocTab));
401 /* Initialize the data */
406 /* Return the created struct */
412 static void FreeO65RelocTab (O65RelocTab* R)
413 /* Free a relocation table */
421 static void O65RelocPutByte (O65RelocTab* R, unsigned B)
422 /* Put the byte into the relocation table */
424 /* Do we have enough space in the buffer? */
425 if (R->Fill == R->Size) {
426 /* We need to grow the buffer */
427 unsigned char* NewBuf = xmalloc (R->Size + RELOC_BLOCKSIZE);
428 memcpy (NewBuf, R->Buf, R->Size);
433 /* Put the byte into the buffer */
434 R->Buf [R->Fill++] = (unsigned char) B;
439 static void O65RelocPutWord (O65RelocTab* R, unsigned W)
440 /* Put a word into the relocation table */
442 O65RelocPutByte (R, W);
443 O65RelocPutByte (R, W >> 8);
448 static void O65WriteReloc (O65RelocTab* R, FILE* F)
449 /* Write the relocation table to the given file */
451 WriteData (F, R->Buf, R->Fill);
456 /*****************************************************************************/
457 /* Option handling */
458 /*****************************************************************************/
462 static O65Option* NewO65Option (unsigned Type, const void* Data, unsigned DataLen)
463 /* Allocate and initialize a new option struct */
467 /* Check the length */
468 CHECK (DataLen <= 253);
470 /* Allocate memory */
471 O = xmalloc (sizeof (O65Option) - 1 + DataLen);
473 /* Initialize the structure */
477 memcpy (O->Data, Data, DataLen);
479 /* Return the created struct */
485 static void FreeO65Option (O65Option* O)
486 /* Free an O65Option struct */
493 /*****************************************************************************/
494 /* Subroutines to write o65 sections */
495 /*****************************************************************************/
499 static void O65WriteHeader (O65Desc* D)
500 /* Write the header of the executable to the given file */
502 static unsigned char Trailer [5] = {
503 0x01, 0x00, 0x6F, 0x36, 0x35
508 /* Write the fixed header */
509 WriteData (D->F, Trailer, sizeof (Trailer));
510 Write8 (D->F, D->Header.Version);
511 Write16 (D->F, D->Header.Mode);
512 WriteSize (D, D->Header.TextBase);
513 WriteSize (D, D->Header.TextSize);
514 WriteSize (D, D->Header.DataBase);
515 WriteSize (D, D->Header.DataSize);
516 WriteSize (D, D->Header.BssBase);
517 WriteSize (D, D->Header.BssSize);
518 WriteSize (D, D->Header.ZPBase);
519 WriteSize (D, D->Header.ZPSize);
520 WriteSize (D, D->Header.StackSize);
522 /* Write the options */
525 Write8 (D->F, O->Len + 2); /* Account for len and type bytes */
526 Write8 (D->F, O->Type);
528 WriteData (D->F, O->Data, O->Len);
533 /* Write the end-of-options byte */
539 static unsigned O65WriteExpr (ExprNode* E, int Signed, unsigned Size,
540 unsigned long Offs, void* Data)
541 /* Called from SegWrite for an expression. Evaluate the expression, check the
542 * range and write the expression value to the file, update the relocation
551 unsigned char RelocType;
553 /* Cast the Data pointer to its real type, an O65Desc */
554 O65Desc* D = (O65Desc*) Data;
556 /* Check for a constant expression */
557 if (IsConstExpr (E)) {
558 /* Write out the constant expression */
559 return SegWriteConstExpr (((O65Desc*)Data)->F, E, Signed, Size);
562 /* We have a relocatable expression that needs a relocation table entry.
563 * Calculate the number of bytes between this entry and the last one, and
564 * setup all necessary intermediate bytes in the relocation table.
566 Offs += D->SegSize; /* Calulate full offset */
567 Diff = ((long) Offs) - D->LastOffs;
568 while (Diff > 0xFE) {
569 O65RelocPutByte (D->CurReloc, 0xFF);
572 O65RelocPutByte (D->CurReloc, (unsigned char) Diff);
574 /* Remember this offset for the next time */
577 /* Determine the expression to relocate */
579 if (E->Op == EXPR_BYTE0 || E->Op == EXPR_BYTE1 ||
580 E->Op == EXPR_BYTE2 || E->Op == EXPR_BYTE3 ||
581 E->Op == EXPR_WORD0 || E->Op == EXPR_WORD1) {
582 /* Use the real expression */
586 /* Recursively collect information about this expression */
587 O65ParseExpr (Expr, InitExprDesc (&ED, D), 1);
589 /* We cannot handle more than one external reference */
590 RefCount = (ED.SegRef != 0) + (ED.SecRef != 0) + (ED.ExtRef != 0);
595 /* Bail out if we cannot handle the expression */
597 return SEG_EXPR_TOO_COMPLEX;
600 /* Safety: Check that we have exactly one reference */
601 CHECK (RefCount == 1);
603 /* Write out the offset that goes into the segment. */
606 case EXPR_BYTE0: BinVal &= 0xFF; break;
607 case EXPR_BYTE1: BinVal = (BinVal >> 8) & 0xFF; break;
608 case EXPR_BYTE2: BinVal = (BinVal >> 16) & 0xFF; break;
609 case EXPR_BYTE3: BinVal = (BinVal >> 24) & 0xFF; break;
610 case EXPR_WORD0: BinVal &= 0xFFFF; break;
611 case EXPR_WORD1: BinVal = (BinVal >> 16) & 0xFFFF; break;
613 WriteVal (D->F, BinVal, Size);
615 /* Determine the actual type of relocation entry needed from the
616 * information gathered about the expression.
618 if (E->Op == EXPR_BYTE0) {
619 RelocType = O65RELOC_LOW;
620 } else if (E->Op == EXPR_BYTE1) {
621 RelocType = O65RELOC_HIGH;
622 } else if (E->Op == EXPR_BYTE2) {
623 RelocType = O65RELOC_SEG;
628 RelocType = O65RELOC_LOW;
632 RelocType = O65RELOC_WORD;
636 RelocType = O65RELOC_SEGADR;
640 /* 4 byte expression not supported by o65 */
641 return SEG_EXPR_TOO_COMPLEX;
644 Internal ("O65WriteExpr: Invalid expression size: %u", Size);
645 RelocType = 0; /* Avoid gcc warnings */
649 /* Determine which segment we're referencing */
650 if (ED.SegRef || ED.SecRef) {
654 /* Segment or section reference. */
656 /* Get segment from section */
657 ED.SegRef = ED.SecRef->Seg;
660 /* Search for the segment and map it to it's o65 segmentID */
661 Seg = O65FindSeg (D, ED.SegRef);
663 /* For some reason, we didn't find this segment in the list of
664 * segments written to the o65 file.
666 return SEG_EXPR_INVALID;
668 RelocType |= O65SegType (Seg);
669 O65RelocPutByte (D->CurReloc, RelocType);
671 /* Output additional data if needed */
672 switch (RelocType & O65RELOC_MASK) {
674 O65RelocPutByte (D->CurReloc, ED.Val & 0xFF);
677 O65RelocPutWord (D->CurReloc, ED.Val & 0xFFFF);
681 } else if (ED.ExtRef) {
682 /* Imported symbol */
683 RelocType |= O65SEG_UNDEF;
684 O65RelocPutByte (D->CurReloc, RelocType);
685 /* Put the number of the imported symbol into the table */
686 O65RelocPutWord (D->CurReloc, ExtSymNum (ED.ExtRef));
690 /* OOPS - something bad happened */
691 Internal ("External reference not handled");
701 static void O65WriteSeg (O65Desc* D, SegDesc** Seg, unsigned Count, int DoWrite)
702 /* Write one segment to the o65 output file */
707 /* Initialize variables */
711 /* Write out all segments */
712 for (I = 0; I < Count; ++I) {
714 /* Get the segment from the list node */
717 /* Keep the user happy */
718 Print (stdout, 1, " Writing `%s'\n", GetString (S->Name));
720 /* Write this segment */
722 RelocLineInfo (S->Seg);
723 SegWrite (D->F, S->Seg, O65WriteExpr, D);
726 /* Mark the segment as dumped */
729 /* Calculate the total size */
730 D->SegSize += S->Seg->Size;
733 /* Terminate the relocation table for this segment */
735 O65RelocPutByte (D->CurReloc, 0);
738 /* Check the size of the segment for overflow */
739 if ((D->Header.Mode & MF_SIZE_MASK) == MF_SIZE_16BIT && D->SegSize > 0xFFFF) {
740 Error ("Segment overflow in file `%s'", D->Filename);
747 static void O65WriteTextSeg (O65Desc* D)
748 /* Write the code segment to the o65 output file */
750 /* Initialize variables */
751 D->CurReloc = D->TextReloc;
753 /* Dump all text segments */
754 O65WriteSeg (D, D->TextSeg, D->TextCount, 1);
756 /* Set the size of the segment */
757 D->Header.TextSize = D->SegSize;
762 static void O65WriteDataSeg (O65Desc* D)
763 /* Write the data segment to the o65 output file */
765 /* Initialize variables */
766 D->CurReloc = D->DataReloc;
768 /* Dump all data segments */
769 O65WriteSeg (D, D->DataSeg, D->DataCount, 1);
771 /* Set the size of the segment */
772 D->Header.DataSize = D->SegSize;
777 static void O65WriteBssSeg (O65Desc* D)
778 /* "Write" the bss segments to the o65 output file. This will only update
779 * the relevant header fields.
782 /* Initialize variables */
785 /* Dump all data segments */
786 O65WriteSeg (D, D->BssSeg, D->BssCount, 0);
788 /* Set the size of the segment */
789 D->Header.BssSize = D->SegSize;
794 static void O65WriteZPSeg (O65Desc* D)
795 /* "Write" the zeropage segments to the o65 output file. This will only update
796 * the relevant header fields.
799 /* Initialize variables */
802 /* Dump all data segments */
803 O65WriteSeg (D, D->ZPSeg, D->ZPCount, 0);
805 /* Set the size of the segment */
806 D->Header.ZPSize = D->SegSize;
811 static void O65WriteImports (O65Desc* D)
812 /* Write the list of imported symbols to the O65 file */
816 /* Write the number of imports */
817 WriteSize (D, ExtSymCount (D->Imports));
819 /* Write out the symbol names, zero terminated */
820 S = ExtSymList (D->Imports);
823 const char* Name = GetString (ExtSymName (S));
824 /* And write it to the output file */
825 WriteData (D->F, Name, strlen (Name) + 1);
833 static void O65WriteTextReloc (O65Desc* D)
834 /* Write the relocation for the text segment to the output file */
836 O65WriteReloc (D->TextReloc, D->F);
841 static void O65WriteDataReloc (O65Desc* D)
842 /* Write the relocation for the data segment to the output file */
844 O65WriteReloc (D->DataReloc, D->F);
849 static void O65WriteExports (O65Desc* D)
850 /* Write the list of exports */
854 /* Write the number of exports */
855 WriteSize (D, ExtSymCount (D->Exports));
857 /* Write out the symbol information */
858 S = ExtSymList (D->Exports);
862 unsigned char SegmentID;
866 unsigned NameIdx = ExtSymName (S);
867 const char* Name = GetString (NameIdx);
869 /* Get the export for this symbol. We've checked before that this
870 * export does really exist, so if it is unresolved, or if we don't
871 * find it, there is an error in the linker code.
873 Export* E = FindExport (NameIdx);
874 if (E == 0 || IsUnresolvedExport (E)) {
875 Internal ("Unresolved export `%s' found in O65WriteExports", Name);
878 /* Get the expression for the symbol */
881 /* Recursively collect information about this expression */
882 O65ParseExpr (Expr, InitExprDesc (&ED, D), 1);
884 /* We cannot handle expressions with imported symbols, or expressions
885 * with more than one segment reference here
887 if (ED.ExtRef != 0 || (ED.SegRef != 0 && ED.SecRef != 0)) {
891 /* Bail out if we cannot handle the expression */
893 Error ("Expression for symbol `%s' is too complex", Name);
896 /* Determine the segment id for the expression */
897 if (ED.SegRef != 0 || ED.SecRef != 0) {
901 /* Segment or section reference */
902 if (ED.SecRef != 0) {
903 ED.SegRef = ED.SecRef->Seg; /* Get segment from section */
906 /* Search for the segment and map it to it's o65 segmentID */
907 Seg = O65FindSeg (D, ED.SegRef);
909 /* For some reason, we didn't find this segment in the list of
910 * segments written to the o65 file.
912 Error ("Segment for symbol `%s' is undefined", Name);
914 SegmentID = O65SegType (Seg);
919 SegmentID = O65SEG_ABS;
923 /* Write the name to the output file */
924 WriteData (D->F, Name, strlen (Name) + 1);
926 /* Output the segment id followed by the literal value */
927 Write8 (D->F, SegmentID);
928 WriteSize (D, ED.Val);
937 /*****************************************************************************/
939 /*****************************************************************************/
943 O65Desc* NewO65Desc (void)
944 /* Create, initialize and return a new O65 descriptor struct */
946 /* Allocate a new structure */
947 O65Desc* D = xmalloc (sizeof (O65Desc));
949 /* Initialize the header */
950 D->Header.Version = 0;
952 D->Header.TextBase = 0;
953 D->Header.TextSize = 0;
954 D->Header.DataBase = 0;
955 D->Header.DataSize = 0;
956 D->Header.BssBase = 0;
957 D->Header.BssSize = 0;
958 D->Header.ZPBase = 0;
959 D->Header.ZPSize = 0;
960 D->Header.StackSize = 0; /* Let OS choose a good value */
962 /* Initialize other data */
964 D->Exports = NewExtSymTab ();
965 D->Imports = NewExtSymTab ();
969 D->TextReloc = NewO65RelocTab ();
970 D->DataReloc = NewO65RelocTab ();
980 /* Return the created struct */
986 void FreeO65Desc (O65Desc* D)
987 /* Delete the descriptor struct with cleanup */
989 /* Free the segment arrays */
995 /* Free the relocation tables */
996 FreeO65RelocTab (D->DataReloc);
997 FreeO65RelocTab (D->TextReloc);
999 /* Free the option list */
1000 while (D->Options) {
1001 O65Option* O = D->Options;
1002 D->Options = D->Options->Next;
1006 /* Free the external symbol tables */
1007 FreeExtSymTab (D->Exports);
1008 FreeExtSymTab (D->Imports);
1010 /* Free the struct itself */
1016 void O65Set6502 (O65Desc* D)
1017 /* Enable 6502 mode */
1019 D->Header.Mode = (D->Header.Mode & ~MF_CPU_MASK) | MF_CPU_6502;
1024 void O65Set65816 (O65Desc* D)
1025 /* Enable 816 mode */
1027 D->Header.Mode = (D->Header.Mode & ~MF_CPU_MASK) | MF_CPU_65816;
1032 void O65SetSmallModel (O65Desc* D)
1033 /* Enable a small memory model executable */
1035 D->Header.Mode = (D->Header.Mode & ~MF_SIZE_MASK) | MF_SIZE_16BIT;
1040 void O65SetLargeModel (O65Desc* D)
1041 /* Enable a large memory model executable */
1043 D->Header.Mode = (D->Header.Mode & ~MF_SIZE_MASK) | MF_SIZE_32BIT;
1048 void O65SetAlignment (O65Desc* D, unsigned Align)
1049 /* Set the executable alignment */
1051 /* Remove all alignment bits from the mode word */
1052 D->Header.Mode &= ~MF_ALIGN_MASK;
1054 /* Set the alignment bits */
1056 case 1: D->Header.Mode |= MF_ALIGN_1; break;
1057 case 2: D->Header.Mode |= MF_ALIGN_2; break;
1058 case 4: D->Header.Mode |= MF_ALIGN_4; break;
1059 case 256: D->Header.Mode |= MF_ALIGN_256; break;
1060 default: Error ("Invalid alignment for O65 format: %u", Align);
1066 void O65SetOption (O65Desc* D, unsigned Type, const void* Data, unsigned DataLen)
1067 /* Set an o65 header option */
1069 /* Create a new option structure */
1070 O65Option* O = NewO65Option (Type, Data, DataLen);
1072 /* Insert it into the linked list */
1073 O->Next = D->Options;
1079 void O65SetOS (O65Desc* D, unsigned OS, unsigned Version, unsigned Id)
1080 /* Set an option describing the target operating system */
1082 /* Setup the option data */
1083 unsigned char Opt[4];
1087 /* Write the correct option length */
1091 /* No id for these two */
1092 O65SetOption (D, O65OPT_OS, Opt, 2);
1096 /* Set the 16 bit id */
1097 Opt[2] = (unsigned char) Id;
1098 Opt[3] = (unsigned char) (Id >> 8);
1099 O65SetOption (D, O65OPT_OS, Opt, 4);
1103 Internal ("Trying to set invalid O65 operating system: %u", OS);
1109 ExtSym* O65GetImport (O65Desc* D, unsigned Ident)
1110 /* Return the imported symbol or NULL if not found */
1112 /* Retrieve the symbol from the table */
1113 return GetExtSym (D->Imports, Ident);
1118 void O65SetImport (O65Desc* D, unsigned Ident)
1119 /* Set an imported identifier */
1121 /* Insert the entry into the table */
1122 NewExtSym (D->Imports, Ident);
1127 ExtSym* O65GetExport (O65Desc* D, unsigned Ident)
1128 /* Return the exported symbol or NULL if not found */
1130 /* Retrieve the symbol from the table */
1131 return GetExtSym (D->Exports, Ident);
1136 void O65SetExport (O65Desc* D, unsigned Ident)
1137 /* Set an exported identifier */
1139 /* Get the export for this symbol and check if it does exist and is
1140 * a resolved symbol.
1142 Export* E = FindExport (Ident);
1143 if (E == 0 || IsUnresolvedExport (E)) {
1144 Error ("Unresolved export: `%s'", GetString (Ident));
1147 /* Insert the entry into the table */
1148 NewExtSym (D->Exports, Ident);
1153 static void O65SetupSegments (O65Desc* D, File* F)
1154 /* Setup segment assignments */
1159 unsigned TextIdx, DataIdx, BssIdx, ZPIdx;
1161 /* Initialize the counters */
1167 /* Walk over the memory list */
1170 /* Walk through the segment list and count the segment types */
1174 /* Get the segment from the list node */
1177 /* Check the segment type. */
1178 switch (O65SegType (S)) {
1179 case O65SEG_TEXT: D->TextCount++; break;
1180 case O65SEG_DATA: D->DataCount++; break;
1181 case O65SEG_BSS: D->BssCount++; break;
1182 case O65SEG_ZP: D->ZPCount++; break;
1183 default: Internal ("Invalid return from O65SegType");
1186 /* Next segment node */
1189 /* Next memory area */
1193 /* Allocate memory according to the numbers */
1194 D->TextSeg = xmalloc (D->TextCount * sizeof (SegDesc*));
1195 D->DataSeg = xmalloc (D->DataCount * sizeof (SegDesc*));
1196 D->BssSeg = xmalloc (D->BssCount * sizeof (SegDesc*));
1197 D->ZPSeg = xmalloc (D->ZPCount * sizeof (SegDesc*));
1199 /* Walk again through the list and setup the segment arrays */
1200 TextIdx = DataIdx = BssIdx = ZPIdx = 0;
1207 /* Get the segment from the list node */
1210 /* Check the segment type. */
1211 switch (O65SegType (S)) {
1212 case O65SEG_TEXT: D->TextSeg [TextIdx++] = S; break;
1213 case O65SEG_DATA: D->DataSeg [DataIdx++] = S; break;
1214 case O65SEG_BSS: D->BssSeg [BssIdx++] = S; break;
1215 case O65SEG_ZP: D->ZPSeg [ZPIdx++] = S; break;
1216 default: Internal ("Invalid return from O65SegType");
1219 /* Next segment node */
1222 /* Next memory area */
1229 static int O65Unresolved (unsigned Name, void* D)
1230 /* Called if an unresolved symbol is encountered */
1232 /* Check if the symbol is an imported o65 symbol */
1233 if (O65GetImport (D, Name) != 0) {
1234 /* This is an external symbol, relax... */
1237 /* This is actually an unresolved external. Bump the counter */
1238 ((O65Desc*) D)->Undef++;
1245 static void O65SetupHeader (O65Desc* D)
1246 /* Set additional stuff in the header */
1248 /* Set the base addresses of the segments */
1249 if (D->TextCount > 0) {
1250 SegDesc* FirstSeg = D->TextSeg [0];
1251 D->Header.TextBase = FirstSeg->Seg->PC;
1253 if (D->DataCount > 0) {
1254 SegDesc* FirstSeg = D->DataSeg [0];
1255 D->Header.DataBase = FirstSeg->Seg->PC;
1257 if (D->BssCount > 0) {
1258 SegDesc* FirstSeg = D->BssSeg [0];
1259 D->Header.BssBase = FirstSeg->Seg->PC;
1261 if (D->ZPCount > 0) {
1262 SegDesc* FirstSeg = D->ZPSeg [0];
1263 D->Header.ZPBase = FirstSeg->Seg->PC;
1266 /* If we have byte wise relocation and an alignment of 1, we can set
1267 * the "simple addressing" bit in the header.
1269 if ((D->Header.Mode & MF_RELOC_MASK) == MF_RELOC_BYTE &&
1270 (D->Header.Mode & MF_ALIGN_MASK) == MF_ALIGN_1) {
1271 D->Header.Mode = (D->Header.Mode & ~MF_ADDR_MASK) | MF_ADDR_SIMPLE;
1277 void O65WriteTarget (O65Desc* D, File* F)
1278 /* Write an o65 output file */
1280 char OptBuf [256]; /* Buffer for option strings */
1284 /* Place the filename in the control structure */
1285 D->Filename = GetString (F->Name);
1287 /* Check for unresolved symbols. The function O65Unresolved is called
1288 * if we get an unresolved symbol.
1290 D->Undef = 0; /* Reset the counter */
1291 CheckExports (O65Unresolved, D);
1293 /* We had unresolved symbols, cannot create output file */
1294 Error ("%u unresolved external(s) found - cannot create output file", D->Undef);
1297 /* Setup the segment arrays */
1298 O65SetupSegments (D, F);
1300 /* Setup additional stuff in the header */
1304 D->F = fopen (D->Filename, "wb");
1306 Error ("Cannot open `%s': %s", D->Filename, strerror (errno));
1309 /* Keep the user happy */
1310 Print (stdout, 1, "Opened `%s'...\n", D->Filename);
1312 /* Define some more options: A timestamp and the linker version */
1314 strcpy (OptBuf, ctime (&T));
1315 OptLen = strlen (OptBuf);
1316 while (OptLen > 0 && IsControl (OptBuf[OptLen-1])) {
1319 OptBuf[OptLen] = '\0';
1320 O65SetOption (D, O65OPT_TIMESTAMP, OptBuf, OptLen + 1);
1321 sprintf (OptBuf, "ld65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
1322 O65SetOption (D, O65OPT_ASM, OptBuf, strlen (OptBuf) + 1);
1324 /* Write the header */
1327 /* Write the text segment */
1328 O65WriteTextSeg (D);
1330 /* Write the data segment */
1331 O65WriteDataSeg (D);
1333 /* "Write" the bss segments */
1336 /* "Write" the zeropage segments */
1339 /* Write the undefined references list */
1340 O65WriteImports (D);
1342 /* Write the text segment relocation table */
1343 O65WriteTextReloc (D);
1345 /* Write the data segment relocation table */
1346 O65WriteDataReloc (D);
1348 /* Write the list of exports */
1349 O65WriteExports (D);
1351 /* Seek back to the start and write the updated header */
1352 fseek (D->F, 0, SEEK_SET);
1355 /* Close the file */
1356 if (fclose (D->F) != 0) {
1357 Error ("Cannot write to `%s': %s", D->Filename, strerror (errno));
1360 /* Reset the file and filename */