]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Don't use SF_TRAMPOLINE, change symbol references instead.
[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_LOCAL_IDENT || (Tok == TOK_IDENT && !IsMacro (SVal))) {
394
395         /* Did we have whitespace before the ident? */
396         int HadWS = WS;
397
398         /* Generate the symbol table entry, then skip the name */
399         SymEntry* Sym;
400         if (Tok == TOK_IDENT) {
401             Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
402         } else {
403             Sym = SymFindLocal (SVal, SYM_ALLOC_NEW);
404         }
405         NextTok ();
406
407         /* If a colon follows, this is a label definition. If there
408          * is no colon, it's an assignment.
409          */
410         if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
411             /* If it's an assign token, we have a label */
412             unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
413             /* Skip the '=' */
414             NextTok ();
415             /* Define the symbol with the expression following the '=' */
416             SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
417             /* Don't allow anything after a symbol definition */
418             Done = 1;
419         } else {
420             /* Define a label */
421             SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
422             /* Skip the colon. If NoColonLabels is enabled, allow labels
423              * without a colon if there is no whitespace before the
424              * identifier.
425              */
426             if (Tok != TOK_COLON) {
427                 if (HadWS || !NoColonLabels) {
428                     Error ("`:' expected");
429                     /* Try some smart error recovery */
430                     if (Tok == TOK_NAMESPACE) {
431                         NextTok ();
432                     }
433                 }
434             } else {
435                 /* Skip the colon */
436                 NextTok ();
437             }
438         }
439     }
440
441     if (!Done) {
442
443         if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
444             /* A control command */
445             HandlePseudo ();
446         } else if (Tok == TOK_MNEMO) {
447             /* A mnemonic - assemble one instruction */
448             HandleInstruction (IVal);
449         } else if (Tok == TOK_IDENT && IsMacro (SVal)) {
450             /* A macro expansion */
451             MacExpandStart ();
452         } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
453             NextTok ();
454             if (Tok != TOK_EQ) {
455                 Error ("`=' expected");
456                 SkipUntilSep ();
457             } else {
458                 /* Skip the equal sign */
459                 NextTok ();
460                 /* Enter absolute mode */
461                 DoPCAssign ();
462             }
463         }
464     }
465
466     /* Line separator must come here */
467     ConsumeSep ();
468 }
469
470
471
472 static void Assemble (void)
473 /* Start the ball rolling ... */
474 {
475     /* Prime the pump */
476     NextTok ();
477
478     /* Assemble lines until end of file */
479     while (Tok != TOK_EOF) {
480         OneLine ();
481     }
482 }
483
484
485
486 static void CreateObjFile (void)
487 /* Create the object file */
488 {
489     /* Open the object, write the header */
490     ObjOpen ();
491
492     /* Write the object file options */
493     WriteOptions ();
494
495     /* Write the list of input files */
496     WriteFiles ();
497
498     /* Write the segment data to the file */
499     WriteSegments ();
500
501     /* Write the import list */
502     WriteImports ();
503
504     /* Write the export list */
505     WriteExports ();
506
507     /* Write debug symbols if requested */
508     WriteDbgSyms ();
509
510     /* Write line infos if requested */
511     WriteLineInfo ();
512
513     /* Write the string pool */
514     WriteStrPool ();
515
516     /* Write the assertions */
517     WriteAssertions ();
518
519     /* Write an updated header and close the file */
520     ObjClose ();
521 }
522
523
524
525 int main (int argc, char* argv [])
526 /* Assembler main program */
527 {
528     /* Program long options */
529     static const LongOpt OptTab[] = {
530         { "--auto-import",      0,      OptAutoImport           },
531         { "--cpu",              1,      OptCPU                  },
532         { "--debug-info",       0,      OptDebugInfo            },
533         { "--feature",          1,      OptFeature              },
534         { "--help",             0,      OptHelp                 },
535         { "--ignore-case",      0,      OptIgnoreCase           },
536         { "--include-dir",      1,      OptIncludeDir           },
537         { "--listing",          0,      OptListing              },
538         { "--memory-model",     1,      OptMemoryModel          },
539         { "--pagelength",       1,      OptPageLength           },
540         { "--smart",            0,      OptSmart                },
541         { "--target",           1,      OptTarget               },
542         { "--verbose",          0,      OptVerbose              },
543         { "--version",          0,      OptVersion              },
544     };
545
546     unsigned I;
547
548     /* Initialize the cmdline module */
549     InitCmdLine (&argc, &argv, "ca65");
550
551     /* Enter the base lexical level. We must do that here, since we may
552      * define symbols using -D.
553      */
554     SymEnterLevel ("", ST_GLOBAL, ADDR_SIZE_DEFAULT);
555
556     /* Check the parameters */
557     I = 1;
558     while (I < ArgCount) {
559
560         /* Get the argument */
561         const char* Arg = ArgVec [I];
562
563         /* Check for an option */
564         if (Arg[0] == '-') {
565             switch (Arg[1]) {
566
567                 case '-':
568                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
569                     break;
570
571                 case 'g':
572                     OptDebugInfo (Arg, 0);
573                     break;
574
575                 case 'h':
576                     OptHelp (Arg, 0);
577                     break;
578
579                 case 'i':
580                     OptIgnoreCase (Arg, 0);
581                     break;
582
583                 case 'l':
584                     OptListing (Arg, 0);
585                     break;
586
587                 case 'm':
588                     if (Arg[2] == 'm') {
589                         OptMemoryModel (Arg, GetArg (&I, 3));
590                     } else {
591                         UnknownOption (Arg);
592                     }
593                     break;
594
595                 case 'o':
596                     OutFile = GetArg (&I, 2);
597                     break;
598
599                 case 's':
600                     OptSmart (Arg, 0);
601                     break;
602
603                 case 't':
604                     OptTarget (Arg, GetArg (&I, 2));
605                     break;
606
607                 case 'v':
608                     OptVerbose (Arg, 0);
609                     break;
610
611                 case 'D':
612                     DefineSymbol (GetArg (&I, 2));
613                     break;
614
615                 case 'I':
616                     OptIncludeDir (Arg, GetArg (&I, 2));
617                     break;
618
619                 case 'U':
620                     OptAutoImport (Arg, 0);
621                     break;
622
623                 case 'V':
624                     OptVersion (Arg, 0);
625                     break;
626
627                 case 'W':
628                     WarnLevel = atoi (GetArg (&I, 2));
629                     break;
630
631                 default:
632                     UnknownOption (Arg);
633                     break;
634
635             }
636         } else {
637             /* Filename. Check if we already had one */
638             if (InFile) {
639                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
640                          ProgName, Arg);
641                 exit (EXIT_FAILURE);
642             } else {
643                 InFile = Arg;
644             }
645         }
646
647         /* Next argument */
648         ++I;
649     }
650
651     /* Do we have an input file? */
652     if (InFile == 0) {
653         fprintf (stderr, "%s: No input files\n", ProgName);
654         exit (EXIT_FAILURE);
655     }
656
657     /* If no CPU given, use the default CPU for the target */
658     if (GetCPU () == CPU_UNKNOWN) {
659         if (Target != TGT_UNKNOWN) {
660             SetCPU (DefaultCPU[Target]);
661         } else {
662             SetCPU (CPU_6502);
663         }
664     }
665
666     /* If no memory model was given, use the default */
667     if (MemoryModel == MMODEL_UNKNOWN) {
668         SetMemoryModel (MMODEL_NEAR);
669     }
670
671     /* Intialize the target translation tables */
672     TgtTranslateInit ();
673
674     /* Initialize the segments */
675     InitSegments ();
676
677     /* Initialize the scanner, open the input file */
678     InitScanner (InFile);
679
680     /* Define the default options */
681     SetOptions ();
682
683     /* Assemble the input */
684     Assemble ();
685
686     /* If we didn't have any errors, check the segment stack */
687     if (ErrorCount == 0) {
688         SegStackCheck ();
689     }
690
691     /* If we didn't have any errors, check the unnamed labels */
692     if (ErrorCount == 0) {
693         ULabCheck ();
694     }
695
696     /* If we didn't have any errors, check the symbol table */
697     if (ErrorCount == 0) {
698         SymCheck ();
699     }
700
701     /* If we didn't have any errors, check and resolve the segment data */
702     if (ErrorCount == 0) {
703         SegCheck ();
704     }
705
706     /* If we didn't have an errors, index the line infos */
707     MakeLineInfoIndex ();
708
709     /* Dump the data */
710     if (Verbosity >= 2) {
711         SymDump (stdout);
712         SegDump ();
713     }
714
715     /* If we didn't have any errors, create the object and listing files */
716     if (ErrorCount == 0) {
717         CreateObjFile ();
718         if (Listing) {
719             CreateListing ();
720         }
721     }
722
723     /* Close the input file */
724     DoneScanner ();
725
726     /* Return an apropriate exit code */
727     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
728 }
729
730
731