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 /*****************************************************************************/
62 /*****************************************************************************/
64 /*****************************************************************************/
69 #define HASHTAB_MASK 0x3FU
70 #define HASHTAB_SIZE (HASHTAB_MASK + 1)
71 static Segment* HashTab[HASHTAB_SIZE];
73 /* List of all segments */
74 static Collection SegmentList = STATIC_COLLECTION_INITIALIZER;
78 /*****************************************************************************/
80 /*****************************************************************************/
84 static Segment* NewSegment (unsigned Name, unsigned char AddrSize)
85 /* Create a new segment and initialize it */
90 Segment* S = xmalloc (sizeof (Segment));
92 /* Initialize the fields */
104 S->AddrSize = AddrSize;
110 /* Insert the segment into the segment list and assign the segment id */
111 S->Id = CollCount (&SegmentList);
112 CollAppend (&SegmentList, S);
114 /* Insert the segment into the segment hash list */
115 Hash = (S->Name & HASHTAB_MASK);
116 S->Next = HashTab[Hash];
119 /* Return the new entry */
125 Segment* GetSegment (unsigned Name, unsigned char AddrSize, const char* ObjName)
126 /* Search for a segment and return an existing one. If the segment does not
127 * exist, create a new one and return that. ObjName is only used for the error
128 * message and may be NULL if the segment is linker generated.
131 /* Try to locate the segment in the table */
132 Segment* S = SegFind (Name);
134 /* If we don't have that segment already, allocate it using the type of
138 /* Create a new segment */
139 S = NewSegment (Name, AddrSize);
141 /* Check if the existing segment has the requested address size */
142 if (S->AddrSize != AddrSize) {
143 /* Allow an empty object name */
145 ObjName = "[linker generated]";
147 Error ("Module `%s': Type mismatch for segment `%s'", ObjName,
152 /* Return the segment */
158 Section* NewSection (Segment* Seg, unsigned char Align, unsigned char AddrSize)
159 /* Create a new section for the given segment */
164 /* Allocate memory */
165 Section* S = xmalloc (sizeof (Section));
167 /* Initialize the data */
175 S->AddrSize = AddrSize;
177 /* Calculate the alignment bytes needed for the section */
178 V = (0x01UL << S->Align) - 1;
179 S->Fill = (((Seg->Size + V) & ~V) - Seg->Size);
181 /* Adjust the segment size and set the section offset */
182 Seg->Size += S->Fill;
183 S->Offs = Seg->Size; /* Current size is offset */
185 /* Insert the section into the segment */
186 if (Seg->SecRoot == 0) {
187 /* First section in this segment */
190 Seg->SecLast->Next = S;
194 /* Return the struct */
200 Section* ReadSection (FILE* F, ObjData* O)
201 /* Read a section from a file */
211 /* Read the segment data */
212 (void) Read32 (F); /* File size of data */
213 Name = MakeGlobalStringId (O, ReadVar (F)); /* Segment name */
214 Size = Read32 (F); /* Size of data */
215 Align = Read8 (F); /* Alignment */
216 Type = Read8 (F); /* Segment type */
217 FragCount = ReadVar (F); /* Number of fragments */
220 /* Print some data */
221 Print (stdout, 2, "Module `%s': Found segment `%s', size = %u, align = %u, type = %u\n",
222 GetObjFileName (O), GetString (Name), Size, Align, Type);
224 /* Get the segment for this section */
225 S = GetSegment (Name, Type, GetObjFileName (O));
227 /* Allocate the section we will return later */
228 Sec = NewSection (S, Align, Type);
230 /* Remember the object file this section was from */
233 /* Set up the minimum segment alignment */
234 if (Sec->Align > S->Align) {
235 /* Section needs larger alignment, use this one */
236 S->Align = Sec->Align;
240 /* Start reading fragments from the file and insert them into the section . */
241 while (FragCount--) {
245 /* Read the fragment type */
246 unsigned char Type = Read8 (F);
248 /* Extract the check mask from the type */
249 unsigned char Bytes = Type & FRAG_BYTEMASK;
250 Type &= FRAG_TYPEMASK;
252 /* Handle the different fragment types */
256 Frag = NewFragment (Type, ReadVar (F), Sec);
257 ReadData (F, Frag->LitBuf, Frag->Size);
262 Frag = NewFragment (Type, Bytes, Sec);
263 Frag->Expr = ReadExpr (F, O);
267 /* Will allocate memory, but we don't care... */
268 Frag = NewFragment (Type, ReadVar (F), Sec);
272 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
273 GetObjFileName (O), GetString (S->Name), Type);
278 /* Read the line infos into the list of the fragment */
279 ReadLineInfoList (F, O, &Frag->LineInfos);
281 /* Resolve the back pointers */
282 FragResolveLineInfos (Frag);
284 /* Remember the module we had this fragment from */
288 /* Return the section */
294 Segment* SegFind (unsigned Name)
295 /* Return the given segment or NULL if not found. */
297 Segment* S = HashTab[Name & HASHTAB_MASK];
299 if (Name == S->Name) {
311 int IsBSSType (Segment* S)
312 /* Check if the given segment is a BSS style segment, that is, it does not
313 * contain non-zero data.
316 /* Loop over all sections */
317 Section* Sec = S->SecRoot;
319 /* Loop over all fragments */
320 Fragment* F = Sec->FragRoot;
322 if (F->Type == FRAG_LITERAL) {
323 unsigned char* Data = F->LitBuf;
324 unsigned long Count = F->Size;
330 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
331 if (GetExprVal (F->Expr) != 0) {
345 /* Dump the segments and it's contents */
351 for (I = 0; I < CollCount (&SegmentList); ++I) {
352 const Segment* Seg = CollConstAt (&SegmentList, I);
353 Section* S = Seg->SecRoot;
354 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);
406 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
407 /* Write a supposedly constant expression to the target file. Do a range
408 * check and return one of the SEG_EXPR_xxx codes.
411 static const unsigned long U_HighRange [4] = {
412 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
414 static const long S_HighRange [4] = {
415 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
417 static const long S_LowRange [4] = {
418 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
422 /* Get the expression value */
423 long Val = GetExprVal (E);
426 CHECK (Size >= 1 && Size <= 4);
428 /* Check for a range error */
430 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
432 return SEG_EXPR_RANGE_ERROR;
435 if (((unsigned long)Val) > U_HighRange [Size-1]) {
437 return SEG_EXPR_RANGE_ERROR;
441 /* Write the value to the file */
442 WriteVal (F, Val, Size);
450 void SegWrite (const char* TgtName, FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
451 /* Write the data from the given segment to a file. For expressions, F is
452 * called (see description of SegWriteFunc above).
457 unsigned long Offs = 0;
460 /* Remember the output file and offset for the segment */
461 S->OutputName = TgtName;
462 S->OutputOffs = (unsigned long) ftell (Tgt);
464 /* Loop over all sections in this segment */
469 /* Output were this section is from */
470 Print (stdout, 2, " Section from \"%s\"\n", GetObjFileName (Sec->Obj));
472 /* If we have fill bytes, write them now */
473 Print (stdout, 2, " Filling 0x%lx bytes with 0x%02x\n",
474 Sec->Fill, S->FillVal);
475 WriteMult (Tgt, S->FillVal, Sec->Fill);
478 /* Loop over all fragments in this section */
479 Frag = Sec->FragRoot;
482 /* Do fragment alignment checks */
486 /* Output fragment data */
487 switch (Frag->Type) {
490 WriteData (Tgt, Frag->LitBuf, Frag->Size);
495 Sign = (Frag->Type == FRAG_SEXPR);
496 /* Call the users function and evaluate the result */
497 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
502 case SEG_EXPR_RANGE_ERROR:
503 Error ("Range error in module `%s', line %lu",
504 GetFragmentSourceName (Frag),
505 GetFragmentSourceLine (Frag));
508 case SEG_EXPR_TOO_COMPLEX:
509 Error ("Expression too complex in module `%s', line %lu",
510 GetFragmentSourceName (Frag),
511 GetFragmentSourceLine (Frag));
514 case SEG_EXPR_INVALID:
515 Error ("Invalid expression in module `%s', line %lu",
516 GetFragmentSourceName (Frag),
517 GetFragmentSourceLine (Frag));
521 Internal ("Invalid return code from SegWriteFunc");
526 WriteMult (Tgt, S->FillVal, Frag->Size);
530 Internal ("Invalid fragment type: %02X", Frag->Type);
533 /* Update the offset */
534 Print (stdout, 2, " Fragment with 0x%x bytes\n",
549 static int CmpSegStart (const void* K1, const void* K2)
550 /* Compare function for qsort */
552 /* Get the real segment pointers */
553 const Segment* S1 = *(const Segment**)K1;
554 const Segment* S2 = *(const Segment**)K2;
556 /* Compare the start addresses */
557 if (S1->PC > S2->PC) {
559 } else if (S1->PC < S2->PC) {
562 /* Sort segments with equal starts by name */
563 return strcmp (GetString (S1->Name), GetString (S2->Name));
569 void PrintSegmentMap (FILE* F)
570 /* Print a segment map to the given file */
573 /* Allocate memory for the segment pool */
574 Segment** SegPool = xmalloc (CollCount (&SegmentList) * sizeof (Segment*));
576 /* Copy the segment pointers */
578 for (I = 0; I < CollCount (&SegmentList); ++I) {
579 SegPool[I] = CollAtUnchecked (&SegmentList, I);
582 /* Sort the array by increasing start addresses */
583 qsort (SegPool, CollCount (&SegmentList), sizeof (Segment*), CmpSegStart);
586 fprintf (F, "Name Start End Size\n"
587 "--------------------------------------------\n");
589 /* Print the segments */
590 for (I = 0; I < CollCount (&SegmentList); ++I) {
592 /* Get a pointer to the segment */
593 Segment* S = SegPool[I];
595 /* Print empty segments only if explicitly requested */
596 if (VerboseMap || S->Size > 0) {
597 /* Print the segment data */
598 long End = S->PC + S->Size;
600 /* Point to last element addressed */
603 fprintf (F, "%-20s %06lX %06lX %06lX\n",
604 GetString (S->Name), S->PC, End, S->Size);
608 /* Free the segment pool */
614 void PrintDbgSegments (FILE* F)
615 /* Output the segments to the debug file */
617 /* Walk over all segments */
619 for (I = 0; I < CollCount (&SegmentList); ++I) {
621 /* Get the next segment */
622 const Segment* S = CollAtUnchecked (&SegmentList, I);
624 /* Print the segment data */
626 "seg\tid=%u,name=\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s",
627 S->Id, GetString (S->Name), S->PC, S->Size,
628 AddrSizeToStr (S->AddrSize),
629 S->ReadOnly? "ro" : "rw");
631 fprintf (F, ",oname=\"%s\",ooffs=%lu",
632 S->OutputName, S->OutputOffs);
640 void CheckSegments (void)
641 /* Walk through the segment list and check if there are segments that were
642 * not written to the output file. Output an error if this is the case.
646 for (I = 0; I < CollCount (&SegmentList); ++I) {
648 /* Get the next segment */
649 const Segment* S = CollAtUnchecked (&SegmentList, I);
652 if (S->Size > 0 && S->Dumped == 0) {
653 Error ("Missing memory area assignment for segment `%s'",
654 GetString (S->Name));