]> git.sur5r.net Git - cc65/blob - src/ca65/segment.c
Free expression trees when they're no longer needed
[cc65] / src / ca65 / segment.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 segment.c                                 */
4 /*                                                                           */
5 /*                   Segments for the ca65 macroassembler                    */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2003 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 <string.h>
37 #include <errno.h>
38
39 /* common */
40 #include "segnames.h"
41 #include "xmalloc.h"
42
43 /* cc65 */
44 #include "error.h"
45 #include "fragment.h"
46 #include "global.h"
47 #include "lineinfo.h"
48 #include "listing.h"
49 #include "objcode.h"
50 #include "objfile.h"
51 #include "segment.h"
52 #include "spool.h"
53 #include "symtab.h"
54
55
56
57 /*****************************************************************************/
58 /*                                   Data                                    */
59 /*****************************************************************************/
60
61
62
63 /* Are we in absolute mode or in relocatable mode? */
64 int             RelocMode = 1;
65 unsigned long   AbsPC     = 0;          /* PC if in absolute mode */
66
67
68
69 typedef struct Segment Segment;
70 struct Segment {
71     Segment*        List;               /* List of all segments */
72     Fragment*       Root;               /* Root of fragment list */
73     Fragment*       Last;               /* Pointer to last fragment */
74     unsigned long   FragCount;          /* Number of fragments */
75     unsigned        Num;                /* Segment number */
76     unsigned        Align;              /* Segment alignment */
77     unsigned long   PC;
78     SegDef*         Def;                /* Segment definition (name and type) */
79 };
80
81
82 #define SEG(segdef, num, prev)      \
83     { prev, 0, 0, 0, num, 0, 0, segdef }
84
85 /* Definitions for predefined segments */
86 SegDef NullSegDef     = STATIC_SEGDEF_INITIALIZER (SEGNAME_NULL,     SEGTYPE_ABS);
87 SegDef ZeropageSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_ZEROPAGE, SEGTYPE_ZP);
88 SegDef DataSegDef     = STATIC_SEGDEF_INITIALIZER (SEGNAME_DATA,     SEGTYPE_ABS);
89 SegDef BssSegDef      = STATIC_SEGDEF_INITIALIZER (SEGNAME_BSS,      SEGTYPE_ABS);
90 SegDef RODataSegDef   = STATIC_SEGDEF_INITIALIZER (SEGNAME_RODATA,   SEGTYPE_ABS);
91 SegDef CodeSegDef     = STATIC_SEGDEF_INITIALIZER (SEGNAME_CODE,     SEGTYPE_ABS);
92
93 /* Predefined segments */
94 static Segment NullSeg     = SEG (&NullSegDef,     5, NULL);
95 static Segment ZeropageSeg = SEG (&ZeropageSegDef, 4, &NullSeg);
96 static Segment DataSeg     = SEG (&DataSegDef,     3, &ZeropageSeg);
97 static Segment BssSeg      = SEG (&BssSegDef,      2, &DataSeg);
98 static Segment RODataSeg   = SEG (&RODataSegDef,   1, &BssSeg);
99 static Segment CodeSeg     = SEG (&CodeSegDef,     0, &RODataSeg);
100
101 /* Number of segments */
102 static unsigned SegmentCount = 6;
103
104 /* List of all segments */
105 static Segment* SegmentList = &CodeSeg;
106 static Segment* SegmentLast = &NullSeg;
107
108 /* Currently active segment */
109 static Segment* ActiveSeg = &CodeSeg;
110
111
112
113 /*****************************************************************************/
114 /*                                   Code                                    */
115 /*****************************************************************************/
116
117
118
119 static Segment* NewSegment (const char* Name, unsigned SegType)
120 /* Create a new segment, insert it into the global list and return it */
121 {
122     Segment* S;
123
124     /* Check for too many segments */
125     if (SegmentCount >= 256) {
126         Fatal (FAT_TOO_MANY_SEGMENTS);
127     }
128
129     /* Check the segment name for invalid names */
130     if (!ValidSegName (Name)) {
131         Error (ERR_ILLEGAL_SEGMENT, Name);
132     }
133
134     /* Create a new segment */
135     S = xmalloc (sizeof (*S));
136
137     /* Initialize it */
138     S->List      = 0;
139     S->Root      = 0;
140     S->Last      = 0;
141     S->FragCount = 0;
142     S->Num       = SegmentCount++;
143     S->Align     = 0;
144     S->PC        = 0;
145     S->Def       = NewSegDef (Name, SegType);
146
147     /* Insert it into the segment list */
148     SegmentLast->List = S;
149     SegmentLast = S;
150
151     /* And return it... */
152     return S;
153 }
154
155
156
157 Fragment* GenFragment (unsigned char Type, unsigned short Len)
158 /* Generate a new fragment, add it to the current segment and return it. */
159 {
160     /* Create the new fragment */
161     Fragment* F = NewFragment (Type, Len);
162
163     /* Insert the fragment into the current segment */
164     if (ActiveSeg->Root) {
165         ActiveSeg->Last->Next = F;
166         ActiveSeg->Last = F;
167     } else {
168         ActiveSeg->Root = ActiveSeg->Last = F;
169     }
170     ++ActiveSeg->FragCount;
171
172     /* Add this fragment to the current listing line */
173     if (LineCur) {
174         if (LineCur->FragList == 0) {
175             LineCur->FragList = F;
176         } else {
177             LineCur->FragLast->LineList = F;
178         }
179         LineCur->FragLast = F;
180     }
181
182     /* Increment the program counter */
183     ActiveSeg->PC += F->Len;
184     if (!RelocMode) {
185         AbsPC += F->Len;
186     }
187
188     /* Return the fragment */
189     return F;
190 }
191
192
193
194 void UseSeg (const SegDef* D)
195 /* Use the segment with the given name */
196 {
197     Segment* Seg = SegmentList;
198     while (Seg) {
199         if (strcmp (Seg->Def->Name, D->Name) == 0) {
200             /* We found this segment. Check if the type is identical */
201             if (D->Type != SEGTYPE_DEFAULT && Seg->Def->Type != D->Type) {
202                 Error (ERR_SEG_ATTR_MISMATCH);
203                 /* Use the new attribute to avoid errors */
204                 Seg->Def->Type = D->Type;
205             }
206             ActiveSeg = Seg;
207             return;
208         }
209         /* Check next segment */
210         Seg = Seg->List;
211     }
212
213     /* Segment is not in list, create a new one */
214     if (D->Type == SEGTYPE_DEFAULT) {
215         Seg = NewSegment (D->Name, SEGTYPE_ABS);
216     } else {
217         Seg = NewSegment (D->Name, D->Type);
218     }
219     ActiveSeg = Seg;
220 }
221
222
223
224 unsigned long GetPC (void)
225 /* Get the program counter of the current segment */
226 {
227     return RelocMode? ActiveSeg->PC : AbsPC;
228 }
229
230
231
232 void SetAbsPC (unsigned long PC)
233 /* Set the program counter in absolute mode */
234 {
235     RelocMode = 0;
236     AbsPC = PC;
237 }
238
239
240
241 const SegDef* GetCurrentSeg (void)
242 /* Get a pointer to the segment defininition of the current segment */
243 {
244     return ActiveSeg->Def;
245 }
246
247
248
249 unsigned GetSegNum (void)
250 /* Get the number of the current segment */
251 {
252     return ActiveSeg->Num;
253 }
254
255
256
257 void SegAlign (unsigned Power, int Val)
258 /* Align the PC segment to 2^Power. If Val is -1, emit fill fragments (the
259  * actual fill value will be determined by the linker), otherwise use the
260  * given value.
261  */
262 {
263     unsigned char Data [4];
264     unsigned long Align = (1UL << Power) - 1;
265     unsigned long NewPC = (ActiveSeg->PC + Align) & ~Align;
266     unsigned long Count = NewPC - ActiveSeg->PC;
267
268     if (Val != -1) {
269         /* User defined fill value */
270         memset (Data, Val, sizeof (Data));
271         while (Count) {
272             if (Count > sizeof (Data)) {
273                 EmitData (Data, sizeof (Data));
274                 Count -= sizeof (Data);
275             } else {
276                 EmitData (Data, Count);
277                 Count = 0;
278             }
279         }
280     } else {
281         /* Linker defined fill value */
282         EmitFill (Count);
283     }
284
285     /* Remember the alignment in the header */
286     if (ActiveSeg->Align < Power) {
287         ActiveSeg->Align = Power;
288     }
289 }
290
291
292
293 int IsZPSeg (void)
294 /* Return true if the current segment is a zeropage segment */
295 {
296     return (ActiveSeg->Def->Type == SEGTYPE_ZP);
297 }
298
299
300
301 int IsFarSeg (void)
302 /* Return true if the current segment is a far segment */
303 {
304     return (ActiveSeg->Def->Type == SEGTYPE_FAR);
305 }
306
307
308
309 unsigned GetSegType (unsigned SegNum)
310 /* Return the type of the segment with the given number */
311 {
312     /* Search for the segment */
313     Segment* S = SegmentList;
314     while (S && SegNum) {
315         --SegNum;
316         S = S->List;
317     }
318
319     /* Did we find it? */
320     if (S == 0) {
321         FAIL ("Invalid segment number");
322     }
323
324     /* Return the segment type */
325     return S->Def->Type;
326 }
327
328
329
330 void SegCheck (void)
331 /* Check the segments for range and other errors */
332 {
333     Segment* S = SegmentList;
334     while (S) {
335         Fragment* F = S->Root;
336         while (F) {
337             if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
338                 F->V.Expr = FinalizeExpr (F->V.Expr);
339                 if (IsConstExpr (F->V.Expr)) {
340                     /* We are able to evaluate the expression. Get the value
341                      * and check for range errors.
342                      */
343                     unsigned I;
344                     long Val = GetExprVal (F->V.Expr);
345                     int Abs = (F->Type != FRAG_SEXPR);
346
347                     if (F->Len == 1) {
348                         if (Abs) {
349                             /* Absolute value */
350                             if (Val > 255) {
351                                 PError (&F->Pos, ERR_RANGE);
352                             }
353                         } else {
354                             /* PC relative value */
355                             if (Val < -128 || Val > 127) {
356                                 PError (&F->Pos, ERR_RANGE);
357                             }
358                         }
359                     } else if (F->Len == 2) {
360                         if (Abs) {
361                             /* Absolute value */
362                             if (Val > 65535) {
363                                 PError (&F->Pos, ERR_RANGE);
364                             }
365                         } else {
366                             /* PC relative value */
367                             if (Val < -32768 || Val > 32767) {
368                                 PError (&F->Pos, ERR_RANGE);
369                             }
370                         }
371                     }
372
373                     /* We don't need the expression tree any longer */
374                     FreeExpr (F->V.Expr);
375
376                     /* Convert the fragment into a literal fragment */
377                     for (I = 0; I < F->Len; ++I) {
378                         F->V.Data [I] = Val & 0xFF;
379                         Val >>= 8;
380                     }
381                     F->Type = FRAG_LITERAL;
382                 } else {
383                     /* We cannot evaluate the expression now, leave the job for
384                      * the linker. However, we are able to check for explicit
385                      * byte expressions and we will do so.
386                      */
387                     if (F->Type == FRAG_EXPR && F->Len == 1 && !IsByteExpr (F->V.Expr)) {
388                         PError (&F->Pos, ERR_RANGE);
389                     }
390                 }
391             }
392             F = F->Next;
393         }
394         S = S->List;
395     }
396 }
397
398
399
400 void SegDump (void)
401 /* Dump the contents of all segments */
402 {
403     unsigned X = 0;
404     Segment* S = SegmentList;
405     printf ("\n");
406     while (S) {
407         unsigned I;
408         Fragment* F;
409         int State = -1;
410         printf ("New segment: %s", S->Def->Name);
411         F = S->Root;
412         while (F) {
413             if (F->Type == FRAG_LITERAL) {
414                 if (State != 0) {
415                     printf ("\n  Literal:");
416                     X = 15;
417                     State = 0;
418                 }
419                 for (I = 0; I < F->Len; ++I) {
420                     printf (" %02X", F->V.Data [I]);
421                     X += 3;
422                 }
423             } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
424                 State = 1;
425                 printf ("\n  Expression (%u): ", F->Len);
426                 DumpExpr (F->V.Expr);
427             } else if (F->Type == FRAG_FILL) {
428                 State = 1;
429                 printf ("\n  Fill bytes (%u)", F->Len);
430             } else {
431                 Internal ("Unknown fragment type: %u", F->Type);
432             }
433             if (X > 65) {
434                 State = -1;
435             }
436             F = F->Next;
437         }
438         printf ("\n  End PC = $%04X\n", (unsigned)(S->PC & 0xFFFF));
439         S = S->List;
440     }
441     printf ("\n");
442 }
443
444
445
446 static void WriteOneSeg (Segment* Seg)
447 /* Write one segment to the object file */
448 {
449     Fragment* Frag;
450     unsigned LineInfoIndex;
451     unsigned long DataSize;
452     unsigned long EndPos;
453
454     /* Remember the file position, then write a dummy for the size of the
455      * following data
456      */
457     unsigned long SizePos = ObjGetFilePos ();
458     ObjWrite32 (0);
459
460     /* Write the segment data */
461     ObjWriteVar (GetStringId (Seg->Def->Name)); /* Name of the segment */
462     ObjWrite32 (Seg->PC);                       /* Size */
463     ObjWrite8 (Seg->Align);                     /* Segment alignment */
464     ObjWrite8 (Seg->Def->Type);                 /* Type of the segment */
465     ObjWriteVar (Seg->FragCount);               /* Number of fragments */
466
467     /* Now walk through the fragment list for this segment and write the
468      * fragments.
469      */
470     Frag = Seg->Root;
471     while (Frag) {
472
473         /* Write data depending on the type */
474         switch (Frag->Type) {
475
476             case FRAG_LITERAL:
477                 ObjWrite8 (FRAG_LITERAL);
478                 ObjWriteVar (Frag->Len);
479                 ObjWriteData (Frag->V.Data, Frag->Len);
480                 break;
481
482             case FRAG_EXPR:
483                 switch (Frag->Len) {
484                     case 1:   ObjWrite8 (FRAG_EXPR8);   break;
485                     case 2:   ObjWrite8 (FRAG_EXPR16);  break;
486                     case 3:   ObjWrite8 (FRAG_EXPR24);  break;
487                     case 4:   ObjWrite8 (FRAG_EXPR32);  break;
488                     default:  Internal ("Invalid fragment size: %u", Frag->Len);
489                 }
490                 WriteExpr (Frag->V.Expr);
491                 break;
492
493             case FRAG_SEXPR:
494                 switch (Frag->Len) {
495                     case 1:   ObjWrite8 (FRAG_SEXPR8);  break;
496                     case 2:   ObjWrite8 (FRAG_SEXPR16); break;
497                     case 3:   ObjWrite8 (FRAG_SEXPR24); break;
498                     case 4:   ObjWrite8 (FRAG_SEXPR32); break;
499                     default:  Internal ("Invalid fragment size: %u", Frag->Len);
500                 }
501                 WriteExpr (Frag->V.Expr);
502                 break;
503
504             case FRAG_FILL:
505                 ObjWrite8 (FRAG_FILL);
506                 ObjWriteVar (Frag->Len);
507                 break;
508
509             default:
510                 Internal ("Invalid fragment type: %u", Frag->Type);
511
512         }
513
514         /* Write the file position of this fragment */
515         ObjWritePos (&Frag->Pos);
516
517         /* Write extra line info for this fragment. Zero is considered
518          * "no line info", so add one to the value.
519          */
520         LineInfoIndex = Frag->LI? Frag->LI->Index + 1 : 0;
521         ObjWriteVar (LineInfoIndex);
522
523         /* Next fragment */
524         Frag = Frag->Next;
525     }
526
527     /* Calculate the size of the data, seek back and write it */
528     EndPos = ObjGetFilePos ();          /* Remember where we are */
529     DataSize = EndPos - SizePos - 4;    /* Don't count size itself */
530     ObjSetFilePos (SizePos);            /* Seek back to the size */
531     ObjWrite32 (DataSize);              /* Write the size */
532     ObjSetFilePos (EndPos);             /* Seek back to the end */
533 }
534
535
536
537 void WriteSegments (void)
538 /* Write the segment data to the object file */
539 {
540     Segment* Seg;
541
542     /* Tell the object file module that we're about to start the seg list */
543     ObjStartSegments ();
544
545     /* First thing is segment count */
546     ObjWriteVar (SegmentCount);
547
548     /* Now walk through all segments and write them to the object file */
549     Seg = SegmentList;
550     while (Seg) {
551         /* Write one segment */
552         WriteOneSeg (Seg);
553         /* Next segment */
554         Seg = Seg->List;
555     }
556
557     /* Done writing segments */
558     ObjEndSegments ();
559 }
560
561
562