4 /* Main program for the ca65 macroassembler */
8 /* (C) 1998-2013, 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 " --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 NewSymbol ("__ATARI__", 1);
213 NewSymbol ("__ATARIXL__", 1);
217 CBMSystem ("__C16__");
221 CBMSystem ("__C64__");
225 CBMSystem ("__VIC20__");
229 CBMSystem ("__C128__");
233 CBMSystem ("__C16__");
234 NewSymbol ("__PLUS4__", 1);
238 CBMSystem ("__CBM510__");
242 CBMSystem ("__CBM610__");
246 CBMSystem ("__PET__");
250 NewSymbol ("__BBC__", 1);
254 NewSymbol ("__APPLE2__", 1);
258 NewSymbol ("__APPLE2__", 1);
259 NewSymbol ("__APPLE2ENH__", 1);
263 /* Do not handle as a CBM system */
264 NewSymbol ("__GEOS__", 1);
265 NewSymbol ("__GEOS_CBM__", 1);
269 NewSymbol ("__GEOS__", 1);
270 NewSymbol ("__GEOS_APPLE__", 1);
274 NewSymbol ("__LUNIX__", 1);
278 NewSymbol ("__ATMOS__", 1);
282 NewSymbol ("__NES__", 1);
285 case TGT_SUPERVISION:
286 NewSymbol ("__SUPERVISION__", 1);
290 NewSymbol ("__LYNX__", 1);
294 NewSymbol ("__SIM6502__", 1);
298 NewSymbol ("__SIM65C02__", 1);
302 AbEnd ("Invalid target name: `%s'", Sys);
306 /* Initialize the translation tables for the target system */
312 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
313 /* Handle an option that remembers a file name for later */
315 /* Cannot have the option twice */
316 if (SB_NotEmpty (Name)) {
317 AbEnd ("Cannot use option `%s' twice", Opt);
319 /* Remember the file name for later */
320 SB_CopyStr (Name, Arg);
326 static void DefineSymbol (const char* Def)
327 /* Define a symbol from the command line */
331 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
334 /* The symbol must start with a character or underline */
335 if (!IsIdStart (Def [0])) {
340 /* Copy the symbol, checking the rest */
341 while (IsIdChar (*P)) {
342 SB_AppendChar (&SymName, *P++);
344 SB_Terminate (&SymName);
346 /* Do we have a value given? */
353 /* We have a value */
357 if (sscanf (P, "%lx", &Val) != 1) {
361 if (sscanf (P, "%li", &Val) != 1) {
367 /* Define the new symbol */
368 NewSymbol (SB_GetConstBuf (&SymName), Val);
370 /* Release string memory */
376 static void OptAutoImport (const char* Opt attribute ((unused)),
377 const char* Arg attribute ((unused)))
378 /* Mark unresolved symbols as imported */
385 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
386 /* Add an include search path for binaries */
388 AddSearchPath (BinSearchPath, Arg);
393 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
394 /* Handle the --cpu option */
396 cpu_t CPU = FindCPU (Arg);
397 if (CPU == CPU_UNKNOWN) {
398 AbEnd ("Invalid CPU: `%s'", Arg);
406 static void OptCreateDep (const char* Opt, const char* Arg)
407 /* Handle the --create-dep option */
409 FileNameOption (Opt, Arg, &DepName);
414 static void OptCreateFullDep (const char* Opt attribute ((unused)),
416 /* Handle the --create-full-dep option */
418 FileNameOption (Opt, Arg, &FullDepName);
423 static void OptDebug (const char* Opt attribute ((unused)),
424 const char* Arg attribute ((unused)))
425 /* Compiler debug mode */
432 static void OptDebugInfo (const char* Opt attribute ((unused)),
433 const char* Arg attribute ((unused)))
434 /* Add debug info to the object file */
441 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
442 /* Set an emulation feature */
444 /* Make a string buffer from Arg */
447 /* Set the feature, check for errors */
448 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
449 AbEnd ("Illegal emulation feature: `%s'", Arg);
455 static void OptHelp (const char* Opt attribute ((unused)),
456 const char* Arg attribute ((unused)))
457 /* Print usage information and exit */
465 static void OptIgnoreCase (const char* Opt attribute ((unused)),
466 const char* Arg attribute ((unused)))
467 /* Ignore case on symbols */
474 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
475 /* Add an include search path */
477 AddSearchPath (IncSearchPath, Arg);
482 static void OptLargeAlignment (const char* Opt attribute ((unused)),
483 const char* Arg attribute ((unused)))
484 /* Don't warn about large alignments */
491 static void OptListBytes (const char* Opt, const char* Arg)
492 /* Set the maximum number of bytes per listing line */
497 /* Convert the argument to a number */
498 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
502 /* Check the bounds */
503 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
504 AbEnd ("Argument for option `%s' is out of range", Opt);
513 static void OptListing (const char* Opt, const char* Arg)
514 /* Create a listing file */
516 /* Since the meaning of -l and --listing has changed, print an error if
517 * the filename is empty or begins with the option char.
519 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
520 Fatal ("The meaning of `%s' has changed. It does now "
521 "expect a file name as argument.", Opt);
524 /* Get the file name */
525 FileNameOption (Opt, Arg, &ListingName);
530 static void OptMemoryModel (const char* Opt, const char* Arg)
531 /* Set the memory model */
535 /* Check the current memory model */
536 if (MemoryModel != MMODEL_UNKNOWN) {
537 AbEnd ("Cannot use option `%s' twice", Opt);
540 /* Translate the memory model name and check it */
541 M = FindMemoryModel (Arg);
542 if (M == MMODEL_UNKNOWN) {
543 AbEnd ("Unknown memory model: %s", Arg);
544 } else if (M == MMODEL_HUGE) {
545 AbEnd ("Unsupported memory model: %s", Arg);
548 /* Set the memory model */
554 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
555 /* Handle the --pagelength option */
557 int Len = atoi (Arg);
558 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
559 AbEnd ("Invalid page length: %d", Len);
566 static void OptRelaxChecks (const char* Opt attribute ((unused)),
567 const char* Arg attribute ((unused)))
568 /* Handle the --relax-checks options */
575 static void OptSmart (const char* Opt attribute ((unused)),
576 const char* Arg attribute ((unused)))
577 /* Handle the -s/--smart options */
584 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
585 /* Set the target system */
592 static void OptVerbose (const char* Opt attribute ((unused)),
593 const char* Arg attribute ((unused)))
594 /* Increase verbosity */
601 static void OptVersion (const char* Opt attribute ((unused)),
602 const char* Arg attribute ((unused)))
603 /* Print the assembler version */
605 fprintf (stderr, "ca65 V%s\n", GetVersionAsString ());
610 static void DoPCAssign (void)
611 /* Start absolute code */
613 long PC = ConstExpression ();
614 if (PC < 0 || PC > 0xFFFFFF) {
615 Error ("Range error");
617 EnterAbsoluteMode (PC);
623 static void OneLine (void)
624 /* Assemble one line */
627 unsigned long PC = 0;
632 /* Initialize the new listing line if we are actually reading from file
633 * and not from internally pushed input.
635 if (!HavePushedInput ()) {
639 /* Single colon means unnamed label */
640 if (CurTok.Tok == TOK_COLON) {
645 /* If the first token on the line is an identifier, check for a macro or
648 if (CurTok.Tok == TOK_IDENT) {
649 if (UbiquitousIdents) {
650 /* Macros CAN be instructions, so check for them first */
651 Mac = FindMacro (&CurTok.SVal);
653 Instr = FindInstruction (&CurTok.SVal);
656 /* Macros and symbols may NOT use the names of instructions */
657 Instr = FindInstruction (&CurTok.SVal);
659 Mac = FindMacro (&CurTok.SVal);
664 /* Handle an identifier. This may be a cheap local symbol, or a fully
665 * scoped identifier which may start with a namespace token (for global
668 if (CurTok.Tok == TOK_LOCAL_IDENT ||
669 CurTok.Tok == TOK_NAMESPACE ||
670 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
672 /* Did we have whitespace before the ident? */
673 int HadWS = CurTok.WS;
675 /* Generate the symbol table entry, then skip the name */
676 Sym = ParseAnySymName (SYM_ALLOC_NEW);
678 /* If a colon follows, this is a label definition. If there
679 * is no colon, it's an assignment.
681 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
683 /* Determine the symbol flags from the assignment token */
684 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
689 /* Define the symbol with the expression following the '=' */
690 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
692 /* Don't allow anything after a symbol definition */
696 } else if (CurTok.Tok == TOK_SET) {
700 /* .SET defines variables (= redefinable symbols) */
703 /* Read the assignment expression, which must be constant */
704 Expr = GenLiteralExpr (ConstExpression ());
706 /* Define the symbol with the constant expression following
709 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
711 /* Don't allow anything after a symbol definition */
717 /* A label. Remember the current segment, so we can later
718 * determine the size of the data stored under the label.
723 /* Define the label */
724 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
726 /* Skip the colon. If NoColonLabels is enabled, allow labels
727 * without a colon if there is no whitespace before the
730 if (CurTok.Tok != TOK_COLON) {
731 if (HadWS || !NoColonLabels) {
732 Error ("`:' expected");
733 /* Try some smart error recovery */
734 if (CurTok.Tok == TOK_NAMESPACE) {
743 /* If we come here, a new identifier may be waiting, which may
744 * be a macro or instruction.
746 if (CurTok.Tok == TOK_IDENT) {
747 if (UbiquitousIdents) {
748 /* Macros CAN be instructions, so check for them first */
749 Mac = FindMacro (&CurTok.SVal);
751 Instr = FindInstruction (&CurTok.SVal);
754 /* Macros and symbols may NOT use the names of instructions */
755 Instr = FindInstruction (&CurTok.SVal);
757 Mac = FindMacro (&CurTok.SVal);
764 /* We've handled a possible label, now handle the remainder of the line */
765 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
766 /* A control command */
768 } else if (Mac != 0) {
769 /* A macro expansion */
770 MacExpandStart (Mac);
771 } else if (Instr >= 0) {
772 /* A mnemonic - assemble one instruction */
773 HandleInstruction (Instr);
774 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
776 if (CurTok.Tok != TOK_EQ) {
777 Error ("`=' expected");
780 /* Skip the equal sign */
782 /* Enter absolute mode */
787 /* If we have defined a label, remember its size. Sym is also set by
788 * a symbol assignment, but in this case Done is false, so we don't
793 if (Seg == ActiveSeg) {
795 Size = GetPC () - PC;
797 /* The line has switched the segment */
800 DefSizeOfSymbol (Sym, Size);
803 /* Line separator must come here */
809 static void Assemble (void)
810 /* Start the ball rolling ... */
815 /* Assemble lines until end of file */
816 while (CurTok.Tok != TOK_EOF) {
823 static void CreateObjFile (void)
824 /* Create the object file */
826 /* Open the object, write the header */
829 /* Write the object file options */
832 /* Write the list of input files */
835 /* Write the segment data to the file */
838 /* Write the import list */
841 /* Write the export list */
844 /* Write debug symbols if requested */
847 /* Write the scopes if requested */
850 /* Write line infos if requested */
853 /* Write the string pool */
856 /* Write the assertions */
859 /* Write the spans */
862 /* Write an updated header and close the file */
868 int main (int argc, char* argv [])
869 /* Assembler main program */
871 /* Program long options */
872 static const LongOpt OptTab[] = {
873 { "--auto-import", 0, OptAutoImport },
874 { "--bin-include-dir", 1, OptBinIncludeDir },
875 { "--cpu", 1, OptCPU },
876 { "--create-dep", 1, OptCreateDep },
877 { "--create-full-dep", 1, OptCreateFullDep },
878 { "--debug", 0, OptDebug },
879 { "--debug-info", 0, OptDebugInfo },
880 { "--feature", 1, OptFeature },
881 { "--help", 0, OptHelp },
882 { "--ignore-case", 0, OptIgnoreCase },
883 { "--include-dir", 1, OptIncludeDir },
884 { "--large-alignment", 0, OptLargeAlignment },
885 { "--list-bytes", 1, OptListBytes },
886 { "--listing", 1, OptListing },
887 { "--memory-model", 1, OptMemoryModel },
888 { "--pagelength", 1, OptPageLength },
889 { "--relax-checks", 0, OptRelaxChecks },
890 { "--smart", 0, OptSmart },
891 { "--target", 1, OptTarget },
892 { "--verbose", 0, OptVerbose },
893 { "--version", 0, OptVersion },
896 /* Name of the global name space */
897 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
901 /* Initialize the cmdline module */
902 InitCmdLine (&argc, &argv, "ca65");
904 /* Initialize the string pool */
907 /* Initialize the include search paths */
910 /* Create the predefined segments */
913 /* Enter the base lexical level. We must do that here, since we may
914 * define symbols using -D.
916 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
918 /* Initialize the line infos. Must be done here, since we need line infos
919 * for symbol definitions.
923 /* Check the parameters */
925 while (I < ArgCount) {
927 /* Get the argument */
928 const char* Arg = ArgVec [I];
930 /* Check for an option */
935 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
943 OptDebugInfo (Arg, 0);
951 OptIgnoreCase (Arg, 0);
955 OptListing (Arg, GetArg (&I, 2));
960 OptMemoryModel (Arg, GetArg (&I, 3));
967 OutFile = GetArg (&I, 2);
975 OptTarget (Arg, GetArg (&I, 2));
983 DefineSymbol (GetArg (&I, 2));
987 OptIncludeDir (Arg, GetArg (&I, 2));
991 OptAutoImport (Arg, 0);
999 WarnLevel = atoi (GetArg (&I, 2));
1003 UnknownOption (Arg);
1008 /* Filename. Check if we already had one */
1010 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
1012 exit (EXIT_FAILURE);
1022 /* Do we have an input file? */
1024 fprintf (stderr, "%s: No input files\n", ProgName);
1025 exit (EXIT_FAILURE);
1028 /* Add the default include search paths. */
1029 FinishIncludePaths ();
1031 /* If no CPU given, use the default CPU for the target */
1032 if (GetCPU () == CPU_UNKNOWN) {
1033 if (Target != TGT_UNKNOWN) {
1034 SetCPU (GetTargetProperties (Target)->DefaultCPU);
1040 /* If no memory model was given, use the default */
1041 if (MemoryModel == MMODEL_UNKNOWN) {
1042 SetMemoryModel (MMODEL_NEAR);
1045 /* Set the default segment sizes according to the memory model */
1048 /* Initialize the scanner, open the input file */
1049 InitScanner (InFile);
1051 /* Define the default options */
1054 /* Assemble the input */
1057 /* If we didn't have any errors, check the pseudo insn stacks */
1058 if (ErrorCount == 0) {
1062 /* If we didn't have any errors, check and cleanup the unnamed labels */
1063 if (ErrorCount == 0) {
1067 /* If we didn't have any errors, check the symbol table */
1068 if (ErrorCount == 0) {
1072 /* If we didn't have any errors, check the hll debug symbols */
1073 if (ErrorCount == 0) {
1077 /* If we didn't have any errors, close the file scope lexical level */
1078 if (ErrorCount == 0) {
1082 /* If we didn't have any errors, check and resolve the segment data */
1083 if (ErrorCount == 0) {
1087 /* If we didn't have any errors, check the assertions */
1088 if (ErrorCount == 0) {
1093 if (Verbosity >= 2) {
1098 /* If we didn't have an errors, finish off the line infos */
1101 /* If we didn't have any errors, create the object, listing and
1104 if (ErrorCount == 0) {
1106 if (SB_GetLen (&ListingName) > 0) {
1109 CreateDependencies ();
1112 /* Close the input file */
1115 /* Return an apropriate exit code */
1116 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;