]> git.sur5r.net Git - cc65/blob - src/ld65/segments.c
Replace more linked lists by collections.
[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->Align       = 0;
100     S->FillVal     = 0;
101     S->AddrSize    = AddrSize;
102     S->ReadOnly    = 0;
103     S->Relocatable = 0;
104     S->Dumped      = 0;
105
106     /* Insert the segment into the segment list and assign the segment id */
107     if (SegRoot == 0) {
108         S->Id = 0;
109     } else {
110         S->Id = SegRoot->Id + 1;
111     }
112     S->List = SegRoot;
113     SegRoot = S;
114     ++SegCount;
115
116     /* Insert the segment into the segment hash list */
117     Hash = (S->Name & HASHTAB_MASK);
118     S->Next = HashTab[Hash];
119     HashTab[Hash] = S;
120
121     /* Return the new entry */
122     return S;
123 }
124
125
126
127 Segment* GetSegment (unsigned Name, unsigned char AddrSize, const char* ObjName)
128 /* Search for a segment and return an existing one. If the segment does not
129  * exist, create a new one and return that. ObjName is only used for the error
130  * message and may be NULL if the segment is linker generated.
131  */
132 {
133     /* Try to locate the segment in the table */
134     Segment* S = SegFind (Name);
135
136     /* If we don't have that segment already, allocate it using the type of
137      * the first section.
138      */
139     if (S == 0) {
140         /* Create a new segment */
141         S = NewSegment (Name, AddrSize);
142     } else {
143         /* Check if the existing segment has the requested address size */
144         if (S->AddrSize != AddrSize) {
145             /* Allow an empty object name */
146             if (ObjName == 0) {
147                 ObjName = "[linker generated]";
148             }
149             Error ("Module `%s': Type mismatch for segment `%s'", ObjName,
150                    GetString (Name));
151         }
152     }
153
154     /* Return the segment */
155     return S;
156 }
157
158
159
160 Section* NewSection (Segment* Seg, unsigned char Align, unsigned char AddrSize)
161 /* Create a new section for the given segment */
162 {
163     unsigned long V;
164
165
166     /* Allocate memory */
167     Section* S = xmalloc (sizeof (Section));
168
169     /* Initialize the data */
170     S->Next     = 0;
171     S->Seg      = Seg;
172     S->FragRoot = 0;
173     S->FragLast = 0;
174     S->Size     = 0;
175     S->Align    = Align;
176     S->AddrSize = AddrSize;
177
178     /* Calculate the alignment bytes needed for the section */
179     V = (0x01UL << S->Align) - 1;
180     S->Fill = (unsigned char) (((Seg->Size + V) & ~V) - Seg->Size);
181
182     /* Adjust the segment size and set the section offset */
183     Seg->Size  += S->Fill;
184     S->Offs     = Seg->Size;    /* Current size is offset */
185
186     /* Insert the section into the segment */
187     if (Seg->SecRoot == 0) {
188         /* First section in this segment */
189         Seg->SecRoot = S;
190     } else {
191         Seg->SecLast->Next = S;
192     }
193     Seg->SecLast = S;
194
195     /* Return the struct */
196     return S;
197 }
198
199
200
201 Section* ReadSection (FILE* F, ObjData* O)
202 /* Read a section from a file */
203 {
204     unsigned      Name;
205     unsigned      Size;
206     unsigned char Align;
207     unsigned char Type;
208     unsigned      FragCount;
209     Segment*      S;
210     Section*      Sec;
211     LineInfo*     LI;
212
213     /* Read the segment data */
214     (void) Read32 (F);            /* File size of data */
215     Name      = MakeGlobalStringId (O, ReadVar (F));    /* Segment name */
216     Size      = Read32 (F);       /* Size of data */
217     Align     = Read8 (F);        /* Alignment */
218     Type      = Read8 (F);        /* Segment type */
219     FragCount = ReadVar (F);      /* Number of fragments */
220
221
222     /* Print some data */
223     Print (stdout, 2, "Module `%s': Found segment `%s', size = %u, align = %u, type = %u\n",
224            GetObjFileName (O), GetString (Name), Size, Align, Type);
225
226     /* Get the segment for this section */
227     S = GetSegment (Name, Type, GetObjFileName (O));
228
229     /* Allocate the section we will return later */
230     Sec = NewSection (S, Align, Type);
231
232     /* Set up the minimum segment alignment */
233     if (Sec->Align > S->Align) {
234         /* Section needs larger alignment, use this one */
235         S->Align    = Sec->Align;
236         S->AlignObj = O;
237     }
238
239     /* Start reading fragments from the file and insert them into the section . */
240     LI = 0;
241     while (FragCount--) {
242
243         Fragment* Frag;
244         FilePos   Pos;
245         unsigned  LineInfoIndex;
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 file position of the fragment */
281         ReadFilePos (F, &Pos);
282
283         /* Generate a LineInfo for this fragment. First check if this fragment
284          * was generated by the same line than that before. If not, generate
285          * a new LineInfo.
286          */
287         if (LI == 0 || LI->Pos.Line != Pos.Line || LI->Pos.Col != Pos.Col ||
288             LI->Pos.Name != Pos.Name) {
289             /* We don't have a previous line info or this one is different */
290             LI = NewLineInfo (O, &Pos);
291             CollAppend (&O->LineInfos, LI);
292         }
293         AddLineInfo (Frag, LI);
294
295         /* Read additional line info and resolve it */
296         LineInfoIndex = ReadVar (F);
297         if (LineInfoIndex) {
298             --LineInfoIndex;
299             /* The line info index was written by the assembler and must
300              * therefore be part of the line infos read from the object file.
301              * To make sure this is true, don't compare against the count
302              * of line infos in the collection (which grows) but against the
303              * count initialized when reading from the file.
304              */
305             if (LineInfoIndex >= O->LineInfoCount) {
306                 Internal ("In module `%s', file `%s', line %lu: Invalid line "
307                           "info with index %u (max count %u)",
308                           GetObjFileName (O),
309                           GetFragmentSourceName (Frag),
310                           GetFragmentSourceLine (Frag),
311                           LineInfoIndex,
312                           O->LineInfoCount);
313             }
314             /* Add line info to the fragment */
315             AddLineInfo (Frag, CollAt (&O->LineInfos, LineInfoIndex));
316         }
317
318         /* Remember the module we had this fragment from */
319         Frag->Obj = O;
320     }
321
322     /* Return the section */
323     return Sec;
324 }
325
326
327
328 Segment* SegFind (unsigned Name)
329 /* Return the given segment or NULL if not found. */
330 {
331     Segment* S = HashTab[Name & HASHTAB_MASK];
332     while (S) {
333         if (Name == S->Name) {
334             /* Found */
335             break;
336         }
337         S = S->Next;
338     }
339     /* Not found */
340     return S;
341 }
342
343
344
345 int IsBSSType (Segment* S)
346 /* Check if the given segment is a BSS style segment, that is, it does not
347  * contain non-zero data.
348  */
349 {
350     /* Loop over all sections */
351     Section* Sec = S->SecRoot;
352     while (Sec) {
353         /* Loop over all fragments */
354         Fragment* F = Sec->FragRoot;
355         while (F) {
356             if (F->Type == FRAG_LITERAL) {
357                 unsigned char* Data = F->LitBuf;
358                 unsigned long Count = F->Size;
359                 while (Count--) {
360                     if (*Data++ != 0) {
361                         return 0;
362                     }
363                 }
364             } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
365                 if (GetExprVal (F->Expr) != 0) {
366                     return 0;
367                 }
368             }
369             F = F->Next;
370         }
371         Sec = Sec->Next;
372     }
373     return 1;
374 }
375
376
377
378 void SegDump (void)
379 /* Dump the segments and it's contents */
380 {
381     unsigned I;
382     unsigned long Count;
383     unsigned char* Data;
384
385     Segment* Seg = SegRoot;
386     while (Seg) {
387         Section* S = Seg->SecRoot;
388         printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
389         while (S) {
390             Fragment* F = S->FragRoot;
391             printf ("  Section:\n");
392             while (F) {
393                 switch (F->Type) {
394
395                     case FRAG_LITERAL:
396                         printf ("    Literal (%u bytes):", F->Size);
397                         Count = F->Size;
398                         Data  = F->LitBuf;
399                         I = 100;
400                         while (Count--) {
401                             if (I > 75) {
402                                 printf ("\n   ");
403                                 I = 3;
404                             }
405                             printf (" %02X", *Data++);
406                             I += 3;
407                         }
408                         printf ("\n");
409                         break;
410
411                     case FRAG_EXPR:
412                         printf ("    Expression (%u bytes):\n", F->Size);
413                         printf ("    ");
414                         DumpExpr (F->Expr, 0);
415                         break;
416
417                     case FRAG_SEXPR:
418                         printf ("    Signed expression (%u bytes):\n", F->Size);
419                         printf ("      ");
420                         DumpExpr (F->Expr, 0);
421                         break;
422
423                     case FRAG_FILL:
424                         printf ("    Empty space (%u bytes)\n", F->Size);
425                         break;
426
427                     default:
428                         Internal ("Invalid fragment type: %02X", F->Type);
429                 }
430                 F = F->Next;
431             }
432             S = S->Next;
433         }
434         Seg = Seg->List;
435     }
436 }
437
438
439
440 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
441 /* Write a supposedly constant expression to the target file. Do a range
442  * check and return one of the SEG_EXPR_xxx codes.
443  */
444 {
445     static const unsigned long U_HighRange [4] = {
446         0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
447     };
448     static const long S_HighRange [4] = {
449         0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
450     };
451     static const long S_LowRange [4] = {
452         0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
453     };
454
455
456     /* Get the expression value */
457     long Val = GetExprVal (E);
458
459     /* Check the size */
460     CHECK (Size >= 1 && Size <= 4);
461
462     /* Check for a range error */
463     if (Signed) {
464         if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
465             /* Range error */
466             return SEG_EXPR_RANGE_ERROR;
467         }
468     } else {
469         if (((unsigned long)Val) > U_HighRange [Size-1]) {
470             /* Range error */
471             return SEG_EXPR_RANGE_ERROR;
472         }
473     }
474
475     /* Write the value to the file */
476     WriteVal (F, Val, Size);
477
478     /* Success */
479     return SEG_EXPR_OK;
480 }
481
482
483
484 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
485 /* Write the data from the given segment to a file. For expressions, F is
486  * called (see description of SegWriteFunc above).
487  */
488 {
489     int Sign;
490     unsigned long Offs = 0;
491
492     /* Loop over all sections in this segment */
493     Section* Sec = S->SecRoot;
494     while (Sec) {
495         Fragment* Frag;
496
497         /* If we have fill bytes, write them now */
498         WriteMult (Tgt, S->FillVal, Sec->Fill);
499         Offs += Sec->Fill;
500
501         /* Loop over all fragments in this section */
502         Frag = Sec->FragRoot;
503         while (Frag) {
504
505             /* Do fragment alignment checks */
506
507
508
509             /* Output fragment data */
510             switch (Frag->Type) {
511
512                 case FRAG_LITERAL:
513                     WriteData (Tgt, Frag->LitBuf, Frag->Size);
514                     break;
515
516                 case FRAG_EXPR:
517                 case FRAG_SEXPR:
518                     Sign = (Frag->Type == FRAG_SEXPR);
519                     /* Call the users function and evaluate the result */
520                     switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
521
522                         case SEG_EXPR_OK:
523                             break;
524
525                         case SEG_EXPR_RANGE_ERROR:
526                             Error ("Range error in module `%s', line %lu",
527                                    GetFragmentSourceName (Frag),
528                                    GetFragmentSourceLine (Frag));
529                             break;
530
531                         case SEG_EXPR_TOO_COMPLEX:
532                             Error ("Expression too complex in module `%s', line %lu",
533                                    GetFragmentSourceName (Frag),
534                                    GetFragmentSourceLine (Frag));
535                             break;
536
537                         case SEG_EXPR_INVALID:
538                             Error ("Invalid expression in module `%s', line %lu",
539                                    GetFragmentSourceName (Frag),
540                                    GetFragmentSourceLine (Frag));
541                             break;
542
543                         default:
544                             Internal ("Invalid return code from SegWriteFunc");
545                     }
546                     break;
547
548                 case FRAG_FILL:
549                     WriteMult (Tgt, S->FillVal, Frag->Size);
550                     break;
551
552                 default:
553                     Internal ("Invalid fragment type: %02X", Frag->Type);
554             }
555
556             /* Update the offset */
557             Offs += Frag->Size;
558
559             /* Next fragment */
560             Frag = Frag->Next;
561         }
562
563         /* Next section */
564         Sec = Sec->Next;
565     }
566 }
567
568
569
570 static int CmpSegStart (const void* K1, const void* K2)
571 /* Compare function for qsort */
572 {
573     /* Get the real segment pointers */
574     const Segment* S1 = *(const Segment**)K1;
575     const Segment* S2 = *(const Segment**)K2;
576
577     /* Compare the start addresses */
578     if (S1->PC > S2->PC) {
579         return 1;
580     } else if (S1->PC < S2->PC) {
581         return -1;
582     } else {
583         /* Sort segments with equal starts by name */
584         return strcmp (GetString (S1->Name), GetString (S2->Name));
585     }
586 }
587
588
589
590 void PrintSegmentMap (FILE* F)
591 /* Print a segment map to the given file */
592 {
593     unsigned I;
594     Segment* S;
595     Segment** SegPool;
596
597     /* Allocate memory for the segment pool */
598     SegPool = xmalloc (SegCount * sizeof (Segment*));
599
600     /* Collect pointers to the segments */
601     I = 0;
602     S = SegRoot;
603     while (S) {
604
605         /* Check the count for safety */
606         CHECK (I < SegCount);
607
608         /* Remember the pointer */
609         SegPool [I] = S;
610
611         /* Follow the linked list */
612         S = S->List;
613
614         /* Next array index */
615         ++I;
616     }
617     CHECK (I == SegCount);
618
619     /* Sort the array by increasing start addresses */
620     qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
621
622     /* Print a header */
623     fprintf (F, "Name                  Start   End     Size\n"
624                 "--------------------------------------------\n");
625
626     /* Print the segments */
627     for (I = 0; I < SegCount; ++I) {
628
629         /* Get a pointer to the segment */
630         S = SegPool [I];
631
632         /* Print empty segments only if explicitly requested */
633         if (VerboseMap || S->Size > 0) {
634             /* Print the segment data */
635             long End = S->PC + S->Size;
636             if (S->Size > 0) {
637                 /* Point to last element addressed */
638                 --End;
639             }
640             fprintf (F, "%-20s  %06lX  %06lX  %06lX\n",
641                      GetString (S->Name), S->PC, End, S->Size);
642         }
643     }
644
645     /* Free the segment pool */
646     xfree (SegPool);
647 }
648
649
650
651 void PrintDbgSegments (FILE* F)
652 /* Output the segments to the debug file */
653 {
654     Segment* S;
655
656     /* Walk over all segments */
657     S = SegRoot;
658     while (S) {
659
660         /* Ignore empty segments */
661         if (S->Size > 0) {
662
663             /* Print the segment data */
664             fprintf (F, 
665                      "segment\tid=%u,name=\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s\n",
666                      S->Id, GetString (S->Name), S->PC, S->Size,
667                      AddrSizeToStr (S->AddrSize),
668                      S->ReadOnly? "ro" : "rw");
669         }
670
671         /* Follow the linked list */
672         S = S->List;
673     }
674 }
675
676
677
678 void CheckSegments (void)
679 /* Walk through the segment list and check if there are segments that were
680  * not written to the output file. Output an error if this is the case.
681  */
682 {
683     Segment* S = SegRoot;
684     while (S) {
685         if (S->Size > 0 && S->Dumped == 0) {
686             Error ("Missing memory area assignment for segment `%s'",
687                    GetString (S->Name));
688         }
689         S = S->List;
690     }
691 }
692
693
694