]> git.sur5r.net Git - cc65/blob - src/ld65/exports.c
ad426d238b8668e6ce4b28dca8294ebf31d57a68
[cc65] / src / ld65 / exports.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 exports.c                                 */
4 /*                                                                           */
5 /*                   Exports handling for the ld65 linker                    */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998     Ullrich von Bassewitz                                        */
10 /*              Wacholderweg 14                                              */
11 /*              D-70597 Stuttgart                                            */
12 /* EMail:       uz@musoftware.de                                             */
13 /*                                                                           */
14 /*                                                                           */
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.                                    */
18 /*                                                                           */
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:                            */
22 /*                                                                           */
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              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39
40 /* common */
41 #include "check.h"
42 #include "coll.h"
43 #include "hashstr.h"
44 #include "symdefs.h"
45 #include "xmalloc.h"
46
47 /* ld65 */
48 #include "condes.h"
49 #include "error.h"
50 #include "fileio.h"
51 #include "global.h"
52 #include "objdata.h"
53 #include "expr.h"
54 #include "exports.h"
55
56
57
58 /*****************************************************************************/
59 /*                                   Data                                    */
60 /*****************************************************************************/
61
62
63
64 /* Hash table */
65 #define HASHTAB_SIZE    4081
66 static Export*          HashTab [HASHTAB_SIZE];
67
68 /* Import management variables */
69 static unsigned         ImpCount = 0;           /* Import count */
70 static unsigned         ImpOpen  = 0;           /* Count of open imports */
71
72 /* Export management variables */
73 static unsigned         ExpCount = 0;           /* Export count */
74 static Export**         ExpPool  = 0;           /* Exports array */
75
76 /* Defines for the flags in Export */
77 #define EXP_USERMARK    0x0001
78
79
80
81 /*****************************************************************************/
82 /*                              Import handling                              */
83 /*****************************************************************************/
84
85
86
87 static Export* NewExport (unsigned char Type, const char* Name, ObjData* Obj);
88 /* Create a new export and initialize it */
89
90
91
92 static Import* NewImport (unsigned char Type, ObjData* Obj)
93 /* Create a new import and initialize it */
94 {
95     /* Allocate memory */
96     Import* I = xmalloc (sizeof (Import));
97
98     /* Initialize the fields */
99     I->Next     = 0;
100     I->Obj      = Obj;
101     I->V.Name   = 0;
102     I->Type     = Type;
103
104     /* Return the new structure */
105     return I;
106 }
107
108
109
110 void InsertImport (Import* I)
111 /* Insert an import into the table */
112 {
113     Export* E;
114     unsigned HashVal;
115
116     /* As long as the import is not inserted, V.Name is valid */
117     const char* Name = I->V.Name;
118
119     /* Create a hash value for the given name */
120     HashVal = HashStr (Name) % HASHTAB_SIZE;
121
122     /* Search through the list in that slot and print matching duplicates */
123     if (HashTab [HashVal] == 0) {
124         /* The slot is empty, we need to insert a dummy export */
125         E = HashTab [HashVal] = NewExport (0, Name, 0);
126         ++ExpCount;
127     } else {
128         E = HashTab [HashVal];
129         while (1) {
130             if (strcmp (E->Name, Name) == 0) {
131                 /* We have an entry, L points to it */
132                 break;
133             }
134             if (E->Next == 0) {
135                 /* End of list an entry not found, insert a dummy */
136                 E->Next = NewExport (0, Name, 0);
137                 E = E->Next;            /* Point to dummy */
138                 ++ExpCount;             /* One export more */
139                 break;
140             } else {
141                 E = E->Next;
142             }
143         }
144     }
145
146     /* Ok, E now points to a valid exports entry for the given import. Insert
147      * the import into the imports list and update the counters.
148      */
149     I->V.Exp   = E;
150     I->Next    = E->ImpList;
151     E->ImpList = I;
152     E->ImpCount++;
153     ++ImpCount;                 /* Total import count */
154     if (E->Expr == 0) {
155         /* This is a dummy export */
156         ++ImpOpen;
157     }
158
159     /* Now free the name since it's no longer needed */
160     xfree (Name);
161 }
162
163
164
165 Import* ReadImport (FILE* F, ObjData* Obj)
166 /* Read an import from a file and return it */
167 {
168     Import* I;
169
170     /* Read the import type and check it */
171     unsigned char Type = Read8 (F);
172     if (Type != IMP_ZP && Type != IMP_ABS) {
173         Error ("Unknown import type in module `%s': %02X",
174                GetObjFileName (Obj), Type);
175     }
176
177     /* Create a new import */
178     I = NewImport (Type, Obj);
179
180     /* Read the name */
181     I->V.Name = ReadStr (F);
182
183     /* Read the file position */
184     ReadFilePos (F, &I->Pos);
185
186     /* Return the new import */
187     return I;
188 }
189
190
191
192 /*****************************************************************************/
193 /*                                   Code                                    */
194 /*****************************************************************************/
195
196
197
198 static Export* NewExport (unsigned char Type, const char* Name, ObjData* Obj)
199 /* Create a new export and initialize it */
200 {
201     /* Allocate memory */
202     Export* E = xmalloc (sizeof (Export));
203
204     /* Initialize the fields */
205     E->Next     = 0;
206     E->Flags    = 0;
207     E->Obj      = Obj;
208     E->ImpCount = 0;
209     E->ImpList  = 0;
210     E->Expr     = 0;
211     E->Type     = Type;
212     memset (E->ConDes, 0, sizeof (E->ConDes));
213     if (Name) {
214         E->Name = xstrdup (Name);
215     } else {
216         /* Name will get added later */
217         E->Name = 0;
218     }
219
220     /* Return the new entry */
221     return E;
222 }
223
224
225
226 void InsertExport (Export* E)
227 /* Insert an exported identifier and check if it's already in the list */
228 {
229     Export* L;
230     Export* Last;
231     Import* Imp;
232     unsigned HashVal;
233
234     /* Insert the export into any condes tables if needed */
235     if (IS_EXP_CONDES (E->Type)) {
236         ConDesAddExport (E);
237     }
238
239     /* Create a hash value for the given name */
240     HashVal = HashStr (E->Name) % HASHTAB_SIZE;
241
242     /* Search through the list in that slot */
243     if (HashTab [HashVal] == 0) {
244         /* The slot is empty */
245         HashTab [HashVal] = E;
246         ++ExpCount;
247     } else {
248
249         Last = 0;
250         L = HashTab [HashVal];
251         do {
252             if (strcmp (L->Name, E->Name) == 0) {
253                 /* This may be an unresolved external */
254                 if (L->Expr == 0) {
255
256                     /* This *is* an unresolved external */
257                     E->Next     = L->Next;
258                     E->ImpCount = L->ImpCount;
259                     E->ImpList  = L->ImpList;
260                     if (Last) {
261                         Last->Next = E;
262                     } else {
263                         HashTab [HashVal] = E;
264                     }
265                     ImpOpen -= E->ImpCount;     /* Decrease open imports now */
266                     xfree (L);
267                     /* We must run through the import list and change the
268                      * export pointer now.
269                      */
270                     Imp = E->ImpList;
271                     while (Imp) {
272                         Imp->V.Exp = E;
273                         Imp = Imp->Next;
274                     }
275                 } else {
276                     /* Duplicate entry, ignore it */
277                     Warning ("Duplicate external identifier: `%s'", L->Name);
278                 }
279                 return;
280             }
281             Last = L;
282             L = L->Next;
283
284         } while (L);
285
286         /* Insert export at end of queue */
287         Last->Next = E;
288         ++ExpCount;
289     }
290 }
291
292
293
294 Export* ReadExport (FILE* F, ObjData* O)
295 /* Read an export from a file */
296 {
297     unsigned char Type;
298     unsigned      ConDesCount;
299     Export* E;
300
301     /* Read the type */
302     Type = Read8 (F);
303
304     /* Create a new export without a name */
305     E = NewExport (Type, 0, O);
306
307     /* Read the constructor/destructor decls if we have any */
308     ConDesCount = GET_EXP_CONDES_COUNT (Type);
309     if (ConDesCount > 0) {
310
311         unsigned char ConDes[CD_TYPE_COUNT];
312         unsigned I;
313
314         /* Read the data into temp storage */
315         ReadData (F, ConDes, ConDesCount);
316
317         /* Re-order the data. In the file, each decl is encoded into a byte
318          * which contains the type and the priority. In memory, we will use
319          * an array of types which contain the priority. This array was
320          * cleared by the constructor (NewExport), so we must only set the
321          * fields that contain values.
322          */
323         for (I = 0; I < ConDesCount; ++I) {
324             unsigned ConDesType = CD_GET_TYPE (ConDes[I]);
325             unsigned ConDesPrio = CD_GET_PRIO (ConDes[I]);
326             E->ConDes[ConDesType] = ConDesPrio;
327         }
328     }
329
330     /* Read the name */
331     E->Name = ReadStr (F);
332
333     /* Read the value */
334     if (IS_EXP_EXPR (Type)) {
335         E->Expr = ReadExpr (F, O);
336     } else {
337         E->Expr = LiteralExpr (Read32 (F), O);
338     }
339
340     /* Last is the file position where the definition was done */
341     ReadFilePos (F, &E->Pos);
342
343     /* Return the new export */
344     return E;
345 }
346
347
348
349 Export* CreateConstExport (const char* Name, long Value)
350 /* Create an export for a literal date */
351 {
352     /* Create a new export */
353     Export* E = NewExport (EXP_ABS | EXP_CONST | EXP_EQUATE, Name, 0);
354
355     /* Assign the value */
356     E->Expr = LiteralExpr (Value, 0);
357
358     /* Insert the export */
359     InsertExport (E);
360
361     /* Return the new export */
362     return E;
363 }
364
365
366
367 Export* CreateMemExport (const char* Name, Memory* Mem, unsigned long Offs)
368 /* Create an relative export for a memory area offset */
369 {
370     /* Create a new export */
371     Export* E = NewExport (EXP_ABS | EXP_EXPR | EXP_LABEL, Name, 0);
372
373     /* Assign the value */
374     E->Expr = MemExpr (Mem, Offs, 0);
375
376     /* Insert the export */
377     InsertExport (E);
378
379     /* Return the new export */
380     return E;
381 }
382
383
384
385 Export* CreateSegExport (const char* Name, Section* Sec, unsigned long Offs)
386 /* Create a relative export to a segment (section) */
387 {
388     /* Create a new export */
389     Export* E = NewExport (EXP_ABS | EXP_EXPR | EXP_LABEL, Name, 0);
390
391     /* Assign the value */
392     E->Expr = SegExpr (Sec, Offs, 0);
393
394     /* Insert the export */
395     InsertExport (E);
396
397     /* Return the new export */
398     return E;
399 }
400
401
402
403 static Export* FindExport (const char* Name)
404 /* Check for an identifier in the list. Return 0 if not found, otherwise
405  * return a pointer to the export.                       
406  */
407 {
408     /* Get a pointer to the list with the symbols hash value */
409     Export* L = HashTab [HashStr (Name) % HASHTAB_SIZE];
410     while (L) {
411         /* Search through the list in that slot */
412         if (strcmp (L->Name, Name) == 0) {
413             /* Entry found */
414             return L;
415         }
416         L = L->Next;
417     }
418
419     /* Not found */
420     return 0;
421 }
422
423
424
425 int IsUnresolved (const char* Name)
426 /* Check if this symbol is an unresolved export */
427 {
428     /* Find the export */
429     Export* E = FindExport (Name);
430
431     /* Check if it's unresolved */
432     return E != 0 && E->Expr == 0;
433 }
434
435
436
437 int IsConstExport (const Export* E)
438 /* Return true if the expression associated with this export is const */
439 {
440     if (E->Expr == 0) {
441         /* External symbols cannot be const */
442         return 0;
443     } else {
444         return IsConstExpr (E->Expr);
445     }
446 }
447
448
449
450 long GetExportVal (const Export* E)
451 /* Get the value of this export */
452 {
453     if (E->Expr == 0) {
454         /* OOPS */
455         Internal ("`%s' is an undefined external", E->Name);
456     }
457     return GetExprVal (E->Expr);
458 }
459
460
461
462 static void CheckSymType (const Export* E)
463 /* Check the types for one export */
464 {
465     /* External with matching imports */
466     Import* Imp = E->ImpList;
467     int ZP = IS_EXP_ZP (E->Type);
468     while (Imp) {
469         if (ZP != IS_IMP_ZP (Imp->Type)) {
470             /* Export is ZP, import is abs or the other way round */
471             if (E->Obj) {
472                 /* User defined export */
473                 Warning ("Type mismatch for `%s', export in "
474                          "%s(%lu), import in %s(%lu)",
475                          E->Name, GetSourceFileName (E->Obj, Imp->Pos.Name),
476                          E->Pos.Line, GetSourceFileName (Imp->Obj, Imp->Pos.Name),
477                          Imp->Pos.Line);
478             } else {
479                 /* Export created by the linker */
480                 Warning ("Type mismatch for `%s', imported from %s(%lu)",
481                          E->Name, GetSourceFileName (Imp->Obj, Imp->Pos.Name),
482                          Imp->Pos.Line);
483             }
484         }
485         Imp = Imp->Next;
486     }
487 }
488
489
490
491 static void CheckSymTypes (void)
492 /* Check for symbol tape mismatches */
493 {
494     unsigned I;
495
496     /* Print all open imports */
497     for (I = 0; I < ExpCount; ++I) {
498         const Export* E = ExpPool [I];
499         if (E->Expr != 0 && E->ImpCount > 0) {
500             /* External with matching imports */
501             CheckSymType (E);
502         }
503     }
504 }
505
506
507
508 static void PrintUnresolved (ExpCheckFunc F, void* Data)
509 /* Print a list of unresolved symbols. On unresolved symbols, F is
510  * called (see the comments on ExpCheckFunc in the data section).
511  */
512 {
513     unsigned I;
514
515     /* Print all open imports */
516     for (I = 0; I < ExpCount; ++I) {
517         Export* E = ExpPool [I];
518         if (E->Expr == 0 && E->ImpCount > 0 && F (E->Name, Data) == 0) {
519             /* Unresolved external */
520             Import* Imp = E->ImpList;
521             fprintf (stderr,
522                      "Unresolved external `%s' referenced in:\n",
523                      E->Name);
524             while (Imp) {
525                 const char* Name = GetSourceFileName (Imp->Obj, Imp->Pos.Name);
526                 fprintf (stderr, "  %s(%lu)\n", Name, Imp->Pos.Line);
527                 Imp = Imp->Next;
528             }
529         }
530     }
531 }
532
533
534
535 static int CmpExpName (const void* K1, const void* K2)
536 /* Compare function for qsort */
537 {
538     return strcmp ((*(Export**)K1)->Name, (*(Export**)K2)->Name);
539 }
540
541
542
543 static void CreateExportPool (void)
544 /* Create an array with pointer to all exports */
545 {
546     unsigned I, J;
547
548     /* Allocate memory */
549     if (ExpPool) {
550         xfree (ExpPool);
551     }
552     ExpPool = xmalloc (ExpCount * sizeof (Export*));
553
554     /* Walk through the list and insert the exports */
555     for (I = 0, J = 0; I < sizeof (HashTab) / sizeof (HashTab [0]); ++I) {
556         Export* E = HashTab [I];
557         while (E) {
558             CHECK (J < ExpCount);
559             ExpPool [J++] = E;
560             E = E->Next;
561         }
562     }
563
564     /* Sort them by name */
565     qsort (ExpPool, ExpCount, sizeof (Export*), CmpExpName);
566 }
567
568
569
570 void CheckExports (ExpCheckFunc F, void* Data)
571 /* Check if there are any unresolved symbols. On unresolved symbols, F is
572  * called (see the comments on ExpCheckFunc in the data section).
573  */
574 {
575     /* Create an export pool */
576     CreateExportPool ();
577
578     /* Check for symbol type mismatches */
579     CheckSymTypes ();
580
581     /* Check for unresolved externals (check here for special bin formats) */
582     if (ImpOpen != 0) {
583         /* Print all open imports */
584         PrintUnresolved (F, Data);
585     }
586 }
587
588
589
590 void PrintExportMap (FILE* F)
591 /* Print an export map to the given file */
592 {
593     unsigned I;
594     unsigned Count;
595
596     /* Print all exports */
597     Count = 0;
598     for (I = 0; I < ExpCount; ++I) {
599         const Export* E = ExpPool [I];
600
601         /* Print unreferenced symbols only if explictly requested */
602         if (VerboseMap || E->ImpCount > 0 || IS_EXP_CONDES (E->Type)) {
603             fprintf (F,
604                      "%-25s %06lX %c%c%c%c   ",
605                      E->Name,
606                      GetExportVal (E),
607                      E->ImpCount? 'R' : ' ',
608                      IS_EXP_LABEL (E->Type)? 'L' : 'E',
609                      IS_EXP_ZP (E->Type)? 'Z' : ' ',
610                      IS_EXP_CONDES (E->Type)? 'I' : ' ');
611             if (++Count == 2) {
612                 Count = 0;
613                 fprintf (F, "\n");
614             }
615         }
616     }
617     fprintf (F, "\n");
618 }
619
620
621
622 void PrintImportMap (FILE* F)
623 /* Print an import map to the given file */
624 {
625     unsigned I;
626     const Import* Imp;
627
628     /* Loop over all exports */
629     for (I = 0; I < ExpCount; ++I) {
630
631         /* Get the export */
632         const Export* Exp = ExpPool [I];
633
634         /* Print the symbol only if there are imports, or if a verbose map
635          * file is requested.
636          */
637         if (VerboseMap || Exp->ImpCount > 0) {
638
639             /* Print the export */
640             fprintf (F,
641                      "%s (%s):\n",
642                      Exp->Name,
643                      GetObjFileName (Exp->Obj));
644
645             /* Print all imports for this symbol */
646             Imp = Exp->ImpList;
647             while (Imp) {
648
649                 /* Print the import */
650                 fprintf (F,
651                          "    %-25s %s(%lu)\n",
652                          GetObjFileName (Imp->Obj),
653                          GetSourceFileName (Imp->Obj, Imp->Pos.Name),
654                          Imp->Pos.Line);
655
656                 /* Next import */
657                 Imp = Imp->Next;
658             }
659         }
660     }
661     fprintf (F, "\n");
662 }
663
664
665
666 void PrintExportLabels (FILE* F)
667 /* Print the exports in a VICE label file */
668 {
669     unsigned I;
670
671     /* Print all exports */
672     for (I = 0; I < ExpCount; ++I) {
673         const Export* E = ExpPool [I];
674         fprintf (F, "al %06lX .%s\n", GetExportVal (E), E->Name);
675     }
676 }
677
678
679
680 void MarkExport (Export* E)
681 /* Mark the export */
682 {
683     E->Flags |= EXP_USERMARK;
684 }
685
686
687
688 void UnmarkExport (Export* E)
689 /* Remove the mark from the export */
690 {
691     E->Flags &= ~EXP_USERMARK;
692 }
693
694
695
696 int ExportHasMark (Export* E)
697 /* Return true if the export has a mark */
698 {
699     return (E->Flags & EXP_USERMARK) != 0;
700 }
701
702
703
704 void CircularRefError (const Export* E)
705 /* Print an error about a circular reference using to define the given export */
706 {
707     Error ("Circular reference for symbol `%s', %s(%lu)",
708            E->Name, GetSourceFileName (E->Obj, E->Pos.Name), E->Pos.Line);
709 }
710
711
712