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