1 /*****************************************************************************/
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 /*****************************************************************************/
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 " --relax-checks\t\tRelax some checks (see docs)\n"
129 " --smart\t\t\tEnable smart mode\n"
130 " --target sys\t\t\tSet the target system\n"
131 " --verbose\t\t\tIncrease verbosity\n"
132 " --version\t\t\tPrint the assembler version\n",
138 static void SetOptions (void)
139 /* Set the option for the translator */
141 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
143 /* Set the translator */
144 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
145 OptTranslator (&Buf);
147 /* Set date and time */
148 OptDateTime ((unsigned long) time(0));
150 /* Release memory for the string */
156 static void NewSymbol (const char* SymName, long Val)
157 /* Define a symbol with a fixed numeric value in the current scope */
162 /* Convert the name to a string buffer */
163 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
164 SB_CopyStr (&SymBuf, SymName);
166 /* Search for the symbol, allocate a new one if it doesn't exist */
167 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
169 /* Check if have already a symbol with this name */
170 if (SymIsDef (Sym)) {
171 AbEnd ("`%s' is already defined", SymName);
174 /* Generate an expression for the symbol */
175 Expr = GenLiteralExpr (Val);
177 /* Mark the symbol as defined */
178 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
180 /* Free string buffer memory */
186 static void CBMSystem (const char* Sys)
187 /* Define a CBM system */
189 NewSymbol ("__CBM__", 1);
195 static void SetSys (const char* Sys)
196 /* Define a target system */
198 switch (Target = FindTarget (Sys)) {
204 AbEnd ("Cannot use `module' as a target for the assembler");
208 NewSymbol ("__ATARI__", 1);
212 CBMSystem ("__C16__");
216 CBMSystem ("__C64__");
220 CBMSystem ("__VIC20__");
224 CBMSystem ("__C128__");
228 CBMSystem ("__PLUS4__");
232 CBMSystem ("__CBM510__");
236 CBMSystem ("__CBM610__");
240 CBMSystem ("__PET__");
244 NewSymbol ("__BBC__", 1);
248 NewSymbol ("__APPLE2__", 1);
252 NewSymbol ("__APPLE2ENH__", 1);
256 /* Do not handle as a CBM system */
257 NewSymbol ("__GEOS__", 1);
258 NewSymbol ("__GEOS_CBM__", 1);
262 NewSymbol ("__GEOS__", 1);
263 NewSymbol ("__GEOS_APPLE__", 1);
267 NewSymbol ("__LUNIX__", 1);
271 NewSymbol ("__ATMOS__", 1);
275 NewSymbol ("__NES__", 1);
278 case TGT_SUPERVISION:
279 NewSymbol ("__SUPERVISION__", 1);
283 NewSymbol ("__LYNX__", 1);
287 AbEnd ("Invalid target name: `%s'", Sys);
291 /* Initialize the translation tables for the target system */
297 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
298 /* Handle an option that remembers a file name for later */
300 /* Cannot have the option twice */
301 if (SB_NotEmpty (Name)) {
302 AbEnd ("Cannot use option `%s' twice", Opt);
304 /* Remember the file name for later */
305 SB_CopyStr (Name, Arg);
311 static void DefineSymbol (const char* Def)
312 /* Define a symbol from the command line */
317 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
320 /* The symbol must start with a character or underline */
321 if (!IsIdStart (Def [0])) {
326 /* Copy the symbol, checking the rest */
328 while (IsIdChar (*P)) {
329 SB_AppendChar (&SymName, *P++);
331 SB_Terminate (&SymName);
333 /* Do we have a value given? */
340 /* We have a value */
344 if (sscanf (P, "%lx", &Val) != 1) {
348 if (sscanf (P, "%li", &Val) != 1) {
354 /* Define the new symbol */
355 NewSymbol (SB_GetConstBuf (&SymName), Val);
357 /* Release string memory */
363 static void OptAutoImport (const char* Opt attribute ((unused)),
364 const char* Arg attribute ((unused)))
365 /* Mark unresolved symbols as imported */
372 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
373 /* Add an include search path for binaries */
375 AddSearchPath (BinSearchPath, Arg);
380 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
381 /* Handle the --cpu option */
383 cpu_t CPU = FindCPU (Arg);
384 if (CPU == CPU_UNKNOWN) {
385 AbEnd ("Invalid CPU: `%s'", Arg);
393 static void OptCreateDep (const char* Opt, const char* Arg)
394 /* Handle the --create-dep option */
396 FileNameOption (Opt, Arg, &DepName);
401 static void OptCreateFullDep (const char* Opt attribute ((unused)),
403 /* Handle the --create-full-dep option */
405 FileNameOption (Opt, Arg, &FullDepName);
410 static void OptDebugInfo (const char* Opt attribute ((unused)),
411 const char* Arg attribute ((unused)))
412 /* Add debug info to the object file */
419 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
420 /* Set an emulation feature */
422 /* Make a string buffer from Arg */
425 /* Set the feature, check for errors */
426 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
427 AbEnd ("Illegal emulation feature: `%s'", Arg);
433 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
434 const char* Arg attribute ((unused)))
435 /* Forget all currently defined include paths */
437 ForgetAllIncludePaths ();
442 static void OptHelp (const char* Opt attribute ((unused)),
443 const char* Arg attribute ((unused)))
444 /* Print usage information and exit */
452 static void OptIgnoreCase (const char* Opt attribute ((unused)),
453 const char* Arg attribute ((unused)))
454 /* Ignore case on symbols */
461 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
462 /* Add an include search path */
464 AddSearchPath (IncSearchPath, Arg);
469 static void OptLargeAlignment (const char* Opt attribute ((unused)),
470 const char* Arg attribute ((unused)))
471 /* Don't warn about large alignments */
478 static void OptListBytes (const char* Opt, const char* Arg)
479 /* Set the maximum number of bytes per listing line */
484 /* Convert the argument to a number */
485 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
489 /* Check the bounds */
490 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
491 AbEnd ("Argument for option `%s' is out of range", Opt);
500 static void OptListing (const char* Opt, const char* Arg)
501 /* Create a listing file */
503 /* Since the meaning of -l and --listing has changed, print an error if
504 * the filename is empty or begins with the option char.
506 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
507 Fatal ("The meaning of `%s' has changed. It does now "
508 "expect a file name as argument.", Opt);
511 /* Get the file name */
512 FileNameOption (Opt, Arg, &ListingName);
517 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
518 /* Set a macro package directory */
520 /* Make a string buffer from Arg */
523 /* Use the directory */
524 MacPackSetDir (SB_InitFromString (&Dir, Arg));
529 static void OptMemoryModel (const char* Opt, const char* Arg)
530 /* Set the memory model */
534 /* Check the current memory model */
535 if (MemoryModel != MMODEL_UNKNOWN) {
536 AbEnd ("Cannot use option `%s' twice", Opt);
539 /* Translate the memory model name and check it */
540 M = FindMemoryModel (Arg);
541 if (M == MMODEL_UNKNOWN) {
542 AbEnd ("Unknown memory model: %s", Arg);
543 } else if (M == MMODEL_HUGE) {
544 AbEnd ("Unsupported memory model: %s", Arg);
547 /* Set the memory model */
553 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
554 /* Handle the --pagelength option */
556 int Len = atoi (Arg);
557 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
558 AbEnd ("Invalid page length: %d", Len);
565 static void OptRelaxChecks (const char* Opt attribute ((unused)),
566 const char* Arg attribute ((unused)))
567 /* Handle the --relax-checks options */
574 static void OptSmart (const char* Opt attribute ((unused)),
575 const char* Arg attribute ((unused)))
576 /* Handle the -s/--smart options */
583 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
584 /* Set the target system */
591 static void OptVerbose (const char* Opt attribute ((unused)),
592 const char* Arg attribute ((unused)))
593 /* Increase verbosity */
600 static void OptVersion (const char* Opt attribute ((unused)),
601 const char* Arg attribute ((unused)))
602 /* Print the assembler version */
604 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
609 static void DoPCAssign (void)
610 /* Start absolute code */
612 long PC = ConstExpression ();
613 if (PC < 0 || PC > 0xFFFFFF) {
614 Error ("Range error");
616 EnterAbsoluteMode (PC);
622 static void OneLine (void)
623 /* Assemble one line */
626 unsigned long PC = 0;
631 /* Initialize the new listing line if we are actually reading from file
632 * and not from internally pushed input.
634 if (!HavePushedInput ()) {
638 /* Single colon means unnamed label */
639 if (CurTok.Tok == TOK_COLON) {
644 /* If the first token on the line is an identifier, check for a macro or
647 if (CurTok.Tok == TOK_IDENT) {
648 if (!UbiquitousIdents) {
649 /* Macros and symbols cannot use instruction names */
650 Instr = FindInstruction (&CurTok.SVal);
652 Mac = FindMacro (&CurTok.SVal);
655 /* Macros and symbols may use the names of instructions */
656 Mac = FindMacro (&CurTok.SVal);
660 /* Handle an identifier. This may be a cheap local symbol, or a fully
661 * scoped identifier which may start with a namespace token (for global
664 if (CurTok.Tok == TOK_LOCAL_IDENT ||
665 CurTok.Tok == TOK_NAMESPACE ||
666 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
668 /* Did we have whitespace before the ident? */
669 int HadWS = CurTok.WS;
671 /* Generate the symbol table entry, then skip the name */
672 Sym = ParseAnySymName (SYM_ALLOC_NEW);
674 /* If a colon follows, this is a label definition. If there
675 * is no colon, it's an assignment.
677 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
679 /* Determine the symbol flags from the assignment token */
680 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
685 /* Define the symbol with the expression following the '=' */
686 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
688 /* Don't allow anything after a symbol definition */
692 } else if (CurTok.Tok == TOK_SET) {
696 /* .SET defines variables (= redefinable symbols) */
699 /* Read the assignment expression, which must be constant */
700 Expr = GenLiteralExpr (ConstExpression ());
702 /* Define the symbol with the constant expression following
705 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
707 /* Don't allow anything after a symbol definition */
713 /* A label. Remember the current segment, so we can later
714 * determine the size of the data stored under the label.
719 /* Define the label */
720 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
722 /* Skip the colon. If NoColonLabels is enabled, allow labels
723 * without a colon if there is no whitespace before the
726 if (CurTok.Tok != TOK_COLON) {
727 if (HadWS || !NoColonLabels) {
728 Error ("`:' expected");
729 /* Try some smart error recovery */
730 if (CurTok.Tok == TOK_NAMESPACE) {
739 /* If we come here, a new identifier may be waiting, which may
740 * be a macro or instruction.
742 if (CurTok.Tok == TOK_IDENT) {
743 if (!UbiquitousIdents) {
744 /* Macros and symbols cannot use instruction names */
745 Instr = FindInstruction (&CurTok.SVal);
747 Mac = FindMacro (&CurTok.SVal);
750 /* Macros and symbols may use the names of instructions */
751 Mac = FindMacro (&CurTok.SVal);
757 /* We've handled a possible label, now handle the remainder of the line */
758 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
759 /* A control command */
761 } else if (Mac != 0) {
762 /* A macro expansion */
763 MacExpandStart (Mac);
764 } else if (Instr >= 0 ||
765 (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
766 /* A mnemonic - assemble one instruction */
767 HandleInstruction (Instr);
768 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
770 if (CurTok.Tok != TOK_EQ) {
771 Error ("`=' expected");
774 /* Skip the equal sign */
776 /* Enter absolute mode */
781 /* If we have defined a label, remember its size. Sym is also set by
782 * a symbol assignment, but in this case Done is false, so we don't
787 if (Seg == ActiveSeg) {
789 Size = GetPC () - PC;
791 /* The line has switched the segment */
794 DefSizeOfSymbol (Sym, Size);
797 /* Line separator must come here */
803 static void Assemble (void)
804 /* Start the ball rolling ... */
809 /* Assemble lines until end of file */
810 while (CurTok.Tok != TOK_EOF) {
817 static void CreateObjFile (void)
818 /* Create the object file */
820 /* Open the object, write the header */
823 /* Write the object file options */
826 /* Write the list of input files */
829 /* Write the segment data to the file */
832 /* Write the import list */
835 /* Write the export list */
838 /* Write debug symbols if requested */
841 /* Write the scopes if requested */
844 /* Write line infos if requested */
847 /* Write the string pool */
850 /* Write the assertions */
853 /* Write the spans */
856 /* Write an updated header and close the file */
862 int main (int argc, char* argv [])
863 /* Assembler main program */
865 /* Program long options */
866 static const LongOpt OptTab[] = {
867 { "--auto-import", 0, OptAutoImport },
868 { "--bin-include-dir", 1, OptBinIncludeDir },
869 { "--cpu", 1, OptCPU },
870 { "--create-dep", 1, OptCreateDep },
871 { "--create-full-dep", 1, OptCreateFullDep },
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 { "--macpack-dir", 1, OptMacPackDir },
882 { "--memory-model", 1, OptMemoryModel },
883 { "--pagelength", 1, OptPageLength },
884 { "--relax-checks", 0, OptRelaxChecks },
885 { "--smart", 0, OptSmart },
886 { "--target", 1, OptTarget },
887 { "--verbose", 0, OptVerbose },
888 { "--version", 0, OptVersion },
891 /* Name of the global name space */
892 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
896 /* Initialize the cmdline module */
897 InitCmdLine (&argc, &argv, "ca65");
899 /* Initialize the string pool */
902 /* Initialize the include search paths */
905 /* Create the predefined segments */
908 /* Enter the base lexical level. We must do that here, since we may
909 * define symbols using -D.
911 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
913 /* Initialize the line infos. Must be done here, since we need line infos
914 * for symbol definitions.
918 /* Check the parameters */
920 while (I < ArgCount) {
922 /* Get the argument */
923 const char* Arg = ArgVec [I];
925 /* Check for an option */
930 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
934 OptDebugInfo (Arg, 0);
942 OptIgnoreCase (Arg, 0);
946 OptListing (Arg, GetArg (&I, 2));
951 OptMemoryModel (Arg, GetArg (&I, 3));
958 OutFile = GetArg (&I, 2);
966 OptTarget (Arg, GetArg (&I, 2));
974 DefineSymbol (GetArg (&I, 2));
978 OptIncludeDir (Arg, GetArg (&I, 2));
982 OptAutoImport (Arg, 0);
990 WarnLevel = atoi (GetArg (&I, 2));
999 /* Filename. Check if we already had one */
1001 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
1003 exit (EXIT_FAILURE);
1013 /* Do we have an input file? */
1015 fprintf (stderr, "%s: No input files\n", ProgName);
1016 exit (EXIT_FAILURE);
1019 /* If no CPU given, use the default CPU for the target */
1020 if (GetCPU () == CPU_UNKNOWN) {
1021 if (Target != TGT_UNKNOWN) {
1022 SetCPU (GetTargetProperties (Target)->DefaultCPU);
1028 /* If no memory model was given, use the default */
1029 if (MemoryModel == MMODEL_UNKNOWN) {
1030 SetMemoryModel (MMODEL_NEAR);
1033 /* Set the default segment sizes according to the memory model */
1036 /* Initialize the scanner, open the input file */
1037 InitScanner (InFile);
1039 /* Define the default options */
1042 /* Assemble the input */
1045 /* If we didn't have any errors, check the pseudo insn stacks */
1046 if (ErrorCount == 0) {
1050 /* If we didn't have any errors, check and cleanup the unnamed labels */
1051 if (ErrorCount == 0) {
1055 /* If we didn't have any errors, check the symbol table */
1056 if (ErrorCount == 0) {
1060 /* If we didn't have any errors, check the hll debug symbols */
1061 if (ErrorCount == 0) {
1065 /* If we didn't have any errors, close the file scope lexical level */
1066 if (ErrorCount == 0) {
1070 /* If we didn't have any errors, check and resolve the segment data */
1071 if (ErrorCount == 0) {
1075 /* If we didn't have any errors, check the assertions */
1076 if (ErrorCount == 0) {
1081 if (Verbosity >= 2) {
1086 /* If we didn't have an errors, finish off the line infos */
1089 /* If we didn't have any errors, create the object, listing and
1092 if (ErrorCount == 0) {
1094 if (SB_GetLen (&ListingName) > 0) {
1097 CreateDependencies ();
1100 /* Close the input file */
1103 /* Return an apropriate exit code */
1104 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;