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