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