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 */
88 "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 " --memory-model model\tSet the memory model\n"
116 " --pagelength n\tSet the page length for the listing\n"
117 " --smart\t\tEnable smart mode\n"
118 " --target sys\t\tSet the target system\n"
119 " --verbose\t\tIncrease verbosity\n"
120 " --version\t\tPrint the assembler version\n",
126 static void SetOptions (void)
127 /* Set the option for the translator */
131 /* Set the translator */
132 sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
135 /* Set date and time */
136 OptDateTime ((unsigned long) time(0));
141 static void NewSymbol (const char* SymName, long Val)
142 /* Define a symbol with a fixed numeric value in the current scope */
146 /* Search for the symbol, allocate a new one if it doesn't exist */
147 SymEntry* Sym = SymFind (CurrentScope, SymName, SYM_ALLOC_NEW);
149 /* Check if have already a symbol with this name */
150 if (SymIsDef (Sym)) {
151 AbEnd ("`%s' is already defined", SymName);
154 /* Generate an expression for the symbol */
155 Expr = GenLiteralExpr (Val);
157 /* Mark the symbol as defined */
158 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
163 static void CBMSystem (const char* Sys)
164 /* Define a CBM system */
166 NewSymbol ("__CBM__", 1);
172 static void SetSys (const char* Sys)
173 /* Define a target system */
175 switch (Target = FindTarget (Sys)) {
181 AbEnd ("Cannot use `module' as a target for the assembler");
185 NewSymbol ("__ATARI__", 1);
189 CBMSystem ("__C16__");
193 CBMSystem ("__C64__");
197 CBMSystem ("__VIC20__");
201 CBMSystem ("__C128__");
205 CBMSystem ("__ACE__");
209 CBMSystem ("__PLUS4__");
213 CBMSystem ("__CBM510__");
217 CBMSystem ("__CBM610__");
221 CBMSystem ("__PET__");
225 NewSymbol ("__BBC__", 1);
229 NewSymbol ("__APPLE2__", 1);
233 NewSymbol ("__APPLE2ENH__", 1);
237 /* Do not handle as a CBM system */
238 NewSymbol ("__GEOS__", 1);
242 NewSymbol ("__LUNIX__", 1);
246 NewSymbol ("__ATMOS__", 1);
250 NewSymbol ("__NES__", 1);
253 case TGT_SUPERVISION:
254 NewSymbol ("__SUPERVISION__", 1);
258 NewSymbol ("__LYNX__", 1);
262 AbEnd ("Invalid target name: `%s'", Sys);
266 /* Initialize the translation tables for the target system */
272 static void DefineSymbol (const char* Def)
273 /* Define a symbol from the command line */
278 char SymName [MAX_STR_LEN+1];
281 /* The symbol must start with a character or underline */
282 if (Def [0] != '_' && !IsAlpha (Def [0])) {
287 /* Copy the symbol, checking the rest */
289 while (IsAlNum (*P) || *P == '_') {
290 if (I <= MAX_STR_LEN) {
297 /* Do we have a value given? */
304 /* We have a value */
308 if (sscanf (P, "%lx", &Val) != 1) {
312 if (sscanf (P, "%li", &Val) != 1) {
318 /* Define the new symbol */
319 NewSymbol (SymName, Val);
324 static void OptAutoImport (const char* Opt attribute ((unused)),
325 const char* Arg attribute ((unused)))
326 /* Mark unresolved symbols as imported */
333 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
334 /* Handle the --cpu option */
336 cpu_t CPU = FindCPU (Arg);
337 if (CPU == CPU_UNKNOWN) {
338 AbEnd ("Invalid CPU: `%s'", Arg);
346 static void OptDebugInfo (const char* Opt attribute ((unused)),
347 const char* Arg attribute ((unused)))
348 /* Add debug info to the object file */
355 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
356 /* Set an emulation feature */
358 /* Set the feature, check for errors */
359 if (SetFeature (Arg) == FEAT_UNKNOWN) {
360 AbEnd ("Illegal emulation feature: `%s'", Arg);
366 static void OptHelp (const char* Opt attribute ((unused)),
367 const char* Arg attribute ((unused)))
368 /* Print usage information and exit */
376 static void OptIgnoreCase (const char* Opt attribute ((unused)),
377 const char* Arg attribute ((unused)))
378 /* Ignore case on symbols */
385 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
386 /* Add an include search path */
388 AddIncludePath (Arg);
393 static void OptListBytes (const char* Opt, const char* Arg)
394 /* Set the maximum number of bytes per listing line */
399 /* Convert the argument to a number */
400 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
401 AbEnd ("Invalid argument for option `%s'", Opt);
404 /* Check the bounds */
405 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
406 AbEnd ("Argument for option `%s' is out of range", Opt);
415 static void OptListing (const char* Opt attribute ((unused)),
416 const char* Arg attribute ((unused)))
417 /* Create a listing file */
424 static void OptMemoryModel (const char* Opt, const char* Arg)
425 /* Set the memory model */
429 /* Check the current memory model */
430 if (MemoryModel != MMODEL_UNKNOWN) {
431 AbEnd ("Cannot use option `%s' twice", Opt);
434 /* Translate the memory model name and check it */
435 M = FindMemoryModel (Arg);
436 if (M == MMODEL_UNKNOWN) {
437 AbEnd ("Unknown memory model: %s", Arg);
438 } else if (M == MMODEL_HUGE) {
439 AbEnd ("Unsupported memory model: %s", Arg);
442 /* Set the memory model */
448 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
449 /* Handle the --pagelength option */
451 int Len = atoi (Arg);
452 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
453 AbEnd ("Invalid page length: %d", Len);
460 static void OptSmart (const char* Opt attribute ((unused)),
461 const char* Arg attribute ((unused)))
462 /* Handle the -s/--smart options */
469 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
470 /* Set the target system */
477 static void OptVerbose (const char* Opt attribute ((unused)),
478 const char* Arg attribute ((unused)))
479 /* Increase verbosity */
486 static void OptVersion (const char* Opt attribute ((unused)),
487 const char* Arg attribute ((unused)))
488 /* Print the assembler version */
491 "ca65 V%u.%u.%u - %s\n",
492 VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
497 static void DoPCAssign (void)
498 /* Start absolute code */
500 long PC = ConstExpression ();
501 if (PC < 0 || PC > 0xFFFFFF) {
502 Error ("Range error");
510 static void OneLine (void)
511 /* Assemble one line */
514 unsigned long PC = 0;
519 /* Initialize the new listing line if we are actually reading from file
520 * and not from internally pushed input.
522 if (!HavePushedInput ()) {
526 if (Tok == TOK_COLON) {
527 /* An unnamed label */
532 /* If the first token on the line is an identifier, check for a macro or
535 if (Tok == TOK_IDENT) {
536 if (!UbiquitousIdents) {
537 /* Macros and symbols cannot use instruction names */
538 Instr = FindInstruction (SVal);
540 Macro = IsMacro (SVal);
543 /* Macros and symbols may use the names of instructions */
544 Macro = IsMacro (SVal);
548 /* Handle an identifier */
549 if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
551 /* Did we have whitespace before the ident? */
554 /* Generate the symbol table entry, then skip the name */
555 if (Tok == TOK_IDENT) {
556 Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
558 Sym = SymFindLocal (SymLast, SVal, SYM_ALLOC_NEW);
562 /* If a colon follows, this is a label definition. If there
563 * is no colon, it's an assignment.
565 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
566 /* If it's an assign token, we have a label */
567 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
570 /* Define the symbol with the expression following the '=' */
571 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
572 /* Don't allow anything after a symbol definition */
576 /* A label. Remember the current segment, so we can later
577 * determine the size of the data stored under the label.
582 /* Define the label */
583 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
585 /* Skip the colon. If NoColonLabels is enabled, allow labels
586 * without a colon if there is no whitespace before the
589 if (Tok != TOK_COLON) {
590 if (HadWS || !NoColonLabels) {
591 Error ("`:' expected");
592 /* Try some smart error recovery */
593 if (Tok == TOK_NAMESPACE) {
602 /* If we come here, a new identifier may be waiting, which may
603 * be a macro or instruction.
605 if (Tok == TOK_IDENT) {
606 if (!UbiquitousIdents) {
607 /* Macros and symbols cannot use instruction names */
608 Instr = FindInstruction (SVal);
610 Macro = IsMacro (SVal);
613 /* Macros and symbols may use the names of instructions */
614 Macro = IsMacro (SVal);
620 /* We've handled a possible label, now handle the remainder of the line */
621 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
622 /* A control command */
625 /* A macro expansion */
627 } else if (Instr >= 0 ||
628 (UbiquitousIdents && ((Instr = FindInstruction (SVal)) >= 0))) {
629 /* A mnemonic - assemble one instruction */
630 HandleInstruction (Instr);
631 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
634 Error ("`=' expected");
637 /* Skip the equal sign */
639 /* Enter absolute mode */
644 /* If we have defined a label, remember its size. Sym is also set by
645 * a symbol assignment, but in this case Done is false, so we don't
650 if (Seg == ActiveSeg) {
652 Size = GetPC () - PC;
654 /* The line has switched the segment */
657 DefSizeOfSymbol (Sym, Size);
660 /* Line separator must come here */
666 static void Assemble (void)
667 /* Start the ball rolling ... */
672 /* Assemble lines until end of file */
673 while (Tok != TOK_EOF) {
680 static void CreateObjFile (void)
681 /* Create the object file */
683 /* Open the object, write the header */
686 /* Write the object file options */
689 /* Write the list of input files */
692 /* Write the segment data to the file */
695 /* Write the import list */
698 /* Write the export list */
701 /* Write debug symbols if requested */
704 /* Write line infos if requested */
707 /* Write the string pool */
710 /* Write the assertions */
713 /* Write an updated header and close the file */
719 int main (int argc, char* argv [])
720 /* Assembler main program */
722 /* Program long options */
723 static const LongOpt OptTab[] = {
724 { "--auto-import", 0, OptAutoImport },
725 { "--cpu", 1, OptCPU },
726 { "--debug-info", 0, OptDebugInfo },
727 { "--feature", 1, OptFeature },
728 { "--help", 0, OptHelp },
729 { "--ignore-case", 0, OptIgnoreCase },
730 { "--include-dir", 1, OptIncludeDir },
731 { "--list-bytes", 1, OptListBytes },
732 { "--listing", 0, OptListing },
733 { "--memory-model", 1, OptMemoryModel },
734 { "--pagelength", 1, OptPageLength },
735 { "--smart", 0, OptSmart },
736 { "--target", 1, OptTarget },
737 { "--verbose", 0, OptVerbose },
738 { "--version", 0, OptVersion },
743 /* Initialize the cmdline module */
744 InitCmdLine (&argc, &argv, "ca65");
746 /* Enter the base lexical level. We must do that here, since we may
747 * define symbols using -D.
749 SymEnterLevel ("", ST_GLOBAL, ADDR_SIZE_DEFAULT);
751 /* Check the parameters */
753 while (I < ArgCount) {
755 /* Get the argument */
756 const char* Arg = ArgVec [I];
758 /* Check for an option */
763 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
767 OptDebugInfo (Arg, 0);
775 OptIgnoreCase (Arg, 0);
784 OptMemoryModel (Arg, GetArg (&I, 3));
791 OutFile = GetArg (&I, 2);
799 OptTarget (Arg, GetArg (&I, 2));
807 DefineSymbol (GetArg (&I, 2));
811 OptIncludeDir (Arg, GetArg (&I, 2));
815 OptAutoImport (Arg, 0);
823 WarnLevel = atoi (GetArg (&I, 2));
832 /* Filename. Check if we already had one */
834 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
846 /* Do we have an input file? */
848 fprintf (stderr, "%s: No input files\n", ProgName);
852 /* If no CPU given, use the default CPU for the target */
853 if (GetCPU () == CPU_UNKNOWN) {
854 if (Target != TGT_UNKNOWN) {
855 SetCPU (DefaultCPU[Target]);
861 /* If no memory model was given, use the default */
862 if (MemoryModel == MMODEL_UNKNOWN) {
863 SetMemoryModel (MMODEL_NEAR);
866 /* Initialize the segments */
869 /* Initialize the scanner, open the input file */
870 InitScanner (InFile);
872 /* Define the default options */
875 /* Assemble the input */
878 /* If we didn't have any errors, check the segment stack */
879 if (ErrorCount == 0) {
883 /* If we didn't have any errors, check the unnamed labels */
884 if (ErrorCount == 0) {
888 /* If we didn't have any errors, check the symbol table */
889 if (ErrorCount == 0) {
893 /* If we didn't have any errors, check and resolve the segment data */
894 if (ErrorCount == 0) {
898 /* If we didn't have an errors, index the line infos */
899 MakeLineInfoIndex ();
902 if (Verbosity >= 2) {
907 /* If we didn't have any errors, create the object and listing files */
908 if (ErrorCount == 0) {
915 /* Close the input file */
918 /* Return an apropriate exit code */
919 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;