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