]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Merge remote-tracking branch 'upstream/master'
[cc65] / src / ca65 / main.c
1 /*                                                                           */
2 /*                                  main.c                                   */
3 /*                                                                           */
4 /*                 Main program for the ca65 macroassembler                  */
5 /*                                                                           */
6 /*                                                                           */
7 /*                                                                           */
8 /* (C) 1998-2013, 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             "  --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_ATARIXL:
212             NewSymbol ("__ATARI__", 1);
213             NewSymbol ("__ATARIXL__", 1);
214             break;
215
216         case TGT_C16:
217             CBMSystem ("__C16__");
218             break;
219
220         case TGT_C64:
221             CBMSystem ("__C64__");
222             break;
223
224         case TGT_VIC20:
225             CBMSystem ("__VIC20__");
226             break;
227
228         case TGT_C128:
229             CBMSystem ("__C128__");
230             break;
231
232         case TGT_PLUS4:
233             CBMSystem ("__PLUS4__");
234             break;
235
236         case TGT_CBM510:
237             CBMSystem ("__CBM510__");
238             break;
239
240         case TGT_CBM610:
241             CBMSystem ("__CBM610__");
242             break;
243
244         case TGT_PET:
245             CBMSystem ("__PET__");
246             break;
247
248         case TGT_BBC:
249             NewSymbol ("__BBC__", 1);
250             break;
251
252         case TGT_APPLE2:
253             NewSymbol ("__APPLE2__", 1);
254             break;
255
256         case TGT_APPLE2ENH:
257             NewSymbol ("__APPLE2__", 1);
258             NewSymbol ("__APPLE2ENH__", 1);
259             break;
260
261         case TGT_GEOS_CBM:
262             /* Do not handle as a CBM system */
263             NewSymbol ("__GEOS__", 1);
264             NewSymbol ("__GEOS_CBM__", 1);
265             break;
266
267         case TGT_GEOS_APPLE:
268             NewSymbol ("__GEOS__", 1);
269             NewSymbol ("__GEOS_APPLE__", 1);
270             break;
271
272         case TGT_LUNIX:
273             NewSymbol ("__LUNIX__", 1);
274             break;
275
276         case TGT_ATMOS:
277             NewSymbol ("__ATMOS__", 1);
278             break;
279
280         case TGT_NES:
281             NewSymbol ("__NES__", 1);
282             break;
283
284         case TGT_SUPERVISION:
285             NewSymbol ("__SUPERVISION__", 1);
286             break;
287
288         case TGT_LYNX:
289             NewSymbol ("__LYNX__", 1);
290             break;
291
292         case TGT_SIM6502:
293             NewSymbol ("__SIM6502__", 1);
294             break;
295
296         case TGT_SIM65C02:
297             NewSymbol ("__SIM65C02__", 1);
298             break;
299
300         default:
301             AbEnd ("Invalid target name: `%s'", Sys);
302
303     }
304
305     /* Initialize the translation tables for the target system */
306     TgtTranslateInit ();
307 }
308
309
310
311 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
312 /* Handle an option that remembers a file name for later */
313 {
314     /* Cannot have the option twice */
315     if (SB_NotEmpty (Name)) {
316         AbEnd ("Cannot use option `%s' twice", Opt);
317     }
318     /* Remember the file name for later */
319     SB_CopyStr (Name, Arg);
320     SB_Terminate (Name);
321 }
322
323
324
325 static void DefineSymbol (const char* Def)
326 /* Define a symbol from the command line */
327 {
328     const char* P;
329     long Val;
330     StrBuf SymName = AUTO_STRBUF_INITIALIZER;
331
332
333     /* The symbol must start with a character or underline */
334     if (!IsIdStart (Def [0])) {
335         InvDef (Def);
336     }
337     P = Def;
338
339     /* Copy the symbol, checking the rest */
340     while (IsIdChar (*P)) {
341         SB_AppendChar (&SymName, *P++);
342     }
343     SB_Terminate (&SymName);
344
345     /* Do we have a value given? */
346     if (*P != '=') {
347         if (*P != '\0') {
348             InvDef (Def);
349         }
350         Val = 0;
351     } else {
352         /* We have a value */
353         ++P;
354         if (*P == '$') {
355             ++P;
356             if (sscanf (P, "%lx", &Val) != 1) {
357                 InvDef (Def);
358             }
359         } else {
360             if (sscanf (P, "%li", &Val) != 1) {
361                 InvDef (Def);
362             }
363         }
364     }
365
366     /* Define the new symbol */
367     NewSymbol (SB_GetConstBuf (&SymName), Val);
368
369     /* Release string memory */
370     SB_Done (&SymName);
371 }
372
373
374
375 static void OptAutoImport (const char* Opt attribute ((unused)),
376                            const char* Arg attribute ((unused)))
377 /* Mark unresolved symbols as imported */
378 {
379     AutoImport = 1;
380 }
381
382
383
384 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
385 /* Add an include search path for binaries */
386 {
387     AddSearchPath (BinSearchPath, Arg);
388 }
389
390
391
392 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
393 /* Handle the --cpu option */
394 {
395     cpu_t CPU = FindCPU (Arg);
396     if (CPU == CPU_UNKNOWN) {
397         AbEnd ("Invalid CPU: `%s'", Arg);
398     } else {
399         SetCPU (CPU);
400     }
401 }
402
403
404
405 static void OptCreateDep (const char* Opt, const char* Arg)
406 /* Handle the --create-dep option */
407 {
408     FileNameOption (Opt, Arg, &DepName);
409 }
410
411
412
413 static void OptCreateFullDep (const char* Opt attribute ((unused)),
414                               const char* Arg)
415 /* Handle the --create-full-dep option */
416 {
417     FileNameOption (Opt, Arg, &FullDepName);
418 }
419
420
421
422 static void OptDebug (const char* Opt attribute ((unused)),
423                       const char* Arg attribute ((unused)))
424 /* Compiler debug mode */
425 {
426     ++Debug;
427 }
428
429
430
431 static void OptDebugInfo (const char* Opt attribute ((unused)),
432                           const char* Arg attribute ((unused)))
433 /* Add debug info to the object file */
434 {
435     DbgSyms = 1;
436 }
437
438
439
440 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
441 /* Set an emulation feature */
442 {
443     /* Make a string buffer from Arg */
444     StrBuf Feature;
445
446     /* Set the feature, check for errors */
447     if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
448         AbEnd ("Illegal emulation feature: `%s'", Arg);
449     }
450 }
451
452
453
454 static void OptHelp (const char* Opt attribute ((unused)),
455                      const char* Arg attribute ((unused)))
456 /* Print usage information and exit */
457 {
458     Usage ();
459     exit (EXIT_SUCCESS);
460 }
461
462
463
464 static void OptIgnoreCase (const char* Opt attribute ((unused)),
465                            const char* Arg attribute ((unused)))
466 /* Ignore case on symbols */
467 {
468     IgnoreCase = 1;
469 }
470
471
472
473 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
474 /* Add an include search path */
475 {
476     AddSearchPath (IncSearchPath, Arg);
477 }
478
479
480
481 static void OptLargeAlignment (const char* Opt attribute ((unused)),
482                                const char* Arg attribute ((unused)))
483 /* Don't warn about large alignments */
484 {
485     LargeAlignment = 1;
486 }
487
488
489
490 static void OptListBytes (const char* Opt, const char* Arg)
491 /* Set the maximum number of bytes per listing line */
492 {
493     unsigned Num;
494     char     Check;
495
496     /* Convert the argument to a number */
497     if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
498         InvArg (Opt, Arg);
499     }
500
501     /* Check the bounds */
502     if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
503         AbEnd ("Argument for option `%s' is out of range", Opt);
504     }
505
506     /* Use the value */
507     SetListBytes (Num);
508 }
509
510
511
512 static void OptListing (const char* Opt, const char* Arg)
513 /* Create a listing file */
514 {
515     /* Since the meaning of -l and --listing has changed, print an error if
516      * the filename is empty or begins with the option char.
517      */
518     if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
519         Fatal ("The meaning of `%s' has changed. It does now "
520                "expect a file name as argument.", Opt);
521     }
522
523     /* Get the file name */
524     FileNameOption (Opt, Arg, &ListingName);
525 }
526
527
528
529 static void 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\n", GetVersionAsString ());
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",            0,      OptDebug                },
873         { "--debug-info",       0,      OptDebugInfo            },
874         { "--feature",          1,      OptFeature              },
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     /* Add the default include search paths. */
1023     FinishIncludePaths ();
1024
1025     /* If no CPU given, use the default CPU for the target */
1026     if (GetCPU () == CPU_UNKNOWN) {
1027         if (Target != TGT_UNKNOWN) {
1028             SetCPU (GetTargetProperties (Target)->DefaultCPU);
1029         } else {
1030             SetCPU (CPU_6502);
1031         }
1032     }
1033
1034     /* If no memory model was given, use the default */
1035     if (MemoryModel == MMODEL_UNKNOWN) {
1036         SetMemoryModel (MMODEL_NEAR);
1037     }
1038
1039     /* Set the default segment sizes according to the memory model */
1040     SetSegmentSizes ();
1041
1042     /* Initialize the scanner, open the input file */
1043     InitScanner (InFile);
1044
1045     /* Define the default options */
1046     SetOptions ();
1047
1048     /* Assemble the input */
1049     Assemble ();
1050
1051     /* If we didn't have any errors, check the pseudo insn stacks */
1052     if (ErrorCount == 0) {
1053         CheckPseudo ();
1054     }
1055
1056     /* If we didn't have any errors, check and cleanup the unnamed labels */
1057     if (ErrorCount == 0) {
1058         ULabDone ();
1059     }
1060
1061     /* If we didn't have any errors, check the symbol table */
1062     if (ErrorCount == 0) {
1063         SymCheck ();
1064     }
1065
1066     /* If we didn't have any errors, check the hll debug symbols */
1067     if (ErrorCount == 0) {
1068         DbgInfoCheck ();
1069     }
1070
1071     /* If we didn't have any errors, close the file scope lexical level */
1072     if (ErrorCount == 0) {
1073         SymLeaveLevel ();
1074     }
1075
1076     /* If we didn't have any errors, check and resolve the segment data */
1077     if (ErrorCount == 0) {
1078         SegDone ();
1079     }
1080
1081     /* If we didn't have any errors, check the assertions */
1082     if (ErrorCount == 0) {
1083         CheckAssertions ();
1084     }
1085
1086     /* Dump the data */
1087     if (Verbosity >= 2) {
1088         SymDump (stdout);
1089         SegDump ();
1090     }
1091
1092     /* If we didn't have an errors, finish off the line infos */
1093     DoneLineInfo ();
1094
1095     /* If we didn't have any errors, create the object, listing and
1096      * dependency files
1097      */
1098     if (ErrorCount == 0) {
1099         CreateObjFile ();
1100         if (SB_GetLen (&ListingName) > 0) {
1101             CreateListing ();
1102         }
1103        CreateDependencies ();
1104     }
1105
1106     /* Close the input file */
1107     DoneScanner ();
1108
1109     /* Return an apropriate exit code */
1110     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
1111 }
1112
1113
1114