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