OSDN Git Service

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