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