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 " --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 " --smart\t\t\tEnable smart mode\n"
129 " --target sys\t\t\tSet the target system\n"
130 " --verbose\t\t\tIncrease verbosity\n"
131 " --version\t\t\tPrint the assembler version\n",
137 static void SetOptions (void)
138 /* Set the option for the translator */
140 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
142 /* Set the translator */
143 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
144 OptTranslator (&Buf);
146 /* Set date and time */
147 OptDateTime ((unsigned long) time(0));
149 /* Release memory for the string */
155 static void NewSymbol (const char* SymName, long Val)
156 /* Define a symbol with a fixed numeric value in the current scope */
161 /* Convert the name to a string buffer */
162 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
163 SB_CopyStr (&SymBuf, SymName);
165 /* Search for the symbol, allocate a new one if it doesn't exist */
166 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
168 /* Check if have already a symbol with this name */
169 if (SymIsDef (Sym)) {
170 AbEnd ("`%s' is already defined", SymName);
173 /* Generate an expression for the symbol */
174 Expr = GenLiteralExpr (Val);
176 /* Mark the symbol as defined */
177 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
179 /* Free string buffer memory */
185 static void CBMSystem (const char* Sys)
186 /* Define a CBM system */
188 NewSymbol ("__CBM__", 1);
194 static void SetSys (const char* Sys)
195 /* Define a target system */
197 switch (Target = FindTarget (Sys)) {
203 AbEnd ("Cannot use `module' as a target for the assembler");
207 NewSymbol ("__ATARI__", 1);
211 CBMSystem ("__C16__");
215 CBMSystem ("__C64__");
219 CBMSystem ("__VIC20__");
223 CBMSystem ("__C128__");
227 CBMSystem ("__PLUS4__");
231 CBMSystem ("__CBM510__");
235 CBMSystem ("__CBM610__");
239 CBMSystem ("__PET__");
243 NewSymbol ("__BBC__", 1);
247 NewSymbol ("__APPLE2__", 1);
251 NewSymbol ("__APPLE2ENH__", 1);
255 /* Do not handle as a CBM system */
256 NewSymbol ("__GEOS__", 1);
257 NewSymbol ("__GEOS_CBM__", 1);
261 NewSymbol ("__GEOS__", 1);
262 NewSymbol ("__GEOS_APPLE__", 1);
266 NewSymbol ("__LUNIX__", 1);
270 NewSymbol ("__ATMOS__", 1);
274 NewSymbol ("__NES__", 1);
277 case TGT_SUPERVISION:
278 NewSymbol ("__SUPERVISION__", 1);
282 NewSymbol ("__LYNX__", 1);
286 AbEnd ("Invalid target name: `%s'", Sys);
290 /* Initialize the translation tables for the target system */
296 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
297 /* Handle an option that remembers a file name for later */
299 /* Cannot have the option twice */
300 if (SB_NotEmpty (Name)) {
301 AbEnd ("Cannot use option `%s' twice", Opt);
303 /* Remember the file name for later */
304 SB_CopyStr (Name, Arg);
310 static void DefineSymbol (const char* Def)
311 /* 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 */
327 while (IsIdChar (*P)) {
328 SB_AppendChar (&SymName, *P++);
330 SB_Terminate (&SymName);
332 /* Do we have a value given? */
339 /* We have a value */
343 if (sscanf (P, "%lx", &Val) != 1) {
347 if (sscanf (P, "%li", &Val) != 1) {
353 /* Define the new symbol */
354 NewSymbol (SB_GetConstBuf (&SymName), Val);
356 /* Release string memory */
362 static void OptAutoImport (const char* Opt attribute ((unused)),
363 const char* Arg attribute ((unused)))
364 /* Mark unresolved symbols as imported */
371 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
372 /* Add an include search path for binaries */
374 AddSearchPath (BinSearchPath, Arg);
379 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
380 /* Handle the --cpu option */
382 cpu_t CPU = FindCPU (Arg);
383 if (CPU == CPU_UNKNOWN) {
384 AbEnd ("Invalid CPU: `%s'", Arg);
392 static void OptCreateDep (const char* Opt, const char* Arg)
393 /* Handle the --create-dep option */
395 FileNameOption (Opt, Arg, &DepName);
400 static void OptCreateFullDep (const char* Opt attribute ((unused)),
402 /* Handle the --create-full-dep option */
404 FileNameOption (Opt, Arg, &FullDepName);
409 static void OptDebugInfo (const char* Opt attribute ((unused)),
410 const char* Arg attribute ((unused)))
411 /* Add debug info to the object file */
418 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
419 /* Set an emulation feature */
421 /* Make a string buffer from Arg */
424 /* Set the feature, check for errors */
425 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
426 AbEnd ("Illegal emulation feature: `%s'", Arg);
432 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
433 const char* Arg attribute ((unused)))
434 /* Forget all currently defined include paths */
436 ForgetAllIncludePaths ();
441 static void OptHelp (const char* Opt attribute ((unused)),
442 const char* Arg attribute ((unused)))
443 /* Print usage information and exit */
451 static void OptIgnoreCase (const char* Opt attribute ((unused)),
452 const char* Arg attribute ((unused)))
453 /* Ignore case on symbols */
460 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
461 /* Add an include search path */
463 AddSearchPath (IncSearchPath, Arg);
468 static void OptLargeAlignment (const char* Opt attribute ((unused)),
469 const char* Arg attribute ((unused)))
470 /* Don't warn about large alignments */
477 static void OptListBytes (const char* Opt, const char* Arg)
478 /* Set the maximum number of bytes per listing line */
483 /* Convert the argument to a number */
484 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
488 /* Check the bounds */
489 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
490 AbEnd ("Argument for option `%s' is out of range", Opt);
499 static void OptListing (const char* Opt, const char* Arg)
500 /* Create a listing file */
502 /* Since the meaning of -l and --listing has changed, print an error if
503 * the filename is empty or begins with the option char.
505 if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
506 Fatal ("The meaning of `%s' has changed. It does now "
507 "expect a file name as argument.", Opt);
510 /* Get the file name */
511 FileNameOption (Opt, Arg, &ListingName);
516 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
517 /* Set a macro package directory */
519 /* Make a string buffer from Arg */
522 /* Use the directory */
523 MacPackSetDir (SB_InitFromString (&Dir, Arg));
528 static void OptMemoryModel (const char* Opt, const char* Arg)
529 /* Set the memory model */
533 /* Check the current memory model */
534 if (MemoryModel != MMODEL_UNKNOWN) {
535 AbEnd ("Cannot use option `%s' twice", Opt);
538 /* Translate the memory model name and check it */
539 M = FindMemoryModel (Arg);
540 if (M == MMODEL_UNKNOWN) {
541 AbEnd ("Unknown memory model: %s", Arg);
542 } else if (M == MMODEL_HUGE) {
543 AbEnd ("Unsupported memory model: %s", Arg);
546 /* Set the memory model */
552 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
553 /* Handle the --pagelength option */
555 int Len = atoi (Arg);
556 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
557 AbEnd ("Invalid page length: %d", Len);
564 static void OptSmart (const char* Opt attribute ((unused)),
565 const char* Arg attribute ((unused)))
566 /* Handle the -s/--smart options */
573 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
574 /* Set the target system */
581 static void OptVerbose (const char* Opt attribute ((unused)),
582 const char* Arg attribute ((unused)))
583 /* Increase verbosity */
590 static void OptVersion (const char* Opt attribute ((unused)),
591 const char* Arg attribute ((unused)))
592 /* Print the assembler version */
594 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
599 static void DoPCAssign (void)
600 /* Start absolute code */
602 long PC = ConstExpression ();
603 if (PC < 0 || PC > 0xFFFFFF) {
604 Error ("Range error");
606 EnterAbsoluteMode (PC);
612 static void OneLine (void)
613 /* Assemble one line */
616 unsigned long PC = 0;
621 /* Initialize the new listing line if we are actually reading from file
622 * and not from internally pushed input.
624 if (!HavePushedInput ()) {
628 /* Single colon means unnamed label */
629 if (CurTok.Tok == TOK_COLON) {
634 /* If the first token on the line is an identifier, check for a macro or
637 if (CurTok.Tok == TOK_IDENT) {
638 if (!UbiquitousIdents) {
639 /* Macros and symbols cannot use instruction names */
640 Instr = FindInstruction (&CurTok.SVal);
642 Mac = FindMacro (&CurTok.SVal);
645 /* Macros and symbols may use the names of instructions */
646 Mac = FindMacro (&CurTok.SVal);
650 /* Handle an identifier. This may be a cheap local symbol, or a fully
651 * scoped identifier which may start with a namespace token (for global
654 if (CurTok.Tok == TOK_LOCAL_IDENT ||
655 CurTok.Tok == TOK_NAMESPACE ||
656 (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
658 /* Did we have whitespace before the ident? */
659 int HadWS = CurTok.WS;
661 /* Generate the symbol table entry, then skip the name */
662 Sym = ParseAnySymName (SYM_ALLOC_NEW);
664 /* If a colon follows, this is a label definition. If there
665 * is no colon, it's an assignment.
667 if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
669 /* Determine the symbol flags from the assignment token */
670 unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
675 /* Define the symbol with the expression following the '=' */
676 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
678 /* Don't allow anything after a symbol definition */
682 } else if (CurTok.Tok == TOK_SET) {
686 /* .SET defines variables (= redefinable symbols) */
689 /* Read the assignment expression, which must be constant */
690 Expr = GenLiteralExpr (ConstExpression ());
692 /* Define the symbol with the constant expression following
695 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
697 /* Don't allow anything after a symbol definition */
703 /* A label. Remember the current segment, so we can later
704 * determine the size of the data stored under the label.
709 /* Define the label */
710 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
712 /* Skip the colon. If NoColonLabels is enabled, allow labels
713 * without a colon if there is no whitespace before the
716 if (CurTok.Tok != TOK_COLON) {
717 if (HadWS || !NoColonLabels) {
718 Error ("`:' expected");
719 /* Try some smart error recovery */
720 if (CurTok.Tok == TOK_NAMESPACE) {
729 /* If we come here, a new identifier may be waiting, which may
730 * be a macro or instruction.
732 if (CurTok.Tok == TOK_IDENT) {
733 if (!UbiquitousIdents) {
734 /* Macros and symbols cannot use instruction names */
735 Instr = FindInstruction (&CurTok.SVal);
737 Mac = FindMacro (&CurTok.SVal);
740 /* Macros and symbols may use the names of instructions */
741 Mac = FindMacro (&CurTok.SVal);
747 /* We've handled a possible label, now handle the remainder of the line */
748 if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
749 /* A control command */
751 } else if (Mac != 0) {
752 /* A macro expansion */
753 MacExpandStart (Mac);
754 } else if (Instr >= 0 ||
755 (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
756 /* A mnemonic - assemble one instruction */
757 HandleInstruction (Instr);
758 } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
760 if (CurTok.Tok != TOK_EQ) {
761 Error ("`=' expected");
764 /* Skip the equal sign */
766 /* Enter absolute mode */
771 /* If we have defined a label, remember its size. Sym is also set by
772 * a symbol assignment, but in this case Done is false, so we don't
777 if (Seg == ActiveSeg) {
779 Size = GetPC () - PC;
781 /* The line has switched the segment */
784 DefSizeOfSymbol (Sym, Size);
787 /* Line separator must come here */
793 static void Assemble (void)
794 /* Start the ball rolling ... */
799 /* Assemble lines until end of file */
800 while (CurTok.Tok != TOK_EOF) {
807 static void CreateObjFile (void)
808 /* Create the object file */
810 /* Open the object, write the header */
813 /* Write the object file options */
816 /* Write the list of input files */
819 /* Write the segment data to the file */
822 /* Write the import list */
825 /* Write the export list */
828 /* Write debug symbols if requested */
831 /* Write the scopes if requested */
834 /* Write line infos if requested */
837 /* Write the string pool */
840 /* Write the assertions */
843 /* Write the spans */
846 /* Write an updated header and close the file */
852 int main (int argc, char* argv [])
853 /* Assembler main program */
855 /* Program long options */
856 static const LongOpt OptTab[] = {
857 { "--auto-import", 0, OptAutoImport },
858 { "--bin-include-dir", 1, OptBinIncludeDir },
859 { "--cpu", 1, OptCPU },
860 { "--create-dep", 1, OptCreateDep },
861 { "--create-full-dep", 1, OptCreateFullDep },
862 { "--debug-info", 0, OptDebugInfo },
863 { "--feature", 1, OptFeature },
864 { "--forget-inc-paths", 0, OptForgetIncPaths },
865 { "--help", 0, OptHelp },
866 { "--ignore-case", 0, OptIgnoreCase },
867 { "--include-dir", 1, OptIncludeDir },
868 { "--large-alignment", 0, OptLargeAlignment },
869 { "--list-bytes", 1, OptListBytes },
870 { "--listing", 1, OptListing },
871 { "--macpack-dir", 1, OptMacPackDir },
872 { "--memory-model", 1, OptMemoryModel },
873 { "--pagelength", 1, OptPageLength },
874 { "--smart", 0, OptSmart },
875 { "--target", 1, OptTarget },
876 { "--verbose", 0, OptVerbose },
877 { "--version", 0, OptVersion },
880 /* Name of the global name space */
881 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
885 /* Initialize the cmdline module */
886 InitCmdLine (&argc, &argv, "ca65");
888 /* Initialize the string pool */
891 /* Initialize the include search paths */
894 /* Create the predefined segments */
897 /* Enter the base lexical level. We must do that here, since we may
898 * define symbols using -D.
900 SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
902 /* Initialize the line infos. Must be done here, since we need line infos
903 * for symbol definitions.
907 /* Check the parameters */
909 while (I < ArgCount) {
911 /* Get the argument */
912 const char* Arg = ArgVec [I];
914 /* Check for an option */
919 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 /* If no CPU given, use the default CPU for the target */
1009 if (GetCPU () == CPU_UNKNOWN) {
1010 if (Target != TGT_UNKNOWN) {
1011 SetCPU (GetTargetProperties (Target)->DefaultCPU);
1017 /* If no memory model was given, use the default */
1018 if (MemoryModel == MMODEL_UNKNOWN) {
1019 SetMemoryModel (MMODEL_NEAR);
1022 /* Set the default segment sizes according to the memory model */
1025 /* Initialize the scanner, open the input file */
1026 InitScanner (InFile);
1028 /* Define the default options */
1031 /* Assemble the input */
1034 /* If we didn't have any errors, check the pseudo insn stacks */
1035 if (ErrorCount == 0) {
1039 /* If we didn't have any errors, check and cleanup the unnamed labels */
1040 if (ErrorCount == 0) {
1044 /* If we didn't have any errors, check the symbol table */
1045 if (ErrorCount == 0) {
1049 /* If we didn't have any errors, check the hll debug symbols */
1050 if (ErrorCount == 0) {
1054 /* If we didn't have any errors, close the file scope lexical level */
1055 if (ErrorCount == 0) {
1059 /* If we didn't have any errors, check and resolve the segment data */
1060 if (ErrorCount == 0) {
1064 /* If we didn't have any errors, check the assertions */
1065 if (ErrorCount == 0) {
1070 if (Verbosity >= 2) {
1075 /* If we didn't have an errors, finish off the line infos */
1078 /* If we didn't have any errors, create the object, listing and
1081 if (ErrorCount == 0) {
1083 if (SB_GetLen (&ListingName) > 0) {
1086 CreateDependencies ();
1089 /* Close the input file */
1092 /* Return an apropriate exit code */
1093 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;