]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Add the label/equate bit to the exports and debug symbols
[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 "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 "symtab.h"
69 #include "ulabel.h"
70
71
72
73 /*****************************************************************************/
74 /*                                   Code                                    */
75 /*****************************************************************************/
76
77
78
79 static void Usage (void)
80 /* Print usage information and exit */
81 {
82     fprintf (stderr,
83              "Usage: %s [options] file\n"
84              "Short options:\n"
85              "  -g\t\t\tAdd debug info to object file\n"
86              "  -h\t\t\tHelp (this text)\n"
87              "  -i\t\t\tIgnore case of symbols\n"
88              "  -l\t\t\tCreate a listing if assembly was ok\n"
89              "  -o name\t\tName the output file\n"
90              "  -s\t\t\tEnable smart mode\n"
91              "  -t sys\t\tSet the target system\n"
92              "  -v\t\t\tIncrease verbosity\n"
93              "  -D name[=value]\tDefine a symbol\n"
94              "  -I dir\t\tSet an include directory search path\n"
95              "  -U\t\t\tMark unresolved symbols as import\n"
96              "  -V\t\t\tPrint the assembler version\n"
97              "  -W n\t\t\tSet warning level n\n"
98              "\n"
99              "Long options:\n"
100              "  --auto-import\t\tMark unresolved symbols as import\n"
101              "  --cpu type\t\tSet cpu type\n"
102              "  --debug-info\t\tAdd debug info to object file\n"
103              "  --feature name\tSet an emulation feature\n"
104              "  --help\t\tHelp (this text)\n"
105              "  --ignore-case\t\tIgnore case of symbols\n"
106              "  --include-dir dir\tSet an include directory search path\n"
107              "  --listing\t\tCreate a listing if assembly was ok\n"
108              "  --pagelength n\tSet the page length for the listing\n"
109              "  --smart\t\tEnable smart mode\n"
110              "  --target sys\t\tSet the target system\n"
111              "  --verbose\t\tIncrease verbosity\n"
112              "  --version\t\tPrint the assembler version\n",
113              ProgName);
114 }
115
116
117
118 static void SetOptions (void)
119 /* Set the option for the translator */
120 {
121     char Buf [256];
122
123     /* Set the translator */
124     sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
125     OptTranslator (Buf);
126
127     /* Set date and time */
128     OptDateTime ((unsigned long) time(0));
129 }
130
131
132
133 static void DefineSymbol (const char* Def)
134 /* Define a symbol from the command line */
135 {
136     const char* P;
137     unsigned I;
138     long Val;
139     char SymName [MAX_STR_LEN+1];
140
141     /* The symbol must start with a character or underline */
142     if (Def [0] != '_' && !IsAlpha (Def [0])) {
143         InvDef (Def);
144     }
145     P = Def;
146
147     /* Copy the symbol, checking the rest */
148     I = 0;
149     while (IsAlNum (*P) || *P == '_') {
150         if (I <= MAX_STR_LEN) {
151             SymName [I++] = *P;
152         }
153         ++P;
154     }
155     SymName [I] = '\0';
156
157     /* Do we have a value given? */
158     if (*P != '=') {
159         if (*P != '\0') {
160             InvDef (Def);
161         }
162         Val = 0;
163     } else {
164         /* We have a value */
165         ++P;
166         if (*P == '$') {
167             ++P;
168             if (sscanf (P, "%lx", &Val) != 1) {
169                 InvDef (Def);
170             }
171         } else {
172             if (sscanf (P, "%li", &Val) != 1) {
173                 InvDef (Def);
174             }
175         }
176     }
177
178     /* Check if have already a symbol with this name */
179     if (SymIsDef (SymName)) {
180         AbEnd ("`%s' is already defined", SymName);
181     }
182
183     /* Define the symbol */
184     SymDef (SymName, LiteralExpr (Val), 0, 0);
185 }
186
187
188
189 static void OptAutoImport (const char* Opt, const char* Arg)
190 /* Mark unresolved symbols as imported */
191 {
192     AutoImport = 1;
193 }
194
195
196
197 static void OptCPU (const char* Opt, const char* Arg)
198 /* Handle the --cpu option */
199 {
200     if (Arg == 0) {
201         NeedArg (Opt);
202     }
203     if (strcmp (Arg, "6502") == 0) {
204         SetCPU (CPU_6502);
205     } else if (strcmp (Arg, "65C02") == 0) {
206         SetCPU (CPU_65C02);
207     } else if (strcmp (Arg, "65816") == 0) {
208         SetCPU (CPU_65816);
209 #ifdef SUNPLUS
210     } else if (strcmp (Arg, "sunplus") == 0) {
211         SetCPU (CPU_SUNPLUS);
212 #endif
213     } else {
214         AbEnd ("Invalid CPU: `%s'", Arg);
215     }
216 }
217
218
219
220 static void OptDebugInfo (const char* Opt, const char* Arg)
221 /* Add debug info to the object file */
222 {
223     DbgSyms = 1;
224 }
225
226
227
228 static void OptFeature (const char* Opt, 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, const char* Arg)
240 /* Print usage information and exit */
241 {
242     Usage ();
243     exit (EXIT_SUCCESS);
244 }
245
246
247
248 static void OptIgnoreCase (const char* Opt, const char* Arg)
249 /* Ignore case on symbols */
250 {
251     IgnoreCase = 1;
252 }
253
254
255
256 static void OptIncludeDir (const char* Opt, const char* Arg)
257 /* Add an include search path */
258 {
259     if (Arg == 0) {
260         NeedArg (Opt);
261     }
262     AddIncludePath (Arg);
263 }
264
265
266
267 static void OptListing (const char* Opt, const char* Arg)
268 /* Create a listing file */
269 {
270     Listing = 1;
271 }
272
273
274
275 static void OptPageLength (const char* Opt, const char* Arg)
276 /* Handle the --pagelength option */
277 {
278     int Len;
279     if (Arg == 0) {
280         NeedArg (Opt);
281     }
282     Len = atoi (Arg);
283     if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
284         AbEnd ("Invalid page length: %d", Len);
285     }
286     PageLength = Len;
287 }
288
289
290
291 static void OptSmart (const char* Opt, const char* Arg)
292 /* Handle the -s/--smart options */
293 {
294     SmartMode = 1;
295 }
296
297
298
299 static void OptTarget (const char* Opt, const char* Arg)
300 /* Set the target system */
301 {
302     if (Arg == 0) {
303         NeedArg (Opt);
304     }
305
306     /* Map the target name to a target id */
307     Target = FindTarget (Arg);
308     if (Target == TGT_UNKNOWN) {
309         AbEnd ("Invalid target name: `%s'", Arg);
310     }
311 }
312
313
314
315 static void OptVerbose (const char* Opt, const char* Arg)
316 /* Increase verbosity */
317 {
318     ++Verbosity;
319 }
320
321
322
323 static void OptVersion (const char* Opt, const char* Arg)
324 /* Print the assembler version */
325 {
326     fprintf (stderr,
327              "ca65 V%u.%u.%u - (C) Copyright 1998-2000 Ullrich von Bassewitz\n",
328              VER_MAJOR, VER_MINOR, VER_PATCH);
329 }
330
331
332
333 static void DoPCAssign (void)
334 /* Start absolute code */
335 {
336     long PC = ConstExpression ();
337     if (PC < 0 || PC > 0xFFFFFF) {
338         Error (ERR_RANGE);
339     } else {
340         SetAbsPC (PC);
341     }
342 }
343
344
345
346 static void OneLine (void)
347 /* Assemble one line */
348 {
349     char Ident [MAX_STR_LEN+1];
350     int Done = 0;
351
352     /* Initialize the new listing line if we are actually reading from file
353      * and not from internally pushed input.
354      */
355     if (!HavePushedInput ()) {
356         InitListingLine ();
357     }
358
359     if (Tok == TOK_COLON) {
360         /* An unnamed label */
361         ULabDef ();
362         NextTok ();
363     }
364
365     /* Assemble the line */
366     if (Tok == TOK_IDENT) {
367
368         /* Is it a macro? */
369         if (IsMacro (SVal)) {
370
371             /* Yes, start a macro expansion */
372             MacExpandStart ();
373             Done = 1;
374
375         } else {
376
377             /* No, label. Remember the identifier, then skip it */
378             int HadWS = WS;     /* Did we have whitespace before the ident? */
379             strcpy (Ident, SVal);
380             NextTok ();
381
382             /* If a colon follows, this is a label definition. If there
383              * is no colon, it's an assignment.
384              */
385             if (Tok == TOK_EQ) {
386                 /* Skip the '=' */
387                 NextTok ();
388                 /* Define the symbol with the expression following the '=' */
389                 SymDef (Ident, Expression(), 0, 0);
390                 /* Don't allow anything after a symbol definition */
391                 Done = 1;
392             } else {
393                 /* Define a label */
394                 SymDef (Ident, CurrentPC(), IsZPSeg(), 1);
395                 /* Skip the colon. If NoColonLabels is enabled, allow labels
396                  * without a colon if there is no whitespace before the
397                  * identifier.
398                  */
399                 if (Tok != TOK_COLON) {
400                     if (HadWS || !NoColonLabels) {
401                         Error (ERR_COLON_EXPECTED);
402                     }
403                     if (Tok == TOK_NAMESPACE) {
404                         /* Smart :: handling */
405                         NextTok ();
406                     }
407                 } else {
408                     /* Skip the colon */
409                     NextTok ();
410                 }
411             }
412         }
413     }
414
415     if (!Done) {
416
417         if (TokIsPseudo (Tok)) {
418             /* A control command, IVal is index into table */
419             HandlePseudo ();
420         } else if (Tok == TOK_MNEMO) {
421             /* A mnemonic - assemble one instruction */
422             HandleInstruction (IVal);
423         } else if (Tok == TOK_IDENT && IsMacro (SVal)) {
424             /* A macro expansion */
425             MacExpandStart ();
426         } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
427             NextTok ();
428             if (Tok != TOK_EQ) {
429                 Error (ERR_EQ_EXPECTED);
430                 SkipUntilSep ();
431             } else {
432                 /* Skip the equal sign */
433                 NextTok ();
434                 /* Enter absolute mode */
435                 DoPCAssign ();
436             }
437         }
438     }
439
440     /* Line separator must come here */
441     ConsumeSep ();
442 }
443
444
445
446 static void Assemble (void)
447 /* Start the ball rolling ... */
448 {
449     /* Prime the pump */
450     NextTok ();
451
452     /* Assemble lines until end of file */
453     while (Tok != TOK_EOF) {
454         OneLine ();
455     }
456 }
457
458
459
460 static void CreateObjFile (void)
461 /* Create the object file */
462 {
463     /* Open the object, write the header */
464     ObjOpen ();
465
466     /* Write the object file options */
467     WriteOptions ();
468
469     /* Write the list of input files */
470     WriteFiles ();
471
472     /* Write the segment data to the file */
473     WriteSegments ();
474
475     /* Write the import list */
476     WriteImports ();
477
478     /* Write the export list */
479     WriteExports ();
480
481     /* Write debug symbols if requested */
482     WriteDbgSyms ();
483
484     /* Write line infos if requested */
485     WriteLineInfo ();
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     int 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     /* Intialize the target translation tables */
617     TgtTranslateInit ();
618
619     /* Initialize the scanner, open the input file */
620     InitScanner (InFile);
621
622     /* Define the default options */
623     SetOptions ();
624
625     /* Assemble the input */
626     Assemble ();
627
628     /* If we didn't have any errors, check the unnamed labels */
629     if (ErrorCount == 0) {
630         ULabCheck ();
631     }
632
633     /* If we didn't have any errors, check the symbol table */
634     if (ErrorCount == 0) {
635         SymCheck ();
636     }
637
638     /* If we didn't have any errors, check and resolve the segment data */
639     if (ErrorCount == 0) {
640         SegCheck ();
641     }
642
643     /* If we didn't have an errors, index the line infos */
644     MakeLineInfoIndex ();
645
646     /* Dump the data */
647     if (Verbosity >= 2) {
648         SymDump (stdout);
649         SegDump ();
650     }
651
652     /* If we didn't have any errors, create the object and listing files */
653     if (ErrorCount == 0) {
654         CreateObjFile ();
655         if (Listing) {
656             CreateListing ();
657         }
658     }
659
660     /* Close the input file */
661     DoneScanner ();
662
663     /* Return an apropriate exit code */
664     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
665 }
666
667
668