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 */
151 /* Convert the name to a string buffer */
152 StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
153 SB_CopyStr (&SymBuf, SymName);
155 /* Search for the symbol, allocate a new one if it doesn't exist */
156 SymEntry* Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
158 /* Check if have already a symbol with this name */
159 if (SymIsDef (Sym)) {
160 AbEnd ("`%s' is already defined", SymName);
163 /* Generate an expression for the symbol */
164 Expr = GenLiteralExpr (Val);
166 /* Mark the symbol as defined */
167 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
169 /* Free string buffer memory */
175 static void CBMSystem (const char* Sys)
176 /* Define a CBM system */
178 NewSymbol ("__CBM__", 1);
184 static void SetSys (const char* Sys)
185 /* Define a target system */
187 switch (Target = FindTarget (Sys)) {
193 AbEnd ("Cannot use `module' as a target for the assembler");
197 NewSymbol ("__ATARI__", 1);
201 CBMSystem ("__C16__");
205 CBMSystem ("__C64__");
209 CBMSystem ("__VIC20__");
213 CBMSystem ("__C128__");
217 CBMSystem ("__ACE__");
221 CBMSystem ("__PLUS4__");
225 CBMSystem ("__CBM510__");
229 CBMSystem ("__CBM610__");
233 CBMSystem ("__PET__");
237 NewSymbol ("__BBC__", 1);
241 NewSymbol ("__APPLE2__", 1);
245 NewSymbol ("__APPLE2ENH__", 1);
249 /* Do not handle as a CBM system */
250 NewSymbol ("__GEOS__", 1);
254 NewSymbol ("__LUNIX__", 1);
258 NewSymbol ("__ATMOS__", 1);
262 NewSymbol ("__NES__", 1);
265 case TGT_SUPERVISION:
266 NewSymbol ("__SUPERVISION__", 1);
270 NewSymbol ("__LYNX__", 1);
274 AbEnd ("Invalid target name: `%s'", Sys);
278 /* Initialize the translation tables for the target system */
284 static void DefineSymbol (const char* Def)
285 /* Define a symbol from the command line */
290 StrBuf SymName = AUTO_STRBUF_INITIALIZER;
293 /* The symbol must start with a character or underline */
294 if (!IsIdStart (Def [0])) {
299 /* Copy the symbol, checking the rest */
301 while (IsIdChar (*P)) {
302 SB_AppendChar (&SymName, *P++);
304 SB_Terminate (&SymName);
306 /* Do we have a value given? */
313 /* We have a value */
317 if (sscanf (P, "%lx", &Val) != 1) {
321 if (sscanf (P, "%li", &Val) != 1) {
327 /* Define the new symbol */
328 NewSymbol (SB_GetConstBuf (&SymName), Val);
330 /* Release string memory */
336 static void OptAutoImport (const char* Opt attribute ((unused)),
337 const char* Arg attribute ((unused)))
338 /* Mark unresolved symbols as imported */
345 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
346 /* Handle the --cpu option */
348 cpu_t CPU = FindCPU (Arg);
349 if (CPU == CPU_UNKNOWN) {
350 AbEnd ("Invalid CPU: `%s'", Arg);
358 static void OptDebugInfo (const char* Opt attribute ((unused)),
359 const char* Arg attribute ((unused)))
360 /* Add debug info to the object file */
367 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
368 /* Set an emulation feature */
370 /* Make a string buffer from Arg */
373 /* Set the feature, check for errors */
374 if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
375 AbEnd ("Illegal emulation feature: `%s'", Arg);
381 static void OptHelp (const char* Opt attribute ((unused)),
382 const char* Arg attribute ((unused)))
383 /* Print usage information and exit */
391 static void OptIgnoreCase (const char* Opt attribute ((unused)),
392 const char* Arg attribute ((unused)))
393 /* Ignore case on symbols */
400 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
401 /* Add an include search path */
403 AddIncludePath (Arg);
408 static void OptListBytes (const char* Opt, const char* Arg)
409 /* Set the maximum number of bytes per listing line */
414 /* Convert the argument to a number */
415 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
416 AbEnd ("Invalid argument for option `%s'", Opt);
419 /* Check the bounds */
420 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
421 AbEnd ("Argument for option `%s' is out of range", Opt);
430 static void OptListing (const char* Opt attribute ((unused)),
431 const char* Arg attribute ((unused)))
432 /* Create a listing file */
439 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
440 /* Set a macro package directory */
442 /* Make a string buffer from Arg */
445 /* Use the directory */
446 MacPackSetDir (SB_InitFromString (&Dir, Arg));
451 static void OptMemoryModel (const char* Opt, const char* Arg)
452 /* Set the memory model */
456 /* Check the current memory model */
457 if (MemoryModel != MMODEL_UNKNOWN) {
458 AbEnd ("Cannot use option `%s' twice", Opt);
461 /* Translate the memory model name and check it */
462 M = FindMemoryModel (Arg);
463 if (M == MMODEL_UNKNOWN) {
464 AbEnd ("Unknown memory model: %s", Arg);
465 } else if (M == MMODEL_HUGE) {
466 AbEnd ("Unsupported memory model: %s", Arg);
469 /* Set the memory model */
475 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
476 /* Handle the --pagelength option */
478 int Len = atoi (Arg);
479 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
480 AbEnd ("Invalid page length: %d", Len);
487 static void OptSmart (const char* Opt attribute ((unused)),
488 const char* Arg attribute ((unused)))
489 /* Handle the -s/--smart options */
496 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
497 /* Set the target system */
504 static void OptVerbose (const char* Opt attribute ((unused)),
505 const char* Arg attribute ((unused)))
506 /* Increase verbosity */
513 static void OptVersion (const char* Opt attribute ((unused)),
514 const char* Arg attribute ((unused)))
515 /* Print the assembler version */
518 "ca65 V%u.%u.%u - %s\n",
519 VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
524 static void DoPCAssign (void)
525 /* Start absolute code */
527 long PC = ConstExpression ();
528 if (PC < 0 || PC > 0xFFFFFF) {
529 Error ("Range error");
531 EnterAbsoluteMode (PC);
537 static void OneLine (void)
538 /* Assemble one line */
541 unsigned long PC = 0;
546 /* Initialize the new listing line if we are actually reading from file
547 * and not from internally pushed input.
549 if (!HavePushedInput ()) {
553 if (Tok == TOK_COLON) {
554 /* An unnamed label */
559 /* If the first token on the line is an identifier, check for a macro or
562 if (Tok == TOK_IDENT) {
563 if (!UbiquitousIdents) {
564 /* Macros and symbols cannot use instruction names */
565 Instr = FindInstruction (&SVal);
567 Macro = IsMacro (&SVal);
570 /* Macros and symbols may use the names of instructions */
571 Macro = IsMacro (&SVal);
575 /* Handle an identifier */
576 if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
578 /* Did we have whitespace before the ident? */
581 /* Generate the symbol table entry, then skip the name */
582 if (Tok == TOK_IDENT) {
583 Sym = SymFind (CurrentScope, &SVal, SYM_ALLOC_NEW);
585 Sym = SymFindLocal (SymLast, &SVal, SYM_ALLOC_NEW);
589 /* If a colon follows, this is a label definition. If there
590 * is no colon, it's an assignment.
592 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
594 /* Determine the symbol flags from the assignment token */
595 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
600 /* Define the symbol with the expression following the '=' */
601 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
603 /* Don't allow anything after a symbol definition */
607 } else if (Tok == TOK_SET) {
611 /* .SET defines variables (= redefinable symbols) */
614 /* Read the assignment expression, which must be constant */
615 Expr = GenLiteralExpr (ConstExpression ());
617 /* Define the symbol with the constant expression following
620 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
622 /* Don't allow anything after a symbol definition */
628 /* A label. Remember the current segment, so we can later
629 * determine the size of the data stored under the label.
634 /* Define the label */
635 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
637 /* Skip the colon. If NoColonLabels is enabled, allow labels
638 * without a colon if there is no whitespace before the
641 if (Tok != TOK_COLON) {
642 if (HadWS || !NoColonLabels) {
643 Error ("`:' expected");
644 /* Try some smart error recovery */
645 if (Tok == TOK_NAMESPACE) {
654 /* If we come here, a new identifier may be waiting, which may
655 * be a macro or instruction.
657 if (Tok == TOK_IDENT) {
658 if (!UbiquitousIdents) {
659 /* Macros and symbols cannot use instruction names */
660 Instr = FindInstruction (&SVal);
662 Macro = IsMacro (&SVal);
665 /* Macros and symbols may use the names of instructions */
666 Macro = IsMacro (&SVal);
672 /* We've handled a possible label, now handle the remainder of the line */
673 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
674 /* A control command */
677 /* A macro expansion */
679 } else if (Instr >= 0 ||
680 (UbiquitousIdents && ((Instr = FindInstruction (&SVal)) >= 0))) {
681 /* A mnemonic - assemble one instruction */
682 HandleInstruction (Instr);
683 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
686 Error ("`=' expected");
689 /* Skip the equal sign */
691 /* Enter absolute mode */
696 /* If we have defined a label, remember its size. Sym is also set by
697 * a symbol assignment, but in this case Done is false, so we don't
702 if (Seg == ActiveSeg) {
704 Size = GetPC () - PC;
706 /* The line has switched the segment */
709 DefSizeOfSymbol (Sym, Size);
712 /* Line separator must come here */
718 static void Assemble (void)
719 /* Start the ball rolling ... */
724 /* Assemble lines until end of file */
725 while (Tok != TOK_EOF) {
732 static void CreateObjFile (void)
733 /* Create the object file */
735 /* Open the object, write the header */
738 /* Write the object file options */
741 /* Write the list of input files */
744 /* Write the segment data to the file */
747 /* Write the import list */
750 /* Write the export list */
753 /* Write debug symbols if requested */
756 /* Write line infos if requested */
759 /* Write the string pool */
762 /* Write the assertions */
765 /* Write an updated header and close the file */
771 int main (int argc, char* argv [])
772 /* Assembler main program */
774 /* Program long options */
775 static const LongOpt OptTab[] = {
776 { "--auto-import", 0, OptAutoImport },
777 { "--cpu", 1, OptCPU },
778 { "--debug-info", 0, OptDebugInfo },
779 { "--feature", 1, OptFeature },
780 { "--help", 0, OptHelp },
781 { "--ignore-case", 0, OptIgnoreCase },
782 { "--include-dir", 1, OptIncludeDir },
783 { "--list-bytes", 1, OptListBytes },
784 { "--listing", 0, OptListing },
785 { "--macpack-dir", 1, OptMacPackDir },
786 { "--memory-model", 1, OptMemoryModel },
787 { "--pagelength", 1, OptPageLength },
788 { "--smart", 0, OptSmart },
789 { "--target", 1, OptTarget },
790 { "--verbose", 0, OptVerbose },
791 { "--version", 0, OptVersion },
794 /* Name of the global name space */
795 static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
799 /* Initialize the cmdline module */
800 InitCmdLine (&argc, &argv, "ca65");
802 /* Enter the base lexical level. We must do that here, since we may
803 * define symbols using -D.
805 SymEnterLevel (&GlobalNameSpace, ST_GLOBAL, ADDR_SIZE_DEFAULT);
807 /* Check the parameters */
809 while (I < ArgCount) {
811 /* Get the argument */
812 const char* Arg = ArgVec [I];
814 /* Check for an option */
819 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
823 OptDebugInfo (Arg, 0);
831 OptIgnoreCase (Arg, 0);
840 OptMemoryModel (Arg, GetArg (&I, 3));
847 OutFile = GetArg (&I, 2);
855 OptTarget (Arg, GetArg (&I, 2));
863 DefineSymbol (GetArg (&I, 2));
867 OptIncludeDir (Arg, GetArg (&I, 2));
871 OptAutoImport (Arg, 0);
879 WarnLevel = atoi (GetArg (&I, 2));
888 /* Filename. Check if we already had one */
890 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
902 /* Do we have an input file? */
904 fprintf (stderr, "%s: No input files\n", ProgName);
908 /* If no CPU given, use the default CPU for the target */
909 if (GetCPU () == CPU_UNKNOWN) {
910 if (Target != TGT_UNKNOWN) {
911 SetCPU (DefaultCPU[Target]);
917 /* If no memory model was given, use the default */
918 if (MemoryModel == MMODEL_UNKNOWN) {
919 SetMemoryModel (MMODEL_NEAR);
922 /* Initialize the segments */
925 /* Initialize the scanner, open the input file */
926 InitScanner (InFile);
928 /* Define the default options */
931 /* Assemble the input */
934 /* If we didn't have any errors, check the segment stack */
935 if (ErrorCount == 0) {
939 /* If we didn't have any errors, check the unnamed labels */
940 if (ErrorCount == 0) {
944 /* If we didn't have any errors, check the symbol table */
945 if (ErrorCount == 0) {
949 /* If we didn't have any errors, check and resolve the segment data */
950 if (ErrorCount == 0) {
954 /* If we didn't have any errors, check the assertions */
955 if (ErrorCount == 0) {
959 /* If we didn't have an errors, index the line infos */
960 MakeLineInfoIndex ();
963 if (Verbosity >= 2) {
968 /* If we didn't have any errors, create the object and listing files */
969 if (ErrorCount == 0) {
976 /* Close the input file */
979 /* Return an apropriate exit code */
980 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;