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 ("__ATARI5200__", 1);
213 NewSymbol ("__ATARI__", 1);
217 NewSymbol ("__ATARI__", 1);
218 NewSymbol ("__ATARIXL__", 1);
222 CBMSystem ("__C16__");
226 CBMSystem ("__C64__");
230 CBMSystem ("__VIC20__");
234 CBMSystem ("__C128__");
238 CBMSystem ("__C16__");
239 NewSymbol ("__PLUS4__", 1);
243 CBMSystem ("__CBM510__");
247 CBMSystem ("__CBM610__");
251 CBMSystem ("__PET__");
255 NewSymbol ("__BBC__", 1);
259 NewSymbol ("__APPLE2__", 1);
263 NewSymbol ("__APPLE2__", 1);
264 NewSymbol ("__APPLE2ENH__", 1);
268 /* Do not handle as a CBM system */
269 NewSymbol ("__GEOS__", 1);
270 NewSymbol ("__GEOS_CBM__", 1);
274 NewSymbol ("__GEOS__", 1);
275 NewSymbol ("__GEOS_APPLE__", 1);
279 NewSymbol ("__LUNIX__", 1);
283 NewSymbol ("__ATMOS__", 1);
287 NewSymbol ("__NES__", 1);
290 case TGT_SUPERVISION:
291 NewSymbol ("__SUPERVISION__", 1);
295 NewSymbol ("__LYNX__", 1);
299 NewSymbol ("__SIM6502__", 1);
303 NewSymbol ("__SIM65C02__", 1);
307 NewSymbol ("__OSIC1P__", 1);
311 NewSymbol ("__PCE__", 1);
315 AbEnd ("Invalid target name: `%s'", Sys);
319 /* Initialize the translation tables for the target system */
325 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
326 /* Handle an option that remembers a file name for later */
328 /* Cannot have the option twice */
329 if (SB_NotEmpty (Name)) {
330 AbEnd ("Cannot use option `%s' twice", Opt);
332 /* Remember the file name for later */
333 SB_CopyStr (Name, Arg);
339 static void DefineSymbol (const char* Def)
340 /* Define a symbol from the command line */
344 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
347 /* The symbol must start with a character or underline */
348 if (!IsIdStart (Def [0])) {
353 /* Copy the symbol, checking the rest */
354 while (IsIdChar (*P)) {
355 SB_AppendChar (&SymName, *P++);
357 SB_Terminate (&SymName);
359 /* Do we have a value given? */
366 /* We have a value */
370 if (sscanf (P, "%lx", &Val) != 1) {
374 if (sscanf (P, "%li", &Val) != 1) {
380 /* Define the new symbol */
381 NewSymbol (SB_GetConstBuf (&SymName), Val);
383 /* Release string memory */
389 static void OptAutoImport (const char* Opt attribute ((unused)),
390 const char* Arg attribute ((unused)))
391 /* Mark unresolved symbols as imported */
398 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
399 /* Add an include search path for binaries */
401 AddSearchPath (BinSearchPath, Arg);
406 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
407 /* Handle the --cpu option */
409 cpu_t CPU = FindCPU (Arg);
410 if (CPU == CPU_UNKNOWN) {
411 AbEnd ("Invalid CPU: `%s'", Arg);
419 static void OptCreateDep (const char* Opt, const char* Arg)
420 /* Handle the --create-dep option */
422 FileNameOption (Opt, Arg, &DepName);
427 static void OptCreateFullDep (const char* Opt attribute ((unused)),
429 /* Handle the --create-full-dep option */
431 FileNameOption (Opt, Arg, &FullDepName);
436 static void OptDebug (const char* Opt attribute ((unused)),
437 const char* Arg attribute ((unused)))
438 /* Compiler debug mode */
445 static void OptDebugInfo (const char* Opt attribute ((unused)),
446 const char* Arg attribute ((unused)))
447 /* Add debug info to the object file */
454 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
455 /* Set an emulation feature */
457 /* Make a string buffer from Arg */
460 /* Set the feature, check for errors */
461 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
462 AbEnd ("Illegal emulation feature: `%s'", Arg);
468 static void OptHelp (const char* Opt attribute ((unused)),
469 const char* Arg attribute ((unused)))
470 /* Print usage information and exit */
478 static void OptIgnoreCase (const char* Opt attribute ((unused)),
479 const char* Arg attribute ((unused)))
480 /* Ignore case on symbols */
487 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
488 /* Add an include search path */
490 AddSearchPath (IncSearchPath, Arg);
495 static void OptLargeAlignment (const char* Opt attribute ((unused)),
496 const char* Arg attribute ((unused)))
497 /* Don't warn about large alignments */
504 static void OptListBytes (const char* Opt, const char* Arg)
505 /* Set the maximum number of bytes per listing line */
510 /* Convert the argument to a number */
511 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
515 /* Check the bounds */
516 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
517 AbEnd ("Argument for option `%s' is out of range", Opt);
526 static void OptListing (const char* Opt, const char* Arg)
527 /* Create a listing file */
529 /* Since the meaning of -l and --listing has changed, print an error if
530 ** the filename is empty or begins with the option char.
532 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
533 Fatal ("The meaning of `%s' has changed. It does now "
534 "expect a file name as argument.", Opt);
537 /* Get the file name */
538 FileNameOption (Opt, Arg, &ListingName);
543 static void OptMemoryModel (const char* Opt, const char* Arg)
544 /* Set the memory model */
548 /* Check the current memory model */
549 if (MemoryModel != MMODEL_UNKNOWN) {
550 AbEnd ("Cannot use option `%s' twice", Opt);
553 /* Translate the memory model name and check it */
554 M = FindMemoryModel (Arg);
555 if (M == MMODEL_UNKNOWN) {
556 AbEnd ("Unknown memory model: %s", Arg);
557 } else if (M == MMODEL_HUGE) {
558 AbEnd ("Unsupported memory model: %s", Arg);
561 /* Set the memory model */
567 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
568 /* Handle the --pagelength option */
570 int Len = atoi (Arg);
571 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
572 AbEnd ("Invalid page length: %d", Len);
579 static void OptRelaxChecks (const char* Opt attribute ((unused)),
580 const char* Arg attribute ((unused)))
581 /* Handle the --relax-checks options */
588 static void OptSmart (const char* Opt attribute ((unused)),
589 const char* Arg attribute ((unused)))
590 /* Handle the -s/--smart options */
597 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
598 /* Set the target system */
605 static void OptVerbose (const char* Opt attribute ((unused)),
606 const char* Arg attribute ((unused)))
607 /* Increase verbosity */
614 static void OptVersion (const char* Opt attribute ((unused)),
615 const char* Arg attribute ((unused)))
616 /* Print the assembler version */
618 fprintf (stderr, "ca65 V%s\n", GetVersionAsString ());
623 static void DoPCAssign (void)
624 /* Start absolute code */
626 long PC = ConstExpression ();
627 if (PC < 0 || PC > 0xFFFFFF) {
628 Error ("Range error");
630 EnterAbsoluteMode (PC);
636 static void OneLine (void)
637 /* Assemble one line */
640 unsigned long PC = 0;
645 /* Initialize the new listing line if we are actually reading from file
646 ** and not from internally pushed input.
648 if (!HavePushedInput ()) {
652 /* Single colon means unnamed label */
653 if (CurTok.Tok == TOK_COLON) {
658 /* If the first token on the line is an identifier, check for a macro or
661 if (CurTok.Tok == TOK_IDENT) {
662 if (UbiquitousIdents) {
663 /* Macros CAN be instructions, so check for them first */
664 Mac = FindMacro (&CurTok.SVal);
666 Instr = FindInstruction (&CurTok.SVal);
669 /* Macros and symbols may NOT use the names of instructions */
670 Instr = FindInstruction (&CurTok.SVal);
672 Mac = FindMacro (&CurTok.SVal);
677 /* Handle an identifier. This may be a cheap local symbol, or a fully
678 ** scoped identifier which may start with a namespace token (for global
681 if (CurTok.Tok == TOK_LOCAL_IDENT ||
682 CurTok.Tok == TOK_NAMESPACE ||
683 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
685 /* Did we have whitespace before the ident? */
686 int HadWS = CurTok.WS;
688 /* Generate the symbol table entry, then skip the name */
689 Sym = ParseAnySymName (SYM_ALLOC_NEW);
691 /* If a colon follows, this is a label definition. If there
692 ** is no colon, it's an assignment.
694 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
696 /* Determine the symbol flags from the assignment token */
697 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
702 /* Define the symbol with the expression following the '=' */
703 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
705 /* Don't allow anything after a symbol definition */
709 } else if (CurTok.Tok == TOK_SET) {
713 /* .SET defines variables (= redefinable symbols) */
716 /* Read the assignment expression, which must be constant */
717 Expr = GenLiteralExpr (ConstExpression ());
719 /* Define the symbol with the constant expression following
722 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
724 /* Don't allow anything after a symbol definition */
730 /* A label. Remember the current segment, so we can later
731 ** determine the size of the data stored under the label.
736 /* Define the label */
737 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
739 /* Skip the colon. If NoColonLabels is enabled, allow labels
740 ** without a colon if there is no whitespace before the
743 if (CurTok.Tok != TOK_COLON) {
744 if (HadWS || !NoColonLabels) {
745 Error ("`:' expected");
746 /* Try some smart error recovery */
747 if (CurTok.Tok == TOK_NAMESPACE) {
756 /* If we come here, a new identifier may be waiting, which may
757 ** be a macro or instruction.
759 if (CurTok.Tok == TOK_IDENT) {
760 if (UbiquitousIdents) {
761 /* Macros CAN be instructions, so check for them first */
762 Mac = FindMacro (&CurTok.SVal);
764 Instr = FindInstruction (&CurTok.SVal);
767 /* Macros and symbols may NOT use the names of instructions */
768 Instr = FindInstruction (&CurTok.SVal);
770 Mac = FindMacro (&CurTok.SVal);
777 /* We've handled a possible label, now handle the remainder of the line */
778 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
779 /* A control command */
781 } else if (Mac != 0) {
782 /* A macro expansion */
783 MacExpandStart (Mac);
784 } else if (Instr >= 0) {
785 /* A mnemonic - assemble one instruction */
786 HandleInstruction (Instr);
787 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
789 if (CurTok.Tok != TOK_EQ) {
790 Error ("`=' expected");
793 /* Skip the equal sign */
795 /* Enter absolute mode */
800 /* If we have defined a label, remember its size. Sym is also set by
801 ** a symbol assignment, but in this case Done is false, so we don't
806 if (Seg == ActiveSeg) {
808 Size = GetPC () - PC;
810 /* The line has switched the segment */
813 DefSizeOfSymbol (Sym, Size);
816 /* Line separator must come here */
822 static void Assemble (void)
823 /* Start the ball rolling ... */
828 /* Assemble lines until end of file */
829 while (CurTok.Tok != TOK_EOF) {
836 static void CreateObjFile (void)
837 /* Create the object file */
839 /* Open the object, write the header */
842 /* Write the object file options */
845 /* Write the list of input files */
848 /* Write the segment data to the file */
851 /* Write the import list */
854 /* Write the export list */
857 /* Write debug symbols if requested */
860 /* Write the scopes if requested */
863 /* Write line infos if requested */
866 /* Write the string pool */
869 /* Write the assertions */
872 /* Write the spans */
875 /* Write an updated header and close the file */
881 int main (int argc, char* argv [])
882 /* Assembler main program */
884 /* Program long options */
885 static const LongOpt OptTab[] = {
886 { "--auto-import", 0, OptAutoImport },
887 { "--bin-include-dir", 1, OptBinIncludeDir },
888 { "--cpu", 1, OptCPU },
889 { "--create-dep", 1, OptCreateDep },
890 { "--create-full-dep", 1, OptCreateFullDep },
891 { "--debug", 0, OptDebug },
892 { "--debug-info", 0, OptDebugInfo },
893 { "--feature", 1, OptFeature },
894 { "--help", 0, OptHelp },
895 { "--ignore-case", 0, OptIgnoreCase },
896 { "--include-dir", 1, OptIncludeDir },
897 { "--large-alignment", 0, OptLargeAlignment },
898 { "--list-bytes", 1, OptListBytes },
899 { "--listing", 1, OptListing },
900 { "--memory-model", 1, OptMemoryModel },
901 { "--pagelength", 1, OptPageLength },
902 { "--relax-checks", 0, OptRelaxChecks },
903 { "--smart", 0, OptSmart },
904 { "--target", 1, OptTarget },
905 { "--verbose", 0, OptVerbose },
906 { "--version", 0, OptVersion },
909 /* Name of the global name space */
910 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
914 /* Initialize the cmdline module */
915 InitCmdLine (&argc, &argv, "ca65");
917 /* Initialize the string pool */
920 /* Initialize the include search paths */
923 /* Create the predefined segments */
926 /* Enter the base lexical level. We must do that here, since we may
927 ** define symbols using -D.
929 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
931 /* Initialize the line infos. Must be done here, since we need line infos
932 ** for symbol definitions.
936 /* Check the parameters */
938 while (I < ArgCount) {
940 /* Get the argument */
941 const char* Arg = ArgVec [I];
943 /* Check for an option */
948 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
956 OptDebugInfo (Arg, 0);
964 OptIgnoreCase (Arg, 0);
968 OptListing (Arg, GetArg (&I, 2));
973 OptMemoryModel (Arg, GetArg (&I, 3));
980 OutFile = GetArg (&I, 2);
988 OptTarget (Arg, GetArg (&I, 2));
996 DefineSymbol (GetArg (&I, 2));
1000 OptIncludeDir (Arg, GetArg (&I, 2));
1004 OptAutoImport (Arg, 0);
1008 OptVersion (Arg, 0);
1012 WarnLevel = atoi (GetArg (&I, 2));
1016 UnknownOption (Arg);
1021 /* Filename. Check if we already had one */
1023 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
1025 exit (EXIT_FAILURE);
1035 /* Do we have an input file? */
1037 fprintf (stderr, "%s: No input files\n", ProgName);
1038 exit (EXIT_FAILURE);
1041 /* Add the default include search paths. */
1042 FinishIncludePaths ();
1044 /* If no CPU given, use the default CPU for the target */
1045 if (GetCPU () == CPU_UNKNOWN) {
1046 if (Target != TGT_UNKNOWN) {
1047 SetCPU (GetTargetProperties (Target)->DefaultCPU);
1053 /* If no memory model was given, use the default */
1054 if (MemoryModel == MMODEL_UNKNOWN) {
1055 SetMemoryModel (MMODEL_NEAR);
1058 /* Set the default segment sizes according to the memory model */
1061 /* Initialize the scanner, open the input file */
1062 InitScanner (InFile);
1064 /* Define the default options */
1067 /* Assemble the input */
1070 /* If we didn't have any errors, check the pseudo insn stacks */
1071 if (ErrorCount == 0) {
1075 /* If we didn't have any errors, check and cleanup the unnamed labels */
1076 if (ErrorCount == 0) {
1080 /* If we didn't have any errors, check the symbol table */
1081 if (ErrorCount == 0) {
1085 /* If we didn't have any errors, check the hll debug symbols */
1086 if (ErrorCount == 0) {
1090 /* If we didn't have any errors, close the file scope lexical level */
1091 if (ErrorCount == 0) {
1095 /* If we didn't have any errors, check and resolve the segment data */
1096 if (ErrorCount == 0) {
1100 /* If we didn't have any errors, check the assertions */
1101 if (ErrorCount == 0) {
1106 if (Verbosity >= 2) {
1111 /* If we didn't have an errors, finish off the line infos */
1114 /* If we didn't have any errors, create the object, listing and
1117 if (ErrorCount == 0) {
1119 if (SB_GetLen (&ListingName) > 0) {
1122 CreateDependencies ();
1125 /* Close the input file */
1128 /* Return an apropriate exit code */
1129 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;