]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Changed the object file and library format. There is now an additional
[cc65] / src / ca65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                 Main program for the ca65 macroassembler                  */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2003 Ullrich von Bassewitz                                       */
10 /*               Römerstrasse 52                                             */
11 /*               D-70794 Filderstadt                                         */
12 /* EMail:        uz@cc65.org                                                 */
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 "lineinfo.h"
60 #include "listing.h"
61 #include "macro.h"
62 #include "nexttok.h"
63 #include "objcode.h"
64 #include "objfile.h"
65 #include "options.h"
66 #include "pseudo.h"
67 #include "scanner.h"
68 #include "spool.h"
69 #include "symtab.h"
70 #include "ulabel.h"
71
72
73
74 /*****************************************************************************/
75 /*                                   Code                                    */
76 /*****************************************************************************/
77
78
79
80 static void Usage (void)
81 /* Print usage information and exit */
82 {
83     fprintf (stderr,
84              "Usage: %s [options] file\n"
85              "Short options:\n"
86              "  -D name[=value]\tDefine a symbol\n"
87              "  -I dir\t\tSet an include directory search path\n"
88              "  -U\t\t\tMark unresolved symbols as import\n"
89              "  -V\t\t\tPrint the assembler version\n"
90              "  -W n\t\t\tSet warning level n\n"
91              "  -g\t\t\tAdd debug info to object file\n"
92              "  -h\t\t\tHelp (this text)\n"
93              "  -i\t\t\tIgnore case of symbols\n"
94              "  -l\t\t\tCreate a listing if assembly was ok\n"
95              "  -o name\t\tName the output file\n"
96              "  -s\t\t\tEnable smart mode\n"
97              "  -t sys\t\tSet the target system\n"
98              "  -v\t\t\tIncrease verbosity\n"
99              "\n"
100              "Long options:\n"
101              "  --auto-import\t\tMark unresolved symbols as import\n"
102              "  --cpu type\t\tSet cpu type\n"
103              "  --debug-info\t\tAdd debug info to object file\n"
104              "  --feature name\tSet an emulation feature\n"
105              "  --help\t\tHelp (this text)\n"
106              "  --ignore-case\t\tIgnore case of symbols\n"
107              "  --include-dir dir\tSet an include directory search path\n"
108              "  --listing\t\tCreate a listing if assembly was ok\n"
109              "  --pagelength n\tSet the page length for the listing\n"
110              "  --smart\t\tEnable smart mode\n"
111              "  --target sys\t\tSet the target system\n"
112              "  --verbose\t\tIncrease verbosity\n"
113              "  --version\t\tPrint the assembler version\n",
114              ProgName);
115 }
116
117
118
119 static void SetOptions (void)
120 /* Set the option for the translator */
121 {
122     char Buf [256];
123
124     /* Set the translator */
125     sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
126     OptTranslator (Buf);
127
128     /* Set date and time */
129     OptDateTime ((unsigned long) time(0));
130 }
131
132
133
134 static void DefineSymbol (const char* Def)
135 /* Define a symbol from the command line */
136 {
137     const char* P;
138     unsigned I;
139     long Val;
140     char SymName [MAX_STR_LEN+1];
141
142     /* The symbol must start with a character or underline */
143     if (Def [0] != '_' && !IsAlpha (Def [0])) {
144         InvDef (Def);
145     }
146     P = Def;
147
148     /* Copy the symbol, checking the rest */
149     I = 0;
150     while (IsAlNum (*P) || *P == '_') {
151         if (I <= MAX_STR_LEN) {
152             SymName [I++] = *P;
153         }
154         ++P;
155     }
156     SymName [I] = '\0';
157
158     /* Do we have a value given? */
159     if (*P != '=') {
160         if (*P != '\0') {
161             InvDef (Def);
162         }
163         Val = 0;
164     } else {
165         /* We have a value */
166         ++P;
167         if (*P == '$') {
168             ++P;
169             if (sscanf (P, "%lx", &Val) != 1) {
170                 InvDef (Def);
171             }
172         } else {
173             if (sscanf (P, "%li", &Val) != 1) {
174                 InvDef (Def);
175             }
176         }
177     }
178
179     /* Check if have already a symbol with this name */
180     if (SymIsDef (SymName, SCOPE_ANY)) {
181         AbEnd ("`%s' is already defined", SymName);
182     }
183
184     /* Define the symbol */
185     SymDef (SymName, LiteralExpr (Val), 0, 0);
186 }
187
188
189
190 static void OptAutoImport (const char* Opt attribute ((unused)),
191                            const char* Arg attribute ((unused)))
192 /* Mark unresolved symbols as imported */
193 {
194     AutoImport = 1;
195 }
196
197
198
199 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
200 /* Handle the --cpu option */
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 attribute ((unused)),
220                           const char* Arg attribute ((unused)))
221 /* Add debug info to the object file */
222 {
223     DbgSyms = 1;
224 }
225
226
227
228 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
229 /* Set an emulation feature */
230 {
231     /* Set the feature, check for errors */
232     if (SetFeature (Arg) == FEAT_UNKNOWN) {
233         AbEnd ("Illegal emulation feature: `%s'", Arg);
234     }
235 }
236
237
238
239 static void OptHelp (const char* Opt attribute ((unused)),
240                      const char* Arg attribute ((unused)))
241 /* Print usage information and exit */
242 {
243     Usage ();
244     exit (EXIT_SUCCESS);
245 }
246
247
248
249 static void OptIgnoreCase (const char* Opt attribute ((unused)),
250                            const char* Arg attribute ((unused)))
251 /* Ignore case on symbols */
252 {
253     IgnoreCase = 1;
254 }
255
256
257
258 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
259 /* Add an include search path */
260 {
261     AddIncludePath (Arg);
262 }
263
264
265
266 static void OptListing (const char* Opt attribute ((unused)),
267                         const char* Arg attribute ((unused)))
268 /* Create a listing file */
269 {
270     Listing = 1;
271 }
272
273
274
275 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
276 /* Handle the --pagelength option */
277 {
278     int Len = atoi (Arg);
279     if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
280         AbEnd ("Invalid page length: %d", Len);
281     }
282     PageLength = Len;
283 }
284
285
286
287 static void OptSmart (const char* Opt attribute ((unused)),
288                       const char* Arg attribute ((unused)))
289 /* Handle the -s/--smart options */
290 {
291     SmartMode = 1;
292 }
293
294
295
296 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
297 /* Set the target system */
298 {
299     /* Map the target name to a target id */
300     Target = FindTarget (Arg);
301     if (Target == TGT_UNKNOWN) {
302         AbEnd ("Invalid target name: `%s'", Arg);
303     } else if (Target == TGT_MODULE) {
304         AbEnd ("Cannot use `module' as a target for the assembler");
305     }
306 }
307
308
309
310 static void OptVerbose (const char* Opt attribute ((unused)),
311                         const char* Arg attribute ((unused)))
312 /* Increase verbosity */
313 {
314     ++Verbosity;
315 }
316
317
318
319 static void OptVersion (const char* Opt attribute ((unused)),
320                         const char* Arg attribute ((unused)))
321 /* Print the assembler version */
322 {
323     fprintf (stderr,
324              "ca65 V%u.%u.%u - %s\n",
325              VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
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, 0);
387                 /* Don't allow anything after a symbol definition */
388                 Done = 1;
389             } else {
390                 /* Define a label */
391                 SymDef (Ident, CurrentPC(), IsZPSeg(), 1);
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 line infos if requested */
482     WriteLineInfo ();
483
484     /* Write the string pool */
485     WriteStrPool ();
486
487     /* Write an updated header and close the file */
488     ObjClose ();
489 }
490
491
492
493 int main (int argc, char* argv [])
494 /* Assembler main program */
495 {
496     /* Program long options */
497     static const LongOpt OptTab[] = {
498         { "--auto-import",      0,      OptAutoImport           },
499         { "--cpu",              1,      OptCPU                  },
500         { "--debug-info",       0,      OptDebugInfo            },
501         { "--feature",          1,      OptFeature              },
502         { "--help",             0,      OptHelp                 },
503         { "--ignore-case",      0,      OptIgnoreCase           },
504         { "--include-dir",      1,      OptIncludeDir           },
505         { "--listing",          0,      OptListing              },
506         { "--pagelength",       1,      OptPageLength           },
507         { "--smart",            0,      OptSmart                },
508         { "--target",           1,      OptTarget               },
509         { "--verbose",          0,      OptVerbose              },
510         { "--version",          0,      OptVersion              },
511     };
512
513     unsigned I;
514
515     /* Initialize the cmdline module */
516     InitCmdLine (&argc, &argv, "ca65");
517
518     /* Enter the base lexical level. We must do that here, since we may
519      * define symbols using -D.
520      */
521     SymEnterLevel ();
522
523     /* Check the parameters */
524     I = 1;
525     while (I < ArgCount) {
526
527         /* Get the argument */
528         const char* Arg = ArgVec [I];
529
530         /* Check for an option */
531         if (Arg [0] == '-') {
532             switch (Arg [1]) {
533
534                 case '-':
535                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
536                     break;
537
538                 case 'g':
539                     OptDebugInfo (Arg, 0);
540                     break;
541
542                 case 'h':
543                     OptHelp (Arg, 0);
544                     break;
545
546                 case 'i':
547                     OptIgnoreCase (Arg, 0);
548                     break;
549
550                 case 'l':
551                     OptListing (Arg, 0);
552                     break;
553
554                 case 'o':
555                     OutFile = GetArg (&I, 2);
556                     break;
557
558                 case 's':
559                     OptSmart (Arg, 0);
560                     break;
561
562                 case 't':
563                     OptTarget (Arg, GetArg (&I, 2));
564                     break;
565
566                 case 'v':
567                     OptVerbose (Arg, 0);
568                     break;
569
570                 case 'D':
571                     DefineSymbol (GetArg (&I, 2));
572                     break;
573
574                 case 'I':
575                     OptIncludeDir (Arg, GetArg (&I, 2));
576                     break;
577
578                 case 'U':
579                     OptAutoImport (Arg, 0);
580                     break;
581
582                 case 'V':
583                     OptVersion (Arg, 0);
584                     break;
585
586                 case 'W':
587                     WarnLevel = atoi (GetArg (&I, 2));
588                     break;
589
590                 default:
591                     UnknownOption (Arg);
592                     break;
593
594             }
595         } else {
596             /* Filename. Check if we already had one */
597             if (InFile) {
598                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
599                          ProgName, Arg);
600                 exit (EXIT_FAILURE);
601             } else {
602                 InFile = Arg;
603             }
604         }
605
606         /* Next argument */
607         ++I;
608     }
609
610     /* Do we have an input file? */
611     if (InFile == 0) {
612         fprintf (stderr, "%s: No input files\n", ProgName);
613         exit (EXIT_FAILURE);
614     }
615
616     /* If no CPU given, use the default CPU for the target */
617     if (GetCPU () == CPU_UNKNOWN) {
618         if (Target != TGT_UNKNOWN) {
619             SetCPU (DefaultCPU[Target]);
620         } else {
621             SetCPU (CPU_6502);
622         }
623     }
624
625     /* Intialize the target translation tables */
626     TgtTranslateInit ();
627
628     /* Initialize the scanner, open the input file */
629     InitScanner (InFile);
630
631     /* Define the default options */
632     SetOptions ();
633
634     /* Assemble the input */
635     Assemble ();
636
637     /* If we didn't have any errors, check the segment stack */
638     if (ErrorCount == 0) {
639         SegStackCheck ();
640     }
641
642     /* If we didn't have any errors, check the unnamed labels */
643     if (ErrorCount == 0) {
644         ULabCheck ();
645     }
646
647     /* If we didn't have any errors, check the symbol table */
648     if (ErrorCount == 0) {
649         SymCheck ();
650     }
651
652     /* If we didn't have any errors, check and resolve the segment data */
653     if (ErrorCount == 0) {
654         SegCheck ();
655     }
656
657     /* If we didn't have an errors, index the line infos */
658     MakeLineInfoIndex ();
659
660     /* Dump the data */
661     if (Verbosity >= 2) {
662         SymDump (stdout);
663         SegDump ();
664     }
665
666     /* If we didn't have any errors, create the object and listing files */
667     if (ErrorCount == 0) {
668         CreateObjFile ();
669         if (Listing) {
670             CreateListing ();
671         }
672     }
673
674     /* Close the input file */
675     DoneScanner ();
676
677     /* Return an apropriate exit code */
678     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
679 }
680
681
682