]> git.sur5r.net Git - cc65/blob - src/ld65/main.c
Added a new "--force-import" command line option to the linker.
[cc65] / src / ld65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                     Main program for the ld65 linker                      */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2009, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
12 /* EMail:         uz@cc65.org                                                */
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 #include <errno.h>
40
41 /* common */
42 #include "addrsize.h"
43 #include "chartype.h"
44 #include "cmdline.h"
45 #include "filetype.h"
46 #include "libdefs.h"
47 #include "objdefs.h"
48 #include "print.h"
49 #include "target.h"
50 #include "version.h"
51 #include "xmalloc.h"
52
53 /* ld65 */
54 #include "asserts.h"
55 #include "binfmt.h"
56 #include "condes.h"
57 #include "config.h"
58 #include "dbgfile.h"
59 #include "error.h"
60 #include "exports.h"
61 #include "fileio.h"
62 #include "filepath.h"
63 #include "global.h"
64 #include "library.h"
65 #include "mapfile.h"
66 #include "objfile.h"
67 #include "scanner.h"
68 #include "segments.h"
69 #include "spool.h"
70 #include "tgtcfg.h"
71
72
73
74 /*****************************************************************************/
75 /*                                   Data                                    */
76 /*****************************************************************************/
77
78
79
80 static unsigned         ObjFiles   = 0; /* Count of object files linked */
81 static unsigned         LibFiles   = 0; /* Count of library files linked */
82
83
84
85 /*****************************************************************************/
86 /*                                   Code                                    */
87 /*****************************************************************************/
88
89
90
91 static void Usage (void)
92 /* Print usage information and exit */
93 {
94     printf ("Usage: %s [options] module ...\n"
95             "Short options:\n"
96             "  -(\t\t\tStart a library group\n"
97             "  -)\t\t\tEnd a library group\n"
98             "  -C name\t\tUse linker config file\n"
99             "  -D sym=val\t\tDefine a symbol\n"
100             "  -L path\t\tSpecify a library search path\n"
101             "  -Ln name\t\tCreate a VICE label file\n"
102             "  -S addr\t\tSet the default start address\n"
103             "  -V\t\t\tPrint the linker version\n"
104             "  -h\t\t\tHelp (this text)\n"
105             "  -m name\t\tCreate a map file\n"
106             "  -o name\t\tName the default output file\n"
107             "  -t sys\t\tSet the target system\n"
108             "  -v\t\t\tVerbose mode\n"
109             "  -vm\t\t\tVerbose map file\n"
110             "\n"
111             "Long options:\n"
112             "  --cfg-path path\tSpecify a config file search path\n"
113             "  --config name\t\tUse linker config file\n"
114             "  --dbgfile name\tGenerate debug information\n"
115             "  --define sym=val\tDefine a symbol\n"
116             "  --dump-config name\tDump a builtin configuration\n"
117             "  --end-group\t\tEnd a library group\n"
118             "  --force-import sym\tForce an import of symbol `sym'\n"
119             "  --help\t\tHelp (this text)\n"
120             "  --lib file\t\tLink this library\n"
121             "  --lib-path path\tSpecify a library search path\n"
122             "  --mapfile name\tCreate a map file\n"
123             "  --module-id id\tSpecify a module id\n"
124             "  --obj file\t\tLink this object file\n"
125             "  --obj-path path\tSpecify an object file search path\n"
126             "  --start-addr addr\tSet the default start address\n"
127             "  --start-group\t\tStart a library group\n"
128             "  --target sys\t\tSet the target system\n"
129             "  --version\t\tPrint the linker version\n",
130             ProgName);
131 }
132
133
134
135 static unsigned long CvtNumber (const char* Arg, const char* Number)
136 /* Convert a number from a string. Allow '$' and '0x' prefixes for hex
137  * numbers.
138  */
139 {
140     unsigned long Val;
141     int           Converted;
142
143     /* Convert */
144     if (*Number == '$') {
145         ++Number;
146         Converted = sscanf (Number, "%lx", &Val);
147     } else {
148         Converted = sscanf (Number, "%li", (long*)&Val);
149     }
150
151     /* Check if we do really have a number */
152     if (Converted != 1) {
153         Error ("Invalid number given in argument: %s\n", Arg);
154     }
155
156     /* Return the result */
157     return Val;
158 }
159
160
161
162 static void LinkFile (const char* Name, FILETYPE Type)
163 /* Handle one file */
164 {
165     char*         PathName;
166     FILE*         F;
167     unsigned long Magic;
168
169
170     /* If we don't know the file type, determine it from the extension */
171     if (Type == FILETYPE_UNKNOWN) {
172         Type = GetFileType (Name);
173     }
174
175     /* For known file types, search the file in the directory list */
176     switch (Type) {
177
178         case FILETYPE_LIB:
179             PathName = SearchFile (Name, SEARCH_LIB);
180             break;
181
182         case FILETYPE_OBJ:
183             PathName = SearchFile (Name, SEARCH_OBJ);
184             break;
185
186         default:
187             PathName = xstrdup (Name);   /* Use the name as is */
188             break;
189     }
190
191     /* We must have a valid name now */
192     if (PathName == 0) {
193         Error ("Input file `%s' not found", Name);
194     }
195
196     /* Try to open the file */
197     F = fopen (PathName, "rb");
198     if (F == 0) {
199         Error ("Cannot open `%s': %s", PathName, strerror (errno));
200     }
201
202     /* Read the magic word */
203     Magic = Read32 (F);
204
205     /* Check the magic for known file types. The handling is somewhat weird
206      * since we may have given a file with a ".lib" extension, which was
207      * searched and found in a directory for library files, but we now find
208      * out (by looking at the magic) that it's indeed an object file. We just
209      * ignore the problem and hope no one will notice...
210      */
211     switch (Magic) {
212
213         case OBJ_MAGIC:
214             ObjAdd (F, PathName);
215             ++ObjFiles;
216             break;
217
218         case LIB_MAGIC:
219             LibAdd (F, PathName);
220             ++LibFiles;
221             break;
222
223         default:
224             fclose (F);
225             Error ("File `%s' has unknown type", PathName);
226
227     }
228
229     /* Free allocated memory. */
230     xfree (PathName);
231 }
232
233
234
235 static void DefineSymbol (const char* Def)
236 /* Define a symbol from the command line */
237 {
238     const char* P;
239     unsigned I;
240     long Val;
241     StrBuf SymName = AUTO_STRBUF_INITIALIZER;
242
243
244     /* The symbol must start with a character or underline */
245     if (Def [0] != '_' && !IsAlpha (Def [0])) {
246         InvDef (Def);
247     }
248     P = Def;
249
250     /* Copy the symbol, checking the remainder */
251     I = 0;
252     while (IsAlNum (*P) || *P == '_') {
253         SB_AppendChar (&SymName, *P++);
254     }
255     SB_Terminate (&SymName);
256
257     /* Do we have a value given? */
258     if (*P != '=') {
259         InvDef (Def);
260     } else {
261         /* We have a value */
262         ++P;
263         if (*P == '$') {
264             ++P;
265             if (sscanf (P, "%lx", &Val) != 1) {
266                 InvDef (Def);
267             }
268         } else {
269             if (sscanf (P, "%li", &Val) != 1) {
270                 InvDef (Def);
271             }
272         }
273     }
274
275     /* Define the new symbol */
276     CreateConstExport (GetStringId (SB_GetConstBuf (&SymName)), Val);
277 }
278
279
280
281 static void OptCfgPath (const char* Opt attribute ((unused)), const char* Arg)
282 /* Specify a config file search path */
283 {
284     AddSearchPath (Arg, SEARCH_CFG);
285 }
286
287
288
289 static void OptConfig (const char* Opt attribute ((unused)), const char* Arg)
290 /* Define the config file */
291 {
292     char* PathName;
293
294     if (CfgAvail ()) {
295         Error ("Cannot use -C/-t twice");
296     }
297     /* Search for the file */
298     PathName = SearchFile (Arg, SEARCH_CFG);
299     if (PathName == 0) {
300         Error ("Cannot find config file `%s'", Arg);
301     } else {
302         CfgSetName (PathName);
303     }
304 }
305
306
307
308 static void OptDbgFile (const char* Opt attribute ((unused)), const char* Arg)
309 /* Give the name of the debug file */
310 {
311     DbgFileName = Arg;
312 }
313
314
315
316 static void OptDefine (const char* Opt attribute ((unused)), const char* Arg)
317 /* Define a symbol on the command line */
318 {
319     DefineSymbol (Arg);
320 }
321
322
323
324 static void OptDumpConfig (const char* Opt attribute ((unused)), const char* Arg)
325 /* Dump a builtin linker configuration */
326 {
327     /* Map the given target name to its id */
328     target_t T = FindTarget (Arg);
329     if (T == TGT_UNKNOWN) {
330         Error ("Target system `%s' is unknown", Arg);
331     }
332
333     /* Dump the builtin configuration */
334     DumpBuiltinConfig (stdout, T);
335 }
336
337
338
339 static void OptEndGroup (const char* Opt attribute ((unused)),
340                          const char* Arg attribute ((unused)))
341 /* End a library group */
342 {
343     LibEndGroup ();
344 }
345
346
347
348 static void OptForceImport (const char* Opt attribute ((unused)), const char* Arg)
349 /* Force an import of a symbol */
350 {
351     /* An optional address size may be specified */
352     const char* ColPos = strchr (Arg, ':');
353     if (ColPos == 0) {
354
355         /* Use default address size (which for now is always absolute
356          * addressing) 
357          */
358         InsertImport (GenImport (Arg, ADDR_SIZE_ABS));
359
360     } else {
361
362         char* A;
363
364         /* Get the address size and check it */
365         unsigned char AddrSize = AddrSizeFromStr (ColPos+1);
366         if (AddrSize == ADDR_SIZE_INVALID) {
367             Error ("Invalid address size `%s'", ColPos+1);
368         }
369
370         /* Create a copy of the argument */
371         A = xstrdup (Arg);
372
373         /* We need just the symbol */
374         A[ColPos - Arg] = '\0';
375
376         /* Generate the import */
377         InsertImport (GenImport (A, AddrSize));
378
379         /* Delete the copy of the argument */
380         xfree (A);
381     }
382 }
383
384
385
386 static void OptHelp (const char* Opt attribute ((unused)),
387                      const char* Arg attribute ((unused)))
388 /* Print usage information and exit */
389 {
390     Usage ();
391     exit (EXIT_SUCCESS);
392 }
393
394
395
396 static void OptLib (const char* Opt attribute ((unused)), const char* Arg)
397 /* Link a library */
398 {
399     LinkFile (Arg, FILETYPE_LIB);
400 }
401
402
403
404 static void OptLibPath (const char* Opt attribute ((unused)), const char* Arg)
405 /* Specify a library file search path */
406 {
407     AddSearchPath (Arg, SEARCH_LIB);
408 }
409
410
411
412 static void OptMapFile (const char* Opt attribute ((unused)), const char* Arg)
413 /* Give the name of the map file */
414 {
415     MapFileName = Arg;
416 }
417
418
419
420 static void OptModuleId (const char* Opt, const char* Arg)
421 /* Specify a module id */
422 {
423     unsigned long Id = CvtNumber (Opt, Arg);
424     if (Id > 0xFFFFUL) {
425         Error ("Range error in module id");
426     }
427     ModuleId = (unsigned) Id;
428 }
429
430
431
432 static void OptObj (const char* Opt attribute ((unused)), const char* Arg)
433 /* Link an object file */
434 {
435     LinkFile (Arg, FILETYPE_OBJ);
436 }
437
438
439
440 static void OptObjPath (const char* Opt attribute ((unused)), const char* Arg)
441 /* Specify an object file search path */
442 {
443     AddSearchPath (Arg, SEARCH_OBJ);
444 }
445
446
447
448 static void OptStartAddr (const char* Opt, const char* Arg)
449 /* Set the default start address */
450 {
451     StartAddr = CvtNumber (Opt, Arg);
452     HaveStartAddr = 1;
453 }
454
455
456
457 static void OptStartGroup (const char* Opt attribute ((unused)),
458                            const char* Arg attribute ((unused)))
459 /* Start a library group */
460 {
461     LibStartGroup ();
462 }
463
464
465
466 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
467 /* Set the target system */
468 {
469     const TargetDesc* D;
470
471     /* Map the target name to a target id */
472     Target = FindTarget (Arg);
473     if (Target == TGT_UNKNOWN) {
474         Error ("Invalid target name: `%s'", Arg);
475     }
476
477     /* Get the target description record */
478     D = &Targets[Target];
479
480     /* Set the target data */
481     DefaultBinFmt = D->BinFmt;
482     CfgSetBuf (D->Cfg);
483 }
484
485
486
487 static void OptVersion (const char* Opt attribute ((unused)),
488                         const char* Arg attribute ((unused)))
489 /* Print the assembler version */
490 {
491     fprintf (stderr,
492              "ld65 V%u.%u.%u - (C) Copyright 1998-2005 Ullrich von Bassewitz\n",
493              VER_MAJOR, VER_MINOR, VER_PATCH);
494 }
495
496
497
498 int main (int argc, char* argv [])
499 /* Assembler main program */
500 {
501     /* Program long options */
502     static const LongOpt OptTab[] = {
503         { "--cfg-path",         1,      OptCfgPath              },
504         { "--config",           1,      OptConfig               },
505         { "--dbgfile",          1,      OptDbgFile              },
506         { "--define",           1,      OptDefine               },
507         { "--dump-config",      1,      OptDumpConfig           },
508         { "--end-group",        0,      OptEndGroup             },
509         { "--force-import",     1,      OptForceImport          },
510         { "--help",             0,      OptHelp                 },
511         { "--lib",              1,      OptLib                  },
512         { "--lib-path",         1,      OptLibPath              },
513         { "--mapfile",          1,      OptMapFile              },
514         { "--module-id",        1,      OptModuleId             },
515         { "--obj",              1,      OptObj                  },
516         { "--obj-path",         1,      OptObjPath              },
517         { "--start-addr",       1,      OptStartAddr            },
518         { "--start-group",      0,      OptStartGroup           },
519         { "--target",           1,      OptTarget               },
520         { "--version",          0,      OptVersion              },
521     };
522
523     unsigned I;
524     unsigned MemoryAreaOverflows;
525
526     /* Initialize the cmdline module */
527     InitCmdLine (&argc, &argv, "ld65");
528
529     /* Initialize the input file search paths */
530     InitSearchPaths ();
531
532     /* Initialize the string pool */
533     InitStrPool ();
534
535     /* Check the parameters */
536     I = 1;
537     while (I < ArgCount) {
538
539         /* Get the argument */
540         const char* Arg = ArgVec[I];
541
542         /* Check for an option */
543         if (Arg [0] == '-') {
544
545             /* An option */
546             switch (Arg [1]) {
547
548                 case '-':
549                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
550                     break;
551
552                 case '(':
553                     OptStartGroup (Arg, 0);
554                     break;
555
556                 case ')':
557                     OptEndGroup (Arg, 0);
558                     break;
559
560                 case 'h':
561                 case '?':
562                     OptHelp (Arg, 0);
563                     break;
564
565                 case 'm':
566                     OptMapFile (Arg, GetArg (&I, 2));
567                     break;
568
569                 case 'o':
570                     OutputName = GetArg (&I, 2);
571                     break;
572
573                 case 't':
574                     if (CfgAvail ()) {
575                         Error ("Cannot use -C/-t twice");
576                     }
577                     OptTarget (Arg, GetArg (&I, 2));
578                     break;
579
580                 case 'v':
581                     switch (Arg [2]) {
582                         case 'm':   VerboseMap = 1;     break;
583                         case '\0':  ++Verbosity;        break;
584                         default:    UnknownOption (Arg);
585                     }
586                     break;
587
588                 case 'C':
589                     OptConfig (Arg, GetArg (&I, 2));
590                     break;
591
592                 case 'D':
593                     OptDefine (Arg, GetArg (&I, 2));
594                     break;
595
596                 case 'L':
597                     switch (Arg [2]) {
598                         /* ## The first one is obsolete and will go */
599                         case 'n': LabelFileName = GetArg (&I, 3);   break;
600                         default:  OptLibPath (Arg, GetArg (&I, 2)); break;
601                     }
602                     break;
603
604                 case 'S':
605                     OptStartAddr (Arg, GetArg (&I, 2));
606                     break;
607
608                 case 'V':
609                     OptVersion (Arg, 0);
610                     break;
611
612                 default:
613                     UnknownOption (Arg);
614                     break;
615             }
616
617         } else {
618
619             /* A filename */
620             LinkFile (Arg, FILETYPE_UNKNOWN);
621
622         }
623
624         /* Next argument */
625         ++I;
626     }
627
628     /* Check if we had any object files */
629     if (ObjFiles == 0) {
630         Error ("No object files to link");
631     }
632
633     /* Check if we have a valid configuration */
634     if (!CfgAvail ()) {
635         Error ("Memory configuration missing");
636     }
637
638     /* Check if we have open library groups */
639     LibCheckGroup ();
640
641     /* Read the config file */
642     CfgRead ();
643
644     /* Create the condes tables if requested */
645     ConDesCreate ();
646
647     /* Assign start addresses for the segments, define linker symbols. The
648      * function will return the number of memory area overflows (zero on
649      * success).
650      */
651     MemoryAreaOverflows = CfgAssignSegments ();
652
653     /* Check module assertions */
654     CheckAssertions ();
655
656     /* Check for import/export mismatches */
657     CheckExports ();
658
659     /* If we had a memory area overflow before, we cannot generate the output
660      * file. However, we will generate a short map file if requested, since
661      * this will help the user to rearrange segments and fix the overflow.
662      */
663     if (MemoryAreaOverflows) {
664         if (MapFileName) {
665             CreateMapFile (SHORT_MAPFILE);
666         }
667         Error ("Cannot generate output due to memory area overflow%s",
668                (MemoryAreaOverflows > 1)? "s" : "");
669     }
670
671     /* Create the output file */
672     CfgWriteTarget ();
673
674     /* Check for segments not written to the output file */
675     CheckSegments ();
676
677     /* If requested, create a map file and a label file for VICE */
678     if (MapFileName) {
679         CreateMapFile (LONG_MAPFILE);
680     }
681     if (LabelFileName) {
682         CreateLabelFile ();
683     }
684     if (DbgFileName) {
685         CreateDbgFile ();
686     }
687
688     /* Dump the data for debugging */
689     if (Verbosity > 1) {
690         SegDump ();
691         ConDesDump ();
692     }
693
694     /* Return an apropriate exit code */
695     return EXIT_SUCCESS;
696 }
697
698
699
700