1 /*****************************************************************************/
5 /* Segment handling for the ld65 linker */
9 /* (C) 1998-2000 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
12 /* EMail: uz@musoftware.de */
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. */
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: */
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 */
32 /*****************************************************************************/
39 #include "../common/exprdefs.h"
40 #include "../common/symdefs.h"
41 #include "../common/segdefs.h"
42 #include "../common/hashstr.h"
53 /*****************************************************************************/
55 /*****************************************************************************/
59 /* Fragment structure */
60 typedef struct Fragment_ Fragment;
62 Fragment* Next; /* Next fragment in list */
63 ObjData* Obj; /* Source of fragment */
64 unsigned long Size; /* Size of data/expression */
65 ExprNode* Expr; /* Expression if FRAG_EXPR */
66 FilePos Pos; /* File position in source */
67 unsigned char Type; /* Type of fragment */
68 unsigned char LitBuf [1]; /* Dynamically alloc'ed literal buffer */
74 #define HASHTAB_SIZE 253
75 static Segment* HashTab [HASHTAB_SIZE];
77 static unsigned SegCount = 0; /* Segment count */
78 static Segment* SegRoot = 0; /* List of all segments */
82 /*****************************************************************************/
84 /*****************************************************************************/
88 static Fragment* NewFragment (unsigned char Type, unsigned long Size, Section* S)
89 /* Create a new fragment and insert it into the segment S */
92 Fragment* F = Xmalloc (sizeof (Fragment) - 1 + Size); /* Portable? */
94 /* Initialize the data */
101 /* Insert the code fragment into the segment */
102 if (S->FragRoot == 0) {
106 S->FragLast->Next = F;
111 /* Return the new fragment */
117 static Segment* NewSegment (const char* Name, unsigned char Type)
118 /* Create a new segment and initialize it */
120 /* Get the length of the symbol name */
121 unsigned Len = strlen (Name);
123 /* Allocate memory */
124 Segment* S = Xmalloc (sizeof (Segment) + Len);
126 /* Initialize the fields */
137 memcpy (S->Name, Name, Len);
138 S->Name [Len] = '\0';
140 /* Insert the segment into the segment list */
145 /* Return the new entry */
151 static Section* NewSection (Segment* Seg, unsigned char Align, unsigned char Type)
152 /* Create a new section for the given segment */
157 /* Allocate memory */
158 Section* S = Xmalloc (sizeof (Segment));
160 /* Initialize the data */
169 /* Calculate the alignment bytes needed for the section */
170 V = (0x01UL << S->Align) - 1;
171 S->Fill = (unsigned char) (((Seg->Size + V) & ~V) - Seg->Size);
173 /* Adjust the segment size and set the section offset */
174 Seg->Size += S->Fill;
175 S->Offs = Seg->Size; /* Current size is offset */
177 /* Insert the section into the segment */
178 if (Seg->SecRoot == 0) {
179 /* First section in this segment */
182 Seg->SecLast->Next = S;
186 /* Return the struct */
192 static Segment* SegFindInternal (const char* Name, unsigned HashVal)
193 /* Try to find the segment with the given name, return a pointer to the
194 * segment structure, or 0 if not found.
197 Segment* S = HashTab [HashVal];
199 if (strcmp (Name, S->Name) == 0) {
211 Section* ReadSection (FILE* F, ObjData* O)
212 /* Read a section from a file */
228 /* Read the alignment */
231 /* Read the segment type */
234 /* Print some data */
236 printf ("Module `%s': Found segment `%s', size = %lu, align = %u, type = %u\n",
237 O->Name, Name, Size, Align, Type);
240 /* Create a hash over the name and try to locate the segment in the table */
241 HashVal = HashStr (Name) % HASHTAB_SIZE;
242 S = SegFindInternal (Name, HashVal);
244 /* If we don't have that segment already, allocate it using the type of
248 /* Create a new segment and insert it */
249 S = NewSegment (Name, Type);
250 S->Next = HashTab [HashVal];
251 HashTab [HashVal] = S;
254 /* Allocate the section we will return later */
255 Sec = NewSection (S, Align, Type);
257 /* Check if the section has the same type as the segment */
258 if (Sec->Type != S->Type) {
260 Error ("Module `%s': Type mismatch for segment `%s'", O->Name, S->Name);
263 /* Set up the minimum segment alignment */
264 if (Sec->Align > S->Align) {
265 /* Section needs larger alignment, use this one */
266 S->Align = Sec->Align;
270 /* Start reading fragments from the file and insert them into the section . */
275 /* Read the fragment type */
276 unsigned char Type = Read8 (F);
278 /* Handle the different fragment types */
282 Frag = NewFragment (FRAG_LITERAL, Read8 (F), Sec);
286 Frag = NewFragment (FRAG_LITERAL, Read16 (F), Sec);
290 Frag = NewFragment (FRAG_LITERAL, Read24 (F), Sec);
294 Frag = NewFragment (FRAG_LITERAL, Read32 (F), Sec);
305 Frag = NewFragment (Type & FRAG_TYPEMASK, Type & FRAG_BYTEMASK, Sec);
309 /* Will allocate memory, but we don't care... */
310 Frag = NewFragment (FRAG_FILL, Read16 (F), Sec);
314 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
315 O->Name, S->Name, Type);
320 /* Now read the fragment data */
321 switch (Frag->Type) {
325 ReadData (F, Frag->LitBuf, Frag->Size);
331 Frag->Expr = ReadExpr (F, O);
336 /* Read the file position of the fragment */
337 ReadFilePos (F, &Frag->Pos);
339 /* Remember the module we had this fragment from */
343 CHECK (Size >= Frag->Size);
347 /* Increment the segment size by the section size */
348 S->Size += Sec->Size;
350 /* Return the section */
356 Segment* SegFind (const char* Name)
357 /* Return the given segment or NULL if not found. */
359 return SegFindInternal (Name, HashStr (Name) % HASHTAB_SIZE);
364 int IsBSSType (Segment* S)
365 /* Check if the given segment is a BSS style segment, that is, it does not
366 * contain non-zero data.
369 /* Loop over all sections */
370 Section* Sec = S->SecRoot;
372 /* Loop over all fragments */
373 Fragment* F = Sec->FragRoot;
375 if (F->Type == FRAG_LITERAL) {
376 unsigned char* Data = F->LitBuf;
377 unsigned long Count = F->Size;
383 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
384 if (GetExprVal (F->Expr) != 0) {
398 /* Dump the segments and it's contents */
404 Segment* Seg = SegRoot;
406 Section* S = Seg->SecRoot;
407 printf ("Segment: %s (%lu)\n", Seg->Name, Seg->Size);
409 Fragment* F = S->FragRoot;
410 printf (" Section:\n");
415 printf (" Literal (%lu bytes):", F->Size);
424 printf (" %02X", *Data++);
431 printf (" Expression (%lu bytes):\n", F->Size);
437 printf (" Signed expression (%lu bytes):\n", F->Size);
443 printf (" Empty space (%lu bytes)\n", F->Size);
447 Internal ("Invalid fragment type: %02X", F->Type);
459 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
460 /* Write a supposedly constant expression to the target file. Do a range
461 * check and return one of the SEG_EXPR_xxx codes.
464 static const unsigned long U_HighRange [4] = {
465 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
467 static const long S_HighRange [4] = {
468 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
470 static const long S_LowRange [4] = {
471 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
475 /* Get the expression value */
476 long Val = GetExprVal (E);
479 CHECK (Size >= 1 && Size <= 4);
481 /* Check for a range error */
483 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
485 return SEG_EXPR_RANGE_ERROR;
488 if (((unsigned long)Val) > U_HighRange [Size-1]) {
490 return SEG_EXPR_RANGE_ERROR;
494 /* Write the value to the file */
495 WriteVal (F, Val, Size);
503 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
504 /* Write the data from the given segment to a file. For expressions, F is
505 * called (see description of SegWriteFunc above).
509 unsigned long Offs = 0;
511 /* Loop over all sections in this segment */
512 Section* Sec = S->SecRoot;
516 /* If we have fill bytes, write them now */
517 WriteMult (Tgt, S->FillVal, Sec->Fill);
519 /* Loop over all fragments in this section */
520 Frag = Sec->FragRoot;
523 switch (Frag->Type) {
526 WriteData (Tgt, Frag->LitBuf, Frag->Size);
531 Sign = (Frag->Type == FRAG_SEXPR);
532 /* Call the users function and evaluate the result */
533 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
538 case SEG_EXPR_RANGE_ERROR:
539 Error ("Range error in module `%s', line %lu",
540 Frag->Obj->Files [Frag->Pos.Name], Frag->Pos.Line);
543 case SEG_EXPR_TOO_COMPLEX:
544 Error ("Expression too complex in module `%s', line %lu",
545 Frag->Obj->Files [Frag->Pos.Name], Frag->Pos.Line);
549 Internal ("Invalid return code from SegWriteFunc");
554 WriteMult (Tgt, S->FillVal, Frag->Size);
558 Internal ("Invalid fragment type: %02X", Frag->Type);
561 /* Update the offset */
575 static int CmpSegStart (const void* K1, const void* K2)
576 /* Compare function for qsort */
578 /* Get the real segment pointers */
579 const Segment* S1 = *(const Segment**)K1;
580 const Segment* S2 = *(const Segment**)K2;
582 /* Compare the start addresses */
583 if (S1->PC > S2->PC) {
585 } else if (S1->PC < S2->PC) {
588 /* Sort segments with equal starts by name */
589 return strcmp (S1->Name, S2->Name);
595 void PrintSegmentMap (FILE* F)
596 /* Print a segment map to the given file */
602 /* Allocate memory for the segment pool */
603 SegPool = Xmalloc (SegCount * sizeof (Segment*));
605 /* Collect pointers to the segments */
610 /* Check the count for safety */
611 CHECK (I < SegCount);
613 /* Remember the pointer */
616 /* Follow the linked list */
619 /* Next array index */
622 CHECK (I == SegCount);
624 /* Sort the array by increasing start addresses */
625 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
628 fprintf (F, "Name Start End Size\n"
629 "--------------------------------------------\n");
631 /* Print the segments */
632 for (I = 0; I < SegCount; ++I) {
634 /* Get a pointer to the segment */
637 /* Print empty segments only if explicitly requested */
638 if (VerboseMap || S->Size > 0) {
639 /* Print the segment data */
640 fprintf (F, "%-20s %06lX %06lX %06lX\n",
641 S->Name, S->PC, S->PC + S->Size, S->Size);
645 /* Free the segment pool */
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.
656 Segment* S = SegRoot;
658 if (S->Size > 0 && S->Dumped == 0) {
659 Error ("Missing memory area assignment for segment `%s'", S->Name);