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 */
306 /* Allocate memory */
307 Export* E = xmalloc (sizeof (Export));
309 /* Initialize the fields */
318 E->DefLines = EmptyCollection;
319 E->RefLines = EmptyCollection;
321 E->Type = Type | SYM_EXPORT;
322 E->AddrSize = AddrSize;
323 for (I = 0; I < sizeof (E->ConDes) / sizeof (E->ConDes[0]); ++I) {
324 E->ConDes[I] = CD_PRIO_NONE;
327 /* Return the new entry */
333 void FreeExport (Export* E)
334 /* Free an export. NOTE: This won't remove the export from the exports table,
335 * so it may only be called for unused exports (exports from modules that
336 * aren't referenced).
340 PRECONDITION ((E->Flags & EXP_INLIST) == 0);
342 /* Free the line infos */
343 DoneCollection (&E->DefLines);
344 DoneCollection (&E->RefLines);
346 /* Free the export expression */
349 /* Free the struct */
355 Export* ReadExport (FILE* F, ObjData* O)
356 /* Read an export from a file */
358 unsigned ConDesCount;
363 unsigned Type = ReadVar (F);
365 /* Read the address size */
366 unsigned char AddrSize = Read8 (F);
368 /* Create a new export without a name */
369 E = NewExport (Type, AddrSize, INVALID_STRING_ID, O);
371 /* Read the constructor/destructor decls if we have any */
372 ConDesCount = SYM_GET_CONDES_COUNT (Type);
373 if (ConDesCount > 0) {
375 unsigned char ConDes[CD_TYPE_COUNT];
377 /* Read the data into temp storage */
378 ReadData (F, ConDes, ConDesCount);
380 /* Re-order the data. In the file, each decl is encoded into a byte
381 * which contains the type and the priority. In memory, we will use
382 * an array of types which contain the priority.
384 for (I = 0; I < ConDesCount; ++I) {
385 E->ConDes[CD_GET_TYPE (ConDes[I])] = CD_GET_PRIO (ConDes[I]);
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 /* If this symbol is exported as a condes, and the condes type declares a
409 * forced import, add this import to the object module.
411 for (I = 0; I < CD_TYPE_COUNT; ++I) {
412 const ConDesImport* CDI;
413 if (E->ConDes[I] != CD_PRIO_NONE && (CDI = ConDesGetImport (I)) != 0) {
417 /* Generate a new import and insert it */
418 Import* Imp = InsertImport (GenImport (CDI->Name, CDI->AddrSize));
420 /* Add line info for the config file and for the export that is
421 * actually the condes that forces the import.
423 CollAppend (&Imp->RefLines, GenLineInfo (&CDI->Pos));
424 for (J = 0; J < CollCount (&E->DefLines); ++J) {
425 CollAppend (&Imp->RefLines, DupLineInfo (CollAt (&E->DefLines, J)));
430 /* Return the new export */
436 void InsertExport (Export* E)
437 /* Insert an exported identifier and check if it's already in the list */
444 /* Mark the export as inserted */
445 E->Flags |= EXP_INLIST;
447 /* Insert the export into any condes tables if needed */
448 if (SYM_IS_CONDES (E->Type)) {
452 /* Create a hash value for the given name */
453 Hash = (E->Name & HASHTAB_MASK);
455 /* Search through the list in that slot */
456 if (HashTab[Hash] == 0) {
457 /* The slot is empty */
465 if (L->Name == E->Name) {
466 /* This may be an unresolved external */
469 /* This *is* an unresolved external. Use the actual export
470 * in E instead of the dummy one in L.
473 E->ImpCount = L->ImpCount;
474 E->ImpList = L->ImpList;
480 ImpOpen -= E->ImpCount; /* Decrease open imports now */
482 /* We must run through the import list and change the
483 * export pointer now.
491 /* Duplicate entry, ignore it */
492 Warning ("Duplicate external identifier: `%s'",
493 GetString (L->Name));
502 /* Insert export at end of queue */
510 const LineInfo* GetExportPos (const Export* E)
511 /* Return the basic line info of an export */
513 /* Search in DefLines, then in RefLines */
514 const LineInfo* LI = GetAsmLineInfo (&E->DefLines);
516 LI = GetAsmLineInfo (&E->RefLines);
523 Export* CreateConstExport (unsigned Name, long Value)
524 /* Create an export for a literal date */
526 /* Create a new export */
527 Export* E = NewExport (SYM_CONST|SYM_EQUATE, ADDR_SIZE_ABS, Name, 0);
529 /* Assign the value */
530 E->Expr = LiteralExpr (Value, 0);
532 /* Insert the export */
535 /* Return the new export */
541 Export* CreateExprExport (unsigned Name, ExprNode* Expr, unsigned char AddrSize)
542 /* Create an export for an expression */
544 /* Create a new export */
545 Export* E = NewExport (SYM_EXPR|SYM_EQUATE, AddrSize, Name, 0);
547 /* Assign the value expression */
550 /* Insert the export */
553 /* Return the new export */
559 Export* CreateMemoryExport (unsigned Name, MemoryArea* Mem, unsigned long Offs)
560 /* Create an relative export for a memory area offset */
562 /* Create a new export */
563 Export* E = NewExport (SYM_EXPR | SYM_LABEL, ADDR_SIZE_ABS, Name, 0);
565 /* Assign the value */
566 E->Expr = MemoryExpr (Mem, Offs, 0);
568 /* Insert the export */
571 /* Return the new export */
577 Export* CreateSegmentExport (unsigned Name, Segment* Seg, unsigned long Offs)
578 /* Create a relative export to a segment */
580 /* Create a new export */
581 Export* E = NewExport (SYM_EXPR | SYM_LABEL, Seg->AddrSize, Name, 0);
583 /* Assign the value */
584 E->Expr = SegmentExpr (Seg, Offs, 0);
586 /* Insert the export */
589 /* Return the new export */
595 Export* CreateSectionExport (unsigned Name, Section* Sec, unsigned long Offs)
596 /* Create a relative export to a section */
598 /* Create a new export */
599 Export* E = NewExport (SYM_EXPR | SYM_LABEL, Sec->AddrSize, Name, 0);
601 /* Assign the value */
602 E->Expr = SectionExpr (Sec, Offs, 0);
604 /* Insert the export */
607 /* Return the new export */
613 Export* FindExport (unsigned Name)
614 /* Check for an identifier in the list. Return 0 if not found, otherwise
615 * return a pointer to the export.
618 /* Get a pointer to the list with the symbols hash value */
619 Export* L = HashTab[Name & HASHTAB_MASK];
621 /* Search through the list in that slot */
622 if (L->Name == Name) {
635 int IsUnresolved (unsigned Name)
636 /* Check if this symbol is an unresolved export */
638 /* Find the export */
639 return IsUnresolvedExport (FindExport (Name));
644 int IsUnresolvedExport (const Export* E)
645 /* Return true if the given export is unresolved */
647 /* Check if it's unresolved */
648 return E != 0 && E->Expr == 0;
653 int IsConstExport (const Export* E)
654 /* Return true if the expression associated with this export is const */
657 /* External symbols cannot be const */
660 return IsConstExpr (E->Expr);
666 long GetExportVal (const Export* E)
667 /* Get the value of this export */
671 Internal ("`%s' is an undefined external", GetString (E->Name));
673 return GetExprVal (E->Expr);
678 static void CheckSymType (const Export* E)
679 /* Check the types for one export */
681 /* External with matching imports */
682 Import* I = E->ImpList;
684 if (E->AddrSize != I->AddrSize) {
685 /* Export and import address sizes do not match */
686 StrBuf ExportLoc = STATIC_STRBUF_INITIALIZER;
687 StrBuf ImportLoc = STATIC_STRBUF_INITIALIZER;
688 const char* ExpAddrSize = AddrSizeToStr (E->AddrSize);
689 const char* ImpAddrSize = AddrSizeToStr (I->AddrSize);
690 const LineInfo* ExportLI = GetExportPos (E);
691 const LineInfo* ImportLI = GetImportPos (I);
693 /* Generate strings that describe the location of the im- and
694 * exports. This depends on the place from where they come:
695 * Object file or linker config.
698 /* The export comes from an object file */
699 SB_Printf (&ExportLoc, "%s, %s(%u)",
700 GetString (E->Obj->Name),
701 GetSourceName (ExportLI),
702 GetSourceLine (ExportLI));
704 SB_Printf (&ExportLoc, "%s(%u)",
705 GetSourceName (ExportLI),
706 GetSourceLine (ExportLI));
709 /* The import comes from an object file */
710 SB_Printf (&ImportLoc, "%s, %s(%u)",
711 GetString (I->Obj->Name),
712 GetSourceName (ImportLI),
713 GetSourceLine (ImportLI));
715 SB_Printf (&ImportLoc, "%s(%u)",
716 GetSourceName (ImportLI),
717 GetSourceLine (ImportLI));
720 /* Output the diagnostic */
721 Warning ("Address size mismatch for `%s': "
722 "Exported from %s as `%s', "
723 "import in %s as `%s'",
725 SB_GetConstBuf (&ExportLoc),
727 SB_GetConstBuf (&ImportLoc),
730 /* Free the temporary strings */
731 SB_Done (&ExportLoc);
732 SB_Done (&ImportLoc);
740 static void CheckSymTypes (void)
741 /* Check for symbol tape mismatches */
745 /* Print all open imports */
746 for (I = 0; I < ExpCount; ++I) {
747 const Export* E = ExpPool [I];
748 if (E->Expr != 0 && E->ImpCount > 0) {
749 /* External with matching imports */
757 static void PrintUnresolved (ExpCheckFunc F, void* Data)
758 /* Print a list of unresolved symbols. On unresolved symbols, F is
759 * called (see the comments on ExpCheckFunc in the data section).
764 /* Print all open imports */
765 for (I = 0; I < ExpCount; ++I) {
766 Export* E = ExpPool [I];
767 if (E->Expr == 0 && E->ImpCount > 0 && F (E->Name, Data) == 0) {
768 /* Unresolved external */
769 Import* Imp = E->ImpList;
771 "Unresolved external `%s' referenced in:\n",
772 GetString (E->Name));
775 for (J = 0; J < CollCount (&Imp->RefLines); ++J) {
776 const LineInfo* LI = CollConstAt (&Imp->RefLines, J);
790 static int CmpExpName (const void* K1, const void* K2)
791 /* Compare function for qsort */
793 return SB_Compare (GetStrBuf ((*(Export**)K1)->Name),
794 GetStrBuf ((*(Export**)K2)->Name));
799 static void CreateExportPool (void)
800 /* Create an array with pointer to all exports */
804 /* Allocate memory */
808 ExpPool = xmalloc (ExpCount * sizeof (Export*));
810 /* Walk through the list and insert the exports */
811 for (I = 0, J = 0; I < sizeof (HashTab) / sizeof (HashTab [0]); ++I) {
812 Export* E = HashTab[I];
814 CHECK (J < ExpCount);
820 /* Sort them by name */
821 qsort (ExpPool, ExpCount, sizeof (Export*), CmpExpName);
826 void CheckExports (void)
827 /* Setup the list of all exports and check for export/import symbol type
831 /* Create an export pool */
834 /* Check for symbol type mismatches */
840 void CheckUnresolvedImports (ExpCheckFunc F, void* Data)
841 /* Check if there are any unresolved imports. On unresolved imports, F is
842 * called (see the comments on ExpCheckFunc in the data section).
845 /* Check for unresolved externals */
847 /* Print all open imports */
848 PrintUnresolved (F, Data);
854 static char GetAddrSizeCode (unsigned char AddrSize)
855 /* Get a one char code for the address size */
858 case ADDR_SIZE_ZP: return 'Z';
859 case ADDR_SIZE_ABS: return 'A';
860 case ADDR_SIZE_FAR: return 'F';
861 case ADDR_SIZE_LONG: return 'L';
863 Internal ("Invalid address size: %u", AddrSize);
871 void PrintExportMap (FILE* F)
872 /* Print an export map to the given file */
877 /* Print all exports */
879 for (I = 0; I < ExpCount; ++I) {
880 const Export* E = ExpPool [I];
882 /* Print unreferenced symbols only if explictly requested */
883 if (VerboseMap || E->ImpCount > 0 || SYM_IS_CONDES (E->Type)) {
885 "%-25s %06lX %c%c%c%c ",
888 E->ImpCount? 'R' : ' ',
889 SYM_IS_LABEL (E->Type)? 'L' : 'E',
890 GetAddrSizeCode (E->AddrSize),
891 SYM_IS_CONDES (E->Type)? 'I' : ' ');
903 void PrintImportMap (FILE* F)
904 /* Print an import map to the given file */
909 /* Loop over all exports */
910 for (I = 0; I < ExpCount; ++I) {
913 const Export* Exp = ExpPool [I];
915 /* Print the symbol only if there are imports, or if a verbose map
918 if (VerboseMap || Exp->ImpCount > 0) {
920 /* Print the export */
923 GetString (Exp->Name),
924 GetObjFileName (Exp->Obj));
926 /* Print all imports for this symbol */
930 /* Print the import */
931 const LineInfo* LI = GetImportPos (Imp);
934 GetObjFileName (Imp->Obj),
948 void PrintExportLabels (FILE* F)
949 /* Print the exports in a VICE label file */
953 /* Print all exports */
954 for (I = 0; I < ExpCount; ++I) {
955 const Export* E = ExpPool [I];
956 fprintf (F, "al %06lX .%s\n", GetExportVal (E), GetString (E->Name));
962 void MarkExport (Export* E)
963 /* Mark the export */
965 E->Flags |= EXP_USERMARK;
970 void UnmarkExport (Export* E)
971 /* Remove the mark from the export */
973 E->Flags &= ~EXP_USERMARK;
978 int ExportHasMark (Export* E)
979 /* Return true if the export has a mark */
981 return (E->Flags & EXP_USERMARK) != 0;
986 void CircularRefError (const Export* E)
987 /* Print an error about a circular reference using to define the given export */
989 const LineInfo* LI = GetExportPos (E);
990 Error ("Circular reference for symbol `%s', %s(%u)",