]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Added command line response files
[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 "target.h"
45 #include "tgttrans.h"
46 #include "version.h"
47
48 /* ca65 */
49 #include "abend.h"
50 #include "error.h"
51 #include "expr.h"
52 #include "feature.h"
53 #include "filetab.h"
54 #include "global.h"
55 #include "incpath.h"
56 #include "instr.h"
57 #include "istack.h"
58 #include "listing.h"
59 #include "macro.h"
60 #include "nexttok.h"
61 #include "objcode.h"
62 #include "objfile.h"
63 #include "options.h"
64 #include "pseudo.h"
65 #include "scanner.h"
66 #include "symtab.h"
67 #include "ulabel.h"
68
69
70
71 /*****************************************************************************/
72 /*                                   Code                                    */
73 /*****************************************************************************/
74
75
76
77 static void Usage (void)
78 /* Print usage information and exit */
79 {
80     fprintf (stderr,
81              "Usage: %s [options] file\n"
82              "Short options:\n"
83              "  -g\t\t\tAdd debug info to object file\n"
84              "  -h\t\t\tHelp (this text)\n"
85              "  -i\t\t\tIgnore case of symbols\n"
86              "  -l\t\t\tCreate a listing if assembly was ok\n"
87              "  -o name\t\tName the output file\n"
88              "  -s\t\t\tEnable smart mode\n"
89              "  -t sys\t\tSet the target system\n"
90              "  -v\t\t\tIncrease verbosity\n"
91              "  -D name[=value]\tDefine a symbol\n"
92              "  -I dir\t\tSet an include directory search path\n"
93              "  -U\t\t\tMark unresolved symbols as import\n"
94              "  -V\t\t\tPrint the assembler version\n"
95              "  -W n\t\t\tSet warning level n\n"
96              "\n"
97              "Long options:\n"
98              "  --auto-import\t\tMark unresolved symbols as import\n"
99              "  --cpu type\t\tSet cpu type\n"
100              "  --debug-info\t\tAdd debug info to object file\n"
101              "  --feature name\tSet an emulation feature\n"
102              "  --help\t\tHelp (this text)\n"
103              "  --ignore-case\t\tIgnore case of symbols\n"
104              "  --include-dir dir\tSet an include directory search path\n"
105              "  --listing\t\tCreate a listing if assembly was ok\n"
106              "  --pagelength n\tSet the page length for the listing\n"
107              "  --smart\t\tEnable smart mode\n"
108              "  --target sys\t\tSet the target system\n"
109              "  --verbose\t\tIncrease verbosity\n"
110              "  --version\t\tPrint the assembler version\n",
111              ProgName);
112 }
113
114
115
116 static void SetOptions (void)
117 /* Set the option for the translator */
118 {
119     char Buf [256];
120
121     /* Set the translator */
122     sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
123     OptTranslator (Buf);
124
125     /* Set date and time */
126     OptDateTime ((unsigned long) time(0));
127 }
128
129
130
131 static void DefineSymbol (const char* Def)
132 /* Define a symbol from the command line */
133 {
134     const char* P;
135     unsigned I;
136     long Val;
137     char SymName [MAX_STR_LEN+1];
138
139     /* The symbol must start with a character or underline */
140     if (Def [0] != '_' && !IsAlpha (Def [0])) {
141         InvDef (Def);
142     }
143     P = Def;
144
145     /* Copy the symbol, checking the rest */
146     I = 0;
147     while (IsAlNum (*P) || *P == '_') {
148         if (I <= MAX_STR_LEN) {
149             SymName [I++] = *P;
150         }
151         ++P;
152     }
153     SymName [I] = '\0';
154
155     /* Do we have a value given? */
156     if (*P != '=') {
157         if (*P != '\0') {
158             InvDef (Def);
159         }
160         Val = 0;
161     } else {
162         /* We have a value */
163         ++P;
164         if (*P == '$') {
165             ++P;
166             if (sscanf (P, "%lx", &Val) != 1) {
167                 InvDef (Def);
168             }
169         } else {
170             if (sscanf (P, "%li", &Val) != 1) {
171                 InvDef (Def);
172             }
173         }
174     }
175
176     /* Check if have already a symbol with this name */
177     if (SymIsDef (SymName)) {
178         AbEnd ("`%s' is already defined", SymName);
179     }
180
181     /* Define the symbol */
182     SymDef (SymName, LiteralExpr (Val), 0);
183 }
184
185
186
187 static void OptAutoImport (const char* Opt, const char* Arg)
188 /* Mark unresolved symbols as imported */
189 {
190     AutoImport = 1;
191 }
192
193
194
195 static void OptCPU (const char* Opt, const char* Arg)
196 /* Handle the --cpu option */
197 {
198     if (Arg == 0) {
199         NeedArg (Opt);
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, const char* Arg)
219 /* Add debug info to the object file */
220 {
221     DbgSyms = 1;
222 }
223
224
225
226 static void OptFeature (const char* Opt, const char* Arg)
227 /* Set an emulation feature */
228 {
229     /* Set the feature, check for errors */
230     if (SetFeature (Arg) == FEAT_UNKNOWN) {
231         AbEnd ("Illegal emulation feature: `%s'", Arg);
232     }
233 }
234
235
236
237 static void OptHelp (const char* Opt, const char* Arg)
238 /* Print usage information and exit */
239 {
240     Usage ();
241     exit (EXIT_SUCCESS);
242 }
243
244
245
246 static void OptIgnoreCase (const char* Opt, const char* Arg)
247 /* Ignore case on symbols */
248 {
249     IgnoreCase = 1;
250 }
251
252
253
254 static void OptIncludeDir (const char* Opt, const char* Arg)
255 /* Add an include search path */
256 {
257     if (Arg == 0) {
258         NeedArg (Opt);
259     }
260     AddIncludePath (Arg);
261 }
262
263
264
265 static void OptListing (const char* Opt, const char* Arg)
266 /* Create a listing file */
267 {
268     Listing = 1;
269 }
270
271
272
273 static void OptPageLength (const char* Opt, const char* Arg)
274 /* Handle the --pagelength option */
275 {
276     int Len;
277     if (Arg == 0) {
278         NeedArg (Opt);
279     }
280     Len = atoi (Arg);
281     if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
282         AbEnd ("Invalid page length: %d", Len);
283     }
284     PageLength = Len;
285 }
286
287
288
289 static void OptSmart (const char* Opt, const char* Arg)
290 /* Handle the -s/--smart options */
291 {
292     SmartMode = 1;
293 }
294
295
296
297 static void OptTarget (const char* Opt, const char* Arg)
298 /* Set the target system */
299 {
300     if (Arg == 0) {
301         NeedArg (Opt);
302     }
303
304     /* Map the target name to a target id */
305     Target = FindTarget (Arg);
306     if (Target == TGT_UNKNOWN) {
307         AbEnd ("Invalid target name: `%s'", Arg);
308     }
309 }
310
311
312
313 static void OptVerbose (const char* Opt, const char* Arg)
314 /* Increase verbosity */
315 {
316     ++Verbose;
317 }
318
319
320
321 static void OptVersion (const char* Opt, const char* Arg)
322 /* Print the assembler version */
323 {
324     fprintf (stderr,
325              "ca65 V%u.%u.%u - (C) Copyright 1998-2000 Ullrich von Bassewitz\n",
326              VER_MAJOR, VER_MINOR, VER_PATCH);
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);
388                 /* Don't allow anything after a symbol definition */
389                 Done = 1;
390             } else {
391                 /* Define a label */
392                 SymDef (Ident, CurrentPC (), IsZPSeg ());
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 an updated header and close the file */
483     ObjClose ();
484 }
485
486
487
488 int main (int argc, char* argv [])
489 /* Assembler main program */
490 {
491     /* Program long options */
492     static const LongOpt OptTab[] = {
493         { "--auto-import",      0,      OptAutoImport           },
494         { "--cpu",              1,      OptCPU                  },
495         { "--debug-info",       0,      OptDebugInfo            },
496         { "--feature",          1,      OptFeature              },
497         { "--help",             0,      OptHelp                 },
498         { "--ignore-case",      0,      OptIgnoreCase           },
499         { "--include-dir",      1,      OptIncludeDir           },
500         { "--listing",          0,      OptListing              },
501         { "--pagelength",       1,      OptPageLength           },
502         { "--smart",            0,      OptSmart                },
503         { "--target",           1,      OptTarget               },
504         { "--verbose",          0,      OptVerbose              },
505         { "--version",          0,      OptVersion              },
506     };
507
508     int I;
509
510     /* Initialize the cmdline module */
511     InitCmdLine (&argc, &argv, "ca65");
512
513     /* Enter the base lexical level. We must do that here, since we may
514      * define symbols using -D.
515      */
516     SymEnterLevel ();
517
518     /* Check the parameters */
519     I = 1;
520     while (I < ArgCount) {
521
522         /* Get the argument */
523         const char* Arg = ArgVec [I];
524
525         /* Check for an option */
526         if (Arg [0] == '-') {
527             switch (Arg [1]) {
528
529                 case '-':
530                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
531                     break;
532
533                 case 'g':
534                     OptDebugInfo (Arg, 0);
535                     break;
536
537                 case 'h':
538                     OptHelp (Arg, 0);
539                     break;
540
541                 case 'i':
542                     OptIgnoreCase (Arg, 0);
543                     break;
544
545                 case 'l':
546                     OptListing (Arg, 0);
547                     break;
548
549                 case 'o':
550                     OutFile = GetArg (&I, 2);
551                     break;
552
553                 case 's':
554                     OptSmart (Arg, 0);
555                     break;
556
557                 case 't':
558                     OptTarget (Arg, GetArg (&I, 2));
559                     break;
560
561                 case 'v':
562                     OptVerbose (Arg, 0);
563                     break;
564
565                 case 'D':
566                     DefineSymbol (GetArg (&I, 2));
567                     break;
568
569                 case 'I':
570                     OptIncludeDir (Arg, GetArg (&I, 2));
571                     break;
572
573                 case 'U':
574                     OptAutoImport (Arg, 0);
575                     break;
576
577                 case 'V':
578                     OptVersion (Arg, 0);
579                     break;
580
581                 case 'W':
582                     WarnLevel = atoi (GetArg (&I, 2));
583                     break;
584
585                 default:
586                     UnknownOption (Arg);
587                     break;
588
589             }
590         } else {
591             /* Filename. Check if we already had one */
592             if (InFile) {
593                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
594                          ProgName, Arg);
595                 exit (EXIT_FAILURE);
596             } else {
597                 InFile = Arg;
598             }
599         }
600
601         /* Next argument */
602         ++I;
603     }
604
605     /* Do we have an input file? */
606     if (InFile == 0) {
607         fprintf (stderr, "%s: No input files\n", ProgName);
608         exit (EXIT_FAILURE);
609     }
610
611     /* Intialize the target translation tables */
612     TgtTranslateInit ();
613
614     /* Initialize the scanner, open the input file */
615     InitScanner (InFile);
616
617     /* Define the default options */
618     SetOptions ();
619
620     /* Assemble the input */
621     Assemble ();
622
623     /* If we didn't have any errors, check the unnamed labels */
624     if (ErrorCount == 0) {
625         ULabCheck ();
626     }
627
628     /* If we didn't have any errors, check the symbol table */
629     if (ErrorCount == 0) {
630         SymCheck ();
631     }
632
633     /* If we didn't have any errors, check and resolve the segment data */
634     if (ErrorCount == 0) {
635         SegCheck ();
636     }
637
638     /* Dump the data */
639     if (Verbose >= 2) {
640         SymDump (stdout);
641         SegDump ();
642     }
643
644     /* If we didn't have any errors, create the object and listing files */
645     if (ErrorCount == 0) {
646         CreateObjFile ();
647         if (Listing) {
648             CreateListing ();
649         }
650     }
651
652     /* Close the input file */
653     DoneScanner ();
654
655     /* Return an apropriate exit code */
656     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
657 }
658
659
660