1 /*****************************************************************************/
5 /* Segment handling for the ld65 linker */
9 /* (C) 1998-2010, Ullrich von Bassewitz */
10 /* Roemerstrasse 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 AddrSize)
84 /* Create a new segment and initialize it */
89 Segment* S = xmalloc (sizeof (Segment));
91 /* Initialize the fields */
101 S->AddrSize = AddrSize;
106 /* Insert the segment into the segment list */
111 /* Insert the segment into the segment hash list */
112 Hash = (S->Name & HASHTAB_MASK);
113 S->Next = HashTab[Hash];
116 /* Return the new entry */
122 Segment* GetSegment (unsigned Name, unsigned char AddrSize, const char* ObjName)
123 /* Search for a segment and return an existing one. If the segment does not
124 * exist, create a new one and return that. ObjName is only used for the error
125 * message and may be NULL if the segment is linker generated.
128 /* Try to locate the segment in the table */
129 Segment* S = SegFind (Name);
131 /* If we don't have that segment already, allocate it using the type of
135 /* Create a new segment */
136 S = NewSegment (Name, AddrSize);
138 /* Check if the existing segment has the requested address size */
139 if (S->AddrSize != AddrSize) {
140 /* Allow an empty object name */
142 ObjName = "[linker generated]";
144 Error ("Module `%s': Type mismatch for segment `%s'", ObjName,
149 /* Return the segment */
155 Section* NewSection (Segment* Seg, unsigned char Align, unsigned char AddrSize)
156 /* Create a new section for the given segment */
161 /* Allocate memory */
162 Section* S = xmalloc (sizeof (Section));
164 /* Initialize the data */
171 S->AddrSize = AddrSize;
173 /* Calculate the alignment bytes needed for the section */
174 V = (0x01UL << S->Align) - 1;
175 S->Fill = (unsigned char) (((Seg->Size + V) & ~V) - Seg->Size);
177 /* Adjust the segment size and set the section offset */
178 Seg->Size += S->Fill;
179 S->Offs = Seg->Size; /* Current size is offset */
181 /* Insert the section into the segment */
182 if (Seg->SecRoot == 0) {
183 /* First section in this segment */
186 Seg->SecLast->Next = S;
190 /* Return the struct */
196 Section* ReadSection (FILE* F, ObjData* O)
197 /* Read a section from a file */
208 /* Read the segment data */
209 (void) Read32 (F); /* File size of data */
210 Name = MakeGlobalStringId (O, ReadVar (F)); /* Segment name */
211 Size = Read32 (F); /* Size of data */
212 Align = Read8 (F); /* Alignment */
213 Type = Read8 (F); /* Segment type */
214 FragCount = ReadVar (F); /* Number of fragments */
217 /* Print some data */
218 Print (stdout, 2, "Module `%s': Found segment `%s', size = %u, align = %u, type = %u\n",
219 GetObjFileName (O), GetString (Name), Size, Align, Type);
221 /* Get the segment for this section */
222 S = GetSegment (Name, Type, GetObjFileName (O));
224 /* Allocate the section we will return later */
225 Sec = NewSection (S, Align, Type);
227 /* Set up the minimum segment alignment */
228 if (Sec->Align > S->Align) {
229 /* Section needs larger alignment, use this one */
230 S->Align = Sec->Align;
234 /* Start reading fragments from the file and insert them into the section . */
236 while (FragCount--) {
240 unsigned LineInfoIndex;
242 /* Read the fragment type */
243 unsigned char Type = Read8 (F);
245 /* Extract the check mask from the type */
246 unsigned char Bytes = Type & FRAG_BYTEMASK;
247 Type &= FRAG_TYPEMASK;
249 /* Handle the different fragment types */
253 Frag = NewFragment (Type, ReadVar (F), Sec);
254 ReadData (F, Frag->LitBuf, Frag->Size);
259 Frag = NewFragment (Type, Bytes, Sec);
260 Frag->Expr = ReadExpr (F, O);
264 /* Will allocate memory, but we don't care... */
265 Frag = NewFragment (Type, ReadVar (F), Sec);
269 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
270 GetObjFileName (O), GetString (S->Name), Type);
275 /* Read the file position of the fragment */
276 ReadFilePos (F, &Pos);
278 /* Generate a LineInfo for this fragment. First check if this fragment
279 * was generated by the same line than that before. If not, generate
282 if (LI == 0 || LI->Pos.Line != Pos.Line || LI->Pos.Col != Pos.Col ||
283 LI->Pos.Name != Pos.Name) {
284 /* We don't have a previous line info or this one is different */
285 LI = NewLineInfo (O, &Pos);
286 CollAppend (&O->LineInfos, LI);
288 AddLineInfo (Frag, LI);
290 /* Read additional line info and resolve it */
291 LineInfoIndex = ReadVar (F);
294 /* The line info index was written by the assembler and must
295 * therefore be part of the line infos read from the object file.
296 * To make sure this is true, don't compare against the count
297 * of line infos in the collection (which grows) but against the
298 * count initialized when reading from the file.
300 if (LineInfoIndex >= O->LineInfoCount) {
301 Internal ("In module `%s', file `%s', line %lu: Invalid line "
302 "info with index %u (max count %u)",
304 GetFragmentSourceName (Frag),
305 GetFragmentSourceLine (Frag),
309 /* Add line info to the fragment */
310 AddLineInfo (Frag, CollAt (&O->LineInfos, LineInfoIndex));
313 /* Remember the module we had this fragment from */
317 /* Return the section */
323 Segment* SegFind (unsigned Name)
324 /* Return the given segment or NULL if not found. */
326 Segment* S = HashTab[Name & HASHTAB_MASK];
328 if (Name == S->Name) {
340 int IsBSSType (Segment* S)
341 /* Check if the given segment is a BSS style segment, that is, it does not
342 * contain non-zero data.
345 /* Loop over all sections */
346 Section* Sec = S->SecRoot;
348 /* Loop over all fragments */
349 Fragment* F = Sec->FragRoot;
351 if (F->Type == FRAG_LITERAL) {
352 unsigned char* Data = F->LitBuf;
353 unsigned long Count = F->Size;
359 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
360 if (GetExprVal (F->Expr) != 0) {
374 /* Dump the segments and it's contents */
380 Segment* Seg = SegRoot;
382 Section* S = Seg->SecRoot;
383 printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
385 Fragment* F = S->FragRoot;
386 printf (" Section:\n");
391 printf (" Literal (%u bytes):", F->Size);
400 printf (" %02X", *Data++);
407 printf (" Expression (%u bytes):\n", F->Size);
409 DumpExpr (F->Expr, 0);
413 printf (" Signed expression (%u bytes):\n", F->Size);
415 DumpExpr (F->Expr, 0);
419 printf (" Empty space (%u bytes)\n", F->Size);
423 Internal ("Invalid fragment type: %02X", F->Type);
435 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
436 /* Write a supposedly constant expression to the target file. Do a range
437 * check and return one of the SEG_EXPR_xxx codes.
440 static const unsigned long U_HighRange [4] = {
441 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
443 static const long S_HighRange [4] = {
444 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
446 static const long S_LowRange [4] = {
447 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
451 /* Get the expression value */
452 long Val = GetExprVal (E);
455 CHECK (Size >= 1 && Size <= 4);
457 /* Check for a range error */
459 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
461 return SEG_EXPR_RANGE_ERROR;
464 if (((unsigned long)Val) > U_HighRange [Size-1]) {
466 return SEG_EXPR_RANGE_ERROR;
470 /* Write the value to the file */
471 WriteVal (F, Val, Size);
479 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
480 /* Write the data from the given segment to a file. For expressions, F is
481 * called (see description of SegWriteFunc above).
485 unsigned long Offs = 0;
487 /* Loop over all sections in this segment */
488 Section* Sec = S->SecRoot;
492 /* If we have fill bytes, write them now */
493 WriteMult (Tgt, S->FillVal, Sec->Fill);
496 /* Loop over all fragments in this section */
497 Frag = Sec->FragRoot;
500 /* Do fragment alignment checks */
504 /* Output fragment data */
505 switch (Frag->Type) {
508 WriteData (Tgt, Frag->LitBuf, Frag->Size);
513 Sign = (Frag->Type == FRAG_SEXPR);
514 /* Call the users function and evaluate the result */
515 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
520 case SEG_EXPR_RANGE_ERROR:
521 Error ("Range error in module `%s', line %lu",
522 GetFragmentSourceName (Frag),
523 GetFragmentSourceLine (Frag));
526 case SEG_EXPR_TOO_COMPLEX:
527 Error ("Expression too complex in module `%s', line %lu",
528 GetFragmentSourceName (Frag),
529 GetFragmentSourceLine (Frag));
532 case SEG_EXPR_INVALID:
533 Error ("Invalid expression in module `%s', line %lu",
534 GetFragmentSourceName (Frag),
535 GetFragmentSourceLine (Frag));
539 Internal ("Invalid return code from SegWriteFunc");
544 WriteMult (Tgt, S->FillVal, Frag->Size);
548 Internal ("Invalid fragment type: %02X", Frag->Type);
551 /* Update the offset */
565 static int CmpSegStart (const void* K1, const void* K2)
566 /* Compare function for qsort */
568 /* Get the real segment pointers */
569 const Segment* S1 = *(const Segment**)K1;
570 const Segment* S2 = *(const Segment**)K2;
572 /* Compare the start addresses */
573 if (S1->PC > S2->PC) {
575 } else if (S1->PC < S2->PC) {
578 /* Sort segments with equal starts by name */
579 return strcmp (GetString (S1->Name), GetString (S2->Name));
585 void PrintSegmentMap (FILE* F)
586 /* Print a segment map to the given file */
592 /* Allocate memory for the segment pool */
593 SegPool = xmalloc (SegCount * sizeof (Segment*));
595 /* Collect pointers to the segments */
600 /* Check the count for safety */
601 CHECK (I < SegCount);
603 /* Remember the pointer */
606 /* Follow the linked list */
609 /* Next array index */
612 CHECK (I == SegCount);
614 /* Sort the array by increasing start addresses */
615 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
618 fprintf (F, "Name Start End Size\n"
619 "--------------------------------------------\n");
621 /* Print the segments */
622 for (I = 0; I < SegCount; ++I) {
624 /* Get a pointer to the segment */
627 /* Print empty segments only if explicitly requested */
628 if (VerboseMap || S->Size > 0) {
629 /* Print the segment data */
630 long End = S->PC + S->Size;
632 /* Point to last element addressed */
635 fprintf (F, "%-20s %06lX %06lX %06lX\n",
636 GetString (S->Name), S->PC, End, S->Size);
640 /* Free the segment pool */
646 void PrintDbgSegments (FILE* F)
647 /* Output the segments to the debug file */
651 /* Walk over all segments */
655 /* Ignore empty segments */
658 /* Print the segment data */
659 fprintf (F, "segment\t\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s\n",
660 GetString (S->Name), S->PC, S->Size,
661 AddrSizeToStr (S->AddrSize),
662 S->ReadOnly? "ro" : "rw");
665 /* Follow the linked list */
672 void CheckSegments (void)
673 /* Walk through the segment list and check if there are segments that were
674 * not written to the output file. Output an error if this is the case.
677 Segment* S = SegRoot;
679 if (S->Size > 0 && S->Dumped == 0) {
680 Error ("Missing memory area assignment for segment `%s'",
681 GetString (S->Name));