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%s", GetVersionAsString ());
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 */
524 fprintf (stderr, "ca65 V%s - %s\n", GetVersionAsString (), Copyright);
529 static void DoPCAssign (void)
530 /* Start absolute code */
532 long PC = ConstExpression ();
533 if (PC < 0 || PC > 0xFFFFFF) {
534 Error ("Range error");
536 EnterAbsoluteMode (PC);
542 static void OneLine (void)
543 /* Assemble one line */
546 unsigned long PC = 0;
551 /* Initialize the new listing line if we are actually reading from file
552 * and not from internally pushed input.
554 if (!HavePushedInput ()) {
558 if (Tok == TOK_COLON) {
559 /* An unnamed label */
564 /* If the first token on the line is an identifier, check for a macro or
567 if (Tok == TOK_IDENT) {
568 if (!UbiquitousIdents) {
569 /* Macros and symbols cannot use instruction names */
570 Instr = FindInstruction (&SVal);
572 Macro = IsMacro (&SVal);
575 /* Macros and symbols may use the names of instructions */
576 Macro = IsMacro (&SVal);
580 /* Handle an identifier */
581 if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
583 /* Did we have whitespace before the ident? */
586 /* Generate the symbol table entry, then skip the name */
587 if (Tok == TOK_IDENT) {
588 Sym = SymFind (CurrentScope, &SVal, SYM_ALLOC_NEW);
590 Sym = SymFindLocal (SymLast, &SVal, SYM_ALLOC_NEW);
594 /* If a colon follows, this is a label definition. If there
595 * is no colon, it's an assignment.
597 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
599 /* Determine the symbol flags from the assignment token */
600 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
605 /* Define the symbol with the expression following the '=' */
606 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
608 /* Don't allow anything after a symbol definition */
612 } else if (Tok == TOK_SET) {
616 /* .SET defines variables (= redefinable symbols) */
619 /* Read the assignment expression, which must be constant */
620 Expr = GenLiteralExpr (ConstExpression ());
622 /* Define the symbol with the constant expression following
625 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
627 /* Don't allow anything after a symbol definition */
633 /* A label. Remember the current segment, so we can later
634 * determine the size of the data stored under the label.
639 /* Define the label */
640 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
642 /* Skip the colon. If NoColonLabels is enabled, allow labels
643 * without a colon if there is no whitespace before the
646 if (Tok != TOK_COLON) {
647 if (HadWS || !NoColonLabels) {
648 Error ("`:' expected");
649 /* Try some smart error recovery */
650 if (Tok == TOK_NAMESPACE) {
659 /* If we come here, a new identifier may be waiting, which may
660 * be a macro or instruction.
662 if (Tok == TOK_IDENT) {
663 if (!UbiquitousIdents) {
664 /* Macros and symbols cannot use instruction names */
665 Instr = FindInstruction (&SVal);
667 Macro = IsMacro (&SVal);
670 /* Macros and symbols may use the names of instructions */
671 Macro = IsMacro (&SVal);
677 /* We've handled a possible label, now handle the remainder of the line */
678 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
679 /* A control command */
682 /* A macro expansion */
684 } else if (Instr >= 0 ||
685 (UbiquitousIdents && ((Instr = FindInstruction (&SVal)) >= 0))) {
686 /* A mnemonic - assemble one instruction */
687 HandleInstruction (Instr);
688 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
691 Error ("`=' expected");
694 /* Skip the equal sign */
696 /* Enter absolute mode */
701 /* If we have defined a label, remember its size. Sym is also set by
702 * a symbol assignment, but in this case Done is false, so we don't
707 if (Seg == ActiveSeg) {
709 Size = GetPC () - PC;
711 /* The line has switched the segment */
714 DefSizeOfSymbol (Sym, Size);
717 /* Line separator must come here */
723 static void Assemble (void)
724 /* Start the ball rolling ... */
729 /* Assemble lines until end of file */
730 while (Tok != TOK_EOF) {
737 static void CreateObjFile (void)
738 /* Create the object file */
740 /* Open the object, write the header */
743 /* Write the object file options */
746 /* Write the list of input files */
749 /* Write the segment data to the file */
752 /* Write the import list */
755 /* Write the export list */
758 /* Write debug symbols if requested */
761 /* Write line infos if requested */
764 /* Write the string pool */
767 /* Write the assertions */
770 /* Write an updated header and close the file */
776 int main (int argc, char* argv [])
777 /* Assembler main program */
779 /* Program long options */
780 static const LongOpt OptTab[] = {
781 { "--auto-import", 0, OptAutoImport },
782 { "--cpu", 1, OptCPU },
783 { "--debug-info", 0, OptDebugInfo },
784 { "--feature", 1, OptFeature },
785 { "--forget-inc-paths", 0, OptForgetIncPaths },
786 { "--help", 0, OptHelp },
787 { "--ignore-case", 0, OptIgnoreCase },
788 { "--include-dir", 1, OptIncludeDir },
789 { "--list-bytes", 1, OptListBytes },
790 { "--listing", 0, OptListing },
791 { "--macpack-dir", 1, OptMacPackDir },
792 { "--memory-model", 1, OptMemoryModel },
793 { "--pagelength", 1, OptPageLength },
794 { "--smart", 0, OptSmart },
795 { "--target", 1, OptTarget },
796 { "--verbose", 0, OptVerbose },
797 { "--version", 0, OptVersion },
800 /* Name of the global name space */
801 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
805 /* Initialize the cmdline module */
806 InitCmdLine (&argc, &argv, "ca65");
808 /* Initialize the include search paths */
811 /* Enter the base lexical level. We must do that here, since we may
812 * define symbols using -D.
814 SymEnterLevel (&GlobalNameSpace, ST_GLOBAL, ADDR_SIZE_DEFAULT);
816 /* Check the parameters */
818 while (I < ArgCount) {
820 /* Get the argument */
821 const char* Arg = ArgVec [I];
823 /* Check for an option */
828 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
832 OptDebugInfo (Arg, 0);
840 OptIgnoreCase (Arg, 0);
849 OptMemoryModel (Arg, GetArg (&I, 3));
856 OutFile = GetArg (&I, 2);
864 OptTarget (Arg, GetArg (&I, 2));
872 DefineSymbol (GetArg (&I, 2));
876 OptIncludeDir (Arg, GetArg (&I, 2));
880 OptAutoImport (Arg, 0);
888 WarnLevel = atoi (GetArg (&I, 2));
897 /* Filename. Check if we already had one */
899 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
911 /* Do we have an input file? */
913 fprintf (stderr, "%s: No input files\n", ProgName);
917 /* If no CPU given, use the default CPU for the target */
918 if (GetCPU () == CPU_UNKNOWN) {
919 if (Target != TGT_UNKNOWN) {
920 SetCPU (DefaultCPU[Target]);
926 /* If no memory model was given, use the default */
927 if (MemoryModel == MMODEL_UNKNOWN) {
928 SetMemoryModel (MMODEL_NEAR);
931 /* Initialize the segments */
934 /* Initialize the scanner, open the input file */
935 InitScanner (InFile);
937 /* Define the default options */
940 /* Assemble the input */
943 /* If we didn't have any errors, check the segment stack */
944 if (ErrorCount == 0) {
948 /* If we didn't have any errors, check the unnamed labels */
949 if (ErrorCount == 0) {
953 /* If we didn't have any errors, check the symbol table */
954 if (ErrorCount == 0) {
958 /* If we didn't have any errors, check and resolve the segment data */
959 if (ErrorCount == 0) {
963 /* If we didn't have any errors, check the assertions */
964 if (ErrorCount == 0) {
968 /* If we didn't have an errors, index the line infos */
969 MakeLineInfoIndex ();
972 if (Verbosity >= 2) {
977 /* If we didn't have any errors, create the object and listing files */
978 if (ErrorCount == 0) {
985 /* Close the input file */
988 /* Return an apropriate exit code */
989 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;