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"
82 /*****************************************************************************/
84 /*****************************************************************************/
88 static void Usage (void)
89 /* Print usage information and exit */
91 printf ("Usage: %s [options] file\n"
93 " -D name[=value]\t\tDefine a symbol\n"
94 " -I dir\t\t\tSet an include directory search path\n"
95 " -U\t\t\t\tMark unresolved symbols as import\n"
96 " -V\t\t\t\tPrint the assembler version\n"
97 " -W n\t\t\t\tSet warning level n\n"
98 " -g\t\t\t\tAdd debug info to object file\n"
99 " -h\t\t\t\tHelp (this text)\n"
100 " -i\t\t\t\tIgnore case of symbols\n"
101 " -l name\t\t\tCreate a listing file if assembly was ok\n"
102 " -mm model\t\t\tSet the memory model\n"
103 " -o name\t\t\tName the output file\n"
104 " -s\t\t\t\tEnable smart mode\n"
105 " -t sys\t\t\tSet the target system\n"
106 " -v\t\t\t\tIncrease verbosity\n"
109 " --auto-import\t\t\tMark unresolved symbols as import\n"
110 " --bin-include-dir dir\t\tSet a search path for binary includes\n"
111 " --cpu type\t\t\tSet cpu type\n"
112 " --create-dep name\t\tCreate a make dependency file\n"
113 " --create-full-dep name\tCreate a full make dependency file\n"
114 " --debug-info\t\t\tAdd debug info to object file\n"
115 " --feature name\t\tSet an emulation feature\n"
116 " --forget-inc-paths\t\tForget include search paths\n"
117 " --help\t\t\tHelp (this text)\n"
118 " --ignore-case\t\t\tIgnore case of symbols\n"
119 " --include-dir dir\t\tSet an include directory search path\n"
120 " --listing name\t\tCreate a listing file if assembly was ok\n"
121 " --list-bytes n\t\tMaximum number of bytes per listing line\n"
122 " --macpack-dir dir\t\tSet a macro package directory\n"
123 " --memory-model model\t\tSet the memory model\n"
124 " --pagelength n\t\tSet the page length for the listing\n"
125 " --smart\t\t\tEnable smart mode\n"
126 " --target sys\t\t\tSet the target system\n"
127 " --verbose\t\t\tIncrease verbosity\n"
128 " --version\t\t\tPrint the assembler version\n",
134 static void SetOptions (void)
135 /* Set the option for the translator */
137 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
139 /* Set the translator */
140 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
141 OptTranslator (&Buf);
143 /* Set date and time */
144 OptDateTime ((unsigned long) time(0));
146 /* Release memory for the string */
152 static void NewSymbol (const char* SymName, long Val)
153 /* Define a symbol with a fixed numeric value in the current scope */
158 /* Convert the name to a string buffer */
159 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
160 SB_CopyStr (&SymBuf, SymName);
162 /* Search for the symbol, allocate a new one if it doesn't exist */
163 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
165 /* Check if have already a symbol with this name */
166 if (SymIsDef (Sym)) {
167 AbEnd ("`%s' is already defined", SymName);
170 /* Generate an expression for the symbol */
171 Expr = GenLiteralExpr (Val);
173 /* Mark the symbol as defined */
174 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
176 /* Free string buffer memory */
182 static void CBMSystem (const char* Sys)
183 /* Define a CBM system */
185 NewSymbol ("__CBM__", 1);
191 static void SetSys (const char* Sys)
192 /* Define a target system */
194 switch (Target = FindTarget (Sys)) {
200 AbEnd ("Cannot use `module' as a target for the assembler");
204 NewSymbol ("__ATARI__", 1);
208 CBMSystem ("__C16__");
212 CBMSystem ("__C64__");
216 CBMSystem ("__VIC20__");
220 CBMSystem ("__C128__");
224 CBMSystem ("__PLUS4__");
228 CBMSystem ("__CBM510__");
232 CBMSystem ("__CBM610__");
236 CBMSystem ("__PET__");
240 NewSymbol ("__BBC__", 1);
244 NewSymbol ("__APPLE2__", 1);
248 NewSymbol ("__APPLE2ENH__", 1);
252 /* Do not handle as a CBM system */
253 NewSymbol ("__GEOS__", 1);
257 NewSymbol ("__LUNIX__", 1);
261 NewSymbol ("__ATMOS__", 1);
265 NewSymbol ("__NES__", 1);
268 case TGT_SUPERVISION:
269 NewSymbol ("__SUPERVISION__", 1);
273 NewSymbol ("__LYNX__", 1);
277 AbEnd ("Invalid target name: `%s'", Sys);
281 /* Initialize the translation tables for the target system */
287 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
288 /* Handle an option that remembers a file name for later */
290 /* Cannot have the option twice */
291 if (SB_NotEmpty (Name)) {
292 AbEnd ("Cannot use option `%s' twice", Opt);
294 /* Remember the file name for later */
295 SB_CopyStr (Name, Arg);
301 static void DefineSymbol (const char* Def)
302 /* Define a symbol from the command line */
307 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
310 /* The symbol must start with a character or underline */
311 if (!IsIdStart (Def [0])) {
316 /* Copy the symbol, checking the rest */
318 while (IsIdChar (*P)) {
319 SB_AppendChar (&SymName, *P++);
321 SB_Terminate (&SymName);
323 /* Do we have a value given? */
330 /* We have a value */
334 if (sscanf (P, "%lx", &Val) != 1) {
338 if (sscanf (P, "%li", &Val) != 1) {
344 /* Define the new symbol */
345 NewSymbol (SB_GetConstBuf (&SymName), Val);
347 /* Release string memory */
353 static void OptAutoImport (const char* Opt attribute ((unused)),
354 const char* Arg attribute ((unused)))
355 /* Mark unresolved symbols as imported */
362 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
363 /* Add an include search path for binaries */
365 AddSearchPath (BinSearchPath, Arg);
370 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
371 /* Handle the --cpu option */
373 cpu_t CPU = FindCPU (Arg);
374 if (CPU == CPU_UNKNOWN) {
375 AbEnd ("Invalid CPU: `%s'", Arg);
383 static void OptCreateDep (const char* Opt, const char* Arg)
384 /* Handle the --create-dep option */
386 FileNameOption (Opt, Arg, &DepName);
391 static void OptCreateFullDep (const char* Opt attribute ((unused)),
393 /* Handle the --create-full-dep option */
395 FileNameOption (Opt, Arg, &FullDepName);
400 static void OptDebugInfo (const char* Opt attribute ((unused)),
401 const char* Arg attribute ((unused)))
402 /* Add debug info to the object file */
409 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
410 /* Set an emulation feature */
412 /* Make a string buffer from Arg */
415 /* Set the feature, check for errors */
416 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
417 AbEnd ("Illegal emulation feature: `%s'", Arg);
423 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
424 const char* Arg attribute ((unused)))
425 /* Forget all currently defined include paths */
427 ForgetAllIncludePaths ();
432 static void OptHelp (const char* Opt attribute ((unused)),
433 const char* Arg attribute ((unused)))
434 /* Print usage information and exit */
442 static void OptIgnoreCase (const char* Opt attribute ((unused)),
443 const char* Arg attribute ((unused)))
444 /* Ignore case on symbols */
451 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
452 /* Add an include search path */
454 AddSearchPath (IncSearchPath, Arg);
459 static void OptListBytes (const char* Opt, const char* Arg)
460 /* Set the maximum number of bytes per listing line */
465 /* Convert the argument to a number */
466 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
470 /* Check the bounds */
471 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
472 AbEnd ("Argument for option `%s' is out of range", Opt);
481 static void OptListing (const char* Opt, const char* Arg)
482 /* Create a listing file */
484 /* Since the meaning of -l and --listing has changed, print an error if
485 * the filename is empty or begins with the option char.
487 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
488 Fatal ("The meaning of `%s' has changed. It does now "
489 "expect a file name as argument.", Opt);
492 /* Get the file name */
493 FileNameOption (Opt, Arg, &ListingName);
498 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
499 /* Set a macro package directory */
501 /* Make a string buffer from Arg */
504 /* Use the directory */
505 MacPackSetDir (SB_InitFromString (&Dir, Arg));
510 static void OptMemoryModel (const char* Opt, const char* Arg)
511 /* Set the memory model */
515 /* Check the current memory model */
516 if (MemoryModel != MMODEL_UNKNOWN) {
517 AbEnd ("Cannot use option `%s' twice", Opt);
520 /* Translate the memory model name and check it */
521 M = FindMemoryModel (Arg);
522 if (M == MMODEL_UNKNOWN) {
523 AbEnd ("Unknown memory model: %s", Arg);
524 } else if (M == MMODEL_HUGE) {
525 AbEnd ("Unsupported memory model: %s", Arg);
528 /* Set the memory model */
534 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
535 /* Handle the --pagelength option */
537 int Len = atoi (Arg);
538 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
539 AbEnd ("Invalid page length: %d", Len);
546 static void OptSmart (const char* Opt attribute ((unused)),
547 const char* Arg attribute ((unused)))
548 /* Handle the -s/--smart options */
555 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
556 /* Set the target system */
563 static void OptVerbose (const char* Opt attribute ((unused)),
564 const char* Arg attribute ((unused)))
565 /* Increase verbosity */
572 static void OptVersion (const char* Opt attribute ((unused)),
573 const char* Arg attribute ((unused)))
574 /* Print the assembler version */
576 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
581 static void DoPCAssign (void)
582 /* Start absolute code */
584 long PC = ConstExpression ();
585 if (PC < 0 || PC > 0xFFFFFF) {
586 Error ("Range error");
588 EnterAbsoluteMode (PC);
594 static void OneLine (void)
595 /* Assemble one line */
598 unsigned long PC = 0;
603 /* Initialize the new listing line if we are actually reading from file
604 * and not from internally pushed input.
606 if (!HavePushedInput ()) {
610 /* Single colon means unnamed label */
611 if (CurTok.Tok == TOK_COLON) {
616 /* If the first token on the line is an identifier, check for a macro or
619 if (CurTok.Tok == TOK_IDENT) {
620 if (!UbiquitousIdents) {
621 /* Macros and symbols cannot use instruction names */
622 Instr = FindInstruction (&CurTok.SVal);
624 Mac = FindMacro (&CurTok.SVal);
627 /* Macros and symbols may use the names of instructions */
628 Mac = FindMacro (&CurTok.SVal);
632 /* Handle an identifier. This may be a cheap local symbol, or a fully
633 * scoped identifier which may start with a namespace token (for global
636 if (CurTok.Tok == TOK_LOCAL_IDENT ||
637 CurTok.Tok == TOK_NAMESPACE ||
638 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
640 /* Did we have whitespace before the ident? */
641 int HadWS = CurTok.WS;
643 /* Generate the symbol table entry, then skip the name */
644 Sym = ParseAnySymName (SYM_ALLOC_NEW);
646 /* If a colon follows, this is a label definition. If there
647 * is no colon, it's an assignment.
649 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
651 /* Determine the symbol flags from the assignment token */
652 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
657 /* Define the symbol with the expression following the '=' */
658 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
660 /* Don't allow anything after a symbol definition */
664 } else if (CurTok.Tok == TOK_SET) {
668 /* .SET defines variables (= redefinable symbols) */
671 /* Read the assignment expression, which must be constant */
672 Expr = GenLiteralExpr (ConstExpression ());
674 /* Define the symbol with the constant expression following
677 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
679 /* Don't allow anything after a symbol definition */
685 /* A label. Remember the current segment, so we can later
686 * determine the size of the data stored under the label.
691 /* Define the label */
692 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
694 /* Skip the colon. If NoColonLabels is enabled, allow labels
695 * without a colon if there is no whitespace before the
698 if (CurTok.Tok != TOK_COLON) {
699 if (HadWS || !NoColonLabels) {
700 Error ("`:' expected");
701 /* Try some smart error recovery */
702 if (CurTok.Tok == TOK_NAMESPACE) {
711 /* If we come here, a new identifier may be waiting, which may
712 * be a macro or instruction.
714 if (CurTok.Tok == TOK_IDENT) {
715 if (!UbiquitousIdents) {
716 /* Macros and symbols cannot use instruction names */
717 Instr = FindInstruction (&CurTok.SVal);
719 Mac = FindMacro (&CurTok.SVal);
722 /* Macros and symbols may use the names of instructions */
723 Mac = FindMacro (&CurTok.SVal);
729 /* We've handled a possible label, now handle the remainder of the line */
730 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
731 /* A control command */
733 } else if (Mac != 0) {
734 /* A macro expansion */
735 MacExpandStart (Mac);
736 } else if (Instr >= 0 ||
737 (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
738 /* A mnemonic - assemble one instruction */
739 HandleInstruction (Instr);
740 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
742 if (CurTok.Tok != TOK_EQ) {
743 Error ("`=' expected");
746 /* Skip the equal sign */
748 /* Enter absolute mode */
753 /* If we have defined a label, remember its size. Sym is also set by
754 * a symbol assignment, but in this case Done is false, so we don't
759 if (Seg == ActiveSeg) {
761 Size = GetPC () - PC;
763 /* The line has switched the segment */
766 DefSizeOfSymbol (Sym, Size);
769 /* Line separator must come here */
775 static void Assemble (void)
776 /* Start the ball rolling ... */
781 /* Assemble lines until end of file */
782 while (CurTok.Tok != TOK_EOF) {
789 static void CreateObjFile (void)
790 /* Create the object file */
792 /* Open the object, write the header */
795 /* Write the object file options */
798 /* Write the list of input files */
801 /* Write the segment data to the file */
804 /* Write the import list */
807 /* Write the export list */
810 /* Write debug symbols if requested */
813 /* Write the scopes if requested */
816 /* Write line infos if requested */
819 /* Write the string pool */
822 /* Write the assertions */
825 /* Write an updated header and close the file */
831 int main (int argc, char* argv [])
832 /* Assembler main program */
834 /* Program long options */
835 static const LongOpt OptTab[] = {
836 { "--auto-import", 0, OptAutoImport },
837 { "--bin-include-dir", 1, OptBinIncludeDir },
838 { "--cpu", 1, OptCPU },
839 { "--create-dep", 1, OptCreateDep },
840 { "--create-full-dep", 1, OptCreateFullDep },
841 { "--debug-info", 0, OptDebugInfo },
842 { "--feature", 1, OptFeature },
843 { "--forget-inc-paths", 0, OptForgetIncPaths },
844 { "--help", 0, OptHelp },
845 { "--ignore-case", 0, OptIgnoreCase },
846 { "--include-dir", 1, OptIncludeDir },
847 { "--list-bytes", 1, OptListBytes },
848 { "--listing", 1, OptListing },
849 { "--macpack-dir", 1, OptMacPackDir },
850 { "--memory-model", 1, OptMemoryModel },
851 { "--pagelength", 1, OptPageLength },
852 { "--smart", 0, OptSmart },
853 { "--target", 1, OptTarget },
854 { "--verbose", 0, OptVerbose },
855 { "--version", 0, OptVersion },
858 /* Name of the global name space */
859 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
863 /* Initialize the cmdline module */
864 InitCmdLine (&argc, &argv, "ca65");
866 /* Initialize the include search paths */
869 /* Create the predefined segments */
872 /* Enter the base lexical level. We must do that here, since we may
873 * define symbols using -D.
875 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
877 /* Initialize the line infos. Must be done here, since we need line infos
878 * for symbol definitions.
882 /* Check the parameters */
884 while (I < ArgCount) {
886 /* Get the argument */
887 const char* Arg = ArgVec [I];
889 /* Check for an option */
894 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
898 OptDebugInfo (Arg, 0);
906 OptIgnoreCase (Arg, 0);
910 OptListing (Arg, GetArg (&I, 2));
915 OptMemoryModel (Arg, GetArg (&I, 3));
922 OutFile = GetArg (&I, 2);
930 OptTarget (Arg, GetArg (&I, 2));
938 DefineSymbol (GetArg (&I, 2));
942 OptIncludeDir (Arg, GetArg (&I, 2));
946 OptAutoImport (Arg, 0);
954 WarnLevel = atoi (GetArg (&I, 2));
963 /* Filename. Check if we already had one */
965 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
977 /* Do we have an input file? */
979 fprintf (stderr, "%s: No input files\n", ProgName);
983 /* If no CPU given, use the default CPU for the target */
984 if (GetCPU () == CPU_UNKNOWN) {
985 if (Target != TGT_UNKNOWN) {
986 SetCPU (DefaultCPU[Target]);
992 /* If no memory model was given, use the default */
993 if (MemoryModel == MMODEL_UNKNOWN) {
994 SetMemoryModel (MMODEL_NEAR);
997 /* Set the default segment sizes according to the memory model */
1000 /* Initialize the scanner, open the input file */
1001 InitScanner (InFile);
1003 /* Define the default options */
1006 /* Assemble the input */
1009 /* If we didn't have any errors, check the pseudo insn stacks */
1010 if (ErrorCount == 0) {
1014 /* If we didn't have any errors, check the unnamed labels */
1015 if (ErrorCount == 0) {
1019 /* If we didn't have any errors, check the symbol table */
1020 if (ErrorCount == 0) {
1024 /* If we didn't have any errors, close the file scope lexical level */
1025 if (ErrorCount == 0) {
1029 /* If we didn't have any errors, check and resolve the segment data */
1030 if (ErrorCount == 0) {
1034 /* If we didn't have any errors, check the assertions */
1035 if (ErrorCount == 0) {
1040 if (Verbosity >= 2) {
1045 /* If we didn't have an errors, finish off the line infos */
1048 /* If we didn't have any errors, create the object, listing and
1051 if (ErrorCount == 0) {
1053 if (SB_GetLen (&ListingName) > 0) {
1056 CreateDependencies ();
1059 /* Close the input file */
1062 /* Return an apropriate exit code */
1063 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;