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 /*****************************************************************************/
56 #include "studyexpr.h"
61 /*****************************************************************************/
63 /*****************************************************************************/
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
70 static int RelocMode = 1;
71 static unsigned long AbsPC = 0; /* PC if in absolute mode */
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);
81 /* Collection containing all segments */
82 Collection SegmentList = STATIC_COLLECTION_INITIALIZER;
84 /* Currently active segment */
89 /*****************************************************************************/
91 /*****************************************************************************/
95 static Segment* NewSegFromDef (SegDef* Def)
96 /* Create a new segment from a segment definition. Used only internally, no
100 /* Create a new segment */
101 Segment* S = xmalloc (sizeof (*S));
107 S->Num = CollCount (&SegmentList);
114 /* Insert it into the segment list */
115 CollAppend (&SegmentList, S);
117 /* And return it... */
123 static Segment* NewSegment (const char* Name, unsigned char AddrSize)
124 /* Create a new segment, insert it into the global list and return it */
126 /* Check for too many segments */
127 if (CollCount (&SegmentList) >= 256) {
128 Fatal ("Too many segments");
131 /* Check the segment name for invalid names */
132 if (!ValidSegName (Name)) {
133 Error ("Illegal segment name: `%s'", Name);
136 /* Create a new segment and return it */
137 return NewSegFromDef (NewSegDef (Name, AddrSize));
142 Fragment* GenFragment (unsigned char Type, unsigned short Len)
143 /* Generate a new fragment, add it to the current segment and return it. */
145 /* Create the new fragment */
146 Fragment* F = NewFragment (Type, Len);
148 /* Insert the fragment into the current segment */
149 if (ActiveSeg->Root) {
150 ActiveSeg->Last->Next = F;
153 ActiveSeg->Root = ActiveSeg->Last = F;
155 ++ActiveSeg->FragCount;
157 /* Add this fragment to the current listing line */
159 if (LineCur->FragList == 0) {
160 LineCur->FragList = F;
162 LineCur->FragLast->LineList = F;
164 LineCur->FragLast = F;
167 /* Increment the program counter */
168 ActiveSeg->PC += F->Len;
170 /* Relocatable mode is switched per segment */
171 if (!ActiveSeg->RelocMode) {
172 ActiveSeg->AbsPC += F->Len;
175 /* Relocatable mode is switched globally */
181 /* Return the fragment */
187 void UseSeg (const SegDef* D)
188 /* Use the segment with the given name */
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;
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);
210 ActiveSeg = NewSegment (D->Name, D->AddrSize);
216 unsigned long GetPC (void)
217 /* Get the program counter of the current segment */
220 /* Relocatable mode is switched per segment */
221 return ActiveSeg->RelocMode? ActiveSeg->PC : ActiveSeg->AbsPC;
223 /* Relocatable mode is switched globally */
224 return RelocMode? ActiveSeg->PC : AbsPC;
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.
236 /* Relocatable mode is switched per segment */
237 ActiveSeg->RelocMode = 0;
238 ActiveSeg->AbsPC = PC;
240 /* Relocatable mode is switched globally */
248 int GetRelocMode (void)
249 /* Return true if we're currently in relocatable mode */
252 /* Relocatable mode is switched per segment */
253 return ActiveSeg->RelocMode;
255 /* Relocatable mode is switched globally */
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.
268 /* Relocatable mode is switched per segment */
269 ActiveSeg->RelocMode = 1;
271 /* Relocatable mode is switched globally */
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
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;
290 /* User defined fill value */
291 memset (Data, Val, sizeof (Data));
293 if (Count > sizeof (Data)) {
294 EmitData (Data, sizeof (Data));
295 Count -= sizeof (Data);
297 EmitData (Data, Count);
302 /* Linker defined fill value */
306 /* Remember the alignment in the header */
307 if (ActiveSeg->Align < Power) {
308 ActiveSeg->Align = Power;
314 unsigned char GetSegAddrSize (unsigned SegNum)
315 /* Return the address size of the segment with the given number */
317 /* Is there such a segment? */
318 if (SegNum >= CollCount (&SegmentList)) {
319 FAIL ("Invalid segment number");
322 /* Return the address size */
323 return ((Segment*) CollAtUnchecked (&SegmentList, SegNum))->Def->AddrSize;
329 /* Check the segments for range and other errors */
331 static const unsigned long U_Hi[4] = {
332 0x000000FFUL, 0x0000FFFFUL, 0x00FFFFFFUL, 0xFFFFFFFFUL
334 static const long S_Hi[4] = {
335 0x0000007FL, 0x00007FFFL, 0x007FFFFFL, 0x7FFFFFFFL
339 for (I = 0; I < CollCount (&SegmentList); ++I) {
340 Segment* S = CollAtUnchecked (&SegmentList, I);
341 Fragment* F = S->Root;
343 if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
345 /* We have an expression, study it */
348 StudyExpr (F->V.Expr, &ED);
350 /* Try to simplify it before looking further */
351 F->V.Expr = SimplifyExpr (F->V.Expr, &ED);
353 /* Check if the expression is constant */
354 if (ED_IsConst (&ED)) {
358 /* The expression is constant. Check for range errors. */
360 if (F->Type == FRAG_SEXPR) {
361 long Hi = S_Hi[F->Len-1];
363 if (ED.Val > Hi || ED.Val < Lo) {
365 "Range error (%ld not in [%ld..%ld])",
369 if (((unsigned long)ED.Val) > U_Hi[F->Len-1]) {
371 "Range error (%lu not in [0..%lu])",
372 (unsigned long)ED.Val, U_Hi[F->Len-1]);
376 /* We don't need the expression tree any longer */
377 FreeExpr (F->V.Expr);
379 /* Convert the fragment into a literal fragment */
380 for (J = 0; J < F->Len; ++J) {
381 F->V.Data[J] = ED.Val & 0xFF;
384 F->Type = FRAG_LITERAL;
386 } else if (ED.AddrSize != ADDR_SIZE_DEFAULT) {
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.
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");
399 /* Release memory allocated for the expression decriptor */
410 /* Dump the contents of all segments */
416 for (I = 0; I < CollCount (&SegmentList); ++I) {
417 Segment* S = CollAtUnchecked (&SegmentList, I);
421 printf ("New segment: %s", S->Def->Name);
424 if (F->Type == FRAG_LITERAL) {
426 printf ("\n Literal:");
430 for (I = 0; I < F->Len; ++I) {
431 printf (" %02X", F->V.Data [I]);
434 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
436 printf ("\n Expression (%u): ", F->Len);
437 DumpExpr (F->V.Expr, SymResolve);
438 } else if (F->Type == FRAG_FILL) {
440 printf ("\n Fill bytes (%u)", F->Len);
442 Internal ("Unknown fragment type: %u", F->Type);
449 printf ("\n End PC = $%04X\n", (unsigned)(S->PC & 0xFFFF));
456 void InitSegments (void)
457 /* Initialize segments */
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);
470 void SetSegmentSizes (void)
471 /* Set the default segment sizes according to the memory model */
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.
477 switch (MemoryModel) {
483 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
487 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
488 DataSegDef.AddrSize = ADDR_SIZE_FAR;
489 BssSegDef.AddrSize = ADDR_SIZE_FAR;
490 RODataSegDef.AddrSize = ADDR_SIZE_FAR;
494 Internal ("Invalid memory model: %d", MemoryModel);
500 static void WriteOneSeg (Segment* Seg)
501 /* Write one segment to the object file */
504 unsigned long DataSize;
505 unsigned long EndPos;
507 /* Remember the file position, then write a dummy for the size of the
510 unsigned long SizePos = ObjGetFilePos ();
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 */
520 /* Now walk through the fragment list for this segment and write the
526 /* Write data depending on the type */
527 switch (Frag->Type) {
530 ObjWrite8 (FRAG_LITERAL);
531 ObjWriteVar (Frag->Len);
532 ObjWriteData (Frag->V.Data, 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);
543 WriteExpr (Frag->V.Expr);
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);
554 WriteExpr (Frag->V.Expr);
558 ObjWrite8 (FRAG_FILL);
559 ObjWriteVar (Frag->Len);
563 Internal ("Invalid fragment type: %u", Frag->Type);
567 /* Write the line infos for this fragment */
568 WriteLineInfo (&Frag->LI);
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 */
584 void WriteSegments (void)
585 /* Write the segment data to the object file */
589 /* Tell the object file module that we're about to start the seg list */
592 /* First thing is segment count */
593 ObjWriteVar (CollCount (&SegmentList));
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));
601 /* Done writing segments */