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 /*****************************************************************************/
61 /*****************************************************************************/
63 /*****************************************************************************/
68 #define HASHTAB_MASK 0x3FU
69 #define HASHTAB_SIZE (HASHTAB_MASK + 1)
70 static Segment* HashTab [HASHTAB_SIZE];
72 static unsigned SegCount = 0; /* Segment count */
73 static Segment* SegRoot = 0; /* List of all segments */
77 /*****************************************************************************/
79 /*****************************************************************************/
83 static Segment* NewSegment (unsigned Name, unsigned char Type)
84 /* Create a new segment and initialize it */
89 Segment* S = xmalloc (sizeof (Segment));
91 /* Initialize the fields */
104 /* Insert the segment into the segment list */
109 /* Insert the segment into the segment hash list */
110 Hash = (S->Name & HASHTAB_MASK);
111 S->Next = HashTab[Hash];
114 /* Return the new entry */
120 Segment* GetSegment (unsigned Name, unsigned char Type, const char* ObjName)
121 /* Search for a segment and return an existing one. If the segment does not
122 * exist, create a new one and return that. ObjName is only used for the error
123 * message and may be NULL if the segment is linker generated.
126 /* Try to locate the segment in the table */
127 Segment* S = SegFind (Name);
129 /* If we don't have that segment already, allocate it using the type of
133 /* Create a new segment */
134 S = NewSegment (Name, Type);
136 /* Check if the existing segment has the requested type */
137 if (S->Type != Type) {
138 /* Allow an empty object name */
140 ObjName = "[linker generated]";
142 Error ("Module `%s': Type mismatch for segment `%s'", ObjName,
147 /* Return the segment */
153 Section* NewSection (Segment* Seg, unsigned char Align, unsigned char Type)
154 /* Create a new section for the given segment */
159 /* Allocate memory */
160 Section* S = xmalloc (sizeof (Section));
162 /* Initialize the data */
171 /* Calculate the alignment bytes needed for the section */
172 V = (0x01UL << S->Align) - 1;
173 S->Fill = (unsigned char) (((Seg->Size + V) & ~V) - Seg->Size);
175 /* Adjust the segment size and set the section offset */
176 Seg->Size += S->Fill;
177 S->Offs = Seg->Size; /* Current size is offset */
179 /* Insert the section into the segment */
180 if (Seg->SecRoot == 0) {
181 /* First section in this segment */
184 Seg->SecLast->Next = S;
188 /* Return the struct */
194 Section* ReadSection (FILE* F, ObjData* O)
195 /* Read a section from a file */
205 /* Read the segment data */
206 (void) Read32 (F); /* File size of data */
207 Name = MakeGlobalStringId (O, ReadVar (F)); /* Segment name */
208 Size = Read32 (F); /* Size of data */
209 Align = Read8 (F); /* Alignment */
210 Type = Read8 (F); /* Segment type */
211 FragCount = ReadVar (F); /* Number of fragments */
214 /* Print some data */
215 Print (stdout, 2, "Module `%s': Found segment `%s', size = %u, align = %u, type = %u\n",
216 GetObjFileName (O), GetString (Name), Size, Align, Type);
218 /* Get the segment for this section */
219 S = GetSegment (Name, Type, GetObjFileName (O));
221 /* Allocate the section we will return later */
222 Sec = NewSection (S, Align, Type);
224 /* Set up the minimum segment alignment */
225 if (Sec->Align > S->Align) {
226 /* Section needs larger alignment, use this one */
227 S->Align = Sec->Align;
231 /* Start reading fragments from the file and insert them into the section . */
232 while (FragCount--) {
235 unsigned LineInfoIndex;
237 /* Read the fragment type */
238 unsigned char Type = Read8 (F);
240 /* Extract the check mask from the type */
241 unsigned char Check = Type & FRAG_CHECKMASK;
242 unsigned char Bytes = Type & FRAG_BYTEMASK;
243 Type &= FRAG_TYPEMASK;
245 /* Handle the different fragment types */
249 Frag = NewFragment (Type, ReadVar (F), Sec);
250 ReadData (F, Frag->LitBuf, Frag->Size);
255 Frag = NewFragment (Type, Bytes, Sec);
256 Frag->Expr = ReadExpr (F, O);
260 /* Will allocate memory, but we don't care... */
261 Frag = NewFragment (Type, ReadVar (F), Sec);
265 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
266 GetObjFileName (O), GetString (S->Name), Type);
271 /* A list of check expressions may follow */
274 /* Read the number of expressions that follow */
275 unsigned Count = ReadVar (F);
277 /* Read the expressions */
283 /* Read the file position of the fragment */
284 ReadFilePos (F, &Frag->Pos);
286 /* Read the additional line info and resolve it */
287 LineInfoIndex = ReadVar (F);
290 if (LineInfoIndex >= O->LineInfoCount) {
291 Internal ("In module `%s', file `%s', line %lu: Invalid line "
292 "info with index %u (max count %u)",
294 GetSourceFileName (O, Frag->Pos.Name),
295 Frag->Pos.Line, LineInfoIndex, O->LineInfoCount);
297 /* Point from the fragment to the line info... */
298 Frag->LI = O->LineInfos[LineInfoIndex];
299 /* ...and back from the line info to the fragment */
300 CollAppend (&Frag->LI->Fragments, Frag);
303 /* Remember the module we had this fragment from */
307 /* Return the section */
313 Segment* SegFind (unsigned Name)
314 /* Return the given segment or NULL if not found. */
316 Segment* S = HashTab[Name & HASHTAB_MASK];
318 if (Name == S->Name) {
330 int IsBSSType (Segment* S)
331 /* Check if the given segment is a BSS style segment, that is, it does not
332 * contain non-zero data.
335 /* Loop over all sections */
336 Section* Sec = S->SecRoot;
338 /* Loop over all fragments */
339 Fragment* F = Sec->FragRoot;
341 if (F->Type == FRAG_LITERAL) {
342 unsigned char* Data = F->LitBuf;
343 unsigned long Count = F->Size;
349 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
350 if (GetExprVal (F->Expr) != 0) {
364 /* Dump the segments and it's contents */
370 Segment* Seg = SegRoot;
372 Section* S = Seg->SecRoot;
373 printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
375 Fragment* F = S->FragRoot;
376 printf (" Section:\n");
381 printf (" Literal (%u bytes):", F->Size);
390 printf (" %02X", *Data++);
397 printf (" Expression (%u bytes):\n", F->Size);
403 printf (" Signed expression (%u bytes):\n", F->Size);
409 printf (" Empty space (%u bytes)\n", F->Size);
413 Internal ("Invalid fragment type: %02X", F->Type);
425 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
426 /* Write a supposedly constant expression to the target file. Do a range
427 * check and return one of the SEG_EXPR_xxx codes.
430 static const unsigned long U_HighRange [4] = {
431 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
433 static const long S_HighRange [4] = {
434 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
436 static const long S_LowRange [4] = {
437 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
441 /* Get the expression value */
442 long Val = GetExprVal (E);
445 CHECK (Size >= 1 && Size <= 4);
447 /* Check for a range error */
449 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
451 return SEG_EXPR_RANGE_ERROR;
454 if (((unsigned long)Val) > U_HighRange [Size-1]) {
456 return SEG_EXPR_RANGE_ERROR;
460 /* Write the value to the file */
461 WriteVal (F, Val, Size);
469 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
470 /* Write the data from the given segment to a file. For expressions, F is
471 * called (see description of SegWriteFunc above).
475 unsigned long Offs = 0;
477 /* Loop over all sections in this segment */
478 Section* Sec = S->SecRoot;
482 /* If we have fill bytes, write them now */
483 WriteMult (Tgt, S->FillVal, Sec->Fill);
486 /* Loop over all fragments in this section */
487 Frag = Sec->FragRoot;
490 /* Do fragment alignment checks */
494 /* Output fragment data */
495 switch (Frag->Type) {
498 WriteData (Tgt, Frag->LitBuf, Frag->Size);
503 Sign = (Frag->Type == FRAG_SEXPR);
504 /* Call the users function and evaluate the result */
505 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
510 case SEG_EXPR_RANGE_ERROR:
511 Error ("Range error in module `%s', line %lu",
512 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
516 case SEG_EXPR_TOO_COMPLEX:
517 Error ("Expression too complex in module `%s', line %lu",
518 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
522 case SEG_EXPR_INVALID:
523 Error ("Invalid expression in module `%s', line %lu",
524 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
529 Internal ("Invalid return code from SegWriteFunc");
534 WriteMult (Tgt, S->FillVal, Frag->Size);
538 Internal ("Invalid fragment type: %02X", Frag->Type);
541 /* Update the offset */
555 static int CmpSegStart (const void* K1, const void* K2)
556 /* Compare function for qsort */
558 /* Get the real segment pointers */
559 const Segment* S1 = *(const Segment**)K1;
560 const Segment* S2 = *(const Segment**)K2;
562 /* Compare the start addresses */
563 if (S1->PC > S2->PC) {
565 } else if (S1->PC < S2->PC) {
568 /* Sort segments with equal starts by name */
569 return strcmp (GetString (S1->Name), GetString (S2->Name));
575 void PrintSegmentMap (FILE* F)
576 /* Print a segment map to the given file */
582 /* Allocate memory for the segment pool */
583 SegPool = xmalloc (SegCount * sizeof (Segment*));
585 /* Collect pointers to the segments */
590 /* Check the count for safety */
591 CHECK (I < SegCount);
593 /* Remember the pointer */
596 /* Follow the linked list */
599 /* Next array index */
602 CHECK (I == SegCount);
604 /* Sort the array by increasing start addresses */
605 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
608 fprintf (F, "Name Start End Size\n"
609 "--------------------------------------------\n");
611 /* Print the segments */
612 for (I = 0; I < SegCount; ++I) {
614 /* Get a pointer to the segment */
617 /* Print empty segments only if explicitly requested */
618 if (VerboseMap || S->Size > 0) {
619 /* Print the segment data */
620 long End = S->PC + S->Size;
622 /* Point to last element addressed */
625 fprintf (F, "%-20s %06lX %06lX %06lX\n",
626 GetString (S->Name), S->PC, End, S->Size);
630 /* Free the segment pool */
636 void CheckSegments (void)
637 /* Walk through the segment list and check if there are segments that were
638 * not written to the output file. Output an error if this is the case.
641 Segment* S = SegRoot;
643 if (S->Size > 0 && S->Dumped == 0) {
644 Error ("Missing memory area assignment for segment `%s'",
645 GetString (S->Name));