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