]> git.sur5r.net Git - cc65/blob - src/ld65/segments.c
a097d9d0351fd0de053e2bdd927fd60530b3af5a
[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 "hashfunc.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         /* Remember the module we had this fragment from */
282         Frag->Obj = O;
283     }
284
285     /* Return the section */
286     return Sec;
287 }
288
289
290
291 Segment* SegFind (unsigned Name)
292 /* Return the given segment or NULL if not found. */
293 {
294     Segment* S = HashTab[Name & HASHTAB_MASK];
295     while (S) {
296         if (Name == S->Name) {
297             /* Found */
298             break;
299         }
300         S = S->Next;
301     }
302     /* Not found */
303     return S;
304 }
305
306
307
308 int IsBSSType (Segment* S)
309 /* Check if the given segment is a BSS style segment, that is, it does not
310  * contain non-zero data.
311  */
312 {
313     /* Loop over all sections */
314     Section* Sec = S->SecRoot;
315     while (Sec) {
316         /* Loop over all fragments */
317         Fragment* F = Sec->FragRoot;
318         while (F) {
319             if (F->Type == FRAG_LITERAL) {
320                 unsigned char* Data = F->LitBuf;
321                 unsigned long Count = F->Size;
322                 while (Count--) {
323                     if (*Data++ != 0) {
324                         return 0;
325                     }
326                 }
327             } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
328                 if (GetExprVal (F->Expr) != 0) {
329                     return 0;
330                 }
331             }
332             F = F->Next;
333         }
334         Sec = Sec->Next;
335     }
336     return 1;
337 }
338
339
340
341 void SegDump (void)
342 /* Dump the segments and it's contents */
343 {
344     unsigned I;
345     unsigned long Count;
346     unsigned char* Data;
347
348     for (I = 0; I < CollCount (&SegmentList); ++I) {
349         const Segment* Seg = CollConstAt (&SegmentList, I);
350         Section* S = Seg->SecRoot;
351         printf ("Segment: %s (%lu)\n", GetString (Seg->Name), Seg->Size);
352         while (S) {
353             unsigned J;
354             Fragment* F = S->FragRoot;
355             printf ("  Section:\n");
356             while (F) {
357                 switch (F->Type) {
358
359                     case FRAG_LITERAL:
360                         printf ("    Literal (%u bytes):", F->Size);
361                         Count = F->Size;
362                         Data  = F->LitBuf;
363                         J = 100;
364                         while (Count--) {
365                             if (J > 75) {
366                                 printf ("\n   ");
367                                 J = 3;
368                             }
369                             printf (" %02X", *Data++);
370                             J += 3;
371                         }
372                         printf ("\n");
373                         break;
374
375                     case FRAG_EXPR:
376                         printf ("    Expression (%u bytes):\n", F->Size);
377                         printf ("    ");
378                         DumpExpr (F->Expr, 0);
379                         break;
380
381                     case FRAG_SEXPR:
382                         printf ("    Signed expression (%u bytes):\n", F->Size);
383                         printf ("      ");
384                         DumpExpr (F->Expr, 0);
385                         break;
386
387                     case FRAG_FILL:
388                         printf ("    Empty space (%u bytes)\n", F->Size);
389                         break;
390
391                     default:
392                         Internal ("Invalid fragment type: %02X", F->Type);
393                 }
394                 F = F->Next;
395             }
396             S = S->Next;
397         }
398     }
399 }
400
401
402
403 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
404 /* Write a supposedly constant expression to the target file. Do a range
405  * check and return one of the SEG_EXPR_xxx codes.
406  */
407 {
408     static const unsigned long U_Hi[4] = {
409         0x000000FFUL, 0x0000FFFFUL, 0x00FFFFFFUL, 0xFFFFFFFFUL
410     };
411     static const long S_Hi[4] = {
412         0x0000007FL, 0x00007FFFL, 0x007FFFFFL, 0x7FFFFFFFL
413     };
414     static const long S_Lo[4] = {
415         ~0x0000007FL, ~0x00007FFFL, ~0x007FFFFFL, ~0x7FFFFFFFL
416     };
417
418
419     /* Get the expression value */
420     long Val = GetExprVal (E);
421
422     /* Check the size */
423     CHECK (Size >= 1 && Size <= 4);
424
425     /* Check for a range error */
426     if (Signed) {
427         if (Val > S_Hi[Size-1] || Val < S_Lo[Size-1]) {
428             /* Range error */
429             return SEG_EXPR_RANGE_ERROR;
430         }
431     } else {
432         if (((unsigned long)Val) > U_Hi[Size-1]) {
433             /* Range error */
434             return SEG_EXPR_RANGE_ERROR;
435         }
436     }
437
438     /* Write the value to the file */
439     WriteVal (F, Val, Size);
440
441     /* Success */
442     return SEG_EXPR_OK;
443 }
444
445
446
447 void SegWrite (const char* TgtName, FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
448 /* Write the data from the given segment to a file. For expressions, F is
449  * called (see description of SegWriteFunc above).
450  */
451 {
452     Section*      Sec;
453     int           Sign;
454     unsigned long Offs = 0;
455
456
457     /* Remember the output file and offset for the segment */
458     S->OutputName = TgtName;
459     S->OutputOffs = (unsigned long) ftell (Tgt);
460
461     /* Loop over all sections in this segment */
462     Sec = S->SecRoot;
463     while (Sec) {
464         Fragment* Frag;
465
466         /* Output were this section is from */
467         Print (stdout, 2, "      Section from \"%s\"\n", GetObjFileName (Sec->Obj));
468
469         /* If we have fill bytes, write them now */
470         Print (stdout, 2, "        Filling 0x%lx bytes with 0x%02x\n",
471                Sec->Fill, S->FillVal);
472         WriteMult (Tgt, S->FillVal, Sec->Fill);
473         Offs += Sec->Fill;
474
475         /* Loop over all fragments in this section */
476         Frag = Sec->FragRoot;
477         while (Frag) {
478
479             /* Do fragment alignment checks */
480
481
482
483             /* Output fragment data */
484             switch (Frag->Type) {
485
486                 case FRAG_LITERAL:
487                     WriteData (Tgt, Frag->LitBuf, Frag->Size);
488                     break;
489
490                 case FRAG_EXPR:
491                 case FRAG_SEXPR:
492                     Sign = (Frag->Type == FRAG_SEXPR);
493                     /* Call the users function and evaluate the result */
494                     switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
495
496                         case SEG_EXPR_OK:
497                             break;
498
499                         case SEG_EXPR_RANGE_ERROR:
500                             Error ("Range error in module `%s', line %lu",
501                                    GetFragmentSourceName (Frag),
502                                    GetFragmentSourceLine (Frag));
503                             break;
504
505                         case SEG_EXPR_TOO_COMPLEX:
506                             Error ("Expression too complex in module `%s', line %lu",
507                                    GetFragmentSourceName (Frag),
508                                    GetFragmentSourceLine (Frag));
509                             break;
510
511                         case SEG_EXPR_INVALID:
512                             Error ("Invalid expression in module `%s', line %lu",
513                                    GetFragmentSourceName (Frag),
514                                    GetFragmentSourceLine (Frag));
515                             break;
516
517                         default:
518                             Internal ("Invalid return code from SegWriteFunc");
519                     }
520                     break;
521
522                 case FRAG_FILL:
523                     WriteMult (Tgt, S->FillVal, Frag->Size);
524                     break;
525
526                 default:
527                     Internal ("Invalid fragment type: %02X", Frag->Type);
528             }
529
530             /* Update the offset */
531             Print (stdout, 2, "        Fragment with 0x%x bytes\n",
532                    Frag->Size);
533             Offs += Frag->Size;
534
535             /* Next fragment */
536             Frag = Frag->Next;
537         }
538
539         /* Next section */
540         Sec = Sec->Next;
541     }
542 }
543
544
545
546 unsigned SegmentCount (void)
547 /* Return the total number of segments */
548 {
549     return CollCount (&SegmentList);
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
578     /* Allocate memory for the segment pool */
579     Segment** SegPool = xmalloc (CollCount (&SegmentList) * sizeof (Segment*));
580
581     /* Copy the segment pointers */
582     unsigned I;
583     for (I = 0; I < CollCount (&SegmentList); ++I) {
584         SegPool[I] = CollAtUnchecked (&SegmentList, I);
585     }
586
587     /* Sort the array by increasing start addresses */
588     qsort (SegPool, CollCount (&SegmentList), sizeof (Segment*), CmpSegStart);
589
590     /* Print a header */
591     fprintf (F, "Name                  Start   End     Size\n"
592                 "--------------------------------------------\n");
593
594     /* Print the segments */
595     for (I = 0; I < CollCount (&SegmentList); ++I) {
596
597         /* Get a pointer to the segment */
598         Segment* S = SegPool[I];
599
600         /* Print empty segments only if explicitly requested */
601         if (VerboseMap || S->Size > 0) {
602             /* Print the segment data */
603             long End = S->PC + S->Size;
604             if (S->Size > 0) {
605                 /* Point to last element addressed */
606                 --End;
607             }
608             fprintf (F, "%-20s  %06lX  %06lX  %06lX\n",
609                      GetString (S->Name), S->PC, End, S->Size);
610         }
611     }
612
613     /* Free the segment pool */
614     xfree (SegPool);
615 }
616
617
618
619 void PrintDbgSegments (FILE* F)
620 /* Output the segments to the debug file */
621 {
622     /* Walk over all segments */
623     unsigned I;
624     for (I = 0; I < CollCount (&SegmentList); ++I) {
625
626         /* Get the next segment */
627         const Segment* S = CollAtUnchecked (&SegmentList, I);
628
629         /* Print the segment data */
630         fprintf (F,
631                  "seg\tid=%u,name=\"%s\",start=0x%06lX,size=0x%04lX,addrsize=%s,type=%s",
632                  S->Id, GetString (S->Name), S->PC, S->Size,
633                  AddrSizeToStr (S->AddrSize),
634                  S->ReadOnly? "ro" : "rw");
635         if (S->OutputName) {
636             fprintf (F, ",oname=\"%s\",ooffs=%lu",
637                      S->OutputName, S->OutputOffs);
638         }
639         fputc ('\n', F);
640     }
641 }
642
643
644
645 void CheckSegments (void)
646 /* Walk through the segment list and check if there are segments that were
647  * not written to the output file. Output an error if this is the case.
648  */
649 {
650     unsigned I;
651     for (I = 0; I < CollCount (&SegmentList); ++I) {
652
653         /* Get the next segment */
654         const Segment* S = CollAtUnchecked (&SegmentList, I);
655
656         /* Check it */
657         if (S->Size > 0 && S->Dumped == 0) {
658             Error ("Missing memory area assignment for segment `%s'",
659                    GetString (S->Name));
660         }
661     }
662 }
663
664
665