]> git.sur5r.net Git - cc65/blob - src/ld65/segments.c
fe6c78dd74c1e7b8224d27c6887c9b73827b42b6
[cc65] / src / ld65 / segments.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                segments.c                                 */
4 /*                                                                           */
5 /*                   Segment handling for the ld65 linker                    */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2012, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
12 /* EMail:         uz@cc65.org                                                */
13 /*                                                                           */
14 /*                                                                           */
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.                                    */
18 /*                                                                           */
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:                            */
22 /*                                                                           */
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              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdlib.h>
37 #include <string.h>
38
39 /* common */
40 #include "addrsize.h"
41 #include "alignment.h"
42 #include "check.h"
43 #include "coll.h"
44 #include "exprdefs.h"
45 #include "fragdefs.h"
46 #include "hashfunc.h"
47 #include "print.h"
48 #include "segdefs.h"
49 #include "symdefs.h"
50 #include "xmalloc.h"
51
52 /* ld65 */
53 #include "error.h"
54 #include "expr.h"
55 #include "fileio.h"
56 #include "fragment.h"
57 #include "global.h"
58 #include "lineinfo.h"
59 #include "segments.h"
60 #include "spool.h"
61
62
63
64 /*****************************************************************************/
65 /*                                   Data                                    */
66 /*****************************************************************************/
67
68
69
70 /* Hash table */
71 #define HASHTAB_MASK    0x3FU
72 #define HASHTAB_SIZE    (HASHTAB_MASK + 1)
73 static Segment*         HashTab[HASHTAB_SIZE];
74
75 /* List of all segments */
76 static Collection       SegmentList = STATIC_COLLECTION_INITIALIZER;
77
78
79
80 /*****************************************************************************/
81 /*                                   Code                                    */
82 /*****************************************************************************/
83
84
85
86 static Segment* NewSegment (unsigned Name, unsigned char AddrSize)
87 /* Create a new segment and initialize it */
88 {
89     unsigned Hash;
90
91     /* Allocate memory */
92     Segment* S = xmalloc (sizeof (Segment));
93
94     /* Initialize the fields */
95     S->Name        = Name;
96     S->Next        = 0;
97     S->Flags       = SEG_FLAG_NONE;
98     S->Sections    = EmptyCollection;
99     S->MemArea     = 0;
100     S->PC          = 0;
101     S->Size        = 0;
102     S->OutputName  = 0;
103     S->OutputOffs  = 0;
104     S->Alignment   = 1;
105     S->FillVal     = 0;
106     S->AddrSize    = AddrSize;
107     S->ReadOnly    = 0;
108     S->Dumped      = 0;
109
110     /* Insert the segment into the segment list and assign the segment id */
111     S->Id = CollCount (&SegmentList);
112     CollAppend (&SegmentList, S);
113
114     /* Insert the segment into the segment hash list */
115     Hash = (S->Name & HASHTAB_MASK);
116     S->Next = HashTab[Hash];
117     HashTab[Hash] = S;
118
119     /* Return the new entry */
120     return S;
121 }
122
123
124
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.
129  */
130 {
131     /* Try to locate the segment in the table */
132     Segment* S = SegFind (Name);
133
134     /* If we don't have that segment already, allocate it using the type of
135      * the first section.
136      */
137     if (S == 0) {
138         /* Create a new segment */
139         S = NewSegment (Name, AddrSize);
140     } else {
141         /* Check if the existing segment has the requested address size */
142         if (S->AddrSize != AddrSize) {
143             /* Allow an empty object name */
144             if (ObjName == 0) {
145                 ObjName = "[linker generated]";
146             }
147             Error ("Module `%s': Type mismatch for segment `%s'", ObjName,
148                    GetString (Name));
149         }
150     }
151
152     /* Return the segment */
153     return S;
154 }
155
156
157
158 Section* NewSection (Segment* Seg, unsigned long Alignment, unsigned char AddrSize)
159 /* Create a new section for the given segment */
160 {
161     /* Allocate memory */
162     Section* S = xmalloc (sizeof (Section));
163
164     /* Initialize the data */
165     S->Next     = 0;
166     S->Seg      = Seg;
167     S->Obj      = 0;
168     S->FragRoot = 0;
169     S->FragLast = 0;
170     S->Size     = 0;
171     S->Alignment= Alignment;
172     S->AddrSize = AddrSize;
173
174     /* Calculate the alignment bytes needed for the section */
175     S->Fill = AlignCount (Seg->Size, S->Alignment);
176
177     /* Adjust the segment size and set the section offset */
178     Seg->Size  += S->Fill;
179     S->Offs     = Seg->Size;    /* Current size is offset */
180
181     /* Insert the section into the segment */
182     CollAppend (&Seg->Sections, S);
183
184     /* Return the struct */
185     return S;
186 }
187
188
189
190 Section* ReadSection (FILE* F, ObjData* O)
191 /* Read a section from a file */
192 {
193     unsigned      Name;
194     unsigned      Flags;
195     unsigned      Size;
196     unsigned long Alignment;
197     unsigned char Type;
198     unsigned      FragCount;
199     Segment*      S;
200     Section*      Sec;
201
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 */
210
211
212     /* Print some data */
213     Print (stdout, 2,
214            "Module `%s': Found segment `%s', size = %u, alignment = %lu, type = %u\n",
215            GetObjFileName (O), GetString (Name), Size, Alignment, Type);
216
217     /* Get the segment for this section */
218     S = GetSegment (Name, Type, GetObjFileName (O));
219
220     /* Allocate the section we will return later */
221     Sec = NewSection (S, Alignment, Type);
222
223     /* Remember the object file this section was from */
224     Sec->Obj = O;
225
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,
233                    GetObjFileName (O));
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));
238         }
239         S->Alignment = Alignment;
240     }
241
242     /* Start reading fragments from the file and insert them into the section . */
243     while (FragCount--) {
244
245         Fragment* Frag;
246
247         /* Read the fragment type */
248         unsigned char Type = Read8 (F);
249
250         /* Extract the check mask from the type */
251         unsigned char Bytes = Type & FRAG_BYTEMASK;
252         Type &= FRAG_TYPEMASK;
253
254         /* Handle the different fragment types */
255         switch (Type) {
256
257             case FRAG_LITERAL:
258                 Frag = NewFragment (Type, ReadVar (F), Sec);
259                 ReadData (F, Frag->LitBuf, Frag->Size);
260                 break;
261
262             case FRAG_EXPR:
263             case FRAG_SEXPR:
264                 Frag = NewFragment (Type, Bytes, Sec);
265                 Frag->Expr = ReadExpr (F, O);
266                 break;
267
268             case FRAG_FILL:
269                 /* Will allocate memory, but we don't care... */
270                 Frag = NewFragment (Type, ReadVar (F), Sec);
271                 break;
272
273             default:
274                 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
275                        GetObjFileName (O), GetString (S->Name), Type);
276                 /* NOTREACHED */
277                 return 0;
278         }
279
280         /* Read the line infos into the list of the fragment */
281         ReadLineInfoList (F, O, &Frag->LineInfos);
282
283         /* Remember the module we had this fragment from */
284         Frag->Obj = O;
285     }
286
287     /* Return the section */
288     return Sec;
289 }
290
291
292
293 Segment* SegFind (unsigned Name)
294 /* Return the given segment or NULL if not found. */
295 {
296     Segment* S = HashTab[Name & HASHTAB_MASK];
297     while (S) {
298         if (Name == S->Name) {
299             /* Found */
300             break;
301         }
302         S = S->Next;
303     }
304     /* Not found */
305     return S;
306 }
307
308
309
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.
313  */
314 {
315     /* Loop over all sections */
316     unsigned I;
317     for (I = 0; I < CollCount (&S->Sections); ++I) {
318
319         /* Get the next section */
320         Section* Sec = CollAtUnchecked (&S->Sections, I);
321
322         /* Loop over all fragments */
323         Fragment* F = Sec->FragRoot;
324         while (F) {
325             if (F->Type == FRAG_LITERAL) {
326                 unsigned char* Data = F->LitBuf;
327                 unsigned long Count = F->Size;
328                 while (Count--) {
329                     if (*Data++ != 0) {
330                         return 0;
331                     }
332                 }
333             } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
334                 if (GetExprVal (F->Expr) != 0) {
335                     return 0;
336                 }
337             }
338             F = F->Next;
339         }
340     }
341     return 1;
342 }
343
344
345
346 void SegDump (void)
347 /* Dump the segments and it's contents */
348 {
349     unsigned I, J;
350     unsigned long Count;
351     unsigned char* Data;
352
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);
358             unsigned J;
359             Fragment* F = S->FragRoot;
360             printf ("  Section:\n");
361             while (F) {
362                 switch (F->Type) {
363
364                     case FRAG_LITERAL:
365                         printf ("    Literal (%u bytes):", F->Size);
366                         Count = F->Size;
367                         Data  = F->LitBuf;
368                         J = 100;
369                         while (Count--) {
370                             if (J > 75) {
371                                 printf ("\n   ");
372                                 J = 3;
373                             }
374                             printf (" %02X", *Data++);
375                             J += 3;
376                         }
377                         printf ("\n");
378                         break;
379
380                     case FRAG_EXPR:
381                         printf ("    Expression (%u bytes):\n", F->Size);
382                         printf ("    ");
383                         DumpExpr (F->Expr, 0);
384                         break;
385
386                     case FRAG_SEXPR:
387                         printf ("    Signed expression (%u bytes):\n", F->Size);
388                         printf ("      ");
389                         DumpExpr (F->Expr, 0);
390                         break;
391
392                     case FRAG_FILL:
393                         printf ("    Empty space (%u bytes)\n", F->Size);
394                         break;
395
396                     default:
397                         Internal ("Invalid fragment type: %02X", F->Type);
398                 }
399                 F = F->Next;
400             }
401         }
402     }
403 }
404
405
406
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.
410  */
411 {
412     static const unsigned long U_Hi[4] = {
413         0x000000FFUL, 0x0000FFFFUL, 0x00FFFFFFUL, 0xFFFFFFFFUL
414     };
415     static const long S_Hi[4] = {
416         0x0000007FL, 0x00007FFFL, 0x007FFFFFL, 0x7FFFFFFFL
417     };
418     static const long S_Lo[4] = {
419         ~0x0000007FL, ~0x00007FFFL, ~0x007FFFFFL, ~0x7FFFFFFFL
420     };
421
422
423     /* Get the expression value */
424     long Val = GetExprVal (E);
425
426     /* Check the size */
427     CHECK (Size >= 1 && Size <= 4);
428
429     /* Check for a range error */
430     if (Signed) {
431         if (Val > S_Hi[Size-1] || Val < S_Lo[Size-1]) {
432             /* Range error */
433             return SEG_EXPR_RANGE_ERROR;
434         }
435     } else {
436         if (((unsigned long)Val) > U_Hi[Size-1]) {
437             /* Range error */
438             return SEG_EXPR_RANGE_ERROR;
439         }
440     }
441
442     /* Write the value to the file */
443     WriteVal (F, Val, Size);
444
445     /* Success */
446     return SEG_EXPR_OK;
447 }
448
449
450
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).
454  */
455 {
456     unsigned      I;
457     int           Sign;
458     unsigned long Offs = 0;
459
460
461     /* Remember the output file and offset for the segment */
462     S->OutputName = TgtName;
463     S->OutputOffs = (unsigned long) ftell (Tgt);
464
465     /* Loop over all sections in this segment */
466     for (I = 0; I < CollCount (&S->Sections); ++I) {
467
468         Section*        Sec = CollAtUnchecked (&S->Sections, I);
469         Fragment*       Frag;
470         unsigned char   FillVal;
471
472         /* Output were this section is from */
473         Print (stdout, 2, "      Section from \"%s\"\n", GetObjFileName (Sec->Obj));
474
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.
478          */
479         FillVal = (I == 0)? S->MemArea->FillVal : S->FillVal;
480         Print (stdout, 2, "        Filling 0x%lx bytes with 0x%02x\n",
481                Sec->Fill, FillVal);
482         WriteMult (Tgt, FillVal, Sec->Fill);
483         Offs += Sec->Fill;
484
485         /* Loop over all fragments in this section */
486         Frag = Sec->FragRoot;
487         while (Frag) {
488
489             /* Output fragment data */
490             switch (Frag->Type) {
491
492                 case FRAG_LITERAL:
493                     WriteData (Tgt, Frag->LitBuf, Frag->Size);
494                     break;
495
496                 case FRAG_EXPR:
497                 case FRAG_SEXPR:
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)) {
501
502                         case SEG_EXPR_OK:
503                             break;
504
505                         case SEG_EXPR_RANGE_ERROR:
506                             Error ("Range error in module `%s', line %u",
507                                    GetFragmentSourceName (Frag),
508                                    GetFragmentSourceLine (Frag));
509                             break;
510
511                         case SEG_EXPR_TOO_COMPLEX:
512                             Error ("Expression too complex in module `%s', line %u",
513                                    GetFragmentSourceName (Frag),
514                                    GetFragmentSourceLine (Frag));
515                             break;
516
517                         case SEG_EXPR_INVALID:
518                             Error ("Invalid expression in module `%s', line %u",
519                                    GetFragmentSourceName (Frag),
520                                    GetFragmentSourceLine (Frag));
521                             break;
522
523                         default:
524                             Internal ("Invalid return code from SegWriteFunc");
525                     }
526                     break;
527
528                 case FRAG_FILL:
529                     WriteMult (Tgt, S->FillVal, Frag->Size);
530                     break;
531
532                 default:
533                     Internal ("Invalid fragment type: %02X", Frag->Type);
534             }
535
536             /* Update the offset */
537             Print (stdout, 2, "        Fragment with 0x%x bytes\n",
538                    Frag->Size);
539             Offs += Frag->Size;
540
541             /* Next fragment */
542             Frag = Frag->Next;
543         }
544     }
545 }
546
547
548
549 unsigned SegmentCount (void)
550 /* Return the total number of segments */
551 {
552     return CollCount (&SegmentList);
553 }
554
555
556
557 static int CmpSegStart (const void* K1, const void* K2)
558 /* Compare function for qsort */
559 {
560     /* Get the real segment pointers */
561     const Segment* S1 = *(const Segment**)K1;
562     const Segment* S2 = *(const Segment**)K2;
563
564     /* Compare the start addresses */
565     if (S1->PC > S2->PC) {
566         return 1;
567     } else if (S1->PC < S2->PC) {
568         return -1;
569     } else {
570         /* Sort segments with equal starts by name */
571         return strcmp (GetString (S1->Name), GetString (S2->Name));
572     }
573 }
574
575
576
577 void PrintSegmentMap (FILE* F)
578 /* Print a segment map to the given file */
579 {
580
581     /* Allocate memory for the segment pool */
582     Segment** SegPool = xmalloc (CollCount (&SegmentList) * sizeof (Segment*));
583
584     /* Copy the segment pointers */
585     unsigned I;
586     for (I = 0; I < CollCount (&SegmentList); ++I) {
587         SegPool[I] = CollAtUnchecked (&SegmentList, I);
588     }
589
590     /* Sort the array by increasing start addresses */
591     qsort (SegPool, CollCount (&SegmentList), sizeof (Segment*), CmpSegStart);
592
593     /* Print a header */
594     fprintf (F, "Name                   Start     End    Size  Align\n"
595                 "----------------------------------------------------\n");
596
597     /* Print the segments */
598     for (I = 0; I < CollCount (&SegmentList); ++I) {
599
600         /* Get a pointer to the segment */
601         Segment* S = SegPool[I];
602
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;
607             if (S->Size > 0) {
608                 /* Point to last element addressed */
609                 --End;
610             }
611             fprintf (F, "%-20s  %06lX  %06lX  %06lX  %05lX\n",
612                      GetString (S->Name), S->PC, End, S->Size, S->Alignment);
613         }
614     }
615
616     /* Free the segment pool */
617     xfree (SegPool);
618 }
619
620
621
622 void PrintDbgSegments (FILE* F)
623 /* Output the segments to the debug file */
624 {
625     /* Walk over all segments */
626     unsigned I;
627     for (I = 0; I < CollCount (&SegmentList); ++I) {
628
629         /* Get the next segment */
630         const Segment* S = CollAtUnchecked (&SegmentList, I);
631
632         /* Print the segment data */
633         fprintf (F,
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");
638         if (S->OutputName) {
639             fprintf (F, ",oname=\"%s\",ooffs=%lu",
640                      S->OutputName, S->OutputOffs);
641         }
642         fputc ('\n', F);
643     }
644 }
645
646
647
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.
651  */
652 {
653     unsigned I;
654     for (I = 0; I < CollCount (&SegmentList); ++I) {
655
656         /* Get the next segment */
657         const Segment* S = CollAtUnchecked (&SegmentList, I);
658
659         /* Check it */
660         if (S->Size > 0 && S->Dumped == 0) {
661             Error ("Missing memory area assignment for segment `%s'",
662                    GetString (S->Name));
663         }
664     }
665 }
666
667
668