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