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