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