]> git.sur5r.net Git - cc65/blob - src/ca65/segment.c
3e50d96ac0c6f4376bd7fc5a1dccdda2b4a14264
[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                     /* Convert the fragment into a literal fragment */
374                     for (I = 0; I < F->Len; ++I) {
375                         F->V.Data [I] = Val & 0xFF;
376                         Val >>= 8;
377                     }
378                     F->Type = FRAG_LITERAL;
379                 } else {
380                     /* We cannot evaluate the expression now, leave the job for
381                      * the linker. However, we are able to check for explicit
382                      * byte expressions and we will do so.
383                      */
384                     if (F->Type == FRAG_EXPR && F->Len == 1 && !IsByteExpr (F->V.Expr)) {
385                         PError (&F->Pos, ERR_RANGE);
386                     }
387                 }
388             }
389             F = F->Next;
390         }
391         S = S->List;
392     }
393 }
394
395
396
397 void SegDump (void)
398 /* Dump the contents of all segments */
399 {
400     unsigned X = 0;
401     Segment* S = SegmentList;
402     printf ("\n");
403     while (S) {
404         unsigned I;
405         Fragment* F;
406         int State = -1;
407         printf ("New segment: %s", S->Def->Name);
408         F = S->Root;
409         while (F) {
410             if (F->Type == FRAG_LITERAL) {
411                 if (State != 0) {
412                     printf ("\n  Literal:");
413                     X = 15;
414                     State = 0;
415                 }
416                 for (I = 0; I < F->Len; ++I) {
417                     printf (" %02X", F->V.Data [I]);
418                     X += 3;
419                 }
420             } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
421                 State = 1;
422                 printf ("\n  Expression (%u): ", F->Len);
423                 DumpExpr (F->V.Expr);
424             } else if (F->Type == FRAG_FILL) {
425                 State = 1;
426                 printf ("\n  Fill bytes (%u)", F->Len);
427             } else {
428                 Internal ("Unknown fragment type: %u", F->Type);
429             }
430             if (X > 65) {
431                 State = -1;
432             }
433             F = F->Next;
434         }
435         printf ("\n  End PC = $%04X\n", (unsigned)(S->PC & 0xFFFF));
436         S = S->List;
437     }
438     printf ("\n");
439 }
440
441
442
443 static void WriteOneSeg (Segment* Seg)
444 /* Write one segment to the object file */
445 {
446     Fragment* Frag;
447     unsigned LineInfoIndex;
448     unsigned long DataSize;
449     unsigned long EndPos;
450
451     /* Remember the file position, then write a dummy for the size of the
452      * following data
453      */
454     unsigned long SizePos = ObjGetFilePos ();
455     ObjWrite32 (0);
456
457     /* Write the segment data */
458     ObjWriteVar (GetStringId (Seg->Def->Name)); /* Name of the segment */
459     ObjWrite32 (Seg->PC);                       /* Size */
460     ObjWrite8 (Seg->Align);                     /* Segment alignment */
461     ObjWrite8 (Seg->Def->Type);                 /* Type of the segment */
462     ObjWriteVar (Seg->FragCount);               /* Number of fragments */
463
464     /* Now walk through the fragment list for this segment and write the
465      * fragments.
466      */
467     Frag = Seg->Root;
468     while (Frag) {
469
470         /* Write data depending on the type */
471         switch (Frag->Type) {
472
473             case FRAG_LITERAL:
474                 ObjWrite8 (FRAG_LITERAL);
475                 ObjWriteVar (Frag->Len);
476                 ObjWriteData (Frag->V.Data, Frag->Len);
477                 break;
478
479             case FRAG_EXPR:
480                 switch (Frag->Len) {
481                     case 1:   ObjWrite8 (FRAG_EXPR8);   break;
482                     case 2:   ObjWrite8 (FRAG_EXPR16);  break;
483                     case 3:   ObjWrite8 (FRAG_EXPR24);  break;
484                     case 4:   ObjWrite8 (FRAG_EXPR32);  break;
485                     default:  Internal ("Invalid fragment size: %u", Frag->Len);
486                 }
487                 WriteExpr (Frag->V.Expr);
488                 break;
489
490             case FRAG_SEXPR:
491                 switch (Frag->Len) {
492                     case 1:   ObjWrite8 (FRAG_SEXPR8);  break;
493                     case 2:   ObjWrite8 (FRAG_SEXPR16); break;
494                     case 3:   ObjWrite8 (FRAG_SEXPR24); break;
495                     case 4:   ObjWrite8 (FRAG_SEXPR32); break;
496                     default:  Internal ("Invalid fragment size: %u", Frag->Len);
497                 }
498                 WriteExpr (Frag->V.Expr);
499                 break;
500
501             case FRAG_FILL:
502                 ObjWrite8 (FRAG_FILL);
503                 ObjWriteVar (Frag->Len);
504                 break;
505
506             default:
507                 Internal ("Invalid fragment type: %u", Frag->Type);
508
509         }
510
511         /* Write the file position of this fragment */
512         ObjWritePos (&Frag->Pos);
513
514         /* Write extra line info for this fragment. Zero is considered
515          * "no line info", so add one to the value.
516          */
517         LineInfoIndex = Frag->LI? Frag->LI->Index + 1 : 0;
518         ObjWriteVar (LineInfoIndex);
519
520         /* Next fragment */
521         Frag = Frag->Next;
522     }
523
524     /* Calculate the size of the data, seek back and write it */
525     EndPos = ObjGetFilePos ();          /* Remember where we are */
526     DataSize = EndPos - SizePos - 4;    /* Don't count size itself */
527     ObjSetFilePos (SizePos);            /* Seek back to the size */
528     ObjWrite32 (DataSize);              /* Write the size */
529     ObjSetFilePos (EndPos);             /* Seek back to the end */
530 }
531
532
533
534 void WriteSegments (void)
535 /* Write the segment data to the object file */
536 {
537     Segment* Seg;
538
539     /* Tell the object file module that we're about to start the seg list */
540     ObjStartSegments ();
541
542     /* First thing is segment count */
543     ObjWriteVar (SegmentCount);
544
545     /* Now walk through all segments and write them to the object file */
546     Seg = SegmentList;
547     while (Seg) {
548         /* Write one segment */
549         WriteOneSeg (Seg);
550         /* Next segment */
551         Seg = Seg->List;
552     }
553
554     /* Done writing segments */
555     ObjEndSegments ();
556 }
557
558
559