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