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 */
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 /* The only possible flag is currently SEG_FLAG_BANKREF, and it must be
221 * applied to the segment, not the section.
225 /* Allocate the section we will return later */
226 Sec = NewSection (S, Alignment, Type);
228 /* Remember the object file this section was from */
231 /* Set up the combined segment alignment */
232 if (Sec->Alignment > 1) {
233 Alignment = LeastCommonMultiple (S->Alignment, Sec->Alignment);
234 if (Alignment > MAX_ALIGNMENT) {
235 Error ("Combined alignment for segment `%s' is %lu which exceeds "
236 "%lu. Last module requiring alignment was `%s'.",
237 GetString (Name), Alignment, MAX_ALIGNMENT,
239 } else if (Alignment >= LARGE_ALIGNMENT) {
240 Warning ("Combined alignment for segment `%s' is suspiciously "
241 "large (%lu). Last module requiring alignment was `%s'.",
242 GetString (Name), Alignment, GetObjFileName (O));
244 S->Alignment = Alignment;
247 /* Start reading fragments from the file and insert them into the section . */
248 while (FragCount--) {
252 /* Read the fragment type */
253 unsigned char Type = Read8 (F);
255 /* Extract the check mask from the type */
256 unsigned char Bytes = Type & FRAG_BYTEMASK;
257 Type &= FRAG_TYPEMASK;
259 /* Handle the different fragment types */
263 Frag = NewFragment (Type, ReadVar (F), Sec);
264 ReadData (F, Frag->LitBuf, Frag->Size);
269 Frag = NewFragment (Type, Bytes, Sec);
270 Frag->Expr = ReadExpr (F, O);
274 /* Will allocate memory, but we don't care... */
275 Frag = NewFragment (Type, ReadVar (F), Sec);
279 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
280 GetObjFileName (O), GetString (S->Name), Type);
285 /* Read the line infos into the list of the fragment */
286 ReadLineInfoList (F, O, &Frag->LineInfos);
288 /* Remember the module we had this fragment from */
292 /* Return the section */
298 Segment* SegFind (unsigned Name)
299 /* Return the given segment or NULL if not found. */
301 Segment* S = HashTab[Name & HASHTAB_MASK];
303 if (Name == S->Name) {
315 int IsBSSType (Segment* S)
316 /* Check if the given segment is a BSS style segment, that is, it does not
317 * contain non-zero data.
320 /* Loop over all sections */
322 for (I = 0; I < CollCount (&S->Sections); ++I) {
324 /* Get the next section */
325 Section* Sec = CollAtUnchecked (&S->Sections, I);
327 /* Loop over all fragments */
328 Fragment* F = Sec->FragRoot;
330 if (F->Type == FRAG_LITERAL) {
331 unsigned char* Data = F->LitBuf;
332 unsigned long Count = F->Size;
338 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
339 if (GetExprVal (F->Expr) != 0) {
352 /* Dump the segments and it's contents */
358 for (I = 0; I < CollCount (&SegmentList); ++I) {
359 Segment* Seg = CollAtUnchecked (&SegmentList, I);
360 printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
361 for (J = 0; J < CollCount (&Seg->Sections); ++J) {
362 Section* S = CollAtUnchecked (&Seg->Sections, J);
364 Fragment* F = S->FragRoot;
365 printf (" Section:\n");
370 printf (" Literal (%u bytes):", F->Size);
379 printf (" %02X", *Data++);
386 printf (" Expression (%u bytes):\n", F->Size);
388 DumpExpr (F->Expr, 0);
392 printf (" Signed expression (%u bytes):\n", F->Size);
394 DumpExpr (F->Expr, 0);
398 printf (" Empty space (%u bytes)\n", F->Size);
402 Internal ("Invalid fragment type: %02X", F->Type);
412 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
413 /* Write a supposedly constant expression to the target file. Do a range
414 * check and return one of the SEG_EXPR_xxx codes.
417 static const unsigned long U_Hi[4] = {
418 0x000000FFUL, 0x0000FFFFUL, 0x00FFFFFFUL, 0xFFFFFFFFUL
420 static const long S_Hi[4] = {
421 0x0000007FL, 0x00007FFFL, 0x007FFFFFL, 0x7FFFFFFFL
423 static const long S_Lo[4] = {
424 ~0x0000007FL, ~0x00007FFFL, ~0x007FFFFFL, ~0x7FFFFFFFL
428 /* Get the expression value */
429 long Val = GetExprVal (E);
432 CHECK (Size >= 1 && Size <= 4);
434 /* Check for a range error */
436 if (Val > S_Hi[Size-1] || Val < S_Lo[Size-1]) {
438 return SEG_EXPR_RANGE_ERROR;
441 if (((unsigned long)Val) > U_Hi[Size-1]) {
443 return SEG_EXPR_RANGE_ERROR;
447 /* Write the value to the file */
448 WriteVal (F, Val, Size);
456 void SegWrite (const char* TgtName, FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
457 /* Write the data from the given segment to a file. For expressions, F is
458 * called (see description of SegWriteFunc above).
463 unsigned long Offs = 0;
466 /* Remember the output file and offset for the segment */
467 S->OutputName = TgtName;
468 S->OutputOffs = (unsigned long) ftell (Tgt);
470 /* Loop over all sections in this segment */
471 for (I = 0; I < CollCount (&S->Sections); ++I) {
472 Section* Sec = CollAtUnchecked (&S->Sections, I);
475 /* Output were this section is from */
476 Print (stdout, 2, " Section from \"%s\"\n", GetObjFileName (Sec->Obj));
478 /* If we have fill bytes, write them now */
479 Print (stdout, 2, " Filling 0x%lx bytes with 0x%02x\n",
480 Sec->Fill, S->FillVal);
481 WriteMult (Tgt, S->FillVal, Sec->Fill);
484 /* Loop over all fragments in this section */
485 Frag = Sec->FragRoot;
488 /* Output fragment data */
489 switch (Frag->Type) {
492 WriteData (Tgt, Frag->LitBuf, Frag->Size);
497 Sign = (Frag->Type == FRAG_SEXPR);
498 /* Call the users function and evaluate the result */
499 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
504 case SEG_EXPR_RANGE_ERROR:
505 Error ("Range error in module `%s', line %u",
506 GetFragmentSourceName (Frag),
507 GetFragmentSourceLine (Frag));
510 case SEG_EXPR_TOO_COMPLEX:
511 Error ("Expression too complex in module `%s', line %u",
512 GetFragmentSourceName (Frag),
513 GetFragmentSourceLine (Frag));
516 case SEG_EXPR_INVALID:
517 Error ("Invalid expression in module `%s', line %u",
518 GetFragmentSourceName (Frag),
519 GetFragmentSourceLine (Frag));
523 Internal ("Invalid return code from SegWriteFunc");
528 WriteMult (Tgt, S->FillVal, Frag->Size);
532 Internal ("Invalid fragment type: %02X", Frag->Type);
535 /* Update the offset */
536 Print (stdout, 2, " Fragment with 0x%x bytes\n",
548 unsigned SegmentCount (void)
549 /* Return the total number of segments */
551 return CollCount (&SegmentList);
556 static int CmpSegStart (const void* K1, const void* K2)
557 /* Compare function for qsort */
559 /* Get the real segment pointers */
560 const Segment* S1 = *(const Segment**)K1;
561 const Segment* S2 = *(const Segment**)K2;
563 /* Compare the start addresses */
564 if (S1->PC > S2->PC) {
566 } else if (S1->PC < S2->PC) {
569 /* Sort segments with equal starts by name */
570 return strcmp (GetString (S1->Name), GetString (S2->Name));
576 void PrintSegmentMap (FILE* F)
577 /* Print a segment map to the given file */
580 /* Allocate memory for the segment pool */
581 Segment** SegPool = xmalloc (CollCount (&SegmentList) * sizeof (Segment*));
583 /* Copy the segment pointers */
585 for (I = 0; I < CollCount (&SegmentList); ++I) {
586 SegPool[I] = CollAtUnchecked (&SegmentList, I);
589 /* Sort the array by increasing start addresses */
590 qsort (SegPool, CollCount (&SegmentList), sizeof (Segment*), CmpSegStart);
593 fprintf (F, "Name Start End Size Align\n"
594 "----------------------------------------------------\n");
596 /* Print the segments */
597 for (I = 0; I < CollCount (&SegmentList); ++I) {
599 /* Get a pointer to the segment */
600 Segment* S = SegPool[I];
602 /* Print empty segments only if explicitly requested */
603 if (VerboseMap || S->Size > 0) {
604 /* Print the segment data */
605 long End = S->PC + S->Size;
607 /* Point to last element addressed */
610 fprintf (F, "%-20s %06lX %06lX %06lX %05lX\n",
611 GetString (S->Name), S->PC, End, S->Size, S->Alignment);
615 /* Free the segment pool */
621 void PrintDbgSegments (FILE* F)
622 /* Output the segments to the debug file */
624 /* Walk over all segments */
626 for (I = 0; I < CollCount (&SegmentList); ++I) {
628 /* Get the next segment */
629 const Segment* S = CollAtUnchecked (&SegmentList, I);
631 /* Print the segment data */
633 "seg\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, ",oname=\"%s\",ooffs=%lu",
639 S->OutputName, S->OutputOffs);
647 void CheckSegments (void)
648 /* Walk through the segment list and check if there are segments that were
649 * not written to the output file. Output an error if this is the case.
653 for (I = 0; I < CollCount (&SegmentList); ++I) {
655 /* Get the next segment */
656 const Segment* S = CollAtUnchecked (&SegmentList, I);
659 if (S->Size > 0 && S->Dumped == 0) {
660 Error ("Missing memory area assignment for segment `%s'",
661 GetString (S->Name));