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