1 /*****************************************************************************/
5 /* Exports handling for the ld65 linker */
9 /* (C) 1998-2013, 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 /* We have no object file information and no line info for a new
202 Error ("Invalid import size 0x%02X for symbol `%s'",
204 GetString (I->Name));
207 /* Return the new import */
213 Import* InsertImport (Import* I)
214 /* Insert an import into the table, return I */
218 /* As long as the import is not inserted, V.Name is valid */
219 unsigned Name = I->Name;
221 /* Create a hash value for the given name */
222 unsigned Hash = (Name & HASHTAB_MASK);
224 /* Search through the list in that slot for a symbol with that name */
225 if (HashTab[Hash] == 0) {
226 /* The slot is empty, we need to insert a dummy export */
227 E = HashTab[Hash] = NewExport (0, ADDR_SIZE_DEFAULT, Name, 0);
232 if (E->Name == Name) {
233 /* We have an entry, L points to it */
237 /* End of list an entry not found, insert a dummy */
238 E->Next = NewExport (0, ADDR_SIZE_DEFAULT, Name, 0);
239 E = E->Next; /* Point to dummy */
240 ++ExpCount; /* One export more */
248 /* Ok, E now points to a valid exports entry for the given import. Insert
249 * the import into the imports list and update the counters.
252 I->Next = E->ImpList;
255 ++ImpCount; /* Total import count */
257 /* This is a dummy export */
261 /* Mark the import so we know it's in the list */
262 I->Flags |= IMP_INLIST;
264 /* Return the import to allow shorter code */
270 const LineInfo* GetImportPos (const Import* Imp)
271 /* Return the basic line info of an import */
273 /* Search in DefLines, then in RefLines */
274 const LineInfo* LI = GetAsmLineInfo (&Imp->DefLines);
276 LI = GetAsmLineInfo (&Imp->RefLines);
283 /*****************************************************************************/
285 /*****************************************************************************/
289 static Export* NewExport (unsigned Type, unsigned char AddrSize,
290 unsigned Name, ObjData* Obj)
291 /* Create a new export and initialize it */
295 /* Allocate memory */
296 Export* E = xmalloc (sizeof (Export));
298 /* Initialize the fields */
307 E->DefLines = EmptyCollection;
308 E->RefLines = EmptyCollection;
310 E->Type = Type | SYM_EXPORT;
311 E->AddrSize = AddrSize;
312 for (I = 0; I < sizeof (E->ConDes) / sizeof (E->ConDes[0]); ++I) {
313 E->ConDes[I] = CD_PRIO_NONE;
316 /* Return the new entry */
322 void FreeExport (Export* E)
323 /* Free an export. NOTE: This won't remove the export from the exports table,
324 * so it may only be called for unused exports (exports from modules that
325 * aren't referenced).
329 PRECONDITION ((E->Flags & EXP_INLIST) == 0);
331 /* Free the line infos */
332 DoneCollection (&E->DefLines);
333 DoneCollection (&E->RefLines);
335 /* Free the export expression */
338 /* Free the struct */
344 Export* ReadExport (FILE* F, ObjData* O)
345 /* Read an export from a file */
347 unsigned ConDesCount;
352 unsigned Type = ReadVar (F);
354 /* Read the address size */
355 unsigned char AddrSize = Read8 (F);
357 /* Create a new export without a name */
358 E = NewExport (Type, AddrSize, INVALID_STRING_ID, O);
360 /* Read the constructor/destructor decls if we have any */
361 ConDesCount = SYM_GET_CONDES_COUNT (Type);
362 if (ConDesCount > 0) {
364 unsigned char ConDes[CD_TYPE_COUNT];
366 /* Read the data into temp storage */
367 ReadData (F, ConDes, ConDesCount);
369 /* Re-order the data. In the file, each decl is encoded into a byte
370 * which contains the type and the priority. In memory, we will use
371 * an array of types which contain the priority.
373 for (I = 0; I < ConDesCount; ++I) {
374 E->ConDes[CD_GET_TYPE (ConDes[I])] = CD_GET_PRIO (ConDes[I]);
379 E->Name = MakeGlobalStringId (O, ReadVar (F));
382 if (SYM_IS_EXPR (Type)) {
383 E->Expr = ReadExpr (F, O);
385 E->Expr = LiteralExpr (Read32 (F), O);
389 if (SYM_HAS_SIZE (Type)) {
390 E->Size = ReadVar (F);
393 /* Last are the locations */
394 ReadLineInfoList (F, O, &E->DefLines);
395 ReadLineInfoList (F, O, &E->RefLines);
397 /* If this symbol is exported as a condes, and the condes type declares a
398 * forced import, add this import to the object module.
400 for (I = 0; I < CD_TYPE_COUNT; ++I) {
401 const ConDesImport* CDI;
402 if (E->ConDes[I] != CD_PRIO_NONE && (CDI = ConDesGetImport (I)) != 0) {
406 /* Generate a new import and insert it */
407 Import* Imp = InsertImport (GenImport (CDI->Name, CDI->AddrSize));
409 /* Add line info for the config file and for the export that is
410 * actually the condes that forces the import.
412 CollAppend (&Imp->RefLines, GenLineInfo (&CDI->Pos));
413 for (J = 0; J < CollCount (&E->DefLines); ++J) {
414 CollAppend (&Imp->RefLines, DupLineInfo (CollAt (&E->DefLines, J)));
419 /* Return the new export */
425 void InsertExport (Export* E)
426 /* Insert an exported identifier and check if it's already in the list */
433 /* Mark the export as inserted */
434 E->Flags |= EXP_INLIST;
436 /* Insert the export into any condes tables if needed */
437 if (SYM_IS_CONDES (E->Type)) {
441 /* Create a hash value for the given name */
442 Hash = (E->Name & HASHTAB_MASK);
444 /* Search through the list in that slot */
445 if (HashTab[Hash] == 0) {
446 /* The slot is empty */
454 if (L->Name == E->Name) {
455 /* This may be an unresolved external */
458 /* This *is* an unresolved external. Use the actual export
459 * in E instead of the dummy one in L.
462 E->ImpCount = L->ImpCount;
463 E->ImpList = L->ImpList;
469 ImpOpen -= E->ImpCount; /* Decrease open imports now */
471 /* We must run through the import list and change the
472 * export pointer now.
480 /* Duplicate entry, ignore it */
481 Warning ("Duplicate external identifier: `%s'",
482 GetString (L->Name));
491 /* Insert export at end of queue */
499 const LineInfo* GetExportPos (const Export* E)
500 /* Return the basic line info of an export */
502 /* Search in DefLines, then in RefLines */
503 const LineInfo* LI = GetAsmLineInfo (&E->DefLines);
505 LI = GetAsmLineInfo (&E->RefLines);
512 Export* CreateConstExport (unsigned Name, long Value)
513 /* Create an export for a literal date */
515 /* Create a new export */
516 Export* E = NewExport (SYM_CONST|SYM_EQUATE, ADDR_SIZE_ABS, Name, 0);
518 /* Assign the value */
519 E->Expr = LiteralExpr (Value, 0);
521 /* Insert the export */
524 /* Return the new export */
530 Export* CreateExprExport (unsigned Name, ExprNode* Expr, unsigned char AddrSize)
531 /* Create an export for an expression */
533 /* Create a new export */
534 Export* E = NewExport (SYM_EXPR|SYM_EQUATE, AddrSize, Name, 0);
536 /* Assign the value expression */
539 /* Insert the export */
542 /* Return the new export */
548 Export* CreateMemoryExport (unsigned Name, MemoryArea* Mem, unsigned long Offs)
549 /* Create an relative export for a memory area offset */
551 /* Create a new export */
552 Export* E = NewExport (SYM_EXPR | SYM_LABEL, ADDR_SIZE_ABS, Name, 0);
554 /* Assign the value */
555 E->Expr = MemoryExpr (Mem, Offs, 0);
557 /* Insert the export */
560 /* Return the new export */
566 Export* CreateSegmentExport (unsigned Name, Segment* Seg, unsigned long Offs)
567 /* Create a relative export to a segment */
569 /* Create a new export */
570 Export* E = NewExport (SYM_EXPR | SYM_LABEL, Seg->AddrSize, Name, 0);
572 /* Assign the value */
573 E->Expr = SegmentExpr (Seg, Offs, 0);
575 /* Insert the export */
578 /* Return the new export */
584 Export* CreateSectionExport (unsigned Name, Section* Sec, unsigned long Offs)
585 /* Create a relative export to a section */
587 /* Create a new export */
588 Export* E = NewExport (SYM_EXPR | SYM_LABEL, Sec->AddrSize, Name, 0);
590 /* Assign the value */
591 E->Expr = SectionExpr (Sec, Offs, 0);
593 /* Insert the export */
596 /* Return the new export */
602 Export* FindExport (unsigned Name)
603 /* Check for an identifier in the list. Return 0 if not found, otherwise
604 * return a pointer to the export.
607 /* Get a pointer to the list with the symbols hash value */
608 Export* L = HashTab[Name & HASHTAB_MASK];
610 /* Search through the list in that slot */
611 if (L->Name == Name) {
624 int IsUnresolved (unsigned Name)
625 /* Check if this symbol is an unresolved export */
627 /* Find the export */
628 return IsUnresolvedExport (FindExport (Name));
633 int IsUnresolvedExport (const Export* E)
634 /* Return true if the given export is unresolved */
636 /* Check if it's unresolved */
637 return E != 0 && E->Expr == 0;
642 int IsConstExport (const Export* E)
643 /* Return true if the expression associated with this export is const */
646 /* External symbols cannot be const */
649 return IsConstExpr (E->Expr);
655 long GetExportVal (const Export* E)
656 /* Get the value of this export */
660 Internal ("`%s' is an undefined external", GetString (E->Name));
662 return GetExprVal (E->Expr);
667 static void CheckSymType (const Export* E)
668 /* Check the types for one export */
670 /* External with matching imports */
671 Import* I = E->ImpList;
673 if (E->AddrSize != I->AddrSize) {
674 /* Export and import address sizes do not match */
675 StrBuf ExportLoc = STATIC_STRBUF_INITIALIZER;
676 StrBuf ImportLoc = STATIC_STRBUF_INITIALIZER;
677 const char* ExpAddrSize = AddrSizeToStr (E->AddrSize);
678 const char* ImpAddrSize = AddrSizeToStr (I->AddrSize);
679 const LineInfo* ExportLI = GetExportPos (E);
680 const LineInfo* ImportLI = GetImportPos (I);
682 /* Generate strings that describe the location of the im- and
683 * exports. This depends on the place from where they come:
684 * Object file or linker config.
687 /* The export comes from an object file */
688 SB_Printf (&ExportLoc, "%s, %s(%u)",
689 GetString (E->Obj->Name),
690 GetSourceName (ExportLI),
691 GetSourceLine (ExportLI));
693 SB_Printf (&ExportLoc, "%s(%u)",
694 GetSourceName (ExportLI),
695 GetSourceLine (ExportLI));
698 /* The import comes from an object file */
699 SB_Printf (&ImportLoc, "%s, %s(%u)",
700 GetString (I->Obj->Name),
701 GetSourceName (ImportLI),
702 GetSourceLine (ImportLI));
703 } else if (ImportLI) {
704 /* The import is linker generated and we have line
707 SB_Printf (&ImportLoc, "%s(%u)",
708 GetSourceName (ImportLI),
709 GetSourceLine (ImportLI));
711 /* The import is linker generated and we don't have line
714 SB_Printf (&ImportLoc, "%s", GetObjFileName (I->Obj));
717 /* Output the diagnostic */
718 Warning ("Address size mismatch for `%s': "
719 "Exported from %s as `%s', "
720 "import in %s as `%s'",
722 SB_GetConstBuf (&ExportLoc),
724 SB_GetConstBuf (&ImportLoc),
727 /* Free the temporary strings */
728 SB_Done (&ExportLoc);
729 SB_Done (&ImportLoc);
737 static void CheckSymTypes (void)
738 /* Check for symbol tape mismatches */
742 /* Print all open imports */
743 for (I = 0; I < ExpCount; ++I) {
744 const Export* E = ExpPool [I];
745 if (E->Expr != 0 && E->ImpCount > 0) {
746 /* External with matching imports */
754 static void PrintUnresolved (ExpCheckFunc F, void* Data)
755 /* Print a list of unresolved symbols. On unresolved symbols, F is
756 * called (see the comments on ExpCheckFunc in the data section).
761 /* Print all open imports */
762 for (I = 0; I < ExpCount; ++I) {
763 Export* E = ExpPool [I];
764 if (E->Expr == 0 && E->ImpCount > 0 && F (E->Name, Data) == 0) {
765 /* Unresolved external */
766 Import* Imp = E->ImpList;
768 "Unresolved external `%s' referenced in:\n",
769 GetString (E->Name));
772 for (J = 0; J < CollCount (&Imp->RefLines); ++J) {
773 const LineInfo* LI = CollConstAt (&Imp->RefLines, J);
787 static int CmpExpName (const void* K1, const void* K2)
788 /* Compare function for qsort */
790 return SB_Compare (GetStrBuf ((*(Export**)K1)->Name),
791 GetStrBuf ((*(Export**)K2)->Name));
796 static void CreateExportPool (void)
797 /* Create an array with pointer to all exports */
801 /* Allocate memory */
805 ExpPool = xmalloc (ExpCount * sizeof (Export*));
807 /* Walk through the list and insert the exports */
808 for (I = 0, J = 0; I < sizeof (HashTab) / sizeof (HashTab [0]); ++I) {
809 Export* E = HashTab[I];
811 CHECK (J < ExpCount);
817 /* Sort them by name */
818 qsort (ExpPool, ExpCount, sizeof (Export*), CmpExpName);
823 void CheckExports (void)
824 /* Setup the list of all exports and check for export/import symbol type
828 /* Create an export pool */
831 /* Check for symbol type mismatches */
837 void CheckUnresolvedImports (ExpCheckFunc F, void* Data)
838 /* Check if there are any unresolved imports. On unresolved imports, F is
839 * called (see the comments on ExpCheckFunc in the data section).
842 /* Check for unresolved externals */
844 /* Print all open imports */
845 PrintUnresolved (F, Data);
851 static char GetAddrSizeCode (unsigned char AddrSize)
852 /* Get a one char code for the address size */
855 case ADDR_SIZE_ZP: return 'Z';
856 case ADDR_SIZE_ABS: return 'A';
857 case ADDR_SIZE_FAR: return 'F';
858 case ADDR_SIZE_LONG: return 'L';
860 Internal ("Invalid address size: %u", AddrSize);
868 void PrintExportMap (FILE* F)
869 /* Print an export map to the given file */
874 /* Print all exports */
876 for (I = 0; I < ExpCount; ++I) {
877 const Export* E = ExpPool [I];
879 /* Print unreferenced symbols only if explictly requested */
880 if (VerboseMap || E->ImpCount > 0 || SYM_IS_CONDES (E->Type)) {
882 "%-25s %06lX %c%c%c%c ",
885 E->ImpCount? 'R' : ' ',
886 SYM_IS_LABEL (E->Type)? 'L' : 'E',
887 GetAddrSizeCode (E->AddrSize),
888 SYM_IS_CONDES (E->Type)? 'I' : ' ');
900 void PrintImportMap (FILE* F)
901 /* Print an import map to the given file */
906 /* Loop over all exports */
907 for (I = 0; I < ExpCount; ++I) {
910 const Export* Exp = ExpPool [I];
912 /* Print the symbol only if there are imports, or if a verbose map
915 if (VerboseMap || Exp->ImpCount > 0) {
917 /* Print the export */
920 GetString (Exp->Name),
921 GetObjFileName (Exp->Obj));
923 /* Print all imports for this symbol */
927 /* Print the import. Beware: The import might be linker
928 * generated, in which case there is no object file and
929 * sometimes no line information.
931 const LineInfo* LI = GetImportPos (Imp);
935 GetObjFileName (Imp->Obj),
941 GetObjFileName (Imp->Obj));
954 void PrintExportLabels (FILE* F)
955 /* Print the exports in a VICE label file */
959 /* Print all exports */
960 for (I = 0; I < ExpCount; ++I) {
961 const Export* E = ExpPool [I];
962 fprintf (F, "al %06lX .%s\n", GetExportVal (E), GetString (E->Name));
968 void MarkExport (Export* E)
969 /* Mark the export */
971 E->Flags |= EXP_USERMARK;
976 void UnmarkExport (Export* E)
977 /* Remove the mark from the export */
979 E->Flags &= ~EXP_USERMARK;
984 int ExportHasMark (Export* E)
985 /* Return true if the export has a mark */
987 return (E->Flags & EXP_USERMARK) != 0;
992 void CircularRefError (const Export* E)
993 /* Print an error about a circular reference using to define the given export */
995 const LineInfo* LI = GetExportPos (E);
996 Error ("Circular reference for symbol `%s', %s(%u)",