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