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