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