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