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 " --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 ("__ATARI2600__", 1);
212 NewSymbol ("__ATARI5200__", 1);
216 NewSymbol ("__ATARI__", 1);
220 NewSymbol ("__ATARI__", 1);
221 NewSymbol ("__ATARIXL__", 1);
225 CBMSystem ("__C16__");
229 CBMSystem ("__C64__");
233 CBMSystem ("__C65__");
237 CBMSystem ("__VIC20__");
241 CBMSystem ("__C128__");
245 CBMSystem ("__C16__");
246 NewSymbol ("__PLUS4__", 1);
250 CBMSystem ("__CBM510__");
254 CBMSystem ("__CBM610__");
258 CBMSystem ("__PET__");
262 NewSymbol ("__BBC__", 1);
266 NewSymbol ("__APPLE2__", 1);
270 NewSymbol ("__APPLE2__", 1);
271 NewSymbol ("__APPLE2ENH__", 1);
275 NewSymbol ("__GAMATE__", 1);
279 /* Do not handle as a CBM system */
280 NewSymbol ("__GEOS__", 1);
281 NewSymbol ("__GEOS_CBM__", 1);
284 case TGT_CREATIVISION:
285 NewSymbol ("__CREATIVISION__", 1);
289 NewSymbol ("__GEOS__", 1);
290 NewSymbol ("__GEOS_APPLE__", 1);
294 NewSymbol ("__LUNIX__", 1);
298 NewSymbol ("__ATMOS__", 1);
302 NewSymbol ("__TELESTRAT__", 1);
306 NewSymbol ("__NES__", 1);
309 case TGT_SUPERVISION:
310 NewSymbol ("__SUPERVISION__", 1);
314 NewSymbol ("__LYNX__", 1);
318 NewSymbol ("__SIM6502__", 1);
322 NewSymbol ("__SIM65C02__", 1);
326 NewSymbol ("__OSIC1P__", 1);
330 NewSymbol ("__PCE__", 1);
334 AbEnd ("Invalid target name: `%s'", Sys);
338 /* Initialize the translation tables for the target system */
344 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
345 /* Handle an option that remembers a file name for later */
347 /* Cannot have the option twice */
348 if (SB_NotEmpty (Name)) {
349 AbEnd ("Cannot use option `%s' twice", Opt);
351 /* Remember the file name for later */
352 SB_CopyStr (Name, Arg);
358 static void DefineSymbol (const char* Def)
359 /* Define a symbol from the command line */
363 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
366 /* The symbol must start with a character or underline */
367 if (!IsIdStart (Def [0])) {
372 /* Copy the symbol, checking the rest */
373 while (IsIdChar (*P)) {
374 SB_AppendChar (&SymName, *P++);
376 SB_Terminate (&SymName);
378 /* Do we have a value given? */
385 /* We have a value */
389 if (sscanf (P, "%lx", &Val) != 1) {
393 if (sscanf (P, "%li", &Val) != 1) {
399 /* Define the new symbol */
400 NewSymbol (SB_GetConstBuf (&SymName), Val);
402 /* Release string memory */
408 static void OptAutoImport (const char* Opt attribute ((unused)),
409 const char* Arg attribute ((unused)))
410 /* Mark unresolved symbols as imported */
417 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
418 /* Add an include search path for binaries */
420 AddSearchPath (BinSearchPath, Arg);
425 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
426 /* Handle the --cpu option */
428 cpu_t CPU = FindCPU (Arg);
429 if (CPU == CPU_UNKNOWN) {
430 AbEnd ("Invalid CPU: `%s'", Arg);
438 static void OptCreateDep (const char* Opt, const char* Arg)
439 /* Handle the --create-dep option */
441 FileNameOption (Opt, Arg, &DepName);
446 static void OptCreateFullDep (const char* Opt attribute ((unused)),
448 /* Handle the --create-full-dep option */
450 FileNameOption (Opt, Arg, &FullDepName);
455 static void OptDebug (const char* Opt attribute ((unused)),
456 const char* Arg attribute ((unused)))
457 /* Compiler debug mode */
464 static void OptDebugInfo (const char* Opt attribute ((unused)),
465 const char* Arg attribute ((unused)))
466 /* Add debug info to the object file */
473 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
474 /* Set an emulation feature */
476 /* Make a string buffer from Arg */
479 /* Set the feature, check for errors */
480 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
481 AbEnd ("Illegal emulation feature: `%s'", Arg);
487 static void OptHelp (const char* Opt attribute ((unused)),
488 const char* Arg attribute ((unused)))
489 /* Print usage information and exit */
497 static void OptIgnoreCase (const char* Opt attribute ((unused)),
498 const char* Arg attribute ((unused)))
499 /* Ignore case on symbols */
506 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
507 /* Add an include search path */
509 AddSearchPath (IncSearchPath, Arg);
514 static void OptLargeAlignment (const char* Opt attribute ((unused)),
515 const char* Arg attribute ((unused)))
516 /* Don't warn about large alignments */
523 static void OptListBytes (const char* Opt, const char* Arg)
524 /* Set the maximum number of bytes per listing line */
529 /* Convert the argument to a number */
530 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
534 /* Check the bounds */
535 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
536 AbEnd ("Argument for option `%s' is out of range", Opt);
545 static void OptListing (const char* Opt, const char* Arg)
546 /* Create a listing file */
548 /* Since the meaning of -l and --listing has changed, print an error if
549 ** the filename is empty or begins with the option char.
551 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
552 Fatal ("The meaning of `%s' has changed. It does now "
553 "expect a file name as argument.", Opt);
556 /* Get the file name */
557 FileNameOption (Opt, Arg, &ListingName);
562 static void OptMemoryModel (const char* Opt, const char* Arg)
563 /* Set the memory model */
567 /* Check the current memory model */
568 if (MemoryModel != MMODEL_UNKNOWN) {
569 AbEnd ("Cannot use option `%s' twice", Opt);
572 /* Translate the memory model name and check it */
573 M = FindMemoryModel (Arg);
574 if (M == MMODEL_UNKNOWN) {
575 AbEnd ("Unknown memory model: %s", Arg);
576 } else if (M == MMODEL_HUGE) {
577 AbEnd ("Unsupported memory model: %s", Arg);
580 /* Set the memory model */
586 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
587 /* Handle the --pagelength option */
589 int Len = atoi (Arg);
590 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
591 AbEnd ("Invalid page length: %d", Len);
598 static void OptRelaxChecks (const char* Opt attribute ((unused)),
599 const char* Arg attribute ((unused)))
600 /* Handle the --relax-checks options */
607 static void OptSmart (const char* Opt attribute ((unused)),
608 const char* Arg attribute ((unused)))
609 /* Handle the -s/--smart options */
616 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
617 /* Set the target system */
624 static void OptVerbose (const char* Opt attribute ((unused)),
625 const char* Arg attribute ((unused)))
626 /* Increase verbosity */
633 static void OptVersion (const char* Opt attribute ((unused)),
634 const char* Arg attribute ((unused)))
635 /* Print the assembler version */
637 fprintf (stderr, "%s V%s\n", ProgName, GetVersionAsString ());
643 static void DoPCAssign (void)
644 /* Start absolute code */
646 long PC = ConstExpression ();
647 if (PC < 0 || PC > 0xFFFFFF) {
648 Error ("Range error");
650 EnterAbsoluteMode (PC);
656 static void OneLine (void)
657 /* Assemble one line */
660 unsigned long PC = 0;
665 /* Initialize the new listing line if we are actually reading from file
666 ** and not from internally pushed input.
668 if (!HavePushedInput ()) {
672 /* Single colon means unnamed label */
673 if (CurTok.Tok == TOK_COLON) {
678 /* If the first token on the line is an identifier, check for a macro or
681 if (CurTok.Tok == TOK_IDENT) {
682 if (UbiquitousIdents) {
683 /* Macros CAN be instructions, so check for them first */
684 Mac = FindMacro (&CurTok.SVal);
686 Instr = FindInstruction (&CurTok.SVal);
689 /* Macros and symbols may NOT use the names of instructions */
690 Instr = FindInstruction (&CurTok.SVal);
692 Mac = FindMacro (&CurTok.SVal);
697 /* Handle an identifier. This may be a cheap local symbol, or a fully
698 ** scoped identifier which may start with a namespace token (for global
701 if (CurTok.Tok == TOK_LOCAL_IDENT ||
702 CurTok.Tok == TOK_NAMESPACE ||
703 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
705 /* Did we have whitespace before the ident? */
706 int HadWS = CurTok.WS;
708 /* Generate the symbol table entry, then skip the name */
709 Sym = ParseAnySymName (SYM_ALLOC_NEW);
711 /* If a colon follows, this is a label definition. If there
712 ** is no colon, it's an assignment.
714 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
716 /* Determine the symbol flags from the assignment token */
717 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
722 /* Define the symbol with the expression following the '=' */
723 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
725 /* Don't allow anything after a symbol definition */
729 } else if (CurTok.Tok == TOK_SET) {
733 /* .SET defines variables (= redefinable symbols) */
736 /* Read the assignment expression, which must be constant */
737 Expr = GenLiteralExpr (ConstExpression ());
739 /* Define the symbol with the constant expression following
742 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
744 /* Don't allow anything after a symbol definition */
750 /* A label. Remember the current segment, so we can later
751 ** determine the size of the data stored under the label.
756 /* Define the label */
757 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
759 /* Skip the colon. If NoColonLabels is enabled, allow labels
760 ** without a colon if there is no whitespace before the
763 if (CurTok.Tok != TOK_COLON) {
764 if (HadWS || !NoColonLabels) {
765 Error ("`:' expected");
766 /* Try some smart error recovery */
767 if (CurTok.Tok == TOK_NAMESPACE) {
776 /* If we come here, a new identifier may be waiting, which may
777 ** be a macro or instruction.
779 if (CurTok.Tok == TOK_IDENT) {
780 if (UbiquitousIdents) {
781 /* Macros CAN be instructions, so check for them first */
782 Mac = FindMacro (&CurTok.SVal);
784 Instr = FindInstruction (&CurTok.SVal);
787 /* Macros and symbols may NOT use the names of instructions */
788 Instr = FindInstruction (&CurTok.SVal);
790 Mac = FindMacro (&CurTok.SVal);
797 /* We've handled a possible label, now handle the remainder of the line */
798 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
799 /* A control command */
801 } else if (Mac != 0) {
802 /* A macro expansion */
803 MacExpandStart (Mac);
804 } else if (Instr >= 0) {
805 /* A mnemonic - assemble one instruction */
806 HandleInstruction (Instr);
807 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
809 if (CurTok.Tok != TOK_EQ) {
810 Error ("`=' expected");
813 /* Skip the equal sign */
815 /* Enter absolute mode */
820 /* If we have defined a label, remember its size. Sym is also set by
821 ** a symbol assignment, but in this case Done is false, so we don't
826 if (Seg == ActiveSeg) {
828 Size = GetPC () - PC;
830 /* The line has switched the segment */
833 DefSizeOfSymbol (Sym, Size);
836 /* Line separator must come here */
842 static void Assemble (void)
843 /* Start the ball rolling ... */
848 /* Assemble lines until end of file */
849 while (CurTok.Tok != TOK_EOF) {
856 static void CreateObjFile (void)
857 /* Create the object file */
859 /* Open the object, write the header */
862 /* Write the object file options */
865 /* Write the list of input files */
868 /* Write the segment data to the file */
871 /* Write the import list */
874 /* Write the export list */
877 /* Write debug symbols if requested */
880 /* Write the scopes if requested */
883 /* Write line infos if requested */
886 /* Write the string pool */
889 /* Write the assertions */
892 /* Write the spans */
895 /* Write an updated header and close the file */
901 int main (int argc, char* argv [])
902 /* Assembler main program */
904 /* Program long options */
905 static const LongOpt OptTab[] = {
906 { "--auto-import", 0, OptAutoImport },
907 { "--bin-include-dir", 1, OptBinIncludeDir },
908 { "--cpu", 1, OptCPU },
909 { "--create-dep", 1, OptCreateDep },
910 { "--create-full-dep", 1, OptCreateFullDep },
911 { "--debug", 0, OptDebug },
912 { "--debug-info", 0, OptDebugInfo },
913 { "--feature", 1, OptFeature },
914 { "--help", 0, OptHelp },
915 { "--ignore-case", 0, OptIgnoreCase },
916 { "--include-dir", 1, OptIncludeDir },
917 { "--large-alignment", 0, OptLargeAlignment },
918 { "--list-bytes", 1, OptListBytes },
919 { "--listing", 1, OptListing },
920 { "--memory-model", 1, OptMemoryModel },
921 { "--pagelength", 1, OptPageLength },
922 { "--relax-checks", 0, OptRelaxChecks },
923 { "--smart", 0, OptSmart },
924 { "--target", 1, OptTarget },
925 { "--verbose", 0, OptVerbose },
926 { "--version", 0, OptVersion },
929 /* Name of the global name space */
930 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
934 /* Initialize the cmdline module */
935 InitCmdLine (&argc, &argv, "ca65");
937 /* Initialize the string pool */
940 /* Initialize the include search paths */
943 /* Create the predefined segments */
946 /* Enter the base lexical level. We must do that here, since we may
947 ** define symbols using -D.
949 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
951 /* Initialize the line infos. Must be done here, since we need line infos
952 ** for symbol definitions.
956 /* Check the parameters */
958 while (I < ArgCount) {
960 /* Get the argument */
961 const char* Arg = ArgVec [I];
963 /* Check for an option */
968 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
976 OptDebugInfo (Arg, 0);
984 OptIgnoreCase (Arg, 0);
988 OptListing (Arg, GetArg (&I, 2));
993 OptMemoryModel (Arg, GetArg (&I, 3));
1000 OutFile = GetArg (&I, 2);
1008 OptTarget (Arg, GetArg (&I, 2));
1012 OptVerbose (Arg, 0);
1016 DefineSymbol (GetArg (&I, 2));
1020 OptIncludeDir (Arg, GetArg (&I, 2));
1024 OptAutoImport (Arg, 0);
1028 OptVersion (Arg, 0);
1032 WarnLevel = atoi (GetArg (&I, 2));
1036 UnknownOption (Arg);
1041 /* Filename. Check if we already had one */
1043 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
1045 exit (EXIT_FAILURE);
1055 /* Do we have an input file? */
1057 fprintf (stderr, "%s: No input files\n", ProgName);
1058 exit (EXIT_FAILURE);
1061 /* Add the default include search paths. */
1062 FinishIncludePaths ();
1064 /* If no CPU given, use the default CPU for the target */
1065 if (GetCPU () == CPU_UNKNOWN) {
1066 if (Target != TGT_UNKNOWN) {
1067 SetCPU (GetTargetProperties (Target)->DefaultCPU);
1073 /* If no memory model was given, use the default */
1074 if (MemoryModel == MMODEL_UNKNOWN) {
1075 SetMemoryModel (MMODEL_NEAR);
1078 /* Set the default segment sizes according to the memory model */
1081 /* Initialize the scanner, open the input file */
1082 InitScanner (InFile);
1084 /* Define the default options */
1087 /* Assemble the input */
1090 /* If we didn't have any errors, check the pseudo insn stacks */
1091 if (ErrorCount == 0) {
1095 /* If we didn't have any errors, check and cleanup the unnamed labels */
1096 if (ErrorCount == 0) {
1100 /* If we didn't have any errors, check the symbol table */
1101 if (ErrorCount == 0) {
1105 /* If we didn't have any errors, check the hll debug symbols */
1106 if (ErrorCount == 0) {
1110 /* If we didn't have any errors, close the file scope lexical level */
1111 if (ErrorCount == 0) {
1115 /* If we didn't have any errors, check and resolve the segment data */
1116 if (ErrorCount == 0) {
1120 /* If we didn't have any errors, check the assertions */
1121 if (ErrorCount == 0) {
1126 if (Verbosity >= 2) {
1131 /* If we didn't have an errors, finish off the line infos */
1134 /* If we didn't have any errors, create the object, listing and
1137 if (ErrorCount == 0) {
1139 if (SB_GetLen (&ListingName) > 0) {
1142 CreateDependencies ();
1145 /* Close the input file */
1148 /* Return an apropriate exit code */
1149 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;