4 /* Main program for the ca65 macroassembler */
8 /* (C) 1998-2012, Ullrich von Bassewitz */
10 /* D-70794 Filderstadt */
11 /* EMail: uz@cc65.org */
14 /* This software is provided 'as-is', without any expressed or implied */
15 /* warranty. In no event will the authors be held liable for any damages */
16 /* arising from the use of this software. */
18 /* Permission is granted to anyone to use this software for any purpose, */
19 /* including commercial applications, and to alter it and redistribute it */
20 /* freely, subject to the following restrictions: */
22 /* 1. The origin of this software must not be misrepresented; you must not */
23 /* claim that you wrote the original software. If you use this software */
24 /* in a product, an acknowledgment in the product documentation would be */
25 /* appreciated but is not required. */
26 /* 2. Altered source versions must be plainly marked as such, and must not */
27 /* be misrepresented as being the original software. */
28 /* 3. This notice may not be removed or altered from any source */
31 /*****************************************************************************/
44 #include "debugflag.h"
47 #include "scopedefs.h"
83 /*****************************************************************************/
85 /*****************************************************************************/
89 static void Usage (void)
90 /* Print usage information and exit */
92 printf ("Usage: %s [options] file\n"
94 " -D name[=value]\t\tDefine a symbol\n"
95 " -I dir\t\t\tSet an include directory search path\n"
96 " -U\t\t\t\tMark unresolved symbols as import\n"
97 " -V\t\t\t\tPrint the assembler version\n"
98 " -W n\t\t\t\tSet warning level n\n"
99 " -d\t\t\t\tDebug mode\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\t\t\tDebug mode\n"
117 " --debug-info\t\t\tAdd debug info to object file\n"
118 " --feature name\t\tSet an emulation feature\n"
119 " --forget-inc-paths\t\tForget include search paths\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 ("__ATARI__", 1);
213 CBMSystem ("__C16__");
217 CBMSystem ("__C64__");
221 CBMSystem ("__VIC20__");
225 CBMSystem ("__C128__");
229 CBMSystem ("__PLUS4__");
233 CBMSystem ("__CBM510__");
237 CBMSystem ("__CBM610__");
241 CBMSystem ("__PET__");
245 NewSymbol ("__BBC__", 1);
249 NewSymbol ("__APPLE2__", 1);
253 NewSymbol ("__APPLE2ENH__", 1);
257 /* Do not handle as a CBM system */
258 NewSymbol ("__GEOS__", 1);
259 NewSymbol ("__GEOS_CBM__", 1);
263 NewSymbol ("__GEOS__", 1);
264 NewSymbol ("__GEOS_APPLE__", 1);
268 NewSymbol ("__LUNIX__", 1);
272 NewSymbol ("__ATMOS__", 1);
276 NewSymbol ("__NES__", 1);
279 case TGT_SUPERVISION:
280 NewSymbol ("__SUPERVISION__", 1);
284 NewSymbol ("__LYNX__", 1);
288 AbEnd ("Invalid target name: `%s'", Sys);
292 /* Initialize the translation tables for the target system */
298 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
299 /* Handle an option that remembers a file name for later */
301 /* Cannot have the option twice */
302 if (SB_NotEmpty (Name)) {
303 AbEnd ("Cannot use option `%s' twice", Opt);
305 /* Remember the file name for later */
306 SB_CopyStr (Name, Arg);
312 static void DefineSymbol (const char* Def)
313 /* 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 */
327 while (IsIdChar (*P)) {
328 SB_AppendChar (&SymName, *P++);
330 SB_Terminate (&SymName);
332 /* Do we have a value given? */
339 /* We have a value */
343 if (sscanf (P, "%lx", &Val) != 1) {
347 if (sscanf (P, "%li", &Val) != 1) {
353 /* Define the new symbol */
354 NewSymbol (SB_GetConstBuf (&SymName), Val);
356 /* Release string memory */
362 static void OptAutoImport (const char* Opt attribute ((unused)),
363 const char* Arg attribute ((unused)))
364 /* Mark unresolved symbols as imported */
371 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
372 /* Add an include search path for binaries */
374 AddSearchPath (BinSearchPath, Arg);
379 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
380 /* Handle the --cpu option */
382 cpu_t CPU = FindCPU (Arg);
383 if (CPU == CPU_UNKNOWN) {
384 AbEnd ("Invalid CPU: `%s'", Arg);
392 static void OptCreateDep (const char* Opt, const char* Arg)
393 /* Handle the --create-dep option */
395 FileNameOption (Opt, Arg, &DepName);
400 static void OptCreateFullDep (const char* Opt attribute ((unused)),
402 /* Handle the --create-full-dep option */
404 FileNameOption (Opt, Arg, &FullDepName);
409 static void OptDebug (const char* Opt attribute ((unused)),
410 const char* Arg attribute ((unused)))
411 /* Compiler debug mode */
418 static void OptDebugInfo (const char* Opt attribute ((unused)),
419 const char* Arg attribute ((unused)))
420 /* Add debug info to the object file */
427 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
428 /* Set an emulation feature */
430 /* Make a string buffer from Arg */
433 /* Set the feature, check for errors */
434 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
435 AbEnd ("Illegal emulation feature: `%s'", Arg);
441 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
442 const char* Arg attribute ((unused)))
443 /* Forget all currently defined include paths */
445 ForgetAllIncludePaths ();
450 static void OptHelp (const char* Opt attribute ((unused)),
451 const char* Arg attribute ((unused)))
452 /* Print usage information and exit */
460 static void OptIgnoreCase (const char* Opt attribute ((unused)),
461 const char* Arg attribute ((unused)))
462 /* Ignore case on symbols */
469 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
470 /* Add an include search path */
472 AddSearchPath (IncSearchPath, Arg);
477 static void OptLargeAlignment (const char* Opt attribute ((unused)),
478 const char* Arg attribute ((unused)))
479 /* Don't warn about large alignments */
486 static void OptListBytes (const char* Opt, const char* Arg)
487 /* Set the maximum number of bytes per listing line */
492 /* Convert the argument to a number */
493 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
497 /* Check the bounds */
498 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
499 AbEnd ("Argument for option `%s' is out of range", Opt);
508 static void OptListing (const char* Opt, const char* Arg)
509 /* Create a listing file */
511 /* Since the meaning of -l and --listing has changed, print an error if
512 * the filename is empty or begins with the option char.
514 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
515 Fatal ("The meaning of `%s' has changed. It does now "
516 "expect a file name as argument.", Opt);
519 /* Get the file name */
520 FileNameOption (Opt, Arg, &ListingName);
525 static void OptMemoryModel (const char* Opt, const char* Arg)
526 /* Set the memory model */
530 /* Check the current memory model */
531 if (MemoryModel != MMODEL_UNKNOWN) {
532 AbEnd ("Cannot use option `%s' twice", Opt);
535 /* Translate the memory model name and check it */
536 M = FindMemoryModel (Arg);
537 if (M == MMODEL_UNKNOWN) {
538 AbEnd ("Unknown memory model: %s", Arg);
539 } else if (M == MMODEL_HUGE) {
540 AbEnd ("Unsupported memory model: %s", Arg);
543 /* Set the memory model */
549 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
550 /* Handle the --pagelength option */
552 int Len = atoi (Arg);
553 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
554 AbEnd ("Invalid page length: %d", Len);
561 static void OptRelaxChecks (const char* Opt attribute ((unused)),
562 const char* Arg attribute ((unused)))
563 /* Handle the --relax-checks options */
570 static void OptSmart (const char* Opt attribute ((unused)),
571 const char* Arg attribute ((unused)))
572 /* Handle the -s/--smart options */
579 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
580 /* Set the target system */
587 static void OptVerbose (const char* Opt attribute ((unused)),
588 const char* Arg attribute ((unused)))
589 /* Increase verbosity */
596 static void OptVersion (const char* Opt attribute ((unused)),
597 const char* Arg attribute ((unused)))
598 /* Print the assembler version */
600 fprintf (stderr, "ca65 V%s\n", GetVersionAsString ());
605 static void DoPCAssign (void)
606 /* Start absolute code */
608 long PC = ConstExpression ();
609 if (PC < 0 || PC > 0xFFFFFF) {
610 Error ("Range error");
612 EnterAbsoluteMode (PC);
618 static void OneLine (void)
619 /* Assemble one line */
622 unsigned long PC = 0;
627 /* Initialize the new listing line if we are actually reading from file
628 * and not from internally pushed input.
630 if (!HavePushedInput ()) {
634 /* Single colon means unnamed label */
635 if (CurTok.Tok == TOK_COLON) {
640 /* If the first token on the line is an identifier, check for a macro or
643 if (CurTok.Tok == TOK_IDENT) {
644 if (!UbiquitousIdents) {
645 /* Macros and symbols cannot use instruction names */
646 Instr = FindInstruction (&CurTok.SVal);
648 Mac = FindMacro (&CurTok.SVal);
651 /* Macros and symbols may use the names of instructions */
652 Mac = FindMacro (&CurTok.SVal);
656 /* Handle an identifier. This may be a cheap local symbol, or a fully
657 * scoped identifier which may start with a namespace token (for global
660 if (CurTok.Tok == TOK_LOCAL_IDENT ||
661 CurTok.Tok == TOK_NAMESPACE ||
662 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
664 /* Did we have whitespace before the ident? */
665 int HadWS = CurTok.WS;
667 /* Generate the symbol table entry, then skip the name */
668 Sym = ParseAnySymName (SYM_ALLOC_NEW);
670 /* If a colon follows, this is a label definition. If there
671 * is no colon, it's an assignment.
673 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
675 /* Determine the symbol flags from the assignment token */
676 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
681 /* Define the symbol with the expression following the '=' */
682 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
684 /* Don't allow anything after a symbol definition */
688 } else if (CurTok.Tok == TOK_SET) {
692 /* .SET defines variables (= redefinable symbols) */
695 /* Read the assignment expression, which must be constant */
696 Expr = GenLiteralExpr (ConstExpression ());
698 /* Define the symbol with the constant expression following
701 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
703 /* Don't allow anything after a symbol definition */
709 /* A label. Remember the current segment, so we can later
710 * determine the size of the data stored under the label.
715 /* Define the label */
716 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
718 /* Skip the colon. If NoColonLabels is enabled, allow labels
719 * without a colon if there is no whitespace before the
722 if (CurTok.Tok != TOK_COLON) {
723 if (HadWS || !NoColonLabels) {
724 Error ("`:' expected");
725 /* Try some smart error recovery */
726 if (CurTok.Tok == TOK_NAMESPACE) {
735 /* If we come here, a new identifier may be waiting, which may
736 * be a macro or instruction.
738 if (CurTok.Tok == TOK_IDENT) {
739 if (!UbiquitousIdents) {
740 /* Macros and symbols cannot use instruction names */
741 Instr = FindInstruction (&CurTok.SVal);
743 Mac = FindMacro (&CurTok.SVal);
746 /* Macros and symbols may use the names of instructions */
747 Mac = FindMacro (&CurTok.SVal);
753 /* We've handled a possible label, now handle the remainder of the line */
754 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
755 /* A control command */
757 } else if (Mac != 0) {
758 /* A macro expansion */
759 MacExpandStart (Mac);
760 } else if (Instr >= 0 ||
761 (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
762 /* A mnemonic - assemble one instruction */
763 HandleInstruction (Instr);
764 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
766 if (CurTok.Tok != TOK_EQ) {
767 Error ("`=' expected");
770 /* Skip the equal sign */
772 /* Enter absolute mode */
777 /* If we have defined a label, remember its size. Sym is also set by
778 * a symbol assignment, but in this case Done is false, so we don't
783 if (Seg == ActiveSeg) {
785 Size = GetPC () - PC;
787 /* The line has switched the segment */
790 DefSizeOfSymbol (Sym, Size);
793 /* Line separator must come here */
799 static void Assemble (void)
800 /* Start the ball rolling ... */
805 /* Assemble lines until end of file */
806 while (CurTok.Tok != TOK_EOF) {
813 static void CreateObjFile (void)
814 /* Create the object file */
816 /* Open the object, write the header */
819 /* Write the object file options */
822 /* Write the list of input files */
825 /* Write the segment data to the file */
828 /* Write the import list */
831 /* Write the export list */
834 /* Write debug symbols if requested */
837 /* Write the scopes if requested */
840 /* Write line infos if requested */
843 /* Write the string pool */
846 /* Write the assertions */
849 /* Write the spans */
852 /* Write an updated header and close the file */
858 int main (int argc, char* argv [])
859 /* Assembler main program */
861 /* Program long options */
862 static const LongOpt OptTab[] = {
863 { "--auto-import", 0, OptAutoImport },
864 { "--bin-include-dir", 1, OptBinIncludeDir },
865 { "--cpu", 1, OptCPU },
866 { "--create-dep", 1, OptCreateDep },
867 { "--create-full-dep", 1, OptCreateFullDep },
868 { "--debug", 0, OptDebug },
869 { "--debug-info", 0, OptDebugInfo },
870 { "--feature", 1, OptFeature },
871 { "--forget-inc-paths", 0, OptForgetIncPaths },
872 { "--help", 0, OptHelp },
873 { "--ignore-case", 0, OptIgnoreCase },
874 { "--include-dir", 1, OptIncludeDir },
875 { "--large-alignment", 0, OptLargeAlignment },
876 { "--list-bytes", 1, OptListBytes },
877 { "--listing", 1, OptListing },
878 { "--memory-model", 1, OptMemoryModel },
879 { "--pagelength", 1, OptPageLength },
880 { "--relax-checks", 0, OptRelaxChecks },
881 { "--smart", 0, OptSmart },
882 { "--target", 1, OptTarget },
883 { "--verbose", 0, OptVerbose },
884 { "--version", 0, OptVersion },
887 /* Name of the global name space */
888 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
892 /* Initialize the cmdline module */
893 InitCmdLine (&argc, &argv, "ca65");
895 /* Initialize the string pool */
898 /* Initialize the include search paths */
901 /* Create the predefined segments */
904 /* Enter the base lexical level. We must do that here, since we may
905 * define symbols using -D.
907 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
909 /* Initialize the line infos. Must be done here, since we need line infos
910 * for symbol definitions.
914 /* Check the parameters */
916 while (I < ArgCount) {
918 /* Get the argument */
919 const char* Arg = ArgVec [I];
921 /* Check for an option */
926 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;