1 /*****************************************************************************/
5 /* Main program for the ca65 macroassembler */
9 /* (C) 1998-2003 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 " --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 DefineSymbol (const char* Def)
141 /* Define a symbol from the command line */
146 char SymName [MAX_STR_LEN+1];
151 /* The symbol must start with a character or underline */
152 if (Def [0] != '_' && !IsAlpha (Def [0])) {
157 /* Copy the symbol, checking the rest */
159 while (IsAlNum (*P) || *P == '_') {
160 if (I <= MAX_STR_LEN) {
167 /* Do we have a value given? */
174 /* We have a value */
178 if (sscanf (P, "%lx", &Val) != 1) {
182 if (sscanf (P, "%li", &Val) != 1) {
188 /* Search for the symbol, allocate a new one if it doesn't exist */
189 Sym = SymFind (CurrentScope, SymName, SYM_ALLOC_NEW);
191 /* Check if have already a symbol with this name */
192 if (SymIsDef (Sym)) {
193 AbEnd ("`%s' is already defined", SymName);
196 /* Generate an expression for the symbol */
197 Expr = GenLiteralExpr (Val);
199 /* Mark the symbol as defined */
200 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
205 static void OptAutoImport (const char* Opt attribute ((unused)),
206 const char* Arg attribute ((unused)))
207 /* Mark unresolved symbols as imported */
214 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
215 /* Handle the --cpu option */
217 cpu_t CPU = FindCPU (Arg);
218 if (CPU == CPU_UNKNOWN) {
219 AbEnd ("Invalid CPU: `%s'", Arg);
227 static void OptDebugInfo (const char* Opt attribute ((unused)),
228 const char* Arg attribute ((unused)))
229 /* Add debug info to the object file */
236 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
237 /* Set an emulation feature */
239 /* Set the feature, check for errors */
240 if (SetFeature (Arg) == FEAT_UNKNOWN) {
241 AbEnd ("Illegal emulation feature: `%s'", Arg);
247 static void OptHelp (const char* Opt attribute ((unused)),
248 const char* Arg attribute ((unused)))
249 /* Print usage information and exit */
257 static void OptIgnoreCase (const char* Opt attribute ((unused)),
258 const char* Arg attribute ((unused)))
259 /* Ignore case on symbols */
266 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
267 /* Add an include search path */
269 AddIncludePath (Arg);
274 static void OptListing (const char* Opt attribute ((unused)),
275 const char* Arg attribute ((unused)))
276 /* Create a listing file */
283 static void OptMemoryModel (const char* Opt, const char* Arg)
284 /* Set the memory model */
288 /* Check the current memory model */
289 if (MemoryModel != MMODEL_UNKNOWN) {
290 AbEnd ("Cannot use option `%s' twice", Opt);
293 /* Translate the memory model name and check it */
294 M = FindMemoryModel (Arg);
295 if (M == MMODEL_UNKNOWN) {
296 AbEnd ("Unknown memory model: %s", Arg);
297 } else if (M == MMODEL_HUGE) {
298 AbEnd ("Unsupported memory model: %s", Arg);
301 /* Set the memory model */
307 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
308 /* Handle the --pagelength option */
310 int Len = atoi (Arg);
311 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
312 AbEnd ("Invalid page length: %d", Len);
319 static void OptSmart (const char* Opt attribute ((unused)),
320 const char* Arg attribute ((unused)))
321 /* Handle the -s/--smart options */
328 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
329 /* Set the target system */
331 /* Map the target name to a target id */
332 Target = FindTarget (Arg);
333 if (Target == TGT_UNKNOWN) {
334 AbEnd ("Invalid target name: `%s'", Arg);
335 } else if (Target == TGT_MODULE) {
336 AbEnd ("Cannot use `module' as a target for the assembler");
342 static void OptVerbose (const char* Opt attribute ((unused)),
343 const char* Arg attribute ((unused)))
344 /* Increase verbosity */
351 static void OptVersion (const char* Opt attribute ((unused)),
352 const char* Arg attribute ((unused)))
353 /* Print the assembler version */
356 "ca65 V%u.%u.%u - %s\n",
357 VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
362 static void DoPCAssign (void)
363 /* Start absolute code */
365 long PC = ConstExpression ();
366 if (PC < 0 || PC > 0xFFFFFF) {
367 Error ("Range error");
375 static void OneLine (void)
376 /* Assemble one line */
379 unsigned long PC = 0;
385 /* Initialize the new listing line if we are actually reading from file
386 * and not from internally pushed input.
388 if (!HavePushedInput ()) {
392 if (Tok == TOK_COLON) {
393 /* An unnamed label */
398 /* If the first token on the line is an identifier, check for a macro or
401 if (Tok == TOK_IDENT) {
402 if (!UbiquitousIdents) {
403 /* Macros and symbols cannot use instruction names */
404 Instr = FindInstruction (SVal);
406 Macro = IsMacro (SVal);
409 /* Macros and symbols may use the names of instructions */
410 Macro = IsMacro (SVal);
414 /* Handle an identifier */
415 if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
417 /* Did we have whitespace before the ident? */
420 /* Generate the symbol table entry, then skip the name */
421 if (Tok == TOK_IDENT) {
422 Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
424 Sym = SymFindLocal (SymLast, SVal, SYM_ALLOC_NEW);
428 /* If a colon follows, this is a label definition. If there
429 * is no colon, it's an assignment.
431 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
432 /* If it's an assign token, we have a label */
433 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
436 /* Define the symbol with the expression following the '=' */
437 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
438 /* Don't allow anything after a symbol definition */
441 /* A label. Remember the current segment, so we can later
442 * determine the size of the data stored under the label.
447 /* Define the label */
448 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
450 /* Skip the colon. If NoColonLabels is enabled, allow labels
451 * without a colon if there is no whitespace before the
454 if (Tok != TOK_COLON) {
455 if (HadWS || !NoColonLabels) {
456 Error ("`:' expected");
457 /* Try some smart error recovery */
458 if (Tok == TOK_NAMESPACE) {
471 if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
472 /* A control command */
475 /* A macro expansion */
477 } else if (Instr >= 0 ||
478 (UbiquitousIdents && ((Instr = FindInstruction (SVal)) >= 0))) {
479 /* A mnemonic - assemble one instruction */
480 HandleInstruction (Instr);
481 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
484 Error ("`=' expected");
487 /* Skip the equal sign */
489 /* Enter absolute mode */
494 /* If we have defined a label, remember its size. Sym is also set by
495 * a symbol assignment, but in this case Done is false, so we don't
500 if (Seg == ActiveSeg) {
502 Size = GetPC () - PC;
504 /* The line has switched the segment */
507 DefSizeOfSymbol (Sym, Size);
511 /* Line separator must come here */
517 static void Assemble (void)
518 /* Start the ball rolling ... */
523 /* Assemble lines until end of file */
524 while (Tok != TOK_EOF) {
531 static void CreateObjFile (void)
532 /* Create the object file */
534 /* Open the object, write the header */
537 /* Write the object file options */
540 /* Write the list of input files */
543 /* Write the segment data to the file */
546 /* Write the import list */
549 /* Write the export list */
552 /* Write debug symbols if requested */
555 /* Write line infos if requested */
558 /* Write the string pool */
561 /* Write the assertions */
564 /* Write an updated header and close the file */
570 int main (int argc, char* argv [])
571 /* Assembler main program */
573 /* Program long options */
574 static const LongOpt OptTab[] = {
575 { "--auto-import", 0, OptAutoImport },
576 { "--cpu", 1, OptCPU },
577 { "--debug-info", 0, OptDebugInfo },
578 { "--feature", 1, OptFeature },
579 { "--help", 0, OptHelp },
580 { "--ignore-case", 0, OptIgnoreCase },
581 { "--include-dir", 1, OptIncludeDir },
582 { "--listing", 0, OptListing },
583 { "--memory-model", 1, OptMemoryModel },
584 { "--pagelength", 1, OptPageLength },
585 { "--smart", 0, OptSmart },
586 { "--target", 1, OptTarget },
587 { "--verbose", 0, OptVerbose },
588 { "--version", 0, OptVersion },
593 /* Initialize the cmdline module */
594 InitCmdLine (&argc, &argv, "ca65");
596 /* Enter the base lexical level. We must do that here, since we may
597 * define symbols using -D.
599 SymEnterLevel ("", ST_GLOBAL, ADDR_SIZE_DEFAULT);
601 /* Check the parameters */
603 while (I < ArgCount) {
605 /* Get the argument */
606 const char* Arg = ArgVec [I];
608 /* Check for an option */
613 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
617 OptDebugInfo (Arg, 0);
625 OptIgnoreCase (Arg, 0);
634 OptMemoryModel (Arg, GetArg (&I, 3));
641 OutFile = GetArg (&I, 2);
649 OptTarget (Arg, GetArg (&I, 2));
657 DefineSymbol (GetArg (&I, 2));
661 OptIncludeDir (Arg, GetArg (&I, 2));
665 OptAutoImport (Arg, 0);
673 WarnLevel = atoi (GetArg (&I, 2));
682 /* Filename. Check if we already had one */
684 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
696 /* Do we have an input file? */
698 fprintf (stderr, "%s: No input files\n", ProgName);
702 /* If no CPU given, use the default CPU for the target */
703 if (GetCPU () == CPU_UNKNOWN) {
704 if (Target != TGT_UNKNOWN) {
705 SetCPU (DefaultCPU[Target]);
711 /* If no memory model was given, use the default */
712 if (MemoryModel == MMODEL_UNKNOWN) {
713 SetMemoryModel (MMODEL_NEAR);
716 /* Intialize the target translation tables */
719 /* Initialize the segments */
722 /* Initialize the scanner, open the input file */
723 InitScanner (InFile);
725 /* Define the default options */
728 /* Assemble the input */
731 /* If we didn't have any errors, check the segment stack */
732 if (ErrorCount == 0) {
736 /* If we didn't have any errors, check the unnamed labels */
737 if (ErrorCount == 0) {
741 /* If we didn't have any errors, check the symbol table */
742 if (ErrorCount == 0) {
746 /* If we didn't have any errors, check and resolve the segment data */
747 if (ErrorCount == 0) {
751 /* If we didn't have an errors, index the line infos */
752 MakeLineInfoIndex ();
755 if (Verbosity >= 2) {
760 /* If we didn't have any errors, create the object and listing files */
761 if (ErrorCount == 0) {
768 /* Close the input file */
771 /* Return an apropriate exit code */
772 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;