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 /*****************************************************************************/
40 #include "alignment.h"
63 /*****************************************************************************/
65 /*****************************************************************************/
70 #define HASHTAB_MASK 0x3FU
71 #define HASHTAB_SIZE (HASHTAB_MASK + 1)
72 static Segment* HashTab[HASHTAB_SIZE];
74 /* List of all segments */
75 static Collection SegmentList = STATIC_COLLECTION_INITIALIZER;
79 /*****************************************************************************/
81 /*****************************************************************************/
85 static Segment* NewSegment (unsigned Name, unsigned char AddrSize)
86 /* Create a new segment and initialize it */
91 Segment* S = xmalloc (sizeof (Segment));
93 /* Initialize the fields */
96 S->Sections = EmptyCollection;
104 S->AddrSize = AddrSize;
109 /* Insert the segment into the segment list and assign the segment id */
110 S->Id = CollCount (&SegmentList);
111 CollAppend (&SegmentList, S);
113 /* Insert the segment into the segment hash list */
114 Hash = (S->Name & HASHTAB_MASK);
115 S->Next = HashTab[Hash];
118 /* Return the new entry */
124 Segment* GetSegment (unsigned Name, unsigned char AddrSize, const char* ObjName)
125 /* Search for a segment and return an existing one. If the segment does not
126 * exist, create a new one and return that. ObjName is only used for the error
127 * message and may be NULL if the segment is linker generated.
130 /* Try to locate the segment in the table */
131 Segment* S = SegFind (Name);
133 /* If we don't have that segment already, allocate it using the type of
137 /* Create a new segment */
138 S = NewSegment (Name, AddrSize);
140 /* Check if the existing segment has the requested address size */
141 if (S->AddrSize != AddrSize) {
142 /* Allow an empty object name */
144 ObjName = "[linker generated]";
146 Error ("Module `%s': Type mismatch for segment `%s'", ObjName,
151 /* Return the segment */
157 Section* NewSection (Segment* Seg, unsigned long Alignment, unsigned char AddrSize)
158 /* Create a new section for the given segment */
160 /* Allocate memory */
161 Section* S = xmalloc (sizeof (Section));
163 /* Initialize the data */
170 S->Alignment= Alignment;
171 S->AddrSize = AddrSize;
173 /* Calculate the alignment bytes needed for the section */
174 S->Fill = AlignCount (Seg->Size, S->Alignment);
176 /* Adjust the segment size and set the section offset */
177 Seg->Size += S->Fill;
178 S->Offs = Seg->Size; /* Current size is offset */
180 /* Insert the section into the segment */
181 CollAppend (&Seg->Sections, S);
183 /* Return the struct */
189 Section* ReadSection (FILE* F, ObjData* O)
190 /* Read a section from a file */
194 unsigned long Alignment;
200 /* Read the segment data */
201 (void) Read32 (F); /* File size of data */
202 Name = MakeGlobalStringId (O, ReadVar (F)); /* Segment name */
203 Size = ReadVar (F); /* Size of data */
204 Alignment = ReadVar (F); /* Alignment */
205 Type = Read8 (F); /* Segment type */
206 FragCount = ReadVar (F); /* Number of fragments */
209 /* Print some data */
211 "Module `%s': Found segment `%s', size = %u, alignment = %lu, type = %u\n",
212 GetObjFileName (O), GetString (Name), Size, Alignment, Type);
214 /* Get the segment for this section */
215 S = GetSegment (Name, Type, GetObjFileName (O));
217 /* Allocate the section we will return later */
218 Sec = NewSection (S, Alignment, Type);
220 /* Remember the object file this section was from */
223 /* Set up the combined segment alignment */
224 if (Sec->Alignment > 1) {
225 Alignment = LeastCommonMultiple (S->Alignment, Sec->Alignment);
226 if (Alignment > MAX_ALIGNMENT) {
227 Error ("Combined alignment for segment `%s' is %lu which exceeds "
228 "%lu. Last module requiring alignment was `%s'.",
229 GetString (Name), Alignment, MAX_ALIGNMENT,
231 } else if (Alignment >= LARGE_ALIGNMENT) {
232 Warning ("Combined alignment for segment `%s' is suspiciously "
233 "large (%lu). Last module requiring alignment was `%s'.",
234 GetString (Name), Alignment, GetObjFileName (O));
236 S->Alignment = Alignment;
239 /* Start reading fragments from the file and insert them into the section . */
240 while (FragCount--) {
244 /* Read the fragment type */
245 unsigned char Type = Read8 (F);
247 /* Extract the check mask from the type */
248 unsigned char Bytes = Type & FRAG_BYTEMASK;
249 Type &= FRAG_TYPEMASK;
251 /* Handle the different fragment types */
255 Frag = NewFragment (Type, ReadVar (F), Sec);
256 ReadData (F, Frag->LitBuf, Frag->Size);
261 Frag = NewFragment (Type, Bytes, Sec);
262 Frag->Expr = ReadExpr (F, O);
266 /* Will allocate memory, but we don't care... */
267 Frag = NewFragment (Type, ReadVar (F), Sec);
271 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
272 GetObjFileName (O), GetString (S->Name), Type);
277 /* Read the line infos into the list of the fragment */
278 ReadLineInfoList (F, O, &Frag->LineInfos);
280 /* Remember the module we had this fragment from */
284 /* Return the section */
290 Segment* SegFind (unsigned Name)
291 /* Return the given segment or NULL if not found. */
293 Segment* S = HashTab[Name & HASHTAB_MASK];
295 if (Name == S->Name) {
307 int IsBSSType (Segment* S)
308 /* Check if the given segment is a BSS style segment, that is, it does not
309 * contain non-zero data.
312 /* Loop over all sections */
314 for (I = 0; I < CollCount (&S->Sections); ++I) {
316 /* Get the next section */
317 Section* Sec = CollAtUnchecked (&S->Sections, I);
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) {
344 /* Dump the segments and it's contents */
350 for (I = 0; I < CollCount (&SegmentList); ++I) {
351 Segment* Seg = CollAtUnchecked (&SegmentList, I);
352 printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
353 for (J = 0; J < CollCount (&Seg->Sections); ++J) {
354 Section* S = CollAtUnchecked (&Seg->Sections, J);
356 Fragment* F = S->FragRoot;
357 printf (" Section:\n");
362 printf (" Literal (%u bytes):", F->Size);
371 printf (" %02X", *Data++);
378 printf (" Expression (%u bytes):\n", F->Size);
380 DumpExpr (F->Expr, 0);
384 printf (" Signed expression (%u bytes):\n", F->Size);
386 DumpExpr (F->Expr, 0);
390 printf (" Empty space (%u bytes)\n", F->Size);
394 Internal ("Invalid fragment type: %02X", F->Type);
404 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
405 /* Write a supposedly constant expression to the target file. Do a range
406 * check and return one of the SEG_EXPR_xxx codes.
409 static const unsigned long U_Hi[4] = {
410 0x000000FFUL, 0x0000FFFFUL, 0x00FFFFFFUL, 0xFFFFFFFFUL
412 static const long S_Hi[4] = {
413 0x0000007FL, 0x00007FFFL, 0x007FFFFFL, 0x7FFFFFFFL
415 static const long S_Lo[4] = {
416 ~0x0000007FL, ~0x00007FFFL, ~0x007FFFFFL, ~0x7FFFFFFFL
420 /* Get the expression value */
421 long Val = GetExprVal (E);
424 CHECK (Size >= 1 && Size <= 4);
426 /* Check for a range error */
428 if (Val > S_Hi[Size-1] || Val < S_Lo[Size-1]) {
430 return SEG_EXPR_RANGE_ERROR;
433 if (((unsigned long)Val) > U_Hi[Size-1]) {
435 return SEG_EXPR_RANGE_ERROR;
439 /* Write the value to the file */
440 WriteVal (F, Val, Size);
448 void SegWrite (const char* TgtName, FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
449 /* Write the data from the given segment to a file. For expressions, F is
450 * called (see description of SegWriteFunc above).
455 unsigned long Offs = 0;
458 /* Remember the output file and offset for the segment */
459 S->OutputName = TgtName;
460 S->OutputOffs = (unsigned long) ftell (Tgt);
462 /* Loop over all sections in this segment */
463 for (I = 0; I < CollCount (&S->Sections); ++I) {
464 Section* Sec = CollAtUnchecked (&S->Sections, I);
467 /* Output were this section is from */
468 Print (stdout, 2, " Section from \"%s\"\n", GetObjFileName (Sec->Obj));
470 /* If we have fill bytes, write them now */
471 Print (stdout, 2, " Filling 0x%lx bytes with 0x%02x\n",
472 Sec->Fill, S->FillVal);
473 WriteMult (Tgt, S->FillVal, Sec->Fill);
476 /* Loop over all fragments in this section */
477 Frag = Sec->FragRoot;
480 /* Output fragment data */
481 switch (Frag->Type) {
484 WriteData (Tgt, Frag->LitBuf, Frag->Size);
489 Sign = (Frag->Type == FRAG_SEXPR);
490 /* Call the users function and evaluate the result */
491 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
496 case SEG_EXPR_RANGE_ERROR:
497 Error ("Range error in module `%s', line %u",
498 GetFragmentSourceName (Frag),
499 GetFragmentSourceLine (Frag));
502 case SEG_EXPR_TOO_COMPLEX:
503 Error ("Expression too complex in module `%s', line %u",
504 GetFragmentSourceName (Frag),
505 GetFragmentSourceLine (Frag));
508 case SEG_EXPR_INVALID:
509 Error ("Invalid expression in module `%s', line %u",
510 GetFragmentSourceName (Frag),
511 GetFragmentSourceLine (Frag));
515 Internal ("Invalid return code from SegWriteFunc");
520 WriteMult (Tgt, S->FillVal, Frag->Size);
524 Internal ("Invalid fragment type: %02X", Frag->Type);
527 /* Update the offset */
528 Print (stdout, 2, " Fragment with 0x%x bytes\n",
540 unsigned SegmentCount (void)
541 /* Return the total number of segments */
543 return CollCount (&SegmentList);
548 static int CmpSegStart (const void* K1, const void* K2)
549 /* Compare function for qsort */
551 /* Get the real segment pointers */
552 const Segment* S1 = *(const Segment**)K1;
553 const Segment* S2 = *(const Segment**)K2;
555 /* Compare the start addresses */
556 if (S1->PC > S2->PC) {
558 } else if (S1->PC < S2->PC) {
561 /* Sort segments with equal starts by name */
562 return strcmp (GetString (S1->Name), GetString (S2->Name));
568 void PrintSegmentMap (FILE* F)
569 /* Print a segment map to the given file */
572 /* Allocate memory for the segment pool */
573 Segment** SegPool = xmalloc (CollCount (&SegmentList) * sizeof (Segment*));
575 /* Copy the segment pointers */
577 for (I = 0; I < CollCount (&SegmentList); ++I) {
578 SegPool[I] = CollAtUnchecked (&SegmentList, I);
581 /* Sort the array by increasing start addresses */
582 qsort (SegPool, CollCount (&SegmentList), sizeof (Segment*), CmpSegStart);
585 fprintf (F, "Name Start End Size Align\n"
586 "----------------------------------------------------\n");
588 /* Print the segments */
589 for (I = 0; I < CollCount (&SegmentList); ++I) {
591 /* Get a pointer to the segment */
592 Segment* S = SegPool[I];
594 /* Print empty segments only if explicitly requested */
595 if (VerboseMap || S->Size > 0) {
596 /* Print the segment data */
597 long End = S->PC + S->Size;
599 /* Point to last element addressed */
602 fprintf (F, "%-20s %06lX %06lX %06lX %05lX\n",
603 GetString (S->Name), S->PC, End, S->Size, S->Alignment);
607 /* Free the segment pool */
613 void PrintDbgSegments (FILE* F)
614 /* Output the segments to the debug file */
616 /* Walk over all segments */
618 for (I = 0; I < CollCount (&SegmentList); ++I) {
620 /* Get the next segment */
621 const Segment* S = CollAtUnchecked (&SegmentList, I);
623 /* Print the segment data */
625 "seg\tid=%u,name=\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s",
626 S->Id, GetString (S->Name), S->PC, S->Size,
627 AddrSizeToStr (S->AddrSize),
628 S->ReadOnly? "ro" : "rw");
630 fprintf (F, ",oname=\"%s\",ooffs=%lu",
631 S->OutputName, S->OutputOffs);
639 void CheckSegments (void)
640 /* Walk through the segment list and check if there are segments that were
641 * not written to the output file. Output an error if this is the case.
645 for (I = 0; I < CollCount (&SegmentList); ++I) {
647 /* Get the next segment */
648 const Segment* S = CollAtUnchecked (&SegmentList, I);
651 if (S->Size > 0 && S->Dumped == 0) {
652 Error ("Missing memory area assignment for segment `%s'",
653 GetString (S->Name));