1 /*****************************************************************************/
5 /* Main program for the ca65 macroassembler */
9 /* (C) 1998-2010, 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 " --bin-include-dir dir\tSet a search path for binary includes\n"
110 " --cpu type\t\tSet cpu type\n"
111 " --debug-info\t\tAdd debug info to object file\n"
112 " --feature name\tSet an emulation feature\n"
113 " --forget-inc-paths\tForget include search paths\n"
114 " --help\t\tHelp (this text)\n"
115 " --ignore-case\t\tIgnore case of symbols\n"
116 " --include-dir dir\tSet an include directory search path\n"
117 " --listing\t\tCreate a listing if assembly was ok\n"
118 " --list-bytes n\tMaximum number of bytes per listing line\n"
119 " --macpack-dir dir\tSet a macro package directory\n"
120 " --memory-model model\tSet the memory model\n"
121 " --pagelength n\tSet the page length for the listing\n"
122 " --smart\t\tEnable smart mode\n"
123 " --target sys\t\tSet the target system\n"
124 " --verbose\t\tIncrease verbosity\n"
125 " --version\t\tPrint the assembler version\n",
131 static void SetOptions (void)
132 /* Set the option for the translator */
134 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
136 /* Set the translator */
137 SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
138 OptTranslator (&Buf);
140 /* Set date and time */
141 OptDateTime ((unsigned long) time(0));
143 /* Release memory for the string */
149 static void NewSymbol (const char* SymName, long Val)
150 /* Define a symbol with a fixed numeric value in the current scope */
155 /* Convert the name to a string buffer */
156 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
157 SB_CopyStr (&SymBuf, SymName);
159 /* Search for the symbol, allocate a new one if it doesn't exist */
160 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
162 /* Check if have already a symbol with this name */
163 if (SymIsDef (Sym)) {
164 AbEnd ("`%s' is already defined", SymName);
167 /* Generate an expression for the symbol */
168 Expr = GenLiteralExpr (Val);
170 /* Mark the symbol as defined */
171 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
173 /* Free string buffer memory */
179 static void CBMSystem (const char* Sys)
180 /* Define a CBM system */
182 NewSymbol ("__CBM__", 1);
188 static void SetSys (const char* Sys)
189 /* Define a target system */
191 switch (Target = FindTarget (Sys)) {
197 AbEnd ("Cannot use `module' as a target for the assembler");
201 NewSymbol ("__ATARI__", 1);
205 CBMSystem ("__C16__");
209 CBMSystem ("__C64__");
213 CBMSystem ("__VIC20__");
217 CBMSystem ("__C128__");
221 CBMSystem ("__PLUS4__");
225 CBMSystem ("__CBM510__");
229 CBMSystem ("__CBM610__");
233 CBMSystem ("__PET__");
237 NewSymbol ("__BBC__", 1);
241 NewSymbol ("__APPLE2__", 1);
245 NewSymbol ("__APPLE2ENH__", 1);
249 /* Do not handle as a CBM system */
250 NewSymbol ("__GEOS__", 1);
254 NewSymbol ("__LUNIX__", 1);
258 NewSymbol ("__ATMOS__", 1);
262 NewSymbol ("__NES__", 1);
265 case TGT_SUPERVISION:
266 NewSymbol ("__SUPERVISION__", 1);
270 NewSymbol ("__LYNX__", 1);
274 AbEnd ("Invalid target name: `%s'", Sys);
278 /* Initialize the translation tables for the target system */
284 static void DefineSymbol (const char* Def)
285 /* Define a symbol from the command line */
290 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
293 /* The symbol must start with a character or underline */
294 if (!IsIdStart (Def [0])) {
299 /* Copy the symbol, checking the rest */
301 while (IsIdChar (*P)) {
302 SB_AppendChar (&SymName, *P++);
304 SB_Terminate (&SymName);
306 /* Do we have a value given? */
313 /* We have a value */
317 if (sscanf (P, "%lx", &Val) != 1) {
321 if (sscanf (P, "%li", &Val) != 1) {
327 /* Define the new symbol */
328 NewSymbol (SB_GetConstBuf (&SymName), Val);
330 /* Release string memory */
336 static void OptAutoImport (const char* Opt attribute ((unused)),
337 const char* Arg attribute ((unused)))
338 /* Mark unresolved symbols as imported */
345 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
346 /* Add an include search path for binaries */
348 AddIncludePath (Arg, INC_BIN);
353 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
354 /* Handle the --cpu option */
356 cpu_t CPU = FindCPU (Arg);
357 if (CPU == CPU_UNKNOWN) {
358 AbEnd ("Invalid CPU: `%s'", Arg);
366 static void OptDebugInfo (const char* Opt attribute ((unused)),
367 const char* Arg attribute ((unused)))
368 /* Add debug info to the object file */
375 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
376 /* Set an emulation feature */
378 /* Make a string buffer from Arg */
381 /* Set the feature, check for errors */
382 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
383 AbEnd ("Illegal emulation feature: `%s'", Arg);
389 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
390 const char* Arg attribute ((unused)))
391 /* Forget all currently defined include paths */
393 ForgetAllIncludePaths ();
398 static void OptHelp (const char* Opt attribute ((unused)),
399 const char* Arg attribute ((unused)))
400 /* Print usage information and exit */
408 static void OptIgnoreCase (const char* Opt attribute ((unused)),
409 const char* Arg attribute ((unused)))
410 /* Ignore case on symbols */
417 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
418 /* Add an include search path */
420 AddIncludePath (Arg, INC_STD);
425 static void OptListBytes (const char* Opt, const char* Arg)
426 /* Set the maximum number of bytes per listing line */
431 /* Convert the argument to a number */
432 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
436 /* Check the bounds */
437 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
438 AbEnd ("Argument for option `%s' is out of range", Opt);
447 static void OptListing (const char* Opt attribute ((unused)),
448 const char* Arg attribute ((unused)))
449 /* Create a listing file */
456 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
457 /* Set a macro package directory */
459 /* Make a string buffer from Arg */
462 /* Use the directory */
463 MacPackSetDir (SB_InitFromString (&Dir, Arg));
468 static void OptMemoryModel (const char* Opt, const char* Arg)
469 /* Set the memory model */
473 /* Check the current memory model */
474 if (MemoryModel != MMODEL_UNKNOWN) {
475 AbEnd ("Cannot use option `%s' twice", Opt);
478 /* Translate the memory model name and check it */
479 M = FindMemoryModel (Arg);
480 if (M == MMODEL_UNKNOWN) {
481 AbEnd ("Unknown memory model: %s", Arg);
482 } else if (M == MMODEL_HUGE) {
483 AbEnd ("Unsupported memory model: %s", Arg);
486 /* Set the memory model */
492 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
493 /* Handle the --pagelength option */
495 int Len = atoi (Arg);
496 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
497 AbEnd ("Invalid page length: %d", Len);
504 static void OptSmart (const char* Opt attribute ((unused)),
505 const char* Arg attribute ((unused)))
506 /* Handle the -s/--smart options */
513 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
514 /* Set the target system */
521 static void OptVerbose (const char* Opt attribute ((unused)),
522 const char* Arg attribute ((unused)))
523 /* Increase verbosity */
530 static void OptVersion (const char* Opt attribute ((unused)),
531 const char* Arg attribute ((unused)))
532 /* Print the assembler version */
534 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
539 static void DoPCAssign (void)
540 /* Start absolute code */
542 long PC = ConstExpression ();
543 if (PC < 0 || PC > 0xFFFFFF) {
544 Error ("Range error");
546 EnterAbsoluteMode (PC);
552 static void OneLine (void)
553 /* Assemble one line */
556 unsigned long PC = 0;
561 /* Initialize the new listing line if we are actually reading from file
562 * and not from internally pushed input.
564 if (!HavePushedInput ()) {
568 if (Tok == TOK_COLON) {
569 /* An unnamed label */
574 /* If the first token on the line is an identifier, check for a macro or
577 if (Tok == TOK_IDENT) {
578 if (!UbiquitousIdents) {
579 /* Macros and symbols cannot use instruction names */
580 Instr = FindInstruction (&SVal);
582 Macro = IsMacro (&SVal);
585 /* Macros and symbols may use the names of instructions */
586 Macro = IsMacro (&SVal);
590 /* Handle an identifier. This may be a cheap local symbol, or a fully
591 * scoped identifier which may start with a namespace token (for global
594 if (Tok == TOK_LOCAL_IDENT ||
595 Tok == TOK_NAMESPACE ||
596 (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
598 /* Did we have whitespace before the ident? */
601 /* Generate the symbol table entry, then skip the name */
602 if (Tok == TOK_LOCAL_IDENT) {
603 Sym = SymFindLocal (SymLast, &SVal, SYM_ALLOC_NEW);
606 Sym = ParseScopedSymName (SYM_ALLOC_NEW);
609 /* If a colon follows, this is a label definition. If there
610 * is no colon, it's an assignment.
612 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
614 /* Determine the symbol flags from the assignment token */
615 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
620 /* Define the symbol with the expression following the '=' */
621 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
623 /* Don't allow anything after a symbol definition */
627 } else if (Tok == TOK_SET) {
631 /* .SET defines variables (= redefinable symbols) */
634 /* Read the assignment expression, which must be constant */
635 Expr = GenLiteralExpr (ConstExpression ());
637 /* Define the symbol with the constant expression following
640 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
642 /* Don't allow anything after a symbol definition */
648 /* A label. Remember the current segment, so we can later
649 * determine the size of the data stored under the label.
654 /* Define the label */
655 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
657 /* Skip the colon. If NoColonLabels is enabled, allow labels
658 * without a colon if there is no whitespace before the
661 if (Tok != TOK_COLON) {
662 if (HadWS || !NoColonLabels) {
663 Error ("`:' expected");
664 /* Try some smart error recovery */
665 if (Tok == TOK_NAMESPACE) {
674 /* If we come here, a new identifier may be waiting, which may
675 * be a macro or instruction.
677 if (Tok == TOK_IDENT) {
678 if (!UbiquitousIdents) {
679 /* Macros and symbols cannot use instruction names */
680 Instr = FindInstruction (&SVal);
682 Macro = IsMacro (&SVal);
685 /* Macros and symbols may use the names of instructions */
686 Macro = IsMacro (&SVal);
692 /* We've handled a possible label, now handle the remainder of the line */
693 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
694 /* A control command */
697 /* A macro expansion */
699 } else if (Instr >= 0 ||
700 (UbiquitousIdents && ((Instr = FindInstruction (&SVal)) >= 0))) {
701 /* A mnemonic - assemble one instruction */
702 HandleInstruction (Instr);
703 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
706 Error ("`=' expected");
709 /* Skip the equal sign */
711 /* Enter absolute mode */
716 /* If we have defined a label, remember its size. Sym is also set by
717 * a symbol assignment, but in this case Done is false, so we don't
722 if (Seg == ActiveSeg) {
724 Size = GetPC () - PC;
726 /* The line has switched the segment */
729 DefSizeOfSymbol (Sym, Size);
732 /* Line separator must come here */
738 static void Assemble (void)
739 /* Start the ball rolling ... */
744 /* Assemble lines until end of file */
745 while (Tok != TOK_EOF) {
752 static void CreateObjFile (void)
753 /* Create the object file */
755 /* Open the object, write the header */
758 /* Write the object file options */
761 /* Write the list of input files */
764 /* Write the segment data to the file */
767 /* Write the import list */
770 /* Write the export list */
773 /* Write debug symbols if requested */
776 /* Write line infos if requested */
779 /* Write the string pool */
782 /* Write the assertions */
785 /* Write an updated header and close the file */
791 int main (int argc, char* argv [])
792 /* Assembler main program */
794 /* Program long options */
795 static const LongOpt OptTab[] = {
796 { "--auto-import", 0, OptAutoImport },
797 { "--bin-include-dir", 1, OptBinIncludeDir },
798 { "--cpu", 1, OptCPU },
799 { "--debug-info", 0, OptDebugInfo },
800 { "--feature", 1, OptFeature },
801 { "--forget-inc-paths", 0, OptForgetIncPaths },
802 { "--help", 0, OptHelp },
803 { "--ignore-case", 0, OptIgnoreCase },
804 { "--include-dir", 1, OptIncludeDir },
805 { "--list-bytes", 1, OptListBytes },
806 { "--listing", 0, OptListing },
807 { "--macpack-dir", 1, OptMacPackDir },
808 { "--memory-model", 1, OptMemoryModel },
809 { "--pagelength", 1, OptPageLength },
810 { "--smart", 0, OptSmart },
811 { "--target", 1, OptTarget },
812 { "--verbose", 0, OptVerbose },
813 { "--version", 0, OptVersion },
816 /* Name of the global name space */
817 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
821 /* Initialize the cmdline module */
822 InitCmdLine (&argc, &argv, "ca65");
824 /* Initialize the include search paths */
827 /* Enter the base lexical level. We must do that here, since we may
828 * define symbols using -D.
830 SymEnterLevel (&GlobalNameSpace, ST_GLOBAL, ADDR_SIZE_DEFAULT);
832 /* Check the parameters */
834 while (I < ArgCount) {
836 /* Get the argument */
837 const char* Arg = ArgVec [I];
839 /* Check for an option */
844 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
848 OptDebugInfo (Arg, 0);
856 OptIgnoreCase (Arg, 0);
865 OptMemoryModel (Arg, GetArg (&I, 3));
872 OutFile = GetArg (&I, 2);
880 OptTarget (Arg, GetArg (&I, 2));
888 DefineSymbol (GetArg (&I, 2));
892 OptIncludeDir (Arg, GetArg (&I, 2));
896 OptAutoImport (Arg, 0);
904 WarnLevel = atoi (GetArg (&I, 2));
913 /* Filename. Check if we already had one */
915 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
927 /* Do we have an input file? */
929 fprintf (stderr, "%s: No input files\n", ProgName);
933 /* If no CPU given, use the default CPU for the target */
934 if (GetCPU () == CPU_UNKNOWN) {
935 if (Target != TGT_UNKNOWN) {
936 SetCPU (DefaultCPU[Target]);
942 /* If no memory model was given, use the default */
943 if (MemoryModel == MMODEL_UNKNOWN) {
944 SetMemoryModel (MMODEL_NEAR);
947 /* Initialize the segments */
950 /* Initialize the scanner, open the input file */
951 InitScanner (InFile);
953 /* Define the default options */
956 /* Assemble the input */
959 /* If we didn't have any errors, check the pseudo insn stacks */
960 if (ErrorCount == 0) {
964 /* If we didn't have any errors, check the unnamed labels */
965 if (ErrorCount == 0) {
969 /* If we didn't have any errors, check the symbol table */
970 if (ErrorCount == 0) {
974 /* If we didn't have any errors, check and resolve the segment data */
975 if (ErrorCount == 0) {
979 /* If we didn't have any errors, check the assertions */
980 if (ErrorCount == 0) {
984 /* If we didn't have an errors, index the line infos */
985 MakeLineInfoIndex ();
988 if (Verbosity >= 2) {
993 /* If we didn't have any errors, create the object and listing files */
994 if (ErrorCount == 0) {
1001 /* Close the input file */
1004 /* Return an apropriate exit code */
1005 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;