1 /*****************************************************************************/
5 /* Segment handling for the ld65 linker */
9 /* (C) 1998-2003 Ullrich von Bassewitz */
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 */
207 /* Read the segment data */
208 (void) Read32 (F); /* File size of data */
209 Name = MakeGlobalStringId (O, ReadVar (F)); /* Segment name */
210 Size = Read32 (F); /* Size of data */
211 Align = Read8 (F); /* Alignment */
212 Type = Read8 (F); /* Segment type */
213 FragCount = ReadVar (F); /* Number of fragments */
216 /* Print some data */
217 Print (stdout, 2, "Module `%s': Found segment `%s', size = %u, align = %u, type = %u\n",
218 GetObjFileName (O), GetString (Name), Size, Align, Type);
220 /* Get the segment for this section */
221 S = GetSegment (Name, Type, GetObjFileName (O));
223 /* Allocate the section we will return later */
224 Sec = NewSection (S, Align, Type);
226 /* Set up the minimum segment alignment */
227 if (Sec->Align > S->Align) {
228 /* Section needs larger alignment, use this one */
229 S->Align = Sec->Align;
233 /* Start reading fragments from the file and insert them into the section . */
234 while (FragCount--) {
237 unsigned LineInfoIndex;
239 /* Read the fragment type */
240 unsigned char Type = Read8 (F);
242 /* Extract the check mask from the type */
243 unsigned char Bytes = Type & FRAG_BYTEMASK;
244 Type &= FRAG_TYPEMASK;
246 /* Handle the different fragment types */
250 Frag = NewFragment (Type, ReadVar (F), Sec);
251 ReadData (F, Frag->LitBuf, Frag->Size);
256 Frag = NewFragment (Type, Bytes, Sec);
257 Frag->Expr = ReadExpr (F, O);
261 /* Will allocate memory, but we don't care... */
262 Frag = NewFragment (Type, ReadVar (F), Sec);
266 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
267 GetObjFileName (O), GetString (S->Name), Type);
272 /* Read the file position of the fragment */
273 ReadFilePos (F, &Frag->Pos);
275 /* Read the additional line info and resolve it */
276 LineInfoIndex = ReadVar (F);
279 if (LineInfoIndex >= O->LineInfoCount) {
280 Internal ("In module `%s', file `%s', line %lu: Invalid line "
281 "info with index %u (max count %u)",
283 GetSourceFileName (O, Frag->Pos.Name),
284 Frag->Pos.Line, LineInfoIndex, O->LineInfoCount);
286 /* Point from the fragment to the line info... */
287 Frag->LI = O->LineInfos[LineInfoIndex];
288 /* ...and back from the line info to the fragment */
289 CollAppend (&Frag->LI->Fragments, Frag);
292 /* Remember the module we had this fragment from */
296 /* Return the section */
302 Segment* SegFind (unsigned Name)
303 /* Return the given segment or NULL if not found. */
305 Segment* S = HashTab[Name & HASHTAB_MASK];
307 if (Name == S->Name) {
319 int IsBSSType (Segment* S)
320 /* Check if the given segment is a BSS style segment, that is, it does not
321 * contain non-zero data.
324 /* Loop over all sections */
325 Section* Sec = S->SecRoot;
327 /* Loop over all fragments */
328 Fragment* F = Sec->FragRoot;
330 if (F->Type == FRAG_LITERAL) {
331 unsigned char* Data = F->LitBuf;
332 unsigned long Count = F->Size;
338 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
339 if (GetExprVal (F->Expr) != 0) {
353 /* Dump the segments and it's contents */
359 Segment* Seg = SegRoot;
361 Section* S = Seg->SecRoot;
362 printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
364 Fragment* F = S->FragRoot;
365 printf (" Section:\n");
370 printf (" Literal (%u bytes):", F->Size);
379 printf (" %02X", *Data++);
386 printf (" Expression (%u bytes):\n", F->Size);
388 DumpExpr (F->Expr, 0);
392 printf (" Signed expression (%u bytes):\n", F->Size);
394 DumpExpr (F->Expr, 0);
398 printf (" Empty space (%u bytes)\n", F->Size);
402 Internal ("Invalid fragment type: %02X", F->Type);
414 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
415 /* Write a supposedly constant expression to the target file. Do a range
416 * check and return one of the SEG_EXPR_xxx codes.
419 static const unsigned long U_HighRange [4] = {
420 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
422 static const long S_HighRange [4] = {
423 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
425 static const long S_LowRange [4] = {
426 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
430 /* Get the expression value */
431 long Val = GetExprVal (E);
434 CHECK (Size >= 1 && Size <= 4);
436 /* Check for a range error */
438 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
440 return SEG_EXPR_RANGE_ERROR;
443 if (((unsigned long)Val) > U_HighRange [Size-1]) {
445 return SEG_EXPR_RANGE_ERROR;
449 /* Write the value to the file */
450 WriteVal (F, Val, Size);
458 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
459 /* Write the data from the given segment to a file. For expressions, F is
460 * called (see description of SegWriteFunc above).
464 unsigned long Offs = 0;
466 /* Loop over all sections in this segment */
467 Section* Sec = S->SecRoot;
471 /* If we have fill bytes, write them now */
472 WriteMult (Tgt, S->FillVal, Sec->Fill);
475 /* Loop over all fragments in this section */
476 Frag = Sec->FragRoot;
479 /* Do fragment alignment checks */
483 /* Output fragment data */
484 switch (Frag->Type) {
487 WriteData (Tgt, Frag->LitBuf, Frag->Size);
492 Sign = (Frag->Type == FRAG_SEXPR);
493 /* Call the users function and evaluate the result */
494 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
499 case SEG_EXPR_RANGE_ERROR:
500 Error ("Range error in module `%s', line %lu",
501 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
505 case SEG_EXPR_TOO_COMPLEX:
506 Error ("Expression too complex in module `%s', line %lu",
507 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
511 case SEG_EXPR_INVALID:
512 Error ("Invalid expression in module `%s', line %lu",
513 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
518 Internal ("Invalid return code from SegWriteFunc");
523 WriteMult (Tgt, S->FillVal, Frag->Size);
527 Internal ("Invalid fragment type: %02X", Frag->Type);
530 /* Update the offset */
544 static int CmpSegStart (const void* K1, const void* K2)
545 /* Compare function for qsort */
547 /* Get the real segment pointers */
548 const Segment* S1 = *(const Segment**)K1;
549 const Segment* S2 = *(const Segment**)K2;
551 /* Compare the start addresses */
552 if (S1->PC > S2->PC) {
554 } else if (S1->PC < S2->PC) {
557 /* Sort segments with equal starts by name */
558 return strcmp (GetString (S1->Name), GetString (S2->Name));
564 void PrintSegmentMap (FILE* F)
565 /* Print a segment map to the given file */
571 /* Allocate memory for the segment pool */
572 SegPool = xmalloc (SegCount * sizeof (Segment*));
574 /* Collect pointers to the segments */
579 /* Check the count for safety */
580 CHECK (I < SegCount);
582 /* Remember the pointer */
585 /* Follow the linked list */
588 /* Next array index */
591 CHECK (I == SegCount);
593 /* Sort the array by increasing start addresses */
594 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
597 fprintf (F, "Name Start End Size\n"
598 "--------------------------------------------\n");
600 /* Print the segments */
601 for (I = 0; I < SegCount; ++I) {
603 /* Get a pointer to the segment */
606 /* Print empty segments only if explicitly requested */
607 if (VerboseMap || S->Size > 0) {
608 /* Print the segment data */
609 long End = S->PC + S->Size;
611 /* Point to last element addressed */
614 fprintf (F, "%-20s %06lX %06lX %06lX\n",
615 GetString (S->Name), S->PC, End, S->Size);
619 /* Free the segment pool */
625 void PrintDbgSegments (FILE* F)
626 /* Output the segments to the debug file */
630 /* Walk over all segments */
634 /* Ignore empty segments */
637 /* Print the segment data */
638 fprintf (F, "segment\t\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s\n",
639 GetString (S->Name), S->PC, S->Size,
640 AddrSizeToStr (S->AddrSize),
641 S->ReadOnly? "ro" : "rw");
644 /* Follow the linked list */
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'",
660 GetString (S->Name));