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 CBMSystem ("__C16__");
216 CBMSystem ("__C64__");
220 CBMSystem ("__VIC20__");
224 CBMSystem ("__C128__");
228 CBMSystem ("__PLUS4__");
232 CBMSystem ("__CBM510__");
236 CBMSystem ("__CBM610__");
240 CBMSystem ("__PET__");
244 NewSymbol ("__BBC__", 1);
248 NewSymbol ("__APPLE2__", 1);
252 NewSymbol ("__APPLE2ENH__", 1);
256 /* Do not handle as a CBM system */
257 NewSymbol ("__GEOS__", 1);
258 NewSymbol ("__GEOS_CBM__", 1);
262 NewSymbol ("__GEOS__", 1);
263 NewSymbol ("__GEOS_APPLE__", 1);
267 NewSymbol ("__LUNIX__", 1);
271 NewSymbol ("__ATMOS__", 1);
275 NewSymbol ("__NES__", 1);
278 case TGT_SUPERVISION:
279 NewSymbol ("__SUPERVISION__", 1);
283 NewSymbol ("__LYNX__", 1);
287 AbEnd ("Invalid target name: `%s'", Sys);
291 /* Initialize the translation tables for the target system */
297 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
298 /* Handle an option that remembers a file name for later */
300 /* Cannot have the option twice */
301 if (SB_NotEmpty (Name)) {
302 AbEnd ("Cannot use option `%s' twice", Opt);
304 /* Remember the file name for later */
305 SB_CopyStr (Name, Arg);
311 static void DefineSymbol (const char* Def)
312 /* Define a symbol from the command line */
316 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
319 /* The symbol must start with a character or underline */
320 if (!IsIdStart (Def [0])) {
325 /* Copy the symbol, checking the rest */
326 while (IsIdChar (*P)) {
327 SB_AppendChar (&SymName, *P++);
329 SB_Terminate (&SymName);
331 /* Do we have a value given? */
338 /* We have a value */
342 if (sscanf (P, "%lx", &Val) != 1) {
346 if (sscanf (P, "%li", &Val) != 1) {
352 /* Define the new symbol */
353 NewSymbol (SB_GetConstBuf (&SymName), Val);
355 /* Release string memory */
361 static void OptAutoImport (const char* Opt attribute ((unused)),
362 const char* Arg attribute ((unused)))
363 /* Mark unresolved symbols as imported */
370 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
371 /* Add an include search path for binaries */
373 AddSearchPath (BinSearchPath, Arg);
378 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
379 /* Handle the --cpu option */
381 cpu_t CPU = FindCPU (Arg);
382 if (CPU == CPU_UNKNOWN) {
383 AbEnd ("Invalid CPU: `%s'", Arg);
391 static void OptCreateDep (const char* Opt, const char* Arg)
392 /* Handle the --create-dep option */
394 FileNameOption (Opt, Arg, &DepName);
399 static void OptCreateFullDep (const char* Opt attribute ((unused)),
401 /* Handle the --create-full-dep option */
403 FileNameOption (Opt, Arg, &FullDepName);
408 static void OptDebug (const char* Opt attribute ((unused)),
409 const char* Arg attribute ((unused)))
410 /* Compiler debug mode */
417 static void OptDebugInfo (const char* Opt attribute ((unused)),
418 const char* Arg attribute ((unused)))
419 /* Add debug info to the object file */
426 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
427 /* Set an emulation feature */
429 /* Make a string buffer from Arg */
432 /* Set the feature, check for errors */
433 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
434 AbEnd ("Illegal emulation feature: `%s'", Arg);
440 static void OptHelp (const char* Opt attribute ((unused)),
441 const char* Arg attribute ((unused)))
442 /* Print usage information and exit */
450 static void OptIgnoreCase (const char* Opt attribute ((unused)),
451 const char* Arg attribute ((unused)))
452 /* Ignore case on symbols */
459 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
460 /* Add an include search path */
462 AddSearchPath (IncSearchPath, Arg);
467 static void OptLargeAlignment (const char* Opt attribute ((unused)),
468 const char* Arg attribute ((unused)))
469 /* Don't warn about large alignments */
476 static void OptListBytes (const char* Opt, const char* Arg)
477 /* Set the maximum number of bytes per listing line */
482 /* Convert the argument to a number */
483 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
487 /* Check the bounds */
488 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
489 AbEnd ("Argument for option `%s' is out of range", Opt);
498 static void OptListing (const char* Opt, const char* Arg)
499 /* Create a listing file */
501 /* Since the meaning of -l and --listing has changed, print an error if
502 * the filename is empty or begins with the option char.
504 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
505 Fatal ("The meaning of `%s' has changed. It does now "
506 "expect a file name as argument.", Opt);
509 /* Get the file name */
510 FileNameOption (Opt, Arg, &ListingName);
515 static void OptMemoryModel (const char* Opt, const char* Arg)
516 /* Set the memory model */
520 /* Check the current memory model */
521 if (MemoryModel != MMODEL_UNKNOWN) {
522 AbEnd ("Cannot use option `%s' twice", Opt);
525 /* Translate the memory model name and check it */
526 M = FindMemoryModel (Arg);
527 if (M == MMODEL_UNKNOWN) {
528 AbEnd ("Unknown memory model: %s", Arg);
529 } else if (M == MMODEL_HUGE) {
530 AbEnd ("Unsupported memory model: %s", Arg);
533 /* Set the memory model */
539 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
540 /* Handle the --pagelength option */
542 int Len = atoi (Arg);
543 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
544 AbEnd ("Invalid page length: %d", Len);
551 static void OptRelaxChecks (const char* Opt attribute ((unused)),
552 const char* Arg attribute ((unused)))
553 /* Handle the --relax-checks options */
560 static void OptSmart (const char* Opt attribute ((unused)),
561 const char* Arg attribute ((unused)))
562 /* Handle the -s/--smart options */
569 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
570 /* Set the target system */
577 static void OptVerbose (const char* Opt attribute ((unused)),
578 const char* Arg attribute ((unused)))
579 /* Increase verbosity */
586 static void OptVersion (const char* Opt attribute ((unused)),
587 const char* Arg attribute ((unused)))
588 /* Print the assembler version */
590 fprintf (stderr, "ca65 V%s\n", GetVersionAsString ());
595 static void DoPCAssign (void)
596 /* Start absolute code */
598 long PC = ConstExpression ();
599 if (PC < 0 || PC > 0xFFFFFF) {
600 Error ("Range error");
602 EnterAbsoluteMode (PC);
608 static void OneLine (void)
609 /* Assemble one line */
612 unsigned long PC = 0;
617 /* Initialize the new listing line if we are actually reading from file
618 * and not from internally pushed input.
620 if (!HavePushedInput ()) {
624 /* Single colon means unnamed label */
625 if (CurTok.Tok == TOK_COLON) {
630 /* If the first token on the line is an identifier, check for a macro or
633 if (CurTok.Tok == TOK_IDENT) {
634 if (!UbiquitousIdents) {
635 /* Macros and symbols cannot use instruction names */
636 Instr = FindInstruction (&CurTok.SVal);
638 Mac = FindMacro (&CurTok.SVal);
641 /* Macros and symbols may use the names of instructions */
642 Mac = FindMacro (&CurTok.SVal);
646 /* Handle an identifier. This may be a cheap local symbol, or a fully
647 * scoped identifier which may start with a namespace token (for global
650 if (CurTok.Tok == TOK_LOCAL_IDENT ||
651 CurTok.Tok == TOK_NAMESPACE ||
652 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
654 /* Did we have whitespace before the ident? */
655 int HadWS = CurTok.WS;
657 /* Generate the symbol table entry, then skip the name */
658 Sym = ParseAnySymName (SYM_ALLOC_NEW);
660 /* If a colon follows, this is a label definition. If there
661 * is no colon, it's an assignment.
663 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
665 /* Determine the symbol flags from the assignment token */
666 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
671 /* Define the symbol with the expression following the '=' */
672 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
674 /* Don't allow anything after a symbol definition */
678 } else if (CurTok.Tok == TOK_SET) {
682 /* .SET defines variables (= redefinable symbols) */
685 /* Read the assignment expression, which must be constant */
686 Expr = GenLiteralExpr (ConstExpression ());
688 /* Define the symbol with the constant expression following
691 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
693 /* Don't allow anything after a symbol definition */
699 /* A label. Remember the current segment, so we can later
700 * determine the size of the data stored under the label.
705 /* Define the label */
706 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
708 /* Skip the colon. If NoColonLabels is enabled, allow labels
709 * without a colon if there is no whitespace before the
712 if (CurTok.Tok != TOK_COLON) {
713 if (HadWS || !NoColonLabels) {
714 Error ("`:' expected");
715 /* Try some smart error recovery */
716 if (CurTok.Tok == TOK_NAMESPACE) {
725 /* If we come here, a new identifier may be waiting, which may
726 * be a macro or instruction.
728 if (CurTok.Tok == TOK_IDENT) {
729 if (!UbiquitousIdents) {
730 /* Macros and symbols cannot use instruction names */
731 Instr = FindInstruction (&CurTok.SVal);
733 Mac = FindMacro (&CurTok.SVal);
736 /* Macros and symbols may use the names of instructions */
737 Mac = FindMacro (&CurTok.SVal);
743 /* We've handled a possible label, now handle the remainder of the line */
744 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
745 /* A control command */
747 } else if (Mac != 0) {
748 /* A macro expansion */
749 MacExpandStart (Mac);
750 } else if (Instr >= 0 ||
751 (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
752 /* A mnemonic - assemble one instruction */
753 HandleInstruction (Instr);
754 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
756 if (CurTok.Tok != TOK_EQ) {
757 Error ("`=' expected");
760 /* Skip the equal sign */
762 /* Enter absolute mode */
767 /* If we have defined a label, remember its size. Sym is also set by
768 * a symbol assignment, but in this case Done is false, so we don't
773 if (Seg == ActiveSeg) {
775 Size = GetPC () - PC;
777 /* The line has switched the segment */
780 DefSizeOfSymbol (Sym, Size);
783 /* Line separator must come here */
789 static void Assemble (void)
790 /* Start the ball rolling ... */
795 /* Assemble lines until end of file */
796 while (CurTok.Tok != TOK_EOF) {
803 static void CreateObjFile (void)
804 /* Create the object file */
806 /* Open the object, write the header */
809 /* Write the object file options */
812 /* Write the list of input files */
815 /* Write the segment data to the file */
818 /* Write the import list */
821 /* Write the export list */
824 /* Write debug symbols if requested */
827 /* Write the scopes if requested */
830 /* Write line infos if requested */
833 /* Write the string pool */
836 /* Write the assertions */
839 /* Write the spans */
842 /* Write an updated header and close the file */
848 int main (int argc, char* argv [])
849 /* Assembler main program */
851 /* Program long options */
852 static const LongOpt OptTab[] = {
853 { "--auto-import", 0, OptAutoImport },
854 { "--bin-include-dir", 1, OptBinIncludeDir },
855 { "--cpu", 1, OptCPU },
856 { "--create-dep", 1, OptCreateDep },
857 { "--create-full-dep", 1, OptCreateFullDep },
858 { "--debug", 0, OptDebug },
859 { "--debug-info", 0, OptDebugInfo },
860 { "--feature", 1, OptFeature },
861 { "--help", 0, OptHelp },
862 { "--ignore-case", 0, OptIgnoreCase },
863 { "--include-dir", 1, OptIncludeDir },
864 { "--large-alignment", 0, OptLargeAlignment },
865 { "--list-bytes", 1, OptListBytes },
866 { "--listing", 1, OptListing },
867 { "--memory-model", 1, OptMemoryModel },
868 { "--pagelength", 1, OptPageLength },
869 { "--relax-checks", 0, OptRelaxChecks },
870 { "--smart", 0, OptSmart },
871 { "--target", 1, OptTarget },
872 { "--verbose", 0, OptVerbose },
873 { "--version", 0, OptVersion },
876 /* Name of the global name space */
877 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
881 /* Initialize the cmdline module */
882 InitCmdLine (&argc, &argv, "ca65");
884 /* Initialize the string pool */
887 /* Initialize the include search paths */
890 /* Create the predefined segments */
893 /* Enter the base lexical level. We must do that here, since we may
894 * define symbols using -D.
896 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
898 /* Initialize the line infos. Must be done here, since we need line infos
899 * for symbol definitions.
903 /* Check the parameters */
905 while (I < ArgCount) {
907 /* Get the argument */
908 const char* Arg = ArgVec [I];
910 /* Check for an option */
915 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
923 OptDebugInfo (Arg, 0);
931 OptIgnoreCase (Arg, 0);
935 OptListing (Arg, GetArg (&I, 2));
940 OptMemoryModel (Arg, GetArg (&I, 3));
947 OutFile = GetArg (&I, 2);
955 OptTarget (Arg, GetArg (&I, 2));
963 DefineSymbol (GetArg (&I, 2));
967 OptIncludeDir (Arg, GetArg (&I, 2));
971 OptAutoImport (Arg, 0);
979 WarnLevel = atoi (GetArg (&I, 2));
988 /* Filename. Check if we already had one */
990 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
1002 /* Do we have an input file? */
1004 fprintf (stderr, "%s: No input files\n", ProgName);
1005 exit (EXIT_FAILURE);
1008 /* Add the default include search paths. */
1009 FinishIncludePaths ();
1011 /* If no CPU given, use the default CPU for the target */
1012 if (GetCPU () == CPU_UNKNOWN) {
1013 if (Target != TGT_UNKNOWN) {
1014 SetCPU (GetTargetProperties (Target)->DefaultCPU);
1020 /* If no memory model was given, use the default */
1021 if (MemoryModel == MMODEL_UNKNOWN) {
1022 SetMemoryModel (MMODEL_NEAR);
1025 /* Set the default segment sizes according to the memory model */
1028 /* Initialize the scanner, open the input file */
1029 InitScanner (InFile);
1031 /* Define the default options */
1034 /* Assemble the input */
1037 /* If we didn't have any errors, check the pseudo insn stacks */
1038 if (ErrorCount == 0) {
1042 /* If we didn't have any errors, check and cleanup the unnamed labels */
1043 if (ErrorCount == 0) {
1047 /* If we didn't have any errors, check the symbol table */
1048 if (ErrorCount == 0) {
1052 /* If we didn't have any errors, check the hll debug symbols */
1053 if (ErrorCount == 0) {
1057 /* If we didn't have any errors, close the file scope lexical level */
1058 if (ErrorCount == 0) {
1062 /* If we didn't have any errors, check and resolve the segment data */
1063 if (ErrorCount == 0) {
1067 /* If we didn't have any errors, check the assertions */
1068 if (ErrorCount == 0) {
1073 if (Verbosity >= 2) {
1078 /* If we didn't have an errors, finish off the line infos */
1081 /* If we didn't have any errors, create the object, listing and
1084 if (ErrorCount == 0) {
1086 if (SB_GetLen (&ListingName) > 0) {
1089 CreateDependencies ();
1092 /* Close the input file */
1095 /* Return an apropriate exit code */
1096 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;