1 /*****************************************************************************/
5 /* Segment handling for the ld65 linker */
9 /* (C) 1998-2012, 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 /*****************************************************************************/
41 #include "alignment.h"
64 /*****************************************************************************/
66 /*****************************************************************************/
71 #define HASHTAB_MASK 0x3FU
72 #define HASHTAB_SIZE (HASHTAB_MASK + 1)
73 static Segment* HashTab[HASHTAB_SIZE];
75 /* List of all segments */
76 static Collection SegmentList = STATIC_COLLECTION_INITIALIZER;
80 /*****************************************************************************/
82 /*****************************************************************************/
86 static Segment* NewSegment (unsigned Name, unsigned char AddrSize)
87 /* Create a new segment and initialize it */
92 Segment* S = xmalloc (sizeof (Segment));
94 /* Initialize the fields */
97 S->Flags = SEG_FLAG_NONE;
98 S->Sections = EmptyCollection;
106 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 long Alignment, unsigned char AddrSize)
159 /* Create a new section for the given segment */
161 /* Allocate memory */
162 Section* S = xmalloc (sizeof (Section));
164 /* Initialize the data */
171 S->Alignment= Alignment;
172 S->AddrSize = AddrSize;
174 /* Calculate the alignment bytes needed for the section */
175 S->Fill = AlignCount (Seg->Size, S->Alignment);
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 CollAppend (&Seg->Sections, S);
184 /* Return the struct */
190 Section* ReadSection (FILE* F, ObjData* O)
191 /* Read a section from a file */
196 unsigned long Alignment;
202 /* Read the segment data */
203 (void) Read32 (F); /* File size of data */
204 Name = MakeGlobalStringId (O, ReadVar (F)); /* Segment name */
205 Flags = ReadVar (F); /* Segment flags (currently unused) */
206 Size = ReadVar (F); /* Size of data */
207 Alignment = ReadVar (F); /* Alignment */
208 Type = Read8 (F); /* Segment type */
209 FragCount = ReadVar (F); /* Number of fragments */
212 /* Print some data */
214 "Module `%s': Found segment `%s', size = %u, alignment = %lu, type = %u\n",
215 GetObjFileName (O), GetString (Name), Size, Alignment, Type);
217 /* Get the segment for this section */
218 S = GetSegment (Name, Type, GetObjFileName (O));
220 /* Allocate the section we will return later */
221 Sec = NewSection (S, Alignment, Type);
223 /* Remember the object file this section was from */
226 /* Set up the combined segment alignment */
227 if (Sec->Alignment > 1) {
228 Alignment = LeastCommonMultiple (S->Alignment, Sec->Alignment);
229 if (Alignment > MAX_ALIGNMENT) {
230 Error ("Combined alignment for segment `%s' is %lu which exceeds "
231 "%lu. Last module requiring alignment was `%s'.",
232 GetString (Name), Alignment, MAX_ALIGNMENT,
234 } else if (Alignment >= LARGE_ALIGNMENT) {
235 Warning ("Combined alignment for segment `%s' is suspiciously "
236 "large (%lu). Last module requiring alignment was `%s'.",
237 GetString (Name), Alignment, GetObjFileName (O));
239 S->Alignment = Alignment;
242 /* Start reading fragments from the file and insert them into the section . */
243 while (FragCount--) {
247 /* Read the fragment type */
248 unsigned char Type = Read8 (F);
250 /* Extract the check mask from the type */
251 unsigned char Bytes = Type & FRAG_BYTEMASK;
252 Type &= FRAG_TYPEMASK;
254 /* Handle the different fragment types */
258 Frag = NewFragment (Type, ReadVar (F), Sec);
259 ReadData (F, Frag->LitBuf, Frag->Size);
264 Frag = NewFragment (Type, Bytes, Sec);
265 Frag->Expr = ReadExpr (F, O);
269 /* Will allocate memory, but we don't care... */
270 Frag = NewFragment (Type, ReadVar (F), Sec);
274 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
275 GetObjFileName (O), GetString (S->Name), Type);
280 /* Read the line infos into the list of the fragment */
281 ReadLineInfoList (F, O, &Frag->LineInfos);
283 /* Remember the module we had this fragment from */
287 /* Return the section */
293 Segment* SegFind (unsigned Name)
294 /* Return the given segment or NULL if not found. */
296 Segment* S = HashTab[Name & HASHTAB_MASK];
298 if (Name == S->Name) {
310 int IsBSSType (Segment* S)
311 /* Check if the given segment is a BSS style segment, that is, it does not
312 * contain non-zero data.
315 /* Loop over all sections */
317 for (I = 0; I < CollCount (&S->Sections); ++I) {
319 /* Get the next section */
320 Section* Sec = CollAtUnchecked (&S->Sections, I);
322 /* Loop over all fragments */
323 Fragment* F = Sec->FragRoot;
325 if (F->Type == FRAG_LITERAL) {
326 unsigned char* Data = F->LitBuf;
327 unsigned long Count = F->Size;
333 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
334 if (GetExprVal (F->Expr) != 0) {
347 /* Dump the segments and it's contents */
353 for (I = 0; I < CollCount (&SegmentList); ++I) {
354 Segment* Seg = CollAtUnchecked (&SegmentList, I);
355 printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
356 for (J = 0; J < CollCount (&Seg->Sections); ++J) {
357 Section* S = CollAtUnchecked (&Seg->Sections, J);
359 Fragment* F = S->FragRoot;
360 printf (" Section:\n");
365 printf (" Literal (%u bytes):", F->Size);
374 printf (" %02X", *Data++);
381 printf (" Expression (%u bytes):\n", F->Size);
383 DumpExpr (F->Expr, 0);
387 printf (" Signed expression (%u bytes):\n", F->Size);
389 DumpExpr (F->Expr, 0);
393 printf (" Empty space (%u bytes)\n", F->Size);
397 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_Hi[4] = {
413 0x000000FFUL, 0x0000FFFFUL, 0x00FFFFFFUL, 0xFFFFFFFFUL
415 static const long S_Hi[4] = {
416 0x0000007FL, 0x00007FFFL, 0x007FFFFFL, 0x7FFFFFFFL
418 static const long S_Lo[4] = {
419 ~0x0000007FL, ~0x00007FFFL, ~0x007FFFFFL, ~0x7FFFFFFFL
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_Hi[Size-1] || Val < S_Lo[Size-1]) {
433 return SEG_EXPR_RANGE_ERROR;
436 if (((unsigned long)Val) > U_Hi[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 */
466 for (I = 0; I < CollCount (&S->Sections); ++I) {
468 Section* Sec = CollAtUnchecked (&S->Sections, I);
470 unsigned char FillVal;
472 /* Output were this section is from */
473 Print (stdout, 2, " Section from \"%s\"\n", GetObjFileName (Sec->Obj));
475 /* If we have fill bytes, write them now. Beware: If this is the
476 * first section, the fill value is not considered part of the segment
477 * and therefore taken from the memory area.
479 FillVal = (I == 0)? S->MemArea->FillVal : S->FillVal;
480 Print (stdout, 2, " Filling 0x%lx bytes with 0x%02x\n",
482 WriteMult (Tgt, FillVal, Sec->Fill);
485 /* Loop over all fragments in this section */
486 Frag = Sec->FragRoot;
489 /* Output fragment data */
490 switch (Frag->Type) {
493 WriteData (Tgt, Frag->LitBuf, Frag->Size);
498 Sign = (Frag->Type == FRAG_SEXPR);
499 /* Call the users function and evaluate the result */
500 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
505 case SEG_EXPR_RANGE_ERROR:
506 Error ("Range error in module `%s', line %u",
507 GetFragmentSourceName (Frag),
508 GetFragmentSourceLine (Frag));
511 case SEG_EXPR_TOO_COMPLEX:
512 Error ("Expression too complex in module `%s', line %u",
513 GetFragmentSourceName (Frag),
514 GetFragmentSourceLine (Frag));
517 case SEG_EXPR_INVALID:
518 Error ("Invalid expression in module `%s', line %u",
519 GetFragmentSourceName (Frag),
520 GetFragmentSourceLine (Frag));
524 Internal ("Invalid return code from SegWriteFunc");
529 WriteMult (Tgt, S->FillVal, Frag->Size);
533 Internal ("Invalid fragment type: %02X", Frag->Type);
536 /* Update the offset */
537 Print (stdout, 2, " Fragment with 0x%x bytes\n",
549 unsigned SegmentCount (void)
550 /* Return the total number of segments */
552 return CollCount (&SegmentList);
557 static int CmpSegStart (const void* K1, const void* K2)
558 /* Compare function for qsort */
560 /* Get the real segment pointers */
561 const Segment* S1 = *(const Segment**)K1;
562 const Segment* S2 = *(const Segment**)K2;
564 /* Compare the start addresses */
565 if (S1->PC > S2->PC) {
567 } else if (S1->PC < S2->PC) {
570 /* Sort segments with equal starts by name */
571 return strcmp (GetString (S1->Name), GetString (S2->Name));
577 void PrintSegmentMap (FILE* F)
578 /* Print a segment map to the given file */
581 /* Allocate memory for the segment pool */
582 Segment** SegPool = xmalloc (CollCount (&SegmentList) * sizeof (Segment*));
584 /* Copy the segment pointers */
586 for (I = 0; I < CollCount (&SegmentList); ++I) {
587 SegPool[I] = CollAtUnchecked (&SegmentList, I);
590 /* Sort the array by increasing start addresses */
591 qsort (SegPool, CollCount (&SegmentList), sizeof (Segment*), CmpSegStart);
594 fprintf (F, "Name Start End Size Align\n"
595 "----------------------------------------------------\n");
597 /* Print the segments */
598 for (I = 0; I < CollCount (&SegmentList); ++I) {
600 /* Get a pointer to the segment */
601 Segment* S = SegPool[I];
603 /* Print empty segments only if explicitly requested */
604 if (VerboseMap || S->Size > 0) {
605 /* Print the segment data */
606 long End = S->PC + S->Size;
608 /* Point to last element addressed */
611 fprintf (F, "%-20s %06lX %06lX %06lX %05lX\n",
612 GetString (S->Name), S->PC, End, S->Size, S->Alignment);
616 /* Free the segment pool */
622 void PrintDbgSegments (FILE* F)
623 /* Output the segments to the debug file */
625 /* Walk over all segments */
627 for (I = 0; I < CollCount (&SegmentList); ++I) {
629 /* Get the next segment */
630 const Segment* S = CollAtUnchecked (&SegmentList, I);
632 /* Print the segment data */
634 "seg\tid=%u,name=\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s",
635 S->Id, GetString (S->Name), S->PC, S->Size,
636 AddrSizeToStr (S->AddrSize),
637 S->ReadOnly? "ro" : "rw");
639 fprintf (F, ",oname=\"%s\",ooffs=%lu",
640 S->OutputName, S->OutputOffs);
648 void CheckSegments (void)
649 /* Walk through the segment list and check if there are segments that were
650 * not written to the output file. Output an error if this is the case.
654 for (I = 0; I < CollCount (&SegmentList); ++I) {
656 /* Get the next segment */
657 const Segment* S = CollAtUnchecked (&SegmentList, I);
660 if (S->Size > 0 && S->Dumped == 0) {
661 Error ("Missing memory area assignment for segment `%s'",
662 GetString (S->Name));