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