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 /*****************************************************************************/
47 #include "scopedefs.h"
84 /*****************************************************************************/
86 /*****************************************************************************/
90 static void Usage (void)
91 /* Print usage information and exit */
93 printf ("Usage: %s [options] file\n"
95 " -D name[=value]\t\tDefine a symbol\n"
96 " -I dir\t\t\tSet an include directory search path\n"
97 " -U\t\t\t\tMark unresolved symbols as import\n"
98 " -V\t\t\t\tPrint the assembler version\n"
99 " -W n\t\t\t\tSet warning level n\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-info\t\t\tAdd debug info to object file\n"
117 " --feature name\t\tSet an emulation feature\n"
118 " --forget-inc-paths\t\tForget include search paths\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 " --listing name\t\tCreate a listing file if assembly was ok\n"
123 " --list-bytes n\t\tMaximum number of bytes per listing line\n"
124 " --macpack-dir dir\t\tSet a macro package directory\n"
125 " --memory-model model\t\tSet the memory model\n"
126 " --pagelength n\t\tSet the page length for the listing\n"
127 " --smart\t\t\tEnable smart mode\n"
128 " --target sys\t\t\tSet the target system\n"
129 " --verbose\t\t\tIncrease verbosity\n"
130 " --version\t\t\tPrint the assembler version\n",
136 static void SetOptions (void)
137 /* Set the option for the translator */
139 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
141 /* Set the translator */
142 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
143 OptTranslator (&Buf);
145 /* Set date and time */
146 OptDateTime ((unsigned long) time(0));
148 /* Release memory for the string */
154 static void NewSymbol (const char* SymName, long Val)
155 /* Define a symbol with a fixed numeric value in the current scope */
160 /* Convert the name to a string buffer */
161 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
162 SB_CopyStr (&SymBuf, SymName);
164 /* Search for the symbol, allocate a new one if it doesn't exist */
165 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
167 /* Check if have already a symbol with this name */
168 if (SymIsDef (Sym)) {
169 AbEnd ("`%s' is already defined", SymName);
172 /* Generate an expression for the symbol */
173 Expr = GenLiteralExpr (Val);
175 /* Mark the symbol as defined */
176 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
178 /* Free string buffer memory */
184 static void CBMSystem (const char* Sys)
185 /* Define a CBM system */
187 NewSymbol ("__CBM__", 1);
193 static void SetSys (const char* Sys)
194 /* Define a target system */
196 switch (Target = FindTarget (Sys)) {
202 AbEnd ("Cannot use `module' as a target for the assembler");
206 NewSymbol ("__ATARI__", 1);
210 CBMSystem ("__C16__");
214 CBMSystem ("__C64__");
218 CBMSystem ("__VIC20__");
222 CBMSystem ("__C128__");
226 CBMSystem ("__PLUS4__");
230 CBMSystem ("__CBM510__");
234 CBMSystem ("__CBM610__");
238 CBMSystem ("__PET__");
242 NewSymbol ("__BBC__", 1);
246 NewSymbol ("__APPLE2__", 1);
250 NewSymbol ("__APPLE2ENH__", 1);
254 /* Do not handle as a CBM system */
255 NewSymbol ("__GEOS__", 1);
259 NewSymbol ("__LUNIX__", 1);
263 NewSymbol ("__ATMOS__", 1);
267 NewSymbol ("__NES__", 1);
270 case TGT_SUPERVISION:
271 NewSymbol ("__SUPERVISION__", 1);
275 NewSymbol ("__LYNX__", 1);
279 AbEnd ("Invalid target name: `%s'", Sys);
283 /* Initialize the translation tables for the target system */
289 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
290 /* Handle an option that remembers a file name for later */
292 /* Cannot have the option twice */
293 if (SB_NotEmpty (Name)) {
294 AbEnd ("Cannot use option `%s' twice", Opt);
296 /* Remember the file name for later */
297 SB_CopyStr (Name, Arg);
303 static void DefineSymbol (const char* Def)
304 /* Define a symbol from the command line */
309 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
312 /* The symbol must start with a character or underline */
313 if (!IsIdStart (Def [0])) {
318 /* Copy the symbol, checking the rest */
320 while (IsIdChar (*P)) {
321 SB_AppendChar (&SymName, *P++);
323 SB_Terminate (&SymName);
325 /* Do we have a value given? */
332 /* We have a value */
336 if (sscanf (P, "%lx", &Val) != 1) {
340 if (sscanf (P, "%li", &Val) != 1) {
346 /* Define the new symbol */
347 NewSymbol (SB_GetConstBuf (&SymName), Val);
349 /* Release string memory */
355 static void OptAutoImport (const char* Opt attribute ((unused)),
356 const char* Arg attribute ((unused)))
357 /* Mark unresolved symbols as imported */
364 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
365 /* Add an include search path for binaries */
367 AddSearchPath (BinSearchPath, Arg);
372 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
373 /* Handle the --cpu option */
375 cpu_t CPU = FindCPU (Arg);
376 if (CPU == CPU_UNKNOWN) {
377 AbEnd ("Invalid CPU: `%s'", Arg);
385 static void OptCreateDep (const char* Opt, const char* Arg)
386 /* Handle the --create-dep option */
388 FileNameOption (Opt, Arg, &DepName);
393 static void OptCreateFullDep (const char* Opt attribute ((unused)),
395 /* Handle the --create-full-dep option */
397 FileNameOption (Opt, Arg, &FullDepName);
402 static void OptDebugInfo (const char* Opt attribute ((unused)),
403 const char* Arg attribute ((unused)))
404 /* Add debug info to the object file */
411 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
412 /* Set an emulation feature */
414 /* Make a string buffer from Arg */
417 /* Set the feature, check for errors */
418 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
419 AbEnd ("Illegal emulation feature: `%s'", Arg);
425 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
426 const char* Arg attribute ((unused)))
427 /* Forget all currently defined include paths */
429 ForgetAllIncludePaths ();
434 static void OptHelp (const char* Opt attribute ((unused)),
435 const char* Arg attribute ((unused)))
436 /* Print usage information and exit */
444 static void OptIgnoreCase (const char* Opt attribute ((unused)),
445 const char* Arg attribute ((unused)))
446 /* Ignore case on symbols */
453 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
454 /* Add an include search path */
456 AddSearchPath (IncSearchPath, Arg);
461 static void OptListBytes (const char* Opt, const char* Arg)
462 /* Set the maximum number of bytes per listing line */
467 /* Convert the argument to a number */
468 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
472 /* Check the bounds */
473 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
474 AbEnd ("Argument for option `%s' is out of range", Opt);
483 static void OptListing (const char* Opt, const char* Arg)
484 /* Create a listing file */
486 /* Since the meaning of -l and --listing has changed, print an error if
487 * the filename is empty or begins with the option char.
489 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
490 Fatal ("The meaning of `%s' has changed. It does now "
491 "expect a file name as argument.", Opt);
494 /* Get the file name */
495 FileNameOption (Opt, Arg, &ListingName);
500 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
501 /* Set a macro package directory */
503 /* Make a string buffer from Arg */
506 /* Use the directory */
507 MacPackSetDir (SB_InitFromString (&Dir, Arg));
512 static void OptMemoryModel (const char* Opt, const char* Arg)
513 /* Set the memory model */
517 /* Check the current memory model */
518 if (MemoryModel != MMODEL_UNKNOWN) {
519 AbEnd ("Cannot use option `%s' twice", Opt);
522 /* Translate the memory model name and check it */
523 M = FindMemoryModel (Arg);
524 if (M == MMODEL_UNKNOWN) {
525 AbEnd ("Unknown memory model: %s", Arg);
526 } else if (M == MMODEL_HUGE) {
527 AbEnd ("Unsupported memory model: %s", Arg);
530 /* Set the memory model */
536 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
537 /* Handle the --pagelength option */
539 int Len = atoi (Arg);
540 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
541 AbEnd ("Invalid page length: %d", Len);
548 static void OptSmart (const char* Opt attribute ((unused)),
549 const char* Arg attribute ((unused)))
550 /* Handle the -s/--smart options */
557 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
558 /* Set the target system */
565 static void OptVerbose (const char* Opt attribute ((unused)),
566 const char* Arg attribute ((unused)))
567 /* Increase verbosity */
574 static void OptVersion (const char* Opt attribute ((unused)),
575 const char* Arg attribute ((unused)))
576 /* Print the assembler version */
578 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
583 static void DoPCAssign (void)
584 /* Start absolute code */
586 long PC = ConstExpression ();
587 if (PC < 0 || PC > 0xFFFFFF) {
588 Error ("Range error");
590 EnterAbsoluteMode (PC);
596 static void OneLine (void)
597 /* Assemble one line */
600 unsigned long PC = 0;
605 /* Initialize the new listing line if we are actually reading from file
606 * and not from internally pushed input.
608 if (!HavePushedInput ()) {
612 /* Single colon means unnamed label */
613 if (CurTok.Tok == TOK_COLON) {
618 /* If the first token on the line is an identifier, check for a macro or
621 if (CurTok.Tok == TOK_IDENT) {
622 if (!UbiquitousIdents) {
623 /* Macros and symbols cannot use instruction names */
624 Instr = FindInstruction (&CurTok.SVal);
626 Mac = FindMacro (&CurTok.SVal);
629 /* Macros and symbols may use the names of instructions */
630 Mac = FindMacro (&CurTok.SVal);
634 /* Handle an identifier. This may be a cheap local symbol, or a fully
635 * scoped identifier which may start with a namespace token (for global
638 if (CurTok.Tok == TOK_LOCAL_IDENT ||
639 CurTok.Tok == TOK_NAMESPACE ||
640 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
642 /* Did we have whitespace before the ident? */
643 int HadWS = CurTok.WS;
645 /* Generate the symbol table entry, then skip the name */
646 Sym = ParseAnySymName (SYM_ALLOC_NEW);
648 /* If a colon follows, this is a label definition. If there
649 * is no colon, it's an assignment.
651 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
653 /* Determine the symbol flags from the assignment token */
654 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
659 /* Define the symbol with the expression following the '=' */
660 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
662 /* Don't allow anything after a symbol definition */
666 } else if (CurTok.Tok == TOK_SET) {
670 /* .SET defines variables (= redefinable symbols) */
673 /* Read the assignment expression, which must be constant */
674 Expr = GenLiteralExpr (ConstExpression ());
676 /* Define the symbol with the constant expression following
679 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
681 /* Don't allow anything after a symbol definition */
687 /* A label. Remember the current segment, so we can later
688 * determine the size of the data stored under the label.
693 /* Define the label */
694 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
696 /* Skip the colon. If NoColonLabels is enabled, allow labels
697 * without a colon if there is no whitespace before the
700 if (CurTok.Tok != TOK_COLON) {
701 if (HadWS || !NoColonLabels) {
702 Error ("`:' expected");
703 /* Try some smart error recovery */
704 if (CurTok.Tok == TOK_NAMESPACE) {
713 /* If we come here, a new identifier may be waiting, which may
714 * be a macro or instruction.
716 if (CurTok.Tok == TOK_IDENT) {
717 if (!UbiquitousIdents) {
718 /* Macros and symbols cannot use instruction names */
719 Instr = FindInstruction (&CurTok.SVal);
721 Mac = FindMacro (&CurTok.SVal);
724 /* Macros and symbols may use the names of instructions */
725 Mac = FindMacro (&CurTok.SVal);
731 /* We've handled a possible label, now handle the remainder of the line */
732 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
733 /* A control command */
735 } else if (Mac != 0) {
736 /* A macro expansion */
737 MacExpandStart (Mac);
738 } else if (Instr >= 0 ||
739 (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
740 /* A mnemonic - assemble one instruction */
741 HandleInstruction (Instr);
742 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
744 if (CurTok.Tok != TOK_EQ) {
745 Error ("`=' expected");
748 /* Skip the equal sign */
750 /* Enter absolute mode */
755 /* If we have defined a label, remember its size. Sym is also set by
756 * a symbol assignment, but in this case Done is false, so we don't
761 if (Seg == ActiveSeg) {
763 Size = GetPC () - PC;
765 /* The line has switched the segment */
768 DefSizeOfSymbol (Sym, Size);
771 /* Line separator must come here */
777 static void Assemble (void)
778 /* Start the ball rolling ... */
783 /* Assemble lines until end of file */
784 while (CurTok.Tok != TOK_EOF) {
791 static void CreateObjFile (void)
792 /* Create the object file */
794 /* Open the object, write the header */
797 /* Write the object file options */
800 /* Write the list of input files */
803 /* Write the segment data to the file */
806 /* Write the import list */
809 /* Write the export list */
812 /* Write debug symbols if requested */
815 /* Write the scopes if requested */
818 /* Write line infos if requested */
821 /* Write the string pool */
824 /* Write the assertions */
827 /* Write the spans */
830 /* Write an updated header and close the file */
836 int main (int argc, char* argv [])
837 /* Assembler main program */
839 /* Program long options */
840 static const LongOpt OptTab[] = {
841 { "--auto-import", 0, OptAutoImport },
842 { "--bin-include-dir", 1, OptBinIncludeDir },
843 { "--cpu", 1, OptCPU },
844 { "--create-dep", 1, OptCreateDep },
845 { "--create-full-dep", 1, OptCreateFullDep },
846 { "--debug-info", 0, OptDebugInfo },
847 { "--feature", 1, OptFeature },
848 { "--forget-inc-paths", 0, OptForgetIncPaths },
849 { "--help", 0, OptHelp },
850 { "--ignore-case", 0, OptIgnoreCase },
851 { "--include-dir", 1, OptIncludeDir },
852 { "--list-bytes", 1, OptListBytes },
853 { "--listing", 1, OptListing },
854 { "--macpack-dir", 1, OptMacPackDir },
855 { "--memory-model", 1, OptMemoryModel },
856 { "--pagelength", 1, OptPageLength },
857 { "--smart", 0, OptSmart },
858 { "--target", 1, OptTarget },
859 { "--verbose", 0, OptVerbose },
860 { "--version", 0, OptVersion },
863 /* Name of the global name space */
864 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
868 /* Initialize the cmdline module */
869 InitCmdLine (&argc, &argv, "ca65");
871 /* Initialize the string pool */
874 /* Initialize the include search paths */
877 /* Create the predefined segments */
880 /* Enter the base lexical level. We must do that here, since we may
881 * define symbols using -D.
883 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
885 /* Initialize the line infos. Must be done here, since we need line infos
886 * for symbol definitions.
890 /* Check the parameters */
892 while (I < ArgCount) {
894 /* Get the argument */
895 const char* Arg = ArgVec [I];
897 /* Check for an option */
902 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
906 OptDebugInfo (Arg, 0);
914 OptIgnoreCase (Arg, 0);
918 OptListing (Arg, GetArg (&I, 2));
923 OptMemoryModel (Arg, GetArg (&I, 3));
930 OutFile = GetArg (&I, 2);
938 OptTarget (Arg, GetArg (&I, 2));
946 DefineSymbol (GetArg (&I, 2));
950 OptIncludeDir (Arg, GetArg (&I, 2));
954 OptAutoImport (Arg, 0);
962 WarnLevel = atoi (GetArg (&I, 2));
971 /* Filename. Check if we already had one */
973 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
985 /* Do we have an input file? */
987 fprintf (stderr, "%s: No input files\n", ProgName);
991 /* If no CPU given, use the default CPU for the target */
992 if (GetCPU () == CPU_UNKNOWN) {
993 if (Target != TGT_UNKNOWN) {
994 SetCPU (DefaultCPU[Target]);
1000 /* If no memory model was given, use the default */
1001 if (MemoryModel == MMODEL_UNKNOWN) {
1002 SetMemoryModel (MMODEL_NEAR);
1005 /* Set the default segment sizes according to the memory model */
1008 /* Initialize the scanner, open the input file */
1009 InitScanner (InFile);
1011 /* Define the default options */
1014 /* Assemble the input */
1017 /* If we didn't have any errors, check the pseudo insn stacks */
1018 if (ErrorCount == 0) {
1022 /* If we didn't have any errors, check and cleanup the unnamed labels */
1023 if (ErrorCount == 0) {
1027 /* If we didn't have any errors, check the symbol table */
1028 if (ErrorCount == 0) {
1032 /* If we didn't have any errors, check the hll debug symbols */
1033 if (ErrorCount == 0) {
1037 /* If we didn't have any errors, close the file scope lexical level */
1038 if (ErrorCount == 0) {
1042 /* If we didn't have any errors, check and resolve the segment data */
1043 if (ErrorCount == 0) {
1047 /* If we didn't have any errors, check the assertions */
1048 if (ErrorCount == 0) {
1053 if (Verbosity >= 2) {
1058 /* If we didn't have an errors, finish off the line infos */
1061 /* If we didn't have any errors, create the object, listing and
1064 if (ErrorCount == 0) {
1066 if (SB_GetLen (&ListingName) > 0) {
1069 CreateDependencies ();
1072 /* Close the input file */
1075 /* Return an apropriate exit code */
1076 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;