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