]> git.sur5r.net Git - cc65/blob - src/cc65/main.c
a79bc98839e81376727c8007046cdbf04e140504
[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 "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\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              "  --help\t\tHelp (this text)\n"
116              "  --include-dir dir\tSet an include directory search path\n"
117              "  --list-opt-steps\tList all optimizer steps and exit\n"
118              "  --register-space b\tSet space available for register variables\n"
119              "  --register-vars\tEnable register variables\n"
120              "  --rodata-name seg\tSet the name of the RODATA segment\n"
121              "  --signed-chars\tDefault characters are signed\n"
122              "  --static-locals\tMake local variables static\n"
123              "  --target sys\t\tSet the target system\n"
124              "  --verbose\t\tIncrease verbosity\n"
125              "  --version\t\tPrint the compiler version number\n",
126              ProgName);
127 }
128
129
130
131 static void cbmsys (const char* sys)
132 /* Define a CBM system */
133 {
134     DefineNumericMacro ("__CBM__", 1);
135     DefineNumericMacro (sys, 1);
136 }
137
138
139
140 static void SetSys (const char* Sys)
141 /* Define a target system */
142 {
143     switch (Target = FindTarget (Sys)) {
144
145         case TGT_NONE:
146             break;
147
148         case TGT_MODULE:
149             AbEnd ("Cannot use `module' as a target for the compiler");
150             break;
151
152         case TGT_ATARI:
153             DefineNumericMacro ("__ATARI__", 1);
154             break;
155
156         case TGT_C16:
157             cbmsys ("__C16__");
158             break;
159
160         case TGT_C64:
161             cbmsys ("__C64__");
162             break;
163
164         case TGT_VIC20:
165             cbmsys ("__VIC20__");
166             break;
167
168         case TGT_C128:
169             cbmsys ("__C128__");
170             break;
171
172         case TGT_ACE:
173             cbmsys ("__ACE__");
174             break;
175
176         case TGT_PLUS4:
177             cbmsys ("__PLUS4__");
178             break;
179
180         case TGT_CBM510:
181             cbmsys ("__CBM510__");
182             break;
183
184         case TGT_CBM610:
185             cbmsys ("__CBM610__");
186             break;
187
188         case TGT_PET:
189             cbmsys ("__PET__");
190             break;
191
192         case TGT_BBC:
193             DefineNumericMacro ("__BBC__", 1);
194             break;
195
196         case TGT_APPLE2:
197             DefineNumericMacro ("__APPLE2__", 1);
198             break;
199
200         case TGT_GEOS:
201             /* Do not handle as a CBM system */
202             DefineNumericMacro ("__GEOS__", 1);
203             break;
204
205         case TGT_LUNIX:
206             DefineNumericMacro ("__LUNIX__", 1);
207             break;
208
209         case TGT_ATMOS:
210             DefineNumericMacro ("__ATMOS__", 1);
211             break;
212
213         default:
214             AbEnd ("Unknown target system type");
215     }
216
217     /* Initialize the translation tables for the target system */
218     TgtTranslateInit ();
219 }
220
221
222
223 static void DoCreateDep (const char* OutputName)
224 /* Create the dependency file */
225 {
226     /* Make the dependency file name from the output file name */
227     char* DepName = MakeFilename (OutputName, ".u");
228
229     /* Open the file */
230     FILE* F = fopen (DepName, "w");
231     if (F == 0) {
232         Fatal ("Cannot open dependency file `%s': %s", DepName, strerror (errno));
233     }
234
235     /* Write the dependencies to the file */
236     WriteDependencies (F, OutputName);
237
238     /* Close the file, check for errors */
239     if (fclose (F) != 0) {
240         remove (DepName);
241         Fatal ("Cannot write to dependeny file (disk full?)");
242     }
243
244     /* Free the name */
245     xfree (DepName);
246 }
247
248
249
250 static void DefineSym (const char* Def)
251 /* Define a symbol on the command line */
252 {
253     const char* P = Def;
254
255     /* The symbol must start with a character or underline */
256     if (Def [0] != '_' && !IsAlpha (Def [0])) {
257         InvDef (Def);
258     }
259
260     /* Check the symbol name */
261     while (IsAlNum (*P) || *P == '_') {
262         ++P;
263     }
264
265     /* Do we have a value given? */
266     if (*P != '=') {
267         if (*P != '\0') {
268             InvDef (Def);
269         }
270         /* No value given. Define the macro with the value 1 */
271         DefineNumericMacro (Def, 1);
272     } else {
273         /* We have a value, P points to the '=' character. Since the argument
274          * is const, create a copy and replace the '=' in the copy by a zero
275          * terminator.
276          */
277         char* Q;
278         unsigned Len = strlen (Def)+1;
279         char* S = (char*) xmalloc (Len);
280         memcpy (S, Def, Len);
281         Q = S + (P - Def);
282         *Q++ = '\0';
283
284         /* Define this as a macro */
285         DefineTextMacro (S, Q);
286
287         /* Release the allocated memory */
288         xfree (S);
289     }
290 }
291
292
293
294 static void CheckSegName (const char* Seg)
295 /* Abort if the given name is not a valid segment name */
296 {
297     /* Print an error and abort if the name is not ok */
298     if (!ValidSegName (Seg)) {
299         AbEnd ("Segment name `%s' is invalid", Seg);
300     }
301 }
302
303
304
305 static void OptAddSource (const char* Opt attribute ((unused)),
306                           const char* Arg attribute ((unused)))
307 /* Add source lines as comments in generated assembler file */
308 {
309     AddSource = 1;
310 }
311
312
313
314 static void OptAnsi (const char* Opt attribute ((unused)),
315                      const char* Arg attribute ((unused)))
316 /* Compile in strict ANSI mode */
317 {
318     ANSI = 1;
319 }
320
321
322
323 static void OptBssName (const char* Opt attribute ((unused)), const char* Arg)
324 /* Handle the --bss-name option */
325 {
326     /* Check for a valid name */
327     CheckSegName (Arg);
328
329     /* Set the name */
330     NewSegName (SEG_BSS, Arg);
331 }
332
333
334
335 static void OptCheckStack (const char* Opt attribute ((unused)),
336                            const char* Arg attribute ((unused)))
337 /* Handle the --check-stack option */
338 {
339     CheckStack = 1;
340 }
341
342
343
344 static void OptCodeName (const char* Opt attribute ((unused)), const char* Arg)
345 /* Handle the --code-name option */
346 {
347     /* Check for a valid name */
348     CheckSegName (Arg);
349
350     /* Set the name */
351     NewSegName (SEG_CODE, Arg);
352 }
353
354
355
356 static void OptCodeSize (const char* Opt, const char* Arg)
357 /* Handle the --codesize option */
358 {
359     /* Numeric argument expected */
360     if (sscanf (Arg, "%u", &CodeSizeFactor) != 1 ||
361         CodeSizeFactor < 100 ||
362         CodeSizeFactor > 1000) {
363         AbEnd ("Argument for %s is invalid", Opt);
364     }
365 }
366
367
368
369 static void OptCreateDep (const char* Opt attribute ((unused)),
370                           const char* Arg attribute ((unused)))
371 /* Handle the --create-dep option */
372 {
373     CreateDep = 1;
374 }
375
376
377
378 static void OptCPU (const char* Opt, const char* Arg)
379 /* Handle the --cpu option */
380 {
381     CPU = FindCPU (Arg);
382     if (CPU != CPU_6502 && CPU != CPU_65C02) {
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;
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 OptRegisterSpace (const char* Opt, const char* Arg)
534 /* Handle the --register-space option */
535 {
536     /* Numeric argument expected */
537     if (sscanf (Arg, "%u", &RegisterSpace) != 1 || RegisterSpace > 256) {
538         AbEnd ("Argument for option %s is invalid", Opt);
539     }
540 }
541
542
543
544 static void OptRegisterVars (const char* Opt attribute ((unused)),
545                              const char* Arg attribute ((unused)))
546 /* Handle the --register-vars option */
547 {
548     EnableRegVars = 1;
549 }
550
551
552
553 static void OptRodataName (const char* Opt attribute ((unused)), const char* Arg)
554 /* Handle the --rodata-name option */
555 {
556     /* Check for a valid name */
557     CheckSegName (Arg);
558
559     /* Set the name */
560     NewSegName (SEG_RODATA, Arg);
561 }
562
563
564
565 static void OptSignedChars (const char* Opt attribute ((unused)),
566                             const char* Arg attribute ((unused)))
567 /* Make default characters signed */
568 {
569     SignedChars = 1;
570 }
571
572
573
574 static void OptStaticLocals (const char* Opt attribute ((unused)),
575                              const char* Arg attribute ((unused)))
576 /* Place local variables in static storage */
577 {
578     StaticLocals = 1;
579 }
580
581
582
583 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
584 /* Set the target system */
585 {
586     SetSys (Arg);
587 }
588
589
590
591 static void OptVerbose (const char* Opt attribute ((unused)),
592                         const char* Arg attribute ((unused)))
593 /* Increase verbosity */
594 {
595     ++Verbosity;
596 }
597
598
599
600 static void OptVersion (const char* Opt attribute ((unused)),
601                         const char* Arg attribute ((unused)))
602 /* Print the assembler version */
603 {
604     fprintf (stderr,
605              "cc65 V%u.%u.%u\n",
606              VER_MAJOR, VER_MINOR, VER_PATCH);
607 }
608
609
610
611 int main (int argc, char* argv[])
612 {
613     /* Program long options */
614     static const LongOpt OptTab[] = {
615         { "--add-source",       0,      OptAddSource            },
616         { "--ansi",             0,      OptAnsi                 },
617         { "--bss-name",         1,      OptBssName              },
618         { "--check-stack",      0,      OptCheckStack           },
619         { "--code-name",        1,      OptCodeName             },
620         { "--codesize",         1,      OptCodeSize             },
621         { "--cpu",              1,      OptCPU                  },
622         { "--create-dep",       0,      OptCreateDep            },
623         { "--data-name",        1,      OptDataName             },
624         { "--debug",            0,      OptDebug                },
625         { "--debug-info",       0,      OptDebugInfo            },
626         { "--debug-opt",        1,      OptDebugOpt             },
627         { "--disable-opt",      1,      OptDisableOpt           },
628         { "--enable-opt",       1,      OptEnableOpt,           },
629         { "--help",             0,      OptHelp                 },
630         { "--include-dir",      1,      OptIncludeDir           },
631         { "--list-opt-steps",   0,      OptListOptSteps         },
632         { "--register-space",   1,      OptRegisterSpace        },
633         { "--register-vars",    0,      OptRegisterVars         },
634         { "--rodata-name",      1,      OptRodataName           },
635         { "--signed-chars",     0,      OptSignedChars          },
636         { "--static-locals",    0,      OptStaticLocals         },
637         { "--target",           1,      OptTarget               },
638         { "--verbose",          0,      OptVerbose              },
639         { "--version",          0,      OptVersion              },
640     };
641
642     unsigned I;
643
644     /* Initialize the output file name */
645     const char* OutputFile = 0;
646     const char* InputFile  = 0;
647
648     /* Initialize the cmdline module */
649     InitCmdLine (&argc, &argv, "cc65");
650
651     /* Initialize the default segment names */
652     InitSegNames ();
653
654     /* Parse the command line */
655     I = 1;
656     while (I < ArgCount) {
657
658         const char* P;
659
660         /* Get the argument */
661         const char* Arg = ArgVec[I];
662
663         /* Check for an option */
664         if (Arg [0] == '-') {
665
666             switch (Arg [1]) {
667
668                 case '-':
669                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
670                     break;
671
672                 case 'd':
673                     OptDebug (Arg, 0);
674                     break;
675
676                 case 'h':
677                 case '?':
678                     OptHelp (Arg, 0);
679                     break;
680
681                 case 'g':
682                     OptDebugInfo (Arg, 0);
683                     break;
684
685                 case 'j':
686                     OptSignedChars (Arg, 0);
687                     break;
688
689                 case 'o':
690                     OutputFile = GetArg (&I, 2);
691                     break;
692
693                 case 'r':
694                     OptRegisterVars (Arg, 0);
695                     break;
696
697                 case 't':
698                     OptTarget (Arg, GetArg (&I, 2));
699                     break;
700
701                 case 'u':
702                     OptCreateDep (Arg, 0);
703                     break;
704
705                 case 'v':
706                     OptVerbose (Arg, 0);
707                     break;
708
709                 case 'A':
710                     OptAnsi (Arg, 0);
711                     break;
712
713                 case 'C':
714                     P = Arg + 2;
715                     while (*P) {
716                         switch (*P++) {
717                             case 'l':
718                                 OptStaticLocals (Arg, 0);
719                                 break;
720                             default:
721                                 UnknownOption (Arg);
722                                 break;
723                         }
724                     }
725                     break;
726
727                 case 'D':
728                     DefineSym (GetArg (&I, 2));
729                     break;
730
731                 case 'I':
732                     OptIncludeDir (Arg, GetArg (&I, 2));
733                     break;
734
735                 case 'O':
736                     Optimize = 1;
737                     P = Arg + 2;
738                     while (*P) {
739                         switch (*P++) {
740                             case 'f':
741                                 sscanf (P, "%lx", (long*) &OptDisable);
742                                 break;
743                             case 'i':
744                                 FavourSize = 0;
745                                 CodeSizeFactor = 200;
746                                 break;
747                             case 'r':
748                                 EnableRegVars = 1;
749                                 break;
750                             case 's':
751                                 InlineStdFuncs = 1;
752                                 break;
753                         }
754                     }
755                     break;
756
757                 case 'T':
758                     OptAddSource (Arg, 0);
759                     break;
760
761                 case 'V':
762                     OptVersion (Arg, 0);
763                     break;
764
765                 case 'W':
766                     NoWarn = 1;
767                     break;
768
769                 default:
770                     UnknownOption (Arg);
771                     break;
772             }
773         } else {
774             if (InputFile) {
775                 fprintf (stderr, "additional file specs ignored\n");
776             } else {
777                 InputFile = Arg;
778             }
779         }
780
781         /* Next argument */
782         ++I;
783     }
784
785     /* Did we have a file spec on the command line? */
786     if (InputFile == 0) {
787         AbEnd ("No input files");
788     }
789
790     /* Create the output file name if it was not explicitly given */
791     if (OutputFile == 0) {
792         OutputFile = MakeFilename (InputFile, ".s");
793     }
794
795     /* If no CPU given, use the default CPU for the target */
796     if (CPU == CPU_UNKNOWN) {
797         if (Target != TGT_UNKNOWN) {
798             CPU = DefaultCPU[Target];
799         } else {
800             CPU = CPU_6502;
801         }
802     }
803
804     /* Go! */
805     Compile (InputFile);
806
807     /* Create the output file if we didn't had any errors */
808     if (ErrorCount == 0 || Debug) {
809
810         /* Open the file */
811         FILE* F = fopen (OutputFile, "w");
812         if (F == 0) {
813             Fatal ("Cannot open output file `%s': %s", OutputFile, strerror (errno));
814         }
815
816         /* Write the output to the file */
817         WriteOutput (F);
818
819         /* Close the file, check for errors */
820         if (fclose (F) != 0) {
821             remove (OutputFile);
822             Fatal ("Cannot write to output file (disk full?)");
823         }
824
825         /* Create dependencies if requested */
826         if (CreateDep) {
827             DoCreateDep (OutputFile);
828         }
829
830     }
831
832     /* Return an apropriate exit code */
833     return (ErrorCount > 0)? EXIT_FAILURE : EXIT_SUCCESS;
834 }
835
836
837