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