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