1 /*****************************************************************************/
5 /* Segment handling for the ld65 linker */
9 /* (C) 1998-2003 Ullrich von Bassewitz */
10 /* Römerstrasse 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 /*****************************************************************************/
59 /*****************************************************************************/
61 /*****************************************************************************/
66 #define HASHTAB_SIZE 253
67 static Segment* HashTab [HASHTAB_SIZE];
69 static unsigned SegCount = 0; /* Segment count */
70 static Segment* SegRoot = 0; /* List of all segments */
74 /*****************************************************************************/
76 /*****************************************************************************/
80 static Segment* SegFindInternal (const char* Name, unsigned HashVal)
81 /* Try to find the segment with the given name, return a pointer to the
82 * segment structure, or 0 if not found.
85 Segment* S = HashTab [HashVal];
87 if (strcmp (Name, S->Name) == 0) {
99 static Segment* NewSegment (const char* Name, unsigned HashVal, unsigned char Type)
100 /* Create a new segment and initialize it */
102 /* Get the length of the symbol name */
103 unsigned Len = strlen (Name);
105 /* Allocate memory */
106 Segment* S = xmalloc (sizeof (Segment) + Len);
108 /* Initialize the fields */
119 memcpy (S->Name, Name, Len);
120 S->Name [Len] = '\0';
122 /* Insert the segment into the segment list */
127 /* Insert the segment into the segment hash list */
128 S->Next = HashTab [HashVal];
129 HashTab [HashVal] = S;
131 /* Return the new entry */
137 Segment* GetSegment (const char* Name, unsigned char Type, const char* ObjName)
138 /* Search for a segment and return an existing one. If the segment does not
139 * exist, create a new one and return that. ObjName is only used for the error
140 * message and may be NULL if the segment is linker generated.
143 /* Create a hash over the name and try to locate the segment in the table */
144 unsigned HashVal = HashStr (Name) % HASHTAB_SIZE;
145 Segment* S = SegFindInternal (Name, HashVal);
147 /* If we don't have that segment already, allocate it using the type of
151 /* Create a new segment */
152 S = NewSegment (Name, HashVal, Type);
154 /* Check if the existing segment has the requested type */
155 if (S->Type != Type) {
156 /* Allow an empty object name */
158 ObjName = "[linker generated]";
160 Error ("Module `%s': Type mismatch for segment `%s'", ObjName, Name);
164 /* Return the segment */
170 Section* NewSection (Segment* Seg, unsigned char Align, unsigned char Type)
171 /* Create a new section for the given segment */
176 /* Allocate memory */
177 Section* S = xmalloc (sizeof (Segment));
179 /* Initialize the data */
188 /* Calculate the alignment bytes needed for the section */
189 V = (0x01UL << S->Align) - 1;
190 S->Fill = (unsigned char) (((Seg->Size + V) & ~V) - Seg->Size);
192 /* Adjust the segment size and set the section offset */
193 Seg->Size += S->Fill;
194 S->Offs = Seg->Size; /* Current size is offset */
196 /* Insert the section into the segment */
197 if (Seg->SecRoot == 0) {
198 /* First section in this segment */
201 Seg->SecLast->Next = S;
205 /* Return the struct */
211 Section* ReadSection (FILE* F, ObjData* O)
212 /* Read a section from a file */
227 /* Read the alignment */
230 /* Read the segment type */
233 /* Print some data */
234 Print (stdout, 2, "Module `%s': Found segment `%s', size = %lu, align = %u, type = %u\n",
235 GetObjFileName (O), Name, Size, Align, Type);
237 /* Get the segment for this section */
238 S = GetSegment (Name, Type, GetObjFileName (O));
240 /* We have the segment and don't need the name any longer */
243 /* Allocate the section we will return later */
244 Sec = NewSection (S, Align, Type);
246 /* Set up the minimum segment alignment */
247 if (Sec->Align > S->Align) {
248 /* Section needs larger alignment, use this one */
249 S->Align = Sec->Align;
253 /* Start reading fragments from the file and insert them into the section . */
257 unsigned LineInfoIndex;
259 /* Read the fragment type */
260 unsigned char Type = Read8 (F);
262 /* Extract the check mask from the type */
263 unsigned char Check = Type & FRAG_CHECKMASK;
264 Type &= ~FRAG_CHECKMASK;
266 /* Handle the different fragment types */
270 Frag = NewFragment (Type, ReadVar (F), Sec);
281 Frag = NewFragment (Type & FRAG_TYPEMASK, Type & FRAG_BYTEMASK, Sec);
285 /* Will allocate memory, but we don't care... */
286 Frag = NewFragment (Type, ReadVar (F), Sec);
290 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
291 GetObjFileName (O), S->Name, Type);
296 /* Now read the fragment data */
297 switch (Frag->Type) {
301 ReadData (F, Frag->LitBuf, Frag->Size);
307 Frag->Expr = ReadExpr (F, O);
312 /* A check expression may follow */
313 if (Check & FRAG_CHECK_WARN) {
314 Frag->WarnExpr = ReadExpr (F, O);
316 if (Check & FRAG_CHECK_ERROR) {
317 Frag->ErrorExpr = ReadExpr (F, O);
320 /* Read the file position of the fragment */
321 ReadFilePos (F, &Frag->Pos);
323 /* Read the additional line info and resolve it */
324 LineInfoIndex = ReadVar (F);
327 if (LineInfoIndex >= O->LineInfoCount) {
328 Internal ("In module `%s', file `%s', line %lu: Invalid line "
329 "info with index %u (max count %u)",
331 GetSourceFileName (O, Frag->Pos.Name),
332 Frag->Pos.Line, LineInfoIndex, O->LineInfoCount);
334 /* Point from the fragment to the line info... */
335 Frag->LI = O->LineInfos[LineInfoIndex];
336 /* ...and back from the line info to the fragment */
337 CollAppend (&Frag->LI->Fragments, Frag);
340 /* Remember the module we had this fragment from */
344 CHECK (Size >= Frag->Size);
348 /* Return the section */
354 Segment* SegFind (const char* Name)
355 /* Return the given segment or NULL if not found. */
357 return SegFindInternal (Name, HashStr (Name) % HASHTAB_SIZE);
362 int IsBSSType (Segment* S)
363 /* Check if the given segment is a BSS style segment, that is, it does not
364 * contain non-zero data.
367 /* Loop over all sections */
368 Section* Sec = S->SecRoot;
370 /* Loop over all fragments */
371 Fragment* F = Sec->FragRoot;
373 if (F->Type == FRAG_LITERAL) {
374 unsigned char* Data = F->LitBuf;
375 unsigned long Count = F->Size;
381 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
382 if (GetExprVal (F->Expr) != 0) {
396 /* Dump the segments and it's contents */
402 Segment* Seg = SegRoot;
404 Section* S = Seg->SecRoot;
405 printf ("Segment: %s (%lu)\n", Seg->Name, Seg->Size);
407 Fragment* F = S->FragRoot;
408 printf (" Section:\n");
413 printf (" Literal (%lu bytes):", F->Size);
422 printf (" %02X", *Data++);
429 printf (" Expression (%lu bytes):\n", F->Size);
435 printf (" Signed expression (%lu bytes):\n", F->Size);
441 printf (" Empty space (%lu bytes)\n", F->Size);
445 Internal ("Invalid fragment type: %02X", F->Type);
457 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
458 /* Write a supposedly constant expression to the target file. Do a range
459 * check and return one of the SEG_EXPR_xxx codes.
462 static const unsigned long U_HighRange [4] = {
463 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
465 static const long S_HighRange [4] = {
466 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
468 static const long S_LowRange [4] = {
469 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
473 /* Get the expression value */
474 long Val = GetExprVal (E);
477 CHECK (Size >= 1 && Size <= 4);
479 /* Check for a range error */
481 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
483 return SEG_EXPR_RANGE_ERROR;
486 if (((unsigned long)Val) > U_HighRange [Size-1]) {
488 return SEG_EXPR_RANGE_ERROR;
492 /* Write the value to the file */
493 WriteVal (F, Val, Size);
501 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
502 /* Write the data from the given segment to a file. For expressions, F is
503 * called (see description of SegWriteFunc above).
507 unsigned long Offs = 0;
509 /* Loop over all sections in this segment */
510 Section* Sec = S->SecRoot;
514 /* If we have fill bytes, write them now */
515 WriteMult (Tgt, S->FillVal, Sec->Fill);
518 /* Loop over all fragments in this section */
519 Frag = Sec->FragRoot;
522 /* Do fragment alignment checks */
526 /* Output fragment data */
527 switch (Frag->Type) {
530 WriteData (Tgt, Frag->LitBuf, Frag->Size);
535 Sign = (Frag->Type == FRAG_SEXPR);
536 /* Call the users function and evaluate the result */
537 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
542 case SEG_EXPR_RANGE_ERROR:
543 Error ("Range error in module `%s', line %lu",
544 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
548 case SEG_EXPR_TOO_COMPLEX:
549 Error ("Expression too complex in module `%s', line %lu",
550 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
554 case SEG_EXPR_INVALID:
555 Error ("Invalid expression in module `%s', line %lu",
556 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
561 Internal ("Invalid return code from SegWriteFunc");
566 WriteMult (Tgt, S->FillVal, Frag->Size);
570 Internal ("Invalid fragment type: %02X", Frag->Type);
573 /* Update the offset */
587 static int CmpSegStart (const void* K1, const void* K2)
588 /* Compare function for qsort */
590 /* Get the real segment pointers */
591 const Segment* S1 = *(const Segment**)K1;
592 const Segment* S2 = *(const Segment**)K2;
594 /* Compare the start addresses */
595 if (S1->PC > S2->PC) {
597 } else if (S1->PC < S2->PC) {
600 /* Sort segments with equal starts by name */
601 return strcmp (S1->Name, S2->Name);
607 void PrintSegmentMap (FILE* F)
608 /* Print a segment map to the given file */
614 /* Allocate memory for the segment pool */
615 SegPool = xmalloc (SegCount * sizeof (Segment*));
617 /* Collect pointers to the segments */
622 /* Check the count for safety */
623 CHECK (I < SegCount);
625 /* Remember the pointer */
628 /* Follow the linked list */
631 /* Next array index */
634 CHECK (I == SegCount);
636 /* Sort the array by increasing start addresses */
637 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
640 fprintf (F, "Name Start End Size\n"
641 "--------------------------------------------\n");
643 /* Print the segments */
644 for (I = 0; I < SegCount; ++I) {
646 /* Get a pointer to the segment */
649 /* Print empty segments only if explicitly requested */
650 if (VerboseMap || S->Size > 0) {
651 /* Print the segment data */
652 long End = S->PC + S->Size;
654 /* Point to last element addressed */
657 fprintf (F, "%-20s %06lX %06lX %06lX\n",
658 S->Name, S->PC, End, S->Size);
662 /* Free the segment pool */
668 void CheckSegments (void)
669 /* Walk through the segment list and check if there are segments that were
670 * not written to the output file. Output an error if this is the case.
673 Segment* S = SegRoot;
675 if (S->Size > 0 && S->Dumped == 0) {
676 Error ("Missing memory area assignment for segment `%s'", S->Name);