1 /*****************************************************************************/
5 /* Main program for the ld65 linker */
9 /* (C) 1998-2009, Ullrich von Bassewitz */
10 /* Roemerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
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. */
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: */
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 */
32 /*****************************************************************************/
74 /*****************************************************************************/
76 /*****************************************************************************/
80 static unsigned ObjFiles = 0; /* Count of object files linked */
81 static unsigned LibFiles = 0; /* Count of library files linked */
85 /*****************************************************************************/
87 /*****************************************************************************/
91 static void Usage (void)
92 /* Print usage information and exit */
94 printf ("Usage: %s [options] module ...\n"
96 " -(\t\t\tStart a library group\n"
97 " -)\t\t\tEnd a library group\n"
98 " -C name\t\tUse linker config file\n"
99 " -D sym=val\t\tDefine a symbol\n"
100 " -L path\t\tSpecify a library search path\n"
101 " -Ln name\t\tCreate a VICE label file\n"
102 " -S addr\t\tSet the default start address\n"
103 " -V\t\t\tPrint the linker version\n"
104 " -h\t\t\tHelp (this text)\n"
105 " -m name\t\tCreate a map file\n"
106 " -o name\t\tName the default output file\n"
107 " -t sys\t\tSet the target system\n"
108 " -u sym\t\tForce an import of symbol `sym'\n"
109 " -v\t\t\tVerbose mode\n"
110 " -vm\t\t\tVerbose map file\n"
113 " --cfg-path path\tSpecify a config file search path\n"
114 " --config name\t\tUse linker config file\n"
115 " --dbgfile name\tGenerate debug information\n"
116 " --define sym=val\tDefine a symbol\n"
117 " --dump-config name\tDump a builtin configuration\n"
118 " --end-group\t\tEnd a library group\n"
119 " --force-import sym\tForce an import of symbol `sym'\n"
120 " --help\t\tHelp (this text)\n"
121 " --lib file\t\tLink this library\n"
122 " --lib-path path\tSpecify a library search path\n"
123 " --mapfile name\tCreate a map file\n"
124 " --module-id id\tSpecify a module id\n"
125 " --obj file\t\tLink this object file\n"
126 " --obj-path path\tSpecify an object file search path\n"
127 " --start-addr addr\tSet the default start address\n"
128 " --start-group\t\tStart a library group\n"
129 " --target sys\t\tSet the target system\n"
130 " --version\t\tPrint the linker version\n",
136 static unsigned long CvtNumber (const char* Arg, const char* Number)
137 /* Convert a number from a string. Allow '$' and '0x' prefixes for hex
145 if (*Number == '$') {
147 Converted = sscanf (Number, "%lx", &Val);
149 Converted = sscanf (Number, "%li", (long*)&Val);
152 /* Check if we do really have a number */
153 if (Converted != 1) {
154 Error ("Invalid number given in argument: %s\n", Arg);
157 /* Return the result */
163 static void LinkFile (const char* Name, FILETYPE Type)
164 /* Handle one file */
171 /* If we don't know the file type, determine it from the extension */
172 if (Type == FILETYPE_UNKNOWN) {
173 Type = GetFileType (Name);
176 /* For known file types, search the file in the directory list */
180 PathName = SearchFile (Name, SEARCH_LIB);
184 PathName = SearchFile (Name, SEARCH_OBJ);
188 PathName = xstrdup (Name); /* Use the name as is */
192 /* We must have a valid name now */
194 Error ("Input file `%s' not found", Name);
197 /* Try to open the file */
198 F = fopen (PathName, "rb");
200 Error ("Cannot open `%s': %s", PathName, strerror (errno));
203 /* Read the magic word */
206 /* Check the magic for known file types. The handling is somewhat weird
207 * since we may have given a file with a ".lib" extension, which was
208 * searched and found in a directory for library files, but we now find
209 * out (by looking at the magic) that it's indeed an object file. We just
210 * ignore the problem and hope no one will notice...
215 ObjAdd (F, PathName);
220 LibAdd (F, PathName);
226 Error ("File `%s' has unknown type", PathName);
230 /* Free allocated memory. */
236 static void DefineSymbol (const char* Def)
237 /* Define a symbol from the command line */
242 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
245 /* The symbol must start with a character or underline */
246 if (Def [0] != '_' && !IsAlpha (Def [0])) {
251 /* Copy the symbol, checking the remainder */
253 while (IsAlNum (*P) || *P == '_') {
254 SB_AppendChar (&SymName, *P++);
256 SB_Terminate (&SymName);
258 /* Do we have a value given? */
262 /* We have a value */
266 if (sscanf (P, "%lx", &Val) != 1) {
270 if (sscanf (P, "%li", &Val) != 1) {
276 /* Define the new symbol */
277 CreateConstExport (GetStringId (SB_GetConstBuf (&SymName)), Val);
282 static void OptCfgPath (const char* Opt attribute ((unused)), const char* Arg)
283 /* Specify a config file search path */
285 AddSearchPath (Arg, SEARCH_CFG);
290 static void OptConfig (const char* Opt attribute ((unused)), const char* Arg)
291 /* Define the config file */
296 Error ("Cannot use -C/-t twice");
298 /* Search for the file */
299 PathName = SearchFile (Arg, SEARCH_CFG);
301 Error ("Cannot find config file `%s'", Arg);
303 CfgSetName (PathName);
309 static void OptDbgFile (const char* Opt attribute ((unused)), const char* Arg)
310 /* Give the name of the debug file */
317 static void OptDefine (const char* Opt attribute ((unused)), const char* Arg)
318 /* Define a symbol on the command line */
325 static void OptDumpConfig (const char* Opt attribute ((unused)), const char* Arg)
326 /* Dump a builtin linker configuration */
328 /* Map the given target name to its id */
329 target_t T = FindTarget (Arg);
330 if (T == TGT_UNKNOWN) {
331 Error ("Target system `%s' is unknown", Arg);
334 /* Dump the builtin configuration */
335 DumpBuiltinConfig (stdout, T);
340 static void OptEndGroup (const char* Opt attribute ((unused)),
341 const char* Arg attribute ((unused)))
342 /* End a library group */
349 static void OptForceImport (const char* Opt attribute ((unused)), const char* Arg)
350 /* Force an import of a symbol */
352 /* An optional address size may be specified */
353 const char* ColPos = strchr (Arg, ':');
356 /* Use default address size (which for now is always absolute
359 InsertImport (GenImport (Arg, ADDR_SIZE_ABS));
365 /* Get the address size and check it */
366 unsigned char AddrSize = AddrSizeFromStr (ColPos+1);
367 if (AddrSize == ADDR_SIZE_INVALID) {
368 Error ("Invalid address size `%s'", ColPos+1);
371 /* Create a copy of the argument */
374 /* We need just the symbol */
375 A[ColPos - Arg] = '\0';
377 /* Generate the import */
378 InsertImport (GenImport (A, AddrSize));
380 /* Delete the copy of the argument */
387 static void OptHelp (const char* Opt attribute ((unused)),
388 const char* Arg attribute ((unused)))
389 /* Print usage information and exit */
397 static void OptLib (const char* Opt attribute ((unused)), const char* Arg)
400 LinkFile (Arg, FILETYPE_LIB);
405 static void OptLibPath (const char* Opt attribute ((unused)), const char* Arg)
406 /* Specify a library file search path */
408 AddSearchPath (Arg, SEARCH_LIB);
413 static void OptMapFile (const char* Opt attribute ((unused)), const char* Arg)
414 /* Give the name of the map file */
421 static void OptModuleId (const char* Opt, const char* Arg)
422 /* Specify a module id */
424 unsigned long Id = CvtNumber (Opt, Arg);
426 Error ("Range error in module id");
428 ModuleId = (unsigned) Id;
433 static void OptObj (const char* Opt attribute ((unused)), const char* Arg)
434 /* Link an object file */
436 LinkFile (Arg, FILETYPE_OBJ);
441 static void OptObjPath (const char* Opt attribute ((unused)), const char* Arg)
442 /* Specify an object file search path */
444 AddSearchPath (Arg, SEARCH_OBJ);
449 static void OptStartAddr (const char* Opt, const char* Arg)
450 /* Set the default start address */
452 StartAddr = CvtNumber (Opt, Arg);
458 static void OptStartGroup (const char* Opt attribute ((unused)),
459 const char* Arg attribute ((unused)))
460 /* Start a library group */
467 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
468 /* Set the target system */
472 /* Map the target name to a target id */
473 Target = FindTarget (Arg);
474 if (Target == TGT_UNKNOWN) {
475 Error ("Invalid target name: `%s'", Arg);
478 /* Get the target description record */
479 D = &Targets[Target];
481 /* Set the target data */
482 DefaultBinFmt = D->BinFmt;
488 static void OptVersion (const char* Opt attribute ((unused)),
489 const char* Arg attribute ((unused)))
490 /* Print the assembler version */
493 "ld65 V%u.%u.%u - (C) Copyright 1998-2005 Ullrich von Bassewitz\n",
494 VER_MAJOR, VER_MINOR, VER_PATCH);
499 int main (int argc, char* argv [])
500 /* Assembler main program */
502 /* Program long options */
503 static const LongOpt OptTab[] = {
504 { "--cfg-path", 1, OptCfgPath },
505 { "--config", 1, OptConfig },
506 { "--dbgfile", 1, OptDbgFile },
507 { "--define", 1, OptDefine },
508 { "--dump-config", 1, OptDumpConfig },
509 { "--end-group", 0, OptEndGroup },
510 { "--force-import", 1, OptForceImport },
511 { "--help", 0, OptHelp },
512 { "--lib", 1, OptLib },
513 { "--lib-path", 1, OptLibPath },
514 { "--mapfile", 1, OptMapFile },
515 { "--module-id", 1, OptModuleId },
516 { "--obj", 1, OptObj },
517 { "--obj-path", 1, OptObjPath },
518 { "--start-addr", 1, OptStartAddr },
519 { "--start-group", 0, OptStartGroup },
520 { "--target", 1, OptTarget },
521 { "--version", 0, OptVersion },
525 unsigned MemoryAreaOverflows;
527 /* Initialize the cmdline module */
528 InitCmdLine (&argc, &argv, "ld65");
530 /* Initialize the input file search paths */
533 /* Initialize the string pool */
536 /* Check the parameters */
538 while (I < ArgCount) {
540 /* Get the argument */
541 const char* Arg = ArgVec[I];
543 /* Check for an option */
544 if (Arg [0] == '-') {
550 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
554 OptStartGroup (Arg, 0);
558 OptEndGroup (Arg, 0);
567 OptMapFile (Arg, GetArg (&I, 2));
571 OutputName = GetArg (&I, 2);
576 Error ("Cannot use -C/-t twice");
578 OptTarget (Arg, GetArg (&I, 2));
582 OptForceImport (Arg, GetArg (&I, 2));
587 case 'm': VerboseMap = 1; break;
588 case '\0': ++Verbosity; break;
589 default: UnknownOption (Arg);
594 OptConfig (Arg, GetArg (&I, 2));
598 OptDefine (Arg, GetArg (&I, 2));
603 /* ## The first one is obsolete and will go */
604 case 'n': LabelFileName = GetArg (&I, 3); break;
605 default: OptLibPath (Arg, GetArg (&I, 2)); break;
610 OptStartAddr (Arg, GetArg (&I, 2));
625 LinkFile (Arg, FILETYPE_UNKNOWN);
633 /* Check if we had any object files */
635 Error ("No object files to link");
638 /* Check if we have a valid configuration */
640 Error ("Memory configuration missing");
643 /* Check if we have open library groups */
646 /* Read the config file */
649 /* Create the condes tables if requested */
652 /* Assign start addresses for the segments, define linker symbols. The
653 * function will return the number of memory area overflows (zero on
656 MemoryAreaOverflows = CfgAssignSegments ();
658 /* Check module assertions */
661 /* Check for import/export mismatches */
664 /* If we had a memory area overflow before, we cannot generate the output
665 * file. However, we will generate a short map file if requested, since
666 * this will help the user to rearrange segments and fix the overflow.
668 if (MemoryAreaOverflows) {
670 CreateMapFile (SHORT_MAPFILE);
672 Error ("Cannot generate output due to memory area overflow%s",
673 (MemoryAreaOverflows > 1)? "s" : "");
676 /* Create the output file */
679 /* Check for segments not written to the output file */
682 /* If requested, create a map file and a label file for VICE */
684 CreateMapFile (LONG_MAPFILE);
693 /* Dump the data for debugging */
699 /* Return an apropriate exit code */