1 /*****************************************************************************/
5 /* Segments for the ca65 macroassembler */
9 /* (C) 1998-2007 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 /*****************************************************************************/
55 #include "studyexpr.h"
60 /*****************************************************************************/
62 /*****************************************************************************/
66 /* If OrgPerSeg is false, all segments share the RelocMode flag and a PC
67 * used when in absolute mode. OrgPerSeg may be set by .feature org_per_seg
69 static int RelocMode = 1;
70 static unsigned long AbsPC = 0; /* PC if in absolute mode */
72 /* Segment initializer macro */
73 #define SEG(segdef, num, prev) \
74 { prev, 0, 0, 0, num, 0, 1, 0, 0, segdef }
76 /* Definitions for predefined segments */
77 SegDef NullSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_NULL, ADDR_SIZE_ABS);
78 SegDef ZeropageSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_ZEROPAGE, ADDR_SIZE_ZP);
79 SegDef DataSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_DATA, ADDR_SIZE_ABS);
80 SegDef BssSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_BSS, ADDR_SIZE_ABS);
81 SegDef RODataSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_RODATA, ADDR_SIZE_ABS);
82 SegDef CodeSegDef = STATIC_SEGDEF_INITIALIZER (SEGNAME_CODE, ADDR_SIZE_ABS);
84 /* Predefined segments */
85 static Segment NullSeg = SEG (&NullSegDef, 5, NULL);
86 static Segment ZeropageSeg = SEG (&ZeropageSegDef, 4, &NullSeg);
87 static Segment DataSeg = SEG (&DataSegDef, 3, &ZeropageSeg);
88 static Segment BssSeg = SEG (&BssSegDef, 2, &DataSeg);
89 static Segment RODataSeg = SEG (&RODataSegDef, 1, &BssSeg);
90 static Segment CodeSeg = SEG (&CodeSegDef, 0, &RODataSeg);
92 /* Number of segments */
93 static unsigned SegmentCount = 6;
95 /* List of all segments */
96 Segment* SegmentList = &CodeSeg;
97 static Segment* SegmentLast = &NullSeg;
99 /* Currently active segment */
100 Segment* ActiveSeg = &CodeSeg;
104 /*****************************************************************************/
106 /*****************************************************************************/
110 static Segment* NewSegment (const char* Name, unsigned char AddrSize)
111 /* Create a new segment, insert it into the global list and return it */
115 /* Check for too many segments */
116 if (SegmentCount >= 256) {
117 Fatal ("Too many segments");
120 /* Check the segment name for invalid names */
121 if (!ValidSegName (Name)) {
122 Error ("Illegal segment name: `%s'", Name);
125 /* Create a new segment */
126 S = xmalloc (sizeof (*S));
133 S->Num = SegmentCount++;
138 S->Def = NewSegDef (Name, AddrSize);
140 /* Insert it into the segment list */
141 SegmentLast->List = S;
144 /* And return it... */
150 Fragment* GenFragment (unsigned char Type, unsigned short Len)
151 /* Generate a new fragment, add it to the current segment and return it. */
153 /* Create the new fragment */
154 Fragment* F = NewFragment (Type, Len);
156 /* Insert the fragment into the current segment */
157 if (ActiveSeg->Root) {
158 ActiveSeg->Last->Next = F;
161 ActiveSeg->Root = ActiveSeg->Last = F;
163 ++ActiveSeg->FragCount;
165 /* Add this fragment to the current listing line */
167 if (LineCur->FragList == 0) {
168 LineCur->FragList = F;
170 LineCur->FragLast->LineList = F;
172 LineCur->FragLast = F;
175 /* Increment the program counter */
176 ActiveSeg->PC += F->Len;
178 /* Relocatable mode is switched per segment */
179 if (!ActiveSeg->RelocMode) {
180 ActiveSeg->AbsPC += F->Len;
183 /* Relocatable mode is switched globally */
189 /* Return the fragment */
195 void UseSeg (const SegDef* D)
196 /* Use the segment with the given name */
198 Segment* Seg = SegmentList;
200 if (strcmp (Seg->Def->Name, D->Name) == 0) {
201 /* We found this segment. Check if the type is identical */
202 if (D->AddrSize != ADDR_SIZE_DEFAULT &&
203 Seg->Def->AddrSize != D->AddrSize) {
204 Error ("Segment attribute mismatch");
205 /* Use the new attribute to avoid errors */
206 Seg->Def->AddrSize = D->AddrSize;
211 /* Check next segment */
215 /* Segment is not in list, create a new one */
216 if (D->AddrSize == ADDR_SIZE_DEFAULT) {
217 Seg = NewSegment (D->Name, ADDR_SIZE_ABS);
219 Seg = NewSegment (D->Name, D->AddrSize);
226 unsigned long GetPC (void)
227 /* Get the program counter of the current segment */
230 /* Relocatable mode is switched per segment */
231 return ActiveSeg->RelocMode? ActiveSeg->PC : ActiveSeg->AbsPC;
233 /* Relocatable mode is switched globally */
234 return RelocMode? ActiveSeg->PC : AbsPC;
240 void EnterAbsoluteMode (unsigned long PC)
241 /* Enter absolute (non relocatable mode). Depending on the OrgPerSeg flag,
242 * this will either switch the mode globally or for the current segment.
246 /* Relocatable mode is switched per segment */
247 ActiveSeg->RelocMode = 0;
248 ActiveSeg->AbsPC = PC;
250 /* Relocatable mode is switched globally */
258 int GetRelocMode (void)
259 /* Return true if we're currently in relocatable mode */
262 /* Relocatable mode is switched per segment */
263 return ActiveSeg->RelocMode;
265 /* Relocatable mode is switched globally */
272 void EnterRelocMode (void)
273 /* Enter relocatable mode. Depending on the OrgPerSeg flag, this will either
274 * switch the mode globally or for the current segment.
278 /* Relocatable mode is switched per segment */
279 ActiveSeg->RelocMode = 1;
281 /* Relocatable mode is switched globally */
288 void SegAlign (unsigned Power, int Val)
289 /* Align the PC segment to 2^Power. If Val is -1, emit fill fragments (the
290 * actual fill value will be determined by the linker), otherwise use the
294 unsigned char Data [4];
295 unsigned long Align = (1UL << Power) - 1;
296 unsigned long NewPC = (ActiveSeg->PC + Align) & ~Align;
297 unsigned long Count = NewPC - ActiveSeg->PC;
300 /* User defined fill value */
301 memset (Data, Val, sizeof (Data));
303 if (Count > sizeof (Data)) {
304 EmitData (Data, sizeof (Data));
305 Count -= sizeof (Data);
307 EmitData (Data, Count);
312 /* Linker defined fill value */
316 /* Remember the alignment in the header */
317 if (ActiveSeg->Align < Power) {
318 ActiveSeg->Align = Power;
324 unsigned char GetSegAddrSize (unsigned SegNum)
325 /* Return the address size of the segment with the given number */
327 /* Search for the segment */
328 Segment* S = SegmentList;
329 while (S && SegNum) {
334 /* Did we find it? */
336 FAIL ("Invalid segment number");
339 /* Return the address size */
340 return S->Def->AddrSize;
346 /* Check the segments for range and other errors */
348 Segment* S = SegmentList;
350 Fragment* F = S->Root;
352 if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
354 /* We have an expression, study it */
357 StudyExpr (F->V.Expr, &ED);
359 /* Try to simplify it before looking further */
360 F->V.Expr = SimplifyExpr (F->V.Expr, &ED);
362 /* Check if the expression is constant */
363 if (ED_IsConst (&ED)) {
365 /* The expression is constant. Check for range errors. */
366 int Abs = (F->Type != FRAG_SEXPR);
374 LIError (&F->LI, "Range error (%ld not in [0..255])", Val);
377 /* PC relative value */
378 if (Val < -128 || Val > 127) {
379 LIError (&F->LI, "Range error (%ld not in [-128..127])", Val);
382 } else if (F->Len == 2) {
386 LIError (&F->LI, "Range error (%ld not in [0..65535])", Val);
389 /* PC relative value */
390 if (Val < -32768 || Val > 32767) {
391 LIError (&F->LI, "Range error (%ld not in [-32768..32767])", Val);
396 /* We don't need the expression tree any longer */
397 FreeExpr (F->V.Expr);
399 /* Convert the fragment into a literal fragment */
400 for (I = 0; I < F->Len; ++I) {
401 F->V.Data [I] = Val & 0xFF;
404 F->Type = FRAG_LITERAL;
406 } else if (ED.AddrSize != ADDR_SIZE_DEFAULT) {
408 /* We cannot evaluate the expression now, leave the job for
409 * the linker. However, we can check if the address size
410 * matches the fragment size, and we will do so.
412 if ((F->Len == 1 && ED.AddrSize > ADDR_SIZE_ZP) ||
413 (F->Len == 2 && ED.AddrSize > ADDR_SIZE_ABS) ||
414 (F->Len == 3 && ED.AddrSize > ADDR_SIZE_FAR)) {
415 LIError (&F->LI, "Range error");
419 /* Release memory allocated for the expression decriptor */
431 /* Dump the contents of all segments */
434 Segment* S = SegmentList;
440 printf ("New segment: %s", S->Def->Name);
443 if (F->Type == FRAG_LITERAL) {
445 printf ("\n Literal:");
449 for (I = 0; I < F->Len; ++I) {
450 printf (" %02X", F->V.Data [I]);
453 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
455 printf ("\n Expression (%u): ", F->Len);
456 DumpExpr (F->V.Expr, SymResolve);
457 } else if (F->Type == FRAG_FILL) {
459 printf ("\n Fill bytes (%u)", F->Len);
461 Internal ("Unknown fragment type: %u", F->Type);
468 printf ("\n End PC = $%04X\n", (unsigned)(S->PC & 0xFFFF));
476 static void WriteOneSeg (Segment* Seg)
477 /* Write one segment to the object file */
480 unsigned long DataSize;
481 unsigned long EndPos;
483 /* Remember the file position, then write a dummy for the size of the
486 unsigned long SizePos = ObjGetFilePos ();
489 /* Write the segment data */
490 ObjWriteVar (GetStringId (Seg->Def->Name)); /* Name of the segment */
491 ObjWrite32 (Seg->PC); /* Size */
492 ObjWrite8 (Seg->Align); /* Segment alignment */
493 ObjWrite8 (Seg->Def->AddrSize); /* Address size of the segment */
494 ObjWriteVar (Seg->FragCount); /* Number of fragments */
496 /* Now walk through the fragment list for this segment and write the
502 /* Write data depending on the type */
503 switch (Frag->Type) {
506 ObjWrite8 (FRAG_LITERAL);
507 ObjWriteVar (Frag->Len);
508 ObjWriteData (Frag->V.Data, Frag->Len);
513 case 1: ObjWrite8 (FRAG_EXPR8); break;
514 case 2: ObjWrite8 (FRAG_EXPR16); break;
515 case 3: ObjWrite8 (FRAG_EXPR24); break;
516 case 4: ObjWrite8 (FRAG_EXPR32); break;
517 default: Internal ("Invalid fragment size: %u", Frag->Len);
519 WriteExpr (Frag->V.Expr);
524 case 1: ObjWrite8 (FRAG_SEXPR8); break;
525 case 2: ObjWrite8 (FRAG_SEXPR16); break;
526 case 3: ObjWrite8 (FRAG_SEXPR24); break;
527 case 4: ObjWrite8 (FRAG_SEXPR32); break;
528 default: Internal ("Invalid fragment size: %u", Frag->Len);
530 WriteExpr (Frag->V.Expr);
534 ObjWrite8 (FRAG_FILL);
535 ObjWriteVar (Frag->Len);
539 Internal ("Invalid fragment type: %u", Frag->Type);
543 /* Write the line infos for this fragment */
544 WriteLineInfo (&Frag->LI);
550 /* Calculate the size of the data, seek back and write it */
551 EndPos = ObjGetFilePos (); /* Remember where we are */
552 DataSize = EndPos - SizePos - 4; /* Don't count size itself */
553 ObjSetFilePos (SizePos); /* Seek back to the size */
554 ObjWrite32 (DataSize); /* Write the size */
555 ObjSetFilePos (EndPos); /* Seek back to the end */
560 void InitSegments (void)
561 /* Initialize segments */
563 /* Initialize segment sizes. The segment definitions do already contain
564 * the correct values for the default case (near), so we must only change
565 * things that should be different.
567 switch (MemoryModel) {
573 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
577 CodeSegDef.AddrSize = ADDR_SIZE_FAR;
578 DataSegDef.AddrSize = ADDR_SIZE_FAR;
579 BssSegDef.AddrSize = ADDR_SIZE_FAR;
580 RODataSegDef.AddrSize = ADDR_SIZE_FAR;
584 Internal ("Invalid memory model: %d", MemoryModel);
590 void WriteSegments (void)
591 /* Write the segment data to the object file */
595 /* Tell the object file module that we're about to start the seg list */
598 /* First thing is segment count */
599 ObjWriteVar (SegmentCount);
601 /* Now walk through all segments and write them to the object file */
604 /* Write one segment */
610 /* Done writing segments */