OSDN Git Service

Speed up genmultilib; Add MULTIB_EXTRA_OPTS
[pf3gnuchains/gcc-fork.git] / gcc / gcc.c
1 /* Compiler driver program that can handle many languages.
2    Copyright (C) 1987, 89, 92, 93, 94, 95, 1996 Free Software Foundation, Inc.
3
4 This file is part of GNU CC.
5
6 GNU CC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU CC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU CC; see the file COPYING.  If not, write to
18 the Free Software Foundation, 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA.
20
21 This paragraph is here to try to keep Sun CC from dying.
22 The number of chars here seems crucial!!!!  */
23
24 /* This program is the user interface to the C compiler and possibly to
25 other compilers.  It is used because compilation is a complicated procedure
26 which involves running several programs and passing temporary files between
27 them, forwarding the users switches to those programs selectively,
28 and deleting the temporary files at the end.
29
30 CC recognizes how to compile each input file by suffixes in the file names.
31 Once it knows which kind of compilation to perform, the procedure for
32 compilation is specified by a string called a "spec".  */
33 \f
34 #include <sys/types.h>
35 #include <ctype.h>
36 #include <signal.h>
37 #include <sys/stat.h>
38 #include <errno.h>
39
40 #ifndef _WIN32
41 #include <sys/file.h>   /* May get R_OK, etc. on some systems.  */
42 #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 #ifdef EXTRA_SPECS
1242   else
1243     {
1244       int i;
1245       for (i = 0; i < sizeof (extra_specs) / sizeof (extra_specs[0]); i++)
1246         {
1247           if (! strcmp (name, extra_specs[i].name))
1248             {
1249               extra_specs[i].spec = sl->spec;
1250               break;
1251             }
1252         }
1253     }
1254 #endif
1255
1256   /* Free the old spec */
1257   if (old_spec)
1258     free (old_spec);
1259 }
1260 \f
1261 /* Accumulate a command (program name and args), and run it.  */
1262
1263 /* Vector of pointers to arguments in the current line of specifications.  */
1264
1265 static char **argbuf;
1266
1267 /* Number of elements allocated in argbuf.  */
1268
1269 static int argbuf_length;
1270
1271 /* Number of elements in argbuf currently in use (containing args).  */
1272
1273 static int argbuf_index;
1274
1275 /* This is the list of suffixes and codes (%g/%u/%U) and the associated
1276    temp file.  Used only if MKTEMP_EACH_FILE.  */
1277
1278 static struct temp_name {
1279   char *suffix;         /* suffix associated with the code.  */
1280   int length;           /* strlen (suffix).  */
1281   int unique;           /* Indicates whether %g or %u/%U was used.  */
1282   char *filename;       /* associated filename.  */
1283   int filename_length;  /* strlen (filename).  */
1284   struct temp_name *next;
1285 } *temp_names;
1286
1287 /* Number of commands executed so far.  */
1288
1289 static int execution_count;
1290
1291 /* Number of commands that exited with a signal.  */
1292
1293 static int signal_count;
1294
1295 /* Name with which this program was invoked.  */
1296
1297 static char *programname;
1298 \f
1299 /* Structures to keep track of prefixes to try when looking for files.  */
1300
1301 struct prefix_list
1302 {
1303   char *prefix;               /* String to prepend to the path.  */
1304   struct prefix_list *next;   /* Next in linked list.  */
1305   int require_machine_suffix; /* Don't use without machine_suffix.  */
1306   /* 2 means try both machine_suffix and just_machine_suffix.  */
1307   int *used_flag_ptr;         /* 1 if a file was found with this prefix.  */
1308 };
1309
1310 struct path_prefix
1311 {
1312   struct prefix_list *plist;  /* List of prefixes to try */
1313   int max_len;                /* Max length of a prefix in PLIST */
1314   char *name;                 /* Name of this list (used in config stuff) */
1315 };
1316
1317 /* List of prefixes to try when looking for executables.  */
1318
1319 static struct path_prefix exec_prefixes = { 0, 0, "exec" };
1320
1321 /* List of prefixes to try when looking for startup (crt0) files.  */
1322
1323 static struct path_prefix startfile_prefixes = { 0, 0, "startfile" };
1324
1325 /* List of prefixes to try when looking for include files.  */
1326
1327 static struct path_prefix include_prefixes = { 0, 0, "include" };
1328
1329 /* Suffix to attach to directories searched for commands.
1330    This looks like `MACHINE/VERSION/'.  */
1331
1332 static char *machine_suffix = 0;
1333
1334 /* Suffix to attach to directories searched for commands.
1335    This is just `MACHINE/'.  */
1336
1337 static char *just_machine_suffix = 0;
1338
1339 /* Adjusted value of GCC_EXEC_PREFIX envvar.  */
1340
1341 static char *gcc_exec_prefix;
1342
1343 /* Default prefixes to attach to command names.  */
1344
1345 #ifdef CROSS_COMPILE  /* Don't use these prefixes for a cross compiler.  */
1346 #undef MD_EXEC_PREFIX
1347 #undef MD_STARTFILE_PREFIX
1348 #undef MD_STARTFILE_PREFIX_1
1349 #endif
1350
1351 #ifndef STANDARD_EXEC_PREFIX
1352 #define STANDARD_EXEC_PREFIX "/usr/local/lib/gcc-lib/"
1353 #endif /* !defined STANDARD_EXEC_PREFIX */
1354
1355 static char *standard_exec_prefix = STANDARD_EXEC_PREFIX;
1356 static char *standard_exec_prefix_1 = "/usr/lib/gcc/";
1357 #ifdef MD_EXEC_PREFIX
1358 static char *md_exec_prefix = MD_EXEC_PREFIX;
1359 #endif
1360
1361 #ifndef STANDARD_STARTFILE_PREFIX
1362 #define STANDARD_STARTFILE_PREFIX "/usr/local/lib/"
1363 #endif /* !defined STANDARD_STARTFILE_PREFIX */
1364
1365 #ifdef MD_STARTFILE_PREFIX
1366 static char *md_startfile_prefix = MD_STARTFILE_PREFIX;
1367 #endif
1368 #ifdef MD_STARTFILE_PREFIX_1
1369 static char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
1370 #endif
1371 static char *standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
1372 static char *standard_startfile_prefix_1 = "/lib/";
1373 static char *standard_startfile_prefix_2 = "/usr/lib/";
1374
1375 #ifndef TOOLDIR_BASE_PREFIX
1376 #define TOOLDIR_BASE_PREFIX "/usr/local/"
1377 #endif
1378 static char *tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
1379 static char *tooldir_prefix;
1380
1381 /* Subdirectory to use for locating libraries.  Set by
1382    set_multilib_dir based on the compilation options.  */
1383
1384 static char *multilib_dir;
1385
1386 /* Clear out the vector of arguments (after a command is executed).  */
1387
1388 static void
1389 clear_args ()
1390 {
1391   argbuf_index = 0;
1392 }
1393
1394 /* Add one argument to the vector at the end.
1395    This is done when a space is seen or at the end of the line.
1396    If DELETE_ALWAYS is nonzero, the arg is a filename
1397     and the file should be deleted eventually.
1398    If DELETE_FAILURE is nonzero, the arg is a filename
1399     and the file should be deleted if this compilation fails.  */
1400
1401 static void
1402 store_arg (arg, delete_always, delete_failure)
1403      char *arg;
1404      int delete_always, delete_failure;
1405 {
1406   if (argbuf_index + 1 == argbuf_length)
1407     {
1408       argbuf = (char **) xrealloc (argbuf, (argbuf_length *= 2) * sizeof (char *));
1409     }
1410
1411   argbuf[argbuf_index++] = arg;
1412   argbuf[argbuf_index] = 0;
1413
1414   if (delete_always || delete_failure)
1415     record_temp_file (arg, delete_always, delete_failure);
1416 }
1417 \f
1418 /* Record the names of temporary files we tell compilers to write,
1419    and delete them at the end of the run.  */
1420
1421 /* This is the common prefix we use to make temp file names.
1422    It is chosen once for each run of this program.
1423    It is substituted into a spec by %g.
1424    Thus, all temp file names contain this prefix.
1425    In practice, all temp file names start with this prefix.
1426
1427    This prefix comes from the envvar TMPDIR if it is defined;
1428    otherwise, from the P_tmpdir macro if that is defined;
1429    otherwise, in /usr/tmp or /tmp;
1430    or finally the current directory if all else fails.  */
1431
1432 static char *temp_filename;
1433
1434 /* Length of the prefix.  */
1435
1436 static int temp_filename_length;
1437
1438 /* Define the list of temporary files to delete.  */
1439
1440 struct temp_file
1441 {
1442   char *name;
1443   struct temp_file *next;
1444 };
1445
1446 /* Queue of files to delete on success or failure of compilation.  */
1447 static struct temp_file *always_delete_queue;
1448 /* Queue of files to delete on failure of compilation.  */
1449 static struct temp_file *failure_delete_queue;
1450
1451 /* Record FILENAME as a file to be deleted automatically.
1452    ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
1453    otherwise delete it in any case.
1454    FAIL_DELETE nonzero means delete it if a compilation step fails;
1455    otherwise delete it in any case.  */
1456
1457 static void
1458 record_temp_file (filename, always_delete, fail_delete)
1459      char *filename;
1460      int always_delete;
1461      int fail_delete;
1462 {
1463   register char *name;
1464   name = xmalloc (strlen (filename) + 1);
1465   strcpy (name, filename);
1466
1467   if (always_delete)
1468     {
1469       register struct temp_file *temp;
1470       for (temp = always_delete_queue; temp; temp = temp->next)
1471         if (! strcmp (name, temp->name))
1472           goto already1;
1473       temp = (struct temp_file *) xmalloc (sizeof (struct temp_file));
1474       temp->next = always_delete_queue;
1475       temp->name = name;
1476       always_delete_queue = temp;
1477     already1:;
1478     }
1479
1480   if (fail_delete)
1481     {
1482       register struct temp_file *temp;
1483       for (temp = failure_delete_queue; temp; temp = temp->next)
1484         if (! strcmp (name, temp->name))
1485           goto already2;
1486       temp = (struct temp_file *) xmalloc (sizeof (struct temp_file));
1487       temp->next = failure_delete_queue;
1488       temp->name = name;
1489       failure_delete_queue = temp;
1490     already2:;
1491     }
1492 }
1493
1494 /* Delete all the temporary files whose names we previously recorded.  */
1495
1496 static void
1497 delete_if_ordinary (name)
1498      char *name;
1499 {
1500   struct stat st;
1501 #ifdef DEBUG
1502   int i, c;
1503
1504   printf ("Delete %s? (y or n) ", name);
1505   fflush (stdout);
1506   i = getchar ();
1507   if (i != '\n')
1508     while ((c = getchar ()) != '\n' && c != EOF) ;
1509   if (i == 'y' || i == 'Y')
1510 #endif /* DEBUG */
1511     if (stat (name, &st) >= 0 && S_ISREG (st.st_mode))
1512       if (unlink (name) < 0)
1513         if (verbose_flag)
1514           perror_with_name (name);
1515 }
1516
1517 static void
1518 delete_temp_files ()
1519 {
1520   register struct temp_file *temp;
1521
1522   for (temp = always_delete_queue; temp; temp = temp->next)
1523     delete_if_ordinary (temp->name);
1524   always_delete_queue = 0;
1525 }
1526
1527 /* Delete all the files to be deleted on error.  */
1528
1529 static void
1530 delete_failure_queue ()
1531 {
1532   register struct temp_file *temp;
1533
1534   for (temp = failure_delete_queue; temp; temp = temp->next)
1535     delete_if_ordinary (temp->name);
1536 }
1537
1538 static void
1539 clear_failure_queue ()
1540 {
1541   failure_delete_queue = 0;
1542 }
1543 \f
1544 /* Routine to add variables to the environment.  We do this to pass
1545    the pathname of the gcc driver, and the directories search to the
1546    collect2 program, which is being run as ld.  This way, we can be
1547    sure of executing the right compiler when collect2 wants to build
1548    constructors and destructors.  Since the environment variables we
1549    use come from an obstack, we don't have to worry about allocating
1550    space for them.  */
1551
1552 #ifndef HAVE_PUTENV
1553
1554 void
1555 putenv (str)
1556      char *str;
1557 {
1558 #ifndef VMS                     /* nor about VMS */
1559
1560   extern char **environ;
1561   char **old_environ = environ;
1562   char **envp;
1563   int num_envs = 0;
1564   int name_len = 1;
1565   int str_len = strlen (str);
1566   char *p = str;
1567   int ch;
1568
1569   while ((ch = *p++) != '\0' && ch != '=')
1570     name_len++;
1571
1572   if (!ch)
1573     abort ();
1574
1575   /* Search for replacing an existing environment variable, and
1576      count the number of total environment variables.  */
1577   for (envp = old_environ; *envp; envp++)
1578     {
1579       num_envs++;
1580       if (!strncmp (str, *envp, name_len))
1581         {
1582           *envp = str;
1583           return;
1584         }
1585     }
1586
1587   /* Add a new environment variable */
1588   environ = (char **) xmalloc (sizeof (char *) * (num_envs+2));
1589   *environ = str;
1590   bcopy ((char *) old_environ, (char *) (environ + 1),
1591          sizeof (char *) * (num_envs+1));
1592
1593 #endif  /* VMS */
1594 }
1595
1596 #endif  /* HAVE_PUTENV */
1597
1598 \f
1599 /* Build a list of search directories from PATHS.
1600    PREFIX is a string to prepend to the list.
1601    If CHECK_DIR_P is non-zero we ensure the directory exists.
1602    This is used mostly by putenv_from_prefixes so we use `collect_obstack'.
1603    It is also used by the --print-search-dirs flag.  */
1604
1605 static char *
1606 build_search_list (paths, prefix, check_dir_p)
1607      struct path_prefix *paths;
1608      char *prefix;
1609      int check_dir_p;
1610 {
1611   int suffix_len = (machine_suffix) ? strlen (machine_suffix) : 0;
1612   int just_suffix_len
1613     = (just_machine_suffix) ? strlen (just_machine_suffix) : 0;
1614   int first_time = TRUE;
1615   struct prefix_list *pprefix;
1616
1617   obstack_grow (&collect_obstack, prefix, strlen (prefix));
1618
1619   for (pprefix = paths->plist; pprefix != 0; pprefix = pprefix->next)
1620     {
1621       int len = strlen (pprefix->prefix);
1622
1623       if (machine_suffix
1624           && (!check_dir_p
1625               || is_directory (pprefix->prefix, machine_suffix, 0)))
1626         {
1627           if (!first_time)
1628             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1629             
1630           first_time = FALSE;
1631           obstack_grow (&collect_obstack, pprefix->prefix, len);
1632           obstack_grow (&collect_obstack, machine_suffix, suffix_len);
1633         }
1634
1635       if (just_machine_suffix
1636           && pprefix->require_machine_suffix == 2
1637           && (!check_dir_p
1638               || is_directory (pprefix->prefix, just_machine_suffix, 0)))
1639         {
1640           if (!first_time)
1641             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1642             
1643           first_time = FALSE;
1644           obstack_grow (&collect_obstack, pprefix->prefix, len);
1645           obstack_grow (&collect_obstack, just_machine_suffix,
1646                         just_suffix_len);
1647         }
1648
1649       if (!pprefix->require_machine_suffix)
1650         {
1651           if (!first_time)
1652             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1653
1654           first_time = FALSE;
1655           obstack_grow (&collect_obstack, pprefix->prefix, len);
1656         }
1657     }
1658   obstack_1grow (&collect_obstack, '\0');
1659   return obstack_finish (&collect_obstack);
1660 }
1661
1662 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
1663    for collect.  */
1664
1665 static void
1666 putenv_from_prefixes (paths, env_var)
1667      struct path_prefix *paths;
1668      char *env_var;
1669 {
1670   putenv (build_search_list (paths, env_var, 1));
1671 }
1672 \f
1673 /* Search for NAME using the prefix list PREFIXES.  MODE is passed to
1674    access to check permissions.
1675    Return 0 if not found, otherwise return its name, allocated with malloc.  */
1676
1677 static char *
1678 find_a_file (pprefix, name, mode)
1679      struct path_prefix *pprefix;
1680      char *name;
1681      int mode;
1682 {
1683   char *temp;
1684   char *file_suffix = ((mode & X_OK) != 0 ? EXECUTABLE_SUFFIX : "");
1685   struct prefix_list *pl;
1686   int len = pprefix->max_len + strlen (name) + strlen (file_suffix) + 1;
1687
1688   if (machine_suffix)
1689     len += strlen (machine_suffix);
1690
1691   temp = xmalloc (len);
1692
1693   /* Determine the filename to execute (special case for absolute paths).  */
1694
1695   if (*name == '/' || *name == DIR_SEPARATOR)
1696     {
1697       if (access (name, mode))
1698         {
1699           strcpy (temp, name);
1700           return temp;
1701         }
1702     }
1703   else
1704     for (pl = pprefix->plist; pl; pl = pl->next)
1705       {
1706         if (machine_suffix)
1707           {
1708             /* Some systems have a suffix for executable files.
1709                So try appending that first.  */
1710             if (file_suffix[0] != 0)
1711               {
1712                 strcpy (temp, pl->prefix);
1713                 strcat (temp, machine_suffix);
1714                 strcat (temp, name);
1715                 strcat (temp, file_suffix);
1716                 if (access (temp, mode) == 0)
1717                   {
1718                     if (pl->used_flag_ptr != 0)
1719                       *pl->used_flag_ptr = 1;
1720                     return temp;
1721                   }
1722               }
1723
1724             /* Now try just the name.  */
1725             strcpy (temp, pl->prefix);
1726             strcat (temp, machine_suffix);
1727             strcat (temp, name);
1728             if (access (temp, mode) == 0)
1729               {
1730                 if (pl->used_flag_ptr != 0)
1731                   *pl->used_flag_ptr = 1;
1732                 return temp;
1733               }
1734           }
1735
1736         /* Certain prefixes are tried with just the machine type,
1737            not the version.  This is used for finding as, ld, etc.  */
1738         if (just_machine_suffix && pl->require_machine_suffix == 2)
1739           {
1740             /* Some systems have a suffix for executable files.
1741                So try appending that first.  */
1742             if (file_suffix[0] != 0)
1743               {
1744                 strcpy (temp, pl->prefix);
1745                 strcat (temp, just_machine_suffix);
1746                 strcat (temp, name);
1747                 strcat (temp, file_suffix);
1748                 if (access (temp, mode) == 0)
1749                   {
1750                     if (pl->used_flag_ptr != 0)
1751                       *pl->used_flag_ptr = 1;
1752                     return temp;
1753                   }
1754               }
1755
1756             strcpy (temp, pl->prefix);
1757             strcat (temp, just_machine_suffix);
1758             strcat (temp, name);
1759             if (access (temp, mode) == 0)
1760               {
1761                 if (pl->used_flag_ptr != 0)
1762                   *pl->used_flag_ptr = 1;
1763                 return temp;
1764               }
1765           }
1766
1767         /* Certain prefixes can't be used without the machine suffix
1768            when the machine or version is explicitly specified.  */
1769         if (!pl->require_machine_suffix)
1770           {
1771             /* Some systems have a suffix for executable files.
1772                So try appending that first.  */
1773             if (file_suffix[0] != 0)
1774               {
1775                 strcpy (temp, pl->prefix);
1776                 strcat (temp, name);
1777                 strcat (temp, file_suffix);
1778                 if (access (temp, mode) == 0)
1779                   {
1780                     if (pl->used_flag_ptr != 0)
1781                       *pl->used_flag_ptr = 1;
1782                     return temp;
1783                   }
1784               }
1785
1786             strcpy (temp, pl->prefix);
1787             strcat (temp, name);
1788             if (access (temp, mode) == 0)
1789               {
1790                 if (pl->used_flag_ptr != 0)
1791                   *pl->used_flag_ptr = 1;
1792                 return temp;
1793               }
1794           }
1795       }
1796
1797   free (temp);
1798   return 0;
1799 }
1800
1801 /* Add an entry for PREFIX in PLIST.  If FIRST is set, it goes
1802    at the start of the list, otherwise it goes at the end.
1803
1804    If WARN is nonzero, we will warn if no file is found
1805    through this prefix.  WARN should point to an int
1806    which will be set to 1 if this entry is used.
1807
1808    REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
1809    the complete value of machine_suffix.
1810    2 means try both machine_suffix and just_machine_suffix.  */
1811
1812 static void
1813 add_prefix (pprefix, prefix, first, require_machine_suffix, warn)
1814      struct path_prefix *pprefix;
1815      char *prefix;
1816      int first;
1817      int require_machine_suffix;
1818      int *warn;
1819 {
1820   struct prefix_list *pl, **prev;
1821   int len;
1822
1823   if (!first && pprefix->plist)
1824     {
1825       for (pl = pprefix->plist; pl->next; pl = pl->next)
1826         ;
1827       prev = &pl->next;
1828     }
1829   else
1830     prev = &pprefix->plist;
1831
1832   /* Keep track of the longest prefix */
1833
1834   len = strlen (prefix);
1835   if (len > pprefix->max_len)
1836     pprefix->max_len = len;
1837
1838   pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
1839   pl->prefix = save_string (prefix, len);
1840   pl->require_machine_suffix = require_machine_suffix;
1841   pl->used_flag_ptr = warn;
1842   if (warn)
1843     *warn = 0;
1844
1845   if (*prev)
1846     pl->next = *prev;
1847   else
1848     pl->next = (struct prefix_list *) 0;
1849   *prev = pl;
1850 }
1851
1852 /* Print warnings for any prefixes in the list PPREFIX that were not used.  */
1853
1854 static void
1855 unused_prefix_warnings (pprefix)
1856      struct path_prefix *pprefix;
1857 {
1858   struct prefix_list *pl = pprefix->plist;
1859
1860   while (pl)
1861     {
1862       if (pl->used_flag_ptr != 0 && !*pl->used_flag_ptr)
1863         {
1864           if (pl->require_machine_suffix && machine_suffix)
1865             error ("file path prefix `%s%s' never used", pl->prefix,
1866                    machine_suffix);
1867           else
1868             error ("file path prefix `%s' never used", pl->prefix);
1869
1870           /* Prevent duplicate warnings.  */
1871           *pl->used_flag_ptr = 1;
1872         }
1873       pl = pl->next;
1874     }
1875 }
1876
1877 /* Get rid of all prefixes built up so far in *PLISTP.  */
1878
1879 static void
1880 free_path_prefix (pprefix)
1881      struct path_prefix *pprefix;
1882 {
1883   struct prefix_list *pl = pprefix->plist;
1884   struct prefix_list *temp;
1885
1886   while (pl)
1887     {
1888       temp = pl;
1889       pl = pl->next;
1890       free (temp->prefix);
1891       free ((char *) temp);
1892     }
1893   pprefix->plist = (struct prefix_list *) 0;
1894 }
1895 \f
1896 /* Execute the command specified by the arguments on the current line of spec.
1897    When using pipes, this includes several piped-together commands
1898    with `|' between them.
1899
1900    Return 0 if successful, -1 if failed.  */
1901
1902 static int
1903 execute ()
1904 {
1905   int i;
1906   int n_commands;               /* # of command.  */
1907   char *string;
1908   struct command
1909     {
1910       char *prog;               /* program name.  */
1911       char **argv;              /* vector of args.  */
1912       int pid;                  /* pid of process for this command.  */
1913     };
1914
1915   struct command *commands;     /* each command buffer with above info.  */
1916
1917   /* Count # of piped commands.  */
1918   for (n_commands = 1, i = 0; i < argbuf_index; i++)
1919     if (strcmp (argbuf[i], "|") == 0)
1920       n_commands++;
1921
1922   /* Get storage for each command.  */
1923   commands
1924     = (struct command *) alloca (n_commands * sizeof (struct command));
1925
1926   /* Split argbuf into its separate piped processes,
1927      and record info about each one.
1928      Also search for the programs that are to be run.  */
1929
1930   commands[0].prog = argbuf[0]; /* first command.  */
1931   commands[0].argv = &argbuf[0];
1932   string = find_a_file (&exec_prefixes, commands[0].prog, X_OK);
1933   if (string)
1934     commands[0].argv[0] = string;
1935
1936   for (n_commands = 1, i = 0; i < argbuf_index; i++)
1937     if (strcmp (argbuf[i], "|") == 0)
1938       {                         /* each command.  */
1939 #if defined (__MSDOS__) || defined (_WIN32) || defined (OS2)
1940         fatal ("-pipe not supported");
1941 #endif
1942         argbuf[i] = 0;  /* termination of command args.  */
1943         commands[n_commands].prog = argbuf[i + 1];
1944         commands[n_commands].argv = &argbuf[i + 1];
1945         string = find_a_file (&exec_prefixes, commands[n_commands].prog, X_OK);
1946         if (string)
1947           commands[n_commands].argv[0] = string;
1948         n_commands++;
1949       }
1950
1951   argbuf[argbuf_index] = 0;
1952
1953   /* If -v, print what we are about to do, and maybe query.  */
1954
1955   if (verbose_flag)
1956     {
1957       /* Print each piped command as a separate line.  */
1958       for (i = 0; i < n_commands ; i++)
1959         {
1960           char **j;
1961
1962           for (j = commands[i].argv; *j; j++)
1963             fprintf (stderr, " %s", *j);
1964
1965           /* Print a pipe symbol after all but the last command.  */
1966           if (i + 1 != n_commands)
1967             fprintf (stderr, " |");
1968           fprintf (stderr, "\n");
1969         }
1970       fflush (stderr);
1971 #ifdef DEBUG
1972       fprintf (stderr, "\nGo ahead? (y or n) ");
1973       fflush (stderr);
1974       i = getchar ();
1975       if (i != '\n')
1976         while (getchar () != '\n') ;
1977       if (i != 'y' && i != 'Y')
1978         return 0;
1979 #endif /* DEBUG */
1980     }
1981
1982   /* Run each piped subprocess.  */
1983
1984   for (i = 0; i < n_commands; i++)
1985     {
1986       char *errmsg_fmt, *errmsg_arg;
1987       char *string = commands[i].argv[0];
1988
1989       commands[i].pid = pexecute (string, commands[i].argv,
1990                                   programname, temp_filename,
1991                                   &errmsg_fmt, &errmsg_arg,
1992                                   ((i == 0 ? PEXECUTE_FIRST : 0)
1993                                    | (i + 1 == n_commands ? PEXECUTE_LAST : 0)
1994                                    | (string == commands[i].prog
1995                                       ? PEXECUTE_SEARCH : 0)
1996                                    | (verbose_flag ? PEXECUTE_VERBOSE : 0)));
1997
1998       if (commands[i].pid == -1)
1999         pfatal_pexecute (errmsg_fmt, errmsg_arg);
2000
2001       if (string != commands[i].prog)
2002         free (string);
2003     }
2004
2005   execution_count++;
2006
2007   /* Wait for all the subprocesses to finish.
2008      We don't care what order they finish in;
2009      we know that N_COMMANDS waits will get them all.
2010      Ignore subprocesses that we don't know about,
2011      since they can be spawned by the process that exec'ed us.  */
2012
2013   {
2014     int ret_code = 0;
2015
2016     for (i = 0; i < n_commands; )
2017       {
2018         int j;
2019         int status;
2020         int pid;
2021
2022         pid = pwait (commands[i].pid, &status, 0);
2023         if (pid < 0)
2024           abort ();
2025
2026         for (j = 0; j < n_commands; j++)
2027           if (commands[j].pid == pid)
2028             {
2029               i++;
2030               if (status != 0)
2031                 {
2032                   if (WIFSIGNALED (status))
2033                     {
2034                       fatal ("Internal compiler error: program %s got fatal signal %d",
2035                              commands[j].prog, WTERMSIG (status));
2036                       signal_count++;
2037                       ret_code = -1;
2038                     }
2039                   else if (WIFEXITED (status)
2040                            && WEXITSTATUS (status) >= MIN_FATAL_STATUS)
2041                     ret_code = -1;
2042                 }
2043               break;
2044             }
2045       }
2046     return ret_code;
2047   }
2048 }
2049 \f
2050 /* Find all the switches given to us
2051    and make a vector describing them.
2052    The elements of the vector are strings, one per switch given.
2053    If a switch uses following arguments, then the `part1' field
2054    is the switch itself and the `args' field
2055    is a null-terminated vector containing the following arguments.
2056    The `live_cond' field is 1 if the switch is true in a conditional spec,
2057    -1 if false (overridden by a later switch), and is initialized to zero.
2058    The `valid' field is nonzero if any spec has looked at this switch;
2059    if it remains zero at the end of the run, it must be meaningless.  */
2060
2061 struct switchstr
2062 {
2063   char *part1;
2064   char **args;
2065   int live_cond;
2066   int valid;
2067 };
2068
2069 static struct switchstr *switches;
2070
2071 static int n_switches;
2072
2073 struct infile
2074 {
2075   char *name;
2076   char *language;
2077 };
2078
2079 /* Also a vector of input files specified.  */
2080
2081 static struct infile *infiles;
2082
2083 static int n_infiles;
2084
2085 /* And a vector of corresponding output files is made up later.  */
2086
2087 static char **outfiles;
2088
2089 /* Used to track if none of the -B paths are used.  */
2090 static int warn_B;
2091
2092 /* Used to track if standard path isn't used and -b or -V is specified.  */
2093 static int warn_std;
2094
2095 /* Gives value to pass as "warn" to add_prefix for standard prefixes.  */
2096 static int *warn_std_ptr = 0;
2097
2098 /* Create the vector `switches' and its contents.
2099    Store its length in `n_switches'.  */
2100
2101 static void
2102 process_command (argc, argv)
2103      int argc;
2104      char **argv;
2105 {
2106   register int i;
2107   char *temp;
2108   char *spec_lang = 0;
2109   int last_language_n_infiles;
2110   int have_c = 0;
2111   int have_o = 0;
2112   int lang_n_infiles = 0;
2113
2114   gcc_exec_prefix = getenv ("GCC_EXEC_PREFIX");
2115
2116   n_switches = 0;
2117   n_infiles = 0;
2118
2119   /* Figure compiler version from version string.  */
2120
2121   compiler_version = save_string (version_string, strlen (version_string));
2122   for (temp = compiler_version; *temp; ++temp)
2123     {
2124       if (*temp == ' ')
2125         {
2126           *temp = '\0';
2127           break;
2128         }
2129     }
2130
2131   /* Set up the default search paths.  */
2132
2133   if (gcc_exec_prefix)
2134     {
2135       add_prefix (&exec_prefixes, gcc_exec_prefix, 0, 0, NULL_PTR);
2136       add_prefix (&startfile_prefixes, gcc_exec_prefix, 0, 0, NULL_PTR);
2137     }
2138
2139   /* COMPILER_PATH and LIBRARY_PATH have values
2140      that are lists of directory names with colons.  */
2141
2142   temp = getenv ("COMPILER_PATH");
2143   if (temp)
2144     {
2145       char *startp, *endp;
2146       char *nstore = (char *) alloca (strlen (temp) + 3);
2147
2148       startp = endp = temp;
2149       while (1)
2150         {
2151           if (*endp == PATH_SEPARATOR || *endp == 0)
2152             {
2153               strncpy (nstore, startp, endp-startp);
2154               if (endp == startp)
2155                 strcpy (nstore, concat (".", dir_separator_str, NULL_PTR));
2156               else if (endp[-1] != '/' && endp[-1] != DIR_SEPARATOR)
2157                 {
2158                   nstore[endp-startp] = DIR_SEPARATOR;
2159                   nstore[endp-startp+1] = 0;
2160                 }
2161               else
2162                 nstore[endp-startp] = 0;
2163               add_prefix (&exec_prefixes, nstore, 0, 0, NULL_PTR);
2164               if (*endp == 0)
2165                 break;
2166               endp = startp = endp + 1;
2167             }
2168           else
2169             endp++;
2170         }
2171     }
2172
2173   temp = getenv ("LIBRARY_PATH");
2174   if (temp && ! cross_compile)
2175     {
2176       char *startp, *endp;
2177       char *nstore = (char *) alloca (strlen (temp) + 3);
2178
2179       startp = endp = temp;
2180       while (1)
2181         {
2182           if (*endp == PATH_SEPARATOR || *endp == 0)
2183             {
2184               strncpy (nstore, startp, endp-startp);
2185               if (endp == startp)
2186                 strcpy (nstore, concat (".", dir_separator_str, NULL_PTR));
2187               else if (endp[-1] != '/' && endp[-1] != DIR_SEPARATOR)
2188                 {
2189                   nstore[endp-startp] = DIR_SEPARATOR;
2190                   nstore[endp-startp+1] = 0;
2191                 }
2192               else
2193                 nstore[endp-startp] = 0;
2194               add_prefix (&startfile_prefixes, nstore, 0, 0, NULL_PTR);
2195               if (*endp == 0)
2196                 break;
2197               endp = startp = endp + 1;
2198             }
2199           else
2200             endp++;
2201         }
2202     }
2203
2204   /* Use LPATH like LIBRARY_PATH (for the CMU build program).  */
2205   temp = getenv ("LPATH");
2206   if (temp && ! cross_compile)
2207     {
2208       char *startp, *endp;
2209       char *nstore = (char *) alloca (strlen (temp) + 3);
2210
2211       startp = endp = temp;
2212       while (1)
2213         {
2214           if (*endp == PATH_SEPARATOR || *endp == 0)
2215             {
2216               strncpy (nstore, startp, endp-startp);
2217               if (endp == startp)
2218                 strcpy (nstore, concat (".", dir_separator_str, NULL_PTR));
2219               else if (endp[-1] != '/' && endp[-1] != DIR_SEPARATOR)
2220                 {
2221                   nstore[endp-startp] = DIR_SEPARATOR;
2222                   nstore[endp-startp+1] = 0;
2223                 }
2224               else
2225                 nstore[endp-startp] = 0;
2226               add_prefix (&startfile_prefixes, nstore, 0, 0, NULL_PTR);
2227               if (*endp == 0)
2228                 break;
2229               endp = startp = endp + 1;
2230             }
2231           else
2232             endp++;
2233         }
2234     }
2235
2236   /* Convert new-style -- options to old-style.  */
2237   translate_options (&argc, &argv);
2238
2239   /* Scan argv twice.  Here, the first time, just count how many switches
2240      there will be in their vector, and how many input files in theirs.
2241      Here we also parse the switches that cc itself uses (e.g. -v).  */
2242
2243   for (i = 1; i < argc; i++)
2244     {
2245       if (! strcmp (argv[i], "-dumpspecs"))
2246         {
2247           printf ("*asm:\n%s\n\n", asm_spec);
2248           printf ("*asm_final:\n%s\n\n", asm_final_spec);
2249           printf ("*cpp:\n%s\n\n", cpp_spec);
2250           printf ("*cc1:\n%s\n\n", cc1_spec);
2251           printf ("*cc1plus:\n%s\n\n", cc1plus_spec);
2252           printf ("*endfile:\n%s\n\n", endfile_spec);
2253           printf ("*link:\n%s\n\n", link_spec);
2254           printf ("*lib:\n%s\n\n", lib_spec);
2255           printf ("*libgcc:\n%s\n\n", libgcc_spec);
2256           printf ("*startfile:\n%s\n\n", startfile_spec);
2257           printf ("*switches_need_spaces:\n%s\n\n", switches_need_spaces);
2258           printf ("*signed_char:\n%s\n\n", signed_char_spec);
2259           printf ("*predefines:\n%s\n\n", cpp_predefines);
2260           printf ("*cross_compile:\n%d\n\n", cross_compile);
2261           printf ("*multilib:\n%s\n\n", multilib_select);
2262           printf ("*multilib_defaults:\n%s\n\n", multilib_defaults);
2263           printf ("*multilib_extra:\n%s\n\n", multilib_extra);
2264           printf ("*multilib_matches:\n%s\n\n", multilib_matches);
2265
2266 #ifdef EXTRA_SPECS
2267           {
2268             int j;
2269             for (j = 0; j < sizeof (extra_specs) / sizeof (extra_specs[0]); j++)
2270               printf ("*%s:\n%s\n\n", extra_specs[j].name,
2271                       (extra_specs[j].spec) ? extra_specs[j].spec : "");
2272           }
2273 #endif
2274           exit (0);
2275         }
2276       else if (! strcmp (argv[i], "-dumpversion"))
2277         {
2278           printf ("%s\n", version_string);
2279           exit (0);
2280         }
2281       else if (! strcmp (argv[i], "-dumpmachine"))
2282         {
2283           printf ("%s\n", spec_machine);
2284           exit  (0);
2285         }
2286       else if (! strcmp (argv[i], "-print-search-dirs"))
2287         print_search_dirs = 1;
2288       else if (! strcmp (argv[i], "-print-libgcc-file-name"))
2289         print_file_name = "libgcc.a";
2290       else if (! strncmp (argv[i], "-print-file-name=", 17))
2291         print_file_name = argv[i] + 17;
2292       else if (! strncmp (argv[i], "-print-prog-name=", 17))
2293         print_prog_name = argv[i] + 17;
2294       else if (! strcmp (argv[i], "-print-multi-lib"))
2295         print_multi_lib = 1;
2296       else if (! strcmp (argv[i], "-print-multi-directory"))
2297         print_multi_directory = 1;
2298       else if (! strncmp (argv[i], "-Wa,", 4))
2299         {
2300           int prev, j;
2301           /* Pass the rest of this option to the assembler.  */
2302
2303           n_assembler_options++;
2304           if (!assembler_options)
2305             assembler_options
2306               = (char **) xmalloc (n_assembler_options * sizeof (char **));
2307           else
2308             assembler_options
2309               = (char **) xrealloc (assembler_options,
2310                                     n_assembler_options * sizeof (char **));
2311
2312           /* Split the argument at commas.  */
2313           prev = 4;
2314           for (j = 4; argv[i][j]; j++)
2315             if (argv[i][j] == ',')
2316               {
2317                 assembler_options[n_assembler_options - 1]
2318                   = save_string (argv[i] + prev, j - prev);
2319                 n_assembler_options++;
2320                 assembler_options
2321                   = (char **) xrealloc (assembler_options,
2322                                         n_assembler_options * sizeof (char **));
2323                 prev = j + 1;
2324               }
2325           /* Record the part after the last comma.  */
2326           assembler_options[n_assembler_options - 1] = argv[i] + prev;
2327         }
2328       else if (! strncmp (argv[i], "-Wp,", 4))
2329         {
2330           int prev, j;
2331           /* Pass the rest of this option to the preprocessor.  */
2332
2333           n_preprocessor_options++;
2334           if (!preprocessor_options)
2335             preprocessor_options
2336               = (char **) xmalloc (n_preprocessor_options * sizeof (char **));
2337           else
2338             preprocessor_options
2339               = (char **) xrealloc (preprocessor_options,
2340                                     n_preprocessor_options * sizeof (char **));
2341
2342           /* Split the argument at commas.  */
2343           prev = 4;
2344           for (j = 4; argv[i][j]; j++)
2345             if (argv[i][j] == ',')
2346               {
2347                 preprocessor_options[n_preprocessor_options - 1]
2348                   = save_string (argv[i] + prev, j - prev);
2349                 n_preprocessor_options++;
2350                 preprocessor_options
2351                   = (char **) xrealloc (preprocessor_options,
2352                                         n_preprocessor_options * sizeof (char **));
2353                 prev = j + 1;
2354               }
2355           /* Record the part after the last comma.  */
2356           preprocessor_options[n_preprocessor_options - 1] = argv[i] + prev;
2357         }
2358       else if (argv[i][0] == '+' && argv[i][1] == 'e')
2359         /* The +e options to the C++ front-end.  */
2360         n_switches++;
2361       else if (strncmp (argv[i], "-Wl,", 4) == 0)
2362         {
2363           int j;
2364           /* Split the argument at commas.  */
2365           for (j = 3; argv[i][j]; j++)
2366             n_infiles += (argv[i][j] == ',');
2367         }
2368       else if (strcmp (argv[i], "-Xlinker") == 0)
2369         {
2370           if (i + 1 == argc)
2371             fatal ("argument to `-Xlinker' is missing");
2372
2373           n_infiles++;
2374           i++;
2375         }
2376       else if (strncmp (argv[i], "-l", 2) == 0)
2377         n_infiles++;
2378       else if (strcmp (argv[i], "-save-temps") == 0)
2379         {
2380           save_temps_flag = 1;
2381           n_switches++;
2382         }
2383       else if (argv[i][0] == '-' && argv[i][1] != 0)
2384         {
2385           register char *p = &argv[i][1];
2386           register int c = *p;
2387
2388           switch (c)
2389             {
2390             case 'b':
2391               if (p[1] == 0 && i + 1 == argc)
2392                 fatal ("argument to `-b' is missing");
2393               if (p[1] == 0)
2394                 spec_machine = argv[++i];
2395               else
2396                 spec_machine = p + 1;
2397
2398               warn_std_ptr = &warn_std;
2399               break;
2400
2401             case 'B':
2402               {
2403                 int *temp = (int *) xmalloc (sizeof (int));
2404                 char *value;
2405                 if (p[1] == 0 && i + 1 == argc)
2406                   fatal ("argument to `-B' is missing");
2407                 if (p[1] == 0)
2408                   value = argv[++i];
2409                 else
2410                   value = p + 1;
2411                 add_prefix (&exec_prefixes, value, 1, 0, &warn_B);
2412                 add_prefix (&startfile_prefixes, value, 1, 0, &warn_B);
2413                 add_prefix (&include_prefixes, concat (value, "include", NULL_PTR),
2414                             1, 0, NULL_PTR);
2415
2416                 /* As a kludge, if the arg is "[foo/]stageN/", just add
2417                    "[foo/]include" to the include prefix.  */
2418                 {
2419                   int len = strlen (value);
2420                   if ((len == 7
2421                        || (len > 7
2422                            && (value[len - 8] == '/'
2423                                || value[len - 8] == DIR_SEPARATOR)))
2424                       && strncmp (value + len - 7, "stage", 5) == 0
2425                       && isdigit (value[len - 2])
2426                       && (value[len - 1] == '/'
2427                           || value[len - 1] == DIR_SEPARATOR))
2428                     {
2429                       if (len == 7)
2430                         add_prefix (&include_prefixes, "include",
2431                                     1, 0, NULL_PTR);
2432                       else
2433                         {
2434                           char *string = xmalloc (len + 1);
2435                           strncpy (string, value, len-7);
2436                           strcat (string, "include");
2437                           add_prefix (&include_prefixes, string,
2438                                       1, 0, NULL_PTR);
2439                         }
2440                     }
2441                 }
2442               }
2443               break;
2444
2445             case 'v':   /* Print our subcommands and print versions.  */
2446               n_switches++;
2447               /* If they do anything other than exactly `-v', don't set
2448                  verbose_flag; rather, continue on to give the error.  */
2449               if (p[1] != 0)
2450                 break;
2451               verbose_flag++;
2452               break;
2453
2454             case 'V':
2455               if (p[1] == 0 && i + 1 == argc)
2456                 fatal ("argument to `-V' is missing");
2457               if (p[1] == 0)
2458                 spec_version = argv[++i];
2459               else
2460                 spec_version = p + 1;
2461               compiler_version = spec_version;
2462               warn_std_ptr = &warn_std;
2463               break;
2464
2465             case 'c':
2466               if (p[1] == 0)
2467                 {
2468                   have_c = 1;
2469                   n_switches++;
2470                   break;
2471                 }
2472               goto normal_switch;
2473
2474             case 'o':
2475               have_o = 1;
2476               goto normal_switch;
2477
2478             default:
2479             normal_switch:
2480               n_switches++;
2481
2482               if (SWITCH_TAKES_ARG (c) > (p[1] != 0))
2483                 i += SWITCH_TAKES_ARG (c) - (p[1] != 0);
2484               else if (WORD_SWITCH_TAKES_ARG (p))
2485                 i += WORD_SWITCH_TAKES_ARG (p);
2486             }
2487         }
2488       else
2489         {
2490           n_infiles++;
2491           lang_n_infiles++;
2492         }
2493     }
2494
2495   if (have_c && have_o && lang_n_infiles > 1)
2496     fatal ("cannot specify -o with -c and multiple compilations");
2497
2498   /* Set up the search paths before we go looking for config files.  */
2499
2500   /* These come before the md prefixes so that we will find gcc's subcommands
2501      (such as cpp) rather than those of the host system.  */
2502   /* Use 2 as fourth arg meaning try just the machine as a suffix,
2503      as well as trying the machine and the version.  */
2504 #ifndef OS2
2505   add_prefix (&exec_prefixes, standard_exec_prefix, 0, 2, warn_std_ptr);
2506   add_prefix (&exec_prefixes, standard_exec_prefix_1, 0, 2, warn_std_ptr);
2507 #endif
2508
2509   add_prefix (&startfile_prefixes, standard_exec_prefix, 0, 1, warn_std_ptr);
2510   add_prefix (&startfile_prefixes, standard_exec_prefix_1, 0, 1, warn_std_ptr);
2511
2512   tooldir_prefix = concat (tooldir_base_prefix, spec_machine, 
2513                            dir_separator_str, NULL_PTR);
2514
2515   /* If tooldir is relative, base it on exec_prefixes.  A relative
2516      tooldir lets us move the installed tree as a unit.
2517
2518      If GCC_EXEC_PREFIX is defined, then we want to add two relative
2519      directories, so that we can search both the user specified directory
2520      and the standard place.  */
2521
2522   if (*tooldir_prefix != '/' && *tooldir_prefix != DIR_SEPARATOR)
2523     {
2524       if (gcc_exec_prefix)
2525         {
2526           char *gcc_exec_tooldir_prefix
2527             = concat (gcc_exec_prefix, spec_machine, dir_separator_str,
2528                       spec_version, dir_separator_str, tooldir_prefix, NULL_PTR);
2529
2530           add_prefix (&exec_prefixes,
2531                       concat (gcc_exec_tooldir_prefix, "bin", 
2532                               dir_separator_str, NULL_PTR),
2533                       0, 0, NULL_PTR);
2534           add_prefix (&startfile_prefixes,
2535                       concat (gcc_exec_tooldir_prefix, "lib", 
2536                               dir_separator_str, NULL_PTR),
2537                       0, 0, NULL_PTR);
2538         }
2539
2540       tooldir_prefix = concat (standard_exec_prefix, spec_machine,
2541                                dir_separator_str, spec_version, 
2542                                dir_separator_str, tooldir_prefix, NULL_PTR);
2543     }
2544
2545   add_prefix (&exec_prefixes, 
2546               concat (tooldir_prefix, "bin", dir_separator_str, NULL_PTR),
2547               0, 0, NULL_PTR);
2548   add_prefix (&startfile_prefixes,
2549               concat (tooldir_prefix, "lib", dir_separator_str, NULL_PTR),
2550               0, 0, NULL_PTR);
2551
2552   /* More prefixes are enabled in main, after we read the specs file
2553      and determine whether this is cross-compilation or not.  */
2554
2555
2556   /* Then create the space for the vectors and scan again.  */
2557
2558   switches = ((struct switchstr *)
2559               xmalloc ((n_switches + 1) * sizeof (struct switchstr)));
2560   infiles = (struct infile *) xmalloc ((n_infiles + 1) * sizeof (struct infile));
2561   n_switches = 0;
2562   n_infiles = 0;
2563   last_language_n_infiles = -1;
2564
2565   /* This, time, copy the text of each switch and store a pointer
2566      to the copy in the vector of switches.
2567      Store all the infiles in their vector.  */
2568
2569   for (i = 1; i < argc; i++)
2570     {
2571       /* Just skip the switches that were handled by the preceding loop.  */
2572       if (! strncmp (argv[i], "-Wa,", 4))
2573         ;
2574       else if (! strncmp (argv[i], "-Wp,", 4))
2575         ;
2576       else if (! strcmp (argv[i], "-print-search-dirs"))
2577         ;
2578       else if (! strcmp (argv[i], "-print-libgcc-file-name"))
2579         ;
2580       else if (! strncmp (argv[i], "-print-file-name=", 17))
2581         ;
2582       else if (! strncmp (argv[i], "-print-prog-name=", 17))
2583         ;
2584       else if (! strcmp (argv[i], "-print-multi-lib"))
2585         ;
2586       else if (! strcmp (argv[i], "-print-multi-directory"))
2587         ;
2588       else if (argv[i][0] == '+' && argv[i][1] == 'e')
2589         {
2590           /* Compensate for the +e options to the C++ front-end;
2591              they're there simply for cfront call-compatibility.  We do
2592              some magic in default_compilers to pass them down properly.
2593              Note we deliberately start at the `+' here, to avoid passing
2594              -e0 or -e1 down into the linker.  */
2595           switches[n_switches].part1 = &argv[i][0];
2596           switches[n_switches].args = 0;
2597           switches[n_switches].live_cond = 0;
2598           switches[n_switches].valid = 0;
2599           n_switches++;
2600         }
2601       else if (strncmp (argv[i], "-Wl,", 4) == 0)
2602         {
2603           int prev, j;
2604           /* Split the argument at commas.  */
2605           prev = 4;
2606           for (j = 4; argv[i][j]; j++)
2607             if (argv[i][j] == ',')
2608               {
2609                 infiles[n_infiles].language = 0;
2610                 infiles[n_infiles++].name
2611                   = save_string (argv[i] + prev, j - prev);
2612                 prev = j + 1;
2613               }
2614           /* Record the part after the last comma.  */
2615           infiles[n_infiles].language = 0;
2616           infiles[n_infiles++].name = argv[i] + prev;
2617         }
2618       else if (strcmp (argv[i], "-Xlinker") == 0)
2619         {
2620           infiles[n_infiles].language = 0;
2621           infiles[n_infiles++].name = argv[++i];
2622         }
2623       else if (strncmp (argv[i], "-l", 2) == 0)
2624         {
2625           infiles[n_infiles].language = 0;
2626           infiles[n_infiles++].name = argv[i];
2627         }
2628       else if (argv[i][0] == '-' && argv[i][1] != 0)
2629         {
2630           register char *p = &argv[i][1];
2631           register int c = *p;
2632
2633           if (c == 'B' || c == 'b' || c == 'V')
2634             {
2635               /* Skip a separate arg, if any.  */
2636               if (p[1] == 0)
2637                 i++;
2638               continue;
2639             }
2640           if (c == 'x')
2641             {
2642               if (p[1] == 0 && i + 1 == argc)
2643                 fatal ("argument to `-x' is missing");
2644               if (p[1] == 0)
2645                 spec_lang = argv[++i];
2646               else
2647                 spec_lang = p + 1;
2648               if (! strcmp (spec_lang, "none"))
2649                 /* Suppress the warning if -xnone comes after the last input
2650                    file, because alternate command interfaces like g++ might
2651                    find it useful to place -xnone after each input file.  */
2652                 spec_lang = 0;
2653               else
2654                 last_language_n_infiles = n_infiles;
2655               continue;
2656             }
2657           switches[n_switches].part1 = p;
2658           /* Deal with option arguments in separate argv elements.  */
2659           if ((SWITCH_TAKES_ARG (c) > (p[1] != 0))
2660               || WORD_SWITCH_TAKES_ARG (p))
2661             {
2662               int j = 0;
2663               int n_args = WORD_SWITCH_TAKES_ARG (p);
2664
2665               if (n_args == 0)
2666                 {
2667                   /* Count only the option arguments in separate argv elements.  */
2668                   n_args = SWITCH_TAKES_ARG (c) - (p[1] != 0);
2669                 }
2670               if (i + n_args >= argc)
2671                 fatal ("argument to `-%s' is missing", p);
2672               switches[n_switches].args
2673                 = (char **) xmalloc ((n_args + 1) * sizeof (char *));
2674               while (j < n_args)
2675                 switches[n_switches].args[j++] = argv[++i];
2676               /* Null-terminate the vector.  */
2677               switches[n_switches].args[j] = 0;
2678             }
2679           else if (index (switches_need_spaces, c))
2680             {
2681               /* On some systems, ld cannot handle some options without
2682                  a space.  So split the option from its argument.  */
2683               char *part1 = (char *) xmalloc (2);
2684               part1[0] = c;
2685               part1[1] = '\0';
2686               
2687               switches[n_switches].part1 = part1;
2688               switches[n_switches].args = (char **) xmalloc (2 * sizeof (char *));
2689               switches[n_switches].args[0] = xmalloc (strlen (p));
2690               strcpy (switches[n_switches].args[0], &p[1]);
2691               switches[n_switches].args[1] = 0;
2692             }
2693           else
2694             switches[n_switches].args = 0;
2695
2696           switches[n_switches].live_cond = 0;
2697           switches[n_switches].valid = 0;
2698           /* This is always valid, since gcc.c itself understands it.  */
2699           if (!strcmp (p, "save-temps"))
2700             switches[n_switches].valid = 1;
2701           n_switches++;
2702         }
2703       else
2704         {
2705 #ifdef HAVE_OBJECT_SUFFIX
2706           /* Convert x.o to x.obj if OBJECT_SUFFIX is ".obj".  */
2707           if (strlen (argv[i]) > 2
2708               && argv[i][strlen (argv[i]) - 2] == '.'
2709               && argv[i][strlen (argv[i]) - 1] == 'o')
2710             {
2711               int j;
2712
2713               for (j = 0; j < strlen (argv[i]) - 2; j++)
2714                 obstack_1grow (&obstack, argv[i][j]);
2715
2716               obstack_grow (&obstack, OBJECT_SUFFIX, strlen (OBJECT_SUFFIX));
2717               obstack_1grow (&obstack, 0);
2718               argv[i] = obstack_finish (&obstack);
2719             }
2720 #endif
2721
2722           if (strcmp (argv[i], "-") != 0 && access (argv[i], R_OK) < 0)
2723             {
2724               perror_with_name (argv[i]);
2725               error_count++;
2726             }
2727           else
2728             {
2729               infiles[n_infiles].language = spec_lang;
2730               infiles[n_infiles++].name = argv[i];
2731             }
2732         }
2733     }
2734
2735   if (n_infiles == last_language_n_infiles && spec_lang != 0)
2736     error ("Warning: `-x %s' after last input file has no effect", spec_lang);
2737
2738   switches[n_switches].part1 = 0;
2739   infiles[n_infiles].name = 0;
2740 }
2741 \f
2742 /* Process a spec string, accumulating and running commands.  */
2743
2744 /* These variables describe the input file name.
2745    input_file_number is the index on outfiles of this file,
2746    so that the output file name can be stored for later use by %o.
2747    input_basename is the start of the part of the input file
2748    sans all directory names, and basename_length is the number
2749    of characters starting there excluding the suffix .c or whatever.  */
2750
2751 static char *input_filename;
2752 static int input_file_number;
2753 static int input_filename_length;
2754 static int basename_length;
2755 static char *input_basename;
2756 static char *input_suffix;
2757
2758 /* These are variables used within do_spec and do_spec_1.  */
2759
2760 /* Nonzero if an arg has been started and not yet terminated
2761    (with space, tab or newline).  */
2762 static int arg_going;
2763
2764 /* Nonzero means %d or %g has been seen; the next arg to be terminated
2765    is a temporary file name.  */
2766 static int delete_this_arg;
2767
2768 /* Nonzero means %w has been seen; the next arg to be terminated
2769    is the output file name of this compilation.  */
2770 static int this_is_output_file;
2771
2772 /* Nonzero means %s has been seen; the next arg to be terminated
2773    is the name of a library file and we should try the standard
2774    search dirs for it.  */
2775 static int this_is_library_file;
2776
2777 /* Nonzero means that the input of this command is coming from a pipe.  */
2778 static int input_from_pipe;
2779
2780 /* Process the spec SPEC and run the commands specified therein.
2781    Returns 0 if the spec is successfully processed; -1 if failed.  */
2782
2783 static int
2784 do_spec (spec)
2785      char *spec;
2786 {
2787   int value;
2788
2789   clear_args ();
2790   arg_going = 0;
2791   delete_this_arg = 0;
2792   this_is_output_file = 0;
2793   this_is_library_file = 0;
2794   input_from_pipe = 0;
2795
2796   value = do_spec_1 (spec, 0, NULL_PTR);
2797
2798   /* Force out any unfinished command.
2799      If -pipe, this forces out the last command if it ended in `|'.  */
2800   if (value == 0)
2801     {
2802       if (argbuf_index > 0 && !strcmp (argbuf[argbuf_index - 1], "|"))
2803         argbuf_index--;
2804
2805       if (argbuf_index > 0)
2806         value = execute ();
2807     }
2808
2809   return value;
2810 }
2811
2812 /* Process the sub-spec SPEC as a portion of a larger spec.
2813    This is like processing a whole spec except that we do
2814    not initialize at the beginning and we do not supply a
2815    newline by default at the end.
2816    INSWITCH nonzero means don't process %-sequences in SPEC;
2817    in this case, % is treated as an ordinary character.
2818    This is used while substituting switches.
2819    INSWITCH nonzero also causes SPC not to terminate an argument.
2820
2821    Value is zero unless a line was finished
2822    and the command on that line reported an error.  */
2823
2824 static int
2825 do_spec_1 (spec, inswitch, soft_matched_part)
2826      char *spec;
2827      int inswitch;
2828      char *soft_matched_part;
2829 {
2830   register char *p = spec;
2831   register int c;
2832   int i;
2833   char *string;
2834   int value;
2835
2836   while (c = *p++)
2837     /* If substituting a switch, treat all chars like letters.
2838        Otherwise, NL, SPC, TAB and % are special.  */
2839     switch (inswitch ? 'a' : c)
2840       {
2841       case '\n':
2842         /* End of line: finish any pending argument,
2843            then run the pending command if one has been started.  */
2844         if (arg_going)
2845           {
2846             obstack_1grow (&obstack, 0);
2847             string = obstack_finish (&obstack);
2848             if (this_is_library_file)
2849               string = find_file (string);
2850             store_arg (string, delete_this_arg, this_is_output_file);
2851             if (this_is_output_file)
2852               outfiles[input_file_number] = string;
2853           }
2854         arg_going = 0;
2855
2856         if (argbuf_index > 0 && !strcmp (argbuf[argbuf_index - 1], "|"))
2857           {
2858             for (i = 0; i < n_switches; i++)
2859               if (!strcmp (switches[i].part1, "pipe"))
2860                 break;
2861
2862             /* A `|' before the newline means use a pipe here,
2863                but only if -pipe was specified.
2864                Otherwise, execute now and don't pass the `|' as an arg.  */
2865             if (i < n_switches)
2866               {
2867                 input_from_pipe = 1;
2868                 switches[i].valid = 1;
2869                 break;
2870               }
2871             else
2872               argbuf_index--;
2873           }
2874
2875         if (argbuf_index > 0)
2876           {
2877             value = execute ();
2878             if (value)
2879               return value;
2880           }
2881         /* Reinitialize for a new command, and for a new argument.  */
2882         clear_args ();
2883         arg_going = 0;
2884         delete_this_arg = 0;
2885         this_is_output_file = 0;
2886         this_is_library_file = 0;
2887         input_from_pipe = 0;
2888         break;
2889
2890       case '|':
2891         /* End any pending argument.  */
2892         if (arg_going)
2893           {
2894             obstack_1grow (&obstack, 0);
2895             string = obstack_finish (&obstack);
2896             if (this_is_library_file)
2897               string = find_file (string);
2898             store_arg (string, delete_this_arg, this_is_output_file);
2899             if (this_is_output_file)
2900               outfiles[input_file_number] = string;
2901           }
2902
2903         /* Use pipe */
2904         obstack_1grow (&obstack, c);
2905         arg_going = 1;
2906         break;
2907
2908       case '\t':
2909       case ' ':
2910         /* Space or tab ends an argument if one is pending.  */
2911         if (arg_going)
2912           {
2913             obstack_1grow (&obstack, 0);
2914             string = obstack_finish (&obstack);
2915             if (this_is_library_file)
2916               string = find_file (string);
2917             store_arg (string, delete_this_arg, this_is_output_file);
2918             if (this_is_output_file)
2919               outfiles[input_file_number] = string;
2920           }
2921         /* Reinitialize for a new argument.  */
2922         arg_going = 0;
2923         delete_this_arg = 0;
2924         this_is_output_file = 0;
2925         this_is_library_file = 0;
2926         break;
2927
2928       case '%':
2929         switch (c = *p++)
2930           {
2931           case 0:
2932             fatal ("Invalid specification!  Bug in cc.");
2933
2934           case 'b':
2935             obstack_grow (&obstack, input_basename, basename_length);
2936             arg_going = 1;
2937             break;
2938
2939           case 'd':
2940             delete_this_arg = 2;
2941             break;
2942
2943           /* Dump out the directories specified with LIBRARY_PATH,
2944              followed by the absolute directories
2945              that we search for startfiles.  */
2946           case 'D':
2947             {
2948               struct prefix_list *pl = startfile_prefixes.plist;
2949               int bufsize = 100;
2950               char *buffer = (char *) xmalloc (bufsize);
2951               int idx;
2952
2953               for (; pl; pl = pl->next)
2954                 {
2955 #ifdef RELATIVE_PREFIX_NOT_LINKDIR
2956                   /* Used on systems which record the specified -L dirs
2957                      and use them to search for dynamic linking.  */
2958                   /* Relative directories always come from -B,
2959                      and it is better not to use them for searching
2960                      at run time.  In particular, stage1 loses  */
2961                   if (pl->prefix[0] != '/' && pl->prefix[0] != DIR_SEPARATOR)
2962                     continue;
2963 #endif
2964                   /* Try subdirectory if there is one.  */
2965                   if (multilib_dir != NULL)
2966                     {
2967                       if (machine_suffix)
2968                         {
2969                           if (strlen (pl->prefix) + strlen (machine_suffix)
2970                               >= bufsize)
2971                             bufsize = (strlen (pl->prefix)
2972                                        + strlen (machine_suffix)) * 2 + 1;
2973                           buffer = (char *) xrealloc (buffer, bufsize);
2974                           strcpy (buffer, pl->prefix);
2975                           strcat (buffer, machine_suffix);
2976                           if (is_directory (buffer, multilib_dir, 1))
2977                             {
2978                               do_spec_1 ("-L", 0, NULL_PTR);
2979 #ifdef SPACE_AFTER_L_OPTION
2980                               do_spec_1 (" ", 0, NULL_PTR);
2981 #endif
2982                               do_spec_1 (buffer, 1, NULL_PTR);
2983                               do_spec_1 (multilib_dir, 1, NULL_PTR);
2984                               /* Make this a separate argument.  */
2985                               do_spec_1 (" ", 0, NULL_PTR);
2986                             }
2987                         }
2988                       if (!pl->require_machine_suffix)
2989                         {
2990                           if (is_directory (pl->prefix, multilib_dir, 1))
2991                             {
2992                               do_spec_1 ("-L", 0, NULL_PTR);
2993 #ifdef SPACE_AFTER_L_OPTION
2994                               do_spec_1 (" ", 0, NULL_PTR);
2995 #endif
2996                               do_spec_1 (pl->prefix, 1, NULL_PTR);
2997                               do_spec_1 (multilib_dir, 1, NULL_PTR);
2998                               /* Make this a separate argument.  */
2999                               do_spec_1 (" ", 0, NULL_PTR);
3000                             }
3001                         }
3002                     }
3003                   if (machine_suffix)
3004                     {
3005                       if (is_directory (pl->prefix, machine_suffix, 1))
3006                         {
3007                           do_spec_1 ("-L", 0, NULL_PTR);
3008 #ifdef SPACE_AFTER_L_OPTION
3009                           do_spec_1 (" ", 0, NULL_PTR);
3010 #endif
3011                           do_spec_1 (pl->prefix, 1, NULL_PTR);
3012                           /* Remove slash from machine_suffix.  */
3013                           if (strlen (machine_suffix) >= bufsize)
3014                             bufsize = strlen (machine_suffix) * 2 + 1;
3015                           buffer = (char *) xrealloc (buffer, bufsize);
3016                           strcpy (buffer, machine_suffix);
3017                           idx = strlen (buffer);
3018                           if (buffer[idx - 1] == '/'
3019                               || buffer[idx - 1] == DIR_SEPARATOR)
3020                             buffer[idx - 1] = 0;
3021                           do_spec_1 (buffer, 1, NULL_PTR);
3022                           /* Make this a separate argument.  */
3023                           do_spec_1 (" ", 0, NULL_PTR);
3024                         }
3025                     }
3026                   if (!pl->require_machine_suffix)
3027                     {
3028                       if (is_directory (pl->prefix, "", 1))
3029                         {
3030                           do_spec_1 ("-L", 0, NULL_PTR);
3031 #ifdef SPACE_AFTER_L_OPTION
3032                           do_spec_1 (" ", 0, NULL_PTR);
3033 #endif
3034                           /* Remove slash from pl->prefix.  */
3035                           if (strlen (pl->prefix) >= bufsize)
3036                             bufsize = strlen (pl->prefix) * 2 + 1;
3037                           buffer = (char *) xrealloc (buffer, bufsize);
3038                           strcpy (buffer, pl->prefix);
3039                           idx = strlen (buffer);
3040                           if (buffer[idx - 1] == '/'
3041                               || buffer[idx - 1] == DIR_SEPARATOR)
3042                             buffer[idx - 1] = 0;
3043                           do_spec_1 (buffer, 1, NULL_PTR);
3044                           /* Make this a separate argument.  */
3045                           do_spec_1 (" ", 0, NULL_PTR);
3046                         }
3047                     }
3048                 }
3049               free (buffer);
3050             }
3051             break;
3052
3053           case 'e':
3054             /* {...:%efoo} means report an error with `foo' as error message
3055                and don't execute any more commands for this file.  */
3056             {
3057               char *q = p;
3058               char *buf;
3059               while (*p != 0 && *p != '\n') p++;
3060               buf = (char *) alloca (p - q + 1);
3061               strncpy (buf, q, p - q);
3062               buf[p - q] = 0;
3063               error ("%s", buf);
3064               return -1;
3065             }
3066             break;
3067
3068           case 'g':
3069           case 'u':
3070           case 'U':
3071             if (save_temps_flag)
3072               {
3073                 obstack_grow (&obstack, input_basename, basename_length);
3074                 delete_this_arg = 0;
3075               }
3076             else
3077               {
3078 #ifdef MKTEMP_EACH_FILE
3079                 /* ??? This has a problem: the total number of
3080                    values mktemp can return is limited.
3081                    That matters for the names of object files.
3082                    In 2.4, do something about that.  */
3083                 struct temp_name *t;
3084                 char *suffix = p;
3085                 while (*p == '.' || isalpha (*p)
3086                        || (p[0] == '%' && p[1] == 'O'))
3087                   p++;
3088
3089                 /* See if we already have an association of %g/%u/%U and
3090                    suffix.  */
3091                 for (t = temp_names; t; t = t->next)
3092                   if (t->length == p - suffix
3093                       && strncmp (t->suffix, suffix, p - suffix) == 0
3094                       && t->unique == (c != 'g'))
3095                     break;
3096
3097                 /* Make a new association if needed.  %u requires one.  */
3098                 if (t == 0 || c == 'u')
3099                   {
3100                     if (t == 0)
3101                       {
3102                         t = (struct temp_name *) xmalloc (sizeof (struct temp_name));
3103                         t->next = temp_names;
3104                         temp_names = t;
3105                       }
3106                     t->length = p - suffix;
3107                     t->suffix = save_string (suffix, p - suffix);
3108                     t->unique = (c != 'g');
3109                     temp_filename = choose_temp_base ();
3110                     temp_filename_length = strlen (temp_filename);
3111                     t->filename = temp_filename;
3112                     t->filename_length = temp_filename_length;
3113                   }
3114
3115                 obstack_grow (&obstack, t->filename, t->filename_length);
3116                 delete_this_arg = 1;
3117 #else
3118                 obstack_grow (&obstack, temp_filename, temp_filename_length);
3119                 if (c == 'u' || c == 'U')
3120                   {
3121                     static int unique;
3122                     char buff[9];
3123                     if (c == 'u')
3124                       unique++;
3125                     sprintf (buff, "%d", unique);
3126                     obstack_grow (&obstack, buff, strlen (buff));
3127                   }
3128 #endif
3129                 delete_this_arg = 1;
3130               }
3131             arg_going = 1;
3132             break;
3133
3134           case 'i':
3135             obstack_grow (&obstack, input_filename, input_filename_length);
3136             arg_going = 1;
3137             break;
3138
3139           case 'I':
3140             {
3141               struct prefix_list *pl = include_prefixes.plist;
3142
3143               if (gcc_exec_prefix)
3144                 {
3145                   do_spec_1 ("-iprefix", 1, NULL_PTR);
3146                   /* Make this a separate argument.  */
3147                   do_spec_1 (" ", 0, NULL_PTR);
3148                   do_spec_1 (gcc_exec_prefix, 1, NULL_PTR);
3149                   do_spec_1 (" ", 0, NULL_PTR);
3150                 }
3151
3152               for (; pl; pl = pl->next)
3153                 {
3154                   do_spec_1 ("-isystem", 1, NULL_PTR);
3155                   /* Make this a separate argument.  */
3156                   do_spec_1 (" ", 0, NULL_PTR);
3157                   do_spec_1 (pl->prefix, 1, NULL_PTR);
3158                   do_spec_1 (" ", 0, NULL_PTR);
3159                 }
3160             }
3161             break;
3162
3163           case 'o':
3164             for (i = 0; i < n_infiles; i++)
3165               store_arg (outfiles[i], 0, 0);
3166             break;
3167
3168           case 'O':
3169             obstack_grow (&obstack, OBJECT_SUFFIX, strlen (OBJECT_SUFFIX));
3170             arg_going = 1;
3171             break;
3172
3173           case 's':
3174             this_is_library_file = 1;
3175             break;
3176
3177           case 'w':
3178             this_is_output_file = 1;
3179             break;
3180
3181           case 'W':
3182             {
3183               int cur_index = argbuf_index;
3184               /* Handle the {...} following the %W.  */
3185               if (*p != '{')
3186                 abort ();
3187               p = handle_braces (p + 1);
3188               if (p == 0)
3189                 return -1;
3190               /* If any args were output, mark the last one for deletion
3191                  on failure.  */
3192               if (argbuf_index != cur_index)
3193                 record_temp_file (argbuf[argbuf_index - 1], 0, 1);
3194               break;
3195             }
3196
3197           /* %x{OPTION} records OPTION for %X to output.  */
3198           case 'x':
3199             {
3200               char *p1 = p;
3201               char *string;
3202
3203               /* Skip past the option value and make a copy.  */
3204               if (*p != '{')
3205                 abort ();
3206               while (*p++ != '}')
3207                 ;
3208               string = save_string (p1 + 1, p - p1 - 2);
3209
3210               /* See if we already recorded this option.  */
3211               for (i = 0; i < n_linker_options; i++)
3212                 if (! strcmp (string, linker_options[i]))
3213                   {
3214                     free (string);
3215                     return 0;
3216                   }
3217
3218               /* This option is new; add it.  */
3219               n_linker_options++;
3220               if (!linker_options)
3221                 linker_options
3222                   = (char **) xmalloc (n_linker_options * sizeof (char **));
3223               else
3224                 linker_options
3225                   = (char **) xrealloc (linker_options,
3226                                         n_linker_options * sizeof (char **));
3227
3228               linker_options[n_linker_options - 1] = string;
3229             }
3230             break;
3231
3232           /* Dump out the options accumulated previously using %x.  */
3233           case 'X':
3234             for (i = 0; i < n_linker_options; i++)
3235               {
3236                 do_spec_1 (linker_options[i], 1, NULL_PTR);
3237                 /* Make each accumulated option a separate argument.  */
3238                 do_spec_1 (" ", 0, NULL_PTR);
3239               }
3240             break;
3241
3242           /* Dump out the options accumulated previously using -Wa,.  */
3243           case 'Y':
3244             for (i = 0; i < n_assembler_options; i++)
3245               {
3246                 do_spec_1 (assembler_options[i], 1, NULL_PTR);
3247                 /* Make each accumulated option a separate argument.  */
3248                 do_spec_1 (" ", 0, NULL_PTR);
3249               }
3250             break;
3251
3252           /* Dump out the options accumulated previously using -Wp,.  */
3253           case 'Z':
3254             for (i = 0; i < n_preprocessor_options; i++)
3255               {
3256                 do_spec_1 (preprocessor_options[i], 1, NULL_PTR);
3257                 /* Make each accumulated option a separate argument.  */
3258                 do_spec_1 (" ", 0, NULL_PTR);
3259               }
3260             break;
3261
3262             /* Here are digits and numbers that just process
3263                a certain constant string as a spec.  */
3264
3265           case '1':
3266             value = do_spec_1 (cc1_spec, 0, NULL_PTR);
3267             if (value != 0)
3268               return value;
3269             break;
3270
3271           case '2':
3272             value = do_spec_1 (cc1plus_spec, 0, NULL_PTR);
3273             if (value != 0)
3274               return value;
3275             break;
3276
3277           case 'a':
3278             value = do_spec_1 (asm_spec, 0, NULL_PTR);
3279             if (value != 0)
3280               return value;
3281             break;
3282
3283           case 'A':
3284             value = do_spec_1 (asm_final_spec, 0, NULL_PTR);
3285             if (value != 0)
3286               return value;
3287             break;
3288
3289           case 'c':
3290             value = do_spec_1 (signed_char_spec, 0, NULL_PTR);
3291             if (value != 0)
3292               return value;
3293             break;
3294
3295           case 'C':
3296             value = do_spec_1 (cpp_spec, 0, NULL_PTR);
3297             if (value != 0)
3298               return value;
3299             break;
3300
3301           case 'E':
3302             value = do_spec_1 (endfile_spec, 0, NULL_PTR);
3303             if (value != 0)
3304               return value;
3305             break;
3306
3307           case 'l':
3308             value = do_spec_1 (link_spec, 0, NULL_PTR);
3309             if (value != 0)
3310               return value;
3311             break;
3312
3313           case 'L':
3314             value = do_spec_1 (lib_spec, 0, NULL_PTR);
3315             if (value != 0)
3316               return value;
3317             break;
3318
3319           case 'G':
3320             value = do_spec_1 (libgcc_spec, 0, NULL_PTR);
3321             if (value != 0)
3322               return value;
3323             break;
3324
3325           case 'p':
3326             {
3327               char *x = (char *) alloca (strlen (cpp_predefines) + 1);
3328               char *buf = x;
3329               char *y;
3330
3331               /* Copy all of the -D options in CPP_PREDEFINES into BUF.  */
3332               y = cpp_predefines;
3333               while (*y != 0)
3334                 {
3335                   if (! strncmp (y, "-D", 2))
3336                     /* Copy the whole option.  */
3337                     while (*y && *y != ' ' && *y != '\t')
3338                       *x++ = *y++;
3339                   else if (*y == ' ' || *y == '\t')
3340                     /* Copy whitespace to the result.  */
3341                     *x++ = *y++;
3342                   /* Don't copy other options.  */
3343                   else
3344                     y++;
3345                 }
3346
3347               *x = 0;
3348
3349               value = do_spec_1 (buf, 0, NULL_PTR);
3350               if (value != 0)
3351                 return value;
3352             }
3353             break;
3354
3355           case 'P':
3356             {
3357               char *x = (char *) alloca (strlen (cpp_predefines) * 4 + 1);
3358               char *buf = x;
3359               char *y;
3360
3361               /* Copy all of CPP_PREDEFINES into BUF,
3362                  but put __ after every -D and at the end of each arg.  */
3363               y = cpp_predefines;
3364               while (*y != 0)
3365                 {
3366                   if (! strncmp (y, "-D", 2))
3367                     {
3368                       int flag = 0;
3369
3370                       *x++ = *y++;
3371                       *x++ = *y++;
3372
3373                       if (*y != '_'
3374                           || (*(y+1) != '_' && ! isupper (*(y+1))))
3375                         {
3376                           /* Stick __ at front of macro name.  */
3377                           *x++ = '_';
3378                           *x++ = '_';
3379                           /* Arrange to stick __ at the end as well.  */
3380                           flag = 1;
3381                         }
3382
3383                       /* Copy the macro name.  */
3384                       while (*y && *y != '=' && *y != ' ' && *y != '\t')
3385                         *x++ = *y++;
3386
3387                       if (flag)
3388                         {
3389                           *x++ = '_';
3390                           *x++ = '_';
3391                         }
3392
3393                       /* Copy the value given, if any.  */
3394                       while (*y && *y != ' ' && *y != '\t')
3395                         *x++ = *y++;
3396                     }
3397                   else if (*y == ' ' || *y == '\t')
3398                     /* Copy whitespace to the result.  */
3399                     *x++ = *y++;
3400                   /* Don't copy -A options  */
3401                   else
3402                     y++;
3403                 }
3404               *x++ = ' ';
3405
3406               /* Copy all of CPP_PREDEFINES into BUF,
3407                  but put __ after every -D.  */
3408               y = cpp_predefines;
3409               while (*y != 0)
3410                 {
3411                   if (! strncmp (y, "-D", 2))
3412                     {
3413                       y += 2;
3414
3415                       if (*y != '_'
3416                           || (*(y+1) != '_' && ! isupper (*(y+1))))
3417                         {
3418                           /* Stick -D__ at front of macro name.  */
3419                           *x++ = '-';
3420                           *x++ = 'D';
3421                           *x++ = '_';
3422                           *x++ = '_';
3423
3424                           /* Copy the macro name.  */
3425                           while (*y && *y != '=' && *y != ' ' && *y != '\t')
3426                             *x++ = *y++;
3427
3428                           /* Copy the value given, if any.  */
3429                           while (*y && *y != ' ' && *y != '\t')
3430                             *x++ = *y++;
3431                         }
3432                       else
3433                         {
3434                           /* Do not copy this macro - we have just done it before */
3435                           while (*y && *y != ' ' && *y != '\t')
3436                             y++;
3437                         }
3438                     }
3439                   else if (*y == ' ' || *y == '\t')
3440                     /* Copy whitespace to the result.  */
3441                     *x++ = *y++;
3442                   /* Don't copy -A options  */
3443                   else
3444                     y++;
3445                 }
3446               *x++ = ' ';
3447
3448               /* Copy all of the -A options in CPP_PREDEFINES into BUF.  */
3449               y = cpp_predefines;
3450               while (*y != 0)
3451                 {
3452                   if (! strncmp (y, "-A", 2))
3453                     /* Copy the whole option.  */
3454                     while (*y && *y != ' ' && *y != '\t')
3455                       *x++ = *y++;
3456                   else if (*y == ' ' || *y == '\t')
3457                     /* Copy whitespace to the result.  */
3458                     *x++ = *y++;
3459                   /* Don't copy other options.  */
3460                   else
3461                     y++;
3462                 }
3463
3464               *x = 0;
3465
3466               value = do_spec_1 (buf, 0, NULL_PTR);
3467               if (value != 0)
3468                 return value;
3469             }
3470             break;
3471
3472           case 'S':
3473             value = do_spec_1 (startfile_spec, 0, NULL_PTR);
3474             if (value != 0)
3475               return value;
3476             break;
3477
3478             /* Here we define characters other than letters and digits.  */
3479
3480           case '{':
3481             p = handle_braces (p);
3482             if (p == 0)
3483               return -1;
3484             break;
3485
3486           case '%':
3487             obstack_1grow (&obstack, '%');
3488             break;
3489
3490           case '*':
3491             do_spec_1 (soft_matched_part, 1, NULL_PTR);
3492             do_spec_1 (" ", 0, NULL_PTR);
3493             break;
3494
3495             /* Process a string found as the value of a spec given by name.
3496                This feature allows individual machine descriptions
3497                to add and use their own specs.
3498                %[...] modifies -D options the way %P does;
3499                %(...) uses the spec unmodified.  */
3500           case '(':
3501           case '[':
3502             {
3503               char *name = p;
3504               struct spec_list *sl;
3505               int len;
3506
3507               /* The string after the S/P is the name of a spec that is to be
3508                  processed.  */
3509               while (*p && *p != ')' && *p != ']')
3510                 p++;
3511
3512               /* See if it's in the list */
3513               for (len = p - name, sl = specs; sl; sl = sl->next)
3514                 if (strncmp (sl->name, name, len) == 0 && !sl->name[len])
3515                   {
3516                     name = sl->spec;
3517                     break;
3518                   }
3519
3520               if (sl)
3521                 {
3522                   if (c == '(')
3523                     {
3524                       value = do_spec_1 (name, 0, NULL_PTR);
3525                       if (value != 0)
3526                         return value;
3527                     }
3528                   else
3529                     {
3530                       char *x = (char *) alloca (strlen (name) * 2 + 1);
3531                       char *buf = x;
3532                       char *y = name;
3533
3534                       /* Copy all of NAME into BUF, but put __ after
3535                          every -D and at the end of each arg,  */
3536                       while (1)
3537                         {
3538                           if (! strncmp (y, "-D", 2))
3539                             {
3540                               *x++ = '-';
3541                               *x++ = 'D';
3542                               *x++ = '_';
3543                               *x++ = '_';
3544                               y += 2;
3545                             }
3546                           else if (*y == ' ' || *y == 0)
3547                             {
3548                               *x++ = '_';
3549                               *x++ = '_';
3550                               if (*y == 0)
3551                                 break;
3552                               else
3553                                 *x++ = *y++;
3554                             }
3555                           else
3556                             *x++ = *y++;
3557                         }
3558                       *x = 0;
3559
3560                       value = do_spec_1 (buf, 0, NULL_PTR);
3561                       if (value != 0)
3562                         return value;
3563                     }
3564                 }
3565
3566               /* Discard the closing paren or bracket.  */
3567               if (*p)
3568                 p++;
3569             }
3570             break;
3571
3572           case 'v':
3573             {
3574               int c1 = *p++;  /* Select first or second version number.  */
3575               char *v = compiler_version;
3576               char *q;
3577
3578               /* The format of the version string is
3579                  ([^0-9]*-)?[0-9]+[.][0-9]+([.][0-9]+)?([- ].*)?  */
3580
3581               /* Ignore leading non-digits.  i.e. "foo-" in "foo-2.7.2".  */
3582               while (! isdigit (*v))
3583                 v++;
3584               if (v > compiler_version && v[-1] != '-')
3585                 abort ();
3586
3587               /* If desired, advance to second version number.  */
3588               if (c1 == '2')
3589                 {
3590                   /* Set V after the first period.  */
3591                   while (isdigit (*v))
3592                     v++;
3593                   if (*v != '.')
3594                     abort ();
3595                   v++;
3596                 }
3597
3598               /* Set Q at the next period or at the end.  */
3599               q = v;
3600               while (isdigit (*q))
3601                 q++;
3602               if (*q != 0 && *q != ' ' && *q != '.' && *q != '-')
3603                 abort ();
3604
3605               /* Put that part into the command.  */
3606               obstack_grow (&obstack, v, q - v);
3607               arg_going = 1;
3608             }
3609             break;
3610
3611           case '|':
3612             if (input_from_pipe)
3613               do_spec_1 ("-", 0, NULL_PTR);
3614             break;
3615
3616           default:
3617             abort ();
3618           }
3619         break;
3620
3621       case '\\':
3622         /* Backslash: treat next character as ordinary.  */
3623         c = *p++;
3624
3625         /* fall through */
3626       default:
3627         /* Ordinary character: put it into the current argument.  */
3628         obstack_1grow (&obstack, c);
3629         arg_going = 1;
3630       }
3631
3632   return 0;             /* End of string */
3633 }
3634
3635 /* Return 0 if we call do_spec_1 and that returns -1.  */
3636
3637 static char *
3638 handle_braces (p)
3639      register char *p;
3640 {
3641   register char *q;
3642   char *filter;
3643   int pipe_p = 0;
3644   int negate = 0;
3645   int suffix = 0;
3646
3647   if (*p == '|')
3648     /* A `|' after the open-brace means,
3649        if the test fails, output a single minus sign rather than nothing.
3650        This is used in %{|!pipe:...}.  */
3651     pipe_p = 1, ++p;
3652
3653   if (*p == '!')
3654     /* A `!' after the open-brace negates the condition:
3655        succeed if the specified switch is not present.  */
3656     negate = 1, ++p;
3657
3658   if (*p == '.')
3659     /* A `.' after the open-brace means test against the current suffix.  */
3660     {
3661       if (pipe_p)
3662         abort ();
3663
3664       suffix = 1;
3665       ++p;
3666     }
3667
3668   filter = p;
3669   while (*p != ':' && *p != '}') p++;
3670   if (*p != '}')
3671     {
3672       register int count = 1;
3673       q = p + 1;
3674       while (count > 0)
3675         {
3676           if (*q == '{')
3677             count++;
3678           else if (*q == '}')
3679             count--;
3680           else if (*q == 0)
3681             abort ();
3682           q++;
3683         }
3684     }
3685   else
3686     q = p + 1;
3687
3688   if (suffix)
3689     {
3690       int found = (input_suffix != 0
3691                    && strlen (input_suffix) == p - filter
3692                    && strncmp (input_suffix, filter, p - filter) == 0);
3693
3694       if (p[0] == '}')
3695         abort ();
3696
3697       if (negate != found
3698           && do_spec_1 (save_string (p + 1, q - p - 2), 0, NULL_PTR) < 0)
3699         return 0;
3700
3701       return q;
3702     }
3703   else if (p[-1] == '*' && p[0] == '}')
3704     {
3705       /* Substitute all matching switches as separate args.  */
3706       register int i;
3707       --p;
3708       for (i = 0; i < n_switches; i++)
3709         if (!strncmp (switches[i].part1, filter, p - filter)
3710             && check_live_switch (i, p - filter))
3711           give_switch (i, 0);
3712     }
3713   else
3714     {
3715       /* Test for presence of the specified switch.  */
3716       register int i;
3717       int present = 0;
3718
3719       /* If name specified ends in *, as in {x*:...},
3720          check for %* and handle that case.  */
3721       if (p[-1] == '*' && !negate)
3722         {
3723           int substitution;
3724           char *r = p;
3725
3726           /* First see whether we have %*.  */
3727           substitution = 0;
3728           while (r < q)
3729             {
3730               if (*r == '%' && r[1] == '*')
3731                 substitution = 1;
3732               r++;
3733             }
3734           /* If we do, handle that case.  */
3735           if (substitution)
3736             {
3737               /* Substitute all matching switches as separate args.
3738                  But do this by substituting for %*
3739                  in the text that follows the colon.  */
3740
3741               unsigned hard_match_len = p - filter - 1;
3742               char *string = save_string (p + 1, q - p - 2);
3743
3744               for (i = 0; i < n_switches; i++)
3745                 if (!strncmp (switches[i].part1, filter, hard_match_len)
3746                     && check_live_switch (i, -1))
3747                   {
3748                     do_spec_1 (string, 0, &switches[i].part1[hard_match_len]);
3749                     /* Pass any arguments this switch has.  */
3750                     give_switch (i, 1);
3751                   }
3752
3753               return q;
3754             }
3755         }
3756
3757       /* If name specified ends in *, as in {x*:...},
3758          check for presence of any switch name starting with x.  */
3759       if (p[-1] == '*')
3760         {
3761           for (i = 0; i < n_switches; i++)
3762             {
3763               unsigned hard_match_len = p - filter - 1;
3764
3765               if (!strncmp (switches[i].part1, filter, hard_match_len)
3766                   && check_live_switch (i, hard_match_len))
3767                 {
3768                   present = 1;
3769                 }
3770             }
3771         }
3772       /* Otherwise, check for presence of exact name specified.  */
3773       else
3774         {
3775           for (i = 0; i < n_switches; i++)
3776             {
3777               if (!strncmp (switches[i].part1, filter, p - filter)
3778                   && switches[i].part1[p - filter] == 0
3779                   && check_live_switch (i, -1))
3780                 {
3781                   present = 1;
3782                   break;
3783                 }
3784             }
3785         }
3786
3787       /* If it is as desired (present for %{s...}, absent for %{-s...})
3788          then substitute either the switch or the specified
3789          conditional text.  */
3790       if (present != negate)
3791         {
3792           if (*p == '}')
3793             {
3794               give_switch (i, 0);
3795             }
3796           else
3797             {
3798               if (do_spec_1 (save_string (p + 1, q - p - 2), 0, NULL_PTR) < 0)
3799                 return 0;
3800             }
3801         }
3802       else if (pipe_p)
3803         {
3804           /* Here if a %{|...} conditional fails: output a minus sign,
3805              which means "standard output" or "standard input".  */
3806           do_spec_1 ("-", 0, NULL_PTR);
3807         }
3808     }
3809
3810   return q;
3811 }
3812 \f
3813 /* Return 0 iff switch number SWITCHNUM is obsoleted by a later switch
3814    on the command line.  PREFIX_LENGTH is the length of XXX in an {XXX*}
3815    spec, or -1 if either exact match or %* is used.
3816
3817    A -O switch is obsoleted by a later -O switch.  A -f, -m, or -W switch
3818    whose value does not begin with "no-" is obsoleted by the same value
3819    with the "no-", similarly for a switch with the "no-" prefix.  */
3820
3821 static int
3822 check_live_switch (switchnum, prefix_length)
3823      int switchnum;
3824      int prefix_length;
3825 {
3826   char *name = switches[switchnum].part1;
3827   int i;
3828
3829   /* In the common case of {<at-most-one-letter>*}, a negating
3830      switch would always match, so ignore that case.  We will just
3831      send the conflicting switches to the compiler phase.  */
3832   if (prefix_length >= 0 && prefix_length <= 1)
3833     return 1;
3834
3835   /* If we already processed this switch and determined if it was
3836      live or not, return our past determination.  */
3837   if (switches[switchnum].live_cond != 0)
3838     return switches[switchnum].live_cond > 0;
3839
3840   /* Now search for duplicate in a manner that depends on the name.  */
3841   switch (*name)
3842     {
3843     case 'O':
3844         for (i = switchnum + 1; i < n_switches; i++)
3845           if (switches[i].part1[0] == 'O')
3846             {
3847               switches[switchnum].valid = 1;
3848               switches[switchnum].live_cond = -1;
3849               return 0;
3850             }
3851       break;
3852
3853     case 'W':  case 'f':  case 'm':
3854       if (! strncmp (name + 1, "no-", 3))
3855         {
3856           /* We have Xno-YYY, search for XYYY.  */
3857           for (i = switchnum + 1; i < n_switches; i++)
3858             if (switches[i].part1[0] == name[0]
3859                 && ! strcmp (&switches[i].part1[1], &name[4]))
3860             {
3861               switches[switchnum].valid = 1;
3862               switches[switchnum].live_cond = -1;
3863               return 0;
3864             }
3865         }
3866       else
3867         {
3868           /* We have XYYY, search for Xno-YYY.  */
3869           for (i = switchnum + 1; i < n_switches; i++)
3870             if (switches[i].part1[0] == name[0]
3871                 && switches[i].part1[1] == 'n'
3872                 && switches[i].part1[2] == 'o'
3873                 && switches[i].part1[3] == '-'
3874                 && !strcmp (&switches[i].part1[4], &name[1]))
3875             {
3876               switches[switchnum].valid = 1;
3877               switches[switchnum].live_cond = -1;
3878               return 0;
3879             }
3880         }
3881       break;
3882     }
3883
3884   /* Otherwise the switch is live.  */
3885   switches[switchnum].live_cond = 1;
3886   return 1;
3887 }
3888 \f
3889 /* Pass a switch to the current accumulating command
3890    in the same form that we received it.
3891    SWITCHNUM identifies the switch; it is an index into
3892    the vector of switches gcc received, which is `switches'.
3893    This cannot fail since it never finishes a command line.
3894
3895    If OMIT_FIRST_WORD is nonzero, then we omit .part1 of the argument.  */
3896
3897 static void
3898 give_switch (switchnum, omit_first_word)
3899      int switchnum;
3900      int omit_first_word;
3901 {
3902   if (!omit_first_word)
3903     {
3904       do_spec_1 ("-", 0, NULL_PTR);
3905       do_spec_1 (switches[switchnum].part1, 1, NULL_PTR);
3906     }
3907   do_spec_1 (" ", 0, NULL_PTR);
3908   if (switches[switchnum].args != 0)
3909     {
3910       char **p;
3911       for (p = switches[switchnum].args; *p; p++)
3912         {
3913           do_spec_1 (*p, 1, NULL_PTR);
3914           do_spec_1 (" ", 0, NULL_PTR);
3915         }
3916     }
3917   switches[switchnum].valid = 1;
3918 }
3919 \f
3920 /* Search for a file named NAME trying various prefixes including the
3921    user's -B prefix and some standard ones.
3922    Return the absolute file name found.  If nothing is found, return NAME.  */
3923
3924 static char *
3925 find_file (name)
3926      char *name;
3927 {
3928   char *newname;
3929
3930   /* Try multilib_dir if it is defined.  */
3931   if (multilib_dir != NULL)
3932     {
3933       char *try;
3934
3935       try = (char *) alloca (strlen (multilib_dir) + strlen (name) + 2);
3936       strcpy (try, multilib_dir);
3937       strcat (try, dir_separator_str);
3938       strcat (try, name);
3939
3940       newname = find_a_file (&startfile_prefixes, try, R_OK);
3941
3942       /* If we don't find it in the multi library dir, then fall
3943          through and look for it in the normal places.  */
3944       if (newname != NULL)
3945         return newname;
3946     }
3947
3948   newname = find_a_file (&startfile_prefixes, name, R_OK);
3949   return newname ? newname : name;
3950 }
3951
3952 /* Determine whether a directory exists.  If LINKER, return 0 for
3953    certain fixed names not needed by the linker.  If not LINKER, it is
3954    only important to return 0 if the host machine has a small ARG_MAX
3955    limit.  */
3956
3957 static int
3958 is_directory (path1, path2, linker)
3959      char *path1;
3960      char *path2;
3961      int linker;
3962 {
3963   int len1 = strlen (path1);
3964   int len2 = strlen (path2);
3965   char *path = (char *) alloca (3 + len1 + len2);
3966   char *cp;
3967   struct stat st;
3968
3969 #ifndef SMALL_ARG_MAX
3970   if (! linker)
3971     return 1;
3972 #endif
3973
3974   /* Construct the path from the two parts.  Ensure the string ends with "/.".
3975      The resulting path will be a directory even if the given path is a
3976      symbolic link.  */
3977   bcopy (path1, path, len1);
3978   bcopy (path2, path + len1, len2);
3979   cp = path + len1 + len2;
3980   if (cp[-1] != '/' && cp[-1] != DIR_SEPARATOR)
3981     *cp++ = DIR_SEPARATOR;
3982   *cp++ = '.';
3983   *cp = '\0';
3984
3985   /* Exclude directories that the linker is known to search.  */
3986   if (linker
3987       && ((cp - path == 6
3988            && strcmp (path, concat (dir_separator_str, "lib", 
3989                                     dir_separator_str, ".", NULL_PTR)) == 0)
3990           || (cp - path == 10
3991               && strcmp (path, concat (dir_separator_str, "usr", 
3992                                        dir_separator_str, "lib", 
3993                                        dir_separator_str, ".", NULL_PTR)) == 0)))
3994     return 0;
3995
3996   return (stat (path, &st) >= 0 && S_ISDIR (st.st_mode));
3997 }
3998 \f
3999 /* On fatal signals, delete all the temporary files.  */
4000
4001 static void
4002 fatal_error (signum)
4003      int signum;
4004 {
4005   signal (signum, SIG_DFL);
4006   delete_failure_queue ();
4007   delete_temp_files ();
4008   /* Get the same signal again, this time not handled,
4009      so its normal effect occurs.  */
4010   kill (getpid (), signum);
4011 }
4012
4013 int
4014 main (argc, argv)
4015      int argc;
4016      char **argv;
4017 {
4018   register int i;
4019   int j;
4020   int value;
4021   int linker_was_run = 0;
4022   char *explicit_link_files;
4023   char *specs_file;
4024   char *p;
4025
4026   p = argv[0] + strlen (argv[0]);
4027   while (p != argv[0] && p[-1] != '/' && p[-1] != DIR_SEPARATOR) --p;
4028   programname = p;
4029
4030   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
4031     signal (SIGINT, fatal_error);
4032 #ifdef SIGHUP
4033   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
4034     signal (SIGHUP, fatal_error);
4035 #endif
4036   if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
4037     signal (SIGTERM, fatal_error);
4038 #ifdef SIGPIPE
4039   if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
4040     signal (SIGPIPE, fatal_error);
4041 #endif
4042
4043   argbuf_length = 10;
4044   argbuf = (char **) xmalloc (argbuf_length * sizeof (char *));
4045
4046   obstack_init (&obstack);
4047
4048   /* Build multilib_select, et. al from the separate lines that make up each
4049      multilib selection.  */
4050   {
4051     char **q = multilib_raw;
4052     int need_space;
4053
4054     obstack_init (&multilib_obstack);
4055     while ((p = *q++) != (char *) 0)
4056       obstack_grow (&multilib_obstack, p, strlen (p));
4057
4058     obstack_1grow (&multilib_obstack, 0);
4059     multilib_select = obstack_finish (&multilib_obstack);
4060
4061     q = multilib_matches_raw;
4062     while ((p = *q++) != (char *) 0)
4063       obstack_grow (&multilib_obstack, p, strlen (p));
4064
4065     obstack_1grow (&multilib_obstack, 0);
4066     multilib_matches = obstack_finish (&multilib_obstack);
4067
4068     need_space = FALSE;
4069     for (i = 0;
4070          i < sizeof (multilib_defaults_raw) / sizeof (multilib_defaults_raw[0]);
4071          i++)
4072       {
4073         if (need_space)
4074           obstack_1grow (&multilib_obstack, ' ');
4075         obstack_grow (&multilib_obstack,
4076                       multilib_defaults_raw[i],
4077                       strlen (multilib_defaults_raw[i]));
4078         need_space = TRUE;
4079       }
4080
4081     obstack_1grow (&multilib_obstack, 0);
4082     multilib_defaults = obstack_finish (&multilib_obstack);
4083   }
4084
4085   /* Set up to remember the pathname of gcc and any options
4086      needed for collect.  We use argv[0] instead of programname because
4087      we need the complete pathname.  */
4088   obstack_init (&collect_obstack);
4089   obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=")-1);
4090   obstack_grow (&collect_obstack, argv[0], strlen (argv[0])+1);
4091   putenv (obstack_finish (&collect_obstack));
4092
4093 #ifdef INIT_ENVIRONMENT
4094   /* Set up any other necessary machine specific environment variables.  */
4095   putenv (INIT_ENVIRONMENT);
4096 #endif
4097
4098   /* Choose directory for temp files.  */
4099
4100   temp_filename = choose_temp_base ();
4101   temp_filename_length = strlen (temp_filename);
4102
4103   /* Make a table of what switches there are (switches, n_switches).
4104      Make a table of specified input files (infiles, n_infiles).
4105      Decode switches that are handled locally.  */
4106
4107   process_command (argc, argv);
4108
4109   /* Initialize the vector of specs to just the default.
4110      This means one element containing 0s, as a terminator.  */
4111
4112   compilers = (struct compiler *) xmalloc (sizeof default_compilers);
4113   bcopy ((char *) default_compilers, (char *) compilers,
4114          sizeof default_compilers);
4115   n_compilers = n_default_compilers;
4116
4117   /* Read specs from a file if there is one.  */
4118
4119   machine_suffix = concat (spec_machine, dir_separator_str,
4120                            spec_version, dir_separator_str, NULL_PTR);
4121   just_machine_suffix = concat (spec_machine, dir_separator_str, NULL_PTR);
4122
4123   specs_file = find_a_file (&startfile_prefixes, "specs", R_OK);
4124   /* Read the specs file unless it is a default one.  */
4125   if (specs_file != 0 && strcmp (specs_file, "specs"))
4126     read_specs (specs_file);
4127
4128 #ifdef EXTRA_SPECS
4129   else
4130     {
4131       int k;
4132       for (k = 0; k < sizeof (extra_specs) / sizeof (extra_specs[0]); k++)
4133         set_spec (extra_specs[k].name, extra_specs[k].spec);
4134     }
4135 #endif
4136
4137   /* If not cross-compiling, look for startfiles in the standard places.  */
4138   /* The fact that these are done here, after reading the specs file,
4139      means that it cannot be found in these directories.
4140      But that's okay.  It should never be there anyway.  */
4141   if (!cross_compile)
4142     {
4143 #ifdef MD_EXEC_PREFIX
4144       add_prefix (&exec_prefixes, md_exec_prefix, 0, 0, NULL_PTR);
4145       add_prefix (&startfile_prefixes, md_exec_prefix, 0, 0, NULL_PTR);
4146 #endif
4147
4148 #ifdef MD_STARTFILE_PREFIX
4149       add_prefix (&startfile_prefixes, md_startfile_prefix, 0, 0, NULL_PTR);
4150 #endif
4151
4152 #ifdef MD_STARTFILE_PREFIX_1
4153       add_prefix (&startfile_prefixes, md_startfile_prefix_1, 0, 0, NULL_PTR);
4154 #endif
4155
4156       /* If standard_startfile_prefix is relative, base it on
4157          standard_exec_prefix.  This lets us move the installed tree
4158          as a unit.  If GCC_EXEC_PREFIX is defined, base
4159          standard_startfile_prefix on that as well.  */
4160       if (*standard_startfile_prefix == '/'
4161           || *standard_startfile_prefix == DIR_SEPARATOR)
4162         add_prefix (&startfile_prefixes, standard_startfile_prefix, 0, 0,
4163                     NULL_PTR);
4164       else
4165         {
4166           if (gcc_exec_prefix)
4167             add_prefix (&startfile_prefixes,
4168                         concat (gcc_exec_prefix, machine_suffix,
4169                                 standard_startfile_prefix, NULL_PTR),
4170                         0, 0, NULL_PTR);
4171           add_prefix (&startfile_prefixes,
4172                       concat (standard_exec_prefix,
4173                               machine_suffix,
4174                               standard_startfile_prefix, NULL_PTR),
4175                       0, 0, NULL_PTR);
4176         }                      
4177
4178       add_prefix (&startfile_prefixes, standard_startfile_prefix_1, 0, 0,
4179                   NULL_PTR);
4180       add_prefix (&startfile_prefixes, standard_startfile_prefix_2, 0, 0,
4181                   NULL_PTR);
4182 #if 0 /* Can cause surprises, and one can use -B./ instead.  */
4183       add_prefix (&startfile_prefixes, "./", 0, 1, NULL_PTR);
4184 #endif
4185     }
4186   else
4187     {
4188       if (*standard_startfile_prefix != DIR_SEPARATOR && gcc_exec_prefix)
4189         add_prefix (&startfile_prefixes,
4190                     concat (gcc_exec_prefix, machine_suffix,
4191                             standard_startfile_prefix, NULL_PTR),
4192                     0, 0, NULL_PTR);
4193     }
4194
4195   /* If we have a GCC_EXEC_PREFIX envvar, modify it for cpp's sake.  */
4196   if (gcc_exec_prefix)
4197     {
4198       char * temp = (char *) xmalloc (strlen (gcc_exec_prefix)
4199                                       + strlen (spec_version)
4200                                       + strlen (spec_machine) + 3);
4201       strcpy (temp, gcc_exec_prefix);
4202       strcat (temp, spec_machine);
4203       strcat (temp, dir_separator_str);
4204       strcat (temp, spec_version);
4205       strcat (temp, dir_separator_str);
4206       gcc_exec_prefix = temp;
4207     }
4208
4209   /* Now we have the specs.
4210      Set the `valid' bits for switches that match anything in any spec.  */
4211
4212   validate_all_switches ();
4213
4214   /* Now that we have the switches and the specs, set
4215      the subdirectory based on the options.  */
4216   set_multilib_dir ();
4217
4218   /* Warn about any switches that no pass was interested in.  */
4219
4220   for (i = 0; i < n_switches; i++)
4221     if (! switches[i].valid)
4222       error ("unrecognized option `-%s'", switches[i].part1);
4223
4224   /* Obey some of the options.  */
4225
4226   if (print_search_dirs)
4227     {
4228       printf ("install: %s%s\n", standard_exec_prefix, machine_suffix);
4229       printf ("programs: %s\n", build_search_list (&exec_prefixes, "", 0));
4230       printf ("libraries: %s\n", build_search_list (&startfile_prefixes, "", 0));
4231       exit (0);
4232     }
4233
4234   if (print_file_name)
4235     {
4236       printf ("%s\n", find_file (print_file_name));
4237       exit (0);
4238     }
4239
4240   if (print_prog_name)
4241     {
4242       char *newname = find_a_file (&exec_prefixes, print_prog_name, X_OK);
4243       printf ("%s\n", (newname ? newname : print_prog_name));
4244       exit (0);
4245     }
4246
4247   if (print_multi_lib)
4248     {
4249       print_multilib_info ();
4250       exit (0);
4251     }
4252
4253   if (print_multi_directory)
4254     {
4255       if (multilib_dir == NULL)
4256         printf (".\n");
4257       else
4258         printf ("%s\n", multilib_dir);
4259       exit (0);
4260     }
4261
4262   if (verbose_flag)
4263     {
4264       if (! strcmp (version_string, compiler_version))
4265         fprintf (stderr, "gcc version %s\n", version_string);
4266       else
4267         fprintf (stderr, "gcc driver version %s executing gcc version %s\n",
4268                  version_string, compiler_version);
4269
4270       if (n_infiles == 0)
4271         exit (0);
4272     }
4273
4274   if (n_infiles == 0)
4275     fatal ("No input files");
4276
4277   /* Make a place to record the compiler output file names
4278      that correspond to the input files.  */
4279
4280   outfiles = (char **) xmalloc (n_infiles * sizeof (char *));
4281   bzero ((char *) outfiles, n_infiles * sizeof (char *));
4282
4283   /* Record which files were specified explicitly as link input.  */
4284
4285   explicit_link_files = xmalloc (n_infiles);
4286   bzero (explicit_link_files, n_infiles);
4287
4288   for (i = 0; i < n_infiles; i++)
4289     {
4290       register struct compiler *cp = 0;
4291       int this_file_error = 0;
4292
4293       /* Tell do_spec what to substitute for %i.  */
4294
4295       input_filename = infiles[i].name;
4296       input_filename_length = strlen (input_filename);
4297       input_file_number = i;
4298
4299       /* Use the same thing in %o, unless cp->spec says otherwise.  */
4300
4301       outfiles[i] = input_filename;
4302
4303       /* Figure out which compiler from the file's suffix.  */
4304
4305       cp = lookup_compiler (infiles[i].name, input_filename_length,
4306                             infiles[i].language);
4307
4308       if (cp)
4309         {
4310           /* Ok, we found an applicable compiler.  Run its spec.  */
4311           /* First say how much of input_filename to substitute for %b  */
4312           register char *p;
4313           int len;
4314
4315           if (cp->spec[0][0] == '#')
4316             error ("%s: %s compiler not installed on this system",
4317                    input_filename, &cp->spec[0][1]);
4318
4319           input_basename = input_filename;
4320           for (p = input_filename; *p; p++)
4321             if (*p == '/' || *p == DIR_SEPARATOR)
4322               input_basename = p + 1;
4323
4324           /* Find a suffix starting with the last period,
4325              and set basename_length to exclude that suffix.  */
4326           basename_length = strlen (input_basename);
4327           p = input_basename + basename_length;
4328           while (p != input_basename && *p != '.') --p;
4329           if (*p == '.' && p != input_basename)
4330             {
4331               basename_length = p - input_basename;
4332               input_suffix = p + 1;
4333             }
4334           else
4335             input_suffix = "";
4336
4337           len = 0;
4338           for (j = 0; j < sizeof cp->spec / sizeof cp->spec[0]; j++)
4339             if (cp->spec[j])
4340               len += strlen (cp->spec[j]);
4341
4342           p = (char *) xmalloc (len + 1);
4343
4344           len = 0;
4345           for (j = 0; j < sizeof cp->spec / sizeof cp->spec[0]; j++)
4346             if (cp->spec[j])
4347               {
4348                 strcpy (p + len, cp->spec[j]);
4349                 len += strlen (cp->spec[j]);
4350               }
4351
4352           value = do_spec (p);
4353           free (p);
4354           if (value < 0)
4355             this_file_error = 1;
4356         }
4357
4358       /* If this file's name does not contain a recognized suffix,
4359          record it as explicit linker input.  */
4360
4361       else
4362         explicit_link_files[i] = 1;
4363
4364       /* Clear the delete-on-failure queue, deleting the files in it
4365          if this compilation failed.  */
4366
4367       if (this_file_error)
4368         {
4369           delete_failure_queue ();
4370           error_count++;
4371         }
4372       /* If this compilation succeeded, don't delete those files later.  */
4373       clear_failure_queue ();
4374     }
4375
4376   /* Run ld to link all the compiler output files.  */
4377
4378   if (error_count == 0)
4379     {
4380       int tmp = execution_count;
4381       int i;
4382       int first_time;
4383
4384       /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
4385          for collect.  */
4386       putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH=");
4387       putenv_from_prefixes (&startfile_prefixes, "LIBRARY_PATH=");
4388
4389       /* Build COLLECT_GCC_OPTIONS to have all of the options specified to
4390          the compiler.  */
4391       obstack_grow (&collect_obstack, "COLLECT_GCC_OPTIONS=",
4392                     sizeof ("COLLECT_GCC_OPTIONS=")-1);
4393
4394       first_time = TRUE;
4395       for (i = 0; i < n_switches; i++)
4396         {
4397           char **args;
4398           if (!first_time)
4399             obstack_grow (&collect_obstack, " ", 1);
4400
4401           first_time = FALSE;
4402           obstack_grow (&collect_obstack, "-", 1);
4403           obstack_grow (&collect_obstack, switches[i].part1,
4404                         strlen (switches[i].part1));
4405
4406           for (args = switches[i].args; args && *args; args++)
4407             {
4408               obstack_grow (&collect_obstack, " ", 1);
4409               obstack_grow (&collect_obstack, *args, strlen (*args));
4410             }
4411         }
4412       obstack_grow (&collect_obstack, "\0", 1);
4413       putenv (obstack_finish (&collect_obstack));
4414
4415       value = do_spec (link_command_spec);
4416       if (value < 0)
4417         error_count = 1;
4418       linker_was_run = (tmp != execution_count);
4419     }
4420
4421   /* Warn if a -B option was specified but the prefix was never used.  */
4422   unused_prefix_warnings (&exec_prefixes);
4423   unused_prefix_warnings (&startfile_prefixes);
4424
4425   /* If options said don't run linker,
4426      complain about input files to be given to the linker.  */
4427
4428   if (! linker_was_run && error_count == 0)
4429     for (i = 0; i < n_infiles; i++)
4430       if (explicit_link_files[i])
4431         error ("%s: linker input file unused since linking not done",
4432                outfiles[i]);
4433
4434   /* Delete some or all of the temporary files we made.  */
4435
4436   if (error_count)
4437     delete_failure_queue ();
4438   delete_temp_files ();
4439
4440   exit (error_count > 0 ? (signal_count ? 2 : 1) : 0);
4441   /* NOTREACHED */
4442   return 0;
4443 }
4444
4445 /* Find the proper compilation spec for the file name NAME,
4446    whose length is LENGTH.  LANGUAGE is the specified language,
4447    or 0 if none specified.  */
4448
4449 static struct compiler *
4450 lookup_compiler (name, length, language)
4451      char *name;
4452      int length;
4453      char *language;
4454 {
4455   struct compiler *cp;
4456
4457   /* Look for the language, if one is spec'd.  */
4458   if (language != 0)
4459     {
4460       for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
4461         {
4462           if (language != 0)
4463             {
4464               if (cp->suffix[0] == '@'
4465                   && !strcmp (cp->suffix + 1, language))
4466                 return cp;
4467             }
4468         }
4469       error ("language %s not recognized", language);
4470     }
4471
4472   /* Look for a suffix.  */
4473   for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
4474     {
4475       if (/* The suffix `-' matches only the file name `-'.  */
4476           (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
4477           ||
4478           (strlen (cp->suffix) < length
4479            /* See if the suffix matches the end of NAME.  */
4480 #ifdef OS2
4481            && (!strcmp (cp->suffix,
4482                         name + length - strlen (cp->suffix))
4483             || !strpbrk (cp->suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
4484              && !strcasecmp (cp->suffix,
4485                           name + length - strlen (cp->suffix)))))
4486 #else
4487            && !strcmp (cp->suffix,
4488                        name + length - strlen (cp->suffix))))
4489 #endif
4490         {
4491           if (cp->spec[0][0] == '@')
4492             {
4493               struct compiler *new;
4494               /* An alias entry maps a suffix to a language.
4495                  Search for the language; pass 0 for NAME and LENGTH
4496                  to avoid infinite recursion if language not found.
4497                  Construct the new compiler spec.  */
4498               language = cp->spec[0] + 1;
4499               new = (struct compiler *) xmalloc (sizeof (struct compiler));
4500               new->suffix = cp->suffix;
4501               bcopy ((char *) lookup_compiler (NULL_PTR, 0, language)->spec,
4502                      (char *) new->spec, sizeof new->spec);
4503               return new;
4504             }
4505           /* A non-alias entry: return it.  */
4506           return cp;
4507         }
4508     }
4509
4510   return 0;
4511 }
4512 \f
4513 char *
4514 xmalloc (size)
4515      unsigned size;
4516 {
4517   register char *value = (char *) malloc (size);
4518   if (value == 0)
4519     fatal ("virtual memory exhausted");
4520   return value;
4521 }
4522
4523 char *
4524 xrealloc (ptr, size)
4525      char *ptr;
4526      unsigned size;
4527 {
4528   register char *value = (char *) realloc (ptr, size);
4529   if (value == 0)
4530     fatal ("virtual memory exhausted");
4531   return value;
4532 }
4533
4534 /* This function is based on the one in libiberty.  */
4535
4536 static char *
4537 concat VPROTO((char *first, ...))
4538 {
4539   register int length;
4540   register char *newstr;
4541   register char *end;
4542   register char *arg;
4543   va_list args;
4544 #ifndef __STDC__
4545   char *first;
4546 #endif
4547
4548   /* First compute the size of the result and get sufficient memory.  */
4549
4550   VA_START (args, first);
4551 #ifndef __STDC__
4552   first = va_arg (args, char *);
4553 #endif
4554
4555   arg = first;
4556   length = 0;
4557
4558   while (arg != 0)
4559     {
4560       length += strlen (arg);
4561       arg = va_arg (args, char *);
4562     }
4563
4564   newstr = (char *) xmalloc (length + 1);
4565   va_end (args);
4566
4567   /* Now copy the individual pieces to the result string.  */
4568
4569   VA_START (args, first);
4570 #ifndef __STDC__
4571   first = va_arg (args, char *);
4572 #endif
4573
4574   end = newstr;
4575   arg = first;
4576   while (arg != 0)
4577     {
4578       while (*arg)
4579         *end++ = *arg++;
4580       arg = va_arg (args, char *);
4581     }
4582   *end = '\000';
4583   va_end (args);
4584
4585   return (newstr);
4586 }
4587
4588 static char *
4589 save_string (s, len)
4590      char *s;
4591      int len;
4592 {
4593   register char *result = xmalloc (len + 1);
4594
4595   bcopy (s, result, len);
4596   result[len] = 0;
4597   return result;
4598 }
4599
4600 static void
4601 pfatal_with_name (name)
4602      char *name;
4603 {
4604   fatal ("%s: %s", name, my_strerror (errno));
4605 }
4606
4607 static void
4608 perror_with_name (name)
4609      char *name;
4610 {
4611   error ("%s: %s", name, my_strerror (errno));
4612 }
4613
4614 static void
4615 pfatal_pexecute (errmsg_fmt, errmsg_arg)
4616      char *errmsg_fmt;
4617      char *errmsg_arg;
4618 {
4619   if (errmsg_arg)
4620     {
4621       /* Space for trailing '\0' is in %s.  */
4622       char *msg = xmalloc (strlen (errmsg_fmt) + strlen (errmsg_arg));
4623       sprintf (msg, errmsg_fmt, errmsg_arg);
4624       errmsg_fmt = msg;
4625     }
4626
4627   fatal ("%s: %s", errmsg_fmt, my_strerror (errno));
4628 }
4629
4630 /* More 'friendly' abort that prints the line and file.
4631    config.h can #define abort fancy_abort if you like that sort of thing.  */
4632
4633 void
4634 fancy_abort ()
4635 {
4636   fatal ("Internal gcc abort.");
4637 }
4638 \f
4639 #ifdef HAVE_VPRINTF
4640
4641 /* Output an error message and exit */
4642
4643 static void
4644 fatal VPROTO((char *format, ...))
4645 {
4646 #ifndef __STDC__
4647   char *format;
4648 #endif
4649   va_list ap;
4650
4651   VA_START (ap, format);
4652
4653 #ifndef __STDC__
4654   format = va_arg (ap, char *);
4655 #endif
4656
4657   fprintf (stderr, "%s: ", programname);
4658   vfprintf (stderr, format, ap);
4659   va_end (ap);
4660   fprintf (stderr, "\n");
4661   delete_temp_files ();
4662   exit (1);
4663 }
4664
4665 static void
4666 error VPROTO((char *format, ...))
4667 {
4668 #ifndef __STDC__
4669   char *format;
4670 #endif
4671   va_list ap;
4672
4673   VA_START (ap, format);
4674
4675 #ifndef __STDC__
4676   format = va_arg (ap, char *);
4677 #endif
4678
4679   fprintf (stderr, "%s: ", programname);
4680   vfprintf (stderr, format, ap);
4681   va_end (ap);
4682
4683   fprintf (stderr, "\n");
4684 }
4685
4686 #else /* not HAVE_VPRINTF */
4687
4688 static void
4689 fatal (msg, arg1, arg2)
4690      char *msg, *arg1, *arg2;
4691 {
4692   error (msg, arg1, arg2);
4693   delete_temp_files ();
4694   exit (1);
4695 }
4696
4697 static void
4698 error (msg, arg1, arg2)
4699      char *msg, *arg1, *arg2;
4700 {
4701   fprintf (stderr, "%s: ", programname);
4702   fprintf (stderr, msg, arg1, arg2);
4703   fprintf (stderr, "\n");
4704 }
4705
4706 #endif /* not HAVE_VPRINTF */
4707
4708 \f
4709 static void
4710 validate_all_switches ()
4711 {
4712   struct compiler *comp;
4713   register char *p;
4714   register char c;
4715   struct spec_list *spec;
4716
4717   for (comp = compilers; comp->spec[0]; comp++)
4718     {
4719       int i;
4720       for (i = 0; i < sizeof comp->spec / sizeof comp->spec[0] && comp->spec[i]; i++)
4721         {
4722           p = comp->spec[i];
4723           while (c = *p++)
4724             if (c == '%' && *p == '{')
4725               /* We have a switch spec.  */
4726               validate_switches (p + 1);
4727         }
4728     }
4729
4730   /* look through the linked list of extra specs read from the specs file */
4731   for (spec = specs; spec ; spec = spec->next)
4732     {
4733       p = spec->spec;
4734       while (c = *p++)
4735         if (c == '%' && *p == '{')
4736           /* We have a switch spec.  */
4737           validate_switches (p + 1);
4738     }
4739
4740   p = link_command_spec;
4741   while (c = *p++)
4742     if (c == '%' && *p == '{')
4743       /* We have a switch spec.  */
4744       validate_switches (p + 1);
4745
4746   /* Now notice switches mentioned in the machine-specific specs.  */
4747
4748   p = asm_spec;
4749   while (c = *p++)
4750     if (c == '%' && *p == '{')
4751       /* We have a switch spec.  */
4752       validate_switches (p + 1);
4753
4754   p = asm_final_spec;
4755   while (c = *p++)
4756     if (c == '%' && *p == '{')
4757       /* We have a switch spec.  */
4758       validate_switches (p + 1);
4759
4760   p = cpp_spec;
4761   while (c = *p++)
4762     if (c == '%' && *p == '{')
4763       /* We have a switch spec.  */
4764       validate_switches (p + 1);
4765
4766   p = signed_char_spec;
4767   while (c = *p++)
4768     if (c == '%' && *p == '{')
4769       /* We have a switch spec.  */
4770       validate_switches (p + 1);
4771
4772   p = cc1_spec;
4773   while (c = *p++)
4774     if (c == '%' && *p == '{')
4775       /* We have a switch spec.  */
4776       validate_switches (p + 1);
4777
4778   p = cc1plus_spec;
4779   while (c = *p++)
4780     if (c == '%' && *p == '{')
4781       /* We have a switch spec.  */
4782       validate_switches (p + 1);
4783
4784   p = link_spec;
4785   while (c = *p++)
4786     if (c == '%' && *p == '{')
4787       /* We have a switch spec.  */
4788       validate_switches (p + 1);
4789
4790   p = lib_spec;
4791   while (c = *p++)
4792     if (c == '%' && *p == '{')
4793       /* We have a switch spec.  */
4794       validate_switches (p + 1);
4795
4796   p = libgcc_spec;
4797   while (c = *p++)
4798     if (c == '%' && *p == '{')
4799       /* We have a switch spec.  */
4800       validate_switches (p + 1);
4801
4802   p = startfile_spec;
4803   while (c = *p++)
4804     if (c == '%' && *p == '{')
4805       /* We have a switch spec.  */
4806       validate_switches (p + 1);
4807
4808 #ifdef EXTRA_SPECS
4809   {
4810     int i;
4811     for (i = 0; i < sizeof (extra_specs) / sizeof (extra_specs[0]); i++)
4812       {
4813         p = extra_specs[i].spec;
4814         while (c = *p++)
4815           if (c == '%' && *p == '{')
4816             /* We have a switch spec.  */
4817             validate_switches (p + 1);
4818       }
4819   }
4820 #endif
4821
4822 }
4823
4824 /* Look at the switch-name that comes after START
4825    and mark as valid all supplied switches that match it.  */
4826
4827 static void
4828 validate_switches (start)
4829      char *start;
4830 {
4831   register char *p = start;
4832   char *filter;
4833   register int i;
4834   int suffix = 0;
4835
4836   if (*p == '|')
4837     ++p;
4838
4839   if (*p == '!')
4840     ++p;
4841
4842   if (*p == '.')
4843     suffix = 1, ++p;
4844
4845   filter = p;
4846   while (*p != ':' && *p != '}') p++;
4847
4848   if (suffix)
4849     ;
4850   else if (p[-1] == '*')
4851     {
4852       /* Mark all matching switches as valid.  */
4853       --p;
4854       for (i = 0; i < n_switches; i++)
4855         if (!strncmp (switches[i].part1, filter, p - filter))
4856           switches[i].valid = 1;
4857     }
4858   else
4859     {
4860       /* Mark an exact matching switch as valid.  */
4861       for (i = 0; i < n_switches; i++)
4862         {
4863           if (!strncmp (switches[i].part1, filter, p - filter)
4864               && switches[i].part1[p - filter] == 0)
4865             switches[i].valid = 1;
4866         }
4867     }
4868 }
4869 \f
4870 /* Check whether a particular argument was used.  The first time we
4871    canonialize the switches to keep only the ones we care about.  */
4872
4873 static int
4874 used_arg (p, len)
4875      char *p;
4876      int len;
4877 {
4878   struct mswitchstr {
4879     char *str;
4880     char *replace;
4881     int len;
4882     int rep_len;
4883   };
4884
4885   static struct mswitchstr *mswitches;
4886   static int n_mswitches;
4887   int i, j;
4888
4889   if (!mswitches)
4890     {
4891       struct mswitchstr *matches;
4892       char *q;
4893       int cnt = (*multilib_matches != '\0');
4894
4895       /* Break multilib_matches into the component strings of string and replacement
4896          string */
4897       for (p = multilib_matches; *p != '\0'; p++)
4898         if (*p == ';')
4899           cnt++;
4900
4901       matches = (struct mswitchstr *) alloca ((sizeof (struct mswitchstr)) * cnt);
4902       i = 0;
4903       q = multilib_matches;
4904       while (*q != '\0')
4905         {
4906           matches[i].str = q;
4907           while (*q != ' ')
4908             {
4909               if (*q == '\0')
4910                 abort ();
4911               q++;
4912             }
4913           *q = '\0';
4914           matches[i].len = q - matches[i].str;
4915
4916           matches[i].replace = ++q;
4917           while (*q != ';' && *q != '\0')
4918             {
4919               if (*q == ' ')
4920                 abort ();
4921               q++;
4922             }
4923           matches[i].rep_len = q - matches[i].replace;
4924           i++;
4925           if (*q == ';')
4926             *q++ = '\0';
4927           else
4928             break;
4929         }
4930
4931       /* Now build a list of the replacement string for switches that we care about */
4932       mswitches = (struct mswitchstr *) xmalloc ((sizeof (struct mswitchstr)) * n_switches);
4933       for (i = 0; i < n_switches; i++)
4934         {
4935           int xlen = strlen (switches[i].part1);
4936           for (j = 0; j < cnt; j++)
4937             if (xlen == matches[j].len && ! strcmp (switches[i].part1, matches[j].str))
4938               {
4939                 mswitches[n_mswitches].str = matches[j].replace;
4940                 mswitches[n_mswitches].len = matches[j].rep_len;
4941                 mswitches[n_mswitches].replace = (char *)0;
4942                 mswitches[n_mswitches].rep_len = 0;
4943                 n_mswitches++;
4944                 break;
4945               }
4946         }
4947     }
4948
4949   for (i = 0; i < n_mswitches; i++)
4950     if (len == mswitches[i].len && ! strncmp (p, mswitches[i].str, len))
4951       return 1;
4952
4953   return 0;
4954 }
4955
4956 static int
4957 default_arg (p, len)
4958      char *p;
4959      int len;
4960 {
4961   char *start, *end;
4962   int i;
4963
4964   for (start = multilib_defaults; *start != '\0'; start = end+1)
4965     {
4966       while (*start == ' ' || *start == '\t')
4967         start++;
4968
4969       if (*start == '\0')
4970         break;
4971
4972       for (end = start+1; *end != ' ' && *end != '\t' && *end != '\0'; end++)
4973         ;
4974
4975       if ((end - start) == len && strncmp (p, start, len) == 0)
4976         return 1;
4977     }
4978
4979   return 0;
4980 }
4981
4982 /* Work out the subdirectory to use based on the
4983    options.  The format of multilib_select is a list of elements.
4984    Each element is a subdirectory name followed by a list of options
4985    followed by a semicolon.  gcc will consider each line in turn.  If
4986    none of the options beginning with an exclamation point are
4987    present, and all of the other options are present, that
4988    subdirectory will be used.  */
4989
4990 static void
4991 set_multilib_dir ()
4992 {
4993   char *p = multilib_select;
4994   int this_path_len;
4995   char *this_path, *this_arg;
4996   int not_arg;
4997   int ok;
4998
4999   while (*p != '\0')
5000     {
5001       /* Ignore newlines.  */
5002       if (*p == '\n')
5003         {
5004           ++p;
5005           continue;
5006         }
5007
5008       /* Get the initial path.  */
5009       this_path = p;
5010       while (*p != ' ')
5011         {
5012           if (*p == '\0')
5013             abort ();
5014           ++p;
5015         }
5016       this_path_len = p - this_path;
5017
5018       /* Check the arguments.  */
5019       ok = 1;
5020       ++p;
5021       while (*p != ';')
5022         {
5023           if (*p == '\0')
5024             abort ();
5025
5026           if (! ok)
5027             {
5028               ++p;
5029               continue;
5030             }
5031
5032           this_arg = p;
5033           while (*p != ' ' && *p != ';')
5034             {
5035               if (*p == '\0')
5036                 abort ();
5037               ++p;
5038             }
5039
5040           if (*this_arg != '!')
5041             not_arg = 0;
5042           else
5043             {
5044               not_arg = 1;
5045               ++this_arg;
5046             }
5047
5048           /* If this is a default argument, we can just ignore it.
5049              This is true even if this_arg begins with '!'.  Beginning
5050              with '!' does not mean that this argument is necessarily
5051              inappropriate for this library: it merely means that
5052              there is a more specific library which uses this
5053              argument.  If this argument is a default, we need not
5054              consider that more specific library.  */
5055           if (! default_arg (this_arg, p - this_arg))
5056             {
5057               ok = used_arg (this_arg, p - this_arg);
5058               if (not_arg)
5059                 ok = ! ok;
5060             }
5061
5062           if (*p == ' ')
5063             ++p;
5064         }
5065
5066       if (ok)
5067         {
5068           if (this_path_len != 1
5069               || this_path[0] != '.')
5070             {
5071               multilib_dir = xmalloc (this_path_len + 1);
5072               strncpy (multilib_dir, this_path, this_path_len);
5073               multilib_dir[this_path_len] = '\0';
5074             }
5075           break;
5076         }
5077
5078       ++p;
5079     }      
5080 }
5081
5082 /* Print out the multiple library subdirectory selection
5083    information.  This prints out a series of lines.  Each line looks
5084    like SUBDIRECTORY;@OPTION@OPTION, with as many options as is
5085    required.  Only the desired options are printed out, the negative
5086    matches.  The options are print without a leading dash.  There are
5087    no spaces to make it easy to use the information in the shell.
5088    Each subdirectory is printed only once.  This assumes the ordering
5089    generated by the genmultilib script.  */
5090
5091 static void
5092 print_multilib_info ()
5093 {
5094   char *p = multilib_select;
5095   char *last_path = 0, *this_path;
5096   int skip;
5097   int last_path_len = 0;
5098
5099   while (*p != '\0')
5100     {
5101       /* Ignore newlines.  */
5102       if (*p == '\n')
5103         {
5104           ++p;
5105           continue;
5106         }
5107
5108       /* Get the initial path.  */
5109       this_path = p;
5110       while (*p != ' ')
5111         {
5112           if (*p == '\0')
5113             abort ();
5114           ++p;
5115         }
5116
5117       /* If this is a duplicate, skip it.  */
5118       skip = (last_path != 0 && p - this_path == last_path_len
5119               && ! strncmp (last_path, this_path, last_path_len));
5120
5121       last_path = this_path;
5122       last_path_len = p - this_path;
5123
5124       /* If this directory requires any default arguments, we can skip
5125          it.  We will already have printed a directory identical to
5126          this one which does not require that default argument.  */
5127       if (! skip)
5128         {
5129           char *q;
5130
5131           q = p + 1;
5132           while (*q != ';')
5133             {
5134               char *arg;
5135
5136               if (*q == '\0')
5137                 abort ();
5138
5139               if (*q == '!')
5140                 arg = NULL;
5141               else
5142                 arg = q;
5143
5144               while (*q != ' ' && *q != ';')
5145                 {
5146                   if (*q == '\0')
5147                     abort ();
5148                   ++q;
5149                 }
5150
5151               if (arg != NULL
5152                   && default_arg (arg, q - arg))
5153                 {
5154                   skip = 1;
5155                   break;
5156                 }
5157
5158               if (*q == ' ')
5159                 ++q;
5160             }
5161         }
5162
5163       if (! skip)
5164         {
5165           char *p1;
5166
5167           for (p1 = last_path; p1 < p; p1++)
5168             putchar (*p1);
5169           putchar (';');
5170         }
5171
5172       ++p;
5173       while (*p != ';')
5174         {
5175           int use_arg;
5176
5177           if (*p == '\0')
5178             abort ();
5179
5180           if (skip)
5181             {
5182               ++p;
5183               continue;
5184             }
5185
5186           use_arg = *p != '!';
5187
5188           if (use_arg)
5189             putchar ('@');
5190
5191           while (*p != ' ' && *p != ';')
5192             {
5193               if (*p == '\0')
5194                 abort ();
5195               if (use_arg)
5196                 putchar (*p);
5197               ++p;
5198             }
5199
5200           if (*p == ' ')
5201             ++p;
5202         }
5203
5204       if (! skip)
5205         {
5206           /* If there are extra options, print them now */
5207           if (multilib_extra && *multilib_extra)
5208             {
5209               int print_at = TRUE;
5210               char *q;
5211
5212               for (q = multilib_extra; *q != '\0'; q++)
5213                 {
5214                   if (*q == ' ')
5215                     print_at = TRUE;
5216                   else
5217                     {
5218                       if (print_at)
5219                         putchar ('@');
5220                       putchar (*q);
5221                       print_at = FALSE;
5222                     }
5223                 }
5224             }
5225           putchar ('\n');
5226         }
5227
5228       ++p;
5229     }
5230 }