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