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