1 /*****************************************************************************/
5 /* Segment handling for the ld65 linker */
9 /* (C) 1998-2001 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
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 /* Handle the different fragment types */
266 Frag = NewFragment (Type, ReadVar (F), Sec);
277 Frag = NewFragment (Type & FRAG_TYPEMASK, Type & FRAG_BYTEMASK, Sec);
281 /* Will allocate memory, but we don't care... */
282 Frag = NewFragment (Type, ReadVar (F), Sec);
286 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
287 GetObjFileName (O), S->Name, Type);
292 /* Now read the fragment data */
293 switch (Frag->Type) {
297 ReadData (F, Frag->LitBuf, Frag->Size);
303 Frag->Expr = ReadExpr (F, O);
308 /* Read the file position of the fragment */
309 ReadFilePos (F, &Frag->Pos);
311 /* Read the additional line info and resolve it */
312 LineInfoIndex = ReadVar (F);
315 if (LineInfoIndex >= O->LineInfoCount) {
316 Internal ("In module `%s', file `%s', line %lu: Invalid line "
317 "info with index %u (max count %u)",
319 GetSourceFileName (O, Frag->Pos.Name),
320 Frag->Pos.Line, LineInfoIndex, O->LineInfoCount);
322 /* Point from the fragment to the line info... */
323 Frag->LI = O->LineInfos[LineInfoIndex];
324 /* ...and back from the line info to the fragment */
325 CollAppend (&Frag->LI->Fragments, Frag);
328 /* Remember the module we had this fragment from */
332 CHECK (Size >= Frag->Size);
336 /* Return the section */
342 Segment* SegFind (const char* Name)
343 /* Return the given segment or NULL if not found. */
345 return SegFindInternal (Name, HashStr (Name) % HASHTAB_SIZE);
350 int IsBSSType (Segment* S)
351 /* Check if the given segment is a BSS style segment, that is, it does not
352 * contain non-zero data.
355 /* Loop over all sections */
356 Section* Sec = S->SecRoot;
358 /* Loop over all fragments */
359 Fragment* F = Sec->FragRoot;
361 if (F->Type == FRAG_LITERAL) {
362 unsigned char* Data = F->LitBuf;
363 unsigned long Count = F->Size;
369 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
370 if (GetExprVal (F->Expr) != 0) {
384 /* Dump the segments and it's contents */
390 Segment* Seg = SegRoot;
392 Section* S = Seg->SecRoot;
393 printf ("Segment: %s (%lu)\n", Seg->Name, Seg->Size);
395 Fragment* F = S->FragRoot;
396 printf (" Section:\n");
401 printf (" Literal (%lu bytes):", F->Size);
410 printf (" %02X", *Data++);
417 printf (" Expression (%lu bytes):\n", F->Size);
423 printf (" Signed expression (%lu bytes):\n", F->Size);
429 printf (" Empty space (%lu bytes)\n", F->Size);
433 Internal ("Invalid fragment type: %02X", F->Type);
445 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
446 /* Write a supposedly constant expression to the target file. Do a range
447 * check and return one of the SEG_EXPR_xxx codes.
450 static const unsigned long U_HighRange [4] = {
451 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
453 static const long S_HighRange [4] = {
454 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
456 static const long S_LowRange [4] = {
457 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
461 /* Get the expression value */
462 long Val = GetExprVal (E);
465 CHECK (Size >= 1 && Size <= 4);
467 /* Check for a range error */
469 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
471 return SEG_EXPR_RANGE_ERROR;
474 if (((unsigned long)Val) > U_HighRange [Size-1]) {
476 return SEG_EXPR_RANGE_ERROR;
480 /* Write the value to the file */
481 WriteVal (F, Val, Size);
489 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
490 /* Write the data from the given segment to a file. For expressions, F is
491 * called (see description of SegWriteFunc above).
495 unsigned long Offs = 0;
497 /* Loop over all sections in this segment */
498 Section* Sec = S->SecRoot;
502 /* If we have fill bytes, write them now */
503 WriteMult (Tgt, S->FillVal, Sec->Fill);
506 /* Loop over all fragments in this section */
507 Frag = Sec->FragRoot;
510 switch (Frag->Type) {
513 WriteData (Tgt, Frag->LitBuf, Frag->Size);
518 Sign = (Frag->Type == FRAG_SEXPR);
519 /* Call the users function and evaluate the result */
520 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
525 case SEG_EXPR_RANGE_ERROR:
526 Error ("Range error in module `%s', line %lu",
527 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
531 case SEG_EXPR_TOO_COMPLEX:
532 Error ("Expression too complex in module `%s', line %lu",
533 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
537 case SEG_EXPR_INVALID:
538 Error ("Invalid expression in module `%s', line %lu",
539 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
544 Internal ("Invalid return code from SegWriteFunc");
549 WriteMult (Tgt, S->FillVal, Frag->Size);
553 Internal ("Invalid fragment type: %02X", Frag->Type);
556 /* Update the offset */
570 static int CmpSegStart (const void* K1, const void* K2)
571 /* Compare function for qsort */
573 /* Get the real segment pointers */
574 const Segment* S1 = *(const Segment**)K1;
575 const Segment* S2 = *(const Segment**)K2;
577 /* Compare the start addresses */
578 if (S1->PC > S2->PC) {
580 } else if (S1->PC < S2->PC) {
583 /* Sort segments with equal starts by name */
584 return strcmp (S1->Name, S2->Name);
590 void PrintSegmentMap (FILE* F)
591 /* Print a segment map to the given file */
597 /* Allocate memory for the segment pool */
598 SegPool = xmalloc (SegCount * sizeof (Segment*));
600 /* Collect pointers to the segments */
605 /* Check the count for safety */
606 CHECK (I < SegCount);
608 /* Remember the pointer */
611 /* Follow the linked list */
614 /* Next array index */
617 CHECK (I == SegCount);
619 /* Sort the array by increasing start addresses */
620 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
623 fprintf (F, "Name Start End Size\n"
624 "--------------------------------------------\n");
626 /* Print the segments */
627 for (I = 0; I < SegCount; ++I) {
629 /* Get a pointer to the segment */
632 /* Print empty segments only if explicitly requested */
633 if (VerboseMap || S->Size > 0) {
634 /* Print the segment data */
635 long End = S->PC + S->Size;
637 /* Point to last element addressed */
640 fprintf (F, "%-20s %06lX %06lX %06lX\n",
641 S->Name, S->PC, End, S->Size);
645 /* Free the segment pool */
651 void CheckSegments (void)
652 /* Walk through the segment list and check if there are segments that were
653 * not written to the output file. Output an error if this is the case.
656 Segment* S = SegRoot;
658 if (S->Size > 0 && S->Dumped == 0) {
659 Error ("Missing memory area assignment for segment `%s'", S->Name);