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 /*****************************************************************************/
58 /*****************************************************************************/
60 /*****************************************************************************/
64 /* Header mode bits */
65 #define MF_CPU_65816 0x8000 /* Executable is for 65816 */
66 #define MF_CPU_6502 0x0000 /* Executable is for the 6502 */
67 #define MF_CPU_MASK 0x8000 /* Mask to extract CPU type */
69 #define MF_SIZE_32BIT 0x2000 /* All size words are 32bit */
70 #define MF_SIZE_16BIT 0x0000 /* All size words are 16bit */
71 #define MF_SIZE_MASK 0x2000 /* Mask to extract size */
73 #define MF_ALIGN_1 0x0000 /* Bytewise alignment */
74 #define MF_ALIGN_2 0x0001 /* Align words */
75 #define MF_ALIGN_4 0x0002 /* Align longwords */
76 #define MF_ALIGN_256 0x0003 /* Align pages (256 bytes) */
77 #define MF_ALIGN_MASK 0x0003 /* Mask to extract alignment */
79 /* The four o65 segment types. Note: These values are identical to the values
80 * needed for the segmentID in the o65 spec.
82 #define O65SEG_UNDEF 0x00
83 #define O65SEG_ABS 0x01
84 #define O65SEG_TEXT 0x02
85 #define O65SEG_DATA 0x03
86 #define O65SEG_BSS 0x04
87 #define O65SEG_ZP 0x05
89 /* Relocation type codes for the o65 format */
90 #define O65RELOC_WORD 0x80
91 #define O65RELOC_HIGH 0x40
92 #define O65RELOC_LOW 0x20
93 #define O65RELOC_SEGADR 0xc0
94 #define O65RELOC_SEG 0xa0
95 #define O65RELOC_MASK 0xc0
97 /* O65 executable file header */
98 typedef struct O65Header O65Header;
100 unsigned Version; /* Version number for o65 format */
101 unsigned Mode; /* Mode word */
102 unsigned long TextBase; /* Base address of text segment */
103 unsigned long TextSize; /* Size of text segment */
104 unsigned long DataBase; /* Base of data segment */
105 unsigned long DataSize; /* Size of data segment */
106 unsigned long BssBase; /* Base of bss segment */
107 unsigned long BssSize; /* Size of bss segment */
108 unsigned long ZPBase; /* Base of zeropage segment */
109 unsigned long ZPSize; /* Size of zeropage segment */
110 unsigned long StackSize; /* Requested stack size */
114 typedef struct O65Option O65Option;
116 O65Option* Next; /* Next in option list */
117 unsigned char Type; /* Type of option */
118 unsigned char Len; /* Data length */
119 unsigned char Data [1]; /* Data, dynamically allocated */
122 /* A o65 relocation table */
123 #define RELOC_BLOCKSIZE 4096
124 typedef struct O65RelocTab O65RelocTab;
126 unsigned Size; /* Size of the table */
127 unsigned Fill; /* Amount used */
128 unsigned char* Buf; /* Buffer, dynamically allocated */
131 /* Structure describing the format */
133 O65Header Header; /* File header */
134 O65Option* Options; /* List of file options */
135 ExtSymTab* Exports; /* Table with exported symbols */
136 ExtSymTab* Imports; /* Table with imported symbols */
137 unsigned Undef; /* Count of undefined symbols */
138 FILE* F; /* The file we're writing to */
139 char* Filename; /* Name of the output file */
140 O65RelocTab* TextReloc; /* Relocation table for text segment */
141 O65RelocTab* DataReloc; /* Relocation table for data segment */
143 unsigned TextCount; /* Number of segments assigned to .text */
144 SegDesc** TextSeg; /* Array of text segments */
145 unsigned DataCount; /* Number of segments assigned to .data */
146 SegDesc** DataSeg; /* Array of data segments */
147 unsigned BssCount; /* Number of segments assigned to .bss */
148 SegDesc** BssSeg; /* Array of bss segments */
149 unsigned ZPCount; /* Number of segments assigned to .zp */
150 SegDesc** ZPSeg; /* Array of zp segments */
152 /* Temporary data for writing segments */
153 unsigned long SegSize;
154 O65RelocTab* CurReloc;
158 /* Structure for parsing expression trees */
159 typedef struct ExprDesc ExprDesc;
161 O65Desc* D; /* File format descriptor */
162 long Val; /* The offset value */
163 int TooComplex; /* Expression too complex */
164 Section* SegRef; /* Section referenced if any */
165 ExtSym* ExtRef; /* External reference if any */
170 /*****************************************************************************/
171 /* Helper functions */
172 /*****************************************************************************/
176 static ExprDesc* InitExprDesc (ExprDesc* ED, O65Desc* D)
177 /* Initialize an ExprDesc structure for use with O65ParseExpr */
189 static void WriteSize (const O65Desc* D, unsigned long Val)
190 /* Write a "size" word to the file */
192 switch (D->Header.Mode & MF_SIZE_MASK) {
193 case MF_SIZE_16BIT: Write16 (D->F, (unsigned) Val); break;
194 case MF_SIZE_32BIT: Write32 (D->F, Val); break;
195 default: Internal ("Invalid size in header: %04X", D->Header.Mode);
201 static unsigned O65SegType (const SegDesc* S)
202 /* Map our own segment types into something o65 compatible */
204 /* Check the segment type. Readonly segments are assign to the o65
205 * text segment, writeable segments that contain data are assigned
206 * to data, bss and zp segments are handled respectively.
207 * Beware: Zeropage segments have the SF_BSS flag set, so be sure
208 * to check SF_ZP first.
210 if (S->Flags & SF_RO) {
212 } else if (S->Flags & SF_ZP) {
214 } else if (S->Flags & SF_BSS) {
223 static const SegDesc* FindSeg (SegDesc** const List, unsigned Count, const Segment* S)
224 /* Search for a segment in the given list of segment descriptors and return
225 * the descriptor for a segment if we found it, and NULL if not.
230 for (I = 0; I < Count; ++I) {
231 if (List[I]->Seg == S) {
243 static const SegDesc* O65FindSeg (const O65Desc* D, const Segment* S)
244 /* Search for a segment in the segment lists and return it's segment descriptor */
248 if ((SD = FindSeg (D->TextSeg, D->TextCount, S)) != 0) {
251 if ((SD = FindSeg (D->DataSeg, D->DataCount, S)) != 0) {
254 if ((SD = FindSeg (D->BssSeg, D->BssCount, S)) != 0) {
257 if ((SD = FindSeg (D->ZPSeg, D->ZPCount, S)) != 0) {
267 /*****************************************************************************/
268 /* Expression handling */
269 /*****************************************************************************/
273 static void O65ParseExpr (ExprNode* Expr, ExprDesc* D, int Sign)
274 /* Extract and evaluate all constant factors in an subtree that has only
275 * additions and subtractions. If anything other than additions and
276 * subtractions are found, D->TooComplex is set to true.
285 D->Val -= Expr->V.Val;
287 D->Val += Expr->V.Val;
292 /* Get the referenced Export */
293 E = GetExprExport (Expr);
294 /* If this export has a mark set, we've already encountered it.
295 * This means that the export is used to define it's own value,
296 * which in turn means, that we have a circular reference.
298 if (ExportHasMark (E)) {
299 CircularRefError (E);
300 } else if (E->Expr == 0) {
301 /* Dummy export, must be an o65 imported symbol */
302 ExtSym* S = O65GetImport (D->D, E->Name);
305 /* We cannot have more than one external reference in o65 */
308 /* Remember the external reference */
313 O65ParseExpr (E->Expr, D, Sign);
320 /* We cannot handle more than one segment reference in o65 */
323 /* Remember the segment reference */
324 D->SegRef = GetExprSection (Expr);
329 O65ParseExpr (Expr->Left, D, Sign);
330 O65ParseExpr (Expr->Right, D, Sign);
334 O65ParseExpr (Expr->Left, D, Sign);
335 O65ParseExpr (Expr->Right, D, -Sign);
339 /* Expression contains illegal operators */
348 /*****************************************************************************/
349 /* Relocation tables */
350 /*****************************************************************************/
354 static O65RelocTab* NewO65RelocTab (void)
355 /* Create a new relocation table */
357 /* Allocate a new structure */
358 O65RelocTab* R = xmalloc (sizeof (O65RelocTab));
360 /* Initialize the data */
361 R->Size = RELOC_BLOCKSIZE;
363 R->Buf = xmalloc (RELOC_BLOCKSIZE);
365 /* Return the created struct */
371 static void FreeO65RelocTab (O65RelocTab* R)
372 /* Free a relocation table */
380 static void O65RelocPutByte (O65RelocTab* R, unsigned B)
381 /* Put the byte into the relocation table */
383 /* Do we have enough space in the buffer? */
384 if (R->Fill == R->Size) {
385 /* We need to grow the buffer */
386 unsigned char* NewBuf = xmalloc (R->Size + RELOC_BLOCKSIZE);
387 memcpy (NewBuf, R->Buf, R->Size);
392 /* Put the byte into the buffer */
393 R->Buf [R->Fill++] = (unsigned char) B;
398 static void O65RelocPutWord (O65RelocTab* R, unsigned W)
399 /* Put a word into the relocation table */
401 O65RelocPutByte (R, W);
402 O65RelocPutByte (R, W >> 8);
407 static void O65WriteReloc (O65RelocTab* R, FILE* F)
408 /* Write the relocation table to the given file */
410 WriteData (F, R->Buf, R->Fill);
415 /*****************************************************************************/
416 /* Option handling */
417 /*****************************************************************************/
421 static O65Option* NewO65Option (unsigned Type, const void* Data, unsigned DataLen)
422 /* Allocate and initialize a new option struct */
426 /* Check the length */
427 CHECK (DataLen <= 253);
429 /* Allocate memory */
430 O = xmalloc (sizeof (O65Option) - 1 + DataLen);
432 /* Initialize the structure */
436 memcpy (O->Data, Data, DataLen);
438 /* Return the created struct */
444 static void FreeO65Option (O65Option* O)
445 /* Free an O65Option struct */
452 /*****************************************************************************/
453 /* Subroutines to write o65 sections */
454 /*****************************************************************************/
458 static void O65WriteHeader (O65Desc* D)
459 /* Write the header of the executable to the given file */
461 static unsigned char Trailer [5] = {
462 0x01, 0x00, 0x6F, 0x36, 0x35
468 /* Write the fixed header */
469 WriteData (D->F, Trailer, sizeof (Trailer));
470 Write8 (D->F, D->Header.Version);
471 Write16 (D->F, D->Header.Mode);
472 WriteSize (D, D->Header.TextBase);
473 WriteSize (D, D->Header.TextSize);
474 WriteSize (D, D->Header.DataBase);
475 WriteSize (D, D->Header.DataSize);
476 WriteSize (D, D->Header.BssBase);
477 WriteSize (D, D->Header.BssSize);
478 WriteSize (D, D->Header.ZPBase);
479 WriteSize (D, D->Header.ZPSize);
480 WriteSize (D, D->Header.StackSize);
482 /* Write the options */
485 Write8 (D->F, O->Len + 2); /* Account for len and type bytes */
486 Write8 (D->F, O->Type);
488 WriteData (D->F, O->Data, O->Len);
493 /* Write the end-of-options byte */
499 static unsigned O65WriteExpr (ExprNode* E, int Signed, unsigned Size,
500 unsigned long Offs, void* Data)
501 /* Called from SegWrite for an expression. Evaluate the expression, check the
502 * range and write the expression value to the file, update the relocation
510 unsigned char RelocType;
512 /* Cast the Data pointer to its real type, an O65Desc */
513 O65Desc* D = (O65Desc*) Data;
515 /* Check for a constant expression */
516 if (IsConstExpr (E)) {
517 /* Write out the constant expression */
518 return SegWriteConstExpr (((O65Desc*)Data)->F, E, Signed, Size);
521 /* We have a relocatable expression that needs a relocation table entry.
522 * Calculate the number of bytes between this entry and the last one, and
523 * setup all necessary intermediate bytes in the relocation table.
525 Offs += D->SegSize; /* Calulate full offset */
526 Diff = ((long) Offs) - D->LastOffs;
527 while (Diff > 0xFE) {
528 O65RelocPutByte (D->CurReloc, 0xFF);
531 O65RelocPutByte (D->CurReloc, (unsigned char) Diff);
533 /* Remember this offset for the next time */
536 /* Determine the expression to relocate */
538 if (E->Op == EXPR_BYTE0 || E->Op == EXPR_BYTE1 ||
539 E->Op == EXPR_BYTE2 || E->Op == EXPR_BYTE3 ||
540 E->Op == EXPR_WORD0 || E->Op == EXPR_WORD1) {
541 /* Use the real expression */
545 /* Recursively collect information about this expression */
546 O65ParseExpr (Expr, InitExprDesc (&ED, D), 1);
548 /* We cannot handle both, an imported symbol and a segment ref */
549 if (ED.SegRef != 0 && ED.ExtRef != 0) {
553 /* Bail out if we cannot handle the expression */
555 return SEG_EXPR_TOO_COMPLEX;
558 /* Safety: Check that we are really referencing a symbol or a segment */
559 CHECK (ED.SegRef != 0 || ED.ExtRef != 0);
561 /* Write out the offset that goes into the segment. */
564 case EXPR_BYTE0: BinVal &= 0xFF; break;
565 case EXPR_BYTE1: BinVal = (BinVal >> 8) & 0xFF; break;
566 case EXPR_BYTE2: BinVal = (BinVal >> 16) & 0xFF; break;
567 case EXPR_BYTE3: BinVal = (BinVal >> 24) & 0xFF; break;
568 case EXPR_WORD0: BinVal &= 0xFFFF; break;
569 case EXPR_WORD1: BinVal = (BinVal >> 16) & 0xFFFF; break;
571 WriteVal (D->F, BinVal, Size);
573 /* Determine the actual type of relocation entry needed from the
574 * information gathered about the expression.
576 if (E->Op == EXPR_BYTE0) {
577 RelocType = O65RELOC_LOW;
578 } else if (E->Op == EXPR_BYTE1) {
579 RelocType = O65RELOC_HIGH;
580 } else if (E->Op == EXPR_BYTE2) {
581 RelocType = O65RELOC_SEG;
586 RelocType = O65RELOC_LOW;
590 RelocType = O65RELOC_WORD;
594 RelocType = O65RELOC_SEGADR;
598 /* 4 byte expression not supported by o65 */
599 return SEG_EXPR_TOO_COMPLEX;
602 Internal ("O65WriteExpr: Invalid expression size: %u", Size);
603 RelocType = 0; /* Avoid gcc warnings */
607 /* Determine which segment we're referencing */
609 /* Imported symbol */
610 RelocType |= O65SEG_UNDEF;
611 O65RelocPutByte (D->CurReloc, RelocType);
612 /* Put the number of the imported symbol into the table */
613 O65RelocPutWord (D->CurReloc, ExtSymNum (ED.ExtRef));
615 /* Segment reference. Search for the segment and map it to it's
618 const SegDesc* Seg = O65FindSeg (D, ED.SegRef->Seg);
620 /* For some reason, we didn't find this segment in the list of
621 * segments written to the o65 file.
623 return SEG_EXPR_INVALID;
625 RelocType |= O65SegType (Seg);
626 O65RelocPutByte (D->CurReloc, RelocType);
628 /* Output additional data if needed */
629 switch (RelocType & O65RELOC_MASK) {
631 O65RelocPutByte (D->CurReloc, ED.Val & 0xFF);
634 O65RelocPutWord (D->CurReloc, ED.Val & 0xFFFF);
645 static void O65WriteSeg (O65Desc* D, SegDesc** Seg, unsigned Count, int DoWrite)
646 /* Write one segment to the o65 output file */
651 /* Initialize variables */
655 /* Write out all segments */
656 for (I = 0; I < Count; ++I) {
658 /* Get the segment from the list node */
661 /* Keep the user happy */
662 Print (stdout, 1, " Writing `%s'\n", S->Name);
664 /* Write this segment */
666 RelocLineInfo (S->Seg);
667 SegWrite (D->F, S->Seg, O65WriteExpr, D);
670 /* Mark the segment as dumped */
673 /* Calculate the total size */
674 D->SegSize += S->Seg->Size;
677 /* Terminate the relocation table for this segment */
679 O65RelocPutByte (D->CurReloc, 0);
682 /* Check the size of the segment for overflow */
683 if ((D->Header.Mode & MF_SIZE_MASK) == MF_SIZE_16BIT && D->SegSize > 0xFFFF) {
684 Error ("Segment overflow in file `%s'", D->Filename);
691 static void O65WriteTextSeg (O65Desc* D, Memory* M attribute ((unused)))
692 /* Write the code segment to the o65 output file */
694 /* Initialize variables */
695 D->CurReloc = D->TextReloc;
697 /* Dump all text segments */
698 O65WriteSeg (D, D->TextSeg, D->TextCount, 1);
700 /* Set the size of the segment */
701 D->Header.TextSize = D->SegSize;
706 static void O65WriteDataSeg (O65Desc* D, Memory* M attribute ((unused)))
707 /* Write the data segment to the o65 output file */
709 /* Initialize variables */
710 D->CurReloc = D->DataReloc;
712 /* Dump all data segments */
713 O65WriteSeg (D, D->DataSeg, D->DataCount, 1);
715 /* Set the size of the segment */
716 D->Header.DataSize = D->SegSize;
721 static void O65WriteBssSeg (O65Desc* D, Memory* M attribute ((unused)))
722 /* "Write" the bss segments to the o65 output file. This will only update
723 * the relevant header fields.
726 /* Initialize variables */
729 /* Dump all data segments */
730 O65WriteSeg (D, D->BssSeg, D->BssCount, 0);
732 /* Set the size of the segment */
733 D->Header.BssSize = D->SegSize;
738 static void O65WriteZPSeg (O65Desc* D, Memory* M attribute ((unused)))
739 /* "Write" the zeropage segments to the o65 output file. This will only update
740 * the relevant header fields.
743 /* Initialize variables */
746 /* Dump all data segments */
747 O65WriteSeg (D, D->ZPSeg, D->ZPCount, 0);
749 /* Set the size of the segment */
750 D->Header.ZPSize = D->SegSize;
755 static void O65WriteImports (O65Desc* D)
756 /* Write the list of imported symbols to the O65 file */
760 /* Write the number of imports */
761 WriteSize (D, ExtSymCount (D->Imports));
763 /* Write out the symbol names, zero terminated */
764 S = ExtSymList (D->Imports);
767 const char* Name = ExtSymName (S);
768 /* And write it to the output file */
769 WriteData (D->F, Name, strlen (Name) + 1);
777 static void O65WriteTextReloc (O65Desc* D)
778 /* Write the relocation for the text segment to the output file */
780 O65WriteReloc (D->TextReloc, D->F);
785 static void O65WriteDataReloc (O65Desc* D)
786 /* Write the relocation for the data segment to the output file */
788 O65WriteReloc (D->DataReloc, D->F);
793 static void O65WriteExports (O65Desc* D)
794 /* Write the list of exports */
798 /* Write the number of exports */
799 WriteSize (D, ExtSymCount (D->Exports));
801 /* Write out the symbol information */
802 S = ExtSymList (D->Exports);
806 unsigned char SegmentID;
810 const char* Name = ExtSymName (S);
812 /* Get the export for this symbol. We've checked before that this
813 * export does really exist, so if it is unresolved, or if we don't
814 * find it, there is an error in the linker code.
816 Export* E = FindExport (Name);
817 if (E == 0 || IsUnresolvedExport (E)) {
818 Internal ("Unresolved export `%s' found in O65WriteExports", Name);
821 /* Get the expression for the symbol */
824 /* Recursively collect information about this expression */
825 O65ParseExpr (Expr, InitExprDesc (&ED, D), 1);
827 /* We cannot handle expressions with imported symbols here */
828 if (ED.ExtRef != 0) {
832 /* Bail out if we cannot handle the expression */
834 Error ("Expression for symbol `%s' is too complex", Name);
837 /* Determine the segment id for the expression */
838 if (ED.SegRef == 0) {
840 SegmentID = O65SEG_ABS;
842 /* Segment reference. Search for the segment and map it to it's
845 const SegDesc* Seg = O65FindSeg (D, ED.SegRef->Seg);
847 /* For some reason, we didn't find this segment in the list of
848 * segments written to the o65 file.
850 Error ("Segment for symbol `%s' is undefined", Name);
852 SegmentID = O65SegType (Seg);
855 /* Write the name to the output file */
856 WriteData (D->F, Name, strlen (Name) + 1);
858 /* Output the segment id followed by the literal value */
859 Write8 (D->F, SegmentID);
860 WriteSize (D, ED.Val);
869 /*****************************************************************************/
871 /*****************************************************************************/
875 O65Desc* NewO65Desc (void)
876 /* Create, initialize and return a new O65 descriptor struct */
878 /* Allocate a new structure */
879 O65Desc* D = xmalloc (sizeof (O65Desc));
881 /* Initialize the header */
882 D->Header.Version = 0;
884 D->Header.TextBase = 0;
885 D->Header.TextSize = 0;
886 D->Header.DataBase = 0;
887 D->Header.DataSize = 0;
888 D->Header.BssBase = 0;
889 D->Header.BssSize = 0;
890 D->Header.ZPBase = 0;
891 D->Header.ZPSize = 0;
892 D->Header.StackSize = 0; /* Let OS choose a good value */
894 /* Initialize other data */
896 D->Exports = NewExtSymTab ();
897 D->Imports = NewExtSymTab ();
901 D->TextReloc = NewO65RelocTab ();
902 D->DataReloc = NewO65RelocTab ();
912 /* Return the created struct */
918 void FreeO65Desc (O65Desc* D)
919 /* Delete the descriptor struct with cleanup */
921 /* Free the segment arrays */
927 /* Free the relocation tables */
928 FreeO65RelocTab (D->DataReloc);
929 FreeO65RelocTab (D->TextReloc);
931 /* Free the option list */
933 O65Option* O = D->Options;
934 D->Options = D->Options->Next;
938 /* Free the external symbol tables */
939 FreeExtSymTab (D->Exports);
940 FreeExtSymTab (D->Imports);
942 /* Free the struct itself */
948 void O65Set6502 (O65Desc* D)
949 /* Enable 6502 mode */
951 D->Header.Mode = (D->Header.Mode & ~MF_CPU_MASK) | MF_CPU_6502;
956 void O65Set65816 (O65Desc* D)
957 /* Enable 816 mode */
959 D->Header.Mode = (D->Header.Mode & ~MF_CPU_MASK) | MF_CPU_65816;
964 void O65SetSmallModel (O65Desc* D)
965 /* Enable a small memory model executable */
967 D->Header.Mode = (D->Header.Mode & ~MF_SIZE_MASK) | MF_SIZE_16BIT;
972 void O65SetLargeModel (O65Desc* D)
973 /* Enable a large memory model executable */
975 D->Header.Mode = (D->Header.Mode & ~MF_SIZE_MASK) | MF_SIZE_32BIT;
980 void O65SetAlignment (O65Desc* D, unsigned Align)
981 /* Set the executable alignment */
983 /* Remove all alignment bits from the mode word */
984 D->Header.Mode &= ~MF_ALIGN_MASK;
986 /* Set the alignment bits */
988 case 1: D->Header.Mode |= MF_ALIGN_1; break;
989 case 2: D->Header.Mode |= MF_ALIGN_2; break;
990 case 4: D->Header.Mode |= MF_ALIGN_4; break;
991 case 256: D->Header.Mode |= MF_ALIGN_256; break;
992 default: Error ("Invalid alignment for O65 format: %u", Align);
998 void O65SetOption (O65Desc* D, unsigned Type, const void* Data, unsigned DataLen)
999 /* Set an o65 header option */
1001 /* Create a new option structure */
1002 O65Option* O = NewO65Option (Type, Data, DataLen);
1004 /* Insert it into the linked list */
1005 O->Next = D->Options;
1011 void O65SetOS (O65Desc* D, unsigned OS)
1012 /* Set an option describing the target operating system */
1014 static const unsigned char OSA65 [2] = { O65OS_OSA65, 0 };
1015 static const unsigned char Lunix [2] = { O65OS_LUNIX, 0 };
1017 /* Write the correct option */
1021 O65SetOption (D, O65OPT_OS, OSA65, sizeof (OSA65));
1025 O65SetOption (D, O65OPT_OS, Lunix, sizeof (Lunix));
1029 Internal ("Trying to set invalid O65 operating system: %u", OS);
1036 ExtSym* O65GetImport (O65Desc* D, const char* Ident)
1037 /* Return the imported symbol or NULL if not found */
1039 /* Retrieve the symbol from the table */
1040 return GetExtSym (D->Imports, Ident);
1045 void O65SetImport (O65Desc* D, const char* Ident)
1046 /* Set an imported identifier */
1048 /* Insert the entry into the table */
1049 NewExtSym (D->Imports, Ident);
1054 ExtSym* O65GetExport (O65Desc* D, const char* Ident)
1055 /* Return the exported symbol or NULL if not found */
1057 /* Retrieve the symbol from the table */
1058 return GetExtSym (D->Exports, Ident);
1063 void O65SetExport (O65Desc* D, const char* Ident)
1064 /* Set an exported identifier */
1066 /* Get the export for this symbol and check if it does exist and is
1067 * a resolved symbol.
1069 Export* E = FindExport (Ident);
1070 if (E == 0 || IsUnresolvedExport (E)) {
1071 Error ("Unresolved export: `%s'", Ident);
1074 /* Insert the entry into the table */
1075 NewExtSym (D->Exports, Ident);
1080 static void O65SetupSegments (O65Desc* D, Memory* M)
1081 /* Setup segment assignments */
1085 unsigned TextIdx, DataIdx, BssIdx, ZPIdx;
1087 /* Initialize the counters */
1093 /* Walk through the segment list and count the segment types */
1097 /* Get the segment from the list node */
1100 /* Check the segment type. */
1101 switch (O65SegType (S)) {
1102 case O65SEG_TEXT: D->TextCount++; break;
1103 case O65SEG_DATA: D->DataCount++; break;
1104 case O65SEG_BSS: D->BssCount++; break;
1105 case O65SEG_ZP: D->ZPCount++; break;
1106 default: Internal ("Invalid return from O65SegType");
1109 /* Next segment node */
1113 /* Allocate memory according to the numbers */
1114 D->TextSeg = xmalloc (D->TextCount * sizeof (SegDesc*));
1115 D->DataSeg = xmalloc (D->DataCount * sizeof (SegDesc*));
1116 D->BssSeg = xmalloc (D->BssCount * sizeof (SegDesc*));
1117 D->ZPSeg = xmalloc (D->ZPCount * sizeof (SegDesc*));
1119 /* Walk again through the list and setup the segment arrays */
1120 TextIdx = DataIdx = BssIdx = ZPIdx = 0;
1124 /* Get the segment from the list node */
1127 /* Check the segment type. */
1128 switch (O65SegType (S)) {
1129 case O65SEG_TEXT: D->TextSeg [TextIdx++] = S; break;
1130 case O65SEG_DATA: D->DataSeg [DataIdx++] = S; break;
1131 case O65SEG_BSS: D->BssSeg [BssIdx++] = S; break;
1132 case O65SEG_ZP: D->ZPSeg [ZPIdx++] = S; break;
1133 default: Internal ("Invalid return from O65SegType");
1136 /* Next segment node */
1143 static int O65Unresolved (const char* Name, void* D)
1144 /* Called if an unresolved symbol is encountered */
1146 /* Check if the symbol is an imported o65 symbol */
1147 if (O65GetImport (D, Name) != 0) {
1148 /* This is an external symbol, relax... */
1151 /* This is actually an unresolved external. Bump the counter */
1152 ((O65Desc*) D)->Undef++;
1159 void O65WriteTarget (O65Desc* D, File* F)
1160 /* Write an o65 output file */
1163 char OptBuf [256]; /* Buffer for option strings */
1166 /* Place the filename in the control structure */
1167 D->Filename = F->Name;
1169 /* The o65 format uses only one memory area per file. Check that. */
1172 Warning ("Cannot handle more than one memory area for o65 format");
1175 /* Check for unresolved symbols. The function O65Unresolved is called
1176 * if we get an unresolved symbol.
1178 D->Undef = 0; /* Reset the counter */
1179 CheckExports (O65Unresolved, D);
1181 /* We had unresolved symbols, cannot create output file */
1182 Error ("%u unresolved external(s) found - cannot create output file", D->Undef);
1185 /* Setup the segment arrays */
1186 O65SetupSegments (D, M);
1189 D->F = fopen (F->Name, "wb");
1191 Error ("Cannot open `%s': %s", F->Name, strerror (errno));
1194 /* Keep the user happy */
1195 Print (stdout, 1, "Opened `%s'...\n", F->Name);
1197 /* Define some more options: A timestamp and the linker version */
1199 strcpy (OptBuf, ctime (&T));
1200 O65SetOption (D, O65OPT_TIMESTAMP, OptBuf, strlen (OptBuf) + 1);
1201 sprintf (OptBuf, "ld65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
1202 O65SetOption (D, O65OPT_ASM, OptBuf, strlen (OptBuf) + 1);
1204 /* Write the header */
1207 /* Write the text segment */
1208 O65WriteTextSeg (D, M);
1210 /* Write the data segment */
1211 O65WriteDataSeg (D, M);
1213 /* "Write" the bss segments */
1214 O65WriteBssSeg (D, M);
1216 /* "Write" the zeropage segments */
1217 O65WriteZPSeg (D, M);
1219 /* Write the undefined references list */
1220 O65WriteImports (D);
1222 /* Write the text segment relocation table */
1223 O65WriteTextReloc (D);
1225 /* Write the data segment relocation table */
1226 O65WriteDataReloc (D);
1228 /* Write the list of exports */
1229 O65WriteExports (D);
1231 /* Seek back to the start and write the updated header */
1232 fseek (D->F, 0, SEEK_SET);
1235 /* Close the file */
1236 if (fclose (D->F) != 0) {
1237 Error ("Cannot write to `%s': %s", F->Name, strerror (errno));
1240 /* Reset the file and filename */