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