]> git.sur5r.net Git - cc65/blob - src/cc65/main.c
e7a68d502a827712ffa24acf38923429078c0a04
[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     CPU = FindCPU (Arg);
387     if (CPU != CPU_6502 && CPU != CPU_65C02) {
388         AbEnd ("Invalid argument for %s: `%s'", Opt, Arg);
389     }
390 }
391
392
393
394 static void OptDataName (const char* Opt attribute ((unused)), const char* Arg)
395 /* Handle the --data-name option */
396 {
397     /* Check for a valid name */
398     CheckSegName (Arg);
399
400     /* Set the name */
401     NewSegName (SEG_DATA, Arg);
402 }
403
404
405
406 static void OptDebug (const char* Opt attribute ((unused)),
407                       const char* Arg attribute ((unused)))
408 /* Compiler debug mode */
409 {
410     ++Debug;
411 }
412
413
414
415 static void OptDebugInfo (const char* Opt attribute ((unused)),
416                           const char* Arg attribute ((unused)))
417 /* Add debug info to the object file */
418 {
419     DebugInfo = 1;
420 }
421
422
423
424 static void OptDebugOpt (const char* Opt attribute ((unused)), const char* Arg)
425 /* Debug optimization steps */
426 {
427     char Buf [128];
428     char* Line;
429
430     /* Open the file */
431     FILE* F = fopen (Arg, "r");
432     if (F == 0) {
433         AbEnd ("Cannot open `%s': %s", Arg, strerror (errno));
434     }
435
436     /* Read line by line, ignore empty lines and switch optimization
437      * steps on/off.
438      */
439     while (fgets (Buf, sizeof (Buf), F) != 0) {
440
441         /* Remove trailing control chars. This will also remove the
442          * trailing newline.
443          */
444         unsigned Len = strlen (Buf);
445         while (Len > 0 && IsControl (Buf[Len-1])) {
446             --Len;
447         }
448         Buf[Len] = '\0';
449
450         /* Get a pointer to the buffer and remove leading white space */
451         Line = Buf;
452         while (IsBlank (*Line)) {
453             ++Line;
454         }
455
456         /* Check the first character and enable/disable the step or
457          * ignore the line
458          */
459         switch (*Line) {
460
461             case '\0':
462             case '#':
463             case ';':
464                 /* Empty or comment line */
465                 continue;
466
467             case '-':
468                 DisableOpt (Line+1);
469                 break;
470
471             case '+':
472                 ++Line;
473                 /* FALLTHROUGH */
474
475             default:
476                 EnableOpt (Line);
477                 break;
478
479         }
480
481     }
482
483     /* Close the file, no error check here since we were just reading and
484      * this is only a debug function.
485      */
486     (void) fclose (F);
487 }
488
489
490
491 static void OptDisableOpt (const char* Opt attribute ((unused)), const char* Arg)
492 /* Disable an optimization step */
493 {
494     DisableOpt (Arg);
495 }
496
497
498
499 static void OptEnableOpt (const char* Opt attribute ((unused)), const char* Arg)
500 /* Enable an optimization step */
501 {
502     EnableOpt (Arg);
503 }
504
505
506
507 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
508                                const char* Arg attribute ((unused)))
509 /* Forget all currently defined include paths */
510 {
511     ForgetAllIncludePaths ();
512 }
513
514
515
516 static void OptHelp (const char* Opt attribute ((unused)),
517                      const char* Arg attribute ((unused)))
518 /* Print usage information and exit */
519 {
520     Usage ();
521     exit (EXIT_SUCCESS);
522 }
523
524
525
526 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
527 /* Add an include search path */
528 {
529     AddIncludePath (Arg, INC_SYS | INC_USER);
530 }
531
532
533
534 static void OptListOptSteps (const char* Opt attribute ((unused)),
535                              const char* Arg attribute ((unused)))
536 /* List all optimizer steps */
537 {
538     /* List the optimizer steps */
539     ListOptSteps (stdout);
540
541     /* Terminate */
542     exit (EXIT_SUCCESS);
543 }
544
545
546
547 static void OptRegisterSpace (const char* Opt, const char* Arg)
548 /* Handle the --register-space option */
549 {
550     /* Numeric argument expected */
551     if (sscanf (Arg, "%u", &RegisterSpace) != 1 || RegisterSpace > 256) {
552         AbEnd ("Argument for option %s is invalid", Opt);
553     }
554 }
555
556
557
558 static void OptRegisterVars (const char* Opt attribute ((unused)),
559                              const char* Arg attribute ((unused)))
560 /* Handle the --register-vars option */
561 {
562     EnableRegVars = 1;
563 }
564
565
566
567 static void OptRodataName (const char* Opt attribute ((unused)), const char* Arg)
568 /* Handle the --rodata-name option */
569 {
570     /* Check for a valid name */
571     CheckSegName (Arg);
572
573     /* Set the name */
574     NewSegName (SEG_RODATA, Arg);
575 }
576
577
578
579 static void OptSignedChars (const char* Opt attribute ((unused)),
580                             const char* Arg attribute ((unused)))
581 /* Make default characters signed */
582 {
583     SignedChars = 1;
584 }
585
586
587
588 static void OptStaticLocals (const char* Opt attribute ((unused)),
589                              const char* Arg attribute ((unused)))
590 /* Place local variables in static storage */
591 {
592     StaticLocals = 1;
593 }
594
595
596
597 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
598 /* Set the target system */
599 {
600     SetSys (Arg);
601 }
602
603
604
605 static void OptVerbose (const char* Opt attribute ((unused)),
606                         const char* Arg attribute ((unused)))
607 /* Increase verbosity */
608 {
609     ++Verbosity;
610 }
611
612
613
614 static void OptVersion (const char* Opt attribute ((unused)),
615                         const char* Arg attribute ((unused)))
616 /* Print the assembler version */
617 {
618     fprintf (stderr,
619              "cc65 V%u.%u.%u\n",
620              VER_MAJOR, VER_MINOR, VER_PATCH);
621 }
622
623
624
625 int main (int argc, char* argv[])
626 {
627     /* Program long options */
628     static const LongOpt OptTab[] = {
629         { "--add-source",       0,      OptAddSource            },
630         { "--ansi",             0,      OptAnsi                 },
631         { "--bss-name",         1,      OptBssName              },
632         { "--check-stack",      0,      OptCheckStack           },
633         { "--code-name",        1,      OptCodeName             },
634         { "--codesize",         1,      OptCodeSize             },
635         { "--cpu",              1,      OptCPU                  },
636         { "--create-dep",       0,      OptCreateDep            },
637         { "--data-name",        1,      OptDataName             },
638         { "--debug",            0,      OptDebug                },
639         { "--debug-info",       0,      OptDebugInfo            },
640         { "--debug-opt",        1,      OptDebugOpt             },
641         { "--disable-opt",      1,      OptDisableOpt           },
642         { "--enable-opt",       1,      OptEnableOpt            },
643         { "--forget-inc-paths", 0,      OptForgetIncPaths       },
644         { "--help",             0,      OptHelp                 },
645         { "--include-dir",      1,      OptIncludeDir           },
646         { "--list-opt-steps",   0,      OptListOptSteps         },
647         { "--register-space",   1,      OptRegisterSpace        },
648         { "--register-vars",    0,      OptRegisterVars         },
649         { "--rodata-name",      1,      OptRodataName           },
650         { "--signed-chars",     0,      OptSignedChars          },
651         { "--static-locals",    0,      OptStaticLocals         },
652         { "--target",           1,      OptTarget               },
653         { "--verbose",          0,      OptVerbose              },
654         { "--version",          0,      OptVersion              },
655     };
656
657     unsigned I;
658
659     /* Initialize the output file name */
660     const char* OutputFile = 0;
661     const char* InputFile  = 0;
662
663     /* Initialize the cmdline module */
664     InitCmdLine (&argc, &argv, "cc65");
665
666     /* Initialize the default segment names */
667     InitSegNames ();
668
669     /* Initialize the include search paths */
670     InitIncludePaths ();
671
672     /* Parse the command line */
673     I = 1;
674     while (I < ArgCount) {
675
676         const char* P;
677
678         /* Get the argument */
679         const char* Arg = ArgVec[I];
680
681         /* Check for an option */
682         if (Arg [0] == '-') {
683
684             switch (Arg [1]) {
685
686                 case '-':
687                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
688                     break;
689
690                 case 'd':
691                     OptDebug (Arg, 0);
692                     break;
693
694                 case 'h':
695                 case '?':
696                     OptHelp (Arg, 0);
697                     break;
698
699                 case 'g':
700                     OptDebugInfo (Arg, 0);
701                     break;
702
703                 case 'j':
704                     OptSignedChars (Arg, 0);
705                     break;
706
707                 case 'o':
708                     OutputFile = GetArg (&I, 2);
709                     break;
710
711                 case 'r':
712                     OptRegisterVars (Arg, 0);
713                     break;
714
715                 case 't':
716                     OptTarget (Arg, GetArg (&I, 2));
717                     break;
718
719                 case 'u':
720                     OptCreateDep (Arg, 0);
721                     break;
722
723                 case 'v':
724                     OptVerbose (Arg, 0);
725                     break;
726
727                 case 'A':
728                     OptAnsi (Arg, 0);
729                     break;
730
731                 case 'C':
732                     P = Arg + 2;
733                     while (*P) {
734                         switch (*P++) {
735                             case 'l':
736                                 OptStaticLocals (Arg, 0);
737                                 break;
738                             default:
739                                 UnknownOption (Arg);
740                                 break;
741                         }
742                     }
743                     break;
744
745                 case 'D':
746                     DefineSym (GetArg (&I, 2));
747                     break;
748
749                 case 'I':
750                     OptIncludeDir (Arg, GetArg (&I, 2));
751                     break;
752
753                 case 'O':
754                     Optimize = 1;
755                     P = Arg + 2;
756                     while (*P) {
757                         switch (*P++) {
758                             case 'f':
759                                 sscanf (P, "%lx", (long*) &OptDisable);
760                                 break;
761                             case 'i':
762                                 FavourSize = 0;
763                                 CodeSizeFactor = 200;
764                                 break;
765                             case 'r':
766                                 EnableRegVars = 1;
767                                 break;
768                             case 's':
769                                 InlineStdFuncs = 1;
770                                 break;
771                         }
772                     }
773                     break;
774
775                 case 'T':
776                     OptAddSource (Arg, 0);
777                     break;
778
779                 case 'V':
780                     OptVersion (Arg, 0);
781                     break;
782
783                 case 'W':
784                     NoWarn = 1;
785                     break;
786
787                 default:
788                     UnknownOption (Arg);
789                     break;
790             }
791         } else {
792             if (InputFile) {
793                 fprintf (stderr, "additional file specs ignored\n");
794             } else {
795                 InputFile = Arg;
796             }
797         }
798
799         /* Next argument */
800         ++I;
801     }
802
803     /* Did we have a file spec on the command line? */
804     if (InputFile == 0) {
805         AbEnd ("No input files");
806     }
807
808     /* Create the output file name if it was not explicitly given */
809     if (OutputFile == 0) {
810         OutputFile = MakeFilename (InputFile, ".s");
811     }
812
813     /* If no CPU given, use the default CPU for the target */
814     if (CPU == CPU_UNKNOWN) {
815         if (Target != TGT_UNKNOWN) {
816             CPU = DefaultCPU[Target];
817         } else {
818             CPU = CPU_6502;
819         }
820     }
821
822     /* Go! */
823     Compile (InputFile);
824
825     /* Create the output file if we didn't had any errors */
826     if (ErrorCount == 0 || Debug) {
827
828         /* Open the file */
829         FILE* F = fopen (OutputFile, "w");
830         if (F == 0) {
831             Fatal ("Cannot open output file `%s': %s", OutputFile, strerror (errno));
832         }
833
834         /* Write the output to the file */
835         WriteOutput (F);
836
837         /* Close the file, check for errors */
838         if (fclose (F) != 0) {
839             remove (OutputFile);
840             Fatal ("Cannot write to output file (disk full?)");
841         }
842
843         /* Create dependencies if requested */
844         if (CreateDep) {
845             DoCreateDep (OutputFile);
846         }
847
848     }
849
850     /* Return an apropriate exit code */
851     return (ErrorCount > 0)? EXIT_FAILURE : EXIT_SUCCESS;
852 }
853
854
855