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