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