1 /*****************************************************************************/
5 /* Main program for the ca65 macroassembler */
9 /* (C) 1998-2011, 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 /*****************************************************************************/
81 /*****************************************************************************/
83 /*****************************************************************************/
87 static void Usage (void)
88 /* Print usage information and exit */
90 printf ("Usage: %s [options] file\n"
92 " -D name[=value]\t\tDefine a symbol\n"
93 " -I dir\t\t\tSet an include directory search path\n"
94 " -U\t\t\t\tMark unresolved symbols as import\n"
95 " -V\t\t\t\tPrint the assembler version\n"
96 " -W n\t\t\t\tSet warning level n\n"
97 " -g\t\t\t\tAdd debug info to object file\n"
98 " -h\t\t\t\tHelp (this text)\n"
99 " -i\t\t\t\tIgnore case of symbols\n"
100 " -l name\t\t\tCreate a listing file if assembly was ok\n"
101 " -mm model\t\t\tSet the memory model\n"
102 " -o name\t\t\tName the output file\n"
103 " -s\t\t\t\tEnable smart mode\n"
104 " -t sys\t\t\tSet the target system\n"
105 " -v\t\t\t\tIncrease verbosity\n"
108 " --auto-import\t\t\tMark unresolved symbols as import\n"
109 " --bin-include-dir dir\t\tSet a search path for binary includes\n"
110 " --cpu type\t\t\tSet cpu type\n"
111 " --create-dep name\t\tCreate a make dependency file\n"
112 " --create-full-dep name\tCreate a full make dependency file\n"
113 " --debug-info\t\t\tAdd debug info to object file\n"
114 " --feature name\t\tSet an emulation feature\n"
115 " --forget-inc-paths\t\tForget include search paths\n"
116 " --help\t\t\tHelp (this text)\n"
117 " --ignore-case\t\t\tIgnore case of symbols\n"
118 " --include-dir dir\t\tSet an include directory search path\n"
119 " --listing name\t\tCreate a listing file if assembly was ok\n"
120 " --list-bytes n\t\tMaximum number of bytes per listing line\n"
121 " --macpack-dir dir\t\tSet a macro package directory\n"
122 " --memory-model model\t\tSet the memory model\n"
123 " --pagelength n\t\tSet the page length for the listing\n"
124 " --smart\t\t\tEnable smart mode\n"
125 " --target sys\t\t\tSet the target system\n"
126 " --verbose\t\t\tIncrease verbosity\n"
127 " --version\t\t\tPrint the assembler version\n",
133 static void SetOptions (void)
134 /* Set the option for the translator */
136 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
138 /* Set the translator */
139 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
140 OptTranslator (&Buf);
142 /* Set date and time */
143 OptDateTime ((unsigned long) time(0));
145 /* Release memory for the string */
151 static void NewSymbol (const char* SymName, long Val)
152 /* Define a symbol with a fixed numeric value in the current scope */
157 /* Convert the name to a string buffer */
158 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
159 SB_CopyStr (&SymBuf, SymName);
161 /* Search for the symbol, allocate a new one if it doesn't exist */
162 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
164 /* Check if have already a symbol with this name */
165 if (SymIsDef (Sym)) {
166 AbEnd ("`%s' is already defined", SymName);
169 /* Generate an expression for the symbol */
170 Expr = GenLiteralExpr (Val);
172 /* Mark the symbol as defined */
173 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
175 /* Free string buffer memory */
181 static void CBMSystem (const char* Sys)
182 /* Define a CBM system */
184 NewSymbol ("__CBM__", 1);
190 static void SetSys (const char* Sys)
191 /* Define a target system */
193 switch (Target = FindTarget (Sys)) {
199 AbEnd ("Cannot use `module' as a target for the assembler");
203 NewSymbol ("__ATARI__", 1);
207 CBMSystem ("__C16__");
211 CBMSystem ("__C64__");
215 CBMSystem ("__VIC20__");
219 CBMSystem ("__C128__");
223 CBMSystem ("__PLUS4__");
227 CBMSystem ("__CBM510__");
231 CBMSystem ("__CBM610__");
235 CBMSystem ("__PET__");
239 NewSymbol ("__BBC__", 1);
243 NewSymbol ("__APPLE2__", 1);
247 NewSymbol ("__APPLE2ENH__", 1);
251 /* Do not handle as a CBM system */
252 NewSymbol ("__GEOS__", 1);
256 NewSymbol ("__LUNIX__", 1);
260 NewSymbol ("__ATMOS__", 1);
264 NewSymbol ("__NES__", 1);
267 case TGT_SUPERVISION:
268 NewSymbol ("__SUPERVISION__", 1);
272 NewSymbol ("__LYNX__", 1);
276 AbEnd ("Invalid target name: `%s'", Sys);
280 /* Initialize the translation tables for the target system */
286 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
287 /* Handle an option that remembers a file name for later */
289 /* Cannot have the option twice */
290 if (SB_NotEmpty (Name)) {
291 AbEnd ("Cannot use option `%s' twice", Opt);
293 /* Remember the file name for later */
294 SB_CopyStr (Name, Arg);
300 static void DefineSymbol (const char* Def)
301 /* Define a symbol from the command line */
306 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
309 /* The symbol must start with a character or underline */
310 if (!IsIdStart (Def [0])) {
315 /* Copy the symbol, checking the rest */
317 while (IsIdChar (*P)) {
318 SB_AppendChar (&SymName, *P++);
320 SB_Terminate (&SymName);
322 /* Do we have a value given? */
329 /* We have a value */
333 if (sscanf (P, "%lx", &Val) != 1) {
337 if (sscanf (P, "%li", &Val) != 1) {
343 /* Define the new symbol */
344 NewSymbol (SB_GetConstBuf (&SymName), Val);
346 /* Release string memory */
352 static void OptAutoImport (const char* Opt attribute ((unused)),
353 const char* Arg attribute ((unused)))
354 /* Mark unresolved symbols as imported */
361 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
362 /* Add an include search path for binaries */
364 AddSearchPath (BinSearchPath, Arg);
369 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
370 /* Handle the --cpu option */
372 cpu_t CPU = FindCPU (Arg);
373 if (CPU == CPU_UNKNOWN) {
374 AbEnd ("Invalid CPU: `%s'", Arg);
382 static void OptCreateDep (const char* Opt, const char* Arg)
383 /* Handle the --create-dep option */
385 FileNameOption (Opt, Arg, &DepName);
390 static void OptCreateFullDep (const char* Opt attribute ((unused)),
392 /* Handle the --create-full-dep option */
394 FileNameOption (Opt, Arg, &FullDepName);
399 static void OptDebugInfo (const char* Opt attribute ((unused)),
400 const char* Arg attribute ((unused)))
401 /* Add debug info to the object file */
408 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
409 /* Set an emulation feature */
411 /* Make a string buffer from Arg */
414 /* Set the feature, check for errors */
415 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
416 AbEnd ("Illegal emulation feature: `%s'", Arg);
422 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
423 const char* Arg attribute ((unused)))
424 /* Forget all currently defined include paths */
426 ForgetAllIncludePaths ();
431 static void OptHelp (const char* Opt attribute ((unused)),
432 const char* Arg attribute ((unused)))
433 /* Print usage information and exit */
441 static void OptIgnoreCase (const char* Opt attribute ((unused)),
442 const char* Arg attribute ((unused)))
443 /* Ignore case on symbols */
450 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
451 /* Add an include search path */
453 AddSearchPath (IncSearchPath, Arg);
458 static void OptListBytes (const char* Opt, const char* Arg)
459 /* Set the maximum number of bytes per listing line */
464 /* Convert the argument to a number */
465 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
469 /* Check the bounds */
470 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
471 AbEnd ("Argument for option `%s' is out of range", Opt);
480 static void OptListing (const char* Opt, const char* Arg)
481 /* Create a listing file */
483 /* Since the meaning of -l and --listing has changed, print an error if
484 * the filename is empty or begins with the option char.
486 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
487 Fatal ("The meaning of `%s' has changed. It does now "
488 "expect a file name as argument.", Opt);
491 /* Get the file name */
492 FileNameOption (Opt, Arg, &ListingName);
497 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
498 /* Set a macro package directory */
500 /* Make a string buffer from Arg */
503 /* Use the directory */
504 MacPackSetDir (SB_InitFromString (&Dir, Arg));
509 static void OptMemoryModel (const char* Opt, const char* Arg)
510 /* Set the memory model */
514 /* Check the current memory model */
515 if (MemoryModel != MMODEL_UNKNOWN) {
516 AbEnd ("Cannot use option `%s' twice", Opt);
519 /* Translate the memory model name and check it */
520 M = FindMemoryModel (Arg);
521 if (M == MMODEL_UNKNOWN) {
522 AbEnd ("Unknown memory model: %s", Arg);
523 } else if (M == MMODEL_HUGE) {
524 AbEnd ("Unsupported memory model: %s", Arg);
527 /* Set the memory model */
533 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
534 /* Handle the --pagelength option */
536 int Len = atoi (Arg);
537 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
538 AbEnd ("Invalid page length: %d", Len);
545 static void OptSmart (const char* Opt attribute ((unused)),
546 const char* Arg attribute ((unused)))
547 /* Handle the -s/--smart options */
554 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
555 /* Set the target system */
562 static void OptVerbose (const char* Opt attribute ((unused)),
563 const char* Arg attribute ((unused)))
564 /* Increase verbosity */
571 static void OptVersion (const char* Opt attribute ((unused)),
572 const char* Arg attribute ((unused)))
573 /* Print the assembler version */
575 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
580 static void DoPCAssign (void)
581 /* Start absolute code */
583 long PC = ConstExpression ();
584 if (PC < 0 || PC > 0xFFFFFF) {
585 Error ("Range error");
587 EnterAbsoluteMode (PC);
593 static void OneLine (void)
594 /* Assemble one line */
597 unsigned long PC = 0;
602 /* Initialize the new listing line if we are actually reading from file
603 * and not from internally pushed input.
605 if (!HavePushedInput ()) {
609 if (CurTok.Tok == TOK_COLON) {
610 /* An unnamed label */
615 /* If the first token on the line is an identifier, check for a macro or
618 if (CurTok.Tok == TOK_IDENT) {
619 if (!UbiquitousIdents) {
620 /* Macros and symbols cannot use instruction names */
621 Instr = FindInstruction (&CurTok.SVal);
623 Macro = IsMacro (&CurTok.SVal);
626 /* Macros and symbols may use the names of instructions */
627 Macro = IsMacro (&CurTok.SVal);
631 /* Handle an identifier. This may be a cheap local symbol, or a fully
632 * scoped identifier which may start with a namespace token (for global
635 if (CurTok.Tok == TOK_LOCAL_IDENT ||
636 CurTok.Tok == TOK_NAMESPACE ||
637 (CurTok.Tok == TOK_IDENT && Instr < 0 && !Macro)) {
639 /* Did we have whitespace before the ident? */
640 int HadWS = CurTok.WS;
642 /* Generate the symbol table entry, then skip the name */
643 Sym = ParseAnySymName (SYM_ALLOC_NEW);
645 /* If a colon follows, this is a label definition. If there
646 * is no colon, it's an assignment.
648 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
650 /* Determine the symbol flags from the assignment token */
651 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
656 /* Define the symbol with the expression following the '=' */
657 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
659 /* Don't allow anything after a symbol definition */
663 } else if (CurTok.Tok == TOK_SET) {
667 /* .SET defines variables (= redefinable symbols) */
670 /* Read the assignment expression, which must be constant */
671 Expr = GenLiteralExpr (ConstExpression ());
673 /* Define the symbol with the constant expression following
676 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
678 /* Don't allow anything after a symbol definition */
684 /* A label. Remember the current segment, so we can later
685 * determine the size of the data stored under the label.
690 /* Define the label */
691 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
693 /* Skip the colon. If NoColonLabels is enabled, allow labels
694 * without a colon if there is no whitespace before the
697 if (CurTok.Tok != TOK_COLON) {
698 if (HadWS || !NoColonLabels) {
699 Error ("`:' expected");
700 /* Try some smart error recovery */
701 if (CurTok.Tok == TOK_NAMESPACE) {
710 /* If we come here, a new identifier may be waiting, which may
711 * be a macro or instruction.
713 if (CurTok.Tok == TOK_IDENT) {
714 if (!UbiquitousIdents) {
715 /* Macros and symbols cannot use instruction names */
716 Instr = FindInstruction (&CurTok.SVal);
718 Macro = IsMacro (&CurTok.SVal);
721 /* Macros and symbols may use the names of instructions */
722 Macro = IsMacro (&CurTok.SVal);
728 /* We've handled a possible label, now handle the remainder of the line */
729 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
730 /* A control command */
733 /* A macro expansion */
735 } else if (Instr >= 0 ||
736 (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
737 /* A mnemonic - assemble one instruction */
738 HandleInstruction (Instr);
739 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
741 if (CurTok.Tok != TOK_EQ) {
742 Error ("`=' expected");
745 /* Skip the equal sign */
747 /* Enter absolute mode */
752 /* If we have defined a label, remember its size. Sym is also set by
753 * a symbol assignment, but in this case Done is false, so we don't
758 if (Seg == ActiveSeg) {
760 Size = GetPC () - PC;
762 /* The line has switched the segment */
765 DefSizeOfSymbol (Sym, Size);
768 /* Line separator must come here */
774 static void Assemble (void)
775 /* Start the ball rolling ... */
780 /* Assemble lines until end of file */
781 while (CurTok.Tok != TOK_EOF) {
788 static void CreateObjFile (void)
789 /* Create the object file */
791 /* Open the object, write the header */
794 /* Write the object file options */
797 /* Write the list of input files */
800 /* Write the segment data to the file */
803 /* Write the import list */
806 /* Write the export list */
809 /* Write the scopes if requested */
812 /* Write debug symbols if requested */
815 /* Write line infos if requested */
818 /* Write the string pool */
821 /* Write the assertions */
824 /* Write an updated header and close the file */
830 int main (int argc, char* argv [])
831 /* Assembler main program */
833 /* Program long options */
834 static const LongOpt OptTab[] = {
835 { "--auto-import", 0, OptAutoImport },
836 { "--bin-include-dir", 1, OptBinIncludeDir },
837 { "--cpu", 1, OptCPU },
838 { "--create-dep", 1, OptCreateDep },
839 { "--create-full-dep", 1, OptCreateFullDep },
840 { "--debug-info", 0, OptDebugInfo },
841 { "--feature", 1, OptFeature },
842 { "--forget-inc-paths", 0, OptForgetIncPaths },
843 { "--help", 0, OptHelp },
844 { "--ignore-case", 0, OptIgnoreCase },
845 { "--include-dir", 1, OptIncludeDir },
846 { "--list-bytes", 1, OptListBytes },
847 { "--listing", 1, OptListing },
848 { "--macpack-dir", 1, OptMacPackDir },
849 { "--memory-model", 1, OptMemoryModel },
850 { "--pagelength", 1, OptPageLength },
851 { "--smart", 0, OptSmart },
852 { "--target", 1, OptTarget },
853 { "--verbose", 0, OptVerbose },
854 { "--version", 0, OptVersion },
857 /* Name of the global name space */
858 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
862 /* Initialize the cmdline module */
863 InitCmdLine (&argc, &argv, "ca65");
865 /* Initialize the include search paths */
868 /* Enter the base lexical level. We must do that here, since we may
869 * define symbols using -D.
871 SymEnterLevel (&GlobalNameSpace, ST_GLOBAL, ADDR_SIZE_DEFAULT, 0);
873 /* Initialize the line infos. Must be done here, since we need line infos
874 * for symbol definitions.
878 /* Check the parameters */
880 while (I < ArgCount) {
882 /* Get the argument */
883 const char* Arg = ArgVec [I];
885 /* Check for an option */
890 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
894 OptDebugInfo (Arg, 0);
902 OptIgnoreCase (Arg, 0);
906 OptListing (Arg, GetArg (&I, 2));
911 OptMemoryModel (Arg, GetArg (&I, 3));
918 OutFile = GetArg (&I, 2);
926 OptTarget (Arg, GetArg (&I, 2));
934 DefineSymbol (GetArg (&I, 2));
938 OptIncludeDir (Arg, GetArg (&I, 2));
942 OptAutoImport (Arg, 0);
950 WarnLevel = atoi (GetArg (&I, 2));
959 /* Filename. Check if we already had one */
961 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
973 /* Do we have an input file? */
975 fprintf (stderr, "%s: No input files\n", ProgName);
979 /* If no CPU given, use the default CPU for the target */
980 if (GetCPU () == CPU_UNKNOWN) {
981 if (Target != TGT_UNKNOWN) {
982 SetCPU (DefaultCPU[Target]);
988 /* If no memory model was given, use the default */
989 if (MemoryModel == MMODEL_UNKNOWN) {
990 SetMemoryModel (MMODEL_NEAR);
993 /* Initialize the segments */
996 /* Initialize the scanner, open the input file */
997 InitScanner (InFile);
999 /* Define the default options */
1002 /* Assemble the input */
1005 /* If we didn't have any errors, check the pseudo insn stacks */
1006 if (ErrorCount == 0) {
1010 /* If we didn't have any errors, check the unnamed labels */
1011 if (ErrorCount == 0) {
1015 /* If we didn't have any errors, check the symbol table */
1016 if (ErrorCount == 0) {
1020 /* If we didn't have any errors, check and resolve the segment data */
1021 if (ErrorCount == 0) {
1025 /* If we didn't have any errors, check the assertions */
1026 if (ErrorCount == 0) {
1030 /* If we didn't have an errors, index the line infos */
1031 MakeLineInfoIndex ();
1034 if (Verbosity >= 2) {
1039 /* If we didn't have any errors, create the object, listing and
1042 if (ErrorCount == 0) {
1044 if (SB_GetLen (&ListingName) > 0) {
1047 CreateDependencies ();
1050 /* Close the input file */
1053 /* Return an apropriate exit code */
1054 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;