1 /*****************************************************************************/
5 /* Main program for the ca65 macroassembler */
9 /* (C) 1998-2008, 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 " --help\t\tHelp (this text)\n"
112 " --ignore-case\t\tIgnore case of symbols\n"
113 " --include-dir dir\tSet an include directory search path\n"
114 " --listing\t\tCreate a listing if assembly was ok\n"
115 " --list-bytes n\tMaximum number of bytes per listing line\n"
116 " --macpack-dir dir\tSet a macro package directory\n"
117 " --memory-model model\tSet the memory model\n"
118 " --pagelength n\tSet the page length for the listing\n"
119 " --smart\t\tEnable smart mode\n"
120 " --target sys\t\tSet the target system\n"
121 " --verbose\t\tIncrease verbosity\n"
122 " --version\t\tPrint the assembler version\n",
128 static void SetOptions (void)
129 /* Set the option for the translator */
131 StrBuf Buf = STATIC_STRBUF_INITIALIZER;
133 /* Set the translator */
134 SB_Printf (&Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
135 OptTranslator (&Buf);
137 /* Set date and time */
138 OptDateTime ((unsigned long) time(0));
140 /* Release memory for the string */
146 static void NewSymbol (const char* SymName, long Val)
147 /* Define a symbol with a fixed numeric value in the current scope */
152 /* Convert the name to a string buffer */
153 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
154 SB_CopyStr (&SymBuf, SymName);
156 /* Search for the symbol, allocate a new one if it doesn't exist */
157 Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
159 /* Check if have already a symbol with this name */
160 if (SymIsDef (Sym)) {
161 AbEnd ("`%s' is already defined", SymName);
164 /* Generate an expression for the symbol */
165 Expr = GenLiteralExpr (Val);
167 /* Mark the symbol as defined */
168 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
170 /* Free string buffer memory */
176 static void CBMSystem (const char* Sys)
177 /* Define a CBM system */
179 NewSymbol ("__CBM__", 1);
185 static void SetSys (const char* Sys)
186 /* Define a target system */
188 switch (Target = FindTarget (Sys)) {
194 AbEnd ("Cannot use `module' as a target for the assembler");
198 NewSymbol ("__ATARI__", 1);
202 CBMSystem ("__C16__");
206 CBMSystem ("__C64__");
210 CBMSystem ("__VIC20__");
214 CBMSystem ("__C128__");
218 CBMSystem ("__ACE__");
222 CBMSystem ("__PLUS4__");
226 CBMSystem ("__CBM510__");
230 CBMSystem ("__CBM610__");
234 CBMSystem ("__PET__");
238 NewSymbol ("__BBC__", 1);
242 NewSymbol ("__APPLE2__", 1);
246 NewSymbol ("__APPLE2ENH__", 1);
250 /* Do not handle as a CBM system */
251 NewSymbol ("__GEOS__", 1);
255 NewSymbol ("__LUNIX__", 1);
259 NewSymbol ("__ATMOS__", 1);
263 NewSymbol ("__NES__", 1);
266 case TGT_SUPERVISION:
267 NewSymbol ("__SUPERVISION__", 1);
271 NewSymbol ("__LYNX__", 1);
275 AbEnd ("Invalid target name: `%s'", Sys);
279 /* Initialize the translation tables for the target system */
285 static void DefineSymbol (const char* Def)
286 /* Define a symbol from the command line */
291 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
294 /* The symbol must start with a character or underline */
295 if (!IsIdStart (Def [0])) {
300 /* Copy the symbol, checking the rest */
302 while (IsIdChar (*P)) {
303 SB_AppendChar (&SymName, *P++);
305 SB_Terminate (&SymName);
307 /* Do we have a value given? */
314 /* We have a value */
318 if (sscanf (P, "%lx", &Val) != 1) {
322 if (sscanf (P, "%li", &Val) != 1) {
328 /* Define the new symbol */
329 NewSymbol (SB_GetConstBuf (&SymName), Val);
331 /* Release string memory */
337 static void OptAutoImport (const char* Opt attribute ((unused)),
338 const char* Arg attribute ((unused)))
339 /* Mark unresolved symbols as imported */
346 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
347 /* Handle the --cpu option */
349 cpu_t CPU = FindCPU (Arg);
350 if (CPU == CPU_UNKNOWN) {
351 AbEnd ("Invalid CPU: `%s'", Arg);
359 static void OptDebugInfo (const char* Opt attribute ((unused)),
360 const char* Arg attribute ((unused)))
361 /* Add debug info to the object file */
368 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
369 /* Set an emulation feature */
371 /* Make a string buffer from Arg */
374 /* Set the feature, check for errors */
375 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
376 AbEnd ("Illegal emulation feature: `%s'", Arg);
382 static void OptHelp (const char* Opt attribute ((unused)),
383 const char* Arg attribute ((unused)))
384 /* Print usage information and exit */
392 static void OptIgnoreCase (const char* Opt attribute ((unused)),
393 const char* Arg attribute ((unused)))
394 /* Ignore case on symbols */
401 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
402 /* Add an include search path */
404 AddIncludePath (Arg);
409 static void OptListBytes (const char* Opt, const char* Arg)
410 /* Set the maximum number of bytes per listing line */
415 /* Convert the argument to a number */
416 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
417 AbEnd ("Invalid argument for option `%s'", Opt);
420 /* Check the bounds */
421 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
422 AbEnd ("Argument for option `%s' is out of range", Opt);
431 static void OptListing (const char* Opt attribute ((unused)),
432 const char* Arg attribute ((unused)))
433 /* Create a listing file */
440 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
441 /* Set a macro package directory */
443 /* Make a string buffer from Arg */
446 /* Use the directory */
447 MacPackSetDir (SB_InitFromString (&Dir, Arg));
452 static void OptMemoryModel (const char* Opt, const char* Arg)
453 /* Set the memory model */
457 /* Check the current memory model */
458 if (MemoryModel != MMODEL_UNKNOWN) {
459 AbEnd ("Cannot use option `%s' twice", Opt);
462 /* Translate the memory model name and check it */
463 M = FindMemoryModel (Arg);
464 if (M == MMODEL_UNKNOWN) {
465 AbEnd ("Unknown memory model: %s", Arg);
466 } else if (M == MMODEL_HUGE) {
467 AbEnd ("Unsupported memory model: %s", Arg);
470 /* Set the memory model */
476 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
477 /* Handle the --pagelength option */
479 int Len = atoi (Arg);
480 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
481 AbEnd ("Invalid page length: %d", Len);
488 static void OptSmart (const char* Opt attribute ((unused)),
489 const char* Arg attribute ((unused)))
490 /* Handle the -s/--smart options */
497 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
498 /* Set the target system */
505 static void OptVerbose (const char* Opt attribute ((unused)),
506 const char* Arg attribute ((unused)))
507 /* Increase verbosity */
514 static void OptVersion (const char* Opt attribute ((unused)),
515 const char* Arg attribute ((unused)))
516 /* Print the assembler version */
519 "ca65 V%u.%u.%u - %s\n",
520 VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
525 static void DoPCAssign (void)
526 /* Start absolute code */
528 long PC = ConstExpression ();
529 if (PC < 0 || PC > 0xFFFFFF) {
530 Error ("Range error");
532 EnterAbsoluteMode (PC);
538 static void OneLine (void)
539 /* Assemble one line */
542 unsigned long PC = 0;
547 /* Initialize the new listing line if we are actually reading from file
548 * and not from internally pushed input.
550 if (!HavePushedInput ()) {
554 if (Tok == TOK_COLON) {
555 /* An unnamed label */
560 /* If the first token on the line is an identifier, check for a macro or
563 if (Tok == TOK_IDENT) {
564 if (!UbiquitousIdents) {
565 /* Macros and symbols cannot use instruction names */
566 Instr = FindInstruction (&SVal);
568 Macro = IsMacro (&SVal);
571 /* Macros and symbols may use the names of instructions */
572 Macro = IsMacro (&SVal);
576 /* Handle an identifier */
577 if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
579 /* Did we have whitespace before the ident? */
582 /* Generate the symbol table entry, then skip the name */
583 if (Tok == TOK_IDENT) {
584 Sym = SymFind (CurrentScope, &SVal, SYM_ALLOC_NEW);
586 Sym = SymFindLocal (SymLast, &SVal, SYM_ALLOC_NEW);
590 /* If a colon follows, this is a label definition. If there
591 * is no colon, it's an assignment.
593 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
595 /* Determine the symbol flags from the assignment token */
596 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
601 /* Define the symbol with the expression following the '=' */
602 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
604 /* Don't allow anything after a symbol definition */
608 } else if (Tok == TOK_SET) {
612 /* .SET defines variables (= redefinable symbols) */
615 /* Read the assignment expression, which must be constant */
616 Expr = GenLiteralExpr (ConstExpression ());
618 /* Define the symbol with the constant expression following
621 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
623 /* Don't allow anything after a symbol definition */
629 /* A label. Remember the current segment, so we can later
630 * determine the size of the data stored under the label.
635 /* Define the label */
636 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
638 /* Skip the colon. If NoColonLabels is enabled, allow labels
639 * without a colon if there is no whitespace before the
642 if (Tok != TOK_COLON) {
643 if (HadWS || !NoColonLabels) {
644 Error ("`:' expected");
645 /* Try some smart error recovery */
646 if (Tok == TOK_NAMESPACE) {
655 /* If we come here, a new identifier may be waiting, which may
656 * be a macro or instruction.
658 if (Tok == TOK_IDENT) {
659 if (!UbiquitousIdents) {
660 /* Macros and symbols cannot use instruction names */
661 Instr = FindInstruction (&SVal);
663 Macro = IsMacro (&SVal);
666 /* Macros and symbols may use the names of instructions */
667 Macro = IsMacro (&SVal);
673 /* We've handled a possible label, now handle the remainder of the line */
674 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
675 /* A control command */
678 /* A macro expansion */
680 } else if (Instr >= 0 ||
681 (UbiquitousIdents && ((Instr = FindInstruction (&SVal)) >= 0))) {
682 /* A mnemonic - assemble one instruction */
683 HandleInstruction (Instr);
684 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
687 Error ("`=' expected");
690 /* Skip the equal sign */
692 /* Enter absolute mode */
697 /* If we have defined a label, remember its size. Sym is also set by
698 * a symbol assignment, but in this case Done is false, so we don't
703 if (Seg == ActiveSeg) {
705 Size = GetPC () - PC;
707 /* The line has switched the segment */
710 DefSizeOfSymbol (Sym, Size);
713 /* Line separator must come here */
719 static void Assemble (void)
720 /* Start the ball rolling ... */
725 /* Assemble lines until end of file */
726 while (Tok != TOK_EOF) {
733 static void CreateObjFile (void)
734 /* Create the object file */
736 /* Open the object, write the header */
739 /* Write the object file options */
742 /* Write the list of input files */
745 /* Write the segment data to the file */
748 /* Write the import list */
751 /* Write the export list */
754 /* Write debug symbols if requested */
757 /* Write line infos if requested */
760 /* Write the string pool */
763 /* Write the assertions */
766 /* Write an updated header and close the file */
772 int main (int argc, char* argv [])
773 /* Assembler main program */
775 /* Program long options */
776 static const LongOpt OptTab[] = {
777 { "--auto-import", 0, OptAutoImport },
778 { "--cpu", 1, OptCPU },
779 { "--debug-info", 0, OptDebugInfo },
780 { "--feature", 1, OptFeature },
781 { "--help", 0, OptHelp },
782 { "--ignore-case", 0, OptIgnoreCase },
783 { "--include-dir", 1, OptIncludeDir },
784 { "--list-bytes", 1, OptListBytes },
785 { "--listing", 0, OptListing },
786 { "--macpack-dir", 1, OptMacPackDir },
787 { "--memory-model", 1, OptMemoryModel },
788 { "--pagelength", 1, OptPageLength },
789 { "--smart", 0, OptSmart },
790 { "--target", 1, OptTarget },
791 { "--verbose", 0, OptVerbose },
792 { "--version", 0, OptVersion },
795 /* Name of the global name space */
796 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
800 /* Initialize the cmdline module */
801 InitCmdLine (&argc, &argv, "ca65");
803 /* Enter the base lexical level. We must do that here, since we may
804 * define symbols using -D.
806 SymEnterLevel (&GlobalNameSpace, ST_GLOBAL, ADDR_SIZE_DEFAULT);
808 /* Check the parameters */
810 while (I < ArgCount) {
812 /* Get the argument */
813 const char* Arg = ArgVec [I];
815 /* Check for an option */
820 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
824 OptDebugInfo (Arg, 0);
832 OptIgnoreCase (Arg, 0);
841 OptMemoryModel (Arg, GetArg (&I, 3));
848 OutFile = GetArg (&I, 2);
856 OptTarget (Arg, GetArg (&I, 2));
864 DefineSymbol (GetArg (&I, 2));
868 OptIncludeDir (Arg, GetArg (&I, 2));
872 OptAutoImport (Arg, 0);
880 WarnLevel = atoi (GetArg (&I, 2));
889 /* Filename. Check if we already had one */
891 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
903 /* Do we have an input file? */
905 fprintf (stderr, "%s: No input files\n", ProgName);
909 /* If no CPU given, use the default CPU for the target */
910 if (GetCPU () == CPU_UNKNOWN) {
911 if (Target != TGT_UNKNOWN) {
912 SetCPU (DefaultCPU[Target]);
918 /* If no memory model was given, use the default */
919 if (MemoryModel == MMODEL_UNKNOWN) {
920 SetMemoryModel (MMODEL_NEAR);
923 /* Initialize the segments */
926 /* Initialize the scanner, open the input file */
927 InitScanner (InFile);
929 /* Define the default options */
932 /* Assemble the input */
935 /* If we didn't have any errors, check the segment stack */
936 if (ErrorCount == 0) {
940 /* If we didn't have any errors, check the unnamed labels */
941 if (ErrorCount == 0) {
945 /* If we didn't have any errors, check the symbol table */
946 if (ErrorCount == 0) {
950 /* If we didn't have any errors, check and resolve the segment data */
951 if (ErrorCount == 0) {
955 /* If we didn't have any errors, check the assertions */
956 if (ErrorCount == 0) {
960 /* If we didn't have an errors, index the line infos */
961 MakeLineInfoIndex ();
964 if (Verbosity >= 2) {
969 /* If we didn't have any errors, create the object and listing files */
970 if (ErrorCount == 0) {
977 /* Close the input file */
980 /* Return an apropriate exit code */
981 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;