1 /*****************************************************************************/
5 /* Main program for the ca65 macroassembler */
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 /*****************************************************************************/
81 /*****************************************************************************/
83 /*****************************************************************************/
87 static void Usage (void)
88 /* Print usage information and exit */
90 printf ("Usage: %s [options] file\n"
92 " -D name[=value]\t\tDefine a symbol\n"
93 " -I dir\t\t\tSet an include directory search path\n"
94 " -U\t\t\t\tMark unresolved symbols as import\n"
95 " -V\t\t\t\tPrint the assembler version\n"
96 " -W n\t\t\t\tSet warning level n\n"
97 " -g\t\t\t\tAdd debug info to object file\n"
98 " -h\t\t\t\tHelp (this text)\n"
99 " -i\t\t\t\tIgnore case of symbols\n"
100 " -l\t\t\t\tCreate a listing if assembly was ok\n"
101 " -mm model\t\t\tSet the memory model\n"
102 " -o name\t\t\tName the output file\n"
103 " -s\t\t\t\tEnable smart mode\n"
104 " -t sys\t\t\tSet the target system\n"
105 " -v\t\t\t\tIncrease verbosity\n"
108 " --auto-import\t\t\tMark unresolved symbols as import\n"
109 " --bin-include-dir dir\t\tSet a search path for binary includes\n"
110 " --cpu type\t\t\tSet cpu type\n"
111 " --create-dep name\t\tCreate a make dependency file\n"
112 " --create-full-dep name\tCreate a full make dependency file\n"
113 " --debug-info\t\t\tAdd debug info to object file\n"
114 " --feature name\t\tSet an emulation feature\n"
115 " --forget-inc-paths\t\tForget include search paths\n"
116 " --help\t\t\tHelp (this text)\n"
117 " --ignore-case\t\t\tIgnore case of symbols\n"
118 " --include-dir dir\t\tSet an include directory search path\n"
119 " --listing\t\t\tCreate a listing if assembly was ok\n"
120 " --list-bytes n\t\tMaximum number of bytes per listing line\n"
121 " --macpack-dir dir\t\tSet a macro package directory\n"
122 " --memory-model model\t\tSet the memory model\n"
123 " --pagelength n\t\tSet the page length for the listing\n"
124 " --smart\t\t\tEnable smart mode\n"
125 " --target sys\t\t\tSet the target system\n"
126 " --verbose\t\t\tIncrease verbosity\n"
127 " --version\t\t\tPrint the assembler version\n",
133 static void SetOptions (void)
134 /* Set the option for the translator */
136 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
138 /* Set the translator */
139 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
140 OptTranslator (&Buf);
142 /* Set date and time */
143 OptDateTime ((unsigned long) time(0));
145 /* Release memory for the string */
151 static void NewSymbol (const char* SymName, long Val)
152 /* Define a symbol with a fixed numeric value in the current scope */
157 /* Convert the name to a string buffer */
158 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
159 SB_CopyStr (&SymBuf, SymName);
161 /* Search for the symbol, allocate a new one if it doesn't exist */
162 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
164 /* Check if have already a symbol with this name */
165 if (SymIsDef (Sym)) {
166 AbEnd ("`%s' is already defined", SymName);
169 /* Generate an expression for the symbol */
170 Expr = GenLiteralExpr (Val);
172 /* Mark the symbol as defined */
173 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
175 /* Free string buffer memory */
181 static void CBMSystem (const char* Sys)
182 /* Define a CBM system */
184 NewSymbol ("__CBM__", 1);
190 static void SetSys (const char* Sys)
191 /* Define a target system */
193 switch (Target = FindTarget (Sys)) {
199 AbEnd ("Cannot use `module' as a target for the assembler");
203 NewSymbol ("__ATARI__", 1);
207 CBMSystem ("__C16__");
211 CBMSystem ("__C64__");
215 CBMSystem ("__VIC20__");
219 CBMSystem ("__C128__");
223 CBMSystem ("__PLUS4__");
227 CBMSystem ("__CBM510__");
231 CBMSystem ("__CBM610__");
235 CBMSystem ("__PET__");
239 NewSymbol ("__BBC__", 1);
243 NewSymbol ("__APPLE2__", 1);
247 NewSymbol ("__APPLE2ENH__", 1);
251 /* Do not handle as a CBM system */
252 NewSymbol ("__GEOS__", 1);
256 NewSymbol ("__LUNIX__", 1);
260 NewSymbol ("__ATMOS__", 1);
264 NewSymbol ("__NES__", 1);
267 case TGT_SUPERVISION:
268 NewSymbol ("__SUPERVISION__", 1);
272 NewSymbol ("__LYNX__", 1);
276 AbEnd ("Invalid target name: `%s'", Sys);
280 /* Initialize the translation tables for the target system */
286 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
287 /* Handle an option that remembers a file name for later */
289 /* Cannot have the option twice */
290 if (SB_NotEmpty (Name)) {
291 AbEnd ("Cannot use option `%s' twice", Opt);
293 /* Remember the file name for later */
294 SB_CopyStr (Name, Arg);
300 static void DefineSymbol (const char* Def)
301 /* Define a symbol from the command line */
306 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
309 /* The symbol must start with a character or underline */
310 if (!IsIdStart (Def [0])) {
315 /* Copy the symbol, checking the rest */
317 while (IsIdChar (*P)) {
318 SB_AppendChar (&SymName, *P++);
320 SB_Terminate (&SymName);
322 /* Do we have a value given? */
329 /* We have a value */
333 if (sscanf (P, "%lx", &Val) != 1) {
337 if (sscanf (P, "%li", &Val) != 1) {
343 /* Define the new symbol */
344 NewSymbol (SB_GetConstBuf (&SymName), Val);
346 /* Release string memory */
352 static void OptAutoImport (const char* Opt attribute ((unused)),
353 const char* Arg attribute ((unused)))
354 /* Mark unresolved symbols as imported */
361 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
362 /* Add an include search path for binaries */
364 AddSearchPath (BinSearchPath, Arg);
369 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
370 /* Handle the --cpu option */
372 cpu_t CPU = FindCPU (Arg);
373 if (CPU == CPU_UNKNOWN) {
374 AbEnd ("Invalid CPU: `%s'", Arg);
382 static void OptCreateDep (const char* Opt, const char* Arg)
383 /* Handle the --create-dep option */
385 FileNameOption (Opt, Arg, &DepName);
390 static void OptCreateFullDep (const char* Opt attribute ((unused)),
392 /* Handle the --create-full-dep option */
394 FileNameOption (Opt, Arg, &FullDepName);
399 static void OptDebugInfo (const char* Opt attribute ((unused)),
400 const char* Arg attribute ((unused)))
401 /* Add debug info to the object file */
408 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
409 /* Set an emulation feature */
411 /* Make a string buffer from Arg */
414 /* Set the feature, check for errors */
415 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
416 AbEnd ("Illegal emulation feature: `%s'", Arg);
422 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
423 const char* Arg attribute ((unused)))
424 /* Forget all currently defined include paths */
426 ForgetAllIncludePaths ();
431 static void OptHelp (const char* Opt attribute ((unused)),
432 const char* Arg attribute ((unused)))
433 /* Print usage information and exit */
441 static void OptIgnoreCase (const char* Opt attribute ((unused)),
442 const char* Arg attribute ((unused)))
443 /* Ignore case on symbols */
450 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
451 /* Add an include search path */
453 AddSearchPath (IncSearchPath, Arg);
458 static void OptListBytes (const char* Opt, const char* Arg)
459 /* Set the maximum number of bytes per listing line */
464 /* Convert the argument to a number */
465 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
469 /* Check the bounds */
470 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
471 AbEnd ("Argument for option `%s' is out of range", Opt);
480 static void OptListing (const char* Opt attribute ((unused)),
481 const char* Arg attribute ((unused)))
482 /* Create a listing file */
489 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
490 /* Set a macro package directory */
492 /* Make a string buffer from Arg */
495 /* Use the directory */
496 MacPackSetDir (SB_InitFromString (&Dir, Arg));
501 static void OptMemoryModel (const char* Opt, const char* Arg)
502 /* Set the memory model */
506 /* Check the current memory model */
507 if (MemoryModel != MMODEL_UNKNOWN) {
508 AbEnd ("Cannot use option `%s' twice", Opt);
511 /* Translate the memory model name and check it */
512 M = FindMemoryModel (Arg);
513 if (M == MMODEL_UNKNOWN) {
514 AbEnd ("Unknown memory model: %s", Arg);
515 } else if (M == MMODEL_HUGE) {
516 AbEnd ("Unsupported memory model: %s", Arg);
519 /* Set the memory model */
525 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
526 /* Handle the --pagelength option */
528 int Len = atoi (Arg);
529 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
530 AbEnd ("Invalid page length: %d", Len);
537 static void OptSmart (const char* Opt attribute ((unused)),
538 const char* Arg attribute ((unused)))
539 /* Handle the -s/--smart options */
546 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
547 /* Set the target system */
554 static void OptVerbose (const char* Opt attribute ((unused)),
555 const char* Arg attribute ((unused)))
556 /* Increase verbosity */
563 static void OptVersion (const char* Opt attribute ((unused)),
564 const char* Arg attribute ((unused)))
565 /* Print the assembler version */
567 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
572 static void DoPCAssign (void)
573 /* Start absolute code */
575 long PC = ConstExpression ();
576 if (PC < 0 || PC > 0xFFFFFF) {
577 Error ("Range error");
579 EnterAbsoluteMode (PC);
585 static void OneLine (void)
586 /* Assemble one line */
589 unsigned long PC = 0;
594 /* Initialize the new listing line if we are actually reading from file
595 * and not from internally pushed input.
597 if (!HavePushedInput ()) {
601 if (Tok == TOK_COLON) {
602 /* An unnamed label */
607 /* If the first token on the line is an identifier, check for a macro or
610 if (Tok == TOK_IDENT) {
611 if (!UbiquitousIdents) {
612 /* Macros and symbols cannot use instruction names */
613 Instr = FindInstruction (&SVal);
615 Macro = IsMacro (&SVal);
618 /* Macros and symbols may use the names of instructions */
619 Macro = IsMacro (&SVal);
623 /* Handle an identifier. This may be a cheap local symbol, or a fully
624 * scoped identifier which may start with a namespace token (for global
627 if (Tok == TOK_LOCAL_IDENT ||
628 Tok == TOK_NAMESPACE ||
629 (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
631 /* Did we have whitespace before the ident? */
634 /* Generate the symbol table entry, then skip the name */
635 Sym = ParseAnySymName (SYM_ALLOC_NEW);
637 /* If a colon follows, this is a label definition. If there
638 * is no colon, it's an assignment.
640 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
642 /* Determine the symbol flags from the assignment token */
643 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
648 /* Define the symbol with the expression following the '=' */
649 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
651 /* Don't allow anything after a symbol definition */
655 } else if (Tok == TOK_SET) {
659 /* .SET defines variables (= redefinable symbols) */
662 /* Read the assignment expression, which must be constant */
663 Expr = GenLiteralExpr (ConstExpression ());
665 /* Define the symbol with the constant expression following
668 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
670 /* Don't allow anything after a symbol definition */
676 /* A label. Remember the current segment, so we can later
677 * determine the size of the data stored under the label.
682 /* Define the label */
683 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
685 /* Skip the colon. If NoColonLabels is enabled, allow labels
686 * without a colon if there is no whitespace before the
689 if (Tok != TOK_COLON) {
690 if (HadWS || !NoColonLabels) {
691 Error ("`:' expected");
692 /* Try some smart error recovery */
693 if (Tok == TOK_NAMESPACE) {
702 /* If we come here, a new identifier may be waiting, which may
703 * be a macro or instruction.
705 if (Tok == TOK_IDENT) {
706 if (!UbiquitousIdents) {
707 /* Macros and symbols cannot use instruction names */
708 Instr = FindInstruction (&SVal);
710 Macro = IsMacro (&SVal);
713 /* Macros and symbols may use the names of instructions */
714 Macro = IsMacro (&SVal);
720 /* We've handled a possible label, now handle the remainder of the line */
721 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
722 /* A control command */
725 /* A macro expansion */
727 } else if (Instr >= 0 ||
728 (UbiquitousIdents && ((Instr = FindInstruction (&SVal)) >= 0))) {
729 /* A mnemonic - assemble one instruction */
730 HandleInstruction (Instr);
731 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
734 Error ("`=' expected");
737 /* Skip the equal sign */
739 /* Enter absolute mode */
744 /* If we have defined a label, remember its size. Sym is also set by
745 * a symbol assignment, but in this case Done is false, so we don't
750 if (Seg == ActiveSeg) {
752 Size = GetPC () - PC;
754 /* The line has switched the segment */
757 DefSizeOfSymbol (Sym, Size);
760 /* Line separator must come here */
766 static void Assemble (void)
767 /* Start the ball rolling ... */
772 /* Assemble lines until end of file */
773 while (Tok != TOK_EOF) {
780 static void CreateObjFile (void)
781 /* Create the object file */
783 /* Open the object, write the header */
786 /* Write the object file options */
789 /* Write the list of input files */
792 /* Write the segment data to the file */
795 /* Write the import list */
798 /* Write the export list */
801 /* Write the scopes if requested */
804 /* Write debug symbols if requested */
807 /* Write line infos if requested */
810 /* Write the string pool */
813 /* Write the assertions */
816 /* Write an updated header and close the file */
822 int main (int argc, char* argv [])
823 /* Assembler main program */
825 /* Program long options */
826 static const LongOpt OptTab[] = {
827 { "--auto-import", 0, OptAutoImport },
828 { "--bin-include-dir", 1, OptBinIncludeDir },
829 { "--cpu", 1, OptCPU },
830 { "--create-dep", 1, OptCreateDep },
831 { "--create-full-dep", 1, OptCreateFullDep },
832 { "--debug-info", 0, OptDebugInfo },
833 { "--feature", 1, OptFeature },
834 { "--forget-inc-paths", 0, OptForgetIncPaths },
835 { "--help", 0, OptHelp },
836 { "--ignore-case", 0, OptIgnoreCase },
837 { "--include-dir", 1, OptIncludeDir },
838 { "--list-bytes", 1, OptListBytes },
839 { "--listing", 0, OptListing },
840 { "--macpack-dir", 1, OptMacPackDir },
841 { "--memory-model", 1, OptMemoryModel },
842 { "--pagelength", 1, OptPageLength },
843 { "--smart", 0, OptSmart },
844 { "--target", 1, OptTarget },
845 { "--verbose", 0, OptVerbose },
846 { "--version", 0, OptVersion },
849 /* Name of the global name space */
850 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
854 /* Initialize the cmdline module */
855 InitCmdLine (&argc, &argv, "ca65");
857 /* Initialize the include search paths */
860 /* Enter the base lexical level. We must do that here, since we may
861 * define symbols using -D.
863 SymEnterLevel (&GlobalNameSpace, ST_GLOBAL, ADDR_SIZE_DEFAULT);
865 /* Check the parameters */
867 while (I < ArgCount) {
869 /* Get the argument */
870 const char* Arg = ArgVec [I];
872 /* Check for an option */
877 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
881 OptDebugInfo (Arg, 0);
889 OptIgnoreCase (Arg, 0);
898 OptMemoryModel (Arg, GetArg (&I, 3));
905 OutFile = GetArg (&I, 2);
913 OptTarget (Arg, GetArg (&I, 2));
921 DefineSymbol (GetArg (&I, 2));
925 OptIncludeDir (Arg, GetArg (&I, 2));
929 OptAutoImport (Arg, 0);
937 WarnLevel = atoi (GetArg (&I, 2));
946 /* Filename. Check if we already had one */
948 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
960 /* Do we have an input file? */
962 fprintf (stderr, "%s: No input files\n", ProgName);
966 /* If no CPU given, use the default CPU for the target */
967 if (GetCPU () == CPU_UNKNOWN) {
968 if (Target != TGT_UNKNOWN) {
969 SetCPU (DefaultCPU[Target]);
975 /* If no memory model was given, use the default */
976 if (MemoryModel == MMODEL_UNKNOWN) {
977 SetMemoryModel (MMODEL_NEAR);
980 /* Initialize the segments */
983 /* Initialize the scanner, open the input file */
984 InitScanner (InFile);
986 /* Define the default options */
989 /* Assemble the input */
992 /* If we didn't have any errors, check the pseudo insn stacks */
993 if (ErrorCount == 0) {
997 /* If we didn't have any errors, check the unnamed labels */
998 if (ErrorCount == 0) {
1002 /* If we didn't have any errors, check the symbol table */
1003 if (ErrorCount == 0) {
1007 /* If we didn't have any errors, check and resolve the segment data */
1008 if (ErrorCount == 0) {
1012 /* If we didn't have any errors, check the assertions */
1013 if (ErrorCount == 0) {
1017 /* If we didn't have an errors, index the line infos */
1018 MakeLineInfoIndex ();
1021 if (Verbosity >= 2) {
1026 /* If we didn't have any errors, create the object, listing and
1029 if (ErrorCount == 0) {
1034 CreateDependencies ();
1037 /* Close the input file */
1040 /* Return an apropriate exit code */
1041 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;