1 /*****************************************************************************/
5 /* Main program for the ld65 linker */
9 /* (C) 1998-2013, 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 " --end-group\t\tEnd a library group\n"
118 " --force-import sym\tForce an import of symbol `sym'\n"
119 " --help\t\tHelp (this text)\n"
120 " --lib file\t\tLink this library\n"
121 " --lib-path path\tSpecify a library search path\n"
122 " --mapfile name\tCreate a map file\n"
123 " --module-id id\tSpecify a module id\n"
124 " --obj file\t\tLink this object file\n"
125 " --obj-path path\tSpecify an object file search path\n"
126 " --start-addr addr\tSet the default start address\n"
127 " --start-group\t\tStart a library group\n"
128 " --target sys\t\tSet the target system\n"
129 " --version\t\tPrint the linker version\n",
135 static unsigned long CvtNumber (const char* Arg, const char* Number)
136 /* Convert a number from a string. Allow '$' and '0x' prefixes for hex
144 if (*Number == '$') {
146 Converted = sscanf (Number, "%lx", &Val);
148 Converted = sscanf (Number, "%li", (long*)&Val);
151 /* Check if we do really have a number */
152 if (Converted != 1) {
153 Error ("Invalid number given in argument: %s\n", Arg);
156 /* Return the result */
162 static void LinkFile (const char* Name, FILETYPE Type)
163 /* Handle one file */
170 /* If we don't know the file type, determine it from the extension */
171 if (Type == FILETYPE_UNKNOWN) {
172 Type = GetFileType (Name);
175 /* For known file types, search the file in the directory list */
179 PathName = SearchFile (LibSearchPath, Name);
181 PathName = SearchFile (LibDefaultPath, Name);
186 PathName = SearchFile (ObjSearchPath, Name);
188 PathName = SearchFile (ObjDefaultPath, Name);
193 PathName = xstrdup (Name); /* Use the name as is */
197 /* We must have a valid name now */
199 Error ("Input file `%s' not found", Name);
202 /* Try to open the file */
203 F = fopen (PathName, "rb");
205 Error ("Cannot open `%s': %s", PathName, strerror (errno));
208 /* Read the magic word */
211 /* Check the magic for known file types. The handling is somewhat weird
212 * since we may have given a file with a ".lib" extension, which was
213 * searched and found in a directory for library files, but we now find
214 * out (by looking at the magic) that it's indeed an object file. We just
215 * ignore the problem and hope no one will notice...
220 ObjAdd (F, PathName);
225 LibAdd (F, PathName);
231 Error ("File `%s' has unknown type", PathName);
235 /* Free allocated memory. */
241 static void DefineSymbol (const char* Def)
242 /* Define a symbol from the command line */
246 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
249 /* The symbol must start with a character or underline */
250 if (Def [0] != '_' && !IsAlpha (Def [0])) {
255 /* Copy the symbol, checking the remainder */
256 while (IsAlNum (*P) || *P == '_') {
257 SB_AppendChar (&SymName, *P++);
259 SB_Terminate (&SymName);
261 /* Do we have a value given? */
265 /* We have a value */
269 if (sscanf (P, "%lx", &Val) != 1) {
273 if (sscanf (P, "%li", &Val) != 1) {
279 /* Define the new symbol */
280 CreateConstExport (GetStringId (SB_GetConstBuf (&SymName)), Val);
285 static void OptCfgPath (const char* Opt attribute ((unused)), const char* Arg)
286 /* Specify a config file search path */
288 AddSearchPath (CfgSearchPath, Arg);
293 static void OptConfig (const char* Opt attribute ((unused)), const char* Arg)
294 /* Define the config file */
299 Error ("Cannot use -C/-t twice");
301 /* Search for the file */
302 PathName = SearchFile (CfgSearchPath, Arg);
304 PathName = SearchFile (CfgDefaultPath, Arg);
307 Error ("Cannot find config file `%s'", Arg);
310 /* Read the config */
311 CfgSetName (PathName);
317 static void OptDbgFile (const char* Opt attribute ((unused)), const char* Arg)
318 /* Give the name of the debug file */
325 static void OptDefine (const char* Opt attribute ((unused)), const char* Arg)
326 /* Define a symbol on the command line */
333 static void OptEndGroup (const char* Opt attribute ((unused)),
334 const char* Arg attribute ((unused)))
335 /* End a library group */
342 static void OptForceImport (const char* Opt attribute ((unused)), const char* Arg)
343 /* Force an import of a symbol */
345 /* An optional address size may be specified */
346 const char* ColPos = strchr (Arg, ':');
349 /* Use default address size (which for now is always absolute
352 InsertImport (GenImport (GetStringId (Arg), ADDR_SIZE_ABS));
358 /* Get the address size and check it */
359 unsigned char AddrSize = AddrSizeFromStr (ColPos+1);
360 if (AddrSize == ADDR_SIZE_INVALID) {
361 Error ("Invalid address size `%s'", ColPos+1);
364 /* Create a copy of the argument */
367 /* We need just the symbol */
368 A[ColPos - Arg] = '\0';
370 /* Generate the import */
371 InsertImport (GenImport (GetStringId (A), AddrSize));
373 /* Delete the copy of the argument */
380 static void OptHelp (const char* Opt attribute ((unused)),
381 const char* Arg attribute ((unused)))
382 /* Print usage information and exit */
390 static void OptLib (const char* Opt attribute ((unused)), const char* Arg)
393 LinkFile (Arg, FILETYPE_LIB);
398 static void OptLibPath (const char* Opt attribute ((unused)), const char* Arg)
399 /* Specify a library file search path */
401 AddSearchPath (LibSearchPath, Arg);
406 static void OptMapFile (const char* Opt attribute ((unused)), const char* Arg)
407 /* Give the name of the map file */
414 static void OptModuleId (const char* Opt, const char* Arg)
415 /* Specify a module id */
417 unsigned long Id = CvtNumber (Opt, Arg);
419 Error ("Range error in module id");
421 ModuleId = (unsigned) Id;
426 static void OptObj (const char* Opt attribute ((unused)), const char* Arg)
427 /* Link an object file */
429 LinkFile (Arg, FILETYPE_OBJ);
434 static void OptObjPath (const char* Opt attribute ((unused)), const char* Arg)
435 /* Specify an object file search path */
437 AddSearchPath (ObjSearchPath, Arg);
442 static void OptOutputName (const char* Opt, const char* Arg)
443 /* Give the name of the output file */
445 /* If the name of the output file has been used in the config before
446 * (by using %O) we're actually changing it later, which - in most cases -
447 * gives unexpected results, so emit a warning in this case.
449 if (OutputNameUsed) {
450 Warning ("Option `%s' should precede options `-t' or `-C'", Opt);
457 static void OptStartAddr (const char* Opt, const char* Arg)
458 /* Set the default start address */
460 StartAddr = CvtNumber (Opt, Arg);
466 static void OptStartGroup (const char* Opt attribute ((unused)),
467 const char* Arg attribute ((unused)))
468 /* Start a library group */
475 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
476 /* Set the target system */
478 StrBuf FileName = STATIC_STRBUF_INITIALIZER;
481 /* Map the target name to a target id */
482 Target = FindTarget (Arg);
483 if (Target == TGT_UNKNOWN) {
484 Error ("Invalid target name: `%s'", Arg);
487 /* Set the target binary format */
488 DefaultBinFmt = GetTargetProperties (Target)->BinFmt;
490 /* Build config file name from target name */
491 SB_CopyStr (&FileName, GetTargetName (Target));
492 SB_AppendStr (&FileName, ".cfg");
493 SB_Terminate (&FileName);
495 /* Search for the file */
496 PathName = SearchFile (CfgSearchPath, SB_GetBuf (&FileName));
498 PathName = SearchFile (CfgDefaultPath, SB_GetBuf (&FileName));
501 Error ("Cannot find config file `%s'", SB_GetBuf (&FileName));
504 /* Free file name memory */
508 CfgSetName (PathName);
514 static void OptVersion (const char* Opt attribute ((unused)),
515 const char* Arg attribute ((unused)))
516 /* Print the assembler version */
518 fprintf (stderr, "ld65 V%s\n", GetVersionAsString ());
523 int main (int argc, char* argv [])
524 /* Assembler main program */
526 /* Program long options */
527 static const LongOpt OptTab[] = {
528 { "--cfg-path", 1, OptCfgPath },
529 { "--config", 1, OptConfig },
530 { "--dbgfile", 1, OptDbgFile },
531 { "--define", 1, OptDefine },
532 { "--end-group", 0, OptEndGroup },
533 { "--force-import", 1, OptForceImport },
534 { "--help", 0, OptHelp },
535 { "--lib", 1, OptLib },
536 { "--lib-path", 1, OptLibPath },
537 { "--mapfile", 1, OptMapFile },
538 { "--module-id", 1, OptModuleId },
539 { "--obj", 1, OptObj },
540 { "--obj-path", 1, OptObjPath },
541 { "--start-addr", 1, OptStartAddr },
542 { "--start-group", 0, OptStartGroup },
543 { "--target", 1, OptTarget },
544 { "--version", 0, OptVersion },
548 unsigned MemoryAreaOverflows;
550 /* Initialize the cmdline module */
551 InitCmdLine (&argc, &argv, "ld65");
553 /* Initialize the input file search paths */
556 /* Initialize the string pool */
559 /* Initialize the type pool */
562 /* Check the parameters */
564 while (I < ArgCount) {
566 /* Get the argument */
567 const char* Arg = ArgVec[I];
569 /* Check for an option */
570 if (Arg [0] == '-') {
576 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
580 OptStartGroup (Arg, 0);
584 OptEndGroup (Arg, 0);
593 OptMapFile (Arg, GetArg (&I, 2));
597 OptOutputName (Arg, GetArg (&I, 2));
602 Error ("Cannot use -C/-t twice");
604 OptTarget (Arg, GetArg (&I, 2));
608 OptForceImport (Arg, GetArg (&I, 2));
613 case 'm': VerboseMap = 1; break;
614 case '\0': ++Verbosity; break;
615 default: UnknownOption (Arg);
620 OptConfig (Arg, GetArg (&I, 2));
624 OptDefine (Arg, GetArg (&I, 2));
629 /* ## The first one is obsolete and will go */
630 case 'n': LabelFileName = GetArg (&I, 3); break;
631 default: OptLibPath (Arg, GetArg (&I, 2)); break;
636 OptStartAddr (Arg, GetArg (&I, 2));
651 LinkFile (Arg, FILETYPE_UNKNOWN);
659 /* Check if we had any object files */
661 Error ("No object files to link");
664 /* Check if we have a valid configuration */
666 Error ("Memory configuration missing");
669 /* Check if we have open library groups */
672 /* Create the condes tables if requested */
675 /* Process data from the config file. Assign start addresses for the
676 * segments, define linker symbols. The function will return the number
677 * of memory area overflows (zero on success).
679 MemoryAreaOverflows = CfgProcess ();
681 /* Check module assertions */
684 /* Check for import/export mismatches */
687 /* If we had a memory area overflow before, we cannot generate the output
688 * file. However, we will generate a short map file if requested, since
689 * this will help the user to rearrange segments and fix the overflow.
691 if (MemoryAreaOverflows) {
693 CreateMapFile (SHORT_MAPFILE);
695 Error ("Cannot generate output due to memory area overflow%s",
696 (MemoryAreaOverflows > 1)? "s" : "");
699 /* Create the output file */
702 /* Check for segments not written to the output file */
705 /* If requested, create a map file and a label file for VICE */
707 CreateMapFile (LONG_MAPFILE);
716 /* Dump the data for debugging */
722 /* Return an apropriate exit code */