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