]> git.sur5r.net Git - cc65/blob - src/ca65/segment.c
Make the error message for large alignments more descriptive. Don't use the
[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                 /* Try to simplify it before looking further */
376                 F->V.Expr = SimplifyExpr (F->V.Expr, &ED);
377
378                 /* Check if the expression is constant */
379                 if (ED_IsConst (&ED)) {
380
381                     unsigned J;
382
383                     /* The expression is constant. Check for range errors. */
384                     CHECK (F->Len <= 4);
385                     if (F->Type == FRAG_SEXPR) {
386                         long Hi = S_Hi[F->Len-1];
387                         long Lo = ~Hi;
388                         if (ED.Val > Hi || ED.Val < Lo) {
389                             LIError (&F->LI,
390                                      "Range error (%ld not in [%ld..%ld])",
391                                      ED.Val, Lo, Hi);
392                         }
393                     } else {
394                         if (((unsigned long)ED.Val) > U_Hi[F->Len-1]) {
395                             LIError (&F->LI,
396                                      "Range error (%lu not in [0..%lu])",
397                                      (unsigned long)ED.Val, U_Hi[F->Len-1]);
398                         }
399                     }
400
401                     /* We don't need the expression tree any longer */
402                     FreeExpr (F->V.Expr);
403
404                     /* Convert the fragment into a literal fragment */
405                     for (J = 0; J < F->Len; ++J) {
406                         F->V.Data[J] = ED.Val & 0xFF;
407                         ED.Val >>= 8;
408                     }
409                     F->Type = FRAG_LITERAL;
410
411                 } else if (ED.AddrSize != ADDR_SIZE_DEFAULT) {
412
413                     /* We cannot evaluate the expression now, leave the job for
414                      * the linker. However, we can check if the address size
415                      * matches the fragment size, and we will do so.
416                      */
417                     if ((F->Len == 1 && ED.AddrSize > ADDR_SIZE_ZP)  ||
418                         (F->Len == 2 && ED.AddrSize > ADDR_SIZE_ABS) ||
419                         (F->Len == 3 && ED.AddrSize > ADDR_SIZE_FAR)) {
420                         LIError (&F->LI, "Range error");
421                     }
422                 }
423
424                 /* Release memory allocated for the expression decriptor */
425                 ED_Done (&ED);
426             }
427             F = F->Next;
428         }
429     }
430 }
431
432
433
434 void SegDump (void)
435 /* Dump the contents of all segments */
436 {
437     unsigned I;
438     unsigned X = 0;
439
440     printf ("\n");
441     for (I = 0; I < CollCount (&SegmentList); ++I) {
442         Segment* S = CollAtUnchecked (&SegmentList, I);
443         unsigned I;
444         Fragment* F;
445         int State = -1;
446         printf ("New segment: %s", S->Def->Name);
447         F = S->Root;
448         while (F) {
449             if (F->Type == FRAG_LITERAL) {
450                 if (State != 0) {
451                     printf ("\n  Literal:");
452                     X = 15;
453                     State = 0;
454                 }
455                 for (I = 0; I < F->Len; ++I) {
456                     printf (" %02X", F->V.Data [I]);
457                     X += 3;
458                 }
459             } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
460                 State = 1;
461                 printf ("\n  Expression (%u): ", F->Len);
462                 DumpExpr (F->V.Expr, SymResolve);
463             } else if (F->Type == FRAG_FILL) {
464                 State = 1;
465                 printf ("\n  Fill bytes (%u)", F->Len);
466             } else {
467                 Internal ("Unknown fragment type: %u", F->Type);
468             }
469             if (X > 65) {
470                 State = -1;
471             }
472             F = F->Next;
473         }
474         printf ("\n  End PC = $%04X\n", (unsigned)(S->PC & 0xFFFF));
475     }
476     printf ("\n");
477 }
478
479
480
481 void SegInit (void)
482 /* Initialize segments */
483 {
484     /* Create the predefined segments. Code segment is active */
485     ActiveSeg = NewSegFromDef (&CodeSegDef);
486     NewSegFromDef (&RODataSegDef);
487     NewSegFromDef (&BssSegDef);
488     NewSegFromDef (&DataSegDef);
489     NewSegFromDef (&ZeropageSegDef);
490     NewSegFromDef (&NullSegDef);
491 }
492
493
494
495 void SetSegmentSizes (void)
496 /* Set the default segment sizes according to the memory model */
497 {
498     /* Initialize segment sizes. The segment definitions do already contain
499      * the correct values for the default case (near), so we must only change
500      * things that should be different.
501      */
502     switch (MemoryModel) {
503
504         case MMODEL_NEAR:
505             break;
506
507         case MMODEL_FAR:
508             CodeSegDef.AddrSize = ADDR_SIZE_FAR;
509             break;
510
511         case MMODEL_HUGE:
512             CodeSegDef.AddrSize   = ADDR_SIZE_FAR;
513             DataSegDef.AddrSize   = ADDR_SIZE_FAR;
514             BssSegDef.AddrSize    = ADDR_SIZE_FAR;
515             RODataSegDef.AddrSize = ADDR_SIZE_FAR;
516             break;
517
518         default:
519             Internal ("Invalid memory model: %d", MemoryModel);
520     }
521 }
522
523
524
525 static void WriteOneSeg (Segment* Seg)
526 /* Write one segment to the object file */
527 {
528     Fragment* Frag;
529     unsigned long DataSize;
530     unsigned long EndPos;
531
532     /* Remember the file position, then write a dummy for the size of the
533      * following data
534      */
535     unsigned long SizePos = ObjGetFilePos ();
536     ObjWrite32 (0);
537
538     /* Write the segment data */
539     ObjWriteVar (GetStringId (Seg->Def->Name)); /* Name of the segment */
540     ObjWriteVar (Seg->PC);                      /* Size */
541     ObjWriteVar (Seg->Align);                   /* Segment alignment */
542     ObjWrite8 (Seg->Def->AddrSize);             /* Address size of the segment */
543     ObjWriteVar (Seg->FragCount);               /* Number of fragments */
544
545     /* Now walk through the fragment list for this segment and write the
546      * fragments.
547      */
548     Frag = Seg->Root;
549     while (Frag) {
550
551         /* Write data depending on the type */
552         switch (Frag->Type) {
553
554             case FRAG_LITERAL:
555                 ObjWrite8 (FRAG_LITERAL);
556                 ObjWriteVar (Frag->Len);
557                 ObjWriteData (Frag->V.Data, Frag->Len);
558                 break;
559
560             case FRAG_EXPR:
561                 switch (Frag->Len) {
562                     case 1:   ObjWrite8 (FRAG_EXPR8);   break;
563                     case 2:   ObjWrite8 (FRAG_EXPR16);  break;
564                     case 3:   ObjWrite8 (FRAG_EXPR24);  break;
565                     case 4:   ObjWrite8 (FRAG_EXPR32);  break;
566                     default:  Internal ("Invalid fragment size: %u", Frag->Len);
567                 }
568                 WriteExpr (Frag->V.Expr);
569                 break;
570
571             case FRAG_SEXPR:
572                 switch (Frag->Len) {
573                     case 1:   ObjWrite8 (FRAG_SEXPR8);  break;
574                     case 2:   ObjWrite8 (FRAG_SEXPR16); break;
575                     case 3:   ObjWrite8 (FRAG_SEXPR24); break;
576                     case 4:   ObjWrite8 (FRAG_SEXPR32); break;
577                     default:  Internal ("Invalid fragment size: %u", Frag->Len);
578                 }
579                 WriteExpr (Frag->V.Expr);
580                 break;
581
582             case FRAG_FILL:
583                 ObjWrite8 (FRAG_FILL);
584                 ObjWriteVar (Frag->Len);
585                 break;
586
587             default:
588                 Internal ("Invalid fragment type: %u", Frag->Type);
589
590         }
591
592         /* Write the line infos for this fragment */
593         WriteLineInfo (&Frag->LI);
594
595         /* Next fragment */
596         Frag = Frag->Next;
597     }
598
599     /* Calculate the size of the data, seek back and write it */
600     EndPos = ObjGetFilePos ();          /* Remember where we are */
601     DataSize = EndPos - SizePos - 4;    /* Don't count size itself */
602     ObjSetFilePos (SizePos);            /* Seek back to the size */
603     ObjWrite32 (DataSize);              /* Write the size */
604     ObjSetFilePos (EndPos);             /* Seek back to the end */
605 }
606
607
608
609 void WriteSegments (void)
610 /* Write the segment data to the object file */
611 {
612     unsigned I;
613
614     /* Tell the object file module that we're about to start the seg list */
615     ObjStartSegments ();
616
617     /* First thing is segment count */
618     ObjWriteVar (CollCount (&SegmentList));
619
620     /* Now walk through all segments and write them to the object file */
621     for (I = 0; I < CollCount (&SegmentList); ++I) {
622         /* Write one segment */
623         WriteOneSeg (CollAtUnchecked (&SegmentList, I));
624     }
625
626     /* Done writing segments */
627     ObjEndSegments ();
628 }
629
630
631
632