]> git.sur5r.net Git - cc65/blob - src/ld65/config.c
a67a3127ea207cbbe78500c4414bba8c0da90a5e
[cc65] / src / ld65 / config.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 config.c                                  */
4 /*                                                                           */
5 /*               Target configuration file for the ld65 linker               */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2010, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 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 <stdlib.h>
38 #include <string.h>
39 #include <errno.h>
40
41 /* common */
42 #include "addrsize.h"
43 #include "bitops.h"
44 #include "check.h"
45 #include "print.h"
46 #include "xmalloc.h"
47 #include "xsprintf.h"
48
49 /* ld65 */
50 #include "bin.h"
51 #include "binfmt.h"
52 #include "cfgexpr.h"
53 #include "condes.h"
54 #include "config.h"
55 #include "error.h"
56 #include "exports.h"
57 #include "expr.h"
58 #include "global.h"
59 #include "memarea.h"
60 #include "o65.h"
61 #include "objdata.h"
62 #include "scanner.h"
63 #include "spool.h"
64
65
66
67 /*****************************************************************************/
68 /*                                   Data                                    */
69 /*****************************************************************************/
70
71
72
73 /* Remember which sections we had encountered */
74 static enum {
75     SE_NONE     = 0x0000,
76     SE_MEMORY   = 0x0001,
77     SE_SEGMENTS = 0x0002,
78     SE_FEATURES = 0x0004,
79     SE_FILES    = 0x0008,
80     SE_FORMATS  = 0x0010,
81     SE_SYMBOLS  = 0x0020
82 } SectionsEncountered = SE_NONE;
83
84
85
86 /* File list */
87 static Collection       FileList = STATIC_COLLECTION_INITIALIZER;
88
89 /* Memory list */
90 static Collection       MemoryAreas = STATIC_COLLECTION_INITIALIZER;
91
92 /* Memory attributes */
93 #define MA_START        0x0001
94 #define MA_SIZE         0x0002
95 #define MA_TYPE         0x0004
96 #define MA_FILE         0x0008
97 #define MA_DEFINE       0x0010
98 #define MA_FILL         0x0020
99 #define MA_FILLVAL      0x0040
100
101 /* Segment list */
102 static Collection       SegDescList = STATIC_COLLECTION_INITIALIZER;
103
104 /* Segment attributes */
105 #define SA_TYPE         0x0001
106 #define SA_LOAD         0x0002
107 #define SA_RUN          0x0004
108 #define SA_ALIGN        0x0008
109 #define SA_ALIGN_LOAD   0x0010
110 #define SA_DEFINE       0x0020
111 #define SA_OFFSET       0x0040
112 #define SA_START        0x0080
113 #define SA_OPTIONAL     0x0100
114
115 /* Symbol types used in the CfgSymbol structure */
116 typedef enum {
117     CfgSymExport,               /* Not really used in struct CfgSymbol */
118     CfgSymImport,               /* Dito */
119     CfgSymWeak,                 /* Like export but weak */
120     CfgSymO65Export,            /* An o65 export */
121     CfgSymO65Import,            /* An o65 import */
122 } CfgSymType;
123
124 /* Symbol structure. It is used for o65 imports and exports, but also for
125  * symbols from the SYMBOLS sections (symbols defined in the config file or
126  * forced imports).
127  */
128 typedef struct CfgSymbol CfgSymbol;
129 struct CfgSymbol {
130     CfgSymType  Type;           /* Type of symbol */
131     FilePos     Pos;            /* Config file position */
132     unsigned    Name;           /* Symbol name */
133     ExprNode*   Value;          /* Symbol value if any */
134     unsigned    AddrSize;       /* Address size of symbol */
135 };
136
137 /* Collections with symbols */
138 static Collection       CfgSymbols = STATIC_COLLECTION_INITIALIZER;
139
140 /* Descriptor holding information about the binary formats */
141 static BinDesc* BinFmtDesc      = 0;
142 static O65Desc* O65FmtDesc      = 0;
143
144
145
146 /*****************************************************************************/
147 /*                                 Forwards                                  */
148 /*****************************************************************************/
149
150
151
152 static File* NewFile (unsigned Name);
153 /* Create a new file descriptor and insert it into the list */
154
155
156
157 /*****************************************************************************/
158 /*                              List management                              */
159 /*****************************************************************************/
160
161
162
163 static File* FindFile (unsigned Name)
164 /* Find a file with a given name. */
165 {
166     unsigned I;
167     for (I = 0; I < CollCount (&FileList); ++I) {
168         File* F = CollAtUnchecked (&FileList, I);
169         if (F->Name == Name) {
170             return F;
171         }
172     }
173     return 0;
174 }
175
176
177
178 static File* GetFile (unsigned Name)
179 /* Get a file entry with the given name. Create a new one if needed. */
180 {
181     File* F = FindFile (Name);
182     if (F == 0) {
183         /* Create a new one */
184         F = NewFile (Name);
185     }
186     return F;
187 }
188
189
190
191 static void FileInsert (File* F, MemoryArea* M)
192 /* Insert the memory area into the files list */
193 {
194     M->F = F;
195     CollAppend (&F->MemoryAreas, M);
196 }
197
198
199
200 static MemoryArea* CfgFindMemory (unsigned Name)
201 /* Find the memory are with the given name. Return NULL if not found */
202 {
203     unsigned I;
204     for (I = 0; I < CollCount (&MemoryAreas); ++I) {
205         MemoryArea* M = CollAtUnchecked (&MemoryAreas, I);
206         if (M->Name == Name) {
207             return M;
208         }
209     }
210     return 0;
211 }
212
213
214
215 static MemoryArea* CfgGetMemory (unsigned Name)
216 /* Find the memory are with the given name. Print an error on an invalid name */
217 {
218     MemoryArea* M = CfgFindMemory (Name);
219     if (M == 0) {
220         CfgError (&CfgErrorPos, "Invalid memory area `%s'", GetString (Name));
221     }
222     return M;
223 }
224
225
226
227 static SegDesc* CfgFindSegDesc (unsigned Name)
228 /* Find the segment descriptor with the given name, return NULL if not found. */
229 {
230     unsigned I;
231     for (I = 0; I < CollCount (&SegDescList); ++I) {
232         SegDesc* S = CollAtUnchecked (&SegDescList, I);
233         if (S->Name == Name) {
234             /* Found */
235             return S;
236         }
237     }
238
239     /* Not found */
240     return 0;
241 }
242
243
244
245 static void MemoryInsert (MemoryArea* M, SegDesc* S)
246 /* Insert the segment descriptor into the memory area list */
247 {
248     /* Insert the segment into the segment list of the memory area */
249     CollAppend (&M->SegList, S);
250 }
251
252
253
254 /*****************************************************************************/
255 /*                         Constructors/Destructors                          */
256 /*****************************************************************************/
257
258
259
260 static CfgSymbol* NewCfgSymbol (CfgSymType Type, unsigned Name)
261 /* Create a new CfgSymbol structure with the given type and name. The
262  * current config file position is recorded in the returned struct. The
263  * created struct is inserted into the CfgSymbols collection and returned.
264  */
265 {
266     /* Allocate memory */
267     CfgSymbol* Sym = xmalloc (sizeof (CfgSymbol));
268
269     /* Initialize the fields */
270     Sym->Type     = Type;
271     Sym->Pos      = CfgErrorPos;
272     Sym->Name     = Name;
273     Sym->Value    = 0;
274     Sym->AddrSize = ADDR_SIZE_INVALID;
275
276     /* Insert the symbol into the collection */
277     CollAppend (&CfgSymbols, Sym);
278
279     /* Return the initialized struct */
280     return Sym;
281 }
282
283
284
285 static File* NewFile (unsigned Name)
286 /* Create a new file descriptor and insert it into the list */
287 {
288     /* Allocate memory */
289     File* F = xmalloc (sizeof (File));
290
291     /* Initialize the fields */
292     F->Name    = Name;
293     F->Flags   = 0;
294     F->Format  = BINFMT_DEFAULT;
295     InitCollection (&F->MemoryAreas);
296
297     /* Insert the struct into the list */
298     CollAppend (&FileList, F);
299
300     /* ...and return it */
301     return F;
302 }
303
304
305
306 static MemoryArea* CreateMemoryArea (const FilePos* Pos, unsigned Name)
307 /* Create a new memory area and insert it into the list */
308 {
309     /* Check for duplicate names */
310     MemoryArea* M = CfgFindMemory (Name);
311     if (M) {
312         CfgError (&CfgErrorPos,
313                   "Memory area `%s' defined twice",
314                   GetString (Name));
315     }
316
317     /* Create a new memory area */
318     M = NewMemoryArea (Pos, Name);
319
320     /* Insert the struct into the list ... */
321     CollAppend (&MemoryAreas, M);
322
323     /* ...and return it */
324     return M;
325 }
326
327
328
329 static SegDesc* NewSegDesc (unsigned Name)
330 /* Create a segment descriptor and insert it into the list */
331 {
332
333     /* Check for duplicate names */
334     SegDesc* S = CfgFindSegDesc (Name);
335     if (S) {
336         CfgError (&CfgErrorPos, "Segment `%s' defined twice", GetString (Name));
337     }
338
339     /* Allocate memory */
340     S = xmalloc (sizeof (SegDesc));
341
342     /* Initialize the fields */
343     S->Name    = Name;
344     S->Pos     = CfgErrorPos;
345     S->Seg     = 0;
346     S->Attr    = 0;
347     S->Flags   = 0;
348     S->Align   = 0;
349
350     /* Insert the struct into the list ... */
351     CollAppend (&SegDescList, S);
352
353     /* ...and return it */
354     return S;
355 }
356
357
358
359 static void FreeSegDesc (SegDesc* S)
360 /* Free a segment descriptor */
361 {
362     xfree (S);
363 }
364
365
366
367 /*****************************************************************************/
368 /*                            Config file parsing                            */
369 /*****************************************************************************/
370
371
372
373 static void FlagAttr (unsigned* Flags, unsigned Mask, const char* Name)
374 /* Check if the item is already defined. Print an error if so. If not, set
375  * the marker that we have a definition now.
376  */
377 {
378     if (*Flags & Mask) {
379         CfgError (&CfgErrorPos, "%s is already defined", Name);
380     }
381     *Flags |= Mask;
382 }
383
384
385
386 static void AttrCheck (unsigned Attr, unsigned Mask, const char* Name)
387 /* Check that a mandatory attribute was given */
388 {
389     if ((Attr & Mask) == 0) {
390         CfgError (&CfgErrorPos, "%s attribute is missing", Name);
391     }
392 }
393
394
395
396 static void ParseMemory (void)
397 /* Parse a MEMORY section */
398 {
399     static const IdentTok Attributes [] = {
400         {   "START",    CFGTOK_START    },
401         {   "SIZE",     CFGTOK_SIZE     },
402         {   "TYPE",     CFGTOK_TYPE     },
403         {   "FILE",     CFGTOK_FILE     },
404         {   "DEFINE",   CFGTOK_DEFINE   },
405         {   "FILL",     CFGTOK_FILL     },
406         {   "FILLVAL",  CFGTOK_FILLVAL  },
407     };
408     static const IdentTok Types [] = {
409         {   "RO",       CFGTOK_RO       },
410         {   "RW",       CFGTOK_RW       },
411     };
412
413     while (CfgTok == CFGTOK_IDENT) {
414
415         /* Create a new entry on the heap */
416         MemoryArea* M = CreateMemoryArea (&CfgErrorPos, GetStrBufId (&CfgSVal));
417
418         /* Skip the name and the following colon */
419         CfgNextTok ();
420         CfgConsumeColon ();
421
422         /* Read the attributes */
423         while (CfgTok == CFGTOK_IDENT) {
424
425             /* Map the identifier to a token */
426             cfgtok_t AttrTok;
427             CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute");
428             AttrTok = CfgTok;
429
430             /* An optional assignment follows */
431             CfgNextTok ();
432             CfgOptionalAssign ();
433
434             /* Check which attribute was given */
435             switch (AttrTok) {
436
437                 case CFGTOK_START:
438                     FlagAttr (&M->Attr, MA_START, "START");
439                     M->StartExpr = CfgExpr ();
440                     break;
441
442                 case CFGTOK_SIZE:
443                     FlagAttr (&M->Attr, MA_SIZE, "SIZE");
444                     M->SizeExpr = CfgExpr ();
445                     break;
446
447                 case CFGTOK_TYPE:
448                     FlagAttr (&M->Attr, MA_TYPE, "TYPE");
449                     CfgSpecialToken (Types, ENTRY_COUNT (Types), "Type");
450                     if (CfgTok == CFGTOK_RO) {
451                         M->Flags |= MF_RO;
452                     }
453                     CfgNextTok ();
454                     break;
455
456                 case CFGTOK_FILE:
457                     FlagAttr (&M->Attr, MA_FILE, "FILE");
458                     CfgAssureStr ();
459                     /* Get the file entry and insert the memory area */
460                     FileInsert (GetFile (GetStrBufId (&CfgSVal)), M);
461                     CfgNextTok ();
462                     break;
463
464                 case CFGTOK_DEFINE:
465                     FlagAttr (&M->Attr, MA_DEFINE, "DEFINE");
466                     /* Map the token to a boolean */
467                     CfgBoolToken ();
468                     if (CfgTok == CFGTOK_TRUE) {
469                         M->Flags |= MF_DEFINE;
470                     }
471                     CfgNextTok ();
472                     break;
473
474                 case CFGTOK_FILL:
475                     FlagAttr (&M->Attr, MA_FILL, "FILL");
476                     /* Map the token to a boolean */
477                     CfgBoolToken ();
478                     if (CfgTok == CFGTOK_TRUE) {
479                         M->Flags |= MF_FILL;
480                     }
481                     CfgNextTok ();
482                     break;
483
484                 case CFGTOK_FILLVAL:
485                     FlagAttr (&M->Attr, MA_FILLVAL, "FILLVAL");
486                     M->FillVal = (unsigned char) CfgCheckedConstExpr (0, 0xFF);
487                     break;
488
489                 default:
490                     FAIL ("Unexpected attribute token");
491
492             }
493
494             /* Skip an optional comma */
495             CfgOptionalComma ();
496         }
497
498         /* Skip the semicolon */
499         CfgConsumeSemi ();
500
501         /* Check for mandatory parameters */
502         AttrCheck (M->Attr, MA_START, "START");
503         AttrCheck (M->Attr, MA_SIZE, "SIZE");
504
505         /* If we don't have a file name for output given, use the default
506          * file name.
507          */
508         if ((M->Attr & MA_FILE) == 0) {
509             FileInsert (GetFile (GetStringId (OutputName)), M);
510             OutputNameUsed = 1;
511         }
512     }
513
514     /* Remember we had this section */
515     SectionsEncountered |= SE_MEMORY;
516 }
517
518
519
520 static void ParseFiles (void)
521 /* Parse a FILES section */
522 {
523     static const IdentTok Attributes [] = {
524         {   "FORMAT",   CFGTOK_FORMAT   },
525     };
526     static const IdentTok Formats [] = {
527         {   "O65",      CFGTOK_O65      },
528         {   "BIN",      CFGTOK_BIN      },
529         {   "BINARY",   CFGTOK_BIN      },
530     };
531
532
533     /* The MEMORY section must preceed the FILES section */
534     if ((SectionsEncountered & SE_MEMORY) == 0) {
535         CfgError (&CfgErrorPos, "MEMORY must precede FILES");
536     }
537
538     /* Parse all files */
539     while (CfgTok != CFGTOK_RCURLY) {
540
541         File* F;
542
543         /* We expect a string value here */
544         CfgAssureStr ();
545
546         /* Search for the file, it must exist */
547         F = FindFile (GetStrBufId (&CfgSVal));
548         if (F == 0) {
549             CfgError (&CfgErrorPos,
550                       "File `%s' not found in MEMORY section",
551                       SB_GetConstBuf (&CfgSVal));
552         }
553
554         /* Skip the token and the following colon */
555         CfgNextTok ();
556         CfgConsumeColon ();
557
558         /* Read the attributes */
559         while (CfgTok == CFGTOK_IDENT) {
560
561             /* Map the identifier to a token */
562             cfgtok_t AttrTok;
563             CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute");
564             AttrTok = CfgTok;
565
566             /* An optional assignment follows */
567             CfgNextTok ();
568             CfgOptionalAssign ();
569
570             /* Check which attribute was given */
571             switch (AttrTok) {
572
573                 case CFGTOK_FORMAT:
574                     if (F->Format != BINFMT_DEFAULT) {
575                         /* We've set the format already! */
576                         CfgError (&CfgErrorPos,
577                                   "Cannot set a file format twice");
578                     }
579                     /* Read the format token */
580                     CfgSpecialToken (Formats, ENTRY_COUNT (Formats), "Format");
581                     switch (CfgTok) {
582
583                         case CFGTOK_BIN:
584                             F->Format = BINFMT_BINARY;
585                             break;
586
587                         case CFGTOK_O65:
588                             F->Format = BINFMT_O65;
589                             break;
590
591                         default:
592                             Error ("Unexpected format token");
593                     }
594                     break;
595
596                 default:
597                     FAIL ("Unexpected attribute token");
598
599             }
600
601             /* Skip the attribute value and an optional comma */
602             CfgNextTok ();
603             CfgOptionalComma ();
604         }
605
606         /* Skip the semicolon */
607         CfgConsumeSemi ();
608
609     }
610
611     /* Remember we had this section */
612     SectionsEncountered |= SE_FILES;
613 }
614
615
616
617 static void ParseSegments (void)
618 /* Parse a SEGMENTS section */
619 {
620     static const IdentTok Attributes [] = {
621         {   "ALIGN",            CFGTOK_ALIGN            },
622         {   "ALIGN_LOAD",       CFGTOK_ALIGN_LOAD       },
623         {   "DEFINE",           CFGTOK_DEFINE           },
624         {   "LOAD",             CFGTOK_LOAD             },
625         {   "OFFSET",           CFGTOK_OFFSET           },
626         {   "OPTIONAL",         CFGTOK_OPTIONAL         },
627         {   "RUN",              CFGTOK_RUN              },
628         {   "START",            CFGTOK_START            },
629         {   "TYPE",             CFGTOK_TYPE             },
630     };
631     static const IdentTok Types [] = {
632         {   "RO",               CFGTOK_RO               },
633         {   "RW",               CFGTOK_RW               },
634         {   "BSS",              CFGTOK_BSS              },
635         {   "ZP",               CFGTOK_ZP               },
636     };
637
638     unsigned Count;
639     long     Val;
640
641     /* The MEMORY section must preceed the SEGMENTS section */
642     if ((SectionsEncountered & SE_MEMORY) == 0) {
643         CfgError (&CfgErrorPos, "MEMORY must precede SEGMENTS");
644     }
645
646     while (CfgTok == CFGTOK_IDENT) {
647
648         SegDesc* S;
649
650         /* Create a new entry on the heap */
651         S = NewSegDesc (GetStrBufId (&CfgSVal));
652
653         /* Skip the name and the following colon */
654         CfgNextTok ();
655         CfgConsumeColon ();
656
657         /* Read the attributes */
658         while (CfgTok == CFGTOK_IDENT) {
659
660             /* Map the identifier to a token */
661             cfgtok_t AttrTok;
662             CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute");
663             AttrTok = CfgTok;
664
665             /* An optional assignment follows */
666             CfgNextTok ();
667             CfgOptionalAssign ();
668
669             /* Check which attribute was given */
670             switch (AttrTok) {
671
672                 case CFGTOK_ALIGN:
673                     FlagAttr (&S->Attr, SA_ALIGN, "ALIGN");
674                     Val = CfgCheckedConstExpr (1, 0x10000);
675                     S->Align = BitFind (Val);
676                     if ((0x01L << S->Align) != Val) {
677                         CfgError (&CfgErrorPos, "Alignment must be a power of 2");
678                     }
679                     S->Flags |= SF_ALIGN;
680                     break;
681
682                 case CFGTOK_ALIGN_LOAD:
683                     FlagAttr (&S->Attr, SA_ALIGN_LOAD, "ALIGN_LOAD");
684                     Val = CfgCheckedConstExpr (1, 0x10000);
685                     S->AlignLoad = BitFind (Val);
686                     if ((0x01L << S->AlignLoad) != Val) {
687                         CfgError (&CfgErrorPos, "Alignment must be a power of 2");
688                     }
689                     S->Flags |= SF_ALIGN_LOAD;
690                     break;
691
692                 case CFGTOK_DEFINE:
693                     FlagAttr (&S->Attr, SA_DEFINE, "DEFINE");
694                     /* Map the token to a boolean */
695                     CfgBoolToken ();
696                     if (CfgTok == CFGTOK_TRUE) {
697                         S->Flags |= SF_DEFINE;
698                     }
699                     CfgNextTok ();
700                     break;
701
702                 case CFGTOK_LOAD:
703                     FlagAttr (&S->Attr, SA_LOAD, "LOAD");
704                     S->Load = CfgGetMemory (GetStrBufId (&CfgSVal));
705                     CfgNextTok ();
706                     break;
707
708                 case CFGTOK_OFFSET:
709                     FlagAttr (&S->Attr, SA_OFFSET, "OFFSET");
710                     S->Addr   = CfgCheckedConstExpr (1, 0x1000000);
711                     S->Flags |= SF_OFFSET;
712                     break;
713
714                 case CFGTOK_OPTIONAL:
715                     FlagAttr (&S->Attr, SA_OPTIONAL, "OPTIONAL");
716                     CfgBoolToken ();
717                     if (CfgTok == CFGTOK_TRUE) {
718                         S->Flags |= SF_OPTIONAL;
719                     }
720                     CfgNextTok ();
721                     break;
722
723                 case CFGTOK_RUN:
724                     FlagAttr (&S->Attr, SA_RUN, "RUN");
725                     S->Run = CfgGetMemory (GetStrBufId (&CfgSVal));
726                     CfgNextTok ();
727                     break;
728
729                 case CFGTOK_START:
730                     FlagAttr (&S->Attr, SA_START, "START");
731                     S->Addr   = CfgCheckedConstExpr (1, 0x1000000);
732                     S->Flags |= SF_START;
733                     break;
734
735                 case CFGTOK_TYPE:
736                     FlagAttr (&S->Attr, SA_TYPE, "TYPE");
737                     CfgSpecialToken (Types, ENTRY_COUNT (Types), "Type");
738                     switch (CfgTok) {
739                         case CFGTOK_RO:    S->Flags |= SF_RO;               break;
740                         case CFGTOK_RW:    /* Default */                    break;
741                         case CFGTOK_BSS:   S->Flags |= SF_BSS;              break;
742                         case CFGTOK_ZP:    S->Flags |= (SF_BSS | SF_ZP);    break;
743                         default:           Internal ("Unexpected token: %d", CfgTok);
744                     }
745                     CfgNextTok ();
746                     break;
747
748                 default:
749                     FAIL ("Unexpected attribute token");
750
751             }
752
753             /* Skip an optional comma */
754             CfgOptionalComma ();
755         }
756
757         /* Check for mandatory parameters */
758         AttrCheck (S->Attr, SA_LOAD, "LOAD");
759
760         /* Set defaults for stuff not given */
761         if ((S->Attr & SA_RUN) == 0) {
762             S->Attr |= SA_RUN;
763             S->Run = S->Load;
764         }
765
766         /* An attribute of ALIGN_LOAD doesn't make sense if there are no
767          * separate run and load memory areas.
768          */
769         if ((S->Flags & SF_ALIGN_LOAD) != 0 && (S->Load == S->Run)) {
770             Warning ("%s(%lu): ALIGN_LOAD attribute specified, but no separate "
771                      "LOAD and RUN memory areas assigned",
772                      CfgGetName (), CfgErrorPos.Line);
773             /* Remove the flag */
774             S->Flags &= ~SF_ALIGN_LOAD;
775         }
776
777         /* If the segment is marked as BSS style, it may not have separate
778          * load and run memory areas, because it's is never written to disk.
779          */
780         if ((S->Flags & SF_BSS) != 0 && (S->Load != S->Run)) {
781             Warning ("%s(%lu): Segment with type `bss' has both LOAD and RUN "
782                      "memory areas assigned", CfgGetName (), CfgErrorPos.Line);
783         }
784
785         /* Don't allow read/write data to be put into a readonly area */
786         if ((S->Flags & SF_RO) == 0) {
787             if (S->Run->Flags & MF_RO) {
788                 CfgError (&CfgErrorPos,
789                           "Cannot put r/w segment `%s' in r/o memory area `%s'",
790                           GetString (S->Name), GetString (S->Run->Name));
791             }
792         }
793
794         /* Only one of ALIGN, START and OFFSET may be used */
795         Count = ((S->Flags & SF_ALIGN)  != 0) +
796                 ((S->Flags & SF_OFFSET) != 0) +
797                 ((S->Flags & SF_START)  != 0);
798         if (Count > 1) {
799             CfgError (&CfgErrorPos,
800                       "Only one of ALIGN, START, OFFSET may be used");
801         }
802
803         /* Skip the semicolon */
804         CfgConsumeSemi ();
805     }
806
807     /* Remember we had this section */
808     SectionsEncountered |= SE_SEGMENTS;
809 }
810
811
812
813 static void ParseO65 (void)
814 /* Parse the o65 format section */
815 {
816     static const IdentTok Attributes [] = {
817         {   "EXPORT",   CFGTOK_EXPORT           },
818         {   "IMPORT",   CFGTOK_IMPORT           },
819         {   "TYPE",     CFGTOK_TYPE             },
820         {   "OS",       CFGTOK_OS               },
821         {   "ID",       CFGTOK_ID               },
822         {   "VERSION",  CFGTOK_VERSION          },
823     };
824     static const IdentTok Types [] = {
825         {   "SMALL",    CFGTOK_SMALL            },
826         {   "LARGE",    CFGTOK_LARGE            },
827     };
828     static const IdentTok OperatingSystems [] = {
829         {   "LUNIX",    CFGTOK_LUNIX            },
830         {   "OSA65",    CFGTOK_OSA65            },
831         {   "CC65",     CFGTOK_CC65             },
832         {   "OPENCBM",  CFGTOK_OPENCBM          },
833     };
834
835     /* Bitmask to remember the attributes we got already */
836     enum {
837         atNone          = 0x0000,
838         atOS            = 0x0001,
839         atOSVersion     = 0x0002,
840         atType          = 0x0004,
841         atImport        = 0x0008,
842         atExport        = 0x0010,
843         atID            = 0x0020,
844         atVersion       = 0x0040
845     };
846     unsigned AttrFlags = atNone;
847
848     /* Remember the attributes read */
849     unsigned OS = 0;            /* Initialize to keep gcc happy */
850     unsigned Version = 0;
851
852     /* Read the attributes */
853     while (CfgTok == CFGTOK_IDENT) {
854
855         /* Map the identifier to a token */
856         cfgtok_t AttrTok;
857         CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute");
858         AttrTok = CfgTok;
859
860         /* An optional assignment follows */
861         CfgNextTok ();
862         CfgOptionalAssign ();
863
864         /* Check which attribute was given */
865         switch (AttrTok) {
866
867             case CFGTOK_EXPORT:
868                 /* Remember we had this token (maybe more than once) */
869                 AttrFlags |= atExport;
870                 /* We expect an identifier */
871                 CfgAssureIdent ();
872                 /* Remember it as an export for later */
873                 NewCfgSymbol (CfgSymO65Export, GetStrBufId (&CfgSVal));
874                 /* Eat the identifier token */
875                 CfgNextTok ();
876                 break;
877
878             case CFGTOK_IMPORT:
879                 /* Remember we had this token (maybe more than once) */
880                 AttrFlags |= atImport;
881                 /* We expect an identifier */
882                 CfgAssureIdent ();
883                 /* Remember it as an import for later */
884                 NewCfgSymbol (CfgSymO65Import, GetStrBufId (&CfgSVal));
885                 /* Eat the identifier token */
886                 CfgNextTok ();
887                 break;
888
889             case CFGTOK_TYPE:
890                 /* Cannot have this attribute twice */
891                 FlagAttr (&AttrFlags, atType, "TYPE");
892                 /* Get the type of the executable */
893                 CfgSpecialToken (Types, ENTRY_COUNT (Types), "Type");
894                 switch (CfgTok) {
895
896                     case CFGTOK_SMALL:
897                         O65SetSmallModel (O65FmtDesc);
898                         break;
899
900                     case CFGTOK_LARGE:
901                         O65SetLargeModel (O65FmtDesc);
902                         break;
903
904                     default:
905                         CfgError (&CfgErrorPos, "Unexpected type token");
906                 }
907                 /* Eat the attribute token */
908                 CfgNextTok ();
909                 break;
910
911             case CFGTOK_OS:
912                 /* Cannot use this attribute twice */
913                 FlagAttr (&AttrFlags, atOS, "OS");
914                 /* Get the operating system. It may be specified as name or
915                  * as a number in the range 1..255.
916                  */
917                 if (CfgTok == CFGTOK_INTCON) {
918                     CfgRangeCheck (O65OS_MIN, O65OS_MAX);
919                     OS = (unsigned) CfgIVal;
920                 } else {
921                     CfgSpecialToken (OperatingSystems, ENTRY_COUNT (OperatingSystems), "OS type");
922                     switch (CfgTok) {
923                         case CFGTOK_LUNIX:    OS = O65OS_LUNIX;     break;
924                         case CFGTOK_OSA65:    OS = O65OS_OSA65;     break;
925                         case CFGTOK_CC65:     OS = O65OS_CC65;      break;
926                         case CFGTOK_OPENCBM:  OS = O65OS_OPENCBM;   break;
927                         default:              CfgError (&CfgErrorPos, "Unexpected OS token");
928                     }
929                 }
930                 CfgNextTok ();
931                 break;
932
933             case CFGTOK_ID:
934                 /* Cannot have this attribute twice */
935                 FlagAttr (&AttrFlags, atID, "ID");
936                 /* We're expecting a number in the 0..$FFFF range*/
937                 ModuleId = (unsigned) CfgCheckedConstExpr (0, 0xFFFF);
938                 break;
939
940             case CFGTOK_VERSION:
941                 /* Cannot have this attribute twice */
942                 FlagAttr (&AttrFlags, atVersion, "VERSION");
943                 /* We're expecting a number in byte range */
944                 Version = (unsigned) CfgCheckedConstExpr (0, 0xFF);
945                 break;
946
947             default:
948                 FAIL ("Unexpected attribute token");
949
950         }
951
952         /* Skip an optional comma */
953         CfgOptionalComma ();
954     }
955
956     /* Check if we have all mandatory attributes */
957     AttrCheck (AttrFlags, atOS, "OS");
958
959     /* Check for attributes that may not be combined */
960     if (OS == O65OS_CC65) {
961         if ((AttrFlags & (atImport | atExport)) != 0 && ModuleId < 0x8000) {
962             CfgError (&CfgErrorPos,
963                       "OS type CC65 may not have imports or exports for ids < $8000");
964         }
965     } else {
966         if (AttrFlags & atID) {
967             CfgError (&CfgErrorPos,
968                       "Operating system does not support the ID attribute");
969         }
970     }
971
972     /* Set the O65 operating system to use */
973     O65SetOS (O65FmtDesc, OS, Version, ModuleId);
974 }
975
976
977
978 static void ParseFormats (void)
979 /* Parse a target format section */
980 {
981     static const IdentTok Formats [] = {
982         {   "O65",      CFGTOK_O65      },
983         {   "BIN",      CFGTOK_BIN      },
984         {   "BINARY",   CFGTOK_BIN      },
985     };
986
987     while (CfgTok == CFGTOK_IDENT) {
988
989         /* Map the identifier to a token */
990         cfgtok_t FormatTok;
991         CfgSpecialToken (Formats, ENTRY_COUNT (Formats), "Format");
992         FormatTok = CfgTok;
993
994         /* Skip the name and the following colon */
995         CfgNextTok ();
996         CfgConsumeColon ();
997
998         /* Parse the format options */
999         switch (FormatTok) {
1000
1001             case CFGTOK_O65:
1002                 ParseO65 ();
1003                 break;
1004
1005             case CFGTOK_BIN:
1006                 /* No attribibutes available */
1007                 break;
1008
1009             default:
1010                 Error ("Unexpected format token");
1011         }
1012
1013         /* Skip the semicolon */
1014         CfgConsumeSemi ();
1015     }
1016
1017
1018     /* Remember we had this section */
1019     SectionsEncountered |= SE_FORMATS;
1020 }
1021
1022
1023
1024 static void ParseConDes (void)
1025 /* Parse the CONDES feature */
1026 {
1027     static const IdentTok Attributes [] = {
1028         {   "SEGMENT",          CFGTOK_SEGMENT          },
1029         {   "LABEL",            CFGTOK_LABEL            },
1030         {   "COUNT",            CFGTOK_COUNT            },
1031         {   "TYPE",             CFGTOK_TYPE             },
1032         {   "ORDER",            CFGTOK_ORDER            },
1033     };
1034
1035     static const IdentTok Types [] = {
1036         {   "CONSTRUCTOR",      CFGTOK_CONSTRUCTOR      },
1037         {   "DESTRUCTOR",       CFGTOK_DESTRUCTOR       },
1038         {   "INTERRUPTOR",      CFGTOK_INTERRUPTOR      },
1039     };
1040
1041     static const IdentTok Orders [] = {
1042         {   "DECREASING",       CFGTOK_DECREASING       },
1043         {   "INCREASING",       CFGTOK_INCREASING       },
1044     };
1045
1046     /* Attribute values. */
1047     unsigned SegName = INVALID_STRING_ID;
1048     unsigned Label   = INVALID_STRING_ID;
1049     unsigned Count   = INVALID_STRING_ID;
1050     /* Initialize to avoid gcc warnings: */
1051     int Type = -1;
1052     ConDesOrder Order = cdIncreasing;
1053
1054     /* Bitmask to remember the attributes we got already */
1055     enum {
1056         atNone          = 0x0000,
1057         atSegName       = 0x0001,
1058         atLabel         = 0x0002,
1059         atCount         = 0x0004,
1060         atType          = 0x0008,
1061         atOrder         = 0x0010
1062     };
1063     unsigned AttrFlags = atNone;
1064
1065     /* Parse the attributes */
1066     while (1) {
1067
1068         /* Map the identifier to a token */
1069         cfgtok_t AttrTok;
1070         CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute");
1071         AttrTok = CfgTok;
1072
1073         /* An optional assignment follows */
1074         CfgNextTok ();
1075         CfgOptionalAssign ();
1076
1077         /* Check which attribute was given */
1078         switch (AttrTok) {
1079
1080             case CFGTOK_SEGMENT:
1081                 /* Don't allow this twice */
1082                 FlagAttr (&AttrFlags, atSegName, "SEGMENT");
1083                 /* We expect an identifier */
1084                 CfgAssureIdent ();
1085                 /* Remember the value for later */
1086                 SegName = GetStrBufId (&CfgSVal);
1087                 break;
1088
1089             case CFGTOK_LABEL:
1090                 /* Don't allow this twice */
1091                 FlagAttr (&AttrFlags, atLabel, "LABEL");
1092                 /* We expect an identifier */
1093                 CfgAssureIdent ();
1094                 /* Remember the value for later */
1095                 Label = GetStrBufId (&CfgSVal);
1096                 break;
1097
1098             case CFGTOK_COUNT:
1099                 /* Don't allow this twice */
1100                 FlagAttr (&AttrFlags, atCount, "COUNT");
1101                 /* We expect an identifier */
1102                 CfgAssureIdent ();
1103                 /* Remember the value for later */
1104                 Count = GetStrBufId (&CfgSVal);
1105                 break;
1106
1107             case CFGTOK_TYPE:
1108                 /* Don't allow this twice */
1109                 FlagAttr (&AttrFlags, atType, "TYPE");
1110                 /* The type may be given as id or numerical */
1111                 if (CfgTok == CFGTOK_INTCON) {
1112                     CfgRangeCheck (CD_TYPE_MIN, CD_TYPE_MAX);
1113                     Type = (int) CfgIVal;
1114                 } else {
1115                     CfgSpecialToken (Types, ENTRY_COUNT (Types), "Type");
1116                     switch (CfgTok) {
1117                         case CFGTOK_CONSTRUCTOR: Type = CD_TYPE_CON;    break;
1118                         case CFGTOK_DESTRUCTOR:  Type = CD_TYPE_DES;    break;
1119                         case CFGTOK_INTERRUPTOR: Type = CD_TYPE_INT;    break;
1120                         default: FAIL ("Unexpected type token");
1121                     }
1122                 }
1123                 break;
1124
1125             case CFGTOK_ORDER:
1126                 /* Don't allow this twice */
1127                 FlagAttr (&AttrFlags, atOrder, "ORDER");
1128                 CfgSpecialToken (Orders, ENTRY_COUNT (Orders), "Order");
1129                 switch (CfgTok) {
1130                     case CFGTOK_DECREASING: Order = cdDecreasing;       break;
1131                     case CFGTOK_INCREASING: Order = cdIncreasing;       break;
1132                     default: FAIL ("Unexpected order token");
1133                 }
1134                 break;
1135
1136             default:
1137                 FAIL ("Unexpected attribute token");
1138
1139         }
1140
1141         /* Skip the attribute value */
1142         CfgNextTok ();
1143
1144         /* Semicolon ends the ConDes decl, otherwise accept an optional comma */
1145         if (CfgTok == CFGTOK_SEMI) {
1146             break;
1147         } else if (CfgTok == CFGTOK_COMMA) {
1148             CfgNextTok ();
1149         }
1150     }
1151
1152     /* Check if we have all mandatory attributes */
1153     AttrCheck (AttrFlags, atSegName, "SEGMENT");
1154     AttrCheck (AttrFlags, atLabel, "LABEL");
1155     AttrCheck (AttrFlags, atType, "TYPE");
1156
1157     /* Check if the condes has already attributes defined */
1158     if (ConDesHasSegName(Type) || ConDesHasLabel(Type)) {
1159         CfgError (&CfgErrorPos,
1160                   "CONDES attributes for type %d are already defined",
1161                   Type);
1162     }
1163
1164     /* Define the attributes */
1165     ConDesSetSegName (Type, SegName);
1166     ConDesSetLabel (Type, Label);
1167     if (AttrFlags & atCount) {
1168         ConDesSetCountSym (Type, Count);
1169     }
1170     if (AttrFlags & atOrder) {
1171         ConDesSetOrder (Type, Order);
1172     }
1173 }
1174
1175
1176
1177 static void ParseStartAddress (void)
1178 /* Parse the STARTADDRESS feature */
1179 {
1180     static const IdentTok Attributes [] = {
1181         {   "DEFAULT",  CFGTOK_DEFAULT },
1182     };
1183
1184
1185     /* Attribute values. */
1186     unsigned long DefStartAddr = 0;
1187
1188     /* Bitmask to remember the attributes we got already */
1189     enum {
1190         atNone          = 0x0000,
1191         atDefault       = 0x0001
1192     };
1193     unsigned AttrFlags = atNone;
1194
1195     /* Parse the attributes */
1196     while (1) {
1197
1198         /* Map the identifier to a token */
1199         cfgtok_t AttrTok;
1200         CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute");
1201         AttrTok = CfgTok;
1202
1203         /* An optional assignment follows */
1204         CfgNextTok ();
1205         CfgOptionalAssign ();
1206
1207         /* Check which attribute was given */
1208         switch (AttrTok) {
1209
1210             case CFGTOK_DEFAULT:
1211                 /* Don't allow this twice */
1212                 FlagAttr (&AttrFlags, atDefault, "DEFAULT");
1213                 /* We expect a numeric expression */
1214                 DefStartAddr = CfgCheckedConstExpr (0, 0xFFFFFF);
1215                 break;
1216
1217             default:
1218                 FAIL ("Unexpected attribute token");
1219
1220         }
1221
1222         /* Semicolon ends the ConDes decl, otherwise accept an optional comma */
1223         if (CfgTok == CFGTOK_SEMI) {
1224             break;
1225         } else if (CfgTok == CFGTOK_COMMA) {
1226             CfgNextTok ();
1227         }
1228     }
1229
1230     /* Check if we have all mandatory attributes */
1231     AttrCheck (AttrFlags, atDefault, "DEFAULT");
1232
1233     /* If no start address was given on the command line, use the one given
1234      * here
1235      */
1236     if (!HaveStartAddr) {
1237         StartAddr = DefStartAddr;
1238     }
1239 }
1240
1241
1242
1243 static void ParseFeatures (void)
1244 /* Parse a features section */
1245 {
1246     static const IdentTok Features [] = {
1247         {   "CONDES",       CFGTOK_CONDES       },
1248         {   "STARTADDRESS", CFGTOK_STARTADDRESS },
1249     };
1250
1251     while (CfgTok == CFGTOK_IDENT) {
1252
1253         /* Map the identifier to a token */
1254         cfgtok_t FeatureTok;
1255         CfgSpecialToken (Features, ENTRY_COUNT (Features), "Feature");
1256         FeatureTok = CfgTok;
1257
1258         /* Skip the name and the following colon */
1259         CfgNextTok ();
1260         CfgConsumeColon ();
1261
1262         /* Parse the format options */
1263         switch (FeatureTok) {
1264
1265             case CFGTOK_CONDES:
1266                 ParseConDes ();
1267                 break;
1268
1269             case CFGTOK_STARTADDRESS:
1270                 ParseStartAddress ();
1271                 break;
1272
1273
1274             default:
1275                 FAIL ("Unexpected feature token");
1276         }
1277
1278         /* Skip the semicolon */
1279         CfgConsumeSemi ();
1280     }
1281
1282     /* Remember we had this section */
1283     SectionsEncountered |= SE_FEATURES;
1284 }
1285
1286
1287
1288 static void ParseSymbols (void)
1289 /* Parse a symbols section */
1290 {
1291     static const IdentTok Attributes[] = {
1292         {   "ADDRSIZE", CFGTOK_ADDRSIZE },
1293         {   "TYPE",     CFGTOK_TYPE     },
1294         {   "VALUE",    CFGTOK_VALUE    },
1295     };
1296
1297     static const IdentTok AddrSizes [] = {
1298         {   "ABS",      CFGTOK_ABS      },
1299         {   "ABSOLUTE", CFGTOK_ABS      },
1300         {   "DIRECT",   CFGTOK_ZP       },
1301         {   "DWORD",    CFGTOK_LONG     },
1302         {   "FAR",      CFGTOK_FAR      },
1303         {   "LONG",     CFGTOK_LONG     },
1304         {   "NEAR",     CFGTOK_ABS      },
1305         {   "ZEROPAGE", CFGTOK_ZP       },
1306         {   "ZP",       CFGTOK_ZP       },
1307     };
1308
1309     static const IdentTok Types [] = {
1310         {   "EXPORT",   CFGTOK_EXPORT   },
1311         {   "IMPORT",   CFGTOK_IMPORT   },
1312         {   "WEAK",     CFGTOK_WEAK     },
1313     };
1314
1315     while (CfgTok == CFGTOK_IDENT) {
1316
1317         /* Bitmask to remember the attributes we got already */
1318         enum {
1319             atNone      = 0x0000,
1320             atAddrSize  = 0x0001,
1321             atType      = 0x0002,
1322             atValue     = 0x0004,
1323         };
1324         unsigned AttrFlags = atNone;
1325
1326         ExprNode* Value = 0;
1327         CfgSymType Type = CfgSymExport;
1328         unsigned char AddrSize = ADDR_SIZE_ABS;
1329         Import* Imp;
1330         Export* Exp;
1331         CfgSymbol* Sym;
1332
1333         /* Remember the name */
1334         unsigned Name = GetStrBufId (&CfgSVal);
1335         CfgNextTok ();
1336
1337         /* New syntax - skip the colon */
1338         CfgNextTok ();
1339
1340         /* Parse the attributes */
1341         while (1) {
1342
1343             /* Map the identifier to a token */
1344             cfgtok_t AttrTok;
1345             CfgSpecialToken (Attributes, ENTRY_COUNT (Attributes), "Attribute");
1346             AttrTok = CfgTok;
1347
1348             /* Skip the attribute name */
1349             CfgNextTok ();
1350
1351             /* An optional assignment follows */
1352             CfgOptionalAssign ();
1353
1354             /* Check which attribute was given */
1355             switch (AttrTok) {
1356
1357                 case CFGTOK_ADDRSIZE:
1358                     /* Don't allow this twice */
1359                     FlagAttr (&AttrFlags, atAddrSize, "ADDRSIZE");
1360                     /* Map the type to a token */
1361                     CfgSpecialToken (AddrSizes, ENTRY_COUNT (AddrSizes), "AddrSize");
1362                     switch (CfgTok) {
1363                         case CFGTOK_ABS:    AddrSize = ADDR_SIZE_ABS;   break;
1364                         case CFGTOK_FAR:    AddrSize = ADDR_SIZE_FAR;   break;
1365                         case CFGTOK_LONG:   AddrSize = ADDR_SIZE_LONG;  break;
1366                         case CFGTOK_ZP:     AddrSize = ADDR_SIZE_ZP;    break;
1367                         default:
1368                             Internal ("Unexpected token: %d", CfgTok);
1369                     }
1370                     CfgNextTok ();
1371                     break;
1372
1373                 case CFGTOK_TYPE:
1374                     /* Don't allow this twice */
1375                     FlagAttr (&AttrFlags, atType, "TYPE");
1376                     /* Map the type to a token */
1377                     CfgSpecialToken (Types, ENTRY_COUNT (Types), "Type");
1378                     switch (CfgTok) {
1379                         case CFGTOK_EXPORT:     Type = CfgSymExport;    break;
1380                         case CFGTOK_IMPORT:     Type = CfgSymImport;    break;
1381                         case CFGTOK_WEAK:       Type = CfgSymWeak;      break;
1382                         default:
1383                             Internal ("Unexpected token: %d", CfgTok);
1384                     }
1385                     CfgNextTok ();
1386                     break;
1387
1388                 case CFGTOK_VALUE:
1389                     /* Don't allow this twice */
1390                     FlagAttr (&AttrFlags, atValue, "VALUE");
1391                     /* Value is an expression */
1392                     Value = CfgExpr ();
1393                     break;
1394
1395                 default:
1396                     FAIL ("Unexpected attribute token");
1397
1398             }
1399
1400             /* Semicolon ends the decl, otherwise accept an optional comma */
1401             if (CfgTok == CFGTOK_SEMI) {
1402                 break;
1403             } else if (CfgTok == CFGTOK_COMMA) {
1404                 CfgNextTok ();
1405             }
1406         }
1407
1408         /* We must have a type */
1409         AttrCheck (AttrFlags, atType, "TYPE");
1410
1411         /* Further actions depend on the type */
1412         switch (Type) {
1413
1414             case CfgSymExport:
1415                 /* We must have a value */
1416                 AttrCheck (AttrFlags, atType, "TYPE");
1417                 /* Create the export */
1418                 Exp = CreateExprExport (Name, Value, AddrSize);
1419                 Exp->Pos = CfgErrorPos;
1420                 break;
1421
1422             case CfgSymImport:
1423                 /* An import must not have a value */
1424                 if (AttrFlags & atValue) {
1425                     CfgError (&CfgErrorPos, "Imports must not have a value");
1426                 }
1427                 /* Generate the import */
1428                 Imp = InsertImport (GenImport (Name, AddrSize));
1429                 /* Remember the file position */
1430                 Imp->Pos = CfgErrorPos;
1431                 break;
1432
1433             case CfgSymWeak:
1434                 /* We must have a value */
1435                 AttrCheck (AttrFlags, atType, "TYPE");
1436                 /* Remember the symbol for later */
1437                 Sym = NewCfgSymbol (CfgSymWeak, Name);
1438                 Sym->Value = Value;
1439                 Sym->AddrSize = AddrSize;
1440                 break;
1441
1442             default:
1443                 Internal ("Unexpected symbol type %d", Type);
1444         }
1445
1446         /* Skip the semicolon */
1447         CfgConsumeSemi ();
1448     }
1449
1450     /* Remember we had this section */
1451     SectionsEncountered |= SE_SYMBOLS;
1452 }
1453
1454
1455
1456 static void ParseConfig (void)
1457 /* Parse the config file */
1458 {
1459     static const IdentTok BlockNames [] = {
1460         {   "MEMORY",   CFGTOK_MEMORY   },
1461         {   "FILES",    CFGTOK_FILES    },
1462         {   "SEGMENTS", CFGTOK_SEGMENTS },
1463         {   "FORMATS",  CFGTOK_FORMATS  },
1464         {   "FEATURES", CFGTOK_FEATURES },
1465         {   "SYMBOLS",  CFGTOK_SYMBOLS  },
1466     };
1467     cfgtok_t BlockTok;
1468
1469     do {
1470
1471         /* Read the block ident */
1472         CfgSpecialToken (BlockNames, ENTRY_COUNT (BlockNames), "Block identifier");
1473         BlockTok = CfgTok;
1474         CfgNextTok ();
1475
1476         /* Expected a curly brace */
1477         CfgConsume (CFGTOK_LCURLY, "`{' expected");
1478
1479         /* Read the block */
1480         switch (BlockTok) {
1481
1482             case CFGTOK_MEMORY:
1483                 ParseMemory ();
1484                 break;
1485
1486             case CFGTOK_FILES:
1487                 ParseFiles ();
1488                 break;
1489
1490             case CFGTOK_SEGMENTS:
1491                 ParseSegments ();
1492                 break;
1493
1494             case CFGTOK_FORMATS:
1495                 ParseFormats ();
1496                 break;
1497
1498             case CFGTOK_FEATURES:
1499                 ParseFeatures ();
1500                 break;
1501
1502             case CFGTOK_SYMBOLS:
1503                 ParseSymbols ();
1504                 break;
1505
1506             default:
1507                 FAIL ("Unexpected block token");
1508
1509         }
1510
1511         /* Skip closing brace */
1512         CfgConsume (CFGTOK_RCURLY, "`}' expected");
1513
1514     } while (CfgTok != CFGTOK_EOF);
1515 }
1516
1517
1518
1519 void CfgRead (void)
1520 /* Read the configuration */
1521 {
1522     /* Create the descriptors for the binary formats */
1523     BinFmtDesc = NewBinDesc ();
1524     O65FmtDesc = NewO65Desc ();
1525
1526     /* If we have a config name given, open the file, otherwise we will read
1527      * from a buffer.
1528      */
1529     CfgOpenInput ();
1530
1531     /* Parse the file */
1532     ParseConfig ();
1533
1534     /* Close the input file */
1535     CfgCloseInput ();
1536 }
1537
1538
1539
1540 /*****************************************************************************/
1541 /*                          Config file processing                           */
1542 /*****************************************************************************/
1543
1544
1545
1546 static void ProcessSegments (void)
1547 /* Process the SEGMENTS section */
1548 {
1549     unsigned I;
1550
1551     /* Walk over the list of segment descriptors */
1552     I = 0;
1553     while (I < CollCount (&SegDescList)) {
1554
1555         /* Get the next segment descriptor */
1556         SegDesc* S = CollAtUnchecked (&SegDescList, I);
1557
1558         /* Search for the actual segment in the input files. The function may
1559          * return NULL (no such segment), this is checked later.
1560          */
1561         S->Seg = SegFind (S->Name);
1562
1563         /* If the segment is marked as BSS style, and if the segment exists
1564          * in any of the object file, check that there's no initialized data
1565          * in the segment.
1566          */
1567         if ((S->Flags & SF_BSS) != 0 && S->Seg != 0 && !IsBSSType (S->Seg)) {
1568             Warning ("Segment `%s' with type `bss' contains initialized data",
1569                      GetString (S->Name));
1570         }
1571
1572         /* If this segment does exist in any of the object files, insert the
1573          * segment into the load/run memory areas. Otherwise print a warning
1574          * and discard it, because the segment pointer in the descriptor is
1575          * invalid.
1576          */
1577         if (S->Seg != 0) {
1578
1579             /* Insert the segment into the memory area list */
1580             MemoryInsert (S->Run, S);
1581             if (S->Load != S->Run) {
1582                 /* We have separate RUN and LOAD areas */
1583                 MemoryInsert (S->Load, S);
1584             }
1585
1586             /* Process the next segment descriptor in the next run */
1587             ++I;
1588
1589         } else {
1590
1591             /* Print a warning if the segment is not optional */
1592             if ((S->Flags & SF_OPTIONAL) == 0) {
1593                 CfgWarning (&CfgErrorPos,
1594                             "Segment `%s' does not exist",
1595                             GetString (S->Name));
1596             }
1597
1598             /* Discard the descriptor and remove it from the collection */
1599             FreeSegDesc (S);
1600             CollDelete (&SegDescList, I);
1601         }
1602     }
1603 }
1604
1605
1606
1607 static void ProcessSymbols (void)
1608 /* Process the SYMBOLS section */
1609 {
1610     Export* E;
1611
1612     /* Walk over all symbols */
1613     unsigned I;
1614     for (I = 0; I < CollCount (&CfgSymbols); ++I) {
1615
1616         /* Get the next symbol */
1617         CfgSymbol* Sym = CollAtUnchecked (&CfgSymbols, I);
1618
1619         /* Check what it is. */
1620         switch (Sym->Type) {
1621
1622             case CfgSymO65Export:
1623                 /* Check if the export symbol is also defined as an import. */
1624                 if (O65GetImport (O65FmtDesc, Sym->Name) != 0) {
1625                     CfgError (
1626                         &Sym->Pos,
1627                         "Exported o65 symbol `%s' cannot also be an o65 import",
1628                         GetString (Sym->Name)
1629                     );
1630                 }
1631
1632                 /* Check if we have this symbol defined already. The entry
1633                  * routine will check this also, but we get a more verbose
1634                  * error message when checking it here.
1635                  */
1636                 if (O65GetExport (O65FmtDesc, Sym->Name) != 0) {
1637                     CfgError (
1638                         &Sym->Pos,
1639                         "Duplicate exported o65 symbol: `%s'",
1640                         GetString (Sym->Name)
1641                     );
1642                 }
1643
1644                 /* Insert the symbol into the table */
1645                 O65SetExport (O65FmtDesc, Sym->Name);
1646                 break;
1647
1648             case CfgSymO65Import:
1649                 /* Check if the import symbol is also defined as an export. */
1650                 if (O65GetExport (O65FmtDesc, Sym->Name) != 0) {
1651                     CfgError (
1652                         &Sym->Pos,
1653                         "Imported o65 symbol `%s' cannot also be an o65 export",
1654                         GetString (Sym->Name)
1655                     );
1656                 }
1657
1658                 /* Check if we have this symbol defined already. The entry
1659                  * routine will check this also, but we get a more verbose
1660                  * error message when checking it here.
1661                  */
1662                 if (O65GetImport (O65FmtDesc, Sym->Name) != 0) {
1663                     CfgError (
1664                         &Sym->Pos,
1665                         "Duplicate imported o65 symbol: `%s'",
1666                         GetString (Sym->Name)
1667                     );
1668                 }
1669
1670                 /* Insert the symbol into the table */
1671                 O65SetImport (O65FmtDesc, Sym->Name);
1672                 break;
1673
1674             case CfgSymWeak:
1675                 /* If the symbol is not defined until now, define it */
1676                 if ((E = FindExport (Sym->Name)) == 0 || IsUnresolvedExport (E)) {
1677                     /* The symbol is undefined, generate an export */
1678                     E = CreateExprExport (Sym->Name, Sym->Value, Sym->AddrSize);
1679                     E->Pos = Sym->Pos;
1680                 }
1681                 break;
1682
1683             default:
1684                 Internal ("Unexpected symbol type %d", Sym->Type);
1685                 break;
1686         }
1687     }
1688
1689 }
1690
1691
1692
1693 static void CreateRunDefines (SegDesc* S, unsigned long SegAddr)
1694 /* Create the defines for a RUN segment */
1695 {
1696     Export* E;
1697     StrBuf Buf = STATIC_STRBUF_INITIALIZER;
1698
1699     /* Define the run address of the segment */
1700     SB_Printf (&Buf, "__%s_RUN__", GetString (S->Name));
1701     E = CreateMemoryExport (GetStrBufId (&Buf), S->Run, SegAddr - S->Run->Start);
1702     E->Pos = S->Pos;
1703
1704     /* Define the size of the segment */
1705     SB_Printf (&Buf, "__%s_SIZE__", GetString (S->Name));
1706     E = CreateConstExport (GetStrBufId (&Buf), S->Seg->Size);
1707     E->Pos = S->Pos;
1708
1709     S->Flags |= SF_RUN_DEF;
1710     SB_Done (&Buf);
1711 }
1712
1713
1714
1715 static void CreateLoadDefines (SegDesc* S, unsigned long SegAddr)
1716 /* Create the defines for a LOAD segment */
1717 {
1718     Export* E;
1719     StrBuf Buf = STATIC_STRBUF_INITIALIZER;
1720
1721     /* Define the load address of the segment */
1722     SB_Printf (&Buf, "__%s_LOAD__", GetString (S->Name));
1723     E = CreateMemoryExport (GetStrBufId (&Buf), S->Load, SegAddr - S->Load->Start);
1724     E->Pos = S->Pos;
1725
1726     S->Flags |= SF_LOAD_DEF;
1727     SB_Done (&Buf);
1728 }
1729
1730
1731
1732 unsigned CfgProcess (void)
1733 /* Process the config file after reading in object files and libraries. This
1734  * includes postprocessing of the config file data but also assigning segments
1735  * and defining segment/memory area related symbols. The function will return
1736  * the number of memory area overflows (so zero means anything went ok).
1737  * In case of overflows, a short mapfile can be generated later, to ease the
1738  * task of rearranging segments for the user.
1739  */
1740 {
1741     unsigned Overflows = 0;
1742     unsigned I;
1743
1744     /* Postprocess symbols. We must do that first, since weak symbols are
1745      * defined here, which may be needed later.
1746      */
1747     ProcessSymbols ();
1748
1749     /* Postprocess segments */
1750     ProcessSegments ();
1751
1752     /* Walk through each of the memory sections. Add up the sizes and check
1753      * for an overflow of the section. Assign the start addresses of the
1754      * segments while doing this.
1755      */
1756     for (I = 0; I < CollCount (&MemoryAreas); ++I) {
1757
1758         unsigned J;
1759         unsigned long Addr;
1760
1761         /* Get the next memory area */
1762         MemoryArea* M = CollAtUnchecked (&MemoryAreas, I);
1763
1764         /* Remember if this is a relocatable memory area */
1765         M->Relocatable = RelocatableBinFmt (M->F->Format);
1766
1767         /* Resolve the start address expression, remember the start address
1768          * and mark the memory area as placed.
1769          */
1770         if (!IsConstExpr (M->StartExpr)) {
1771             CfgError (&M->Pos,
1772                       "Start address of memory area `%s' is not constant",
1773                       GetString (M->Name));
1774         }
1775         Addr = M->Start = GetExprVal (M->StartExpr);
1776         M->Flags |= MF_PLACED;
1777
1778         /* If requested, define the symbol for the start of the memory area.
1779          * Doing it here means that the expression for the size of the area
1780          * may reference this symbol.
1781          */
1782         if (M->Flags & MF_DEFINE) {
1783             Export* E;
1784             StrBuf Buf = STATIC_STRBUF_INITIALIZER;
1785
1786             /* Define the start of the memory area */
1787             SB_Printf (&Buf, "__%s_START__", GetString (M->Name));
1788             E = CreateMemoryExport (GetStrBufId (&Buf), M, 0);
1789             E->Pos = M->Pos;
1790
1791             SB_Done (&Buf);
1792         }
1793
1794         /* Resolve the size expression */
1795         if (!IsConstExpr (M->SizeExpr)) {
1796             CfgError (&M->Pos,
1797                       "Size of memory area `%s' is not constant",
1798                       GetString (M->Name));
1799         }
1800         M->Size = GetExprVal (M->SizeExpr);
1801
1802         /* Walk through the segments in this memory area */
1803         for (J = 0; J < CollCount (&M->SegList); ++J) {
1804
1805             /* Get the segment */
1806             SegDesc* S = CollAtUnchecked (&M->SegList, J);
1807
1808             /* Some actions depend on wether this is the load or run memory
1809              * area.
1810              */
1811             if (S->Run == M) {
1812
1813                 /* This is the run (and maybe load) memory area. Handle
1814                  * alignment and explict start address and offset.
1815                  */
1816                 if (S->Flags & SF_ALIGN) {
1817                     /* Align the address */
1818                     unsigned long Val = (0x01UL << S->Align) - 1;
1819                     Addr = (Addr + Val) & ~Val;
1820                 } else if (S->Flags & (SF_OFFSET | SF_START)) {
1821                     /* Give the segment a fixed starting address */
1822                     unsigned long NewAddr = S->Addr;
1823                     if (S->Flags & SF_OFFSET) {
1824                         /* An offset was given, no address, make an address */
1825                         NewAddr += M->Start;
1826                     }
1827                     if (Addr > NewAddr) {
1828                         /* Offset already too large */
1829                         if (S->Flags & SF_OFFSET) {
1830                             CfgError (&M->Pos,
1831                                       "Offset too small in `%s', segment `%s'",
1832                                       GetString (M->Name),
1833                                       GetString (S->Name));
1834                         } else {
1835                             CfgError (&M->Pos,
1836                                       "Start address too low in `%s', segment `%s'",
1837                                       GetString (M->Name),
1838                                       GetString (S->Name));
1839                         }
1840                     }
1841                     Addr = NewAddr;
1842                 }
1843
1844                 /* Set the start address of this segment, set the readonly flag
1845                  * in the segment and and remember if the segment is in a
1846                  * relocatable file or not.
1847                  */
1848                 S->Seg->PC = Addr;
1849                 S->Seg->ReadOnly = (S->Flags & SF_RO) != 0;
1850                 S->Seg->Relocatable = M->Relocatable;
1851
1852                 /* Remember that this segment is placed */
1853                 S->Seg->Placed = 1;
1854
1855             } else if (S->Load == M) {
1856
1857                 /* This is the load memory area, *and* run and load are
1858                  * different (because of the "else" above). Handle alignment.
1859                  */
1860                 if (S->Flags & SF_ALIGN_LOAD) {
1861                     /* Align the address */
1862                     unsigned long Val = (0x01UL << S->AlignLoad) - 1;
1863                     Addr = (Addr + Val) & ~Val;
1864                 }
1865
1866             }
1867
1868             /* Increment the fill level of the memory area and check for an
1869              * overflow.
1870              */
1871             M->FillLevel = Addr + S->Seg->Size - M->Start;
1872             if (M->FillLevel > M->Size && (M->Flags & MF_OVERFLOW) == 0) {
1873                 ++Overflows;
1874                 M->Flags |= MF_OVERFLOW;
1875                 Warning ("Memory area overflow in `%s', segment `%s' (%lu bytes)",
1876                          GetString (M->Name), GetString (S->Name),
1877                          M->FillLevel - M->Size);
1878             }
1879
1880             /* If requested, define symbols for the start and size of the
1881              * segment.
1882              */
1883             if (S->Flags & SF_DEFINE) {
1884                 if (S->Run == M && (S->Flags & SF_RUN_DEF) == 0) {
1885                     CreateRunDefines (S, Addr);
1886                 }
1887                 if (S->Load == M && (S->Flags & SF_LOAD_DEF) == 0) {
1888                     CreateLoadDefines (S, Addr);
1889                 }
1890             }
1891
1892             /* Calculate the new address */
1893             Addr += S->Seg->Size;
1894
1895         }
1896
1897         /* If requested, define symbols for start and size of the memory area */
1898         if (M->Flags & MF_DEFINE) {
1899             Export* E;
1900             StrBuf Buf = STATIC_STRBUF_INITIALIZER;
1901
1902             /* Define the size of the memory area */
1903             SB_Printf (&Buf, "__%s_SIZE__", GetString (M->Name));
1904             E = CreateConstExport (GetStrBufId (&Buf), M->Size);
1905             E->Pos = M->Pos;
1906
1907             /* Define the fill level of the memory area */
1908             SB_Printf (&Buf, "__%s_LAST__", GetString (M->Name));
1909             E = CreateMemoryExport (GetStrBufId (&Buf), M, M->FillLevel);
1910             E->Pos = M->Pos;
1911
1912             SB_Done (&Buf);
1913         }
1914
1915     }
1916
1917     /* Return the number of memory area overflows */
1918     return Overflows;
1919 }
1920
1921
1922
1923 void CfgWriteTarget (void)
1924 /* Write the target file(s) */
1925 {
1926     unsigned I;
1927
1928     /* Walk through the files list */
1929     for (I = 0; I < CollCount (&FileList); ++I) {
1930
1931         /* Get this entry */
1932         File* F = CollAtUnchecked (&FileList, I);
1933
1934         /* We don't need to look at files with no memory areas */
1935         if (CollCount (&F->MemoryAreas) > 0) {
1936
1937             /* Is there an output file? */
1938             if (SB_GetLen (GetStrBuf (F->Name)) > 0) {
1939
1940                 /* Assign a proper binary format */
1941                 if (F->Format == BINFMT_DEFAULT) {
1942                     F->Format = DefaultBinFmt;
1943                 }
1944
1945                 /* Call the apropriate routine for the binary format */
1946                 switch (F->Format) {
1947
1948                     case BINFMT_BINARY:
1949                         BinWriteTarget (BinFmtDesc, F);
1950                         break;
1951
1952                     case BINFMT_O65:
1953                         O65WriteTarget (O65FmtDesc, F);
1954                         break;
1955
1956                     default:
1957                         Internal ("Invalid binary format: %u", F->Format);
1958
1959                 }
1960
1961             } else {
1962
1963                 /* No output file. Walk through the list and mark all segments
1964                  * loading into these memory areas in this file as dumped.
1965                  */
1966                 unsigned J;
1967                 for (J = 0; J < CollCount (&F->MemoryAreas); ++J) {
1968
1969                     unsigned K;
1970
1971                     /* Get this entry */
1972                     MemoryArea* M = CollAtUnchecked (&F->MemoryAreas, J);
1973
1974                     /* Debugging */
1975                     Print (stdout, 2, "Skipping `%s'...\n", GetString (M->Name));
1976
1977                     /* Walk throught the segments */
1978                     for (K = 0; K < CollCount (&M->SegList); ++K) {
1979                         SegDesc* S = CollAtUnchecked (&M->SegList, K);
1980                         if (S->Load == M) {
1981                             /* Load area - mark the segment as dumped */
1982                             S->Seg->Dumped = 1;
1983                         }
1984                     }
1985                 }
1986             }
1987         }
1988     }
1989 }
1990
1991
1992