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