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 */
222 /* Read the segment data */
223 (void) Read32 (F); /* File size of data */
224 Name = ReadStr (F); /* Segment name */
225 Size = Read32 (F); /* Size of data */
226 Align = Read8 (F); /* Alignment */
227 Type = Read8 (F); /* Segment type */
228 FragCount = ReadVar (F); /* Number of fragments */
231 /* Print some data */
232 Print (stdout, 2, "Module `%s': Found segment `%s', size = %u, align = %u, type = %u\n",
233 GetObjFileName (O), Name, Size, Align, Type);
235 /* Get the segment for this section */
236 S = GetSegment (Name, Type, GetObjFileName (O));
238 /* We have the segment and don't need the name any longer */
241 /* Allocate the section we will return later */
242 Sec = NewSection (S, Align, Type);
244 /* Set up the minimum segment alignment */
245 if (Sec->Align > S->Align) {
246 /* Section needs larger alignment, use this one */
247 S->Align = Sec->Align;
251 /* Start reading fragments from the file and insert them into the section . */
252 while (FragCount--) {
255 unsigned LineInfoIndex;
257 /* Read the fragment type */
258 unsigned char Type = Read8 (F);
260 /* Extract the check mask from the type */
261 unsigned char Check = Type & FRAG_CHECKMASK;
262 unsigned char Bytes = Type & FRAG_BYTEMASK;
263 Type &= FRAG_TYPEMASK;
265 /* Handle the different fragment types */
269 Frag = NewFragment (Type, ReadVar (F), Sec);
270 ReadData (F, Frag->LitBuf, Frag->Size);
275 Frag = NewFragment (Type, Bytes, Sec);
276 Frag->Expr = ReadExpr (F, O);
280 /* Will allocate memory, but we don't care... */
281 Frag = NewFragment (Type, ReadVar (F), Sec);
285 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
286 GetObjFileName (O), S->Name, Type);
291 /* A list of check expressions may follow */
294 /* Read the number of expressions that follow */
295 unsigned Count = ReadVar (F);
297 /* Read the expressions */
304 /* Read the file position of the fragment */
305 ReadFilePos (F, &Frag->Pos);
307 /* Read the additional line info and resolve it */
308 LineInfoIndex = ReadVar (F);
311 if (LineInfoIndex >= O->LineInfoCount) {
312 Internal ("In module `%s', file `%s', line %lu: Invalid line "
313 "info with index %u (max count %u)",
315 GetSourceFileName (O, Frag->Pos.Name),
316 Frag->Pos.Line, LineInfoIndex, O->LineInfoCount);
318 /* Point from the fragment to the line info... */
319 Frag->LI = O->LineInfos[LineInfoIndex];
320 /* ...and back from the line info to the fragment */
321 CollAppend (&Frag->LI->Fragments, Frag);
324 /* Remember the module we had this fragment from */
328 /* Return the section */
334 Segment* SegFind (const char* Name)
335 /* Return the given segment or NULL if not found. */
337 return SegFindInternal (Name, HashStr (Name) % HASHTAB_SIZE);
342 int IsBSSType (Segment* S)
343 /* Check if the given segment is a BSS style segment, that is, it does not
344 * contain non-zero data.
347 /* Loop over all sections */
348 Section* Sec = S->SecRoot;
350 /* Loop over all fragments */
351 Fragment* F = Sec->FragRoot;
353 if (F->Type == FRAG_LITERAL) {
354 unsigned char* Data = F->LitBuf;
355 unsigned long Count = F->Size;
361 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
362 if (GetExprVal (F->Expr) != 0) {
376 /* Dump the segments and it's contents */
382 Segment* Seg = SegRoot;
384 Section* S = Seg->SecRoot;
385 printf ("Segment: %s (%lu)\n", Seg->Name, Seg->Size);
387 Fragment* F = S->FragRoot;
388 printf (" Section:\n");
393 printf (" Literal (%u bytes):", F->Size);
402 printf (" %02X", *Data++);
409 printf (" Expression (%u bytes):\n", F->Size);
415 printf (" Signed expression (%u bytes):\n", F->Size);
421 printf (" Empty space (%u bytes)\n", F->Size);
425 Internal ("Invalid fragment type: %02X", F->Type);
437 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
438 /* Write a supposedly constant expression to the target file. Do a range
439 * check and return one of the SEG_EXPR_xxx codes.
442 static const unsigned long U_HighRange [4] = {
443 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
445 static const long S_HighRange [4] = {
446 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
448 static const long S_LowRange [4] = {
449 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
453 /* Get the expression value */
454 long Val = GetExprVal (E);
457 CHECK (Size >= 1 && Size <= 4);
459 /* Check for a range error */
461 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
463 return SEG_EXPR_RANGE_ERROR;
466 if (((unsigned long)Val) > U_HighRange [Size-1]) {
468 return SEG_EXPR_RANGE_ERROR;
472 /* Write the value to the file */
473 WriteVal (F, Val, Size);
481 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
482 /* Write the data from the given segment to a file. For expressions, F is
483 * called (see description of SegWriteFunc above).
487 unsigned long Offs = 0;
489 /* Loop over all sections in this segment */
490 Section* Sec = S->SecRoot;
494 /* If we have fill bytes, write them now */
495 WriteMult (Tgt, S->FillVal, Sec->Fill);
498 /* Loop over all fragments in this section */
499 Frag = Sec->FragRoot;
502 /* Do fragment alignment checks */
506 /* Output fragment data */
507 switch (Frag->Type) {
510 WriteData (Tgt, Frag->LitBuf, Frag->Size);
515 Sign = (Frag->Type == FRAG_SEXPR);
516 /* Call the users function and evaluate the result */
517 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
522 case SEG_EXPR_RANGE_ERROR:
523 Error ("Range error in module `%s', line %lu",
524 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
528 case SEG_EXPR_TOO_COMPLEX:
529 Error ("Expression too complex in module `%s', line %lu",
530 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
534 case SEG_EXPR_INVALID:
535 Error ("Invalid expression in module `%s', line %lu",
536 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
541 Internal ("Invalid return code from SegWriteFunc");
546 WriteMult (Tgt, S->FillVal, Frag->Size);
550 Internal ("Invalid fragment type: %02X", Frag->Type);
553 /* Update the offset */
567 static int CmpSegStart (const void* K1, const void* K2)
568 /* Compare function for qsort */
570 /* Get the real segment pointers */
571 const Segment* S1 = *(const Segment**)K1;
572 const Segment* S2 = *(const Segment**)K2;
574 /* Compare the start addresses */
575 if (S1->PC > S2->PC) {
577 } else if (S1->PC < S2->PC) {
580 /* Sort segments with equal starts by name */
581 return strcmp (S1->Name, S2->Name);
587 void PrintSegmentMap (FILE* F)
588 /* Print a segment map to the given file */
594 /* Allocate memory for the segment pool */
595 SegPool = xmalloc (SegCount * sizeof (Segment*));
597 /* Collect pointers to the segments */
602 /* Check the count for safety */
603 CHECK (I < SegCount);
605 /* Remember the pointer */
608 /* Follow the linked list */
611 /* Next array index */
614 CHECK (I == SegCount);
616 /* Sort the array by increasing start addresses */
617 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
620 fprintf (F, "Name Start End Size\n"
621 "--------------------------------------------\n");
623 /* Print the segments */
624 for (I = 0; I < SegCount; ++I) {
626 /* Get a pointer to the segment */
629 /* Print empty segments only if explicitly requested */
630 if (VerboseMap || S->Size > 0) {
631 /* Print the segment data */
632 long End = S->PC + S->Size;
634 /* Point to last element addressed */
637 fprintf (F, "%-20s %06lX %06lX %06lX\n",
638 S->Name, S->PC, End, S->Size);
642 /* Free the segment pool */
648 void CheckSegments (void)
649 /* Walk through the segment list and check if there are segments that were
650 * not written to the output file. Output an error if this is the case.
653 Segment* S = SegRoot;
655 if (S->Size > 0 && S->Dumped == 0) {
656 Error ("Missing memory area assignment for segment `%s'", S->Name);