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 /*****************************************************************************/
57 #include "studyexpr.h"
62 /*****************************************************************************/
64 /*****************************************************************************/
68 /* If OrgPerSeg is false, all segments share the RelocMode flag and a PC
69 * used when in absolute mode. OrgPerSeg may be set by .feature org_per_seg
71 static int RelocMode = 1;
72 static unsigned long AbsPC = 0; /* PC if in absolute mode */
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);
82 /* Collection containing all segments */
83 Collection SegmentList = STATIC_COLLECTION_INITIALIZER;
85 /* Currently active segment */
90 /*****************************************************************************/
92 /*****************************************************************************/
96 static Segment* NewSegFromDef (SegDef* Def)
97 /* Create a new segment from a segment definition. Used only internally, no
101 /* Create a new segment */
102 Segment* S = xmalloc (sizeof (*S));
108 S->Num = CollCount (&SegmentList);
115 /* Insert it into the segment list */
116 CollAppend (&SegmentList, S);
118 /* And return it... */
124 static Segment* NewSegment (const char* Name, unsigned char AddrSize)
125 /* Create a new segment, insert it into the global list and return it */
127 /* Check for too many segments */
128 if (CollCount (&SegmentList) >= 256) {
129 Fatal ("Too many segments");
132 /* Check the segment name for invalid names */
133 if (!ValidSegName (Name)) {
134 Error ("Illegal segment name: `%s'", Name);
137 /* Create a new segment and return it */
138 return NewSegFromDef (NewSegDef (Name, AddrSize));
143 Fragment* GenFragment (unsigned char Type, unsigned short Len)
144 /* Generate a new fragment, add it to the current segment and return it. */
146 /* Create the new fragment */
147 Fragment* F = NewFragment (Type, Len);
149 /* Insert the fragment into the current segment */
150 if (ActiveSeg->Root) {
151 ActiveSeg->Last->Next = F;
154 ActiveSeg->Root = ActiveSeg->Last = F;
156 ++ActiveSeg->FragCount;
158 /* Add this fragment to the current listing line */
160 if (LineCur->FragList == 0) {
161 LineCur->FragList = F;
163 LineCur->FragLast->LineList = F;
165 LineCur->FragLast = F;
168 /* Increment the program counter */
169 ActiveSeg->PC += F->Len;
171 /* Relocatable mode is switched per segment */
172 if (!ActiveSeg->RelocMode) {
173 ActiveSeg->AbsPC += F->Len;
176 /* Relocatable mode is switched globally */
182 /* Return the fragment */
188 void UseSeg (const SegDef* D)
189 /* Use the segment with the given name */
192 for (I = 0; I < CollCount (&SegmentList); ++I) {
193 Segment* Seg = CollAtUnchecked (&SegmentList, I);
194 if (strcmp (Seg->Def->Name, D->Name) == 0) {
195 /* We found this segment. Check if the type is identical */
196 if (D->AddrSize != ADDR_SIZE_DEFAULT &&
197 Seg->Def->AddrSize != D->AddrSize) {
198 Error ("Segment attribute mismatch");
199 /* Use the new attribute to avoid errors */
200 Seg->Def->AddrSize = D->AddrSize;
207 /* Segment is not in list, create a new one */
208 if (D->AddrSize == ADDR_SIZE_DEFAULT) {
209 ActiveSeg = NewSegment (D->Name, ADDR_SIZE_ABS);
211 ActiveSeg = NewSegment (D->Name, D->AddrSize);
217 unsigned long GetPC (void)
218 /* Get the program counter of the current segment */
221 /* Relocatable mode is switched per segment */
222 return ActiveSeg->RelocMode? ActiveSeg->PC : ActiveSeg->AbsPC;
224 /* Relocatable mode is switched globally */
225 return RelocMode? ActiveSeg->PC : AbsPC;
231 void EnterAbsoluteMode (unsigned long PC)
232 /* Enter absolute (non relocatable mode). Depending on the OrgPerSeg flag,
233 * this will either switch the mode globally or for the current segment.
237 /* Relocatable mode is switched per segment */
238 ActiveSeg->RelocMode = 0;
239 ActiveSeg->AbsPC = PC;
241 /* Relocatable mode is switched globally */
249 int GetRelocMode (void)
250 /* Return true if we're currently in relocatable mode */
253 /* Relocatable mode is switched per segment */
254 return ActiveSeg->RelocMode;
256 /* Relocatable mode is switched globally */
263 void EnterRelocMode (void)
264 /* Enter relocatable mode. Depending on the OrgPerSeg flag, this will either
265 * switch the mode globally or for the current segment.
269 /* Relocatable mode is switched per segment */
270 ActiveSeg->RelocMode = 1;
272 /* Relocatable mode is switched globally */
279 void SegAlign (unsigned Power, int Val)
280 /* Align the PC segment to 2^Power. If Val is -1, emit fill fragments (the
281 * actual fill value will be determined by the linker), otherwise use the
285 unsigned char Data [4];
286 unsigned long Align = (1UL << Power) - 1;
287 unsigned long NewPC = (ActiveSeg->PC + Align) & ~Align;
288 unsigned long Count = NewPC - ActiveSeg->PC;
291 /* User defined fill value */
292 memset (Data, Val, sizeof (Data));
294 if (Count > sizeof (Data)) {
295 EmitData (Data, sizeof (Data));
296 Count -= sizeof (Data);
298 EmitData (Data, Count);
303 /* Linker defined fill value */
307 /* Remember the alignment in the header */
308 if (ActiveSeg->Align < Power) {
309 ActiveSeg->Align = Power;
315 unsigned char GetSegAddrSize (unsigned SegNum)
316 /* Return the address size of the segment with the given number */
318 /* Is there such a segment? */
319 if (SegNum >= CollCount (&SegmentList)) {
320 FAIL ("Invalid segment number");
323 /* Return the address size */
324 return ((Segment*) CollAtUnchecked (&SegmentList, SegNum))->Def->AddrSize;
330 /* Check the segments for range and other errors. Do cleanup. */
332 static const unsigned long U_Hi[4] = {
333 0x000000FFUL, 0x0000FFFFUL, 0x00FFFFFFUL, 0xFFFFFFFFUL
335 static const long S_Hi[4] = {
336 0x0000007FL, 0x00007FFFL, 0x007FFFFFL, 0x7FFFFFFFL
340 for (I = 0; I < CollCount (&SegmentList); ++I) {
341 Segment* S = CollAtUnchecked (&SegmentList, I);
342 Fragment* F = S->Root;
344 if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
346 /* We have an expression, study it */
349 StudyExpr (F->V.Expr, &ED);
351 /* Try to simplify it before looking further */
352 F->V.Expr = SimplifyExpr (F->V.Expr, &ED);
354 /* Check if the expression is constant */
355 if (ED_IsConst (&ED)) {
359 /* The expression is constant. Check for range errors. */
361 if (F->Type == FRAG_SEXPR) {
362 long Hi = S_Hi[F->Len-1];
364 if (ED.Val > Hi || ED.Val < Lo) {
366 "Range error (%ld not in [%ld..%ld])",
370 if (((unsigned long)ED.Val) > U_Hi[F->Len-1]) {
372 "Range error (%lu not in [0..%lu])",
373 (unsigned long)ED.Val, U_Hi[F->Len-1]);
377 /* We don't need the expression tree any longer */
378 FreeExpr (F->V.Expr);
380 /* Convert the fragment into a literal fragment */
381 for (J = 0; J < F->Len; ++J) {
382 F->V.Data[J] = ED.Val & 0xFF;
385 F->Type = FRAG_LITERAL;
387 } else if (ED.AddrSize != ADDR_SIZE_DEFAULT) {
389 /* We cannot evaluate the expression now, leave the job for
390 * the linker. However, we can check if the address size
391 * matches the fragment size, and we will do so.
393 if ((F->Len == 1 && ED.AddrSize > ADDR_SIZE_ZP) ||
394 (F->Len == 2 && ED.AddrSize > ADDR_SIZE_ABS) ||
395 (F->Len == 3 && ED.AddrSize > ADDR_SIZE_FAR)) {
396 LIError (&F->LI, "Range error");
400 /* Release memory allocated for the expression decriptor */
411 /* Dump the contents of all segments */
417 for (I = 0; I < CollCount (&SegmentList); ++I) {
418 Segment* S = CollAtUnchecked (&SegmentList, I);
422 printf ("New segment: %s", S->Def->Name);
425 if (F->Type == FRAG_LITERAL) {
427 printf ("\n Literal:");
431 for (I = 0; I < F->Len; ++I) {
432 printf (" %02X", F->V.Data [I]);
435 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
437 printf ("\n Expression (%u): ", F->Len);
438 DumpExpr (F->V.Expr, SymResolve);
439 } else if (F->Type == FRAG_FILL) {
441 printf ("\n Fill bytes (%u)", F->Len);
443 Internal ("Unknown fragment type: %u", F->Type);
450 printf ("\n End PC = $%04X\n", (unsigned)(S->PC & 0xFFFF));
458 /* Initialize segments */
460 /* Create the predefined segments. Code segment is active */
461 ActiveSeg = NewSegFromDef (&CodeSegDef);
462 NewSegFromDef (&RODataSegDef);
463 NewSegFromDef (&BssSegDef);
464 NewSegFromDef (&DataSegDef);
465 NewSegFromDef (&ZeropageSegDef);
466 NewSegFromDef (&NullSegDef);
471 void SetSegmentSizes (void)
472 /* Set the default segment sizes according to the memory model */
474 /* Initialize segment sizes. The segment definitions do already contain
475 * the correct values for the default case (near), so we must only change
476 * things that should be different.
478 switch (MemoryModel) {
484 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
488 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
489 DataSegDef.AddrSize = ADDR_SIZE_FAR;
490 BssSegDef.AddrSize = ADDR_SIZE_FAR;
491 RODataSegDef.AddrSize = ADDR_SIZE_FAR;
495 Internal ("Invalid memory model: %d", MemoryModel);
501 static void WriteOneSeg (Segment* Seg)
502 /* Write one segment to the object file */
505 unsigned long DataSize;
506 unsigned long EndPos;
508 /* Remember the file position, then write a dummy for the size of the
511 unsigned long SizePos = ObjGetFilePos ();
514 /* Write the segment data */
515 ObjWriteVar (GetStringId (Seg->Def->Name)); /* Name of the segment */
516 ObjWriteVar (Seg->PC); /* Size */
517 ObjWrite8 (Seg->Align); /* Segment alignment */
518 ObjWrite8 (Seg->Def->AddrSize); /* Address size of the segment */
519 ObjWriteVar (Seg->FragCount); /* Number of fragments */
521 /* Now walk through the fragment list for this segment and write the
527 /* Write data depending on the type */
528 switch (Frag->Type) {
531 ObjWrite8 (FRAG_LITERAL);
532 ObjWriteVar (Frag->Len);
533 ObjWriteData (Frag->V.Data, Frag->Len);
538 case 1: ObjWrite8 (FRAG_EXPR8); break;
539 case 2: ObjWrite8 (FRAG_EXPR16); break;
540 case 3: ObjWrite8 (FRAG_EXPR24); break;
541 case 4: ObjWrite8 (FRAG_EXPR32); break;
542 default: Internal ("Invalid fragment size: %u", Frag->Len);
544 WriteExpr (Frag->V.Expr);
549 case 1: ObjWrite8 (FRAG_SEXPR8); break;
550 case 2: ObjWrite8 (FRAG_SEXPR16); break;
551 case 3: ObjWrite8 (FRAG_SEXPR24); break;
552 case 4: ObjWrite8 (FRAG_SEXPR32); break;
553 default: Internal ("Invalid fragment size: %u", Frag->Len);
555 WriteExpr (Frag->V.Expr);
559 ObjWrite8 (FRAG_FILL);
560 ObjWriteVar (Frag->Len);
564 Internal ("Invalid fragment type: %u", Frag->Type);
568 /* Write the line infos for this fragment */
569 WriteLineInfo (&Frag->LI);
575 /* Calculate the size of the data, seek back and write it */
576 EndPos = ObjGetFilePos (); /* Remember where we are */
577 DataSize = EndPos - SizePos - 4; /* Don't count size itself */
578 ObjSetFilePos (SizePos); /* Seek back to the size */
579 ObjWrite32 (DataSize); /* Write the size */
580 ObjSetFilePos (EndPos); /* Seek back to the end */
585 void WriteSegments (void)
586 /* Write the segment data to the object file */
590 /* Tell the object file module that we're about to start the seg list */
593 /* First thing is segment count */
594 ObjWriteVar (CollCount (&SegmentList));
596 /* Now walk through all segments and write them to the object file */
597 for (I = 0; I < CollCount (&SegmentList); ++I) {
598 /* Write one segment */
599 WriteOneSeg (CollAtUnchecked (&SegmentList, I));
602 /* Done writing segments */