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