1 /*****************************************************************************/
5 /* Segments for the ca65 macroassembler */
9 /* (C) 1998-2003 Ullrich von Bassewitz */
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 /*****************************************************************************/
55 #include "studyexpr.h"
60 /*****************************************************************************/
62 /*****************************************************************************/
66 /* Are we in absolute mode or in relocatable mode? */
68 unsigned long AbsPC = 0; /* PC if in absolute mode */
70 /* Segment initializer macro */
71 #define SEG(segdef, num, prev) \
72 { prev, 0, 0, 0, num, 0, 0, segdef }
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 /* 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);
90 /* Number of segments */
91 static unsigned SegmentCount = 6;
93 /* List of all segments */
94 Segment* SegmentList = &CodeSeg;
95 static Segment* SegmentLast = &NullSeg;
97 /* Currently active segment */
98 Segment* ActiveSeg = &CodeSeg;
102 /*****************************************************************************/
104 /*****************************************************************************/
108 static Segment* NewSegment (const char* Name, unsigned char AddrSize)
109 /* Create a new segment, insert it into the global list and return it */
113 /* Check for too many segments */
114 if (SegmentCount >= 256) {
115 Fatal ("Too many segments");
118 /* Check the segment name for invalid names */
119 if (!ValidSegName (Name)) {
120 Error ("Illegal segment name: `%s'", Name);
123 /* Create a new segment */
124 S = xmalloc (sizeof (*S));
131 S->Num = SegmentCount++;
134 S->Def = NewSegDef (Name, AddrSize);
136 /* Insert it into the segment list */
137 SegmentLast->List = S;
140 /* And return it... */
146 Fragment* GenFragment (unsigned char Type, unsigned short Len)
147 /* Generate a new fragment, add it to the current segment and return it. */
149 /* Create the new fragment */
150 Fragment* F = NewFragment (Type, Len);
152 /* Insert the fragment into the current segment */
153 if (ActiveSeg->Root) {
154 ActiveSeg->Last->Next = F;
157 ActiveSeg->Root = ActiveSeg->Last = F;
159 ++ActiveSeg->FragCount;
161 /* Add this fragment to the current listing line */
163 if (LineCur->FragList == 0) {
164 LineCur->FragList = F;
166 LineCur->FragLast->LineList = F;
168 LineCur->FragLast = F;
171 /* Increment the program counter */
172 ActiveSeg->PC += F->Len;
177 /* Return the fragment */
183 void UseSeg (const SegDef* D)
184 /* Use the segment with the given name */
186 Segment* Seg = SegmentList;
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;
199 /* Check next segment */
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);
207 Seg = NewSegment (D->Name, D->AddrSize);
214 unsigned long GetPC (void)
215 /* Get the program counter of the current segment */
217 return RelocMode? ActiveSeg->PC : AbsPC;
222 void SetAbsPC (unsigned long PC)
223 /* Set the program counter in absolute mode */
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
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;
243 /* User defined fill value */
244 memset (Data, Val, sizeof (Data));
246 if (Count > sizeof (Data)) {
247 EmitData (Data, sizeof (Data));
248 Count -= sizeof (Data);
250 EmitData (Data, Count);
255 /* Linker defined fill value */
259 /* Remember the alignment in the header */
260 if (ActiveSeg->Align < Power) {
261 ActiveSeg->Align = Power;
267 unsigned char GetSegAddrSize (unsigned SegNum)
268 /* Return the address size of the segment with the given number */
270 /* Search for the segment */
271 Segment* S = SegmentList;
272 while (S && SegNum) {
277 /* Did we find it? */
279 FAIL ("Invalid segment number");
282 /* Return the address size */
283 return S->Def->AddrSize;
289 /* Check the segments for range and other errors */
291 Segment* S = SegmentList;
293 Fragment* F = S->Root;
295 if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
297 /* We have an expression, study it */
300 StudyExpr (F->V.Expr, &ED);
302 /* Try to simplify it before looking further */
303 F->V.Expr = SimplifyExpr (F->V.Expr, &ED);
305 /* Check if the expression is constant */
306 if (ED_IsConst (&ED)) {
308 /* The expression is constant. Check for range errors. */
309 int Abs = (F->Type != FRAG_SEXPR);
317 PError (&F->Pos, "Range error");
320 /* PC relative value */
321 if (Val < -128 || Val > 127) {
322 PError (&F->Pos, "Range error");
325 } else if (F->Len == 2) {
329 PError (&F->Pos, "Range error");
332 /* PC relative value */
333 if (Val < -32768 || Val > 32767) {
334 PError (&F->Pos, "Range error");
339 /* We don't need the expression tree any longer */
340 FreeExpr (F->V.Expr);
342 /* Convert the fragment into a literal fragment */
343 for (I = 0; I < F->Len; ++I) {
344 F->V.Data [I] = Val & 0xFF;
347 F->Type = FRAG_LITERAL;
349 } else if (ED.AddrSize != ADDR_SIZE_DEFAULT) {
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.
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");
367 /* Release memory allocated for the expression decriptor */
379 /* Dump the contents of all segments */
382 Segment* S = SegmentList;
388 printf ("New segment: %s", S->Def->Name);
391 if (F->Type == FRAG_LITERAL) {
393 printf ("\n Literal:");
397 for (I = 0; I < F->Len; ++I) {
398 printf (" %02X", F->V.Data [I]);
401 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
403 printf ("\n Expression (%u): ", F->Len);
404 DumpExpr (F->V.Expr, SymResolve);
405 } else if (F->Type == FRAG_FILL) {
407 printf ("\n Fill bytes (%u)", F->Len);
409 Internal ("Unknown fragment type: %u", F->Type);
416 printf ("\n End PC = $%04X\n", (unsigned)(S->PC & 0xFFFF));
424 static void WriteOneSeg (Segment* Seg)
425 /* Write one segment to the object file */
428 unsigned LineInfoIndex;
429 unsigned long DataSize;
430 unsigned long EndPos;
432 /* Remember the file position, then write a dummy for the size of the
435 unsigned long SizePos = ObjGetFilePos ();
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 */
445 /* Now walk through the fragment list for this segment and write the
451 /* Write data depending on the type */
452 switch (Frag->Type) {
455 ObjWrite8 (FRAG_LITERAL);
456 ObjWriteVar (Frag->Len);
457 ObjWriteData (Frag->V.Data, 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);
468 WriteExpr (Frag->V.Expr);
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);
479 WriteExpr (Frag->V.Expr);
483 ObjWrite8 (FRAG_FILL);
484 ObjWriteVar (Frag->Len);
488 Internal ("Invalid fragment type: %u", Frag->Type);
492 /* Write the file position of this fragment */
493 ObjWritePos (&Frag->Pos);
495 /* Write extra line info for this fragment. Zero is considered
496 * "no line info", so add one to the value.
498 LineInfoIndex = Frag->LI? Frag->LI->Index + 1 : 0;
499 ObjWriteVar (LineInfoIndex);
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 */
515 void InitSegments (void)
516 /* Initialize segments */
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.
522 switch (MemoryModel) {
528 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
532 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
533 DataSegDef.AddrSize = ADDR_SIZE_FAR;
534 BssSegDef.AddrSize = ADDR_SIZE_FAR;
535 RODataSegDef.AddrSize = ADDR_SIZE_FAR;
539 Internal ("Invalid memory model: %d", MemoryModel);
545 void WriteSegments (void)
546 /* Write the segment data to the object file */
550 /* Tell the object file module that we're about to start the seg list */
553 /* First thing is segment count */
554 ObjWriteVar (SegmentCount);
556 /* Now walk through all segments and write them to the object file */
559 /* Write one segment */
565 /* Done writing segments */