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