]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Fixed a problem with the ubiquitous_idents change
[cc65] / src / ca65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                 Main program for the ca65 macroassembler                  */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2003 Ullrich von Bassewitz                                       */
10 /*               Römerstraße 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 "target.h"
48 #include "tgttrans.h"
49 #include "version.h"
50
51 /* ca65 */
52 #include "abend.h"
53 #include "asserts.h"
54 #include "error.h"
55 #include "expr.h"
56 #include "feature.h"
57 #include "filetab.h"
58 #include "global.h"
59 #include "incpath.h"
60 #include "instr.h"
61 #include "istack.h"
62 #include "lineinfo.h"
63 #include "listing.h"
64 #include "macro.h"
65 #include "nexttok.h"
66 #include "objfile.h"
67 #include "options.h"
68 #include "pseudo.h"
69 #include "scanner.h"
70 #include "segment.h"
71 #include "sizeof.h"
72 #include "spool.h"
73 #include "symtab.h"
74 #include "ulabel.h"
75
76
77
78 /*****************************************************************************/
79 /*                                   Code                                    */
80 /*****************************************************************************/
81
82
83
84 static void Usage (void)
85 /* Print usage information and exit */
86 {
87     fprintf (stderr,
88              "Usage: %s [options] file\n"
89              "Short options:\n"
90              "  -D name[=value]\tDefine a symbol\n"
91              "  -I dir\t\tSet an include directory search path\n"
92              "  -U\t\t\tMark unresolved symbols as import\n"
93              "  -V\t\t\tPrint the assembler version\n"
94              "  -W n\t\t\tSet warning level n\n"
95              "  -g\t\t\tAdd debug info to object file\n"
96              "  -h\t\t\tHelp (this text)\n"
97              "  -i\t\t\tIgnore case of symbols\n"
98              "  -l\t\t\tCreate a listing if assembly was ok\n"
99              "  -mm model\t\tSet the memory model\n"
100              "  -o name\t\tName the output file\n"
101              "  -s\t\t\tEnable smart mode\n"
102              "  -t sys\t\tSet the target system\n"
103              "  -v\t\t\tIncrease verbosity\n"
104              "\n"
105              "Long options:\n"
106              "  --auto-import\t\tMark unresolved symbols as import\n"
107              "  --cpu type\t\tSet cpu type\n"
108              "  --debug-info\t\tAdd debug info to object file\n"
109              "  --feature name\tSet an emulation feature\n"
110              "  --help\t\tHelp (this text)\n"
111              "  --ignore-case\t\tIgnore case of symbols\n"
112              "  --include-dir dir\tSet an include directory search path\n"
113              "  --listing\t\tCreate a listing if assembly was ok\n"
114              "  --memory-model model\tSet the memory model\n"
115              "  --pagelength n\tSet the page length for the listing\n"
116              "  --smart\t\tEnable smart mode\n"
117              "  --target sys\t\tSet the target system\n"
118              "  --verbose\t\tIncrease verbosity\n"
119              "  --version\t\tPrint the assembler version\n",
120              ProgName);
121 }
122
123
124
125 static void SetOptions (void)
126 /* Set the option for the translator */
127 {
128     char Buf [256];
129
130     /* Set the translator */
131     sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
132     OptTranslator (Buf);
133
134     /* Set date and time */
135     OptDateTime ((unsigned long) time(0));
136 }
137
138
139
140 static void DefineSymbol (const char* Def)
141 /* Define a symbol from the command line */
142 {
143     const char* P;
144     unsigned I;
145     long Val;
146     char SymName [MAX_STR_LEN+1];
147     SymEntry* Sym;
148     ExprNode* Expr;
149
150
151     /* The symbol must start with a character or underline */
152     if (Def [0] != '_' && !IsAlpha (Def [0])) {
153         InvDef (Def);
154     }
155     P = Def;
156
157     /* Copy the symbol, checking the rest */
158     I = 0;
159     while (IsAlNum (*P) || *P == '_') {
160         if (I <= MAX_STR_LEN) {
161             SymName [I++] = *P;
162         }
163         ++P;
164     }
165     SymName [I] = '\0';
166
167     /* Do we have a value given? */
168     if (*P != '=') {
169         if (*P != '\0') {
170             InvDef (Def);
171         }
172         Val = 0;
173     } else {
174         /* We have a value */
175         ++P;
176         if (*P == '$') {
177             ++P;
178             if (sscanf (P, "%lx", &Val) != 1) {
179                 InvDef (Def);
180             }
181         } else {
182             if (sscanf (P, "%li", &Val) != 1) {
183                 InvDef (Def);
184             }
185         }
186     }
187
188     /* Search for the symbol, allocate a new one if it doesn't exist */
189     Sym = SymFind (CurrentScope, SymName, SYM_ALLOC_NEW);
190
191     /* Check if have already a symbol with this name */
192     if (SymIsDef (Sym)) {
193         AbEnd ("`%s' is already defined", SymName);
194     }
195
196     /* Generate an expression for the symbol */
197     Expr = GenLiteralExpr (Val);
198
199     /* Mark the symbol as defined */
200     SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
201 }
202
203
204
205 static void OptAutoImport (const char* Opt attribute ((unused)),
206                            const char* Arg attribute ((unused)))
207 /* Mark unresolved symbols as imported */
208 {
209     AutoImport = 1;
210 }
211
212
213
214 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
215 /* Handle the --cpu option */
216 {
217     cpu_t CPU = FindCPU (Arg);
218     if (CPU == CPU_UNKNOWN) {
219         AbEnd ("Invalid CPU: `%s'", Arg);
220     } else {
221         SetCPU (CPU);
222     }
223 }
224
225
226
227 static void OptDebugInfo (const char* Opt attribute ((unused)),
228                           const char* Arg attribute ((unused)))
229 /* Add debug info to the object file */
230 {
231     DbgSyms = 1;
232 }
233
234
235
236 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
237 /* Set an emulation feature */
238 {
239     /* Set the feature, check for errors */
240     if (SetFeature (Arg) == FEAT_UNKNOWN) {
241         AbEnd ("Illegal emulation feature: `%s'", Arg);
242     }
243 }
244
245
246
247 static void OptHelp (const char* Opt attribute ((unused)),
248                      const char* Arg attribute ((unused)))
249 /* Print usage information and exit */
250 {
251     Usage ();
252     exit (EXIT_SUCCESS);
253 }
254
255
256
257 static void OptIgnoreCase (const char* Opt attribute ((unused)),
258                            const char* Arg attribute ((unused)))
259 /* Ignore case on symbols */
260 {
261     IgnoreCase = 1;
262 }
263
264
265
266 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
267 /* Add an include search path */
268 {
269     AddIncludePath (Arg);
270 }
271
272
273
274 static void OptListing (const char* Opt attribute ((unused)),
275                         const char* Arg attribute ((unused)))
276 /* Create a listing file */
277 {
278     Listing = 1;
279 }
280
281
282
283 static void OptMemoryModel (const char* Opt, const char* Arg)
284 /* Set the memory model */
285 {
286     mmodel_t M;
287
288     /* Check the current memory model */
289     if (MemoryModel != MMODEL_UNKNOWN) {
290         AbEnd ("Cannot use option `%s' twice", Opt);
291     }
292
293     /* Translate the memory model name and check it */
294     M = FindMemoryModel (Arg);
295     if (M == MMODEL_UNKNOWN) {
296         AbEnd ("Unknown memory model: %s", Arg);
297     } else if (M == MMODEL_HUGE) {
298         AbEnd ("Unsupported memory model: %s", Arg);
299     }
300
301     /* Set the memory model */
302     SetMemoryModel (M);
303 }
304
305
306
307 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
308 /* Handle the --pagelength option */
309 {
310     int Len = atoi (Arg);
311     if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
312         AbEnd ("Invalid page length: %d", Len);
313     }
314     PageLength = Len;
315 }
316
317
318
319 static void OptSmart (const char* Opt attribute ((unused)),
320                       const char* Arg attribute ((unused)))
321 /* Handle the -s/--smart options */
322 {
323     SmartMode = 1;
324 }
325
326
327
328 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
329 /* Set the target system */
330 {
331     /* Map the target name to a target id */
332     Target = FindTarget (Arg);
333     if (Target == TGT_UNKNOWN) {
334         AbEnd ("Invalid target name: `%s'", Arg);
335     } else if (Target == TGT_MODULE) {
336         AbEnd ("Cannot use `module' as a target for the assembler");
337     }
338 }
339
340
341
342 static void OptVerbose (const char* Opt attribute ((unused)),
343                         const char* Arg attribute ((unused)))
344 /* Increase verbosity */
345 {
346     ++Verbosity;
347 }
348
349
350
351 static void OptVersion (const char* Opt attribute ((unused)),
352                         const char* Arg attribute ((unused)))
353 /* Print the assembler version */
354 {
355     fprintf (stderr,
356              "ca65 V%u.%u.%u - %s\n",
357              VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
358 }
359
360
361
362 static void DoPCAssign (void)
363 /* Start absolute code */
364 {
365     long PC = ConstExpression ();
366     if (PC < 0 || PC > 0xFFFFFF) {
367         Error ("Range error");
368     } else {
369         SetAbsPC (PC);
370     }
371 }
372
373
374
375 static void OneLine (void)
376 /* Assemble one line */
377 {
378     Segment*      Seg   = 0;
379     unsigned long PC    = 0;
380     SymEntry*     Sym   = 0;
381     int           Macro = 0;
382     int           Instr = -1;
383
384     /* Initialize the new listing line if we are actually reading from file
385      * and not from internally pushed input.
386      */
387     if (!HavePushedInput ()) {
388         InitListingLine ();
389     }
390
391     if (Tok == TOK_COLON) {
392         /* An unnamed label */
393         ULabDef ();
394         NextTok ();
395     }
396
397     /* If the first token on the line is an identifier, check for a macro or
398      * an instruction.
399      */
400     if (Tok == TOK_IDENT) {
401         if (!UbiquitousIdents) {
402             /* Macros and symbols cannot use instruction names */
403             Instr = FindInstruction (SVal);
404             if (Instr < 0) {
405                 Macro = IsMacro (SVal);
406             }
407         } else {
408             /* Macros and symbols may use the names of instructions */
409             Macro = IsMacro (SVal);
410         }
411     }
412
413     /* Handle an identifier */
414     if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
415
416         /* Did we have whitespace before the ident? */
417         int HadWS = WS;
418
419         /* Generate the symbol table entry, then skip the name */
420         if (Tok == TOK_IDENT) {
421             Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
422         } else {
423             Sym = SymFindLocal (SymLast, SVal, SYM_ALLOC_NEW);
424         }
425         NextTok ();
426
427         /* If a colon follows, this is a label definition. If there
428          * is no colon, it's an assignment.
429          */
430         if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
431             /* If it's an assign token, we have a label */
432             unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
433             /* Skip the '=' */
434             NextTok ();
435             /* Define the symbol with the expression following the '=' */
436             SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
437             /* Don't allow anything after a symbol definition */
438             ConsumeSep ();
439             return;
440         } else {
441             /* A label. Remember the current segment, so we can later
442              * determine the size of the data stored under the label.
443              */
444             Seg = ActiveSeg;
445             PC  = GetPC ();
446
447             /* Define the label */
448             SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
449
450             /* Skip the colon. If NoColonLabels is enabled, allow labels
451              * without a colon if there is no whitespace before the
452              * identifier.
453              */
454             if (Tok != TOK_COLON) {
455                 if (HadWS || !NoColonLabels) {
456                     Error ("`:' expected");
457                     /* Try some smart error recovery */
458                     if (Tok == TOK_NAMESPACE) {
459                         NextTok ();
460                     }
461                 }
462             } else {
463                 /* Skip the colon */
464                 NextTok ();
465             }
466
467             /* If we come here, a new identifier may be waiting, which may
468              * be a macro or instruction.
469              */
470             if (Tok == TOK_IDENT) {
471                 if (!UbiquitousIdents) {
472                     /* Macros and symbols cannot use instruction names */
473                     Instr = FindInstruction (SVal);
474                     if (Instr < 0) {
475                         Macro = IsMacro (SVal);
476                     }
477                 } else {
478                     /* Macros and symbols may use the names of instructions */
479                     Macro = IsMacro (SVal);
480                 }
481             }
482         }
483     }
484
485     /* We've handled a possible label, now handle the remainder of the line */
486     if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
487         /* A control command */
488         HandlePseudo ();
489     } else if (Macro) {
490         /* A macro expansion */
491         MacExpandStart ();
492     } else if (Instr >= 0 ||
493                (UbiquitousIdents && ((Instr = FindInstruction (SVal)) >= 0))) {
494         /* A mnemonic - assemble one instruction */
495         HandleInstruction (Instr);
496     } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
497         NextTok ();
498         if (Tok != TOK_EQ) {
499             Error ("`=' expected");
500             SkipUntilSep ();
501         } else {
502             /* Skip the equal sign */
503             NextTok ();
504             /* Enter absolute mode */
505             DoPCAssign ();
506         }
507     }
508
509     /* If we have defined a label, remember its size. Sym is also set by
510      * a symbol assignment, but in this case Done is false, so we don't
511      * come here.
512      */
513     if (Sym) {
514         unsigned long Size;
515         if (Seg == ActiveSeg) {
516             /* Same segment */
517             Size = GetPC () - PC;
518         } else {
519             /* The line has switched the segment */
520             Size = 0;
521         }
522         DefSizeOfSymbol (Sym, Size);
523     }
524
525     /* Line separator must come here */
526     ConsumeSep ();
527 }
528
529
530
531 static void Assemble (void)
532 /* Start the ball rolling ... */
533 {
534     /* Prime the pump */
535     NextTok ();
536
537     /* Assemble lines until end of file */
538     while (Tok != TOK_EOF) {
539         OneLine ();
540     }
541 }
542
543
544
545 static void CreateObjFile (void)
546 /* Create the object file */
547 {
548     /* Open the object, write the header */
549     ObjOpen ();
550
551     /* Write the object file options */
552     WriteOptions ();
553
554     /* Write the list of input files */
555     WriteFiles ();
556
557     /* Write the segment data to the file */
558     WriteSegments ();
559
560     /* Write the import list */
561     WriteImports ();
562
563     /* Write the export list */
564     WriteExports ();
565
566     /* Write debug symbols if requested */
567     WriteDbgSyms ();
568
569     /* Write line infos if requested */
570     WriteLineInfo ();
571
572     /* Write the string pool */
573     WriteStrPool ();
574
575     /* Write the assertions */
576     WriteAssertions ();
577
578     /* Write an updated header and close the file */
579     ObjClose ();
580 }
581
582
583
584 int main (int argc, char* argv [])
585 /* Assembler main program */
586 {
587     /* Program long options */
588     static const LongOpt OptTab[] = {
589         { "--auto-import",      0,      OptAutoImport           },
590         { "--cpu",              1,      OptCPU                  },
591         { "--debug-info",       0,      OptDebugInfo            },
592         { "--feature",          1,      OptFeature              },
593         { "--help",             0,      OptHelp                 },
594         { "--ignore-case",      0,      OptIgnoreCase           },
595         { "--include-dir",      1,      OptIncludeDir           },
596         { "--listing",          0,      OptListing              },
597         { "--memory-model",     1,      OptMemoryModel          },
598         { "--pagelength",       1,      OptPageLength           },
599         { "--smart",            0,      OptSmart                },
600         { "--target",           1,      OptTarget               },
601         { "--verbose",          0,      OptVerbose              },
602         { "--version",          0,      OptVersion              },
603     };
604
605     unsigned I;
606
607     /* Initialize the cmdline module */
608     InitCmdLine (&argc, &argv, "ca65");
609
610     /* Enter the base lexical level. We must do that here, since we may
611      * define symbols using -D.
612      */
613     SymEnterLevel ("", ST_GLOBAL, ADDR_SIZE_DEFAULT);
614
615     /* Check the parameters */
616     I = 1;
617     while (I < ArgCount) {
618
619         /* Get the argument */
620         const char* Arg = ArgVec [I];
621
622         /* Check for an option */
623         if (Arg[0] == '-') {
624             switch (Arg[1]) {
625
626                 case '-':
627                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
628                     break;
629
630                 case 'g':
631                     OptDebugInfo (Arg, 0);
632                     break;
633
634                 case 'h':
635                     OptHelp (Arg, 0);
636                     break;
637
638                 case 'i':
639                     OptIgnoreCase (Arg, 0);
640                     break;
641
642                 case 'l':
643                     OptListing (Arg, 0);
644                     break;
645
646                 case 'm':
647                     if (Arg[2] == 'm') {
648                         OptMemoryModel (Arg, GetArg (&I, 3));
649                     } else {
650                         UnknownOption (Arg);
651                     }
652                     break;
653
654                 case 'o':
655                     OutFile = GetArg (&I, 2);
656                     break;
657
658                 case 's':
659                     OptSmart (Arg, 0);
660                     break;
661
662                 case 't':
663                     OptTarget (Arg, GetArg (&I, 2));
664                     break;
665
666                 case 'v':
667                     OptVerbose (Arg, 0);
668                     break;
669
670                 case 'D':
671                     DefineSymbol (GetArg (&I, 2));
672                     break;
673
674                 case 'I':
675                     OptIncludeDir (Arg, GetArg (&I, 2));
676                     break;
677
678                 case 'U':
679                     OptAutoImport (Arg, 0);
680                     break;
681
682                 case 'V':
683                     OptVersion (Arg, 0);
684                     break;
685
686                 case 'W':
687                     WarnLevel = atoi (GetArg (&I, 2));
688                     break;
689
690                 default:
691                     UnknownOption (Arg);
692                     break;
693
694             }
695         } else {
696             /* Filename. Check if we already had one */
697             if (InFile) {
698                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
699                          ProgName, Arg);
700                 exit (EXIT_FAILURE);
701             } else {
702                 InFile = Arg;
703             }
704         }
705
706         /* Next argument */
707         ++I;
708     }
709
710     /* Do we have an input file? */
711     if (InFile == 0) {
712         fprintf (stderr, "%s: No input files\n", ProgName);
713         exit (EXIT_FAILURE);
714     }
715
716     /* If no CPU given, use the default CPU for the target */
717     if (GetCPU () == CPU_UNKNOWN) {
718         if (Target != TGT_UNKNOWN) {
719             SetCPU (DefaultCPU[Target]);
720         } else {
721             SetCPU (CPU_6502);
722         }
723     }
724
725     /* If no memory model was given, use the default */
726     if (MemoryModel == MMODEL_UNKNOWN) {
727         SetMemoryModel (MMODEL_NEAR);
728     }
729
730     /* Intialize the target translation tables */
731     TgtTranslateInit ();
732
733     /* Initialize the segments */
734     InitSegments ();
735
736     /* Initialize the scanner, open the input file */
737     InitScanner (InFile);
738
739     /* Define the default options */
740     SetOptions ();
741
742     /* Assemble the input */
743     Assemble ();
744
745     /* If we didn't have any errors, check the segment stack */
746     if (ErrorCount == 0) {
747         SegStackCheck ();
748     }
749
750     /* If we didn't have any errors, check the unnamed labels */
751     if (ErrorCount == 0) {
752         ULabCheck ();
753     }
754
755     /* If we didn't have any errors, check the symbol table */
756     if (ErrorCount == 0) {
757         SymCheck ();
758     }
759
760     /* If we didn't have any errors, check and resolve the segment data */
761     if (ErrorCount == 0) {
762         SegCheck ();
763     }
764
765     /* If we didn't have an errors, index the line infos */
766     MakeLineInfoIndex ();
767
768     /* Dump the data */
769     if (Verbosity >= 2) {
770         SymDump (stdout);
771         SegDump ();
772     }
773
774     /* If we didn't have any errors, create the object and listing files */
775     if (ErrorCount == 0) {
776         CreateObjFile ();
777         if (Listing) {
778             CreateListing ();
779         }
780     }
781
782     /* Close the input file */
783     DoneScanner ();
784
785     /* Return an apropriate exit code */
786     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
787 }
788
789
790