1 /*****************************************************************************/
5 /* Main program for the ca65 macroassembler */
9 /* (C) 1998-2013, 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 " --help\t\t\tHelp (this text)\n"
121 " --ignore-case\t\t\tIgnore case of symbols\n"
122 " --include-dir dir\t\tSet an include directory search path\n"
123 " --large-alignment\t\tDon't warn about large alignments\n"
124 " --listing name\t\tCreate a listing file if assembly was ok\n"
125 " --list-bytes n\t\tMaximum number of bytes per listing line\n"
126 " --macpack-dir dir\t\tSet a macro package directory\n"
127 " --memory-model model\t\tSet the memory model\n"
128 " --pagelength n\t\tSet the page length for the listing\n"
129 " --relax-checks\t\tRelax some checks (see docs)\n"
130 " --smart\t\t\tEnable smart mode\n"
131 " --target sys\t\t\tSet the target system\n"
132 " --verbose\t\t\tIncrease verbosity\n"
133 " --version\t\t\tPrint the assembler version\n",
139 static void SetOptions (void)
140 /* Set the option for the translator */
142 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
144 /* Set the translator */
145 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
146 OptTranslator (&Buf);
148 /* Set date and time */
149 OptDateTime ((unsigned long) time(0));
151 /* Release memory for the string */
157 static void NewSymbol (const char* SymName, long Val)
158 /* Define a symbol with a fixed numeric value in the current scope */
163 /* Convert the name to a string buffer */
164 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
165 SB_CopyStr (&SymBuf, SymName);
167 /* Search for the symbol, allocate a new one if it doesn't exist */
168 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
170 /* Check if have already a symbol with this name */
171 if (SymIsDef (Sym)) {
172 AbEnd ("`%s' is already defined", SymName);
175 /* Generate an expression for the symbol */
176 Expr = GenLiteralExpr (Val);
178 /* Mark the symbol as defined */
179 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
181 /* Free string buffer memory */
187 static void CBMSystem (const char* Sys)
188 /* Define a CBM system */
190 NewSymbol ("__CBM__", 1);
196 static void SetSys (const char* Sys)
197 /* Define a target system */
199 switch (Target = FindTarget (Sys)) {
205 AbEnd ("Cannot use `module' as a target for the assembler");
209 NewSymbol ("__ATARI2600__", 1);
213 NewSymbol ("__ATARI5200__", 1);
217 NewSymbol ("__ATARI__", 1);
221 NewSymbol ("__ATARI__", 1);
222 NewSymbol ("__ATARIXL__", 1);
226 CBMSystem ("__C16__");
230 CBMSystem ("__C64__");
234 CBMSystem ("__C65__");
238 CBMSystem ("__VIC20__");
242 CBMSystem ("__C128__");
246 CBMSystem ("__C16__");
247 NewSymbol ("__PLUS4__", 1);
251 CBMSystem ("__CBM510__");
255 CBMSystem ("__CBM610__");
259 CBMSystem ("__PET__");
263 NewSymbol ("__BBC__", 1);
267 NewSymbol ("__APPLE2__", 1);
271 NewSymbol ("__APPLE2__", 1);
272 NewSymbol ("__APPLE2ENH__", 1);
276 NewSymbol ("__GAMATE__", 1);
280 /* Do not handle as a CBM system */
281 NewSymbol ("__GEOS__", 1);
282 NewSymbol ("__GEOS_CBM__", 1);
286 NewSymbol ("__GEOS__", 1);
287 NewSymbol ("__GEOS_APPLE__", 1);
291 NewSymbol ("__LUNIX__", 1);
295 NewSymbol ("__ATMOS__", 1);
299 NewSymbol ("__NES__", 1);
302 case TGT_SUPERVISION:
303 NewSymbol ("__SUPERVISION__", 1);
307 NewSymbol ("__LYNX__", 1);
311 NewSymbol ("__SIM6502__", 1);
315 NewSymbol ("__SIM65C02__", 1);
319 NewSymbol ("__OSIC1P__", 1);
323 NewSymbol ("__PCE__", 1);
327 AbEnd ("Invalid target name: `%s'", Sys);
331 /* Initialize the translation tables for the target system */
337 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
338 /* Handle an option that remembers a file name for later */
340 /* Cannot have the option twice */
341 if (SB_NotEmpty (Name)) {
342 AbEnd ("Cannot use option `%s' twice", Opt);
344 /* Remember the file name for later */
345 SB_CopyStr (Name, Arg);
351 static void DefineSymbol (const char* Def)
352 /* Define a symbol from the command line */
356 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
359 /* The symbol must start with a character or underline */
360 if (!IsIdStart (Def [0])) {
365 /* Copy the symbol, checking the rest */
366 while (IsIdChar (*P)) {
367 SB_AppendChar (&SymName, *P++);
369 SB_Terminate (&SymName);
371 /* Do we have a value given? */
378 /* We have a value */
382 if (sscanf (P, "%lx", &Val) != 1) {
386 if (sscanf (P, "%li", &Val) != 1) {
392 /* Define the new symbol */
393 NewSymbol (SB_GetConstBuf (&SymName), Val);
395 /* Release string memory */
401 static void OptAutoImport (const char* Opt attribute ((unused)),
402 const char* Arg attribute ((unused)))
403 /* Mark unresolved symbols as imported */
410 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
411 /* Add an include search path for binaries */
413 AddSearchPath (BinSearchPath, Arg);
418 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
419 /* Handle the --cpu option */
421 cpu_t CPU = FindCPU (Arg);
422 if (CPU == CPU_UNKNOWN) {
423 AbEnd ("Invalid CPU: `%s'", Arg);
431 static void OptCreateDep (const char* Opt, const char* Arg)
432 /* Handle the --create-dep option */
434 FileNameOption (Opt, Arg, &DepName);
439 static void OptCreateFullDep (const char* Opt attribute ((unused)),
441 /* Handle the --create-full-dep option */
443 FileNameOption (Opt, Arg, &FullDepName);
448 static void OptDebug (const char* Opt attribute ((unused)),
449 const char* Arg attribute ((unused)))
450 /* Compiler debug mode */
457 static void OptDebugInfo (const char* Opt attribute ((unused)),
458 const char* Arg attribute ((unused)))
459 /* Add debug info to the object file */
466 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
467 /* Set an emulation feature */
469 /* Make a string buffer from Arg */
472 /* Set the feature, check for errors */
473 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
474 AbEnd ("Illegal emulation feature: `%s'", Arg);
480 static void OptHelp (const char* Opt attribute ((unused)),
481 const char* Arg attribute ((unused)))
482 /* Print usage information and exit */
490 static void OptIgnoreCase (const char* Opt attribute ((unused)),
491 const char* Arg attribute ((unused)))
492 /* Ignore case on symbols */
499 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
500 /* Add an include search path */
502 AddSearchPath (IncSearchPath, Arg);
507 static void OptLargeAlignment (const char* Opt attribute ((unused)),
508 const char* Arg attribute ((unused)))
509 /* Don't warn about large alignments */
516 static void OptListBytes (const char* Opt, const char* Arg)
517 /* Set the maximum number of bytes per listing line */
522 /* Convert the argument to a number */
523 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
527 /* Check the bounds */
528 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
529 AbEnd ("Argument for option `%s' is out of range", Opt);
538 static void OptListing (const char* Opt, const char* Arg)
539 /* Create a listing file */
541 /* Since the meaning of -l and --listing has changed, print an error if
542 ** the filename is empty or begins with the option char.
544 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
545 Fatal ("The meaning of `%s' has changed. It does now "
546 "expect a file name as argument.", Opt);
549 /* Get the file name */
550 FileNameOption (Opt, Arg, &ListingName);
555 static void OptMemoryModel (const char* Opt, const char* Arg)
556 /* Set the memory model */
560 /* Check the current memory model */
561 if (MemoryModel != MMODEL_UNKNOWN) {
562 AbEnd ("Cannot use option `%s' twice", Opt);
565 /* Translate the memory model name and check it */
566 M = FindMemoryModel (Arg);
567 if (M == MMODEL_UNKNOWN) {
568 AbEnd ("Unknown memory model: %s", Arg);
569 } else if (M == MMODEL_HUGE) {
570 AbEnd ("Unsupported memory model: %s", Arg);
573 /* Set the memory model */
579 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
580 /* Handle the --pagelength option */
582 int Len = atoi (Arg);
583 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
584 AbEnd ("Invalid page length: %d", Len);
591 static void OptRelaxChecks (const char* Opt attribute ((unused)),
592 const char* Arg attribute ((unused)))
593 /* Handle the --relax-checks options */
600 static void OptSmart (const char* Opt attribute ((unused)),
601 const char* Arg attribute ((unused)))
602 /* Handle the -s/--smart options */
609 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
610 /* Set the target system */
617 static void OptVerbose (const char* Opt attribute ((unused)),
618 const char* Arg attribute ((unused)))
619 /* Increase verbosity */
626 static void OptVersion (const char* Opt attribute ((unused)),
627 const char* Arg attribute ((unused)))
628 /* Print the assembler version */
630 fprintf (stderr, "%s V%s\n", ProgName, GetVersionAsString ());
636 static void DoPCAssign (void)
637 /* Start absolute code */
639 long PC = ConstExpression ();
640 if (PC < 0 || PC > 0xFFFFFF) {
641 Error ("Range error");
643 EnterAbsoluteMode (PC);
649 static void OneLine (void)
650 /* Assemble one line */
653 unsigned long PC = 0;
658 /* Initialize the new listing line if we are actually reading from file
659 ** and not from internally pushed input.
661 if (!HavePushedInput ()) {
665 /* Single colon means unnamed label */
666 if (CurTok.Tok == TOK_COLON) {
671 /* If the first token on the line is an identifier, check for a macro or
674 if (CurTok.Tok == TOK_IDENT) {
675 if (UbiquitousIdents) {
676 /* Macros CAN be instructions, so check for them first */
677 Mac = FindMacro (&CurTok.SVal);
679 Instr = FindInstruction (&CurTok.SVal);
682 /* Macros and symbols may NOT use the names of instructions */
683 Instr = FindInstruction (&CurTok.SVal);
685 Mac = FindMacro (&CurTok.SVal);
690 /* Handle an identifier. This may be a cheap local symbol, or a fully
691 ** scoped identifier which may start with a namespace token (for global
694 if (CurTok.Tok == TOK_LOCAL_IDENT ||
695 CurTok.Tok == TOK_NAMESPACE ||
696 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
698 /* Did we have whitespace before the ident? */
699 int HadWS = CurTok.WS;
701 /* Generate the symbol table entry, then skip the name */
702 Sym = ParseAnySymName (SYM_ALLOC_NEW);
704 /* If a colon follows, this is a label definition. If there
705 ** is no colon, it's an assignment.
707 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
709 /* Determine the symbol flags from the assignment token */
710 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
715 /* Define the symbol with the expression following the '=' */
716 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
718 /* Don't allow anything after a symbol definition */
722 } else if (CurTok.Tok == TOK_SET) {
726 /* .SET defines variables (= redefinable symbols) */
729 /* Read the assignment expression, which must be constant */
730 Expr = GenLiteralExpr (ConstExpression ());
732 /* Define the symbol with the constant expression following
735 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
737 /* Don't allow anything after a symbol definition */
743 /* A label. Remember the current segment, so we can later
744 ** determine the size of the data stored under the label.
749 /* Define the label */
750 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
752 /* Skip the colon. If NoColonLabels is enabled, allow labels
753 ** without a colon if there is no whitespace before the
756 if (CurTok.Tok != TOK_COLON) {
757 if (HadWS || !NoColonLabels) {
758 Error ("`:' expected");
759 /* Try some smart error recovery */
760 if (CurTok.Tok == TOK_NAMESPACE) {
769 /* If we come here, a new identifier may be waiting, which may
770 ** be a macro or instruction.
772 if (CurTok.Tok == TOK_IDENT) {
773 if (UbiquitousIdents) {
774 /* Macros CAN be instructions, so check for them first */
775 Mac = FindMacro (&CurTok.SVal);
777 Instr = FindInstruction (&CurTok.SVal);
780 /* Macros and symbols may NOT use the names of instructions */
781 Instr = FindInstruction (&CurTok.SVal);
783 Mac = FindMacro (&CurTok.SVal);
790 /* We've handled a possible label, now handle the remainder of the line */
791 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
792 /* A control command */
794 } else if (Mac != 0) {
795 /* A macro expansion */
796 MacExpandStart (Mac);
797 } else if (Instr >= 0) {
798 /* A mnemonic - assemble one instruction */
799 HandleInstruction (Instr);
800 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
802 if (CurTok.Tok != TOK_EQ) {
803 Error ("`=' expected");
806 /* Skip the equal sign */
808 /* Enter absolute mode */
813 /* If we have defined a label, remember its size. Sym is also set by
814 ** a symbol assignment, but in this case Done is false, so we don't
819 if (Seg == ActiveSeg) {
821 Size = GetPC () - PC;
823 /* The line has switched the segment */
826 DefSizeOfSymbol (Sym, Size);
829 /* Line separator must come here */
835 static void Assemble (void)
836 /* Start the ball rolling ... */
841 /* Assemble lines until end of file */
842 while (CurTok.Tok != TOK_EOF) {
849 static void CreateObjFile (void)
850 /* Create the object file */
852 /* Open the object, write the header */
855 /* Write the object file options */
858 /* Write the list of input files */
861 /* Write the segment data to the file */
864 /* Write the import list */
867 /* Write the export list */
870 /* Write debug symbols if requested */
873 /* Write the scopes if requested */
876 /* Write line infos if requested */
879 /* Write the string pool */
882 /* Write the assertions */
885 /* Write the spans */
888 /* Write an updated header and close the file */
894 int main (int argc, char* argv [])
895 /* Assembler main program */
897 /* Program long options */
898 static const LongOpt OptTab[] = {
899 { "--auto-import", 0, OptAutoImport },
900 { "--bin-include-dir", 1, OptBinIncludeDir },
901 { "--cpu", 1, OptCPU },
902 { "--create-dep", 1, OptCreateDep },
903 { "--create-full-dep", 1, OptCreateFullDep },
904 { "--debug", 0, OptDebug },
905 { "--debug-info", 0, OptDebugInfo },
906 { "--feature", 1, OptFeature },
907 { "--help", 0, OptHelp },
908 { "--ignore-case", 0, OptIgnoreCase },
909 { "--include-dir", 1, OptIncludeDir },
910 { "--large-alignment", 0, OptLargeAlignment },
911 { "--list-bytes", 1, OptListBytes },
912 { "--listing", 1, OptListing },
913 { "--memory-model", 1, OptMemoryModel },
914 { "--pagelength", 1, OptPageLength },
915 { "--relax-checks", 0, OptRelaxChecks },
916 { "--smart", 0, OptSmart },
917 { "--target", 1, OptTarget },
918 { "--verbose", 0, OptVerbose },
919 { "--version", 0, OptVersion },
922 /* Name of the global name space */
923 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
927 /* Initialize the cmdline module */
928 InitCmdLine (&argc, &argv, "ca65");
930 /* Initialize the string pool */
933 /* Initialize the include search paths */
936 /* Create the predefined segments */
939 /* Enter the base lexical level. We must do that here, since we may
940 ** define symbols using -D.
942 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
944 /* Initialize the line infos. Must be done here, since we need line infos
945 ** for symbol definitions.
949 /* Check the parameters */
951 while (I < ArgCount) {
953 /* Get the argument */
954 const char* Arg = ArgVec [I];
956 /* Check for an option */
961 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
969 OptDebugInfo (Arg, 0);
977 OptIgnoreCase (Arg, 0);
981 OptListing (Arg, GetArg (&I, 2));
986 OptMemoryModel (Arg, GetArg (&I, 3));
993 OutFile = GetArg (&I, 2);
1001 OptTarget (Arg, GetArg (&I, 2));
1005 OptVerbose (Arg, 0);
1009 DefineSymbol (GetArg (&I, 2));
1013 OptIncludeDir (Arg, GetArg (&I, 2));
1017 OptAutoImport (Arg, 0);
1021 OptVersion (Arg, 0);
1025 WarnLevel = atoi (GetArg (&I, 2));
1029 UnknownOption (Arg);
1034 /* Filename. Check if we already had one */
1036 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
1038 exit (EXIT_FAILURE);
1048 /* Do we have an input file? */
1050 fprintf (stderr, "%s: No input files\n", ProgName);
1051 exit (EXIT_FAILURE);
1054 /* Add the default include search paths. */
1055 FinishIncludePaths ();
1057 /* If no CPU given, use the default CPU for the target */
1058 if (GetCPU () == CPU_UNKNOWN) {
1059 if (Target != TGT_UNKNOWN) {
1060 SetCPU (GetTargetProperties (Target)->DefaultCPU);
1066 /* If no memory model was given, use the default */
1067 if (MemoryModel == MMODEL_UNKNOWN) {
1068 SetMemoryModel (MMODEL_NEAR);
1071 /* Set the default segment sizes according to the memory model */
1074 /* Initialize the scanner, open the input file */
1075 InitScanner (InFile);
1077 /* Define the default options */
1080 /* Assemble the input */
1083 /* If we didn't have any errors, check the pseudo insn stacks */
1084 if (ErrorCount == 0) {
1088 /* If we didn't have any errors, check and cleanup the unnamed labels */
1089 if (ErrorCount == 0) {
1093 /* If we didn't have any errors, check the symbol table */
1094 if (ErrorCount == 0) {
1098 /* If we didn't have any errors, check the hll debug symbols */
1099 if (ErrorCount == 0) {
1103 /* If we didn't have any errors, close the file scope lexical level */
1104 if (ErrorCount == 0) {
1108 /* If we didn't have any errors, check and resolve the segment data */
1109 if (ErrorCount == 0) {
1113 /* If we didn't have any errors, check the assertions */
1114 if (ErrorCount == 0) {
1119 if (Verbosity >= 2) {
1124 /* If we didn't have an errors, finish off the line infos */
1127 /* If we didn't have any errors, create the object, listing and
1130 if (ErrorCount == 0) {
1132 if (SB_GetLen (&ListingName) > 0) {
1135 CreateDependencies ();
1138 /* Close the input file */
1141 /* Return an apropriate exit code */
1142 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;