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