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