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