1 /*****************************************************************************/
5 /* Main program for the ca65 macroassembler */
9 /* (C) 1998-2005, 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 /*****************************************************************************/
79 /*****************************************************************************/
81 /*****************************************************************************/
85 static void Usage (void)
86 /* Print usage information and exit */
88 printf ("Usage: %s [options] file\n"
90 " -D name[=value]\tDefine a symbol\n"
91 " -I dir\t\tSet an include directory search path\n"
92 " -U\t\t\tMark unresolved symbols as import\n"
93 " -V\t\t\tPrint the assembler version\n"
94 " -W n\t\t\tSet warning level n\n"
95 " -g\t\t\tAdd debug info to object file\n"
96 " -h\t\t\tHelp (this text)\n"
97 " -i\t\t\tIgnore case of symbols\n"
98 " -l\t\t\tCreate a listing if assembly was ok\n"
99 " -mm model\t\tSet the memory model\n"
100 " -o name\t\tName the output file\n"
101 " -s\t\t\tEnable smart mode\n"
102 " -t sys\t\tSet the target system\n"
103 " -v\t\t\tIncrease verbosity\n"
106 " --auto-import\t\tMark unresolved symbols as import\n"
107 " --cpu type\t\tSet cpu type\n"
108 " --debug-info\t\tAdd debug info to object file\n"
109 " --feature name\tSet an emulation feature\n"
110 " --help\t\tHelp (this text)\n"
111 " --ignore-case\t\tIgnore case of symbols\n"
112 " --include-dir dir\tSet an include directory search path\n"
113 " --listing\t\tCreate a listing if assembly was ok\n"
114 " --list-bytes n\tMaximum number of bytes per listing line\n"
115 " --macpack-dir dir\tSet a macro package directory\n"
116 " --memory-model model\tSet the memory model\n"
117 " --pagelength n\tSet the page length for the listing\n"
118 " --smart\t\tEnable smart mode\n"
119 " --target sys\t\tSet the target system\n"
120 " --verbose\t\tIncrease verbosity\n"
121 " --version\t\tPrint the assembler version\n",
127 static void SetOptions (void)
128 /* Set the option for the translator */
132 /* Set the translator */
133 sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
136 /* Set date and time */
137 OptDateTime ((unsigned long) time(0));
142 static void NewSymbol (const char* SymName, long Val)
143 /* Define a symbol with a fixed numeric value in the current scope */
147 /* Search for the symbol, allocate a new one if it doesn't exist */
148 SymEntry* Sym = SymFind (CurrentScope, SymName, SYM_ALLOC_NEW);
150 /* Check if have already a symbol with this name */
151 if (SymIsDef (Sym)) {
152 AbEnd ("`%s' is already defined", SymName);
155 /* Generate an expression for the symbol */
156 Expr = GenLiteralExpr (Val);
158 /* Mark the symbol as defined */
159 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
164 static void CBMSystem (const char* Sys)
165 /* Define a CBM system */
167 NewSymbol ("__CBM__", 1);
173 static void SetSys (const char* Sys)
174 /* Define a target system */
176 switch (Target = FindTarget (Sys)) {
182 AbEnd ("Cannot use `module' as a target for the assembler");
186 NewSymbol ("__ATARI__", 1);
190 CBMSystem ("__C16__");
194 CBMSystem ("__C64__");
198 CBMSystem ("__VIC20__");
202 CBMSystem ("__C128__");
206 CBMSystem ("__ACE__");
210 CBMSystem ("__PLUS4__");
214 CBMSystem ("__CBM510__");
218 CBMSystem ("__CBM610__");
222 CBMSystem ("__PET__");
226 NewSymbol ("__BBC__", 1);
230 NewSymbol ("__APPLE2__", 1);
234 NewSymbol ("__APPLE2ENH__", 1);
238 /* Do not handle as a CBM system */
239 NewSymbol ("__GEOS__", 1);
243 NewSymbol ("__LUNIX__", 1);
247 NewSymbol ("__ATMOS__", 1);
251 NewSymbol ("__NES__", 1);
254 case TGT_SUPERVISION:
255 NewSymbol ("__SUPERVISION__", 1);
259 NewSymbol ("__LYNX__", 1);
263 AbEnd ("Invalid target name: `%s'", Sys);
267 /* Initialize the translation tables for the target system */
273 static void DefineSymbol (const char* Def)
274 /* Define a symbol from the command line */
279 char SymName [MAX_STR_LEN+1];
282 /* The symbol must start with a character or underline */
283 if (Def [0] != '_' && !IsAlpha (Def [0])) {
288 /* Copy the symbol, checking the rest */
290 while (IsAlNum (*P) || *P == '_') {
291 if (I <= MAX_STR_LEN) {
298 /* Do we have a value given? */
305 /* We have a value */
309 if (sscanf (P, "%lx", &Val) != 1) {
313 if (sscanf (P, "%li", &Val) != 1) {
319 /* Define the new symbol */
320 NewSymbol (SymName, Val);
325 static void OptAutoImport (const char* Opt attribute ((unused)),
326 const char* Arg attribute ((unused)))
327 /* Mark unresolved symbols as imported */
334 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
335 /* Handle the --cpu option */
337 cpu_t CPU = FindCPU (Arg);
338 if (CPU == CPU_UNKNOWN) {
339 AbEnd ("Invalid CPU: `%s'", Arg);
347 static void OptDebugInfo (const char* Opt attribute ((unused)),
348 const char* Arg attribute ((unused)))
349 /* Add debug info to the object file */
356 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
357 /* Set an emulation feature */
359 /* Set the feature, check for errors */
360 if (SetFeature (Arg) == FEAT_UNKNOWN) {
361 AbEnd ("Illegal emulation feature: `%s'", Arg);
367 static void OptHelp (const char* Opt attribute ((unused)),
368 const char* Arg attribute ((unused)))
369 /* Print usage information and exit */
377 static void OptIgnoreCase (const char* Opt attribute ((unused)),
378 const char* Arg attribute ((unused)))
379 /* Ignore case on symbols */
386 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
387 /* Add an include search path */
389 AddIncludePath (Arg);
394 static void OptListBytes (const char* Opt, const char* Arg)
395 /* Set the maximum number of bytes per listing line */
400 /* Convert the argument to a number */
401 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
402 AbEnd ("Invalid argument for option `%s'", Opt);
405 /* Check the bounds */
406 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
407 AbEnd ("Argument for option `%s' is out of range", Opt);
416 static void OptListing (const char* Opt attribute ((unused)),
417 const char* Arg attribute ((unused)))
418 /* Create a listing file */
425 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
426 /* Set a macro package directory */
428 /* Use the directory */
434 static void OptMemoryModel (const char* Opt, const char* Arg)
435 /* Set the memory model */
439 /* Check the current memory model */
440 if (MemoryModel != MMODEL_UNKNOWN) {
441 AbEnd ("Cannot use option `%s' twice", Opt);
444 /* Translate the memory model name and check it */
445 M = FindMemoryModel (Arg);
446 if (M == MMODEL_UNKNOWN) {
447 AbEnd ("Unknown memory model: %s", Arg);
448 } else if (M == MMODEL_HUGE) {
449 AbEnd ("Unsupported memory model: %s", Arg);
452 /* Set the memory model */
458 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
459 /* Handle the --pagelength option */
461 int Len = atoi (Arg);
462 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
463 AbEnd ("Invalid page length: %d", Len);
470 static void OptSmart (const char* Opt attribute ((unused)),
471 const char* Arg attribute ((unused)))
472 /* Handle the -s/--smart options */
479 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
480 /* Set the target system */
487 static void OptVerbose (const char* Opt attribute ((unused)),
488 const char* Arg attribute ((unused)))
489 /* Increase verbosity */
496 static void OptVersion (const char* Opt attribute ((unused)),
497 const char* Arg attribute ((unused)))
498 /* Print the assembler version */
501 "ca65 V%u.%u.%u - %s\n",
502 VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
507 static void DoPCAssign (void)
508 /* Start absolute code */
510 long PC = ConstExpression ();
511 if (PC < 0 || PC > 0xFFFFFF) {
512 Error ("Range error");
520 static void OneLine (void)
521 /* Assemble one line */
524 unsigned long PC = 0;
529 /* Initialize the new listing line if we are actually reading from file
530 * and not from internally pushed input.
532 if (!HavePushedInput ()) {
536 if (Tok == TOK_COLON) {
537 /* An unnamed label */
542 /* If the first token on the line is an identifier, check for a macro or
545 if (Tok == TOK_IDENT) {
546 if (!UbiquitousIdents) {
547 /* Macros and symbols cannot use instruction names */
548 Instr = FindInstruction (SVal);
550 Macro = IsMacro (SVal);
553 /* Macros and symbols may use the names of instructions */
554 Macro = IsMacro (SVal);
558 /* Handle an identifier */
559 if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
561 /* Did we have whitespace before the ident? */
564 /* Generate the symbol table entry, then skip the name */
565 if (Tok == TOK_IDENT) {
566 Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
568 Sym = SymFindLocal (SymLast, SVal, SYM_ALLOC_NEW);
572 /* If a colon follows, this is a label definition. If there
573 * is no colon, it's an assignment.
575 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
577 /* Determine the symbol flags from the assignment token */
578 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
583 /* Define the symbol with the expression following the '=' */
584 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
586 /* Don't allow anything after a symbol definition */
590 } else if (Tok == TOK_SET) {
594 /* .SET defines variables (= redefinable symbols) */
597 /* Read the assignment expression, which must be constant */
598 Expr = GenLiteralExpr (ConstExpression ());
600 /* Define the symbol with the constant expression following
603 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
605 /* Don't allow anything after a symbol definition */
611 /* A label. Remember the current segment, so we can later
612 * determine the size of the data stored under the label.
617 /* Define the label */
618 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
620 /* Skip the colon. If NoColonLabels is enabled, allow labels
621 * without a colon if there is no whitespace before the
624 if (Tok != TOK_COLON) {
625 if (HadWS || !NoColonLabels) {
626 Error ("`:' expected");
627 /* Try some smart error recovery */
628 if (Tok == TOK_NAMESPACE) {
637 /* If we come here, a new identifier may be waiting, which may
638 * be a macro or instruction.
640 if (Tok == TOK_IDENT) {
641 if (!UbiquitousIdents) {
642 /* Macros and symbols cannot use instruction names */
643 Instr = FindInstruction (SVal);
645 Macro = IsMacro (SVal);
648 /* Macros and symbols may use the names of instructions */
649 Macro = IsMacro (SVal);
655 /* We've handled a possible label, now handle the remainder of the line */
656 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
657 /* A control command */
660 /* A macro expansion */
662 } else if (Instr >= 0 ||
663 (UbiquitousIdents && ((Instr = FindInstruction (SVal)) >= 0))) {
664 /* A mnemonic - assemble one instruction */
665 HandleInstruction (Instr);
666 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
669 Error ("`=' expected");
672 /* Skip the equal sign */
674 /* Enter absolute mode */
679 /* If we have defined a label, remember its size. Sym is also set by
680 * a symbol assignment, but in this case Done is false, so we don't
685 if (Seg == ActiveSeg) {
687 Size = GetPC () - PC;
689 /* The line has switched the segment */
692 DefSizeOfSymbol (Sym, Size);
695 /* Line separator must come here */
701 static void Assemble (void)
702 /* Start the ball rolling ... */
707 /* Assemble lines until end of file */
708 while (Tok != TOK_EOF) {
715 static void CreateObjFile (void)
716 /* Create the object file */
718 /* Open the object, write the header */
721 /* Write the object file options */
724 /* Write the list of input files */
727 /* Write the segment data to the file */
730 /* Write the import list */
733 /* Write the export list */
736 /* Write debug symbols if requested */
739 /* Write line infos if requested */
742 /* Write the string pool */
745 /* Write the assertions */
748 /* Write an updated header and close the file */
754 int main (int argc, char* argv [])
755 /* Assembler main program */
757 /* Program long options */
758 static const LongOpt OptTab[] = {
759 { "--auto-import", 0, OptAutoImport },
760 { "--cpu", 1, OptCPU },
761 { "--debug-info", 0, OptDebugInfo },
762 { "--feature", 1, OptFeature },
763 { "--help", 0, OptHelp },
764 { "--ignore-case", 0, OptIgnoreCase },
765 { "--include-dir", 1, OptIncludeDir },
766 { "--list-bytes", 1, OptListBytes },
767 { "--listing", 0, OptListing },
768 { "--macpack-dir", 1, OptMacPackDir },
769 { "--memory-model", 1, OptMemoryModel },
770 { "--pagelength", 1, OptPageLength },
771 { "--smart", 0, OptSmart },
772 { "--target", 1, OptTarget },
773 { "--verbose", 0, OptVerbose },
774 { "--version", 0, OptVersion },
779 /* Initialize the cmdline module */
780 InitCmdLine (&argc, &argv, "ca65");
782 /* Enter the base lexical level. We must do that here, since we may
783 * define symbols using -D.
785 SymEnterLevel ("", ST_GLOBAL, ADDR_SIZE_DEFAULT);
787 /* Check the parameters */
789 while (I < ArgCount) {
791 /* Get the argument */
792 const char* Arg = ArgVec [I];
794 /* Check for an option */
799 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
803 OptDebugInfo (Arg, 0);
811 OptIgnoreCase (Arg, 0);
820 OptMemoryModel (Arg, GetArg (&I, 3));
827 OutFile = GetArg (&I, 2);
835 OptTarget (Arg, GetArg (&I, 2));
843 DefineSymbol (GetArg (&I, 2));
847 OptIncludeDir (Arg, GetArg (&I, 2));
851 OptAutoImport (Arg, 0);
859 WarnLevel = atoi (GetArg (&I, 2));
868 /* Filename. Check if we already had one */
870 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
882 /* Do we have an input file? */
884 fprintf (stderr, "%s: No input files\n", ProgName);
888 /* If no CPU given, use the default CPU for the target */
889 if (GetCPU () == CPU_UNKNOWN) {
890 if (Target != TGT_UNKNOWN) {
891 SetCPU (DefaultCPU[Target]);
897 /* If no memory model was given, use the default */
898 if (MemoryModel == MMODEL_UNKNOWN) {
899 SetMemoryModel (MMODEL_NEAR);
902 /* Initialize the segments */
905 /* Initialize the scanner, open the input file */
906 InitScanner (InFile);
908 /* Define the default options */
911 /* Assemble the input */
914 /* If we didn't have any errors, check the segment stack */
915 if (ErrorCount == 0) {
919 /* If we didn't have any errors, check the unnamed labels */
920 if (ErrorCount == 0) {
924 /* If we didn't have any errors, check the symbol table */
925 if (ErrorCount == 0) {
929 /* If we didn't have any errors, check and resolve the segment data */
930 if (ErrorCount == 0) {
934 /* If we didn't have any errors, check the assertions */
935 if (ErrorCount == 0) {
939 /* If we didn't have an errors, index the line infos */
940 MakeLineInfoIndex ();
943 if (Verbosity >= 2) {
948 /* If we didn't have any errors, create the object and listing files */
949 if (ErrorCount == 0) {
956 /* Close the input file */
959 /* Return an apropriate exit code */
960 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;