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 PError (&F->Pos, "Range error");
362 /* Release memory allocated for the expression decriptor */
374 /* Dump the contents of all segments */
377 Segment* S = SegmentList;
383 printf ("New segment: %s", S->Def->Name);
386 if (F->Type == FRAG_LITERAL) {
388 printf ("\n Literal:");
392 for (I = 0; I < F->Len; ++I) {
393 printf (" %02X", F->V.Data [I]);
396 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
398 printf ("\n Expression (%u): ", F->Len);
399 DumpExpr (F->V.Expr, SymResolve);
400 } else if (F->Type == FRAG_FILL) {
402 printf ("\n Fill bytes (%u)", F->Len);
404 Internal ("Unknown fragment type: %u", F->Type);
411 printf ("\n End PC = $%04X\n", (unsigned)(S->PC & 0xFFFF));
419 static void WriteOneSeg (Segment* Seg)
420 /* Write one segment to the object file */
423 unsigned LineInfoIndex;
424 unsigned long DataSize;
425 unsigned long EndPos;
427 /* Remember the file position, then write a dummy for the size of the
430 unsigned long SizePos = ObjGetFilePos ();
433 /* Write the segment data */
434 ObjWriteVar (GetStringId (Seg->Def->Name)); /* Name of the segment */
435 ObjWrite32 (Seg->PC); /* Size */
436 ObjWrite8 (Seg->Align); /* Segment alignment */
437 ObjWrite8 (Seg->Def->AddrSize); /* Address size of the segment */
438 ObjWriteVar (Seg->FragCount); /* Number of fragments */
440 /* Now walk through the fragment list for this segment and write the
446 /* Write data depending on the type */
447 switch (Frag->Type) {
450 ObjWrite8 (FRAG_LITERAL);
451 ObjWriteVar (Frag->Len);
452 ObjWriteData (Frag->V.Data, Frag->Len);
457 case 1: ObjWrite8 (FRAG_EXPR8); break;
458 case 2: ObjWrite8 (FRAG_EXPR16); break;
459 case 3: ObjWrite8 (FRAG_EXPR24); break;
460 case 4: ObjWrite8 (FRAG_EXPR32); break;
461 default: Internal ("Invalid fragment size: %u", Frag->Len);
463 WriteExpr (Frag->V.Expr);
468 case 1: ObjWrite8 (FRAG_SEXPR8); break;
469 case 2: ObjWrite8 (FRAG_SEXPR16); break;
470 case 3: ObjWrite8 (FRAG_SEXPR24); break;
471 case 4: ObjWrite8 (FRAG_SEXPR32); break;
472 default: Internal ("Invalid fragment size: %u", Frag->Len);
474 WriteExpr (Frag->V.Expr);
478 ObjWrite8 (FRAG_FILL);
479 ObjWriteVar (Frag->Len);
483 Internal ("Invalid fragment type: %u", Frag->Type);
487 /* Write the file position of this fragment */
488 ObjWritePos (&Frag->Pos);
490 /* Write extra line info for this fragment. Zero is considered
491 * "no line info", so add one to the value.
493 LineInfoIndex = Frag->LI? Frag->LI->Index + 1 : 0;
494 ObjWriteVar (LineInfoIndex);
500 /* Calculate the size of the data, seek back and write it */
501 EndPos = ObjGetFilePos (); /* Remember where we are */
502 DataSize = EndPos - SizePos - 4; /* Don't count size itself */
503 ObjSetFilePos (SizePos); /* Seek back to the size */
504 ObjWrite32 (DataSize); /* Write the size */
505 ObjSetFilePos (EndPos); /* Seek back to the end */
510 void InitSegments (void)
511 /* Initialize segments */
513 /* Initialize segment sizes. The segment definitions do already contain
514 * the correct values for the default case (near), so we must only change
515 * things that should be different.
517 switch (MemoryModel) {
523 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
527 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
528 DataSegDef.AddrSize = ADDR_SIZE_FAR;
529 BssSegDef.AddrSize = ADDR_SIZE_FAR;
530 RODataSegDef.AddrSize = ADDR_SIZE_FAR;
534 Internal ("Invalid memory model: %d", MemoryModel);
540 void WriteSegments (void)
541 /* Write the segment data to the object file */
545 /* Tell the object file module that we're about to start the seg list */
548 /* First thing is segment count */
549 ObjWriteVar (SegmentCount);
551 /* Now walk through all segments and write them to the object file */
554 /* Write one segment */
560 /* Done writing segments */