5 /* Main program for the ca65 macroassembler */
9 /* (C) 1998-2012, 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 /*****************************************************************************/
45 #include "debugflag.h"
48 #include "scopedefs.h"
84 /*****************************************************************************/
86 /*****************************************************************************/
90 static void Usage (void)
91 /* Print usage information and exit */
93 printf ("Usage: %s [options] file\n"
95 " -D name[=value]\t\tDefine a symbol\n"
96 " -I dir\t\t\tSet an include directory search path\n"
97 " -U\t\t\t\tMark unresolved symbols as import\n"
98 " -V\t\t\t\tPrint the assembler version\n"
99 " -W n\t\t\t\tSet warning level n\n"
100 " -d\t\t\t\tDebug mode\n"
101 " -g\t\t\t\tAdd debug info to object file\n"
102 " -h\t\t\t\tHelp (this text)\n"
103 " -i\t\t\t\tIgnore case of symbols\n"
104 " -l name\t\t\tCreate a listing file if assembly was ok\n"
105 " -mm model\t\t\tSet the memory model\n"
106 " -o name\t\t\tName the output file\n"
107 " -s\t\t\t\tEnable smart mode\n"
108 " -t sys\t\t\tSet the target system\n"
109 " -v\t\t\t\tIncrease verbosity\n"
112 " --auto-import\t\t\tMark unresolved symbols as import\n"
113 " --bin-include-dir dir\t\tSet a search path for binary includes\n"
114 " --cpu type\t\t\tSet cpu type\n"
115 " --create-dep name\t\tCreate a make dependency file\n"
116 " --create-full-dep name\tCreate a full make dependency file\n"
117 " --debug\t\t\tDebug mode\n"
118 " --debug-info\t\t\tAdd debug info to object file\n"
119 " --feature name\t\tSet an emulation feature\n"
120 " --forget-inc-paths\t\tForget include search paths\n"
121 " --help\t\t\tHelp (this text)\n"
122 " --ignore-case\t\t\tIgnore case of symbols\n"
123 " --include-dir dir\t\tSet an include directory search path\n"
124 " --large-alignment\t\tDon't warn about large alignments\n"
125 " --listing name\t\tCreate a listing file if assembly was ok\n"
126 " --list-bytes n\t\tMaximum number of bytes per listing line\n"
127 " --macpack-dir dir\t\tSet a macro package directory\n"
128 " --memory-model model\t\tSet the memory model\n"
129 " --pagelength n\t\tSet the page length for the listing\n"
130 " --relax-checks\t\tRelax some checks (see docs)\n"
131 " --smart\t\t\tEnable smart mode\n"
132 " --target sys\t\t\tSet the target system\n"
133 " --verbose\t\t\tIncrease verbosity\n"
134 " --version\t\t\tPrint the assembler version\n",
140 static void SetOptions (void)
141 /* Set the option for the translator */
143 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
145 /* Set the translator */
146 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
147 OptTranslator (&Buf);
149 /* Set date and time */
150 OptDateTime ((unsigned long) time(0));
152 /* Release memory for the string */
158 static void NewSymbol (const char* SymName, long Val)
159 /* Define a symbol with a fixed numeric value in the current scope */
164 /* Convert the name to a string buffer */
165 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
166 SB_CopyStr (&SymBuf, SymName);
168 /* Search for the symbol, allocate a new one if it doesn't exist */
169 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
171 /* Check if have already a symbol with this name */
172 if (SymIsDef (Sym)) {
173 AbEnd ("`%s' is already defined", SymName);
176 /* Generate an expression for the symbol */
177 Expr = GenLiteralExpr (Val);
179 /* Mark the symbol as defined */
180 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
182 /* Free string buffer memory */
188 static void CBMSystem (const char* Sys)
189 /* Define a CBM system */
191 NewSymbol ("__CBM__", 1);
197 static void SetSys (const char* Sys)
198 /* Define a target system */
200 switch (Target = FindTarget (Sys)) {
206 AbEnd ("Cannot use `module' as a target for the assembler");
210 NewSymbol ("__ATARI__", 1);
214 CBMSystem ("__C16__");
218 CBMSystem ("__C64__");
222 CBMSystem ("__VIC20__");
226 CBMSystem ("__C128__");
230 CBMSystem ("__PLUS4__");
234 CBMSystem ("__CBM510__");
238 CBMSystem ("__CBM610__");
242 CBMSystem ("__PET__");
246 NewSymbol ("__BBC__", 1);
250 NewSymbol ("__APPLE2__", 1);
254 NewSymbol ("__APPLE2ENH__", 1);
258 /* Do not handle as a CBM system */
259 NewSymbol ("__GEOS__", 1);
260 NewSymbol ("__GEOS_CBM__", 1);
264 NewSymbol ("__GEOS__", 1);
265 NewSymbol ("__GEOS_APPLE__", 1);
269 NewSymbol ("__LUNIX__", 1);
273 NewSymbol ("__ATMOS__", 1);
277 NewSymbol ("__NES__", 1);
280 case TGT_SUPERVISION:
281 NewSymbol ("__SUPERVISION__", 1);
285 NewSymbol ("__LYNX__", 1);
289 AbEnd ("Invalid target name: `%s'", Sys);
293 /* Initialize the translation tables for the target system */
299 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
300 /* Handle an option that remembers a file name for later */
302 /* Cannot have the option twice */
303 if (SB_NotEmpty (Name)) {
304 AbEnd ("Cannot use option `%s' twice", Opt);
306 /* Remember the file name for later */
307 SB_CopyStr (Name, Arg);
313 static void DefineSymbol (const char* Def)
314 /* Define a symbol from the command line */
319 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
322 /* The symbol must start with a character or underline */
323 if (!IsIdStart (Def [0])) {
328 /* Copy the symbol, checking the rest */
330 while (IsIdChar (*P)) {
331 SB_AppendChar (&SymName, *P++);
333 SB_Terminate (&SymName);
335 /* Do we have a value given? */
342 /* We have a value */
346 if (sscanf (P, "%lx", &Val) != 1) {
350 if (sscanf (P, "%li", &Val) != 1) {
356 /* Define the new symbol */
357 NewSymbol (SB_GetConstBuf (&SymName), Val);
359 /* Release string memory */
365 static void OptAutoImport (const char* Opt attribute ((unused)),
366 const char* Arg attribute ((unused)))
367 /* Mark unresolved symbols as imported */
374 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
375 /* Add an include search path for binaries */
377 AddSearchPath (BinSearchPath, Arg);
382 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
383 /* Handle the --cpu option */
385 cpu_t CPU = FindCPU (Arg);
386 if (CPU == CPU_UNKNOWN) {
387 AbEnd ("Invalid CPU: `%s'", Arg);
395 static void OptCreateDep (const char* Opt, const char* Arg)
396 /* Handle the --create-dep option */
398 FileNameOption (Opt, Arg, &DepName);
403 static void OptCreateFullDep (const char* Opt attribute ((unused)),
405 /* Handle the --create-full-dep option */
407 FileNameOption (Opt, Arg, &FullDepName);
412 static void OptDebug (const char* Opt attribute ((unused)),
413 const char* Arg attribute ((unused)))
414 /* Compiler debug mode */
421 static void OptDebugInfo (const char* Opt attribute ((unused)),
422 const char* Arg attribute ((unused)))
423 /* Add debug info to the object file */
430 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
431 /* Set an emulation feature */
433 /* Make a string buffer from Arg */
436 /* Set the feature, check for errors */
437 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
438 AbEnd ("Illegal emulation feature: `%s'", Arg);
444 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
445 const char* Arg attribute ((unused)))
446 /* Forget all currently defined include paths */
448 ForgetAllIncludePaths ();
453 static void OptHelp (const char* Opt attribute ((unused)),
454 const char* Arg attribute ((unused)))
455 /* Print usage information and exit */
463 static void OptIgnoreCase (const char* Opt attribute ((unused)),
464 const char* Arg attribute ((unused)))
465 /* Ignore case on symbols */
472 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
473 /* Add an include search path */
475 AddSearchPath (IncSearchPath, Arg);
480 static void OptLargeAlignment (const char* Opt attribute ((unused)),
481 const char* Arg attribute ((unused)))
482 /* Don't warn about large alignments */
489 static void OptListBytes (const char* Opt, const char* Arg)
490 /* Set the maximum number of bytes per listing line */
495 /* Convert the argument to a number */
496 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
500 /* Check the bounds */
501 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
502 AbEnd ("Argument for option `%s' is out of range", Opt);
511 static void OptListing (const char* Opt, const char* Arg)
512 /* Create a listing file */
514 /* Since the meaning of -l and --listing has changed, print an error if
515 * the filename is empty or begins with the option char.
517 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
518 Fatal ("The meaning of `%s' has changed. It does now "
519 "expect a file name as argument.", Opt);
522 /* Get the file name */
523 FileNameOption (Opt, Arg, &ListingName);
528 static void OptMemoryModel (const char* Opt, const char* Arg)
529 /* Set the memory model */
533 /* Check the current memory model */
534 if (MemoryModel != MMODEL_UNKNOWN) {
535 AbEnd ("Cannot use option `%s' twice", Opt);
538 /* Translate the memory model name and check it */
539 M = FindMemoryModel (Arg);
540 if (M == MMODEL_UNKNOWN) {
541 AbEnd ("Unknown memory model: %s", Arg);
542 } else if (M == MMODEL_HUGE) {
543 AbEnd ("Unsupported memory model: %s", Arg);
546 /* Set the memory model */
552 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
553 /* Handle the --pagelength option */
555 int Len = atoi (Arg);
556 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
557 AbEnd ("Invalid page length: %d", Len);
564 static void OptRelaxChecks (const char* Opt attribute ((unused)),
565 const char* Arg attribute ((unused)))
566 /* Handle the --relax-checks options */
573 static void OptSmart (const char* Opt attribute ((unused)),
574 const char* Arg attribute ((unused)))
575 /* Handle the -s/--smart options */
582 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
583 /* Set the target system */
590 static void OptVerbose (const char* Opt attribute ((unused)),
591 const char* Arg attribute ((unused)))
592 /* Increase verbosity */
599 static void OptVersion (const char* Opt attribute ((unused)),
600 const char* Arg attribute ((unused)))
601 /* Print the assembler version */
603 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
608 static void DoPCAssign (void)
609 /* Start absolute code */
611 long PC = ConstExpression ();
612 if (PC < 0 || PC > 0xFFFFFF) {
613 Error ("Range error");
615 EnterAbsoluteMode (PC);
621 static void OneLine (void)
622 /* Assemble one line */
625 unsigned long PC = 0;
630 /* Initialize the new listing line if we are actually reading from file
631 * and not from internally pushed input.
633 if (!HavePushedInput ()) {
637 /* Single colon means unnamed label */
638 if (CurTok.Tok == TOK_COLON) {
643 /* If the first token on the line is an identifier, check for a macro or
646 if (CurTok.Tok == TOK_IDENT) {
647 if (!UbiquitousIdents) {
648 /* Macros and symbols cannot use instruction names */
649 Instr = FindInstruction (&CurTok.SVal);
651 Mac = FindMacro (&CurTok.SVal);
654 /* Macros and symbols may use the names of instructions */
655 Mac = FindMacro (&CurTok.SVal);
659 /* Handle an identifier. This may be a cheap local symbol, or a fully
660 * scoped identifier which may start with a namespace token (for global
663 if (CurTok.Tok == TOK_LOCAL_IDENT ||
664 CurTok.Tok == TOK_NAMESPACE ||
665 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
667 /* Did we have whitespace before the ident? */
668 int HadWS = CurTok.WS;
670 /* Generate the symbol table entry, then skip the name */
671 Sym = ParseAnySymName (SYM_ALLOC_NEW);
673 /* If a colon follows, this is a label definition. If there
674 * is no colon, it's an assignment.
676 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
678 /* Determine the symbol flags from the assignment token */
679 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
684 /* Define the symbol with the expression following the '=' */
685 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
687 /* Don't allow anything after a symbol definition */
691 } else if (CurTok.Tok == TOK_SET) {
695 /* .SET defines variables (= redefinable symbols) */
698 /* Read the assignment expression, which must be constant */
699 Expr = GenLiteralExpr (ConstExpression ());
701 /* Define the symbol with the constant expression following
704 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
706 /* Don't allow anything after a symbol definition */
712 /* A label. Remember the current segment, so we can later
713 * determine the size of the data stored under the label.
718 /* Define the label */
719 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
721 /* Skip the colon. If NoColonLabels is enabled, allow labels
722 * without a colon if there is no whitespace before the
725 if (CurTok.Tok != TOK_COLON) {
726 if (HadWS || !NoColonLabels) {
727 Error ("`:' expected");
728 /* Try some smart error recovery */
729 if (CurTok.Tok == TOK_NAMESPACE) {
738 /* If we come here, a new identifier may be waiting, which may
739 * be a macro or instruction.
741 if (CurTok.Tok == TOK_IDENT) {
742 if (!UbiquitousIdents) {
743 /* Macros and symbols cannot use instruction names */
744 Instr = FindInstruction (&CurTok.SVal);
746 Mac = FindMacro (&CurTok.SVal);
749 /* Macros and symbols may use the names of instructions */
750 Mac = FindMacro (&CurTok.SVal);
756 /* We've handled a possible label, now handle the remainder of the line */
757 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
758 /* A control command */
760 } else if (Mac != 0) {
761 /* A macro expansion */
762 MacExpandStart (Mac);
763 } else if (Instr >= 0 ||
764 (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
765 /* A mnemonic - assemble one instruction */
766 HandleInstruction (Instr);
767 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
769 if (CurTok.Tok != TOK_EQ) {
770 Error ("`=' expected");
773 /* Skip the equal sign */
775 /* Enter absolute mode */
780 /* If we have defined a label, remember its size. Sym is also set by
781 * a symbol assignment, but in this case Done is false, so we don't
786 if (Seg == ActiveSeg) {
788 Size = GetPC () - PC;
790 /* The line has switched the segment */
793 DefSizeOfSymbol (Sym, Size);
796 /* Line separator must come here */
802 static void Assemble (void)
803 /* Start the ball rolling ... */
808 /* Assemble lines until end of file */
809 while (CurTok.Tok != TOK_EOF) {
816 static void CreateObjFile (void)
817 /* Create the object file */
819 /* Open the object, write the header */
822 /* Write the object file options */
825 /* Write the list of input files */
828 /* Write the segment data to the file */
831 /* Write the import list */
834 /* Write the export list */
837 /* Write debug symbols if requested */
840 /* Write the scopes if requested */
843 /* Write line infos if requested */
846 /* Write the string pool */
849 /* Write the assertions */
852 /* Write the spans */
855 /* Write an updated header and close the file */
861 int main (int argc, char* argv [])
862 /* Assembler main program */
864 /* Program long options */
865 static const LongOpt OptTab[] = {
866 { "--auto-import", 0, OptAutoImport },
867 { "--bin-include-dir", 1, OptBinIncludeDir },
868 { "--cpu", 1, OptCPU },
869 { "--create-dep", 1, OptCreateDep },
870 { "--create-full-dep", 1, OptCreateFullDep },
871 { "--debug", 0, OptDebug },
872 { "--debug-info", 0, OptDebugInfo },
873 { "--feature", 1, OptFeature },
874 { "--forget-inc-paths", 0, OptForgetIncPaths },
875 { "--help", 0, OptHelp },
876 { "--ignore-case", 0, OptIgnoreCase },
877 { "--include-dir", 1, OptIncludeDir },
878 { "--large-alignment", 0, OptLargeAlignment },
879 { "--list-bytes", 1, OptListBytes },
880 { "--listing", 1, OptListing },
881 { "--memory-model", 1, OptMemoryModel },
882 { "--pagelength", 1, OptPageLength },
883 { "--relax-checks", 0, OptRelaxChecks },
884 { "--smart", 0, OptSmart },
885 { "--target", 1, OptTarget },
886 { "--verbose", 0, OptVerbose },
887 { "--version", 0, OptVersion },
890 /* Name of the global name space */
891 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
895 /* Initialize the cmdline module */
896 InitCmdLine (&argc, &argv, "ca65");
898 /* Initialize the string pool */
901 /* Initialize the include search paths */
904 /* Create the predefined segments */
907 /* Enter the base lexical level. We must do that here, since we may
908 * define symbols using -D.
910 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
912 /* Initialize the line infos. Must be done here, since we need line infos
913 * for symbol definitions.
917 /* Check the parameters */
919 while (I < ArgCount) {
921 /* Get the argument */
922 const char* Arg = ArgVec [I];
924 /* Check for an option */
929 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
937 OptDebugInfo (Arg, 0);
945 OptIgnoreCase (Arg, 0);
949 OptListing (Arg, GetArg (&I, 2));
954 OptMemoryModel (Arg, GetArg (&I, 3));
961 OutFile = GetArg (&I, 2);
969 OptTarget (Arg, GetArg (&I, 2));
977 DefineSymbol (GetArg (&I, 2));
981 OptIncludeDir (Arg, GetArg (&I, 2));
985 OptAutoImport (Arg, 0);
993 WarnLevel = atoi (GetArg (&I, 2));
1002 /* Filename. Check if we already had one */
1004 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
1006 exit (EXIT_FAILURE);
1016 /* Do we have an input file? */
1018 fprintf (stderr, "%s: No input files\n", ProgName);
1019 exit (EXIT_FAILURE);
1022 /* If no CPU given, use the default CPU for the target */
1023 if (GetCPU () == CPU_UNKNOWN) {
1024 if (Target != TGT_UNKNOWN) {
1025 SetCPU (GetTargetProperties (Target)->DefaultCPU);
1031 /* If no memory model was given, use the default */
1032 if (MemoryModel == MMODEL_UNKNOWN) {
1033 SetMemoryModel (MMODEL_NEAR);
1036 /* Set the default segment sizes according to the memory model */
1039 /* Initialize the scanner, open the input file */
1040 InitScanner (InFile);
1042 /* Define the default options */
1045 /* Assemble the input */
1048 /* If we didn't have any errors, check the pseudo insn stacks */
1049 if (ErrorCount == 0) {
1053 /* If we didn't have any errors, check and cleanup the unnamed labels */
1054 if (ErrorCount == 0) {
1058 /* If we didn't have any errors, check the symbol table */
1059 if (ErrorCount == 0) {
1063 /* If we didn't have any errors, check the hll debug symbols */
1064 if (ErrorCount == 0) {
1068 /* If we didn't have any errors, close the file scope lexical level */
1069 if (ErrorCount == 0) {
1073 /* If we didn't have any errors, check and resolve the segment data */
1074 if (ErrorCount == 0) {
1078 /* If we didn't have any errors, check the assertions */
1079 if (ErrorCount == 0) {
1084 if (Verbosity >= 2) {
1089 /* If we didn't have an errors, finish off the line infos */
1092 /* If we didn't have any errors, create the object, listing and
1095 if (ErrorCount == 0) {
1097 if (SB_GetLen (&ListingName) > 0) {
1100 CreateDependencies ();
1103 /* Close the input file */
1106 /* Return an apropriate exit code */
1107 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;