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 /*****************************************************************************/
77 /*****************************************************************************/
79 /*****************************************************************************/
83 static void Usage (void)
84 /* Print usage information and exit */
87 "Usage: %s [options] file\n"
89 " -D name[=value]\tDefine a symbol\n"
90 " -I dir\t\tSet an include directory search path\n"
91 " -U\t\t\tMark unresolved symbols as import\n"
92 " -V\t\t\tPrint the assembler version\n"
93 " -W n\t\t\tSet warning level n\n"
94 " -g\t\t\tAdd debug info to object file\n"
95 " -h\t\t\tHelp (this text)\n"
96 " -i\t\t\tIgnore case of symbols\n"
97 " -l\t\t\tCreate a listing if assembly was ok\n"
98 " -mm model\t\tSet the memory model\n"
99 " -o name\t\tName the output file\n"
100 " -s\t\t\tEnable smart mode\n"
101 " -t sys\t\tSet the target system\n"
102 " -v\t\t\tIncrease verbosity\n"
105 " --auto-import\t\tMark unresolved symbols as import\n"
106 " --cpu type\t\tSet cpu type\n"
107 " --debug-info\t\tAdd debug info to object file\n"
108 " --feature name\tSet an emulation feature\n"
109 " --help\t\tHelp (this text)\n"
110 " --ignore-case\t\tIgnore case of symbols\n"
111 " --include-dir dir\tSet an include directory search path\n"
112 " --listing\t\tCreate a listing if assembly was ok\n"
113 " --memory-model model\tSet the memory model\n"
114 " --pagelength n\tSet the page length for the listing\n"
115 " --smart\t\tEnable smart mode\n"
116 " --target sys\t\tSet the target system\n"
117 " --verbose\t\tIncrease verbosity\n"
118 " --version\t\tPrint the assembler version\n",
124 static void SetOptions (void)
125 /* Set the option for the translator */
129 /* Set the translator */
130 sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
133 /* Set date and time */
134 OptDateTime ((unsigned long) time(0));
139 static void DefineSymbol (const char* Def)
140 /* Define a symbol from the command line */
145 char SymName [MAX_STR_LEN+1];
150 /* The symbol must start with a character or underline */
151 if (Def [0] != '_' && !IsAlpha (Def [0])) {
156 /* Copy the symbol, checking the rest */
158 while (IsAlNum (*P) || *P == '_') {
159 if (I <= MAX_STR_LEN) {
166 /* Do we have a value given? */
173 /* We have a value */
177 if (sscanf (P, "%lx", &Val) != 1) {
181 if (sscanf (P, "%li", &Val) != 1) {
187 /* Search for the symbol, allocate a new one if it doesn't exist */
188 Sym = SymFind (CurrentScope, SymName, SYM_ALLOC_NEW);
190 /* Check if have already a symbol with this name */
191 if (SymIsDef (Sym)) {
192 AbEnd ("`%s' is already defined", SymName);
195 /* Generate an expression for the symbol */
196 Expr = GenLiteralExpr (Val);
198 /* Mark the symbol as defined */
199 SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
204 static void OptAutoImport (const char* Opt attribute ((unused)),
205 const char* Arg attribute ((unused)))
206 /* Mark unresolved symbols as imported */
213 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
214 /* Handle the --cpu option */
216 cpu_t CPU = FindCPU (Arg);
217 if (CPU == CPU_UNKNOWN) {
218 AbEnd ("Invalid CPU: `%s'", Arg);
226 static void OptDebugInfo (const char* Opt attribute ((unused)),
227 const char* Arg attribute ((unused)))
228 /* Add debug info to the object file */
235 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
236 /* Set an emulation feature */
238 /* Set the feature, check for errors */
239 if (SetFeature (Arg) == FEAT_UNKNOWN) {
240 AbEnd ("Illegal emulation feature: `%s'", Arg);
246 static void OptHelp (const char* Opt attribute ((unused)),
247 const char* Arg attribute ((unused)))
248 /* Print usage information and exit */
256 static void OptIgnoreCase (const char* Opt attribute ((unused)),
257 const char* Arg attribute ((unused)))
258 /* Ignore case on symbols */
265 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
266 /* Add an include search path */
268 AddIncludePath (Arg);
273 static void OptListing (const char* Opt attribute ((unused)),
274 const char* Arg attribute ((unused)))
275 /* Create a listing file */
282 static void OptMemoryModel (const char* Opt, const char* Arg)
283 /* Set the memory model */
287 /* Check the current memory model */
288 if (MemoryModel != MMODEL_UNKNOWN) {
289 AbEnd ("Cannot use option `%s' twice", Opt);
292 /* Translate the memory model name and check it */
293 M = FindMemoryModel (Arg);
294 if (M == MMODEL_UNKNOWN) {
295 AbEnd ("Unknown memory model: %s", Arg);
296 } else if (M == MMODEL_HUGE) {
297 AbEnd ("Unsupported memory model: %s", Arg);
300 /* Set the memory model */
306 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
307 /* Handle the --pagelength option */
309 int Len = atoi (Arg);
310 if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
311 AbEnd ("Invalid page length: %d", Len);
318 static void OptSmart (const char* Opt attribute ((unused)),
319 const char* Arg attribute ((unused)))
320 /* Handle the -s/--smart options */
327 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
328 /* Set the target system */
330 /* Map the target name to a target id */
331 Target = FindTarget (Arg);
332 if (Target == TGT_UNKNOWN) {
333 AbEnd ("Invalid target name: `%s'", Arg);
334 } else if (Target == TGT_MODULE) {
335 AbEnd ("Cannot use `module' as a target for the assembler");
341 static void OptVerbose (const char* Opt attribute ((unused)),
342 const char* Arg attribute ((unused)))
343 /* Increase verbosity */
350 static void OptVersion (const char* Opt attribute ((unused)),
351 const char* Arg attribute ((unused)))
352 /* Print the assembler version */
355 "ca65 V%u.%u.%u - %s\n",
356 VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
361 static void DoPCAssign (void)
362 /* Start absolute code */
364 long PC = ConstExpression ();
365 if (PC < 0 || PC > 0xFFFFFF) {
366 Error ("Range error");
374 static void OneLine (void)
375 /* Assemble one line */
379 /* Initialize the new listing line if we are actually reading from file
380 * and not from internally pushed input.
382 if (!HavePushedInput ()) {
386 if (Tok == TOK_COLON) {
387 /* An unnamed label */
392 /* Assemble the line */
393 if (Tok == TOK_IDENT) {
396 if (IsMacro (SVal)) {
398 /* Yes, start a macro expansion */
404 /* No, label. Remember the identifier, then skip it */
405 int HadWS = WS; /* Did we have whitespace before the ident? */
407 /* Generate the symbol table entry, then skip the name */
408 SymEntry* Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
411 /* If a colon follows, this is a label definition. If there
412 * is no colon, it's an assignment.
414 if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
415 /* If it's an assign token, we have a label */
416 unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
419 /* Define the symbol with the expression following the '=' */
420 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
421 /* Don't allow anything after a symbol definition */
425 SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
426 /* Skip the colon. If NoColonLabels is enabled, allow labels
427 * without a colon if there is no whitespace before the
430 if (Tok != TOK_COLON) {
431 if (HadWS || !NoColonLabels) {
432 Error ("`:' expected");
434 if (Tok == TOK_NAMESPACE) {
435 /* Smart :: handling */
448 if (TokIsPseudo (Tok)) {
449 /* A control command, IVal is index into table */
451 } else if (Tok == TOK_MNEMO) {
452 /* A mnemonic - assemble one instruction */
453 HandleInstruction (IVal);
454 } else if (Tok == TOK_IDENT && IsMacro (SVal)) {
455 /* A macro expansion */
457 } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
460 Error ("`=' expected");
463 /* Skip the equal sign */
465 /* Enter absolute mode */
471 /* Line separator must come here */
477 static void Assemble (void)
478 /* Start the ball rolling ... */
483 /* Assemble lines until end of file */
484 while (Tok != TOK_EOF) {
491 static void CreateObjFile (void)
492 /* Create the object file */
494 /* Open the object, write the header */
497 /* Write the object file options */
500 /* Write the list of input files */
503 /* Write the segment data to the file */
506 /* Write the import list */
509 /* Write the export list */
512 /* Write debug symbols if requested */
515 /* Write line infos if requested */
518 /* Write the string pool */
521 /* Write the assertions */
524 /* Write an updated header and close the file */
530 int main (int argc, char* argv [])
531 /* Assembler main program */
533 /* Program long options */
534 static const LongOpt OptTab[] = {
535 { "--auto-import", 0, OptAutoImport },
536 { "--cpu", 1, OptCPU },
537 { "--debug-info", 0, OptDebugInfo },
538 { "--feature", 1, OptFeature },
539 { "--help", 0, OptHelp },
540 { "--ignore-case", 0, OptIgnoreCase },
541 { "--include-dir", 1, OptIncludeDir },
542 { "--listing", 0, OptListing },
543 { "--memory-model", 1, OptMemoryModel },
544 { "--pagelength", 1, OptPageLength },
545 { "--smart", 0, OptSmart },
546 { "--target", 1, OptTarget },
547 { "--verbose", 0, OptVerbose },
548 { "--version", 0, OptVersion },
553 /* Initialize the cmdline module */
554 InitCmdLine (&argc, &argv, "ca65");
556 /* Enter the base lexical level. We must do that here, since we may
557 * define symbols using -D.
559 SymEnterLevel ("", ST_GLOBAL, ADDR_SIZE_DEFAULT);
561 /* Check the parameters */
563 while (I < ArgCount) {
565 /* Get the argument */
566 const char* Arg = ArgVec [I];
568 /* Check for an option */
573 LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
577 OptDebugInfo (Arg, 0);
585 OptIgnoreCase (Arg, 0);
594 OptMemoryModel (Arg, GetArg (&I, 3));
601 OutFile = GetArg (&I, 2);
609 OptTarget (Arg, GetArg (&I, 2));
617 DefineSymbol (GetArg (&I, 2));
621 OptIncludeDir (Arg, GetArg (&I, 2));
625 OptAutoImport (Arg, 0);
633 WarnLevel = atoi (GetArg (&I, 2));
642 /* Filename. Check if we already had one */
644 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
656 /* Do we have an input file? */
658 fprintf (stderr, "%s: No input files\n", ProgName);
662 /* If no CPU given, use the default CPU for the target */
663 if (GetCPU () == CPU_UNKNOWN) {
664 if (Target != TGT_UNKNOWN) {
665 SetCPU (DefaultCPU[Target]);
671 /* If no memory model was given, use the default */
672 if (MemoryModel == MMODEL_UNKNOWN) {
673 MemoryModel = MMODEL_NEAR;
676 /* Intialize the target translation tables */
679 /* Initialize the segments */
682 /* Initialize the scanner, open the input file */
683 InitScanner (InFile);
685 /* Define the default options */
688 /* Assemble the input */
691 /* If we didn't have any errors, check the segment stack */
692 if (ErrorCount == 0) {
696 /* If we didn't have any errors, check the unnamed labels */
697 if (ErrorCount == 0) {
701 /* If we didn't have any errors, check the symbol table */
702 if (ErrorCount == 0) {
706 /* If we didn't have any errors, check and resolve the segment data */
707 if (ErrorCount == 0) {
711 /* If we didn't have an errors, index the line infos */
712 MakeLineInfoIndex ();
715 if (Verbosity >= 2) {
720 /* If we didn't have any errors, create the object and listing files */
721 if (ErrorCount == 0) {
728 /* Close the input file */
731 /* Return an apropriate exit code */
732 return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;