1 /*****************************************************************************/
5 /* Main program for the ca65 macroassembler */
9 /* (C) 1998-2011, 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 /*****************************************************************************/
47 #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 " -g\t\t\t\tAdd debug info to object file\n"
101 " -h\t\t\t\tHelp (this text)\n"
102 " -i\t\t\t\tIgnore case of symbols\n"
103 " -l name\t\t\tCreate a listing file if assembly was ok\n"
104 " -mm model\t\t\tSet the memory model\n"
105 " -o name\t\t\tName the output file\n"
106 " -s\t\t\t\tEnable smart mode\n"
107 " -t sys\t\t\tSet the target system\n"
108 " -v\t\t\t\tIncrease verbosity\n"
111 " --auto-import\t\t\tMark unresolved symbols as import\n"
112 " --bin-include-dir dir\t\tSet a search path for binary includes\n"
113 " --cpu type\t\t\tSet cpu type\n"
114 " --create-dep name\t\tCreate a make dependency file\n"
115 " --create-full-dep name\tCreate a full make dependency file\n"
116 " --debug-info\t\t\tAdd debug info to object file\n"
117 " --feature name\t\tSet an emulation feature\n"
118 " --forget-inc-paths\t\tForget include search paths\n"
119 " --help\t\t\tHelp (this text)\n"
120 " --ignore-case\t\t\tIgnore case of symbols\n"
121 " --include-dir dir\t\tSet an include directory search path\n"
122 " --large-alignment\t\tDon't warn about large alignments\n"
123 " --listing name\t\tCreate a listing file if assembly was ok\n"
124 " --list-bytes n\t\tMaximum number of bytes per listing line\n"
125 " --macpack-dir dir\t\tSet a macro package directory\n"
126 " --memory-model model\t\tSet the memory model\n"
127 " --pagelength n\t\tSet the page length for the listing\n"
128 " --smart\t\t\tEnable smart mode\n"
129 " --target sys\t\t\tSet the target system\n"
130 " --verbose\t\t\tIncrease verbosity\n"
131 " --version\t\t\tPrint the assembler version\n",
137 static void SetOptions (void)
138 /* Set the option for the translator */
140 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
142 /* Set the translator */
143 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
144 OptTranslator (&Buf);
146 /* Set date and time */
147 OptDateTime ((unsigned long) time(0));
149 /* Release memory for the string */
155 static void NewSymbol (const char* SymName, long Val)
156 /* Define a symbol with a fixed numeric value in the current scope */
161 /* Convert the name to a string buffer */
162 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
163 SB_CopyStr (&SymBuf, SymName);
165 /* Search for the symbol, allocate a new one if it doesn't exist */
166 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
168 /* Check if have already a symbol with this name */
169 if (SymIsDef (Sym)) {
170 AbEnd ("`%s' is already defined", SymName);
173 /* Generate an expression for the symbol */
174 Expr = GenLiteralExpr (Val);
176 /* Mark the symbol as defined */
177 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
179 /* Free string buffer memory */
185 static void CBMSystem (const char* Sys)
186 /* Define a CBM system */
188 NewSymbol ("__CBM__", 1);
194 static void SetSys (const char* Sys)
195 /* Define a target system */
197 switch (Target = FindTarget (Sys)) {
203 AbEnd ("Cannot use `module' as a target for the assembler");
207 NewSymbol ("__ATARI__", 1);
211 CBMSystem ("__C16__");
215 CBMSystem ("__C64__");
219 CBMSystem ("__VIC20__");
223 CBMSystem ("__C128__");
227 CBMSystem ("__PLUS4__");
231 CBMSystem ("__CBM510__");
235 CBMSystem ("__CBM610__");
239 CBMSystem ("__PET__");
243 NewSymbol ("__BBC__", 1);
247 NewSymbol ("__APPLE2__", 1);
251 NewSymbol ("__APPLE2ENH__", 1);
255 /* Do not handle as a CBM system */
256 NewSymbol ("__GEOS__", 1);
260 NewSymbol ("__LUNIX__", 1);
264 NewSymbol ("__ATMOS__", 1);
268 NewSymbol ("__NES__", 1);
271 case TGT_SUPERVISION:
272 NewSymbol ("__SUPERVISION__", 1);
276 NewSymbol ("__LYNX__", 1);
280 AbEnd ("Invalid target name: `%s'", Sys);
284 /* Initialize the translation tables for the target system */
290 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
291 /* Handle an option that remembers a file name for later */
293 /* Cannot have the option twice */
294 if (SB_NotEmpty (Name)) {
295 AbEnd ("Cannot use option `%s' twice", Opt);
297 /* Remember the file name for later */
298 SB_CopyStr (Name, Arg);
304 static void DefineSymbol (const char* Def)
305 /* Define a symbol from the command line */
310 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
313 /* The symbol must start with a character or underline */
314 if (!IsIdStart (Def [0])) {
319 /* Copy the symbol, checking the rest */
321 while (IsIdChar (*P)) {
322 SB_AppendChar (&SymName, *P++);
324 SB_Terminate (&SymName);
326 /* Do we have a value given? */
333 /* We have a value */
337 if (sscanf (P, "%lx", &Val) != 1) {
341 if (sscanf (P, "%li", &Val) != 1) {
347 /* Define the new symbol */
348 NewSymbol (SB_GetConstBuf (&SymName), Val);
350 /* Release string memory */
356 static void OptAutoImport (const char* Opt attribute ((unused)),
357 const char* Arg attribute ((unused)))
358 /* Mark unresolved symbols as imported */
365 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
366 /* Add an include search path for binaries */
368 AddSearchPath (BinSearchPath, Arg);
373 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
374 /* Handle the --cpu option */
376 cpu_t CPU = FindCPU (Arg);
377 if (CPU == CPU_UNKNOWN) {
378 AbEnd ("Invalid CPU: `%s'", Arg);
386 static void OptCreateDep (const char* Opt, const char* Arg)
387 /* Handle the --create-dep option */
389 FileNameOption (Opt, Arg, &DepName);
394 static void OptCreateFullDep (const char* Opt attribute ((unused)),
396 /* Handle the --create-full-dep option */
398 FileNameOption (Opt, Arg, &FullDepName);
403 static void OptDebugInfo (const char* Opt attribute ((unused)),
404 const char* Arg attribute ((unused)))
405 /* Add debug info to the object file */
412 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
413 /* Set an emulation feature */
415 /* Make a string buffer from Arg */
418 /* Set the feature, check for errors */
419 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
420 AbEnd ("Illegal emulation feature: `%s'", Arg);
426 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
427 const char* Arg attribute ((unused)))
428 /* Forget all currently defined include paths */
430 ForgetAllIncludePaths ();
435 static void OptHelp (const char* Opt attribute ((unused)),
436 const char* Arg attribute ((unused)))
437 /* Print usage information and exit */
445 static void OptIgnoreCase (const char* Opt attribute ((unused)),
446 const char* Arg attribute ((unused)))
447 /* Ignore case on symbols */
454 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
455 /* Add an include search path */
457 AddSearchPath (IncSearchPath, Arg);
462 static void OptLargeAlignment (const char* Opt attribute ((unused)),
463 const char* Arg attribute ((unused)))
464 /* Don't warn about large alignments */
471 static void OptListBytes (const char* Opt, const char* Arg)
472 /* Set the maximum number of bytes per listing line */
477 /* Convert the argument to a number */
478 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
482 /* Check the bounds */
483 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
484 AbEnd ("Argument for option `%s' is out of range", Opt);
493 static void OptListing (const char* Opt, const char* Arg)
494 /* Create a listing file */
496 /* Since the meaning of -l and --listing has changed, print an error if
497 * the filename is empty or begins with the option char.
499 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
500 Fatal ("The meaning of `%s' has changed. It does now "
501 "expect a file name as argument.", Opt);
504 /* Get the file name */
505 FileNameOption (Opt, Arg, &ListingName);
510 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
511 /* Set a macro package directory */
513 /* Make a string buffer from Arg */
516 /* Use the directory */
517 MacPackSetDir (SB_InitFromString (&Dir, Arg));
522 static void OptMemoryModel (const char* Opt, const char* Arg)
523 /* Set the memory model */
527 /* Check the current memory model */
528 if (MemoryModel != MMODEL_UNKNOWN) {
529 AbEnd ("Cannot use option `%s' twice", Opt);
532 /* Translate the memory model name and check it */
533 M = FindMemoryModel (Arg);
534 if (M == MMODEL_UNKNOWN) {
535 AbEnd ("Unknown memory model: %s", Arg);
536 } else if (M == MMODEL_HUGE) {
537 AbEnd ("Unsupported memory model: %s", Arg);
540 /* Set the memory model */
546 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
547 /* Handle the --pagelength option */
549 int Len = atoi (Arg);
550 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
551 AbEnd ("Invalid page length: %d", Len);
558 static void OptSmart (const char* Opt attribute ((unused)),
559 const char* Arg attribute ((unused)))
560 /* Handle the -s/--smart options */
567 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
568 /* Set the target system */
575 static void OptVerbose (const char* Opt attribute ((unused)),
576 const char* Arg attribute ((unused)))
577 /* Increase verbosity */
584 static void OptVersion (const char* Opt attribute ((unused)),
585 const char* Arg attribute ((unused)))
586 /* Print the assembler version */
588 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
593 static void DoPCAssign (void)
594 /* Start absolute code */
596 long PC = ConstExpression ();
597 if (PC < 0 || PC > 0xFFFFFF) {
598 Error ("Range error");
600 EnterAbsoluteMode (PC);
606 static void OneLine (void)
607 /* Assemble one line */
610 unsigned long PC = 0;
615 /* Initialize the new listing line if we are actually reading from file
616 * and not from internally pushed input.
618 if (!HavePushedInput ()) {
622 /* Single colon means unnamed label */
623 if (CurTok.Tok == TOK_COLON) {
628 /* If the first token on the line is an identifier, check for a macro or
631 if (CurTok.Tok == TOK_IDENT) {
632 if (!UbiquitousIdents) {
633 /* Macros and symbols cannot use instruction names */
634 Instr = FindInstruction (&CurTok.SVal);
636 Mac = FindMacro (&CurTok.SVal);
639 /* Macros and symbols may use the names of instructions */
640 Mac = FindMacro (&CurTok.SVal);
644 /* Handle an identifier. This may be a cheap local symbol, or a fully
645 * scoped identifier which may start with a namespace token (for global
648 if (CurTok.Tok == TOK_LOCAL_IDENT ||
649 CurTok.Tok == TOK_NAMESPACE ||
650 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
652 /* Did we have whitespace before the ident? */
653 int HadWS = CurTok.WS;
655 /* Generate the symbol table entry, then skip the name */
656 Sym = ParseAnySymName (SYM_ALLOC_NEW);
658 /* If a colon follows, this is a label definition. If there
659 * is no colon, it's an assignment.
661 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
663 /* Determine the symbol flags from the assignment token */
664 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
669 /* Define the symbol with the expression following the '=' */
670 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
672 /* Don't allow anything after a symbol definition */
676 } else if (CurTok.Tok == TOK_SET) {
680 /* .SET defines variables (= redefinable symbols) */
683 /* Read the assignment expression, which must be constant */
684 Expr = GenLiteralExpr (ConstExpression ());
686 /* Define the symbol with the constant expression following
689 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
691 /* Don't allow anything after a symbol definition */
697 /* A label. Remember the current segment, so we can later
698 * determine the size of the data stored under the label.
703 /* Define the label */
704 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
706 /* Skip the colon. If NoColonLabels is enabled, allow labels
707 * without a colon if there is no whitespace before the
710 if (CurTok.Tok != TOK_COLON) {
711 if (HadWS || !NoColonLabels) {
712 Error ("`:' expected");
713 /* Try some smart error recovery */
714 if (CurTok.Tok == TOK_NAMESPACE) {
723 /* If we come here, a new identifier may be waiting, which may
724 * be a macro or instruction.
726 if (CurTok.Tok == TOK_IDENT) {
727 if (!UbiquitousIdents) {
728 /* Macros and symbols cannot use instruction names */
729 Instr = FindInstruction (&CurTok.SVal);
731 Mac = FindMacro (&CurTok.SVal);
734 /* Macros and symbols may use the names of instructions */
735 Mac = FindMacro (&CurTok.SVal);
741 /* We've handled a possible label, now handle the remainder of the line */
742 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
743 /* A control command */
745 } else if (Mac != 0) {
746 /* A macro expansion */
747 MacExpandStart (Mac);
748 } else if (Instr >= 0 ||
749 (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
750 /* A mnemonic - assemble one instruction */
751 HandleInstruction (Instr);
752 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
754 if (CurTok.Tok != TOK_EQ) {
755 Error ("`=' expected");
758 /* Skip the equal sign */
760 /* Enter absolute mode */
765 /* If we have defined a label, remember its size. Sym is also set by
766 * a symbol assignment, but in this case Done is false, so we don't
771 if (Seg == ActiveSeg) {
773 Size = GetPC () - PC;
775 /* The line has switched the segment */
778 DefSizeOfSymbol (Sym, Size);
781 /* Line separator must come here */
787 static void Assemble (void)
788 /* Start the ball rolling ... */
793 /* Assemble lines until end of file */
794 while (CurTok.Tok != TOK_EOF) {
801 static void CreateObjFile (void)
802 /* Create the object file */
804 /* Open the object, write the header */
807 /* Write the object file options */
810 /* Write the list of input files */
813 /* Write the segment data to the file */
816 /* Write the import list */
819 /* Write the export list */
822 /* Write debug symbols if requested */
825 /* Write the scopes if requested */
828 /* Write line infos if requested */
831 /* Write the string pool */
834 /* Write the assertions */
837 /* Write the spans */
840 /* Write an updated header and close the file */
846 int main (int argc, char* argv [])
847 /* Assembler main program */
849 /* Program long options */
850 static const LongOpt OptTab[] = {
851 { "--auto-import", 0, OptAutoImport },
852 { "--bin-include-dir", 1, OptBinIncludeDir },
853 { "--cpu", 1, OptCPU },
854 { "--create-dep", 1, OptCreateDep },
855 { "--create-full-dep", 1, OptCreateFullDep },
856 { "--debug-info", 0, OptDebugInfo },
857 { "--feature", 1, OptFeature },
858 { "--forget-inc-paths", 0, OptForgetIncPaths },
859 { "--help", 0, OptHelp },
860 { "--ignore-case", 0, OptIgnoreCase },
861 { "--include-dir", 1, OptIncludeDir },
862 { "--large-alignment", 0, OptLargeAlignment },
863 { "--list-bytes", 1, OptListBytes },
864 { "--listing", 1, OptListing },
865 { "--macpack-dir", 1, OptMacPackDir },
866 { "--memory-model", 1, OptMemoryModel },
867 { "--pagelength", 1, OptPageLength },
868 { "--smart", 0, OptSmart },
869 { "--target", 1, OptTarget },
870 { "--verbose", 0, OptVerbose },
871 { "--version", 0, OptVersion },
874 /* Name of the global name space */
875 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
879 /* Initialize the cmdline module */
880 InitCmdLine (&argc, &argv, "ca65");
882 /* Initialize the string pool */
885 /* Initialize the include search paths */
888 /* Create the predefined segments */
891 /* Enter the base lexical level. We must do that here, since we may
892 * define symbols using -D.
894 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
896 /* Initialize the line infos. Must be done here, since we need line infos
897 * for symbol definitions.
901 /* Check the parameters */
903 while (I < ArgCount) {
905 /* Get the argument */
906 const char* Arg = ArgVec [I];
908 /* Check for an option */
913 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
917 OptDebugInfo (Arg, 0);
925 OptIgnoreCase (Arg, 0);
929 OptListing (Arg, GetArg (&I, 2));
934 OptMemoryModel (Arg, GetArg (&I, 3));
941 OutFile = GetArg (&I, 2);
949 OptTarget (Arg, GetArg (&I, 2));
957 DefineSymbol (GetArg (&I, 2));
961 OptIncludeDir (Arg, GetArg (&I, 2));
965 OptAutoImport (Arg, 0);
973 WarnLevel = atoi (GetArg (&I, 2));
982 /* Filename. Check if we already had one */
984 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
996 /* Do we have an input file? */
998 fprintf (stderr, "%s: No input files\n", ProgName);
1002 /* If no CPU given, use the default CPU for the target */
1003 if (GetCPU () == CPU_UNKNOWN) {
1004 if (Target != TGT_UNKNOWN) {
1005 SetCPU (DefaultCPU[Target]);
1011 /* If no memory model was given, use the default */
1012 if (MemoryModel == MMODEL_UNKNOWN) {
1013 SetMemoryModel (MMODEL_NEAR);
1016 /* Set the default segment sizes according to the memory model */
1019 /* Initialize the scanner, open the input file */
1020 InitScanner (InFile);
1022 /* Define the default options */
1025 /* Assemble the input */
1028 /* If we didn't have any errors, check the pseudo insn stacks */
1029 if (ErrorCount == 0) {
1033 /* If we didn't have any errors, check and cleanup the unnamed labels */
1034 if (ErrorCount == 0) {
1038 /* If we didn't have any errors, check the symbol table */
1039 if (ErrorCount == 0) {
1043 /* If we didn't have any errors, check the hll debug symbols */
1044 if (ErrorCount == 0) {
1048 /* If we didn't have any errors, close the file scope lexical level */
1049 if (ErrorCount == 0) {
1053 /* If we didn't have any errors, check and resolve the segment data */
1054 if (ErrorCount == 0) {
1058 /* If we didn't have any errors, check the assertions */
1059 if (ErrorCount == 0) {
1064 if (Verbosity >= 2) {
1069 /* If we didn't have an errors, finish off the line infos */
1072 /* If we didn't have any errors, create the object, listing and
1075 if (ErrorCount == 0) {
1077 if (SB_GetLen (&ListingName) > 0) {
1080 CreateDependencies ();
1083 /* Close the input file */
1086 /* Return an apropriate exit code */
1087 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;