]> git.sur5r.net Git - cc65/blob - src/cl65/main.c
There's no longer a need to link in the startup file, it's done my magic
[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 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             "  -v\t\t\tVerbose mode\n"
640             "  -vm\t\t\tVerbose map file\n"
641             "  -C name\t\tUse linker config file\n"
642             "  -Cl\t\t\tMake local variables static\n"
643             "  -D sym[=defn]\t\tDefine a preprocessor symbol\n"
644             "  -I dir\t\tSet a compiler include directory path\n"
645             "  -L path\t\tSpecify a library search path\n"
646             "  -Ln name\t\tCreate a VICE label file\n"
647             "  -O\t\t\tOptimize code\n"
648             "  -Oi\t\t\tOptimize code, inline functions\n"
649             "  -Or\t\t\tOptimize code, honour the register keyword\n"
650             "  -Os\t\t\tOptimize code, inline known C funtions\n"
651             "  -S\t\t\tCompile but don't assemble and link\n"
652             "  -T\t\t\tInclude source as comment\n"
653             "  -V\t\t\tPrint the version number\n"
654             "  -W\t\t\tSuppress warnings\n"
655             "  -Wa options\t\tPass options to the assembler\n"
656             "  -Wl options\t\tPass options to the linker\n"
657             "\n"
658             "Long options:\n"
659             "  --add-source\t\tInclude source as comment\n"
660             "  --asm-args options\tPass options to the assembler\n"
661             "  --asm-define sym[=v]\tDefine an assembler symbol\n"
662             "  --asm-include-dir dir\tSet an assembler include directory\n"
663             "  --bss-label name\tDefine and export a BSS segment label\n"
664             "  --bss-name seg\tSet the name of the BSS segment\n"
665             "  --cfg-path path\tSpecify a config file search path\n"
666             "  --check-stack\t\tGenerate stack overflow checks\n"
667             "  --code-label name\tDefine and export a CODE segment label\n"
668             "  --code-name seg\tSet the name of the CODE segment\n"
669             "  --codesize x\t\tAccept larger code by factor x\n"
670             "  --config name\t\tUse linker config file\n"
671             "  --cpu type\t\tSet cpu type\n"
672             "  --create-dep\t\tCreate a make dependency file\n"
673             "  --data-label name\tDefine and export a DATA segment label\n"
674             "  --data-name seg\tSet the name of the DATA segment\n"
675             "  --debug\t\tDebug mode\n"
676             "  --debug-info\t\tAdd debug info\n"
677             "  --feature name\tSet an emulation feature\n"
678             "  --forget-inc-paths\tForget include search paths (compiler)\n"
679             "  --help\t\tHelp (this text)\n"
680             "  --include-dir dir\tSet a compiler include directory path\n"
681             "  --ld-args options\tPass options to the linker\n"
682             "  --lib file\t\tLink this library\n"
683             "  --lib-path path\tSpecify a library search path\n"
684             "  --list-targets\tList all available targets\n"
685             "  --listing\t\tCreate an assembler listing\n"
686             "  --list-bytes n\tNumber of bytes per assembler listing line\n"
687             "  --mapfile name\tCreate a map file\n"
688             "  --memory-model model\tSet the memory model\n"
689             "  --module\t\tLink as a module\n"
690             "  --module-id id\tSpecify a module id for the linker\n"
691             "  --o65-model model\tOverride the o65 model\n"
692             "  --obj file\t\tLink this object file\n"
693             "  --obj-path path\tSpecify an object file search path\n"
694             "  --register-space b\tSet space available for register variables\n"
695             "  --register-vars\tEnable register variables\n"
696             "  --rodata-name seg\tSet the name of the RODATA segment\n"
697             "  --signed-chars\tDefault characters are signed\n"
698             "  --standard std\tLanguage standard (c89, c99, cc65)\n"
699             "  --start-addr addr\tSet the default start address\n"
700             "  --static-locals\tMake local variables static\n"
701             "  --target sys\t\tSet the target system\n"
702             "  --version\t\tPrint the version number\n"
703             "  --verbose\t\tVerbose mode\n"
704             "  --zeropage-label name\tDefine and export a ZEROPAGE segment label\n"
705             "  --zeropage-name seg\tSet the name of the ZEROPAGE segment\n",
706             ProgName);
707 }
708
709
710
711 static void OptAddSource (const char* Opt attribute ((unused)),
712                           const char* Arg attribute ((unused)))
713 /* Strict source code as comments to the generated asm code */
714 {
715     CmdAddArg (&CC65, "-T");
716 }
717
718
719
720 static void OptAsmArgs (const char* Opt attribute ((unused)), const char* Arg)
721 /* Pass arguments to the assembler */
722 {
723     CmdAddArgList (&CA65, Arg);
724 }
725
726
727
728 static void OptAsmDefine (const char* Opt attribute ((unused)), const char* Arg)
729 /* Define an assembler symbol (assembler) */
730 {
731     CmdAddArg2 (&CA65, "-D", Arg);
732 }
733
734
735
736 static void OptAsmIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
737 /* Include directory (assembler) */
738 {
739     CmdAddArg2 (&CA65, "-I", Arg);
740 }
741
742
743
744 static void OptBssLabel (const char* Opt attribute ((unused)), const char* Arg)
745 /* Handle the --bss-label option */
746 {
747     CmdAddArg2 (&CO65, "--bss-label", Arg);
748 }
749
750
751
752 static void OptBssName (const char* Opt attribute ((unused)), const char* Arg)
753 /* Handle the --bss-name option */
754 {
755     CmdAddArg2 (&CC65, "--bss-name", Arg);
756     CmdAddArg2 (&CO65, "--bss-name", Arg);
757 }
758
759
760
761 static void OptCfgPath (const char* Opt attribute ((unused)), const char* Arg)
762 /* Config file search path (linker) */
763 {
764     CmdAddArg2 (&LD65, "--cfg-path", Arg);
765 }
766
767
768
769 static void OptCheckStack (const char* Opt attribute ((unused)),
770                            const char* Arg attribute ((unused)))
771 /* Handle the --check-stack option */
772 {
773     CmdAddArg (&CC65, "--check-stack");
774 }
775
776
777
778 static void OptCodeLabel (const char* Opt attribute ((unused)), const char* Arg)
779 /* Handle the --code-label option */
780 {
781     CmdAddArg2 (&CO65, "--code-label", Arg);
782 }
783
784
785
786 static void OptCodeName (const char* Opt attribute ((unused)), const char* Arg)
787 /* Handle the --code-name option */
788 {
789     CmdAddArg2 (&CC65, "--code-name", Arg);
790     CmdAddArg2 (&CO65, "--code-name", Arg);
791 }
792
793
794
795 static void OptCodeSize (const char* Opt attribute ((unused)), const char* Arg)
796 /* Handle the --codesize option */
797 {
798     CmdAddArg2 (&CC65, "--codesize", Arg);
799 }
800
801
802
803 static void OptConfig (const char* Opt attribute ((unused)), const char* Arg)
804 /* Config file (linker) */
805 {
806     if (LinkerConfig) {
807         Error ("Cannot specify -C/--config twice");
808     }
809     LinkerConfig = Arg;
810 }
811
812
813
814 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
815 /* Handle the --cpu option */
816 {
817     /* Add the cpu type to the assembler and compiler */
818     CmdAddArg2 (&CA65, "--cpu", Arg);
819     CmdAddArg2 (&CC65, "--cpu", Arg);
820 }
821
822
823
824 static void OptCreateDep (const char* Opt attribute ((unused)),
825                           const char* Arg attribute ((unused)))
826 /* Handle the --create-dep option */
827 {
828     CmdAddArg (&CC65, "--create-dep");
829 }
830
831
832
833 static void OptDataLabel (const char* Opt attribute ((unused)), const char* Arg)
834 /* Handle the --data-label option */
835 {
836     CmdAddArg2 (&CO65, "--data-label", Arg);
837 }
838
839
840
841 static void OptDataName (const char* Opt attribute ((unused)), const char* Arg)
842 /* Handle the --data-name option */
843 {
844     CmdAddArg2 (&CC65, "--data-name", Arg);
845     CmdAddArg2 (&CO65, "--data-name", Arg);
846 }
847
848
849
850 static void OptDebug (const char* Opt attribute ((unused)),
851                       const char* Arg attribute ((unused)))
852 /* Debug mode (compiler and cl65 utility) */
853 {
854     CmdAddArg (&CC65, "-d");
855     CmdAddArg (&CO65, "-d");
856     Debug = 1;
857 }
858
859
860
861 static void OptDebugInfo (const char* Opt attribute ((unused)),
862                           const char* Arg attribute ((unused)))
863 /* Debug Info - add to compiler and assembler */
864 {
865     CmdAddArg (&CC65, "-g");
866     CmdAddArg (&CA65, "-g");
867     CmdAddArg (&CO65, "-g");
868 }
869
870
871
872 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
873 /* Emulation features for the assembler */
874 {
875     CmdAddArg2 (&CA65, "--feature", Arg);
876 }
877
878
879
880 static void OptForgetIncPaths (const char* Opt attribute ((unused)),
881                                const char* Arg attribute ((unused)))
882 /* Forget all currently defined include paths */
883 {
884     CmdAddArg (&CC65, "--forget-inc-paths");
885 }
886
887
888
889 static void OptHelp (const char* Opt attribute ((unused)),
890                      const char* Arg attribute ((unused)))
891 /* Print help - cl65 */
892 {
893     Usage ();
894     exit (EXIT_SUCCESS);
895 }
896
897
898
899 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
900 /* Include directory (compiler) */
901 {
902     CmdAddArg2 (&CC65, "-I", Arg);
903 }
904
905
906
907 static void OptLdArgs (const char* Opt attribute ((unused)), const char* Arg)
908 /* Pass arguments to the linker */
909 {
910     CmdAddArgList (&LD65, Arg);
911 }
912
913
914
915 static void OptLib (const char* Opt attribute ((unused)), const char* Arg)
916 /* Library file follows (linker) */
917 {
918     CmdAddArg2 (&LD65, "--lib", Arg);
919 }
920
921
922
923 static void OptLibPath (const char* Opt attribute ((unused)), const char* Arg)
924 /* Library search path (linker) */
925 {
926     CmdAddArg2 (&LD65, "--lib-path", Arg);
927 }
928
929
930
931 static void OptListBytes (const char* Opt attribute ((unused)), const char* Arg)
932 /* Set the maximum number of bytes per asm listing line */
933 {
934     CmdAddArg2 (&CA65, "--list-bytes", Arg);
935 }
936
937
938
939 static void OptListing (const char* Opt attribute ((unused)),
940                         const char* Arg attribute ((unused)))
941 /* Create an assembler listing */
942 {
943     CmdAddArg (&CA65, "-l");
944 }
945
946
947
948 static void OptListTargets (const char* Opt attribute ((unused)),
949                             const char* Arg attribute ((unused)))
950 /* List all targets */
951 {
952     unsigned I;
953
954     /* List the targets */
955     for (I = TGT_NONE; I < TGT_COUNT; ++I) {
956         printf ("%s\n", TargetNames[I]);
957     }
958
959     /* Terminate */
960     exit (EXIT_SUCCESS);
961 }
962
963
964
965 static void OptMapFile (const char* Opt attribute ((unused)), const char* Arg)
966 /* Create a map file */
967 {
968     /* Create a map file (linker) */
969     CmdAddArg2 (&LD65, "-m", Arg);
970 }
971
972
973
974 static void OptMemoryModel (const char* Opt attribute ((unused)), const char* Arg)
975 /* Set the memory model */
976 {
977     mmodel_t MemoryModel = FindMemoryModel (Arg);
978     if (MemoryModel == MMODEL_UNKNOWN) {
979         Error ("Unknown memory model: %s", Arg);
980     } else if (MemoryModel == MMODEL_HUGE) {
981         Error ("Unsupported memory model: %s", Arg);
982     } else {
983         CmdAddArg2 (&CA65, "-mm", Arg);
984         CmdAddArg2 (&CC65, "-mm", Arg);
985     }
986 }
987
988
989
990 static void OptModule (const char* Opt attribute ((unused)),
991                        const char* Arg attribute ((unused)))
992 /* Link as a module */
993 {
994     Module = 1;
995 }
996
997
998
999 static void OptModuleId (const char* Opt attribute ((unused)), const char* Arg)
1000 /* Specify a module if for the linker */
1001 {
1002     /* Pass it straight to the linker */
1003     CmdAddArg2 (&LD65, "--module-id", Arg);
1004 }
1005
1006
1007
1008 static void OptO65Model (const char* Opt attribute ((unused)), const char* Arg)
1009 /* Handle the --o65-model option */
1010 {
1011     CmdAddArg2 (&CO65, "-m", Arg);
1012 }
1013
1014
1015
1016 static void OptObj (const char* Opt attribute ((unused)), const char* Arg)
1017 /* Object file follows (linker) */
1018 {
1019     CmdAddArg2 (&LD65, "--obj", Arg);
1020 }
1021
1022
1023
1024 static void OptObjPath (const char* Opt attribute ((unused)), const char* Arg)
1025 /* Object file search path (linker) */
1026 {
1027     CmdAddArg2 (&LD65, "--obj-path", Arg);
1028 }
1029
1030
1031
1032 static void OptRegisterSpace (const char* Opt attribute ((unused)), const char* Arg)
1033 /* Handle the --register-space option */
1034 {
1035     CmdAddArg2 (&CC65, "--register-space", Arg);
1036 }
1037
1038
1039
1040 static void OptRegisterVars (const char* Opt attribute ((unused)),
1041                              const char* Arg attribute ((unused)))
1042 /* Handle the --register-vars option */
1043 {
1044     CmdAddArg (&CC65, "-r");
1045 }
1046
1047
1048
1049 static void OptRodataName (const char* Opt attribute ((unused)), const char* Arg)
1050 /* Handle the --rodata-name option */
1051 {
1052     CmdAddArg2 (&CC65, "--rodata-name", Arg);
1053 }
1054
1055
1056
1057 static void OptSignedChars (const char* Opt attribute ((unused)),
1058                             const char* Arg attribute ((unused)))
1059 /* Make default characters signed */
1060 {
1061     CmdAddArg (&CC65, "-j");
1062 }
1063
1064
1065
1066 static void OptStandard (const char* Opt attribute ((unused)), const char* Arg)
1067 /* Set the language standard */
1068 {
1069     CmdAddArg2 (&CC65, "--standard", Arg);
1070 }
1071
1072
1073
1074 static void OptStartAddr (const char* Opt attribute ((unused)), const char* Arg)
1075 /* Set the default start address */
1076 {
1077     CmdAddArg2 (&LD65, "-S", Arg);
1078 }
1079
1080
1081
1082 static void OptStaticLocals (const char* Opt attribute ((unused)),
1083                              const char* Arg attribute ((unused)))
1084 /* Place local variables in static storage */
1085 {
1086     CmdAddArg (&CC65, "-Cl");
1087 }
1088
1089
1090
1091 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
1092 /* Set the target system */
1093 {
1094     Target = FindTarget (Arg);
1095     if (Target == TGT_UNKNOWN) {
1096         Error ("No such target system: `%s'", Arg);
1097     } else if (Target == TGT_MODULE) {
1098         Error ("Cannot use `module' as target, use --module instead");
1099     }
1100 }
1101
1102
1103
1104 static void OptVerbose (const char* Opt attribute ((unused)),
1105                         const char* Arg attribute ((unused)))
1106 /* Verbose mode (compiler, assembler, linker) */
1107 {
1108     CmdAddArg (&CC65, "-v");
1109     CmdAddArg (&CA65, "-v");
1110     CmdAddArg (&CO65, "-v");
1111     CmdAddArg (&LD65, "-v");
1112 }
1113
1114
1115
1116 static void OptVersion (const char* Opt attribute ((unused)),
1117                         const char* Arg attribute ((unused)))
1118 /* Print version number */
1119 {
1120     fprintf (stderr,
1121              "cl65 V%u.%u.%u - (C) Copyright 1998-2005 Ullrich von Bassewitz\n",
1122              VER_MAJOR, VER_MINOR, VER_PATCH);
1123 }
1124
1125
1126
1127 static void OptZeropageLabel (const char* Opt attribute ((unused)), const char* Arg)
1128 /* Handle the --zeropage-label option */
1129 {
1130     CmdAddArg2 (&CO65, "--zeropage-label", Arg);
1131 }
1132
1133
1134
1135 static void OptZeropageName (const char* Opt attribute ((unused)), const char* Arg)
1136 /* Handle the --zeropage-name option */
1137 {
1138     CmdAddArg2 (&CO65, "--zeropage-name", Arg);
1139 }
1140
1141
1142
1143 int main (int argc, char* argv [])
1144 /* Utility main program */
1145 {
1146     /* Program long options */
1147     static const LongOpt OptTab[] = {
1148         { "--add-source",       0,      OptAddSource            },
1149         { "--asm-args",         1,      OptAsmArgs              },
1150         { "--asm-define",       1,      OptAsmDefine            },
1151         { "--asm-include-dir",  1,      OptAsmIncludeDir        },
1152         { "--bss-label",        1,      OptBssLabel             },
1153         { "--bss-name",         1,      OptBssName              },
1154         { "--cfg-path",         1,      OptCfgPath              },
1155         { "--check-stack",      0,      OptCheckStack           },
1156         { "--code-label",       1,      OptCodeLabel            },
1157         { "--code-name",        1,      OptCodeName             },
1158         { "--codesize",         1,      OptCodeSize             },
1159         { "--config",           1,      OptConfig               },
1160         { "--cpu",              1,      OptCPU                  },
1161         { "--create-dep",       0,      OptCreateDep            },
1162         { "--data-label",       1,      OptDataLabel            },
1163         { "--data-name",        1,      OptDataName             },
1164         { "--debug",            0,      OptDebug                },
1165         { "--debug-info",       0,      OptDebugInfo            },
1166         { "--feature",          1,      OptFeature              },
1167         { "--forget-inc-paths", 0,      OptForgetIncPaths       },
1168         { "--help",             0,      OptHelp                 },
1169         { "--include-dir",      1,      OptIncludeDir           },
1170         { "--ld-args",          1,      OptLdArgs               },
1171         { "--lib",              1,      OptLib                  },
1172         { "--lib-path",         1,      OptLibPath              },
1173         { "--list-targets",     0,      OptListTargets          },
1174         { "--listing",          0,      OptListing              },
1175         { "--list-bytes",       1,      OptListBytes            },
1176         { "--mapfile",          1,      OptMapFile              },
1177         { "--memory-model",     1,      OptMemoryModel          },
1178         { "--module",           0,      OptModule               },
1179         { "--module-id",        1,      OptModuleId             },
1180         { "--o65-model",        1,      OptO65Model             },
1181         { "--obj",              1,      OptObj                  },
1182         { "--obj-path",         1,      OptObjPath              },
1183         { "--register-space",   1,      OptRegisterSpace        },
1184         { "--register-vars",    0,      OptRegisterVars         },
1185         { "--rodata-name",      1,      OptRodataName           },
1186         { "--signed-chars",     0,      OptSignedChars          },
1187         { "--standard",         1,      OptStandard             },
1188         { "--start-addr",       1,      OptStartAddr            },
1189         { "--static-locals",    0,      OptStaticLocals         },
1190         { "--target",           1,      OptTarget               },
1191         { "--verbose",          0,      OptVerbose              },
1192         { "--version",          0,      OptVersion              },
1193         { "--zeropage-label",   1,      OptZeropageLabel        },
1194         { "--zeropage-name",    1,      OptZeropageName         },
1195     };
1196
1197     unsigned I;
1198
1199     /* Initialize the cmdline module */
1200     InitCmdLine (&argc, &argv, "cl65");
1201
1202     /* Initialize the command descriptors */
1203     CmdInit (&CC65, "cc65");
1204     CmdInit (&CA65, "ca65");
1205     CmdInit (&CO65, "co65");
1206     CmdInit (&LD65, "ld65");
1207     CmdInit (&GRC,  "grc");
1208
1209     /* Our default target is the C64 instead of "none" */
1210     Target = TGT_C64;
1211
1212     /* Check the parameters */
1213     I = 1;
1214     while (I < ArgCount) {
1215
1216         /* Get the argument */
1217         const char* Arg = ArgVec[I];
1218
1219         /* Check for an option */
1220         if (Arg [0] == '-') {
1221
1222             switch (Arg [1]) {
1223
1224                 case '-':
1225                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
1226                     break;
1227
1228                 case 'C':
1229                     if (Arg[2] == 'l' && Arg[3] == '\0') {
1230                         /* Make local variables static */
1231                         OptStaticLocals (Arg, 0);
1232                     } else {
1233                         /* Specify linker config file */
1234                         OptConfig (Arg, GetArg (&I, 2));
1235                     }
1236                     break;
1237
1238                 case 'D':
1239                     /* Define a preprocessor symbol (compiler) */
1240                     CmdAddArg2 (&CC65, "-D", GetArg (&I, 2));
1241                     break;
1242
1243                 case 'I':
1244                     /* Include directory (compiler) */
1245                     OptIncludeDir (Arg, GetArg (&I, 2));
1246                     break;
1247
1248                 case 'L':
1249                     if (Arg[2] == 'n' && Arg[3] == '\0') {
1250                         /* VICE label file (linker) */
1251                         CmdAddArg2 (&LD65, "-Ln", GetArg (&I, 3));
1252                     } else {
1253                         /* Library search path (linker) */
1254                         OptLibPath (Arg, GetArg (&I, 2));
1255                     }
1256                     break;
1257
1258                 case 'O':
1259                     /* Optimize code (compiler, also covers -Oi and others) */
1260                     CmdAddArg (&CC65, Arg);
1261                     break;
1262
1263                 case 'S':
1264                     /* Dont assemble and link the created files */
1265                     DontLink = DontAssemble = 1;
1266                     break;
1267
1268                 case 'T':
1269                     /* Include source as comment (compiler) */
1270                     OptAddSource (Arg, 0);
1271                     break;
1272
1273                 case 'V':
1274                     /* Print version number */
1275                     OptVersion (Arg, 0);
1276                     break;
1277
1278                 case 'W':
1279                     switch (Arg[2]) {
1280
1281                         case 'a':
1282                             OptAsmArgs (Arg, GetArg (&I, 3));
1283                             break;
1284
1285                         case 'l':
1286                             OptLdArgs (Arg, GetArg (&I, 3));
1287                             break;
1288
1289                         case '\0':
1290                             /* Suppress warnings - compiler and assembler */
1291                             CmdAddArg (&CC65, "-W");
1292                             CmdAddArg2 (&CA65, "-W", "0");
1293                             break;
1294
1295                         default:
1296                             UnknownOption (Arg);
1297                             break;
1298                     }
1299                     break;
1300
1301                 case 'c':
1302                     /* Don't link the resulting files */
1303                     DontLink = 1;
1304                     break;
1305
1306                 case 'd':
1307                     /* Debug mode (compiler) */
1308                     OptDebug (Arg, 0);
1309                     break;
1310
1311                 case 'g':
1312                     /* Debugging - add to compiler and assembler */
1313                     OptDebugInfo (Arg, 0);
1314                     break;
1315
1316                 case 'h':
1317                 case '?':
1318                     /* Print help - cl65 */
1319                     OptHelp (Arg, 0);
1320                     break;
1321
1322                 case 'j':
1323                     /* Default characters are signed */
1324                     OptSignedChars (Arg, 0);
1325                     break;
1326
1327                 case 'l':
1328                     /* Create an assembler listing */
1329                     OptListing (Arg, 0);
1330                     break;
1331
1332                 case 'm':
1333                     /* Create a map file (linker) */
1334                     OptMapFile (Arg, GetArg (&I, 2));
1335                     break;
1336
1337                 case 'o':
1338                     /* Name the output file */
1339                     OutputName = GetArg (&I, 2);
1340                     break;
1341
1342                 case 'r':
1343                     /* Enable register variables */
1344                     OptRegisterVars (Arg, 0);
1345                     break;
1346
1347                 case 't':
1348                     /* Set target system - compiler, assembler and linker */
1349                     OptTarget (Arg, GetArg (&I, 2));
1350                     break;
1351
1352                 case 'v':
1353                     if (Arg [2] == 'm') {
1354                         /* Verbose map file (linker) */
1355                         CmdAddArg (&LD65, "-vm");
1356                     } else {
1357                         /* Verbose mode (compiler, assembler, linker) */
1358                         OptVerbose (Arg, 0);
1359                     }
1360                     break;
1361
1362                 default:
1363                     UnknownOption (Arg);
1364             }
1365         } else {
1366
1367             /* Remember the first file name */
1368             if (FirstInput == 0) {
1369                 FirstInput = Arg;
1370             }
1371
1372             /* Determine the file type by the extension */
1373             switch (GetFileType (Arg)) {
1374
1375                 case FILETYPE_C:
1376                     /* Compile the file */
1377                     Compile (Arg);
1378                     break;
1379
1380                 case FILETYPE_ASM:
1381                     /* Assemble the file */
1382                     if (!DontAssemble) {
1383                         Assemble (Arg);
1384                     }
1385                     break;
1386
1387                 case FILETYPE_OBJ:
1388                 case FILETYPE_LIB:
1389                     /* Add to the linker files */
1390                     CmdAddFile (&LD65, Arg);
1391                     break;
1392
1393                 case FILETYPE_GR:
1394                     /* Add to the resource compiler files */
1395                     CompileRes (Arg);
1396                     break;
1397
1398                 case FILETYPE_O65:
1399                     /* Add the the object file converter files */
1400                     ConvertO65 (Arg);
1401                     break;
1402
1403                 default:
1404                     Error ("Don't know what to do with `%s'", Arg);
1405
1406             }
1407
1408         }
1409
1410         /* Next argument */
1411         ++I;
1412     }
1413
1414     /* Check if we had any input files */
1415     if (FirstInput == 0) {
1416         Warning ("No input files");
1417     }
1418
1419     /* Link the given files if requested and if we have any */
1420     if (DontLink == 0 && LD65.FileCount > 0) {
1421         Link ();
1422     }
1423
1424     /* Return an apropriate exit code */
1425     return EXIT_SUCCESS;
1426 }
1427
1428
1429