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