]> git.sur5r.net Git - cc65/blob - src/cl65/main.c
Reverted part of change 4108 that prevented an optimization step to find
[cc65] / src / cl65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*             Main module for the cl65 compile and link utility             */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1999-2009, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
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 /* Check out if we have a spawn() function on the system, or if we must use
37  * our own.
38  */
39 #if defined(__WATCOMC__) || defined(_MSC_VER) || defined(__MINGW32__) || defined(__DJGPP__)
40 #  define HAVE_SPAWN    1
41 #else
42 #  define NEED_SPAWN   1
43 #endif
44
45
46
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <ctype.h>
51 #include <errno.h>
52 #ifdef HAVE_SPAWN
53 #  include <process.h>
54 #endif
55
56 /* common */
57 #include "attrib.h"
58 #include "cmdline.h"
59 #include "filetype.h"
60 #include "fname.h"
61 #include "mmodel.h"
62 #include "strbuf.h"
63 #include "target.h"
64 #include "version.h"
65 #include "xmalloc.h"
66
67 /* cl65 */
68 #include "global.h"
69 #include "error.h"
70
71
72
73 /*****************************************************************************/
74 /*                                   Data                                    */
75 /*****************************************************************************/
76
77
78
79 /* Struct that describes a command */
80 typedef struct CmdDesc CmdDesc;
81 struct CmdDesc {
82     char*       Name;           /* The command name */
83
84     unsigned    ArgCount;       /* Count of arguments */
85     unsigned    ArgMax;         /* Maximum count of arguments */
86     char**      Args;           /* The arguments */
87
88     unsigned    FileCount;      /* Count of files to translate */
89     unsigned    FileMax;        /* Maximum count of files */
90     char**      Files;          /* The files */
91 };
92
93 /* Command descriptors for the different programs */
94 static CmdDesc CC65 = { 0, 0, 0, 0, 0, 0, 0 };
95 static CmdDesc CA65 = { 0, 0, 0, 0, 0, 0, 0 };
96 static CmdDesc CO65 = { 0, 0, 0, 0, 0, 0, 0 };
97 static CmdDesc LD65 = { 0, 0, 0, 0, 0, 0, 0 };
98 static CmdDesc GRC  = { 0, 0, 0, 0, 0, 0, 0 };
99
100 /* Variables controlling the steps we're doing */
101 static int DontLink     = 0;
102 static int DontAssemble = 0;
103
104 /* The name of the output file, NULL if none given */
105 static const char* OutputName = 0;
106
107 /* The name of the linker configuration file if given */
108 static const char* LinkerConfig = 0;
109
110 /* The name of the first input file. This will be used to construct the
111  * executable file name if no explicit name is given.
112  */
113 static const char* FirstInput = 0;
114
115 /* Remember if we should link a module */
116 static int Module = 0;
117
118 /* Extension used for a module */
119 #define MODULE_EXT      ".o65"
120
121 /* Name of the target specific runtime library */
122 static char* TargetLib  = 0;
123
124
125
126 /*****************************************************************************/
127 /*                Include the system specific spawn function                 */
128 /*****************************************************************************/
129
130
131
132 #if defined(NEED_SPAWN)
133 #  if defined(SPAWN_UNIX)
134 #    include "spawn-unix.inc"
135 #  elif defined(SPAWN_AMIGA)
136 #    include "spawn-amiga.inc"
137 #  else
138 #    error "Don't know which spawn module to include!"
139 #  endif
140 #endif
141
142
143
144 /*****************************************************************************/
145 /*                        Command structure handling                         */
146 /*****************************************************************************/
147
148
149
150 static void CmdExpand (CmdDesc* Cmd)
151 /* Expand the argument vector */
152 {
153     unsigned NewMax  = Cmd->ArgMax + 10;
154     char**       NewArgs = xmalloc (NewMax * sizeof (char*));
155     memcpy (NewArgs, Cmd->Args, Cmd->ArgMax * sizeof (char*));
156     xfree (Cmd->Args);
157     Cmd->Args   = NewArgs;
158     Cmd->ArgMax = NewMax;
159 }
160
161
162
163 static void CmdAddArg (CmdDesc* Cmd, const char* Arg)
164 /* Add a new argument to the command */
165 {
166     /* Expand the argument vector if needed */
167     if (Cmd->ArgCount >= Cmd->ArgMax) {
168         CmdExpand (Cmd);
169     }
170
171     /* Add a copy of the new argument, allow a NULL pointer */
172     if (Arg) {
173         Cmd->Args[Cmd->ArgCount++] = xstrdup (Arg);
174     } else {
175         Cmd->Args[Cmd->ArgCount++] = 0;
176     }
177 }
178
179
180
181 static void CmdAddArg2 (CmdDesc* Cmd, const char* Arg1, const char* Arg2)
182 /* Add a new argument pair to the command */
183 {
184     CmdAddArg (Cmd, Arg1);
185     CmdAddArg (Cmd, Arg2);
186 }
187
188
189
190 static void CmdAddArgList (CmdDesc* Cmd, const char* ArgList)
191 /* Add a list of arguments separated by commas */
192 {
193     const char* Arg = ArgList;
194     const char* P   = Arg;
195
196     while (1) {
197         if (*P == '\0' || *P == ',') {
198
199             /* End of argument, add it */
200             unsigned Len = P - Arg;
201
202             /* Expand the argument vector if needed */
203             if (Cmd->ArgCount >= Cmd->ArgMax) {
204                 CmdExpand (Cmd);
205             }
206
207             /* Add the new argument */
208             Cmd->Args[Cmd->ArgCount] = memcpy (xmalloc (Len + 1), Arg, Len);
209             Cmd->Args[Cmd->ArgCount][Len] = '\0';
210             ++Cmd->ArgCount;
211
212             /* If the argument was terminated by a comma, skip it, otherwise
213              * we're done.
214              */
215             if (*P == ',') {
216                 /* Start over at next char */
217                 Arg = ++P;
218             } else {
219                 break;
220             }
221         } else {
222             /* Skip other chars */
223             ++P;
224         }
225     }
226
227 }
228
229
230
231 static void CmdDelArgs (CmdDesc* Cmd, unsigned LastValid)
232 /* Remove all arguments with an index greater than LastValid */
233 {
234     while (Cmd->ArgCount > LastValid) {
235         Cmd->ArgCount--;
236         xfree (Cmd->Args [Cmd->ArgCount]);
237         Cmd->Args [Cmd->ArgCount] = 0;
238     }
239 }
240
241
242
243 static void CmdAddFile (CmdDesc* Cmd, const char* File)
244 /* Add a new file to the command */
245 {
246     /* Expand the file vector if needed */
247     if (Cmd->FileCount == Cmd->FileMax) {
248         unsigned NewMax   = Cmd->FileMax + 10;
249         char**   NewFiles = xmalloc (NewMax * sizeof (char*));
250         memcpy (NewFiles, Cmd->Files, Cmd->FileMax * sizeof (char*));
251         xfree (Cmd->Files);
252         Cmd->Files   = NewFiles;
253         Cmd->FileMax = NewMax;
254     }
255
256     /* If the file name is not NULL (which is legal and is used to terminate
257      * the file list), check if the file name does already exist in the file
258      * list and print a warning if so. Regardless of the search result, add
259      * the file.
260      */
261     if (File) {
262         unsigned I;
263         for (I = 0; I < Cmd->FileCount; ++I) {
264             if (strcmp (Cmd->Files[I], File) == 0) {
265                 /* Duplicate file */
266                 Warning ("Duplicate file in argument list: `%s'", File);
267                 /* No need to search further */
268                 break;
269             }
270         }
271
272         /* Add the file */
273         Cmd->Files [Cmd->FileCount++] = xstrdup (File);
274     } else {
275         /* Add a NULL pointer */
276         Cmd->Files [Cmd->FileCount++] = 0;
277     }
278 }
279
280
281
282 static void CmdInit (CmdDesc* Cmd, const char* Path)
283 /* Initialize the command using the given path to the executable */
284 {
285     /* Remember the command */
286     Cmd->Name = xstrdup (Path);
287
288     /* Use the command name as first argument */
289     CmdAddArg (Cmd, Path);
290 }
291
292
293
294 static void CmdSetOutput (CmdDesc* Cmd, const char* File)
295 /* Set the output file in a command desc */
296 {
297     CmdAddArg2 (Cmd, "-o", File);
298 }
299
300
301
302 static void CmdSetTarget (CmdDesc* Cmd, target_t Target)
303 /* Set the output file in a command desc */
304 {
305     CmdAddArg2 (Cmd, "-t", TargetNames[Target]);
306 }
307
308
309
310 static void CmdPrint (CmdDesc* Cmd, FILE* F)
311 /* Output the command line encoded in the command desc */
312 {
313     unsigned I;
314     for (I = 0; I < Cmd->ArgCount && Cmd->Args[I] != 0; ++I) {
315         fprintf (F, "%s ", Cmd->Args[I]);
316     }
317 }
318
319
320
321 /*****************************************************************************/
322 /*                              Target handling                              */
323 /*****************************************************************************/
324
325
326
327 static void SetTargetFiles (void)
328 /* Set the target system files */
329 {
330     /* Determine the names of the target specific library file */
331     if (Target != TGT_NONE) {
332
333         /* Get a pointer to the system name and its length */
334         const char* TargetName = TargetNames [Target];
335         unsigned    TargetNameLen = strlen (TargetName);
336
337         /* Set the library file */
338         TargetLib = xmalloc (TargetNameLen + 4 + 1);
339         memcpy (TargetLib, TargetName, TargetNameLen);
340         strcpy (TargetLib + TargetNameLen, ".lib");
341
342     }
343 }
344
345
346
347 /*****************************************************************************/
348 /*                               Subprocesses                                */
349 /*****************************************************************************/
350
351
352
353 static void ExecProgram (CmdDesc* Cmd)
354 /* Execute a subprocess with the given name/parameters. Exit on errors. */
355 {
356     int Status;
357
358     /* If in debug mode, output the command line we will execute */
359     if (Debug) {
360         printf ("Executing: ");
361         CmdPrint (Cmd, stdout);
362         printf ("\n");
363     }
364
365     /* Call the program */
366     Status = spawnvp (P_WAIT, Cmd->Name, Cmd->Args);
367
368     /* Check the result code */
369     if (Status < 0) {
370         /* Error executing the program */
371         Error ("Cannot execute `%s': %s", Cmd->Name, strerror (errno));
372     } else if (Status != 0) {
373         /* Called program had an error */
374         exit (Status);
375     }
376 }
377
378
379
380 static void Link (void)
381 /* Link the resulting executable */
382 {
383     unsigned I;
384
385     /* If we have a linker config file given, add it to the command line.
386      * Otherwise pass the target to the linker if we have one.
387      */
388     if (LinkerConfig) {
389         if (Module) {
390             Error ("Cannot use -C and --module together");
391         }
392         CmdAddArg2 (&LD65, "-C", LinkerConfig);
393     } else if (Module) {
394         CmdSetTarget (&LD65, TGT_MODULE);
395     } else {
396         CmdSetTarget (&LD65, Target);
397     }
398
399     /* Determine which target libraries are needed */
400     SetTargetFiles ();
401
402     /* Since linking is always the final step, if we have an output file name
403      * given, set it here. If we don't have an explicit output name given,
404      * try to build one from the name of the first input file.
405      */
406     if (OutputName) {
407
408         CmdSetOutput (&LD65, OutputName);
409
410     } else if (FirstInput && FindExt (FirstInput)) {  /* Only if ext present! */
411
412         const char* Extension = Module? MODULE_EXT : "";
413         char* Output = MakeFilename (FirstInput, Extension);
414         CmdSetOutput (&LD65, Output);
415         xfree (Output);
416
417     }
418
419     /* Add all object files as parameters */
420     for (I = 0; I < LD65.FileCount; ++I) {
421         CmdAddArg (&LD65, LD65.Files [I]);
422     }
423
424     /* Add the system runtime library */
425     if (TargetLib) {
426         CmdAddArg (&LD65, TargetLib);
427     }
428
429     /* Terminate the argument list with a NULL pointer */
430     CmdAddArg (&LD65, 0);
431
432     /* Call the linker */
433     ExecProgram (&LD65);
434 }
435
436
437
438 static void Assemble (const char* File)
439 /* Assemble the given file */
440 {
441     /* Remember the current assembler argument count */
442     unsigned ArgCount = CA65.ArgCount;
443
444     /* Set the target system */
445     CmdSetTarget (&CA65, Target);
446
447     /* If we won't link, this is the final step. In this case, set the
448      * output name.
449      */
450     if (DontLink && OutputName) {
451         CmdSetOutput (&CA65, OutputName);
452     } else {
453         /* The object file name will be the name of the source file
454          * with .s replaced by ".o". Add this file to the list of
455          * linker files.
456          */
457         char* ObjName = MakeFilename (File, ".o");
458         CmdAddFile (&LD65, ObjName);
459         xfree (ObjName);
460     }
461
462     /* Add the file as argument for the assembler */
463     CmdAddArg (&CA65, File);
464
465     /* Add a NULL pointer to terminate the argument list */
466     CmdAddArg (&CA65, 0);
467
468     /* Run the assembler */
469     ExecProgram (&CA65);
470
471     /* Remove the excess arguments */
472     CmdDelArgs (&CA65, ArgCount);
473 }
474
475
476
477 static void Compile (const char* File)
478 /* Compile the given file */
479 {
480     char* AsmName = 0;
481
482     /* Remember the current compiler argument count */
483     unsigned ArgCount = CC65.ArgCount;
484
485     /* Set the target system */
486     CmdSetTarget (&CC65, Target);
487
488     /* If we won't link, this is the final step. In this case, set the
489      * output name.
490      */
491     if (DontAssemble && OutputName) {
492         CmdSetOutput (&CC65, OutputName);
493     } else {
494         /* The assembler file name will be the name of the source file
495          * with .c replaced by ".s".
496          */
497         AsmName = MakeFilename (File, ".s");
498     }
499
500     /* Add the file as argument for the compiler */
501     CmdAddArg (&CC65, File);
502
503     /* Add a NULL pointer to terminate the argument list */
504     CmdAddArg (&CC65, 0);
505
506     /* Run the compiler */
507     ExecProgram (&CC65);
508
509     /* Remove the excess arguments */
510     CmdDelArgs (&CC65, ArgCount);
511
512     /* If this is not the final step, assemble the generated file, then
513      * remove it
514      */
515     if (!DontAssemble) {
516         Assemble (AsmName);
517         if (remove (AsmName) < 0) {
518             Warning ("Cannot remove temporary file `%s': %s",
519                      AsmName, strerror (errno));
520         }
521         xfree (AsmName);
522     }
523 }
524
525
526
527 static void CompileRes (const char* File)
528 /* Compile the given geos resource file */
529 {
530     char* AsmName = 0;
531
532     /* Remember the current assembler argument count */
533     unsigned ArgCount = GRC.ArgCount;
534
535     /* The assembler file name will be the name of the source file
536      * with .grc replaced by ".s".
537      */
538     AsmName = MakeFilename (File, ".s");
539
540     /* Add the file as argument for the resource compiler */
541     CmdAddArg (&GRC, File);
542
543     /* Add a NULL pointer to terminate the argument list */
544     CmdAddArg (&GRC, 0);
545
546     /* Run the compiler */
547     ExecProgram (&GRC);
548
549     /* Remove the excess arguments */
550     CmdDelArgs (&GRC, ArgCount);
551
552     /* If this is not the final step, assemble the generated file, then
553      * remove it
554      */
555     if (!DontAssemble) {
556         Assemble (AsmName);
557         if (remove (AsmName) < 0) {
558             Warning ("Cannot remove temporary file `%s': %s",
559                      AsmName, strerror (errno));
560         }
561     }
562
563     /* Free the assembler file name which was allocated from the heap */
564     xfree (AsmName);
565 }
566
567
568
569 static void ConvertO65 (const char* File)
570 /* Convert an o65 object file into an assembler file */
571 {
572     char* AsmName = 0;
573
574     /* Remember the current converter argument count */
575     unsigned ArgCount = CO65.ArgCount;
576
577     /* If we won't link, this is the final step. In this case, set the
578      * output name.
579      */
580     if (DontAssemble && OutputName) {
581         CmdSetOutput (&CO65, OutputName);
582     } else {
583         /* The assembler file name will be the name of the source file
584          * with .c replaced by ".s".
585          */
586         AsmName = MakeFilename (File, ".s");
587     }
588
589     /* Add the file as argument for the object file converter */
590     CmdAddArg (&CO65, File);
591
592     /* Add a NULL pointer to terminate the argument list */
593     CmdAddArg (&CO65, 0);
594
595     /* Run the converter */
596     ExecProgram (&CO65);
597
598     /* Remove the excess arguments */
599     CmdDelArgs (&CO65, ArgCount);
600
601     /* If this is not the final step, assemble the generated file, then
602      * remove it
603      */
604     if (!DontAssemble) {
605         Assemble (AsmName);
606         if (remove (AsmName) < 0) {
607             Warning ("Cannot remove temporary file `%s': %s",
608                      AsmName, strerror (errno));
609         }
610     }
611
612     /* Free the assembler file name which was allocated from the heap */
613     xfree (AsmName);
614 }
615
616
617
618 /*****************************************************************************/
619 /*                                   Code                                    */
620 /*****************************************************************************/
621
622
623
624 static void Usage (void)
625 /* Print usage information and exit */
626 {
627     printf ("Usage: %s [options] file [...]\n"
628             "Short options:\n"
629             "  -c\t\t\tCompile and assemble but don't link\n"
630             "  -d\t\t\tDebug mode\n"
631             "  -g\t\t\tAdd debug info\n"
632             "  -h\t\t\tHelp (this text)\n"
633             "  -l\t\t\tCreate an assembler listing\n"
634             "  -m name\t\tCreate a map file\n"
635             "  -mm model\t\tSet the memory model\n"
636             "  -o name\t\tName the output file\n"
637             "  -r\t\t\tEnable register variables\n"
638             "  -t sys\t\tSet the target system\n"
639             "  -u sym\t\tForce an import of symbol `sym'\n"
640             "  -v\t\t\tVerbose mode\n"
641             "  -vm\t\t\tVerbose map file\n"
642             "  -C name\t\tUse linker config file\n"
643             "  -Cl\t\t\tMake local variables static\n"
644             "  -D sym[=defn]\t\tDefine a preprocessor symbol\n"
645             "  -I dir\t\tSet a compiler include directory path\n"
646             "  -L path\t\tSpecify a library search path\n"
647             "  -Ln name\t\tCreate a VICE label file\n"
648             "  -O\t\t\tOptimize code\n"
649             "  -Oi\t\t\tOptimize code, inline functions\n"
650             "  -Or\t\t\tOptimize code, honour the register keyword\n"
651             "  -Os\t\t\tOptimize code, inline known C funtions\n"
652             "  -S\t\t\tCompile but don't assemble and link\n"
653             "  -T\t\t\tInclude source as comment\n"
654             "  -V\t\t\tPrint the version number\n"
655             "  -W\t\t\tSuppress warnings\n"
656             "  -Wa options\t\tPass options to the assembler\n"
657             "  -Wl options\t\tPass options to the linker\n"
658             "\n"
659             "Long options:\n"
660             "  --add-source\t\tInclude source as comment\n"
661             "  --asm-args options\tPass options to the assembler\n"
662             "  --asm-define sym[=v]\tDefine an assembler symbol\n"
663             "  --asm-include-dir dir\tSet an assembler include directory\n"
664             "  --bss-label name\tDefine and export a BSS segment label\n"
665             "  --bss-name seg\tSet the name of the BSS segment\n"
666             "  --cfg-path path\tSpecify a config file search path\n"
667             "  --check-stack\t\tGenerate stack overflow checks\n"
668             "  --code-label name\tDefine and export a CODE segment label\n"
669             "  --code-name seg\tSet the name of the CODE segment\n"
670             "  --codesize x\t\tAccept larger code by factor x\n"
671             "  --config name\t\tUse linker config file\n"
672             "  --cpu type\t\tSet cpu type\n"
673             "  --create-dep\t\tCreate a make dependency file\n"
674             "  --data-label name\tDefine and export a DATA segment label\n"
675             "  --data-name seg\tSet the name of the DATA segment\n"
676             "  --debug\t\tDebug mode\n"
677             "  --debug-info\t\tAdd debug info\n"
678             "  --feature name\tSet an emulation feature\n"
679             "  --force-import sym\tForce an import of symbol `sym'\n"
680             "  --forget-inc-paths\tForget include search paths (compiler)\n"
681             "  --help\t\tHelp (this text)\n"
682             "  --include-dir dir\tSet a compiler include directory path\n"
683             "  --ld-args options\tPass options to the linker\n"
684             "  --lib file\t\tLink this library\n"
685             "  --lib-path path\tSpecify a library search path\n"
686             "  --list-targets\tList all available targets\n"
687             "  --listing\t\tCreate an assembler listing\n"
688             "  --list-bytes n\tNumber of bytes per assembler listing line\n"
689             "  --mapfile name\tCreate a map file\n"
690             "  --memory-model model\tSet the memory model\n"
691             "  --module\t\tLink as a module\n"
692             "  --module-id id\tSpecify a module id for the linker\n"
693             "  --o65-model model\tOverride the o65 model\n"
694             "  --obj file\t\tLink this object file\n"
695             "  --obj-path path\tSpecify an object file search path\n"
696             "  --register-space b\tSet space available for register variables\n"
697             "  --register-vars\tEnable register variables\n"
698             "  --rodata-name seg\tSet the name of the RODATA segment\n"
699             "  --signed-chars\tDefault characters are signed\n"
700             "  --standard std\tLanguage standard (c89, c99, cc65)\n"
701             "  --start-addr addr\tSet the default start address\n"
702             "  --static-locals\tMake local variables static\n"
703             "  --target sys\t\tSet the target system\n"
704             "  --version\t\tPrint the version number\n"
705             "  --verbose\t\tVerbose mode\n"
706             "  --zeropage-label name\tDefine and export a ZEROPAGE segment label\n"
707             "  --zeropage-name seg\tSet the name of the ZEROPAGE segment\n",
708             ProgName);
709 }
710
711
712
713 static void OptAddSource (const char* Opt attribute ((unused)),
714                           const char* Arg attribute ((unused)))
715 /* Strict source code as comments to the generated asm code */
716 {
717     CmdAddArg (&CC65, "-T");
718 }
719
720
721
722 static void OptAsmArgs (const char* Opt attribute ((unused)), const char* Arg)
723 /* Pass arguments to the assembler */
724 {
725     CmdAddArgList (&CA65, Arg);
726 }
727
728
729
730 static void OptAsmDefine (const char* Opt attribute ((unused)), const char* Arg)
731 /* Define an assembler symbol (assembler) */
732 {
733     CmdAddArg2 (&CA65, "-D", Arg);
734 }
735
736
737
738 static void OptAsmIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
739 /* Include directory (assembler) */
740 {
741     CmdAddArg2 (&CA65, "-I", Arg);
742 }
743
744
745
746 static void OptBssLabel (const char* Opt attribute ((unused)), const char* Arg)
747 /* Handle the --bss-label option */
748 {
749     CmdAddArg2 (&CO65, "--bss-label", Arg);
750 }
751
752
753
754 static void OptBssName (const char* Opt attribute ((unused)), const char* Arg)
755 /* Handle the --bss-name option */
756 {
757     CmdAddArg2 (&CC65, "--bss-name", Arg);
758     CmdAddArg2 (&CO65, "--bss-name", Arg);
759 }
760
761
762
763 static void OptCfgPath (const char* Opt attribute ((unused)), const char* Arg)
764 /* Config file search path (linker) */
765 {
766     CmdAddArg2 (&LD65, "--cfg-path", Arg);
767 }
768
769
770
771 static void OptCheckStack (const char* Opt attribute ((unused)),
772                            const char* Arg attribute ((unused)))
773 /* Handle the --check-stack option */
774 {
775     CmdAddArg (&CC65, "--check-stack");
776 }
777
778
779
780 static void OptCodeLabel (const char* Opt attribute ((unused)), const char* Arg)
781 /* Handle the --code-label option */
782 {
783     CmdAddArg2 (&CO65, "--code-label", Arg);
784 }
785
786
787
788 static void OptCodeName (const char* Opt attribute ((unused)), const char* Arg)
789 /* Handle the --code-name option */
790 {
791     CmdAddArg2 (&CC65, "--code-name", Arg);
792     CmdAddArg2 (&CO65, "--code-name", Arg);
793 }
794
795
796
797 static void OptCodeSize (const char* Opt attribute ((unused)), const char* Arg)
798 /* Handle the --codesize option */
799 {
800     CmdAddArg2 (&CC65, "--codesize", Arg);
801 }
802
803
804
805 static void OptConfig (const char* Opt attribute ((unused)), const char* Arg)
806 /* Config file (linker) */
807 {
808     if (LinkerConfig) {
809         Error ("Cannot specify -C/--config twice");
810     }
811     LinkerConfig = Arg;
812 }
813
814
815
816 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
817 /* Handle the --cpu option */
818 {
819     /* Add the cpu type to the assembler and compiler */
820     CmdAddArg2 (&CA65, "--cpu", Arg);
821     CmdAddArg2 (&CC65, "--cpu", Arg);
822 }
823
824
825
826 static void OptCreateDep (const char* Opt attribute ((unused)),
827                           const char* Arg attribute ((unused)))
828 /* Handle the --create-dep option */
829 {
830     CmdAddArg (&CC65, "--create-dep");
831 }
832
833
834
835 static void OptDataLabel (const char* Opt attribute ((unused)), const char* Arg)
836 /* Handle the --data-label option */
837 {
838     CmdAddArg2 (&CO65, "--data-label", Arg);
839 }
840
841
842
843 static void OptDataName (const char* Opt attribute ((unused)), const char* Arg)
844 /* Handle the --data-name option */
845 {
846     CmdAddArg2 (&CC65, "--data-name", Arg);
847     CmdAddArg2 (&CO65, "--data-name", Arg);
848 }
849
850
851
852 static void OptDebug (const char* Opt attribute ((unused)),
853                       const char* Arg attribute ((unused)))
854 /* Debug mode (compiler and cl65 utility) */
855 {
856     CmdAddArg (&CC65, "-d");
857     CmdAddArg (&CO65, "-d");
858     Debug = 1;
859 }
860
861
862
863 static void OptDebugInfo (const char* Opt attribute ((unused)),
864                           const char* Arg attribute ((unused)))
865 /* Debug Info - add to compiler and assembler */
866 {
867     CmdAddArg (&CC65, "-g");
868     CmdAddArg (&CA65, "-g");
869     CmdAddArg (&CO65, "-g");
870 }
871
872
873
874 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
875 /* Emulation features for the assembler */
876 {
877     CmdAddArg2 (&CA65, "--feature", Arg);
878 }
879
880
881
882 static void OptForceImport (const char* Opt attribute ((unused)), const char* Arg)
883 /* Emulation features for the assembler */
884 {
885     CmdAddArg2 (&LD65, "-u", Arg);
886 }
887
888
889
890 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
891                                const char* Arg attribute ((unused)))
892 /* Forget all currently defined include paths */
893 {
894     CmdAddArg (&CC65, "--forget-inc-paths");
895 }
896
897
898
899 static void OptHelp (const char* Opt attribute ((unused)),
900                      const char* Arg attribute ((unused)))
901 /* Print help - cl65 */
902 {
903     Usage ();
904     exit (EXIT_SUCCESS);
905 }
906
907
908
909 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
910 /* Include directory (compiler) */
911 {
912     CmdAddArg2 (&CC65, "-I", Arg);
913 }
914
915
916
917 static void OptLdArgs (const char* Opt attribute ((unused)), const char* Arg)
918 /* Pass arguments to the linker */
919 {
920     CmdAddArgList (&LD65, Arg);
921 }
922
923
924
925 static void OptLib (const char* Opt attribute ((unused)), const char* Arg)
926 /* Library file follows (linker) */
927 {
928     CmdAddArg2 (&LD65, "--lib", Arg);
929 }
930
931
932
933 static void OptLibPath (const char* Opt attribute ((unused)), const char* Arg)
934 /* Library search path (linker) */
935 {
936     CmdAddArg2 (&LD65, "--lib-path", Arg);
937 }
938
939
940
941 static void OptListBytes (const char* Opt attribute ((unused)), const char* Arg)
942 /* Set the maximum number of bytes per asm listing line */
943 {
944     CmdAddArg2 (&CA65, "--list-bytes", Arg);
945 }
946
947
948
949 static void OptListing (const char* Opt attribute ((unused)),
950                         const char* Arg attribute ((unused)))
951 /* Create an assembler listing */
952 {
953     CmdAddArg (&CA65, "-l");
954 }
955
956
957
958 static void OptListTargets (const char* Opt attribute ((unused)),
959                             const char* Arg attribute ((unused)))
960 /* List all targets */
961 {
962     unsigned I;
963
964     /* List the targets */
965     for (I = TGT_NONE; I < TGT_COUNT; ++I) {
966         printf ("%s\n", TargetNames[I]);
967     }
968
969     /* Terminate */
970     exit (EXIT_SUCCESS);
971 }
972
973
974
975 static void OptMapFile (const char* Opt attribute ((unused)), const char* Arg)
976 /* Create a map file */
977 {
978     /* Create a map file (linker) */
979     CmdAddArg2 (&LD65, "-m", Arg);
980 }
981
982
983
984 static void OptMemoryModel (const char* Opt attribute ((unused)), const char* Arg)
985 /* Set the memory model */
986 {
987     mmodel_t MemoryModel = FindMemoryModel (Arg);
988     if (MemoryModel == MMODEL_UNKNOWN) {
989         Error ("Unknown memory model: %s", Arg);
990     } else if (MemoryModel == MMODEL_HUGE) {
991         Error ("Unsupported memory model: %s", Arg);
992     } else {
993         CmdAddArg2 (&CA65, "-mm", Arg);
994         CmdAddArg2 (&CC65, "-mm", Arg);
995     }
996 }
997
998
999
1000 static void OptModule (const char* Opt attribute ((unused)),
1001                        const char* Arg attribute ((unused)))
1002 /* Link as a module */
1003 {
1004     Module = 1;
1005 }
1006
1007
1008
1009 static void OptModuleId (const char* Opt attribute ((unused)), const char* Arg)
1010 /* Specify a module if for the linker */
1011 {
1012     /* Pass it straight to the linker */
1013     CmdAddArg2 (&LD65, "--module-id", Arg);
1014 }
1015
1016
1017
1018 static void OptO65Model (const char* Opt attribute ((unused)), const char* Arg)
1019 /* Handle the --o65-model option */
1020 {
1021     CmdAddArg2 (&CO65, "-m", Arg);
1022 }
1023
1024
1025
1026 static void OptObj (const char* Opt attribute ((unused)), const char* Arg)
1027 /* Object file follows (linker) */
1028 {
1029     CmdAddArg2 (&LD65, "--obj", Arg);
1030 }
1031
1032
1033
1034 static void OptObjPath (const char* Opt attribute ((unused)), const char* Arg)
1035 /* Object file search path (linker) */
1036 {
1037     CmdAddArg2 (&LD65, "--obj-path", Arg);
1038 }
1039
1040
1041
1042 static void OptRegisterSpace (const char* Opt attribute ((unused)), const char* Arg)
1043 /* Handle the --register-space option */
1044 {
1045     CmdAddArg2 (&CC65, "--register-space", Arg);
1046 }
1047
1048
1049
1050 static void OptRegisterVars (const char* Opt attribute ((unused)),
1051                              const char* Arg attribute ((unused)))
1052 /* Handle the --register-vars option */
1053 {
1054     CmdAddArg (&CC65, "-r");
1055 }
1056
1057
1058
1059 static void OptRodataName (const char* Opt attribute ((unused)), const char* Arg)
1060 /* Handle the --rodata-name option */
1061 {
1062     CmdAddArg2 (&CC65, "--rodata-name", Arg);
1063 }
1064
1065
1066
1067 static void OptSignedChars (const char* Opt attribute ((unused)),
1068                             const char* Arg attribute ((unused)))
1069 /* Make default characters signed */
1070 {
1071     CmdAddArg (&CC65, "-j");
1072 }
1073
1074
1075
1076 static void OptStandard (const char* Opt attribute ((unused)), const char* Arg)
1077 /* Set the language standard */
1078 {
1079     CmdAddArg2 (&CC65, "--standard", Arg);
1080 }
1081
1082
1083
1084 static void OptStartAddr (const char* Opt attribute ((unused)), const char* Arg)
1085 /* Set the default start address */
1086 {
1087     CmdAddArg2 (&LD65, "-S", Arg);
1088 }
1089
1090
1091
1092 static void OptStaticLocals (const char* Opt attribute ((unused)),
1093                              const char* Arg attribute ((unused)))
1094 /* Place local variables in static storage */
1095 {
1096     CmdAddArg (&CC65, "-Cl");
1097 }
1098
1099
1100
1101 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
1102 /* Set the target system */
1103 {
1104     Target = FindTarget (Arg);
1105     if (Target == TGT_UNKNOWN) {
1106         Error ("No such target system: `%s'", Arg);
1107     } else if (Target == TGT_MODULE) {
1108         Error ("Cannot use `module' as target, use --module instead");
1109     }
1110 }
1111
1112
1113
1114 static void OptVerbose (const char* Opt attribute ((unused)),
1115                         const char* Arg attribute ((unused)))
1116 /* Verbose mode (compiler, assembler, linker) */
1117 {
1118     CmdAddArg (&CC65, "-v");
1119     CmdAddArg (&CA65, "-v");
1120     CmdAddArg (&CO65, "-v");
1121     CmdAddArg (&LD65, "-v");
1122 }
1123
1124
1125
1126 static void OptVersion (const char* Opt attribute ((unused)),
1127                         const char* Arg attribute ((unused)))
1128 /* Print version number */
1129 {
1130     fprintf (stderr,
1131              "cl65 V%s - (C) Copyright 1998-2009 Ullrich von Bassewitz\n",
1132              GetVersionAsString ());
1133 }
1134
1135
1136
1137 static void OptZeropageLabel (const char* Opt attribute ((unused)), const char* Arg)
1138 /* Handle the --zeropage-label option */
1139 {
1140     CmdAddArg2 (&CO65, "--zeropage-label", Arg);
1141 }
1142
1143
1144
1145 static void OptZeropageName (const char* Opt attribute ((unused)), const char* Arg)
1146 /* Handle the --zeropage-name option */
1147 {
1148     CmdAddArg2 (&CO65, "--zeropage-name", Arg);
1149 }
1150
1151
1152
1153 int main (int argc, char* argv [])
1154 /* Utility main program */
1155 {
1156     /* Program long options */
1157     static const LongOpt OptTab[] = {
1158         { "--add-source",       0,      OptAddSource            },
1159         { "--asm-args",         1,      OptAsmArgs              },
1160         { "--asm-define",       1,      OptAsmDefine            },
1161         { "--asm-include-dir",  1,      OptAsmIncludeDir        },
1162         { "--bss-label",        1,      OptBssLabel             },
1163         { "--bss-name",         1,      OptBssName              },
1164         { "--cfg-path",         1,      OptCfgPath              },
1165         { "--check-stack",      0,      OptCheckStack           },
1166         { "--code-label",       1,      OptCodeLabel            },
1167         { "--code-name",        1,      OptCodeName             },
1168         { "--codesize",         1,      OptCodeSize             },
1169         { "--config",           1,      OptConfig               },
1170         { "--cpu",              1,      OptCPU                  },
1171         { "--create-dep",       0,      OptCreateDep            },
1172         { "--data-label",       1,      OptDataLabel            },
1173         { "--data-name",        1,      OptDataName             },
1174         { "--debug",            0,      OptDebug                },
1175         { "--debug-info",       0,      OptDebugInfo            },
1176         { "--feature",          1,      OptFeature              },
1177         { "--force-import",     1,      OptForceImport          },
1178         { "--forget-inc-paths", 0,      OptForgetIncPaths       },
1179         { "--help",             0,      OptHelp                 },
1180         { "--include-dir",      1,      OptIncludeDir           },
1181         { "--ld-args",          1,      OptLdArgs               },
1182         { "--lib",              1,      OptLib                  },
1183         { "--lib-path",         1,      OptLibPath              },
1184         { "--list-targets",     0,      OptListTargets          },
1185         { "--listing",          0,      OptListing              },
1186         { "--list-bytes",       1,      OptListBytes            },
1187         { "--mapfile",          1,      OptMapFile              },
1188         { "--memory-model",     1,      OptMemoryModel          },
1189         { "--module",           0,      OptModule               },
1190         { "--module-id",        1,      OptModuleId             },
1191         { "--o65-model",        1,      OptO65Model             },
1192         { "--obj",              1,      OptObj                  },
1193         { "--obj-path",         1,      OptObjPath              },
1194         { "--register-space",   1,      OptRegisterSpace        },
1195         { "--register-vars",    0,      OptRegisterVars         },
1196         { "--rodata-name",      1,      OptRodataName           },
1197         { "--signed-chars",     0,      OptSignedChars          },
1198         { "--standard",         1,      OptStandard             },
1199         { "--start-addr",       1,      OptStartAddr            },
1200         { "--static-locals",    0,      OptStaticLocals         },
1201         { "--target",           1,      OptTarget               },
1202         { "--verbose",          0,      OptVerbose              },
1203         { "--version",          0,      OptVersion              },
1204         { "--zeropage-label",   1,      OptZeropageLabel        },
1205         { "--zeropage-name",    1,      OptZeropageName         },
1206     };
1207
1208     unsigned I;
1209
1210     /* Initialize the cmdline module */
1211     InitCmdLine (&argc, &argv, "cl65");
1212
1213     /* Initialize the command descriptors */
1214     CmdInit (&CC65, "cc65");
1215     CmdInit (&CA65, "ca65");
1216     CmdInit (&CO65, "co65");
1217     CmdInit (&LD65, "ld65");
1218     CmdInit (&GRC,  "grc");
1219
1220     /* Our default target is the C64 instead of "none" */
1221     Target = TGT_C64;
1222
1223     /* Check the parameters */
1224     I = 1;
1225     while (I < ArgCount) {
1226
1227         /* Get the argument */
1228         const char* Arg = ArgVec[I];
1229
1230         /* Check for an option */
1231         if (Arg [0] == '-') {
1232
1233             switch (Arg [1]) {
1234
1235                 case '-':
1236                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
1237                     break;
1238
1239                 case 'C':
1240                     if (Arg[2] == 'l' && Arg[3] == '\0') {
1241                         /* Make local variables static */
1242                         OptStaticLocals (Arg, 0);
1243                     } else {
1244                         /* Specify linker config file */
1245                         OptConfig (Arg, GetArg (&I, 2));
1246                     }
1247                     break;
1248
1249                 case 'D':
1250                     /* Define a preprocessor symbol (compiler) */
1251                     CmdAddArg2 (&CC65, "-D", GetArg (&I, 2));
1252                     break;
1253
1254                 case 'I':
1255                     /* Include directory (compiler) */
1256                     OptIncludeDir (Arg, GetArg (&I, 2));
1257                     break;
1258
1259                 case 'L':
1260                     if (Arg[2] == 'n' && Arg[3] == '\0') {
1261                         /* VICE label file (linker) */
1262                         CmdAddArg2 (&LD65, "-Ln", GetArg (&I, 3));
1263                     } else {
1264                         /* Library search path (linker) */
1265                         OptLibPath (Arg, GetArg (&I, 2));
1266                     }
1267                     break;
1268
1269                 case 'O':
1270                     /* Optimize code (compiler, also covers -Oi and others) */
1271                     CmdAddArg (&CC65, Arg);
1272                     break;
1273
1274                 case 'S':
1275                     /* Dont assemble and link the created files */
1276                     DontLink = DontAssemble = 1;
1277                     break;
1278
1279                 case 'T':
1280                     /* Include source as comment (compiler) */
1281                     OptAddSource (Arg, 0);
1282                     break;
1283
1284                 case 'V':
1285                     /* Print version number */
1286                     OptVersion (Arg, 0);
1287                     break;
1288
1289                 case 'W':
1290                     switch (Arg[2]) {
1291
1292                         case 'a':
1293                             OptAsmArgs (Arg, GetArg (&I, 3));
1294                             break;
1295
1296                         case 'l':
1297                             OptLdArgs (Arg, GetArg (&I, 3));
1298                             break;
1299
1300                         case '\0':
1301                             /* Suppress warnings - compiler and assembler */
1302                             CmdAddArg (&CC65, "-W");
1303                             CmdAddArg2 (&CA65, "-W", "0");
1304                             break;
1305
1306                         default:
1307                             UnknownOption (Arg);
1308                             break;
1309                     }
1310                     break;
1311
1312                 case 'c':
1313                     /* Don't link the resulting files */
1314                     DontLink = 1;
1315                     break;
1316
1317                 case 'd':
1318                     /* Debug mode (compiler) */
1319                     OptDebug (Arg, 0);
1320                     break;
1321
1322                 case 'g':
1323                     /* Debugging - add to compiler and assembler */
1324                     OptDebugInfo (Arg, 0);
1325                     break;
1326
1327                 case 'h':
1328                 case '?':
1329                     /* Print help - cl65 */
1330                     OptHelp (Arg, 0);
1331                     break;
1332
1333                 case 'j':
1334                     /* Default characters are signed */
1335                     OptSignedChars (Arg, 0);
1336                     break;
1337
1338                 case 'l':
1339                     /* Create an assembler listing */
1340                     OptListing (Arg, 0);
1341                     break;
1342
1343                 case 'm':
1344                     /* Create a map file (linker) */
1345                     OptMapFile (Arg, GetArg (&I, 2));
1346                     break;
1347
1348                 case 'o':
1349                     /* Name the output file */
1350                     OutputName = GetArg (&I, 2);
1351                     break;
1352
1353                 case 'r':
1354                     /* Enable register variables */
1355                     OptRegisterVars (Arg, 0);
1356                     break;
1357
1358                 case 't':
1359                     /* Set target system - compiler, assembler and linker */
1360                     OptTarget (Arg, GetArg (&I, 2));
1361                     break;
1362
1363                 case 'u':
1364                     /* Force an import (linker) */
1365                     OptForceImport (Arg, GetArg (&I, 2));
1366                     break;
1367
1368                 case 'v':
1369                     if (Arg [2] == 'm') {
1370                         /* Verbose map file (linker) */
1371                         CmdAddArg (&LD65, "-vm");
1372                     } else {
1373                         /* Verbose mode (compiler, assembler, linker) */
1374                         OptVerbose (Arg, 0);
1375                     }
1376                     break;
1377
1378                 default:
1379                     UnknownOption (Arg);
1380             }
1381         } else {
1382
1383             /* Remember the first file name */
1384             if (FirstInput == 0) {
1385                 FirstInput = Arg;
1386             }
1387
1388             /* Determine the file type by the extension */
1389             switch (GetFileType (Arg)) {
1390
1391                 case FILETYPE_C:
1392                     /* Compile the file */
1393                     Compile (Arg);
1394                     break;
1395
1396                 case FILETYPE_ASM:
1397                     /* Assemble the file */
1398                     if (!DontAssemble) {
1399                         Assemble (Arg);
1400                     }
1401                     break;
1402
1403                 case FILETYPE_OBJ:
1404                 case FILETYPE_LIB:
1405                     /* Add to the linker files */
1406                     CmdAddFile (&LD65, Arg);
1407                     break;
1408
1409                 case FILETYPE_GR:
1410                     /* Add to the resource compiler files */
1411                     CompileRes (Arg);
1412                     break;
1413
1414                 case FILETYPE_O65:
1415                     /* Add the the object file converter files */
1416                     ConvertO65 (Arg);
1417                     break;
1418
1419                 default:
1420                     Error ("Don't know what to do with `%s'", Arg);
1421
1422             }
1423
1424         }
1425
1426         /* Next argument */
1427         ++I;
1428     }
1429
1430     /* Check if we had any input files */
1431     if (FirstInput == 0) {
1432         Warning ("No input files");
1433     }
1434
1435     /* Link the given files if requested and if we have any */
1436     if (DontLink == 0 && LD65.FileCount > 0) {
1437         Link ();
1438     }
1439
1440     /* Return an apropriate exit code */
1441     return EXIT_SUCCESS;
1442 }
1443
1444
1445