1 /*****************************************************************************/
5 /* Main program for the ca65 macroassembler */
9 /* (C) 1998-2009, 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]\tDefine a symbol\n"
93 " -I dir\t\tSet an include directory search path\n"
94 " -U\t\t\tMark unresolved symbols as import\n"
95 " -V\t\t\tPrint the assembler version\n"
96 " -W n\t\t\tSet warning level n\n"
97 " -g\t\t\tAdd debug info to object file\n"
98 " -h\t\t\tHelp (this text)\n"
99 " -i\t\t\tIgnore case of symbols\n"
100 " -l\t\t\tCreate a listing if assembly was ok\n"
101 " -mm model\t\tSet the memory model\n"
102 " -o name\t\tName the output file\n"
103 " -s\t\t\tEnable smart mode\n"
104 " -t sys\t\tSet the target system\n"
105 " -v\t\t\tIncrease verbosity\n"
108 " --auto-import\t\tMark unresolved symbols as import\n"
109 " --cpu type\t\tSet cpu type\n"
110 " --debug-info\t\tAdd debug info to object file\n"
111 " --feature name\tSet an emulation feature\n"
112 " --forget-inc-paths\tForget include search paths\n"
113 " --help\t\tHelp (this text)\n"
114 " --ignore-case\t\tIgnore case of symbols\n"
115 " --include-dir dir\tSet an include directory search path\n"
116 " --listing\t\tCreate a listing if assembly was ok\n"
117 " --list-bytes n\tMaximum number of bytes per listing line\n"
118 " --macpack-dir dir\tSet a macro package directory\n"
119 " --memory-model model\tSet the memory model\n"
120 " --pagelength n\tSet the page length for the listing\n"
121 " --smart\t\tEnable smart mode\n"
122 " --target sys\t\tSet the target system\n"
123 " --verbose\t\tIncrease verbosity\n"
124 " --version\t\tPrint the assembler version\n",
130 static void SetOptions (void)
131 /* Set the option for the translator */
133 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
135 /* Set the translator */
136 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
137 OptTranslator (&Buf);
139 /* Set date and time */
140 OptDateTime ((unsigned long) time(0));
142 /* Release memory for the string */
148 static void NewSymbol (const char* SymName, long Val)
149 /* Define a symbol with a fixed numeric value in the current scope */
154 /* Convert the name to a string buffer */
155 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
156 SB_CopyStr (&SymBuf, SymName);
158 /* Search for the symbol, allocate a new one if it doesn't exist */
159 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
161 /* Check if have already a symbol with this name */
162 if (SymIsDef (Sym)) {
163 AbEnd ("`%s' is already defined", SymName);
166 /* Generate an expression for the symbol */
167 Expr = GenLiteralExpr (Val);
169 /* Mark the symbol as defined */
170 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
172 /* Free string buffer memory */
178 static void CBMSystem (const char* Sys)
179 /* Define a CBM system */
181 NewSymbol ("__CBM__", 1);
187 static void SetSys (const char* Sys)
188 /* Define a target system */
190 switch (Target = FindTarget (Sys)) {
196 AbEnd ("Cannot use `module' as a target for the assembler");
200 NewSymbol ("__ATARI__", 1);
204 CBMSystem ("__C16__");
208 CBMSystem ("__C64__");
212 CBMSystem ("__VIC20__");
216 CBMSystem ("__C128__");
220 CBMSystem ("__PLUS4__");
224 CBMSystem ("__CBM510__");
228 CBMSystem ("__CBM610__");
232 CBMSystem ("__PET__");
236 NewSymbol ("__BBC__", 1);
240 NewSymbol ("__APPLE2__", 1);
244 NewSymbol ("__APPLE2ENH__", 1);
248 /* Do not handle as a CBM system */
249 NewSymbol ("__GEOS__", 1);
253 NewSymbol ("__LUNIX__", 1);
257 NewSymbol ("__ATMOS__", 1);
261 NewSymbol ("__NES__", 1);
264 case TGT_SUPERVISION:
265 NewSymbol ("__SUPERVISION__", 1);
269 NewSymbol ("__LYNX__", 1);
273 AbEnd ("Invalid target name: `%s'", Sys);
277 /* Initialize the translation tables for the target system */
283 static void DefineSymbol (const char* Def)
284 /* Define a symbol from the command line */
289 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
292 /* The symbol must start with a character or underline */
293 if (!IsIdStart (Def [0])) {
298 /* Copy the symbol, checking the rest */
300 while (IsIdChar (*P)) {
301 SB_AppendChar (&SymName, *P++);
303 SB_Terminate (&SymName);
305 /* Do we have a value given? */
312 /* We have a value */
316 if (sscanf (P, "%lx", &Val) != 1) {
320 if (sscanf (P, "%li", &Val) != 1) {
326 /* Define the new symbol */
327 NewSymbol (SB_GetConstBuf (&SymName), Val);
329 /* Release string memory */
335 static void OptAutoImport (const char* Opt attribute ((unused)),
336 const char* Arg attribute ((unused)))
337 /* Mark unresolved symbols as imported */
344 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
345 /* Handle the --cpu option */
347 cpu_t CPU = FindCPU (Arg);
348 if (CPU == CPU_UNKNOWN) {
349 AbEnd ("Invalid CPU: `%s'", Arg);
357 static void OptDebugInfo (const char* Opt attribute ((unused)),
358 const char* Arg attribute ((unused)))
359 /* Add debug info to the object file */
366 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
367 /* Set an emulation feature */
369 /* Make a string buffer from Arg */
372 /* Set the feature, check for errors */
373 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
374 AbEnd ("Illegal emulation feature: `%s'", Arg);
380 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
381 const char* Arg attribute ((unused)))
382 /* Forget all currently defined include paths */
384 ForgetAllIncludePaths ();
389 static void OptHelp (const char* Opt attribute ((unused)),
390 const char* Arg attribute ((unused)))
391 /* Print usage information and exit */
399 static void OptIgnoreCase (const char* Opt attribute ((unused)),
400 const char* Arg attribute ((unused)))
401 /* Ignore case on symbols */
408 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
409 /* Add an include search path */
411 AddIncludePath (Arg);
416 static void OptListBytes (const char* Opt, const char* Arg)
417 /* Set the maximum number of bytes per listing line */
422 /* Convert the argument to a number */
423 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
427 /* Check the bounds */
428 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
429 AbEnd ("Argument for option `%s' is out of range", Opt);
438 static void OptListing (const char* Opt attribute ((unused)),
439 const char* Arg attribute ((unused)))
440 /* Create a listing file */
447 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
448 /* Set a macro package directory */
450 /* Make a string buffer from Arg */
453 /* Use the directory */
454 MacPackSetDir (SB_InitFromString (&Dir, Arg));
459 static void OptMemoryModel (const char* Opt, const char* Arg)
460 /* Set the memory model */
464 /* Check the current memory model */
465 if (MemoryModel != MMODEL_UNKNOWN) {
466 AbEnd ("Cannot use option `%s' twice", Opt);
469 /* Translate the memory model name and check it */
470 M = FindMemoryModel (Arg);
471 if (M == MMODEL_UNKNOWN) {
472 AbEnd ("Unknown memory model: %s", Arg);
473 } else if (M == MMODEL_HUGE) {
474 AbEnd ("Unsupported memory model: %s", Arg);
477 /* Set the memory model */
483 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
484 /* Handle the --pagelength option */
486 int Len = atoi (Arg);
487 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
488 AbEnd ("Invalid page length: %d", Len);
495 static void OptSmart (const char* Opt attribute ((unused)),
496 const char* Arg attribute ((unused)))
497 /* Handle the -s/--smart options */
504 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
505 /* Set the target system */
512 static void OptVerbose (const char* Opt attribute ((unused)),
513 const char* Arg attribute ((unused)))
514 /* Increase verbosity */
521 static void OptVersion (const char* Opt attribute ((unused)),
522 const char* Arg attribute ((unused)))
523 /* Print the assembler version */
525 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
530 static void DoPCAssign (void)
531 /* Start absolute code */
533 long PC = ConstExpression ();
534 if (PC < 0 || PC > 0xFFFFFF) {
535 Error ("Range error");
537 EnterAbsoluteMode (PC);
543 static void OneLine (void)
544 /* Assemble one line */
547 unsigned long PC = 0;
552 /* Initialize the new listing line if we are actually reading from file
553 * and not from internally pushed input.
555 if (!HavePushedInput ()) {
559 if (Tok == TOK_COLON) {
560 /* An unnamed label */
565 /* If the first token on the line is an identifier, check for a macro or
568 if (Tok == TOK_IDENT) {
569 if (!UbiquitousIdents) {
570 /* Macros and symbols cannot use instruction names */
571 Instr = FindInstruction (&SVal);
573 Macro = IsMacro (&SVal);
576 /* Macros and symbols may use the names of instructions */
577 Macro = IsMacro (&SVal);
581 /* Handle an identifier. This may be a cheap local symbol, or a fully
582 * scoped identifier which may start with a namespace token (for global
585 if (Tok == TOK_LOCAL_IDENT ||
586 Tok == TOK_NAMESPACE ||
587 (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
589 /* Did we have whitespace before the ident? */
592 /* Generate the symbol table entry, then skip the name */
593 if (Tok == TOK_LOCAL_IDENT) {
594 Sym = SymFindLocal (SymLast, &SVal, SYM_ALLOC_NEW);
597 Sym = ParseScopedSymName (SYM_ALLOC_NEW);
600 /* If a colon follows, this is a label definition. If there
601 * is no colon, it's an assignment.
603 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
605 /* Determine the symbol flags from the assignment token */
606 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
611 /* Define the symbol with the expression following the '=' */
612 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
614 /* Don't allow anything after a symbol definition */
618 } else if (Tok == TOK_SET) {
622 /* .SET defines variables (= redefinable symbols) */
625 /* Read the assignment expression, which must be constant */
626 Expr = GenLiteralExpr (ConstExpression ());
628 /* Define the symbol with the constant expression following
631 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
633 /* Don't allow anything after a symbol definition */
639 /* A label. Remember the current segment, so we can later
640 * determine the size of the data stored under the label.
645 /* Define the label */
646 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
648 /* Skip the colon. If NoColonLabels is enabled, allow labels
649 * without a colon if there is no whitespace before the
652 if (Tok != TOK_COLON) {
653 if (HadWS || !NoColonLabels) {
654 Error ("`:' expected");
655 /* Try some smart error recovery */
656 if (Tok == TOK_NAMESPACE) {
665 /* If we come here, a new identifier may be waiting, which may
666 * be a macro or instruction.
668 if (Tok == TOK_IDENT) {
669 if (!UbiquitousIdents) {
670 /* Macros and symbols cannot use instruction names */
671 Instr = FindInstruction (&SVal);
673 Macro = IsMacro (&SVal);
676 /* Macros and symbols may use the names of instructions */
677 Macro = IsMacro (&SVal);
683 /* We've handled a possible label, now handle the remainder of the line */
684 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
685 /* A control command */
688 /* A macro expansion */
690 } else if (Instr >= 0 ||
691 (UbiquitousIdents && ((Instr = FindInstruction (&SVal)) >= 0))) {
692 /* A mnemonic - assemble one instruction */
693 HandleInstruction (Instr);
694 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
697 Error ("`=' expected");
700 /* Skip the equal sign */
702 /* Enter absolute mode */
707 /* If we have defined a label, remember its size. Sym is also set by
708 * a symbol assignment, but in this case Done is false, so we don't
713 if (Seg == ActiveSeg) {
715 Size = GetPC () - PC;
717 /* The line has switched the segment */
720 DefSizeOfSymbol (Sym, Size);
723 /* Line separator must come here */
729 static void Assemble (void)
730 /* Start the ball rolling ... */
735 /* Assemble lines until end of file */
736 while (Tok != TOK_EOF) {
743 static void CreateObjFile (void)
744 /* Create the object file */
746 /* Open the object, write the header */
749 /* Write the object file options */
752 /* Write the list of input files */
755 /* Write the segment data to the file */
758 /* Write the import list */
761 /* Write the export list */
764 /* Write debug symbols if requested */
767 /* Write line infos if requested */
770 /* Write the string pool */
773 /* Write the assertions */
776 /* Write an updated header and close the file */
782 int main (int argc, char* argv [])
783 /* Assembler main program */
785 /* Program long options */
786 static const LongOpt OptTab[] = {
787 { "--auto-import", 0, OptAutoImport },
788 { "--cpu", 1, OptCPU },
789 { "--debug-info", 0, OptDebugInfo },
790 { "--feature", 1, OptFeature },
791 { "--forget-inc-paths", 0, OptForgetIncPaths },
792 { "--help", 0, OptHelp },
793 { "--ignore-case", 0, OptIgnoreCase },
794 { "--include-dir", 1, OptIncludeDir },
795 { "--list-bytes", 1, OptListBytes },
796 { "--listing", 0, OptListing },
797 { "--macpack-dir", 1, OptMacPackDir },
798 { "--memory-model", 1, OptMemoryModel },
799 { "--pagelength", 1, OptPageLength },
800 { "--smart", 0, OptSmart },
801 { "--target", 1, OptTarget },
802 { "--verbose", 0, OptVerbose },
803 { "--version", 0, OptVersion },
806 /* Name of the global name space */
807 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
811 /* Initialize the cmdline module */
812 InitCmdLine (&argc, &argv, "ca65");
814 /* Initialize the include search paths */
817 /* Enter the base lexical level. We must do that here, since we may
818 * define symbols using -D.
820 SymEnterLevel (&GlobalNameSpace, ST_GLOBAL, ADDR_SIZE_DEFAULT);
822 /* Check the parameters */
824 while (I < ArgCount) {
826 /* Get the argument */
827 const char* Arg = ArgVec [I];
829 /* Check for an option */
834 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
838 OptDebugInfo (Arg, 0);
846 OptIgnoreCase (Arg, 0);
855 OptMemoryModel (Arg, GetArg (&I, 3));
862 OutFile = GetArg (&I, 2);
870 OptTarget (Arg, GetArg (&I, 2));
878 DefineSymbol (GetArg (&I, 2));
882 OptIncludeDir (Arg, GetArg (&I, 2));
886 OptAutoImport (Arg, 0);
894 WarnLevel = atoi (GetArg (&I, 2));
903 /* Filename. Check if we already had one */
905 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
917 /* Do we have an input file? */
919 fprintf (stderr, "%s: No input files\n", ProgName);
923 /* If no CPU given, use the default CPU for the target */
924 if (GetCPU () == CPU_UNKNOWN) {
925 if (Target != TGT_UNKNOWN) {
926 SetCPU (DefaultCPU[Target]);
932 /* If no memory model was given, use the default */
933 if (MemoryModel == MMODEL_UNKNOWN) {
934 SetMemoryModel (MMODEL_NEAR);
937 /* Initialize the segments */
940 /* Initialize the scanner, open the input file */
941 InitScanner (InFile);
943 /* Define the default options */
946 /* Assemble the input */
949 /* If we didn't have any errors, check the segment stack */
950 if (ErrorCount == 0) {
954 /* If we didn't have any errors, check the unnamed labels */
955 if (ErrorCount == 0) {
959 /* If we didn't have any errors, check the symbol table */
960 if (ErrorCount == 0) {
964 /* If we didn't have any errors, check and resolve the segment data */
965 if (ErrorCount == 0) {
969 /* If we didn't have any errors, check the assertions */
970 if (ErrorCount == 0) {
974 /* If we didn't have an errors, index the line infos */
975 MakeLineInfoIndex ();
978 if (Verbosity >= 2) {
983 /* If we didn't have any errors, create the object and listing files */
984 if (ErrorCount == 0) {
991 /* Close the input file */
994 /* Return an apropriate exit code */
995 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;