1 /*****************************************************************************/
5 /* Segment handling for the ld65 linker */
9 /* (C) 1998-2011, 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 */
103 S->AddrSize = AddrSize;
109 /* Insert the segment into the segment list and assign the segment id */
113 S->Id = SegRoot->Id + 1;
119 /* Insert the segment into the segment hash list */
120 Hash = (S->Name & HASHTAB_MASK);
121 S->Next = HashTab[Hash];
124 /* Return the new entry */
130 Segment* GetSegment (unsigned Name, unsigned char AddrSize, const char* ObjName)
131 /* Search for a segment and return an existing one. If the segment does not
132 * exist, create a new one and return that. ObjName is only used for the error
133 * message and may be NULL if the segment is linker generated.
136 /* Try to locate the segment in the table */
137 Segment* S = SegFind (Name);
139 /* If we don't have that segment already, allocate it using the type of
143 /* Create a new segment */
144 S = NewSegment (Name, AddrSize);
146 /* Check if the existing segment has the requested address size */
147 if (S->AddrSize != AddrSize) {
148 /* Allow an empty object name */
150 ObjName = "[linker generated]";
152 Error ("Module `%s': Type mismatch for segment `%s'", ObjName,
157 /* Return the segment */
163 Section* NewSection (Segment* Seg, unsigned char Align, unsigned char AddrSize)
164 /* Create a new section for the given segment */
169 /* Allocate memory */
170 Section* S = xmalloc (sizeof (Section));
172 /* Initialize the data */
179 S->AddrSize = AddrSize;
181 /* Calculate the alignment bytes needed for the section */
182 V = (0x01UL << S->Align) - 1;
183 S->Fill = (unsigned char) (((Seg->Size + V) & ~V) - Seg->Size);
185 /* Adjust the segment size and set the section offset */
186 Seg->Size += S->Fill;
187 S->Offs = Seg->Size; /* Current size is offset */
189 /* Insert the section into the segment */
190 if (Seg->SecRoot == 0) {
191 /* First section in this segment */
194 Seg->SecLast->Next = S;
198 /* Return the struct */
204 Section* ReadSection (FILE* F, ObjData* O)
205 /* Read a section from a file */
215 /* Read the segment data */
216 (void) Read32 (F); /* File size of data */
217 Name = MakeGlobalStringId (O, ReadVar (F)); /* Segment name */
218 Size = Read32 (F); /* Size of data */
219 Align = Read8 (F); /* Alignment */
220 Type = Read8 (F); /* Segment type */
221 FragCount = ReadVar (F); /* Number of fragments */
224 /* Print some data */
225 Print (stdout, 2, "Module `%s': Found segment `%s', size = %u, align = %u, type = %u\n",
226 GetObjFileName (O), GetString (Name), Size, Align, Type);
228 /* Get the segment for this section */
229 S = GetSegment (Name, Type, GetObjFileName (O));
231 /* Allocate the section we will return later */
232 Sec = NewSection (S, Align, Type);
234 /* Set up the minimum segment alignment */
235 if (Sec->Align > S->Align) {
236 /* Section needs larger alignment, use this one */
237 S->Align = Sec->Align;
241 /* Start reading fragments from the file and insert them into the section . */
242 while (FragCount--) {
246 /* Read the fragment type */
247 unsigned char Type = Read8 (F);
249 /* Extract the check mask from the type */
250 unsigned char Bytes = Type & FRAG_BYTEMASK;
251 Type &= FRAG_TYPEMASK;
253 /* Handle the different fragment types */
257 Frag = NewFragment (Type, ReadVar (F), Sec);
258 ReadData (F, Frag->LitBuf, Frag->Size);
263 Frag = NewFragment (Type, Bytes, Sec);
264 Frag->Expr = ReadExpr (F, O);
268 /* Will allocate memory, but we don't care... */
269 Frag = NewFragment (Type, ReadVar (F), Sec);
273 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
274 GetObjFileName (O), GetString (S->Name), Type);
279 /* Read the line infos into the list of the fragment */
280 ReadLineInfoList (F, O, &Frag->LineInfos);
282 /* Resolve the back pointers */
283 FragResolveLineInfos (Frag);
285 /* Remember the module we had this fragment from */
289 /* Return the section */
295 Segment* SegFind (unsigned Name)
296 /* Return the given segment or NULL if not found. */
298 Segment* S = HashTab[Name & HASHTAB_MASK];
300 if (Name == S->Name) {
312 int IsBSSType (Segment* S)
313 /* Check if the given segment is a BSS style segment, that is, it does not
314 * contain non-zero data.
317 /* Loop over all sections */
318 Section* Sec = S->SecRoot;
320 /* Loop over all fragments */
321 Fragment* F = Sec->FragRoot;
323 if (F->Type == FRAG_LITERAL) {
324 unsigned char* Data = F->LitBuf;
325 unsigned long Count = F->Size;
331 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
332 if (GetExprVal (F->Expr) != 0) {
346 /* Dump the segments and it's contents */
352 Segment* Seg = SegRoot;
354 Section* S = Seg->SecRoot;
355 printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
357 Fragment* F = S->FragRoot;
358 printf (" Section:\n");
363 printf (" Literal (%u bytes):", F->Size);
372 printf (" %02X", *Data++);
379 printf (" Expression (%u bytes):\n", F->Size);
381 DumpExpr (F->Expr, 0);
385 printf (" Signed expression (%u bytes):\n", F->Size);
387 DumpExpr (F->Expr, 0);
391 printf (" Empty space (%u bytes)\n", F->Size);
395 Internal ("Invalid fragment type: %02X", F->Type);
407 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
408 /* Write a supposedly constant expression to the target file. Do a range
409 * check and return one of the SEG_EXPR_xxx codes.
412 static const unsigned long U_HighRange [4] = {
413 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
415 static const long S_HighRange [4] = {
416 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
418 static const long S_LowRange [4] = {
419 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
423 /* Get the expression value */
424 long Val = GetExprVal (E);
427 CHECK (Size >= 1 && Size <= 4);
429 /* Check for a range error */
431 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
433 return SEG_EXPR_RANGE_ERROR;
436 if (((unsigned long)Val) > U_HighRange [Size-1]) {
438 return SEG_EXPR_RANGE_ERROR;
442 /* Write the value to the file */
443 WriteVal (F, Val, Size);
451 void SegWrite (const char* TgtName, FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
452 /* Write the data from the given segment to a file. For expressions, F is
453 * called (see description of SegWriteFunc above).
458 unsigned long Offs = 0;
461 /* Remember the output file and offset for the segment */
462 S->OutputName = TgtName;
463 S->OutputOffs = (unsigned long) ftell (Tgt);
465 /* Loop over all sections in this segment */
470 /* If we have fill bytes, write them now */
471 WriteMult (Tgt, S->FillVal, Sec->Fill);
474 /* Loop over all fragments in this section */
475 Frag = Sec->FragRoot;
478 /* Do fragment alignment checks */
482 /* Output fragment data */
483 switch (Frag->Type) {
486 WriteData (Tgt, Frag->LitBuf, Frag->Size);
491 Sign = (Frag->Type == FRAG_SEXPR);
492 /* Call the users function and evaluate the result */
493 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
498 case SEG_EXPR_RANGE_ERROR:
499 Error ("Range error in module `%s', line %lu",
500 GetFragmentSourceName (Frag),
501 GetFragmentSourceLine (Frag));
504 case SEG_EXPR_TOO_COMPLEX:
505 Error ("Expression too complex in module `%s', line %lu",
506 GetFragmentSourceName (Frag),
507 GetFragmentSourceLine (Frag));
510 case SEG_EXPR_INVALID:
511 Error ("Invalid expression in module `%s', line %lu",
512 GetFragmentSourceName (Frag),
513 GetFragmentSourceLine (Frag));
517 Internal ("Invalid return code from SegWriteFunc");
522 WriteMult (Tgt, S->FillVal, Frag->Size);
526 Internal ("Invalid fragment type: %02X", Frag->Type);
529 /* Update the offset */
543 static int CmpSegStart (const void* K1, const void* K2)
544 /* Compare function for qsort */
546 /* Get the real segment pointers */
547 const Segment* S1 = *(const Segment**)K1;
548 const Segment* S2 = *(const Segment**)K2;
550 /* Compare the start addresses */
551 if (S1->PC > S2->PC) {
553 } else if (S1->PC < S2->PC) {
556 /* Sort segments with equal starts by name */
557 return strcmp (GetString (S1->Name), GetString (S2->Name));
563 void PrintSegmentMap (FILE* F)
564 /* Print a segment map to the given file */
570 /* Allocate memory for the segment pool */
571 SegPool = xmalloc (SegCount * sizeof (Segment*));
573 /* Collect pointers to the segments */
578 /* Check the count for safety */
579 CHECK (I < SegCount);
581 /* Remember the pointer */
584 /* Follow the linked list */
587 /* Next array index */
590 CHECK (I == SegCount);
592 /* Sort the array by increasing start addresses */
593 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
596 fprintf (F, "Name Start End Size\n"
597 "--------------------------------------------\n");
599 /* Print the segments */
600 for (I = 0; I < SegCount; ++I) {
602 /* Get a pointer to the segment */
605 /* Print empty segments only if explicitly requested */
606 if (VerboseMap || S->Size > 0) {
607 /* Print the segment data */
608 long End = S->PC + S->Size;
610 /* Point to last element addressed */
613 fprintf (F, "%-20s %06lX %06lX %06lX\n",
614 GetString (S->Name), S->PC, End, S->Size);
618 /* Free the segment pool */
624 void PrintDbgSegments (FILE* F)
625 /* Output the segments to the debug file */
627 /* Walk over all segments */
628 Segment* S = SegRoot;
631 /* Print the segment data */
633 "segment\tid=%u,name=\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s",
634 S->Id, GetString (S->Name), S->PC, S->Size,
635 AddrSizeToStr (S->AddrSize),
636 S->ReadOnly? "ro" : "rw");
638 fprintf (F, ",outputname=\"%s\",outputoffs=%lu",
639 S->OutputName, S->OutputOffs);
643 /* Follow the linked list */
650 void CheckSegments (void)
651 /* Walk through the segment list and check if there are segments that were
652 * not written to the output file. Output an error if this is the case.
655 Segment* S = SegRoot;
657 if (S->Size > 0 && S->Dumped == 0) {
658 Error ("Missing memory area assignment for segment `%s'",
659 GetString (S->Name));