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