]> git.sur5r.net Git - cc65/blob - src/ld65/main.c
Added a new extended (and machine specific) zeropage segment named EXTZP.
[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 "libdefs.h"
44 #include "objdefs.h"
45 #include "print.h"
46 #include "target.h"
47 #include "version.h"
48 #include "xmalloc.h"
49
50 /* ld65 */
51 #include "binfmt.h"
52 #include "condes.h"
53 #include "config.h"
54 #include "error.h"
55 #include "exports.h"
56 #include "fileio.h"
57 #include "global.h"
58 #include "library.h"
59 #include "mapfile.h"
60 #include "objfile.h"
61 #include "scanner.h"
62 #include "segments.h"
63 #include "tgtcfg.h"
64
65
66
67 /*****************************************************************************/
68 /*                                   Data                                    */
69 /*****************************************************************************/
70
71
72
73 static unsigned         ObjFiles   = 0; /* Count of object files linked */
74 static unsigned         LibFiles   = 0; /* Count of library files linked */
75 static const char*      LibPath    = 0; /* Search path for modules */
76 static unsigned         LibPathLen = 0; /* Length of LibPath */
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              "  -Ln name\t\tCreate a VICE label file\n"
94              "  -Lp\t\t\tMark write protected segments as such (VICE)\n"
95              "  -S addr\t\tSet the default start address\n"
96              "  -V\t\t\tPrint the linker version\n"
97              "  -h\t\t\tHelp (this text)\n"
98              "  -m name\t\tCreate a map file\n"
99              "  -o name\t\tName the default output file\n"
100              "  -t sys\t\tSet the target system\n"
101              "  -v\t\t\tVerbose mode\n"
102              "  -vm\t\t\tVerbose map file\n"
103              "\n"
104              "Long options:\n"
105              "  --config name\t\tUse linker config file\n"
106              "  --dump-config name\tDump a builtin configuration\n"
107              "  --help\t\tHelp (this text)\n"
108              "  --mapfile name\tCreate a map file\n"
109              "  --module-id id\tSpecify a module id\n"
110              "  --start-addr addr\tSet the default start address\n"
111              "  --target sys\t\tSet the target system\n"
112              "  --version\t\tPrint the linker version\n",
113              ProgName);
114 }
115
116
117
118 static unsigned long CvtNumber (const char* Arg, const char* Number)
119 /* Convert a number from a string. Allow '$' and '0x' prefixes for hex
120  * numbers.
121  */
122 {
123     unsigned long Val;
124     int           Converted;
125
126     /* Convert */
127     if (*Number == '$') {
128         ++Number;
129         Converted = sscanf (Number, "%lx", &Val);
130     } else {
131         Converted = sscanf (Number, "%li", (long*)&Val);
132     }
133
134     /* Check if we do really have a number */
135     if (Converted != 1) {
136         Error ("Invalid number given in argument: %s\n", Arg);
137     }
138
139     /* Return the result */
140     return Val;
141 }
142
143
144
145 static int HasPath (const char* Name)
146 /* Check if the given Name has a path component */
147 {
148     return strchr (Name, '/') != 0 || strchr (Name, '\\') != 0;
149 }
150
151
152
153 static void LinkFile (const char* Name)
154 /* Handle one file */
155 {
156     unsigned long Magic;
157     unsigned Len;
158     char* NewName = 0;
159
160     /* Try to open the file */
161     FILE* F = fopen (Name, "rb");
162     if (F == 0) {
163         /* We couldn't open the file. If the name doesn't have a path, and we
164          * have a search path given, try the name with the search path
165          * prepended.
166          */
167         if (LibPathLen > 0 && !HasPath (Name)) {
168             /* Allocate memory. Account for the trailing zero, and for a
169              * path separator character eventually needed.
170              */
171             Len = LibPathLen;
172             NewName = xmalloc (strlen (Name) + Len + 2);
173             /* Build the new name */
174             memcpy (NewName, LibPath, Len);
175             if (NewName [Len-1] != '/' && NewName [Len-1] != '\\') {
176                 /* We need an additional path separator */
177                 NewName [Len++] = '/';
178             }
179             strcpy (NewName + Len, Name);
180
181             /* Now try to open the new file */
182             F = fopen (NewName, "rb");
183         }
184
185         if (F == 0) {
186             Error ("Cannot open `%s': %s", Name, strerror (errno));
187         }
188     }
189
190     /* Read the magic word */
191     Magic = Read32 (F);
192
193     /* Do we know this type of file? */
194     switch (Magic) {
195
196         case OBJ_MAGIC:
197             ObjAdd (F, Name);
198             ++ObjFiles;
199             break;
200
201         case LIB_MAGIC:
202             LibAdd (F, Name);
203             ++LibFiles;
204             break;
205
206         default:
207             fclose (F);
208             Error ("File `%s' has unknown type", Name);
209
210     }
211
212     /* If we have allocated memory, free it here. Note: Memory will not always
213      * be freed if we run into an error, but that's no problem. Adding more
214      * code to work around it will use more memory than the chunk that's lost.
215      */
216     xfree (NewName);
217 }
218
219
220
221 static void OptConfig (const char* Opt attribute ((unused)), const char* Arg)
222 /* Define the config file */
223 {
224     if (CfgAvail ()) {
225         Error ("Cannot use -C/-t twice");
226     }
227     CfgSetName (Arg);
228 }
229
230
231
232 static void OptDbgFile (const char* Opt attribute ((unused)), const char* Arg)
233 /* Give the name of the debug file */
234 {
235     DbgFileName = Arg;
236 }
237
238
239
240 static void OptDumpConfig (const char* Opt attribute ((unused)), const char* Arg)
241 /* Dump a builtin linker configuration */
242 {
243     /* Map the given target name to its id */
244     target_t T = FindTarget (Arg);
245     if (T == TGT_UNKNOWN) {
246         Error ("Target system `%s' is unknown", Arg);
247     }
248
249     /* Dump the builtin configuration */
250     DumpBuiltinConfig (stdout, T);
251 }
252
253
254
255 static void OptHelp (const char* Opt attribute ((unused)),
256                      const char* Arg attribute ((unused)))
257 /* Print usage information and exit */
258 {
259     Usage ();
260     exit (EXIT_SUCCESS);
261 }
262
263
264
265 static void OptMapFile (const char* Opt attribute ((unused)), const char* Arg)
266 /* Give the name of the map file */
267 {
268     MapFileName = Arg;
269 }
270
271
272
273 static void OptModuleId (const char* Opt, const char* Arg)
274 /* Specify a module id */
275 {
276     unsigned long Id = CvtNumber (Opt, Arg);
277     if (Id > 0xFFFFUL) {
278         Error ("Range error in module id");
279     }
280     ModuleId = (unsigned) Id;
281 }
282
283
284
285 static void OptStartAddr (const char* Opt, const char* Arg)
286 /* Set the default start address */
287 {
288     StartAddr = CvtNumber (Opt, Arg);
289     HaveStartAddr = 1;
290 }
291
292
293
294 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
295 /* Set the target system */
296 {
297     const TargetDesc* D;
298
299     /* Map the target name to a target id */
300     Target = FindTarget (Arg);
301     if (Target == TGT_UNKNOWN) {
302         Error ("Invalid target name: `%s'", Arg);
303     }
304
305     /* Get the target description record */
306     D = &Targets[Target];
307
308     /* Set the target data */
309     DefaultBinFmt = D->BinFmt;
310     CfgSetBuf (D->Cfg);
311 }
312
313
314
315 static void OptVersion (const char* Opt attribute ((unused)),
316                         const char* Arg attribute ((unused)))
317 /* Print the assembler version */
318 {
319     fprintf (stderr,
320              "ld65 V%u.%u.%u - (C) Copyright 1998-2002 Ullrich von Bassewitz\n",
321              VER_MAJOR, VER_MINOR, VER_PATCH);
322 }
323
324
325
326 int main (int argc, char* argv [])
327 /* Assembler main program */
328 {
329     /* Program long options */
330     static const LongOpt OptTab[] = {
331         { "--config",           1,      OptConfig               },
332         { "--dbgfile",          1,      OptDbgFile              },
333         { "--dump-config",      1,      OptDumpConfig           },
334         { "--help",             0,      OptHelp                 },
335         { "--mapfile",          1,      OptMapFile              },
336         { "--module-id",        1,      OptModuleId             },
337         { "--start-addr",       1,      OptStartAddr            },
338         { "--target",           1,      OptTarget               },
339         { "--version",          0,      OptVersion              },
340     };
341
342     unsigned I;
343
344     /* Initialize the cmdline module */
345     InitCmdLine (&argc, &argv, "ld65");
346
347     /* Evaluate the CC65_LIB environment variable */
348     LibPath = getenv ("CC65_LIB");
349     if (LibPath == 0) {
350         /* Use some default path */
351 #ifdef CC65_LIB
352         LibPath = CC65_LIB;
353 #else
354         LibPath = "/usr/lib/cc65/lib/";
355 #endif
356     }
357     LibPathLen = strlen (LibPath);
358
359     /* Check the parameters */
360     I = 1;
361     while (I < ArgCount) {
362
363         /* Get the argument */
364         const char* Arg = ArgVec[I];
365
366         /* Check for an option */
367         if (Arg [0] == '-') {
368
369             /* An option */
370             switch (Arg [1]) {
371
372                 case '-':
373                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
374                     break;
375
376                 case 'h':
377                 case '?':
378                     OptHelp (Arg, 0);
379                     break;
380
381                 case 'm':
382                     OptMapFile (Arg, GetArg (&I, 2));
383                     break;
384
385                 case 'o':
386                     OutputName = GetArg (&I, 2);
387                     break;
388
389                 case 't':
390                     if (CfgAvail ()) {
391                         Error ("Cannot use -C/-t twice");
392                     }
393                     OptTarget (Arg, GetArg (&I, 2));
394                     break;
395
396                 case 'v':
397                     switch (Arg [2]) {
398                         case 'm':   VerboseMap = 1;     break;
399                         case '\0':  ++Verbosity;        break;
400                         default:    UnknownOption (Arg);
401                     }
402                     break;
403
404                 case 'C':
405                     OptConfig (Arg, GetArg (&I, 2));
406                     break;
407
408                 case 'L':
409                     switch (Arg [2]) {
410                         case 'n': LabelFileName = GetArg (&I, 3); break;
411                         case 'p': WProtSegs = 1;                  break;
412                         default:  UnknownOption (Arg);            break;
413                     }
414                     break;
415
416                 case 'S':
417                     OptStartAddr (Arg, GetArg (&I, 2));
418                     break;
419
420                 case 'V':
421                     OptVersion (Arg, 0);
422                     break;
423
424                 default:
425                     UnknownOption (Arg);
426                     break;
427             }
428
429         } else {
430
431             /* A filename */
432             LinkFile (Arg);
433
434         }
435
436         /* Next argument */
437         ++I;
438     }
439
440     /* Check if we had any object files */
441     if (ObjFiles == 0) {
442         Error ("No object files to link");
443     }
444
445     /* Check if we have a valid configuration */
446     if (!CfgAvail ()) {
447         Error ("Memory configuration missing");
448     }
449
450     /* Read the config file */
451     CfgRead ();
452
453     /* Create the condes tables if requested */
454     ConDesCreate ();
455
456     /* Assign start addresses for the segments, define linker symbols */
457     CfgAssignSegments ();
458
459     /* Create the output file */
460     CfgWriteTarget ();
461
462     /* Check for segments not written to the output file */
463     CheckSegments ();
464
465     /* If requested, create a map file and a label file for VICE */
466     if (MapFileName) {
467         CreateMapFile ();
468     }
469     if (LabelFileName) {
470         CreateLabelFile ();
471     }
472     if (DbgFileName) {
473         CreateDbgFile ();
474     }
475
476     /* Dump the data for debugging */
477     if (Verbosity > 1) {
478         SegDump ();
479         ConDesDump ();
480     }
481
482     /* Return an apropriate exit code */
483     return EXIT_SUCCESS;
484 }
485
486
487
488