1 /*****************************************************************************/
5 /* Exports handling for the ld65 linker */
9 /* (C) 1998-2010, Ullrich von Bassewitz */
10 /* Roemerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
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 /*****************************************************************************/
60 /*****************************************************************************/
62 /*****************************************************************************/
67 #define HASHTAB_MASK 0x0FFFU
68 #define HASHTAB_SIZE (HASHTAB_MASK + 1)
69 static Export* HashTab[HASHTAB_SIZE];
71 /* Import management variables */
72 static unsigned ImpCount = 0; /* Import count */
73 static unsigned ImpOpen = 0; /* Count of open imports */
75 /* Export management variables */
76 static unsigned ExpCount = 0; /* Export count */
77 static Export** ExpPool = 0; /* Exports array */
79 /* Defines for the flags in Import */
80 #define IMP_INLIST 0x0001U /* Import is in exports list */
82 /* Defines for the flags in Export */
83 #define EXP_INLIST 0x0001U /* Export is in exports list */
84 #define EXP_USERMARK 0x0002U /* User setable flag */
88 /*****************************************************************************/
90 /*****************************************************************************/
94 static Export* NewExport (unsigned char Type, unsigned char AddrSize,
95 unsigned Name, ObjData* Obj);
96 /* Create a new export and initialize it */
100 static Import* NewImport (unsigned char AddrSize, ObjData* Obj)
101 /* Create a new import and initialize it */
103 /* Allocate memory */
104 Import* I = xmalloc (sizeof (Import));
106 /* Initialize the fields */
109 InitFilePos (&I->Pos);
111 I->Name = INVALID_STRING_ID;
113 I->AddrSize = AddrSize;
115 /* Return the new structure */
121 void FreeImport (Import* I)
122 /* Free an import. NOTE: This won't remove the import from the exports table,
123 * so it may only be called for unused imports (imports from modules that
124 * aren't referenced).
128 PRECONDITION ((I->Flags & IMP_INLIST) == 0);
130 /* Free the struct */
136 Import* ReadImport (FILE* F, ObjData* Obj)
137 /* Read an import from a file and return it */
141 /* Read the import address size */
142 unsigned char AddrSize = Read8 (F);
144 /* Create a new import */
145 I = NewImport (AddrSize, Obj);
148 I->Name = MakeGlobalStringId (Obj, ReadVar (F));
150 /* Read the file position */
151 ReadFilePos (F, &I->Pos);
153 /* Check the address size */
154 if (I->AddrSize == ADDR_SIZE_DEFAULT || I->AddrSize > ADDR_SIZE_LONG) {
155 /* Beware: This function may be called in cases where the object file
156 * is not read completely into memory. In this case, the file list is
157 * invalid. Be sure not to access it in this case.
159 if (ObjHasFiles (I->Obj)) {
160 Error ("Invalid import size in for `%s', imported from %s(%lu): 0x%02X",
162 GetSourceFileName (I->Obj, I->Pos.Name),
166 Error ("Invalid import size in for `%s', imported from %s: 0x%02X",
168 GetObjFileName (I->Obj),
173 /* Return the new import */
179 Import* GenImport (const char* Name, unsigned char AddrSize)
180 /* Generate a new import with the given name and address size and return it */
182 /* Create a new import */
183 Import* I = NewImport (AddrSize, 0);
186 I->Name = GetStringId (Name);
188 /* Check the address size */
189 if (I->AddrSize == ADDR_SIZE_DEFAULT || I->AddrSize > ADDR_SIZE_LONG) {
190 /* Beware: This function may be called in cases where the object file
191 * is not read completely into memory. In this case, the file list is
192 * invalid. Be sure not to access it in this case.
194 if (ObjHasFiles (I->Obj)) {
195 Error ("Invalid import size in for `%s', imported from %s(%lu): 0x%02X",
197 GetSourceFileName (I->Obj, I->Pos.Name),
201 Error ("Invalid import size in for `%s', imported from %s: 0x%02X",
203 GetObjFileName (I->Obj),
208 /* Return the new import */
214 void InsertImport (Import* I)
215 /* Insert an import into the table */
219 /* As long as the import is not inserted, V.Name is valid */
220 unsigned Name = I->Name;
222 /* Create a hash value for the given name */
223 unsigned Hash = (Name & HASHTAB_MASK);
225 /* Search through the list in that slot and print matching duplicates */
226 if (HashTab[Hash] == 0) {
227 /* The slot is empty, we need to insert a dummy export */
228 E = HashTab[Hash] = NewExport (0, ADDR_SIZE_DEFAULT, Name, 0);
233 if (E->Name == Name) {
234 /* We have an entry, L points to it */
238 /* End of list an entry not found, insert a dummy */
239 E->Next = NewExport (0, ADDR_SIZE_DEFAULT, Name, 0);
240 E = E->Next; /* Point to dummy */
241 ++ExpCount; /* One export more */
249 /* Ok, E now points to a valid exports entry for the given import. Insert
250 * the import into the imports list and update the counters.
253 I->Next = E->ImpList;
256 ++ImpCount; /* Total import count */
258 /* This is a dummy export */
262 /* Mark the import so we know it's in the list */
263 I->Flags |= IMP_INLIST;
268 /*****************************************************************************/
270 /*****************************************************************************/
274 static Export* NewExport (unsigned char Type, unsigned char AddrSize,
275 unsigned Name, ObjData* Obj)
276 /* Create a new export and initialize it */
278 /* Allocate memory */
279 Export* E = xmalloc (sizeof (Export));
281 /* Initialize the fields */
290 E->AddrSize = AddrSize;
291 memset (E->ConDes, 0, sizeof (E->ConDes));
293 /* Return the new entry */
299 void FreeExport (Export* E)
300 /* Free an export. NOTE: This won't remove the export from the exports table,
301 * so it may only be called for unused exports (exports from modules that
302 * aren't referenced).
306 PRECONDITION ((E->Flags & EXP_INLIST) == 0);
308 /* Free the export expression */
311 /* Free the struct */
317 void InsertExport (Export* E)
318 /* Insert an exported identifier and check if it's already in the list */
325 /* Mark the export as inserted */
326 E->Flags |= EXP_INLIST;
328 /* Insert the export into any condes tables if needed */
329 if (SYM_IS_CONDES (E->Type)) {
333 /* Create a hash value for the given name */
334 Hash = (E->Name & HASHTAB_MASK);
336 /* Search through the list in that slot */
337 if (HashTab[Hash] == 0) {
338 /* The slot is empty */
346 if (L->Name == E->Name) {
347 /* This may be an unresolved external */
350 /* This *is* an unresolved external. Use the actual export
351 * in E instead of the dummy one in L.
354 E->ImpCount = L->ImpCount;
355 E->ImpList = L->ImpList;
361 ImpOpen -= E->ImpCount; /* Decrease open imports now */
363 /* We must run through the import list and change the
364 * export pointer now.
372 /* Duplicate entry, ignore it */
373 Warning ("Duplicate external identifier: `%s'",
374 GetString (L->Name));
383 /* Insert export at end of queue */
391 Export* ReadExport (FILE* F, ObjData* O)
392 /* Read an export from a file */
394 unsigned ConDesCount;
398 unsigned char Type = ReadVar (F);
400 /* Read the address size */
401 unsigned char AddrSize = Read8 (F);
403 /* Create a new export without a name */
404 E = NewExport (Type, AddrSize, INVALID_STRING_ID, O);
406 /* Read the constructor/destructor decls if we have any */
407 ConDesCount = SYM_GET_CONDES_COUNT (Type);
408 if (ConDesCount > 0) {
410 unsigned char ConDes[CD_TYPE_COUNT];
413 /* Read the data into temp storage */
414 ReadData (F, ConDes, ConDesCount);
416 /* Re-order the data. In the file, each decl is encoded into a byte
417 * which contains the type and the priority. In memory, we will use
418 * an array of types which contain the priority. This array was
419 * cleared by the constructor (NewExport), so we must only set the
420 * fields that contain values.
422 for (I = 0; I < ConDesCount; ++I) {
423 unsigned ConDesType = CD_GET_TYPE (ConDes[I]);
424 unsigned ConDesPrio = CD_GET_PRIO (ConDes[I]);
425 E->ConDes[ConDesType] = ConDesPrio;
430 E->Name = MakeGlobalStringId (O, ReadVar (F));
433 if (SYM_IS_EXPR (Type)) {
434 E->Expr = ReadExpr (F, O);
436 E->Expr = LiteralExpr (Read32 (F), O);
439 /* Last is the file position where the definition was done */
440 ReadFilePos (F, &E->Pos);
442 /* Return the new export */
448 Export* CreateConstExport (unsigned Name, long Value)
449 /* Create an export for a literal date */
451 /* Create a new export */
452 Export* E = NewExport (SYM_CONST | SYM_EQUATE, ADDR_SIZE_ABS, Name, 0);
454 /* Assign the value */
455 E->Expr = LiteralExpr (Value, 0);
457 /* Insert the export */
460 /* Return the new export */
466 Export* CreateMemoryExport (unsigned Name, Memory* Mem, unsigned long Offs)
467 /* Create an relative export for a memory area offset */
469 /* Create a new export */
470 Export* E = NewExport (SYM_EXPR | SYM_LABEL, ADDR_SIZE_ABS, Name, 0);
472 /* Assign the value */
473 E->Expr = MemoryExpr (Mem, Offs, 0);
475 /* Insert the export */
478 /* Return the new export */
484 Export* CreateSegmentExport (unsigned Name, Segment* Seg, unsigned long Offs)
485 /* Create a relative export to a segment */
487 /* Create a new export */
488 Export* E = NewExport (SYM_EXPR | SYM_LABEL, Seg->AddrSize, Name, 0);
490 /* Assign the value */
491 E->Expr = SegmentExpr (Seg, Offs, 0);
493 /* Insert the export */
496 /* Return the new export */
502 Export* CreateSectionExport (unsigned Name, Section* Sec, unsigned long Offs)
503 /* Create a relative export to a section */
505 /* Create a new export */
506 Export* E = NewExport (SYM_EXPR | SYM_LABEL, Sec->AddrSize, Name, 0);
508 /* Assign the value */
509 E->Expr = SectionExpr (Sec, Offs, 0);
511 /* Insert the export */
514 /* Return the new export */
520 Export* FindExport (unsigned Name)
521 /* Check for an identifier in the list. Return 0 if not found, otherwise
522 * return a pointer to the export.
525 /* Get a pointer to the list with the symbols hash value */
526 Export* L = HashTab[Name & HASHTAB_MASK];
528 /* Search through the list in that slot */
529 if (L->Name == Name) {
542 int IsUnresolved (unsigned Name)
543 /* Check if this symbol is an unresolved export */
545 /* Find the export */
546 return IsUnresolvedExport (FindExport (Name));
551 int IsUnresolvedExport (const Export* E)
552 /* Return true if the given export is unresolved */
554 /* Check if it's unresolved */
555 return E != 0 && E->Expr == 0;
560 int IsConstExport (const Export* E)
561 /* Return true if the expression associated with this export is const */
564 /* External symbols cannot be const */
567 return IsConstExpr (E->Expr);
573 long GetExportVal (const Export* E)
574 /* Get the value of this export */
578 Internal ("`%s' is an undefined external", GetString (E->Name));
580 return GetExprVal (E->Expr);
585 static void CheckSymType (const Export* E)
586 /* Check the types for one export */
588 /* External with matching imports */
589 Import* Imp = E->ImpList;
591 if (E->AddrSize != Imp->AddrSize) {
592 /* Export is ZP, import is abs or the other way round */
593 const char* ExpAddrSize = AddrSizeToStr (E->AddrSize);
594 const char* ImpAddrSize = AddrSizeToStr (Imp->AddrSize);
595 const char* ExpObjName = GetObjFileName (E->Obj);
596 const char* ImpObjName = GetObjFileName (Imp->Obj);
598 /* User defined export */
599 Warning ("Address size mismatch for `%s': Exported from %s, "
600 "%s(%lu) as `%s', import in %s, %s(%lu) as `%s'",
603 GetSourceFileName (E->Obj, E->Pos.Name),
607 GetSourceFileName (Imp->Obj, Imp->Pos.Name),
611 /* Export created by the linker */
612 Warning ("Address size mismatch for `%s': Symbol is `%s'"
613 ", but imported from %s, %s(%lu) as `%s'",
617 GetSourceFileName (Imp->Obj, Imp->Pos.Name),
628 static void CheckSymTypes (void)
629 /* Check for symbol tape mismatches */
633 /* Print all open imports */
634 for (I = 0; I < ExpCount; ++I) {
635 const Export* E = ExpPool [I];
636 if (E->Expr != 0 && E->ImpCount > 0) {
637 /* External with matching imports */
645 static void PrintUnresolved (ExpCheckFunc F, void* Data)
646 /* Print a list of unresolved symbols. On unresolved symbols, F is
647 * called (see the comments on ExpCheckFunc in the data section).
652 /* Print all open imports */
653 for (I = 0; I < ExpCount; ++I) {
654 Export* E = ExpPool [I];
655 if (E->Expr == 0 && E->ImpCount > 0 && F (E->Name, Data) == 0) {
656 /* Unresolved external */
657 Import* Imp = E->ImpList;
659 "Unresolved external `%s' referenced in:\n",
660 GetString (E->Name));
662 const char* Name = GetSourceFileName (Imp->Obj, Imp->Pos.Name);
663 fprintf (stderr, " %s(%lu)\n", Name, Imp->Pos.Line);
672 static int CmpExpName (const void* K1, const void* K2)
673 /* Compare function for qsort */
675 return SB_Compare (GetStrBuf ((*(Export**)K1)->Name),
676 GetStrBuf ((*(Export**)K2)->Name));
681 static void CreateExportPool (void)
682 /* Create an array with pointer to all exports */
686 /* Allocate memory */
690 ExpPool = xmalloc (ExpCount * sizeof (Export*));
692 /* Walk through the list and insert the exports */
693 for (I = 0, J = 0; I < sizeof (HashTab) / sizeof (HashTab [0]); ++I) {
694 Export* E = HashTab[I];
696 CHECK (J < ExpCount);
702 /* Sort them by name */
703 qsort (ExpPool, ExpCount, sizeof (Export*), CmpExpName);
708 void CheckExports (void)
709 /* Setup the list of all exports and check for export/import symbol type
713 /* Create an export pool */
716 /* Check for symbol type mismatches */
722 void CheckUnresolvedImports (ExpCheckFunc F, void* Data)
723 /* Check if there are any unresolved imports. On unresolved imports, F is
724 * called (see the comments on ExpCheckFunc in the data section).
727 /* Check for unresolved externals */
729 /* Print all open imports */
730 PrintUnresolved (F, Data);
736 static char GetAddrSizeCode (unsigned char AddrSize)
737 /* Get a one char code for the address size */
740 case ADDR_SIZE_ZP: return 'Z';
741 case ADDR_SIZE_ABS: return 'A';
742 case ADDR_SIZE_FAR: return 'F';
743 case ADDR_SIZE_LONG: return 'L';
745 Internal ("Invalid address size: %u", AddrSize);
753 void PrintExportMap (FILE* F)
754 /* Print an export map to the given file */
759 /* Print all exports */
761 for (I = 0; I < ExpCount; ++I) {
762 const Export* E = ExpPool [I];
764 /* Print unreferenced symbols only if explictly requested */
765 if (VerboseMap || E->ImpCount > 0 || SYM_IS_CONDES (E->Type)) {
767 "%-25s %06lX %c%c%c%c ",
770 E->ImpCount? 'R' : ' ',
771 SYM_IS_LABEL (E->Type)? 'L' : 'E',
772 GetAddrSizeCode (E->AddrSize),
773 SYM_IS_CONDES (E->Type)? 'I' : ' ');
785 void PrintImportMap (FILE* F)
786 /* Print an import map to the given file */
791 /* Loop over all exports */
792 for (I = 0; I < ExpCount; ++I) {
795 const Export* Exp = ExpPool [I];
797 /* Print the symbol only if there are imports, or if a verbose map
800 if (VerboseMap || Exp->ImpCount > 0) {
802 /* Print the export */
805 GetString (Exp->Name),
806 GetObjFileName (Exp->Obj));
808 /* Print all imports for this symbol */
812 /* Print the import */
815 GetObjFileName (Imp->Obj),
816 GetSourceFileName (Imp->Obj, Imp->Pos.Name),
829 void PrintExportLabels (FILE* F)
830 /* Print the exports in a VICE label file */
834 /* Print all exports */
835 for (I = 0; I < ExpCount; ++I) {
836 const Export* E = ExpPool [I];
837 fprintf (F, "al %06lX .%s\n", GetExportVal (E), GetString (E->Name));
843 void MarkExport (Export* E)
844 /* Mark the export */
846 E->Flags |= EXP_USERMARK;
851 void UnmarkExport (Export* E)
852 /* Remove the mark from the export */
854 E->Flags &= ~EXP_USERMARK;
859 int ExportHasMark (Export* E)
860 /* Return true if the export has a mark */
862 return (E->Flags & EXP_USERMARK) != 0;
867 void CircularRefError (const Export* E)
868 /* Print an error about a circular reference using to define the given export */
870 Error ("Circular reference for symbol `%s', %s(%lu)",
872 GetSourceFileName (E->Obj, E->Pos.Name),