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 DefineSymbol (const char* Def)
142 /* Define a symbol from the command line */
147 char SymName [MAX_STR_LEN+1];
152 /* The symbol must start with a character or underline */
153 if (Def [0] != '_' && !IsAlpha (Def [0])) {
158 /* Copy the symbol, checking the rest */
160 while (IsAlNum (*P) || *P == '_') {
161 if (I <= MAX_STR_LEN) {
168 /* Do we have a value given? */
175 /* We have a value */
179 if (sscanf (P, "%lx", &Val) != 1) {
183 if (sscanf (P, "%li", &Val) != 1) {
189 /* Search for the symbol, allocate a new one if it doesn't exist */
190 Sym = SymFind (CurrentScope, SymName, SYM_ALLOC_NEW);
192 /* Check if have already a symbol with this name */
193 if (SymIsDef (Sym)) {
194 AbEnd ("`%s' is already defined", SymName);
197 /* Generate an expression for the symbol */
198 Expr = GenLiteralExpr (Val);
200 /* Mark the symbol as defined */
201 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
206 static void OptAutoImport (const char* Opt attribute ((unused)),
207 const char* Arg attribute ((unused)))
208 /* Mark unresolved symbols as imported */
215 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
216 /* Handle the --cpu option */
218 cpu_t CPU = FindCPU (Arg);
219 if (CPU == CPU_UNKNOWN) {
220 AbEnd ("Invalid CPU: `%s'", Arg);
228 static void OptDebugInfo (const char* Opt attribute ((unused)),
229 const char* Arg attribute ((unused)))
230 /* Add debug info to the object file */
237 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
238 /* Set an emulation feature */
240 /* Set the feature, check for errors */
241 if (SetFeature (Arg) == FEAT_UNKNOWN) {
242 AbEnd ("Illegal emulation feature: `%s'", Arg);
248 static void OptHelp (const char* Opt attribute ((unused)),
249 const char* Arg attribute ((unused)))
250 /* Print usage information and exit */
258 static void OptIgnoreCase (const char* Opt attribute ((unused)),
259 const char* Arg attribute ((unused)))
260 /* Ignore case on symbols */
267 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
268 /* Add an include search path */
270 AddIncludePath (Arg);
275 static void OptListBytes (const char* Opt, const char* Arg)
276 /* Set the maximum number of bytes per listing line */
281 /* Convert the argument to a number */
282 if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
283 AbEnd ("Invalid argument for option `%s'", Opt);
286 /* Check the bounds */
287 if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
288 AbEnd ("Argument for option `%s' is out of range", Opt);
297 static void OptListing (const char* Opt attribute ((unused)),
298 const char* Arg attribute ((unused)))
299 /* Create a listing file */
306 static void OptMemoryModel (const char* Opt, const char* Arg)
307 /* Set the memory model */
311 /* Check the current memory model */
312 if (MemoryModel != MMODEL_UNKNOWN) {
313 AbEnd ("Cannot use option `%s' twice", Opt);
316 /* Translate the memory model name and check it */
317 M = FindMemoryModel (Arg);
318 if (M == MMODEL_UNKNOWN) {
319 AbEnd ("Unknown memory model: %s", Arg);
320 } else if (M == MMODEL_HUGE) {
321 AbEnd ("Unsupported memory model: %s", Arg);
324 /* Set the memory model */
330 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
331 /* Handle the --pagelength option */
333 int Len = atoi (Arg);
334 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
335 AbEnd ("Invalid page length: %d", Len);
342 static void OptSmart (const char* Opt attribute ((unused)),
343 const char* Arg attribute ((unused)))
344 /* Handle the -s/--smart options */
351 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
352 /* Set the target system */
354 /* Map the target name to a target id */
355 Target = FindTarget (Arg);
356 if (Target == TGT_UNKNOWN) {
357 AbEnd ("Invalid target name: `%s'", Arg);
358 } else if (Target == TGT_MODULE) {
359 AbEnd ("Cannot use `module' as a target for the assembler");
365 static void OptVerbose (const char* Opt attribute ((unused)),
366 const char* Arg attribute ((unused)))
367 /* Increase verbosity */
374 static void OptVersion (const char* Opt attribute ((unused)),
375 const char* Arg attribute ((unused)))
376 /* Print the assembler version */
379 "ca65 V%u.%u.%u - %s\n",
380 VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
385 static void DoPCAssign (void)
386 /* Start absolute code */
388 long PC = ConstExpression ();
389 if (PC < 0 || PC > 0xFFFFFF) {
390 Error ("Range error");
398 static void OneLine (void)
399 /* Assemble one line */
402 unsigned long PC = 0;
407 /* Initialize the new listing line if we are actually reading from file
408 * and not from internally pushed input.
410 if (!HavePushedInput ()) {
414 if (Tok == TOK_COLON) {
415 /* An unnamed label */
420 /* If the first token on the line is an identifier, check for a macro or
423 if (Tok == TOK_IDENT) {
424 if (!UbiquitousIdents) {
425 /* Macros and symbols cannot use instruction names */
426 Instr = FindInstruction (SVal);
428 Macro = IsMacro (SVal);
431 /* Macros and symbols may use the names of instructions */
432 Macro = IsMacro (SVal);
436 /* Handle an identifier */
437 if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
439 /* Did we have whitespace before the ident? */
442 /* Generate the symbol table entry, then skip the name */
443 if (Tok == TOK_IDENT) {
444 Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
446 Sym = SymFindLocal (SymLast, SVal, SYM_ALLOC_NEW);
450 /* If a colon follows, this is a label definition. If there
451 * is no colon, it's an assignment.
453 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
454 /* If it's an assign token, we have a label */
455 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
458 /* Define the symbol with the expression following the '=' */
459 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
460 /* Don't allow anything after a symbol definition */
464 /* A label. Remember the current segment, so we can later
465 * determine the size of the data stored under the label.
470 /* Define the label */
471 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
473 /* Skip the colon. If NoColonLabels is enabled, allow labels
474 * without a colon if there is no whitespace before the
477 if (Tok != TOK_COLON) {
478 if (HadWS || !NoColonLabels) {
479 Error ("`:' expected");
480 /* Try some smart error recovery */
481 if (Tok == TOK_NAMESPACE) {
490 /* If we come here, a new identifier may be waiting, which may
491 * be a macro or instruction.
493 if (Tok == TOK_IDENT) {
494 if (!UbiquitousIdents) {
495 /* Macros and symbols cannot use instruction names */
496 Instr = FindInstruction (SVal);
498 Macro = IsMacro (SVal);
501 /* Macros and symbols may use the names of instructions */
502 Macro = IsMacro (SVal);
508 /* We've handled a possible label, now handle the remainder of the line */
509 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
510 /* A control command */
513 /* A macro expansion */
515 } else if (Instr >= 0 ||
516 (UbiquitousIdents && ((Instr = FindInstruction (SVal)) >= 0))) {
517 /* A mnemonic - assemble one instruction */
518 HandleInstruction (Instr);
519 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
522 Error ("`=' expected");
525 /* Skip the equal sign */
527 /* Enter absolute mode */
532 /* If we have defined a label, remember its size. Sym is also set by
533 * a symbol assignment, but in this case Done is false, so we don't
538 if (Seg == ActiveSeg) {
540 Size = GetPC () - PC;
542 /* The line has switched the segment */
545 DefSizeOfSymbol (Sym, Size);
548 /* Line separator must come here */
554 static void Assemble (void)
555 /* Start the ball rolling ... */
560 /* Assemble lines until end of file */
561 while (Tok != TOK_EOF) {
568 static void CreateObjFile (void)
569 /* Create the object file */
571 /* Open the object, write the header */
574 /* Write the object file options */
577 /* Write the list of input files */
580 /* Write the segment data to the file */
583 /* Write the import list */
586 /* Write the export list */
589 /* Write debug symbols if requested */
592 /* Write line infos if requested */
595 /* Write the string pool */
598 /* Write the assertions */
601 /* Write an updated header and close the file */
607 int main (int argc, char* argv [])
608 /* Assembler main program */
610 /* Program long options */
611 static const LongOpt OptTab[] = {
612 { "--auto-import", 0, OptAutoImport },
613 { "--cpu", 1, OptCPU },
614 { "--debug-info", 0, OptDebugInfo },
615 { "--feature", 1, OptFeature },
616 { "--help", 0, OptHelp },
617 { "--ignore-case", 0, OptIgnoreCase },
618 { "--include-dir", 1, OptIncludeDir },
619 { "--list-bytes", 1, OptListBytes },
620 { "--listing", 0, OptListing },
621 { "--memory-model", 1, OptMemoryModel },
622 { "--pagelength", 1, OptPageLength },
623 { "--smart", 0, OptSmart },
624 { "--target", 1, OptTarget },
625 { "--verbose", 0, OptVerbose },
626 { "--version", 0, OptVersion },
631 /* Initialize the cmdline module */
632 InitCmdLine (&argc, &argv, "ca65");
634 /* Enter the base lexical level. We must do that here, since we may
635 * define symbols using -D.
637 SymEnterLevel ("", ST_GLOBAL, ADDR_SIZE_DEFAULT);
639 /* Check the parameters */
641 while (I < ArgCount) {
643 /* Get the argument */
644 const char* Arg = ArgVec [I];
646 /* Check for an option */
651 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
655 OptDebugInfo (Arg, 0);
663 OptIgnoreCase (Arg, 0);
672 OptMemoryModel (Arg, GetArg (&I, 3));
679 OutFile = GetArg (&I, 2);
687 OptTarget (Arg, GetArg (&I, 2));
695 DefineSymbol (GetArg (&I, 2));
699 OptIncludeDir (Arg, GetArg (&I, 2));
703 OptAutoImport (Arg, 0);
711 WarnLevel = atoi (GetArg (&I, 2));
720 /* Filename. Check if we already had one */
722 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
734 /* Do we have an input file? */
736 fprintf (stderr, "%s: No input files\n", ProgName);
740 /* If no CPU given, use the default CPU for the target */
741 if (GetCPU () == CPU_UNKNOWN) {
742 if (Target != TGT_UNKNOWN) {
743 SetCPU (DefaultCPU[Target]);
749 /* If no memory model was given, use the default */
750 if (MemoryModel == MMODEL_UNKNOWN) {
751 SetMemoryModel (MMODEL_NEAR);
754 /* Intialize the target translation tables */
757 /* Initialize the segments */
760 /* Initialize the scanner, open the input file */
761 InitScanner (InFile);
763 /* Define the default options */
766 /* Assemble the input */
769 /* If we didn't have any errors, check the segment stack */
770 if (ErrorCount == 0) {
774 /* If we didn't have any errors, check the unnamed labels */
775 if (ErrorCount == 0) {
779 /* If we didn't have any errors, check the symbol table */
780 if (ErrorCount == 0) {
784 /* If we didn't have any errors, check and resolve the segment data */
785 if (ErrorCount == 0) {
789 /* If we didn't have an errors, index the line infos */
790 MakeLineInfoIndex ();
793 if (Verbosity >= 2) {
798 /* If we didn't have any errors, create the object and listing files */
799 if (ErrorCount == 0) {
806 /* Close the input file */
809 /* Return an apropriate exit code */
810 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;