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