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 Bytes = Type & FRAG_BYTEMASK;
242 Type &= FRAG_TYPEMASK;
244 /* Handle the different fragment types */
248 Frag = NewFragment (Type, ReadVar (F), Sec);
249 ReadData (F, Frag->LitBuf, Frag->Size);
254 Frag = NewFragment (Type, Bytes, Sec);
255 Frag->Expr = ReadExpr (F, O);
259 /* Will allocate memory, but we don't care... */
260 Frag = NewFragment (Type, ReadVar (F), Sec);
264 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
265 GetObjFileName (O), GetString (S->Name), Type);
270 /* Read the file position of the fragment */
271 ReadFilePos (F, &Frag->Pos);
273 /* Read the additional line info and resolve it */
274 LineInfoIndex = ReadVar (F);
277 if (LineInfoIndex >= O->LineInfoCount) {
278 Internal ("In module `%s', file `%s', line %lu: Invalid line "
279 "info with index %u (max count %u)",
281 GetSourceFileName (O, Frag->Pos.Name),
282 Frag->Pos.Line, LineInfoIndex, O->LineInfoCount);
284 /* Point from the fragment to the line info... */
285 Frag->LI = O->LineInfos[LineInfoIndex];
286 /* ...and back from the line info to the fragment */
287 CollAppend (&Frag->LI->Fragments, Frag);
290 /* Remember the module we had this fragment from */
294 /* Return the section */
300 Segment* SegFind (unsigned Name)
301 /* Return the given segment or NULL if not found. */
303 Segment* S = HashTab[Name & HASHTAB_MASK];
305 if (Name == S->Name) {
317 int IsBSSType (Segment* S)
318 /* Check if the given segment is a BSS style segment, that is, it does not
319 * contain non-zero data.
322 /* Loop over all sections */
323 Section* Sec = S->SecRoot;
325 /* Loop over all fragments */
326 Fragment* F = Sec->FragRoot;
328 if (F->Type == FRAG_LITERAL) {
329 unsigned char* Data = F->LitBuf;
330 unsigned long Count = F->Size;
336 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
337 if (GetExprVal (F->Expr) != 0) {
351 /* Dump the segments and it's contents */
357 Segment* Seg = SegRoot;
359 Section* S = Seg->SecRoot;
360 printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
362 Fragment* F = S->FragRoot;
363 printf (" Section:\n");
368 printf (" Literal (%u bytes):", F->Size);
377 printf (" %02X", *Data++);
384 printf (" Expression (%u bytes):\n", F->Size);
390 printf (" Signed expression (%u bytes):\n", F->Size);
396 printf (" Empty space (%u bytes)\n", F->Size);
400 Internal ("Invalid fragment type: %02X", F->Type);
412 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
413 /* Write a supposedly constant expression to the target file. Do a range
414 * check and return one of the SEG_EXPR_xxx codes.
417 static const unsigned long U_HighRange [4] = {
418 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
420 static const long S_HighRange [4] = {
421 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
423 static const long S_LowRange [4] = {
424 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
428 /* Get the expression value */
429 long Val = GetExprVal (E);
432 CHECK (Size >= 1 && Size <= 4);
434 /* Check for a range error */
436 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
438 return SEG_EXPR_RANGE_ERROR;
441 if (((unsigned long)Val) > U_HighRange [Size-1]) {
443 return SEG_EXPR_RANGE_ERROR;
447 /* Write the value to the file */
448 WriteVal (F, Val, Size);
456 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
457 /* Write the data from the given segment to a file. For expressions, F is
458 * called (see description of SegWriteFunc above).
462 unsigned long Offs = 0;
464 /* Loop over all sections in this segment */
465 Section* Sec = S->SecRoot;
469 /* If we have fill bytes, write them now */
470 WriteMult (Tgt, S->FillVal, Sec->Fill);
473 /* Loop over all fragments in this section */
474 Frag = Sec->FragRoot;
477 /* Do fragment alignment checks */
481 /* Output fragment data */
482 switch (Frag->Type) {
485 WriteData (Tgt, Frag->LitBuf, Frag->Size);
490 Sign = (Frag->Type == FRAG_SEXPR);
491 /* Call the users function and evaluate the result */
492 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
497 case SEG_EXPR_RANGE_ERROR:
498 Error ("Range error in module `%s', line %lu",
499 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
503 case SEG_EXPR_TOO_COMPLEX:
504 Error ("Expression too complex in module `%s', line %lu",
505 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
509 case SEG_EXPR_INVALID:
510 Error ("Invalid expression in module `%s', line %lu",
511 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
516 Internal ("Invalid return code from SegWriteFunc");
521 WriteMult (Tgt, S->FillVal, Frag->Size);
525 Internal ("Invalid fragment type: %02X", Frag->Type);
528 /* Update the offset */
542 static int CmpSegStart (const void* K1, const void* K2)
543 /* Compare function for qsort */
545 /* Get the real segment pointers */
546 const Segment* S1 = *(const Segment**)K1;
547 const Segment* S2 = *(const Segment**)K2;
549 /* Compare the start addresses */
550 if (S1->PC > S2->PC) {
552 } else if (S1->PC < S2->PC) {
555 /* Sort segments with equal starts by name */
556 return strcmp (GetString (S1->Name), GetString (S2->Name));
562 void PrintSegmentMap (FILE* F)
563 /* Print a segment map to the given file */
569 /* Allocate memory for the segment pool */
570 SegPool = xmalloc (SegCount * sizeof (Segment*));
572 /* Collect pointers to the segments */
577 /* Check the count for safety */
578 CHECK (I < SegCount);
580 /* Remember the pointer */
583 /* Follow the linked list */
586 /* Next array index */
589 CHECK (I == SegCount);
591 /* Sort the array by increasing start addresses */
592 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
595 fprintf (F, "Name Start End Size\n"
596 "--------------------------------------------\n");
598 /* Print the segments */
599 for (I = 0; I < SegCount; ++I) {
601 /* Get a pointer to the segment */
604 /* Print empty segments only if explicitly requested */
605 if (VerboseMap || S->Size > 0) {
606 /* Print the segment data */
607 long End = S->PC + S->Size;
609 /* Point to last element addressed */
612 fprintf (F, "%-20s %06lX %06lX %06lX\n",
613 GetString (S->Name), S->PC, End, S->Size);
617 /* Free the segment pool */
623 void CheckSegments (void)
624 /* Walk through the segment list and check if there are segments that were
625 * not written to the output file. Output an error if this is the case.
628 Segment* S = SegRoot;
630 if (S->Size > 0 && S->Dumped == 0) {
631 Error ("Missing memory area assignment for segment `%s'",
632 GetString (S->Name));