]> git.sur5r.net Git - cc65/blob - src/cc65/main.c
New target supervision
[cc65] / src / cc65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                             cc65 main program                             */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-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 <string.h>
38 #include <stdlib.h>
39 #include <errno.h>
40
41 /* common */
42 #include "abend.h"
43 #include "chartype.h"
44 #include "cmdline.h"
45 #include "cpu.h"
46 #include "debugflag.h"
47 #include "fname.h"
48 #include "print.h"
49 #include "segnames.h"
50 #include "target.h"
51 #include "tgttrans.h"
52 #include "version.h"
53 #include "xmalloc.h"
54
55 /* cc65 */
56 #include "asmcode.h"
57 #include "compile.h"
58 #include "codeopt.h"
59 #include "error.h"
60 #include "global.h"
61 #include "incpath.h"
62 #include "input.h"
63 #include "macrotab.h"
64 #include "scanner.h"
65 #include "segments.h"
66
67
68
69 /*****************************************************************************/
70 /*                                   Code                                    */
71 /*****************************************************************************/
72
73
74
75 static void Usage (void)
76 {
77     fprintf (stderr,
78              "Usage: %s [options] file\n"
79              "Short options:\n"
80              "  -A\t\t\tStrict ANSI mode\n"
81              "  -Cl\t\t\tMake local variables static\n"
82              "  -Dsym[=defn]\t\tDefine a symbol\n"
83              "  -I dir\t\tSet an include directory search path\n"
84              "  -O\t\t\tOptimize code\n"
85              "  -Oi\t\t\tOptimize code, inline more code\n"
86              "  -Or\t\t\tEnable register variables\n"
87              "  -Os\t\t\tInline some known functions\n"
88              "  -T\t\t\tInclude source as comment\n"
89              "  -V\t\t\tPrint the compiler version number\n"
90              "  -W\t\t\tSuppress warnings\n"
91              "  -d\t\t\tDebug mode\n"
92              "  -g\t\t\tAdd debug info to object file\n"
93              "  -h\t\t\tHelp (this text)\n"
94              "  -j\t\t\tDefault characters are signed\n"
95              "  -o name\t\tName the output file\n"
96              "  -r\t\t\tEnable register variables\n"
97              "  -t sys\t\tSet the target system\n"
98              "  -v\t\t\tIncrease verbosity\n"
99              "\n"
100              "Long options:\n"
101              "  --add-source\t\tInclude source as comment\n"
102              "  --ansi\t\tStrict ANSI mode\n"
103              "  --bss-name seg\tSet the name of the BSS segment\n"
104              "  --check-stack\t\tGenerate stack overflow checks\n"
105              "  --code-name seg\tSet the name of the CODE segment\n"
106              "  --codesize x\t\tAccept larger code by factor x\n"
107              "  --cpu type\t\tSet cpu type (6502, 65c02)\n"
108              "  --create-dep\t\tCreate a make dependency file\n"
109              "  --data-name seg\tSet the name of the DATA segment\n"
110              "  --debug\t\tDebug mode\n"
111              "  --debug-info\t\tAdd debug info to object file\n"
112              "  --debug-opt name\tDebug optimization steps\n"
113              "  --disable-opt name\tDisable an optimization step\n"
114              "  --enable-opt name\tEnable an optimization step\n"
115              "  --forget-inc-paths\tForget include search paths\n"
116              "  --help\t\tHelp (this text)\n"
117              "  --include-dir dir\tSet an include directory search path\n"
118              "  --list-opt-steps\tList all optimizer steps and exit\n"
119              "  --register-space b\tSet space available for register variables\n"
120              "  --register-vars\tEnable register variables\n"
121              "  --rodata-name seg\tSet the name of the RODATA segment\n"
122              "  --signed-chars\tDefault characters are signed\n"
123              "  --static-locals\tMake local variables static\n"
124              "  --target sys\t\tSet the target system\n"
125              "  --verbose\t\tIncrease verbosity\n"
126              "  --version\t\tPrint the compiler version number\n",
127              ProgName);
128 }
129
130
131
132 static void cbmsys (const char* sys)
133 /* Define a CBM system */
134 {
135     DefineNumericMacro ("__CBM__", 1);
136     DefineNumericMacro (sys, 1);
137 }
138
139
140
141 static void SetSys (const char* Sys)
142 /* Define a target system */
143 {
144     switch (Target = FindTarget (Sys)) {
145
146         case TGT_NONE:
147             break;
148
149         case TGT_MODULE:
150             AbEnd ("Cannot use `module' as a target for the compiler");
151             break;
152
153         case TGT_ATARI:
154             DefineNumericMacro ("__ATARI__", 1);
155             break;
156
157         case TGT_C16:
158             cbmsys ("__C16__");
159             break;
160
161         case TGT_C64:
162             cbmsys ("__C64__");
163             break;
164
165         case TGT_VIC20:
166             cbmsys ("__VIC20__");
167             break;
168
169         case TGT_C128:
170             cbmsys ("__C128__");
171             break;
172
173         case TGT_ACE:
174             cbmsys ("__ACE__");
175             break;
176
177         case TGT_PLUS4:
178             cbmsys ("__PLUS4__");
179             break;
180
181         case TGT_CBM510:
182             cbmsys ("__CBM510__");
183             break;
184
185         case TGT_CBM610:
186             cbmsys ("__CBM610__");
187             break;
188
189         case TGT_PET:
190             cbmsys ("__PET__");
191             break;
192
193         case TGT_BBC:
194             DefineNumericMacro ("__BBC__", 1);
195             break;
196
197         case TGT_APPLE2:
198             DefineNumericMacro ("__APPLE2__", 1);
199             break;
200
201         case TGT_GEOS:
202             /* Do not handle as a CBM system */
203             DefineNumericMacro ("__GEOS__", 1);
204             break;
205
206         case TGT_LUNIX:
207             DefineNumericMacro ("__LUNIX__", 1);
208             break;
209
210         case TGT_ATMOS:
211             DefineNumericMacro ("__ATMOS__", 1);
212             break;
213
214         case TGT_NES:
215             DefineNumericMacro ("__NES__", 1);
216             break;
217
218         case TGT_SUPERVISION:
219             DefineNumericMacro ("__SUPERVISION__", 1);
220             break;
221
222         default:    
223             AbEnd ("Unknown target system type %d", Target);
224     }
225
226     /* Initialize the translation tables for the target system */
227     TgtTranslateInit ();
228 }
229
230
231
232 static void DoCreateDep (const char* OutputName)
233 /* Create the dependency file */
234 {
235     /* Make the dependency file name from the output file name */
236     char* DepName = MakeFilename (OutputName, ".u");
237
238     /* Open the file */
239     FILE* F = fopen (DepName, "w");
240     if (F == 0) {
241         Fatal ("Cannot open dependency file `%s': %s", DepName, strerror (errno));
242     }
243
244     /* Write the dependencies to the file */
245     WriteDependencies (F, OutputName);
246
247     /* Close the file, check for errors */
248     if (fclose (F) != 0) {
249         remove (DepName);
250         Fatal ("Cannot write to dependeny file (disk full?)");
251     }
252
253     /* Free the name */
254     xfree (DepName);
255 }
256
257
258
259 static void DefineSym (const char* Def)
260 /* Define a symbol on the command line */
261 {
262     const char* P = Def;
263
264     /* The symbol must start with a character or underline */
265     if (Def [0] != '_' && !IsAlpha (Def [0])) {
266         InvDef (Def);
267     }
268
269     /* Check the symbol name */
270     while (IsAlNum (*P) || *P == '_') {
271         ++P;
272     }
273
274     /* Do we have a value given? */
275     if (*P != '=') {
276         if (*P != '\0') {
277             InvDef (Def);
278         }
279         /* No value given. Define the macro with the value 1 */
280         DefineNumericMacro (Def, 1);
281     } else {
282         /* We have a value, P points to the '=' character. Since the argument
283          * is const, create a copy and replace the '=' in the copy by a zero
284          * terminator.
285          */
286         char* Q;
287         unsigned Len = strlen (Def)+1;
288         char* S = (char*) xmalloc (Len);
289         memcpy (S, Def, Len);
290         Q = S + (P - Def);
291         *Q++ = '\0';
292
293         /* Define this as a macro */
294         DefineTextMacro (S, Q);
295
296         /* Release the allocated memory */
297         xfree (S);
298     }
299 }
300
301
302
303 static void CheckSegName (const char* Seg)
304 /* Abort if the given name is not a valid segment name */
305 {
306     /* Print an error and abort if the name is not ok */
307     if (!ValidSegName (Seg)) {
308         AbEnd ("Segment name `%s' is invalid", Seg);
309     }
310 }
311
312
313
314 static void OptAddSource (const char* Opt attribute ((unused)),
315                           const char* Arg attribute ((unused)))
316 /* Add source lines as comments in generated assembler file */
317 {
318     AddSource = 1;
319 }
320
321
322
323 static void OptAnsi (const char* Opt attribute ((unused)),
324                      const char* Arg attribute ((unused)))
325 /* Compile in strict ANSI mode */
326 {
327     ANSI = 1;
328 }
329
330
331
332 static void OptBssName (const char* Opt attribute ((unused)), const char* Arg)
333 /* Handle the --bss-name option */
334 {
335     /* Check for a valid name */
336     CheckSegName (Arg);
337
338     /* Set the name */
339     NewSegName (SEG_BSS, Arg);
340 }
341
342
343
344 static void OptCheckStack (const char* Opt attribute ((unused)),
345                            const char* Arg attribute ((unused)))
346 /* Handle the --check-stack option */
347 {
348     CheckStack = 1;
349 }
350
351
352
353 static void OptCodeName (const char* Opt attribute ((unused)), const char* Arg)
354 /* Handle the --code-name option */
355 {
356     /* Check for a valid name */
357     CheckSegName (Arg);
358
359     /* Set the name */
360     NewSegName (SEG_CODE, Arg);
361 }
362
363
364
365 static void OptCodeSize (const char* Opt, const char* Arg)
366 /* Handle the --codesize option */
367 {
368     /* Numeric argument expected */
369     if (sscanf (Arg, "%u", &CodeSizeFactor) != 1 ||
370         CodeSizeFactor < 100 ||
371         CodeSizeFactor > 1000) {
372         AbEnd ("Argument for %s is invalid", Opt);
373     }
374 }
375
376
377
378 static void OptCreateDep (const char* Opt attribute ((unused)),
379                           const char* Arg attribute ((unused)))
380 /* Handle the --create-dep option */
381 {
382     CreateDep = 1;
383 }
384
385
386
387 static void OptCPU (const char* Opt, const char* Arg)
388 /* Handle the --cpu option */
389 {
390     /* Find the CPU from the given name */
391     CPU = FindCPU (Arg);
392     if (CPU != CPU_6502 && CPU != CPU_65C02) {
393         AbEnd ("Invalid argument for %s: `%s'", Opt, Arg);
394     }
395 }
396
397
398
399 static void OptDataName (const char* Opt attribute ((unused)), const char* Arg)
400 /* Handle the --data-name option */
401 {
402     /* Check for a valid name */
403     CheckSegName (Arg);
404
405     /* Set the name */
406     NewSegName (SEG_DATA, Arg);
407 }
408
409
410
411 static void OptDebug (const char* Opt attribute ((unused)),
412                       const char* Arg attribute ((unused)))
413 /* Compiler debug mode */
414 {
415     ++Debug;
416 }
417
418
419
420 static void OptDebugInfo (const char* Opt attribute ((unused)),
421                           const char* Arg attribute ((unused)))
422 /* Add debug info to the object file */
423 {
424     DebugInfo = 1;
425 }
426
427
428
429 static void OptDebugOpt (const char* Opt attribute ((unused)), const char* Arg)
430 /* Debug optimization steps */
431 {
432     char Buf [128];
433     char* Line;
434
435     /* Open the file */
436     FILE* F = fopen (Arg, "r");
437     if (F == 0) {
438         AbEnd ("Cannot open `%s': %s", Arg, strerror (errno));
439     }
440
441     /* Read line by line, ignore empty lines and switch optimization
442      * steps on/off.
443      */
444     while (fgets (Buf, sizeof (Buf), F) != 0) {
445
446         /* Remove trailing control chars. This will also remove the
447          * trailing newline.
448          */
449         unsigned Len = strlen (Buf);
450         while (Len > 0 && IsControl (Buf[Len-1])) {
451             --Len;
452         }
453         Buf[Len] = '\0';
454
455         /* Get a pointer to the buffer and remove leading white space */
456         Line = Buf;
457         while (IsBlank (*Line)) {
458             ++Line;
459         }
460
461         /* Check the first character and enable/disable the step or
462          * ignore the line
463          */
464         switch (*Line) {
465
466             case '\0':
467             case '#':
468             case ';':
469                 /* Empty or comment line */
470                 continue;
471
472             case '-':
473                 DisableOpt (Line+1);
474                 break;
475
476             case '+':
477                 ++Line;
478                 /* FALLTHROUGH */
479
480             default:
481                 EnableOpt (Line);
482                 break;
483
484         }
485
486     }
487
488     /* Close the file, no error check here since we were just reading and
489      * this is only a debug function.
490      */
491     (void) fclose (F);
492 }
493
494
495
496 static void OptDisableOpt (const char* Opt attribute ((unused)), const char* Arg)
497 /* Disable an optimization step */
498 {
499     DisableOpt (Arg);
500 }
501
502
503
504 static void OptEnableOpt (const char* Opt attribute ((unused)), const char* Arg)
505 /* Enable an optimization step */
506 {
507     EnableOpt (Arg);
508 }
509
510
511
512 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
513                                const char* Arg attribute ((unused)))
514 /* Forget all currently defined include paths */
515 {
516     ForgetAllIncludePaths ();
517 }
518
519
520
521 static void OptHelp (const char* Opt attribute ((unused)),
522                      const char* Arg attribute ((unused)))
523 /* Print usage information and exit */
524 {
525     Usage ();
526     exit (EXIT_SUCCESS);
527 }
528
529
530
531 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
532 /* Add an include search path */
533 {
534     AddIncludePath (Arg, INC_SYS | INC_USER);
535 }
536
537
538
539 static void OptListOptSteps (const char* Opt attribute ((unused)),
540                              const char* Arg attribute ((unused)))
541 /* List all optimizer steps */
542 {
543     /* List the optimizer steps */
544     ListOptSteps (stdout);
545
546     /* Terminate */
547     exit (EXIT_SUCCESS);
548 }
549
550
551
552 static void OptRegisterSpace (const char* Opt, const char* Arg)
553 /* Handle the --register-space option */
554 {
555     /* Numeric argument expected */
556     if (sscanf (Arg, "%u", &RegisterSpace) != 1 || RegisterSpace > 256) {
557         AbEnd ("Argument for option %s is invalid", Opt);
558     }
559 }
560
561
562
563 static void OptRegisterVars (const char* Opt attribute ((unused)),
564                              const char* Arg attribute ((unused)))
565 /* Handle the --register-vars option */
566 {
567     EnableRegVars = 1;
568 }
569
570
571
572 static void OptRodataName (const char* Opt attribute ((unused)), const char* Arg)
573 /* Handle the --rodata-name option */
574 {
575     /* Check for a valid name */
576     CheckSegName (Arg);
577
578     /* Set the name */
579     NewSegName (SEG_RODATA, Arg);
580 }
581
582
583
584 static void OptSignedChars (const char* Opt attribute ((unused)),
585                             const char* Arg attribute ((unused)))
586 /* Make default characters signed */
587 {
588     SignedChars = 1;
589 }
590
591
592
593 static void OptStaticLocals (const char* Opt attribute ((unused)),
594                              const char* Arg attribute ((unused)))
595 /* Place local variables in static storage */
596 {
597     StaticLocals = 1;
598 }
599
600
601
602 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
603 /* Set the target system */
604 {
605     SetSys (Arg);
606 }
607
608
609
610 static void OptVerbose (const char* Opt attribute ((unused)),
611                         const char* Arg attribute ((unused)))
612 /* Increase verbosity */
613 {
614     ++Verbosity;
615 }
616
617
618
619 static void OptVersion (const char* Opt attribute ((unused)),
620                         const char* Arg attribute ((unused)))
621 /* Print the assembler version */
622 {
623     fprintf (stderr,
624              "cc65 V%u.%u.%u\n",
625              VER_MAJOR, VER_MINOR, VER_PATCH);
626 }
627
628
629
630 int main (int argc, char* argv[])
631 {
632     /* Program long options */
633     static const LongOpt OptTab[] = {
634         { "--add-source",       0,      OptAddSource            },
635         { "--ansi",             0,      OptAnsi                 },
636         { "--bss-name",         1,      OptBssName              },
637         { "--check-stack",      0,      OptCheckStack           },
638         { "--code-name",        1,      OptCodeName             },
639         { "--codesize",         1,      OptCodeSize             },
640         { "--cpu",              1,      OptCPU                  },
641         { "--create-dep",       0,      OptCreateDep            },
642         { "--data-name",        1,      OptDataName             },
643         { "--debug",            0,      OptDebug                },
644         { "--debug-info",       0,      OptDebugInfo            },
645         { "--debug-opt",        1,      OptDebugOpt             },
646         { "--disable-opt",      1,      OptDisableOpt           },
647         { "--enable-opt",       1,      OptEnableOpt            },
648         { "--forget-inc-paths", 0,      OptForgetIncPaths       },
649         { "--help",             0,      OptHelp                 },
650         { "--include-dir",      1,      OptIncludeDir           },
651         { "--list-opt-steps",   0,      OptListOptSteps         },
652         { "--register-space",   1,      OptRegisterSpace        },
653         { "--register-vars",    0,      OptRegisterVars         },
654         { "--rodata-name",      1,      OptRodataName           },
655         { "--signed-chars",     0,      OptSignedChars          },
656         { "--static-locals",    0,      OptStaticLocals         },
657         { "--target",           1,      OptTarget               },
658         { "--verbose",          0,      OptVerbose              },
659         { "--version",          0,      OptVersion              },
660     };
661
662     unsigned I;
663
664     /* Initialize the output file name */
665     const char* OutputFile = 0;
666     const char* InputFile  = 0;
667
668     /* Initialize the cmdline module */
669     InitCmdLine (&argc, &argv, "cc65");
670
671     /* Initialize the default segment names */
672     InitSegNames ();
673
674     /* Initialize the include search paths */
675     InitIncludePaths ();
676
677     /* Parse the command line */
678     I = 1;
679     while (I < ArgCount) {
680
681         const char* P;
682
683         /* Get the argument */
684         const char* Arg = ArgVec[I];
685
686         /* Check for an option */
687         if (Arg [0] == '-') {
688
689             switch (Arg [1]) {
690
691                 case '-':
692                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
693                     break;
694
695                 case 'd':
696                     OptDebug (Arg, 0);
697                     break;
698
699                 case 'h':
700                 case '?':
701                     OptHelp (Arg, 0);
702                     break;
703
704                 case 'g':
705                     OptDebugInfo (Arg, 0);
706                     break;
707
708                 case 'j':
709                     OptSignedChars (Arg, 0);
710                     break;
711
712                 case 'o':
713                     OutputFile = GetArg (&I, 2);
714                     break;
715
716                 case 'r':
717                     OptRegisterVars (Arg, 0);
718                     break;
719
720                 case 't':
721                     OptTarget (Arg, GetArg (&I, 2));
722                     break;
723
724                 case 'u':
725                     OptCreateDep (Arg, 0);
726                     break;
727
728                 case 'v':
729                     OptVerbose (Arg, 0);
730                     break;
731
732                 case 'A':
733                     OptAnsi (Arg, 0);
734                     break;
735
736                 case 'C':
737                     P = Arg + 2;
738                     while (*P) {
739                         switch (*P++) {
740                             case 'l':
741                                 OptStaticLocals (Arg, 0);
742                                 break;
743                             default:
744                                 UnknownOption (Arg);
745                                 break;
746                         }
747                     }
748                     break;
749
750                 case 'D':
751                     DefineSym (GetArg (&I, 2));
752                     break;
753
754                 case 'I':
755                     OptIncludeDir (Arg, GetArg (&I, 2));
756                     break;
757
758                 case 'O':
759                     Optimize = 1;
760                     P = Arg + 2;
761                     while (*P) {
762                         switch (*P++) {
763                             case 'f':
764                                 sscanf (P, "%lx", (long*) &OptDisable);
765                                 break;
766                             case 'i':
767                                 FavourSize = 0;
768                                 CodeSizeFactor = 200;
769                                 break;
770                             case 'r':
771                                 EnableRegVars = 1;
772                                 break;
773                             case 's':
774                                 InlineStdFuncs = 1;
775                                 break;
776                         }
777                     }
778                     break;
779
780                 case 'T':
781                     OptAddSource (Arg, 0);
782                     break;
783
784                 case 'V':
785                     OptVersion (Arg, 0);
786                     break;
787
788                 case 'W':
789                     NoWarn = 1;
790                     break;
791
792                 default:
793                     UnknownOption (Arg);
794                     break;
795             }
796         } else {
797             if (InputFile) {
798                 fprintf (stderr, "additional file specs ignored\n");
799             } else {
800                 InputFile = Arg;
801             }
802         }
803
804         /* Next argument */
805         ++I;
806     }
807
808     /* Did we have a file spec on the command line? */
809     if (InputFile == 0) {
810         AbEnd ("No input files");
811     }
812
813     /* Create the output file name if it was not explicitly given */
814     if (OutputFile == 0) {
815         OutputFile = MakeFilename (InputFile, ".s");
816     }
817
818     /* If no CPU given, use the default CPU for the target */
819     if (CPU == CPU_UNKNOWN) {
820         if (Target != TGT_UNKNOWN) {
821             CPU = DefaultCPU[Target];
822         } else {
823             CPU = CPU_6502;
824         }
825     }
826
827     /* Go! */
828     Compile (InputFile);
829
830     /* Create the output file if we didn't had any errors */
831     if (ErrorCount == 0 || Debug) {
832
833         /* Open the file */
834         FILE* F = fopen (OutputFile, "w");
835         if (F == 0) {
836             Fatal ("Cannot open output file `%s': %s", OutputFile, strerror (errno));
837         }
838
839         /* Write the output to the file */
840         WriteOutput (F);
841
842         /* Close the file, check for errors */
843         if (fclose (F) != 0) {
844             remove (OutputFile);
845             Fatal ("Cannot write to output file (disk full?)");
846         }
847
848         /* Create dependencies if requested */
849         if (CreateDep) {
850             DoCreateDep (OutputFile);
851         }
852
853     }
854
855     /* Return an apropriate exit code */
856     return (ErrorCount > 0)? EXIT_FAILURE : EXIT_SUCCESS;
857 }
858
859
860