]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
5d30bcc0c4b2bff2a8eb3f3e09f277abb3b829bd
[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 "mem.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              "  -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\tPrint 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     exit (EXIT_FAILURE);
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         InvSym (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             InvSym (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                 InvSym (Def);
158             }
159         } else {
160             if (sscanf (P, "%li", &Val) != 1) {
161                 InvSym (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 }
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                  * '='
336                  */
337                 SymDef (Ident, Expression (), 0);
338                 /* Don't allow anything after a symbol definition */
339                 Done = 1;
340             } else {
341                 /* Define a label */
342                 SymDef (Ident, CurrentPC (), IsZPSeg ());
343                 /* Skip the colon. If NoColonLabels is enabled, allow labels
344                  * without a colon if there is no whitespace before the
345                  * identifier.
346                  */
347                 if (Tok != TOK_COLON) {
348                     if (HadWS || !NoColonLabels) {
349                         Error (ERR_COLON_EXPECTED);
350                     }
351                     if (Tok == TOK_NAMESPACE) {
352                         /* Smart :: handling */
353                         NextTok ();
354                     }
355                 } else {
356                     /* Skip the colon */
357                     NextTok ();
358                 }
359             }
360         }
361     }
362
363     if (!Done) {
364
365         if (TokIsPseudo (Tok)) {
366             /* A control command, IVal is index into table */
367             HandlePseudo ();
368         } else if (Tok == TOK_MNEMO) {
369             /* A mnemonic - assemble one instruction */
370             HandleInstruction (IVal);
371         } else if (Tok == TOK_IDENT && IsMacro (SVal)) {
372             /* A macro expansion */
373             MacExpandStart ();
374         }
375     }
376
377     /* Calling InitListingLine again here is part of a hack that introduces
378      * enough magic to make the PC output in the listing work.
379      */
380     InitListingLine ();
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);
454
455     /* Set the program name */
456     ProgName = argv [0];
457
458     /* We must have a file name */
459     if (argc < 2) {
460         Usage ();
461     }
462
463     /* Enter the base lexical level. We must do that here, since we may
464      * define symbols using -D.
465      */
466     SymEnterLevel ();
467
468     /* Check the parameters */
469     I = 1;
470     while (I < argc) {
471
472         /* Get the argument */
473         const char* Arg = argv [I];
474
475         /* Check for an option */
476         if (Arg [0] == '-') {
477             switch (Arg [1]) {
478
479                 case '-':
480                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
481                     break;
482
483                 case 'g':
484                     OptDebugInfo (Arg, 0);
485                     break;
486
487                 case 'i':
488                     OptIgnoreCase (Arg, 0);
489                     break;
490
491                 case 'l':
492                     OptListing (Arg, 0);
493                     break;
494
495                 case 'o':
496                     OutFile = GetArg (&I, 2);
497                     break;
498
499                 case 's':
500                     OptSmart (Arg, 0);
501                     break;
502
503                 case 'v':
504                     OptVerbose (Arg, 0);
505                     break;
506
507                 case 'D':
508                     DefineSymbol (GetArg (&I, 2));
509                     break;
510
511                 case 'I':
512                     OptIncludeDir (Arg, GetArg (&I, 2));
513                     break;
514
515                 case 'U':
516                     OptAutoImport (Arg, 0);
517                     break;
518
519                 case 'V':
520                     OptVersion (Arg, 0);
521                     break;
522
523                 case 'W':
524                     WarnLevel = atoi (GetArg (&I, 2));
525                     break;
526
527                 default:
528                     UnknownOption (Arg);
529                     break;
530
531             }
532         } else {
533             /* Filename. Check if we already had one */
534             if (InFile) {
535                 fprintf (stderr, "Don't know what to do with `%s'\n", Arg);
536                 Usage ();
537             } else {
538                 InFile = Arg;
539             }
540         }
541
542         /* Next argument */
543         ++I;
544     }
545
546     /* Do we have an input file? */
547     if (InFile == 0) {
548         fprintf (stderr, "No input file\n");
549         exit (EXIT_FAILURE);
550     }
551
552     /* Initialize the scanner, open the input file */
553     InitScanner (InFile);
554
555     /* Define the default options */
556     SetOptions ();
557
558     /* Assemble the input */
559     Assemble ();
560
561     /* If we didn't have any errors, check the unnamed labels */
562     if (ErrorCount == 0) {
563         ULabCheck ();
564     }
565
566     /* If we didn't have any errors, check the symbol table */
567     if (ErrorCount == 0) {
568         SymCheck ();
569     }
570
571     /* If we didn't have any errors, check and resolve the segment data */
572     if (ErrorCount == 0) {
573         SegCheck ();
574     }
575
576     /* Dump the data */
577     if (Verbose >= 2) {
578         SymDump (stdout);
579         SegDump ();
580     }
581
582     /* If we didn't have any errors, create the object and listing files */
583     if (ErrorCount == 0) {
584         CreateObjFile ();
585         if (Listing) {
586             CreateListing ();
587         }
588     }
589
590     /* Close the input file */
591     DoneScanner ();
592
593     /* Return an apropriate exit code */
594     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
595 }
596
597
598