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