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 */
103 S->AddrSize = AddrSize;
108 /* Insert the segment into the segment list and assign the segment id */
112 S->Id = SegRoot->Id + 1;
118 /* Insert the segment into the segment hash list */
119 Hash = (S->Name & HASHTAB_MASK);
120 S->Next = HashTab[Hash];
123 /* Return the new entry */
129 Segment* GetSegment (unsigned Name, unsigned char AddrSize, const char* ObjName)
130 /* Search for a segment and return an existing one. If the segment does not
131 * exist, create a new one and return that. ObjName is only used for the error
132 * message and may be NULL if the segment is linker generated.
135 /* Try to locate the segment in the table */
136 Segment* S = SegFind (Name);
138 /* If we don't have that segment already, allocate it using the type of
142 /* Create a new segment */
143 S = NewSegment (Name, AddrSize);
145 /* Check if the existing segment has the requested address size */
146 if (S->AddrSize != AddrSize) {
147 /* Allow an empty object name */
149 ObjName = "[linker generated]";
151 Error ("Module `%s': Type mismatch for segment `%s'", ObjName,
156 /* Return the segment */
162 Section* NewSection (Segment* Seg, unsigned char Align, unsigned char AddrSize)
163 /* Create a new section for the given segment */
168 /* Allocate memory */
169 Section* S = xmalloc (sizeof (Section));
171 /* Initialize the data */
178 S->AddrSize = AddrSize;
180 /* Calculate the alignment bytes needed for the section */
181 V = (0x01UL << S->Align) - 1;
182 S->Fill = (unsigned char) (((Seg->Size + V) & ~V) - Seg->Size);
184 /* Adjust the segment size and set the section offset */
185 Seg->Size += S->Fill;
186 S->Offs = Seg->Size; /* Current size is offset */
188 /* Insert the section into the segment */
189 if (Seg->SecRoot == 0) {
190 /* First section in this segment */
193 Seg->SecLast->Next = S;
197 /* Return the struct */
203 Section* ReadSection (FILE* F, ObjData* O)
204 /* 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 . */
243 while (FragCount--) {
247 unsigned LineInfoIndex;
249 /* Read the fragment type */
250 unsigned char Type = Read8 (F);
252 /* Extract the check mask from the type */
253 unsigned char Bytes = Type & FRAG_BYTEMASK;
254 Type &= FRAG_TYPEMASK;
256 /* Handle the different fragment types */
260 Frag = NewFragment (Type, ReadVar (F), Sec);
261 ReadData (F, Frag->LitBuf, Frag->Size);
266 Frag = NewFragment (Type, Bytes, Sec);
267 Frag->Expr = ReadExpr (F, O);
271 /* Will allocate memory, but we don't care... */
272 Frag = NewFragment (Type, ReadVar (F), Sec);
276 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
277 GetObjFileName (O), GetString (S->Name), Type);
282 /* Read the file position of the fragment */
283 ReadFilePos (F, &Pos);
285 /* Generate a LineInfo for this fragment. First check if this fragment
286 * was generated by the same line than that before. If not, generate
289 if (LI == 0 || LI->Pos.Line != Pos.Line || LI->Pos.Col != Pos.Col ||
290 LI->Pos.Name != Pos.Name) {
291 /* We don't have a previous line info or this one is different */
292 LI = NewLineInfo (O, &Pos);
293 CollAppend (&O->LineInfos, LI);
295 AddLineInfo (Frag, LI);
297 /* Read additional line info and resolve it */
298 LineInfoIndex = ReadVar (F);
301 /* The line info index was written by the assembler and must
302 * therefore be part of the line infos read from the object file.
303 * To make sure this is true, don't compare against the count
304 * of line infos in the collection (which grows) but against the
305 * count initialized when reading from the file.
307 if (LineInfoIndex >= O->LineInfoCount) {
308 Internal ("In module `%s', file `%s', line %lu: Invalid line "
309 "info with index %u (max count %u)",
311 GetFragmentSourceName (Frag),
312 GetFragmentSourceLine (Frag),
316 /* Add line info to the fragment */
317 AddLineInfo (Frag, CollAt (&O->LineInfos, LineInfoIndex));
320 /* Remember the module we had this fragment from */
324 /* Return the section */
330 Segment* SegFind (unsigned Name)
331 /* Return the given segment or NULL if not found. */
333 Segment* S = HashTab[Name & HASHTAB_MASK];
335 if (Name == S->Name) {
347 int IsBSSType (Segment* S)
348 /* Check if the given segment is a BSS style segment, that is, it does not
349 * contain non-zero data.
352 /* Loop over all sections */
353 Section* Sec = S->SecRoot;
355 /* Loop over all fragments */
356 Fragment* F = Sec->FragRoot;
358 if (F->Type == FRAG_LITERAL) {
359 unsigned char* Data = F->LitBuf;
360 unsigned long Count = F->Size;
366 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
367 if (GetExprVal (F->Expr) != 0) {
381 /* Dump the segments and it's contents */
387 Segment* Seg = SegRoot;
389 Section* S = Seg->SecRoot;
390 printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
392 Fragment* F = S->FragRoot;
393 printf (" Section:\n");
398 printf (" Literal (%u bytes):", F->Size);
407 printf (" %02X", *Data++);
414 printf (" Expression (%u bytes):\n", F->Size);
416 DumpExpr (F->Expr, 0);
420 printf (" Signed expression (%u bytes):\n", F->Size);
422 DumpExpr (F->Expr, 0);
426 printf (" Empty space (%u bytes)\n", F->Size);
430 Internal ("Invalid fragment type: %02X", F->Type);
442 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
443 /* Write a supposedly constant expression to the target file. Do a range
444 * check and return one of the SEG_EXPR_xxx codes.
447 static const unsigned long U_HighRange [4] = {
448 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
450 static const long S_HighRange [4] = {
451 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
453 static const long S_LowRange [4] = {
454 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
458 /* Get the expression value */
459 long Val = GetExprVal (E);
462 CHECK (Size >= 1 && Size <= 4);
464 /* Check for a range error */
466 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
468 return SEG_EXPR_RANGE_ERROR;
471 if (((unsigned long)Val) > U_HighRange [Size-1]) {
473 return SEG_EXPR_RANGE_ERROR;
477 /* Write the value to the file */
478 WriteVal (F, Val, Size);
486 void SegWrite (const char* TgtName, FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
487 /* Write the data from the given segment to a file. For expressions, F is
488 * called (see description of SegWriteFunc above).
493 unsigned long Offs = 0;
496 /* Remember the output file and offset for the segment */
497 S->OutputName = TgtName;
498 S->OutputOffs = (unsigned long) ftell (Tgt);
500 /* Loop over all sections in this segment */
505 /* If we have fill bytes, write them now */
506 WriteMult (Tgt, S->FillVal, Sec->Fill);
509 /* Loop over all fragments in this section */
510 Frag = Sec->FragRoot;
513 /* Do fragment alignment checks */
517 /* Output fragment data */
518 switch (Frag->Type) {
521 WriteData (Tgt, Frag->LitBuf, Frag->Size);
526 Sign = (Frag->Type == FRAG_SEXPR);
527 /* Call the users function and evaluate the result */
528 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
533 case SEG_EXPR_RANGE_ERROR:
534 Error ("Range error in module `%s', line %lu",
535 GetFragmentSourceName (Frag),
536 GetFragmentSourceLine (Frag));
539 case SEG_EXPR_TOO_COMPLEX:
540 Error ("Expression too complex in module `%s', line %lu",
541 GetFragmentSourceName (Frag),
542 GetFragmentSourceLine (Frag));
545 case SEG_EXPR_INVALID:
546 Error ("Invalid expression in module `%s', line %lu",
547 GetFragmentSourceName (Frag),
548 GetFragmentSourceLine (Frag));
552 Internal ("Invalid return code from SegWriteFunc");
557 WriteMult (Tgt, S->FillVal, Frag->Size);
561 Internal ("Invalid fragment type: %02X", Frag->Type);
564 /* Update the offset */
578 static int CmpSegStart (const void* K1, const void* K2)
579 /* Compare function for qsort */
581 /* Get the real segment pointers */
582 const Segment* S1 = *(const Segment**)K1;
583 const Segment* S2 = *(const Segment**)K2;
585 /* Compare the start addresses */
586 if (S1->PC > S2->PC) {
588 } else if (S1->PC < S2->PC) {
591 /* Sort segments with equal starts by name */
592 return strcmp (GetString (S1->Name), GetString (S2->Name));
598 void PrintSegmentMap (FILE* F)
599 /* Print a segment map to the given file */
605 /* Allocate memory for the segment pool */
606 SegPool = xmalloc (SegCount * sizeof (Segment*));
608 /* Collect pointers to the segments */
613 /* Check the count for safety */
614 CHECK (I < SegCount);
616 /* Remember the pointer */
619 /* Follow the linked list */
622 /* Next array index */
625 CHECK (I == SegCount);
627 /* Sort the array by increasing start addresses */
628 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
631 fprintf (F, "Name Start End Size\n"
632 "--------------------------------------------\n");
634 /* Print the segments */
635 for (I = 0; I < SegCount; ++I) {
637 /* Get a pointer to the segment */
640 /* Print empty segments only if explicitly requested */
641 if (VerboseMap || S->Size > 0) {
642 /* Print the segment data */
643 long End = S->PC + S->Size;
645 /* Point to last element addressed */
648 fprintf (F, "%-20s %06lX %06lX %06lX\n",
649 GetString (S->Name), S->PC, End, S->Size);
653 /* Free the segment pool */
659 void PrintDbgSegments (FILE* F)
660 /* Output the segments to the debug file */
662 /* Walk over all segments */
663 Segment* S = SegRoot;
666 /* Print the segment data */
668 "segment\tid=%u,name=\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s",
669 S->Id, GetString (S->Name), S->PC, S->Size,
670 AddrSizeToStr (S->AddrSize),
671 S->ReadOnly? "ro" : "rw");
673 fprintf (F, ",outputname=\"%s\",outputoffs=%lu",
674 S->OutputName, S->OutputOffs);
678 /* Follow the linked list */
685 void CheckSegments (void)
686 /* Walk through the segment list and check if there are segments that were
687 * not written to the output file. Output an error if this is the case.
690 Segment* S = SegRoot;
692 if (S->Size > 0 && S->Dumped == 0) {
693 Error ("Missing memory area assignment for segment `%s'",
694 GetString (S->Name));