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;
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 */
216 /* Read the segment data */
217 (void) Read32 (F); /* File size of data */
218 Name = MakeGlobalStringId (O, ReadVar (F)); /* Segment name */
219 Size = Read32 (F); /* Size of data */
220 Align = Read8 (F); /* Alignment */
221 Type = Read8 (F); /* Segment type */
222 FragCount = ReadVar (F); /* Number of fragments */
225 /* Print some data */
226 Print (stdout, 2, "Module `%s': Found segment `%s', size = %u, align = %u, type = %u\n",
227 GetObjFileName (O), GetString (Name), Size, Align, Type);
229 /* Get the segment for this section */
230 S = GetSegment (Name, Type, GetObjFileName (O));
232 /* Allocate the section we will return later */
233 Sec = NewSection (S, Align, Type);
235 /* Set up the minimum segment alignment */
236 if (Sec->Align > S->Align) {
237 /* Section needs larger alignment, use this one */
238 S->Align = Sec->Align;
242 /* Start reading fragments from the file and insert them into the section . */
244 while (FragCount--) {
248 unsigned LineInfoIndex;
250 /* Read the fragment type */
251 unsigned char Type = Read8 (F);
253 /* Extract the check mask from the type */
254 unsigned char Bytes = Type & FRAG_BYTEMASK;
255 Type &= FRAG_TYPEMASK;
257 /* Handle the different fragment types */
261 Frag = NewFragment (Type, ReadVar (F), Sec);
262 ReadData (F, Frag->LitBuf, Frag->Size);
267 Frag = NewFragment (Type, Bytes, Sec);
268 Frag->Expr = ReadExpr (F, O);
272 /* Will allocate memory, but we don't care... */
273 Frag = NewFragment (Type, ReadVar (F), Sec);
277 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
278 GetObjFileName (O), GetString (S->Name), Type);
283 /* Read the file position of the fragment */
284 ReadFilePos (F, &Pos);
286 /* Generate a LineInfo for this fragment. First check if this fragment
287 * was generated by the same line than that before. If not, generate
290 if (LI == 0 || LI->Pos.Line != Pos.Line || LI->Pos.Col != Pos.Col ||
291 LI->Pos.Name != Pos.Name) {
292 /* We don't have a previous line info or this one is different */
293 LI = NewLineInfo (O, &Pos);
294 CollAppend (&O->LineInfos, LI);
296 AddLineInfo (Frag, LI);
298 /* Read additional line info and resolve it */
299 LineInfoIndex = ReadVar (F);
302 /* The line info index was written by the assembler and must
303 * therefore be part of the line infos read from the object file.
304 * To make sure this is true, don't compare against the count
305 * of line infos in the collection (which grows) but against the
306 * count initialized when reading from the file.
308 if (LineInfoIndex >= O->LineInfoCount) {
309 Internal ("In module `%s', file `%s', line %lu: Invalid line "
310 "info with index %u (max count %u)",
312 GetFragmentSourceName (Frag),
313 GetFragmentSourceLine (Frag),
317 /* Add line info to the fragment */
318 AddLineInfo (Frag, CollAt (&O->LineInfos, LineInfoIndex));
321 /* Remember the module we had this fragment from */
325 /* Return the section */
331 Segment* SegFind (unsigned Name)
332 /* Return the given segment or NULL if not found. */
334 Segment* S = HashTab[Name & HASHTAB_MASK];
336 if (Name == S->Name) {
348 int IsBSSType (Segment* S)
349 /* Check if the given segment is a BSS style segment, that is, it does not
350 * contain non-zero data.
353 /* Loop over all sections */
354 Section* Sec = S->SecRoot;
356 /* Loop over all fragments */
357 Fragment* F = Sec->FragRoot;
359 if (F->Type == FRAG_LITERAL) {
360 unsigned char* Data = F->LitBuf;
361 unsigned long Count = F->Size;
367 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
368 if (GetExprVal (F->Expr) != 0) {
382 /* Dump the segments and it's contents */
388 Segment* Seg = SegRoot;
390 Section* S = Seg->SecRoot;
391 printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
393 Fragment* F = S->FragRoot;
394 printf (" Section:\n");
399 printf (" Literal (%u bytes):", F->Size);
408 printf (" %02X", *Data++);
415 printf (" Expression (%u bytes):\n", F->Size);
417 DumpExpr (F->Expr, 0);
421 printf (" Signed expression (%u bytes):\n", F->Size);
423 DumpExpr (F->Expr, 0);
427 printf (" Empty space (%u bytes)\n", F->Size);
431 Internal ("Invalid fragment type: %02X", F->Type);
443 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
444 /* Write a supposedly constant expression to the target file. Do a range
445 * check and return one of the SEG_EXPR_xxx codes.
448 static const unsigned long U_HighRange [4] = {
449 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
451 static const long S_HighRange [4] = {
452 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
454 static const long S_LowRange [4] = {
455 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
459 /* Get the expression value */
460 long Val = GetExprVal (E);
463 CHECK (Size >= 1 && Size <= 4);
465 /* Check for a range error */
467 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
469 return SEG_EXPR_RANGE_ERROR;
472 if (((unsigned long)Val) > U_HighRange [Size-1]) {
474 return SEG_EXPR_RANGE_ERROR;
478 /* Write the value to the file */
479 WriteVal (F, Val, Size);
487 void SegWrite (const char* TgtName, FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
488 /* Write the data from the given segment to a file. For expressions, F is
489 * called (see description of SegWriteFunc above).
494 unsigned long Offs = 0;
497 /* Remember the output file and offset for the segment */
498 S->OutputName = TgtName;
499 S->OutputOffs = (unsigned long) ftell (Tgt);
501 /* Loop over all sections in this segment */
506 /* If we have fill bytes, write them now */
507 WriteMult (Tgt, S->FillVal, Sec->Fill);
510 /* Loop over all fragments in this section */
511 Frag = Sec->FragRoot;
514 /* Do fragment alignment checks */
518 /* Output fragment data */
519 switch (Frag->Type) {
522 WriteData (Tgt, Frag->LitBuf, Frag->Size);
527 Sign = (Frag->Type == FRAG_SEXPR);
528 /* Call the users function and evaluate the result */
529 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
534 case SEG_EXPR_RANGE_ERROR:
535 Error ("Range error in module `%s', line %lu",
536 GetFragmentSourceName (Frag),
537 GetFragmentSourceLine (Frag));
540 case SEG_EXPR_TOO_COMPLEX:
541 Error ("Expression too complex in module `%s', line %lu",
542 GetFragmentSourceName (Frag),
543 GetFragmentSourceLine (Frag));
546 case SEG_EXPR_INVALID:
547 Error ("Invalid expression in module `%s', line %lu",
548 GetFragmentSourceName (Frag),
549 GetFragmentSourceLine (Frag));
553 Internal ("Invalid return code from SegWriteFunc");
558 WriteMult (Tgt, S->FillVal, Frag->Size);
562 Internal ("Invalid fragment type: %02X", Frag->Type);
565 /* Update the offset */
579 static int CmpSegStart (const void* K1, const void* K2)
580 /* Compare function for qsort */
582 /* Get the real segment pointers */
583 const Segment* S1 = *(const Segment**)K1;
584 const Segment* S2 = *(const Segment**)K2;
586 /* Compare the start addresses */
587 if (S1->PC > S2->PC) {
589 } else if (S1->PC < S2->PC) {
592 /* Sort segments with equal starts by name */
593 return strcmp (GetString (S1->Name), GetString (S2->Name));
599 void PrintSegmentMap (FILE* F)
600 /* Print a segment map to the given file */
606 /* Allocate memory for the segment pool */
607 SegPool = xmalloc (SegCount * sizeof (Segment*));
609 /* Collect pointers to the segments */
614 /* Check the count for safety */
615 CHECK (I < SegCount);
617 /* Remember the pointer */
620 /* Follow the linked list */
623 /* Next array index */
626 CHECK (I == SegCount);
628 /* Sort the array by increasing start addresses */
629 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
632 fprintf (F, "Name Start End Size\n"
633 "--------------------------------------------\n");
635 /* Print the segments */
636 for (I = 0; I < SegCount; ++I) {
638 /* Get a pointer to the segment */
641 /* Print empty segments only if explicitly requested */
642 if (VerboseMap || S->Size > 0) {
643 /* Print the segment data */
644 long End = S->PC + S->Size;
646 /* Point to last element addressed */
649 fprintf (F, "%-20s %06lX %06lX %06lX\n",
650 GetString (S->Name), S->PC, End, S->Size);
654 /* Free the segment pool */
660 void PrintDbgSegments (FILE* F)
661 /* Output the segments to the debug file */
663 /* Walk over all segments */
664 Segment* S = SegRoot;
667 /* Print the segment data */
669 "segment\tid=%u,name=\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s",
670 S->Id, GetString (S->Name), S->PC, S->Size,
671 AddrSizeToStr (S->AddrSize),
672 S->ReadOnly? "ro" : "rw");
674 fprintf (F, ",outputname=\"%s\",outputoffs=%lu",
675 S->OutputName, S->OutputOffs);
679 /* Follow the linked list */
686 void CheckSegments (void)
687 /* Walk through the segment list and check if there are segments that were
688 * not written to the output file. Output an error if this is the case.
691 Segment* S = SegRoot;
693 if (S->Size > 0 && S->Dumped == 0) {
694 Error ("Missing memory area assignment for segment `%s'",
695 GetString (S->Name));