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