]> git.sur5r.net Git - cc65/blob - src/ld65/segments.c
Separate processing the linker config file into two phases: The config file is
[cc65] / src / ld65 / segments.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                segments.c                                 */
4 /*                                                                           */
5 /*                   Segment handling for the ld65 linker                    */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2010, 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 "check.h"
41 #include "exprdefs.h"
42 #include "fragdefs.h"
43 #include "hashstr.h"
44 #include "print.h"
45 #include "segdefs.h"
46 #include "symdefs.h"
47 #include "xmalloc.h"
48
49 /* ld65 */
50 #include "error.h"
51 #include "expr.h"
52 #include "fileio.h"
53 #include "fragment.h"
54 #include "global.h"
55 #include "lineinfo.h"
56 #include "segments.h"
57 #include "spool.h"
58
59
60
61 /*****************************************************************************/
62 /*                                   Data                                    */
63 /*****************************************************************************/
64
65
66
67 /* Hash table */
68 #define HASHTAB_MASK    0x3FU
69 #define HASHTAB_SIZE    (HASHTAB_MASK + 1)
70 static Segment*         HashTab [HASHTAB_SIZE];
71
72 static unsigned         SegCount = 0;   /* Segment count */
73 static Segment*         SegRoot = 0;    /* List of all segments */
74
75
76
77 /*****************************************************************************/
78 /*                                   Code                                    */
79 /*****************************************************************************/
80
81
82
83 static Segment* NewSegment (unsigned Name, unsigned char AddrSize)
84 /* Create a new segment and initialize it */
85 {
86     unsigned Hash;
87
88     /* Allocate memory */
89     Segment* S = xmalloc (sizeof (Segment));
90
91     /* Initialize the fields */
92     S->Name        = Name;
93     S->Next        = 0;
94     S->SecRoot     = 0;
95     S->SecLast     = 0;
96     S->PC          = 0;
97     S->Size        = 0;
98     S->AlignObj    = 0;
99     S->OutputName  = 0;
100     S->OutputOffs  = 0;
101     S->Align       = 0;
102     S->FillVal     = 0;
103     S->AddrSize    = AddrSize;
104     S->ReadOnly    = 0;
105     S->Relocatable = 0;
106     S->Placed      = 0;
107     S->Dumped      = 0;
108
109     /* Insert the segment into the segment list and assign the segment id */
110     if (SegRoot == 0) {
111         S->Id = 0;
112     } else {
113         S->Id = SegRoot->Id + 1;
114     }
115     S->List = SegRoot;
116     SegRoot = S;
117     ++SegCount;
118
119     /* Insert the segment into the segment hash list */
120     Hash = (S->Name & HASHTAB_MASK);
121     S->Next = HashTab[Hash];
122     HashTab[Hash] = S;
123
124     /* Return the new entry */
125     return S;
126 }
127
128
129
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.
134  */
135 {
136     /* Try to locate the segment in the table */
137     Segment* S = SegFind (Name);
138
139     /* If we don't have that segment already, allocate it using the type of
140      * the first section.
141      */
142     if (S == 0) {
143         /* Create a new segment */
144         S = NewSegment (Name, AddrSize);
145     } else {
146         /* Check if the existing segment has the requested address size */
147         if (S->AddrSize != AddrSize) {
148             /* Allow an empty object name */
149             if (ObjName == 0) {
150                 ObjName = "[linker generated]";
151             }
152             Error ("Module `%s': Type mismatch for segment `%s'", ObjName,
153                    GetString (Name));
154         }
155     }
156
157     /* Return the segment */
158     return S;
159 }
160
161
162
163 Section* NewSection (Segment* Seg, unsigned char Align, unsigned char AddrSize)
164 /* Create a new section for the given segment */
165 {
166     unsigned long V;
167
168
169     /* Allocate memory */
170     Section* S = xmalloc (sizeof (Section));
171
172     /* Initialize the data */
173     S->Next     = 0;
174     S->Seg      = Seg;
175     S->FragRoot = 0;
176     S->FragLast = 0;
177     S->Size     = 0;
178     S->Align    = Align;
179     S->AddrSize = AddrSize;
180
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);
184
185     /* Adjust the segment size and set the section offset */
186     Seg->Size  += S->Fill;
187     S->Offs     = Seg->Size;    /* Current size is offset */
188
189     /* Insert the section into the segment */
190     if (Seg->SecRoot == 0) {
191         /* First section in this segment */
192         Seg->SecRoot = S;
193     } else {
194         Seg->SecLast->Next = S;
195     }
196     Seg->SecLast = S;
197
198     /* Return the struct */
199     return S;
200 }
201
202
203
204 Section* ReadSection (FILE* F, ObjData* O)
205 /* Read a section from a file */
206 {
207     unsigned      Name;
208     unsigned      Size;
209     unsigned char Align;
210     unsigned char Type;
211     unsigned      FragCount;
212     Segment*      S;
213     Section*      Sec;
214     LineInfo*     LI;
215
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 */
223
224
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);
228
229     /* Get the segment for this section */
230     S = GetSegment (Name, Type, GetObjFileName (O));
231
232     /* Allocate the section we will return later */
233     Sec = NewSection (S, Align, Type);
234
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;
239         S->AlignObj = O;
240     }
241
242     /* Start reading fragments from the file and insert them into the section . */
243     LI = 0;
244     while (FragCount--) {
245
246         Fragment* Frag;
247         FilePos   Pos;
248         unsigned  LineInfoIndex;
249
250         /* Read the fragment type */
251         unsigned char Type = Read8 (F);
252
253         /* Extract the check mask from the type */
254         unsigned char Bytes = Type & FRAG_BYTEMASK;
255         Type &= FRAG_TYPEMASK;
256
257         /* Handle the different fragment types */
258         switch (Type) {
259
260             case FRAG_LITERAL:
261                 Frag = NewFragment (Type, ReadVar (F), Sec);
262                 ReadData (F, Frag->LitBuf, Frag->Size);
263                 break;
264
265             case FRAG_EXPR:
266             case FRAG_SEXPR:
267                 Frag = NewFragment (Type, Bytes, Sec);
268                 Frag->Expr = ReadExpr (F, O);
269                 break;
270
271             case FRAG_FILL:
272                 /* Will allocate memory, but we don't care... */
273                 Frag = NewFragment (Type, ReadVar (F), Sec);
274                 break;
275
276             default:
277                 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
278                        GetObjFileName (O), GetString (S->Name), Type);
279                 /* NOTREACHED */
280                 return 0;
281         }
282
283         /* Read the file position of the fragment */
284         ReadFilePos (F, &Pos);
285
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
288          * a new LineInfo.
289          */
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);
295         }
296         AddLineInfo (Frag, LI);
297
298         /* Read additional line info and resolve it */
299         LineInfoIndex = ReadVar (F);
300         if (LineInfoIndex) {
301             --LineInfoIndex;
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.
307              */
308             if (LineInfoIndex >= O->LineInfoCount) {
309                 Internal ("In module `%s', file `%s', line %lu: Invalid line "
310                           "info with index %u (max count %u)",
311                           GetObjFileName (O),
312                           GetFragmentSourceName (Frag),
313                           GetFragmentSourceLine (Frag),
314                           LineInfoIndex,
315                           O->LineInfoCount);
316             }
317             /* Add line info to the fragment */
318             AddLineInfo (Frag, CollAt (&O->LineInfos, LineInfoIndex));
319         }
320
321         /* Remember the module we had this fragment from */
322         Frag->Obj = O;
323     }
324
325     /* Return the section */
326     return Sec;
327 }
328
329
330
331 Segment* SegFind (unsigned Name)
332 /* Return the given segment or NULL if not found. */
333 {
334     Segment* S = HashTab[Name & HASHTAB_MASK];
335     while (S) {
336         if (Name == S->Name) {
337             /* Found */
338             break;
339         }
340         S = S->Next;
341     }
342     /* Not found */
343     return S;
344 }
345
346
347
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.
351  */
352 {
353     /* Loop over all sections */
354     Section* Sec = S->SecRoot;
355     while (Sec) {
356         /* Loop over all fragments */
357         Fragment* F = Sec->FragRoot;
358         while (F) {
359             if (F->Type == FRAG_LITERAL) {
360                 unsigned char* Data = F->LitBuf;
361                 unsigned long Count = F->Size;
362                 while (Count--) {
363                     if (*Data++ != 0) {
364                         return 0;
365                     }
366                 }
367             } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
368                 if (GetExprVal (F->Expr) != 0) {
369                     return 0;
370                 }
371             }
372             F = F->Next;
373         }
374         Sec = Sec->Next;
375     }
376     return 1;
377 }
378
379
380
381 void SegDump (void)
382 /* Dump the segments and it's contents */
383 {
384     unsigned I;
385     unsigned long Count;
386     unsigned char* Data;
387
388     Segment* Seg = SegRoot;
389     while (Seg) {
390         Section* S = Seg->SecRoot;
391         printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
392         while (S) {
393             Fragment* F = S->FragRoot;
394             printf ("  Section:\n");
395             while (F) {
396                 switch (F->Type) {
397
398                     case FRAG_LITERAL:
399                         printf ("    Literal (%u bytes):", F->Size);
400                         Count = F->Size;
401                         Data  = F->LitBuf;
402                         I = 100;
403                         while (Count--) {
404                             if (I > 75) {
405                                 printf ("\n   ");
406                                 I = 3;
407                             }
408                             printf (" %02X", *Data++);
409                             I += 3;
410                         }
411                         printf ("\n");
412                         break;
413
414                     case FRAG_EXPR:
415                         printf ("    Expression (%u bytes):\n", F->Size);
416                         printf ("    ");
417                         DumpExpr (F->Expr, 0);
418                         break;
419
420                     case FRAG_SEXPR:
421                         printf ("    Signed expression (%u bytes):\n", F->Size);
422                         printf ("      ");
423                         DumpExpr (F->Expr, 0);
424                         break;
425
426                     case FRAG_FILL:
427                         printf ("    Empty space (%u bytes)\n", F->Size);
428                         break;
429
430                     default:
431                         Internal ("Invalid fragment type: %02X", F->Type);
432                 }
433                 F = F->Next;
434             }
435             S = S->Next;
436         }
437         Seg = Seg->List;
438     }
439 }
440
441
442
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.
446  */
447 {
448     static const unsigned long U_HighRange [4] = {
449         0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
450     };
451     static const long S_HighRange [4] = {
452         0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
453     };
454     static const long S_LowRange [4] = {
455         0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
456     };
457
458
459     /* Get the expression value */
460     long Val = GetExprVal (E);
461
462     /* Check the size */
463     CHECK (Size >= 1 && Size <= 4);
464
465     /* Check for a range error */
466     if (Signed) {
467         if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
468             /* Range error */
469             return SEG_EXPR_RANGE_ERROR;
470         }
471     } else {
472         if (((unsigned long)Val) > U_HighRange [Size-1]) {
473             /* Range error */
474             return SEG_EXPR_RANGE_ERROR;
475         }
476     }
477
478     /* Write the value to the file */
479     WriteVal (F, Val, Size);
480
481     /* Success */
482     return SEG_EXPR_OK;
483 }
484
485
486
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).
490  */
491 {
492     Section*      Sec;
493     int           Sign;
494     unsigned long Offs = 0;
495
496
497     /* Remember the output file and offset for the segment */
498     S->OutputName = TgtName;
499     S->OutputOffs = (unsigned long) ftell (Tgt);
500
501     /* Loop over all sections in this segment */
502     Sec = S->SecRoot;
503     while (Sec) {
504         Fragment* Frag;
505
506         /* If we have fill bytes, write them now */
507         WriteMult (Tgt, S->FillVal, Sec->Fill);
508         Offs += Sec->Fill;
509
510         /* Loop over all fragments in this section */
511         Frag = Sec->FragRoot;
512         while (Frag) {
513
514             /* Do fragment alignment checks */
515
516
517
518             /* Output fragment data */
519             switch (Frag->Type) {
520
521                 case FRAG_LITERAL:
522                     WriteData (Tgt, Frag->LitBuf, Frag->Size);
523                     break;
524
525                 case FRAG_EXPR:
526                 case FRAG_SEXPR:
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)) {
530
531                         case SEG_EXPR_OK:
532                             break;
533
534                         case SEG_EXPR_RANGE_ERROR:
535                             Error ("Range error in module `%s', line %lu",
536                                    GetFragmentSourceName (Frag),
537                                    GetFragmentSourceLine (Frag));
538                             break;
539
540                         case SEG_EXPR_TOO_COMPLEX:
541                             Error ("Expression too complex in module `%s', line %lu",
542                                    GetFragmentSourceName (Frag),
543                                    GetFragmentSourceLine (Frag));
544                             break;
545
546                         case SEG_EXPR_INVALID:
547                             Error ("Invalid expression in module `%s', line %lu",
548                                    GetFragmentSourceName (Frag),
549                                    GetFragmentSourceLine (Frag));
550                             break;
551
552                         default:
553                             Internal ("Invalid return code from SegWriteFunc");
554                     }
555                     break;
556
557                 case FRAG_FILL:
558                     WriteMult (Tgt, S->FillVal, Frag->Size);
559                     break;
560
561                 default:
562                     Internal ("Invalid fragment type: %02X", Frag->Type);
563             }
564
565             /* Update the offset */
566             Offs += Frag->Size;
567
568             /* Next fragment */
569             Frag = Frag->Next;
570         }
571
572         /* Next section */
573         Sec = Sec->Next;
574     }
575 }
576
577
578
579 static int CmpSegStart (const void* K1, const void* K2)
580 /* Compare function for qsort */
581 {
582     /* Get the real segment pointers */
583     const Segment* S1 = *(const Segment**)K1;
584     const Segment* S2 = *(const Segment**)K2;
585
586     /* Compare the start addresses */
587     if (S1->PC > S2->PC) {
588         return 1;
589     } else if (S1->PC < S2->PC) {
590         return -1;
591     } else {
592         /* Sort segments with equal starts by name */
593         return strcmp (GetString (S1->Name), GetString (S2->Name));
594     }
595 }
596
597
598
599 void PrintSegmentMap (FILE* F)
600 /* Print a segment map to the given file */
601 {
602     unsigned I;
603     Segment* S;
604     Segment** SegPool;
605
606     /* Allocate memory for the segment pool */
607     SegPool = xmalloc (SegCount * sizeof (Segment*));
608
609     /* Collect pointers to the segments */
610     I = 0;
611     S = SegRoot;
612     while (S) {
613
614         /* Check the count for safety */
615         CHECK (I < SegCount);
616
617         /* Remember the pointer */
618         SegPool [I] = S;
619
620         /* Follow the linked list */
621         S = S->List;
622
623         /* Next array index */
624         ++I;
625     }
626     CHECK (I == SegCount);
627
628     /* Sort the array by increasing start addresses */
629     qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
630
631     /* Print a header */
632     fprintf (F, "Name                  Start   End     Size\n"
633                 "--------------------------------------------\n");
634
635     /* Print the segments */
636     for (I = 0; I < SegCount; ++I) {
637
638         /* Get a pointer to the segment */
639         S = SegPool [I];
640
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;
645             if (S->Size > 0) {
646                 /* Point to last element addressed */
647                 --End;
648             }
649             fprintf (F, "%-20s  %06lX  %06lX  %06lX\n",
650                      GetString (S->Name), S->PC, End, S->Size);
651         }
652     }
653
654     /* Free the segment pool */
655     xfree (SegPool);
656 }
657
658
659
660 void PrintDbgSegments (FILE* F)
661 /* Output the segments to the debug file */
662 {
663     /* Walk over all segments */
664     Segment* S = SegRoot;
665     while (S) {
666
667         /* Print the segment data */
668         fprintf (F,
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");
673         if (S->OutputName) {
674             fprintf (F, ",outputname=\"%s\",outputoffs=%lu",
675                      S->OutputName, S->OutputOffs);
676         }
677         fputc ('\n', F);
678
679         /* Follow the linked list */
680         S = S->List;
681     }
682 }
683
684
685
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.
689  */
690 {
691     Segment* S = SegRoot;
692     while (S) {
693         if (S->Size > 0 && S->Dumped == 0) {
694             Error ("Missing memory area assignment for segment `%s'",
695                    GetString (S->Name));
696         }
697         S = S->List;
698     }
699 }
700
701
702