1 /*****************************************************************************/
5 /* Main program for the ld65 linker */
9 /* (C) 1998-2010, 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 /*****************************************************************************/
75 /*****************************************************************************/
77 /*****************************************************************************/
81 static unsigned ObjFiles = 0; /* Count of object files linked */
82 static unsigned LibFiles = 0; /* Count of library files linked */
86 /*****************************************************************************/
88 /*****************************************************************************/
92 static void Usage (void)
93 /* Print usage information and exit */
95 printf ("Usage: %s [options] module ...\n"
97 " -(\t\t\tStart a library group\n"
98 " -)\t\t\tEnd a library group\n"
99 " -C name\t\tUse linker config file\n"
100 " -D sym=val\t\tDefine a symbol\n"
101 " -L path\t\tSpecify a library search path\n"
102 " -Ln name\t\tCreate a VICE label file\n"
103 " -S addr\t\tSet the default start address\n"
104 " -V\t\t\tPrint the linker version\n"
105 " -h\t\t\tHelp (this text)\n"
106 " -m name\t\tCreate a map file\n"
107 " -o name\t\tName the default output file\n"
108 " -t sys\t\tSet the target system\n"
109 " -u sym\t\tForce an import of symbol `sym'\n"
110 " -v\t\t\tVerbose mode\n"
111 " -vm\t\t\tVerbose map file\n"
114 " --cfg-path path\tSpecify a config file search path\n"
115 " --config name\t\tUse linker config file\n"
116 " --dbgfile name\tGenerate debug information\n"
117 " --define sym=val\tDefine a symbol\n"
118 " --dump-config name\tDump a builtin configuration\n"
119 " --end-group\t\tEnd a library group\n"
120 " --force-import sym\tForce an import of symbol `sym'\n"
121 " --help\t\tHelp (this text)\n"
122 " --lib file\t\tLink this library\n"
123 " --lib-path path\tSpecify a library search path\n"
124 " --mapfile name\tCreate a map file\n"
125 " --module-id id\tSpecify a module id\n"
126 " --obj file\t\tLink this object file\n"
127 " --obj-path path\tSpecify an object file search path\n"
128 " --start-addr addr\tSet the default start address\n"
129 " --start-group\t\tStart a library group\n"
130 " --target sys\t\tSet the target system\n"
131 " --version\t\tPrint the linker version\n",
137 static unsigned long CvtNumber (const char* Arg, const char* Number)
138 /* Convert a number from a string. Allow '$' and '0x' prefixes for hex
146 if (*Number == '$') {
148 Converted = sscanf (Number, "%lx", &Val);
150 Converted = sscanf (Number, "%li", (long*)&Val);
153 /* Check if we do really have a number */
154 if (Converted != 1) {
155 Error ("Invalid number given in argument: %s\n", Arg);
158 /* Return the result */
164 static void LinkFile (const char* Name, FILETYPE Type)
165 /* Handle one file */
172 /* If we don't know the file type, determine it from the extension */
173 if (Type == FILETYPE_UNKNOWN) {
174 Type = GetFileType (Name);
177 /* For known file types, search the file in the directory list */
181 PathName = SearchFile (LibSearchPath, Name);
185 PathName = SearchFile (ObjSearchPath, Name);
189 PathName = xstrdup (Name); /* Use the name as is */
193 /* We must have a valid name now */
195 Error ("Input file `%s' not found", Name);
198 /* Try to open the file */
199 F = fopen (PathName, "rb");
201 Error ("Cannot open `%s': %s", PathName, strerror (errno));
204 /* Read the magic word */
207 /* Check the magic for known file types. The handling is somewhat weird
208 * since we may have given a file with a ".lib" extension, which was
209 * searched and found in a directory for library files, but we now find
210 * out (by looking at the magic) that it's indeed an object file. We just
211 * ignore the problem and hope no one will notice...
216 ObjAdd (F, PathName);
221 LibAdd (F, PathName);
227 Error ("File `%s' has unknown type", PathName);
231 /* Free allocated memory. */
237 static void DefineSymbol (const char* Def)
238 /* Define a symbol from the command line */
243 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
246 /* The symbol must start with a character or underline */
247 if (Def [0] != '_' && !IsAlpha (Def [0])) {
252 /* Copy the symbol, checking the remainder */
254 while (IsAlNum (*P) || *P == '_') {
255 SB_AppendChar (&SymName, *P++);
257 SB_Terminate (&SymName);
259 /* Do we have a value given? */
263 /* We have a value */
267 if (sscanf (P, "%lx", &Val) != 1) {
271 if (sscanf (P, "%li", &Val) != 1) {
277 /* Define the new symbol */
278 CreateConstExport (GetStringId (SB_GetConstBuf (&SymName)), Val);
283 static void OptCfgPath (const char* Opt attribute ((unused)), const char* Arg)
284 /* Specify a config file search path */
286 AddSearchPath (CfgSearchPath, Arg);
291 static void OptConfig (const char* Opt attribute ((unused)), const char* Arg)
292 /* Define the config file */
297 Error ("Cannot use -C/-t twice");
299 /* Search for the file */
300 PathName = SearchFile (CfgSearchPath, Arg);
302 Error ("Cannot find config file `%s'", Arg);
304 CfgSetName (PathName);
307 /* Read the config */
313 static void OptDbgFile (const char* Opt attribute ((unused)), const char* Arg)
314 /* Give the name of the debug file */
321 static void OptDefine (const char* Opt attribute ((unused)), const char* Arg)
322 /* Define a symbol on the command line */
329 static void OptDumpConfig (const char* Opt attribute ((unused)), const char* Arg)
330 /* Dump a builtin linker configuration */
332 /* Map the given target name to its id */
333 target_t T = FindTarget (Arg);
334 if (T == TGT_UNKNOWN) {
335 Error ("Target system `%s' is unknown", Arg);
338 /* Dump the builtin configuration */
339 DumpBuiltinConfig (stdout, T);
344 static void OptEndGroup (const char* Opt attribute ((unused)),
345 const char* Arg attribute ((unused)))
346 /* End a library group */
353 static void OptForceImport (const char* Opt attribute ((unused)), const char* Arg)
354 /* Force an import of a symbol */
356 /* An optional address size may be specified */
357 const char* ColPos = strchr (Arg, ':');
360 /* Use default address size (which for now is always absolute
363 InsertImport (GenImport (GetStringId (Arg), ADDR_SIZE_ABS));
369 /* Get the address size and check it */
370 unsigned char AddrSize = AddrSizeFromStr (ColPos+1);
371 if (AddrSize == ADDR_SIZE_INVALID) {
372 Error ("Invalid address size `%s'", ColPos+1);
375 /* Create a copy of the argument */
378 /* We need just the symbol */
379 A[ColPos - Arg] = '\0';
381 /* Generate the import */
382 InsertImport (GenImport (GetStringId (A), AddrSize));
384 /* Delete the copy of the argument */
391 static void OptHelp (const char* Opt attribute ((unused)),
392 const char* Arg attribute ((unused)))
393 /* Print usage information and exit */
401 static void OptLib (const char* Opt attribute ((unused)), const char* Arg)
404 LinkFile (Arg, FILETYPE_LIB);
409 static void OptLibPath (const char* Opt attribute ((unused)), const char* Arg)
410 /* Specify a library file search path */
412 AddSearchPath (LibSearchPath, Arg);
417 static void OptMapFile (const char* Opt attribute ((unused)), const char* Arg)
418 /* Give the name of the map file */
425 static void OptModuleId (const char* Opt, const char* Arg)
426 /* Specify a module id */
428 unsigned long Id = CvtNumber (Opt, Arg);
430 Error ("Range error in module id");
432 ModuleId = (unsigned) Id;
437 static void OptObj (const char* Opt attribute ((unused)), const char* Arg)
438 /* Link an object file */
440 LinkFile (Arg, FILETYPE_OBJ);
445 static void OptObjPath (const char* Opt attribute ((unused)), const char* Arg)
446 /* Specify an object file search path */
448 AddSearchPath (ObjSearchPath, Arg);
453 static void OptOutputName (const char* Opt, const char* Arg)
454 /* Give the name of the output file */
456 /* If the name of the output file has been used in the config before
457 * (by using %O) we're actually changing it later, which - in most cases -
458 * gives unexpected results, so emit a warning in this case.
460 if (OutputNameUsed) {
461 Warning ("Option `%s' should precede options `-t' or `-C'", Opt);
468 static void OptStartAddr (const char* Opt, const char* Arg)
469 /* Set the default start address */
471 StartAddr = CvtNumber (Opt, Arg);
477 static void OptStartGroup (const char* Opt attribute ((unused)),
478 const char* Arg attribute ((unused)))
479 /* Start a library group */
486 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
487 /* Set the target system */
491 /* Map the target name to a target id */
492 Target = FindTarget (Arg);
493 if (Target == TGT_UNKNOWN) {
494 Error ("Invalid target name: `%s'", Arg);
497 /* Get the target description record */
498 D = &Targets[Target];
500 /* Set the target data */
501 DefaultBinFmt = D->BinFmt;
504 /* Read the target config */
510 static void OptVersion (const char* Opt attribute ((unused)),
511 const char* Arg attribute ((unused)))
512 /* Print the assembler version */
515 "ld65 V%s - (C) Copyright 1998-2009, Ullrich von Bassewitz\n",
516 GetVersionAsString ());
521 int main (int argc, char* argv [])
522 /* Assembler main program */
524 /* Program long options */
525 static const LongOpt OptTab[] = {
526 { "--cfg-path", 1, OptCfgPath },
527 { "--config", 1, OptConfig },
528 { "--dbgfile", 1, OptDbgFile },
529 { "--define", 1, OptDefine },
530 { "--dump-config", 1, OptDumpConfig },
531 { "--end-group", 0, OptEndGroup },
532 { "--force-import", 1, OptForceImport },
533 { "--help", 0, OptHelp },
534 { "--lib", 1, OptLib },
535 { "--lib-path", 1, OptLibPath },
536 { "--mapfile", 1, OptMapFile },
537 { "--module-id", 1, OptModuleId },
538 { "--obj", 1, OptObj },
539 { "--obj-path", 1, OptObjPath },
540 { "--start-addr", 1, OptStartAddr },
541 { "--start-group", 0, OptStartGroup },
542 { "--target", 1, OptTarget },
543 { "--version", 0, OptVersion },
547 unsigned MemoryAreaOverflows;
549 /* Initialize the cmdline module */
550 InitCmdLine (&argc, &argv, "ld65");
552 /* Initialize the input file search paths */
555 /* Initialize the string pool */
558 /* Initialize the type pool */
561 /* Check the parameters */
563 while (I < ArgCount) {
565 /* Get the argument */
566 const char* Arg = ArgVec[I];
568 /* Check for an option */
569 if (Arg [0] == '-') {
575 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
579 OptStartGroup (Arg, 0);
583 OptEndGroup (Arg, 0);
592 OptMapFile (Arg, GetArg (&I, 2));
596 OptOutputName (Arg, GetArg (&I, 2));
601 Error ("Cannot use -C/-t twice");
603 OptTarget (Arg, GetArg (&I, 2));
607 OptForceImport (Arg, GetArg (&I, 2));
612 case 'm': VerboseMap = 1; break;
613 case '\0': ++Verbosity; break;
614 default: UnknownOption (Arg);
619 OptConfig (Arg, GetArg (&I, 2));
623 OptDefine (Arg, GetArg (&I, 2));
628 /* ## The first one is obsolete and will go */
629 case 'n': LabelFileName = GetArg (&I, 3); break;
630 default: OptLibPath (Arg, GetArg (&I, 2)); break;
635 OptStartAddr (Arg, GetArg (&I, 2));
650 LinkFile (Arg, FILETYPE_UNKNOWN);
658 /* Check if we had any object files */
660 Error ("No object files to link");
663 /* Check if we have a valid configuration */
665 Error ("Memory configuration missing");
668 /* Check if we have open library groups */
671 /* Create the condes tables if requested */
674 /* Process data from the config file. Assign start addresses for the
675 * segments, define linker symbols. The function will return the number
676 * of memory area overflows (zero on success).
678 MemoryAreaOverflows = CfgProcess ();
680 /* Check module assertions */
683 /* Check for import/export mismatches */
686 /* If we had a memory area overflow before, we cannot generate the output
687 * file. However, we will generate a short map file if requested, since
688 * this will help the user to rearrange segments and fix the overflow.
690 if (MemoryAreaOverflows) {
692 CreateMapFile (SHORT_MAPFILE);
694 Error ("Cannot generate output due to memory area overflow%s",
695 (MemoryAreaOverflows > 1)? "s" : "");
698 /* Create the output file */
701 /* Check for segments not written to the output file */
704 /* If requested, create a map file and a label file for VICE */
706 CreateMapFile (LONG_MAPFILE);
715 /* Dump the data for debugging */
721 /* Return an apropriate exit code */