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