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