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