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