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