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"
85 /*****************************************************************************/
87 /*****************************************************************************/
91 static void Usage (void)
92 /* Print usage information and exit */
94 printf ("Usage: %s [options] file\n"
96 " -D name[=value]\t\tDefine a symbol\n"
97 " -I dir\t\t\tSet an include directory search path\n"
98 " -U\t\t\t\tMark unresolved symbols as import\n"
99 " -V\t\t\t\tPrint the assembler version\n"
100 " -W n\t\t\t\tSet warning level n\n"
101 " -d\t\t\t\tDebug mode\n"
102 " -g\t\t\t\tAdd debug info to object file\n"
103 " -h\t\t\t\tHelp (this text)\n"
104 " -i\t\t\t\tIgnore case of symbols\n"
105 " -l name\t\t\tCreate a listing file if assembly was ok\n"
106 " -mm model\t\t\tSet the memory model\n"
107 " -o name\t\t\tName the output file\n"
108 " -s\t\t\t\tEnable smart mode\n"
109 " -t sys\t\t\tSet the target system\n"
110 " -v\t\t\t\tIncrease verbosity\n"
113 " --auto-import\t\t\tMark unresolved symbols as import\n"
114 " --bin-include-dir dir\t\tSet a search path for binary includes\n"
115 " --cpu type\t\t\tSet cpu type\n"
116 " --create-dep name\t\tCreate a make dependency file\n"
117 " --create-full-dep name\tCreate a full make dependency file\n"
118 " --debug\t\t\tDebug mode\n"
119 " --debug-info\t\t\tAdd debug info to object file\n"
120 " --feature name\t\tSet an emulation feature\n"
121 " --forget-inc-paths\t\tForget include search paths\n"
122 " --help\t\t\tHelp (this text)\n"
123 " --ignore-case\t\t\tIgnore case of symbols\n"
124 " --include-dir dir\t\tSet an include directory search path\n"
125 " --large-alignment\t\tDon't warn about large alignments\n"
126 " --listing name\t\tCreate a listing file if assembly was ok\n"
127 " --list-bytes n\t\tMaximum number of bytes per listing line\n"
128 " --macpack-dir dir\t\tSet a macro package directory\n"
129 " --memory-model model\t\tSet the memory model\n"
130 " --pagelength n\t\tSet the page length for the listing\n"
131 " --relax-checks\t\tRelax some checks (see docs)\n"
132 " --smart\t\t\tEnable smart mode\n"
133 " --target sys\t\t\tSet the target system\n"
134 " --verbose\t\t\tIncrease verbosity\n"
135 " --version\t\t\tPrint the assembler version\n",
141 static void SetOptions (void)
142 /* Set the option for the translator */
144 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
146 /* Set the translator */
147 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
148 OptTranslator (&Buf);
150 /* Set date and time */
151 OptDateTime ((unsigned long) time(0));
153 /* Release memory for the string */
159 static void NewSymbol (const char* SymName, long Val)
160 /* Define a symbol with a fixed numeric value in the current scope */
165 /* Convert the name to a string buffer */
166 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
167 SB_CopyStr (&SymBuf, SymName);
169 /* Search for the symbol, allocate a new one if it doesn't exist */
170 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
172 /* Check if have already a symbol with this name */
173 if (SymIsDef (Sym)) {
174 AbEnd ("`%s' is already defined", SymName);
177 /* Generate an expression for the symbol */
178 Expr = GenLiteralExpr (Val);
180 /* Mark the symbol as defined */
181 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
183 /* Free string buffer memory */
189 static void CBMSystem (const char* Sys)
190 /* Define a CBM system */
192 NewSymbol ("__CBM__", 1);
198 static void SetSys (const char* Sys)
199 /* Define a target system */
201 switch (Target = FindTarget (Sys)) {
207 AbEnd ("Cannot use `module' as a target for the assembler");
211 NewSymbol ("__ATARI__", 1);
215 CBMSystem ("__C16__");
219 CBMSystem ("__C64__");
223 CBMSystem ("__VIC20__");
227 CBMSystem ("__C128__");
231 CBMSystem ("__PLUS4__");
235 CBMSystem ("__CBM510__");
239 CBMSystem ("__CBM610__");
243 CBMSystem ("__PET__");
247 NewSymbol ("__BBC__", 1);
251 NewSymbol ("__APPLE2__", 1);
255 NewSymbol ("__APPLE2ENH__", 1);
259 /* Do not handle as a CBM system */
260 NewSymbol ("__GEOS__", 1);
261 NewSymbol ("__GEOS_CBM__", 1);
265 NewSymbol ("__GEOS__", 1);
266 NewSymbol ("__GEOS_APPLE__", 1);
270 NewSymbol ("__LUNIX__", 1);
274 NewSymbol ("__ATMOS__", 1);
278 NewSymbol ("__NES__", 1);
281 case TGT_SUPERVISION:
282 NewSymbol ("__SUPERVISION__", 1);
286 NewSymbol ("__LYNX__", 1);
290 AbEnd ("Invalid target name: `%s'", Sys);
294 /* Initialize the translation tables for the target system */
300 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
301 /* Handle an option that remembers a file name for later */
303 /* Cannot have the option twice */
304 if (SB_NotEmpty (Name)) {
305 AbEnd ("Cannot use option `%s' twice", Opt);
307 /* Remember the file name for later */
308 SB_CopyStr (Name, Arg);
314 static void DefineSymbol (const char* Def)
315 /* Define a symbol from the command line */
320 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
323 /* The symbol must start with a character or underline */
324 if (!IsIdStart (Def [0])) {
329 /* Copy the symbol, checking the rest */
331 while (IsIdChar (*P)) {
332 SB_AppendChar (&SymName, *P++);
334 SB_Terminate (&SymName);
336 /* Do we have a value given? */
343 /* We have a value */
347 if (sscanf (P, "%lx", &Val) != 1) {
351 if (sscanf (P, "%li", &Val) != 1) {
357 /* Define the new symbol */
358 NewSymbol (SB_GetConstBuf (&SymName), Val);
360 /* Release string memory */
366 static void OptAutoImport (const char* Opt attribute ((unused)),
367 const char* Arg attribute ((unused)))
368 /* Mark unresolved symbols as imported */
375 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
376 /* Add an include search path for binaries */
378 AddSearchPath (BinSearchPath, Arg);
383 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
384 /* Handle the --cpu option */
386 cpu_t CPU = FindCPU (Arg);
387 if (CPU == CPU_UNKNOWN) {
388 AbEnd ("Invalid CPU: `%s'", Arg);
396 static void OptCreateDep (const char* Opt, const char* Arg)
397 /* Handle the --create-dep option */
399 FileNameOption (Opt, Arg, &DepName);
404 static void OptCreateFullDep (const char* Opt attribute ((unused)),
406 /* Handle the --create-full-dep option */
408 FileNameOption (Opt, Arg, &FullDepName);
413 static void OptDebug (const char* Opt attribute ((unused)),
414 const char* Arg attribute ((unused)))
415 /* Compiler debug mode */
422 static void OptDebugInfo (const char* Opt attribute ((unused)),
423 const char* Arg attribute ((unused)))
424 /* Add debug info to the object file */
431 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
432 /* Set an emulation feature */
434 /* Make a string buffer from Arg */
437 /* Set the feature, check for errors */
438 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
439 AbEnd ("Illegal emulation feature: `%s'", Arg);
445 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
446 const char* Arg attribute ((unused)))
447 /* Forget all currently defined include paths */
449 ForgetAllIncludePaths ();
454 static void OptHelp (const char* Opt attribute ((unused)),
455 const char* Arg attribute ((unused)))
456 /* Print usage information and exit */
464 static void OptIgnoreCase (const char* Opt attribute ((unused)),
465 const char* Arg attribute ((unused)))
466 /* Ignore case on symbols */
473 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
474 /* Add an include search path */
476 AddSearchPath (IncSearchPath, Arg);
481 static void OptLargeAlignment (const char* Opt attribute ((unused)),
482 const char* Arg attribute ((unused)))
483 /* Don't warn about large alignments */
490 static void OptListBytes (const char* Opt, const char* Arg)
491 /* Set the maximum number of bytes per listing line */
496 /* Convert the argument to a number */
497 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
501 /* Check the bounds */
502 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
503 AbEnd ("Argument for option `%s' is out of range", Opt);
512 static void OptListing (const char* Opt, const char* Arg)
513 /* Create a listing file */
515 /* Since the meaning of -l and --listing has changed, print an error if
516 * the filename is empty or begins with the option char.
518 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
519 Fatal ("The meaning of `%s' has changed. It does now "
520 "expect a file name as argument.", Opt);
523 /* Get the file name */
524 FileNameOption (Opt, Arg, &ListingName);
529 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
530 /* Set a macro package directory */
532 /* Make a string buffer from Arg */
535 /* Use the directory */
536 MacPackSetDir (SB_InitFromString (&Dir, Arg));
541 static void OptMemoryModel (const char* Opt, const char* Arg)
542 /* Set the memory model */
546 /* Check the current memory model */
547 if (MemoryModel != MMODEL_UNKNOWN) {
548 AbEnd ("Cannot use option `%s' twice", Opt);
551 /* Translate the memory model name and check it */
552 M = FindMemoryModel (Arg);
553 if (M == MMODEL_UNKNOWN) {
554 AbEnd ("Unknown memory model: %s", Arg);
555 } else if (M == MMODEL_HUGE) {
556 AbEnd ("Unsupported memory model: %s", Arg);
559 /* Set the memory model */
565 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
566 /* Handle the --pagelength option */
568 int Len = atoi (Arg);
569 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
570 AbEnd ("Invalid page length: %d", Len);
577 static void OptRelaxChecks (const char* Opt attribute ((unused)),
578 const char* Arg attribute ((unused)))
579 /* Handle the --relax-checks options */
586 static void OptSmart (const char* Opt attribute ((unused)),
587 const char* Arg attribute ((unused)))
588 /* Handle the -s/--smart options */
595 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
596 /* Set the target system */
603 static void OptVerbose (const char* Opt attribute ((unused)),
604 const char* Arg attribute ((unused)))
605 /* Increase verbosity */
612 static void OptVersion (const char* Opt attribute ((unused)),
613 const char* Arg attribute ((unused)))
614 /* Print the assembler version */
616 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
621 static void DoPCAssign (void)
622 /* Start absolute code */
624 long PC = ConstExpression ();
625 if (PC < 0 || PC > 0xFFFFFF) {
626 Error ("Range error");
628 EnterAbsoluteMode (PC);
634 static void OneLine (void)
635 /* Assemble one line */
638 unsigned long PC = 0;
643 /* Initialize the new listing line if we are actually reading from file
644 * and not from internally pushed input.
646 if (!HavePushedInput ()) {
650 /* Single colon means unnamed label */
651 if (CurTok.Tok == TOK_COLON) {
656 /* If the first token on the line is an identifier, check for a macro or
659 if (CurTok.Tok == TOK_IDENT) {
660 if (!UbiquitousIdents) {
661 /* Macros and symbols cannot use instruction names */
662 Instr = FindInstruction (&CurTok.SVal);
664 Mac = FindMacro (&CurTok.SVal);
667 /* Macros and symbols may use the names of instructions */
668 Mac = FindMacro (&CurTok.SVal);
672 /* Handle an identifier. This may be a cheap local symbol, or a fully
673 * scoped identifier which may start with a namespace token (for global
676 if (CurTok.Tok == TOK_LOCAL_IDENT ||
677 CurTok.Tok == TOK_NAMESPACE ||
678 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
680 /* Did we have whitespace before the ident? */
681 int HadWS = CurTok.WS;
683 /* Generate the symbol table entry, then skip the name */
684 Sym = ParseAnySymName (SYM_ALLOC_NEW);
686 /* If a colon follows, this is a label definition. If there
687 * is no colon, it's an assignment.
689 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
691 /* Determine the symbol flags from the assignment token */
692 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
697 /* Define the symbol with the expression following the '=' */
698 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
700 /* Don't allow anything after a symbol definition */
704 } else if (CurTok.Tok == TOK_SET) {
708 /* .SET defines variables (= redefinable symbols) */
711 /* Read the assignment expression, which must be constant */
712 Expr = GenLiteralExpr (ConstExpression ());
714 /* Define the symbol with the constant expression following
717 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
719 /* Don't allow anything after a symbol definition */
725 /* A label. Remember the current segment, so we can later
726 * determine the size of the data stored under the label.
731 /* Define the label */
732 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
734 /* Skip the colon. If NoColonLabels is enabled, allow labels
735 * without a colon if there is no whitespace before the
738 if (CurTok.Tok != TOK_COLON) {
739 if (HadWS || !NoColonLabels) {
740 Error ("`:' expected");
741 /* Try some smart error recovery */
742 if (CurTok.Tok == TOK_NAMESPACE) {
751 /* If we come here, a new identifier may be waiting, which may
752 * be a macro or instruction.
754 if (CurTok.Tok == TOK_IDENT) {
755 if (!UbiquitousIdents) {
756 /* Macros and symbols cannot use instruction names */
757 Instr = FindInstruction (&CurTok.SVal);
759 Mac = FindMacro (&CurTok.SVal);
762 /* Macros and symbols may use the names of instructions */
763 Mac = FindMacro (&CurTok.SVal);
769 /* We've handled a possible label, now handle the remainder of the line */
770 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
771 /* A control command */
773 } else if (Mac != 0) {
774 /* A macro expansion */
775 MacExpandStart (Mac);
776 } else if (Instr >= 0 ||
777 (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
778 /* A mnemonic - assemble one instruction */
779 HandleInstruction (Instr);
780 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
782 if (CurTok.Tok != TOK_EQ) {
783 Error ("`=' expected");
786 /* Skip the equal sign */
788 /* Enter absolute mode */
793 /* If we have defined a label, remember its size. Sym is also set by
794 * a symbol assignment, but in this case Done is false, so we don't
799 if (Seg == ActiveSeg) {
801 Size = GetPC () - PC;
803 /* The line has switched the segment */
806 DefSizeOfSymbol (Sym, Size);
809 /* Line separator must come here */
815 static void Assemble (void)
816 /* Start the ball rolling ... */
821 /* Assemble lines until end of file */
822 while (CurTok.Tok != TOK_EOF) {
829 static void CreateObjFile (void)
830 /* Create the object file */
832 /* Open the object, write the header */
835 /* Write the object file options */
838 /* Write the list of input files */
841 /* Write the segment data to the file */
844 /* Write the import list */
847 /* Write the export list */
850 /* Write debug symbols if requested */
853 /* Write the scopes if requested */
856 /* Write line infos if requested */
859 /* Write the string pool */
862 /* Write the assertions */
865 /* Write the spans */
868 /* Write an updated header and close the file */
874 int main (int argc, char* argv [])
875 /* Assembler main program */
877 /* Program long options */
878 static const LongOpt OptTab[] = {
879 { "--auto-import", 0, OptAutoImport },
880 { "--bin-include-dir", 1, OptBinIncludeDir },
881 { "--cpu", 1, OptCPU },
882 { "--create-dep", 1, OptCreateDep },
883 { "--create-full-dep", 1, OptCreateFullDep },
884 { "--debug", 0, OptDebug },
885 { "--debug-info", 0, OptDebugInfo },
886 { "--feature", 1, OptFeature },
887 { "--forget-inc-paths", 0, OptForgetIncPaths },
888 { "--help", 0, OptHelp },
889 { "--ignore-case", 0, OptIgnoreCase },
890 { "--include-dir", 1, OptIncludeDir },
891 { "--large-alignment", 0, OptLargeAlignment },
892 { "--list-bytes", 1, OptListBytes },
893 { "--listing", 1, OptListing },
894 { "--macpack-dir", 1, OptMacPackDir },
895 { "--memory-model", 1, OptMemoryModel },
896 { "--pagelength", 1, OptPageLength },
897 { "--relax-checks", 0, OptRelaxChecks },
898 { "--smart", 0, OptSmart },
899 { "--target", 1, OptTarget },
900 { "--verbose", 0, OptVerbose },
901 { "--version", 0, OptVersion },
904 /* Name of the global name space */
905 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
909 /* Initialize the cmdline module */
910 InitCmdLine (&argc, &argv, "ca65");
912 /* Initialize the string pool */
915 /* Initialize the include search paths */
918 /* Create the predefined segments */
921 /* Enter the base lexical level. We must do that here, since we may
922 * define symbols using -D.
924 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
926 /* Initialize the line infos. Must be done here, since we need line infos
927 * for symbol definitions.
931 /* Check the parameters */
933 while (I < ArgCount) {
935 /* Get the argument */
936 const char* Arg = ArgVec [I];
938 /* Check for an option */
943 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
951 OptDebugInfo (Arg, 0);
959 OptIgnoreCase (Arg, 0);
963 OptListing (Arg, GetArg (&I, 2));
968 OptMemoryModel (Arg, GetArg (&I, 3));
975 OutFile = GetArg (&I, 2);
983 OptTarget (Arg, GetArg (&I, 2));
991 DefineSymbol (GetArg (&I, 2));
995 OptIncludeDir (Arg, GetArg (&I, 2));
999 OptAutoImport (Arg, 0);
1003 OptVersion (Arg, 0);
1007 WarnLevel = atoi (GetArg (&I, 2));
1011 UnknownOption (Arg);
1016 /* Filename. Check if we already had one */
1018 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
1020 exit (EXIT_FAILURE);
1030 /* Do we have an input file? */
1032 fprintf (stderr, "%s: No input files\n", ProgName);
1033 exit (EXIT_FAILURE);
1036 /* If no CPU given, use the default CPU for the target */
1037 if (GetCPU () == CPU_UNKNOWN) {
1038 if (Target != TGT_UNKNOWN) {
1039 SetCPU (GetTargetProperties (Target)->DefaultCPU);
1045 /* If no memory model was given, use the default */
1046 if (MemoryModel == MMODEL_UNKNOWN) {
1047 SetMemoryModel (MMODEL_NEAR);
1050 /* Set the default segment sizes according to the memory model */
1053 /* Initialize the scanner, open the input file */
1054 InitScanner (InFile);
1056 /* Define the default options */
1059 /* Assemble the input */
1062 /* If we didn't have any errors, check the pseudo insn stacks */
1063 if (ErrorCount == 0) {
1067 /* If we didn't have any errors, check and cleanup the unnamed labels */
1068 if (ErrorCount == 0) {
1072 /* If we didn't have any errors, check the symbol table */
1073 if (ErrorCount == 0) {
1077 /* If we didn't have any errors, check the hll debug symbols */
1078 if (ErrorCount == 0) {
1082 /* If we didn't have any errors, close the file scope lexical level */
1083 if (ErrorCount == 0) {
1087 /* If we didn't have any errors, check and resolve the segment data */
1088 if (ErrorCount == 0) {
1092 /* If we didn't have any errors, check the assertions */
1093 if (ErrorCount == 0) {
1098 if (Verbosity >= 2) {
1103 /* If we didn't have an errors, finish off the line infos */
1106 /* If we didn't have any errors, create the object, listing and
1109 if (ErrorCount == 0) {
1111 if (SB_GetLen (&ListingName) > 0) {
1114 CreateDependencies ();
1117 /* Close the input file */
1120 /* Return an apropriate exit code */
1121 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;