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