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