]> git.sur5r.net Git - cc65/blob - src/ld65/main.c
No copyright message here.
[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 "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             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 OptEndGroup (const char* Opt attribute ((unused)),
329                          const char* Arg attribute ((unused)))
330 /* End a library group */
331 {
332     LibEndGroup ();
333 }
334
335
336
337 static void OptForceImport (const char* Opt attribute ((unused)), const char* Arg)
338 /* Force an import of a symbol */
339 {
340     /* An optional address size may be specified */
341     const char* ColPos = strchr (Arg, ':');
342     if (ColPos == 0) {
343
344         /* Use default address size (which for now is always absolute
345          * addressing)
346          */
347         InsertImport (GenImport (GetStringId (Arg), ADDR_SIZE_ABS));
348
349     } else {
350
351         char* A;
352
353         /* Get the address size and check it */
354         unsigned char AddrSize = AddrSizeFromStr (ColPos+1);
355         if (AddrSize == ADDR_SIZE_INVALID) {
356             Error ("Invalid address size `%s'", ColPos+1);
357         }
358
359         /* Create a copy of the argument */
360         A = xstrdup (Arg);
361
362         /* We need just the symbol */
363         A[ColPos - Arg] = '\0';
364
365         /* Generate the import */
366         InsertImport (GenImport (GetStringId (A), AddrSize));
367
368         /* Delete the copy of the argument */
369         xfree (A);
370     }
371 }
372
373
374
375 static void OptHelp (const char* Opt attribute ((unused)),
376                      const char* Arg attribute ((unused)))
377 /* Print usage information and exit */
378 {
379     Usage ();
380     exit (EXIT_SUCCESS);
381 }
382
383
384
385 static void OptLib (const char* Opt attribute ((unused)), const char* Arg)
386 /* Link a library */
387 {
388     LinkFile (Arg, FILETYPE_LIB);
389 }
390
391
392
393 static void OptLibPath (const char* Opt attribute ((unused)), const char* Arg)
394 /* Specify a library file search path */
395 {
396     AddSearchPath (LibSearchPath, Arg);
397 }
398
399
400
401 static void OptMapFile (const char* Opt attribute ((unused)), const char* Arg)
402 /* Give the name of the map file */
403 {
404     MapFileName = Arg;
405 }
406
407
408
409 static void OptModuleId (const char* Opt, const char* Arg)
410 /* Specify a module id */
411 {
412     unsigned long Id = CvtNumber (Opt, Arg);
413     if (Id > 0xFFFFUL) {
414         Error ("Range error in module id");
415     }
416     ModuleId = (unsigned) Id;
417 }
418
419
420
421 static void OptObj (const char* Opt attribute ((unused)), const char* Arg)
422 /* Link an object file */
423 {
424     LinkFile (Arg, FILETYPE_OBJ);
425 }
426
427
428
429 static void OptObjPath (const char* Opt attribute ((unused)), const char* Arg)
430 /* Specify an object file search path */
431 {
432     AddSearchPath (ObjSearchPath, Arg);
433 }
434
435
436
437 static void OptOutputName (const char* Opt, const char* Arg)
438 /* Give the name of the output file */
439 {
440     /* If the name of the output file has been used in the config before
441      * (by using %O) we're actually changing it later, which - in most cases -
442      * gives unexpected results, so emit a warning in this case.
443      */
444     if (OutputNameUsed) {
445         Warning ("Option `%s' should precede options `-t' or `-C'", Opt);
446     }
447     OutputName = Arg;
448 }
449
450
451
452 static void OptStartAddr (const char* Opt, const char* Arg)
453 /* Set the default start address */
454 {
455     StartAddr = CvtNumber (Opt, Arg);
456     HaveStartAddr = 1;
457 }
458
459
460
461 static void OptStartGroup (const char* Opt attribute ((unused)),
462                            const char* Arg attribute ((unused)))
463 /* Start a library group */
464 {
465     LibStartGroup ();
466 }
467
468
469
470 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
471 /* Set the target system */
472 {
473     StrBuf FileName = STATIC_STRBUF_INITIALIZER;
474     char*  PathName;
475
476     /* Map the target name to a target id */
477     Target = FindTarget (Arg);
478     if (Target == TGT_UNKNOWN) {
479         Error ("Invalid target name: `%s'", Arg);
480     }
481
482     /* Set the target binary format */
483     DefaultBinFmt = GetTargetProperties (Target)->BinFmt;
484
485     /* Build config file name from target name */
486     SB_CopyStr (&FileName, GetTargetName (Target));
487     SB_AppendStr (&FileName, ".cfg");
488     SB_Terminate (&FileName);
489
490     /* Search for the file */
491     PathName = SearchFile (CfgSearchPath, SB_GetBuf (&FileName));
492     if (PathName == 0) {
493         Error ("Cannot find config file `%s'", SB_GetBuf (&FileName));
494     }
495
496     /* Free file name memory */
497     SB_Done (&FileName);
498
499     /* Read the file */
500     CfgSetName (PathName);
501     CfgRead ();
502 }
503
504
505
506 static void OptVersion (const char* Opt attribute ((unused)),
507                         const char* Arg attribute ((unused)))
508 /* Print the assembler version */
509 {
510     fprintf (stderr, "ld65 V%s\n", GetVersionAsString ());
511 }
512
513
514
515 int main (int argc, char* argv [])
516 /* Assembler main program */
517 {
518     /* Program long options */
519     static const LongOpt OptTab[] = {
520         { "--cfg-path",         1,      OptCfgPath              },
521         { "--config",           1,      OptConfig               },
522         { "--dbgfile",          1,      OptDbgFile              },
523         { "--define",           1,      OptDefine               },
524         { "--end-group",        0,      OptEndGroup             },
525         { "--force-import",     1,      OptForceImport          },
526         { "--help",             0,      OptHelp                 },
527         { "--lib",              1,      OptLib                  },
528         { "--lib-path",         1,      OptLibPath              },
529         { "--mapfile",          1,      OptMapFile              },
530         { "--module-id",        1,      OptModuleId             },
531         { "--obj",              1,      OptObj                  },
532         { "--obj-path",         1,      OptObjPath              },
533         { "--start-addr",       1,      OptStartAddr            },
534         { "--start-group",      0,      OptStartGroup           },
535         { "--target",           1,      OptTarget               },
536         { "--version",          0,      OptVersion              },
537     };
538
539     unsigned I;
540     unsigned MemoryAreaOverflows;
541
542     /* Initialize the cmdline module */
543     InitCmdLine (&argc, &argv, "ld65");
544
545     /* Initialize the input file search paths */
546     InitSearchPaths ();
547
548     /* Initialize the string pool */
549     InitStrPool ();
550
551     /* Initialize the type pool */
552     InitTypePool ();
553
554     /* Check the parameters */
555     I = 1;
556     while (I < ArgCount) {
557
558         /* Get the argument */
559         const char* Arg = ArgVec[I];
560
561         /* Check for an option */
562         if (Arg [0] == '-') {
563
564             /* An option */
565             switch (Arg [1]) {
566
567                 case '-':
568                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
569                     break;
570
571                 case '(':
572                     OptStartGroup (Arg, 0);
573                     break;
574
575                 case ')':
576                     OptEndGroup (Arg, 0);
577                     break;
578
579                 case 'h':
580                 case '?':
581                     OptHelp (Arg, 0);
582                     break;
583
584                 case 'm':
585                     OptMapFile (Arg, GetArg (&I, 2));
586                     break;
587
588                 case 'o':
589                     OptOutputName (Arg, GetArg (&I, 2));
590                     break;
591
592                 case 't':
593                     if (CfgAvail ()) {
594                         Error ("Cannot use -C/-t twice");
595                     }
596                     OptTarget (Arg, GetArg (&I, 2));
597                     break;
598
599                 case 'u':
600                     OptForceImport (Arg, GetArg (&I, 2));
601                     break;
602
603                 case 'v':
604                     switch (Arg [2]) {
605                         case 'm':   VerboseMap = 1;     break;
606                         case '\0':  ++Verbosity;        break;
607                         default:    UnknownOption (Arg);
608                     }
609                     break;
610
611                 case 'C':
612                     OptConfig (Arg, GetArg (&I, 2));
613                     break;
614
615                 case 'D':
616                     OptDefine (Arg, GetArg (&I, 2));
617                     break;
618
619                 case 'L':
620                     switch (Arg [2]) {
621                         /* ## The first one is obsolete and will go */
622                         case 'n': LabelFileName = GetArg (&I, 3);   break;
623                         default:  OptLibPath (Arg, GetArg (&I, 2)); break;
624                     }
625                     break;
626
627                 case 'S':
628                     OptStartAddr (Arg, GetArg (&I, 2));
629                     break;
630
631                 case 'V':
632                     OptVersion (Arg, 0);
633                     break;
634
635                 default:
636                     UnknownOption (Arg);
637                     break;
638             }
639
640         } else {
641
642             /* A filename */
643             LinkFile (Arg, FILETYPE_UNKNOWN);
644
645         }
646
647         /* Next argument */
648         ++I;
649     }
650
651     /* Check if we had any object files */
652     if (ObjFiles == 0) {
653         Error ("No object files to link");
654     }
655
656     /* Check if we have a valid configuration */
657     if (!CfgAvail ()) {
658         Error ("Memory configuration missing");
659     }
660
661     /* Check if we have open library groups */
662     LibCheckGroup ();
663
664     /* Create the condes tables if requested */
665     ConDesCreate ();
666
667     /* Process data from the config file. Assign start addresses for the
668      * segments, define linker symbols. The function will return the number
669      * of memory area overflows (zero on success).
670      */
671     MemoryAreaOverflows = CfgProcess ();
672
673     /* Check module assertions */
674     CheckAssertions ();
675
676     /* Check for import/export mismatches */
677     CheckExports ();
678
679     /* If we had a memory area overflow before, we cannot generate the output
680      * file. However, we will generate a short map file if requested, since
681      * this will help the user to rearrange segments and fix the overflow.
682      */
683     if (MemoryAreaOverflows) {
684         if (MapFileName) {
685             CreateMapFile (SHORT_MAPFILE);
686         }
687         Error ("Cannot generate output due to memory area overflow%s",
688                (MemoryAreaOverflows > 1)? "s" : "");
689     }
690
691     /* Create the output file */
692     CfgWriteTarget ();
693
694     /* Check for segments not written to the output file */
695     CheckSegments ();
696
697     /* If requested, create a map file and a label file for VICE */
698     if (MapFileName) {
699         CreateMapFile (LONG_MAPFILE);
700     }
701     if (LabelFileName) {
702         CreateLabelFile ();
703     }
704     if (DbgFileName) {
705         CreateDbgFile ();
706     }
707
708     /* Dump the data for debugging */
709     if (Verbosity > 1) {
710         SegDump ();
711         ConDesDump ();
712     }
713
714     /* Return an apropriate exit code */
715     return EXIT_SUCCESS;
716 }
717
718
719
720