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