]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
More fixes for Watcom C / C89.
[cc65] / src / ca65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                 Main program for the ca65 macroassembler                  */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2008, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
12 /* EMail:         uz@cc65.org                                                */
13 /*                                                                           */
14 /*                                                                           */
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.                                    */
18 /*                                                                           */
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:                            */
22 /*                                                                           */
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              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <time.h>
40
41 /* common */
42 #include "addrsize.h"
43 #include "chartype.h"
44 #include "cmdline.h"
45 #include "mmodel.h"
46 #include "print.h"
47 #include "strbuf.h"
48 #include "target.h"
49 #include "tgttrans.h"
50 #include "version.h"
51
52 /* ca65 */
53 #include "abend.h"
54 #include "asserts.h"
55 #include "error.h"
56 #include "expr.h"
57 #include "feature.h"
58 #include "filetab.h"
59 #include "global.h"
60 #include "incpath.h"
61 #include "instr.h"
62 #include "istack.h"
63 #include "lineinfo.h"
64 #include "listing.h"
65 #include "macpack.h"
66 #include "macro.h"
67 #include "nexttok.h"
68 #include "objfile.h"
69 #include "options.h"
70 #include "pseudo.h"
71 #include "scanner.h"
72 #include "segment.h"
73 #include "sizeof.h"
74 #include "spool.h"
75 #include "symtab.h"
76 #include "ulabel.h"
77
78
79
80 /*****************************************************************************/
81 /*                                   Code                                    */
82 /*****************************************************************************/
83
84
85
86 static void Usage (void)
87 /* Print usage information and exit */
88 {
89     printf ("Usage: %s [options] file\n"
90             "Short options:\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"
105             "\n"
106             "Long options:\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",
123             ProgName);
124 }
125
126
127
128 static void SetOptions (void)
129 /* Set the option for the translator */
130 {
131     StrBuf Buf = STATIC_STRBUF_INITIALIZER;
132
133     /* Set the translator */
134     SB_Printf (&Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
135     OptTranslator (&Buf);
136
137     /* Set date and time */
138     OptDateTime ((unsigned long) time(0));
139
140     /* Release memory for the string */
141     SB_Done (&Buf);
142 }
143
144
145
146 static void NewSymbol (const char* SymName, long Val)
147 /* Define a symbol with a fixed numeric value in the current scope */
148 {
149     ExprNode* Expr;
150     SymEntry* Sym;
151
152     /* Convert the name to a string buffer */
153     StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
154     SB_CopyStr (&SymBuf, SymName);
155
156     /* Search for the symbol, allocate a new one if it doesn't exist */
157     Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
158
159     /* Check if have already a symbol with this name */
160     if (SymIsDef (Sym)) {
161         AbEnd ("`%s' is already defined", SymName);
162     }
163
164     /* Generate an expression for the symbol */
165     Expr = GenLiteralExpr (Val);
166
167     /* Mark the symbol as defined */
168     SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
169
170     /* Free string buffer memory */
171     SB_Done (&SymBuf);
172 }
173
174
175
176 static void CBMSystem (const char* Sys)
177 /* Define a CBM system */
178 {
179     NewSymbol ("__CBM__", 1);
180     NewSymbol (Sys, 1);
181 }
182
183
184
185 static void SetSys (const char* Sys)
186 /* Define a target system */
187 {
188     switch (Target = FindTarget (Sys)) {
189
190         case TGT_NONE:
191             break;
192
193         case TGT_MODULE:
194             AbEnd ("Cannot use `module' as a target for the assembler");
195             break;
196
197         case TGT_ATARI:
198             NewSymbol ("__ATARI__", 1);
199             break;
200
201         case TGT_C16:
202             CBMSystem ("__C16__");
203             break;
204
205         case TGT_C64:
206             CBMSystem ("__C64__");
207             break;
208
209         case TGT_VIC20:
210             CBMSystem ("__VIC20__");
211             break;
212
213         case TGT_C128:
214             CBMSystem ("__C128__");
215             break;
216
217         case TGT_ACE:
218             CBMSystem ("__ACE__");
219             break;
220
221         case TGT_PLUS4:
222             CBMSystem ("__PLUS4__");
223             break;
224
225         case TGT_CBM510:
226             CBMSystem ("__CBM510__");
227             break;
228
229         case TGT_CBM610:
230             CBMSystem ("__CBM610__");
231             break;
232
233         case TGT_PET:
234             CBMSystem ("__PET__");
235             break;
236
237         case TGT_BBC:
238             NewSymbol ("__BBC__", 1);
239             break;
240
241         case TGT_APPLE2:
242             NewSymbol ("__APPLE2__", 1);
243             break;
244
245         case TGT_APPLE2ENH:
246             NewSymbol ("__APPLE2ENH__", 1);
247             break;
248
249         case TGT_GEOS:
250             /* Do not handle as a CBM system */
251             NewSymbol ("__GEOS__", 1);
252             break;
253
254         case TGT_LUNIX:
255             NewSymbol ("__LUNIX__", 1);
256             break;
257
258         case TGT_ATMOS:
259             NewSymbol ("__ATMOS__", 1);
260             break;
261
262         case TGT_NES:
263             NewSymbol ("__NES__", 1);
264             break;
265
266         case TGT_SUPERVISION:
267             NewSymbol ("__SUPERVISION__", 1);
268             break;
269
270         case TGT_LYNX:
271             NewSymbol ("__LYNX__", 1);
272             break;
273
274         default:
275             AbEnd ("Invalid target name: `%s'", Sys);
276
277     }
278
279     /* Initialize the translation tables for the target system */
280     TgtTranslateInit ();
281 }
282
283
284
285 static void DefineSymbol (const char* Def)
286 /* Define a symbol from the command line */
287 {
288     const char* P;
289     unsigned I;
290     long Val;
291     StrBuf SymName = AUTO_STRBUF_INITIALIZER;
292
293
294     /* The symbol must start with a character or underline */
295     if (!IsIdStart (Def [0])) {
296         InvDef (Def);
297     }
298     P = Def;
299
300     /* Copy the symbol, checking the rest */
301     I = 0;
302     while (IsIdChar (*P)) {
303         SB_AppendChar (&SymName, *P++);
304     }
305     SB_Terminate (&SymName);
306
307     /* Do we have a value given? */
308     if (*P != '=') {
309         if (*P != '\0') {
310             InvDef (Def);
311         }
312         Val = 0;
313     } else {
314         /* We have a value */
315         ++P;
316         if (*P == '$') {
317             ++P;
318             if (sscanf (P, "%lx", &Val) != 1) {
319                 InvDef (Def);
320             }
321         } else {
322             if (sscanf (P, "%li", &Val) != 1) {
323                 InvDef (Def);
324             }
325         }
326     }
327
328     /* Define the new symbol */
329     NewSymbol (SB_GetConstBuf (&SymName), Val);
330
331     /* Release string memory */
332     SB_Done (&SymName);
333 }
334
335
336
337 static void OptAutoImport (const char* Opt attribute ((unused)),
338                            const char* Arg attribute ((unused)))
339 /* Mark unresolved symbols as imported */
340 {
341     AutoImport = 1;
342 }
343
344
345
346 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
347 /* Handle the --cpu option */
348 {
349     cpu_t CPU = FindCPU (Arg);
350     if (CPU == CPU_UNKNOWN) {
351         AbEnd ("Invalid CPU: `%s'", Arg);
352     } else {
353         SetCPU (CPU);
354     }
355 }
356
357
358
359 static void OptDebugInfo (const char* Opt attribute ((unused)),
360                           const char* Arg attribute ((unused)))
361 /* Add debug info to the object file */
362 {
363     DbgSyms = 1;
364 }
365
366
367
368 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
369 /* Set an emulation feature */
370 {
371     /* Make a string buffer from Arg */
372     StrBuf Feature;
373
374     /* Set the feature, check for errors */
375     if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
376         AbEnd ("Illegal emulation feature: `%s'", Arg);
377     }
378 }
379
380
381
382 static void OptHelp (const char* Opt attribute ((unused)),
383                      const char* Arg attribute ((unused)))
384 /* Print usage information and exit */
385 {
386     Usage ();
387     exit (EXIT_SUCCESS);
388 }
389
390
391
392 static void OptIgnoreCase (const char* Opt attribute ((unused)),
393                            const char* Arg attribute ((unused)))
394 /* Ignore case on symbols */
395 {
396     IgnoreCase = 1;
397 }
398
399
400
401 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
402 /* Add an include search path */
403 {
404     AddIncludePath (Arg);
405 }
406
407
408
409 static void OptListBytes (const char* Opt, const char* Arg)
410 /* Set the maximum number of bytes per listing line */
411 {
412     unsigned Num;
413     char     Check;
414
415     /* Convert the argument to a number */
416     if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
417         AbEnd ("Invalid argument for option `%s'", Opt);
418     }
419
420     /* Check the bounds */
421     if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
422         AbEnd ("Argument for option `%s' is out of range", Opt);
423     }
424
425     /* Use the value */
426     SetListBytes (Num);
427 }
428
429
430
431 static void OptListing (const char* Opt attribute ((unused)),
432                         const char* Arg attribute ((unused)))
433 /* Create a listing file */
434 {
435     Listing = 1;
436 }
437
438
439
440 static void OptMacPackDir (const char* Opt attribute ((unused)), const char* Arg)
441 /* Set a macro package directory */
442 {
443     /* Make a string buffer from Arg */
444     StrBuf Dir;
445
446     /* Use the directory */
447     MacPackSetDir (SB_InitFromString (&Dir, Arg));
448 }
449
450
451
452 static void OptMemoryModel (const char* Opt, const char* Arg)
453 /* Set the memory model */
454 {
455     mmodel_t M;
456
457     /* Check the current memory model */
458     if (MemoryModel != MMODEL_UNKNOWN) {
459         AbEnd ("Cannot use option `%s' twice", Opt);
460     }
461
462     /* Translate the memory model name and check it */
463     M = FindMemoryModel (Arg);
464     if (M == MMODEL_UNKNOWN) {
465         AbEnd ("Unknown memory model: %s", Arg);
466     } else if (M == MMODEL_HUGE) {
467         AbEnd ("Unsupported memory model: %s", Arg);
468     }
469
470     /* Set the memory model */
471     SetMemoryModel (M);
472 }
473
474
475
476 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
477 /* Handle the --pagelength option */
478 {
479     int Len = atoi (Arg);
480     if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
481         AbEnd ("Invalid page length: %d", Len);
482     }
483     PageLength = Len;
484 }
485
486
487
488 static void OptSmart (const char* Opt attribute ((unused)),
489                       const char* Arg attribute ((unused)))
490 /* Handle the -s/--smart options */
491 {
492     SmartMode = 1;
493 }
494
495
496
497 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
498 /* Set the target system */
499 {
500     SetSys (Arg);
501 }
502
503
504
505 static void OptVerbose (const char* Opt attribute ((unused)),
506                         const char* Arg attribute ((unused)))
507 /* Increase verbosity */
508 {
509     ++Verbosity;
510 }
511
512
513
514 static void OptVersion (const char* Opt attribute ((unused)),
515                         const char* Arg attribute ((unused)))
516 /* Print the assembler version */
517 {
518     fprintf (stderr,
519              "ca65 V%u.%u.%u - %s\n",
520              VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
521 }
522
523
524
525 static void DoPCAssign (void)
526 /* Start absolute code */
527 {
528     long PC = ConstExpression ();
529     if (PC < 0 || PC > 0xFFFFFF) {
530         Error ("Range error");
531     } else {
532         EnterAbsoluteMode (PC);
533     }
534 }
535
536
537
538 static void OneLine (void)
539 /* Assemble one line */
540 {
541     Segment*      Seg   = 0;
542     unsigned long PC    = 0;
543     SymEntry*     Sym   = 0;
544     int           Macro = 0;
545     int           Instr = -1;
546
547     /* Initialize the new listing line if we are actually reading from file
548      * and not from internally pushed input.
549      */
550     if (!HavePushedInput ()) {
551         InitListingLine ();
552     }
553
554     if (Tok == TOK_COLON) {
555         /* An unnamed label */
556         ULabDef ();
557         NextTok ();
558     }
559
560     /* If the first token on the line is an identifier, check for a macro or
561      * an instruction.
562      */
563     if (Tok == TOK_IDENT) {
564         if (!UbiquitousIdents) {
565             /* Macros and symbols cannot use instruction names */
566             Instr = FindInstruction (&SVal);
567             if (Instr < 0) {
568                 Macro = IsMacro (&SVal);
569             }
570         } else {
571             /* Macros and symbols may use the names of instructions */
572             Macro = IsMacro (&SVal);
573         }
574     }
575
576     /* Handle an identifier */
577     if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
578
579         /* Did we have whitespace before the ident? */
580         int HadWS = WS;
581
582         /* Generate the symbol table entry, then skip the name */
583         if (Tok == TOK_IDENT) {
584             Sym = SymFind (CurrentScope, &SVal, SYM_ALLOC_NEW);
585         } else {
586             Sym = SymFindLocal (SymLast, &SVal, SYM_ALLOC_NEW);
587         }
588         NextTok ();
589
590         /* If a colon follows, this is a label definition. If there
591          * is no colon, it's an assignment.
592          */
593         if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
594
595             /* Determine the symbol flags from the assignment token */
596             unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
597
598             /* Skip the '=' */
599             NextTok ();
600
601             /* Define the symbol with the expression following the '=' */
602             SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
603
604             /* Don't allow anything after a symbol definition */
605             ConsumeSep ();
606             return;
607
608         } else if (Tok == TOK_SET) {
609
610             ExprNode* Expr;
611
612             /* .SET defines variables (= redefinable symbols) */
613             NextTok ();
614
615             /* Read the assignment expression, which must be constant */
616             Expr = GenLiteralExpr (ConstExpression ());
617
618             /* Define the symbol with the constant expression following
619              * the '='
620              */
621             SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
622
623             /* Don't allow anything after a symbol definition */
624             ConsumeSep ();
625             return;
626
627         } else {
628
629             /* A label. Remember the current segment, so we can later
630              * determine the size of the data stored under the label.
631              */
632             Seg = ActiveSeg;
633             PC  = GetPC ();
634
635             /* Define the label */
636             SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
637
638             /* Skip the colon. If NoColonLabels is enabled, allow labels
639              * without a colon if there is no whitespace before the
640              * identifier.
641              */
642             if (Tok != TOK_COLON) {
643                 if (HadWS || !NoColonLabels) {
644                     Error ("`:' expected");
645                     /* Try some smart error recovery */
646                     if (Tok == TOK_NAMESPACE) {
647                         NextTok ();
648                     }
649                 }
650             } else {
651                 /* Skip the colon */
652                 NextTok ();
653             }
654
655             /* If we come here, a new identifier may be waiting, which may
656              * be a macro or instruction.
657              */
658             if (Tok == TOK_IDENT) {
659                 if (!UbiquitousIdents) {
660                     /* Macros and symbols cannot use instruction names */
661                     Instr = FindInstruction (&SVal);
662                     if (Instr < 0) {
663                         Macro = IsMacro (&SVal);
664                     }
665                 } else {
666                     /* Macros and symbols may use the names of instructions */
667                     Macro = IsMacro (&SVal);
668                 }
669             }
670         }
671     }
672
673     /* We've handled a possible label, now handle the remainder of the line */
674     if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
675         /* A control command */
676         HandlePseudo ();
677     } else if (Macro) {
678         /* A macro expansion */
679         MacExpandStart ();
680     } else if (Instr >= 0 ||
681                (UbiquitousIdents && ((Instr = FindInstruction (&SVal)) >= 0))) {
682         /* A mnemonic - assemble one instruction */
683         HandleInstruction (Instr);
684     } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
685         NextTok ();
686         if (Tok != TOK_EQ) {
687             Error ("`=' expected");
688             SkipUntilSep ();
689         } else {
690             /* Skip the equal sign */
691             NextTok ();
692             /* Enter absolute mode */
693             DoPCAssign ();
694         }
695     }
696
697     /* If we have defined a label, remember its size. Sym is also set by
698      * a symbol assignment, but in this case Done is false, so we don't
699      * come here.
700      */
701     if (Sym) {
702         unsigned long Size;
703         if (Seg == ActiveSeg) {
704             /* Same segment */
705             Size = GetPC () - PC;
706         } else {
707             /* The line has switched the segment */
708             Size = 0;
709         }
710         DefSizeOfSymbol (Sym, Size);
711     }
712
713     /* Line separator must come here */
714     ConsumeSep ();
715 }
716
717
718
719 static void Assemble (void)
720 /* Start the ball rolling ... */
721 {
722     /* Prime the pump */
723     NextTok ();
724
725     /* Assemble lines until end of file */
726     while (Tok != TOK_EOF) {
727         OneLine ();
728     }
729 }
730
731
732
733 static void CreateObjFile (void)
734 /* Create the object file */
735 {
736     /* Open the object, write the header */
737     ObjOpen ();
738
739     /* Write the object file options */
740     WriteOptions ();
741
742     /* Write the list of input files */
743     WriteFiles ();
744
745     /* Write the segment data to the file */
746     WriteSegments ();
747
748     /* Write the import list */
749     WriteImports ();
750
751     /* Write the export list */
752     WriteExports ();
753
754     /* Write debug symbols if requested */
755     WriteDbgSyms ();
756
757     /* Write line infos if requested */
758     WriteLineInfo ();
759
760     /* Write the string pool */
761     WriteStrPool ();
762
763     /* Write the assertions */
764     WriteAssertions ();
765
766     /* Write an updated header and close the file */
767     ObjClose ();
768 }
769
770
771
772 int main (int argc, char* argv [])
773 /* Assembler main program */
774 {
775     /* Program long options */
776     static const LongOpt OptTab[] = {
777         { "--auto-import",      0,      OptAutoImport           },
778         { "--cpu",              1,      OptCPU                  },
779         { "--debug-info",       0,      OptDebugInfo            },
780         { "--feature",          1,      OptFeature              },
781         { "--help",             0,      OptHelp                 },
782         { "--ignore-case",      0,      OptIgnoreCase           },
783         { "--include-dir",      1,      OptIncludeDir           },
784         { "--list-bytes",       1,      OptListBytes            },
785         { "--listing",          0,      OptListing              },
786         { "--macpack-dir",      1,      OptMacPackDir           },
787         { "--memory-model",     1,      OptMemoryModel          },
788         { "--pagelength",       1,      OptPageLength           },
789         { "--smart",            0,      OptSmart                },
790         { "--target",           1,      OptTarget               },
791         { "--verbose",          0,      OptVerbose              },
792         { "--version",          0,      OptVersion              },
793     };
794
795     /* Name of the global name space */
796     static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
797
798     unsigned I;
799
800     /* Initialize the cmdline module */
801     InitCmdLine (&argc, &argv, "ca65");
802
803     /* Enter the base lexical level. We must do that here, since we may
804      * define symbols using -D.
805      */
806     SymEnterLevel (&GlobalNameSpace, ST_GLOBAL, ADDR_SIZE_DEFAULT);
807
808     /* Check the parameters */
809     I = 1;
810     while (I < ArgCount) {
811
812         /* Get the argument */
813         const char* Arg = ArgVec [I];
814
815         /* Check for an option */
816         if (Arg[0] == '-') {
817             switch (Arg[1]) {
818
819                 case '-':
820                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
821                     break;
822
823                 case 'g':
824                     OptDebugInfo (Arg, 0);
825                     break;
826
827                 case 'h':
828                     OptHelp (Arg, 0);
829                     break;
830
831                 case 'i':
832                     OptIgnoreCase (Arg, 0);
833                     break;
834
835                 case 'l':
836                     OptListing (Arg, 0);
837                     break;
838
839                 case 'm':
840                     if (Arg[2] == 'm') {
841                         OptMemoryModel (Arg, GetArg (&I, 3));
842                     } else {
843                         UnknownOption (Arg);
844                     }
845                     break;
846
847                 case 'o':
848                     OutFile = GetArg (&I, 2);
849                     break;
850
851                 case 's':
852                     OptSmart (Arg, 0);
853                     break;
854
855                 case 't':
856                     OptTarget (Arg, GetArg (&I, 2));
857                     break;
858
859                 case 'v':
860                     OptVerbose (Arg, 0);
861                     break;
862
863                 case 'D':
864                     DefineSymbol (GetArg (&I, 2));
865                     break;
866
867                 case 'I':
868                     OptIncludeDir (Arg, GetArg (&I, 2));
869                     break;
870
871                 case 'U':
872                     OptAutoImport (Arg, 0);
873                     break;
874
875                 case 'V':
876                     OptVersion (Arg, 0);
877                     break;
878
879                 case 'W':
880                     WarnLevel = atoi (GetArg (&I, 2));
881                     break;
882
883                 default:
884                     UnknownOption (Arg);
885                     break;
886
887             }
888         } else {
889             /* Filename. Check if we already had one */
890             if (InFile) {
891                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
892                          ProgName, Arg);
893                 exit (EXIT_FAILURE);
894             } else {
895                 InFile = Arg;
896             }
897         }
898
899         /* Next argument */
900         ++I;
901     }
902
903     /* Do we have an input file? */
904     if (InFile == 0) {
905         fprintf (stderr, "%s: No input files\n", ProgName);
906         exit (EXIT_FAILURE);
907     }
908
909     /* If no CPU given, use the default CPU for the target */
910     if (GetCPU () == CPU_UNKNOWN) {
911         if (Target != TGT_UNKNOWN) {
912             SetCPU (DefaultCPU[Target]);
913         } else {
914             SetCPU (CPU_6502);
915         }
916     }
917
918     /* If no memory model was given, use the default */
919     if (MemoryModel == MMODEL_UNKNOWN) {
920         SetMemoryModel (MMODEL_NEAR);
921     }
922
923     /* Initialize the segments */
924     InitSegments ();
925
926     /* Initialize the scanner, open the input file */
927     InitScanner (InFile);
928
929     /* Define the default options */
930     SetOptions ();
931
932     /* Assemble the input */
933     Assemble ();
934
935     /* If we didn't have any errors, check the segment stack */
936     if (ErrorCount == 0) {
937         SegStackCheck ();
938     }
939
940     /* If we didn't have any errors, check the unnamed labels */
941     if (ErrorCount == 0) {
942         ULabCheck ();
943     }
944
945     /* If we didn't have any errors, check the symbol table */
946     if (ErrorCount == 0) {
947         SymCheck ();
948     }
949
950     /* If we didn't have any errors, check and resolve the segment data */
951     if (ErrorCount == 0) {
952         SegCheck ();
953     }
954
955     /* If we didn't have any errors, check the assertions */
956     if (ErrorCount == 0) {
957         CheckAssertions ();
958     }
959
960     /* If we didn't have an errors, index the line infos */
961     MakeLineInfoIndex ();
962
963     /* Dump the data */
964     if (Verbosity >= 2) {
965         SymDump (stdout);
966         SegDump ();
967     }
968
969     /* If we didn't have any errors, create the object and listing files */
970     if (ErrorCount == 0) {
971         CreateObjFile ();
972         if (Listing) {
973             CreateListing ();
974         }
975     }
976
977     /* Close the input file */
978     DoneScanner ();
979
980     /* Return an apropriate exit code */
981     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
982 }
983
984
985