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