]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
New --list-bytes option
[cc65] / src / ca65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                 Main program for the ca65 macroassembler                  */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2004 Ullrich von Bassewitz                                       */
10 /*               Römerstraße 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 "addrsize.h"
43 #include "chartype.h"
44 #include "cmdline.h"
45 #include "mmodel.h"
46 #include "print.h"
47 #include "target.h"
48 #include "tgttrans.h"
49 #include "version.h"
50
51 /* ca65 */
52 #include "abend.h"
53 #include "asserts.h"
54 #include "error.h"
55 #include "expr.h"
56 #include "feature.h"
57 #include "filetab.h"
58 #include "global.h"
59 #include "incpath.h"
60 #include "instr.h"
61 #include "istack.h"
62 #include "lineinfo.h"
63 #include "listing.h"
64 #include "macro.h"
65 #include "nexttok.h"
66 #include "objfile.h"
67 #include "options.h"
68 #include "pseudo.h"
69 #include "scanner.h"
70 #include "segment.h"
71 #include "sizeof.h"
72 #include "spool.h"
73 #include "symtab.h"
74 #include "ulabel.h"
75
76
77
78 /*****************************************************************************/
79 /*                                   Code                                    */
80 /*****************************************************************************/
81
82
83
84 static void Usage (void)
85 /* Print usage information and exit */
86 {
87     fprintf (stderr,
88              "Usage: %s [options] file\n"
89              "Short options:\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              "  -g\t\t\tAdd debug info to object file\n"
96              "  -h\t\t\tHelp (this text)\n"
97              "  -i\t\t\tIgnore case of symbols\n"
98              "  -l\t\t\tCreate a listing if assembly was ok\n"
99              "  -mm model\t\tSet the memory model\n"
100              "  -o name\t\tName the output file\n"
101              "  -s\t\t\tEnable smart mode\n"
102              "  -t sys\t\tSet the target system\n"
103              "  -v\t\t\tIncrease verbosity\n"
104              "\n"
105              "Long options:\n"
106              "  --auto-import\t\tMark unresolved symbols as import\n"
107              "  --cpu type\t\tSet cpu type\n"
108              "  --debug-info\t\tAdd debug info to object file\n"
109              "  --feature name\tSet an emulation feature\n"
110              "  --help\t\tHelp (this text)\n"
111              "  --ignore-case\t\tIgnore case of symbols\n"
112              "  --include-dir dir\tSet an include directory search path\n"
113              "  --listing\t\tCreate a listing if assembly was ok\n"
114              "  --list-bytes n\tMaximum number of bytes per listing line\n"
115              "  --memory-model model\tSet the memory model\n"
116              "  --pagelength n\tSet the page length for the listing\n"
117              "  --smart\t\tEnable smart mode\n"
118              "  --target sys\t\tSet the target system\n"
119              "  --verbose\t\tIncrease verbosity\n"
120              "  --version\t\tPrint the assembler version\n",
121              ProgName);
122 }
123
124
125
126 static void SetOptions (void)
127 /* Set the option for the translator */
128 {
129     char Buf [256];
130
131     /* Set the translator */
132     sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
133     OptTranslator (Buf);
134
135     /* Set date and time */
136     OptDateTime ((unsigned long) time(0));
137 }
138
139
140
141 static void DefineSymbol (const char* Def)
142 /* Define a symbol from the command line */
143 {
144     const char* P;
145     unsigned I;
146     long Val;
147     char SymName [MAX_STR_LEN+1];
148     SymEntry* Sym;
149     ExprNode* Expr;
150
151
152     /* The symbol must start with a character or underline */
153     if (Def [0] != '_' && !IsAlpha (Def [0])) {
154         InvDef (Def);
155     }
156     P = Def;
157
158     /* Copy the symbol, checking the rest */
159     I = 0;
160     while (IsAlNum (*P) || *P == '_') {
161         if (I <= MAX_STR_LEN) {
162             SymName [I++] = *P;
163         }
164         ++P;
165     }
166     SymName [I] = '\0';
167
168     /* Do we have a value given? */
169     if (*P != '=') {
170         if (*P != '\0') {
171             InvDef (Def);
172         }
173         Val = 0;
174     } else {
175         /* We have a value */
176         ++P;
177         if (*P == '$') {
178             ++P;
179             if (sscanf (P, "%lx", &Val) != 1) {
180                 InvDef (Def);
181             }
182         } else {
183             if (sscanf (P, "%li", &Val) != 1) {
184                 InvDef (Def);
185             }
186         }
187     }
188
189     /* Search for the symbol, allocate a new one if it doesn't exist */
190     Sym = SymFind (CurrentScope, SymName, SYM_ALLOC_NEW);
191
192     /* Check if have already a symbol with this name */
193     if (SymIsDef (Sym)) {
194         AbEnd ("`%s' is already defined", SymName);
195     }
196
197     /* Generate an expression for the symbol */
198     Expr = GenLiteralExpr (Val);
199
200     /* Mark the symbol as defined */
201     SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
202 }
203
204
205
206 static void OptAutoImport (const char* Opt attribute ((unused)),
207                            const char* Arg attribute ((unused)))
208 /* Mark unresolved symbols as imported */
209 {
210     AutoImport = 1;
211 }
212
213
214
215 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
216 /* Handle the --cpu option */
217 {
218     cpu_t CPU = FindCPU (Arg);
219     if (CPU == CPU_UNKNOWN) {
220         AbEnd ("Invalid CPU: `%s'", Arg);
221     } else {
222         SetCPU (CPU);
223     }
224 }
225
226
227
228 static void OptDebugInfo (const char* Opt attribute ((unused)),
229                           const char* Arg attribute ((unused)))
230 /* Add debug info to the object file */
231 {
232     DbgSyms = 1;
233 }
234
235
236
237 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
238 /* Set an emulation feature */
239 {
240     /* Set the feature, check for errors */
241     if (SetFeature (Arg) == FEAT_UNKNOWN) {
242         AbEnd ("Illegal emulation feature: `%s'", Arg);
243     }
244 }
245
246
247
248 static void OptHelp (const char* Opt attribute ((unused)),
249                      const char* Arg attribute ((unused)))
250 /* Print usage information and exit */
251 {
252     Usage ();
253     exit (EXIT_SUCCESS);
254 }
255
256
257
258 static void OptIgnoreCase (const char* Opt attribute ((unused)),
259                            const char* Arg attribute ((unused)))
260 /* Ignore case on symbols */
261 {
262     IgnoreCase = 1;
263 }
264
265
266
267 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
268 /* Add an include search path */
269 {
270     AddIncludePath (Arg);
271 }
272
273
274
275 static void OptListBytes (const char* Opt, const char* Arg)
276 /* Set the maximum number of bytes per listing line */
277 {
278     unsigned Num;
279     char     Check;
280
281     /* Convert the argument to a number */
282     if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
283         AbEnd ("Invalid argument for option `%s'", Opt);
284     }
285
286     /* Check the bounds */
287     if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
288         AbEnd ("Argument for option `%s' is out of range", Opt);
289     }
290
291     /* Use the value */
292     SetListBytes (Num);
293 }
294
295
296
297 static void OptListing (const char* Opt attribute ((unused)),
298                         const char* Arg attribute ((unused)))
299 /* Create a listing file */
300 {
301     Listing = 1;
302 }
303
304
305
306 static void OptMemoryModel (const char* Opt, const char* Arg)
307 /* Set the memory model */
308 {
309     mmodel_t M;
310
311     /* Check the current memory model */
312     if (MemoryModel != MMODEL_UNKNOWN) {
313         AbEnd ("Cannot use option `%s' twice", Opt);
314     }
315
316     /* Translate the memory model name and check it */
317     M = FindMemoryModel (Arg);
318     if (M == MMODEL_UNKNOWN) {
319         AbEnd ("Unknown memory model: %s", Arg);
320     } else if (M == MMODEL_HUGE) {
321         AbEnd ("Unsupported memory model: %s", Arg);
322     }
323
324     /* Set the memory model */
325     SetMemoryModel (M);
326 }
327
328
329
330 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
331 /* Handle the --pagelength option */
332 {
333     int Len = atoi (Arg);
334     if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
335         AbEnd ("Invalid page length: %d", Len);
336     }
337     PageLength = Len;
338 }
339
340
341
342 static void OptSmart (const char* Opt attribute ((unused)),
343                       const char* Arg attribute ((unused)))
344 /* Handle the -s/--smart options */
345 {
346     SmartMode = 1;
347 }
348
349
350
351 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
352 /* Set the target system */
353 {
354     /* Map the target name to a target id */
355     Target = FindTarget (Arg);
356     if (Target == TGT_UNKNOWN) {
357         AbEnd ("Invalid target name: `%s'", Arg);
358     } else if (Target == TGT_MODULE) {
359         AbEnd ("Cannot use `module' as a target for the assembler");
360     }
361 }
362
363
364
365 static void OptVerbose (const char* Opt attribute ((unused)),
366                         const char* Arg attribute ((unused)))
367 /* Increase verbosity */
368 {
369     ++Verbosity;
370 }
371
372
373
374 static void OptVersion (const char* Opt attribute ((unused)),
375                         const char* Arg attribute ((unused)))
376 /* Print the assembler version */
377 {
378     fprintf (stderr,
379              "ca65 V%u.%u.%u - %s\n",
380              VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
381 }
382
383
384
385 static void DoPCAssign (void)
386 /* Start absolute code */
387 {
388     long PC = ConstExpression ();
389     if (PC < 0 || PC > 0xFFFFFF) {
390         Error ("Range error");
391     } else {
392         SetAbsPC (PC);
393     }
394 }
395
396
397
398 static void OneLine (void)
399 /* Assemble one line */
400 {
401     Segment*      Seg   = 0;
402     unsigned long PC    = 0;
403     SymEntry*     Sym   = 0;
404     int           Macro = 0;
405     int           Instr = -1;
406
407     /* Initialize the new listing line if we are actually reading from file
408      * and not from internally pushed input.
409      */
410     if (!HavePushedInput ()) {
411         InitListingLine ();
412     }
413
414     if (Tok == TOK_COLON) {
415         /* An unnamed label */
416         ULabDef ();
417         NextTok ();
418     }
419
420     /* If the first token on the line is an identifier, check for a macro or
421      * an instruction.
422      */
423     if (Tok == TOK_IDENT) {
424         if (!UbiquitousIdents) {
425             /* Macros and symbols cannot use instruction names */
426             Instr = FindInstruction (SVal);
427             if (Instr < 0) {
428                 Macro = IsMacro (SVal);
429             }
430         } else {
431             /* Macros and symbols may use the names of instructions */
432             Macro = IsMacro (SVal);
433         }
434     }
435
436     /* Handle an identifier */
437     if (Tok == TOK_LOCAL_IDENT || (Tok == TOK_IDENT && Instr < 0 && !Macro)) {
438
439         /* Did we have whitespace before the ident? */
440         int HadWS = WS;
441
442         /* Generate the symbol table entry, then skip the name */
443         if (Tok == TOK_IDENT) {
444             Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
445         } else {
446             Sym = SymFindLocal (SymLast, SVal, SYM_ALLOC_NEW);
447         }
448         NextTok ();
449
450         /* If a colon follows, this is a label definition. If there
451          * is no colon, it's an assignment.
452          */
453         if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
454             /* If it's an assign token, we have a label */
455             unsigned Flags = (Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
456             /* Skip the '=' */
457             NextTok ();
458             /* Define the symbol with the expression following the '=' */
459             SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
460             /* Don't allow anything after a symbol definition */
461             ConsumeSep ();
462             return;
463         } else {
464             /* A label. Remember the current segment, so we can later
465              * determine the size of the data stored under the label.
466              */
467             Seg = ActiveSeg;
468             PC  = GetPC ();
469
470             /* Define the label */
471             SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
472
473             /* Skip the colon. If NoColonLabels is enabled, allow labels
474              * without a colon if there is no whitespace before the
475              * identifier.
476              */
477             if (Tok != TOK_COLON) {
478                 if (HadWS || !NoColonLabels) {
479                     Error ("`:' expected");
480                     /* Try some smart error recovery */
481                     if (Tok == TOK_NAMESPACE) {
482                         NextTok ();
483                     }
484                 }
485             } else {
486                 /* Skip the colon */
487                 NextTok ();
488             }
489
490             /* If we come here, a new identifier may be waiting, which may
491              * be a macro or instruction.
492              */
493             if (Tok == TOK_IDENT) {
494                 if (!UbiquitousIdents) {
495                     /* Macros and symbols cannot use instruction names */
496                     Instr = FindInstruction (SVal);
497                     if (Instr < 0) {
498                         Macro = IsMacro (SVal);
499                     }
500                 } else {
501                     /* Macros and symbols may use the names of instructions */
502                     Macro = IsMacro (SVal);
503                 }
504             }
505         }
506     }
507
508     /* We've handled a possible label, now handle the remainder of the line */
509     if (Tok >= TOK_FIRSTPSEUDO && Tok <= TOK_LASTPSEUDO) {
510         /* A control command */
511         HandlePseudo ();
512     } else if (Macro) {
513         /* A macro expansion */
514         MacExpandStart ();
515     } else if (Instr >= 0 ||
516                (UbiquitousIdents && ((Instr = FindInstruction (SVal)) >= 0))) {
517         /* A mnemonic - assemble one instruction */
518         HandleInstruction (Instr);
519     } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
520         NextTok ();
521         if (Tok != TOK_EQ) {
522             Error ("`=' expected");
523             SkipUntilSep ();
524         } else {
525             /* Skip the equal sign */
526             NextTok ();
527             /* Enter absolute mode */
528             DoPCAssign ();
529         }
530     }
531
532     /* If we have defined a label, remember its size. Sym is also set by
533      * a symbol assignment, but in this case Done is false, so we don't
534      * come here.
535      */
536     if (Sym) {
537         unsigned long Size;
538         if (Seg == ActiveSeg) {
539             /* Same segment */
540             Size = GetPC () - PC;
541         } else {
542             /* The line has switched the segment */
543             Size = 0;
544         }
545         DefSizeOfSymbol (Sym, Size);
546     }
547
548     /* Line separator must come here */
549     ConsumeSep ();
550 }
551
552
553
554 static void Assemble (void)
555 /* Start the ball rolling ... */
556 {
557     /* Prime the pump */
558     NextTok ();
559
560     /* Assemble lines until end of file */
561     while (Tok != TOK_EOF) {
562         OneLine ();
563     }
564 }
565
566
567
568 static void CreateObjFile (void)
569 /* Create the object file */
570 {
571     /* Open the object, write the header */
572     ObjOpen ();
573
574     /* Write the object file options */
575     WriteOptions ();
576
577     /* Write the list of input files */
578     WriteFiles ();
579
580     /* Write the segment data to the file */
581     WriteSegments ();
582
583     /* Write the import list */
584     WriteImports ();
585
586     /* Write the export list */
587     WriteExports ();
588
589     /* Write debug symbols if requested */
590     WriteDbgSyms ();
591
592     /* Write line infos if requested */
593     WriteLineInfo ();
594
595     /* Write the string pool */
596     WriteStrPool ();
597
598     /* Write the assertions */
599     WriteAssertions ();
600
601     /* Write an updated header and close the file */
602     ObjClose ();
603 }
604
605
606
607 int main (int argc, char* argv [])
608 /* Assembler main program */
609 {
610     /* Program long options */
611     static const LongOpt OptTab[] = {
612         { "--auto-import",      0,      OptAutoImport           },
613         { "--cpu",              1,      OptCPU                  },
614         { "--debug-info",       0,      OptDebugInfo            },
615         { "--feature",          1,      OptFeature              },
616         { "--help",             0,      OptHelp                 },
617         { "--ignore-case",      0,      OptIgnoreCase           },
618         { "--include-dir",      1,      OptIncludeDir           },
619         { "--list-bytes",       1,      OptListBytes            },
620         { "--listing",          0,      OptListing              },
621         { "--memory-model",     1,      OptMemoryModel          },
622         { "--pagelength",       1,      OptPageLength           },
623         { "--smart",            0,      OptSmart                },
624         { "--target",           1,      OptTarget               },
625         { "--verbose",          0,      OptVerbose              },
626         { "--version",          0,      OptVersion              },
627     };
628
629     unsigned I;
630
631     /* Initialize the cmdline module */
632     InitCmdLine (&argc, &argv, "ca65");
633
634     /* Enter the base lexical level. We must do that here, since we may
635      * define symbols using -D.
636      */
637     SymEnterLevel ("", ST_GLOBAL, ADDR_SIZE_DEFAULT);
638
639     /* Check the parameters */
640     I = 1;
641     while (I < ArgCount) {
642
643         /* Get the argument */
644         const char* Arg = ArgVec [I];
645
646         /* Check for an option */
647         if (Arg[0] == '-') {
648             switch (Arg[1]) {
649
650                 case '-':
651                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
652                     break;
653
654                 case 'g':
655                     OptDebugInfo (Arg, 0);
656                     break;
657
658                 case 'h':
659                     OptHelp (Arg, 0);
660                     break;
661
662                 case 'i':
663                     OptIgnoreCase (Arg, 0);
664                     break;
665
666                 case 'l':
667                     OptListing (Arg, 0);
668                     break;
669
670                 case 'm':
671                     if (Arg[2] == 'm') {
672                         OptMemoryModel (Arg, GetArg (&I, 3));
673                     } else {
674                         UnknownOption (Arg);
675                     }
676                     break;
677
678                 case 'o':
679                     OutFile = GetArg (&I, 2);
680                     break;
681
682                 case 's':
683                     OptSmart (Arg, 0);
684                     break;
685
686                 case 't':
687                     OptTarget (Arg, GetArg (&I, 2));
688                     break;
689
690                 case 'v':
691                     OptVerbose (Arg, 0);
692                     break;
693
694                 case 'D':
695                     DefineSymbol (GetArg (&I, 2));
696                     break;
697
698                 case 'I':
699                     OptIncludeDir (Arg, GetArg (&I, 2));
700                     break;
701
702                 case 'U':
703                     OptAutoImport (Arg, 0);
704                     break;
705
706                 case 'V':
707                     OptVersion (Arg, 0);
708                     break;
709
710                 case 'W':
711                     WarnLevel = atoi (GetArg (&I, 2));
712                     break;
713
714                 default:
715                     UnknownOption (Arg);
716                     break;
717
718             }
719         } else {
720             /* Filename. Check if we already had one */
721             if (InFile) {
722                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
723                          ProgName, Arg);
724                 exit (EXIT_FAILURE);
725             } else {
726                 InFile = Arg;
727             }
728         }
729
730         /* Next argument */
731         ++I;
732     }
733
734     /* Do we have an input file? */
735     if (InFile == 0) {
736         fprintf (stderr, "%s: No input files\n", ProgName);
737         exit (EXIT_FAILURE);
738     }
739
740     /* If no CPU given, use the default CPU for the target */
741     if (GetCPU () == CPU_UNKNOWN) {
742         if (Target != TGT_UNKNOWN) {
743             SetCPU (DefaultCPU[Target]);
744         } else {
745             SetCPU (CPU_6502);
746         }
747     }
748
749     /* If no memory model was given, use the default */
750     if (MemoryModel == MMODEL_UNKNOWN) {
751         SetMemoryModel (MMODEL_NEAR);
752     }
753
754     /* Intialize the target translation tables */
755     TgtTranslateInit ();
756
757     /* Initialize the segments */
758     InitSegments ();
759
760     /* Initialize the scanner, open the input file */
761     InitScanner (InFile);
762
763     /* Define the default options */
764     SetOptions ();
765
766     /* Assemble the input */
767     Assemble ();
768
769     /* If we didn't have any errors, check the segment stack */
770     if (ErrorCount == 0) {
771         SegStackCheck ();
772     }
773
774     /* If we didn't have any errors, check the unnamed labels */
775     if (ErrorCount == 0) {
776         ULabCheck ();
777     }
778
779     /* If we didn't have any errors, check the symbol table */
780     if (ErrorCount == 0) {
781         SymCheck ();
782     }
783
784     /* If we didn't have any errors, check and resolve the segment data */
785     if (ErrorCount == 0) {
786         SegCheck ();
787     }
788
789     /* If we didn't have an errors, index the line infos */
790     MakeLineInfoIndex ();
791
792     /* Dump the data */
793     if (Verbosity >= 2) {
794         SymDump (stdout);
795         SegDump ();
796     }
797
798     /* If we didn't have any errors, create the object and listing files */
799     if (ErrorCount == 0) {
800         CreateObjFile ();
801         if (Listing) {
802             CreateListing ();
803         }
804     }
805
806     /* Close the input file */
807     DoneScanner ();
808
809     /* Return an apropriate exit code */
810     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
811 }
812
813
814