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