1 /*****************************************************************************/
5 /* Exports handling for the ld65 linker */
9 /* (C) 1998-2011, 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 /*****************************************************************************/
62 /*****************************************************************************/
64 /*****************************************************************************/
69 #define HASHTAB_MASK 0x0FFFU
70 #define HASHTAB_SIZE (HASHTAB_MASK + 1)
71 static Export* HashTab[HASHTAB_SIZE];
73 /* Import management variables */
74 static unsigned ImpCount = 0; /* Import count */
75 static unsigned ImpOpen = 0; /* Count of open imports */
77 /* Export management variables */
78 static unsigned ExpCount = 0; /* Export count */
79 static Export** ExpPool = 0; /* Exports array */
81 /* Defines for the flags in Import */
82 #define IMP_INLIST 0x0001U /* Import is in exports list */
84 /* Defines for the flags in Export */
85 #define EXP_INLIST 0x0001U /* Export is in exports list */
86 #define EXP_USERMARK 0x0002U /* User setable flag */
90 /*****************************************************************************/
92 /*****************************************************************************/
96 static Export* NewExport (unsigned Type, unsigned char AddrSize,
97 unsigned Name, ObjData* Obj);
98 /* Create a new export and initialize it */
102 static Import* NewImport (unsigned char AddrSize, ObjData* Obj)
103 /* Create a new import and initialize it */
105 /* Allocate memory */
106 Import* I = xmalloc (sizeof (Import));
108 /* Initialize the fields */
111 I->DefLines = EmptyCollection;
112 I->RefLines = EmptyCollection;
114 I->Name = INVALID_STRING_ID;
116 I->AddrSize = AddrSize;
118 /* Return the new structure */
124 void FreeImport (Import* I)
125 /* Free an import. NOTE: This won't remove the import from the exports table,
126 * so it may only be called for unused imports (imports from modules that
127 * aren't referenced).
131 PRECONDITION ((I->Flags & IMP_INLIST) == 0);
133 /* Free the line info collections */
134 DoneCollection (&I->DefLines);
135 DoneCollection (&I->RefLines);
137 /* Free the struct */
143 Import* ReadImport (FILE* F, ObjData* Obj)
144 /* Read an import from a file and return it */
148 /* Read the import address size */
149 unsigned char AddrSize = Read8 (F);
151 /* Create a new import */
152 I = NewImport (AddrSize, Obj);
155 I->Name = MakeGlobalStringId (Obj, ReadVar (F));
157 /* Read the line infos */
158 ReadLineInfoList (F, Obj, &I->DefLines);
159 ReadLineInfoList (F, Obj, &I->RefLines);
161 /* Check the address size */
162 if (I->AddrSize == ADDR_SIZE_DEFAULT || I->AddrSize > ADDR_SIZE_LONG) {
163 /* Beware: This function may be called in cases where the object file
164 * is not read completely into memory. In this case, the file list is
165 * invalid. Be sure not to access it in this case.
167 if (ObjHasFiles (I->Obj)) {
168 const LineInfo* LI = GetImportPos (I);
169 Error ("Invalid import size in for `%s', imported from %s(%u): 0x%02X",
175 Error ("Invalid import size in for `%s', imported from %s: 0x%02X",
177 GetObjFileName (I->Obj),
182 /* Return the new import */
188 Import* GenImport (unsigned Name, unsigned char AddrSize)
189 /* Generate a new import with the given name and address size and return it */
191 /* Create a new import */
192 Import* I = NewImport (AddrSize, 0);
197 /* Check the address size */
198 if (I->AddrSize == ADDR_SIZE_DEFAULT || I->AddrSize > ADDR_SIZE_LONG) {
199 /* Beware: This function may be called in cases where the object file
200 * is not read completely into memory. In this case, the file list is
201 * invalid. Be sure not to access it in this case.
203 if (ObjHasFiles (I->Obj)) {
204 const LineInfo* LI = GetImportPos (I);
205 Error ("Invalid import size in for `%s', imported from %s(%u): 0x%02X",
211 Error ("Invalid import size in for `%s', imported from %s: 0x%02X",
213 GetObjFileName (I->Obj),
218 /* Return the new import */
224 Import* InsertImport (Import* I)
225 /* Insert an import into the table, return I */
229 /* As long as the import is not inserted, V.Name is valid */
230 unsigned Name = I->Name;
232 /* Create a hash value for the given name */
233 unsigned Hash = (Name & HASHTAB_MASK);
235 /* Search through the list in that slot and print matching duplicates */
236 if (HashTab[Hash] == 0) {
237 /* The slot is empty, we need to insert a dummy export */
238 E = HashTab[Hash] = NewExport (0, ADDR_SIZE_DEFAULT, Name, 0);
243 if (E->Name == Name) {
244 /* We have an entry, L points to it */
248 /* End of list an entry not found, insert a dummy */
249 E->Next = NewExport (0, ADDR_SIZE_DEFAULT, Name, 0);
250 E = E->Next; /* Point to dummy */
251 ++ExpCount; /* One export more */
259 /* Ok, E now points to a valid exports entry for the given import. Insert
260 * the import into the imports list and update the counters.
263 I->Next = E->ImpList;
266 ++ImpCount; /* Total import count */
268 /* This is a dummy export */
272 /* Mark the import so we know it's in the list */
273 I->Flags |= IMP_INLIST;
275 /* Return the import to allow shorter code */
281 const LineInfo* GetImportPos (const Import* Imp)
282 /* Return the basic line info of an import */
284 /* Search in DefLines, then in RefLines */
285 const LineInfo* LI = GetAsmLineInfo (&Imp->DefLines);
287 LI = GetAsmLineInfo (&Imp->RefLines);
294 /*****************************************************************************/
296 /*****************************************************************************/
300 static Export* NewExport (unsigned Type, unsigned char AddrSize,
301 unsigned Name, ObjData* Obj)
302 /* Create a new export and initialize it */
304 /* Allocate memory */
305 Export* E = xmalloc (sizeof (Export));
307 /* Initialize the fields */
316 E->DefLines = EmptyCollection;
317 E->RefLines = EmptyCollection;
319 E->Type = Type | SYM_EXPORT;
320 E->AddrSize = AddrSize;
321 memset (E->ConDes, 0, sizeof (E->ConDes));
323 /* Return the new entry */
329 void FreeExport (Export* E)
330 /* Free an export. NOTE: This won't remove the export from the exports table,
331 * so it may only be called for unused exports (exports from modules that
332 * aren't referenced).
336 PRECONDITION ((E->Flags & EXP_INLIST) == 0);
338 /* Free the line infos */
339 DoneCollection (&E->DefLines);
340 DoneCollection (&E->RefLines);
342 /* Free the export expression */
345 /* Free the struct */
351 Export* ReadExport (FILE* F, ObjData* O)
352 /* Read an export from a file */
354 unsigned ConDesCount;
358 unsigned Type = ReadVar (F);
360 /* Read the address size */
361 unsigned char AddrSize = Read8 (F);
363 /* Create a new export without a name */
364 E = NewExport (Type, AddrSize, INVALID_STRING_ID, O);
366 /* Read the constructor/destructor decls if we have any */
367 ConDesCount = SYM_GET_CONDES_COUNT (Type);
368 if (ConDesCount > 0) {
370 unsigned char ConDes[CD_TYPE_COUNT];
373 /* Read the data into temp storage */
374 ReadData (F, ConDes, ConDesCount);
376 /* Re-order the data. In the file, each decl is encoded into a byte
377 * which contains the type and the priority. In memory, we will use
378 * an array of types which contain the priority. This array was
379 * cleared by the constructor (NewExport), so we must only set the
380 * fields that contain values.
382 for (I = 0; I < ConDesCount; ++I) {
383 unsigned ConDesType = CD_GET_TYPE (ConDes[I]);
384 unsigned ConDesPrio = CD_GET_PRIO (ConDes[I]);
385 E->ConDes[ConDesType] = ConDesPrio;
390 E->Name = MakeGlobalStringId (O, ReadVar (F));
393 if (SYM_IS_EXPR (Type)) {
394 E->Expr = ReadExpr (F, O);
396 E->Expr = LiteralExpr (Read32 (F), O);
400 if (SYM_HAS_SIZE (Type)) {
401 E->Size = ReadVar (F);
404 /* Last are the locations */
405 ReadLineInfoList (F, O, &E->DefLines);
406 ReadLineInfoList (F, O, &E->RefLines);
408 /* Return the new export */
414 void InsertExport (Export* E)
415 /* Insert an exported identifier and check if it's already in the list */
422 /* Mark the export as inserted */
423 E->Flags |= EXP_INLIST;
425 /* Insert the export into any condes tables if needed */
426 if (SYM_IS_CONDES (E->Type)) {
430 /* Create a hash value for the given name */
431 Hash = (E->Name & HASHTAB_MASK);
433 /* Search through the list in that slot */
434 if (HashTab[Hash] == 0) {
435 /* The slot is empty */
443 if (L->Name == E->Name) {
444 /* This may be an unresolved external */
447 /* This *is* an unresolved external. Use the actual export
448 * in E instead of the dummy one in L.
451 E->ImpCount = L->ImpCount;
452 E->ImpList = L->ImpList;
458 ImpOpen -= E->ImpCount; /* Decrease open imports now */
460 /* We must run through the import list and change the
461 * export pointer now.
469 /* Duplicate entry, ignore it */
470 Warning ("Duplicate external identifier: `%s'",
471 GetString (L->Name));
480 /* Insert export at end of queue */
488 const LineInfo* GetExportPos (const Export* E)
489 /* Return the basic line info of an export */
491 /* Search in DefLines, then in RefLines */
492 const LineInfo* LI = GetAsmLineInfo (&E->DefLines);
494 LI = GetAsmLineInfo (&E->RefLines);
501 Export* CreateConstExport (unsigned Name, long Value)
502 /* Create an export for a literal date */
504 /* Create a new export */
505 Export* E = NewExport (SYM_CONST|SYM_EQUATE, ADDR_SIZE_ABS, Name, 0);
507 /* Assign the value */
508 E->Expr = LiteralExpr (Value, 0);
510 /* Insert the export */
513 /* Return the new export */
519 Export* CreateExprExport (unsigned Name, ExprNode* Expr, unsigned char AddrSize)
520 /* Create an export for an expression */
522 /* Create a new export */
523 Export* E = NewExport (SYM_EXPR|SYM_EQUATE, AddrSize, Name, 0);
525 /* Assign the value expression */
528 /* Insert the export */
531 /* Return the new export */
537 Export* CreateMemoryExport (unsigned Name, MemoryArea* Mem, unsigned long Offs)
538 /* Create an relative export for a memory area offset */
540 /* Create a new export */
541 Export* E = NewExport (SYM_EXPR | SYM_LABEL, ADDR_SIZE_ABS, Name, 0);
543 /* Assign the value */
544 E->Expr = MemoryExpr (Mem, Offs, 0);
546 /* Insert the export */
549 /* Return the new export */
555 Export* CreateSegmentExport (unsigned Name, Segment* Seg, unsigned long Offs)
556 /* Create a relative export to a segment */
558 /* Create a new export */
559 Export* E = NewExport (SYM_EXPR | SYM_LABEL, Seg->AddrSize, Name, 0);
561 /* Assign the value */
562 E->Expr = SegmentExpr (Seg, Offs, 0);
564 /* Insert the export */
567 /* Return the new export */
573 Export* CreateSectionExport (unsigned Name, Section* Sec, unsigned long Offs)
574 /* Create a relative export to a section */
576 /* Create a new export */
577 Export* E = NewExport (SYM_EXPR | SYM_LABEL, Sec->AddrSize, Name, 0);
579 /* Assign the value */
580 E->Expr = SectionExpr (Sec, Offs, 0);
582 /* Insert the export */
585 /* Return the new export */
591 Export* FindExport (unsigned Name)
592 /* Check for an identifier in the list. Return 0 if not found, otherwise
593 * return a pointer to the export.
596 /* Get a pointer to the list with the symbols hash value */
597 Export* L = HashTab[Name & HASHTAB_MASK];
599 /* Search through the list in that slot */
600 if (L->Name == Name) {
613 int IsUnresolved (unsigned Name)
614 /* Check if this symbol is an unresolved export */
616 /* Find the export */
617 return IsUnresolvedExport (FindExport (Name));
622 int IsUnresolvedExport (const Export* E)
623 /* Return true if the given export is unresolved */
625 /* Check if it's unresolved */
626 return E != 0 && E->Expr == 0;
631 int IsConstExport (const Export* E)
632 /* Return true if the expression associated with this export is const */
635 /* External symbols cannot be const */
638 return IsConstExpr (E->Expr);
644 long GetExportVal (const Export* E)
645 /* Get the value of this export */
649 Internal ("`%s' is an undefined external", GetString (E->Name));
651 return GetExprVal (E->Expr);
656 static void CheckSymType (const Export* E)
657 /* Check the types for one export */
659 /* External with matching imports */
660 Import* I = E->ImpList;
662 if (E->AddrSize != I->AddrSize) {
663 /* Export and import address sizes do not match */
664 StrBuf ExportLoc = STATIC_STRBUF_INITIALIZER;
665 StrBuf ImportLoc = STATIC_STRBUF_INITIALIZER;
666 const char* ExpAddrSize = AddrSizeToStr (E->AddrSize);
667 const char* ImpAddrSize = AddrSizeToStr (I->AddrSize);
668 const LineInfo* ExportLI = GetExportPos (E);
669 const LineInfo* ImportLI = GetImportPos (I);
671 /* Generate strings that describe the location of the im- and
672 * exports. This depends on the place from where they come:
673 * Object file or linker config.
676 /* The export comes from an object file */
677 SB_Printf (&ExportLoc, "%s, %s(%u)",
678 GetString (E->Obj->Name),
679 GetSourceName (ExportLI),
680 GetSourceLine (ExportLI));
682 SB_Printf (&ExportLoc, "%s(%u)",
683 GetSourceName (ExportLI),
684 GetSourceLine (ExportLI));
687 /* The import comes from an object file */
688 SB_Printf (&ImportLoc, "%s, %s(%u)",
689 GetString (I->Obj->Name),
690 GetSourceName (ImportLI),
691 GetSourceLine (ImportLI));
693 SB_Printf (&ImportLoc, "%s(%u)",
694 GetSourceName (ImportLI),
695 GetSourceLine (ImportLI));
698 /* Output the diagnostic */
699 Warning ("Address size mismatch for `%s': "
700 "Exported from %s as `%s', "
701 "import in %s as `%s'",
703 SB_GetConstBuf (&ExportLoc),
705 SB_GetConstBuf (&ImportLoc),
708 /* Free the temporary strings */
709 SB_Done (&ExportLoc);
710 SB_Done (&ImportLoc);
718 static void CheckSymTypes (void)
719 /* Check for symbol tape mismatches */
723 /* Print all open imports */
724 for (I = 0; I < ExpCount; ++I) {
725 const Export* E = ExpPool [I];
726 if (E->Expr != 0 && E->ImpCount > 0) {
727 /* External with matching imports */
735 static void PrintUnresolved (ExpCheckFunc F, void* Data)
736 /* Print a list of unresolved symbols. On unresolved symbols, F is
737 * called (see the comments on ExpCheckFunc in the data section).
742 /* Print all open imports */
743 for (I = 0; I < ExpCount; ++I) {
744 Export* E = ExpPool [I];
745 if (E->Expr == 0 && E->ImpCount > 0 && F (E->Name, Data) == 0) {
746 /* Unresolved external */
747 Import* Imp = E->ImpList;
749 "Unresolved external `%s' referenced in:\n",
750 GetString (E->Name));
753 for (J = 0; J < CollCount (&Imp->RefLines); ++J) {
754 const LineInfo* LI = CollConstAt (&Imp->RefLines, J);
768 static int CmpExpName (const void* K1, const void* K2)
769 /* Compare function for qsort */
771 return SB_Compare (GetStrBuf ((*(Export**)K1)->Name),
772 GetStrBuf ((*(Export**)K2)->Name));
777 static void CreateExportPool (void)
778 /* Create an array with pointer to all exports */
782 /* Allocate memory */
786 ExpPool = xmalloc (ExpCount * sizeof (Export*));
788 /* Walk through the list and insert the exports */
789 for (I = 0, J = 0; I < sizeof (HashTab) / sizeof (HashTab [0]); ++I) {
790 Export* E = HashTab[I];
792 CHECK (J < ExpCount);
798 /* Sort them by name */
799 qsort (ExpPool, ExpCount, sizeof (Export*), CmpExpName);
804 void CheckExports (void)
805 /* Setup the list of all exports and check for export/import symbol type
809 /* Create an export pool */
812 /* Check for symbol type mismatches */
818 void CheckUnresolvedImports (ExpCheckFunc F, void* Data)
819 /* Check if there are any unresolved imports. On unresolved imports, F is
820 * called (see the comments on ExpCheckFunc in the data section).
823 /* Check for unresolved externals */
825 /* Print all open imports */
826 PrintUnresolved (F, Data);
832 static char GetAddrSizeCode (unsigned char AddrSize)
833 /* Get a one char code for the address size */
836 case ADDR_SIZE_ZP: return 'Z';
837 case ADDR_SIZE_ABS: return 'A';
838 case ADDR_SIZE_FAR: return 'F';
839 case ADDR_SIZE_LONG: return 'L';
841 Internal ("Invalid address size: %u", AddrSize);
849 void PrintExportMap (FILE* F)
850 /* Print an export map to the given file */
855 /* Print all exports */
857 for (I = 0; I < ExpCount; ++I) {
858 const Export* E = ExpPool [I];
860 /* Print unreferenced symbols only if explictly requested */
861 if (VerboseMap || E->ImpCount > 0 || SYM_IS_CONDES (E->Type)) {
863 "%-25s %06lX %c%c%c%c ",
866 E->ImpCount? 'R' : ' ',
867 SYM_IS_LABEL (E->Type)? 'L' : 'E',
868 GetAddrSizeCode (E->AddrSize),
869 SYM_IS_CONDES (E->Type)? 'I' : ' ');
881 void PrintImportMap (FILE* F)
882 /* Print an import map to the given file */
887 /* Loop over all exports */
888 for (I = 0; I < ExpCount; ++I) {
891 const Export* Exp = ExpPool [I];
893 /* Print the symbol only if there are imports, or if a verbose map
896 if (VerboseMap || Exp->ImpCount > 0) {
898 /* Print the export */
901 GetString (Exp->Name),
902 GetObjFileName (Exp->Obj));
904 /* Print all imports for this symbol */
908 /* Print the import */
909 const LineInfo* LI = GetImportPos (Imp);
912 GetObjFileName (Imp->Obj),
926 void PrintExportLabels (FILE* F)
927 /* Print the exports in a VICE label file */
931 /* Print all exports */
932 for (I = 0; I < ExpCount; ++I) {
933 const Export* E = ExpPool [I];
934 fprintf (F, "al %06lX .%s\n", GetExportVal (E), GetString (E->Name));
940 void MarkExport (Export* E)
941 /* Mark the export */
943 E->Flags |= EXP_USERMARK;
948 void UnmarkExport (Export* E)
949 /* Remove the mark from the export */
951 E->Flags &= ~EXP_USERMARK;
956 int ExportHasMark (Export* E)
957 /* Return true if the export has a mark */
959 return (E->Flags & EXP_USERMARK) != 0;
964 void CircularRefError (const Export* E)
965 /* Print an error about a circular reference using to define the given export */
967 const LineInfo* LI = GetExportPos (E);
968 Error ("Circular reference for symbol `%s', %s(%u)",