1 /*****************************************************************************/
5 /* Segments for the ca65 macroassembler */
9 /* (C) 1998-2011, Ullrich von Bassewitz */
10 /* Roemerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
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. */
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: */
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 */
32 /*****************************************************************************/
41 #include "alignment.h"
58 #include "studyexpr.h"
63 /*****************************************************************************/
65 /*****************************************************************************/
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
72 static int RelocMode = 1;
73 static unsigned long AbsPC = 0; /* PC if in absolute mode */
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);
83 /* Collection containing all segments */
84 Collection SegmentList = STATIC_COLLECTION_INITIALIZER;
86 /* Currently active segment */
91 /*****************************************************************************/
93 /*****************************************************************************/
97 static Segment* NewSegFromDef (SegDef* Def)
98 /* Create a new segment from a segment definition. Used only internally, no
102 /* Create a new segment */
103 Segment* S = xmalloc (sizeof (*S));
109 S->Num = CollCount (&SegmentList);
116 /* Insert it into the segment list */
117 CollAppend (&SegmentList, S);
119 /* And return it... */
125 static Segment* NewSegment (const char* Name, unsigned char AddrSize)
126 /* Create a new segment, insert it into the global list and return it */
128 /* Check for too many segments */
129 if (CollCount (&SegmentList) >= 256) {
130 Fatal ("Too many segments");
133 /* Check the segment name for invalid names */
134 if (!ValidSegName (Name)) {
135 Error ("Illegal segment name: `%s'", Name);
138 /* Create a new segment and return it */
139 return NewSegFromDef (NewSegDef (Name, AddrSize));
144 Fragment* GenFragment (unsigned char Type, unsigned short Len)
145 /* Generate a new fragment, add it to the current segment and return it. */
147 /* Create the new fragment */
148 Fragment* F = NewFragment (Type, Len);
150 /* Insert the fragment into the current segment */
151 if (ActiveSeg->Root) {
152 ActiveSeg->Last->Next = F;
155 ActiveSeg->Root = ActiveSeg->Last = F;
157 ++ActiveSeg->FragCount;
159 /* Add this fragment to the current listing line */
161 if (LineCur->FragList == 0) {
162 LineCur->FragList = F;
164 LineCur->FragLast->LineList = F;
166 LineCur->FragLast = F;
169 /* Increment the program counter */
170 ActiveSeg->PC += F->Len;
172 /* Relocatable mode is switched per segment */
173 if (!ActiveSeg->RelocMode) {
174 ActiveSeg->AbsPC += F->Len;
177 /* Relocatable mode is switched globally */
183 /* Return the fragment */
189 void UseSeg (const SegDef* D)
190 /* Use the segment with the given name */
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;
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);
212 ActiveSeg = NewSegment (D->Name, D->AddrSize);
218 unsigned long GetPC (void)
219 /* Get the program counter of the current segment */
222 /* Relocatable mode is switched per segment */
223 return ActiveSeg->RelocMode? ActiveSeg->PC : ActiveSeg->AbsPC;
225 /* Relocatable mode is switched globally */
226 return RelocMode? ActiveSeg->PC : AbsPC;
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.
238 /* Relocatable mode is switched per segment */
239 ActiveSeg->RelocMode = 0;
240 ActiveSeg->AbsPC = PC;
242 /* Relocatable mode is switched globally */
250 int GetRelocMode (void)
251 /* Return true if we're currently in relocatable mode */
254 /* Relocatable mode is switched per segment */
255 return ActiveSeg->RelocMode;
257 /* Relocatable mode is switched globally */
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.
270 /* Relocatable mode is switched per segment */
271 ActiveSeg->RelocMode = 1;
273 /* Relocatable mode is switched globally */
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
286 unsigned char Data [4];
287 unsigned long CombinedAlignment;
290 /* The segment must have the combined alignment of all separate alignments
291 * in the source. Calculate this alignment and check it for sanity.
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);
298 /* Avoid creating large fills for an object file that is thrown away
304 ActiveSeg->Align = CombinedAlignment;
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)",
312 /* Calculate the number of fill bytes */
313 Count = AlignCount (ActiveSeg->PC, Alignment) - ActiveSeg->PC;
318 /* Emit the data or a fill fragment */
320 /* User defined fill value */
321 memset (Data, FillVal, sizeof (Data));
323 if (Count > sizeof (Data)) {
324 EmitData (Data, sizeof (Data));
325 Count -= sizeof (Data);
327 EmitData (Data, Count);
332 /* Linker defined fill value */
339 unsigned char GetSegAddrSize (unsigned SegNum)
340 /* Return the address size of the segment with the given number */
342 /* Is there such a segment? */
343 if (SegNum >= CollCount (&SegmentList)) {
344 FAIL ("Invalid segment number");
347 /* Return the address size */
348 return ((Segment*) CollAtUnchecked (&SegmentList, SegNum))->Def->AddrSize;
354 /* Check the segments for range and other errors. Do cleanup. */
356 static const unsigned long U_Hi[4] = {
357 0x000000FFUL, 0x0000FFFFUL, 0x00FFFFFFUL, 0xFFFFFFFFUL
359 static const long S_Hi[4] = {
360 0x0000007FL, 0x00007FFFL, 0x007FFFFFL, 0x7FFFFFFFL
364 for (I = 0; I < CollCount (&SegmentList); ++I) {
365 Segment* S = CollAtUnchecked (&SegmentList, I);
366 Fragment* F = S->Root;
368 if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
370 /* We have an expression, study it */
373 StudyExpr (F->V.Expr, &ED);
375 /* Check if the expression is constant */
376 if (ED_IsConst (&ED)) {
380 /* The expression is constant. Check for range errors. */
382 if (F->Type == FRAG_SEXPR) {
383 long Hi = S_Hi[F->Len-1];
385 if (ED.Val > Hi || ED.Val < Lo) {
387 "Range error (%ld not in [%ld..%ld])",
391 if (((unsigned long)ED.Val) > U_Hi[F->Len-1]) {
393 "Range error (%lu not in [0..%lu])",
394 (unsigned long)ED.Val, U_Hi[F->Len-1]);
398 /* We don't need the expression tree any longer */
399 FreeExpr (F->V.Expr);
401 /* Convert the fragment into a literal fragment */
402 for (J = 0; J < F->Len; ++J) {
403 F->V.Data[J] = ED.Val & 0xFF;
406 F->Type = FRAG_LITERAL;
410 /* Finalize the expression */
411 F->V.Expr = FinalizeExpr (F->V.Expr, &F->LI);
413 /* Simplify the expression */
414 /* ### F->V.Expr = SimplifyExpr (F->V.Expr, &ED); */
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.
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");
427 /* Release memory allocated for the expression decriptor */
438 /* Dump the contents of all segments */
444 for (I = 0; I < CollCount (&SegmentList); ++I) {
445 Segment* S = CollAtUnchecked (&SegmentList, I);
449 printf ("New segment: %s", S->Def->Name);
452 if (F->Type == FRAG_LITERAL) {
454 printf ("\n Literal:");
458 for (I = 0; I < F->Len; ++I) {
459 printf (" %02X", F->V.Data [I]);
462 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
464 printf ("\n Expression (%u): ", F->Len);
465 DumpExpr (F->V.Expr, SymResolve);
466 } else if (F->Type == FRAG_FILL) {
468 printf ("\n Fill bytes (%u)", F->Len);
470 Internal ("Unknown fragment type: %u", F->Type);
477 printf ("\n End PC = $%04X\n", (unsigned)(S->PC & 0xFFFF));
485 /* Initialize segments */
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);
498 void SetSegmentSizes (void)
499 /* Set the default segment sizes according to the memory model */
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.
505 switch (MemoryModel) {
511 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
515 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
516 DataSegDef.AddrSize = ADDR_SIZE_FAR;
517 BssSegDef.AddrSize = ADDR_SIZE_FAR;
518 RODataSegDef.AddrSize = ADDR_SIZE_FAR;
522 Internal ("Invalid memory model: %d", MemoryModel);
528 static void WriteOneSeg (Segment* Seg)
529 /* Write one segment to the object file */
532 unsigned long DataSize;
533 unsigned long EndPos;
535 /* Remember the file position, then write a dummy for the size of the
538 unsigned long SizePos = ObjGetFilePos ();
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 */
548 /* Now walk through the fragment list for this segment and write the
554 /* Write data depending on the type */
555 switch (Frag->Type) {
558 ObjWrite8 (FRAG_LITERAL);
559 ObjWriteVar (Frag->Len);
560 ObjWriteData (Frag->V.Data, 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);
571 WriteExpr (Frag->V.Expr);
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);
582 WriteExpr (Frag->V.Expr);
586 ObjWrite8 (FRAG_FILL);
587 ObjWriteVar (Frag->Len);
591 Internal ("Invalid fragment type: %u", Frag->Type);
595 /* Write the line infos for this fragment */
596 WriteLineInfo (&Frag->LI);
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 */
612 void WriteSegments (void)
613 /* Write the segment data to the object file */
617 /* Tell the object file module that we're about to start the seg list */
620 /* First thing is segment count */
621 ObjWriteVar (CollCount (&SegmentList));
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));
629 /* Done writing segments */