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