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