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