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