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