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 /*****************************************************************************/
80 /*****************************************************************************/
82 /*****************************************************************************/
86 static void Usage (void)
87 /* Print usage information and exit */
89 printf ("Usage: %s [options] file\n"
91 " -D name[=value]\tDefine a symbol\n"
92 " -I dir\t\tSet an include directory search path\n"
93 " -U\t\t\tMark unresolved symbols as import\n"
94 " -V\t\t\tPrint the assembler version\n"
95 " -W n\t\t\tSet warning level n\n"
96 " -g\t\t\tAdd debug info to object file\n"
97 " -h\t\t\tHelp (this text)\n"
98 " -i\t\t\tIgnore case of symbols\n"
99 " -l\t\t\tCreate a listing if assembly was ok\n"
100 " -mm model\t\tSet the memory model\n"
101 " -o name\t\tName the output file\n"
102 " -s\t\t\tEnable smart mode\n"
103 " -t sys\t\tSet the target system\n"
104 " -v\t\t\tIncrease verbosity\n"
107 " --auto-import\t\tMark unresolved symbols as import\n"
108 " --cpu type\t\tSet cpu type\n"
109 " --debug-info\t\tAdd debug info to object file\n"
110 " --feature name\tSet an emulation feature\n"
111 " --forget-inc-paths\tForget include search paths\n"
112 " --help\t\tHelp (this text)\n"
113 " --ignore-case\t\tIgnore case of symbols\n"
114 " --include-dir dir\tSet an include directory search path\n"
115 " --listing\t\tCreate a listing if assembly was ok\n"
116 " --list-bytes n\tMaximum number of bytes per listing line\n"
117 " --macpack-dir dir\tSet a macro package directory\n"
118 " --memory-model model\tSet the memory model\n"
119 " --pagelength n\tSet the page length for the listing\n"
120 " --smart\t\tEnable smart mode\n"
121 " --target sys\t\tSet the target system\n"
122 " --verbose\t\tIncrease verbosity\n"
123 " --version\t\tPrint the assembler version\n",
129 static void SetOptions (void)
130 /* Set the option for the translator */
132 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
134 /* Set the translator */
135 SB_Printf (&Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
136 OptTranslator (&Buf);
138 /* Set date and time */
139 OptDateTime ((unsigned long) time(0));
141 /* Release memory for the string */
147 static void NewSymbol (const char* SymName, long Val)
148 /* Define a symbol with a fixed numeric value in the current scope */
153 /* Convert the name to a string buffer */
154 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
155 SB_CopyStr (&SymBuf, SymName);
157 /* Search for the symbol, allocate a new one if it doesn't exist */
158 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
160 /* Check if have already a symbol with this name */
161 if (SymIsDef (Sym)) {
162 AbEnd ("`%s' is already defined", SymName);
165 /* Generate an expression for the symbol */
166 Expr = GenLiteralExpr (Val);
168 /* Mark the symbol as defined */
169 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
171 /* Free string buffer memory */
177 static void CBMSystem (const char* Sys)
178 /* Define a CBM system */
180 NewSymbol ("__CBM__", 1);
186 static void SetSys (const char* Sys)
187 /* Define a target system */
189 switch (Target = FindTarget (Sys)) {
195 AbEnd ("Cannot use `module' as a target for the assembler");
199 NewSymbol ("__ATARI__", 1);
203 CBMSystem ("__C16__");
207 CBMSystem ("__C64__");
211 CBMSystem ("__VIC20__");
215 CBMSystem ("__C128__");
219 CBMSystem ("__PLUS4__");
223 CBMSystem ("__CBM510__");
227 CBMSystem ("__CBM610__");
231 CBMSystem ("__PET__");
235 NewSymbol ("__BBC__", 1);
239 NewSymbol ("__APPLE2__", 1);
243 NewSymbol ("__APPLE2ENH__", 1);
247 /* Do not handle as a CBM system */
248 NewSymbol ("__GEOS__", 1);
252 NewSymbol ("__LUNIX__", 1);
256 NewSymbol ("__ATMOS__", 1);
260 NewSymbol ("__NES__", 1);
263 case TGT_SUPERVISION:
264 NewSymbol ("__SUPERVISION__", 1);
268 NewSymbol ("__LYNX__", 1);
272 AbEnd ("Invalid target name: `%s'", Sys);
276 /* Initialize the translation tables for the target system */
282 static void DefineSymbol (const char* Def)
283 /* Define a symbol from the command line */
288 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
291 /* The symbol must start with a character or underline */
292 if (!IsIdStart (Def [0])) {
297 /* Copy the symbol, checking the rest */
299 while (IsIdChar (*P)) {
300 SB_AppendChar (&SymName, *P++);
302 SB_Terminate (&SymName);
304 /* Do we have a value given? */
311 /* We have a value */
315 if (sscanf (P, "%lx", &Val) != 1) {
319 if (sscanf (P, "%li", &Val) != 1) {
325 /* Define the new symbol */
326 NewSymbol (SB_GetConstBuf (&SymName), Val);
328 /* Release string memory */
334 static void OptAutoImport (const char* Opt attribute ((unused)),
335 const char* Arg attribute ((unused)))
336 /* Mark unresolved symbols as imported */
343 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
344 /* Handle the --cpu option */
346 cpu_t CPU = FindCPU (Arg);
347 if (CPU == CPU_UNKNOWN) {
348 AbEnd ("Invalid CPU: `%s'", Arg);
356 static void OptDebugInfo (const char* Opt attribute ((unused)),
357 const char* Arg attribute ((unused)))
358 /* Add debug info to the object file */
365 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
366 /* Set an emulation feature */
368 /* Make a string buffer from Arg */
371 /* Set the feature, check for errors */
372 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
373 AbEnd ("Illegal emulation feature: `%s'", Arg);
379 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
380 const char* Arg attribute ((unused)))
381 /* Forget all currently defined include paths */
383 ForgetAllIncludePaths ();
388 static void OptHelp (const char* Opt attribute ((unused)),
389 const char* Arg attribute ((unused)))
390 /* Print usage information and exit */
398 static void OptIgnoreCase (const char* Opt attribute ((unused)),
399 const char* Arg attribute ((unused)))
400 /* Ignore case on symbols */
407 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
408 /* Add an include search path */
410 AddIncludePath (Arg);
415 static void OptListBytes (const char* Opt, const char* Arg)
416 /* Set the maximum number of bytes per listing line */
421 /* Convert the argument to a number */
422 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
423 AbEnd ("Invalid argument for option `%s'", Opt);
426 /* Check the bounds */
427 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
428 AbEnd ("Argument for option `%s' is out of range", Opt);
437 static void OptListing (const char* Opt attribute ((unused)),
438 const char* Arg attribute ((unused)))
439 /* Create a listing file */
446 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
447 /* Set a macro package directory */
449 /* Make a string buffer from Arg */
452 /* Use the directory */
453 MacPackSetDir (SB_InitFromString (&Dir, Arg));
458 static void OptMemoryModel (const char* Opt, const char* Arg)
459 /* Set the memory model */
463 /* Check the current memory model */
464 if (MemoryModel != MMODEL_UNKNOWN) {
465 AbEnd ("Cannot use option `%s' twice", Opt);
468 /* Translate the memory model name and check it */
469 M = FindMemoryModel (Arg);
470 if (M == MMODEL_UNKNOWN) {
471 AbEnd ("Unknown memory model: %s", Arg);
472 } else if (M == MMODEL_HUGE) {
473 AbEnd ("Unsupported memory model: %s", Arg);
476 /* Set the memory model */
482 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
483 /* Handle the --pagelength option */
485 int Len = atoi (Arg);
486 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
487 AbEnd ("Invalid page length: %d", Len);
494 static void OptSmart (const char* Opt attribute ((unused)),
495 const char* Arg attribute ((unused)))
496 /* Handle the -s/--smart options */
503 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
504 /* Set the target system */
511 static void OptVerbose (const char* Opt attribute ((unused)),
512 const char* Arg attribute ((unused)))
513 /* Increase verbosity */
520 static void OptVersion (const char* Opt attribute ((unused)),
521 const char* Arg attribute ((unused)))
522 /* Print the assembler version */
525 "ca65 V%u.%u.%u - %s\n",
526 VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
531 static void DoPCAssign (void)
532 /* Start absolute code */
534 long PC = ConstExpression ();
535 if (PC < 0 || PC > 0xFFFFFF) {
536 Error ("Range error");
538 EnterAbsoluteMode (PC);
544 static void OneLine (void)
545 /* Assemble one line */
548 unsigned long PC = 0;
553 /* Initialize the new listing line if we are actually reading from file
554 * and not from internally pushed input.
556 if (!HavePushedInput ()) {
560 if (Tok == TOK_COLON) {
561 /* An unnamed label */
566 /* If the first token on the line is an identifier, check for a macro or
569 if (Tok == TOK_IDENT) {
570 if (!UbiquitousIdents) {
571 /* Macros and symbols cannot use instruction names */
572 Instr = FindInstruction (&SVal);
574 Macro = IsMacro (&SVal);
577 /* Macros and symbols may use the names of instructions */
578 Macro = IsMacro (&SVal);
582 /* Handle an identifier */
583 if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
585 /* Did we have whitespace before the ident? */
588 /* Generate the symbol table entry, then skip the name */
589 if (Tok == TOK_IDENT) {
590 Sym = SymFind (CurrentScope, &SVal, SYM_ALLOC_NEW);
592 Sym = SymFindLocal (SymLast, &SVal, SYM_ALLOC_NEW);
596 /* If a colon follows, this is a label definition. If there
597 * is no colon, it's an assignment.
599 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
601 /* Determine the symbol flags from the assignment token */
602 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
607 /* Define the symbol with the expression following the '=' */
608 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
610 /* Don't allow anything after a symbol definition */
614 } else if (Tok == TOK_SET) {
618 /* .SET defines variables (= redefinable symbols) */
621 /* Read the assignment expression, which must be constant */
622 Expr = GenLiteralExpr (ConstExpression ());
624 /* Define the symbol with the constant expression following
627 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
629 /* Don't allow anything after a symbol definition */
635 /* A label. Remember the current segment, so we can later
636 * determine the size of the data stored under the label.
641 /* Define the label */
642 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
644 /* Skip the colon. If NoColonLabels is enabled, allow labels
645 * without a colon if there is no whitespace before the
648 if (Tok != TOK_COLON) {
649 if (HadWS || !NoColonLabels) {
650 Error ("`:' expected");
651 /* Try some smart error recovery */
652 if (Tok == TOK_NAMESPACE) {
661 /* If we come here, a new identifier may be waiting, which may
662 * be a macro or instruction.
664 if (Tok == TOK_IDENT) {
665 if (!UbiquitousIdents) {
666 /* Macros and symbols cannot use instruction names */
667 Instr = FindInstruction (&SVal);
669 Macro = IsMacro (&SVal);
672 /* Macros and symbols may use the names of instructions */
673 Macro = IsMacro (&SVal);
679 /* We've handled a possible label, now handle the remainder of the line */
680 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
681 /* A control command */
684 /* A macro expansion */
686 } else if (Instr >= 0 ||
687 (UbiquitousIdents && ((Instr = FindInstruction (&SVal)) >= 0))) {
688 /* A mnemonic - assemble one instruction */
689 HandleInstruction (Instr);
690 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
693 Error ("`=' expected");
696 /* Skip the equal sign */
698 /* Enter absolute mode */
703 /* If we have defined a label, remember its size. Sym is also set by
704 * a symbol assignment, but in this case Done is false, so we don't
709 if (Seg == ActiveSeg) {
711 Size = GetPC () - PC;
713 /* The line has switched the segment */
716 DefSizeOfSymbol (Sym, Size);
719 /* Line separator must come here */
725 static void Assemble (void)
726 /* Start the ball rolling ... */
731 /* Assemble lines until end of file */
732 while (Tok != TOK_EOF) {
739 static void CreateObjFile (void)
740 /* Create the object file */
742 /* Open the object, write the header */
745 /* Write the object file options */
748 /* Write the list of input files */
751 /* Write the segment data to the file */
754 /* Write the import list */
757 /* Write the export list */
760 /* Write debug symbols if requested */
763 /* Write line infos if requested */
766 /* Write the string pool */
769 /* Write the assertions */
772 /* Write an updated header and close the file */
778 int main (int argc, char* argv [])
779 /* Assembler main program */
781 /* Program long options */
782 static const LongOpt OptTab[] = {
783 { "--auto-import", 0, OptAutoImport },
784 { "--cpu", 1, OptCPU },
785 { "--debug-info", 0, OptDebugInfo },
786 { "--feature", 1, OptFeature },
787 { "--forget-inc-paths", 0, OptForgetIncPaths },
788 { "--help", 0, OptHelp },
789 { "--ignore-case", 0, OptIgnoreCase },
790 { "--include-dir", 1, OptIncludeDir },
791 { "--list-bytes", 1, OptListBytes },
792 { "--listing", 0, OptListing },
793 { "--macpack-dir", 1, OptMacPackDir },
794 { "--memory-model", 1, OptMemoryModel },
795 { "--pagelength", 1, OptPageLength },
796 { "--smart", 0, OptSmart },
797 { "--target", 1, OptTarget },
798 { "--verbose", 0, OptVerbose },
799 { "--version", 0, OptVersion },
802 /* Name of the global name space */
803 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
807 /* Initialize the cmdline module */
808 InitCmdLine (&argc, &argv, "ca65");
810 /* Initialize the include search paths */
813 /* Enter the base lexical level. We must do that here, since we may
814 * define symbols using -D.
816 SymEnterLevel (&GlobalNameSpace, ST_GLOBAL, ADDR_SIZE_DEFAULT);
818 /* Check the parameters */
820 while (I < ArgCount) {
822 /* Get the argument */
823 const char* Arg = ArgVec [I];
825 /* Check for an option */
830 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
834 OptDebugInfo (Arg, 0);
842 OptIgnoreCase (Arg, 0);
851 OptMemoryModel (Arg, GetArg (&I, 3));
858 OutFile = GetArg (&I, 2);
866 OptTarget (Arg, GetArg (&I, 2));
874 DefineSymbol (GetArg (&I, 2));
878 OptIncludeDir (Arg, GetArg (&I, 2));
882 OptAutoImport (Arg, 0);
890 WarnLevel = atoi (GetArg (&I, 2));
899 /* Filename. Check if we already had one */
901 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
913 /* Do we have an input file? */
915 fprintf (stderr, "%s: No input files\n", ProgName);
919 /* If no CPU given, use the default CPU for the target */
920 if (GetCPU () == CPU_UNKNOWN) {
921 if (Target != TGT_UNKNOWN) {
922 SetCPU (DefaultCPU[Target]);
928 /* If no memory model was given, use the default */
929 if (MemoryModel == MMODEL_UNKNOWN) {
930 SetMemoryModel (MMODEL_NEAR);
933 /* Initialize the segments */
936 /* Initialize the scanner, open the input file */
937 InitScanner (InFile);
939 /* Define the default options */
942 /* Assemble the input */
945 /* If we didn't have any errors, check the segment stack */
946 if (ErrorCount == 0) {
950 /* If we didn't have any errors, check the unnamed labels */
951 if (ErrorCount == 0) {
955 /* If we didn't have any errors, check the symbol table */
956 if (ErrorCount == 0) {
960 /* If we didn't have any errors, check and resolve the segment data */
961 if (ErrorCount == 0) {
965 /* If we didn't have any errors, check the assertions */
966 if (ErrorCount == 0) {
970 /* If we didn't have an errors, index the line infos */
971 MakeLineInfoIndex ();
974 if (Verbosity >= 2) {
979 /* If we didn't have any errors, create the object and listing files */
980 if (ErrorCount == 0) {
987 /* Close the input file */
990 /* Return an apropriate exit code */
991 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;