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 NewSymbol ("__OSIC1P__", 1);
306 AbEnd ("Invalid target name: `%s'", Sys);
310 /* Initialize the translation tables for the target system */
316 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
317 /* Handle an option that remembers a file name for later */
319 /* Cannot have the option twice */
320 if (SB_NotEmpty (Name)) {
321 AbEnd ("Cannot use option `%s' twice", Opt);
323 /* Remember the file name for later */
324 SB_CopyStr (Name, Arg);
330 static void DefineSymbol (const char* Def)
331 /* Define a symbol from the command line */
335 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
338 /* The symbol must start with a character or underline */
339 if (!IsIdStart (Def [0])) {
344 /* Copy the symbol, checking the rest */
345 while (IsIdChar (*P)) {
346 SB_AppendChar (&SymName, *P++);
348 SB_Terminate (&SymName);
350 /* Do we have a value given? */
357 /* We have a value */
361 if (sscanf (P, "%lx", &Val) != 1) {
365 if (sscanf (P, "%li", &Val) != 1) {
371 /* Define the new symbol */
372 NewSymbol (SB_GetConstBuf (&SymName), Val);
374 /* Release string memory */
380 static void OptAutoImport (const char* Opt attribute ((unused)),
381 const char* Arg attribute ((unused)))
382 /* Mark unresolved symbols as imported */
389 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
390 /* Add an include search path for binaries */
392 AddSearchPath (BinSearchPath, Arg);
397 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
398 /* Handle the --cpu option */
400 cpu_t CPU = FindCPU (Arg);
401 if (CPU == CPU_UNKNOWN) {
402 AbEnd ("Invalid CPU: `%s'", Arg);
410 static void OptCreateDep (const char* Opt, const char* Arg)
411 /* Handle the --create-dep option */
413 FileNameOption (Opt, Arg, &DepName);
418 static void OptCreateFullDep (const char* Opt attribute ((unused)),
420 /* Handle the --create-full-dep option */
422 FileNameOption (Opt, Arg, &FullDepName);
427 static void OptDebug (const char* Opt attribute ((unused)),
428 const char* Arg attribute ((unused)))
429 /* Compiler debug mode */
436 static void OptDebugInfo (const char* Opt attribute ((unused)),
437 const char* Arg attribute ((unused)))
438 /* Add debug info to the object file */
445 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
446 /* Set an emulation feature */
448 /* Make a string buffer from Arg */
451 /* Set the feature, check for errors */
452 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
453 AbEnd ("Illegal emulation feature: `%s'", Arg);
459 static void OptHelp (const char* Opt attribute ((unused)),
460 const char* Arg attribute ((unused)))
461 /* Print usage information and exit */
469 static void OptIgnoreCase (const char* Opt attribute ((unused)),
470 const char* Arg attribute ((unused)))
471 /* Ignore case on symbols */
478 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
479 /* Add an include search path */
481 AddSearchPath (IncSearchPath, Arg);
486 static void OptLargeAlignment (const char* Opt attribute ((unused)),
487 const char* Arg attribute ((unused)))
488 /* Don't warn about large alignments */
495 static void OptListBytes (const char* Opt, const char* Arg)
496 /* Set the maximum number of bytes per listing line */
501 /* Convert the argument to a number */
502 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
506 /* Check the bounds */
507 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
508 AbEnd ("Argument for option `%s' is out of range", Opt);
517 static void OptListing (const char* Opt, const char* Arg)
518 /* Create a listing file */
520 /* Since the meaning of -l and --listing has changed, print an error if
521 * the filename is empty or begins with the option char.
523 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
524 Fatal ("The meaning of `%s' has changed. It does now "
525 "expect a file name as argument.", Opt);
528 /* Get the file name */
529 FileNameOption (Opt, Arg, &ListingName);
534 static void OptMemoryModel (const char* Opt, const char* Arg)
535 /* Set the memory model */
539 /* Check the current memory model */
540 if (MemoryModel != MMODEL_UNKNOWN) {
541 AbEnd ("Cannot use option `%s' twice", Opt);
544 /* Translate the memory model name and check it */
545 M = FindMemoryModel (Arg);
546 if (M == MMODEL_UNKNOWN) {
547 AbEnd ("Unknown memory model: %s", Arg);
548 } else if (M == MMODEL_HUGE) {
549 AbEnd ("Unsupported memory model: %s", Arg);
552 /* Set the memory model */
558 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
559 /* Handle the --pagelength option */
561 int Len = atoi (Arg);
562 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
563 AbEnd ("Invalid page length: %d", Len);
570 static void OptRelaxChecks (const char* Opt attribute ((unused)),
571 const char* Arg attribute ((unused)))
572 /* Handle the --relax-checks options */
579 static void OptSmart (const char* Opt attribute ((unused)),
580 const char* Arg attribute ((unused)))
581 /* Handle the -s/--smart options */
588 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
589 /* Set the target system */
596 static void OptVerbose (const char* Opt attribute ((unused)),
597 const char* Arg attribute ((unused)))
598 /* Increase verbosity */
605 static void OptVersion (const char* Opt attribute ((unused)),
606 const char* Arg attribute ((unused)))
607 /* Print the assembler version */
609 fprintf (stderr, "ca65 V%s\n", GetVersionAsString ());
614 static void DoPCAssign (void)
615 /* Start absolute code */
617 long PC = ConstExpression ();
618 if (PC < 0 || PC > 0xFFFFFF) {
619 Error ("Range error");
621 EnterAbsoluteMode (PC);
627 static void OneLine (void)
628 /* Assemble one line */
631 unsigned long PC = 0;
636 /* Initialize the new listing line if we are actually reading from file
637 * and not from internally pushed input.
639 if (!HavePushedInput ()) {
643 /* Single colon means unnamed label */
644 if (CurTok.Tok == TOK_COLON) {
649 /* If the first token on the line is an identifier, check for a macro or
652 if (CurTok.Tok == TOK_IDENT) {
653 if (!UbiquitousIdents) {
654 /* Macros and symbols cannot use instruction names */
655 Instr = FindInstruction (&CurTok.SVal);
657 Mac = FindMacro (&CurTok.SVal);
660 /* Macros and symbols may use the names of instructions */
661 Mac = FindMacro (&CurTok.SVal);
665 /* Handle an identifier. This may be a cheap local symbol, or a fully
666 * scoped identifier which may start with a namespace token (for global
669 if (CurTok.Tok == TOK_LOCAL_IDENT ||
670 CurTok.Tok == TOK_NAMESPACE ||
671 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
673 /* Did we have whitespace before the ident? */
674 int HadWS = CurTok.WS;
676 /* Generate the symbol table entry, then skip the name */
677 Sym = ParseAnySymName (SYM_ALLOC_NEW);
679 /* If a colon follows, this is a label definition. If there
680 * is no colon, it's an assignment.
682 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
684 /* Determine the symbol flags from the assignment token */
685 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
690 /* Define the symbol with the expression following the '=' */
691 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
693 /* Don't allow anything after a symbol definition */
697 } else if (CurTok.Tok == TOK_SET) {
701 /* .SET defines variables (= redefinable symbols) */
704 /* Read the assignment expression, which must be constant */
705 Expr = GenLiteralExpr (ConstExpression ());
707 /* Define the symbol with the constant expression following
710 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
712 /* Don't allow anything after a symbol definition */
718 /* A label. Remember the current segment, so we can later
719 * determine the size of the data stored under the label.
724 /* Define the label */
725 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
727 /* Skip the colon. If NoColonLabels is enabled, allow labels
728 * without a colon if there is no whitespace before the
731 if (CurTok.Tok != TOK_COLON) {
732 if (HadWS || !NoColonLabels) {
733 Error ("`:' expected");
734 /* Try some smart error recovery */
735 if (CurTok.Tok == TOK_NAMESPACE) {
744 /* If we come here, a new identifier may be waiting, which may
745 * be a macro or instruction.
747 if (CurTok.Tok == TOK_IDENT) {
748 if (!UbiquitousIdents) {
749 /* Macros and symbols cannot use instruction names */
750 Instr = FindInstruction (&CurTok.SVal);
752 Mac = FindMacro (&CurTok.SVal);
755 /* Macros and symbols may use the names of instructions */
756 Mac = FindMacro (&CurTok.SVal);
762 /* We've handled a possible label, now handle the remainder of the line */
763 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
764 /* A control command */
766 } else if (Mac != 0) {
767 /* A macro expansion */
768 MacExpandStart (Mac);
769 } else if (Instr >= 0 ||
770 (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
771 /* A mnemonic - assemble one instruction */
772 HandleInstruction (Instr);
773 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
775 if (CurTok.Tok != TOK_EQ) {
776 Error ("`=' expected");
779 /* Skip the equal sign */
781 /* Enter absolute mode */
786 /* If we have defined a label, remember its size. Sym is also set by
787 * a symbol assignment, but in this case Done is false, so we don't
792 if (Seg == ActiveSeg) {
794 Size = GetPC () - PC;
796 /* The line has switched the segment */
799 DefSizeOfSymbol (Sym, Size);
802 /* Line separator must come here */
808 static void Assemble (void)
809 /* Start the ball rolling ... */
814 /* Assemble lines until end of file */
815 while (CurTok.Tok != TOK_EOF) {
822 static void CreateObjFile (void)
823 /* Create the object file */
825 /* Open the object, write the header */
828 /* Write the object file options */
831 /* Write the list of input files */
834 /* Write the segment data to the file */
837 /* Write the import list */
840 /* Write the export list */
843 /* Write debug symbols if requested */
846 /* Write the scopes if requested */
849 /* Write line infos if requested */
852 /* Write the string pool */
855 /* Write the assertions */
858 /* Write the spans */
861 /* Write an updated header and close the file */
867 int main (int argc, char* argv [])
868 /* Assembler main program */
870 /* Program long options */
871 static const LongOpt OptTab[] = {
872 { "--auto-import", 0, OptAutoImport },
873 { "--bin-include-dir", 1, OptBinIncludeDir },
874 { "--cpu", 1, OptCPU },
875 { "--create-dep", 1, OptCreateDep },
876 { "--create-full-dep", 1, OptCreateFullDep },
877 { "--debug", 0, OptDebug },
878 { "--debug-info", 0, OptDebugInfo },
879 { "--feature", 1, OptFeature },
880 { "--help", 0, OptHelp },
881 { "--ignore-case", 0, OptIgnoreCase },
882 { "--include-dir", 1, OptIncludeDir },
883 { "--large-alignment", 0, OptLargeAlignment },
884 { "--list-bytes", 1, OptListBytes },
885 { "--listing", 1, OptListing },
886 { "--memory-model", 1, OptMemoryModel },
887 { "--pagelength", 1, OptPageLength },
888 { "--relax-checks", 0, OptRelaxChecks },
889 { "--smart", 0, OptSmart },
890 { "--target", 1, OptTarget },
891 { "--verbose", 0, OptVerbose },
892 { "--version", 0, OptVersion },
895 /* Name of the global name space */
896 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
900 /* Initialize the cmdline module */
901 InitCmdLine (&argc, &argv, "ca65");
903 /* Initialize the string pool */
906 /* Initialize the include search paths */
909 /* Create the predefined segments */
912 /* Enter the base lexical level. We must do that here, since we may
913 * define symbols using -D.
915 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
917 /* Initialize the line infos. Must be done here, since we need line infos
918 * for symbol definitions.
922 /* Check the parameters */
924 while (I < ArgCount) {
926 /* Get the argument */
927 const char* Arg = ArgVec [I];
929 /* Check for an option */
934 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
942 OptDebugInfo (Arg, 0);
950 OptIgnoreCase (Arg, 0);
954 OptListing (Arg, GetArg (&I, 2));
959 OptMemoryModel (Arg, GetArg (&I, 3));
966 OutFile = GetArg (&I, 2);
974 OptTarget (Arg, GetArg (&I, 2));
982 DefineSymbol (GetArg (&I, 2));
986 OptIncludeDir (Arg, GetArg (&I, 2));
990 OptAutoImport (Arg, 0);
998 WarnLevel = atoi (GetArg (&I, 2));
1002 UnknownOption (Arg);
1007 /* Filename. Check if we already had one */
1009 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
1011 exit (EXIT_FAILURE);
1021 /* Do we have an input file? */
1023 fprintf (stderr, "%s: No input files\n", ProgName);
1024 exit (EXIT_FAILURE);
1027 /* Add the default include search paths. */
1028 FinishIncludePaths ();
1030 /* If no CPU given, use the default CPU for the target */
1031 if (GetCPU () == CPU_UNKNOWN) {
1032 if (Target != TGT_UNKNOWN) {
1033 SetCPU (GetTargetProperties (Target)->DefaultCPU);
1039 /* If no memory model was given, use the default */
1040 if (MemoryModel == MMODEL_UNKNOWN) {
1041 SetMemoryModel (MMODEL_NEAR);
1044 /* Set the default segment sizes according to the memory model */
1047 /* Initialize the scanner, open the input file */
1048 InitScanner (InFile);
1050 /* Define the default options */
1053 /* Assemble the input */
1056 /* If we didn't have any errors, check the pseudo insn stacks */
1057 if (ErrorCount == 0) {
1061 /* If we didn't have any errors, check and cleanup the unnamed labels */
1062 if (ErrorCount == 0) {
1066 /* If we didn't have any errors, check the symbol table */
1067 if (ErrorCount == 0) {
1071 /* If we didn't have any errors, check the hll debug symbols */
1072 if (ErrorCount == 0) {
1076 /* If we didn't have any errors, close the file scope lexical level */
1077 if (ErrorCount == 0) {
1081 /* If we didn't have any errors, check and resolve the segment data */
1082 if (ErrorCount == 0) {
1086 /* If we didn't have any errors, check the assertions */
1087 if (ErrorCount == 0) {
1092 if (Verbosity >= 2) {
1097 /* If we didn't have an errors, finish off the line infos */
1100 /* If we didn't have any errors, create the object, listing and
1103 if (ErrorCount == 0) {
1105 if (SB_GetLen (&ListingName) > 0) {
1108 CreateDependencies ();
1111 /* Close the input file */
1114 /* Return an apropriate exit code */
1115 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;