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