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