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 /*****************************************************************************/
61 /*****************************************************************************/
63 /*****************************************************************************/
68 #define HASHTAB_MASK 0x0FFFU
69 #define HASHTAB_SIZE (HASHTAB_MASK + 1)
70 static Export* HashTab[HASHTAB_SIZE];
72 /* Import management variables */
73 static unsigned ImpCount = 0; /* Import count */
74 static unsigned ImpOpen = 0; /* Count of open imports */
76 /* Export management variables */
77 static unsigned ExpCount = 0; /* Export count */
78 static Export** ExpPool = 0; /* Exports array */
80 /* Defines for the flags in Import */
81 #define IMP_INLIST 0x0001U /* Import is in exports list */
83 /* Defines for the flags in Export */
84 #define EXP_INLIST 0x0001U /* Export is in exports list */
85 #define EXP_USERMARK 0x0002U /* User setable flag */
89 /*****************************************************************************/
91 /*****************************************************************************/
95 static Export* NewExport (unsigned char Type, unsigned char AddrSize,
96 unsigned Name, ObjData* Obj);
97 /* Create a new export and initialize it */
101 static Import* NewImport (unsigned char AddrSize, ObjData* Obj)
102 /* Create a new import and initialize it */
104 /* Allocate memory */
105 Import* I = xmalloc (sizeof (Import));
107 /* Initialize the fields */
110 InitFilePos (&I->Pos);
112 I->Name = INVALID_STRING_ID;
114 I->AddrSize = AddrSize;
116 /* Return the new structure */
122 void FreeImport (Import* I)
123 /* Free an import. NOTE: This won't remove the import from the exports table,
124 * so it may only be called for unused imports (imports from modules that
125 * aren't referenced).
129 PRECONDITION ((I->Flags & IMP_INLIST) == 0);
131 /* Free the struct */
137 Import* ReadImport (FILE* F, ObjData* Obj)
138 /* Read an import from a file and return it */
142 /* Read the import address size */
143 unsigned char AddrSize = Read8 (F);
145 /* Create a new import */
146 I = NewImport (AddrSize, Obj);
149 I->Name = MakeGlobalStringId (Obj, ReadVar (F));
151 /* Read the file position */
152 ReadFilePos (F, &I->Pos);
154 /* Check the address size */
155 if (I->AddrSize == ADDR_SIZE_DEFAULT || I->AddrSize > ADDR_SIZE_LONG) {
156 /* Beware: This function may be called in cases where the object file
157 * is not read completely into memory. In this case, the file list is
158 * invalid. Be sure not to access it in this case.
160 if (ObjHasFiles (I->Obj)) {
161 Error ("Invalid import size in for `%s', imported from %s(%lu): 0x%02X",
163 GetSourceFileName (I->Obj, I->Pos.Name),
167 Error ("Invalid import size in for `%s', imported from %s: 0x%02X",
169 GetObjFileName (I->Obj),
174 /* Return the new import */
180 Import* GenImport (unsigned Name, unsigned char AddrSize)
181 /* Generate a new import with the given name and address size and return it */
183 /* Create a new import */
184 Import* I = NewImport (AddrSize, 0);
189 /* Check the address size */
190 if (I->AddrSize == ADDR_SIZE_DEFAULT || I->AddrSize > ADDR_SIZE_LONG) {
191 /* Beware: This function may be called in cases where the object file
192 * is not read completely into memory. In this case, the file list is
193 * invalid. Be sure not to access it in this case.
195 if (ObjHasFiles (I->Obj)) {
196 Error ("Invalid import size in for `%s', imported from %s(%lu): 0x%02X",
198 GetSourceFileName (I->Obj, I->Pos.Name),
202 Error ("Invalid import size in for `%s', imported from %s: 0x%02X",
204 GetObjFileName (I->Obj),
209 /* Return the new import */
215 Import* InsertImport (Import* I)
216 /* Insert an import into the table, return I */
220 /* As long as the import is not inserted, V.Name is valid */
221 unsigned Name = I->Name;
223 /* Create a hash value for the given name */
224 unsigned Hash = (Name & HASHTAB_MASK);
226 /* Search through the list in that slot and print matching duplicates */
227 if (HashTab[Hash] == 0) {
228 /* The slot is empty, we need to insert a dummy export */
229 E = HashTab[Hash] = NewExport (0, ADDR_SIZE_DEFAULT, Name, 0);
234 if (E->Name == Name) {
235 /* We have an entry, L points to it */
239 /* End of list an entry not found, insert a dummy */
240 E->Next = NewExport (0, ADDR_SIZE_DEFAULT, Name, 0);
241 E = E->Next; /* Point to dummy */
242 ++ExpCount; /* One export more */
250 /* Ok, E now points to a valid exports entry for the given import. Insert
251 * the import into the imports list and update the counters.
254 I->Next = E->ImpList;
257 ++ImpCount; /* Total import count */
259 /* This is a dummy export */
263 /* Mark the import so we know it's in the list */
264 I->Flags |= IMP_INLIST;
266 /* Return the import to allow shorter code */
272 /*****************************************************************************/
274 /*****************************************************************************/
278 static Export* NewExport (unsigned char Type, unsigned char AddrSize,
279 unsigned Name, ObjData* Obj)
280 /* Create a new export and initialize it */
282 /* Allocate memory */
283 Export* E = xmalloc (sizeof (Export));
285 /* Initialize the fields */
294 E->AddrSize = AddrSize;
295 memset (E->ConDes, 0, sizeof (E->ConDes));
297 /* Return the new entry */
303 void FreeExport (Export* E)
304 /* Free an export. NOTE: This won't remove the export from the exports table,
305 * so it may only be called for unused exports (exports from modules that
306 * aren't referenced).
310 PRECONDITION ((E->Flags & EXP_INLIST) == 0);
312 /* Free the export expression */
315 /* Free the struct */
321 void InsertExport (Export* E)
322 /* Insert an exported identifier and check if it's already in the list */
329 /* Mark the export as inserted */
330 E->Flags |= EXP_INLIST;
332 /* Insert the export into any condes tables if needed */
333 if (SYM_IS_CONDES (E->Type)) {
337 /* Create a hash value for the given name */
338 Hash = (E->Name & HASHTAB_MASK);
340 /* Search through the list in that slot */
341 if (HashTab[Hash] == 0) {
342 /* The slot is empty */
350 if (L->Name == E->Name) {
351 /* This may be an unresolved external */
354 /* This *is* an unresolved external. Use the actual export
355 * in E instead of the dummy one in L.
358 E->ImpCount = L->ImpCount;
359 E->ImpList = L->ImpList;
365 ImpOpen -= E->ImpCount; /* Decrease open imports now */
367 /* We must run through the import list and change the
368 * export pointer now.
376 /* Duplicate entry, ignore it */
377 Warning ("Duplicate external identifier: `%s'",
378 GetString (L->Name));
387 /* Insert export at end of queue */
395 Export* ReadExport (FILE* F, ObjData* O)
396 /* Read an export from a file */
398 unsigned ConDesCount;
402 unsigned char Type = ReadVar (F);
404 /* Read the address size */
405 unsigned char AddrSize = Read8 (F);
407 /* Create a new export without a name */
408 E = NewExport (Type, AddrSize, INVALID_STRING_ID, O);
410 /* Read the constructor/destructor decls if we have any */
411 ConDesCount = SYM_GET_CONDES_COUNT (Type);
412 if (ConDesCount > 0) {
414 unsigned char ConDes[CD_TYPE_COUNT];
417 /* Read the data into temp storage */
418 ReadData (F, ConDes, ConDesCount);
420 /* Re-order the data. In the file, each decl is encoded into a byte
421 * which contains the type and the priority. In memory, we will use
422 * an array of types which contain the priority. This array was
423 * cleared by the constructor (NewExport), so we must only set the
424 * fields that contain values.
426 for (I = 0; I < ConDesCount; ++I) {
427 unsigned ConDesType = CD_GET_TYPE (ConDes[I]);
428 unsigned ConDesPrio = CD_GET_PRIO (ConDes[I]);
429 E->ConDes[ConDesType] = ConDesPrio;
434 E->Name = MakeGlobalStringId (O, ReadVar (F));
437 if (SYM_IS_EXPR (Type)) {
438 E->Expr = ReadExpr (F, O);
440 E->Expr = LiteralExpr (Read32 (F), O);
443 /* Last is the file position where the definition was done */
444 ReadFilePos (F, &E->Pos);
446 /* Return the new export */
452 Export* CreateConstExport (unsigned Name, long Value)
453 /* Create an export for a literal date */
455 /* Create a new export */
456 Export* E = NewExport (SYM_CONST | SYM_EQUATE, ADDR_SIZE_ABS, Name, 0);
458 /* Assign the value */
459 E->Expr = LiteralExpr (Value, 0);
461 /* Insert the export */
464 /* Return the new export */
470 Export* CreateMemoryExport (unsigned Name, MemoryArea* Mem, unsigned long Offs)
471 /* Create an relative export for a memory area offset */
473 /* Create a new export */
474 Export* E = NewExport (SYM_EXPR | SYM_LABEL, ADDR_SIZE_ABS, Name, 0);
476 /* Assign the value */
477 E->Expr = MemoryExpr (Mem, Offs, 0);
479 /* Insert the export */
482 /* Return the new export */
488 Export* CreateSegmentExport (unsigned Name, Segment* Seg, unsigned long Offs)
489 /* Create a relative export to a segment */
491 /* Create a new export */
492 Export* E = NewExport (SYM_EXPR | SYM_LABEL, Seg->AddrSize, Name, 0);
494 /* Assign the value */
495 E->Expr = SegmentExpr (Seg, Offs, 0);
497 /* Insert the export */
500 /* Return the new export */
506 Export* CreateSectionExport (unsigned Name, Section* Sec, unsigned long Offs)
507 /* Create a relative export to a section */
509 /* Create a new export */
510 Export* E = NewExport (SYM_EXPR | SYM_LABEL, Sec->AddrSize, Name, 0);
512 /* Assign the value */
513 E->Expr = SectionExpr (Sec, Offs, 0);
515 /* Insert the export */
518 /* Return the new export */
524 Export* FindExport (unsigned Name)
525 /* Check for an identifier in the list. Return 0 if not found, otherwise
526 * return a pointer to the export.
529 /* Get a pointer to the list with the symbols hash value */
530 Export* L = HashTab[Name & HASHTAB_MASK];
532 /* Search through the list in that slot */
533 if (L->Name == Name) {
546 int IsUnresolved (unsigned Name)
547 /* Check if this symbol is an unresolved export */
549 /* Find the export */
550 return IsUnresolvedExport (FindExport (Name));
555 int IsUnresolvedExport (const Export* E)
556 /* Return true if the given export is unresolved */
558 /* Check if it's unresolved */
559 return E != 0 && E->Expr == 0;
564 int IsConstExport (const Export* E)
565 /* Return true if the expression associated with this export is const */
568 /* External symbols cannot be const */
571 return IsConstExpr (E->Expr);
577 long GetExportVal (const Export* E)
578 /* Get the value of this export */
582 Internal ("`%s' is an undefined external", GetString (E->Name));
584 return GetExprVal (E->Expr);
589 static void CheckSymType (const Export* E)
590 /* Check the types for one export */
592 /* External with matching imports */
593 Import* Imp = E->ImpList;
595 if (E->AddrSize != Imp->AddrSize) {
596 /* Export is ZP, import is abs or the other way round */
597 const char* ExpAddrSize = AddrSizeToStr (E->AddrSize);
598 const char* ImpAddrSize = AddrSizeToStr (Imp->AddrSize);
599 const char* ExpObjName = GetObjFileName (E->Obj);
600 const char* ImpObjName = GetObjFileName (Imp->Obj);
602 /* User defined export */
603 Warning ("Address size mismatch for `%s': Exported from %s, "
604 "%s(%lu) as `%s', import in %s, %s(%lu) as `%s'",
607 GetSourceFileName (E->Obj, E->Pos.Name),
611 GetSourceFileName (Imp->Obj, Imp->Pos.Name),
615 /* Export created by the linker */
616 Warning ("Address size mismatch for `%s': Symbol is `%s'"
617 ", but imported from %s, %s(%lu) as `%s'",
621 GetSourceFileName (Imp->Obj, Imp->Pos.Name),
632 static void CheckSymTypes (void)
633 /* Check for symbol tape mismatches */
637 /* Print all open imports */
638 for (I = 0; I < ExpCount; ++I) {
639 const Export* E = ExpPool [I];
640 if (E->Expr != 0 && E->ImpCount > 0) {
641 /* External with matching imports */
649 static void PrintUnresolved (ExpCheckFunc F, void* Data)
650 /* Print a list of unresolved symbols. On unresolved symbols, F is
651 * called (see the comments on ExpCheckFunc in the data section).
656 /* Print all open imports */
657 for (I = 0; I < ExpCount; ++I) {
658 Export* E = ExpPool [I];
659 if (E->Expr == 0 && E->ImpCount > 0 && F (E->Name, Data) == 0) {
660 /* Unresolved external */
661 Import* Imp = E->ImpList;
663 "Unresolved external `%s' referenced in:\n",
664 GetString (E->Name));
666 const char* Name = GetSourceFileName (Imp->Obj, Imp->Pos.Name);
667 fprintf (stderr, " %s(%lu)\n", Name, Imp->Pos.Line);
676 static int CmpExpName (const void* K1, const void* K2)
677 /* Compare function for qsort */
679 return SB_Compare (GetStrBuf ((*(Export**)K1)->Name),
680 GetStrBuf ((*(Export**)K2)->Name));
685 static void CreateExportPool (void)
686 /* Create an array with pointer to all exports */
690 /* Allocate memory */
694 ExpPool = xmalloc (ExpCount * sizeof (Export*));
696 /* Walk through the list and insert the exports */
697 for (I = 0, J = 0; I < sizeof (HashTab) / sizeof (HashTab [0]); ++I) {
698 Export* E = HashTab[I];
700 CHECK (J < ExpCount);
706 /* Sort them by name */
707 qsort (ExpPool, ExpCount, sizeof (Export*), CmpExpName);
712 void CheckExports (void)
713 /* Setup the list of all exports and check for export/import symbol type
717 /* Create an export pool */
720 /* Check for symbol type mismatches */
726 void CheckUnresolvedImports (ExpCheckFunc F, void* Data)
727 /* Check if there are any unresolved imports. On unresolved imports, F is
728 * called (see the comments on ExpCheckFunc in the data section).
731 /* Check for unresolved externals */
733 /* Print all open imports */
734 PrintUnresolved (F, Data);
740 static char GetAddrSizeCode (unsigned char AddrSize)
741 /* Get a one char code for the address size */
744 case ADDR_SIZE_ZP: return 'Z';
745 case ADDR_SIZE_ABS: return 'A';
746 case ADDR_SIZE_FAR: return 'F';
747 case ADDR_SIZE_LONG: return 'L';
749 Internal ("Invalid address size: %u", AddrSize);
757 void PrintExportMap (FILE* F)
758 /* Print an export map to the given file */
763 /* Print all exports */
765 for (I = 0; I < ExpCount; ++I) {
766 const Export* E = ExpPool [I];
768 /* Print unreferenced symbols only if explictly requested */
769 if (VerboseMap || E->ImpCount > 0 || SYM_IS_CONDES (E->Type)) {
771 "%-25s %06lX %c%c%c%c ",
774 E->ImpCount? 'R' : ' ',
775 SYM_IS_LABEL (E->Type)? 'L' : 'E',
776 GetAddrSizeCode (E->AddrSize),
777 SYM_IS_CONDES (E->Type)? 'I' : ' ');
789 void PrintImportMap (FILE* F)
790 /* Print an import map to the given file */
795 /* Loop over all exports */
796 for (I = 0; I < ExpCount; ++I) {
799 const Export* Exp = ExpPool [I];
801 /* Print the symbol only if there are imports, or if a verbose map
804 if (VerboseMap || Exp->ImpCount > 0) {
806 /* Print the export */
809 GetString (Exp->Name),
810 GetObjFileName (Exp->Obj));
812 /* Print all imports for this symbol */
816 /* Print the import */
819 GetObjFileName (Imp->Obj),
820 GetSourceFileName (Imp->Obj, Imp->Pos.Name),
833 void PrintExportLabels (FILE* F)
834 /* Print the exports in a VICE label file */
838 /* Print all exports */
839 for (I = 0; I < ExpCount; ++I) {
840 const Export* E = ExpPool [I];
841 fprintf (F, "al %06lX .%s\n", GetExportVal (E), GetString (E->Name));
847 void MarkExport (Export* E)
848 /* Mark the export */
850 E->Flags |= EXP_USERMARK;
855 void UnmarkExport (Export* E)
856 /* Remove the mark from the export */
858 E->Flags &= ~EXP_USERMARK;
863 int ExportHasMark (Export* E)
864 /* Return true if the export has a mark */
866 return (E->Flags & EXP_USERMARK) != 0;
871 void CircularRefError (const Export* E)
872 /* Print an error about a circular reference using to define the given export */
874 Error ("Circular reference for symbol `%s', %s(%lu)",
876 GetSourceFileName (E->Obj, E->Pos.Name),