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