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) {
565 /* If it's an assign token, we have a label */
566 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
569 /* Define the symbol with the expression following the '=' */
570 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
571 /* Don't allow anything after a symbol definition */
575 /* A label. Remember the current segment, so we can later
576 * determine the size of the data stored under the label.
581 /* Define the label */
582 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
584 /* Skip the colon. If NoColonLabels is enabled, allow labels
585 * without a colon if there is no whitespace before the
588 if (Tok != TOK_COLON) {
589 if (HadWS || !NoColonLabels) {
590 Error ("`:' expected");
591 /* Try some smart error recovery */
592 if (Tok == TOK_NAMESPACE) {
601 /* If we come here, a new identifier may be waiting, which may
602 * be a macro or instruction.
604 if (Tok == TOK_IDENT) {
605 if (!UbiquitousIdents) {
606 /* Macros and symbols cannot use instruction names */
607 Instr = FindInstruction (SVal);
609 Macro = IsMacro (SVal);
612 /* Macros and symbols may use the names of instructions */
613 Macro = IsMacro (SVal);
619 /* We've handled a possible label, now handle the remainder of the line */
620 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
621 /* A control command */
624 /* A macro expansion */
626 } else if (Instr >= 0 ||
627 (UbiquitousIdents && ((Instr = FindInstruction (SVal)) >= 0))) {
628 /* A mnemonic - assemble one instruction */
629 HandleInstruction (Instr);
630 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
633 Error ("`=' expected");
636 /* Skip the equal sign */
638 /* Enter absolute mode */
643 /* If we have defined a label, remember its size. Sym is also set by
644 * a symbol assignment, but in this case Done is false, so we don't
649 if (Seg == ActiveSeg) {
651 Size = GetPC () - PC;
653 /* The line has switched the segment */
656 DefSizeOfSymbol (Sym, Size);
659 /* Line separator must come here */
665 static void Assemble (void)
666 /* Start the ball rolling ... */
671 /* Assemble lines until end of file */
672 while (Tok != TOK_EOF) {
679 static void CreateObjFile (void)
680 /* Create the object file */
682 /* Open the object, write the header */
685 /* Write the object file options */
688 /* Write the list of input files */
691 /* Write the segment data to the file */
694 /* Write the import list */
697 /* Write the export list */
700 /* Write debug symbols if requested */
703 /* Write line infos if requested */
706 /* Write the string pool */
709 /* Write the assertions */
712 /* Write an updated header and close the file */
718 int main (int argc, char* argv [])
719 /* Assembler main program */
721 /* Program long options */
722 static const LongOpt OptTab[] = {
723 { "--auto-import", 0, OptAutoImport },
724 { "--cpu", 1, OptCPU },
725 { "--debug-info", 0, OptDebugInfo },
726 { "--feature", 1, OptFeature },
727 { "--help", 0, OptHelp },
728 { "--ignore-case", 0, OptIgnoreCase },
729 { "--include-dir", 1, OptIncludeDir },
730 { "--list-bytes", 1, OptListBytes },
731 { "--listing", 0, OptListing },
732 { "--memory-model", 1, OptMemoryModel },
733 { "--pagelength", 1, OptPageLength },
734 { "--smart", 0, OptSmart },
735 { "--target", 1, OptTarget },
736 { "--verbose", 0, OptVerbose },
737 { "--version", 0, OptVersion },
742 /* Initialize the cmdline module */
743 InitCmdLine (&argc, &argv, "ca65");
745 /* Enter the base lexical level. We must do that here, since we may
746 * define symbols using -D.
748 SymEnterLevel ("", ST_GLOBAL, ADDR_SIZE_DEFAULT);
750 /* Check the parameters */
752 while (I < ArgCount) {
754 /* Get the argument */
755 const char* Arg = ArgVec [I];
757 /* Check for an option */
762 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
766 OptDebugInfo (Arg, 0);
774 OptIgnoreCase (Arg, 0);
783 OptMemoryModel (Arg, GetArg (&I, 3));
790 OutFile = GetArg (&I, 2);
798 OptTarget (Arg, GetArg (&I, 2));
806 DefineSymbol (GetArg (&I, 2));
810 OptIncludeDir (Arg, GetArg (&I, 2));
814 OptAutoImport (Arg, 0);
822 WarnLevel = atoi (GetArg (&I, 2));
831 /* Filename. Check if we already had one */
833 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
845 /* Do we have an input file? */
847 fprintf (stderr, "%s: No input files\n", ProgName);
851 /* If no CPU given, use the default CPU for the target */
852 if (GetCPU () == CPU_UNKNOWN) {
853 if (Target != TGT_UNKNOWN) {
854 SetCPU (DefaultCPU[Target]);
860 /* If no memory model was given, use the default */
861 if (MemoryModel == MMODEL_UNKNOWN) {
862 SetMemoryModel (MMODEL_NEAR);
865 /* Initialize the segments */
868 /* Initialize the scanner, open the input file */
869 InitScanner (InFile);
871 /* Define the default options */
874 /* Assemble the input */
877 /* If we didn't have any errors, check the segment stack */
878 if (ErrorCount == 0) {
882 /* If we didn't have any errors, check the unnamed labels */
883 if (ErrorCount == 0) {
887 /* If we didn't have any errors, check the symbol table */
888 if (ErrorCount == 0) {
892 /* If we didn't have any errors, check and resolve the segment data */
893 if (ErrorCount == 0) {
897 /* If we didn't have an errors, index the line infos */
898 MakeLineInfoIndex ();
901 if (Verbosity >= 2) {
906 /* If we didn't have any errors, create the object and listing files */
907 if (ErrorCount == 0) {
914 /* Close the input file */
917 /* Return an apropriate exit code */
918 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;