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