]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Move target handling routines into the common directory.
[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 "target.h"
45 #include "version.h"
46
47 /* ca65 */
48 #include "abend.h"
49 #include "error.h"
50 #include "expr.h"
51 #include "filetab.h"
52 #include "global.h"
53 #include "incpath.h"
54 #include "instr.h"
55 #include "istack.h"
56 #include "listing.h"
57 #include "macro.h"
58 #include "nexttok.h"
59 #include "objcode.h"
60 #include "objfile.h"
61 #include "options.h"
62 #include "pseudo.h"
63 #include "scanner.h"
64 #include "symtab.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     if (Arg == 0) {
287         NeedArg (Opt);
288     }
289
290     /* Map the target name to a target id */
291     Target = FindTarget (Arg);
292     if (Target == TGT_UNKNOWN) {
293         AbEnd ("Invalid target name: `%s'", Arg);
294     }
295 }
296
297
298
299 static void OptVerbose (const char* Opt, const char* Arg)
300 /* Increase verbosity */
301 {
302     ++Verbose;
303 }
304
305
306
307 static void OptVersion (const char* Opt, const char* Arg)
308 /* Print the assembler version */
309 {
310     fprintf (stderr,
311              "ca65 V%u.%u.%u - (C) Copyright 1998-2000 Ullrich von Bassewitz\n",
312              VER_MAJOR, VER_MINOR, VER_PATCH);
313 }
314
315
316
317 static void OneLine (void)
318 /* Assemble one line */
319 {
320     char Ident [MAX_STR_LEN+1];
321     int Done = 0;
322
323     /* Initialize the new listing line if we are actually reading from file
324      * and not from internally pushed input.
325      */
326     if (!HavePushedInput ()) {
327         InitListingLine ();
328     }
329
330     if (Tok == TOK_COLON) {
331         /* An unnamed label */
332         ULabDef ();
333         NextTok ();
334     }
335
336     /* Assemble the line */
337     if (Tok == TOK_IDENT) {
338
339         /* Is it a macro? */
340         if (IsMacro (SVal)) {
341
342             /* Yes, start a macro expansion */
343             MacExpandStart ();
344             Done = 1;
345
346         } else {
347
348             /* No, label. Remember the identifier, then skip it */
349             int HadWS = WS;     /* Did we have whitespace before the ident? */
350             strcpy (Ident, SVal);
351             NextTok ();
352
353             /* If a colon follows, this is a label definition. If there
354              * is no colon, it's an assignment.
355              */
356             if (Tok == TOK_EQ) {
357                 /* Skip the '=' */
358                 NextTok ();
359                 /* Define the symbol with the expression following the '=' */
360                 SymDef (Ident, Expression (), 0);
361                 /* Don't allow anything after a symbol definition */
362                 Done = 1;
363             } else {
364                 /* Define a label */
365                 SymDef (Ident, CurrentPC (), IsZPSeg ());
366                 /* Skip the colon. If NoColonLabels is enabled, allow labels
367                  * without a colon if there is no whitespace before the
368                  * identifier.
369                  */
370                 if (Tok != TOK_COLON) {
371                     if (HadWS || !NoColonLabels) {
372                         Error (ERR_COLON_EXPECTED);
373                     }
374                     if (Tok == TOK_NAMESPACE) {
375                         /* Smart :: handling */
376                         NextTok ();
377                     }
378                 } else {
379                     /* Skip the colon */
380                     NextTok ();
381                 }
382             }
383         }
384     }
385
386     if (!Done) {
387
388         if (TokIsPseudo (Tok)) {
389             /* A control command, IVal is index into table */
390             HandlePseudo ();
391         } else if (Tok == TOK_MNEMO) {
392             /* A mnemonic - assemble one instruction */
393             HandleInstruction (IVal);
394         } else if (Tok == TOK_IDENT && IsMacro (SVal)) {
395             /* A macro expansion */
396             MacExpandStart ();
397         }
398     }
399
400     /* Line separator must come here */
401     ConsumeSep ();
402 }
403
404
405
406 static void Assemble (void)
407 /* Start the ball rolling ... */
408 {
409     /* Prime the pump */
410     NextTok ();
411
412     /* Assemble lines until end of file */
413     while (Tok != TOK_EOF) {
414         OneLine ();
415     }
416 }
417
418
419
420 static void CreateObjFile (void)
421 /* Create the object file */
422 {
423     /* Open the object, write the header */
424     ObjOpen ();
425
426     /* Write the object file options */
427     WriteOptions ();
428
429     /* Write the list of input files */
430     WriteFiles ();
431
432     /* Write the segment data to the file */
433     WriteSegments ();
434
435     /* Write the import list */
436     WriteImports ();
437
438     /* Write the export list */
439     WriteExports ();
440
441     /* Write debug symbols if requested */
442     WriteDbgSyms ();
443
444     /* Write an updated header and close the file */
445     ObjClose ();
446 }
447
448
449
450 int main (int argc, char* argv [])
451 /* Assembler main program */
452 {
453     /* Program long options */
454     static const LongOpt OptTab[] = {
455         { "--auto-import",      0,      OptAutoImport           },
456         { "--cpu",              1,      OptCPU                  },
457         { "--debug-info",       0,      OptDebugInfo            },
458         { "--help",             0,      OptHelp                 },
459         { "--ignore-case",      0,      OptIgnoreCase           },
460         { "--include-dir",      1,      OptIncludeDir           },
461         { "--listing",          0,      OptListing              },
462         { "--pagelength",       1,      OptPageLength           },
463         { "--smart",            0,      OptSmart                },
464         { "--target",           1,      OptTarget               },
465         { "--verbose",          0,      OptVerbose              },
466         { "--version",          0,      OptVersion              },
467     };
468
469     int I;
470
471     /* Initialize the cmdline module */
472     InitCmdLine (argc, argv, "ca65");
473
474     /* Enter the base lexical level. We must do that here, since we may
475      * define symbols using -D.
476      */
477     SymEnterLevel ();
478
479     /* Check the parameters */
480     I = 1;
481     while (I < argc) {
482
483         /* Get the argument */
484         const char* Arg = argv [I];
485
486         /* Check for an option */
487         if (Arg [0] == '-') {
488             switch (Arg [1]) {
489
490                 case '-':
491                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
492                     break;
493
494                 case 'g':
495                     OptDebugInfo (Arg, 0);
496                     break;
497
498                 case 'h':
499                     OptHelp (Arg, 0);
500                     break;
501
502                 case 'i':
503                     OptIgnoreCase (Arg, 0);
504                     break;
505
506                 case 'l':
507                     OptListing (Arg, 0);
508                     break;
509
510                 case 'o':
511                     OutFile = GetArg (&I, 2);
512                     break;
513
514                 case 's':
515                     OptSmart (Arg, 0);
516                     break;
517
518                 case 't':
519                     OptTarget (Arg, GetArg (&I, 2));
520                     break;
521
522                 case 'v':
523                     OptVerbose (Arg, 0);
524                     break;
525
526                 case 'D':
527                     DefineSymbol (GetArg (&I, 2));
528                     break;
529
530                 case 'I':
531                     OptIncludeDir (Arg, GetArg (&I, 2));
532                     break;
533
534                 case 'U':
535                     OptAutoImport (Arg, 0);
536                     break;
537
538                 case 'V':
539                     OptVersion (Arg, 0);
540                     break;
541
542                 case 'W':
543                     WarnLevel = atoi (GetArg (&I, 2));
544                     break;
545
546                 default:
547                     UnknownOption (Arg);
548                     break;
549
550             }
551         } else {
552             /* Filename. Check if we already had one */
553             if (InFile) {
554                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
555                          ProgName, Arg);
556                 exit (EXIT_FAILURE);
557             } else {
558                 InFile = Arg;
559             }
560         }
561
562         /* Next argument */
563         ++I;
564     }
565
566     /* Do we have an input file? */
567     if (InFile == 0) {
568         fprintf (stderr, "%s: No input files\n", ProgName);
569         exit (EXIT_FAILURE);
570     }
571
572     /* Initialize the scanner, open the input file */
573     InitScanner (InFile);
574
575     /* Define the default options */
576     SetOptions ();
577
578     /* Assemble the input */
579     Assemble ();
580
581     /* If we didn't have any errors, check the unnamed labels */
582     if (ErrorCount == 0) {
583         ULabCheck ();
584     }
585
586     /* If we didn't have any errors, check the symbol table */
587     if (ErrorCount == 0) {
588         SymCheck ();
589     }
590
591     /* If we didn't have any errors, check and resolve the segment data */
592     if (ErrorCount == 0) {
593         SegCheck ();
594     }
595
596     /* Dump the data */
597     if (Verbose >= 2) {
598         SymDump (stdout);
599         SegDump ();
600     }
601
602     /* If we didn't have any errors, create the object and listing files */
603     if (ErrorCount == 0) {
604         CreateObjFile ();
605         if (Listing) {
606             CreateListing ();
607         }
608     }
609
610     /* Close the input file */
611     DoneScanner ();
612
613     /* Return an apropriate exit code */
614     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
615 }
616
617
618