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 /*****************************************************************************/
76 /*****************************************************************************/
78 /*****************************************************************************/
82 static void Usage (void)
83 /* Print usage information and exit */
86 "Usage: %s [options] file\n"
88 " -D name[=value]\tDefine a symbol\n"
89 " -I dir\t\tSet an include directory search path\n"
90 " -U\t\t\tMark unresolved symbols as import\n"
91 " -V\t\t\tPrint the assembler version\n"
92 " -W n\t\t\tSet warning level n\n"
93 " -g\t\t\tAdd debug info to object file\n"
94 " -h\t\t\tHelp (this text)\n"
95 " -i\t\t\tIgnore case of symbols\n"
96 " -l\t\t\tCreate a listing if assembly was ok\n"
97 " -o name\t\tName the output file\n"
98 " -s\t\t\tEnable smart mode\n"
99 " -t sys\t\tSet the target system\n"
100 " -v\t\t\tIncrease verbosity\n"
103 " --auto-import\t\tMark unresolved symbols as import\n"
104 " --cpu type\t\tSet cpu type\n"
105 " --debug-info\t\tAdd debug info to object file\n"
106 " --feature name\tSet an emulation feature\n"
107 " --help\t\tHelp (this text)\n"
108 " --ignore-case\t\tIgnore case of symbols\n"
109 " --include-dir dir\tSet an include directory search path\n"
110 " --listing\t\tCreate a listing if assembly was ok\n"
111 " --pagelength n\tSet the page length for the listing\n"
112 " --smart\t\tEnable smart mode\n"
113 " --target sys\t\tSet the target system\n"
114 " --verbose\t\tIncrease verbosity\n"
115 " --version\t\tPrint the assembler version\n",
121 static void SetOptions (void)
122 /* Set the option for the translator */
126 /* Set the translator */
127 sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
130 /* Set date and time */
131 OptDateTime ((unsigned long) time(0));
136 static void DefineSymbol (const char* Def)
137 /* Define a symbol from the command line */
142 char SymName [MAX_STR_LEN+1];
146 /* The symbol must start with a character or underline */
147 if (Def [0] != '_' && !IsAlpha (Def [0])) {
152 /* Copy the symbol, checking the rest */
154 while (IsAlNum (*P) || *P == '_') {
155 if (I <= MAX_STR_LEN) {
162 /* Do we have a value given? */
169 /* We have a value */
173 if (sscanf (P, "%lx", &Val) != 1) {
177 if (sscanf (P, "%li", &Val) != 1) {
183 /* Search for the symbol, allocate a new one if it doesn't exist */
184 Sym = SymFind (CurrentScope, SymName, SYM_ALLOC_NEW);
186 /* Check if have already a symbol with this name */
187 if (SymIsDef (Sym)) {
188 AbEnd ("`%s' is already defined", SymName);
191 /* Mark the symbol as defined */
192 SymDef (Sym, GenLiteralExpr (Val), ADDR_SIZE_DEFAULT, SF_NONE);
197 static void OptAutoImport (const char* Opt attribute ((unused)),
198 const char* Arg attribute ((unused)))
199 /* Mark unresolved symbols as imported */
206 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
207 /* Handle the --cpu option */
209 cpu_t CPU = FindCPU (Arg);
210 if (CPU == CPU_UNKNOWN) {
211 AbEnd ("Invalid CPU: `%s'", Arg);
219 static void OptDebugInfo (const char* Opt attribute ((unused)),
220 const char* Arg attribute ((unused)))
221 /* Add debug info to the object file */
228 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
229 /* Set an emulation feature */
231 /* Set the feature, check for errors */
232 if (SetFeature (Arg) == FEAT_UNKNOWN) {
233 AbEnd ("Illegal emulation feature: `%s'", Arg);
239 static void OptHelp (const char* Opt attribute ((unused)),
240 const char* Arg attribute ((unused)))
241 /* Print usage information and exit */
249 static void OptIgnoreCase (const char* Opt attribute ((unused)),
250 const char* Arg attribute ((unused)))
251 /* Ignore case on symbols */
258 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
259 /* Add an include search path */
261 AddIncludePath (Arg);
266 static void OptListing (const char* Opt attribute ((unused)),
267 const char* Arg attribute ((unused)))
268 /* Create a listing file */
275 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
276 /* Handle the --pagelength option */
278 int Len = atoi (Arg);
279 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
280 AbEnd ("Invalid page length: %d", Len);
287 static void OptSmart (const char* Opt attribute ((unused)),
288 const char* Arg attribute ((unused)))
289 /* Handle the -s/--smart options */
296 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
297 /* Set the target system */
299 /* Map the target name to a target id */
300 Target = FindTarget (Arg);
301 if (Target == TGT_UNKNOWN) {
302 AbEnd ("Invalid target name: `%s'", Arg);
303 } else if (Target == TGT_MODULE) {
304 AbEnd ("Cannot use `module' as a target for the assembler");
310 static void OptVerbose (const char* Opt attribute ((unused)),
311 const char* Arg attribute ((unused)))
312 /* Increase verbosity */
319 static void OptVersion (const char* Opt attribute ((unused)),
320 const char* Arg attribute ((unused)))
321 /* Print the assembler version */
324 "ca65 V%u.%u.%u - %s\n",
325 VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
330 static void DoPCAssign (void)
331 /* Start absolute code */
333 long PC = ConstExpression ();
334 if (PC < 0 || PC > 0xFFFFFF) {
335 Error ("Range error");
343 static void OneLine (void)
344 /* Assemble one line */
348 /* Initialize the new listing line if we are actually reading from file
349 * and not from internally pushed input.
351 if (!HavePushedInput ()) {
355 if (Tok == TOK_COLON) {
356 /* An unnamed label */
361 /* Assemble the line */
362 if (Tok == TOK_IDENT) {
365 if (IsMacro (SVal)) {
367 /* Yes, start a macro expansion */
373 /* No, label. Remember the identifier, then skip it */
374 int HadWS = WS; /* Did we have whitespace before the ident? */
376 /* Generate the symbol table entry, then skip the name */
377 SymEntry* Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
380 /* If a colon follows, this is a label definition. If there
381 * is no colon, it's an assignment.
383 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
384 /* If it's an assign token, we have a label */
385 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
388 /* Define the symbol with the expression following the '=' */
389 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
390 /* Don't allow anything after a symbol definition */
394 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
395 /* Skip the colon. If NoColonLabels is enabled, allow labels
396 * without a colon if there is no whitespace before the
399 if (Tok != TOK_COLON) {
400 if (HadWS || !NoColonLabels) {
401 Error ("`:' expected");
403 if (Tok == TOK_NAMESPACE) {
404 /* Smart :: handling */
417 if (TokIsPseudo (Tok)) {
418 /* A control command, IVal is index into table */
420 } else if (Tok == TOK_MNEMO) {
421 /* A mnemonic - assemble one instruction */
422 HandleInstruction (IVal);
423 } else if (Tok == TOK_IDENT && IsMacro (SVal)) {
424 /* A macro expansion */
426 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
429 Error ("`=' expected");
432 /* Skip the equal sign */
434 /* Enter absolute mode */
440 /* Line separator must come here */
446 static void Assemble (void)
447 /* Start the ball rolling ... */
452 /* Assemble lines until end of file */
453 while (Tok != TOK_EOF) {
460 static void CreateObjFile (void)
461 /* Create the object file */
463 /* Open the object, write the header */
466 /* Write the object file options */
469 /* Write the list of input files */
472 /* Write the segment data to the file */
475 /* Write the import list */
478 /* Write the export list */
481 /* Write debug symbols if requested */
484 /* Write line infos if requested */
487 /* Write the string pool */
490 /* Write the assertions */
493 /* Write an updated header and close the file */
499 int main (int argc, char* argv [])
500 /* Assembler main program */
502 /* Program long options */
503 static const LongOpt OptTab[] = {
504 { "--auto-import", 0, OptAutoImport },
505 { "--cpu", 1, OptCPU },
506 { "--debug-info", 0, OptDebugInfo },
507 { "--feature", 1, OptFeature },
508 { "--help", 0, OptHelp },
509 { "--ignore-case", 0, OptIgnoreCase },
510 { "--include-dir", 1, OptIncludeDir },
511 { "--listing", 0, OptListing },
512 { "--pagelength", 1, OptPageLength },
513 { "--smart", 0, OptSmart },
514 { "--target", 1, OptTarget },
515 { "--verbose", 0, OptVerbose },
516 { "--version", 0, OptVersion },
521 /* Initialize the cmdline module */
522 InitCmdLine (&argc, &argv, "ca65");
524 /* Enter the base lexical level. We must do that here, since we may
525 * define symbols using -D.
527 SymEnterLevel ("", ST_GLOBAL, ADDR_SIZE_DEFAULT);
529 /* Check the parameters */
531 while (I < ArgCount) {
533 /* Get the argument */
534 const char* Arg = ArgVec [I];
536 /* Check for an option */
537 if (Arg [0] == '-') {
541 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
545 OptDebugInfo (Arg, 0);
553 OptIgnoreCase (Arg, 0);
561 OutFile = GetArg (&I, 2);
569 OptTarget (Arg, GetArg (&I, 2));
577 DefineSymbol (GetArg (&I, 2));
581 OptIncludeDir (Arg, GetArg (&I, 2));
585 OptAutoImport (Arg, 0);
593 WarnLevel = atoi (GetArg (&I, 2));
602 /* Filename. Check if we already had one */
604 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
616 /* Do we have an input file? */
618 fprintf (stderr, "%s: No input files\n", ProgName);
622 /* If no CPU given, use the default CPU for the target */
623 if (GetCPU () == CPU_UNKNOWN) {
624 if (Target != TGT_UNKNOWN) {
625 SetCPU (DefaultCPU[Target]);
631 /* Intialize the target translation tables */
634 /* Initialize the scanner, open the input file */
635 InitScanner (InFile);
637 /* Define the default options */
640 /* Assemble the input */
643 /* If we didn't have any errors, check the segment stack */
644 if (ErrorCount == 0) {
648 /* If we didn't have any errors, check the unnamed labels */
649 if (ErrorCount == 0) {
653 /* If we didn't have any errors, check the symbol table */
654 if (ErrorCount == 0) {
658 /* If we didn't have any errors, check and resolve the segment data */
659 if (ErrorCount == 0) {
663 /* If we didn't have an errors, index the line infos */
664 MakeLineInfoIndex ();
667 if (Verbosity >= 2) {
672 /* If we didn't have any errors, create the object and listing files */
673 if (ErrorCount == 0) {
680 /* Close the input file */
683 /* Return an apropriate exit code */
684 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;