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