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