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