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