]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Use __attribute ((unused)) instead of -Wno-unused-parameter
[cc65] / src / ca65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                 Main program for the ca65 macroassembler                  */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2000 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              "  -g\t\t\tAdd debug info to object file\n"
86              "  -h\t\t\tHelp (this text)\n"
87              "  -i\t\t\tIgnore case of symbols\n"
88              "  -l\t\t\tCreate a listing if assembly was ok\n"
89              "  -o name\t\tName the output file\n"
90              "  -s\t\t\tEnable smart mode\n"
91              "  -t sys\t\tSet the target system\n"
92              "  -v\t\t\tIncrease verbosity\n"
93              "  -D name[=value]\tDefine a symbol\n"
94              "  -I dir\t\tSet an include directory search path\n"
95              "  -U\t\t\tMark unresolved symbols as import\n"
96              "  -V\t\t\tPrint the assembler version\n"
97              "  -W n\t\t\tSet warning level n\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)) {
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     }
303 }
304
305
306
307 static void OptVerbose (const char* Opt attribute ((unused)),
308                         const char* Arg attribute ((unused)))
309 /* Increase verbosity */
310 {
311     ++Verbosity;
312 }
313
314
315
316 static void OptVersion (const char* Opt attribute ((unused)),
317                         const char* Arg attribute ((unused)))
318 /* Print the assembler version */
319 {
320     fprintf (stderr,
321              "ca65 V%u.%u.%u - (C) Copyright 1998-2000 Ullrich von Bassewitz\n",
322              VER_MAJOR, VER_MINOR, VER_PATCH);
323 }
324
325
326
327 static void DoPCAssign (void)
328 /* Start absolute code */
329 {
330     long PC = ConstExpression ();
331     if (PC < 0 || PC > 0xFFFFFF) {
332         Error (ERR_RANGE);
333     } else {
334         SetAbsPC (PC);
335     }
336 }
337
338
339
340 static void OneLine (void)
341 /* Assemble one line */
342 {
343     char Ident [MAX_STR_LEN+1];
344     int Done = 0;
345
346     /* Initialize the new listing line if we are actually reading from file
347      * and not from internally pushed input.
348      */
349     if (!HavePushedInput ()) {
350         InitListingLine ();
351     }
352
353     if (Tok == TOK_COLON) {
354         /* An unnamed label */
355         ULabDef ();
356         NextTok ();
357     }
358
359     /* Assemble the line */
360     if (Tok == TOK_IDENT) {
361
362         /* Is it a macro? */
363         if (IsMacro (SVal)) {
364
365             /* Yes, start a macro expansion */
366             MacExpandStart ();
367             Done = 1;
368
369         } else {
370
371             /* No, label. Remember the identifier, then skip it */
372             int HadWS = WS;     /* Did we have whitespace before the ident? */
373             strcpy (Ident, SVal);
374             NextTok ();
375
376             /* If a colon follows, this is a label definition. If there
377              * is no colon, it's an assignment.
378              */
379             if (Tok == TOK_EQ) {
380                 /* Skip the '=' */
381                 NextTok ();
382                 /* Define the symbol with the expression following the '=' */
383                 SymDef (Ident, Expression(), 0, 0);
384                 /* Don't allow anything after a symbol definition */
385                 Done = 1;
386             } else {
387                 /* Define a label */
388                 SymDef (Ident, CurrentPC(), IsZPSeg(), 1);
389                 /* Skip the colon. If NoColonLabels is enabled, allow labels
390                  * without a colon if there is no whitespace before the
391                  * identifier.
392                  */
393                 if (Tok != TOK_COLON) {
394                     if (HadWS || !NoColonLabels) {
395                         Error (ERR_COLON_EXPECTED);
396                     }
397                     if (Tok == TOK_NAMESPACE) {
398                         /* Smart :: handling */
399                         NextTok ();
400                     }
401                 } else {
402                     /* Skip the colon */
403                     NextTok ();
404                 }
405             }
406         }
407     }
408
409     if (!Done) {
410
411         if (TokIsPseudo (Tok)) {
412             /* A control command, IVal is index into table */
413             HandlePseudo ();
414         } else if (Tok == TOK_MNEMO) {
415             /* A mnemonic - assemble one instruction */
416             HandleInstruction (IVal);
417         } else if (Tok == TOK_IDENT && IsMacro (SVal)) {
418             /* A macro expansion */
419             MacExpandStart ();
420         } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
421             NextTok ();
422             if (Tok != TOK_EQ) {
423                 Error (ERR_EQ_EXPECTED);
424                 SkipUntilSep ();
425             } else {
426                 /* Skip the equal sign */
427                 NextTok ();
428                 /* Enter absolute mode */
429                 DoPCAssign ();
430             }
431         }
432     }
433
434     /* Line separator must come here */
435     ConsumeSep ();
436 }
437
438
439
440 static void Assemble (void)
441 /* Start the ball rolling ... */
442 {
443     /* Prime the pump */
444     NextTok ();
445
446     /* Assemble lines until end of file */
447     while (Tok != TOK_EOF) {
448         OneLine ();
449     }
450 }
451
452
453
454 static void CreateObjFile (void)
455 /* Create the object file */
456 {
457     /* Open the object, write the header */
458     ObjOpen ();
459
460     /* Write the object file options */
461     WriteOptions ();
462
463     /* Write the list of input files */
464     WriteFiles ();
465
466     /* Write the segment data to the file */
467     WriteSegments ();
468
469     /* Write the import list */
470     WriteImports ();
471
472     /* Write the export list */
473     WriteExports ();
474
475     /* Write debug symbols if requested */
476     WriteDbgSyms ();
477
478     /* Write line infos if requested */
479     WriteLineInfo ();
480
481     /* Write an updated header and close the file */
482     ObjClose ();
483 }
484
485
486
487 int main (int argc, char* argv [])
488 /* Assembler main program */
489 {
490     /* Program long options */
491     static const LongOpt OptTab[] = {
492         { "--auto-import",      0,      OptAutoImport           },
493         { "--cpu",              1,      OptCPU                  },
494         { "--debug-info",       0,      OptDebugInfo            },
495         { "--feature",          1,      OptFeature              },
496         { "--help",             0,      OptHelp                 },
497         { "--ignore-case",      0,      OptIgnoreCase           },
498         { "--include-dir",      1,      OptIncludeDir           },
499         { "--listing",          0,      OptListing              },
500         { "--pagelength",       1,      OptPageLength           },
501         { "--smart",            0,      OptSmart                },
502         { "--target",           1,      OptTarget               },
503         { "--verbose",          0,      OptVerbose              },
504         { "--version",          0,      OptVersion              },
505     };
506
507     unsigned I;
508
509     /* Initialize the cmdline module */
510     InitCmdLine (&argc, &argv, "ca65");
511
512     /* Enter the base lexical level. We must do that here, since we may
513      * define symbols using -D.
514      */
515     SymEnterLevel ();
516
517     /* Check the parameters */
518     I = 1;
519     while (I < ArgCount) {
520
521         /* Get the argument */
522         const char* Arg = ArgVec [I];
523
524         /* Check for an option */
525         if (Arg [0] == '-') {
526             switch (Arg [1]) {
527
528                 case '-':
529                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
530                     break;
531
532                 case 'g':
533                     OptDebugInfo (Arg, 0);
534                     break;
535
536                 case 'h':
537                     OptHelp (Arg, 0);
538                     break;
539
540                 case 'i':
541                     OptIgnoreCase (Arg, 0);
542                     break;
543
544                 case 'l':
545                     OptListing (Arg, 0);
546                     break;
547
548                 case 'o':
549                     OutFile = GetArg (&I, 2);
550                     break;
551
552                 case 's':
553                     OptSmart (Arg, 0);
554                     break;
555
556                 case 't':
557                     OptTarget (Arg, GetArg (&I, 2));
558                     break;
559
560                 case 'v':
561                     OptVerbose (Arg, 0);
562                     break;
563
564                 case 'D':
565                     DefineSymbol (GetArg (&I, 2));
566                     break;
567
568                 case 'I':
569                     OptIncludeDir (Arg, GetArg (&I, 2));
570                     break;
571
572                 case 'U':
573                     OptAutoImport (Arg, 0);
574                     break;
575
576                 case 'V':
577                     OptVersion (Arg, 0);
578                     break;
579
580                 case 'W':
581                     WarnLevel = atoi (GetArg (&I, 2));
582                     break;
583
584                 default:
585                     UnknownOption (Arg);
586                     break;
587
588             }
589         } else {
590             /* Filename. Check if we already had one */
591             if (InFile) {
592                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
593                          ProgName, Arg);
594                 exit (EXIT_FAILURE);
595             } else {
596                 InFile = Arg;
597             }
598         }
599
600         /* Next argument */
601         ++I;
602     }
603
604     /* Do we have an input file? */
605     if (InFile == 0) {
606         fprintf (stderr, "%s: No input files\n", ProgName);
607         exit (EXIT_FAILURE);
608     }
609
610     /* Intialize the target translation tables */
611     TgtTranslateInit ();
612
613     /* Initialize the scanner, open the input file */
614     InitScanner (InFile);
615
616     /* Define the default options */
617     SetOptions ();
618
619     /* Assemble the input */
620     Assemble ();
621
622     /* If we didn't have any errors, check the unnamed labels */
623     if (ErrorCount == 0) {
624         ULabCheck ();
625     }
626
627     /* If we didn't have any errors, check the symbol table */
628     if (ErrorCount == 0) {
629         SymCheck ();
630     }
631
632     /* If we didn't have any errors, check and resolve the segment data */
633     if (ErrorCount == 0) {
634         SegCheck ();
635     }
636
637     /* If we didn't have an errors, index the line infos */
638     MakeLineInfoIndex ();
639
640     /* Dump the data */
641     if (Verbosity >= 2) {
642         SymDump (stdout);
643         SegDump ();
644     }
645
646     /* If we didn't have any errors, create the object and listing files */
647     if (ErrorCount == 0) {
648         CreateObjFile ();
649         if (Listing) {
650             CreateListing ();
651         }
652     }
653
654     /* Close the input file */
655     DoneScanner ();
656
657     /* Return an apropriate exit code */
658     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
659 }
660
661
662