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