]> git.sur5r.net Git - cc65/blob - src/ld65/segments.c
Changed the object file and library format. There is now an additional
[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ömerstrasse 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 "hashstr.h"
43 #include "print.h"
44 #include "segdefs.h"
45 #include "symdefs.h"
46 #include "xmalloc.h"
47
48 /* ld65 */
49 #include "error.h"
50 #include "expr.h"
51 #include "fileio.h"
52 #include "fragment.h"
53 #include "global.h"
54 #include "lineinfo.h"
55 #include "segments.h"
56
57
58
59 /*****************************************************************************/
60 /*                                   Data                                    */
61 /*****************************************************************************/
62
63
64
65 /* Hash table */
66 #define HASHTAB_SIZE    253
67 static Segment*         HashTab [HASHTAB_SIZE];
68
69 static unsigned         SegCount = 0;   /* Segment count */
70 static Segment*         SegRoot = 0;    /* List of all segments */
71
72
73
74 /*****************************************************************************/
75 /*                                   Code                                    */
76 /*****************************************************************************/
77
78
79
80 static Segment* SegFindInternal (const char* Name, unsigned HashVal)
81 /* Try to find the segment with the given name, return a pointer to the
82  * segment structure, or 0 if not found.
83  */
84 {
85     Segment* S = HashTab [HashVal];
86     while (S) {
87         if (strcmp (Name, S->Name) == 0) {
88             /* Found */
89             break;
90         }
91         S = S->Next;
92     }
93     /* Not found */
94     return S;
95 }
96
97
98
99 static Segment* NewSegment (const char* Name, unsigned HashVal, unsigned char Type)
100 /* Create a new segment and initialize it */
101 {
102     /* Get the length of the symbol name */
103     unsigned Len = strlen (Name);
104
105     /* Allocate memory */
106     Segment* S = xmalloc (sizeof (Segment) + Len);
107
108     /* Initialize the fields */
109     S->Next     = 0;
110     S->SecRoot  = 0;
111     S->SecLast  = 0;
112     S->PC       = 0;
113     S->Size     = 0;
114     S->AlignObj = 0;
115     S->Align    = 0;
116     S->FillVal  = 0;
117     S->Type     = Type;
118     S->Dumped   = 0;
119     memcpy (S->Name, Name, Len);
120     S->Name [Len] = '\0';
121
122     /* Insert the segment into the segment list */
123     S->List = SegRoot;
124     SegRoot = S;
125     ++SegCount;
126
127     /* Insert the segment into the segment hash list */
128     S->Next = HashTab [HashVal];
129     HashTab [HashVal] = S;
130
131     /* Return the new entry */
132     return S;
133 }
134
135
136
137 Segment* GetSegment (const char* Name, unsigned char Type, const char* ObjName)
138 /* Search for a segment and return an existing one. If the segment does not
139  * exist, create a new one and return that. ObjName is only used for the error
140  * message and may be NULL if the segment is linker generated.
141  */
142 {
143     /* Create a hash over the name and try to locate the segment in the table */
144     unsigned HashVal = HashStr (Name) % HASHTAB_SIZE;
145     Segment* S = SegFindInternal (Name, HashVal);
146
147     /* If we don't have that segment already, allocate it using the type of
148      * the first section.
149      */
150     if (S == 0) {
151         /* Create a new segment */
152         S = NewSegment (Name, HashVal, Type);
153     } else {
154         /* Check if the existing segment has the requested type */
155         if (S->Type != Type) {
156             /* Allow an empty object name */
157             if (ObjName == 0) {
158                 ObjName = "[linker generated]";
159             }
160             Error ("Module `%s': Type mismatch for segment `%s'", ObjName, Name);
161         }
162     }
163
164     /* Return the segment */
165     return S;
166 }
167
168
169
170 Section* NewSection (Segment* Seg, unsigned char Align, unsigned char Type)
171 /* Create a new section for the given segment */
172 {
173     unsigned long V;
174
175
176     /* Allocate memory */
177     Section* S = xmalloc (sizeof (Segment));
178
179     /* Initialize the data */
180     S->Next     = 0;
181     S->Seg      = Seg;
182     S->FragRoot = 0;
183     S->FragLast = 0;
184     S->Size     = 0;
185     S->Align    = Align;
186     S->Type     = Type;
187
188     /* Calculate the alignment bytes needed for the section */
189     V = (0x01UL << S->Align) - 1;
190     S->Fill = (unsigned char) (((Seg->Size + V) & ~V) - Seg->Size);
191
192     /* Adjust the segment size and set the section offset */
193     Seg->Size  += S->Fill;
194     S->Offs     = Seg->Size;    /* Current size is offset */
195
196     /* Insert the section into the segment */
197     if (Seg->SecRoot == 0) {
198         /* First section in this segment */
199         Seg->SecRoot = S;
200     } else {
201         Seg->SecLast->Next = S;
202     }
203     Seg->SecLast = S;
204
205     /* Return the struct */
206     return S;
207 }
208
209
210
211 Section* ReadSection (FILE* F, ObjData* O)
212 /* Read a section from a file */
213 {
214     char* Name;
215     unsigned long Size;
216     unsigned char Align;
217     unsigned char Type;
218     Segment* S;
219     Section* Sec;
220
221     /* Read the name */
222     Name = ReadStr (F);
223
224     /* Read the size */
225     Size = Read32 (F);
226
227     /* Read the alignment */
228     Align = Read8 (F);
229
230     /* Read the segment type */
231     Type = Read8 (F);
232
233     /* Print some data */
234     Print (stdout, 2, "Module `%s': Found segment `%s', size = %lu, align = %u, type = %u\n",
235            GetObjFileName (O), Name, Size, Align, Type);
236
237     /* Get the segment for this section */
238     S = GetSegment (Name, Type, GetObjFileName (O));
239
240     /* We have the segment and don't need the name any longer */
241     xfree (Name);
242
243     /* Allocate the section we will return later */
244     Sec = NewSection (S, Align, Type);
245
246     /* Set up the minimum segment alignment */
247     if (Sec->Align > S->Align) {
248         /* Section needs larger alignment, use this one */
249         S->Align    = Sec->Align;
250         S->AlignObj = O;
251     }
252
253     /* Start reading fragments from the file and insert them into the section . */
254     while (Size) {
255
256         Fragment* Frag;
257         unsigned  LineInfoIndex;
258
259         /* Read the fragment type */
260         unsigned char Type = Read8 (F);
261
262         /* Extract the check mask from the type */
263         unsigned char Check = Type & FRAG_CHECKMASK;
264         Type &= ~FRAG_CHECKMASK;
265
266         /* Handle the different fragment types */
267         switch (Type) {
268
269             case FRAG_LITERAL:
270                 Frag = NewFragment (Type, ReadVar (F), Sec);
271                 break;
272
273             case FRAG_EXPR8:
274             case FRAG_EXPR16:
275             case FRAG_EXPR24:
276             case FRAG_EXPR32:
277             case FRAG_SEXPR8:
278             case FRAG_SEXPR16:
279             case FRAG_SEXPR24:
280             case FRAG_SEXPR32:
281                 Frag = NewFragment (Type & FRAG_TYPEMASK, Type & FRAG_BYTEMASK, Sec);
282                 break;
283
284             case FRAG_FILL:
285                 /* Will allocate memory, but we don't care... */
286                 Frag = NewFragment (Type, ReadVar (F), Sec);
287                 break;
288
289             default:
290                 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
291                        GetObjFileName (O), S->Name, Type);
292                 /* NOTREACHED */
293                 return 0;
294         }
295
296         /* Now read the fragment data */
297         switch (Frag->Type) {
298
299             case FRAG_LITERAL:
300                 /* Literal data */
301                 ReadData (F, Frag->LitBuf, Frag->Size);
302                 break;
303
304             case FRAG_EXPR:
305             case FRAG_SEXPR:
306                 /* An expression */
307                 Frag->Expr = ReadExpr (F, O);
308                 break;
309
310         }
311
312         /* A check expression may follow */
313         if (Check & FRAG_CHECK_WARN) {
314             Frag->WarnExpr = ReadExpr (F, O);
315         }
316         if (Check & FRAG_CHECK_ERROR) {
317             Frag->ErrorExpr = ReadExpr (F, O);
318         }
319
320         /* Read the file position of the fragment */
321         ReadFilePos (F, &Frag->Pos);
322
323         /* Read the additional line info and resolve it */
324         LineInfoIndex = ReadVar (F);
325         if (LineInfoIndex) {
326             --LineInfoIndex;
327             if (LineInfoIndex >= O->LineInfoCount) {
328                 Internal ("In module `%s', file `%s', line %lu: Invalid line "
329                           "info with index %u (max count %u)",
330                           GetObjFileName (O),
331                           GetSourceFileName (O, Frag->Pos.Name),
332                           Frag->Pos.Line, LineInfoIndex, O->LineInfoCount);
333             }
334             /* Point from the fragment to the line info... */
335             Frag->LI = O->LineInfos[LineInfoIndex];
336             /* ...and back from the line info to the fragment */
337             CollAppend (&Frag->LI->Fragments, Frag);
338         }
339
340         /* Remember the module we had this fragment from */
341         Frag->Obj = O;
342
343         /* Next one */
344         CHECK (Size >= Frag->Size);
345         Size -= Frag->Size;
346     }
347
348     /* Return the section */
349     return Sec;
350 }
351
352
353
354 Segment* SegFind (const char* Name)
355 /* Return the given segment or NULL if not found. */
356 {
357     return SegFindInternal (Name, HashStr (Name) % HASHTAB_SIZE);
358 }
359
360
361
362 int IsBSSType (Segment* S)
363 /* Check if the given segment is a BSS style segment, that is, it does not
364  * contain non-zero data.
365  */
366 {
367     /* Loop over all sections */
368     Section* Sec = S->SecRoot;
369     while (Sec) {
370         /* Loop over all fragments */
371         Fragment* F = Sec->FragRoot;
372         while (F) {
373             if (F->Type == FRAG_LITERAL) {
374                 unsigned char* Data = F->LitBuf;
375                 unsigned long Count = F->Size;
376                 while (Count--) {
377                     if (*Data++ != 0) {
378                         return 0;
379                     }
380                 }
381             } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
382                 if (GetExprVal (F->Expr) != 0) {
383                     return 0;
384                 }
385             }
386             F = F->Next;
387         }
388         Sec = Sec->Next;
389     }
390     return 1;
391 }
392
393
394
395 void SegDump (void)
396 /* Dump the segments and it's contents */
397 {
398     unsigned I;
399     unsigned long Count;
400     unsigned char* Data;
401
402     Segment* Seg = SegRoot;
403     while (Seg) {
404         Section* S = Seg->SecRoot;
405         printf ("Segment: %s (%lu)\n", Seg->Name, Seg->Size);
406         while (S) {
407             Fragment* F = S->FragRoot;
408             printf ("  Section:\n");
409             while (F) {
410                 switch (F->Type) {
411
412                     case FRAG_LITERAL:
413                         printf ("    Literal (%lu bytes):", F->Size);
414                         Count = F->Size;
415                         Data  = F->LitBuf;
416                         I = 100;
417                         while (Count--) {
418                             if (I > 75) {
419                                 printf ("\n   ");
420                                 I = 3;
421                             }
422                             printf (" %02X", *Data++);
423                             I += 3;
424                         }
425                         printf ("\n");
426                         break;
427
428                     case FRAG_EXPR:
429                         printf ("    Expression (%lu bytes):\n", F->Size);
430                         printf ("    ");
431                         DumpExpr (F->Expr);
432                         break;
433
434                     case FRAG_SEXPR:
435                         printf ("    Signed expression (%lu bytes):\n", F->Size);
436                         printf ("      ");
437                         DumpExpr (F->Expr);
438                         break;
439
440                     case FRAG_FILL:
441                         printf ("    Empty space (%lu bytes)\n", F->Size);
442                         break;
443
444                     default:
445                         Internal ("Invalid fragment type: %02X", F->Type);
446                 }
447                 F = F->Next;
448             }
449             S = S->Next;
450         }
451         Seg = Seg->List;
452     }
453 }
454
455
456
457 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
458 /* Write a supposedly constant expression to the target file. Do a range
459  * check and return one of the SEG_EXPR_xxx codes.
460  */
461 {
462     static const unsigned long U_HighRange [4] = {
463         0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
464     };
465     static const long S_HighRange [4] = {
466         0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
467     };
468     static const long S_LowRange [4] = {
469         0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
470     };
471
472
473     /* Get the expression value */
474     long Val = GetExprVal (E);
475
476     /* Check the size */
477     CHECK (Size >= 1 && Size <= 4);
478
479     /* Check for a range error */
480     if (Signed) {
481         if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
482             /* Range error */
483             return SEG_EXPR_RANGE_ERROR;
484         }
485     } else {
486         if (((unsigned long)Val) > U_HighRange [Size-1]) {
487             /* Range error */
488             return SEG_EXPR_RANGE_ERROR;
489         }
490     }
491
492     /* Write the value to the file */
493     WriteVal (F, Val, Size);
494
495     /* Success */
496     return SEG_EXPR_OK;
497 }
498
499
500
501 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
502 /* Write the data from the given segment to a file. For expressions, F is
503  * called (see description of SegWriteFunc above).
504  */
505 {
506     int Sign;
507     unsigned long Offs = 0;
508
509     /* Loop over all sections in this segment */
510     Section* Sec = S->SecRoot;
511     while (Sec) {
512         Fragment* Frag;
513
514         /* If we have fill bytes, write them now */
515         WriteMult (Tgt, S->FillVal, Sec->Fill);
516         Offs += Sec->Fill;
517
518         /* Loop over all fragments in this section */
519         Frag = Sec->FragRoot;
520         while (Frag) {
521                                       
522             /* Do fragment alignment checks */
523
524
525
526             /* Output fragment data */
527             switch (Frag->Type) {
528
529                 case FRAG_LITERAL:
530                     WriteData (Tgt, Frag->LitBuf, Frag->Size);
531                     break;
532
533                 case FRAG_EXPR:
534                 case FRAG_SEXPR:
535                     Sign = (Frag->Type == FRAG_SEXPR);
536                     /* Call the users function and evaluate the result */
537                     switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
538
539                         case SEG_EXPR_OK:
540                             break;
541
542                         case SEG_EXPR_RANGE_ERROR:
543                             Error ("Range error in module `%s', line %lu",
544                                    GetSourceFileName (Frag->Obj, Frag->Pos.Name),
545                                    Frag->Pos.Line);
546                             break;
547
548                         case SEG_EXPR_TOO_COMPLEX:
549                             Error ("Expression too complex in module `%s', line %lu",
550                                    GetSourceFileName (Frag->Obj, Frag->Pos.Name),
551                                    Frag->Pos.Line);
552                             break;
553
554                         case SEG_EXPR_INVALID:
555                             Error ("Invalid expression in module `%s', line %lu",
556                                    GetSourceFileName (Frag->Obj, Frag->Pos.Name),
557                                    Frag->Pos.Line);
558                             break;
559
560                         default:
561                             Internal ("Invalid return code from SegWriteFunc");
562                     }
563                     break;
564
565                 case FRAG_FILL:
566                     WriteMult (Tgt, S->FillVal, Frag->Size);
567                     break;
568
569                 default:
570                     Internal ("Invalid fragment type: %02X", Frag->Type);
571             }
572
573             /* Update the offset */
574             Offs += Frag->Size;
575
576             /* Next fragment */
577             Frag = Frag->Next;
578         }
579
580         /* Next section */
581         Sec = Sec->Next;
582     }
583 }
584
585
586
587 static int CmpSegStart (const void* K1, const void* K2)
588 /* Compare function for qsort */
589 {
590     /* Get the real segment pointers */
591     const Segment* S1 = *(const Segment**)K1;
592     const Segment* S2 = *(const Segment**)K2;
593
594     /* Compare the start addresses */
595     if (S1->PC > S2->PC) {
596         return 1;
597     } else if (S1->PC < S2->PC) {
598         return -1;
599     } else {
600         /* Sort segments with equal starts by name */
601         return strcmp (S1->Name, S2->Name);
602     }
603 }
604
605
606
607 void PrintSegmentMap (FILE* F)
608 /* Print a segment map to the given file */
609 {
610     unsigned I;
611     Segment* S;
612     Segment** SegPool;
613
614     /* Allocate memory for the segment pool */
615     SegPool = xmalloc (SegCount * sizeof (Segment*));
616
617     /* Collect pointers to the segments */
618     I = 0;
619     S = SegRoot;
620     while (S) {
621
622         /* Check the count for safety */
623         CHECK (I < SegCount);
624
625         /* Remember the pointer */
626         SegPool [I] = S;
627
628         /* Follow the linked list */
629         S = S->List;
630
631         /* Next array index */
632         ++I;
633     }
634     CHECK (I == SegCount);
635
636     /* Sort the array by increasing start addresses */
637     qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
638
639     /* Print a header */
640     fprintf (F, "Name                  Start   End     Size\n"
641                 "--------------------------------------------\n");
642
643     /* Print the segments */
644     for (I = 0; I < SegCount; ++I) {
645
646         /* Get a pointer to the segment */
647         S = SegPool [I];
648
649         /* Print empty segments only if explicitly requested */
650         if (VerboseMap || S->Size > 0) {
651             /* Print the segment data */
652             long End = S->PC + S->Size;
653             if (S->Size > 0) {
654                 /* Point to last element addressed */
655                 --End;
656             }
657             fprintf (F, "%-20s  %06lX  %06lX  %06lX\n",
658                      S->Name, S->PC, End, S->Size);
659         }
660     }
661
662     /* Free the segment pool */
663     xfree (SegPool);
664 }
665
666
667
668 void CheckSegments (void)
669 /* Walk through the segment list and check if there are segments that were
670  * not written to the output file. Output an error if this is the case.
671  */
672 {
673     Segment* S = SegRoot;
674     while (S) {
675         if (S->Size > 0 && S->Dumped == 0) {
676             Error ("Missing memory area assignment for segment `%s'", S->Name);
677         }
678         S = S->List;
679     }
680 }
681
682
683