]> git.sur5r.net Git - cc65/blob - src/ld65/segments.c
Fixed an error: The amount of fill bytes for a section was declared as an
[cc65] / src / ld65 / segments.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                segments.c                                 */
4 /*                                                                           */
5 /*                   Segment handling for the ld65 linker                    */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2011, 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->Obj      = 0;
176     S->FragRoot = 0;
177     S->FragLast = 0;
178     S->Size     = 0;
179     S->Align    = Align;
180     S->AddrSize = AddrSize;
181
182     /* Calculate the alignment bytes needed for the section */
183     V = (0x01UL << S->Align) - 1;
184     S->Fill = (((Seg->Size + V) & ~V) - Seg->Size);
185
186     /* Adjust the segment size and set the section offset */
187     Seg->Size  += S->Fill;
188     S->Offs     = Seg->Size;    /* Current size is offset */
189
190     /* Insert the section into the segment */
191     if (Seg->SecRoot == 0) {
192         /* First section in this segment */
193         Seg->SecRoot = S;
194     } else {
195         Seg->SecLast->Next = S;
196     }
197     Seg->SecLast = S;
198
199     /* Return the struct */
200     return S;
201 }
202
203
204
205 Section* ReadSection (FILE* F, ObjData* O)
206 /* Read a section from a file */
207 {
208     unsigned      Name;
209     unsigned      Size;
210     unsigned char Align;
211     unsigned char Type;
212     unsigned      FragCount;
213     Segment*      S;
214     Section*      Sec;
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     /* Remember the object file this section was from */
236     Sec->Obj = O;
237
238     /* Set up the minimum segment alignment */
239     if (Sec->Align > S->Align) {
240         /* Section needs larger alignment, use this one */
241         S->Align    = Sec->Align;
242         S->AlignObj = O;
243     }
244
245     /* Start reading fragments from the file and insert them into the section . */
246     while (FragCount--) {
247
248         Fragment* Frag;
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 line infos into the list of the fragment */
284         ReadLineInfoList (F, O, &Frag->LineInfos);
285
286         /* Resolve the back pointers */
287         FragResolveLineInfos (Frag);
288
289         /* Remember the module we had this fragment from */
290         Frag->Obj = O;
291     }
292
293     /* Return the section */
294     return Sec;
295 }
296
297
298
299 Segment* SegFind (unsigned Name)
300 /* Return the given segment or NULL if not found. */
301 {
302     Segment* S = HashTab[Name & HASHTAB_MASK];
303     while (S) {
304         if (Name == S->Name) {
305             /* Found */
306             break;
307         }
308         S = S->Next;
309     }
310     /* Not found */
311     return S;
312 }
313
314
315
316 int IsBSSType (Segment* S)
317 /* Check if the given segment is a BSS style segment, that is, it does not
318  * contain non-zero data.
319  */
320 {
321     /* Loop over all sections */
322     Section* Sec = S->SecRoot;
323     while (Sec) {
324         /* Loop over all fragments */
325         Fragment* F = Sec->FragRoot;
326         while (F) {
327             if (F->Type == FRAG_LITERAL) {
328                 unsigned char* Data = F->LitBuf;
329                 unsigned long Count = F->Size;
330                 while (Count--) {
331                     if (*Data++ != 0) {
332                         return 0;
333                     }
334                 }
335             } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
336                 if (GetExprVal (F->Expr) != 0) {
337                     return 0;
338                 }
339             }
340             F = F->Next;
341         }
342         Sec = Sec->Next;
343     }
344     return 1;
345 }
346
347
348
349 void SegDump (void)
350 /* Dump the segments and it's contents */
351 {
352     unsigned I;
353     unsigned long Count;
354     unsigned char* Data;
355
356     Segment* Seg = SegRoot;
357     while (Seg) {
358         Section* S = Seg->SecRoot;
359         printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
360         while (S) {
361             Fragment* F = S->FragRoot;
362             printf ("  Section:\n");
363             while (F) {
364                 switch (F->Type) {
365
366                     case FRAG_LITERAL:
367                         printf ("    Literal (%u bytes):", F->Size);
368                         Count = F->Size;
369                         Data  = F->LitBuf;
370                         I = 100;
371                         while (Count--) {
372                             if (I > 75) {
373                                 printf ("\n   ");
374                                 I = 3;
375                             }
376                             printf (" %02X", *Data++);
377                             I += 3;
378                         }
379                         printf ("\n");
380                         break;
381
382                     case FRAG_EXPR:
383                         printf ("    Expression (%u bytes):\n", F->Size);
384                         printf ("    ");
385                         DumpExpr (F->Expr, 0);
386                         break;
387
388                     case FRAG_SEXPR:
389                         printf ("    Signed expression (%u bytes):\n", F->Size);
390                         printf ("      ");
391                         DumpExpr (F->Expr, 0);
392                         break;
393
394                     case FRAG_FILL:
395                         printf ("    Empty space (%u bytes)\n", F->Size);
396                         break;
397
398                     default:
399                         Internal ("Invalid fragment type: %02X", F->Type);
400                 }
401                 F = F->Next;
402             }
403             S = S->Next;
404         }
405         Seg = Seg->List;
406     }
407 }
408
409
410
411 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
412 /* Write a supposedly constant expression to the target file. Do a range
413  * check and return one of the SEG_EXPR_xxx codes.
414  */
415 {
416     static const unsigned long U_HighRange [4] = {
417         0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
418     };
419     static const long S_HighRange [4] = {
420         0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
421     };
422     static const long S_LowRange [4] = {
423         0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
424     };
425
426
427     /* Get the expression value */
428     long Val = GetExprVal (E);
429
430     /* Check the size */
431     CHECK (Size >= 1 && Size <= 4);
432
433     /* Check for a range error */
434     if (Signed) {
435         if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
436             /* Range error */
437             return SEG_EXPR_RANGE_ERROR;
438         }
439     } else {
440         if (((unsigned long)Val) > U_HighRange [Size-1]) {
441             /* Range error */
442             return SEG_EXPR_RANGE_ERROR;
443         }
444     }
445
446     /* Write the value to the file */
447     WriteVal (F, Val, Size);
448
449     /* Success */
450     return SEG_EXPR_OK;
451 }
452
453
454
455 void SegWrite (const char* TgtName, FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
456 /* Write the data from the given segment to a file. For expressions, F is
457  * called (see description of SegWriteFunc above).
458  */
459 {
460     Section*      Sec;
461     int           Sign;
462     unsigned long Offs = 0;
463
464
465     /* Remember the output file and offset for the segment */
466     S->OutputName = TgtName;
467     S->OutputOffs = (unsigned long) ftell (Tgt);
468
469     /* Loop over all sections in this segment */
470     Sec = S->SecRoot;
471     while (Sec) {
472         Fragment* Frag;
473
474         /* Output were this section is from */
475         Print (stdout, 2, "      Section from \"%s\"\n", GetObjFileName (Sec->Obj));
476
477         /* If we have fill bytes, write them now */
478         Print (stdout, 2, "        Filling 0x%lx bytes with 0x%02x\n",
479                Sec->Fill, S->FillVal);
480         WriteMult (Tgt, S->FillVal, Sec->Fill);
481         Offs += Sec->Fill;
482
483         /* Loop over all fragments in this section */
484         Frag = Sec->FragRoot;
485         while (Frag) {
486
487             /* Do fragment alignment checks */
488
489
490
491             /* Output fragment data */
492             switch (Frag->Type) {
493
494                 case FRAG_LITERAL:
495                     WriteData (Tgt, Frag->LitBuf, Frag->Size);
496                     break;
497
498                 case FRAG_EXPR:
499                 case FRAG_SEXPR:
500                     Sign = (Frag->Type == FRAG_SEXPR);
501                     /* Call the users function and evaluate the result */
502                     switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
503
504                         case SEG_EXPR_OK:
505                             break;
506
507                         case SEG_EXPR_RANGE_ERROR:
508                             Error ("Range error in module `%s', line %lu",
509                                    GetFragmentSourceName (Frag),
510                                    GetFragmentSourceLine (Frag));
511                             break;
512
513                         case SEG_EXPR_TOO_COMPLEX:
514                             Error ("Expression too complex in module `%s', line %lu",
515                                    GetFragmentSourceName (Frag),
516                                    GetFragmentSourceLine (Frag));
517                             break;
518
519                         case SEG_EXPR_INVALID:
520                             Error ("Invalid expression in module `%s', line %lu",
521                                    GetFragmentSourceName (Frag),
522                                    GetFragmentSourceLine (Frag));
523                             break;
524
525                         default:
526                             Internal ("Invalid return code from SegWriteFunc");
527                     }
528                     break;
529
530                 case FRAG_FILL:
531                     WriteMult (Tgt, S->FillVal, Frag->Size);
532                     break;
533
534                 default:
535                     Internal ("Invalid fragment type: %02X", Frag->Type);
536             }
537
538             /* Update the offset */
539             Print (stdout, 2, "        Fragment with 0x%x bytes\n",
540                    Frag->Size);
541             Offs += Frag->Size;
542
543             /* Next fragment */
544             Frag = Frag->Next;
545         }
546
547         /* Next section */
548         Sec = Sec->Next;
549     }
550 }
551
552
553
554 static int CmpSegStart (const void* K1, const void* K2)
555 /* Compare function for qsort */
556 {
557     /* Get the real segment pointers */
558     const Segment* S1 = *(const Segment**)K1;
559     const Segment* S2 = *(const Segment**)K2;
560
561     /* Compare the start addresses */
562     if (S1->PC > S2->PC) {
563         return 1;
564     } else if (S1->PC < S2->PC) {
565         return -1;
566     } else {
567         /* Sort segments with equal starts by name */
568         return strcmp (GetString (S1->Name), GetString (S2->Name));
569     }
570 }
571
572
573
574 void PrintSegmentMap (FILE* F)
575 /* Print a segment map to the given file */
576 {
577     unsigned I;
578     Segment* S;
579     Segment** SegPool;
580
581     /* Allocate memory for the segment pool */
582     SegPool = xmalloc (SegCount * sizeof (Segment*));
583
584     /* Collect pointers to the segments */
585     I = 0;
586     S = SegRoot;
587     while (S) {
588
589         /* Check the count for safety */
590         CHECK (I < SegCount);
591
592         /* Remember the pointer */
593         SegPool [I] = S;
594
595         /* Follow the linked list */
596         S = S->List;
597
598         /* Next array index */
599         ++I;
600     }
601     CHECK (I == SegCount);
602
603     /* Sort the array by increasing start addresses */
604     qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
605
606     /* Print a header */
607     fprintf (F, "Name                  Start   End     Size\n"
608                 "--------------------------------------------\n");
609
610     /* Print the segments */
611     for (I = 0; I < SegCount; ++I) {
612
613         /* Get a pointer to the segment */
614         S = SegPool [I];
615
616         /* Print empty segments only if explicitly requested */
617         if (VerboseMap || S->Size > 0) {
618             /* Print the segment data */
619             long End = S->PC + S->Size;
620             if (S->Size > 0) {
621                 /* Point to last element addressed */
622                 --End;
623             }
624             fprintf (F, "%-20s  %06lX  %06lX  %06lX\n",
625                      GetString (S->Name), S->PC, End, S->Size);
626         }
627     }
628
629     /* Free the segment pool */
630     xfree (SegPool);
631 }
632
633
634
635 void PrintDbgSegments (FILE* F)
636 /* Output the segments to the debug file */
637 {
638     /* Walk over all segments */
639     Segment* S = SegRoot;
640     while (S) {
641
642         /* Print the segment data */
643         fprintf (F,
644                  "segment\tid=%u,name=\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s",
645                  S->Id, GetString (S->Name), S->PC, S->Size,
646                  AddrSizeToStr (S->AddrSize),
647                  S->ReadOnly? "ro" : "rw");
648         if (S->OutputName) {
649             fprintf (F, ",outputname=\"%s\",outputoffs=%lu",
650                      S->OutputName, S->OutputOffs);
651         }
652         fputc ('\n', F);
653
654         /* Follow the linked list */
655         S = S->List;
656     }
657 }
658
659
660
661 void CheckSegments (void)
662 /* Walk through the segment list and check if there are segments that were
663  * not written to the output file. Output an error if this is the case.
664  */
665 {
666     Segment* S = SegRoot;
667     while (S) {
668         if (S->Size > 0 && S->Dumped == 0) {
669             Error ("Missing memory area assignment for segment `%s'",
670                    GetString (S->Name));
671         }
672         S = S->List;
673     }
674 }
675
676
677