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 */
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 >= CollCount (&O->LineInfos)) {
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,
285 CollCount (&O->LineInfos));
287 /* Point from the fragment to the line info... */
288 Frag->LI = CollAt (&O->LineInfos, LineInfoIndex);
289 /* ...and back from the line info to the fragment */
290 CollAppend (&Frag->LI->Fragments, Frag);
293 /* Remember the module we had this fragment from */
297 /* Return the section */
303 Segment* SegFind (unsigned Name)
304 /* Return the given segment or NULL if not found. */
306 Segment* S = HashTab[Name & HASHTAB_MASK];
308 if (Name == S->Name) {
320 int IsBSSType (Segment* S)
321 /* Check if the given segment is a BSS style segment, that is, it does not
322 * contain non-zero data.
325 /* Loop over all sections */
326 Section* Sec = S->SecRoot;
328 /* Loop over all fragments */
329 Fragment* F = Sec->FragRoot;
331 if (F->Type == FRAG_LITERAL) {
332 unsigned char* Data = F->LitBuf;
333 unsigned long Count = F->Size;
339 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
340 if (GetExprVal (F->Expr) != 0) {
354 /* Dump the segments and it's contents */
360 Segment* Seg = SegRoot;
362 Section* S = Seg->SecRoot;
363 printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
365 Fragment* F = S->FragRoot;
366 printf (" Section:\n");
371 printf (" Literal (%u bytes):", F->Size);
380 printf (" %02X", *Data++);
387 printf (" Expression (%u bytes):\n", F->Size);
389 DumpExpr (F->Expr, 0);
393 printf (" Signed expression (%u bytes):\n", F->Size);
395 DumpExpr (F->Expr, 0);
399 printf (" Empty space (%u bytes)\n", F->Size);
403 Internal ("Invalid fragment type: %02X", F->Type);
415 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
416 /* Write a supposedly constant expression to the target file. Do a range
417 * check and return one of the SEG_EXPR_xxx codes.
420 static const unsigned long U_HighRange [4] = {
421 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
423 static const long S_HighRange [4] = {
424 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
426 static const long S_LowRange [4] = {
427 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
431 /* Get the expression value */
432 long Val = GetExprVal (E);
435 CHECK (Size >= 1 && Size <= 4);
437 /* Check for a range error */
439 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
441 return SEG_EXPR_RANGE_ERROR;
444 if (((unsigned long)Val) > U_HighRange [Size-1]) {
446 return SEG_EXPR_RANGE_ERROR;
450 /* Write the value to the file */
451 WriteVal (F, Val, Size);
459 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
460 /* Write the data from the given segment to a file. For expressions, F is
461 * called (see description of SegWriteFunc above).
465 unsigned long Offs = 0;
467 /* Loop over all sections in this segment */
468 Section* Sec = S->SecRoot;
472 /* If we have fill bytes, write them now */
473 WriteMult (Tgt, S->FillVal, Sec->Fill);
476 /* Loop over all fragments in this section */
477 Frag = Sec->FragRoot;
480 /* Do fragment alignment checks */
484 /* Output fragment data */
485 switch (Frag->Type) {
488 WriteData (Tgt, Frag->LitBuf, Frag->Size);
493 Sign = (Frag->Type == FRAG_SEXPR);
494 /* Call the users function and evaluate the result */
495 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
500 case SEG_EXPR_RANGE_ERROR:
501 Error ("Range error in module `%s', line %lu",
502 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
506 case SEG_EXPR_TOO_COMPLEX:
507 Error ("Expression too complex in module `%s', line %lu",
508 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
512 case SEG_EXPR_INVALID:
513 Error ("Invalid expression in module `%s', line %lu",
514 GetSourceFileName (Frag->Obj, Frag->Pos.Name),
519 Internal ("Invalid return code from SegWriteFunc");
524 WriteMult (Tgt, S->FillVal, Frag->Size);
528 Internal ("Invalid fragment type: %02X", Frag->Type);
531 /* Update the offset */
545 static int CmpSegStart (const void* K1, const void* K2)
546 /* Compare function for qsort */
548 /* Get the real segment pointers */
549 const Segment* S1 = *(const Segment**)K1;
550 const Segment* S2 = *(const Segment**)K2;
552 /* Compare the start addresses */
553 if (S1->PC > S2->PC) {
555 } else if (S1->PC < S2->PC) {
558 /* Sort segments with equal starts by name */
559 return strcmp (GetString (S1->Name), GetString (S2->Name));
565 void PrintSegmentMap (FILE* F)
566 /* Print a segment map to the given file */
572 /* Allocate memory for the segment pool */
573 SegPool = xmalloc (SegCount * sizeof (Segment*));
575 /* Collect pointers to the segments */
580 /* Check the count for safety */
581 CHECK (I < SegCount);
583 /* Remember the pointer */
586 /* Follow the linked list */
589 /* Next array index */
592 CHECK (I == SegCount);
594 /* Sort the array by increasing start addresses */
595 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
598 fprintf (F, "Name Start End Size\n"
599 "--------------------------------------------\n");
601 /* Print the segments */
602 for (I = 0; I < SegCount; ++I) {
604 /* Get a pointer to the segment */
607 /* Print empty segments only if explicitly requested */
608 if (VerboseMap || S->Size > 0) {
609 /* Print the segment data */
610 long End = S->PC + S->Size;
612 /* Point to last element addressed */
615 fprintf (F, "%-20s %06lX %06lX %06lX\n",
616 GetString (S->Name), S->PC, End, S->Size);
620 /* Free the segment pool */
626 void PrintDbgSegments (FILE* F)
627 /* Output the segments to the debug file */
631 /* Walk over all segments */
635 /* Ignore empty segments */
638 /* Print the segment data */
639 fprintf (F, "segment\t\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s\n",
640 GetString (S->Name), S->PC, S->Size,
641 AddrSizeToStr (S->AddrSize),
642 S->ReadOnly? "ro" : "rw");
645 /* Follow the linked list */
652 void CheckSegments (void)
653 /* Walk through the segment list and check if there are segments that were
654 * not written to the output file. Output an error if this is the case.
657 Segment* S = SegRoot;
659 if (S->Size > 0 && S->Dumped == 0) {
660 Error ("Missing memory area assignment for segment `%s'",
661 GetString (S->Name));