1 /*****************************************************************************/
5 /* Module to handle the o65 binary format */
9 /* (C) 1999-2001 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
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 /*****************************************************************************/
59 /*****************************************************************************/
61 /*****************************************************************************/
65 /* Header mode bits */
66 #define MF_CPU_65816 0x8000 /* Executable is for 65816 */
67 #define MF_CPU_6502 0x0000 /* Executable is for the 6502 */
68 #define MF_CPU_MASK 0x8000 /* Mask to extract CPU type */
70 #define MF_RELOC_PAGE 0x4000 /* Page wise relocation */
71 #define MF_RELOC_BYTE 0x0000 /* Byte wise relocation */
72 #define MF_RELOC_MASK 0x4000 /* Mask to extract relocation type */
74 #define MF_SIZE_32BIT 0x2000 /* All size words are 32bit */
75 #define MF_SIZE_16BIT 0x0000 /* All size words are 16bit */
76 #define MF_SIZE_MASK 0x2000 /* Mask to extract size */
78 #define MF_FTYPE_OBJ 0x1000 /* Object file */
79 #define MF_FTYPE_EXE 0x0000 /* Executable file */
80 #define MF_FTYPE_MASK 0x1000 /* Mask to extract type */
82 #define MF_ADDR_SIMPLE 0x0800 /* Simple addressing */
83 #define MF_ADDR_DEFAULT 0x0000 /* Default addressing */
84 #define MF_ADDR_MASK 0x0800 /* Mask to extract addressing */
86 #define MF_ALIGN_1 0x0000 /* Bytewise alignment */
87 #define MF_ALIGN_2 0x0001 /* Align words */
88 #define MF_ALIGN_4 0x0002 /* Align longwords */
89 #define MF_ALIGN_256 0x0003 /* Align pages (256 bytes) */
90 #define MF_ALIGN_MASK 0x0003 /* Mask to extract alignment */
92 /* The four o65 segment types. Note: These values are identical to the values
93 * needed for the segmentID in the o65 spec.
95 #define O65SEG_UNDEF 0x00
96 #define O65SEG_ABS 0x01
97 #define O65SEG_TEXT 0x02
98 #define O65SEG_DATA 0x03
99 #define O65SEG_BSS 0x04
100 #define O65SEG_ZP 0x05
102 /* Relocation type codes for the o65 format */
103 #define O65RELOC_WORD 0x80
104 #define O65RELOC_HIGH 0x40
105 #define O65RELOC_LOW 0x20
106 #define O65RELOC_SEGADR 0xC0
107 #define O65RELOC_SEG 0xA0
108 #define O65RELOC_MASK 0xE0
110 /* O65 executable file header */
111 typedef struct O65Header O65Header;
113 unsigned Version; /* Version number for o65 format */
114 unsigned Mode; /* Mode word */
115 unsigned long TextBase; /* Base address of text segment */
116 unsigned long TextSize; /* Size of text segment */
117 unsigned long DataBase; /* Base of data segment */
118 unsigned long DataSize; /* Size of data segment */
119 unsigned long BssBase; /* Base of bss segment */
120 unsigned long BssSize; /* Size of bss segment */
121 unsigned long ZPBase; /* Base of zeropage segment */
122 unsigned long ZPSize; /* Size of zeropage segment */
123 unsigned long StackSize; /* Requested stack size */
127 typedef struct O65Option O65Option;
129 O65Option* Next; /* Next in option list */
130 unsigned char Type; /* Type of option */
131 unsigned char Len; /* Data length */
132 unsigned char Data [1]; /* Data, dynamically allocated */
135 /* A o65 relocation table */
136 #define RELOC_BLOCKSIZE 4096
137 typedef struct O65RelocTab O65RelocTab;
139 unsigned Size; /* Size of the table */
140 unsigned Fill; /* Amount used */
141 unsigned char* Buf; /* Buffer, dynamically allocated */
144 /* Structure describing the format */
146 O65Header Header; /* File header */
147 O65Option* Options; /* List of file options */
148 ExtSymTab* Exports; /* Table with exported symbols */
149 ExtSymTab* Imports; /* Table with imported symbols */
150 unsigned Undef; /* Count of undefined symbols */
151 FILE* F; /* The file we're writing to */
152 char* Filename; /* Name of the output file */
153 O65RelocTab* TextReloc; /* Relocation table for text segment */
154 O65RelocTab* DataReloc; /* Relocation table for data segment */
156 unsigned TextCount; /* Number of segments assigned to .text */
157 SegDesc** TextSeg; /* Array of text segments */
158 unsigned DataCount; /* Number of segments assigned to .data */
159 SegDesc** DataSeg; /* Array of data segments */
160 unsigned BssCount; /* Number of segments assigned to .bss */
161 SegDesc** BssSeg; /* Array of bss segments */
162 unsigned ZPCount; /* Number of segments assigned to .zp */
163 SegDesc** ZPSeg; /* Array of zp segments */
165 /* Temporary data for writing segments */
166 unsigned long SegSize;
167 O65RelocTab* CurReloc;
171 /* Structure for parsing expression trees */
172 typedef struct ExprDesc ExprDesc;
174 O65Desc* D; /* File format descriptor */
175 long Val; /* The offset value */
176 int TooComplex; /* Expression too complex */
177 Segment* SegRef; /* Segment reference if any */
178 Section* SecRef; /* Section reference if any */
179 ExtSym* ExtRef; /* External reference if any */
184 /*****************************************************************************/
185 /* Helper functions */
186 /*****************************************************************************/
190 static ExprDesc* InitExprDesc (ExprDesc* ED, O65Desc* D)
191 /* Initialize an ExprDesc structure for use with O65ParseExpr */
204 static void WriteSize (const O65Desc* D, unsigned long Val)
205 /* Write a "size" word to the file */
207 switch (D->Header.Mode & MF_SIZE_MASK) {
208 case MF_SIZE_16BIT: Write16 (D->F, (unsigned) Val); break;
209 case MF_SIZE_32BIT: Write32 (D->F, Val); break;
210 default: Internal ("Invalid size in header: %04X", D->Header.Mode);
216 static unsigned O65SegType (const SegDesc* S)
217 /* Map our own segment types into something o65 compatible */
219 /* Check the segment type. Readonly segments are assign to the o65
220 * text segment, writeable segments that contain data are assigned
221 * to data, bss and zp segments are handled respectively.
222 * Beware: Zeropage segments have the SF_BSS flag set, so be sure
223 * to check SF_ZP first.
225 if (S->Flags & SF_RO) {
227 } else if (S->Flags & SF_ZP) {
229 } else if (S->Flags & SF_BSS) {
238 static const SegDesc* FindSeg (SegDesc** const List, unsigned Count, const Segment* S)
239 /* Search for a segment in the given list of segment descriptors and return
240 * the descriptor for a segment if we found it, and NULL if not.
245 for (I = 0; I < Count; ++I) {
246 if (List[I]->Seg == S) {
258 static const SegDesc* O65FindSeg (const O65Desc* D, const Segment* S)
259 /* Search for a segment in the segment lists and return it's segment descriptor */
263 if ((SD = FindSeg (D->TextSeg, D->TextCount, S)) != 0) {
266 if ((SD = FindSeg (D->DataSeg, D->DataCount, S)) != 0) {
269 if ((SD = FindSeg (D->BssSeg, D->BssCount, S)) != 0) {
272 if ((SD = FindSeg (D->ZPSeg, D->ZPCount, S)) != 0) {
282 /*****************************************************************************/
283 /* Expression handling */
284 /*****************************************************************************/
288 static void O65ParseExpr (ExprNode* Expr, ExprDesc* D, int Sign)
289 /* Extract and evaluate all constant factors in an subtree that has only
290 * additions and subtractions. If anything other than additions and
291 * subtractions are found, D->TooComplex is set to true.
301 D->Val -= Expr->V.Val;
303 D->Val += Expr->V.Val;
308 /* Get the referenced Export */
309 E = GetExprExport (Expr);
310 /* If this export has a mark set, we've already encountered it.
311 * This means that the export is used to define it's own value,
312 * which in turn means, that we have a circular reference.
314 if (ExportHasMark (E)) {
315 CircularRefError (E);
316 } else if (E->Expr == 0) {
317 /* Dummy export, must be an o65 imported symbol */
318 ExtSym* S = O65GetImport (D->D, E->Name);
321 /* We cannot have more than one external reference in o65 */
324 /* Remember the external reference */
329 O65ParseExpr (E->Expr, D, Sign);
336 /* We cannot handle more than one segment reference in o65 */
339 /* Remember the segment reference */
340 D->SecRef = GetExprSection (Expr);
341 /* Add the offset of the section to the constant value */
342 Val = D->SecRef->Offs + D->SecRef->Seg->PC;
353 /* We cannot handle more than one segment reference in o65 */
356 /* Remember the segment reference */
357 D->SegRef = Expr->V.Seg;
358 /* Add the offset of the segment to the constant value */
369 O65ParseExpr (Expr->Left, D, Sign);
370 O65ParseExpr (Expr->Right, D, Sign);
374 O65ParseExpr (Expr->Left, D, Sign);
375 O65ParseExpr (Expr->Right, D, -Sign);
379 /* Expression contains illegal operators */
388 /*****************************************************************************/
389 /* Relocation tables */
390 /*****************************************************************************/
394 static O65RelocTab* NewO65RelocTab (void)
395 /* Create a new relocation table */
397 /* Allocate a new structure */
398 O65RelocTab* R = xmalloc (sizeof (O65RelocTab));
400 /* Initialize the data */
401 R->Size = RELOC_BLOCKSIZE;
403 R->Buf = xmalloc (RELOC_BLOCKSIZE);
405 /* Return the created struct */
411 static void FreeO65RelocTab (O65RelocTab* R)
412 /* Free a relocation table */
420 static void O65RelocPutByte (O65RelocTab* R, unsigned B)
421 /* Put the byte into the relocation table */
423 /* Do we have enough space in the buffer? */
424 if (R->Fill == R->Size) {
425 /* We need to grow the buffer */
426 unsigned char* NewBuf = xmalloc (R->Size + RELOC_BLOCKSIZE);
427 memcpy (NewBuf, R->Buf, R->Size);
432 /* Put the byte into the buffer */
433 R->Buf [R->Fill++] = (unsigned char) B;
438 static void O65RelocPutWord (O65RelocTab* R, unsigned W)
439 /* Put a word into the relocation table */
441 O65RelocPutByte (R, W);
442 O65RelocPutByte (R, W >> 8);
447 static void O65WriteReloc (O65RelocTab* R, FILE* F)
448 /* Write the relocation table to the given file */
450 WriteData (F, R->Buf, R->Fill);
455 /*****************************************************************************/
456 /* Option handling */
457 /*****************************************************************************/
461 static O65Option* NewO65Option (unsigned Type, const void* Data, unsigned DataLen)
462 /* Allocate and initialize a new option struct */
466 /* Check the length */
467 CHECK (DataLen <= 253);
469 /* Allocate memory */
470 O = xmalloc (sizeof (O65Option) - 1 + DataLen);
472 /* Initialize the structure */
476 memcpy (O->Data, Data, DataLen);
478 /* Return the created struct */
484 static void FreeO65Option (O65Option* O)
485 /* Free an O65Option struct */
492 /*****************************************************************************/
493 /* Subroutines to write o65 sections */
494 /*****************************************************************************/
498 static void O65WriteHeader (O65Desc* D)
499 /* Write the header of the executable to the given file */
501 static unsigned char Trailer [5] = {
502 0x01, 0x00, 0x6F, 0x36, 0x35
507 /* Write the fixed header */
508 WriteData (D->F, Trailer, sizeof (Trailer));
509 Write8 (D->F, D->Header.Version);
510 Write16 (D->F, D->Header.Mode);
511 WriteSize (D, D->Header.TextBase);
512 WriteSize (D, D->Header.TextSize);
513 WriteSize (D, D->Header.DataBase);
514 WriteSize (D, D->Header.DataSize);
515 WriteSize (D, D->Header.BssBase);
516 WriteSize (D, D->Header.BssSize);
517 WriteSize (D, D->Header.ZPBase);
518 WriteSize (D, D->Header.ZPSize);
519 WriteSize (D, D->Header.StackSize);
521 /* Write the options */
524 Write8 (D->F, O->Len + 2); /* Account for len and type bytes */
525 Write8 (D->F, O->Type);
527 WriteData (D->F, O->Data, O->Len);
532 /* Write the end-of-options byte */
538 static unsigned O65WriteExpr (ExprNode* E, int Signed, unsigned Size,
539 unsigned long Offs, void* Data)
540 /* Called from SegWrite for an expression. Evaluate the expression, check the
541 * range and write the expression value to the file, update the relocation
550 unsigned char RelocType;
552 /* Cast the Data pointer to its real type, an O65Desc */
553 O65Desc* D = (O65Desc*) Data;
555 /* Check for a constant expression */
556 if (IsConstExpr (E)) {
557 /* Write out the constant expression */
558 return SegWriteConstExpr (((O65Desc*)Data)->F, E, Signed, Size);
561 /* We have a relocatable expression that needs a relocation table entry.
562 * Calculate the number of bytes between this entry and the last one, and
563 * setup all necessary intermediate bytes in the relocation table.
565 Offs += D->SegSize; /* Calulate full offset */
566 Diff = ((long) Offs) - D->LastOffs;
567 while (Diff > 0xFE) {
568 O65RelocPutByte (D->CurReloc, 0xFF);
571 O65RelocPutByte (D->CurReloc, (unsigned char) Diff);
573 /* Remember this offset for the next time */
576 /* Determine the expression to relocate */
578 if (E->Op == EXPR_BYTE0 || E->Op == EXPR_BYTE1 ||
579 E->Op == EXPR_BYTE2 || E->Op == EXPR_BYTE3 ||
580 E->Op == EXPR_WORD0 || E->Op == EXPR_WORD1) {
581 /* Use the real expression */
585 /* Recursively collect information about this expression */
586 O65ParseExpr (Expr, InitExprDesc (&ED, D), 1);
588 /* We cannot handle more than one external reference */
589 RefCount = (ED.SegRef != 0) + (ED.SecRef != 0) + (ED.ExtRef != 0);
594 /* Bail out if we cannot handle the expression */
596 return SEG_EXPR_TOO_COMPLEX;
599 /* Safety: Check that we have exactly one reference */
600 CHECK (RefCount == 1);
602 /* Write out the offset that goes into the segment. */
605 case EXPR_BYTE0: BinVal &= 0xFF; break;
606 case EXPR_BYTE1: BinVal = (BinVal >> 8) & 0xFF; break;
607 case EXPR_BYTE2: BinVal = (BinVal >> 16) & 0xFF; break;
608 case EXPR_BYTE3: BinVal = (BinVal >> 24) & 0xFF; break;
609 case EXPR_WORD0: BinVal &= 0xFFFF; break;
610 case EXPR_WORD1: BinVal = (BinVal >> 16) & 0xFFFF; break;
612 WriteVal (D->F, BinVal, Size);
614 /* Determine the actual type of relocation entry needed from the
615 * information gathered about the expression.
617 if (E->Op == EXPR_BYTE0) {
618 RelocType = O65RELOC_LOW;
619 } else if (E->Op == EXPR_BYTE1) {
620 RelocType = O65RELOC_HIGH;
621 } else if (E->Op == EXPR_BYTE2) {
622 RelocType = O65RELOC_SEG;
627 RelocType = O65RELOC_LOW;
631 RelocType = O65RELOC_WORD;
635 RelocType = O65RELOC_SEGADR;
639 /* 4 byte expression not supported by o65 */
640 return SEG_EXPR_TOO_COMPLEX;
643 Internal ("O65WriteExpr: Invalid expression size: %u", Size);
644 RelocType = 0; /* Avoid gcc warnings */
648 /* Determine which segment we're referencing */
649 if (ED.SegRef || ED.SecRef) {
653 /* Segment or section reference. */
655 /* Get segment from section */
656 ED.SegRef = ED.SecRef->Seg;
659 /* Search for the segment and map it to it's o65 segmentID */
660 Seg = O65FindSeg (D, ED.SegRef);
662 /* For some reason, we didn't find this segment in the list of
663 * segments written to the o65 file.
665 return SEG_EXPR_INVALID;
667 RelocType |= O65SegType (Seg);
668 O65RelocPutByte (D->CurReloc, RelocType);
670 /* Output additional data if needed */
671 switch (RelocType & O65RELOC_MASK) {
673 O65RelocPutByte (D->CurReloc, ED.Val & 0xFF);
676 O65RelocPutWord (D->CurReloc, ED.Val & 0xFFFF);
680 } else if (ED.ExtRef) {
681 /* Imported symbol */
682 RelocType |= O65SEG_UNDEF;
683 O65RelocPutByte (D->CurReloc, RelocType);
684 /* Put the number of the imported symbol into the table */
685 O65RelocPutWord (D->CurReloc, ExtSymNum (ED.ExtRef));
689 /* OOPS - something bad happened */
690 Internal ("External reference not handled");
700 static void O65WriteSeg (O65Desc* D, SegDesc** Seg, unsigned Count, int DoWrite)
701 /* Write one segment to the o65 output file */
706 /* Initialize variables */
710 /* Write out all segments */
711 for (I = 0; I < Count; ++I) {
713 /* Get the segment from the list node */
716 /* Keep the user happy */
717 Print (stdout, 1, " Writing `%s'\n", S->Name);
719 /* Write this segment */
721 RelocLineInfo (S->Seg);
722 SegWrite (D->F, S->Seg, O65WriteExpr, D);
725 /* Mark the segment as dumped */
728 /* Calculate the total size */
729 D->SegSize += S->Seg->Size;
732 /* Terminate the relocation table for this segment */
734 O65RelocPutByte (D->CurReloc, 0);
737 /* Check the size of the segment for overflow */
738 if ((D->Header.Mode & MF_SIZE_MASK) == MF_SIZE_16BIT && D->SegSize > 0xFFFF) {
739 Error ("Segment overflow in file `%s'", D->Filename);
746 static void O65WriteTextSeg (O65Desc* D)
747 /* Write the code segment to the o65 output file */
749 /* Initialize variables */
750 D->CurReloc = D->TextReloc;
752 /* Dump all text segments */
753 O65WriteSeg (D, D->TextSeg, D->TextCount, 1);
755 /* Set the size of the segment */
756 D->Header.TextSize = D->SegSize;
761 static void O65WriteDataSeg (O65Desc* D)
762 /* Write the data segment to the o65 output file */
764 /* Initialize variables */
765 D->CurReloc = D->DataReloc;
767 /* Dump all data segments */
768 O65WriteSeg (D, D->DataSeg, D->DataCount, 1);
770 /* Set the size of the segment */
771 D->Header.DataSize = D->SegSize;
776 static void O65WriteBssSeg (O65Desc* D)
777 /* "Write" the bss segments to the o65 output file. This will only update
778 * the relevant header fields.
781 /* Initialize variables */
784 /* Dump all data segments */
785 O65WriteSeg (D, D->BssSeg, D->BssCount, 0);
787 /* Set the size of the segment */
788 D->Header.BssSize = D->SegSize;
793 static void O65WriteZPSeg (O65Desc* D)
794 /* "Write" the zeropage segments to the o65 output file. This will only update
795 * the relevant header fields.
798 /* Initialize variables */
801 /* Dump all data segments */
802 O65WriteSeg (D, D->ZPSeg, D->ZPCount, 0);
804 /* Set the size of the segment */
805 D->Header.ZPSize = D->SegSize;
810 static void O65WriteImports (O65Desc* D)
811 /* Write the list of imported symbols to the O65 file */
815 /* Write the number of imports */
816 WriteSize (D, ExtSymCount (D->Imports));
818 /* Write out the symbol names, zero terminated */
819 S = ExtSymList (D->Imports);
822 const char* Name = ExtSymName (S);
823 /* And write it to the output file */
824 WriteData (D->F, Name, strlen (Name) + 1);
832 static void O65WriteTextReloc (O65Desc* D)
833 /* Write the relocation for the text segment to the output file */
835 O65WriteReloc (D->TextReloc, D->F);
840 static void O65WriteDataReloc (O65Desc* D)
841 /* Write the relocation for the data segment to the output file */
843 O65WriteReloc (D->DataReloc, D->F);
848 static void O65WriteExports (O65Desc* D)
849 /* Write the list of exports */
853 /* Write the number of exports */
854 WriteSize (D, ExtSymCount (D->Exports));
856 /* Write out the symbol information */
857 S = ExtSymList (D->Exports);
861 unsigned char SegmentID;
865 const char* Name = ExtSymName (S);
867 /* Get the export for this symbol. We've checked before that this
868 * export does really exist, so if it is unresolved, or if we don't
869 * find it, there is an error in the linker code.
871 Export* E = FindExport (Name);
872 if (E == 0 || IsUnresolvedExport (E)) {
873 Internal ("Unresolved export `%s' found in O65WriteExports", Name);
876 /* Get the expression for the symbol */
879 /* Recursively collect information about this expression */
880 O65ParseExpr (Expr, InitExprDesc (&ED, D), 1);
882 /* We cannot handle expressions with imported symbols, or expressions
883 * with more than one segment reference here
885 if (ED.ExtRef != 0 || (ED.SegRef != 0 && ED.SecRef != 0)) {
889 /* Bail out if we cannot handle the expression */
891 Error ("Expression for symbol `%s' is too complex", Name);
894 /* Determine the segment id for the expression */
895 if (ED.SegRef != 0 || ED.SecRef != 0) {
899 /* Segment or section reference */
900 if (ED.SecRef != 0) {
901 ED.SegRef = ED.SecRef->Seg; /* Get segment from section */
904 /* Search for the segment and map it to it's o65 segmentID */
905 Seg = O65FindSeg (D, ED.SegRef);
907 /* For some reason, we didn't find this segment in the list of
908 * segments written to the o65 file.
910 Error ("Segment for symbol `%s' is undefined", Name);
912 SegmentID = O65SegType (Seg);
917 SegmentID = O65SEG_ABS;
921 /* Write the name to the output file */
922 WriteData (D->F, Name, strlen (Name) + 1);
924 /* Output the segment id followed by the literal value */
925 Write8 (D->F, SegmentID);
926 WriteSize (D, ED.Val);
935 /*****************************************************************************/
937 /*****************************************************************************/
941 O65Desc* NewO65Desc (void)
942 /* Create, initialize and return a new O65 descriptor struct */
944 /* Allocate a new structure */
945 O65Desc* D = xmalloc (sizeof (O65Desc));
947 /* Initialize the header */
948 D->Header.Version = 0;
950 D->Header.TextBase = 0;
951 D->Header.TextSize = 0;
952 D->Header.DataBase = 0;
953 D->Header.DataSize = 0;
954 D->Header.BssBase = 0;
955 D->Header.BssSize = 0;
956 D->Header.ZPBase = 0;
957 D->Header.ZPSize = 0;
958 D->Header.StackSize = 0; /* Let OS choose a good value */
960 /* Initialize other data */
962 D->Exports = NewExtSymTab ();
963 D->Imports = NewExtSymTab ();
967 D->TextReloc = NewO65RelocTab ();
968 D->DataReloc = NewO65RelocTab ();
978 /* Return the created struct */
984 void FreeO65Desc (O65Desc* D)
985 /* Delete the descriptor struct with cleanup */
987 /* Free the segment arrays */
993 /* Free the relocation tables */
994 FreeO65RelocTab (D->DataReloc);
995 FreeO65RelocTab (D->TextReloc);
997 /* Free the option list */
999 O65Option* O = D->Options;
1000 D->Options = D->Options->Next;
1004 /* Free the external symbol tables */
1005 FreeExtSymTab (D->Exports);
1006 FreeExtSymTab (D->Imports);
1008 /* Free the struct itself */
1014 void O65Set6502 (O65Desc* D)
1015 /* Enable 6502 mode */
1017 D->Header.Mode = (D->Header.Mode & ~MF_CPU_MASK) | MF_CPU_6502;
1022 void O65Set65816 (O65Desc* D)
1023 /* Enable 816 mode */
1025 D->Header.Mode = (D->Header.Mode & ~MF_CPU_MASK) | MF_CPU_65816;
1030 void O65SetSmallModel (O65Desc* D)
1031 /* Enable a small memory model executable */
1033 D->Header.Mode = (D->Header.Mode & ~MF_SIZE_MASK) | MF_SIZE_16BIT;
1038 void O65SetLargeModel (O65Desc* D)
1039 /* Enable a large memory model executable */
1041 D->Header.Mode = (D->Header.Mode & ~MF_SIZE_MASK) | MF_SIZE_32BIT;
1046 void O65SetAlignment (O65Desc* D, unsigned Align)
1047 /* Set the executable alignment */
1049 /* Remove all alignment bits from the mode word */
1050 D->Header.Mode &= ~MF_ALIGN_MASK;
1052 /* Set the alignment bits */
1054 case 1: D->Header.Mode |= MF_ALIGN_1; break;
1055 case 2: D->Header.Mode |= MF_ALIGN_2; break;
1056 case 4: D->Header.Mode |= MF_ALIGN_4; break;
1057 case 256: D->Header.Mode |= MF_ALIGN_256; break;
1058 default: Error ("Invalid alignment for O65 format: %u", Align);
1064 void O65SetOption (O65Desc* D, unsigned Type, const void* Data, unsigned DataLen)
1065 /* Set an o65 header option */
1067 /* Create a new option structure */
1068 O65Option* O = NewO65Option (Type, Data, DataLen);
1070 /* Insert it into the linked list */
1071 O->Next = D->Options;
1077 void O65SetOS (O65Desc* D, unsigned OS, unsigned Version, unsigned Id)
1078 /* Set an option describing the target operating system */
1080 /* Setup the option data */
1081 unsigned char Opt[4];
1085 /* Write the correct option length */
1089 /* No id for these two */
1090 O65SetOption (D, O65OPT_OS, Opt, 2);
1094 /* Set the 16 bit id */
1095 Opt[2] = (unsigned char) Id;
1096 Opt[3] = (unsigned char) (Id >> 8);
1097 O65SetOption (D, O65OPT_OS, Opt, 4);
1101 Internal ("Trying to set invalid O65 operating system: %u", OS);
1107 ExtSym* O65GetImport (O65Desc* D, const char* Ident)
1108 /* Return the imported symbol or NULL if not found */
1110 /* Retrieve the symbol from the table */
1111 return GetExtSym (D->Imports, Ident);
1116 void O65SetImport (O65Desc* D, const char* Ident)
1117 /* Set an imported identifier */
1119 /* Insert the entry into the table */
1120 NewExtSym (D->Imports, Ident);
1125 ExtSym* O65GetExport (O65Desc* D, const char* Ident)
1126 /* Return the exported symbol or NULL if not found */
1128 /* Retrieve the symbol from the table */
1129 return GetExtSym (D->Exports, Ident);
1134 void O65SetExport (O65Desc* D, const char* Ident)
1135 /* Set an exported identifier */
1137 /* Get the export for this symbol and check if it does exist and is
1138 * a resolved symbol.
1140 Export* E = FindExport (Ident);
1141 if (E == 0 || IsUnresolvedExport (E)) {
1142 Error ("Unresolved export: `%s'", Ident);
1145 /* Insert the entry into the table */
1146 NewExtSym (D->Exports, Ident);
1151 static void O65SetupSegments (O65Desc* D, File* F)
1152 /* Setup segment assignments */
1157 unsigned TextIdx, DataIdx, BssIdx, ZPIdx;
1159 /* Initialize the counters */
1165 /* Walk over the memory list */
1168 /* Walk through the segment list and count the segment types */
1172 /* Get the segment from the list node */
1175 /* Check the segment type. */
1176 switch (O65SegType (S)) {
1177 case O65SEG_TEXT: D->TextCount++; break;
1178 case O65SEG_DATA: D->DataCount++; break;
1179 case O65SEG_BSS: D->BssCount++; break;
1180 case O65SEG_ZP: D->ZPCount++; break;
1181 default: Internal ("Invalid return from O65SegType");
1184 /* Next segment node */
1187 /* Next memory area */
1191 /* Allocate memory according to the numbers */
1192 D->TextSeg = xmalloc (D->TextCount * sizeof (SegDesc*));
1193 D->DataSeg = xmalloc (D->DataCount * sizeof (SegDesc*));
1194 D->BssSeg = xmalloc (D->BssCount * sizeof (SegDesc*));
1195 D->ZPSeg = xmalloc (D->ZPCount * sizeof (SegDesc*));
1197 /* Walk again through the list and setup the segment arrays */
1198 TextIdx = DataIdx = BssIdx = ZPIdx = 0;
1205 /* Get the segment from the list node */
1208 /* Check the segment type. */
1209 switch (O65SegType (S)) {
1210 case O65SEG_TEXT: D->TextSeg [TextIdx++] = S; break;
1211 case O65SEG_DATA: D->DataSeg [DataIdx++] = S; break;
1212 case O65SEG_BSS: D->BssSeg [BssIdx++] = S; break;
1213 case O65SEG_ZP: D->ZPSeg [ZPIdx++] = S; break;
1214 default: Internal ("Invalid return from O65SegType");
1217 /* Next segment node */
1220 /* Next memory area */
1227 static int O65Unresolved (const char* Name, void* D)
1228 /* Called if an unresolved symbol is encountered */
1230 /* Check if the symbol is an imported o65 symbol */
1231 if (O65GetImport (D, Name) != 0) {
1232 /* This is an external symbol, relax... */
1235 /* This is actually an unresolved external. Bump the counter */
1236 ((O65Desc*) D)->Undef++;
1243 static void O65SetupHeader (O65Desc* D)
1244 /* Set additional stuff in the header */
1246 /* Set the base addresses of the segments */
1247 if (D->TextCount > 0) {
1248 SegDesc* FirstSeg = D->TextSeg [0];
1249 D->Header.TextBase = FirstSeg->Seg->PC;
1251 if (D->DataCount > 0) {
1252 SegDesc* FirstSeg = D->DataSeg [0];
1253 D->Header.DataBase = FirstSeg->Seg->PC;
1255 if (D->BssCount > 0) {
1256 SegDesc* FirstSeg = D->BssSeg [0];
1257 D->Header.BssBase = FirstSeg->Seg->PC;
1259 if (D->ZPCount > 0) {
1260 SegDesc* FirstSeg = D->ZPSeg [0];
1261 D->Header.ZPBase = FirstSeg->Seg->PC;
1264 /* If we have byte wise relocation and an alignment of 1, we can set
1265 * the "simple addressing" bit in the header.
1267 if ((D->Header.Mode & MF_RELOC_MASK) == MF_RELOC_BYTE &&
1268 (D->Header.Mode & MF_ALIGN_MASK) == MF_ALIGN_1) {
1269 D->Header.Mode = (D->Header.Mode & ~MF_ADDR_MASK) | MF_ADDR_SIMPLE;
1275 void O65WriteTarget (O65Desc* D, File* F)
1276 /* Write an o65 output file */
1278 char OptBuf [256]; /* Buffer for option strings */
1282 /* Place the filename in the control structure */
1283 D->Filename = F->Name;
1285 /* Check for unresolved symbols. The function O65Unresolved is called
1286 * if we get an unresolved symbol.
1288 D->Undef = 0; /* Reset the counter */
1289 CheckExports (O65Unresolved, D);
1291 /* We had unresolved symbols, cannot create output file */
1292 Error ("%u unresolved external(s) found - cannot create output file", D->Undef);
1295 /* Setup the segment arrays */
1296 O65SetupSegments (D, F);
1298 /* Setup additional stuff in the header */
1302 D->F = fopen (F->Name, "wb");
1304 Error ("Cannot open `%s': %s", F->Name, strerror (errno));
1307 /* Keep the user happy */
1308 Print (stdout, 1, "Opened `%s'...\n", F->Name);
1310 /* Define some more options: A timestamp and the linker version */
1312 strcpy (OptBuf, ctime (&T));
1313 OptLen = strlen (OptBuf);
1314 while (OptLen > 0 && IsControl (OptBuf[OptLen-1])) {
1317 OptBuf[OptLen] = '\0';
1318 O65SetOption (D, O65OPT_TIMESTAMP, OptBuf, OptLen + 1);
1319 sprintf (OptBuf, "ld65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
1320 O65SetOption (D, O65OPT_ASM, OptBuf, strlen (OptBuf) + 1);
1322 /* Write the header */
1325 /* Write the text segment */
1326 O65WriteTextSeg (D);
1328 /* Write the data segment */
1329 O65WriteDataSeg (D);
1331 /* "Write" the bss segments */
1334 /* "Write" the zeropage segments */
1337 /* Write the undefined references list */
1338 O65WriteImports (D);
1340 /* Write the text segment relocation table */
1341 O65WriteTextReloc (D);
1343 /* Write the data segment relocation table */
1344 O65WriteDataReloc (D);
1346 /* Write the list of exports */
1347 O65WriteExports (D);
1349 /* Seek back to the start and write the updated header */
1350 fseek (D->F, 0, SEEK_SET);
1353 /* Close the file */
1354 if (fclose (D->F) != 0) {
1355 Error ("Cannot write to `%s': %s", F->Name, strerror (errno));
1358 /* Reset the file and filename */