]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Added -h option
[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 "listing.h"
51 #include "macro.h"
52 #include "nexttok.h"
53 #include "objcode.h"
54 #include "objfile.h"
55 #include "options.h"
56 #include "pseudo.h"
57 #include "scanner.h"
58 #include "symtab.h"
59 #include "ulabel.h"
60
61
62
63 /*****************************************************************************/
64 /*                                   Code                                    */
65 /*****************************************************************************/
66
67
68
69 static void Usage (void)
70 /* Print usage information and exit */
71 {
72     fprintf (stderr,
73              "Usage: %s [options] file\n"
74              "Short options:\n"
75              "  -g\t\t\tAdd debug info to object file\n"
76              "  -h\t\t\tHelp (this text)\n"
77              "  -i\t\t\tIgnore case of symbols\n"
78              "  -l\t\t\tCreate a listing if assembly was ok\n"
79              "  -o name\t\tName the output file\n"
80              "  -s\t\t\tEnable smart mode\n"
81              "  -v\t\t\tIncrease verbosity\n"
82              "  -D name[=value]\tDefine a symbol\n"
83              "  -I dir\t\tSet an include directory search path\n"
84              "  -U\t\t\tMark unresolved symbols as import\n"
85              "  -V\t\t\tPrint the assembler version\n"
86              "  -W n\t\t\tSet warning level n\n"
87              "\n"
88              "Long options:\n"
89              "  --auto-import\t\tMark unresolved symbols as import\n"
90              "  --cpu type\t\tSet cpu type\n"
91              "  --debug-info\t\tAdd debug info to object file\n"
92              "  --help\t\tHelp (this text)\n"
93              "  --ignore-case\t\tIgnore case of symbols\n"
94              "  --include-dir dir\tSet an include directory search path\n"
95              "  --listing\t\tCreate a listing if assembly was ok\n"
96              "  --pagelength n\tSet the page length for the listing\n"
97              "  --smart\t\tEnable smart mode\n"
98              "  --verbose\t\tIncrease verbosity\n"
99              "  --version\t\tPrint the assembler version\n",
100              ProgName);
101 }
102
103
104
105 static void SetOptions (void)
106 /* Set the option for the translator */
107 {
108     char Buf [256];
109
110     /* Set the translator */
111     sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
112     OptTranslator (Buf);
113
114     /* Set date and time */
115     OptDateTime ((unsigned long) time(0));
116 }
117
118
119
120 static void DefineSymbol (const char* Def)
121 /* Define a symbol from the command line */
122 {
123     const char* P;
124     unsigned I;
125     long Val;
126     char SymName [MAX_STR_LEN+1];
127
128     /* The symbol must start with a character or underline */
129     if (Def [0] != '_' && !isalpha (Def [0])) {
130         InvDef (Def);
131     }
132     P = Def;
133
134     /* Copy the symbol, checking the rest */
135     I = 0;
136     while (isalnum (*P) || *P == '_') {
137         if (I <= MAX_STR_LEN) {
138             SymName [I++] = *P;
139         }
140         ++P;
141     }
142     SymName [I] = '\0';
143
144     /* Do we have a value given? */
145     if (*P != '=') {
146         if (*P != '\0') {
147             InvDef (Def);
148         }
149         Val = 0;
150     } else {
151         /* We have a value */
152         ++P;
153         if (*P == '$') {
154             ++P;
155             if (sscanf (P, "%lx", &Val) != 1) {
156                 InvDef (Def);
157             }
158         } else {
159             if (sscanf (P, "%li", &Val) != 1) {
160                 InvDef (Def);
161             }
162         }
163     }
164
165     /* Check if have already a symbol with this name */
166     if (SymIsDef (SymName)) {
167         fprintf (stderr, "`%s' is already defined\n", SymName);
168         exit (EXIT_FAILURE);
169     }
170
171     /* Define the symbol */
172     SymDef (SymName, LiteralExpr (Val), 0);
173 }
174
175
176
177 static void OptAutoImport (const char* Opt, const char* Arg)
178 /* Mark unresolved symbols as imported */
179 {
180     AutoImport = 1;
181 }
182
183
184
185 static void OptCPU (const char* Opt, const char* Arg)
186 /* Handle the --cpu option */
187 {
188     if (Arg == 0) {
189         NeedArg (Opt);
190     }
191     if (strcmp (Arg, "6502") == 0) {
192         SetCPU (CPU_6502);
193     } else if (strcmp (Arg, "65C02") == 0) {
194         SetCPU (CPU_65C02);
195     } else if (strcmp (Arg, "65816") == 0) {
196         SetCPU (CPU_65816);
197 #ifdef SUNPLUS
198     } else if (strcmp (Arg, "sunplus") == 0) {
199         SetCPU (CPU_SUNPLUS);
200 #endif
201     } else {
202         fprintf (stderr, "Invalid CPU: `%s'\n", Arg);
203         exit (EXIT_FAILURE);
204     }
205 }
206
207
208
209 static void OptDebugInfo (const char* Opt, const char* Arg)
210 /* Add debug info to the object file */
211 {
212     DbgSyms = 1;
213 }
214
215
216
217 static void OptHelp (const char* Opt, const char* Arg)
218 /* Print usage information and exit */
219 {
220     Usage ();
221     exit (EXIT_SUCCESS);
222 }
223
224
225
226 static void OptIgnoreCase (const char* Opt, const char* Arg)
227 /* Ignore case on symbols */
228 {
229     IgnoreCase = 1;
230 }
231
232
233
234 static void OptIncludeDir (const char* Opt, const char* Arg)
235 /* Add an include search path */
236 {
237     if (Arg == 0) {
238         NeedArg (Opt);
239     }
240     AddIncludePath (Arg);
241 }
242
243
244
245 static void OptListing (const char* Opt, const char* Arg)
246 /* Create a listing file */
247 {
248     Listing = 1;
249 }
250
251
252
253 static void OptPageLength (const char* Opt, const char* Arg)
254 /* Handle the --pagelength option */
255 {
256     int Len;
257     if (Arg == 0) {
258         NeedArg (Opt);
259     }
260     Len = atoi (Arg);
261     if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
262         fprintf (stderr, "Invalid page length: %d\n", Len);
263         exit (EXIT_FAILURE);
264     }
265     PageLength = Len;
266 }
267
268
269
270 static void OptSmart (const char* Opt, const char* Arg)
271 /* Handle the -s/--smart options */
272 {
273     SmartMode = 1;
274 }
275
276
277
278 static void OptVerbose (const char* Opt, const char* Arg)
279 /* Increase verbosity */
280 {
281     ++Verbose;
282 }
283
284
285
286 static void OptVersion (const char* Opt, const char* Arg)
287 /* Print the assembler version */
288 {
289     fprintf (stderr,
290              "ca65 V%u.%u.%u - (C) Copyright 1998-2000 Ullrich von Bassewitz\n",
291              VER_MAJOR, VER_MINOR, VER_PATCH);
292 }
293
294
295
296 static void OneLine (void)
297 /* Assemble one line */
298 {
299     char Ident [MAX_STR_LEN+1];
300     int Done = 0;
301
302     /* Initialize the listing line */
303     InitListingLine ();
304
305     if (Tok == TOK_COLON) {
306         /* An unnamed label */
307         ULabDef ();
308         NextTok ();
309     }
310
311     /* Assemble the line */
312     if (Tok == TOK_IDENT) {
313
314         /* Is it a macro? */
315         if (IsMacro (SVal)) {
316
317             /* Yes, start a macro expansion */
318             MacExpandStart ();
319             Done = 1;
320
321         } else {
322
323             /* No, label. Remember the identifier, then skip it */
324             int HadWS = WS;     /* Did we have whitespace before the ident? */
325             strcpy (Ident, SVal);
326             NextTok ();
327
328             /* If a colon follows, this is a label definition. If there
329              * is no colon, it's an assignment.
330              */
331             if (Tok == TOK_EQ) {
332                 /* Skip the '=' */
333                 NextTok ();
334                 /* Define the symbol with the expression following the '=' */
335                 SymDef (Ident, Expression (), 0);
336                 /* Don't allow anything after a symbol definition */
337                 Done = 1;
338             } else {
339                 /* Define a label */
340                 SymDef (Ident, CurrentPC (), IsZPSeg ());
341                 /* Skip the colon. If NoColonLabels is enabled, allow labels
342                  * without a colon if there is no whitespace before the
343                  * identifier.
344                  */
345                 if (Tok != TOK_COLON) {
346                     if (HadWS || !NoColonLabels) {
347                         Error (ERR_COLON_EXPECTED);
348                     }
349                     if (Tok == TOK_NAMESPACE) {
350                         /* Smart :: handling */
351                         NextTok ();
352                     }
353                 } else {
354                     /* Skip the colon */
355                     NextTok ();
356                 }
357             }
358         }
359     }
360
361     if (!Done) {
362
363         if (TokIsPseudo (Tok)) {
364             /* A control command, IVal is index into table */
365             HandlePseudo ();
366         } else if (Tok == TOK_MNEMO) {
367             /* A mnemonic - assemble one instruction */
368             HandleInstruction (IVal);
369         } else if (Tok == TOK_IDENT && IsMacro (SVal)) {
370             /* A macro expansion */
371             MacExpandStart ();
372         }
373     }
374
375     /* Calling InitListingLine again here is part of a hack that introduces
376      * enough magic to make the PC output in the listing work.
377      */
378     InitListingLine ();
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