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