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