1 /*****************************************************************************/
5 /* Main program for the ca65 macroassembler */
9 /* (C) 1998-2004 Ullrich von Bassewitz */
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 /*****************************************************************************/
78 /*****************************************************************************/
80 /*****************************************************************************/
84 static void Usage (void)
85 /* Print usage information and exit */
87 printf ("Usage: %s [options] file\n"
89 " -D name[=value]\tDefine a symbol\n"
90 " -I dir\t\tSet an include directory search path\n"
91 " -U\t\t\tMark unresolved symbols as import\n"
92 " -V\t\t\tPrint the assembler version\n"
93 " -W n\t\t\tSet warning level n\n"
94 " -g\t\t\tAdd debug info to object file\n"
95 " -h\t\t\tHelp (this text)\n"
96 " -i\t\t\tIgnore case of symbols\n"
97 " -l\t\t\tCreate a listing if assembly was ok\n"
98 " -mm model\t\tSet the memory model\n"
99 " -o name\t\tName the output file\n"
100 " -s\t\t\tEnable smart mode\n"
101 " -t sys\t\tSet the target system\n"
102 " -v\t\t\tIncrease verbosity\n"
105 " --auto-import\t\tMark unresolved symbols as import\n"
106 " --cpu type\t\tSet cpu type\n"
107 " --debug-info\t\tAdd debug info to object file\n"
108 " --feature name\tSet an emulation feature\n"
109 " --help\t\tHelp (this text)\n"
110 " --ignore-case\t\tIgnore case of symbols\n"
111 " --include-dir dir\tSet an include directory search path\n"
112 " --listing\t\tCreate a listing if assembly was ok\n"
113 " --list-bytes n\tMaximum number of bytes per listing line\n"
114 " --memory-model model\tSet the memory model\n"
115 " --pagelength n\tSet the page length for the listing\n"
116 " --smart\t\tEnable smart mode\n"
117 " --target sys\t\tSet the target system\n"
118 " --verbose\t\tIncrease verbosity\n"
119 " --version\t\tPrint the assembler version\n",
125 static void SetOptions (void)
126 /* Set the option for the translator */
130 /* Set the translator */
131 sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
134 /* Set date and time */
135 OptDateTime ((unsigned long) time(0));
140 static void NewSymbol (const char* SymName, long Val)
141 /* Define a symbol with a fixed numeric value in the current scope */
145 /* Search for the symbol, allocate a new one if it doesn't exist */
146 SymEntry* Sym = SymFind (CurrentScope, SymName, SYM_ALLOC_NEW);
148 /* Check if have already a symbol with this name */
149 if (SymIsDef (Sym)) {
150 AbEnd ("`%s' is already defined", SymName);
153 /* Generate an expression for the symbol */
154 Expr = GenLiteralExpr (Val);
156 /* Mark the symbol as defined */
157 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
162 static void CBMSystem (const char* Sys)
163 /* Define a CBM system */
165 NewSymbol ("__CBM__", 1);
171 static void SetSys (const char* Sys)
172 /* Define a target system */
174 switch (Target = FindTarget (Sys)) {
180 AbEnd ("Cannot use `module' as a target for the assembler");
184 NewSymbol ("__ATARI__", 1);
188 CBMSystem ("__C16__");
192 CBMSystem ("__C64__");
196 CBMSystem ("__VIC20__");
200 CBMSystem ("__C128__");
204 CBMSystem ("__ACE__");
208 CBMSystem ("__PLUS4__");
212 CBMSystem ("__CBM510__");
216 CBMSystem ("__CBM610__");
220 CBMSystem ("__PET__");
224 NewSymbol ("__BBC__", 1);
228 NewSymbol ("__APPLE2__", 1);
232 NewSymbol ("__APPLE2ENH__", 1);
236 /* Do not handle as a CBM system */
237 NewSymbol ("__GEOS__", 1);
241 NewSymbol ("__LUNIX__", 1);
245 NewSymbol ("__ATMOS__", 1);
249 NewSymbol ("__NES__", 1);
252 case TGT_SUPERVISION:
253 NewSymbol ("__SUPERVISION__", 1);
257 NewSymbol ("__LYNX__", 1);
261 AbEnd ("Invalid target name: `%s'", Sys);
265 /* Initialize the translation tables for the target system */
271 static void DefineSymbol (const char* Def)
272 /* Define a symbol from the command line */
277 char SymName [MAX_STR_LEN+1];
280 /* The symbol must start with a character or underline */
281 if (Def [0] != '_' && !IsAlpha (Def [0])) {
286 /* Copy the symbol, checking the rest */
288 while (IsAlNum (*P) || *P == '_') {
289 if (I <= MAX_STR_LEN) {
296 /* Do we have a value given? */
303 /* We have a value */
307 if (sscanf (P, "%lx", &Val) != 1) {
311 if (sscanf (P, "%li", &Val) != 1) {
317 /* Define the new symbol */
318 NewSymbol (SymName, Val);
323 static void OptAutoImport (const char* Opt attribute ((unused)),
324 const char* Arg attribute ((unused)))
325 /* Mark unresolved symbols as imported */
332 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
333 /* Handle the --cpu option */
335 cpu_t CPU = FindCPU (Arg);
336 if (CPU == CPU_UNKNOWN) {
337 AbEnd ("Invalid CPU: `%s'", Arg);
345 static void OptDebugInfo (const char* Opt attribute ((unused)),
346 const char* Arg attribute ((unused)))
347 /* Add debug info to the object file */
354 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
355 /* Set an emulation feature */
357 /* Set the feature, check for errors */
358 if (SetFeature (Arg) == FEAT_UNKNOWN) {
359 AbEnd ("Illegal emulation feature: `%s'", Arg);
365 static void OptHelp (const char* Opt attribute ((unused)),
366 const char* Arg attribute ((unused)))
367 /* Print usage information and exit */
375 static void OptIgnoreCase (const char* Opt attribute ((unused)),
376 const char* Arg attribute ((unused)))
377 /* Ignore case on symbols */
384 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
385 /* Add an include search path */
387 AddIncludePath (Arg);
392 static void OptListBytes (const char* Opt, const char* Arg)
393 /* Set the maximum number of bytes per listing line */
398 /* Convert the argument to a number */
399 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
400 AbEnd ("Invalid argument for option `%s'", Opt);
403 /* Check the bounds */
404 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
405 AbEnd ("Argument for option `%s' is out of range", Opt);
414 static void OptListing (const char* Opt attribute ((unused)),
415 const char* Arg attribute ((unused)))
416 /* Create a listing file */
423 static void OptMemoryModel (const char* Opt, const char* Arg)
424 /* Set the memory model */
428 /* Check the current memory model */
429 if (MemoryModel != MMODEL_UNKNOWN) {
430 AbEnd ("Cannot use option `%s' twice", Opt);
433 /* Translate the memory model name and check it */
434 M = FindMemoryModel (Arg);
435 if (M == MMODEL_UNKNOWN) {
436 AbEnd ("Unknown memory model: %s", Arg);
437 } else if (M == MMODEL_HUGE) {
438 AbEnd ("Unsupported memory model: %s", Arg);
441 /* Set the memory model */
447 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
448 /* Handle the --pagelength option */
450 int Len = atoi (Arg);
451 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
452 AbEnd ("Invalid page length: %d", Len);
459 static void OptSmart (const char* Opt attribute ((unused)),
460 const char* Arg attribute ((unused)))
461 /* Handle the -s/--smart options */
468 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
469 /* Set the target system */
476 static void OptVerbose (const char* Opt attribute ((unused)),
477 const char* Arg attribute ((unused)))
478 /* Increase verbosity */
485 static void OptVersion (const char* Opt attribute ((unused)),
486 const char* Arg attribute ((unused)))
487 /* Print the assembler version */
490 "ca65 V%u.%u.%u - %s\n",
491 VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
496 static void DoPCAssign (void)
497 /* Start absolute code */
499 long PC = ConstExpression ();
500 if (PC < 0 || PC > 0xFFFFFF) {
501 Error ("Range error");
509 static void OneLine (void)
510 /* Assemble one line */
513 unsigned long PC = 0;
518 /* Initialize the new listing line if we are actually reading from file
519 * and not from internally pushed input.
521 if (!HavePushedInput ()) {
525 if (Tok == TOK_COLON) {
526 /* An unnamed label */
531 /* If the first token on the line is an identifier, check for a macro or
534 if (Tok == TOK_IDENT) {
535 if (!UbiquitousIdents) {
536 /* Macros and symbols cannot use instruction names */
537 Instr = FindInstruction (SVal);
539 Macro = IsMacro (SVal);
542 /* Macros and symbols may use the names of instructions */
543 Macro = IsMacro (SVal);
547 /* Handle an identifier */
548 if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
550 /* Did we have whitespace before the ident? */
553 /* Generate the symbol table entry, then skip the name */
554 if (Tok == TOK_IDENT) {
555 Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
557 Sym = SymFindLocal (SymLast, SVal, SYM_ALLOC_NEW);
561 /* If a colon follows, this is a label definition. If there
562 * is no colon, it's an assignment.
564 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
566 /* Determine the symbol flags from the assignment token */
567 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
572 /* Define the symbol with the expression following the '=' */
573 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
575 /* Don't allow anything after a symbol definition */
579 } else if (Tok == TOK_SET) {
583 /* .SET defines variables (= redefinable symbols) */
586 /* Read the assignment expression, which must be constant */
587 Expr = GenLiteralExpr (ConstExpression ());
589 /* Define the symbol with the constant expression following
592 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
594 /* Don't allow anything after a symbol definition */
600 /* A label. Remember the current segment, so we can later
601 * determine the size of the data stored under the label.
606 /* Define the label */
607 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
609 /* Skip the colon. If NoColonLabels is enabled, allow labels
610 * without a colon if there is no whitespace before the
613 if (Tok != TOK_COLON) {
614 if (HadWS || !NoColonLabels) {
615 Error ("`:' expected");
616 /* Try some smart error recovery */
617 if (Tok == TOK_NAMESPACE) {
626 /* If we come here, a new identifier may be waiting, which may
627 * be a macro or instruction.
629 if (Tok == TOK_IDENT) {
630 if (!UbiquitousIdents) {
631 /* Macros and symbols cannot use instruction names */
632 Instr = FindInstruction (SVal);
634 Macro = IsMacro (SVal);
637 /* Macros and symbols may use the names of instructions */
638 Macro = IsMacro (SVal);
644 /* We've handled a possible label, now handle the remainder of the line */
645 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
646 /* A control command */
649 /* A macro expansion */
651 } else if (Instr >= 0 ||
652 (UbiquitousIdents && ((Instr = FindInstruction (SVal)) >= 0))) {
653 /* A mnemonic - assemble one instruction */
654 HandleInstruction (Instr);
655 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
658 Error ("`=' expected");
661 /* Skip the equal sign */
663 /* Enter absolute mode */
668 /* If we have defined a label, remember its size. Sym is also set by
669 * a symbol assignment, but in this case Done is false, so we don't
674 if (Seg == ActiveSeg) {
676 Size = GetPC () - PC;
678 /* The line has switched the segment */
681 DefSizeOfSymbol (Sym, Size);
684 /* Line separator must come here */
690 static void Assemble (void)
691 /* Start the ball rolling ... */
696 /* Assemble lines until end of file */
697 while (Tok != TOK_EOF) {
704 static void CreateObjFile (void)
705 /* Create the object file */
707 /* Open the object, write the header */
710 /* Write the object file options */
713 /* Write the list of input files */
716 /* Write the segment data to the file */
719 /* Write the import list */
722 /* Write the export list */
725 /* Write debug symbols if requested */
728 /* Write line infos if requested */
731 /* Write the string pool */
734 /* Write the assertions */
737 /* Write an updated header and close the file */
743 int main (int argc, char* argv [])
744 /* Assembler main program */
746 /* Program long options */
747 static const LongOpt OptTab[] = {
748 { "--auto-import", 0, OptAutoImport },
749 { "--cpu", 1, OptCPU },
750 { "--debug-info", 0, OptDebugInfo },
751 { "--feature", 1, OptFeature },
752 { "--help", 0, OptHelp },
753 { "--ignore-case", 0, OptIgnoreCase },
754 { "--include-dir", 1, OptIncludeDir },
755 { "--list-bytes", 1, OptListBytes },
756 { "--listing", 0, OptListing },
757 { "--memory-model", 1, OptMemoryModel },
758 { "--pagelength", 1, OptPageLength },
759 { "--smart", 0, OptSmart },
760 { "--target", 1, OptTarget },
761 { "--verbose", 0, OptVerbose },
762 { "--version", 0, OptVersion },
767 /* Initialize the cmdline module */
768 InitCmdLine (&argc, &argv, "ca65");
770 /* Enter the base lexical level. We must do that here, since we may
771 * define symbols using -D.
773 SymEnterLevel ("", ST_GLOBAL, ADDR_SIZE_DEFAULT);
775 /* Check the parameters */
777 while (I < ArgCount) {
779 /* Get the argument */
780 const char* Arg = ArgVec [I];
782 /* Check for an option */
787 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
791 OptDebugInfo (Arg, 0);
799 OptIgnoreCase (Arg, 0);
808 OptMemoryModel (Arg, GetArg (&I, 3));
815 OutFile = GetArg (&I, 2);
823 OptTarget (Arg, GetArg (&I, 2));
831 DefineSymbol (GetArg (&I, 2));
835 OptIncludeDir (Arg, GetArg (&I, 2));
839 OptAutoImport (Arg, 0);
847 WarnLevel = atoi (GetArg (&I, 2));
856 /* Filename. Check if we already had one */
858 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
870 /* Do we have an input file? */
872 fprintf (stderr, "%s: No input files\n", ProgName);
876 /* If no CPU given, use the default CPU for the target */
877 if (GetCPU () == CPU_UNKNOWN) {
878 if (Target != TGT_UNKNOWN) {
879 SetCPU (DefaultCPU[Target]);
885 /* If no memory model was given, use the default */
886 if (MemoryModel == MMODEL_UNKNOWN) {
887 SetMemoryModel (MMODEL_NEAR);
890 /* Initialize the segments */
893 /* Initialize the scanner, open the input file */
894 InitScanner (InFile);
896 /* Define the default options */
899 /* Assemble the input */
902 /* If we didn't have any errors, check the segment stack */
903 if (ErrorCount == 0) {
907 /* If we didn't have any errors, check the unnamed labels */
908 if (ErrorCount == 0) {
912 /* If we didn't have any errors, check the symbol table */
913 if (ErrorCount == 0) {
917 /* If we didn't have any errors, check and resolve the segment data */
918 if (ErrorCount == 0) {
922 /* If we didn't have any errors, check the assertions */
923 if (ErrorCount == 0) {
927 /* If we didn't have an errors, index the line infos */
928 MakeLineInfoIndex ();
931 if (Verbosity >= 2) {
936 /* If we didn't have any errors, create the object and listing files */
937 if (ErrorCount == 0) {
944 /* Close the input file */
947 /* Return an apropriate exit code */
948 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;