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