OSDN Git Service

Remove CYGNUS LOCAL tags.
[pf3gnuchains/gcc-fork.git] / gcc / gcc.c
1 /* Compiler driver program that can handle many languages.
2    Copyright (C) 1987, 89, 92, 93, 94, 95, 1996 Free Software Foundation, Inc.
3
4 This file is part of GNU CC.
5
6 GNU CC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU CC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU CC; see the file COPYING.  If not, write to
18 the Free Software Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.
20
21 This paragraph is here to try to keep Sun CC from dying.
22 The number of chars here seems crucial!!!!  */
23
24 /* This program is the user interface to the C compiler and possibly to
25 other compilers.  It is used because compilation is a complicated procedure
26 which involves running several programs and passing temporary files between
27 them, forwarding the users switches to those programs selectively,
28 and deleting the temporary files at the end.
29
30 CC recognizes how to compile each input file by suffixes in the file names.
31 Once it knows which kind of compilation to perform, the procedure for
32 compilation is specified by a string called a "spec".  */
33 \f
34 #include <sys/types.h>
35 #include <ctype.h>
36 #include <signal.h>
37 #include <sys/stat.h>
38 #include <errno.h>
39
40 #ifndef _WIN32
41 #include <sys/file.h>   /* May get R_OK, etc. on some systems.  */
42 #else
43 #include <process.h>
44 int __spawnv ();
45 int __spawnvp ();
46 #endif
47
48 #include "config.h"
49 #include "obstack.h"
50 #include "gansidecl.h"
51
52 #ifdef __STDC__
53 #include <stdarg.h>
54 #else
55 #include <varargs.h>
56 #endif
57 #include <stdio.h>
58
59 /* Include multi-lib information.  */
60 #include "multilib.h"
61
62 #ifndef R_OK
63 #define R_OK 4
64 #define W_OK 2
65 #define X_OK 1
66 #endif
67
68 #ifndef WIFSIGNALED
69 #define WIFSIGNALED(S) (((S) & 0xff) != 0 && ((S) & 0xff) != 0x7f)
70 #endif
71 #ifndef WTERMSIG
72 #define WTERMSIG(S) ((S) & 0x7f)
73 #endif
74 #ifndef WIFEXITED
75 #define WIFEXITED(S) (((S) & 0xff) == 0)
76 #endif
77 #ifndef WEXITSTATUS
78 #define WEXITSTATUS(S) (((S) & 0xff00) >> 8)
79 #endif
80
81 /* Define O_RDONLY if the system hasn't defined it for us. */
82 #ifndef O_RDONLY
83 #define O_RDONLY 0
84 #endif
85
86 #ifdef USG
87 #define vfork fork
88 #endif /* USG */
89
90 /* Test if something is a normal file.  */
91 #ifndef S_ISREG
92 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
93 #endif
94
95 /* Test if something is a directory.  */
96 #ifndef S_ISDIR
97 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
98 #endif
99
100 /* By default there is no special suffix for executables.  */
101 #ifndef EXECUTABLE_SUFFIX
102 #define EXECUTABLE_SUFFIX ""
103 #endif
104
105 /* By default, the suffix for object files is ".o". */
106 #ifdef OBJECT_SUFFIX
107 #define HAVE_OBJECT_SUFFIX
108 #else
109 #define OBJECT_SUFFIX ".o"
110 #endif
111
112 /* By default, colon separates directories in a path.  */
113 #ifndef PATH_SEPARATOR
114 #define PATH_SEPARATOR ':'
115 #endif
116
117 #ifndef DIR_SEPARATOR
118 #define DIR_SEPARATOR '/'
119 #endif
120
121 static char dir_separator_str[] = {DIR_SEPARATOR, 0};
122
123 #define obstack_chunk_alloc xmalloc
124 #define obstack_chunk_free free
125
126 extern void free ();
127 extern char *getenv ();
128
129 extern char *choose_temp_base PROTO((void));
130
131 #ifndef errno
132 extern int errno;
133 #endif
134
135 #ifndef HAVE_STRERROR
136 extern int sys_nerr;
137 #if defined(bsd4_4)
138 extern const char *const sys_errlist[];
139 #else
140 extern char *sys_errlist[];
141 #endif
142 #else
143 extern char *strerror();
144 #endif
145
146 extern int execv (), execvp ();
147
148 /* If a stage of compilation returns an exit status >= 1,
149    compilation of that file ceases.  */
150
151 #define MIN_FATAL_STATUS 1
152
153 /* Flag saying to print the directories gcc will search through looking for
154    programs, libraries, etc.  */
155
156 static int print_search_dirs;
157
158 /* Flag saying to print the full filename of this file
159    as found through our usual search mechanism.  */
160
161 static char *print_file_name = NULL;
162
163 /* As print_file_name, but search for executable file. */
164
165 static char *print_prog_name = NULL;
166
167 /* Flag saying to print the relative path we'd use to
168    find libgcc.a given the current compiler flags.  */
169
170 static int print_multi_directory;
171
172 /* Flag saying to print the list of subdirectories and
173    compiler flags used to select them in a standard form.  */
174
175 static int print_multi_lib;
176
177 /* Flag indicating whether we should print the command and arguments */
178
179 static int verbose_flag;
180
181 /* Nonzero means write "temp" files in source directory
182    and use the source file's name in them, and don't delete them.  */
183
184 static int save_temps_flag;
185
186 /* The compiler version.  */
187
188 static char *compiler_version;
189
190 /* The target version specified with -V */
191
192 static char *spec_version = DEFAULT_TARGET_VERSION;
193
194 /* The target machine specified with -b.  */
195
196 static char *spec_machine = DEFAULT_TARGET_MACHINE;
197
198 /* Nonzero if cross-compiling.
199    When -b is used, the value comes from the `specs' file.  */
200
201 #ifdef CROSS_COMPILE
202 static int cross_compile = 1;
203 #else
204 static int cross_compile = 0;
205 #endif
206
207 /* The number of errors that have occurred; the link phase will not be
208    run if this is non-zero.  */
209 static int error_count = 0;
210
211 /* This is the obstack which we use to allocate many strings.  */
212
213 static struct obstack obstack;
214
215 /* This is the obstack to build an environment variable to pass to
216    collect2 that describes all of the relevant switches of what to
217    pass the compiler in building the list of pointers to constructors
218    and destructors.  */
219
220 static struct obstack collect_obstack;
221
222 extern char *version_string;
223
224 /* Forward declaration for prototypes.  */
225 struct path_prefix;
226
227 static void set_spec            PROTO((char *, char *));
228 static struct compiler *lookup_compiler PROTO((char *, int, char *));
229 static char *build_search_list  PROTO((struct path_prefix *, char *, int));
230 static void putenv_from_prefixes PROTO((struct path_prefix *, char *));
231 static char *find_a_file        PROTO((struct path_prefix *, char *, int));
232 static void add_prefix          PROTO((struct path_prefix *, char *, int, int, int *));
233 static char *skip_whitespace    PROTO((char *));
234 static void record_temp_file    PROTO((char *, int, int));
235 static void delete_if_ordinary  PROTO((char *));
236 static void delete_temp_files   PROTO((void));
237 static void delete_failure_queue PROTO((void));
238 static void clear_failure_queue PROTO((void));
239 static int check_live_switch    PROTO((int, int));
240 static char *handle_braces      PROTO((char *));
241 static char *save_string        PROTO((char *, int));
242 static char *concat             PVPROTO((char *, ...));
243 static int do_spec              PROTO((char *));
244 static int do_spec_1            PROTO((char *, int, char *));
245 static char *find_file          PROTO((char *));
246 static int is_directory         PROTO((char *, char *, int));
247 static void validate_switches   PROTO((char *));
248 static void validate_all_switches PROTO((void));
249 static void give_switch         PROTO((int, int));
250 static int used_arg             PROTO((char *, int));
251 static int default_arg          PROTO((char *, int));
252 static void set_multilib_dir    PROTO((void));
253 static void print_multilib_info PROTO((void));
254 static void pfatal_with_name    PROTO((char *));
255 static void perror_with_name    PROTO((char *));
256 static void perror_exec         PROTO((char *));
257 #ifdef HAVE_VPRINTF
258 static void fatal               PVPROTO((char *, ...));
259 static void error               PVPROTO((char *, ...));
260 #else
261 /* We must not provide any prototype here, even if ANSI C.  */
262 static void fatal               PROTO(());
263 static void error               PROTO(());
264 #endif
265
266 void fancy_abort ();
267 char *xmalloc ();
268 char *xrealloc ();
269 \f
270 /* Specs are strings containing lines, each of which (if not blank)
271 is made up of a program name, and arguments separated by spaces.
272 The program name must be exact and start from root, since no path
273 is searched and it is unreliable to depend on the current working directory.
274 Redirection of input or output is not supported; the subprograms must
275 accept filenames saying what files to read and write.
276
277 In addition, the specs can contain %-sequences to substitute variable text
278 or for conditional text.  Here is a table of all defined %-sequences.
279 Note that spaces are not generated automatically around the results of
280 expanding these sequences; therefore, you can concatenate them together
281 or with constant text in a single argument.
282
283  %%     substitute one % into the program name or argument.
284  %i     substitute the name of the input file being processed.
285  %b     substitute the basename of the input file being processed.
286         This is the substring up to (and not including) the last period
287         and not including the directory.
288  %g     substitute the temporary-file-name-base.  This is a string chosen
289         once per compilation.  Different temporary file names are made by
290         concatenation of constant strings on the end, as in `%g.s'.
291         %g also has the same effect of %d.
292  %u     like %g, but make the temporary file name unique.
293  %U     returns the last file name generated with %u.
294  %d     marks the argument containing or following the %d as a
295         temporary file name, so that that file will be deleted if CC exits
296         successfully.  Unlike %g, this contributes no text to the argument.
297  %w     marks the argument containing or following the %w as the
298         "output file" of this compilation.  This puts the argument
299         into the sequence of arguments that %o will substitute later.
300  %W{...}
301         like %{...} but mark last argument supplied within
302         as a file to be deleted on failure.
303  %o     substitutes the names of all the output files, with spaces
304         automatically placed around them.  You should write spaces
305         around the %o as well or the results are undefined.
306         %o is for use in the specs for running the linker.
307         Input files whose names have no recognized suffix are not compiled
308         at all, but they are included among the output files, so they will
309         be linked.
310  %O     substitutes the suffix for object files.
311  %p     substitutes the standard macro predefinitions for the
312         current target machine.  Use this when running cpp.
313  %P     like %p, but puts `__' before and after the name of each macro.
314         (Except macros that already have __.)
315         This is for ANSI C.
316  %I     Substitute a -iprefix option made from GCC_EXEC_PREFIX.
317  %s     current argument is the name of a library or startup file of some sort.
318         Search for that file in a standard list of directories
319         and substitute the full name found.
320  %eSTR  Print STR as an error message.  STR is terminated by a newline.
321         Use this when inconsistent options are detected.
322  %x{OPTION}     Accumulate an option for %X.
323  %X     Output the accumulated linker options specified by compilations.
324  %Y     Output the accumulated assembler options specified by compilations.
325  %Z     Output the accumulated preprocessor options specified by compilations.
326  %v1    Substitute the major version number of GCC.
327         (For version 2.5.n, this is 2.)
328  %v2    Substitute the minor version number of GCC.
329         (For version 2.5.n, this is 5.)
330  %a     process ASM_SPEC as a spec.
331         This allows config.h to specify part of the spec for running as.
332  %A     process ASM_FINAL_SPEC as a spec.  A capital A is actually
333         used here.  This can be used to run a post-processor after the
334         assembler has done it's job.
335  %D     Dump out a -L option for each directory in startfile_prefixes.
336         If multilib_dir is set, extra entries are generated with it affixed.
337  %l     process LINK_SPEC as a spec.
338  %L     process LIB_SPEC as a spec.
339  %G     process LIBGCC_SPEC as a spec.
340  %S     process STARTFILE_SPEC as a spec.  A capital S is actually used here.
341  %E     process ENDFILE_SPEC as a spec.  A capital E is actually used here.
342  %c     process SIGNED_CHAR_SPEC as a spec.
343  %C     process CPP_SPEC as a spec.  A capital C is actually used here.
344  %1     process CC1_SPEC as a spec.
345  %2     process CC1PLUS_SPEC as a spec.
346  %|     output "-" if the input for the current command is coming from a pipe.
347  %*     substitute the variable part of a matched option.  (See below.)
348         Note that each comma in the substituted string is replaced by
349         a single space.
350  %{S}   substitutes the -S switch, if that switch was given to CC.
351         If that switch was not specified, this substitutes nothing.
352         Here S is a metasyntactic variable.
353  %{S*}  substitutes all the switches specified to CC whose names start
354         with -S.  This is used for -o, -D, -I, etc; switches that take
355         arguments.  CC considers `-o foo' as being one switch whose
356         name starts with `o'.  %{o*} would substitute this text,
357         including the space; thus, two arguments would be generated.
358  %{S*:X} substitutes X if one or more switches whose names start with -S are
359         specified to CC.  Note that the tail part of the -S option
360         (i.e. the part matched by the `*') will be substituted for each
361         occurrence of %* within X.
362  %{S:X} substitutes X, but only if the -S switch was given to CC.
363  %{!S:X} substitutes X, but only if the -S switch was NOT given to CC.
364  %{|S:X} like %{S:X}, but if no S switch, substitute `-'.
365  %{|!S:X} like %{!S:X}, but if there is an S switch, substitute `-'.
366  %{.S:X} substitutes X, but only if processing a file with suffix S.
367  %{!.S:X} substitutes X, but only if NOT processing a file with suffix S.
368  %(Spec) processes a specification defined in a specs file as *Spec:
369  %[Spec] as above, but put __ around -D arguments
370
371 The conditional text X in a %{S:X} or %{!S:X} construct may contain
372 other nested % constructs or spaces, or even newlines.  They are
373 processed as usual, as described above.
374
375 The -O, -f, -m, and -W switches are handled specifically in these
376 constructs.  If another value of -O or the negated form of a -f, -m, or
377 -W switch is found later in the command line, the earlier switch
378 value is ignored, except with {S*} where S is just one letter; this
379 passes all matching options.
380
381 The character | is used to indicate that a command should be piped to
382 the following command, but only if -pipe is specified.
383
384 Note that it is built into CC which switches take arguments and which
385 do not.  You might think it would be useful to generalize this to
386 allow each compiler's spec to say which switches take arguments.  But
387 this cannot be done in a consistent fashion.  CC cannot even decide
388 which input files have been specified without knowing which switches
389 take arguments, and it must know which input files to compile in order
390 to tell which compilers to run.
391
392 CC also knows implicitly that arguments starting in `-l' are to be
393 treated as compiler output files, and passed to the linker in their
394 proper position among the other output files.  */
395 \f
396 /* Define the macros used for specs %a, %l, %L, %S, %c, %C, %1.  */
397
398 /* config.h can define ASM_SPEC to provide extra args to the assembler
399    or extra switch-translations.  */
400 #ifndef ASM_SPEC
401 #define ASM_SPEC ""
402 #endif
403
404 /* config.h can define ASM_FINAL_SPEC to run a post processor after
405    the assembler has run.  */
406 #ifndef ASM_FINAL_SPEC
407 #define ASM_FINAL_SPEC ""
408 #endif
409
410 /* config.h can define CPP_SPEC to provide extra args to the C preprocessor
411    or extra switch-translations.  */
412 #ifndef CPP_SPEC
413 #define CPP_SPEC ""
414 #endif
415
416 /* config.h can define CC1_SPEC to provide extra args to cc1 and cc1plus
417    or extra switch-translations.  */
418 #ifndef CC1_SPEC
419 #define CC1_SPEC ""
420 #endif
421
422 /* config.h can define CC1PLUS_SPEC to provide extra args to cc1plus
423    or extra switch-translations.  */
424 #ifndef CC1PLUS_SPEC
425 #define CC1PLUS_SPEC ""
426 #endif
427
428 /* config.h can define LINK_SPEC to provide extra args to the linker
429    or extra switch-translations.  */
430 #ifndef LINK_SPEC
431 #define LINK_SPEC ""
432 #endif
433
434 /* config.h can define LIB_SPEC to override the default libraries.  */
435 #ifndef LIB_SPEC
436 #define LIB_SPEC "%{!shared:%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}}"
437 #endif
438
439 /* config.h can define LIBGCC_SPEC to override how and when libgcc.a is
440    included.  */
441 #ifndef LIBGCC_SPEC
442 #if defined(LINK_LIBGCC_SPECIAL) || defined(LINK_LIBGCC_SPECIAL_1)
443 /* Have gcc do the search for libgcc.a.  */
444 #define LIBGCC_SPEC "libgcc.a%s"
445 #else
446 #define LIBGCC_SPEC "-lgcc"
447 #endif
448 #endif
449
450 /* config.h can define STARTFILE_SPEC to override the default crt0 files.  */
451 #ifndef STARTFILE_SPEC
452 #define STARTFILE_SPEC  \
453   "%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
454 #endif
455
456 /* config.h can define SWITCHES_NEED_SPACES to control which options
457    require spaces between the option and the argument.  */
458 #ifndef SWITCHES_NEED_SPACES
459 #define SWITCHES_NEED_SPACES ""
460 #endif
461
462 /* config.h can define ENDFILE_SPEC to override the default crtn files.  */
463 #ifndef ENDFILE_SPEC
464 #define ENDFILE_SPEC ""
465 #endif
466
467 /* This spec is used for telling cpp whether char is signed or not.  */
468 #ifndef SIGNED_CHAR_SPEC
469 /* Use #if rather than ?:
470    because MIPS C compiler rejects like ?: in initializers.  */
471 #if DEFAULT_SIGNED_CHAR
472 #define SIGNED_CHAR_SPEC "%{funsigned-char:-D__CHAR_UNSIGNED__}"
473 #else
474 #define SIGNED_CHAR_SPEC "%{!fsigned-char:-D__CHAR_UNSIGNED__}"
475 #endif
476 #endif
477
478 /* MULTILIB_SELECT comes from multilib.h.  It gives a
479    string interpreted by set_multilib_dir to select a library
480    subdirectory based on the compiler options.  */
481 #ifndef MULTILIB_SELECT
482 #define MULTILIB_SELECT ". ;"
483 #endif
484
485 static char *cpp_spec = CPP_SPEC;
486 static char *cpp_predefines = CPP_PREDEFINES;
487 static char *cc1_spec = CC1_SPEC;
488 static char *cc1plus_spec = CC1PLUS_SPEC;
489 static char *signed_char_spec = SIGNED_CHAR_SPEC;
490 static char *asm_spec = ASM_SPEC;
491 static char *asm_final_spec = ASM_FINAL_SPEC;
492 static char *link_spec = LINK_SPEC;
493 static char *lib_spec = LIB_SPEC;
494 static char *libgcc_spec = LIBGCC_SPEC;
495 static char *endfile_spec = ENDFILE_SPEC;
496 static char *startfile_spec = STARTFILE_SPEC;
497 static char *switches_need_spaces = SWITCHES_NEED_SPACES;
498 static char *multilib_select = MULTILIB_SELECT;
499
500 #ifdef EXTRA_SPECS
501 static struct { char *name, *spec; } extra_specs[] = { EXTRA_SPECS };
502 #endif
503
504 /* This defines which switch letters take arguments.  */
505
506 #define DEFAULT_SWITCH_TAKES_ARG(CHAR)      \
507   ((CHAR) == 'D' || (CHAR) == 'U' || (CHAR) == 'o' \
508    || (CHAR) == 'e' || (CHAR) == 'T' || (CHAR) == 'u' \
509    || (CHAR) == 'I' || (CHAR) == 'm' || (CHAR) == 'x' \
510    || (CHAR) == 'L' || (CHAR) == 'A')
511
512 #ifndef SWITCH_TAKES_ARG
513 #define SWITCH_TAKES_ARG(CHAR) DEFAULT_SWITCH_TAKES_ARG(CHAR)
514 #endif
515
516 /* This defines which multi-letter switches take arguments.  */
517
518 #define DEFAULT_WORD_SWITCH_TAKES_ARG(STR)              \
519  (!strcmp (STR, "Tdata") || !strcmp (STR, "Ttext")      \
520   || !strcmp (STR, "Tbss") || !strcmp (STR, "include")  \
521   || !strcmp (STR, "imacros") || !strcmp (STR, "aux-info") \
522   || !strcmp (STR, "idirafter") || !strcmp (STR, "iprefix") \
523   || !strcmp (STR, "iwithprefix") || !strcmp (STR, "iwithprefixbefore") \
524   || !strcmp (STR, "isystem"))
525
526 #ifndef WORD_SWITCH_TAKES_ARG
527 #define WORD_SWITCH_TAKES_ARG(STR) DEFAULT_WORD_SWITCH_TAKES_ARG (STR)
528 #endif
529 \f
530 /* Record the mapping from file suffixes for compilation specs.  */
531
532 struct compiler
533 {
534   char *suffix;                 /* Use this compiler for input files
535                                    whose names end in this suffix.  */
536
537   char *spec[4];                /* To use this compiler, concatenate these
538                                    specs and pass to do_spec.  */
539 };
540
541 /* Pointer to a vector of `struct compiler' that gives the spec for
542    compiling a file, based on its suffix.
543    A file that does not end in any of these suffixes will be passed
544    unchanged to the loader and nothing else will be done to it.
545
546    An entry containing two 0s is used to terminate the vector.
547
548    If multiple entries match a file, the last matching one is used.  */
549
550 static struct compiler *compilers;
551
552 /* Number of entries in `compilers', not counting the null terminator.  */
553
554 static int n_compilers;
555
556 /* The default list of file name suffixes and their compilation specs.  */
557
558 static struct compiler default_compilers[] =
559 {
560   {".c", "@c"},
561   {"@c",
562    "cpp -lang-c%{ansi:89} %{nostdinc*} %{C} %{v} %{A*} %{I*} %{P} %I\
563         %{C:%{!E:%eGNU C does not support -C without using -E}}\
564         %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d} %{MG}\
565         -undef -D__GNUC__=%v1 -D__GNUC_MINOR__=%v2\
566         %{ansi:-trigraphs -$ -D__STRICT_ANSI__}\
567         %{!undef:%{!ansi:%p} %P} %{trigraphs} \
568         %c %{O*:%{!O0:-D__OPTIMIZE__}} %{traditional} %{ftraditional:-traditional}\
569         %{traditional-cpp:-traditional}\
570         %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{D*} %{U*} %{i*} %Z\
571         %i %{!M:%{!MM:%{!E:%{!pipe:%g.i}}}}%{E:%W{o*}}%{M:%W{o*}}%{MM:%W{o*}} |\n",
572    "%{!M:%{!MM:%{!E:cc1 %{!pipe:%g.i} %1 \
573                    %{!Q:-quiet} -dumpbase %b.c %{d*} %{m*} %{a*}\
574                    %{g*} %{O*} %{W*} %{w} %{pedantic*} %{ansi} \
575                    %{traditional} %{v:-version} %{pg:-p} %{p} %{f*}\
576                    %{aux-info*}\
577                    %{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
578                    %{S:%W{o*}%{!o*:-o %b.s}}%{!S:-o %{|!pipe:%g.s}} |\n\
579               %{!S:as %a %Y\
580                       %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}\
581                       %{!pipe:%g.s} %A\n }}}}"},
582   {"-",
583    "%{E:cpp -lang-c%{ansi:89} %{nostdinc*} %{C} %{v} %{A*} %{I*} %{P} %I\
584         %{C:%{!E:%eGNU C does not support -C without using -E}}\
585         %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d} %{MG}\
586         -undef -D__GNUC__=%v1 -D__GNUC_MINOR__=%v2\
587         %{ansi:-trigraphs -$ -D__STRICT_ANSI__}\
588         %{!undef:%{!ansi:%p} %P} %{trigraphs}\
589         %c %{O*:%{!O0:-D__OPTIMIZE__}} %{traditional} %{ftraditional:-traditional}\
590         %{traditional-cpp:-traditional}\
591         %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{D*} %{U*} %{i*} %Z\
592         %i %W{o*}}\
593     %{!E:%e-E required when input is from standard input}"},
594   {".m", "@objective-c"},
595   {"@objective-c",
596    "cpp -lang-objc %{nostdinc*} %{C} %{v} %{A*} %{I*} %{P} %I\
597         %{C:%{!E:%eGNU C does not support -C without using -E}}\
598         %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d} %{MG}\
599         -undef -D__OBJC__ -D__GNUC__=%v1 -D__GNUC_MINOR__=%v2\
600          %{ansi:-trigraphs -$ -D__STRICT_ANSI__}\
601         %{!undef:%{!ansi:%p} %P} %{trigraphs}\
602         %c %{O*:%{!O0:-D__OPTIMIZE__}} %{traditional} %{ftraditional:-traditional}\
603         %{traditional-cpp:-traditional}\
604         %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{D*} %{U*} %{i*} %Z\
605         %i %{!M:%{!MM:%{!E:%{!pipe:%g.i}}}}%{E:%W{o*}}%{M:%W{o*}}%{MM:%W{o*}} |\n",
606    "%{!M:%{!MM:%{!E:cc1obj %{!pipe:%g.i} %1 \
607                    %{!Q:-quiet} -dumpbase %b.m %{d*} %{m*} %{a*}\
608                    %{g*} %{O*} %{W*} %{w} %{pedantic*} %{ansi} \
609                    %{traditional} %{v:-version} %{pg:-p} %{p} %{f*} \
610                    -lang-objc %{gen-decls} \
611                    %{aux-info*}\
612                    %{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
613                    %{S:%W{o*}%{!o*:-o %b.s}}%{!S:-o %{|!pipe:%g.s}} |\n\
614               %{!S:as %a %Y\
615                       %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}\
616                       %{!pipe:%g.s} %A\n }}}}"},
617   {".h", "@c-header"},
618   {"@c-header",
619    "%{!E:%eCompilation of header file requested} \
620     cpp %{nostdinc*} %{C} %{v} %{A*} %{I*} %{P} %I\
621         %{C:%{!E:%eGNU C does not support -C without using -E}}\
622          %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d} %{MG}\
623         -undef -D__GNUC__=%v1 -D__GNUC_MINOR__=%v2\
624          %{ansi:-trigraphs -$ -D__STRICT_ANSI__}\
625         %{!undef:%{!ansi:%p} %P} %{trigraphs}\
626         %c %{O*:%{!O0:-D__OPTIMIZE__}} %{traditional} %{ftraditional:-traditional}\
627         %{traditional-cpp:-traditional}\
628         %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{D*} %{U*} %{i*} %Z\
629         %i %W{o*}"},
630   {".i", "@cpp-output"},
631   {"@cpp-output",
632    "%{!M:%{!MM:%{!E:cc1 %i %1 %{!Q:-quiet} %{d*} %{m*} %{a*}\
633                         %{g*} %{O*} %{W*} %{w} %{pedantic*} %{ansi}\
634                         %{traditional} %{v:-version} %{pg:-p} %{p} %{f*}\
635                         %{aux-info*}\
636                         %{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
637                         %{S:%W{o*}%{!o*:-o %b.s}}%{!S:-o %{|!pipe:%g.s}} |\n\
638                      %{!S:as %a %Y\
639                              %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}\
640                              %{!pipe:%g.s} %A\n }}}}"},
641   {".s", "@assembler"},
642   {"@assembler",
643    "%{!M:%{!MM:%{!E:%{!S:as %a %Y\
644                             %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}\
645                             %i %A\n }}}}"},
646   {".S", "@assembler-with-cpp"},
647   {"@assembler-with-cpp",
648    "cpp -lang-asm %{nostdinc*} %{C} %{v} %{A*} %{I*} %{P} %I\
649         %{C:%{!E:%eGNU C does not support -C without using -E}}\
650         %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d} %{MG} %{trigraphs}\
651         -undef -$ %{!undef:%p %P} -D__ASSEMBLER__ \
652         %c %{O*:%{!O0:-D__OPTIMIZE__}} %{traditional} %{ftraditional:-traditional}\
653         %{traditional-cpp:-traditional}\
654         %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{D*} %{U*} %{i*} %Z\
655         %i %{!M:%{!MM:%{!E:%{!pipe:%g.s}}}}%{E:%W{o*}}%{M:%W{o*}}%{MM:%W{o*}} |\n",
656    "%{!M:%{!MM:%{!E:%{!S:as %a %Y\
657                     %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}\
658                     %{!pipe:%g.s} %A\n }}}}"},
659 #include "specs.h"
660   /* Mark end of table */
661   {0, 0}
662 };
663
664 /* Number of elements in default_compilers, not counting the terminator.  */
665
666 static int n_default_compilers
667   = (sizeof default_compilers / sizeof (struct compiler)) - 1;
668
669 /* Here is the spec for running the linker, after compiling all files.  */
670
671 /* -u* was put back because both BSD and SysV seem to support it.  */
672 /* %{static:} simply prevents an error message if the target machine
673    doesn't handle -static.  */
674 /* We want %{T*} after %{L*} and %D so that it can be used to specify linker
675    scripts which exist in user specified directories, or in standard
676    directories.  */
677 #ifdef LINK_LIBGCC_SPECIAL
678 /* Don't generate -L options.  */
679 static char *link_command_spec = "\
680 %{!fsyntax-only: \
681  %{!c:%{!M:%{!MM:%{!E:%{!S:ld %l %X %{o*} %{A} %{d} %{e*} %{m} %{N} %{n} \
682                         %{r} %{s} %{t} %{u*} %{x} %{z} %{Z}\
683                         %{!A:%{!nostdlib:%{!nostartfiles:%S}}}\
684                         %{static:} %{L*} %{T*} %o\
685                         %{!nostdlib:%{!nodefaultlibs:%G %L %G}}\
686                         %{!A:%{!nostdlib:%{!nostartfiles:%E}}}\n }}}}}}";
687 #else
688 /* Use -L.  */
689 static char *link_command_spec = "\
690 %{!fsyntax-only: \
691  %{!c:%{!M:%{!MM:%{!E:%{!S:ld %l %X %{o*} %{A} %{d} %{e*} %{m} %{N} %{n} \
692                         %{r} %{s} %{t} %{u*} %{x} %{z} %{Z}\
693                         %{!A:%{!nostdlib:%{!nostartfiles:%S}}}\
694                         %{static:} %{L*} %D %{T*} %o\
695                         %{!nostdlib:%{!nodefaultlibs:%G %L %G}}\
696                         %{!A:%{!nostdlib:%{!nostartfiles:%E}}}\n }}}}}}";
697 #endif
698
699 /* A vector of options to give to the linker.
700    These options are accumulated by %x,
701    and substituted into the linker command with %X.  */
702 static int n_linker_options;
703 static char **linker_options;
704
705 /* A vector of options to give to the assembler.
706    These options are accumulated by -Wa,
707    and substituted into the assembler command with %Y.  */
708 static int n_assembler_options;
709 static char **assembler_options;
710
711 /* A vector of options to give to the preprocessor.
712    These options are accumulated by -Wp,
713    and substituted into the preprocessor command with %Z.  */
714 static int n_preprocessor_options;
715 static char **preprocessor_options;
716 \f
717 /* Define how to map long options into short ones.  */
718
719 /* This structure describes one mapping.  */
720 struct option_map
721 {
722   /* The long option's name.  */
723   char *name;
724   /* The equivalent short option.  */
725   char *equivalent;
726   /* Argument info.  A string of flag chars; NULL equals no options.
727      a => argument required.
728      o => argument optional.
729      j => join argument to equivalent, making one word.
730      * => require other text after NAME as an argument.  */
731   char *arg_info;
732 };
733
734 /* This is the table of mappings.  Mappings are tried sequentially
735    for each option encountered; the first one that matches, wins.  */
736
737 struct option_map option_map[] =
738  {
739    {"--all-warnings", "-Wall", 0},
740    {"--ansi", "-ansi", 0},
741    {"--assemble", "-S", 0},
742    {"--assert", "-A", "a"},
743    {"--comments", "-C", 0},
744    {"--compile", "-c", 0},
745    {"--debug", "-g", "oj"},
746    {"--define-macro", "-D", "a"},
747    {"--dependencies", "-M", 0},
748    {"--dump", "-d", "a"},
749    {"--dumpbase", "-dumpbase", "a"},
750    {"--entry", "-e", 0},
751    {"--extra-warnings", "-W", 0},
752    {"--for-assembler", "-Wa", "a"},
753    {"--for-linker", "-Xlinker", "a"},
754    {"--force-link", "-u", "a"},
755    {"--imacros", "-imacros", "a"},
756    {"--include", "-include", "a"},
757    {"--include-barrier", "-I-", 0},
758    {"--include-directory", "-I", "a"},
759    {"--include-directory-after", "-idirafter", "a"},
760    {"--include-prefix", "-iprefix", "a"},
761    {"--include-with-prefix", "-iwithprefix", "a"},
762    {"--include-with-prefix-before", "-iwithprefixbefore", "a"},
763    {"--include-with-prefix-after", "-iwithprefix", "a"},
764    {"--language", "-x", "a"},
765    {"--library-directory", "-L", "a"},
766    {"--machine", "-m", "aj"},
767    {"--machine-", "-m", "*j"},
768    {"--no-line-commands", "-P", 0},
769    {"--no-precompiled-includes", "-noprecomp", 0},
770    {"--no-standard-includes", "-nostdinc", 0},
771    {"--no-standard-libraries", "-nostdlib", 0},
772    {"--no-warnings", "-w", 0},
773    {"--optimize", "-O", "oj"},
774    {"--output", "-o", "a"},
775    {"--pedantic", "-pedantic", 0},
776    {"--pedantic-errors", "-pedantic-errors", 0},
777    {"--pipe", "-pipe", 0},
778    {"--prefix", "-B", "a"},
779    {"--preprocess", "-E", 0},
780    {"--print-search-dirs", "-print-search-dirs", 0},
781    {"--print-file-name", "-print-file-name=", "aj"},
782    {"--print-libgcc-file-name", "-print-libgcc-file-name", 0},
783    {"--print-missing-file-dependencies", "-MG", 0},
784    {"--print-multi-lib", "-print-multi-lib", 0},
785    {"--print-multi-directory", "-print-multi-directory", 0},
786    {"--print-prog-name", "-print-prog-name=", "aj"},
787    {"--profile", "-p", 0},
788    {"--profile-blocks", "-a", 0},
789    {"--quiet", "-q", 0},
790    {"--save-temps", "-save-temps", 0},
791    {"--shared", "-shared", 0},
792    {"--silent", "-q", 0},
793    {"--static", "-static", 0},
794    {"--symbolic", "-symbolic", 0},
795    {"--target", "-b", "a"},
796    {"--trace-includes", "-H", 0},
797    {"--traditional", "-traditional", 0},
798    {"--traditional-cpp", "-traditional-cpp", 0},
799    {"--trigraphs", "-trigraphs", 0},
800    {"--undefine-macro", "-U", "a"},
801    {"--use-version", "-V", "a"},
802    {"--user-dependencies", "-MM", 0},
803    {"--verbose", "-v", 0},
804    {"--version", "-dumpversion", 0},
805    {"--warn-", "-W", "*j"},
806    {"--write-dependencies", "-MD", 0},
807    {"--write-user-dependencies", "-MMD", 0},
808    {"--", "-f", "*j"}
809  };
810 \f
811 /* Translate the options described by *ARGCP and *ARGVP.
812    Make a new vector and store it back in *ARGVP,
813    and store its length in *ARGVC.  */
814
815 static void
816 translate_options (argcp, argvp)
817      int *argcp;
818      char ***argvp;
819 {
820   int i, j, k;
821   int argc = *argcp;
822   char **argv = *argvp;
823   char **newv = (char **) xmalloc ((argc + 2) * 2 * sizeof (char *));
824   int newindex = 0;
825
826   i = 0;
827   newv[newindex++] = argv[i++];
828
829   while (i < argc)
830     {
831       /* Translate -- options.  */
832       if (argv[i][0] == '-' && argv[i][1] == '-')
833         {
834           /* Find a mapping that applies to this option.  */
835           for (j = 0; j < sizeof (option_map) / sizeof (option_map[0]); j++)
836             {
837               int optlen = strlen (option_map[j].name);
838               int arglen = strlen (argv[i]);
839               int complen = arglen > optlen ? optlen : arglen;
840               char *arginfo = option_map[j].arg_info;
841
842               if (arginfo == 0)
843                 arginfo = "";
844
845               if (!strncmp (argv[i], option_map[j].name, complen))
846                 {
847                   char *arg = 0;
848
849                   if (arglen < optlen)
850                     {
851                       for (k = j + 1;
852                            k < sizeof (option_map) / sizeof (option_map[0]);
853                            k++)
854                         if (strlen (option_map[k].name) >= arglen
855                             && !strncmp (argv[i], option_map[k].name, arglen))
856                           {
857                             error ("Ambiguous abbreviation %s", argv[i]);
858                             break;
859                           }
860
861                       if (k != sizeof (option_map) / sizeof (option_map[0]))
862                         break;
863                     }
864
865                   if (arglen > optlen)
866                     {
867                       /* If the option has an argument, accept that.  */
868                       if (argv[i][optlen] == '=')
869                         arg = argv[i] + optlen + 1;
870
871                       /* If this mapping requires extra text at end of name,
872                          accept that as "argument".  */
873                       else if (index (arginfo, '*') != 0)
874                         arg = argv[i] + optlen;
875
876                       /* Otherwise, extra text at end means mismatch.
877                          Try other mappings.  */
878                       else
879                         continue;
880                     }
881
882                   else if (index (arginfo, '*') != 0)
883                     {
884                       error ("Incomplete `%s' option", option_map[j].name);
885                       break;
886                     }
887
888                   /* Handle arguments.  */
889                   if (index (arginfo, 'a') != 0)
890                     {
891                       if (arg == 0)
892                         {
893                           if (i + 1 == argc)
894                             {
895                               error ("Missing argument to `%s' option",
896                                      option_map[j].name);
897                               break;
898                             }
899
900                           arg = argv[++i];
901                         }
902                     }
903                   else if (index (arginfo, '*') != 0)
904                     ;
905                   else if (index (arginfo, 'o') == 0)
906                     {
907                       if (arg != 0)
908                         error ("Extraneous argument to `%s' option",
909                                option_map[j].name);
910                       arg = 0;
911                     }
912
913                   /* Store the translation as one argv elt or as two.  */
914                   if (arg != 0 && index (arginfo, 'j') != 0)
915                     newv[newindex++] = concat (option_map[j].equivalent, arg,
916                                                NULL_PTR);
917                   else if (arg != 0)
918                     {
919                       newv[newindex++] = option_map[j].equivalent;
920                       newv[newindex++] = arg;
921                     }
922                   else
923                     newv[newindex++] = option_map[j].equivalent;
924
925                   break;
926                 }
927             }
928           i++;
929         }
930
931       /* Handle old-fashioned options--just copy them through,
932          with their arguments.  */
933       else if (argv[i][0] == '-')
934         {
935           char *p = argv[i] + 1;
936           int c = *p;
937           int nskip = 1;
938
939           if (SWITCH_TAKES_ARG (c) > (p[1] != 0))
940             nskip += SWITCH_TAKES_ARG (c) - (p[1] != 0);
941           else if (WORD_SWITCH_TAKES_ARG (p))
942             nskip += WORD_SWITCH_TAKES_ARG (p);
943           else if ((c == 'B' || c == 'b' || c == 'V' || c == 'x')
944                    && p[1] == 0)
945             nskip += 1;
946           else if (! strcmp (p, "Xlinker"))
947             nskip += 1;
948
949           /* Watch out for an option at the end of the command line that
950              is missing arguments, and avoid skipping past the end of the
951              command line.  */
952           if (nskip + i > argc)
953             nskip = argc - i;
954
955           while (nskip > 0)
956             {
957               newv[newindex++] = argv[i++];
958               nskip--;
959             }
960         }
961       else
962         /* Ordinary operands, or +e options.  */
963         newv[newindex++] = argv[i++];
964     }
965
966   newv[newindex] = 0;
967
968   *argvp = newv;
969   *argcp = newindex;
970 }
971 \f
972 char *
973 my_strerror(e)
974      int e;
975 {
976
977 #ifdef HAVE_STRERROR
978   return strerror(e);
979
980 #else
981
982   static char buffer[30];
983   if (!e)
984     return "cannot access";
985
986   if (e > 0 && e < sys_nerr)
987     return sys_errlist[e];
988
989   sprintf (buffer, "Unknown error %d", e);
990   return buffer;
991 #endif
992 }
993 \f
994 /* Read compilation specs from a file named FILENAME,
995    replacing the default ones.
996
997    A suffix which starts with `*' is a definition for
998    one of the machine-specific sub-specs.  The "suffix" should be
999    *asm, *cc1, *cpp, *link, *startfile, *signed_char, etc.
1000    The corresponding spec is stored in asm_spec, etc.,
1001    rather than in the `compilers' vector.
1002
1003    Anything invalid in the file is a fatal error.  */
1004
1005 static void
1006 read_specs (filename)
1007      char *filename;
1008 {
1009   int desc;
1010   int readlen;
1011   struct stat statbuf;
1012   char *buffer;
1013   register char *p;
1014
1015   if (verbose_flag)
1016     fprintf (stderr, "Reading specs from %s\n", filename);
1017
1018   /* Open and stat the file.  */
1019   desc = open (filename, O_RDONLY, 0);
1020   if (desc < 0)
1021     pfatal_with_name (filename);
1022   if (stat (filename, &statbuf) < 0)
1023     pfatal_with_name (filename);
1024
1025   /* Read contents of file into BUFFER.  */
1026   buffer = xmalloc ((unsigned) statbuf.st_size + 1);
1027   readlen = read (desc, buffer, (unsigned) statbuf.st_size);
1028   if (readlen < 0)
1029     pfatal_with_name (filename);
1030   buffer[readlen] = 0;
1031   close (desc);
1032
1033   /* Scan BUFFER for specs, putting them in the vector.  */
1034   p = buffer;
1035   while (1)
1036     {
1037       char *suffix;
1038       char *spec;
1039       char *in, *out, *p1, *p2;
1040
1041       /* Advance P in BUFFER to the next nonblank nocomment line.  */
1042       p = skip_whitespace (p);
1043       if (*p == 0)
1044         break;
1045
1046       /* Find the colon that should end the suffix.  */
1047       p1 = p;
1048       while (*p1 && *p1 != ':' && *p1 != '\n') p1++;
1049       /* The colon shouldn't be missing.  */
1050       if (*p1 != ':')
1051         fatal ("specs file malformed after %d characters", p1 - buffer);
1052       /* Skip back over trailing whitespace.  */
1053       p2 = p1;
1054       while (p2 > buffer && (p2[-1] == ' ' || p2[-1] == '\t')) p2--;
1055       /* Copy the suffix to a string.  */
1056       suffix = save_string (p, p2 - p);
1057       /* Find the next line.  */
1058       p = skip_whitespace (p1 + 1);
1059       if (p[1] == 0)
1060         fatal ("specs file malformed after %d characters", p - buffer);
1061       p1 = p;
1062       /* Find next blank line.  */
1063       while (*p1 && !(*p1 == '\n' && p1[1] == '\n')) p1++;
1064       /* Specs end at the blank line and do not include the newline.  */
1065       spec = save_string (p, p1 - p);
1066       p = p1;
1067
1068       /* Delete backslash-newline sequences from the spec.  */
1069       in = spec;
1070       out = spec;
1071       while (*in != 0)
1072         {
1073           if (in[0] == '\\' && in[1] == '\n')
1074             in += 2;
1075           else if (in[0] == '#')
1076             {
1077               while (*in && *in != '\n') in++;
1078             }
1079           else
1080             *out++ = *in++;
1081         }
1082       *out = 0;
1083
1084       if (suffix[0] == '*')
1085         {
1086           if (! strcmp (suffix, "*link_command"))
1087             link_command_spec = spec;
1088           else
1089             set_spec (suffix + 1, spec);
1090         }
1091       else
1092         {
1093           /* Add this pair to the vector.  */
1094           compilers
1095             = ((struct compiler *)
1096                xrealloc (compilers, (n_compilers + 2) * sizeof (struct compiler)));
1097           compilers[n_compilers].suffix = suffix;
1098           bzero ((char *) compilers[n_compilers].spec,
1099                  sizeof compilers[n_compilers].spec);
1100           compilers[n_compilers].spec[0] = spec;
1101           n_compilers++;
1102           bzero ((char *) &compilers[n_compilers],
1103                  sizeof compilers[n_compilers]);
1104         }
1105
1106       if (*suffix == 0)
1107         link_command_spec = spec;
1108     }
1109
1110   if (link_command_spec == 0)
1111     fatal ("spec file has no spec for linking");
1112 }
1113
1114 static char *
1115 skip_whitespace (p)
1116      char *p;
1117 {
1118   while (1)
1119     {
1120       /* A fully-blank line is a delimiter in the SPEC file and shouldn't
1121          be considered whitespace.  */
1122       if (p[0] == '\n' && p[1] == '\n' && p[2] == '\n')
1123         return p + 1;
1124       else if (*p == '\n' || *p == ' ' || *p == '\t')
1125         p++;
1126       else if (*p == '#')
1127         {
1128           while (*p != '\n') p++;
1129           p++;
1130         }
1131       else
1132         break;
1133     }
1134
1135   return p;
1136 }
1137 \f
1138 /* Structure to keep track of the specs that have been defined so far.  These
1139    are accessed using %(specname) or %[specname] in a compiler or link spec. */
1140
1141 struct spec_list
1142 {
1143   char *name;                 /* Name of the spec. */
1144   char *spec;                 /* The spec itself. */
1145   struct spec_list *next;     /* Next spec in linked list. */
1146 };
1147
1148 /* List of specs that have been defined so far. */
1149
1150 static struct spec_list *specs = (struct spec_list *) 0;
1151 \f
1152 /* Change the value of spec NAME to SPEC.  If SPEC is empty, then the spec is
1153    removed; If the spec starts with a + then SPEC is added to the end of the
1154    current spec. */
1155
1156 static void
1157 set_spec (name, spec)
1158      char *name;
1159      char *spec;
1160 {
1161   struct spec_list *sl;
1162   char *old_spec;
1163
1164   /* See if the spec already exists */
1165   for (sl = specs; sl; sl = sl->next)
1166     if (strcmp (sl->name, name) == 0)
1167       break;
1168
1169   if (!sl)
1170     {
1171       /* Not found - make it */
1172       sl = (struct spec_list *) xmalloc (sizeof (struct spec_list));
1173       sl->name = save_string (name, strlen (name));
1174       sl->spec = save_string ("", 0);
1175       sl->next = specs;
1176       specs = sl;
1177     }
1178
1179   old_spec = sl->spec;
1180   if (name && spec[0] == '+' && isspace (spec[1]))
1181     sl->spec = concat (old_spec, spec + 1, NULL_PTR);
1182   else
1183     sl->spec = save_string (spec, strlen (spec));
1184
1185   if (! strcmp (name, "asm"))
1186     asm_spec = sl->spec;
1187   else if (! strcmp (name, "asm_final"))
1188     asm_final_spec = sl->spec;
1189   else if (! strcmp (name, "cc1"))
1190     cc1_spec = sl->spec;
1191   else if (! strcmp (name, "cc1plus"))
1192     cc1plus_spec = sl->spec;
1193   else if (! strcmp (name, "cpp"))
1194     cpp_spec = sl->spec;
1195   else if (! strcmp (name, "endfile"))
1196     endfile_spec = sl->spec;
1197   else if (! strcmp (name, "lib"))
1198     lib_spec = sl->spec;
1199   else if (! strcmp (name, "libgcc"))
1200     libgcc_spec = sl->spec;
1201   else if (! strcmp (name, "link"))
1202     link_spec = sl->spec;
1203   else if (! strcmp (name, "predefines"))
1204     cpp_predefines = sl->spec;
1205   else if (! strcmp (name, "signed_char"))
1206     signed_char_spec = sl->spec;
1207   else if (! strcmp (name, "startfile"))
1208     startfile_spec = sl->spec;
1209   else if (! strcmp (name, "switches_need_spaces"))
1210     switches_need_spaces = sl->spec;
1211   else if (! strcmp (name, "cross_compile"))
1212     cross_compile = atoi (sl->spec);
1213   else if (! strcmp (name, "multilib"))
1214     multilib_select = sl->spec;
1215 #ifdef EXTRA_SPECS
1216   else
1217     {
1218       int i;
1219       for (i = 0; i < sizeof (extra_specs) / sizeof (extra_specs[0]); i++)
1220         {
1221           if (! strcmp (name, extra_specs[i].name))
1222             {
1223               extra_specs[i].spec = sl->spec;
1224               break;
1225             }
1226         }
1227     }
1228 #endif
1229
1230   /* Free the old spec */
1231   if (old_spec)
1232     free (old_spec);
1233 }
1234 \f
1235 /* Accumulate a command (program name and args), and run it.  */
1236
1237 /* Vector of pointers to arguments in the current line of specifications.  */
1238
1239 static char **argbuf;
1240
1241 /* Number of elements allocated in argbuf.  */
1242
1243 static int argbuf_length;
1244
1245 /* Number of elements in argbuf currently in use (containing args).  */
1246
1247 static int argbuf_index;
1248
1249 /* This is the list of suffixes and codes (%g/%u/%U) and the associated
1250    temp file.  Used only if MKTEMP_EACH_FILE.  */
1251
1252 static struct temp_name {
1253   char *suffix;         /* suffix associated with the code.  */
1254   int length;           /* strlen (suffix).  */
1255   int unique;           /* Indicates whether %g or %u/%U was used.  */
1256   char *filename;       /* associated filename.  */
1257   int filename_length;  /* strlen (filename).  */
1258   struct temp_name *next;
1259 } *temp_names;
1260
1261 /* Number of commands executed so far.  */
1262
1263 static int execution_count;
1264
1265 /* Number of commands that exited with a signal.  */
1266
1267 static int signal_count;
1268
1269 /* Name with which this program was invoked.  */
1270
1271 static char *programname;
1272 \f
1273 /* Structures to keep track of prefixes to try when looking for files. */
1274
1275 struct prefix_list
1276 {
1277   char *prefix;               /* String to prepend to the path. */
1278   struct prefix_list *next;   /* Next in linked list. */
1279   int require_machine_suffix; /* Don't use without machine_suffix.  */
1280   /* 2 means try both machine_suffix and just_machine_suffix.  */
1281   int *used_flag_ptr;         /* 1 if a file was found with this prefix.  */
1282 };
1283
1284 struct path_prefix
1285 {
1286   struct prefix_list *plist;  /* List of prefixes to try */
1287   int max_len;                /* Max length of a prefix in PLIST */
1288   char *name;                 /* Name of this list (used in config stuff) */
1289 };
1290
1291 /* List of prefixes to try when looking for executables. */
1292
1293 static struct path_prefix exec_prefixes = { 0, 0, "exec" };
1294
1295 /* List of prefixes to try when looking for startup (crt0) files. */
1296
1297 static struct path_prefix startfile_prefixes = { 0, 0, "startfile" };
1298
1299 /* List of prefixes to try when looking for include files.  */
1300
1301 static struct path_prefix include_prefixes = { 0, 0, "include" };
1302
1303 /* Suffix to attach to directories searched for commands.
1304    This looks like `MACHINE/VERSION/'.  */
1305
1306 static char *machine_suffix = 0;
1307
1308 /* Suffix to attach to directories searched for commands.
1309    This is just `MACHINE/'.  */
1310
1311 static char *just_machine_suffix = 0;
1312
1313 /* Adjusted value of GCC_EXEC_PREFIX envvar.  */
1314
1315 static char *gcc_exec_prefix;
1316
1317 /* Default prefixes to attach to command names.  */
1318
1319 #ifdef CROSS_COMPILE  /* Don't use these prefixes for a cross compiler.  */
1320 #undef MD_EXEC_PREFIX
1321 #undef MD_STARTFILE_PREFIX
1322 #undef MD_STARTFILE_PREFIX_1
1323 #endif
1324
1325 #ifndef STANDARD_EXEC_PREFIX
1326 #define STANDARD_EXEC_PREFIX "/usr/local/lib/gcc-lib/"
1327 #endif /* !defined STANDARD_EXEC_PREFIX */
1328
1329 static char *standard_exec_prefix = STANDARD_EXEC_PREFIX;
1330 static char *standard_exec_prefix_1 = "/usr/lib/gcc/";
1331 #ifdef MD_EXEC_PREFIX
1332 static char *md_exec_prefix = MD_EXEC_PREFIX;
1333 #endif
1334
1335 #ifndef STANDARD_STARTFILE_PREFIX
1336 #define STANDARD_STARTFILE_PREFIX "/usr/local/lib/"
1337 #endif /* !defined STANDARD_STARTFILE_PREFIX */
1338
1339 #ifdef MD_STARTFILE_PREFIX
1340 static char *md_startfile_prefix = MD_STARTFILE_PREFIX;
1341 #endif
1342 #ifdef MD_STARTFILE_PREFIX_1
1343 static char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
1344 #endif
1345 static char *standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
1346 static char *standard_startfile_prefix_1 = "/lib/";
1347 static char *standard_startfile_prefix_2 = "/usr/lib/";
1348
1349 #ifndef TOOLDIR_BASE_PREFIX
1350 #define TOOLDIR_BASE_PREFIX "/usr/local/"
1351 #endif
1352 static char *tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
1353 static char *tooldir_prefix;
1354
1355 /* Subdirectory to use for locating libraries.  Set by
1356    set_multilib_dir based on the compilation options.  */
1357
1358 static char *multilib_dir;
1359
1360 /* Clear out the vector of arguments (after a command is executed).  */
1361
1362 static void
1363 clear_args ()
1364 {
1365   argbuf_index = 0;
1366 }
1367
1368 /* Add one argument to the vector at the end.
1369    This is done when a space is seen or at the end of the line.
1370    If DELETE_ALWAYS is nonzero, the arg is a filename
1371     and the file should be deleted eventually.
1372    If DELETE_FAILURE is nonzero, the arg is a filename
1373     and the file should be deleted if this compilation fails.  */
1374
1375 static void
1376 store_arg (arg, delete_always, delete_failure)
1377      char *arg;
1378      int delete_always, delete_failure;
1379 {
1380   if (argbuf_index + 1 == argbuf_length)
1381     {
1382       argbuf = (char **) xrealloc (argbuf, (argbuf_length *= 2) * sizeof (char *));
1383     }
1384
1385   argbuf[argbuf_index++] = arg;
1386   argbuf[argbuf_index] = 0;
1387
1388   if (delete_always || delete_failure)
1389     record_temp_file (arg, delete_always, delete_failure);
1390 }
1391 \f
1392 /* Record the names of temporary files we tell compilers to write,
1393    and delete them at the end of the run.  */
1394
1395 /* This is the common prefix we use to make temp file names.
1396    It is chosen once for each run of this program.
1397    It is substituted into a spec by %g.
1398    Thus, all temp file names contain this prefix.
1399    In practice, all temp file names start with this prefix.
1400
1401    This prefix comes from the envvar TMPDIR if it is defined;
1402    otherwise, from the P_tmpdir macro if that is defined;
1403    otherwise, in /usr/tmp or /tmp;
1404    or finally the current directory if all else fails.  */
1405
1406 static char *temp_filename;
1407
1408 /* Length of the prefix.  */
1409
1410 static int temp_filename_length;
1411
1412 /* Define the list of temporary files to delete.  */
1413
1414 struct temp_file
1415 {
1416   char *name;
1417   struct temp_file *next;
1418 };
1419
1420 /* Queue of files to delete on success or failure of compilation.  */
1421 static struct temp_file *always_delete_queue;
1422 /* Queue of files to delete on failure of compilation.  */
1423 static struct temp_file *failure_delete_queue;
1424
1425 /* Record FILENAME as a file to be deleted automatically.
1426    ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
1427    otherwise delete it in any case.
1428    FAIL_DELETE nonzero means delete it if a compilation step fails;
1429    otherwise delete it in any case.  */
1430
1431 static void
1432 record_temp_file (filename, always_delete, fail_delete)
1433      char *filename;
1434      int always_delete;
1435      int fail_delete;
1436 {
1437   register char *name;
1438   name = xmalloc (strlen (filename) + 1);
1439   strcpy (name, filename);
1440
1441   if (always_delete)
1442     {
1443       register struct temp_file *temp;
1444       for (temp = always_delete_queue; temp; temp = temp->next)
1445         if (! strcmp (name, temp->name))
1446           goto already1;
1447       temp = (struct temp_file *) xmalloc (sizeof (struct temp_file));
1448       temp->next = always_delete_queue;
1449       temp->name = name;
1450       always_delete_queue = temp;
1451     already1:;
1452     }
1453
1454   if (fail_delete)
1455     {
1456       register struct temp_file *temp;
1457       for (temp = failure_delete_queue; temp; temp = temp->next)
1458         if (! strcmp (name, temp->name))
1459           goto already2;
1460       temp = (struct temp_file *) xmalloc (sizeof (struct temp_file));
1461       temp->next = failure_delete_queue;
1462       temp->name = name;
1463       failure_delete_queue = temp;
1464     already2:;
1465     }
1466 }
1467
1468 /* Delete all the temporary files whose names we previously recorded.  */
1469
1470 static void
1471 delete_if_ordinary (name)
1472      char *name;
1473 {
1474   struct stat st;
1475 #ifdef DEBUG
1476   int i, c;
1477
1478   printf ("Delete %s? (y or n) ", name);
1479   fflush (stdout);
1480   i = getchar ();
1481   if (i != '\n')
1482     while ((c = getchar ()) != '\n' && c != EOF) ;
1483   if (i == 'y' || i == 'Y')
1484 #endif /* DEBUG */
1485     if (stat (name, &st) >= 0 && S_ISREG (st.st_mode))
1486       if (unlink (name) < 0)
1487         if (verbose_flag)
1488           perror_with_name (name);
1489 }
1490
1491 static void
1492 delete_temp_files ()
1493 {
1494   register struct temp_file *temp;
1495
1496   for (temp = always_delete_queue; temp; temp = temp->next)
1497     delete_if_ordinary (temp->name);
1498   always_delete_queue = 0;
1499 }
1500
1501 /* Delete all the files to be deleted on error.  */
1502
1503 static void
1504 delete_failure_queue ()
1505 {
1506   register struct temp_file *temp;
1507
1508   for (temp = failure_delete_queue; temp; temp = temp->next)
1509     delete_if_ordinary (temp->name);
1510 }
1511
1512 static void
1513 clear_failure_queue ()
1514 {
1515   failure_delete_queue = 0;
1516 }
1517 \f
1518 /* Routine to add variables to the environment.  We do this to pass
1519    the pathname of the gcc driver, and the directories search to the
1520    collect2 program, which is being run as ld.  This way, we can be
1521    sure of executing the right compiler when collect2 wants to build
1522    constructors and destructors.  Since the environment variables we
1523    use come from an obstack, we don't have to worry about allocating
1524    space for them.  */
1525
1526 #ifndef HAVE_PUTENV
1527
1528 void
1529 putenv (str)
1530      char *str;
1531 {
1532 #ifndef VMS                     /* nor about VMS */
1533
1534   extern char **environ;
1535   char **old_environ = environ;
1536   char **envp;
1537   int num_envs = 0;
1538   int name_len = 1;
1539   int str_len = strlen (str);
1540   char *p = str;
1541   int ch;
1542
1543   while ((ch = *p++) != '\0' && ch != '=')
1544     name_len++;
1545
1546   if (!ch)
1547     abort ();
1548
1549   /* Search for replacing an existing environment variable, and
1550      count the number of total environment variables.  */
1551   for (envp = old_environ; *envp; envp++)
1552     {
1553       num_envs++;
1554       if (!strncmp (str, *envp, name_len))
1555         {
1556           *envp = str;
1557           return;
1558         }
1559     }
1560
1561   /* Add a new environment variable */
1562   environ = (char **) xmalloc (sizeof (char *) * (num_envs+2));
1563   *environ = str;
1564   bcopy ((char *) old_environ, (char *) (environ + 1),
1565          sizeof (char *) * (num_envs+1));
1566
1567 #endif  /* VMS */
1568 }
1569
1570 #endif  /* HAVE_PUTENV */
1571
1572 \f
1573 /* Build a list of search directories from PATHS.
1574    PREFIX is a string to prepend to the list.
1575    If CHECK_DIR_P is non-zero we ensure the directory exists.
1576    This is used mostly by putenv_from_prefixes so we use `collect_obstack'.
1577    It is also used by the --print-search-dirs flag.  */
1578
1579 static char *
1580 build_search_list (paths, prefix, check_dir_p)
1581      struct path_prefix *paths;
1582      char *prefix;
1583      int check_dir_p;
1584 {
1585   int suffix_len = (machine_suffix) ? strlen (machine_suffix) : 0;
1586   int just_suffix_len
1587     = (just_machine_suffix) ? strlen (just_machine_suffix) : 0;
1588   int first_time = TRUE;
1589   struct prefix_list *pprefix;
1590
1591   obstack_grow (&collect_obstack, prefix, strlen (prefix));
1592
1593   for (pprefix = paths->plist; pprefix != 0; pprefix = pprefix->next)
1594     {
1595       int len = strlen (pprefix->prefix);
1596
1597       if (machine_suffix
1598           && (!check_dir_p
1599               || is_directory (pprefix->prefix, machine_suffix, 0)))
1600         {
1601           if (!first_time)
1602             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1603             
1604           first_time = FALSE;
1605           obstack_grow (&collect_obstack, pprefix->prefix, len);
1606           obstack_grow (&collect_obstack, machine_suffix, suffix_len);
1607         }
1608
1609       if (just_machine_suffix
1610           && pprefix->require_machine_suffix == 2
1611           && (!check_dir_p
1612               || is_directory (pprefix->prefix, just_machine_suffix, 0)))
1613         {
1614           if (!first_time)
1615             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1616             
1617           first_time = FALSE;
1618           obstack_grow (&collect_obstack, pprefix->prefix, len);
1619           obstack_grow (&collect_obstack, just_machine_suffix,
1620                         just_suffix_len);
1621         }
1622
1623       if (!pprefix->require_machine_suffix)
1624         {
1625           if (!first_time)
1626             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1627
1628           first_time = FALSE;
1629           obstack_grow (&collect_obstack, pprefix->prefix, len);
1630         }
1631     }
1632   obstack_1grow (&collect_obstack, '\0');
1633   return obstack_finish (&collect_obstack);
1634 }
1635
1636 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables for collect.  */
1637
1638 static void
1639 putenv_from_prefixes (paths, env_var)
1640      struct path_prefix *paths;
1641      char *env_var;
1642 {
1643   putenv (build_search_list (paths, env_var, 1));
1644 }
1645 \f
1646 /* Search for NAME using the prefix list PREFIXES.  MODE is passed to
1647    access to check permissions.
1648    Return 0 if not found, otherwise return its name, allocated with malloc. */
1649
1650 static char *
1651 find_a_file (pprefix, name, mode)
1652      struct path_prefix *pprefix;
1653      char *name;
1654      int mode;
1655 {
1656   char *temp;
1657   char *file_suffix = ((mode & X_OK) != 0 ? EXECUTABLE_SUFFIX : "");
1658   struct prefix_list *pl;
1659   int len = pprefix->max_len + strlen (name) + strlen (file_suffix) + 1;
1660
1661   if (machine_suffix)
1662     len += strlen (machine_suffix);
1663
1664   temp = xmalloc (len);
1665
1666   /* Determine the filename to execute (special case for absolute paths).  */
1667
1668   if (*name == '/' || *name == DIR_SEPARATOR)
1669     {
1670       if (access (name, mode))
1671         {
1672           strcpy (temp, name);
1673           return temp;
1674         }
1675     }
1676   else
1677     for (pl = pprefix->plist; pl; pl = pl->next)
1678       {
1679         if (machine_suffix)
1680           {
1681             /* Some systems have a suffix for executable files.
1682                So try appending that first.  */
1683             if (file_suffix[0] != 0)
1684               {
1685                 strcpy (temp, pl->prefix);
1686                 strcat (temp, machine_suffix);
1687                 strcat (temp, name);
1688                 strcat (temp, file_suffix);
1689                 if (access (temp, mode) == 0)
1690                   {
1691                     if (pl->used_flag_ptr != 0)
1692                       *pl->used_flag_ptr = 1;
1693                     return temp;
1694                   }
1695               }
1696
1697             /* Now try just the name.  */
1698             strcpy (temp, pl->prefix);
1699             strcat (temp, machine_suffix);
1700             strcat (temp, name);
1701             if (access (temp, mode) == 0)
1702               {
1703                 if (pl->used_flag_ptr != 0)
1704                   *pl->used_flag_ptr = 1;
1705                 return temp;
1706               }
1707           }
1708
1709         /* Certain prefixes are tried with just the machine type,
1710            not the version.  This is used for finding as, ld, etc.  */
1711         if (just_machine_suffix && pl->require_machine_suffix == 2)
1712           {
1713             /* Some systems have a suffix for executable files.
1714                So try appending that first.  */
1715             if (file_suffix[0] != 0)
1716               {
1717                 strcpy (temp, pl->prefix);
1718                 strcat (temp, just_machine_suffix);
1719                 strcat (temp, name);
1720                 strcat (temp, file_suffix);
1721                 if (access (temp, mode) == 0)
1722                   {
1723                     if (pl->used_flag_ptr != 0)
1724                       *pl->used_flag_ptr = 1;
1725                     return temp;
1726                   }
1727               }
1728
1729             strcpy (temp, pl->prefix);
1730             strcat (temp, just_machine_suffix);
1731             strcat (temp, name);
1732             if (access (temp, mode) == 0)
1733               {
1734                 if (pl->used_flag_ptr != 0)
1735                   *pl->used_flag_ptr = 1;
1736                 return temp;
1737               }
1738           }
1739
1740         /* Certain prefixes can't be used without the machine suffix
1741            when the machine or version is explicitly specified.  */
1742         if (!pl->require_machine_suffix)
1743           {
1744             /* Some systems have a suffix for executable files.
1745                So try appending that first.  */
1746             if (file_suffix[0] != 0)
1747               {
1748                 strcpy (temp, pl->prefix);
1749                 strcat (temp, name);
1750                 strcat (temp, file_suffix);
1751                 if (access (temp, mode) == 0)
1752                   {
1753                     if (pl->used_flag_ptr != 0)
1754                       *pl->used_flag_ptr = 1;
1755                     return temp;
1756                   }
1757               }
1758
1759             strcpy (temp, pl->prefix);
1760             strcat (temp, name);
1761             if (access (temp, mode) == 0)
1762               {
1763                 if (pl->used_flag_ptr != 0)
1764                   *pl->used_flag_ptr = 1;
1765                 return temp;
1766               }
1767           }
1768       }
1769
1770   free (temp);
1771   return 0;
1772 }
1773
1774 /* Add an entry for PREFIX in PLIST.  If FIRST is set, it goes
1775    at the start of the list, otherwise it goes at the end.
1776
1777    If WARN is nonzero, we will warn if no file is found
1778    through this prefix.  WARN should point to an int
1779    which will be set to 1 if this entry is used.
1780
1781    REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
1782    the complete value of machine_suffix.
1783    2 means try both machine_suffix and just_machine_suffix.  */
1784
1785 static void
1786 add_prefix (pprefix, prefix, first, require_machine_suffix, warn)
1787      struct path_prefix *pprefix;
1788      char *prefix;
1789      int first;
1790      int require_machine_suffix;
1791      int *warn;
1792 {
1793   struct prefix_list *pl, **prev;
1794   int len;
1795
1796   if (!first && pprefix->plist)
1797     {
1798       for (pl = pprefix->plist; pl->next; pl = pl->next)
1799         ;
1800       prev = &pl->next;
1801     }
1802   else
1803     prev = &pprefix->plist;
1804
1805   /* Keep track of the longest prefix */
1806
1807   len = strlen (prefix);
1808   if (len > pprefix->max_len)
1809     pprefix->max_len = len;
1810
1811   pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
1812   pl->prefix = save_string (prefix, len);
1813   pl->require_machine_suffix = require_machine_suffix;
1814   pl->used_flag_ptr = warn;
1815   if (warn)
1816     *warn = 0;
1817
1818   if (*prev)
1819     pl->next = *prev;
1820   else
1821     pl->next = (struct prefix_list *) 0;
1822   *prev = pl;
1823 }
1824
1825 /* Print warnings for any prefixes in the list PPREFIX that were not used.  */
1826
1827 static void
1828 unused_prefix_warnings (pprefix)
1829      struct path_prefix *pprefix;
1830 {
1831   struct prefix_list *pl = pprefix->plist;
1832
1833   while (pl)
1834     {
1835       if (pl->used_flag_ptr != 0 && !*pl->used_flag_ptr)
1836         {
1837           if (pl->require_machine_suffix && machine_suffix)
1838             error ("file path prefix `%s%s' never used", pl->prefix,
1839                    machine_suffix);
1840           else
1841             error ("file path prefix `%s' never used", pl->prefix);
1842
1843           /* Prevent duplicate warnings.  */
1844           *pl->used_flag_ptr = 1;
1845         }
1846       pl = pl->next;
1847     }
1848 }
1849
1850 /* Get rid of all prefixes built up so far in *PLISTP. */
1851
1852 static void
1853 free_path_prefix (pprefix)
1854      struct path_prefix *pprefix;
1855 {
1856   struct prefix_list *pl = pprefix->plist;
1857   struct prefix_list *temp;
1858
1859   while (pl)
1860     {
1861       temp = pl;
1862       pl = pl->next;
1863       free (temp->prefix);
1864       free ((char *) temp);
1865     }
1866   pprefix->plist = (struct prefix_list *) 0;
1867 }
1868 \f
1869 /* stdin file number.  */
1870 #define STDIN_FILE_NO 0
1871
1872 /* stdout file number.  */
1873 #define STDOUT_FILE_NO 1
1874
1875 /* value of `pipe': port index for reading.  */
1876 #define READ_PORT 0
1877
1878 /* value of `pipe': port index for writing.  */
1879 #define WRITE_PORT 1
1880
1881 /* Pipe waiting from last process, to be used as input for the next one.
1882    Value is STDIN_FILE_NO if no pipe is waiting
1883    (i.e. the next command is the first of a group).  */
1884
1885 static int last_pipe_input;
1886
1887 /* Fork one piped subcommand.  FUNC is the system call to use
1888    (either execv or execvp).  ARGV is the arg vector to use.
1889    NOT_LAST is nonzero if this is not the last subcommand
1890    (i.e. its output should be piped to the next one.)  */
1891
1892 #ifdef __MSDOS__
1893
1894 #include <process.h>
1895 static int
1896 pexecute (search_flag, program, argv, not_last)
1897      int search_flag;
1898      char *program;
1899      char *argv[];
1900      int not_last;
1901 {
1902 #ifdef __GO32__
1903   int i = (search_flag ? spawnv : spawnvp) (1, program, argv);
1904 #else
1905   char *scmd, *rf;
1906   FILE *argfile;
1907   int i, el = search_flag ? 0 : 4;
1908
1909   scmd = (char *) xmalloc (strlen (program) + strlen (temp_filename) + 6 + el);
1910   rf = scmd + strlen(program) + 2 + el;
1911   sprintf (scmd, "%s%s @%s.gp", program,
1912            (search_flag ? "" : ".exe"), temp_filename);
1913   argfile = fopen (rf, "w");
1914   if (argfile == 0)
1915     pfatal_with_name (rf);
1916
1917   for (i=1; argv[i]; i++)
1918     {
1919       char *cp;
1920       for (cp = argv[i]; *cp; cp++)
1921         {
1922           if (*cp == '"' || *cp == '\'' || *cp == '\\' || isspace (*cp))
1923             fputc ('\\', argfile);
1924           fputc (*cp, argfile);
1925         }
1926       fputc ('\n', argfile);
1927     }
1928   fclose (argfile);
1929
1930   i = system (scmd);
1931
1932   remove (rf);
1933 #endif
1934   
1935   if (i == -1)
1936     {
1937       perror_exec (program);
1938       return MIN_FATAL_STATUS << 8;
1939     }
1940   return i << 8;
1941 }
1942
1943 #endif
1944
1945 #if !defined(__MSDOS__) && !defined(OS2) && !defined(_WIN32)
1946
1947 static int
1948 pexecute (search_flag, program, argv, not_last)
1949      int search_flag;
1950      char *program;
1951      char *argv[];
1952      int not_last;
1953 {
1954   int (*func)() = (search_flag ? execv : execvp);
1955   int pid;
1956   int pdes[2];
1957   int input_desc = last_pipe_input;
1958   int output_desc = STDOUT_FILE_NO;
1959   int retries, sleep_interval;
1960
1961   /* If this isn't the last process, make a pipe for its output,
1962      and record it as waiting to be the input to the next process.  */
1963
1964   if (not_last)
1965     {
1966       if (pipe (pdes) < 0)
1967         pfatal_with_name ("pipe");
1968       output_desc = pdes[WRITE_PORT];
1969       last_pipe_input = pdes[READ_PORT];
1970     }
1971   else
1972     last_pipe_input = STDIN_FILE_NO;
1973
1974   /* Fork a subprocess; wait and retry if it fails.  */
1975   sleep_interval = 1;
1976   for (retries = 0; retries < 4; retries++)
1977     {
1978       pid = vfork ();
1979       if (pid >= 0)
1980         break;
1981       sleep (sleep_interval);
1982       sleep_interval *= 2;
1983     }
1984
1985   switch (pid)
1986     {
1987     case -1:
1988 #ifdef vfork
1989       pfatal_with_name ("fork");
1990 #else
1991       pfatal_with_name ("vfork");
1992 #endif
1993       /* NOTREACHED */
1994       return 0;
1995
1996     case 0: /* child */
1997       /* Move the input and output pipes into place, if nec.  */
1998       if (input_desc != STDIN_FILE_NO)
1999         {
2000           close (STDIN_FILE_NO);
2001           dup (input_desc);
2002           close (input_desc);
2003         }
2004       if (output_desc != STDOUT_FILE_NO)
2005         {
2006           close (STDOUT_FILE_NO);
2007           dup (output_desc);
2008           close (output_desc);
2009         }
2010
2011       /* Close the parent's descs that aren't wanted here.  */
2012       if (last_pipe_input != STDIN_FILE_NO)
2013         close (last_pipe_input);
2014
2015       /* Exec the program.  */
2016       (*func) (program, argv);
2017       perror_exec (program);
2018       exit (-1);
2019       /* NOTREACHED */
2020       return 0;
2021
2022     default:
2023       /* In the parent, after forking.
2024          Close the descriptors that we made for this child.  */
2025       if (input_desc != STDIN_FILE_NO)
2026         close (input_desc);
2027       if (output_desc != STDOUT_FILE_NO)
2028         close (output_desc);
2029
2030       /* Return child's process number.  */
2031       return pid;
2032     }
2033 }
2034
2035 #endif /* not __MSDOS__ and not OS2 and not _WIN32 */
2036
2037 #if defined(OS2)
2038
2039 static int
2040 pexecute (search_flag, program, argv, not_last)
2041      int search_flag;
2042      char *program;
2043      char *argv[];
2044      int not_last;
2045 {
2046   return (search_flag ? spawnv : spawnvp) (1, program, argv);
2047 }
2048 #endif /* OS2 */
2049
2050 #if defined(_WIN32)
2051
2052 static int
2053 pexecute (search_flag, program, argv, not_last)
2054      int search_flag;
2055      char *program;
2056      char *argv[];
2057      int not_last;
2058 {
2059   return (search_flag ? __spawnv : __spawnvp) (1, program, argv);
2060 }
2061 #endif /* _WIN32 */
2062
2063 \f
2064 /* Execute the command specified by the arguments on the current line of spec.
2065    When using pipes, this includes several piped-together commands
2066    with `|' between them.
2067
2068    Return 0 if successful, -1 if failed.  */
2069
2070 static int
2071 execute ()
2072 {
2073   int i;
2074   int n_commands;               /* # of command.  */
2075   char *string;
2076   struct command
2077     {
2078       char *prog;               /* program name.  */
2079       char **argv;              /* vector of args.  */
2080       int pid;                  /* pid of process for this command.  */
2081     };
2082
2083   struct command *commands;     /* each command buffer with above info.  */
2084
2085   /* Count # of piped commands.  */
2086   for (n_commands = 1, i = 0; i < argbuf_index; i++)
2087     if (strcmp (argbuf[i], "|") == 0)
2088       n_commands++;
2089
2090   /* Get storage for each command.  */
2091   commands
2092     = (struct command *) alloca (n_commands * sizeof (struct command));
2093
2094   /* Split argbuf into its separate piped processes,
2095      and record info about each one.
2096      Also search for the programs that are to be run.  */
2097
2098   commands[0].prog = argbuf[0]; /* first command.  */
2099   commands[0].argv = &argbuf[0];
2100   string = find_a_file (&exec_prefixes, commands[0].prog, X_OK);
2101   if (string)
2102     commands[0].argv[0] = string;
2103
2104   for (n_commands = 1, i = 0; i < argbuf_index; i++)
2105     if (strcmp (argbuf[i], "|") == 0)
2106       {                         /* each command.  */
2107 #ifdef __MSDOS__
2108         fatal ("-pipe not supported under MS-DOS");
2109 #endif
2110         argbuf[i] = 0;  /* termination of command args.  */
2111         commands[n_commands].prog = argbuf[i + 1];
2112         commands[n_commands].argv = &argbuf[i + 1];
2113         string = find_a_file (&exec_prefixes, commands[n_commands].prog, X_OK);
2114         if (string)
2115           commands[n_commands].argv[0] = string;
2116         n_commands++;
2117       }
2118
2119   argbuf[argbuf_index] = 0;
2120
2121   /* If -v, print what we are about to do, and maybe query.  */
2122
2123   if (verbose_flag)
2124     {
2125       /* Print each piped command as a separate line.  */
2126       for (i = 0; i < n_commands ; i++)
2127         {
2128           char **j;
2129
2130           for (j = commands[i].argv; *j; j++)
2131             fprintf (stderr, " %s", *j);
2132
2133           /* Print a pipe symbol after all but the last command.  */
2134           if (i + 1 != n_commands)
2135             fprintf (stderr, " |");
2136           fprintf (stderr, "\n");
2137         }
2138       fflush (stderr);
2139 #ifdef DEBUG
2140       fprintf (stderr, "\nGo ahead? (y or n) ");
2141       fflush (stderr);
2142       i = getchar ();
2143       if (i != '\n')
2144         while (getchar () != '\n') ;
2145       if (i != 'y' && i != 'Y')
2146         return 0;
2147 #endif /* DEBUG */
2148     }
2149
2150   /* Run each piped subprocess.  */
2151
2152   last_pipe_input = STDIN_FILE_NO;
2153   for (i = 0; i < n_commands; i++)
2154     {
2155       char *string = commands[i].argv[0];
2156
2157       commands[i].pid = pexecute (string != commands[i].prog,
2158                                   string, commands[i].argv,
2159                                   i + 1 < n_commands);
2160
2161       if (string != commands[i].prog)
2162         free (string);
2163     }
2164
2165   execution_count++;
2166
2167   /* Wait for all the subprocesses to finish.
2168      We don't care what order they finish in;
2169      we know that N_COMMANDS waits will get them all.
2170      Ignore subprocesses that we don't know about,
2171      since they can be spawned by the process that exec'ed us.  */
2172
2173   {
2174     int ret_code = 0;
2175
2176     for (i = 0; i < n_commands; )
2177       {
2178         int j;
2179         int status;
2180         int pid;
2181
2182 #ifdef __MSDOS__
2183         status = pid = commands[i].pid;
2184 #else
2185 #ifdef _WIN32
2186         pid = cwait (&status, commands[i].pid, WAIT_CHILD);
2187 #else
2188         pid = wait (&status);
2189 #endif
2190 #endif
2191         if (pid < 0)
2192           abort ();
2193
2194         for (j = 0; j < n_commands; j++)
2195           if (commands[j].pid == pid)
2196             {
2197               i++;
2198               if (status != 0)
2199                 {
2200                   if (WIFSIGNALED (status))
2201                     {
2202                       fatal ("Internal compiler error: program %s got fatal signal %d",
2203                              commands[j].prog, WTERMSIG (status));
2204                       signal_count++;
2205                       ret_code = -1;
2206                     }
2207                   else if (WIFEXITED (status)
2208                            && WEXITSTATUS (status) >= MIN_FATAL_STATUS)
2209                     ret_code = -1;
2210                 }
2211               break;
2212             }
2213       }
2214     return ret_code;
2215   }
2216 }
2217 \f
2218 /* Find all the switches given to us
2219    and make a vector describing them.
2220    The elements of the vector are strings, one per switch given.
2221    If a switch uses following arguments, then the `part1' field
2222    is the switch itself and the `args' field
2223    is a null-terminated vector containing the following arguments.
2224    The `live_cond' field is 1 if the switch is true in a conditional spec,
2225    -1 if false (overridden by a later switch), and is initialized to zero.
2226    The `valid' field is nonzero if any spec has looked at this switch;
2227    if it remains zero at the end of the run, it must be meaningless.  */
2228
2229 struct switchstr
2230 {
2231   char *part1;
2232   char **args;
2233   int live_cond;
2234   int valid;
2235 };
2236
2237 static struct switchstr *switches;
2238
2239 static int n_switches;
2240
2241 struct infile
2242 {
2243   char *name;
2244   char *language;
2245 };
2246
2247 /* Also a vector of input files specified.  */
2248
2249 static struct infile *infiles;
2250
2251 static int n_infiles;
2252
2253 /* And a vector of corresponding output files is made up later.  */
2254
2255 static char **outfiles;
2256
2257 /* Used to track if none of the -B paths are used.  */
2258 static int warn_B;
2259
2260 /* Used to track if standard path isn't used and -b or -V is specified.  */
2261 static int warn_std;
2262
2263 /* Gives value to pass as "warn" to add_prefix for standard prefixes.  */
2264 static int *warn_std_ptr = 0;
2265
2266 /* Create the vector `switches' and its contents.
2267    Store its length in `n_switches'.  */
2268
2269 static void
2270 process_command (argc, argv)
2271      int argc;
2272      char **argv;
2273 {
2274   register int i;
2275   char *temp;
2276   char *spec_lang = 0;
2277   int last_language_n_infiles;
2278   int have_c = 0;
2279   int have_o = 0;
2280   int lang_n_infiles = 0;
2281
2282   gcc_exec_prefix = getenv ("GCC_EXEC_PREFIX");
2283
2284   n_switches = 0;
2285   n_infiles = 0;
2286
2287   /* Figure compiler version from version string.  */
2288
2289   compiler_version = save_string (version_string, strlen (version_string));
2290   for (temp = compiler_version; *temp; ++temp)
2291     {
2292       if (*temp == ' ')
2293         {
2294           *temp = '\0';
2295           break;
2296         }
2297     }
2298
2299   /* Set up the default search paths.  */
2300
2301   if (gcc_exec_prefix)
2302     {
2303       add_prefix (&exec_prefixes, gcc_exec_prefix, 0, 0, NULL_PTR);
2304       add_prefix (&startfile_prefixes, gcc_exec_prefix, 0, 0, NULL_PTR);
2305     }
2306
2307   /* COMPILER_PATH and LIBRARY_PATH have values
2308      that are lists of directory names with colons.  */
2309
2310   temp = getenv ("COMPILER_PATH");
2311   if (temp)
2312     {
2313       char *startp, *endp;
2314       char *nstore = (char *) alloca (strlen (temp) + 3);
2315
2316       startp = endp = temp;
2317       while (1)
2318         {
2319           if (*endp == PATH_SEPARATOR || *endp == 0)
2320             {
2321               strncpy (nstore, startp, endp-startp);
2322               if (endp == startp)
2323                 strcpy (nstore, concat (".", dir_separator_str, NULL_PTR));
2324               else if (endp[-1] != '/' && endp[-1] != DIR_SEPARATOR)
2325                 {
2326                   nstore[endp-startp] = DIR_SEPARATOR;
2327                   nstore[endp-startp+1] = 0;
2328                 }
2329               else
2330                 nstore[endp-startp] = 0;
2331               add_prefix (&exec_prefixes, nstore, 0, 0, NULL_PTR);
2332               if (*endp == 0)
2333                 break;
2334               endp = startp = endp + 1;
2335             }
2336           else
2337             endp++;
2338         }
2339     }
2340
2341   temp = getenv ("LIBRARY_PATH");
2342   if (temp && ! cross_compile)
2343     {
2344       char *startp, *endp;
2345       char *nstore = (char *) alloca (strlen (temp) + 3);
2346
2347       startp = endp = temp;
2348       while (1)
2349         {
2350           if (*endp == PATH_SEPARATOR || *endp == 0)
2351             {
2352               strncpy (nstore, startp, endp-startp);
2353               if (endp == startp)
2354                 strcpy (nstore, concat (".", dir_separator_str, NULL_PTR));
2355               else if (endp[-1] != '/' && endp[-1] != DIR_SEPARATOR)
2356                 {
2357                   nstore[endp-startp] = DIR_SEPARATOR;
2358                   nstore[endp-startp+1] = 0;
2359                 }
2360               else
2361                 nstore[endp-startp] = 0;
2362               add_prefix (&startfile_prefixes, nstore, 0, 0, NULL_PTR);
2363               if (*endp == 0)
2364                 break;
2365               endp = startp = endp + 1;
2366             }
2367           else
2368             endp++;
2369         }
2370     }
2371
2372   /* Use LPATH like LIBRARY_PATH (for the CMU build program).  */
2373   temp = getenv ("LPATH");
2374   if (temp && ! cross_compile)
2375     {
2376       char *startp, *endp;
2377       char *nstore = (char *) alloca (strlen (temp) + 3);
2378
2379       startp = endp = temp;
2380       while (1)
2381         {
2382           if (*endp == PATH_SEPARATOR || *endp == 0)
2383             {
2384               strncpy (nstore, startp, endp-startp);
2385               if (endp == startp)
2386                 strcpy (nstore, concat (".", dir_separator_str, NULL_PTR));
2387               else if (endp[-1] != '/' && endp[-1] != DIR_SEPARATOR)
2388                 {
2389                   nstore[endp-startp] = DIR_SEPARATOR;
2390                   nstore[endp-startp+1] = 0;
2391                 }
2392               else
2393                 nstore[endp-startp] = 0;
2394               add_prefix (&startfile_prefixes, nstore, 0, 0, NULL_PTR);
2395               if (*endp == 0)
2396                 break;
2397               endp = startp = endp + 1;
2398             }
2399           else
2400             endp++;
2401         }
2402     }
2403
2404   /* Convert new-style -- options to old-style.  */
2405   translate_options (&argc, &argv);
2406
2407   /* Scan argv twice.  Here, the first time, just count how many switches
2408      there will be in their vector, and how many input files in theirs.
2409      Here we also parse the switches that cc itself uses (e.g. -v).  */
2410
2411   for (i = 1; i < argc; i++)
2412     {
2413       if (! strcmp (argv[i], "-dumpspecs"))
2414         {
2415           printf ("*asm:\n%s\n\n", asm_spec);
2416           printf ("*asm_final:\n%s\n\n", asm_final_spec);
2417           printf ("*cpp:\n%s\n\n", cpp_spec);
2418           printf ("*cc1:\n%s\n\n", cc1_spec);
2419           printf ("*cc1plus:\n%s\n\n", cc1plus_spec);
2420           printf ("*endfile:\n%s\n\n", endfile_spec);
2421           printf ("*link:\n%s\n\n", link_spec);
2422           printf ("*lib:\n%s\n\n", lib_spec);
2423           printf ("*libgcc:\n%s\n\n", libgcc_spec);
2424           printf ("*startfile:\n%s\n\n", startfile_spec);
2425           printf ("*switches_need_spaces:\n%s\n\n", switches_need_spaces);
2426           printf ("*signed_char:\n%s\n\n", signed_char_spec);
2427           printf ("*predefines:\n%s\n\n", cpp_predefines);
2428           printf ("*cross_compile:\n%d\n\n", cross_compile);
2429           printf ("*multilib:\n%s\n\n", multilib_select);
2430
2431 #ifdef EXTRA_SPECS
2432           {
2433             int j;
2434             for (j = 0; j < sizeof (extra_specs) / sizeof (extra_specs[0]); j++)
2435               printf ("*%s:\n%s\n\n", extra_specs[j].name,
2436                       (extra_specs[j].spec) ? extra_specs[j].spec : "");
2437           }
2438 #endif
2439           exit (0);
2440         }
2441       else if (! strcmp (argv[i], "-dumpversion"))
2442         {
2443           printf ("%s\n", version_string);
2444           exit (0);
2445         }
2446       else if (! strcmp (argv[i], "-dumpmachine"))
2447         {
2448           printf ("%s\n", spec_machine);
2449           exit  (0);
2450         }
2451       else if (! strcmp (argv[i], "-print-search-dirs"))
2452         print_search_dirs = 1;
2453       else if (! strcmp (argv[i], "-print-libgcc-file-name"))
2454         print_file_name = "libgcc.a";
2455       else if (! strncmp (argv[i], "-print-file-name=", 17))
2456         print_file_name = argv[i] + 17;
2457       else if (! strncmp (argv[i], "-print-prog-name=", 17))
2458         print_prog_name = argv[i] + 17;
2459       else if (! strcmp (argv[i], "-print-multi-lib"))
2460         print_multi_lib = 1;
2461       else if (! strcmp (argv[i], "-print-multi-directory"))
2462         print_multi_directory = 1;
2463       else if (! strncmp (argv[i], "-Wa,", 4))
2464         {
2465           int prev, j;
2466           /* Pass the rest of this option to the assembler.  */
2467
2468           n_assembler_options++;
2469           if (!assembler_options)
2470             assembler_options
2471               = (char **) xmalloc (n_assembler_options * sizeof (char **));
2472           else
2473             assembler_options
2474               = (char **) xrealloc (assembler_options,
2475                                     n_assembler_options * sizeof (char **));
2476
2477           /* Split the argument at commas.  */
2478           prev = 4;
2479           for (j = 4; argv[i][j]; j++)
2480             if (argv[i][j] == ',')
2481               {
2482                 assembler_options[n_assembler_options - 1]
2483                   = save_string (argv[i] + prev, j - prev);
2484                 n_assembler_options++;
2485                 assembler_options
2486                   = (char **) xrealloc (assembler_options,
2487                                         n_assembler_options * sizeof (char **));
2488                 prev = j + 1;
2489               }
2490           /* Record the part after the last comma.  */
2491           assembler_options[n_assembler_options - 1] = argv[i] + prev;
2492         }
2493       else if (! strncmp (argv[i], "-Wp,", 4))
2494         {
2495           int prev, j;
2496           /* Pass the rest of this option to the preprocessor.  */
2497
2498           n_preprocessor_options++;
2499           if (!preprocessor_options)
2500             preprocessor_options
2501               = (char **) xmalloc (n_preprocessor_options * sizeof (char **));
2502           else
2503             preprocessor_options
2504               = (char **) xrealloc (preprocessor_options,
2505                                     n_preprocessor_options * sizeof (char **));
2506
2507           /* Split the argument at commas.  */
2508           prev = 4;
2509           for (j = 4; argv[i][j]; j++)
2510             if (argv[i][j] == ',')
2511               {
2512                 preprocessor_options[n_preprocessor_options - 1]
2513                   = save_string (argv[i] + prev, j - prev);
2514                 n_preprocessor_options++;
2515                 preprocessor_options
2516                   = (char **) xrealloc (preprocessor_options,
2517                                         n_preprocessor_options * sizeof (char **));
2518                 prev = j + 1;
2519               }
2520           /* Record the part after the last comma.  */
2521           preprocessor_options[n_preprocessor_options - 1] = argv[i] + prev;
2522         }
2523       else if (argv[i][0] == '+' && argv[i][1] == 'e')
2524         /* The +e options to the C++ front-end.  */
2525         n_switches++;
2526       else if (strncmp (argv[i], "-Wl,", 4) == 0)
2527         {
2528           int j;
2529           /* Split the argument at commas.  */
2530           for (j = 3; argv[i][j]; j++)
2531             n_infiles += (argv[i][j] == ',');
2532         }
2533       else if (strcmp (argv[i], "-Xlinker") == 0)
2534         {
2535           if (i + 1 == argc)
2536             fatal ("argument to `-Xlinker' is missing");
2537
2538           n_infiles++;
2539           i++;
2540         }
2541       else if (strncmp (argv[i], "-l", 2) == 0)
2542         n_infiles++;
2543       else if (strcmp (argv[i], "-save-temps") == 0)
2544         {
2545           save_temps_flag = 1;
2546           n_switches++;
2547         }
2548       else if (argv[i][0] == '-' && argv[i][1] != 0)
2549         {
2550           register char *p = &argv[i][1];
2551           register int c = *p;
2552
2553           switch (c)
2554             {
2555             case 'b':
2556               if (p[1] == 0 && i + 1 == argc)
2557                 fatal ("argument to `-b' is missing");
2558               if (p[1] == 0)
2559                 spec_machine = argv[++i];
2560               else
2561                 spec_machine = p + 1;
2562
2563               warn_std_ptr = &warn_std;
2564               break;
2565
2566             case 'B':
2567               {
2568                 int *temp = (int *) xmalloc (sizeof (int));
2569                 char *value;
2570                 if (p[1] == 0 && i + 1 == argc)
2571                   fatal ("argument to `-B' is missing");
2572                 if (p[1] == 0)
2573                   value = argv[++i];
2574                 else
2575                   value = p + 1;
2576                 add_prefix (&exec_prefixes, value, 1, 0, &warn_B);
2577                 add_prefix (&startfile_prefixes, value, 1, 0, &warn_B);
2578                 add_prefix (&include_prefixes, concat (value, "include", NULL_PTR),
2579                             1, 0, NULL_PTR);
2580
2581                 /* As a kludge, if the arg is "[foo/]stageN/", just add
2582                    "[foo/]include" to the include prefix.  */
2583                 {
2584                   int len = strlen (value);
2585                   if ((len == 7
2586                        || (len > 7
2587                            && (value[len - 8] == '/'
2588                                || value[len - 8] == DIR_SEPARATOR)))
2589                       && strncmp (value + len - 7, "stage", 5) == 0
2590                       && isdigit (value[len - 2])
2591                       && (value[len - 1] == '/'
2592                           || value[len - 1] == DIR_SEPARATOR))
2593                     {
2594                       if (len == 7)
2595                         add_prefix (&include_prefixes, "include",
2596                                     1, 0, NULL_PTR);
2597                       else
2598                         {
2599                           char *string = xmalloc (len + 1);
2600                           strncpy (string, value, len-7);
2601                           strcat (string, "include");
2602                           add_prefix (&include_prefixes, string,
2603                                       1, 0, NULL_PTR);
2604                         }
2605                     }
2606                 }
2607               }
2608               break;
2609
2610             case 'v':   /* Print our subcommands and print versions.  */
2611               n_switches++;
2612               /* If they do anything other than exactly `-v', don't set
2613                  verbose_flag; rather, continue on to give the error.  */
2614               if (p[1] != 0)
2615                 break;
2616               verbose_flag++;
2617               break;
2618
2619             case 'V':
2620               if (p[1] == 0 && i + 1 == argc)
2621                 fatal ("argument to `-V' is missing");
2622               if (p[1] == 0)
2623                 spec_version = argv[++i];
2624               else
2625                 spec_version = p + 1;
2626               compiler_version = spec_version;
2627               warn_std_ptr = &warn_std;
2628               break;
2629
2630             case 'c':
2631               if (p[1] == 0)
2632                 {
2633                   have_c = 1;
2634                   n_switches++;
2635                   break;
2636                 }
2637               goto normal_switch;
2638
2639             case 'o':
2640               have_o = 1;
2641               goto normal_switch;
2642
2643             default:
2644             normal_switch:
2645               n_switches++;
2646
2647               if (SWITCH_TAKES_ARG (c) > (p[1] != 0))
2648                 i += SWITCH_TAKES_ARG (c) - (p[1] != 0);
2649               else if (WORD_SWITCH_TAKES_ARG (p))
2650                 i += WORD_SWITCH_TAKES_ARG (p);
2651             }
2652         }
2653       else
2654         {
2655           n_infiles++;
2656           lang_n_infiles++;
2657         }
2658     }
2659
2660   if (have_c && have_o && lang_n_infiles > 1)
2661     fatal ("cannot specify -o with -c and multiple compilations");
2662
2663   /* Set up the search paths before we go looking for config files.  */
2664
2665   /* These come before the md prefixes so that we will find gcc's subcommands
2666      (such as cpp) rather than those of the host system.  */
2667   /* Use 2 as fourth arg meaning try just the machine as a suffix,
2668      as well as trying the machine and the version.  */
2669 #ifndef OS2
2670   add_prefix (&exec_prefixes, standard_exec_prefix, 0, 2, warn_std_ptr);
2671   add_prefix (&exec_prefixes, standard_exec_prefix_1, 0, 2, warn_std_ptr);
2672 #endif
2673
2674   add_prefix (&startfile_prefixes, standard_exec_prefix, 0, 1, warn_std_ptr);
2675   add_prefix (&startfile_prefixes, standard_exec_prefix_1, 0, 1, warn_std_ptr);
2676
2677   tooldir_prefix = concat (tooldir_base_prefix, spec_machine, 
2678                            dir_separator_str, NULL_PTR);
2679
2680   /* If tooldir is relative, base it on exec_prefixes.  A relative
2681      tooldir lets us move the installed tree as a unit.
2682
2683      If GCC_EXEC_PREFIX is defined, then we want to add two relative
2684      directories, so that we can search both the user specified directory
2685      and the standard place.  */
2686
2687   if (*tooldir_prefix != '/' && *tooldir_prefix != DIR_SEPARATOR)
2688     {
2689       if (gcc_exec_prefix)
2690         {
2691           char *gcc_exec_tooldir_prefix
2692             = concat (gcc_exec_prefix, spec_machine, dir_separator_str,
2693                       spec_version, dir_separator_str, tooldir_prefix, NULL_PTR);
2694
2695           add_prefix (&exec_prefixes,
2696                       concat (gcc_exec_tooldir_prefix, "bin", 
2697                               dir_separator_str, NULL_PTR),
2698                       0, 0, NULL_PTR);
2699           add_prefix (&startfile_prefixes,
2700                       concat (gcc_exec_tooldir_prefix, "lib", 
2701                               dir_separator_str, NULL_PTR),
2702                       0, 0, NULL_PTR);
2703         }
2704
2705       tooldir_prefix = concat (standard_exec_prefix, spec_machine,
2706                                dir_separator_str, spec_version, 
2707                                dir_separator_str, tooldir_prefix, NULL_PTR);
2708     }
2709
2710   add_prefix (&exec_prefixes, 
2711               concat (tooldir_prefix, "bin", dir_separator_str, NULL_PTR),
2712               0, 0, NULL_PTR);
2713   add_prefix (&startfile_prefixes,
2714               concat (tooldir_prefix, "lib", dir_separator_str, NULL_PTR),
2715               0, 0, NULL_PTR);
2716
2717   /* More prefixes are enabled in main, after we read the specs file
2718      and determine whether this is cross-compilation or not.  */
2719
2720
2721   /* Then create the space for the vectors and scan again.  */
2722
2723   switches = ((struct switchstr *)
2724               xmalloc ((n_switches + 1) * sizeof (struct switchstr)));
2725   infiles = (struct infile *) xmalloc ((n_infiles + 1) * sizeof (struct infile));
2726   n_switches = 0;
2727   n_infiles = 0;
2728   last_language_n_infiles = -1;
2729
2730   /* This, time, copy the text of each switch and store a pointer
2731      to the copy in the vector of switches.
2732      Store all the infiles in their vector.  */
2733
2734   for (i = 1; i < argc; i++)
2735     {
2736       /* Just skip the switches that were handled by the preceding loop.  */
2737       if (! strncmp (argv[i], "-Wa,", 4))
2738         ;
2739       else if (! strncmp (argv[i], "-Wp,", 4))
2740         ;
2741       else if (! strcmp (argv[i], "-print-search-dirs"))
2742         ;
2743       else if (! strcmp (argv[i], "-print-libgcc-file-name"))
2744         ;
2745       else if (! strncmp (argv[i], "-print-file-name=", 17))
2746         ;
2747       else if (! strncmp (argv[i], "-print-prog-name=", 17))
2748         ;
2749       else if (! strcmp (argv[i], "-print-multi-lib"))
2750         ;
2751       else if (! strcmp (argv[i], "-print-multi-directory"))
2752         ;
2753       else if (argv[i][0] == '+' && argv[i][1] == 'e')
2754         {
2755           /* Compensate for the +e options to the C++ front-end;
2756              they're there simply for cfront call-compatibility.  We do
2757              some magic in default_compilers to pass them down properly.
2758              Note we deliberately start at the `+' here, to avoid passing
2759              -e0 or -e1 down into the linker.  */
2760           switches[n_switches].part1 = &argv[i][0];
2761           switches[n_switches].args = 0;
2762           switches[n_switches].live_cond = 0;
2763           switches[n_switches].valid = 0;
2764           n_switches++;
2765         }
2766       else if (strncmp (argv[i], "-Wl,", 4) == 0)
2767         {
2768           int prev, j;
2769           /* Split the argument at commas.  */
2770           prev = 4;
2771           for (j = 4; argv[i][j]; j++)
2772             if (argv[i][j] == ',')
2773               {
2774                 infiles[n_infiles].language = 0;
2775                 infiles[n_infiles++].name
2776                   = save_string (argv[i] + prev, j - prev);
2777                 prev = j + 1;
2778               }
2779           /* Record the part after the last comma.  */
2780           infiles[n_infiles].language = 0;
2781           infiles[n_infiles++].name = argv[i] + prev;
2782         }
2783       else if (strcmp (argv[i], "-Xlinker") == 0)
2784         {
2785           infiles[n_infiles].language = 0;
2786           infiles[n_infiles++].name = argv[++i];
2787         }
2788       else if (strncmp (argv[i], "-l", 2) == 0)
2789         {
2790           infiles[n_infiles].language = 0;
2791           infiles[n_infiles++].name = argv[i];
2792         }
2793       else if (argv[i][0] == '-' && argv[i][1] != 0)
2794         {
2795           register char *p = &argv[i][1];
2796           register int c = *p;
2797
2798           if (c == 'B' || c == 'b' || c == 'V')
2799             {
2800               /* Skip a separate arg, if any.  */
2801               if (p[1] == 0)
2802                 i++;
2803               continue;
2804             }
2805           if (c == 'x')
2806             {
2807               if (p[1] == 0 && i + 1 == argc)
2808                 fatal ("argument to `-x' is missing");
2809               if (p[1] == 0)
2810                 spec_lang = argv[++i];
2811               else
2812                 spec_lang = p + 1;
2813               if (! strcmp (spec_lang, "none"))
2814                 /* Suppress the warning if -xnone comes after the last input
2815                    file, because alternate command interfaces like g++ might
2816                    find it useful to place -xnone after each input file.  */
2817                 spec_lang = 0;
2818               else
2819                 last_language_n_infiles = n_infiles;
2820               continue;
2821             }
2822           switches[n_switches].part1 = p;
2823           /* Deal with option arguments in separate argv elements.  */
2824           if ((SWITCH_TAKES_ARG (c) > (p[1] != 0))
2825               || WORD_SWITCH_TAKES_ARG (p))
2826             {
2827               int j = 0;
2828               int n_args = WORD_SWITCH_TAKES_ARG (p);
2829
2830               if (n_args == 0)
2831                 {
2832                   /* Count only the option arguments in separate argv elements.  */
2833                   n_args = SWITCH_TAKES_ARG (c) - (p[1] != 0);
2834                 }
2835               if (i + n_args >= argc)
2836                 fatal ("argument to `-%s' is missing", p);
2837               switches[n_switches].args
2838                 = (char **) xmalloc ((n_args + 1) * sizeof (char *));
2839               while (j < n_args)
2840                 switches[n_switches].args[j++] = argv[++i];
2841               /* Null-terminate the vector.  */
2842               switches[n_switches].args[j] = 0;
2843             }
2844           else if (index (switches_need_spaces, c))
2845             {
2846               /* On some systems, ld cannot handle some options without
2847                  a space.  So split the option from its argument.  */
2848               char *part1 = (char *) xmalloc (2);
2849               part1[0] = c;
2850               part1[1] = '\0';
2851               
2852               switches[n_switches].part1 = part1;
2853               switches[n_switches].args = (char **) xmalloc (2 * sizeof (char *));
2854               switches[n_switches].args[0] = xmalloc (strlen (p));
2855               strcpy (switches[n_switches].args[0], &p[1]);
2856               switches[n_switches].args[1] = 0;
2857             }
2858           else
2859             switches[n_switches].args = 0;
2860
2861           switches[n_switches].live_cond = 0;
2862           switches[n_switches].valid = 0;
2863           /* This is always valid, since gcc.c itself understands it.  */
2864           if (!strcmp (p, "save-temps"))
2865             switches[n_switches].valid = 1;
2866           n_switches++;
2867         }
2868       else
2869         {
2870 #ifdef HAVE_OBJECT_SUFFIX
2871           /* Convert x.o to x.obj if OBJECT_SUFFIX is ".obj".  */
2872           if (strlen (argv[i]) > 2
2873               && argv[i][strlen (argv[i]) - 2] == '.'
2874               && argv[i][strlen (argv[i]) - 1] == 'o')
2875             {
2876               int j;
2877
2878               for (j = 0; j < strlen (argv[i]) - 2; j++)
2879                 obstack_1grow (&obstack, argv[i][j]);
2880
2881               obstack_grow (&obstack, OBJECT_SUFFIX, strlen (OBJECT_SUFFIX));
2882               obstack_1grow (&obstack, 0);
2883               argv[i] = obstack_finish (&obstack);
2884             }
2885 #endif
2886
2887           if (strcmp (argv[i], "-") != 0 && access (argv[i], R_OK) < 0)
2888             {
2889               perror_with_name (argv[i]);
2890               error_count++;
2891             }
2892           else
2893             {
2894               infiles[n_infiles].language = spec_lang;
2895               infiles[n_infiles++].name = argv[i];
2896             }
2897         }
2898     }
2899
2900   if (n_infiles == last_language_n_infiles && spec_lang != 0)
2901     error ("Warning: `-x %s' after last input file has no effect", spec_lang);
2902
2903   switches[n_switches].part1 = 0;
2904   infiles[n_infiles].name = 0;
2905 }
2906 \f
2907 /* Process a spec string, accumulating and running commands.  */
2908
2909 /* These variables describe the input file name.
2910    input_file_number is the index on outfiles of this file,
2911    so that the output file name can be stored for later use by %o.
2912    input_basename is the start of the part of the input file
2913    sans all directory names, and basename_length is the number
2914    of characters starting there excluding the suffix .c or whatever.  */
2915
2916 static char *input_filename;
2917 static int input_file_number;
2918 static int input_filename_length;
2919 static int basename_length;
2920 static char *input_basename;
2921 static char *input_suffix;
2922
2923 /* These are variables used within do_spec and do_spec_1.  */
2924
2925 /* Nonzero if an arg has been started and not yet terminated
2926    (with space, tab or newline).  */
2927 static int arg_going;
2928
2929 /* Nonzero means %d or %g has been seen; the next arg to be terminated
2930    is a temporary file name.  */
2931 static int delete_this_arg;
2932
2933 /* Nonzero means %w has been seen; the next arg to be terminated
2934    is the output file name of this compilation.  */
2935 static int this_is_output_file;
2936
2937 /* Nonzero means %s has been seen; the next arg to be terminated
2938    is the name of a library file and we should try the standard
2939    search dirs for it.  */
2940 static int this_is_library_file;
2941
2942 /* Nonzero means that the input of this command is coming from a pipe.  */
2943 static int input_from_pipe;
2944
2945 /* Process the spec SPEC and run the commands specified therein.
2946    Returns 0 if the spec is successfully processed; -1 if failed.  */
2947
2948 static int
2949 do_spec (spec)
2950      char *spec;
2951 {
2952   int value;
2953
2954   clear_args ();
2955   arg_going = 0;
2956   delete_this_arg = 0;
2957   this_is_output_file = 0;
2958   this_is_library_file = 0;
2959   input_from_pipe = 0;
2960
2961   value = do_spec_1 (spec, 0, NULL_PTR);
2962
2963   /* Force out any unfinished command.
2964      If -pipe, this forces out the last command if it ended in `|'.  */
2965   if (value == 0)
2966     {
2967       if (argbuf_index > 0 && !strcmp (argbuf[argbuf_index - 1], "|"))
2968         argbuf_index--;
2969
2970       if (argbuf_index > 0)
2971         value = execute ();
2972     }
2973
2974   return value;
2975 }
2976
2977 /* Process the sub-spec SPEC as a portion of a larger spec.
2978    This is like processing a whole spec except that we do
2979    not initialize at the beginning and we do not supply a
2980    newline by default at the end.
2981    INSWITCH nonzero means don't process %-sequences in SPEC;
2982    in this case, % is treated as an ordinary character.
2983    This is used while substituting switches.
2984    INSWITCH nonzero also causes SPC not to terminate an argument.
2985
2986    Value is zero unless a line was finished
2987    and the command on that line reported an error.  */
2988
2989 static int
2990 do_spec_1 (spec, inswitch, soft_matched_part)
2991      char *spec;
2992      int inswitch;
2993      char *soft_matched_part;
2994 {
2995   register char *p = spec;
2996   register int c;
2997   int i;
2998   char *string;
2999   int value;
3000
3001   while (c = *p++)
3002     /* If substituting a switch, treat all chars like letters.
3003        Otherwise, NL, SPC, TAB and % are special.  */
3004     switch (inswitch ? 'a' : c)
3005       {
3006       case '\n':
3007         /* End of line: finish any pending argument,
3008            then run the pending command if one has been started.  */
3009         if (arg_going)
3010           {
3011             obstack_1grow (&obstack, 0);
3012             string = obstack_finish (&obstack);
3013             if (this_is_library_file)
3014               string = find_file (string);
3015             store_arg (string, delete_this_arg, this_is_output_file);
3016             if (this_is_output_file)
3017               outfiles[input_file_number] = string;
3018           }
3019         arg_going = 0;
3020
3021         if (argbuf_index > 0 && !strcmp (argbuf[argbuf_index - 1], "|"))
3022           {
3023             for (i = 0; i < n_switches; i++)
3024               if (!strcmp (switches[i].part1, "pipe"))
3025                 break;
3026
3027             /* A `|' before the newline means use a pipe here,
3028                but only if -pipe was specified.
3029                Otherwise, execute now and don't pass the `|' as an arg.  */
3030             if (i < n_switches)
3031               {
3032                 input_from_pipe = 1;
3033                 switches[i].valid = 1;
3034                 break;
3035               }
3036             else
3037               argbuf_index--;
3038           }
3039
3040         if (argbuf_index > 0)
3041           {
3042             value = execute ();
3043             if (value)
3044               return value;
3045           }
3046         /* Reinitialize for a new command, and for a new argument.  */
3047         clear_args ();
3048         arg_going = 0;
3049         delete_this_arg = 0;
3050         this_is_output_file = 0;
3051         this_is_library_file = 0;
3052         input_from_pipe = 0;
3053         break;
3054
3055       case '|':
3056         /* End any pending argument.  */
3057         if (arg_going)
3058           {
3059             obstack_1grow (&obstack, 0);
3060             string = obstack_finish (&obstack);
3061             if (this_is_library_file)
3062               string = find_file (string);
3063             store_arg (string, delete_this_arg, this_is_output_file);
3064             if (this_is_output_file)
3065               outfiles[input_file_number] = string;
3066           }
3067
3068         /* Use pipe */
3069         obstack_1grow (&obstack, c);
3070         arg_going = 1;
3071         break;
3072
3073       case '\t':
3074       case ' ':
3075         /* Space or tab ends an argument if one is pending.  */
3076         if (arg_going)
3077           {
3078             obstack_1grow (&obstack, 0);
3079             string = obstack_finish (&obstack);
3080             if (this_is_library_file)
3081               string = find_file (string);
3082             store_arg (string, delete_this_arg, this_is_output_file);
3083             if (this_is_output_file)
3084               outfiles[input_file_number] = string;
3085           }
3086         /* Reinitialize for a new argument.  */
3087         arg_going = 0;
3088         delete_this_arg = 0;
3089         this_is_output_file = 0;
3090         this_is_library_file = 0;
3091         break;
3092
3093       case '%':
3094         switch (c = *p++)
3095           {
3096           case 0:
3097             fatal ("Invalid specification!  Bug in cc.");
3098
3099           case 'b':
3100             obstack_grow (&obstack, input_basename, basename_length);
3101             arg_going = 1;
3102             break;
3103
3104           case 'd':
3105             delete_this_arg = 2;
3106             break;
3107
3108           /* Dump out the directories specified with LIBRARY_PATH,
3109              followed by the absolute directories
3110              that we search for startfiles.  */
3111           case 'D':
3112             {
3113               struct prefix_list *pl = startfile_prefixes.plist;
3114               int bufsize = 100;
3115               char *buffer = (char *) xmalloc (bufsize);
3116               int idx;
3117
3118               for (; pl; pl = pl->next)
3119                 {
3120 #ifdef RELATIVE_PREFIX_NOT_LINKDIR
3121                   /* Used on systems which record the specified -L dirs
3122                      and use them to search for dynamic linking.  */
3123                   /* Relative directories always come from -B,
3124                      and it is better not to use them for searching
3125                      at run time.  In particular, stage1 loses  */
3126                   if (pl->prefix[0] != '/' && pl->prefix[0] != DIR_SEPARATOR)
3127                     continue;
3128 #endif
3129                   /* Try subdirectory if there is one.  */
3130                   if (multilib_dir != NULL)
3131                     {
3132                       if (machine_suffix)
3133                         {
3134                           if (strlen (pl->prefix) + strlen (machine_suffix)
3135                               >= bufsize)
3136                             bufsize = (strlen (pl->prefix)
3137                                        + strlen (machine_suffix)) * 2 + 1;
3138                           buffer = (char *) xrealloc (buffer, bufsize);
3139                           strcpy (buffer, pl->prefix);
3140                           strcat (buffer, machine_suffix);
3141                           if (is_directory (buffer, multilib_dir, 1))
3142                             {
3143                               do_spec_1 ("-L", 0, NULL_PTR);
3144 #ifdef SPACE_AFTER_L_OPTION
3145                               do_spec_1 (" ", 0, NULL_PTR);
3146 #endif
3147                               do_spec_1 (buffer, 1, NULL_PTR);
3148                               do_spec_1 (multilib_dir, 1, NULL_PTR);
3149                               /* Make this a separate argument.  */
3150                               do_spec_1 (" ", 0, NULL_PTR);
3151                             }
3152                         }
3153                       if (!pl->require_machine_suffix)
3154                         {
3155                           if (is_directory (pl->prefix, multilib_dir, 1))
3156                             {
3157                               do_spec_1 ("-L", 0, NULL_PTR);
3158 #ifdef SPACE_AFTER_L_OPTION
3159                               do_spec_1 (" ", 0, NULL_PTR);
3160 #endif
3161                               do_spec_1 (pl->prefix, 1, NULL_PTR);
3162                               do_spec_1 (multilib_dir, 1, NULL_PTR);
3163                               /* Make this a separate argument.  */
3164                               do_spec_1 (" ", 0, NULL_PTR);
3165                             }
3166                         }
3167                     }
3168                   if (machine_suffix)
3169                     {
3170                       if (is_directory (pl->prefix, machine_suffix, 1))
3171                         {
3172                           do_spec_1 ("-L", 0, NULL_PTR);
3173 #ifdef SPACE_AFTER_L_OPTION
3174                           do_spec_1 (" ", 0, NULL_PTR);
3175 #endif
3176                           do_spec_1 (pl->prefix, 1, NULL_PTR);
3177                           /* Remove slash from machine_suffix.  */
3178                           if (strlen (machine_suffix) >= bufsize)
3179                             bufsize = strlen (machine_suffix) * 2 + 1;
3180                           buffer = (char *) xrealloc (buffer, bufsize);
3181                           strcpy (buffer, machine_suffix);
3182                           idx = strlen (buffer);
3183                           if (buffer[idx - 1] == '/'
3184                               || buffer[idx - 1] == DIR_SEPARATOR)
3185                             buffer[idx - 1] = 0;
3186                           do_spec_1 (buffer, 1, NULL_PTR);
3187                           /* Make this a separate argument.  */
3188                           do_spec_1 (" ", 0, NULL_PTR);
3189                         }
3190                     }
3191                   if (!pl->require_machine_suffix)
3192                     {
3193                       if (is_directory (pl->prefix, "", 1))
3194                         {
3195                           do_spec_1 ("-L", 0, NULL_PTR);
3196 #ifdef SPACE_AFTER_L_OPTION
3197                           do_spec_1 (" ", 0, NULL_PTR);
3198 #endif
3199                           /* Remove slash from pl->prefix.  */
3200                           if (strlen (pl->prefix) >= bufsize)
3201                             bufsize = strlen (pl->prefix) * 2 + 1;
3202                           buffer = (char *) xrealloc (buffer, bufsize);
3203                           strcpy (buffer, pl->prefix);
3204                           idx = strlen (buffer);
3205                           if (buffer[idx - 1] == '/'
3206                               || buffer[idx - 1] == DIR_SEPARATOR)
3207                             buffer[idx - 1] = 0;
3208                           do_spec_1 (buffer, 1, NULL_PTR);
3209                           /* Make this a separate argument.  */
3210                           do_spec_1 (" ", 0, NULL_PTR);
3211                         }
3212                     }
3213                 }
3214               free (buffer);
3215             }
3216             break;
3217
3218           case 'e':
3219             /* {...:%efoo} means report an error with `foo' as error message
3220                and don't execute any more commands for this file.  */
3221             {
3222               char *q = p;
3223               char *buf;
3224               while (*p != 0 && *p != '\n') p++;
3225               buf = (char *) alloca (p - q + 1);
3226               strncpy (buf, q, p - q);
3227               buf[p - q] = 0;
3228               error ("%s", buf);
3229               return -1;
3230             }
3231             break;
3232
3233           case 'g':
3234           case 'u':
3235           case 'U':
3236             if (save_temps_flag)
3237               {
3238                 obstack_grow (&obstack, input_basename, basename_length);
3239                 delete_this_arg = 0;
3240               }
3241             else
3242               {
3243 #ifdef MKTEMP_EACH_FILE
3244                 /* ??? This has a problem: the total number of
3245                    values mktemp can return is limited.
3246                    That matters for the names of object files.
3247                    In 2.4, do something about that.  */
3248                 struct temp_name *t;
3249                 char *suffix = p;
3250                 while (*p == '.' || isalpha (*p)
3251                        || (p[0] == '%' && p[1] == 'O'))
3252                   p++;
3253
3254                 /* See if we already have an association of %g/%u/%U and
3255                    suffix.  */
3256                 for (t = temp_names; t; t = t->next)
3257                   if (t->length == p - suffix
3258                       && strncmp (t->suffix, suffix, p - suffix) == 0
3259                       && t->unique == (c != 'g'))
3260                     break;
3261
3262                 /* Make a new association if needed.  %u requires one.  */
3263                 if (t == 0 || c == 'u')
3264                   {
3265                     if (t == 0)
3266                       {
3267                         t = (struct temp_name *) xmalloc (sizeof (struct temp_name));
3268                         t->next = temp_names;
3269                         temp_names = t;
3270                       }
3271                     t->length = p - suffix;
3272                     t->suffix = save_string (suffix, p - suffix);
3273                     t->unique = (c != 'g');
3274                     temp_filename = choose_temp_base ();
3275                     temp_filename_length = strlen (temp_filename);
3276                     t->filename = temp_filename;
3277                     t->filename_length = temp_filename_length;
3278                   }
3279
3280                 obstack_grow (&obstack, t->filename, t->filename_length);
3281                 delete_this_arg = 1;
3282 #else
3283                 obstack_grow (&obstack, temp_filename, temp_filename_length);
3284                 if (c == 'u' || c == 'U')
3285                   {
3286                     static int unique;
3287                     char buff[9];
3288                     if (c == 'u')
3289                       unique++;
3290                     sprintf (buff, "%d", unique);
3291                     obstack_grow (&obstack, buff, strlen (buff));
3292                   }
3293 #endif
3294                 delete_this_arg = 1;
3295               }
3296             arg_going = 1;
3297             break;
3298
3299           case 'i':
3300             obstack_grow (&obstack, input_filename, input_filename_length);
3301             arg_going = 1;
3302             break;
3303
3304           case 'I':
3305             {
3306               struct prefix_list *pl = include_prefixes.plist;
3307
3308               if (gcc_exec_prefix)
3309                 {
3310                   do_spec_1 ("-iprefix", 1, NULL_PTR);
3311                   /* Make this a separate argument.  */
3312                   do_spec_1 (" ", 0, NULL_PTR);
3313                   do_spec_1 (gcc_exec_prefix, 1, NULL_PTR);
3314                   do_spec_1 (" ", 0, NULL_PTR);
3315                 }
3316
3317               for (; pl; pl = pl->next)
3318                 {
3319                   do_spec_1 ("-isystem", 1, NULL_PTR);
3320                   /* Make this a separate argument.  */
3321                   do_spec_1 (" ", 0, NULL_PTR);
3322                   do_spec_1 (pl->prefix, 1, NULL_PTR);
3323                   do_spec_1 (" ", 0, NULL_PTR);
3324                 }
3325             }
3326             break;
3327
3328           case 'o':
3329             for (i = 0; i < n_infiles; i++)
3330               store_arg (outfiles[i], 0, 0);
3331             break;
3332
3333           case 'O':
3334             obstack_grow (&obstack, OBJECT_SUFFIX, strlen (OBJECT_SUFFIX));
3335             arg_going = 1;
3336             break;
3337
3338           case 's':
3339             this_is_library_file = 1;
3340             break;
3341
3342           case 'w':
3343             this_is_output_file = 1;
3344             break;
3345
3346           case 'W':
3347             {
3348               int cur_index = argbuf_index;
3349               /* Handle the {...} following the %W.  */
3350               if (*p != '{')
3351                 abort ();
3352               p = handle_braces (p + 1);
3353               if (p == 0)
3354                 return -1;
3355               /* If any args were output, mark the last one for deletion
3356                  on failure.  */
3357               if (argbuf_index != cur_index)
3358                 record_temp_file (argbuf[argbuf_index - 1], 0, 1);
3359               break;
3360             }
3361
3362           /* %x{OPTION} records OPTION for %X to output.  */
3363           case 'x':
3364             {
3365               char *p1 = p;
3366               char *string;
3367
3368               /* Skip past the option value and make a copy.  */
3369               if (*p != '{')
3370                 abort ();
3371               while (*p++ != '}')
3372                 ;
3373               string = save_string (p1 + 1, p - p1 - 2);
3374
3375               /* See if we already recorded this option.  */
3376               for (i = 0; i < n_linker_options; i++)
3377                 if (! strcmp (string, linker_options[i]))
3378                   {
3379                     free (string);
3380                     return 0;
3381                   }
3382
3383               /* This option is new; add it.  */
3384               n_linker_options++;
3385               if (!linker_options)
3386                 linker_options
3387                   = (char **) xmalloc (n_linker_options * sizeof (char **));
3388               else
3389                 linker_options
3390                   = (char **) xrealloc (linker_options,
3391                                         n_linker_options * sizeof (char **));
3392
3393               linker_options[n_linker_options - 1] = string;
3394             }
3395             break;
3396
3397           /* Dump out the options accumulated previously using %x.  */
3398           case 'X':
3399             for (i = 0; i < n_linker_options; i++)
3400               {
3401                 do_spec_1 (linker_options[i], 1, NULL_PTR);
3402                 /* Make each accumulated option a separate argument.  */
3403                 do_spec_1 (" ", 0, NULL_PTR);
3404               }
3405             break;
3406
3407           /* Dump out the options accumulated previously using -Wa,.  */
3408           case 'Y':
3409             for (i = 0; i < n_assembler_options; i++)
3410               {
3411                 do_spec_1 (assembler_options[i], 1, NULL_PTR);
3412                 /* Make each accumulated option a separate argument.  */
3413                 do_spec_1 (" ", 0, NULL_PTR);
3414               }
3415             break;
3416
3417           /* Dump out the options accumulated previously using -Wp,.  */
3418           case 'Z':
3419             for (i = 0; i < n_preprocessor_options; i++)
3420               {
3421                 do_spec_1 (preprocessor_options[i], 1, NULL_PTR);
3422                 /* Make each accumulated option a separate argument.  */
3423                 do_spec_1 (" ", 0, NULL_PTR);
3424               }
3425             break;
3426
3427             /* Here are digits and numbers that just process
3428                a certain constant string as a spec.  */
3429
3430           case '1':
3431             value = do_spec_1 (cc1_spec, 0, NULL_PTR);
3432             if (value != 0)
3433               return value;
3434             break;
3435
3436           case '2':
3437             value = do_spec_1 (cc1plus_spec, 0, NULL_PTR);
3438             if (value != 0)
3439               return value;
3440             break;
3441
3442           case 'a':
3443             value = do_spec_1 (asm_spec, 0, NULL_PTR);
3444             if (value != 0)
3445               return value;
3446             break;
3447
3448           case 'A':
3449             value = do_spec_1 (asm_final_spec, 0, NULL_PTR);
3450             if (value != 0)
3451               return value;
3452             break;
3453
3454           case 'c':
3455             value = do_spec_1 (signed_char_spec, 0, NULL_PTR);
3456             if (value != 0)
3457               return value;
3458             break;
3459
3460           case 'C':
3461             value = do_spec_1 (cpp_spec, 0, NULL_PTR);
3462             if (value != 0)
3463               return value;
3464             break;
3465
3466           case 'E':
3467             value = do_spec_1 (endfile_spec, 0, NULL_PTR);
3468             if (value != 0)
3469               return value;
3470             break;
3471
3472           case 'l':
3473             value = do_spec_1 (link_spec, 0, NULL_PTR);
3474             if (value != 0)
3475               return value;
3476             break;
3477
3478           case 'L':
3479             value = do_spec_1 (lib_spec, 0, NULL_PTR);
3480             if (value != 0)
3481               return value;
3482             break;
3483
3484           case 'G':
3485             value = do_spec_1 (libgcc_spec, 0, NULL_PTR);
3486             if (value != 0)
3487               return value;
3488             break;
3489
3490           case 'p':
3491             {
3492               char *x = (char *) alloca (strlen (cpp_predefines) + 1);
3493               char *buf = x;
3494               char *y;
3495
3496               /* Copy all of the -D options in CPP_PREDEFINES into BUF.  */
3497               y = cpp_predefines;
3498               while (*y != 0)
3499                 {
3500                   if (! strncmp (y, "-D", 2))
3501                     /* Copy the whole option.  */
3502                     while (*y && *y != ' ' && *y != '\t')
3503                       *x++ = *y++;
3504                   else if (*y == ' ' || *y == '\t')
3505                     /* Copy whitespace to the result.  */
3506                     *x++ = *y++;
3507                   /* Don't copy other options.  */
3508                   else
3509                     y++;
3510                 }
3511
3512               *x = 0;
3513
3514               value = do_spec_1 (buf, 0, NULL_PTR);
3515               if (value != 0)
3516                 return value;
3517             }
3518             break;
3519
3520           case 'P':
3521             {
3522               char *x = (char *) alloca (strlen (cpp_predefines) * 4 + 1);
3523               char *buf = x;
3524               char *y;
3525
3526               /* Copy all of CPP_PREDEFINES into BUF,
3527                  but put __ after every -D and at the end of each arg.  */
3528               y = cpp_predefines;
3529               while (*y != 0)
3530                 {
3531                   if (! strncmp (y, "-D", 2))
3532                     {
3533                       int flag = 0;
3534
3535                       *x++ = *y++;
3536                       *x++ = *y++;
3537
3538                       if (*y != '_'
3539                           || (*(y+1) != '_' && ! isupper (*(y+1))))
3540                         {
3541                           /* Stick __ at front of macro name.  */
3542                           *x++ = '_';
3543                           *x++ = '_';
3544                           /* Arrange to stick __ at the end as well.  */
3545                           flag = 1;
3546                         }
3547
3548                       /* Copy the macro name.  */
3549                       while (*y && *y != '=' && *y != ' ' && *y != '\t')
3550                         *x++ = *y++;
3551
3552                       if (flag)
3553                         {
3554                           *x++ = '_';
3555                           *x++ = '_';
3556                         }
3557
3558                       /* Copy the value given, if any.  */
3559                       while (*y && *y != ' ' && *y != '\t')
3560                         *x++ = *y++;
3561                     }
3562                   else if (*y == ' ' || *y == '\t')
3563                     /* Copy whitespace to the result.  */
3564                     *x++ = *y++;
3565                   /* Don't copy -A options  */
3566                   else
3567                     y++;
3568                 }
3569               *x++ = ' ';
3570
3571               /* Copy all of CPP_PREDEFINES into BUF,
3572                  but put __ after every -D.  */
3573               y = cpp_predefines;
3574               while (*y != 0)
3575                 {
3576                   if (! strncmp (y, "-D", 2))
3577                     {
3578                       y += 2;
3579
3580                       if (*y != '_'
3581                           || (*(y+1) != '_' && ! isupper (*(y+1))))
3582                         {
3583                           /* Stick -D__ at front of macro name.  */
3584                           *x++ = '-';
3585                           *x++ = 'D';
3586                           *x++ = '_';
3587                           *x++ = '_';
3588
3589                           /* Copy the macro name.  */
3590                           while (*y && *y != '=' && *y != ' ' && *y != '\t')
3591                             *x++ = *y++;
3592
3593                           /* Copy the value given, if any.  */
3594                           while (*y && *y != ' ' && *y != '\t')
3595                             *x++ = *y++;
3596                         }
3597                       else
3598                         {
3599                           /* Do not copy this macro - we have just done it before */
3600                           while (*y && *y != ' ' && *y != '\t')
3601                             y++;
3602                         }
3603                     }
3604                   else if (*y == ' ' || *y == '\t')
3605                     /* Copy whitespace to the result.  */
3606                     *x++ = *y++;
3607                   /* Don't copy -A options  */
3608                   else
3609                     y++;
3610                 }
3611               *x++ = ' ';
3612
3613               /* Copy all of the -A options in CPP_PREDEFINES into BUF.  */
3614               y = cpp_predefines;
3615               while (*y != 0)
3616                 {
3617                   if (! strncmp (y, "-A", 2))
3618                     /* Copy the whole option.  */
3619                     while (*y && *y != ' ' && *y != '\t')
3620                       *x++ = *y++;
3621                   else if (*y == ' ' || *y == '\t')
3622                     /* Copy whitespace to the result.  */
3623                     *x++ = *y++;
3624                   /* Don't copy other options.  */
3625                   else
3626                     y++;
3627                 }
3628
3629               *x = 0;
3630
3631               value = do_spec_1 (buf, 0, NULL_PTR);
3632               if (value != 0)
3633                 return value;
3634             }
3635             break;
3636
3637           case 'S':
3638             value = do_spec_1 (startfile_spec, 0, NULL_PTR);
3639             if (value != 0)
3640               return value;
3641             break;
3642
3643             /* Here we define characters other than letters and digits.  */
3644
3645           case '{':
3646             p = handle_braces (p);
3647             if (p == 0)
3648               return -1;
3649             break;
3650
3651           case '%':
3652             obstack_1grow (&obstack, '%');
3653             break;
3654
3655           case '*':
3656             do_spec_1 (soft_matched_part, 1, NULL_PTR);
3657             do_spec_1 (" ", 0, NULL_PTR);
3658             break;
3659
3660             /* Process a string found as the value of a spec given by name.
3661                This feature allows individual machine descriptions
3662                to add and use their own specs.
3663                %[...] modifies -D options the way %P does;
3664                %(...) uses the spec unmodified.  */
3665           case '(':
3666           case '[':
3667             {
3668               char *name = p;
3669               struct spec_list *sl;
3670               int len;
3671
3672               /* The string after the S/P is the name of a spec that is to be
3673                  processed. */
3674               while (*p && *p != ')' && *p != ']')
3675                 p++;
3676
3677               /* See if it's in the list */
3678               for (len = p - name, sl = specs; sl; sl = sl->next)
3679                 if (strncmp (sl->name, name, len) == 0 && !sl->name[len])
3680                   {
3681                     name = sl->spec;
3682                     break;
3683                   }
3684
3685               if (sl)
3686                 {
3687                   if (c == '(')
3688                     {
3689                       value = do_spec_1 (name, 0, NULL_PTR);
3690                       if (value != 0)
3691                         return value;
3692                     }
3693                   else
3694                     {
3695                       char *x = (char *) alloca (strlen (name) * 2 + 1);
3696                       char *buf = x;
3697                       char *y = name;
3698
3699                       /* Copy all of NAME into BUF, but put __ after
3700                          every -D and at the end of each arg,  */
3701                       while (1)
3702                         {
3703                           if (! strncmp (y, "-D", 2))
3704                             {
3705                               *x++ = '-';
3706                               *x++ = 'D';
3707                               *x++ = '_';
3708                               *x++ = '_';
3709                               y += 2;
3710                             }
3711                           else if (*y == ' ' || *y == 0)
3712                             {
3713                               *x++ = '_';
3714                               *x++ = '_';
3715                               if (*y == 0)
3716                                 break;
3717                               else
3718                                 *x++ = *y++;
3719                             }
3720                           else
3721                             *x++ = *y++;
3722                         }
3723                       *x = 0;
3724
3725                       value = do_spec_1 (buf, 0, NULL_PTR);
3726                       if (value != 0)
3727                         return value;
3728                     }
3729                 }
3730
3731               /* Discard the closing paren or bracket.  */
3732               if (*p)
3733                 p++;
3734             }
3735             break;
3736
3737           case 'v':
3738             {
3739               int c1 = *p++;  /* Select first or second version number.  */
3740               char *v = compiler_version;
3741               char *q, *copy;
3742               /* If desired, advance to second version number.  */
3743               if (c1 == '2')
3744                 {
3745                   /* Set V after the first period.  */
3746                   while (*v != 0 && *v != ' ' && *v != '.')
3747                     v++;
3748                   if (*v == '.')
3749                     v++;
3750                 }
3751               /* Set Q at the next period or at the end.  */
3752               q = v;
3753               while (*q != 0 && *q != ' ' && *q != '.')
3754                 q++;
3755               /* Empty string means zero.  */
3756               if (v == q)
3757                 {
3758                   v = "0";
3759                   q = v + 1;
3760                 }
3761               /* Put that part into the command.  */
3762               obstack_grow (&obstack, v, q - v);
3763               arg_going = 1;
3764             }
3765             break;
3766
3767           case '|':
3768             if (input_from_pipe)
3769               do_spec_1 ("-", 0, NULL_PTR);
3770             break;
3771
3772           default:
3773             abort ();
3774           }
3775         break;
3776
3777       case '\\':
3778         /* Backslash: treat next character as ordinary.  */
3779         c = *p++;
3780
3781         /* fall through */
3782       default:
3783         /* Ordinary character: put it into the current argument.  */
3784         obstack_1grow (&obstack, c);
3785         arg_going = 1;
3786       }
3787
3788   return 0;             /* End of string */
3789 }
3790
3791 /* Return 0 if we call do_spec_1 and that returns -1.  */
3792
3793 static char *
3794 handle_braces (p)
3795      register char *p;
3796 {
3797   register char *q;
3798   char *filter;
3799   int pipe_p = 0;
3800   int negate = 0;
3801   int suffix = 0;
3802
3803   if (*p == '|')
3804     /* A `|' after the open-brace means,
3805        if the test fails, output a single minus sign rather than nothing.
3806        This is used in %{|!pipe:...}.  */
3807     pipe_p = 1, ++p;
3808
3809   if (*p == '!')
3810     /* A `!' after the open-brace negates the condition:
3811        succeed if the specified switch is not present.  */
3812     negate = 1, ++p;
3813
3814   if (*p == '.')
3815     /* A `.' after the open-brace means test against the current suffix.  */
3816     {
3817       if (pipe_p)
3818         abort ();
3819
3820       suffix = 1;
3821       ++p;
3822     }
3823
3824   filter = p;
3825   while (*p != ':' && *p != '}') p++;
3826   if (*p != '}')
3827     {
3828       register int count = 1;
3829       q = p + 1;
3830       while (count > 0)
3831         {
3832           if (*q == '{')
3833             count++;
3834           else if (*q == '}')
3835             count--;
3836           else if (*q == 0)
3837             abort ();
3838           q++;
3839         }
3840     }
3841   else
3842     q = p + 1;
3843
3844   if (suffix)
3845     {
3846       int found = (input_suffix != 0
3847                    && strlen (input_suffix) == p - filter
3848                    && strncmp (input_suffix, filter, p - filter) == 0);
3849
3850       if (p[0] == '}')
3851         abort ();
3852
3853       if (negate != found
3854           && do_spec_1 (save_string (p + 1, q - p - 2), 0, NULL_PTR) < 0)
3855         return 0;
3856
3857       return q;
3858     }
3859   else if (p[-1] == '*' && p[0] == '}')
3860     {
3861       /* Substitute all matching switches as separate args.  */
3862       register int i;
3863       --p;
3864       for (i = 0; i < n_switches; i++)
3865         if (!strncmp (switches[i].part1, filter, p - filter)
3866             && check_live_switch (i, p - filter))
3867           give_switch (i, 0);
3868     }
3869   else
3870     {
3871       /* Test for presence of the specified switch.  */
3872       register int i;
3873       int present = 0;
3874
3875       /* If name specified ends in *, as in {x*:...},
3876          check for %* and handle that case.  */
3877       if (p[-1] == '*' && !negate)
3878         {
3879           int substitution;
3880           char *r = p;
3881
3882           /* First see whether we have %*.  */
3883           substitution = 0;
3884           while (r < q)
3885             {
3886               if (*r == '%' && r[1] == '*')
3887                 substitution = 1;
3888               r++;
3889             }
3890           /* If we do, handle that case.  */
3891           if (substitution)
3892             {
3893               /* Substitute all matching switches as separate args.
3894                  But do this by substituting for %*
3895                  in the text that follows the colon.  */
3896
3897               unsigned hard_match_len = p - filter - 1;
3898               char *string = save_string (p + 1, q - p - 2);
3899
3900               for (i = 0; i < n_switches; i++)
3901                 if (!strncmp (switches[i].part1, filter, hard_match_len)
3902                     && check_live_switch (i, -1))
3903                   {
3904                     do_spec_1 (string, 0, &switches[i].part1[hard_match_len]);
3905                     /* Pass any arguments this switch has.  */
3906                     give_switch (i, 1);
3907                   }
3908
3909               return q;
3910             }
3911         }
3912
3913       /* If name specified ends in *, as in {x*:...},
3914          check for presence of any switch name starting with x.  */
3915       if (p[-1] == '*')
3916         {
3917           for (i = 0; i < n_switches; i++)
3918             {
3919               unsigned hard_match_len = p - filter - 1;
3920
3921               if (!strncmp (switches[i].part1, filter, hard_match_len)
3922                   && check_live_switch (i, hard_match_len))
3923                 {
3924                   present = 1;
3925                 }
3926             }
3927         }
3928       /* Otherwise, check for presence of exact name specified.  */
3929       else
3930         {
3931           for (i = 0; i < n_switches; i++)
3932             {
3933               if (!strncmp (switches[i].part1, filter, p - filter)
3934                   && switches[i].part1[p - filter] == 0
3935                   && check_live_switch (i, -1))
3936                 {
3937                   present = 1;
3938                   break;
3939                 }
3940             }
3941         }
3942
3943       /* If it is as desired (present for %{s...}, absent for %{-s...})
3944          then substitute either the switch or the specified
3945          conditional text.  */
3946       if (present != negate)
3947         {
3948           if (*p == '}')
3949             {
3950               give_switch (i, 0);
3951             }
3952           else
3953             {
3954               if (do_spec_1 (save_string (p + 1, q - p - 2), 0, NULL_PTR) < 0)
3955                 return 0;
3956             }
3957         }
3958       else if (pipe_p)
3959         {
3960           /* Here if a %{|...} conditional fails: output a minus sign,
3961              which means "standard output" or "standard input".  */
3962           do_spec_1 ("-", 0, NULL_PTR);
3963         }
3964     }
3965
3966   return q;
3967 }
3968 \f
3969 /* Return 0 iff switch number SWITCHNUM is obsoleted by a later switch
3970    on the command line.  PREFIX_LENGTH is the length of XXX in an {XXX*}
3971    spec, or -1 if either exact match or %* is used.
3972
3973    A -O switch is obsoleted by a later -O switch.  A -f, -m, or -W switch
3974    whose value does not begin with "no-" is obsoleted by the same value
3975    with the "no-", similarly for a switch with the "no-" prefix.  */
3976
3977 static int
3978 check_live_switch (switchnum, prefix_length)
3979      int switchnum;
3980      int prefix_length;
3981 {
3982   char *name = switches[switchnum].part1;
3983   int i;
3984
3985   /* In the common case of {<at-most-one-letter>*}, a negating
3986      switch would always match, so ignore that case.  We will just
3987      send the conflicting switches to the compiler phase.  */
3988   if (prefix_length >= 0 && prefix_length <= 1)
3989     return 1;
3990
3991   /* If we already processed this switch and determined if it was
3992      live or not, return our past determination.  */
3993   if (switches[switchnum].live_cond != 0)
3994     return switches[switchnum].live_cond > 0;
3995
3996   /* Now search for duplicate in a manner that depends on the name.  */
3997   switch (*name)
3998     {
3999     case 'O':
4000         for (i = switchnum + 1; i < n_switches; i++)
4001           if (switches[i].part1[0] == 'O')
4002             {
4003               switches[switchnum].valid = 1;
4004               switches[switchnum].live_cond = -1;
4005               return 0;
4006             }
4007       break;
4008
4009     case 'W':  case 'f':  case 'm':
4010       if (! strncmp (name + 1, "no-", 3))
4011         {
4012           /* We have Xno-YYY, search for XYYY. */
4013           for (i = switchnum + 1; i < n_switches; i++)
4014             if (switches[i].part1[0] == name[0]
4015                 && ! strcmp (&switches[i].part1[1], &name[4]))
4016             {
4017               switches[switchnum].valid = 1;
4018               switches[switchnum].live_cond = -1;
4019               return 0;
4020             }
4021         }
4022       else
4023         {
4024           /* We have XYYY, search for Xno-YYY.  */
4025           for (i = switchnum + 1; i < n_switches; i++)
4026             if (switches[i].part1[0] == name[0]
4027                 && switches[i].part1[1] == 'n'
4028                 && switches[i].part1[2] == 'o'
4029                 && switches[i].part1[3] == '-'
4030                 && !strcmp (&switches[i].part1[4], &name[1]))
4031             {
4032               switches[switchnum].valid = 1;
4033               switches[switchnum].live_cond = -1;
4034               return 0;
4035             }
4036         }
4037       break;
4038     }
4039
4040   /* Otherwise the switch is live.  */
4041   switches[switchnum].live_cond = 1;
4042   return 1;
4043 }
4044 \f
4045 /* Pass a switch to the current accumulating command
4046    in the same form that we received it.
4047    SWITCHNUM identifies the switch; it is an index into
4048    the vector of switches gcc received, which is `switches'.
4049    This cannot fail since it never finishes a command line.
4050
4051    If OMIT_FIRST_WORD is nonzero, then we omit .part1 of the argument.  */
4052
4053 static void
4054 give_switch (switchnum, omit_first_word)
4055      int switchnum;
4056      int omit_first_word;
4057 {
4058   if (!omit_first_word)
4059     {
4060       do_spec_1 ("-", 0, NULL_PTR);
4061       do_spec_1 (switches[switchnum].part1, 1, NULL_PTR);
4062     }
4063   do_spec_1 (" ", 0, NULL_PTR);
4064   if (switches[switchnum].args != 0)
4065     {
4066       char **p;
4067       for (p = switches[switchnum].args; *p; p++)
4068         {
4069           do_spec_1 (*p, 1, NULL_PTR);
4070           do_spec_1 (" ", 0, NULL_PTR);
4071         }
4072     }
4073   switches[switchnum].valid = 1;
4074 }
4075 \f
4076 /* Search for a file named NAME trying various prefixes including the
4077    user's -B prefix and some standard ones.
4078    Return the absolute file name found.  If nothing is found, return NAME.  */
4079
4080 static char *
4081 find_file (name)
4082      char *name;
4083 {
4084   char *newname;
4085
4086   /* Try multilib_dir if it is defined.  */
4087   if (multilib_dir != NULL)
4088     {
4089       char *try;
4090
4091       try = (char *) alloca (strlen (multilib_dir) + strlen (name) + 2);
4092       strcpy (try, multilib_dir);
4093       strcat (try, dir_separator_str);
4094       strcat (try, name);
4095
4096       newname = find_a_file (&startfile_prefixes, try, R_OK);
4097
4098       /* If we don't find it in the multi library dir, then fall
4099          through and look for it in the normal places.  */
4100       if (newname != NULL)
4101         return newname;
4102     }
4103
4104   newname = find_a_file (&startfile_prefixes, name, R_OK);
4105   return newname ? newname : name;
4106 }
4107
4108 /* Determine whether a directory exists.  If LINKER, return 0 for
4109    certain fixed names not needed by the linker.  If not LINKER, it is
4110    only important to return 0 if the host machine has a small ARG_MAX
4111    limit.  */
4112
4113 static int
4114 is_directory (path1, path2, linker)
4115      char *path1;
4116      char *path2;
4117      int linker;
4118 {
4119   int len1 = strlen (path1);
4120   int len2 = strlen (path2);
4121   char *path = (char *) alloca (3 + len1 + len2);
4122   char *cp;
4123   struct stat st;
4124
4125 #ifndef SMALL_ARG_MAX
4126   if (! linker)
4127     return 1;
4128 #endif
4129
4130   /* Construct the path from the two parts.  Ensure the string ends with "/.".
4131      The resulting path will be a directory even if the given path is a
4132      symbolic link.  */
4133   bcopy (path1, path, len1);
4134   bcopy (path2, path + len1, len2);
4135   cp = path + len1 + len2;
4136   if (cp[-1] != '/' && cp[-1] != DIR_SEPARATOR)
4137     *cp++ = DIR_SEPARATOR;
4138   *cp++ = '.';
4139   *cp = '\0';
4140
4141   /* Exclude directories that the linker is known to search.  */
4142   if (linker
4143       && ((cp - path == 6
4144            && strcmp (path, concat (dir_separator_str, "lib", 
4145                                     dir_separator_str, ".", NULL_PTR)) == 0)
4146           || (cp - path == 10
4147               && strcmp (path, concat (dir_separator_str, "usr", 
4148                                        dir_separator_str, "lib", 
4149                                        dir_separator_str, ".", NULL_PTR)) == 0)))
4150     return 0;
4151
4152   return (stat (path, &st) >= 0 && S_ISDIR (st.st_mode));
4153 }
4154 \f
4155 /* On fatal signals, delete all the temporary files.  */
4156
4157 static void
4158 fatal_error (signum)
4159      int signum;
4160 {
4161   signal (signum, SIG_DFL);
4162   delete_failure_queue ();
4163   delete_temp_files ();
4164   /* Get the same signal again, this time not handled,
4165      so its normal effect occurs.  */
4166   kill (getpid (), signum);
4167 }
4168
4169 int
4170 main (argc, argv)
4171      int argc;
4172      char **argv;
4173 {
4174   register int i;
4175   int j;
4176   int value;
4177   int linker_was_run = 0;
4178   char *explicit_link_files;
4179   char *specs_file;
4180   char *p;
4181
4182   p = argv[0] + strlen (argv[0]);
4183   while (p != argv[0] && p[-1] != '/' && p[-1] != DIR_SEPARATOR) --p;
4184   programname = p;
4185
4186   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
4187     signal (SIGINT, fatal_error);
4188 #ifdef SIGHUP
4189   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
4190     signal (SIGHUP, fatal_error);
4191 #endif
4192   if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
4193     signal (SIGTERM, fatal_error);
4194 #ifdef SIGPIPE
4195   if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
4196     signal (SIGPIPE, fatal_error);
4197 #endif
4198
4199   argbuf_length = 10;
4200   argbuf = (char **) xmalloc (argbuf_length * sizeof (char *));
4201
4202   obstack_init (&obstack);
4203
4204   /* Set up to remember the pathname of gcc and any options
4205      needed for collect.  We use argv[0] instead of programname because
4206      we need the complete pathname.  */
4207   obstack_init (&collect_obstack);
4208   obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=")-1);
4209   obstack_grow (&collect_obstack, argv[0], strlen (argv[0])+1);
4210   putenv (obstack_finish (&collect_obstack));
4211
4212 #ifdef INIT_ENVIRONMENT
4213   /* Set up any other necessary machine specific environment variables.  */
4214   putenv (INIT_ENVIRONMENT);
4215 #endif
4216
4217   /* Choose directory for temp files.  */
4218
4219   temp_filename = choose_temp_base ();
4220   temp_filename_length = strlen (temp_filename);
4221
4222   /* Make a table of what switches there are (switches, n_switches).
4223      Make a table of specified input files (infiles, n_infiles).
4224      Decode switches that are handled locally.  */
4225
4226   process_command (argc, argv);
4227
4228   /* Initialize the vector of specs to just the default.
4229      This means one element containing 0s, as a terminator.  */
4230
4231   compilers = (struct compiler *) xmalloc (sizeof default_compilers);
4232   bcopy ((char *) default_compilers, (char *) compilers,
4233          sizeof default_compilers);
4234   n_compilers = n_default_compilers;
4235
4236   /* Read specs from a file if there is one.  */
4237
4238   machine_suffix = concat (spec_machine, dir_separator_str,
4239                            spec_version, dir_separator_str, NULL_PTR);
4240   just_machine_suffix = concat (spec_machine, dir_separator_str, NULL_PTR);
4241
4242   specs_file = find_a_file (&startfile_prefixes, "specs", R_OK);
4243   /* Read the specs file unless it is a default one.  */
4244   if (specs_file != 0 && strcmp (specs_file, "specs"))
4245     read_specs (specs_file);
4246
4247 #ifdef EXTRA_SPECS
4248   else
4249     {
4250       int k;
4251       for (k = 0; k < sizeof (extra_specs) / sizeof (extra_specs[0]); k++)
4252         set_spec (extra_specs[k].name, extra_specs[k].spec);
4253     }
4254 #endif
4255
4256   /* If not cross-compiling, look for startfiles in the standard places.  */
4257   /* The fact that these are done here, after reading the specs file,
4258      means that it cannot be found in these directories.
4259      But that's okay.  It should never be there anyway.  */
4260   if (!cross_compile)
4261     {
4262 #ifdef MD_EXEC_PREFIX
4263       add_prefix (&exec_prefixes, md_exec_prefix, 0, 0, NULL_PTR);
4264       add_prefix (&startfile_prefixes, md_exec_prefix, 0, 0, NULL_PTR);
4265 #endif
4266
4267 #ifdef MD_STARTFILE_PREFIX
4268       add_prefix (&startfile_prefixes, md_startfile_prefix, 0, 0, NULL_PTR);
4269 #endif
4270
4271 #ifdef MD_STARTFILE_PREFIX_1
4272       add_prefix (&startfile_prefixes, md_startfile_prefix_1, 0, 0, NULL_PTR);
4273 #endif
4274
4275       /* If standard_startfile_prefix is relative, base it on
4276          standard_exec_prefix.  This lets us move the installed tree
4277          as a unit.  If GCC_EXEC_PREFIX is defined, base
4278          standard_startfile_prefix on that as well.  */
4279       if (*standard_startfile_prefix == '/'
4280           || *standard_startfile_prefix == DIR_SEPARATOR)
4281         add_prefix (&startfile_prefixes, standard_startfile_prefix, 0, 0,
4282                     NULL_PTR);
4283       else
4284         {
4285           if (gcc_exec_prefix)
4286             add_prefix (&startfile_prefixes,
4287                         concat (gcc_exec_prefix, machine_suffix,
4288                                 standard_startfile_prefix, NULL_PTR),
4289                         0, 0, NULL_PTR);
4290           add_prefix (&startfile_prefixes,
4291                       concat (standard_exec_prefix,
4292                               machine_suffix,
4293                               standard_startfile_prefix, NULL_PTR),
4294                       0, 0, NULL_PTR);
4295         }                      
4296
4297       add_prefix (&startfile_prefixes, standard_startfile_prefix_1, 0, 0,
4298                   NULL_PTR);
4299       add_prefix (&startfile_prefixes, standard_startfile_prefix_2, 0, 0,
4300                   NULL_PTR);
4301 #if 0 /* Can cause surprises, and one can use -B./ instead.  */
4302       add_prefix (&startfile_prefixes, "./", 0, 1, NULL_PTR);
4303 #endif
4304     }
4305   else
4306     {
4307       if (*standard_startfile_prefix != DIR_SEPARATOR && gcc_exec_prefix)
4308         add_prefix (&startfile_prefixes,
4309                     concat (gcc_exec_prefix, machine_suffix,
4310                             standard_startfile_prefix, NULL_PTR),
4311                     0, 0, NULL_PTR);
4312     }
4313
4314   /* If we have a GCC_EXEC_PREFIX envvar, modify it for cpp's sake.  */
4315   if (gcc_exec_prefix)
4316     {
4317       char * temp = (char *) xmalloc (strlen (gcc_exec_prefix)
4318                                       + strlen (spec_version)
4319                                       + strlen (spec_machine) + 3);
4320       strcpy (temp, gcc_exec_prefix);
4321       strcat (temp, spec_machine);
4322       strcat (temp, dir_separator_str);
4323       strcat (temp, spec_version);
4324       strcat (temp, dir_separator_str);
4325       gcc_exec_prefix = temp;
4326     }
4327
4328   /* Now we have the specs.
4329      Set the `valid' bits for switches that match anything in any spec.  */
4330
4331   validate_all_switches ();
4332
4333   /* Now that we have the switches and the specs, set
4334      the subdirectory based on the options.  */
4335   set_multilib_dir ();
4336
4337   /* Warn about any switches that no pass was interested in.  */
4338
4339   for (i = 0; i < n_switches; i++)
4340     if (! switches[i].valid)
4341       error ("unrecognized option `-%s'", switches[i].part1);
4342
4343   /* Obey some of the options.  */
4344
4345   if (print_search_dirs)
4346     {
4347       printf ("install: %s%s\n", standard_exec_prefix, machine_suffix);
4348       printf ("programs: %s\n", build_search_list (&exec_prefixes, "", 0));
4349       printf ("libraries: %s\n", build_search_list (&startfile_prefixes, "", 0));
4350       exit (0);
4351     }
4352
4353   if (print_file_name)
4354     {
4355       printf ("%s\n", find_file (print_file_name));
4356       exit (0);
4357     }
4358
4359   if (print_prog_name)
4360     {
4361       char *newname = find_a_file (&exec_prefixes, print_prog_name, X_OK);
4362       printf ("%s\n", (newname ? newname : print_prog_name));
4363       exit (0);
4364     }
4365
4366   if (print_multi_lib)
4367     {
4368       print_multilib_info ();
4369       exit (0);
4370     }
4371
4372   if (print_multi_directory)
4373     {
4374       if (multilib_dir == NULL)
4375         printf (".\n");
4376       else
4377         printf ("%s\n", multilib_dir);
4378       exit (0);
4379     }
4380
4381   if (verbose_flag)
4382     {
4383       if (! strcmp (version_string, compiler_version))
4384         fprintf (stderr, "gcc version %s\n", version_string);
4385       else
4386         fprintf (stderr, "gcc driver version %s executing gcc version %s\n",
4387                  version_string, compiler_version);
4388
4389       if (n_infiles == 0)
4390         exit (0);
4391     }
4392
4393   if (n_infiles == 0)
4394     fatal ("No input files");
4395
4396   /* Make a place to record the compiler output file names
4397      that correspond to the input files.  */
4398
4399   outfiles = (char **) xmalloc (n_infiles * sizeof (char *));
4400   bzero ((char *) outfiles, n_infiles * sizeof (char *));
4401
4402   /* Record which files were specified explicitly as link input.  */
4403
4404   explicit_link_files = xmalloc (n_infiles);
4405   bzero (explicit_link_files, n_infiles);
4406
4407   for (i = 0; i < n_infiles; i++)
4408     {
4409       register struct compiler *cp = 0;
4410       int this_file_error = 0;
4411
4412       /* Tell do_spec what to substitute for %i.  */
4413
4414       input_filename = infiles[i].name;
4415       input_filename_length = strlen (input_filename);
4416       input_file_number = i;
4417
4418       /* Use the same thing in %o, unless cp->spec says otherwise.  */
4419
4420       outfiles[i] = input_filename;
4421
4422       /* Figure out which compiler from the file's suffix.  */
4423
4424       cp = lookup_compiler (infiles[i].name, input_filename_length,
4425                             infiles[i].language);
4426
4427       if (cp)
4428         {
4429           /* Ok, we found an applicable compiler.  Run its spec.  */
4430           /* First say how much of input_filename to substitute for %b  */
4431           register char *p;
4432           int len;
4433
4434           input_basename = input_filename;
4435           for (p = input_filename; *p; p++)
4436             if (*p == '/' || *p == DIR_SEPARATOR)
4437               input_basename = p + 1;
4438
4439           /* Find a suffix starting with the last period,
4440              and set basename_length to exclude that suffix.  */
4441           basename_length = strlen (input_basename);
4442           p = input_basename + basename_length;
4443           while (p != input_basename && *p != '.') --p;
4444           if (*p == '.' && p != input_basename)
4445             {
4446               basename_length = p - input_basename;
4447               input_suffix = p + 1;
4448             }
4449           else
4450             input_suffix = "";
4451
4452           len = 0;
4453           for (j = 0; j < sizeof cp->spec / sizeof cp->spec[0]; j++)
4454             if (cp->spec[j])
4455               len += strlen (cp->spec[j]);
4456
4457           p = (char *) xmalloc (len + 1);
4458
4459           len = 0;
4460           for (j = 0; j < sizeof cp->spec / sizeof cp->spec[0]; j++)
4461             if (cp->spec[j])
4462               {
4463                 strcpy (p + len, cp->spec[j]);
4464                 len += strlen (cp->spec[j]);
4465               }
4466
4467           value = do_spec (p);
4468           free (p);
4469           if (value < 0)
4470             this_file_error = 1;
4471         }
4472
4473       /* If this file's name does not contain a recognized suffix,
4474          record it as explicit linker input.  */
4475
4476       else
4477         explicit_link_files[i] = 1;
4478
4479       /* Clear the delete-on-failure queue, deleting the files in it
4480          if this compilation failed.  */
4481
4482       if (this_file_error)
4483         {
4484           delete_failure_queue ();
4485           error_count++;
4486         }
4487       /* If this compilation succeeded, don't delete those files later.  */
4488       clear_failure_queue ();
4489     }
4490
4491   /* Run ld to link all the compiler output files.  */
4492
4493   if (error_count == 0)
4494     {
4495       int tmp = execution_count;
4496       int i;
4497       int first_time;
4498
4499       /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
4500          for collect.  */
4501       putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH=");
4502       putenv_from_prefixes (&startfile_prefixes, "LIBRARY_PATH=");
4503
4504       /* Build COLLECT_GCC_OPTIONS to have all of the options specified to
4505          the compiler.  */
4506       obstack_grow (&collect_obstack, "COLLECT_GCC_OPTIONS=",
4507                     sizeof ("COLLECT_GCC_OPTIONS=")-1);
4508
4509       first_time = TRUE;
4510       for (i = 0; i < n_switches; i++)
4511         {
4512           char **args;
4513           if (!first_time)
4514             obstack_grow (&collect_obstack, " ", 1);
4515
4516           first_time = FALSE;
4517           obstack_grow (&collect_obstack, "-", 1);
4518           obstack_grow (&collect_obstack, switches[i].part1,
4519                         strlen (switches[i].part1));
4520
4521           for (args = switches[i].args; args && *args; args++)
4522             {
4523               obstack_grow (&collect_obstack, " ", 1);
4524               obstack_grow (&collect_obstack, *args, strlen (*args));
4525             }
4526         }
4527       obstack_grow (&collect_obstack, "\0", 1);
4528       putenv (obstack_finish (&collect_obstack));
4529
4530       value = do_spec (link_command_spec);
4531       if (value < 0)
4532         error_count = 1;
4533       linker_was_run = (tmp != execution_count);
4534     }
4535
4536   /* Warn if a -B option was specified but the prefix was never used.  */
4537   unused_prefix_warnings (&exec_prefixes);
4538   unused_prefix_warnings (&startfile_prefixes);
4539
4540   /* If options said don't run linker,
4541      complain about input files to be given to the linker.  */
4542
4543   if (! linker_was_run && error_count == 0)
4544     for (i = 0; i < n_infiles; i++)
4545       if (explicit_link_files[i])
4546         error ("%s: linker input file unused since linking not done",
4547                outfiles[i]);
4548
4549   /* Delete some or all of the temporary files we made.  */
4550
4551   if (error_count)
4552     delete_failure_queue ();
4553   delete_temp_files ();
4554
4555   exit (error_count > 0 ? (signal_count ? 2 : 1) : 0);
4556   /* NOTREACHED */
4557   return 0;
4558 }
4559
4560 /* Find the proper compilation spec for the file name NAME,
4561    whose length is LENGTH.  LANGUAGE is the specified language,
4562    or 0 if none specified.  */
4563
4564 static struct compiler *
4565 lookup_compiler (name, length, language)
4566      char *name;
4567      int length;
4568      char *language;
4569 {
4570   struct compiler *cp;
4571
4572   /* Look for the language, if one is spec'd.  */
4573   if (language != 0)
4574     {
4575       for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
4576         {
4577           if (language != 0)
4578             {
4579               if (cp->suffix[0] == '@'
4580                   && !strcmp (cp->suffix + 1, language))
4581                 return cp;
4582             }
4583         }
4584       error ("language %s not recognized", language);
4585     }
4586
4587   /* Look for a suffix.  */
4588   for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
4589     {
4590       if (/* The suffix `-' matches only the file name `-'.  */
4591           (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
4592           ||
4593           (strlen (cp->suffix) < length
4594            /* See if the suffix matches the end of NAME.  */
4595 #ifdef OS2
4596            && (!strcmp (cp->suffix,
4597                         name + length - strlen (cp->suffix))
4598             || !strpbrk (cp->suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
4599              && !strcasecmp (cp->suffix,
4600                           name + length - strlen (cp->suffix)))))
4601 #else
4602            && !strcmp (cp->suffix,
4603                        name + length - strlen (cp->suffix))))
4604 #endif
4605         {
4606           if (cp->spec[0][0] == '@')
4607             {
4608               struct compiler *new;
4609               /* An alias entry maps a suffix to a language.
4610                  Search for the language; pass 0 for NAME and LENGTH
4611                  to avoid infinite recursion if language not found.
4612                  Construct the new compiler spec.  */
4613               language = cp->spec[0] + 1;
4614               new = (struct compiler *) xmalloc (sizeof (struct compiler));
4615               new->suffix = cp->suffix;
4616               bcopy ((char *) lookup_compiler (NULL_PTR, 0, language)->spec,
4617                      (char *) new->spec, sizeof new->spec);
4618               return new;
4619             }
4620           /* A non-alias entry: return it.  */
4621           return cp;
4622         }
4623     }
4624
4625   return 0;
4626 }
4627 \f
4628 char *
4629 xmalloc (size)
4630      unsigned size;
4631 {
4632   register char *value = (char *) malloc (size);
4633   if (value == 0)
4634     fatal ("virtual memory exhausted");
4635   return value;
4636 }
4637
4638 char *
4639 xrealloc (ptr, size)
4640      char *ptr;
4641      unsigned size;
4642 {
4643   register char *value = (char *) realloc (ptr, size);
4644   if (value == 0)
4645     fatal ("virtual memory exhausted");
4646   return value;
4647 }
4648
4649 /* This function is based on the one in libiberty.  */
4650
4651 static char *
4652 concat VPROTO((char *first, ...))
4653 {
4654   register int length;
4655   register char *newstr;
4656   register char *end;
4657   register char *arg;
4658   va_list args;
4659 #ifndef __STDC__
4660   char *first;
4661 #endif
4662
4663   /* First compute the size of the result and get sufficient memory. */
4664
4665   VA_START (args, first);
4666 #ifndef __STDC__
4667   first = va_arg (args, char *);
4668 #endif
4669
4670   arg = first;
4671   length = 0;
4672
4673   while (arg != 0)
4674     {
4675       length += strlen (arg);
4676       arg = va_arg (args, char *);
4677     }
4678
4679   newstr = (char *) xmalloc (length + 1);
4680   va_end (args);
4681
4682   /* Now copy the individual pieces to the result string. */
4683
4684   VA_START (args, first);
4685 #ifndef __STDC__
4686   first = va_arg (args, char *);
4687 #endif
4688
4689   end = newstr;
4690   arg = first;
4691   while (arg != 0)
4692     {
4693       while (*arg)
4694         *end++ = *arg++;
4695       arg = va_arg (args, char *);
4696     }
4697   *end = '\000';
4698   va_end (args);
4699
4700   return (newstr);
4701 }
4702
4703 static char *
4704 save_string (s, len)
4705      char *s;
4706      int len;
4707 {
4708   register char *result = xmalloc (len + 1);
4709
4710   bcopy (s, result, len);
4711   result[len] = 0;
4712   return result;
4713 }
4714
4715 static void
4716 pfatal_with_name (name)
4717      char *name;
4718 {
4719   fatal ("%s: %s", name, my_strerror (errno));
4720 }
4721
4722 static void
4723 perror_with_name (name)
4724      char *name;
4725 {
4726   error ("%s: %s", name, my_strerror (errno));
4727 }
4728
4729 static void
4730 perror_exec (name)
4731      char *name;
4732 {
4733   error ("installation problem, cannot exec `%s': %s",
4734          name, my_strerror (errno));
4735 }
4736
4737 /* More 'friendly' abort that prints the line and file.
4738    config.h can #define abort fancy_abort if you like that sort of thing.  */
4739
4740 void
4741 fancy_abort ()
4742 {
4743   fatal ("Internal gcc abort.");
4744 }
4745 \f
4746 #ifdef HAVE_VPRINTF
4747
4748 /* Output an error message and exit */
4749
4750 static void
4751 fatal VPROTO((char *format, ...))
4752 {
4753 #ifndef __STDC__
4754   char *format;
4755 #endif
4756   va_list ap;
4757
4758   VA_START (ap, format);
4759
4760 #ifndef __STDC__
4761   format = va_arg (ap, char*);
4762 #endif
4763
4764   fprintf (stderr, "%s: ", programname);
4765   vfprintf (stderr, format, ap);
4766   va_end (ap);
4767   fprintf (stderr, "\n");
4768   delete_temp_files ();
4769   exit (1);
4770 }
4771
4772 static void
4773 error VPROTO((char *format, ...))
4774 {
4775 #ifndef __STDC__
4776   char *format;
4777 #endif
4778   va_list ap;
4779
4780   VA_START (ap, format);
4781
4782 #ifndef __STDC__
4783   format = va_arg (ap, char*);
4784 #endif
4785
4786   fprintf (stderr, "%s: ", programname);
4787   vfprintf (stderr, format, ap);
4788   va_end (ap);
4789
4790   fprintf (stderr, "\n");
4791 }
4792
4793 #else /* not HAVE_VPRINTF */
4794
4795 static void
4796 fatal (msg, arg1, arg2)
4797      char *msg, *arg1, *arg2;
4798 {
4799   error (msg, arg1, arg2);
4800   delete_temp_files ();
4801   exit (1);
4802 }
4803
4804 static void
4805 error (msg, arg1, arg2)
4806      char *msg, *arg1, *arg2;
4807 {
4808   fprintf (stderr, "%s: ", programname);
4809   fprintf (stderr, msg, arg1, arg2);
4810   fprintf (stderr, "\n");
4811 }
4812
4813 #endif /* not HAVE_VPRINTF */
4814
4815 \f
4816 static void
4817 validate_all_switches ()
4818 {
4819   struct compiler *comp;
4820   register char *p;
4821   register char c;
4822   struct spec_list *spec;
4823
4824   for (comp = compilers; comp->spec[0]; comp++)
4825     {
4826       int i;
4827       for (i = 0; i < sizeof comp->spec / sizeof comp->spec[0] && comp->spec[i]; i++)
4828         {
4829           p = comp->spec[i];
4830           while (c = *p++)
4831             if (c == '%' && *p == '{')
4832               /* We have a switch spec.  */
4833               validate_switches (p + 1);
4834         }
4835     }
4836
4837   /* look through the linked list of extra specs read from the specs file */
4838   for (spec = specs; spec ; spec = spec->next)
4839     {
4840       p = spec->spec;
4841       while (c = *p++)
4842         if (c == '%' && *p == '{')
4843           /* We have a switch spec.  */
4844           validate_switches (p + 1);
4845     }
4846
4847   p = link_command_spec;
4848   while (c = *p++)
4849     if (c == '%' && *p == '{')
4850       /* We have a switch spec.  */
4851       validate_switches (p + 1);
4852
4853   /* Now notice switches mentioned in the machine-specific specs.  */
4854
4855   p = asm_spec;
4856   while (c = *p++)
4857     if (c == '%' && *p == '{')
4858       /* We have a switch spec.  */
4859       validate_switches (p + 1);
4860
4861   p = asm_final_spec;
4862   while (c = *p++)
4863     if (c == '%' && *p == '{')
4864       /* We have a switch spec.  */
4865       validate_switches (p + 1);
4866
4867   p = cpp_spec;
4868   while (c = *p++)
4869     if (c == '%' && *p == '{')
4870       /* We have a switch spec.  */
4871       validate_switches (p + 1);
4872
4873   p = signed_char_spec;
4874   while (c = *p++)
4875     if (c == '%' && *p == '{')
4876       /* We have a switch spec.  */
4877       validate_switches (p + 1);
4878
4879   p = cc1_spec;
4880   while (c = *p++)
4881     if (c == '%' && *p == '{')
4882       /* We have a switch spec.  */
4883       validate_switches (p + 1);
4884
4885   p = cc1plus_spec;
4886   while (c = *p++)
4887     if (c == '%' && *p == '{')
4888       /* We have a switch spec.  */
4889       validate_switches (p + 1);
4890
4891   p = link_spec;
4892   while (c = *p++)
4893     if (c == '%' && *p == '{')
4894       /* We have a switch spec.  */
4895       validate_switches (p + 1);
4896
4897   p = lib_spec;
4898   while (c = *p++)
4899     if (c == '%' && *p == '{')
4900       /* We have a switch spec.  */
4901       validate_switches (p + 1);
4902
4903   p = libgcc_spec;
4904   while (c = *p++)
4905     if (c == '%' && *p == '{')
4906       /* We have a switch spec.  */
4907       validate_switches (p + 1);
4908
4909   p = startfile_spec;
4910   while (c = *p++)
4911     if (c == '%' && *p == '{')
4912       /* We have a switch spec.  */
4913       validate_switches (p + 1);
4914
4915 #ifdef EXTRA_SPECS
4916   {
4917     int i;
4918     for (i = 0; i < sizeof (extra_specs) / sizeof (extra_specs[0]); i++)
4919       {
4920         p = extra_specs[i].spec;
4921         while (c = *p++)
4922           if (c == '%' && *p == '{')
4923             /* We have a switch spec.  */
4924             validate_switches (p + 1);
4925       }
4926   }
4927 #endif
4928
4929 }
4930
4931 /* Look at the switch-name that comes after START
4932    and mark as valid all supplied switches that match it.  */
4933
4934 static void
4935 validate_switches (start)
4936      char *start;
4937 {
4938   register char *p = start;
4939   char *filter;
4940   register int i;
4941   int suffix = 0;
4942
4943   if (*p == '|')
4944     ++p;
4945
4946   if (*p == '!')
4947     ++p;
4948
4949   if (*p == '.')
4950     suffix = 1, ++p;
4951
4952   filter = p;
4953   while (*p != ':' && *p != '}') p++;
4954
4955   if (suffix)
4956     ;
4957   else if (p[-1] == '*')
4958     {
4959       /* Mark all matching switches as valid.  */
4960       --p;
4961       for (i = 0; i < n_switches; i++)
4962         if (!strncmp (switches[i].part1, filter, p - filter))
4963           switches[i].valid = 1;
4964     }
4965   else
4966     {
4967       /* Mark an exact matching switch as valid.  */
4968       for (i = 0; i < n_switches; i++)
4969         {
4970           if (!strncmp (switches[i].part1, filter, p - filter)
4971               && switches[i].part1[p - filter] == 0)
4972             switches[i].valid = 1;
4973         }
4974     }
4975 }
4976 \f
4977 /* Check whether a particular argument was used.  */
4978
4979 static int
4980 used_arg (p, len)
4981      char *p;
4982      int len;
4983 {
4984   int i;
4985
4986   for (i = 0; i < n_switches; i++)
4987     if (! strncmp (switches[i].part1, p, len)
4988         && strlen (switches[i].part1) == len)
4989       return 1;
4990   return 0;
4991 }
4992
4993 /* Check whether a particular argument is a default argument.  */
4994
4995 #ifndef MULTILIB_DEFAULTS
4996 #define MULTILIB_DEFAULTS { NULL }
4997 #endif
4998
4999 static char *multilib_defaults[] = MULTILIB_DEFAULTS;
5000
5001 static int
5002 default_arg (p, len)
5003      char *p;
5004      int len;
5005 {
5006   int count = sizeof multilib_defaults / sizeof multilib_defaults[0];
5007   int i;
5008
5009   for (i = 0; i < count; i++)
5010     if (multilib_defaults[i] != NULL
5011         && strncmp (multilib_defaults[i], p, len) == 0
5012         && multilib_defaults[i][len] == '\0')
5013       return 1;
5014
5015   return 0;
5016 }
5017
5018 /* Work out the subdirectory to use based on the
5019    options.  The format of multilib_select is a list of elements.
5020    Each element is a subdirectory name followed by a list of options
5021    followed by a semicolon.  gcc will consider each line in turn.  If
5022    none of the options beginning with an exclamation point are
5023    present, and all of the other options are present, that
5024    subdirectory will be used.  */
5025
5026 static void
5027 set_multilib_dir ()
5028 {
5029   char *p = multilib_select;
5030   int this_path_len;
5031   char *this_path, *this_arg;
5032   int not_arg;
5033   int ok;
5034
5035   while (*p != '\0')
5036     {
5037       /* Ignore newlines.  */
5038       if (*p == '\n')
5039         {
5040           ++p;
5041           continue;
5042         }
5043
5044       /* Get the initial path.  */
5045       this_path = p;
5046       while (*p != ' ')
5047         {
5048           if (*p == '\0')
5049             abort ();
5050           ++p;
5051         }
5052       this_path_len = p - this_path;
5053
5054       /* Check the arguments.  */
5055       ok = 1;
5056       ++p;
5057       while (*p != ';')
5058         {
5059           if (*p == '\0')
5060             abort ();
5061
5062           if (! ok)
5063             {
5064               ++p;
5065               continue;
5066             }
5067
5068           this_arg = p;
5069           while (*p != ' ' && *p != ';')
5070             {
5071               if (*p == '\0')
5072                 abort ();
5073               ++p;
5074             }
5075
5076           if (*this_arg != '!')
5077             not_arg = 0;
5078           else
5079             {
5080               not_arg = 1;
5081               ++this_arg;
5082             }
5083
5084           /* If this is a default argument, we can just ignore it.
5085              This is true even if this_arg begins with '!'.  Beginning
5086              with '!' does not mean that this argument is necessarily
5087              inappropriate for this library: it merely means that
5088              there is a more specific library which uses this
5089              argument.  If this argument is a default, we need not
5090              consider that more specific library.  */
5091           if (! default_arg (this_arg, p - this_arg))
5092             {
5093               ok = used_arg (this_arg, p - this_arg);
5094               if (not_arg)
5095                 ok = ! ok;
5096             }
5097
5098           if (*p == ' ')
5099             ++p;
5100         }
5101
5102       if (ok)
5103         {
5104           if (this_path_len != 1
5105               || this_path[0] != '.')
5106             {
5107               multilib_dir = xmalloc (this_path_len + 1);
5108               strncpy (multilib_dir, this_path, this_path_len);
5109               multilib_dir[this_path_len] = '\0';
5110             }
5111           break;
5112         }
5113
5114       ++p;
5115     }      
5116 }
5117
5118 /* Print out the multiple library subdirectory selection
5119    information.  This prints out a series of lines.  Each line looks
5120    like SUBDIRECTORY;@OPTION@OPTION, with as many options as is
5121    required.  Only the desired options are printed out, the negative
5122    matches.  The options are print without a leading dash.  There are
5123    no spaces to make it easy to use the information in the shell.
5124    Each subdirectory is printed only once.  This assumes the ordering
5125    generated by the genmultilib script.  */
5126
5127 static void
5128 print_multilib_info ()
5129 {
5130   char *p = multilib_select;
5131   char *last_path = 0, *this_path;
5132   int skip;
5133   int last_path_len = 0;
5134
5135   while (*p != '\0')
5136     {
5137       /* Ignore newlines.  */
5138       if (*p == '\n')
5139         {
5140           ++p;
5141           continue;
5142         }
5143
5144       /* Get the initial path.  */
5145       this_path = p;
5146       while (*p != ' ')
5147         {
5148           if (*p == '\0')
5149             abort ();
5150           ++p;
5151         }
5152
5153       /* If this is a duplicate, skip it.  */
5154       skip = (last_path != 0 && p - this_path == last_path_len
5155               && ! strncmp (last_path, this_path, last_path_len));
5156
5157       last_path = this_path;
5158       last_path_len = p - this_path;
5159
5160       /* If this directory requires any default arguments, we can skip
5161          it.  We will already have printed a directory identical to
5162          this one which does not require that default argument.  */
5163       if (! skip)
5164         {
5165           char *q;
5166
5167           q = p + 1;
5168           while (*q != ';')
5169             {
5170               char *arg;
5171
5172               if (*q == '\0')
5173                 abort ();
5174
5175               if (*q == '!')
5176                 arg = NULL;
5177               else
5178                 arg = q;
5179
5180               while (*q != ' ' && *q != ';')
5181                 {
5182                   if (*q == '\0')
5183                     abort ();
5184                   ++q;
5185                 }
5186
5187               if (arg != NULL
5188                   && default_arg (arg, q - arg))
5189                 {
5190                   skip = 1;
5191                   break;
5192                 }
5193
5194               if (*q == ' ')
5195                 ++q;
5196             }
5197         }
5198
5199       if (! skip)
5200         {
5201           char *p1;
5202
5203           for (p1 = last_path; p1 < p; p1++)
5204             putchar (*p1);
5205           putchar (';');
5206         }
5207
5208       ++p;
5209       while (*p != ';')
5210         {
5211           int use_arg;
5212
5213           if (*p == '\0')
5214             abort ();
5215
5216           if (skip)
5217             {
5218               ++p;
5219               continue;
5220             }
5221
5222           use_arg = *p != '!';
5223
5224           if (use_arg)
5225             putchar ('@');
5226
5227           while (*p != ' ' && *p != ';')
5228             {
5229               if (*p == '\0')
5230                 abort ();
5231               if (use_arg)
5232                 putchar (*p);
5233               ++p;
5234             }
5235
5236           if (*p == ' ')
5237             ++p;
5238         }
5239
5240       if (! skip)
5241         putchar ('\n');
5242
5243       ++p;
5244     }
5245 }