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