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