]> git.sur5r.net Git - cc65/blob - src/ca65/segment.c
Renamed some stuff. Write out the segment size as var, not 32 bit.
[cc65] / src / ca65 / segment.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 segment.c                                 */
4 /*                                                                           */
5 /*                   Segments for the ca65 macroassembler                    */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2011, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
12 /* EMail:         uz@cc65.org                                                */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <string.h>
37 #include <errno.h>
38
39 /* common */
40 #include "addrsize.h"
41 #include "coll.h"
42 #include "mmodel.h"
43 #include "segnames.h"
44 #include "xmalloc.h"
45
46 /* cc65 */
47 #include "error.h"
48 #include "fragment.h"
49 #include "global.h"
50 #include "lineinfo.h"
51 #include "listing.h"
52 #include "objcode.h"
53 #include "objfile.h"
54 #include "segment.h"
55 #include "span.h"
56 #include "spool.h"
57 #include "studyexpr.h"
58 #include "symtab.h"
59
60
61
62 /*****************************************************************************/
63 /*                                   Data                                    */
64 /*****************************************************************************/
65
66
67
68 /* If OrgPerSeg is false, all segments share the RelocMode flag and a PC
69  * used when in absolute mode. OrgPerSeg may be set by .feature org_per_seg
70  */
71 static int              RelocMode = 1;
72 static unsigned long    AbsPC     = 0;          /* PC if in absolute mode */
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 /* Collection containing all segments */
83 Collection SegmentList = STATIC_COLLECTION_INITIALIZER;
84
85 /* Currently active segment */
86 Segment* ActiveSeg;
87
88
89
90 /*****************************************************************************/
91 /*                                   Code                                    */
92 /*****************************************************************************/
93
94
95
96 static Segment* NewSegFromDef (SegDef* Def)
97 /* Create a new segment from a segment definition. Used only internally, no
98  * checks.
99  */
100 {
101     /* Create a new segment */
102     Segment* S = xmalloc (sizeof (*S));
103
104     /* Initialize it */
105     S->Root      = 0;
106     S->Last      = 0;
107     S->FragCount = 0;
108     S->Num       = CollCount (&SegmentList);
109     S->Align     = 0;
110     S->RelocMode = 1;
111     S->PC        = 0;
112     S->AbsPC     = 0;
113     S->Def       = Def;
114
115     /* Insert it into the segment list */
116     CollAppend (&SegmentList, S);
117
118     /* And return it... */
119     return S;
120 }
121
122
123
124 static Segment* NewSegment (const char* Name, unsigned char AddrSize)
125 /* Create a new segment, insert it into the global list and return it */
126 {
127     /* Check for too many segments */
128     if (CollCount (&SegmentList) >= 256) {
129         Fatal ("Too many segments");
130     }
131
132     /* Check the segment name for invalid names */
133     if (!ValidSegName (Name)) {
134         Error ("Illegal segment name: `%s'", Name);
135     }
136
137     /* Create a new segment and return it */
138     return NewSegFromDef (NewSegDef (Name, AddrSize));
139 }
140
141
142
143 Fragment* GenFragment (unsigned char Type, unsigned short Len)
144 /* Generate a new fragment, add it to the current segment and return it. */
145 {
146     /* Create the new fragment */
147     Fragment* F = NewFragment (Type, Len);
148
149     /* Insert the fragment into the current segment */
150     if (ActiveSeg->Root) {
151         ActiveSeg->Last->Next = F;
152         ActiveSeg->Last = F;
153     } else {
154         ActiveSeg->Root = ActiveSeg->Last = F;
155     }
156     ++ActiveSeg->FragCount;
157
158     /* Add this fragment to the current listing line */
159     if (LineCur) {
160         if (LineCur->FragList == 0) {
161             LineCur->FragList = F;
162         } else {
163             LineCur->FragLast->LineList = F;
164         }
165         LineCur->FragLast = F;
166     }
167
168     /* Increment the program counter */
169     ActiveSeg->PC += F->Len;
170     if (OrgPerSeg) {
171         /* Relocatable mode is switched per segment */
172         if (!ActiveSeg->RelocMode) {
173             ActiveSeg->AbsPC += F->Len;
174         }
175     } else {
176         /* Relocatable mode is switched globally */
177         if (!RelocMode) {
178             AbsPC += F->Len;
179         }
180     }
181
182     /* Return the fragment */
183     return F;
184 }
185
186
187
188 void UseSeg (const SegDef* D)
189 /* Use the segment with the given name */
190 {
191     unsigned I;
192     for (I = 0; I < CollCount (&SegmentList); ++I) {
193         Segment* Seg = CollAtUnchecked (&SegmentList, I);
194         if (strcmp (Seg->Def->Name, D->Name) == 0) {
195             /* We found this segment. Check if the type is identical */
196             if (D->AddrSize != ADDR_SIZE_DEFAULT &&
197                 Seg->Def->AddrSize != D->AddrSize) {
198                 Error ("Segment attribute mismatch");
199                 /* Use the new attribute to avoid errors */
200                 Seg->Def->AddrSize = D->AddrSize;
201             }
202             ActiveSeg = Seg;
203             return;
204         }
205     }
206
207     /* Segment is not in list, create a new one */
208     if (D->AddrSize == ADDR_SIZE_DEFAULT) {
209         ActiveSeg = NewSegment (D->Name, ADDR_SIZE_ABS);
210     } else {
211         ActiveSeg = NewSegment (D->Name, D->AddrSize);
212     }
213 }
214
215
216
217 unsigned long GetPC (void)
218 /* Get the program counter of the current segment */
219 {
220     if (OrgPerSeg) {
221         /* Relocatable mode is switched per segment */
222         return ActiveSeg->RelocMode? ActiveSeg->PC : ActiveSeg->AbsPC;
223     } else {
224         /* Relocatable mode is switched globally */
225         return RelocMode? ActiveSeg->PC : AbsPC;
226     }
227 }
228
229
230
231 void EnterAbsoluteMode (unsigned long PC)
232 /* Enter absolute (non relocatable mode). Depending on the OrgPerSeg flag,
233  * this will either switch the mode globally or for the current segment.
234  */
235 {
236     if (OrgPerSeg) {
237         /* Relocatable mode is switched per segment */
238         ActiveSeg->RelocMode = 0;
239         ActiveSeg->AbsPC = PC;
240     } else {
241         /* Relocatable mode is switched globally */
242         RelocMode = 0;
243         AbsPC = PC;
244     }
245 }
246
247
248
249 int GetRelocMode (void)
250 /* Return true if we're currently in relocatable mode */
251 {
252     if (OrgPerSeg) {
253         /* Relocatable mode is switched per segment */
254         return ActiveSeg->RelocMode;
255     } else {
256         /* Relocatable mode is switched globally */
257         return RelocMode;
258     }
259 }
260
261
262
263 void EnterRelocMode (void)
264 /* Enter relocatable mode. Depending on the OrgPerSeg flag, this will either
265  * switch the mode globally or for the current segment.
266  */
267 {
268     if (OrgPerSeg) {
269         /* Relocatable mode is switched per segment */
270         ActiveSeg->RelocMode = 1;
271     } else {
272         /* Relocatable mode is switched globally */
273         RelocMode = 1;
274     }
275 }
276
277
278
279 void SegAlign (unsigned Power, int Val)
280 /* Align the PC segment to 2^Power. If Val is -1, emit fill fragments (the
281  * actual fill value will be determined by the linker), otherwise use the
282  * given value.
283  */
284 {
285     unsigned char Data [4];
286     unsigned long Align = (1UL << Power) - 1;
287     unsigned long NewPC = (ActiveSeg->PC + Align) & ~Align;
288     unsigned long Count = NewPC - ActiveSeg->PC;
289
290     if (Val != -1) {
291         /* User defined fill value */
292         memset (Data, Val, sizeof (Data));
293         while (Count) {
294             if (Count > sizeof (Data)) {
295                 EmitData (Data, sizeof (Data));
296                 Count -= sizeof (Data);
297             } else {
298                 EmitData (Data, Count);
299                 Count = 0;
300             }
301         }
302     } else {
303         /* Linker defined fill value */
304         EmitFill (Count);
305     }
306
307     /* Remember the alignment in the header */
308     if (ActiveSeg->Align < Power) {
309         ActiveSeg->Align = Power;
310     }
311 }
312
313
314
315 unsigned char GetSegAddrSize (unsigned SegNum)
316 /* Return the address size of the segment with the given number */
317 {
318     /* Is there such a segment? */
319     if (SegNum >= CollCount (&SegmentList)) {
320         FAIL ("Invalid segment number");
321     }
322
323     /* Return the address size */
324     return ((Segment*) CollAtUnchecked (&SegmentList, SegNum))->Def->AddrSize;
325 }
326
327
328
329 void SegDone (void)
330 /* Check the segments for range and other errors. Do cleanup. */
331 {
332     static const unsigned long U_Hi[4] = {
333         0x000000FFUL, 0x0000FFFFUL, 0x00FFFFFFUL, 0xFFFFFFFFUL
334     };
335     static const long S_Hi[4] = {
336         0x0000007FL, 0x00007FFFL, 0x007FFFFFL, 0x7FFFFFFFL
337     };
338
339     unsigned I;
340     for (I = 0; I < CollCount (&SegmentList); ++I) {
341         Segment* S = CollAtUnchecked (&SegmentList, I);
342         Fragment* F = S->Root;
343         while (F) {
344             if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
345
346                 /* We have an expression, study it */
347                 ExprDesc ED;
348                 ED_Init (&ED);
349                 StudyExpr (F->V.Expr, &ED);
350
351                 /* Try to simplify it before looking further */
352                 F->V.Expr = SimplifyExpr (F->V.Expr, &ED);
353
354                 /* Check if the expression is constant */
355                 if (ED_IsConst (&ED)) {
356
357                     unsigned J;
358
359                     /* The expression is constant. Check for range errors. */
360                     CHECK (F->Len <= 4);
361                     if (F->Type == FRAG_SEXPR) {
362                         long Hi = S_Hi[F->Len-1];
363                         long Lo = ~Hi;
364                         if (ED.Val > Hi || ED.Val < Lo) {
365                             LIError (&F->LI,
366                                      "Range error (%ld not in [%ld..%ld])",
367                                      ED.Val, Lo, Hi);
368                         }
369                     } else {
370                         if (((unsigned long)ED.Val) > U_Hi[F->Len-1]) {
371                             LIError (&F->LI,
372                                      "Range error (%lu not in [0..%lu])",
373                                      (unsigned long)ED.Val, U_Hi[F->Len-1]);
374                         }
375                     }
376
377                     /* We don't need the expression tree any longer */
378                     FreeExpr (F->V.Expr);
379
380                     /* Convert the fragment into a literal fragment */
381                     for (J = 0; J < F->Len; ++J) {
382                         F->V.Data[J] = ED.Val & 0xFF;
383                         ED.Val >>= 8;
384                     }
385                     F->Type = FRAG_LITERAL;
386
387                 } else if (ED.AddrSize != ADDR_SIZE_DEFAULT) {
388
389                     /* We cannot evaluate the expression now, leave the job for
390                      * the linker. However, we can check if the address size
391                      * matches the fragment size, and we will do so.
392                      */
393                     if ((F->Len == 1 && ED.AddrSize > ADDR_SIZE_ZP)  ||
394                         (F->Len == 2 && ED.AddrSize > ADDR_SIZE_ABS) ||
395                         (F->Len == 3 && ED.AddrSize > ADDR_SIZE_FAR)) {
396                         LIError (&F->LI, "Range error");
397                     }
398                 }
399
400                 /* Release memory allocated for the expression decriptor */
401                 ED_Done (&ED);
402             }
403             F = F->Next;
404         }
405     }
406 }
407
408
409
410 void SegDump (void)
411 /* Dump the contents of all segments */
412 {
413     unsigned I;
414     unsigned X = 0;
415
416     printf ("\n");
417     for (I = 0; I < CollCount (&SegmentList); ++I) {
418         Segment* S = CollAtUnchecked (&SegmentList, I);
419         unsigned I;
420         Fragment* F;
421         int State = -1;
422         printf ("New segment: %s", S->Def->Name);
423         F = S->Root;
424         while (F) {
425             if (F->Type == FRAG_LITERAL) {
426                 if (State != 0) {
427                     printf ("\n  Literal:");
428                     X = 15;
429                     State = 0;
430                 }
431                 for (I = 0; I < F->Len; ++I) {
432                     printf (" %02X", F->V.Data [I]);
433                     X += 3;
434                 }
435             } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
436                 State = 1;
437                 printf ("\n  Expression (%u): ", F->Len);
438                 DumpExpr (F->V.Expr, SymResolve);
439             } else if (F->Type == FRAG_FILL) {
440                 State = 1;
441                 printf ("\n  Fill bytes (%u)", F->Len);
442             } else {
443                 Internal ("Unknown fragment type: %u", F->Type);
444             }
445             if (X > 65) {
446                 State = -1;
447             }
448             F = F->Next;
449         }
450         printf ("\n  End PC = $%04X\n", (unsigned)(S->PC & 0xFFFF));
451     }
452     printf ("\n");
453 }
454
455
456
457 void SegInit (void)
458 /* Initialize segments */
459 {
460     /* Create the predefined segments. Code segment is active */
461     ActiveSeg = NewSegFromDef (&CodeSegDef);
462     NewSegFromDef (&RODataSegDef);
463     NewSegFromDef (&BssSegDef);
464     NewSegFromDef (&DataSegDef);
465     NewSegFromDef (&ZeropageSegDef);
466     NewSegFromDef (&NullSegDef);
467 }
468
469
470
471 void SetSegmentSizes (void)
472 /* Set the default segment sizes according to the memory model */
473 {
474     /* Initialize segment sizes. The segment definitions do already contain
475      * the correct values for the default case (near), so we must only change
476      * things that should be different.
477      */
478     switch (MemoryModel) {
479
480         case MMODEL_NEAR:
481             break;
482
483         case MMODEL_FAR:
484             CodeSegDef.AddrSize = ADDR_SIZE_FAR;
485             break;
486
487         case MMODEL_HUGE:
488             CodeSegDef.AddrSize   = ADDR_SIZE_FAR;
489             DataSegDef.AddrSize   = ADDR_SIZE_FAR;
490             BssSegDef.AddrSize    = ADDR_SIZE_FAR;
491             RODataSegDef.AddrSize = ADDR_SIZE_FAR;
492             break;
493
494         default:
495             Internal ("Invalid memory model: %d", MemoryModel);
496     }
497 }
498
499
500
501 static void WriteOneSeg (Segment* Seg)
502 /* Write one segment to the object file */
503 {
504     Fragment* Frag;
505     unsigned long DataSize;
506     unsigned long EndPos;
507
508     /* Remember the file position, then write a dummy for the size of the
509      * following data
510      */
511     unsigned long SizePos = ObjGetFilePos ();
512     ObjWrite32 (0);
513
514     /* Write the segment data */
515     ObjWriteVar (GetStringId (Seg->Def->Name)); /* Name of the segment */
516     ObjWriteVar (Seg->PC);                       /* Size */
517     ObjWrite8 (Seg->Align);                     /* Segment alignment */
518     ObjWrite8 (Seg->Def->AddrSize);             /* Address size of the segment */
519     ObjWriteVar (Seg->FragCount);               /* Number of fragments */
520
521     /* Now walk through the fragment list for this segment and write the
522      * fragments.
523      */
524     Frag = Seg->Root;
525     while (Frag) {
526
527         /* Write data depending on the type */
528         switch (Frag->Type) {
529
530             case FRAG_LITERAL:
531                 ObjWrite8 (FRAG_LITERAL);
532                 ObjWriteVar (Frag->Len);
533                 ObjWriteData (Frag->V.Data, Frag->Len);
534                 break;
535
536             case FRAG_EXPR:
537                 switch (Frag->Len) {
538                     case 1:   ObjWrite8 (FRAG_EXPR8);   break;
539                     case 2:   ObjWrite8 (FRAG_EXPR16);  break;
540                     case 3:   ObjWrite8 (FRAG_EXPR24);  break;
541                     case 4:   ObjWrite8 (FRAG_EXPR32);  break;
542                     default:  Internal ("Invalid fragment size: %u", Frag->Len);
543                 }
544                 WriteExpr (Frag->V.Expr);
545                 break;
546
547             case FRAG_SEXPR:
548                 switch (Frag->Len) {
549                     case 1:   ObjWrite8 (FRAG_SEXPR8);  break;
550                     case 2:   ObjWrite8 (FRAG_SEXPR16); break;
551                     case 3:   ObjWrite8 (FRAG_SEXPR24); break;
552                     case 4:   ObjWrite8 (FRAG_SEXPR32); break;
553                     default:  Internal ("Invalid fragment size: %u", Frag->Len);
554                 }
555                 WriteExpr (Frag->V.Expr);
556                 break;
557
558             case FRAG_FILL:
559                 ObjWrite8 (FRAG_FILL);
560                 ObjWriteVar (Frag->Len);
561                 break;
562
563             default:
564                 Internal ("Invalid fragment type: %u", Frag->Type);
565
566         }
567
568         /* Write the line infos for this fragment */
569         WriteLineInfo (&Frag->LI);
570
571         /* Next fragment */
572         Frag = Frag->Next;
573     }
574
575     /* Calculate the size of the data, seek back and write it */
576     EndPos = ObjGetFilePos ();          /* Remember where we are */
577     DataSize = EndPos - SizePos - 4;    /* Don't count size itself */
578     ObjSetFilePos (SizePos);            /* Seek back to the size */
579     ObjWrite32 (DataSize);              /* Write the size */
580     ObjSetFilePos (EndPos);             /* Seek back to the end */
581 }
582
583
584
585 void WriteSegments (void)
586 /* Write the segment data to the object file */
587 {
588     unsigned I;
589
590     /* Tell the object file module that we're about to start the seg list */
591     ObjStartSegments ();
592
593     /* First thing is segment count */
594     ObjWriteVar (CollCount (&SegmentList));
595
596     /* Now walk through all segments and write them to the object file */
597     for (I = 0; I < CollCount (&SegmentList); ++I) {
598         /* Write one segment */
599         WriteOneSeg (CollAtUnchecked (&SegmentList, I));
600     }
601
602     /* Done writing segments */
603     ObjEndSegments ();
604 }
605
606
607
608