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