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 /*****************************************************************************/
56 /*****************************************************************************/
58 /*****************************************************************************/
62 /* Fragment structure */
63 typedef struct Fragment_ Fragment;
65 Fragment* Next; /* Next fragment in list */
66 ObjData* Obj; /* Source of fragment */
67 unsigned long Size; /* Size of data/expression */
68 ExprNode* Expr; /* Expression if FRAG_EXPR */
69 FilePos Pos; /* File position in source */
70 unsigned char Type; /* Type of fragment */
71 unsigned char LitBuf [1]; /* Dynamically alloc'ed literal buffer */
77 #define HASHTAB_SIZE 253
78 static Segment* HashTab [HASHTAB_SIZE];
80 static unsigned SegCount = 0; /* Segment count */
81 static Segment* SegRoot = 0; /* List of all segments */
85 /*****************************************************************************/
87 /*****************************************************************************/
91 static Fragment* NewFragment (unsigned char Type, unsigned long Size, Section* S)
92 /* Create a new fragment and insert it into the segment S */
95 Fragment* F = xmalloc (sizeof (Fragment) - 1 + Size); /* Portable? */
97 /* Initialize the data */
104 /* Insert the code fragment into the segment */
105 if (S->FragRoot == 0) {
109 S->FragLast->Next = F;
114 /* Return the new fragment */
120 static Segment* NewSegment (const char* Name, unsigned char Type)
121 /* Create a new segment and initialize it */
123 /* Get the length of the symbol name */
124 unsigned Len = strlen (Name);
126 /* Allocate memory */
127 Segment* S = xmalloc (sizeof (Segment) + Len);
129 /* Initialize the fields */
140 memcpy (S->Name, Name, Len);
141 S->Name [Len] = '\0';
143 /* Insert the segment into the segment list */
148 /* Return the new entry */
154 static Section* NewSection (Segment* Seg, unsigned char Align, unsigned char Type)
155 /* Create a new section for the given segment */
160 /* Allocate memory */
161 Section* S = xmalloc (sizeof (Segment));
163 /* Initialize the data */
172 /* Calculate the alignment bytes needed for the section */
173 V = (0x01UL << S->Align) - 1;
174 S->Fill = (unsigned char) (((Seg->Size + V) & ~V) - Seg->Size);
176 /* Adjust the segment size and set the section offset */
177 Seg->Size += S->Fill;
178 S->Offs = Seg->Size; /* Current size is offset */
180 /* Insert the section into the segment */
181 if (Seg->SecRoot == 0) {
182 /* First section in this segment */
185 Seg->SecLast->Next = S;
189 /* Return the struct */
195 static Segment* SegFindInternal (const char* Name, unsigned HashVal)
196 /* Try to find the segment with the given name, return a pointer to the
197 * segment structure, or 0 if not found.
200 Segment* S = HashTab [HashVal];
202 if (strcmp (Name, S->Name) == 0) {
214 Section* ReadSection (FILE* F, ObjData* O)
215 /* Read a section from a file */
231 /* Read the alignment */
234 /* Read the segment type */
237 /* Print some data */
239 printf ("Module `%s': Found segment `%s', size = %lu, align = %u, type = %u\n",
240 O->Name, Name, Size, Align, Type);
243 /* Create a hash over the name and try to locate the segment in the table */
244 HashVal = HashStr (Name) % HASHTAB_SIZE;
245 S = SegFindInternal (Name, HashVal);
247 /* If we don't have that segment already, allocate it using the type of
251 /* Create a new segment and insert it */
252 S = NewSegment (Name, Type);
253 S->Next = HashTab [HashVal];
254 HashTab [HashVal] = S;
257 /* We have the segment and don't need the name any longer */
260 /* Allocate the section we will return later */
261 Sec = NewSection (S, Align, Type);
263 /* Check if the section has the same type as the segment */
264 if (Sec->Type != S->Type) {
266 Error ("Module `%s': Type mismatch for segment `%s'", O->Name, S->Name);
269 /* Set up the minimum segment alignment */
270 if (Sec->Align > S->Align) {
271 /* Section needs larger alignment, use this one */
272 S->Align = Sec->Align;
276 /* Start reading fragments from the file and insert them into the section . */
281 /* Read the fragment type */
282 unsigned char Type = Read8 (F);
284 /* Handle the different fragment types */
288 Frag = NewFragment (Type, ReadVar (F), Sec);
299 Frag = NewFragment (Type & FRAG_TYPEMASK, Type & FRAG_BYTEMASK, Sec);
303 /* Will allocate memory, but we don't care... */
304 Frag = NewFragment (Type, ReadVar (F), Sec);
308 Error ("Unknown fragment type in module `%s', segment `%s': %02X",
309 O->Name, S->Name, Type);
314 /* Now read the fragment data */
315 switch (Frag->Type) {
319 ReadData (F, Frag->LitBuf, Frag->Size);
325 Frag->Expr = ReadExpr (F, O);
330 /* Read the file position of the fragment */
331 ReadFilePos (F, &Frag->Pos);
333 /* Remember the module we had this fragment from */
337 CHECK (Size >= Frag->Size);
341 /* Increment the segment size by the section size */
342 S->Size += Sec->Size;
344 /* Return the section */
350 Segment* SegFind (const char* Name)
351 /* Return the given segment or NULL if not found. */
353 return SegFindInternal (Name, HashStr (Name) % HASHTAB_SIZE);
358 int IsBSSType (Segment* S)
359 /* Check if the given segment is a BSS style segment, that is, it does not
360 * contain non-zero data.
363 /* Loop over all sections */
364 Section* Sec = S->SecRoot;
366 /* Loop over all fragments */
367 Fragment* F = Sec->FragRoot;
369 if (F->Type == FRAG_LITERAL) {
370 unsigned char* Data = F->LitBuf;
371 unsigned long Count = F->Size;
377 } else if (F->Type == FRAG_EXPR || F->Type == FRAG_SEXPR) {
378 if (GetExprVal (F->Expr) != 0) {
392 /* Dump the segments and it's contents */
398 Segment* Seg = SegRoot;
400 Section* S = Seg->SecRoot;
401 printf ("Segment: %s (%lu)\n", Seg->Name, Seg->Size);
403 Fragment* F = S->FragRoot;
404 printf (" Section:\n");
409 printf (" Literal (%lu bytes):", F->Size);
418 printf (" %02X", *Data++);
425 printf (" Expression (%lu bytes):\n", F->Size);
431 printf (" Signed expression (%lu bytes):\n", F->Size);
437 printf (" Empty space (%lu bytes)\n", F->Size);
441 Internal ("Invalid fragment type: %02X", F->Type);
453 unsigned SegWriteConstExpr (FILE* F, ExprNode* E, int Signed, unsigned Size)
454 /* Write a supposedly constant expression to the target file. Do a range
455 * check and return one of the SEG_EXPR_xxx codes.
458 static const unsigned long U_HighRange [4] = {
459 0x000000FF, 0x0000FFFF, 0x00FFFFFF, 0xFFFFFFFF
461 static const long S_HighRange [4] = {
462 0x0000007F, 0x00007FFF, 0x007FFFFF, 0x7FFFFFFF
464 static const long S_LowRange [4] = {
465 0xFFFFFF80, 0xFFFF8000, 0xFF800000, 0x80000000
469 /* Get the expression value */
470 long Val = GetExprVal (E);
473 CHECK (Size >= 1 && Size <= 4);
475 /* Check for a range error */
477 if (Val > S_HighRange [Size-1] || Val < S_LowRange [Size-1]) {
479 return SEG_EXPR_RANGE_ERROR;
482 if (((unsigned long)Val) > U_HighRange [Size-1]) {
484 return SEG_EXPR_RANGE_ERROR;
488 /* Write the value to the file */
489 WriteVal (F, Val, Size);
497 void SegWrite (FILE* Tgt, Segment* S, SegWriteFunc F, void* Data)
498 /* Write the data from the given segment to a file. For expressions, F is
499 * called (see description of SegWriteFunc above).
503 unsigned long Offs = 0;
505 /* Loop over all sections in this segment */
506 Section* Sec = S->SecRoot;
510 /* If we have fill bytes, write them now */
511 WriteMult (Tgt, S->FillVal, Sec->Fill);
513 /* Loop over all fragments in this section */
514 Frag = Sec->FragRoot;
517 switch (Frag->Type) {
520 WriteData (Tgt, Frag->LitBuf, Frag->Size);
525 Sign = (Frag->Type == FRAG_SEXPR);
526 /* Call the users function and evaluate the result */
527 switch (F (Frag->Expr, Sign, Frag->Size, Offs, Data)) {
532 case SEG_EXPR_RANGE_ERROR:
533 Error ("Range error in module `%s', line %lu",
534 Frag->Obj->Files [Frag->Pos.Name], Frag->Pos.Line);
537 case SEG_EXPR_TOO_COMPLEX:
538 Error ("Expression too complex in module `%s', line %lu",
539 Frag->Obj->Files [Frag->Pos.Name], Frag->Pos.Line);
543 Internal ("Invalid return code from SegWriteFunc");
548 WriteMult (Tgt, S->FillVal, Frag->Size);
552 Internal ("Invalid fragment type: %02X", Frag->Type);
555 /* Update the offset */
569 static int CmpSegStart (const void* K1, const void* K2)
570 /* Compare function for qsort */
572 /* Get the real segment pointers */
573 const Segment* S1 = *(const Segment**)K1;
574 const Segment* S2 = *(const Segment**)K2;
576 /* Compare the start addresses */
577 if (S1->PC > S2->PC) {
579 } else if (S1->PC < S2->PC) {
582 /* Sort segments with equal starts by name */
583 return strcmp (S1->Name, S2->Name);
589 void PrintSegmentMap (FILE* F)
590 /* Print a segment map to the given file */
596 /* Allocate memory for the segment pool */
597 SegPool = xmalloc (SegCount * sizeof (Segment*));
599 /* Collect pointers to the segments */
604 /* Check the count for safety */
605 CHECK (I < SegCount);
607 /* Remember the pointer */
610 /* Follow the linked list */
613 /* Next array index */
616 CHECK (I == SegCount);
618 /* Sort the array by increasing start addresses */
619 qsort (SegPool, SegCount, sizeof (Segment*), CmpSegStart);
622 fprintf (F, "Name Start End Size\n"
623 "--------------------------------------------\n");
625 /* Print the segments */
626 for (I = 0; I < SegCount; ++I) {
628 /* Get a pointer to the segment */
631 /* Print empty segments only if explicitly requested */
632 if (VerboseMap || S->Size > 0) {
633 /* Print the segment data */
634 fprintf (F, "%-20s %06lX %06lX %06lX\n",
635 S->Name, S->PC, S->PC + S->Size, S->Size);
639 /* Free the segment pool */
645 void CheckSegments (void)
646 /* Walk through the segment list and check if there are segments that were
647 * not written to the output file. Output an error if this is the case.
650 Segment* S = SegRoot;
652 if (S->Size > 0 && S->Dumped == 0) {
653 Error ("Missing memory area assignment for segment `%s'", S->Name);