OSDN Git Service

2000-09-15 Kazu Hirata <kazu@hxi.com>
[pf3gnuchains/gcc-fork.git] / gcc / gcc.c
1 /* Compiler driver program that can handle many languages.
2    Copyright (C) 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3    1999, 2000 Free Software Foundation, Inc.
4
5 This file is part of GNU CC.
6
7 GNU CC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU CC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU CC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.
21
22 This paragraph is here to try to keep Sun CC from dying.
23 The number of chars here seems crucial!!!!  */
24
25 /* This program is the user interface to the C compiler and possibly to
26 other compilers.  It is used because compilation is a complicated procedure
27 which involves running several programs and passing temporary files between
28 them, forwarding the users switches to those programs selectively,
29 and deleting the temporary files at the end.
30
31 CC recognizes how to compile each input file by suffixes in the file names.
32 Once it knows which kind of compilation to perform, the procedure for
33 compilation is specified by a string called a "spec".  */
34
35 #include "config.h"
36 #include "system.h"
37 #include <signal.h>
38 #include "obstack.h"
39 #include "intl.h"
40 #include "prefix.h"
41 #include "gcc.h"
42
43 #ifdef VMS
44 #define exit __posix_exit
45 #endif
46
47 #ifdef HAVE_SYS_RESOURCE_H
48 #include <sys/resource.h>
49 #endif
50 #if defined (HAVE_DECL_GETRUSAGE) && !HAVE_DECL_GETRUSAGE
51 extern int getrusage PARAMS ((int, struct rusage *));
52 #endif
53
54 /* By default there is no special suffix for executables.  */
55 #ifdef EXECUTABLE_SUFFIX
56 #define HAVE_EXECUTABLE_SUFFIX
57 #else
58 #define EXECUTABLE_SUFFIX ""
59 #endif
60
61 /* By default, the suffix for object files is ".o".  */
62 #ifdef OBJECT_SUFFIX
63 #define HAVE_OBJECT_SUFFIX
64 #else
65 #define OBJECT_SUFFIX ".o"
66 #endif
67
68 #ifndef VMS
69 /* FIXME: the location independence code for VMS is hairier than this,
70    and hasn't been written.  */
71 #ifndef DIR_UP
72 #define DIR_UP ".."
73 #endif /* DIR_UP */
74 #endif /* VMS */
75
76 static char dir_separator_str[] = { DIR_SEPARATOR, 0 };
77
78 #define obstack_chunk_alloc xmalloc
79 #define obstack_chunk_free free
80
81 #ifndef GET_ENV_PATH_LIST
82 #define GET_ENV_PATH_LIST(VAR,NAME)     do { (VAR) = getenv (NAME); } while (0)
83 #endif
84
85 /* Most every one is fine with LIBRARY_PATH.  For some, it conflicts.  */
86 #ifndef LIBRARY_PATH_ENV
87 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
88 #endif
89
90 #ifndef HAVE_KILL
91 #define kill(p,s) raise(s)
92 #endif
93
94 /* If a stage of compilation returns an exit status >= 1,
95    compilation of that file ceases.  */
96
97 #define MIN_FATAL_STATUS 1
98
99 /* Flag saying to pass the greatest exit code returned by a sub-process
100    to the calling program.  */
101 static int pass_exit_codes;
102
103 /* Flag saying to print the directories gcc will search through looking for
104    programs, libraries, etc.  */
105
106 static int print_search_dirs;
107
108 /* Flag saying to print the full filename of this file
109    as found through our usual search mechanism.  */
110
111 static const char *print_file_name = NULL;
112
113 /* As print_file_name, but search for executable file.  */
114
115 static const char *print_prog_name = NULL;
116
117 /* Flag saying to print the relative path we'd use to
118    find libgcc.a given the current compiler flags.  */
119
120 static int print_multi_directory;
121
122 /* Flag saying to print the list of subdirectories and
123    compiler flags used to select them in a standard form.  */
124
125 static int print_multi_lib;
126
127 /* Flag saying to print the command line options understood by gcc and its
128    sub-processes.  */
129
130 static int print_help_list;
131
132 /* Flag indicating whether we should print the command and arguments */
133
134 static int verbose_flag;
135
136 /* Flag indicating whether we should report subprocess execution times
137    (if this is supported by the system - see pexecute.c).  */
138
139 static int report_times;
140
141 /* Nonzero means write "temp" files in source directory
142    and use the source file's name in them, and don't delete them.  */
143
144 static int save_temps_flag;
145
146 /* The compiler version.  */
147
148 static const char *compiler_version;
149
150 /* The target version specified with -V */
151
152 static const char *spec_version = DEFAULT_TARGET_VERSION;
153
154 /* The target machine specified with -b.  */
155
156 static const char *spec_machine = DEFAULT_TARGET_MACHINE;
157
158 /* Nonzero if cross-compiling.
159    When -b is used, the value comes from the `specs' file.  */
160
161 #ifdef CROSS_COMPILE
162 static const char *cross_compile = "1";
163 #else
164 static const char *cross_compile = "0";
165 #endif
166
167 /* The number of errors that have occurred; the link phase will not be
168    run if this is non-zero.  */
169 static int error_count = 0;
170
171 /* Greatest exit code of sub-processes that has been encountered up to
172    now.  */
173 static int greatest_status = 1;
174
175 /* This is the obstack which we use to allocate many strings.  */
176
177 static struct obstack obstack;
178
179 /* This is the obstack to build an environment variable to pass to
180    collect2 that describes all of the relevant switches of what to
181    pass the compiler in building the list of pointers to constructors
182    and destructors.  */
183
184 static struct obstack collect_obstack;
185
186 /* These structs are used to collect resource usage information for
187    subprocesses.  */
188 #ifdef HAVE_GETRUSAGE
189 static struct rusage rus, prus;
190 #endif
191
192 /* Forward declaration for prototypes.  */
193 struct path_prefix;
194
195 static void init_spec           PARAMS ((void));
196 #ifndef VMS
197 static char **split_directories PARAMS ((const char *, int *));
198 static void free_split_directories PARAMS ((char **));
199 static char *make_relative_prefix PARAMS ((const char *, const char *, const char *));
200 #endif /* VMS */
201 static void store_arg           PARAMS ((const char *, int, int));
202 static char *load_specs         PARAMS ((const char *));
203 static void read_specs          PARAMS ((const char *, int));
204 static void set_spec            PARAMS ((const char *, const char *));
205 static struct compiler *lookup_compiler PARAMS ((const char *, size_t, const char *));
206 static char *build_search_list  PARAMS ((struct path_prefix *, const char *, int));
207 static void putenv_from_prefixes PARAMS ((struct path_prefix *, const char *));
208 static int access_check         PARAMS ((const char *, int));
209 static char *find_a_file        PARAMS ((struct path_prefix *, const char *, int));
210 static void add_prefix          PARAMS ((struct path_prefix *, const char *,
211                                          const char *, int, int, int *));
212 static void translate_options   PARAMS ((int *, const char *const **));
213 static char *skip_whitespace    PARAMS ((char *));
214 static void record_temp_file    PARAMS ((const char *, int, int));
215 static void delete_if_ordinary  PARAMS ((const char *));
216 static void delete_temp_files   PARAMS ((void));
217 static void delete_failure_queue PARAMS ((void));
218 static void clear_failure_queue PARAMS ((void));
219 static int check_live_switch    PARAMS ((int, int));
220 static const char *handle_braces PARAMS ((const char *));
221 static char *save_string        PARAMS ((const char *, int));
222 static int do_spec_1            PARAMS ((const char *, int, const char *));
223 static const char *find_file    PARAMS ((const char *));
224 static int is_directory         PARAMS ((const char *, const char *, int));
225 static void validate_switches   PARAMS ((const char *));
226 static void validate_all_switches PARAMS ((void));
227 static void give_switch         PARAMS ((int, int, int));
228 static int used_arg             PARAMS ((const char *, int));
229 static int default_arg          PARAMS ((const char *, int));
230 static void set_multilib_dir    PARAMS ((void));
231 static void print_multilib_info PARAMS ((void));
232 static void pfatal_with_name    PARAMS ((const char *)) ATTRIBUTE_NORETURN;
233 static void perror_with_name    PARAMS ((const char *));
234 static void pfatal_pexecute     PARAMS ((const char *, const char *))
235   ATTRIBUTE_NORETURN;
236 static void error               PARAMS ((const char *, ...))
237   ATTRIBUTE_PRINTF_1;
238 static void notice              PARAMS ((const char *, ...))
239   ATTRIBUTE_PRINTF_1;
240 static void display_help        PARAMS ((void));
241 static void add_preprocessor_option     PARAMS ((const char *, int));
242 static void add_assembler_option        PARAMS ((const char *, int));
243 static void add_linker_option           PARAMS ((const char *, int));
244 static void process_command             PARAMS ((int, const char *const *));
245 static int execute                      PARAMS ((void));
246 static void clear_args                  PARAMS ((void));
247 static void fatal_error                 PARAMS ((int));
248 static void set_input                   PARAMS ((const char *));
249 \f
250 /* Specs are strings containing lines, each of which (if not blank)
251 is made up of a program name, and arguments separated by spaces.
252 The program name must be exact and start from root, since no path
253 is searched and it is unreliable to depend on the current working directory.
254 Redirection of input or output is not supported; the subprograms must
255 accept filenames saying what files to read and write.
256
257 In addition, the specs can contain %-sequences to substitute variable text
258 or for conditional text.  Here is a table of all defined %-sequences.
259 Note that spaces are not generated automatically around the results of
260 expanding these sequences; therefore, you can concatenate them together
261 or with constant text in a single argument.
262
263  %%     substitute one % into the program name or argument.
264  %i     substitute the name of the input file being processed.
265  %b     substitute the basename of the input file being processed.
266         This is the substring up to (and not including) the last period
267         and not including the directory.
268  %B     same as %b, but include the file suffix (text after the last period).
269  %gSUFFIX
270         substitute a file name that has suffix SUFFIX and is chosen
271         once per compilation, and mark the argument a la %d.  To reduce
272         exposure to denial-of-service attacks, the file name is now
273         chosen in a way that is hard to predict even when previously
274         chosen file names are known.  For example, `%g.s ... %g.o ... %g.s'
275         might turn into `ccUVUUAU.s ccXYAXZ12.o ccUVUUAU.s'.  SUFFIX matches
276         the regexp "[.A-Za-z]*%O"; "%O" is treated exactly as if it
277         had been pre-processed.  Previously, %g was simply substituted
278         with a file name chosen once per compilation, without regard
279         to any appended suffix (which was therefore treated just like
280         ordinary text), making such attacks more likely to succeed.
281  %uSUFFIX
282         like %g, but generates a new temporary file name even if %uSUFFIX
283         was already seen.
284  %USUFFIX
285         substitutes the last file name generated with %uSUFFIX, generating a
286         new one if there is no such last file name.  In the absence of any
287         %uSUFFIX, this is just like %gSUFFIX, except they don't share
288         the same suffix "space", so `%g.s ... %U.s ... %g.s ... %U.s'
289         would involve the generation of two distinct file names, one
290         for each `%g.s' and another for each `%U.s'.  Previously, %U was
291         simply substituted with a file name chosen for the previous %u,
292         without regard to any appended suffix.
293  %jSUFFIX
294         substitutes the name of the HOST_BIT_BUCKET, if any, and if it is
295         writable, and if save-temps is off; otherwise, substitute the name
296         of a temporary file, just like %u.  This temporary file is not
297         meant for communication between processes, but rather as a junk
298         disposal mechanism.
299  %d     marks the argument containing or following the %d as a
300         temporary file name, so that that file will be deleted if CC exits
301         successfully.  Unlike %g, this contributes no text to the argument.
302  %w     marks the argument containing or following the %w as the
303         "output file" of this compilation.  This puts the argument
304         into the sequence of arguments that %o will substitute later.
305  %W{...}
306         like %{...} but mark last argument supplied within
307         as a file to be deleted on failure.
308  %o     substitutes the names of all the output files, with spaces
309         automatically placed around them.  You should write spaces
310         around the %o as well or the results are undefined.
311         %o is for use in the specs for running the linker.
312         Input files whose names have no recognized suffix are not compiled
313         at all, but they are included among the output files, so they will
314         be linked.
315  %O     substitutes the suffix for object files.  Note that this is
316         handled specially when it immediately follows %g, %u, or %U
317         (with or without a suffix argument) because of the need for
318         those to form complete file names.  The handling is such that
319         %O is treated exactly as if it had already been substituted,
320         except that %g, %u, and %U do not currently support additional
321         SUFFIX characters following %O as they would following, for
322         example, `.o'.
323  %p     substitutes the standard macro predefinitions for the
324         current target machine.  Use this when running cpp.
325  %P     like %p, but puts `__' before and after the name of each macro.
326         (Except macros that already have __.)
327         This is for ANSI C.
328  %I     Substitute a -iprefix option made from GCC_EXEC_PREFIX.
329  %s     current argument is the name of a library or startup file of some sort.
330         Search for that file in a standard list of directories
331         and substitute the full name found.
332  %eSTR  Print STR as an error message.  STR is terminated by a newline.
333         Use this when inconsistent options are detected.
334  %x{OPTION}     Accumulate an option for %X.
335  %X     Output the accumulated linker options specified by compilations.
336  %Y     Output the accumulated assembler options specified by compilations.
337  %Z     Output the accumulated preprocessor options specified by compilations.
338  %v1    Substitute the major version number of GCC.
339         (For version 2.5.3, this is 2.)
340  %v2    Substitute the minor version number of GCC.
341         (For version 2.5.3, this is 5.)
342  %v3    Substitute the patch level number of GCC.
343         (For version 2.5.3, this is 3.)
344  %a     process ASM_SPEC as a spec.
345         This allows config.h to specify part of the spec for running as.
346  %A     process ASM_FINAL_SPEC as a spec.  A capital A is actually
347         used here.  This can be used to run a post-processor after the
348         assembler has done its job.
349  %D     Dump out a -L option for each directory in startfile_prefixes.
350         If multilib_dir is set, extra entries are generated with it affixed.
351  %l     process LINK_SPEC as a spec.
352  %L     process LIB_SPEC as a spec.
353  %G     process LIBGCC_SPEC as a spec.
354  %S     process STARTFILE_SPEC as a spec.  A capital S is actually used here.
355  %E     process ENDFILE_SPEC as a spec.  A capital E is actually used here.
356  %c     process SIGNED_CHAR_SPEC as a spec.
357  %C     process CPP_SPEC as a spec.  A capital C is actually used here.
358  %1     process CC1_SPEC as a spec.
359  %2     process CC1PLUS_SPEC as a spec.
360  %|     output "-" if the input for the current command is coming from a pipe.
361  %*     substitute the variable part of a matched option.  (See below.)
362         Note that each comma in the substituted string is replaced by
363         a single space.
364  %{S}   substitutes the -S switch, if that switch was given to CC.
365         If that switch was not specified, this substitutes nothing.
366         Here S is a metasyntactic variable.
367  %{S*}  substitutes all the switches specified to CC whose names start
368         with -S.  This is used for -o, -D, -I, etc; switches that take
369         arguments.  CC considers `-o foo' as being one switch whose
370         name starts with `o'.  %{o*} would substitute this text,
371         including the space; thus, two arguments would be generated.
372  %{^S*} likewise, but don't put a blank between a switch and any args.
373  %{S*:X} substitutes X if one or more switches whose names start with -S are
374         specified to CC.  Note that the tail part of the -S option
375         (i.e. the part matched by the `*') will be substituted for each
376         occurrence of %* within X.
377  %{<S}  remove all occurences of S from the command line.
378         Note - this option is position dependent.  % commands in the
379         spec string before this option will see S, % commands in the
380         spec string after this option will not.
381  %{S:X} substitutes X, but only if the -S switch was given to CC.
382  %{!S:X} substitutes X, but only if the -S switch was NOT given to CC.
383  %{|S:X} like %{S:X}, but if no S switch, substitute `-'.
384  %{|!S:X} like %{!S:X}, but if there is an S switch, substitute `-'.
385  %{.S:X} substitutes X, but only if processing a file with suffix S.
386  %{!.S:X} substitutes X, but only if NOT processing a file with suffix S.
387  %{S|P:X} substitutes X if either -S or -P was given to CC.  This may be
388           combined with ! and . as above binding stronger than the OR.
389  %(Spec) processes a specification defined in a specs file as *Spec:
390  %[Spec] as above, but put __ around -D arguments
391
392 The conditional text X in a %{S:X} or %{!S:X} construct may contain
393 other nested % constructs or spaces, or even newlines.  They are
394 processed as usual, as described above.
395
396 The -O, -f, -m, and -W switches are handled specifically in these
397 constructs.  If another value of -O or the negated form of a -f, -m, or
398 -W switch is found later in the command line, the earlier switch
399 value is ignored, except with {S*} where S is just one letter; this
400 passes all matching options.
401
402 The character | at the beginning of the predicate text is used to indicate
403 that a command should be piped to the following command, but only if -pipe
404 is specified.
405
406 Note that it is built into CC which switches take arguments and which
407 do not.  You might think it would be useful to generalize this to
408 allow each compiler's spec to say which switches take arguments.  But
409 this cannot be done in a consistent fashion.  CC cannot even decide
410 which input files have been specified without knowing which switches
411 take arguments, and it must know which input files to compile in order
412 to tell which compilers to run.
413
414 CC also knows implicitly that arguments starting in `-l' are to be
415 treated as compiler output files, and passed to the linker in their
416 proper position among the other output files.  */
417 \f
418 /* Define the macros used for specs %a, %l, %L, %S, %c, %C, %1.  */
419
420 /* config.h can define ASM_SPEC to provide extra args to the assembler
421    or extra switch-translations.  */
422 #ifndef ASM_SPEC
423 #define ASM_SPEC ""
424 #endif
425
426 /* config.h can define ASM_FINAL_SPEC to run a post processor after
427    the assembler has run.  */
428 #ifndef ASM_FINAL_SPEC
429 #define ASM_FINAL_SPEC ""
430 #endif
431
432 /* config.h can define CPP_SPEC to provide extra args to the C preprocessor
433    or extra switch-translations.  */
434 #ifndef CPP_SPEC
435 #define CPP_SPEC ""
436 #endif
437
438 /* config.h can define CC1_SPEC to provide extra args to cc1 and cc1plus
439    or extra switch-translations.  */
440 #ifndef CC1_SPEC
441 #define CC1_SPEC ""
442 #endif
443
444 /* config.h can define CC1PLUS_SPEC to provide extra args to cc1plus
445    or extra switch-translations.  */
446 #ifndef CC1PLUS_SPEC
447 #define CC1PLUS_SPEC ""
448 #endif
449
450 /* config.h can define LINK_SPEC to provide extra args to the linker
451    or extra switch-translations.  */
452 #ifndef LINK_SPEC
453 #define LINK_SPEC ""
454 #endif
455
456 /* config.h can define LIB_SPEC to override the default libraries.  */
457 #ifndef LIB_SPEC
458 #define LIB_SPEC "%{!shared:%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}}"
459 #endif
460
461 /* config.h can define LIBGCC_SPEC to override how and when libgcc.a is
462    included.  */
463 #ifndef LIBGCC_SPEC
464 #if defined(LINK_LIBGCC_SPECIAL) || defined(LINK_LIBGCC_SPECIAL_1)
465 /* Have gcc do the search for libgcc.a.  */
466 #define LIBGCC_SPEC "libgcc.a%s"
467 #else
468 #define LIBGCC_SPEC "-lgcc"
469 #endif
470 #endif
471
472 /* config.h can define STARTFILE_SPEC to override the default crt0 files.  */
473 #ifndef STARTFILE_SPEC
474 #define STARTFILE_SPEC  \
475   "%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
476 #endif
477
478 /* config.h can define SWITCHES_NEED_SPACES to control which options
479    require spaces between the option and the argument.  */
480 #ifndef SWITCHES_NEED_SPACES
481 #define SWITCHES_NEED_SPACES ""
482 #endif
483
484 /* config.h can define ENDFILE_SPEC to override the default crtn files.  */
485 #ifndef ENDFILE_SPEC
486 #define ENDFILE_SPEC ""
487 #endif
488
489 /* This spec is used for telling cpp whether char is signed or not.  */
490 #ifndef SIGNED_CHAR_SPEC
491 /* Use #if rather than ?:
492    because MIPS C compiler rejects like ?: in initializers.  */
493 #if DEFAULT_SIGNED_CHAR
494 #define SIGNED_CHAR_SPEC "%{funsigned-char:-D__CHAR_UNSIGNED__}"
495 #else
496 #define SIGNED_CHAR_SPEC "%{!fsigned-char:-D__CHAR_UNSIGNED__}"
497 #endif
498 #endif
499
500 #ifndef LINKER_NAME
501 #define LINKER_NAME "collect2"
502 #endif
503
504 /* Here is the spec for running the linker, after compiling all files.  */
505
506 /* -u* was put back because both BSD and SysV seem to support it.  */
507 /* %{static:} simply prevents an error message if the target machine
508    doesn't handle -static.  */
509 /* We want %{T*} after %{L*} and %D so that it can be used to specify linker
510    scripts which exist in user specified directories, or in standard
511    directories.  */
512 #ifndef LINK_COMMAND_SPEC
513 #define LINK_COMMAND_SPEC "\
514 %{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
515     %(linker) %l %X %{o*} %{A} %{d} %{e*} %{m} %{N} %{n} %{r} %{s} %{t}\
516     %{u*} %{x} %{z} %{Z} %{!A:%{!nostdlib:%{!nostartfiles:%S}}}\
517     %{static:} %{L*} %(link_libgcc) %o %{!nostdlib:%{!nodefaultlibs:%G %L %G}}\
518     %{!A:%{!nostdlib:%{!nostartfiles:%E}}} %{T*} }}}}}}"
519 #endif
520
521 #ifndef LINK_LIBGCC_SPEC
522 # ifdef LINK_LIBGCC_SPECIAL
523 /* Don't generate -L options for startfile prefix list.  */
524 #  define LINK_LIBGCC_SPEC ""
525 # else
526 /* Do generate them.  */
527 #  define LINK_LIBGCC_SPEC "%D"
528 # endif
529 #endif
530
531 static const char *cpp_spec = CPP_SPEC;
532 static const char *cpp_predefines = CPP_PREDEFINES;
533 static const char *cc1_spec = CC1_SPEC;
534 static const char *cc1plus_spec = CC1PLUS_SPEC;
535 static const char *signed_char_spec = SIGNED_CHAR_SPEC;
536 static const char *asm_spec = ASM_SPEC;
537 static const char *asm_final_spec = ASM_FINAL_SPEC;
538 static const char *link_spec = LINK_SPEC;
539 static const char *lib_spec = LIB_SPEC;
540 static const char *libgcc_spec = LIBGCC_SPEC;
541 static const char *endfile_spec = ENDFILE_SPEC;
542 static const char *startfile_spec = STARTFILE_SPEC;
543 static const char *switches_need_spaces = SWITCHES_NEED_SPACES;
544 static const char *linker_name_spec = LINKER_NAME;
545 static const char *link_command_spec = LINK_COMMAND_SPEC;
546 static const char *link_libgcc_spec = LINK_LIBGCC_SPEC;
547
548 /* Standard options to cpp, cc1, and as, to reduce duplication in specs.
549    There should be no need to override these in target dependent files,
550    but we need to copy them to the specs file so that newer versions
551    of the GCC driver can correctly drive older tool chains with the
552    appropriate -B options.  */
553
554 static const char *trad_capable_cpp =
555 "%{traditional|ftraditional|traditional-cpp:trad}cpp0";
556
557 static const char *cpp_options =
558 "%{C:%{!E:%eGNU C does not support -C without using -E}}\
559  %{std*} %{nostdinc*}\
560  %{C} %{v} %{A*} %{I*} %{P} %{$} %I\
561  %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d} %{MG}\
562  %{!no-gcc:-D__GNUC__=%v1 -D__GNUC_MINOR__=%v2 -D__GNUC_PATCHLEVEL__=%v3}\
563  %{!undef:%{!ansi:%{!std=*:%p}%{std=gnu*:%p}} %P} %{trigraphs}\
564  %c %{Os:-D__OPTIMIZE_SIZE__} %{O*:%{!O0:-D__OPTIMIZE__}}\
565  %{ffast-math:-D__FAST_MATH__}\
566  %{fshort-wchar:-U__WCHAR_TYPE__ -D__WCHAR_TYPE__=short\\ unsigned\\ int}\
567  %{fshow-column} %{fno-show-column}\
568  %{fleading-underscore} %{fno-leading-underscore}\
569  %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{U*} %{D*} %{i*} %Z %i\
570  %{E:%W{o*}}%{M:%W{o*}}%{MM:%W{o*}}";
571
572 static const char *cc1_options =
573 "%{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
574  %1 %{!Q:-quiet} -dumpbase %B %{d*} %{m*} %{a*}\
575  %{g*} %{O*} %{W*} %{w} %{pedantic*} %{std*} %{ansi}\
576  %{traditional} %{v:-version} %{pg:-p} %{p} %{f*}\
577  %{aux-info*} %{Qn:-fno-ident} %{--help:--help}\
578  %{!fsyntax-only:%{S:%W{o*}%{!o*:-o %b.s}}}\
579  %{fsyntax-only:-o %j}";
580
581 static const char *asm_options =
582 "%a %Y %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}";
583
584 /* Some compilers have limits on line lengths, and the multilib_select
585    and/or multilib_matches strings can be very long, so we build them at
586    run time.  */
587 static struct obstack multilib_obstack;
588 static const char *multilib_select;
589 static const char *multilib_matches;
590 static const char *multilib_defaults;
591 static const char *multilib_exclusions;
592 #include "multilib.h"
593
594 /* Check whether a particular argument is a default argument.  */
595
596 #ifndef MULTILIB_DEFAULTS
597 #define MULTILIB_DEFAULTS { "" }
598 #endif
599
600 static const char *const multilib_defaults_raw[] = MULTILIB_DEFAULTS;
601
602 struct user_specs
603 {
604   struct user_specs *next;
605   const char *filename;
606 };
607
608 static struct user_specs *user_specs_head, *user_specs_tail;
609
610 /* This defines which switch letters take arguments.  */
611
612 #define DEFAULT_SWITCH_TAKES_ARG(CHAR) \
613   ((CHAR) == 'D' || (CHAR) == 'U' || (CHAR) == 'o' \
614    || (CHAR) == 'e' || (CHAR) == 'T' || (CHAR) == 'u' \
615    || (CHAR) == 'I' || (CHAR) == 'm' || (CHAR) == 'x' \
616    || (CHAR) == 'L' || (CHAR) == 'A' || (CHAR) == 'V' \
617    || (CHAR) == 'B' || (CHAR) == 'b')
618
619 #ifndef SWITCH_TAKES_ARG
620 #define SWITCH_TAKES_ARG(CHAR) DEFAULT_SWITCH_TAKES_ARG(CHAR)
621 #endif
622
623 /* This defines which multi-letter switches take arguments.  */
624
625 #define DEFAULT_WORD_SWITCH_TAKES_ARG(STR)              \
626  (!strcmp (STR, "Tdata") || !strcmp (STR, "Ttext")      \
627   || !strcmp (STR, "Tbss") || !strcmp (STR, "include")  \
628   || !strcmp (STR, "imacros") || !strcmp (STR, "aux-info") \
629   || !strcmp (STR, "idirafter") || !strcmp (STR, "iprefix") \
630   || !strcmp (STR, "iwithprefix") || !strcmp (STR, "iwithprefixbefore") \
631   || !strcmp (STR, "isystem") || !strcmp (STR, "specs"))
632
633 #ifndef WORD_SWITCH_TAKES_ARG
634 #define WORD_SWITCH_TAKES_ARG(STR) DEFAULT_WORD_SWITCH_TAKES_ARG (STR)
635 #endif
636 \f
637 #ifdef HAVE_EXECUTABLE_SUFFIX
638 /* This defines which switches stop a full compilation.  */
639 #define DEFAULT_SWITCH_CURTAILS_COMPILATION(CHAR) \
640   ((CHAR) == 'c' || (CHAR) == 'S')
641
642 #ifndef SWITCH_CURTAILS_COMPILATION
643 #define SWITCH_CURTAILS_COMPILATION(CHAR) \
644   DEFAULT_SWITCH_CURTAILS_COMPILATION(CHAR)
645 #endif
646 #endif
647
648 /* Record the mapping from file suffixes for compilation specs.  */
649
650 struct compiler
651 {
652   const char *suffix;           /* Use this compiler for input files
653                                    whose names end in this suffix.  */
654
655   const char *spec;             /* To use this compiler, run this spec.  */
656 };
657
658 /* Pointer to a vector of `struct compiler' that gives the spec for
659    compiling a file, based on its suffix.
660    A file that does not end in any of these suffixes will be passed
661    unchanged to the loader and nothing else will be done to it.
662
663    An entry containing two 0s is used to terminate the vector.
664
665    If multiple entries match a file, the last matching one is used.  */
666
667 static struct compiler *compilers;
668
669 /* Number of entries in `compilers', not counting the null terminator.  */
670
671 static int n_compilers;
672
673 /* The default list of file name suffixes and their compilation specs.  */
674
675 static struct compiler default_compilers[] =
676 {
677   /* Add lists of suffixes of known languages here.  If those languages
678      were not present when we built the driver, we will hit these copies
679      and be given a more meaningful error than "file not used since
680      linking is not done".  */
681   {".m",  "#Objective-C"},
682   {".cc", "#C++"}, {".cxx", "#C++"}, {".cpp", "#C++"},
683   {".c++", "#C++"}, {".C", "#C++"},
684   {".ads", "#Ada"}, {".adb", "#Ada"}, {".ada", "#Ada"},
685   {".f", "#Fortran"}, {".for", "#Fortran"}, {".F", "#Fortran"},
686   {".fpp", "#Fortran"}, {".r", "#Ratfor"},
687   {".p", "#Pascal"}, {".pas", "#Pascal"},
688   {".ch", "#Chill"}, {".chi", "#Chill"},
689   {".java", "#Java"}, {".class", "#Java"},
690   {".zip", "#Java"}, {".jar", "#Java"},
691   /* Next come the entries for C.  */
692   {".c", "@c"},
693   {"@c",
694 #if USE_CPPLIB
695      "%{E|M|MM:%(trad_capable_cpp) -lang-c %{ansi:-std=c89} %(cpp_options)}\
696       %{!E:%{!M:%{!MM:cc1 -lang-c %{ansi:-std=c89} %(cpp_options)\
697                           %(cc1_options) %{!fsyntax-only:%{!S:-o %{|!pipe:%g.s} |\n\
698       as %(asm_options) %{!pipe:%g.s} %A }}}}}"
699 #else /* ! USE_CPPLIB */
700      "%(trad_capable_cpp) -lang-c %{ansi:-std=c89} %(cpp_options) \
701                           %{!M:%{!MM:%{!E:%{!pipe:%g.i} |\n\
702       cc1 %{!pipe:%g.i} %(cc1_options) %{!fsyntax-only:%{!S:-o %{|!pipe:%g.s} |\n\
703       as %(asm_options) %{!pipe:%g.s} %A }}}}}\n"
704 #endif /* ! USE_CPPLIB */
705   },
706   {"-",
707    "%{!E:%e-E required when input is from standard input}\
708     %(trad_capable_cpp) -lang-c %{ansi:-std=c89} %(cpp_options)"},
709   {".h", "@c-header"},
710   {"@c-header",
711    "%{!E:%eCompilation of header file requested} \
712     %(trad_capable_cpp) -lang-c %{ansi:-std=c89} %(cpp_options)"},
713   {".i", "@cpp-output"},
714   {"@cpp-output",
715    "%{!M:%{!MM:%{!E:\
716     cc1 %i %(cc1_options) %{!fsyntax-only:%{!S:-o %{|!pipe:%g.s} |\n\
717     as %(asm_options) %{!pipe:%g.s} %A }}}}}"},
718   {".s", "@assembler"},
719   {"@assembler",
720    "%{!M:%{!MM:%{!E:%{!S:as %(asm_options) %i %A }}}}"},
721   {".S", "@assembler-with-cpp"},
722   {"@assembler-with-cpp",
723    "%(trad_capable_cpp) -lang-asm %(cpp_options) \
724                         %{!M:%{!MM:%{!E:%{!S: %{!pipe:%g.s} |\n\
725     as %(asm_options) %{!pipe:%g.s} %A }}}}"},
726 #include "specs.h"
727   /* Mark end of table */
728   {0, 0}
729 };
730
731 /* Number of elements in default_compilers, not counting the terminator.  */
732
733 static int n_default_compilers
734   = (sizeof default_compilers / sizeof (struct compiler)) - 1;
735
736 /* A vector of options to give to the linker.
737    These options are accumulated by %x,
738    and substituted into the linker command with %X.  */
739 static int n_linker_options;
740 static char **linker_options;
741
742 /* A vector of options to give to the assembler.
743    These options are accumulated by -Wa,
744    and substituted into the assembler command with %Y.  */
745 static int n_assembler_options;
746 static char **assembler_options;
747
748 /* A vector of options to give to the preprocessor.
749    These options are accumulated by -Wp,
750    and substituted into the preprocessor command with %Z.  */
751 static int n_preprocessor_options;
752 static char **preprocessor_options;
753 \f
754 /* Define how to map long options into short ones.  */
755
756 /* This structure describes one mapping.  */
757 struct option_map
758 {
759   /* The long option's name.  */
760   const char *name;
761   /* The equivalent short option.  */
762   const char *equivalent;
763   /* Argument info.  A string of flag chars; NULL equals no options.
764      a => argument required.
765      o => argument optional.
766      j => join argument to equivalent, making one word.
767      * => require other text after NAME as an argument.  */
768   const char *arg_info;
769 };
770
771 /* This is the table of mappings.  Mappings are tried sequentially
772    for each option encountered; the first one that matches, wins.  */
773
774 struct option_map option_map[] =
775  {
776    {"--all-warnings", "-Wall", 0},
777    {"--ansi", "-ansi", 0},
778    {"--assemble", "-S", 0},
779    {"--assert", "-A", "a"},
780    {"--classpath", "-fclasspath=", "aj"},
781    {"--CLASSPATH", "-fCLASSPATH=", "aj"},
782    {"--comments", "-C", 0},
783    {"--compile", "-c", 0},
784    {"--debug", "-g", "oj"},
785    {"--define-macro", "-D", "aj"},
786    {"--dependencies", "-M", 0},
787    {"--dump", "-d", "a"},
788    {"--dumpbase", "-dumpbase", "a"},
789    {"--entry", "-e", 0},
790    {"--extra-warnings", "-W", 0},
791    {"--for-assembler", "-Wa", "a"},
792    {"--for-linker", "-Xlinker", "a"},
793    {"--force-link", "-u", "a"},
794    {"--imacros", "-imacros", "a"},
795    {"--include", "-include", "a"},
796    {"--include-barrier", "-I-", 0},
797    {"--include-directory", "-I", "aj"},
798    {"--include-directory-after", "-idirafter", "a"},
799    {"--include-prefix", "-iprefix", "a"},
800    {"--include-with-prefix", "-iwithprefix", "a"},
801    {"--include-with-prefix-before", "-iwithprefixbefore", "a"},
802    {"--include-with-prefix-after", "-iwithprefix", "a"},
803    {"--language", "-x", "a"},
804    {"--library-directory", "-L", "a"},
805    {"--machine", "-m", "aj"},
806    {"--machine-", "-m", "*j"},
807    {"--no-line-commands", "-P", 0},
808    {"--no-precompiled-includes", "-noprecomp", 0},
809    {"--no-standard-includes", "-nostdinc", 0},
810    {"--no-standard-libraries", "-nostdlib", 0},
811    {"--no-warnings", "-w", 0},
812    {"--optimize", "-O", "oj"},
813    {"--output", "-o", "a"},
814    {"--output-class-directory", "-foutput-class-dir=", "ja"},
815    {"--pedantic", "-pedantic", 0},
816    {"--pedantic-errors", "-pedantic-errors", 0},
817    {"--pipe", "-pipe", 0},
818    {"--prefix", "-B", "a"},
819    {"--preprocess", "-E", 0},
820    {"--print-search-dirs", "-print-search-dirs", 0},
821    {"--print-file-name", "-print-file-name=", "aj"},
822    {"--print-libgcc-file-name", "-print-libgcc-file-name", 0},
823    {"--print-missing-file-dependencies", "-MG", 0},
824    {"--print-multi-lib", "-print-multi-lib", 0},
825    {"--print-multi-directory", "-print-multi-directory", 0},
826    {"--print-prog-name", "-print-prog-name=", "aj"},
827    {"--profile", "-p", 0},
828    {"--profile-blocks", "-a", 0},
829    {"--quiet", "-q", 0},
830    {"--save-temps", "-save-temps", 0},
831    {"--shared", "-shared", 0},
832    {"--silent", "-q", 0},
833    {"--specs", "-specs=", "aj"},
834    {"--static", "-static", 0},
835    {"--std", "-std=", "aj"},
836    {"--symbolic", "-symbolic", 0},
837    {"--target", "-b", "a"},
838    {"--time", "-time", 0},
839    {"--trace-includes", "-H", 0},
840    {"--traditional", "-traditional", 0},
841    {"--traditional-cpp", "-traditional-cpp", 0},
842    {"--trigraphs", "-trigraphs", 0},
843    {"--undefine-macro", "-U", "aj"},
844    {"--use-version", "-V", "a"},
845    {"--user-dependencies", "-MM", 0},
846    {"--verbose", "-v", 0},
847    {"--version", "-dumpversion", 0},
848    {"--warn-", "-W", "*j"},
849    {"--write-dependencies", "-MD", 0},
850    {"--write-user-dependencies", "-MMD", 0},
851    {"--", "-f", "*j"}
852  };
853 \f
854 /* Translate the options described by *ARGCP and *ARGVP.
855    Make a new vector and store it back in *ARGVP,
856    and store its length in *ARGVC.  */
857
858 static void
859 translate_options (argcp, argvp)
860      int *argcp;
861      const char *const **argvp;
862 {
863   int i;
864   int argc = *argcp;
865   const char *const *argv = *argvp;
866   const char **newv =
867     (const char **) xmalloc ((argc + 2) * 2 * sizeof (const char *));
868   int newindex = 0;
869
870   i = 0;
871   newv[newindex++] = argv[i++];
872
873   while (i < argc)
874     {
875       /* Translate -- options.  */
876       if (argv[i][0] == '-' && argv[i][1] == '-')
877         {
878           size_t j;
879           /* Find a mapping that applies to this option.  */
880           for (j = 0; j < ARRAY_SIZE (option_map); j++)
881             {
882               size_t optlen = strlen (option_map[j].name);
883               size_t arglen = strlen (argv[i]);
884               size_t complen = arglen > optlen ? optlen : arglen;
885               const char *arginfo = option_map[j].arg_info;
886
887               if (arginfo == 0)
888                 arginfo = "";
889
890               if (!strncmp (argv[i], option_map[j].name, complen))
891                 {
892                   const char *arg = 0;
893
894                   if (arglen < optlen)
895                     {
896                       size_t k;
897                       for (k = j + 1; k < ARRAY_SIZE (option_map); k++)
898                         if (strlen (option_map[k].name) >= arglen
899                             && !strncmp (argv[i], option_map[k].name, arglen))
900                           {
901                             error ("Ambiguous abbreviation %s", argv[i]);
902                             break;
903                           }
904
905                       if (k != ARRAY_SIZE (option_map))
906                         break;
907                     }
908
909                   if (arglen > optlen)
910                     {
911                       /* If the option has an argument, accept that.  */
912                       if (argv[i][optlen] == '=')
913                         arg = argv[i] + optlen + 1;
914
915                       /* If this mapping requires extra text at end of name,
916                          accept that as "argument".  */
917                       else if (index (arginfo, '*') != 0)
918                         arg = argv[i] + optlen;
919
920                       /* Otherwise, extra text at end means mismatch.
921                          Try other mappings.  */
922                       else
923                         continue;
924                     }
925
926                   else if (index (arginfo, '*') != 0)
927                     {
928                       error ("Incomplete `%s' option", option_map[j].name);
929                       break;
930                     }
931
932                   /* Handle arguments.  */
933                   if (index (arginfo, 'a') != 0)
934                     {
935                       if (arg == 0)
936                         {
937                           if (i + 1 == argc)
938                             {
939                               error ("Missing argument to `%s' option",
940                                      option_map[j].name);
941                               break;
942                             }
943
944                           arg = argv[++i];
945                         }
946                     }
947                   else if (index (arginfo, '*') != 0)
948                     ;
949                   else if (index (arginfo, 'o') == 0)
950                     {
951                       if (arg != 0)
952                         error ("Extraneous argument to `%s' option",
953                                option_map[j].name);
954                       arg = 0;
955                     }
956
957                   /* Store the translation as one argv elt or as two.  */
958                   if (arg != 0 && index (arginfo, 'j') != 0)
959                     newv[newindex++] = concat (option_map[j].equivalent, arg,
960                                                NULL_PTR);
961                   else if (arg != 0)
962                     {
963                       newv[newindex++] = option_map[j].equivalent;
964                       newv[newindex++] = arg;
965                     }
966                   else
967                     newv[newindex++] = option_map[j].equivalent;
968
969                   break;
970                 }
971             }
972           i++;
973         }
974
975       /* Handle old-fashioned options--just copy them through,
976          with their arguments.  */
977       else if (argv[i][0] == '-')
978         {
979           const char *p = argv[i] + 1;
980           int c = *p;
981           int nskip = 1;
982
983           if (SWITCH_TAKES_ARG (c) > (p[1] != 0))
984             nskip += SWITCH_TAKES_ARG (c) - (p[1] != 0);
985           else if (WORD_SWITCH_TAKES_ARG (p))
986             nskip += WORD_SWITCH_TAKES_ARG (p);
987           else if ((c == 'B' || c == 'b' || c == 'V' || c == 'x')
988                    && p[1] == 0)
989             nskip += 1;
990           else if (! strcmp (p, "Xlinker"))
991             nskip += 1;
992
993           /* Watch out for an option at the end of the command line that
994              is missing arguments, and avoid skipping past the end of the
995              command line.  */
996           if (nskip + i > argc)
997             nskip = argc - i;
998
999           while (nskip > 0)
1000             {
1001               newv[newindex++] = argv[i++];
1002               nskip--;
1003             }
1004         }
1005       else
1006         /* Ordinary operands, or +e options.  */
1007         newv[newindex++] = argv[i++];
1008     }
1009
1010   newv[newindex] = 0;
1011
1012   *argvp = newv;
1013   *argcp = newindex;
1014 }
1015 \f
1016 static char *
1017 skip_whitespace (p)
1018      char *p;
1019 {
1020   while (1)
1021     {
1022       /* A fully-blank line is a delimiter in the SPEC file and shouldn't
1023          be considered whitespace.  */
1024       if (p[0] == '\n' && p[1] == '\n' && p[2] == '\n')
1025         return p + 1;
1026       else if (*p == '\n' || *p == ' ' || *p == '\t')
1027         p++;
1028       else if (*p == '#')
1029         {
1030           while (*p != '\n')
1031             p++;
1032           p++;
1033         }
1034       else
1035         break;
1036     }
1037
1038   return p;
1039 }
1040 \f
1041 /* Structure to keep track of the specs that have been defined so far.
1042    These are accessed using %(specname) or %[specname] in a compiler
1043    or link spec.  */
1044
1045 struct spec_list
1046 {
1047                                 /* The following 2 fields must be first */
1048                                 /* to allow EXTRA_SPECS to be initialized */
1049   const char *name;             /* name of the spec.  */
1050   const char *ptr;              /* available ptr if no static pointer */
1051
1052                                 /* The following fields are not initialized */
1053                                 /* by EXTRA_SPECS */
1054   const char **ptr_spec;        /* pointer to the spec itself.  */
1055   struct spec_list *next;       /* Next spec in linked list.  */
1056   int name_len;                 /* length of the name */
1057   int alloc_p;                  /* whether string was allocated */
1058 };
1059
1060 #define INIT_STATIC_SPEC(NAME,PTR) \
1061 { NAME, NULL_PTR, PTR, (struct spec_list *) 0, sizeof (NAME) - 1, 0 }
1062
1063 /* List of statically defined specs.  */
1064 static struct spec_list static_specs[] =
1065 {
1066   INIT_STATIC_SPEC ("asm",                      &asm_spec),
1067   INIT_STATIC_SPEC ("asm_final",                &asm_final_spec),
1068   INIT_STATIC_SPEC ("asm_options",              &asm_options),
1069   INIT_STATIC_SPEC ("cpp",                      &cpp_spec),
1070   INIT_STATIC_SPEC ("cpp_options",              &cpp_options),
1071   INIT_STATIC_SPEC ("trad_capable_cpp",         &trad_capable_cpp),
1072   INIT_STATIC_SPEC ("cc1",                      &cc1_spec),
1073   INIT_STATIC_SPEC ("cc1_options",              &cc1_options),
1074   INIT_STATIC_SPEC ("cc1plus",                  &cc1plus_spec),
1075   INIT_STATIC_SPEC ("endfile",                  &endfile_spec),
1076   INIT_STATIC_SPEC ("link",                     &link_spec),
1077   INIT_STATIC_SPEC ("lib",                      &lib_spec),
1078   INIT_STATIC_SPEC ("libgcc",                   &libgcc_spec),
1079   INIT_STATIC_SPEC ("startfile",                &startfile_spec),
1080   INIT_STATIC_SPEC ("switches_need_spaces",     &switches_need_spaces),
1081   INIT_STATIC_SPEC ("signed_char",              &signed_char_spec),
1082   INIT_STATIC_SPEC ("predefines",               &cpp_predefines),
1083   INIT_STATIC_SPEC ("cross_compile",            &cross_compile),
1084   INIT_STATIC_SPEC ("version",                  &compiler_version),
1085   INIT_STATIC_SPEC ("multilib",                 &multilib_select),
1086   INIT_STATIC_SPEC ("multilib_defaults",        &multilib_defaults),
1087   INIT_STATIC_SPEC ("multilib_extra",           &multilib_extra),
1088   INIT_STATIC_SPEC ("multilib_matches",         &multilib_matches),
1089   INIT_STATIC_SPEC ("multilib_exclusions",      &multilib_exclusions),
1090   INIT_STATIC_SPEC ("linker",                   &linker_name_spec),
1091   INIT_STATIC_SPEC ("link_libgcc",              &link_libgcc_spec),
1092 };
1093
1094 #ifdef EXTRA_SPECS              /* additional specs needed */
1095 /* Structure to keep track of just the first two args of a spec_list.
1096    That is all that the EXTRA_SPECS macro gives us.  */
1097 struct spec_list_1
1098 {
1099   const char *name;
1100   const char *ptr;
1101 };
1102
1103 static struct spec_list_1 extra_specs_1[] = { EXTRA_SPECS };
1104 static struct spec_list *extra_specs = (struct spec_list *) 0;
1105 #endif
1106
1107 /* List of dynamically allocates specs that have been defined so far.  */
1108
1109 static struct spec_list *specs = (struct spec_list *) 0;
1110 \f
1111 /* Initialize the specs lookup routines.  */
1112
1113 static void
1114 init_spec ()
1115 {
1116   struct spec_list *next = (struct spec_list *) 0;
1117   struct spec_list *sl   = (struct spec_list *) 0;
1118   int i;
1119
1120   if (specs)
1121     return;                     /* Already initialized.  */
1122
1123   if (verbose_flag)
1124     notice ("Using builtin specs.\n");
1125
1126 #ifdef EXTRA_SPECS
1127   extra_specs = (struct spec_list *)
1128     xcalloc (sizeof (struct spec_list), ARRAY_SIZE (extra_specs_1));
1129
1130   for (i = ARRAY_SIZE (extra_specs_1) - 1; i >= 0; i--)
1131     {
1132       sl = &extra_specs[i];
1133       sl->name = extra_specs_1[i].name;
1134       sl->ptr = extra_specs_1[i].ptr;
1135       sl->next = next;
1136       sl->name_len = strlen (sl->name);
1137       sl->ptr_spec = &sl->ptr;
1138       next = sl;
1139     }
1140 #endif
1141
1142   for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1143     {
1144       sl = &static_specs[i];
1145       sl->next = next;
1146       next = sl;
1147     }
1148
1149   specs = sl;
1150 }
1151 \f
1152 /* Change the value of spec NAME to SPEC.  If SPEC is empty, then the spec is
1153    removed; If the spec starts with a + then SPEC is added to the end of the
1154    current spec.  */
1155
1156 static void
1157 set_spec (name, spec)
1158      const char *name;
1159      const char *spec;
1160 {
1161   struct spec_list *sl;
1162   const char *old_spec;
1163   int name_len = strlen (name);
1164   int i;
1165
1166   /* If this is the first call, initialize the statically allocated specs.  */
1167   if (!specs)
1168     {
1169       struct spec_list *next = (struct spec_list *) 0;
1170       for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1171         {
1172           sl = &static_specs[i];
1173           sl->next = next;
1174           next = sl;
1175         }
1176       specs = sl;
1177     }
1178
1179   /* See if the spec already exists.  */
1180   for (sl = specs; sl; sl = sl->next)
1181     if (name_len == sl->name_len && !strcmp (sl->name, name))
1182       break;
1183
1184   if (!sl)
1185     {
1186       /* Not found - make it.  */
1187       sl = (struct spec_list *) xmalloc (sizeof (struct spec_list));
1188       sl->name = xstrdup (name);
1189       sl->name_len = name_len;
1190       sl->ptr_spec = &sl->ptr;
1191       sl->alloc_p = 0;
1192       *(sl->ptr_spec) = "";
1193       sl->next = specs;
1194       specs = sl;
1195     }
1196
1197   old_spec = *(sl->ptr_spec);
1198   *(sl->ptr_spec) = ((spec[0] == '+' && ISSPACE ((unsigned char)spec[1]))
1199                      ? concat (old_spec, spec + 1, NULL_PTR)
1200                      : xstrdup (spec));
1201
1202 #ifdef DEBUG_SPECS
1203   if (verbose_flag)
1204     notice ("Setting spec %s to '%s'\n\n", name, *(sl->ptr_spec));
1205 #endif
1206
1207   /* Free the old spec.  */
1208   if (old_spec && sl->alloc_p)
1209     free ((PTR) old_spec);
1210
1211   sl->alloc_p = 1;
1212 }
1213 \f
1214 /* Accumulate a command (program name and args), and run it.  */
1215
1216 /* Vector of pointers to arguments in the current line of specifications.  */
1217
1218 static const char **argbuf;
1219
1220 /* Number of elements allocated in argbuf.  */
1221
1222 static int argbuf_length;
1223
1224 /* Number of elements in argbuf currently in use (containing args).  */
1225
1226 static int argbuf_index;
1227
1228 /* This is the list of suffixes and codes (%g/%u/%U/%j) and the associated
1229    temp file.  If the HOST_BIT_BUCKET is used for %j, no entry is made for
1230    it here.  */
1231
1232 static struct temp_name {
1233   const char *suffix;   /* suffix associated with the code.  */
1234   int length;           /* strlen (suffix).  */
1235   int unique;           /* Indicates whether %g or %u/%U was used.  */
1236   const char *filename; /* associated filename.  */
1237   int filename_length;  /* strlen (filename).  */
1238   struct temp_name *next;
1239 } *temp_names;
1240
1241 /* Number of commands executed so far.  */
1242
1243 static int execution_count;
1244
1245 /* Number of commands that exited with a signal.  */
1246
1247 static int signal_count;
1248
1249 /* Name with which this program was invoked.  */
1250
1251 static const char *programname;
1252 \f
1253 /* Structures to keep track of prefixes to try when looking for files.  */
1254
1255 struct prefix_list
1256 {
1257   char *prefix;               /* String to prepend to the path.  */
1258   struct prefix_list *next;   /* Next in linked list.  */
1259   int require_machine_suffix; /* Don't use without machine_suffix.  */
1260   /* 2 means try both machine_suffix and just_machine_suffix.  */
1261   int *used_flag_ptr;         /* 1 if a file was found with this prefix.  */
1262   int priority;               /* Sort key - priority within list */
1263 };
1264
1265 struct path_prefix
1266 {
1267   struct prefix_list *plist;  /* List of prefixes to try */
1268   int max_len;                /* Max length of a prefix in PLIST */
1269   const char *name;           /* Name of this list (used in config stuff) */
1270 };
1271
1272 /* List of prefixes to try when looking for executables.  */
1273
1274 static struct path_prefix exec_prefixes = { 0, 0, "exec" };
1275
1276 /* List of prefixes to try when looking for startup (crt0) files.  */
1277
1278 static struct path_prefix startfile_prefixes = { 0, 0, "startfile" };
1279
1280 /* List of prefixes to try when looking for include files.  */
1281
1282 static struct path_prefix include_prefixes = { 0, 0, "include" };
1283
1284 /* Suffix to attach to directories searched for commands.
1285    This looks like `MACHINE/VERSION/'.  */
1286
1287 static const char *machine_suffix = 0;
1288
1289 /* Suffix to attach to directories searched for commands.
1290    This is just `MACHINE/'.  */
1291
1292 static const char *just_machine_suffix = 0;
1293
1294 /* Adjusted value of GCC_EXEC_PREFIX envvar.  */
1295
1296 static const char *gcc_exec_prefix;
1297
1298 /* Default prefixes to attach to command names.  */
1299
1300 #ifdef CROSS_COMPILE  /* Don't use these prefixes for a cross compiler.  */
1301 #undef MD_EXEC_PREFIX
1302 #undef MD_STARTFILE_PREFIX
1303 #undef MD_STARTFILE_PREFIX_1
1304 #endif
1305
1306 #ifndef STANDARD_EXEC_PREFIX
1307 #define STANDARD_EXEC_PREFIX "/usr/local/lib/gcc-lib/"
1308 #endif /* !defined STANDARD_EXEC_PREFIX */
1309
1310 static const char *standard_exec_prefix = STANDARD_EXEC_PREFIX;
1311 static const char *standard_exec_prefix_1 = "/usr/lib/gcc/";
1312 #ifdef MD_EXEC_PREFIX
1313 static const char *md_exec_prefix = MD_EXEC_PREFIX;
1314 #endif
1315
1316 #ifndef STANDARD_STARTFILE_PREFIX
1317 #define STANDARD_STARTFILE_PREFIX "/usr/local/lib/"
1318 #endif /* !defined STANDARD_STARTFILE_PREFIX */
1319
1320 #ifdef MD_STARTFILE_PREFIX
1321 static const char *md_startfile_prefix = MD_STARTFILE_PREFIX;
1322 #endif
1323 #ifdef MD_STARTFILE_PREFIX_1
1324 static const char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
1325 #endif
1326 static const char *standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
1327 static const char *standard_startfile_prefix_1 = "/lib/";
1328 static const char *standard_startfile_prefix_2 = "/usr/lib/";
1329
1330 #ifndef TOOLDIR_BASE_PREFIX
1331 #define TOOLDIR_BASE_PREFIX "/usr/local/"
1332 #endif
1333 static const char *tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
1334 static const char *tooldir_prefix;
1335
1336 #ifndef STANDARD_BINDIR_PREFIX
1337 #define STANDARD_BINDIR_PREFIX "/usr/local/bin"
1338 #endif
1339 static const char *standard_bindir_prefix = STANDARD_BINDIR_PREFIX;
1340
1341 /* Subdirectory to use for locating libraries.  Set by
1342    set_multilib_dir based on the compilation options.  */
1343
1344 static const char *multilib_dir;
1345
1346 /* Clear out the vector of arguments (after a command is executed).  */
1347
1348 static void
1349 clear_args ()
1350 {
1351   argbuf_index = 0;
1352 }
1353
1354 /* Add one argument to the vector at the end.
1355    This is done when a space is seen or at the end of the line.
1356    If DELETE_ALWAYS is nonzero, the arg is a filename
1357     and the file should be deleted eventually.
1358    If DELETE_FAILURE is nonzero, the arg is a filename
1359     and the file should be deleted if this compilation fails.  */
1360
1361 static void
1362 store_arg (arg, delete_always, delete_failure)
1363      const char *arg;
1364      int delete_always, delete_failure;
1365 {
1366   if (argbuf_index + 1 == argbuf_length)
1367     argbuf
1368       = (const char **) xrealloc (argbuf,
1369                                   (argbuf_length *= 2) * sizeof (const char *));
1370
1371   argbuf[argbuf_index++] = arg;
1372   argbuf[argbuf_index] = 0;
1373
1374   if (delete_always || delete_failure)
1375     record_temp_file (arg, delete_always, delete_failure);
1376 }
1377 \f
1378 /* Load specs from a file name named FILENAME, replacing occurances of
1379    various different types of line-endings, \r\n, \n\r and just \r, with
1380    a single \n.  */
1381
1382 static char *
1383 load_specs (filename)
1384      const char *filename;
1385 {
1386   int desc;
1387   int readlen;
1388   struct stat statbuf;
1389   char *buffer;
1390   char *buffer_p;
1391   char *specs;
1392   char *specs_p;
1393
1394   if (verbose_flag)
1395     notice ("Reading specs from %s\n", filename);
1396
1397   /* Open and stat the file.  */
1398   desc = open (filename, O_RDONLY, 0);
1399   if (desc < 0)
1400     pfatal_with_name (filename);
1401   if (stat (filename, &statbuf) < 0)
1402     pfatal_with_name (filename);
1403
1404   /* Read contents of file into BUFFER.  */
1405   buffer = xmalloc ((unsigned) statbuf.st_size + 1);
1406   readlen = read (desc, buffer, (unsigned) statbuf.st_size);
1407   if (readlen < 0)
1408     pfatal_with_name (filename);
1409   buffer[readlen] = 0;
1410   close (desc);
1411
1412   specs = xmalloc (readlen + 1);
1413   specs_p = specs;
1414   for (buffer_p = buffer; buffer_p && *buffer_p; buffer_p++)
1415     {
1416       int skip = 0;
1417       char c = *buffer_p;
1418       if (c == '\r')
1419         {
1420           if (buffer_p > buffer && *(buffer_p - 1) == '\n')     /* \n\r */
1421             skip = 1;
1422           else if (*(buffer_p + 1) == '\n')                     /* \r\n */
1423             skip = 1;
1424           else                                                  /* \r */
1425             c = '\n';
1426         }
1427       if (! skip)
1428         *specs_p++ = c;
1429     }
1430   *specs_p = '\0';
1431
1432   free (buffer);
1433   return (specs);
1434 }
1435
1436 /* Read compilation specs from a file named FILENAME,
1437    replacing the default ones.
1438
1439    A suffix which starts with `*' is a definition for
1440    one of the machine-specific sub-specs.  The "suffix" should be
1441    *asm, *cc1, *cpp, *link, *startfile, *signed_char, etc.
1442    The corresponding spec is stored in asm_spec, etc.,
1443    rather than in the `compilers' vector.
1444
1445    Anything invalid in the file is a fatal error.  */
1446
1447 static void
1448 read_specs (filename, main_p)
1449      const char *filename;
1450      int main_p;
1451 {
1452   char *buffer;
1453   register char *p;
1454
1455   buffer = load_specs (filename);
1456
1457   /* Scan BUFFER for specs, putting them in the vector.  */
1458   p = buffer;
1459   while (1)
1460     {
1461       char *suffix;
1462       char *spec;
1463       char *in, *out, *p1, *p2, *p3;
1464
1465       /* Advance P in BUFFER to the next nonblank nocomment line.  */
1466       p = skip_whitespace (p);
1467       if (*p == 0)
1468         break;
1469
1470       /* Is this a special command that starts with '%'? */
1471       /* Don't allow this for the main specs file, since it would
1472          encourage people to overwrite it.  */
1473       if (*p == '%' && !main_p)
1474         {
1475           p1 = p;
1476           while (*p && *p != '\n')
1477             p++;
1478
1479           /* Skip '\n'.  */
1480           p++;
1481
1482           if (!strncmp (p1, "%include", sizeof ("%include") - 1)
1483               && (p1[sizeof "%include" - 1] == ' '
1484                   || p1[sizeof "%include" - 1] == '\t'))
1485             {
1486               char *new_filename;
1487
1488               p1 += sizeof ("%include");
1489               while (*p1 == ' ' || *p1 == '\t')
1490                 p1++;
1491
1492               if (*p1++ != '<' || p[-2] != '>')
1493                 fatal ("specs %%include syntax malformed after %ld characters",
1494                        (long) (p1 - buffer + 1));
1495
1496               p[-2] = '\0';
1497               new_filename = find_a_file (&startfile_prefixes, p1, R_OK);
1498               read_specs (new_filename ? new_filename : p1, FALSE);
1499               continue;
1500             }
1501           else if (!strncmp (p1, "%include_noerr", sizeof "%include_noerr" - 1)
1502                    && (p1[sizeof "%include_noerr" - 1] == ' '
1503                        || p1[sizeof "%include_noerr" - 1] == '\t'))
1504             {
1505               char *new_filename;
1506
1507               p1 += sizeof "%include_noerr";
1508               while (*p1 == ' ' || *p1 == '\t')
1509                 p1++;
1510
1511               if (*p1++ != '<' || p[-2] != '>')
1512                 fatal ("specs %%include syntax malformed after %ld characters",
1513                        (long) (p1 - buffer + 1));
1514
1515               p[-2] = '\0';
1516               new_filename = find_a_file (&startfile_prefixes, p1, R_OK);
1517               if (new_filename)
1518                 read_specs (new_filename, FALSE);
1519               else if (verbose_flag)
1520                 notice ("Could not find specs file %s\n", p1);
1521               continue;
1522             }
1523           else if (!strncmp (p1, "%rename", sizeof "%rename" - 1)
1524                    && (p1[sizeof "%rename" - 1] == ' '
1525                        || p1[sizeof "%rename" - 1] == '\t'))
1526             {
1527               int name_len;
1528               struct spec_list *sl;
1529
1530               /* Get original name */
1531               p1 += sizeof "%rename";
1532               while (*p1 == ' ' || *p1 == '\t')
1533                 p1++;
1534
1535               if (! ISALPHA ((unsigned char) *p1))
1536                 fatal ("specs %%rename syntax malformed after %ld characters",
1537                        (long) (p1 - buffer));
1538
1539               p2 = p1;
1540               while (*p2 && !ISSPACE ((unsigned char) *p2))
1541                 p2++;
1542
1543               if (*p2 != ' ' && *p2 != '\t')
1544                 fatal ("specs %%rename syntax malformed after %ld characters",
1545                        (long) (p2 - buffer));
1546
1547               name_len = p2 - p1;
1548               *p2++ = '\0';
1549               while (*p2 == ' ' || *p2 == '\t')
1550                 p2++;
1551
1552               if (! ISALPHA ((unsigned char) *p2))
1553                 fatal ("specs %%rename syntax malformed after %ld characters",
1554                        (long) (p2 - buffer));
1555
1556               /* Get new spec name.  */
1557               p3 = p2;
1558               while (*p3 && !ISSPACE ((unsigned char) *p3))
1559                 p3++;
1560
1561               if (p3 != p - 1)
1562                 fatal ("specs %%rename syntax malformed after %ld characters",
1563                        (long) (p3 - buffer));
1564               *p3 = '\0';
1565
1566               for (sl = specs; sl; sl = sl->next)
1567                 if (name_len == sl->name_len && !strcmp (sl->name, p1))
1568                   break;
1569
1570               if (!sl)
1571                 fatal ("specs %s spec was not found to be renamed", p1);
1572
1573               if (strcmp (p1, p2) == 0)
1574                 continue;
1575
1576               if (verbose_flag)
1577                 {
1578                   notice ("rename spec %s to %s\n", p1, p2);
1579 #ifdef DEBUG_SPECS
1580                   notice ("spec is '%s'\n\n", *(sl->ptr_spec));
1581 #endif
1582                 }
1583
1584               set_spec (p2, *(sl->ptr_spec));
1585               if (sl->alloc_p)
1586                 free ((PTR) *(sl->ptr_spec));
1587
1588               *(sl->ptr_spec) = "";
1589               sl->alloc_p = 0;
1590               continue;
1591             }
1592           else
1593             fatal ("specs unknown %% command after %ld characters",
1594                    (long) (p1 - buffer));
1595         }
1596
1597       /* Find the colon that should end the suffix.  */
1598       p1 = p;
1599       while (*p1 && *p1 != ':' && *p1 != '\n')
1600         p1++;
1601
1602       /* The colon shouldn't be missing.  */
1603       if (*p1 != ':')
1604         fatal ("specs file malformed after %ld characters",
1605                (long) (p1 - buffer));
1606
1607       /* Skip back over trailing whitespace.  */
1608       p2 = p1;
1609       while (p2 > buffer && (p2[-1] == ' ' || p2[-1] == '\t'))
1610         p2--;
1611
1612       /* Copy the suffix to a string.  */
1613       suffix = save_string (p, p2 - p);
1614       /* Find the next line.  */
1615       p = skip_whitespace (p1 + 1);
1616       if (p[1] == 0)
1617         fatal ("specs file malformed after %ld characters",
1618                (long) (p - buffer));
1619
1620       p1 = p;
1621       /* Find next blank line or end of string.  */
1622       while (*p1 && !(*p1 == '\n' && (p1[1] == '\n' || p1[1] == '\0')))
1623         p1++;
1624
1625       /* Specs end at the blank line and do not include the newline.  */
1626       spec = save_string (p, p1 - p);
1627       p = p1;
1628
1629       /* Delete backslash-newline sequences from the spec.  */
1630       in = spec;
1631       out = spec;
1632       while (*in != 0)
1633         {
1634           if (in[0] == '\\' && in[1] == '\n')
1635             in += 2;
1636           else if (in[0] == '#')
1637             while (*in && *in != '\n')
1638               in++;
1639
1640           else
1641             *out++ = *in++;
1642         }
1643       *out = 0;
1644
1645       if (suffix[0] == '*')
1646         {
1647           if (! strcmp (suffix, "*link_command"))
1648             link_command_spec = spec;
1649           else
1650             set_spec (suffix + 1, spec);
1651         }
1652       else
1653         {
1654           /* Add this pair to the vector.  */
1655           compilers
1656             = ((struct compiler *)
1657                xrealloc (compilers,
1658                          (n_compilers + 2) * sizeof (struct compiler)));
1659
1660           compilers[n_compilers].suffix = suffix;
1661           compilers[n_compilers].spec = spec;
1662           n_compilers++;
1663           memset (&compilers[n_compilers], 0, sizeof compilers[n_compilers]);
1664         }
1665
1666       if (*suffix == 0)
1667         link_command_spec = spec;
1668     }
1669
1670   if (link_command_spec == 0)
1671     fatal ("spec file has no spec for linking");
1672 }
1673 \f
1674 /* Record the names of temporary files we tell compilers to write,
1675    and delete them at the end of the run.  */
1676
1677 /* This is the common prefix we use to make temp file names.
1678    It is chosen once for each run of this program.
1679    It is substituted into a spec by %g or %j.
1680    Thus, all temp file names contain this prefix.
1681    In practice, all temp file names start with this prefix.
1682
1683    This prefix comes from the envvar TMPDIR if it is defined;
1684    otherwise, from the P_tmpdir macro if that is defined;
1685    otherwise, in /usr/tmp or /tmp;
1686    or finally the current directory if all else fails.  */
1687
1688 static const char *temp_filename;
1689
1690 /* Length of the prefix.  */
1691
1692 static int temp_filename_length;
1693
1694 /* Define the list of temporary files to delete.  */
1695
1696 struct temp_file
1697 {
1698   const char *name;
1699   struct temp_file *next;
1700 };
1701
1702 /* Queue of files to delete on success or failure of compilation.  */
1703 static struct temp_file *always_delete_queue;
1704 /* Queue of files to delete on failure of compilation.  */
1705 static struct temp_file *failure_delete_queue;
1706
1707 /* Record FILENAME as a file to be deleted automatically.
1708    ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
1709    otherwise delete it in any case.
1710    FAIL_DELETE nonzero means delete it if a compilation step fails;
1711    otherwise delete it in any case.  */
1712
1713 static void
1714 record_temp_file (filename, always_delete, fail_delete)
1715      const char *filename;
1716      int always_delete;
1717      int fail_delete;
1718 {
1719   register char *const name = xstrdup (filename);
1720
1721   if (always_delete)
1722     {
1723       register struct temp_file *temp;
1724       for (temp = always_delete_queue; temp; temp = temp->next)
1725         if (! strcmp (name, temp->name))
1726           goto already1;
1727
1728       temp = (struct temp_file *) xmalloc (sizeof (struct temp_file));
1729       temp->next = always_delete_queue;
1730       temp->name = name;
1731       always_delete_queue = temp;
1732
1733     already1:;
1734     }
1735
1736   if (fail_delete)
1737     {
1738       register struct temp_file *temp;
1739       for (temp = failure_delete_queue; temp; temp = temp->next)
1740         if (! strcmp (name, temp->name))
1741           goto already2;
1742
1743       temp = (struct temp_file *) xmalloc (sizeof (struct temp_file));
1744       temp->next = failure_delete_queue;
1745       temp->name = name;
1746       failure_delete_queue = temp;
1747
1748     already2:;
1749     }
1750 }
1751
1752 /* Delete all the temporary files whose names we previously recorded.  */
1753
1754 static void
1755 delete_if_ordinary (name)
1756      const char *name;
1757 {
1758   struct stat st;
1759 #ifdef DEBUG
1760   int i, c;
1761
1762   printf ("Delete %s? (y or n) ", name);
1763   fflush (stdout);
1764   i = getchar ();
1765   if (i != '\n')
1766     while ((c = getchar ()) != '\n' && c != EOF)
1767       ;
1768
1769   if (i == 'y' || i == 'Y')
1770 #endif /* DEBUG */
1771     if (stat (name, &st) >= 0 && S_ISREG (st.st_mode))
1772       if (unlink (name) < 0)
1773         if (verbose_flag)
1774           perror_with_name (name);
1775 }
1776
1777 static void
1778 delete_temp_files ()
1779 {
1780   register struct temp_file *temp;
1781
1782   for (temp = always_delete_queue; temp; temp = temp->next)
1783     delete_if_ordinary (temp->name);
1784   always_delete_queue = 0;
1785 }
1786
1787 /* Delete all the files to be deleted on error.  */
1788
1789 static void
1790 delete_failure_queue ()
1791 {
1792   register struct temp_file *temp;
1793
1794   for (temp = failure_delete_queue; temp; temp = temp->next)
1795     delete_if_ordinary (temp->name);
1796 }
1797
1798 static void
1799 clear_failure_queue ()
1800 {
1801   failure_delete_queue = 0;
1802 }
1803 \f
1804 /* Routine to add variables to the environment.  We do this to pass
1805    the pathname of the gcc driver, and the directories search to the
1806    collect2 program, which is being run as ld.  This way, we can be
1807    sure of executing the right compiler when collect2 wants to build
1808    constructors and destructors.  Since the environment variables we
1809    use come from an obstack, we don't have to worry about allocating
1810    space for them.  */
1811
1812 #ifndef HAVE_PUTENV
1813
1814 void
1815 putenv (str)
1816      char *str;
1817 {
1818 #ifndef VMS                     /* nor about VMS */
1819
1820   extern char **environ;
1821   char **old_environ = environ;
1822   char **envp;
1823   int num_envs = 0;
1824   int name_len = 1;
1825   int str_len = strlen (str);
1826   char *p = str;
1827   int ch;
1828
1829   while ((ch = *p++) != '\0' && ch != '=')
1830     name_len++;
1831
1832   if (!ch)
1833     abort ();
1834
1835   /* Search for replacing an existing environment variable, and
1836      count the number of total environment variables.  */
1837   for (envp = old_environ; *envp; envp++)
1838     {
1839       num_envs++;
1840       if (!strncmp (str, *envp, name_len))
1841         {
1842           *envp = str;
1843           return;
1844         }
1845     }
1846
1847   /* Add a new environment variable */
1848   environ = (char **) xmalloc (sizeof (char *) * (num_envs + 2));
1849   *environ = str;
1850   memcpy ((char *) (environ + 1), (char *) old_environ,
1851           sizeof (char *) * (num_envs + 1));
1852
1853 #endif  /* VMS */
1854 }
1855
1856 #endif /* HAVE_PUTENV */
1857 \f
1858 /* Build a list of search directories from PATHS.
1859    PREFIX is a string to prepend to the list.
1860    If CHECK_DIR_P is non-zero we ensure the directory exists.
1861    This is used mostly by putenv_from_prefixes so we use `collect_obstack'.
1862    It is also used by the --print-search-dirs flag.  */
1863
1864 static char *
1865 build_search_list (paths, prefix, check_dir_p)
1866      struct path_prefix *paths;
1867      const char *prefix;
1868      int check_dir_p;
1869 {
1870   int suffix_len = (machine_suffix) ? strlen (machine_suffix) : 0;
1871   int just_suffix_len
1872     = (just_machine_suffix) ? strlen (just_machine_suffix) : 0;
1873   int first_time = TRUE;
1874   struct prefix_list *pprefix;
1875
1876   obstack_grow (&collect_obstack, prefix, strlen (prefix));
1877   obstack_1grow (&collect_obstack, '=');
1878
1879   for (pprefix = paths->plist; pprefix != 0; pprefix = pprefix->next)
1880     {
1881       int len = strlen (pprefix->prefix);
1882
1883       if (machine_suffix
1884           && (! check_dir_p
1885               || is_directory (pprefix->prefix, machine_suffix, 0)))
1886         {
1887           if (!first_time)
1888             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1889
1890           first_time = FALSE;
1891           obstack_grow (&collect_obstack, pprefix->prefix, len);
1892           obstack_grow (&collect_obstack, machine_suffix, suffix_len);
1893         }
1894
1895       if (just_machine_suffix
1896           && pprefix->require_machine_suffix == 2
1897           && (! check_dir_p
1898               || is_directory (pprefix->prefix, just_machine_suffix, 0)))
1899         {
1900           if (! first_time)
1901             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1902
1903           first_time = FALSE;
1904           obstack_grow (&collect_obstack, pprefix->prefix, len);
1905           obstack_grow (&collect_obstack, just_machine_suffix,
1906                         just_suffix_len);
1907         }
1908
1909       if (! pprefix->require_machine_suffix)
1910         {
1911           if (! first_time)
1912             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1913
1914           first_time = FALSE;
1915           obstack_grow (&collect_obstack, pprefix->prefix, len);
1916         }
1917     }
1918
1919   obstack_1grow (&collect_obstack, '\0');
1920   return obstack_finish (&collect_obstack);
1921 }
1922
1923 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
1924    for collect.  */
1925
1926 static void
1927 putenv_from_prefixes (paths, env_var)
1928      struct path_prefix *paths;
1929      const char *env_var;
1930 {
1931   putenv (build_search_list (paths, env_var, 1));
1932 }
1933 \f
1934 #ifndef VMS
1935
1936 /* FIXME: the location independence code for VMS is hairier than this,
1937    and hasn't been written.  */
1938
1939 /* Split a filename into component directories.  */
1940
1941 static char **
1942 split_directories (name, ptr_num_dirs)
1943      const char *name;
1944      int *ptr_num_dirs;
1945 {
1946   int num_dirs = 0;
1947   char **dirs;
1948   const char *p, *q;
1949   int ch;
1950
1951   /* Count the number of directories.  Special case MSDOS disk names as part
1952      of the initial directory.  */
1953   p = name;
1954 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1955   if (name[1] == ':' && IS_DIR_SEPARATOR (name[2]))
1956     {
1957       p += 3;
1958       num_dirs++;
1959     }
1960 #endif /* HAVE_DOS_BASED_FILE_SYSTEM */
1961
1962   while ((ch = *p++) != '\0')
1963     {
1964       if (IS_DIR_SEPARATOR (ch))
1965         {
1966           num_dirs++;
1967           while (IS_DIR_SEPARATOR (*p))
1968             p++;
1969         }
1970     }
1971
1972   dirs = (char **) xmalloc (sizeof (char *) * (num_dirs + 2));
1973
1974   /* Now copy the directory parts.  */
1975   num_dirs = 0;
1976   p = name;
1977 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
1978   if (name[1] == ':' && IS_DIR_SEPARATOR (name[2]))
1979     {
1980       dirs[num_dirs++] = save_string (p, 3);
1981       p += 3;
1982     }
1983 #endif /* HAVE_DOS_BASED_FILE_SYSTEM */
1984
1985   q = p;
1986   while ((ch = *p++) != '\0')
1987     {
1988       if (IS_DIR_SEPARATOR (ch))
1989         {
1990           while (IS_DIR_SEPARATOR (*p))
1991             p++;
1992
1993           dirs[num_dirs++] = save_string (q, p - q);
1994           q = p;
1995         }
1996     }
1997
1998   if (p - 1 - q > 0)
1999     dirs[num_dirs++] = save_string (q, p - 1 - q);
2000
2001   dirs[num_dirs] = NULL_PTR;
2002   if (ptr_num_dirs)
2003     *ptr_num_dirs = num_dirs;
2004
2005   return dirs;
2006 }
2007
2008 /* Release storage held by split directories.  */
2009
2010 static void
2011 free_split_directories (dirs)
2012      char **dirs;
2013 {
2014   int i = 0;
2015
2016   while (dirs[i] != NULL_PTR)
2017     free (dirs[i++]);
2018
2019   free ((char *) dirs);
2020 }
2021
2022 /* Given three strings PROGNAME, BIN_PREFIX, PREFIX, return a string that gets
2023    to PREFIX starting with the directory portion of PROGNAME and a relative
2024    pathname of the difference between BIN_PREFIX and PREFIX.
2025
2026    For example, if BIN_PREFIX is /alpha/beta/gamma/gcc/delta, PREFIX is
2027    /alpha/beta/gamma/omega/, and PROGNAME is /red/green/blue/gcc, then this
2028    function will return /red/green/blue/../omega.
2029
2030    If no relative prefix can be found, return NULL.  */
2031
2032 static char *
2033 make_relative_prefix (progname, bin_prefix, prefix)
2034      const char *progname;
2035      const char *bin_prefix;
2036      const char *prefix;
2037 {
2038   char **prog_dirs, **bin_dirs, **prefix_dirs;
2039   int prog_num, bin_num, prefix_num, std_loc_p;
2040   int i, n, common;
2041
2042   prog_dirs = split_directories (progname, &prog_num);
2043   bin_dirs = split_directories (bin_prefix, &bin_num);
2044
2045   /* If there is no full pathname, try to find the program by checking in each
2046      of the directories specified in the PATH environment variable.  */
2047   if (prog_num == 1)
2048     {
2049       char *temp;
2050
2051       GET_ENV_PATH_LIST (temp, "PATH");
2052       if (temp)
2053         {
2054           char *startp, *endp;
2055           char *nstore = (char *) alloca (strlen (temp) + strlen (progname) + 1);
2056
2057           startp = endp = temp;
2058           while (1)
2059             {
2060               if (*endp == PATH_SEPARATOR || *endp == 0)
2061                 {
2062                   if (endp == startp)
2063                     {
2064                       nstore[0] = '.';
2065                       nstore[1] = DIR_SEPARATOR;
2066                       nstore[2] = '\0';
2067                     }
2068                   else
2069                     {
2070                       strncpy (nstore, startp, endp - startp);
2071                       if (! IS_DIR_SEPARATOR (endp[-1]))
2072                         {
2073                           nstore[endp - startp] = DIR_SEPARATOR;
2074                           nstore[endp - startp + 1] = 0;
2075                         }
2076                       else
2077                         nstore[endp - startp] = 0;
2078                     }
2079                   strcat (nstore, progname);
2080                   if (! access (nstore, X_OK)
2081 #ifdef HAVE_EXECUTABLE_SUFFIX
2082                       || ! access (strcat (nstore, EXECUTABLE_SUFFIX), X_OK)
2083 #endif
2084                       )
2085                     {
2086                       free_split_directories (prog_dirs);
2087                       progname = nstore;
2088                       prog_dirs = split_directories (progname, &prog_num);
2089                       break;
2090                     }
2091
2092                   if (*endp == 0)
2093                     break;
2094                   endp = startp = endp + 1;
2095                 }
2096               else
2097                 endp++;
2098             }
2099         }
2100     }
2101
2102   /* Remove the program name from comparison of directory names.  */
2103   prog_num--;
2104
2105   /* Determine if the compiler is installed in the standard location, and if
2106      so, we don't need to specify relative directories.  Also, if argv[0]
2107      doesn't contain any directory specifiers, there is not much we can do.  */
2108   std_loc_p = 0;
2109   if (prog_num == bin_num)
2110     {
2111       for (i = 0; i < bin_num; i++)
2112         {
2113           if (strcmp (prog_dirs[i], bin_dirs[i]) != 0)
2114             break;
2115         }
2116
2117       if (prog_num <= 0 || i == bin_num)
2118         {
2119           std_loc_p = 1;
2120           free_split_directories (prog_dirs);
2121           free_split_directories (bin_dirs);
2122           prog_dirs = bin_dirs = (char **) 0;
2123           return NULL_PTR;
2124         }
2125     }
2126
2127   prefix_dirs = split_directories (prefix, &prefix_num);
2128
2129   /* Find how many directories are in common between bin_prefix & prefix.  */
2130   n = (prefix_num < bin_num) ? prefix_num : bin_num;
2131   for (common = 0; common < n; common++)
2132     {
2133       if (strcmp (bin_dirs[common], prefix_dirs[common]) != 0)
2134         break;
2135     }
2136
2137   /* If there are no common directories, there can be no relative prefix.  */
2138   if (common == 0)
2139     {
2140       free_split_directories (prog_dirs);
2141       free_split_directories (bin_dirs);
2142       free_split_directories (prefix_dirs);
2143       return NULL_PTR;
2144     }
2145
2146   /* Build up the pathnames in argv[0].  */
2147   for (i = 0; i < prog_num; i++)
2148     obstack_grow (&obstack, prog_dirs[i], strlen (prog_dirs[i]));
2149
2150   /* Now build up the ..'s.  */
2151   for (i = common; i < n; i++)
2152     {
2153       obstack_grow (&obstack, DIR_UP, sizeof (DIR_UP) - 1);
2154       obstack_1grow (&obstack, DIR_SEPARATOR);
2155     }
2156
2157   /* Put in directories to move over to prefix.  */
2158   for (i = common; i < prefix_num; i++)
2159     obstack_grow (&obstack, prefix_dirs[i], strlen (prefix_dirs[i]));
2160
2161   free_split_directories (prog_dirs);
2162   free_split_directories (bin_dirs);
2163   free_split_directories (prefix_dirs);
2164
2165   obstack_1grow (&obstack, '\0');
2166   return obstack_finish (&obstack);
2167 }
2168 #endif /* VMS */
2169 \f
2170 /* Check whether NAME can be accessed in MODE.  This is like access,
2171    except that it never considers directories to be executable.  */
2172
2173 static int
2174 access_check (name, mode)
2175      const char *name;
2176      int mode;
2177 {
2178   if (mode == X_OK)
2179     {
2180       struct stat st;
2181
2182       if (stat (name, &st) < 0
2183           || S_ISDIR (st.st_mode))
2184         return -1;
2185     }
2186
2187   return access (name, mode);
2188 }
2189
2190 /* Search for NAME using the prefix list PREFIXES.  MODE is passed to
2191    access to check permissions.
2192    Return 0 if not found, otherwise return its name, allocated with malloc.  */
2193
2194 static char *
2195 find_a_file (pprefix, name, mode)
2196      struct path_prefix *pprefix;
2197      const char *name;
2198      int mode;
2199 {
2200   char *temp;
2201   const char *file_suffix = ((mode & X_OK) != 0 ? EXECUTABLE_SUFFIX : "");
2202   struct prefix_list *pl;
2203   int len = pprefix->max_len + strlen (name) + strlen (file_suffix) + 1;
2204
2205 #ifdef DEFAULT_ASSEMBLER
2206   if (! strcmp(name, "as") && access (DEFAULT_ASSEMBLER, mode) == 0)
2207     return xstrdup (DEFAULT_ASSEMBLER);
2208 #endif
2209
2210 #ifdef DEFAULT_LINKER
2211   if (! strcmp(name, "ld") && access (DEFAULT_LINKER, mode) == 0)
2212     return xstrdup (DEFAULT_LINKER);
2213 #endif
2214
2215   if (machine_suffix)
2216     len += strlen (machine_suffix);
2217
2218   temp = xmalloc (len);
2219
2220   /* Determine the filename to execute (special case for absolute paths).  */
2221
2222   if (IS_DIR_SEPARATOR (*name)
2223 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
2224       /* Check for disk name on MS-DOS-based systems.  */
2225       || (name[0] && name[1] == ':' && IS_DIR_SEPARATOR (name[2]))
2226 #endif
2227       )
2228     {
2229       if (access (name, mode) == 0)
2230         {
2231           strcpy (temp, name);
2232           return temp;
2233         }
2234     }
2235   else
2236     for (pl = pprefix->plist; pl; pl = pl->next)
2237       {
2238         if (machine_suffix)
2239           {
2240             /* Some systems have a suffix for executable files.
2241                So try appending that first.  */
2242             if (file_suffix[0] != 0)
2243               {
2244                 strcpy (temp, pl->prefix);
2245                 strcat (temp, machine_suffix);
2246                 strcat (temp, name);
2247                 strcat (temp, file_suffix);
2248                 if (access_check (temp, mode) == 0)
2249                   {
2250                     if (pl->used_flag_ptr != 0)
2251                       *pl->used_flag_ptr = 1;
2252                     return temp;
2253                   }
2254               }
2255
2256             /* Now try just the name.  */
2257             strcpy (temp, pl->prefix);
2258             strcat (temp, machine_suffix);
2259             strcat (temp, name);
2260             if (access_check (temp, mode) == 0)
2261               {
2262                 if (pl->used_flag_ptr != 0)
2263                   *pl->used_flag_ptr = 1;
2264                 return temp;
2265               }
2266           }
2267
2268         /* Certain prefixes are tried with just the machine type,
2269            not the version.  This is used for finding as, ld, etc.  */
2270         if (just_machine_suffix && pl->require_machine_suffix == 2)
2271           {
2272             /* Some systems have a suffix for executable files.
2273                So try appending that first.  */
2274             if (file_suffix[0] != 0)
2275               {
2276                 strcpy (temp, pl->prefix);
2277                 strcat (temp, just_machine_suffix);
2278                 strcat (temp, name);
2279                 strcat (temp, file_suffix);
2280                 if (access_check (temp, mode) == 0)
2281                   {
2282                     if (pl->used_flag_ptr != 0)
2283                       *pl->used_flag_ptr = 1;
2284                     return temp;
2285                   }
2286               }
2287
2288             strcpy (temp, pl->prefix);
2289             strcat (temp, just_machine_suffix);
2290             strcat (temp, name);
2291             if (access_check (temp, mode) == 0)
2292               {
2293                 if (pl->used_flag_ptr != 0)
2294                   *pl->used_flag_ptr = 1;
2295                 return temp;
2296               }
2297           }
2298
2299         /* Certain prefixes can't be used without the machine suffix
2300            when the machine or version is explicitly specified.  */
2301         if (! pl->require_machine_suffix)
2302           {
2303             /* Some systems have a suffix for executable files.
2304                So try appending that first.  */
2305             if (file_suffix[0] != 0)
2306               {
2307                 strcpy (temp, pl->prefix);
2308                 strcat (temp, name);
2309                 strcat (temp, file_suffix);
2310                 if (access_check (temp, mode) == 0)
2311                   {
2312                     if (pl->used_flag_ptr != 0)
2313                       *pl->used_flag_ptr = 1;
2314                     return temp;
2315                   }
2316               }
2317
2318             strcpy (temp, pl->prefix);
2319             strcat (temp, name);
2320             if (access_check (temp, mode) == 0)
2321               {
2322                 if (pl->used_flag_ptr != 0)
2323                   *pl->used_flag_ptr = 1;
2324                 return temp;
2325               }
2326           }
2327       }
2328
2329   free (temp);
2330   return 0;
2331 }
2332
2333 /* Ranking of prefixes in the sort list. -B prefixes are put before
2334    all others.  */
2335
2336 enum path_prefix_priority
2337 {
2338   PREFIX_PRIORITY_B_OPT,
2339   PREFIX_PRIORITY_LAST
2340 };
2341
2342 /* Add an entry for PREFIX in PLIST.  The PLIST is kept in assending
2343    order according to PRIORITY.  Within each PRIORITY, new entries are
2344    appended.
2345
2346    If WARN is nonzero, we will warn if no file is found
2347    through this prefix.  WARN should point to an int
2348    which will be set to 1 if this entry is used.
2349
2350    COMPONENT is the value to be passed to update_path.
2351
2352    REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
2353    the complete value of machine_suffix.
2354    2 means try both machine_suffix and just_machine_suffix.  */
2355
2356 static void
2357 add_prefix (pprefix, prefix, component, priority, require_machine_suffix, warn)
2358      struct path_prefix *pprefix;
2359      const char *prefix;
2360      const char *component;
2361      /* enum prefix_priority */ int priority;
2362      int require_machine_suffix;
2363      int *warn;
2364 {
2365   struct prefix_list *pl, **prev;
2366   int len;
2367
2368   for (prev = &pprefix->plist;
2369        (*prev) != NULL && (*prev)->priority <= priority;
2370        prev = &(*prev)->next)
2371     ;
2372
2373   /* Keep track of the longest prefix */
2374
2375   prefix = update_path (prefix, component);
2376   len = strlen (prefix);
2377   if (len > pprefix->max_len)
2378     pprefix->max_len = len;
2379
2380   pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
2381   pl->prefix = save_string (prefix, len);
2382   pl->require_machine_suffix = require_machine_suffix;
2383   pl->used_flag_ptr = warn;
2384   pl->priority = priority;
2385   if (warn)
2386     *warn = 0;
2387
2388   /* Insert after PREV */
2389   pl->next = (*prev);
2390   (*prev) = pl;
2391 }
2392 \f
2393 /* Execute the command specified by the arguments on the current line of spec.
2394    When using pipes, this includes several piped-together commands
2395    with `|' between them.
2396
2397    Return 0 if successful, -1 if failed.  */
2398
2399 static int
2400 execute ()
2401 {
2402   int i;
2403   int n_commands;               /* # of command.  */
2404   char *string;
2405   struct command
2406   {
2407     const char *prog;           /* program name.  */
2408     const char **argv;          /* vector of args.  */
2409     int pid;                    /* pid of process for this command.  */
2410   };
2411
2412   struct command *commands;     /* each command buffer with above info.  */
2413
2414   /* Count # of piped commands.  */
2415   for (n_commands = 1, i = 0; i < argbuf_index; i++)
2416     if (strcmp (argbuf[i], "|") == 0)
2417       n_commands++;
2418
2419   /* Get storage for each command.  */
2420   commands = (struct command *) alloca (n_commands * sizeof (struct command));
2421
2422   /* Split argbuf into its separate piped processes,
2423      and record info about each one.
2424      Also search for the programs that are to be run.  */
2425
2426   commands[0].prog = argbuf[0]; /* first command.  */
2427   commands[0].argv = &argbuf[0];
2428   string = find_a_file (&exec_prefixes, commands[0].prog, X_OK);
2429
2430   if (string)
2431     commands[0].argv[0] = string;
2432
2433   for (n_commands = 1, i = 0; i < argbuf_index; i++)
2434     if (strcmp (argbuf[i], "|") == 0)
2435       {                         /* each command.  */
2436 #if defined (__MSDOS__) || defined (OS2) || defined (VMS)
2437         fatal ("-pipe not supported");
2438 #endif
2439         argbuf[i] = 0;  /* termination of command args.  */
2440         commands[n_commands].prog = argbuf[i + 1];
2441         commands[n_commands].argv = &argbuf[i + 1];
2442         string = find_a_file (&exec_prefixes, commands[n_commands].prog, X_OK);
2443         if (string)
2444           commands[n_commands].argv[0] = string;
2445         n_commands++;
2446       }
2447
2448   argbuf[argbuf_index] = 0;
2449
2450   /* If -v, print what we are about to do, and maybe query.  */
2451
2452   if (verbose_flag)
2453     {
2454       /* For help listings, put a blank line between sub-processes.  */
2455       if (print_help_list)
2456         fputc ('\n', stderr);
2457
2458       /* Print each piped command as a separate line.  */
2459       for (i = 0; i < n_commands; i++)
2460         {
2461           const char *const *j;
2462
2463           for (j = commands[i].argv; *j; j++)
2464             fprintf (stderr, " %s", *j);
2465
2466           /* Print a pipe symbol after all but the last command.  */
2467           if (i + 1 != n_commands)
2468             fprintf (stderr, " |");
2469           fprintf (stderr, "\n");
2470         }
2471       fflush (stderr);
2472 #ifdef DEBUG
2473       notice ("\nGo ahead? (y or n) ");
2474       fflush (stderr);
2475       i = getchar ();
2476       if (i != '\n')
2477         while (getchar () != '\n')
2478           ;
2479
2480       if (i != 'y' && i != 'Y')
2481         return 0;
2482 #endif /* DEBUG */
2483     }
2484
2485   /* Run each piped subprocess.  */
2486
2487   for (i = 0; i < n_commands; i++)
2488     {
2489       char *errmsg_fmt, *errmsg_arg;
2490       const char *string = commands[i].argv[0];
2491
2492       /* For some bizarre reason, the second argument of execvp() is
2493          char *const *, not const char *const *.  */
2494       commands[i].pid = pexecute (string, (char *const *) commands[i].argv,
2495                                   programname, temp_filename,
2496                                   &errmsg_fmt, &errmsg_arg,
2497                                   ((i == 0 ? PEXECUTE_FIRST : 0)
2498                                    | (i + 1 == n_commands ? PEXECUTE_LAST : 0)
2499                                    | (string == commands[i].prog
2500                                       ? PEXECUTE_SEARCH : 0)
2501                                    | (verbose_flag ? PEXECUTE_VERBOSE : 0)));
2502
2503       if (commands[i].pid == -1)
2504         pfatal_pexecute (errmsg_fmt, errmsg_arg);
2505
2506       if (string != commands[i].prog)
2507         free ((PTR) string);
2508     }
2509
2510   execution_count++;
2511
2512   /* Wait for all the subprocesses to finish.
2513      We don't care what order they finish in;
2514      we know that N_COMMANDS waits will get them all.
2515      Ignore subprocesses that we don't know about,
2516      since they can be spawned by the process that exec'ed us.  */
2517
2518   {
2519     int ret_code = 0;
2520 #ifdef HAVE_GETRUSAGE
2521     struct timeval d;
2522     double ut = 0.0, st = 0.0;
2523 #endif
2524
2525     for (i = 0; i < n_commands;)
2526       {
2527         int j;
2528         int status;
2529         int pid;
2530
2531         pid = pwait (commands[i].pid, &status, 0);
2532         if (pid < 0)
2533           abort ();
2534
2535 #ifdef HAVE_GETRUSAGE
2536         if (report_times)
2537           {
2538             /* getrusage returns the total resource usage of all children
2539                up to now.  Copy the previous values into prus, get the
2540                current statistics, then take the difference.  */
2541
2542             prus = rus;
2543             getrusage (RUSAGE_CHILDREN, &rus);
2544             d.tv_sec = rus.ru_utime.tv_sec - prus.ru_utime.tv_sec;
2545             d.tv_usec = rus.ru_utime.tv_usec - prus.ru_utime.tv_usec;
2546             ut = (double) d.tv_sec + (double) d.tv_usec / 1.0e6;
2547
2548             d.tv_sec = rus.ru_stime.tv_sec - prus.ru_stime.tv_sec;
2549             d.tv_usec = rus.ru_stime.tv_usec - prus.ru_stime.tv_usec;
2550             st = (double) d.tv_sec + (double) d.tv_usec / 1.0e6;
2551           }
2552 #endif
2553
2554         for (j = 0; j < n_commands; j++)
2555           if (commands[j].pid == pid)
2556             {
2557               i++;
2558               if (WIFSIGNALED (status))
2559                 {
2560 #ifdef SIGPIPE
2561                   /* SIGPIPE is a special case.  It happens in -pipe mode
2562                      when the compiler dies before the preprocessor is
2563                      done, or the assembler dies before the compiler is
2564                      done.  There's generally been an error already, and
2565                      this is just fallout.  So don't generate another error
2566                      unless we would otherwise have succeeded.  */
2567                   if (WTERMSIG (status) == SIGPIPE
2568                       && (signal_count || greatest_status >= MIN_FATAL_STATUS))
2569                     ;
2570                   else
2571 #endif
2572                     fatal ("\
2573 Internal error: %s (program %s)\n\
2574 Please submit a full bug report.\n\
2575 See %s for instructions.",
2576                            strsignal (WTERMSIG (status)), commands[j].prog,
2577                            GCCBUGURL);
2578                   signal_count++;
2579                   ret_code = -1;
2580                 }
2581               else if (WIFEXITED (status)
2582                        && WEXITSTATUS (status) >= MIN_FATAL_STATUS)
2583                 {
2584                   if (WEXITSTATUS (status) > greatest_status)
2585                     greatest_status = WEXITSTATUS (status);
2586                   ret_code = -1;
2587                 }
2588 #ifdef HAVE_GETRUSAGE
2589               if (report_times && ut + st != 0)
2590                 notice ("# %s %.2f %.2f\n", commands[j].prog, ut, st);
2591 #endif
2592               break;
2593             }
2594       }
2595     return ret_code;
2596   }
2597 }
2598 \f
2599 /* Find all the switches given to us
2600    and make a vector describing them.
2601    The elements of the vector are strings, one per switch given.
2602    If a switch uses following arguments, then the `part1' field
2603    is the switch itself and the `args' field
2604    is a null-terminated vector containing the following arguments.
2605    The `live_cond' field is:
2606    0 when initialized
2607    1 if the switch is true in a conditional spec,
2608    -1 if false (overridden by a later switch)
2609    -2 if this switch should be ignored (used in %{<S})
2610    The `validated' field is nonzero if any spec has looked at this switch;
2611    if it remains zero at the end of the run, it must be meaningless.  */
2612
2613 #define SWITCH_OK       0
2614 #define SWITCH_FALSE   -1
2615 #define SWITCH_IGNORE  -2
2616 #define SWITCH_LIVE     1
2617
2618 struct switchstr
2619 {
2620   const char *part1;
2621   const char **args;
2622   int live_cond;
2623   int validated;
2624 };
2625
2626 static struct switchstr *switches;
2627
2628 static int n_switches;
2629
2630 struct infile
2631 {
2632   const char *name;
2633   const char *language;
2634 };
2635
2636 /* Also a vector of input files specified.  */
2637
2638 static struct infile *infiles;
2639
2640 static int n_infiles;
2641
2642 /* This counts the number of libraries added by lang_specific_driver, so that
2643    we can tell if there were any user supplied any files or libraries.  */
2644
2645 static int added_libraries;
2646
2647 /* And a vector of corresponding output files is made up later.  */
2648
2649 static const char **outfiles;
2650
2651 /* Used to track if none of the -B paths are used.  */
2652 static int warn_B;
2653
2654 /* Used to track if standard path isn't used and -b or -V is specified.  */
2655 static int warn_std;
2656
2657 /* Gives value to pass as "warn" to add_prefix for standard prefixes.  */
2658 static int *warn_std_ptr = 0;
2659 \f
2660 #if defined(HAVE_OBJECT_SUFFIX) || defined(HAVE_EXECUTABLE_SUFFIX)
2661
2662 /* Convert NAME to a new name if it is the standard suffix.  DO_EXE
2663    is true if we should look for an executable suffix as well.  */
2664
2665 static char *
2666 convert_filename (name, do_exe)
2667      char *name;
2668      int do_exe;
2669 {
2670   int i;
2671   int len;
2672
2673   if (name == NULL)
2674     return NULL;
2675
2676   len = strlen (name);
2677
2678 #ifdef HAVE_OBJECT_SUFFIX
2679   /* Convert x.o to x.obj if OBJECT_SUFFIX is ".obj".  */
2680   if (len > 2
2681       && name[len - 2] == '.'
2682       && name[len - 1] == 'o')
2683     {
2684       obstack_grow (&obstack, name, len - 2);
2685       obstack_grow0 (&obstack, OBJECT_SUFFIX, strlen (OBJECT_SUFFIX));
2686       name = obstack_finish (&obstack);
2687     }
2688 #endif
2689
2690 #ifdef HAVE_EXECUTABLE_SUFFIX
2691   /* If there is no filetype, make it the executable suffix (which includes
2692      the ".").  But don't get confused if we have just "-o".  */
2693   if (! do_exe || EXECUTABLE_SUFFIX[0] == 0 || (len == 2 && name[0] == '-'))
2694     return name;
2695
2696   for (i = len - 1; i >= 0; i--)
2697     if (IS_DIR_SEPARATOR (name[i]))
2698       break;
2699
2700   for (i++; i < len; i++)
2701     if (name[i] == '.')
2702       return name;
2703
2704   obstack_grow (&obstack, name, len);
2705   obstack_grow0 (&obstack, EXECUTABLE_SUFFIX, strlen (EXECUTABLE_SUFFIX));
2706   name = obstack_finish (&obstack);
2707 #endif
2708
2709   return name;
2710 }
2711 #endif
2712 \f
2713 /* Display the command line switches accepted by gcc.  */
2714 static void
2715 display_help ()
2716 {
2717   printf (_("Usage: %s [options] file...\n"), programname);
2718   fputs (_("Options:\n"), stdout);
2719
2720   fputs (_("  -pass-exit-codes         Exit with highest error code from a phase\n"), stdout);
2721   fputs (_("  --help                   Display this information\n"), stdout);
2722   if (! verbose_flag)
2723     fputs (_("  (Use '-v --help' to display command line options of sub-processes)\n"), stdout);
2724   fputs (_("  -dumpspecs               Display all of the built in spec strings\n"), stdout);
2725   fputs (_("  -dumpversion             Display the version of the compiler\n"), stdout);
2726   fputs (_("  -dumpmachine             Display the compiler's target processor\n"), stdout);
2727   fputs (_("  -print-search-dirs       Display the directories in the compiler's search path\n"), stdout);
2728   fputs (_("  -print-libgcc-file-name  Display the name of the compiler's companion library\n"), stdout);
2729   fputs (_("  -print-file-name=<lib>   Display the full path to library <lib>\n"), stdout);
2730   fputs (_("  -print-prog-name=<prog>  Display the full path to compiler component <prog>\n"), stdout);
2731   fputs (_("  -print-multi-directory   Display the root directory for versions of libgcc\n"), stdout);
2732   fputs (_("\
2733   -print-multi-lib         Display the mapping between command line options and\n\
2734                            multiple library search directories\n"), stdout);
2735   fputs (_("  -Wa,<options>            Pass comma-separated <options> on to the assembler\n"), stdout);
2736   fputs (_("  -Wp,<options>            Pass comma-separated <options> on to the preprocessor\n"), stdout);
2737   fputs (_("  -Wl,<options>            Pass comma-separated <options> on to the linker\n"), stdout);
2738   fputs (_("  -Xlinker <arg>           Pass <arg> on to the linker\n"), stdout);
2739   fputs (_("  -save-temps              Do not delete intermediate files\n"), stdout);
2740   fputs (_("  -pipe                    Use pipes rather than intermediate files\n"), stdout);
2741   fputs (_("  -time                    Time the execution of each subprocess\n"), stdout);
2742   fputs (_("  -specs=<file>            Override builtin specs with the contents of <file>\n"), stdout);
2743   fputs (_("  -std=<standard>          Assume that the input sources are for <standard>\n"), stdout);
2744   fputs (_("  -B <directory>           Add <directory> to the compiler's search paths\n"), stdout);
2745   fputs (_("  -b <machine>             Run gcc for target <machine>, if installed\n"), stdout);
2746   fputs (_("  -V <version>             Run gcc version number <version>, if installed\n"), stdout);
2747   fputs (_("  -v                       Display the programs invoked by the compiler\n"), stdout);
2748   fputs (_("  -E                       Preprocess only; do not compile, assemble or link\n"), stdout);
2749   fputs (_("  -S                       Compile only; do not assemble or link\n"), stdout);
2750   fputs (_("  -c                       Compile and assemble, but do not link\n"), stdout);
2751   fputs (_("  -o <file>                Place the output into <file>\n"), stdout);
2752   fputs (_("\
2753   -x <language>            Specify the language of the following input files\n\
2754                            Permissable languages include: c c++ assembler none\n\
2755                            'none' means revert to the default behaviour of\n\
2756                            guessing the language based on the file's extension\n\
2757 "), stdout);
2758
2759   printf (_("\
2760 \nOptions starting with -g, -f, -m, -O or -W are automatically passed on to\n\
2761 the various sub-processes invoked by %s.  In order to pass other options\n\
2762 on to these processes the -W<letter> options must be used.\n\
2763 "), programname);
2764
2765   /* The rest of the options are displayed by invocations of the various
2766      sub-processes.  */
2767 }
2768
2769 static void
2770 add_preprocessor_option (option, len)
2771      const char *option;
2772      int len;
2773 {
2774   n_preprocessor_options++;
2775
2776   if (! preprocessor_options)
2777     preprocessor_options
2778       = (char **) xmalloc (n_preprocessor_options * sizeof (char *));
2779   else
2780     preprocessor_options
2781       = (char **) xrealloc (preprocessor_options,
2782                             n_preprocessor_options * sizeof (char *));
2783
2784   preprocessor_options [n_preprocessor_options - 1] =
2785     save_string (option, len);
2786 }
2787
2788 static void
2789 add_assembler_option (option, len)
2790      const char *option;
2791      int len;
2792 {
2793   n_assembler_options++;
2794
2795   if (! assembler_options)
2796     assembler_options
2797       = (char **) xmalloc (n_assembler_options * sizeof (char *));
2798   else
2799     assembler_options
2800       = (char **) xrealloc (assembler_options,
2801                             n_assembler_options * sizeof (char *));
2802
2803   assembler_options [n_assembler_options - 1] = save_string (option, len);
2804 }
2805
2806 static void
2807 add_linker_option (option, len)
2808      const char *option;
2809      int len;
2810 {
2811   n_linker_options++;
2812
2813   if (! linker_options)
2814     linker_options
2815       = (char **) xmalloc (n_linker_options * sizeof (char *));
2816   else
2817     linker_options
2818       = (char **) xrealloc (linker_options,
2819                             n_linker_options * sizeof (char *));
2820
2821   linker_options [n_linker_options - 1] = save_string (option, len);
2822 }
2823 \f
2824 /* Create the vector `switches' and its contents.
2825    Store its length in `n_switches'.  */
2826
2827 static void
2828 process_command (argc, argv)
2829      int argc;
2830      const char *const *argv;
2831 {
2832   register int i;
2833   const char *temp;
2834   char *temp1;
2835   const char *spec_lang = 0;
2836   int last_language_n_infiles;
2837   int have_c = 0;
2838   int have_o = 0;
2839   int lang_n_infiles = 0;
2840
2841   GET_ENV_PATH_LIST (gcc_exec_prefix, "GCC_EXEC_PREFIX");
2842
2843   n_switches = 0;
2844   n_infiles = 0;
2845   added_libraries = 0;
2846
2847   /* Figure compiler version from version string.  */
2848
2849   compiler_version = temp1 = xstrdup (version_string);
2850
2851   for (; *temp1; ++temp1)
2852     {
2853       if (*temp1 == ' ')
2854         {
2855           *temp1 = '\0';
2856           break;
2857         }
2858     }
2859
2860   /* Set up the default search paths.  If there is no GCC_EXEC_PREFIX,
2861      see if we can create it from the pathname specified in argv[0].  */
2862
2863 #ifndef VMS
2864   /* FIXME: make_relative_prefix doesn't yet work for VMS.  */
2865   if (!gcc_exec_prefix)
2866     {
2867       gcc_exec_prefix = make_relative_prefix (argv[0], standard_bindir_prefix,
2868                                               standard_exec_prefix);
2869       if (gcc_exec_prefix)
2870         putenv (concat ("GCC_EXEC_PREFIX=", gcc_exec_prefix, NULL_PTR));
2871     }
2872 #endif
2873
2874   if (gcc_exec_prefix)
2875     {
2876       int len = strlen (gcc_exec_prefix);
2877       if (len > (int) sizeof ("/lib/gcc-lib/") - 1
2878           && (IS_DIR_SEPARATOR (gcc_exec_prefix[len-1])))
2879         {
2880           temp = gcc_exec_prefix + len - sizeof ("/lib/gcc-lib/") + 1;
2881           if (IS_DIR_SEPARATOR (*temp)
2882               && strncmp (temp + 1, "lib", 3) == 0
2883               && IS_DIR_SEPARATOR (temp[4])
2884               && strncmp (temp + 5, "gcc-lib", 7) == 0)
2885             len -= sizeof ("/lib/gcc-lib/") - 1;
2886         }
2887
2888       set_std_prefix (gcc_exec_prefix, len);
2889       add_prefix (&exec_prefixes, gcc_exec_prefix, "GCC",
2890                   PREFIX_PRIORITY_LAST, 0, NULL_PTR);
2891       add_prefix (&startfile_prefixes, gcc_exec_prefix, "GCC",
2892                   PREFIX_PRIORITY_LAST, 0, NULL_PTR);
2893     }
2894
2895   /* COMPILER_PATH and LIBRARY_PATH have values
2896      that are lists of directory names with colons.  */
2897
2898   GET_ENV_PATH_LIST (temp, "COMPILER_PATH");
2899   if (temp)
2900     {
2901       const char *startp, *endp;
2902       char *nstore = (char *) alloca (strlen (temp) + 3);
2903
2904       startp = endp = temp;
2905       while (1)
2906         {
2907           if (*endp == PATH_SEPARATOR || *endp == 0)
2908             {
2909               strncpy (nstore, startp, endp - startp);
2910               if (endp == startp)
2911                 strcpy (nstore, concat (".", dir_separator_str, NULL_PTR));
2912               else if (!IS_DIR_SEPARATOR (endp[-1]))
2913                 {
2914                   nstore[endp - startp] = DIR_SEPARATOR;
2915                   nstore[endp - startp + 1] = 0;
2916                 }
2917               else
2918                 nstore[endp - startp] = 0;
2919               add_prefix (&exec_prefixes, nstore, 0,
2920                           PREFIX_PRIORITY_LAST, 0, NULL_PTR);
2921               add_prefix (&include_prefixes,
2922                           concat (nstore, "include", NULL_PTR),
2923                           0, PREFIX_PRIORITY_LAST, 0, NULL_PTR);
2924               if (*endp == 0)
2925                 break;
2926               endp = startp = endp + 1;
2927             }
2928           else
2929             endp++;
2930         }
2931     }
2932
2933   GET_ENV_PATH_LIST (temp, LIBRARY_PATH_ENV);
2934   if (temp && *cross_compile == '0')
2935     {
2936       const char *startp, *endp;
2937       char *nstore = (char *) alloca (strlen (temp) + 3);
2938
2939       startp = endp = temp;
2940       while (1)
2941         {
2942           if (*endp == PATH_SEPARATOR || *endp == 0)
2943             {
2944               strncpy (nstore, startp, endp - startp);
2945               if (endp == startp)
2946                 strcpy (nstore, concat (".", dir_separator_str, NULL_PTR));
2947               else if (!IS_DIR_SEPARATOR (endp[-1]))
2948                 {
2949                   nstore[endp - startp] = DIR_SEPARATOR;
2950                   nstore[endp - startp + 1] = 0;
2951                 }
2952               else
2953                 nstore[endp - startp] = 0;
2954               add_prefix (&startfile_prefixes, nstore, NULL_PTR,
2955                           PREFIX_PRIORITY_LAST, 0, NULL_PTR);
2956               if (*endp == 0)
2957                 break;
2958               endp = startp = endp + 1;
2959             }
2960           else
2961             endp++;
2962         }
2963     }
2964
2965   /* Use LPATH like LIBRARY_PATH (for the CMU build program).  */
2966   GET_ENV_PATH_LIST (temp, "LPATH");
2967   if (temp && *cross_compile == '0')
2968     {
2969       const char *startp, *endp;
2970       char *nstore = (char *) alloca (strlen (temp) + 3);
2971
2972       startp = endp = temp;
2973       while (1)
2974         {
2975           if (*endp == PATH_SEPARATOR || *endp == 0)
2976             {
2977               strncpy (nstore, startp, endp - startp);
2978               if (endp == startp)
2979                 strcpy (nstore, concat (".", dir_separator_str, NULL_PTR));
2980               else if (!IS_DIR_SEPARATOR (endp[-1]))
2981                 {
2982                   nstore[endp - startp] = DIR_SEPARATOR;
2983                   nstore[endp - startp + 1] = 0;
2984                 }
2985               else
2986                 nstore[endp - startp] = 0;
2987               add_prefix (&startfile_prefixes, nstore, NULL_PTR,
2988                           PREFIX_PRIORITY_LAST, 0, NULL_PTR);
2989               if (*endp == 0)
2990                 break;
2991               endp = startp = endp + 1;
2992             }
2993           else
2994             endp++;
2995         }
2996     }
2997
2998   /* Convert new-style -- options to old-style.  */
2999   translate_options (&argc, &argv);
3000
3001   /* Do language-specific adjustment/addition of flags.  */
3002   lang_specific_driver (&argc, &argv, &added_libraries);
3003
3004   /* Scan argv twice.  Here, the first time, just count how many switches
3005      there will be in their vector, and how many input files in theirs.
3006      Here we also parse the switches that cc itself uses (e.g. -v).  */
3007
3008   for (i = 1; i < argc; i++)
3009     {
3010       if (! strcmp (argv[i], "-dumpspecs"))
3011         {
3012           struct spec_list *sl;
3013           init_spec ();
3014           for (sl = specs; sl; sl = sl->next)
3015             printf ("*%s:\n%s\n\n", sl->name, *(sl->ptr_spec));
3016           if (link_command_spec)
3017             printf ("*link_command:\n%s\n\n", link_command_spec);
3018           exit (0);
3019         }
3020       else if (! strcmp (argv[i], "-dumpversion"))
3021         {
3022           printf ("%s\n", spec_version);
3023           exit (0);
3024         }
3025       else if (! strcmp (argv[i], "-dumpmachine"))
3026         {
3027           printf ("%s\n", spec_machine);
3028           exit (0);
3029         }
3030       else if (strcmp (argv[i], "-fhelp") == 0)
3031         {
3032           /* translate_options () has turned --help into -fhelp.  */
3033           print_help_list = 1;
3034
3035           /* We will be passing a dummy file on to the sub-processes.  */
3036           n_infiles++;
3037           n_switches++;
3038
3039           add_preprocessor_option ("--help", 6);
3040           add_assembler_option ("--help", 6);
3041           add_linker_option ("--help", 6);
3042         }
3043       else if (! strcmp (argv[i], "-pass-exit-codes"))
3044         {
3045           pass_exit_codes = 1;
3046           n_switches++;
3047         }
3048       else if (! strcmp (argv[i], "-print-search-dirs"))
3049         print_search_dirs = 1;
3050       else if (! strcmp (argv[i], "-print-libgcc-file-name"))
3051         print_file_name = "libgcc.a";
3052       else if (! strncmp (argv[i], "-print-file-name=", 17))
3053         print_file_name = argv[i] + 17;
3054       else if (! strncmp (argv[i], "-print-prog-name=", 17))
3055         print_prog_name = argv[i] + 17;
3056       else if (! strcmp (argv[i], "-print-multi-lib"))
3057         print_multi_lib = 1;
3058       else if (! strcmp (argv[i], "-print-multi-directory"))
3059         print_multi_directory = 1;
3060       else if (! strncmp (argv[i], "-Wa,", 4))
3061         {
3062           int prev, j;
3063           /* Pass the rest of this option to the assembler.  */
3064
3065           /* Split the argument at commas.  */
3066           prev = 4;
3067           for (j = 4; argv[i][j]; j++)
3068             if (argv[i][j] == ',')
3069               {
3070                 add_assembler_option (argv[i] + prev, j - prev);
3071                 prev = j + 1;
3072               }
3073
3074           /* Record the part after the last comma.  */
3075           add_assembler_option (argv[i] + prev, j - prev);
3076         }
3077       else if (! strncmp (argv[i], "-Wp,", 4))
3078         {
3079           int prev, j;
3080           /* Pass the rest of this option to the preprocessor.  */
3081
3082           /* Split the argument at commas.  */
3083           prev = 4;
3084           for (j = 4; argv[i][j]; j++)
3085             if (argv[i][j] == ',')
3086               {
3087                 add_preprocessor_option (argv[i] + prev, j - prev);
3088                 prev = j + 1;
3089               }
3090
3091           /* Record the part after the last comma.  */
3092           add_preprocessor_option (argv[i] + prev, j - prev);
3093         }
3094       else if (argv[i][0] == '+' && argv[i][1] == 'e')
3095         /* The +e options to the C++ front-end.  */
3096         n_switches++;
3097       else if (strncmp (argv[i], "-Wl,", 4) == 0)
3098         {
3099           int j;
3100           /* Split the argument at commas.  */
3101           for (j = 3; argv[i][j]; j++)
3102             n_infiles += (argv[i][j] == ',');
3103         }
3104       else if (strcmp (argv[i], "-Xlinker") == 0)
3105         {
3106           if (i + 1 == argc)
3107             fatal ("argument to `-Xlinker' is missing");
3108
3109           n_infiles++;
3110           i++;
3111         }
3112       else if (strncmp (argv[i], "-l", 2) == 0)
3113         n_infiles++;
3114       else if (strcmp (argv[i], "-save-temps") == 0)
3115         {
3116           save_temps_flag = 1;
3117           n_switches++;
3118         }
3119       else if (strcmp (argv[i], "-specs") == 0)
3120         {
3121           struct user_specs *user = (struct user_specs *)
3122             xmalloc (sizeof (struct user_specs));
3123           if (++i >= argc)
3124             fatal ("argument to `-specs' is missing");
3125
3126           user->next = (struct user_specs *) 0;
3127           user->filename = argv[i];
3128           if (user_specs_tail)
3129             user_specs_tail->next = user;
3130           else
3131             user_specs_head = user;
3132           user_specs_tail = user;
3133         }
3134       else if (strncmp (argv[i], "-specs=", 7) == 0)
3135         {
3136           struct user_specs *user = (struct user_specs *)
3137             xmalloc (sizeof (struct user_specs));
3138           if (strlen (argv[i]) == 7)
3139             fatal ("argument to `-specs=' is missing");
3140
3141           user->next = (struct user_specs *) 0;
3142           user->filename = argv[i] + 7;
3143           if (user_specs_tail)
3144             user_specs_tail->next = user;
3145           else
3146             user_specs_head = user;
3147           user_specs_tail = user;
3148         }
3149       else if (strcmp (argv[i], "-time") == 0)
3150         report_times = 1;
3151       else if (argv[i][0] == '-' && argv[i][1] != 0)
3152         {
3153           register const char *p = &argv[i][1];
3154           register int c = *p;
3155
3156           switch (c)
3157             {
3158             case 'b':
3159               n_switches++;
3160               if (p[1] == 0 && i + 1 == argc)
3161                 fatal ("argument to `-b' is missing");
3162               if (p[1] == 0)
3163                 spec_machine = argv[++i];
3164               else
3165                 spec_machine = p + 1;
3166
3167               warn_std_ptr = &warn_std;
3168               break;
3169
3170             case 'B':
3171               {
3172                 const char *value;
3173                 if (p[1] == 0 && i + 1 == argc)
3174                   fatal ("argument to `-B' is missing");
3175                 if (p[1] == 0)
3176                   value = argv[++i];
3177                 else
3178                   value = p + 1;
3179                 {
3180                   /* As a kludge, if the arg is "[foo/]stageN/", just
3181                      add "[foo/]include" to the include prefix.  */
3182                   int len = strlen (value);
3183                   if ((len == 7
3184                        || (len > 7
3185                            && (IS_DIR_SEPARATOR (value[len - 8]))))
3186                       && strncmp (value + len - 7, "stage", 5) == 0
3187                       && ISDIGIT (value[len - 2])
3188                       && (IS_DIR_SEPARATOR (value[len - 1])))
3189                     {
3190                       if (len == 7)
3191                         add_prefix (&include_prefixes, "include", NULL_PTR,
3192                                     PREFIX_PRIORITY_B_OPT, 0, NULL_PTR);
3193                       else
3194                         {
3195                           char *string = xmalloc (len + 1);
3196                           strncpy (string, value, len-7);
3197                           strcpy (string+len-7, "include");
3198                           add_prefix (&include_prefixes, string, NULL_PTR,
3199                                       PREFIX_PRIORITY_B_OPT, 0, NULL_PTR);
3200                         }
3201                     }
3202                 }
3203                 add_prefix (&exec_prefixes, value, NULL_PTR,
3204                             PREFIX_PRIORITY_B_OPT, 0, &warn_B);
3205                 add_prefix (&startfile_prefixes, value, NULL_PTR,
3206                             PREFIX_PRIORITY_B_OPT, 0, &warn_B);
3207                 add_prefix (&include_prefixes, concat (value, "include",
3208                                                        NULL_PTR),
3209                             NULL_PTR,
3210                             PREFIX_PRIORITY_B_OPT, 0, NULL_PTR);
3211                 n_switches++;
3212               }
3213               break;
3214
3215             case 'v':   /* Print our subcommands and print versions.  */
3216               n_switches++;
3217               /* If they do anything other than exactly `-v', don't set
3218                  verbose_flag; rather, continue on to give the error.  */
3219               if (p[1] != 0)
3220                 break;
3221               verbose_flag++;
3222               break;
3223
3224             case 'V':
3225               n_switches++;
3226               if (p[1] == 0 && i + 1 == argc)
3227                 fatal ("argument to `-V' is missing");
3228               if (p[1] == 0)
3229                 spec_version = argv[++i];
3230               else
3231                 spec_version = p + 1;
3232               compiler_version = spec_version;
3233               warn_std_ptr = &warn_std;
3234
3235               /* Validate the version number.  Use the same checks
3236                  done when inserting it into a spec.
3237
3238                  The format of the version string is
3239                  ([^0-9]*-)?[0-9]+[.][0-9]+([.][0-9]+)?([- ].*)?  */
3240               {
3241                 const char *v = compiler_version;
3242
3243                 /* Ignore leading non-digits.  i.e. "foo-" in "foo-2.7.2".  */
3244                 while (! ISDIGIT (*v))
3245                   v++;
3246
3247                 if (v > compiler_version && v[-1] != '-')
3248                   fatal ("invalid version number format");
3249
3250                 /* Set V after the first period.  */
3251                 while (ISDIGIT (*v))
3252                   v++;
3253
3254                 if (*v != '.')
3255                   fatal ("invalid version number format");
3256
3257                 v++;
3258                 while (ISDIGIT (*v))
3259                   v++;
3260
3261                 if (*v != 0 && *v != ' ' && *v != '.' && *v != '-')
3262                   fatal ("invalid version number format");
3263               }
3264               break;
3265
3266             case 'S':
3267             case 'c':
3268               if (p[1] == 0)
3269                 {
3270                   have_c = 1;
3271                   n_switches++;
3272                   break;
3273                 }
3274               goto normal_switch;
3275
3276             case 'o':
3277               have_o = 1;
3278 #if defined(HAVE_EXECUTABLE_SUFFIX)
3279               if (! have_c)
3280                 {
3281                   int skip;
3282
3283                   /* Forward scan, just in case -S or -c is specified
3284                      after -o.  */
3285                   int j = i + 1;
3286                   if (p[1] == 0)
3287                     ++j;
3288                   while (j < argc)
3289                     {
3290                       if (argv[j][0] == '-')
3291                         {
3292                           if (SWITCH_CURTAILS_COMPILATION (argv[j][1])
3293                               && argv[j][2] == 0)
3294                             {
3295                               have_c = 1;
3296                               break;
3297                             }
3298                           else if (skip = SWITCH_TAKES_ARG (argv[j][1]))
3299                             j += skip - (argv[j][2] != 0);
3300                           else if (skip = WORD_SWITCH_TAKES_ARG (argv[j] + 1))
3301                             j += skip;
3302                         }
3303                       j++;
3304                     }
3305                 }
3306 #endif
3307 #if defined(HAVE_EXECUTABLE_SUFFIX) || defined(HAVE_OBJECT_SUFFIX)
3308               if (p[1] == 0)
3309                 argv[i + 1] = convert_filename (argv[i + 1], ! have_c);
3310               else
3311                 argv[i] = convert_filename (argv[i], ! have_c);
3312 #endif
3313               goto normal_switch;
3314
3315             default:
3316             normal_switch:
3317               n_switches++;
3318
3319               if (SWITCH_TAKES_ARG (c) > (p[1] != 0))
3320                 i += SWITCH_TAKES_ARG (c) - (p[1] != 0);
3321               else if (WORD_SWITCH_TAKES_ARG (p))
3322                 i += WORD_SWITCH_TAKES_ARG (p);
3323             }
3324         }
3325       else
3326         {
3327           n_infiles++;
3328           lang_n_infiles++;
3329         }
3330     }
3331
3332   if (have_c && have_o && lang_n_infiles > 1)
3333     fatal ("cannot specify -o with -c or -S and multiple compilations");
3334
3335   /* Set up the search paths before we go looking for config files.  */
3336
3337   /* These come before the md prefixes so that we will find gcc's subcommands
3338      (such as cpp) rather than those of the host system.  */
3339   /* Use 2 as fourth arg meaning try just the machine as a suffix,
3340      as well as trying the machine and the version.  */
3341 #ifndef OS2
3342   add_prefix (&exec_prefixes, standard_exec_prefix, "GCC",
3343               PREFIX_PRIORITY_LAST, 1, warn_std_ptr);
3344   add_prefix (&exec_prefixes, standard_exec_prefix, "BINUTILS",
3345               PREFIX_PRIORITY_LAST, 2, warn_std_ptr);
3346   add_prefix (&exec_prefixes, standard_exec_prefix_1, "BINUTILS",
3347               PREFIX_PRIORITY_LAST, 2, warn_std_ptr);
3348 #endif
3349
3350   add_prefix (&startfile_prefixes, standard_exec_prefix, "BINUTILS",
3351               PREFIX_PRIORITY_LAST, 1, warn_std_ptr);
3352   add_prefix (&startfile_prefixes, standard_exec_prefix_1, "BINUTILS",
3353               PREFIX_PRIORITY_LAST, 1, warn_std_ptr);
3354
3355   tooldir_prefix = concat (tooldir_base_prefix, spec_machine,
3356                            dir_separator_str, NULL_PTR);
3357
3358   /* If tooldir is relative, base it on exec_prefixes.  A relative
3359      tooldir lets us move the installed tree as a unit.
3360
3361      If GCC_EXEC_PREFIX is defined, then we want to add two relative
3362      directories, so that we can search both the user specified directory
3363      and the standard place.  */
3364
3365   if (!IS_DIR_SEPARATOR (*tooldir_prefix))
3366     {
3367       if (gcc_exec_prefix)
3368         {
3369           char *gcc_exec_tooldir_prefix
3370             = concat (gcc_exec_prefix, spec_machine, dir_separator_str,
3371                       spec_version, dir_separator_str, tooldir_prefix, NULL_PTR);
3372
3373           add_prefix (&exec_prefixes,
3374                       concat (gcc_exec_tooldir_prefix, "bin",
3375                               dir_separator_str, NULL_PTR),
3376                       NULL_PTR, PREFIX_PRIORITY_LAST, 0, NULL_PTR);
3377           add_prefix (&startfile_prefixes,
3378                       concat (gcc_exec_tooldir_prefix, "lib",
3379                               dir_separator_str, NULL_PTR),
3380                       NULL_PTR, PREFIX_PRIORITY_LAST, 0, NULL_PTR);
3381         }
3382
3383       tooldir_prefix = concat (standard_exec_prefix, spec_machine,
3384                                dir_separator_str, spec_version,
3385                                dir_separator_str, tooldir_prefix, NULL_PTR);
3386     }
3387
3388   add_prefix (&exec_prefixes,
3389               concat (tooldir_prefix, "bin", dir_separator_str, NULL_PTR),
3390               "BINUTILS", PREFIX_PRIORITY_LAST, 0, NULL_PTR);
3391   add_prefix (&startfile_prefixes,
3392               concat (tooldir_prefix, "lib", dir_separator_str, NULL_PTR),
3393               "BINUTILS", PREFIX_PRIORITY_LAST, 0, NULL_PTR);
3394
3395   /* More prefixes are enabled in main, after we read the specs file
3396      and determine whether this is cross-compilation or not.  */
3397
3398   /* Then create the space for the vectors and scan again.  */
3399
3400   switches = ((struct switchstr *)
3401               xmalloc ((n_switches + 1) * sizeof (struct switchstr)));
3402   infiles = (struct infile *) xmalloc ((n_infiles + 1) * sizeof (struct infile));
3403   n_switches = 0;
3404   n_infiles = 0;
3405   last_language_n_infiles = -1;
3406
3407   /* This, time, copy the text of each switch and store a pointer
3408      to the copy in the vector of switches.
3409      Store all the infiles in their vector.  */
3410
3411   for (i = 1; i < argc; i++)
3412     {
3413       /* Just skip the switches that were handled by the preceding loop.  */
3414       if (! strncmp (argv[i], "-Wa,", 4))
3415         ;
3416       else if (! strncmp (argv[i], "-Wp,", 4))
3417         ;
3418       else if (! strcmp (argv[i], "-pass-exit-codes"))
3419         ;
3420       else if (! strcmp (argv[i], "-print-search-dirs"))
3421         ;
3422       else if (! strcmp (argv[i], "-print-libgcc-file-name"))
3423         ;
3424       else if (! strncmp (argv[i], "-print-file-name=", 17))
3425         ;
3426       else if (! strncmp (argv[i], "-print-prog-name=", 17))
3427         ;
3428       else if (! strcmp (argv[i], "-print-multi-lib"))
3429         ;
3430       else if (! strcmp (argv[i], "-print-multi-directory"))
3431         ;
3432       else if (strcmp (argv[i], "-fhelp") == 0)
3433         {
3434           if (verbose_flag)
3435             {
3436               /* Create a dummy input file, so that we can pass --help on to
3437                  the various sub-processes.  */
3438               infiles[n_infiles].language = "c";
3439               infiles[n_infiles++].name   = "help-dummy";
3440
3441               /* Preserve the --help switch so that it can be caught by the
3442                  cc1 spec string.  */
3443               switches[n_switches].part1     = "--help";
3444               switches[n_switches].args      = 0;
3445               switches[n_switches].live_cond = SWITCH_OK;
3446               switches[n_switches].validated     = 0;
3447
3448               n_switches++;
3449             }
3450         }
3451       else if (argv[i][0] == '+' && argv[i][1] == 'e')
3452         {
3453           /* Compensate for the +e options to the C++ front-end;
3454              they're there simply for cfront call-compatibility.  We do
3455              some magic in default_compilers to pass them down properly.
3456              Note we deliberately start at the `+' here, to avoid passing
3457              -e0 or -e1 down into the linker.  */
3458           switches[n_switches].part1 = &argv[i][0];
3459           switches[n_switches].args = 0;
3460           switches[n_switches].live_cond = SWITCH_OK;
3461           switches[n_switches].validated = 0;
3462           n_switches++;
3463         }
3464       else if (strncmp (argv[i], "-Wl,", 4) == 0)
3465         {
3466           int prev, j;
3467           /* Split the argument at commas.  */
3468           prev = 4;
3469           for (j = 4; argv[i][j]; j++)
3470             if (argv[i][j] == ',')
3471               {
3472                 infiles[n_infiles].language = "*";
3473                 infiles[n_infiles++].name
3474                   = save_string (argv[i] + prev, j - prev);
3475                 prev = j + 1;
3476               }
3477           /* Record the part after the last comma.  */
3478           infiles[n_infiles].language = "*";
3479           infiles[n_infiles++].name = argv[i] + prev;
3480         }
3481       else if (strcmp (argv[i], "-Xlinker") == 0)
3482         {
3483           infiles[n_infiles].language = "*";
3484           infiles[n_infiles++].name = argv[++i];
3485         }
3486       else if (strncmp (argv[i], "-l", 2) == 0)
3487         {
3488           infiles[n_infiles].language = "*";
3489           infiles[n_infiles++].name = argv[i];
3490         }
3491       else if (strcmp (argv[i], "-specs") == 0)
3492         i++;
3493       else if (strncmp (argv[i], "-specs=", 7) == 0)
3494         ;
3495       else if (strcmp (argv[i], "-time") == 0)
3496         ;
3497       else if ((save_temps_flag || report_times)
3498                && strcmp (argv[i], "-pipe") == 0)
3499         {
3500           /* -save-temps overrides -pipe, so that temp files are produced */
3501           if (save_temps_flag)
3502             error ("Warning: -pipe ignored since -save-temps specified");
3503           /* -time overrides -pipe because we can't get correct stats when
3504              multiple children are running at once.  */
3505           else if (report_times)
3506             error ("Warning: -pipe ignored since -time specified");
3507         }
3508       else if (argv[i][0] == '-' && argv[i][1] != 0)
3509         {
3510           const char *p = &argv[i][1];
3511           int c = *p;
3512
3513           if (c == 'x')
3514             {
3515               if (p[1] == 0 && i + 1 == argc)
3516                 fatal ("argument to `-x' is missing");
3517               if (p[1] == 0)
3518                 spec_lang = argv[++i];
3519               else
3520                 spec_lang = p + 1;
3521               if (! strcmp (spec_lang, "none"))
3522                 /* Suppress the warning if -xnone comes after the last input
3523                    file, because alternate command interfaces like g++ might
3524                    find it useful to place -xnone after each input file.  */
3525                 spec_lang = 0;
3526               else
3527                 last_language_n_infiles = n_infiles;
3528               continue;
3529             }
3530           switches[n_switches].part1 = p;
3531           /* Deal with option arguments in separate argv elements.  */
3532           if ((SWITCH_TAKES_ARG (c) > (p[1] != 0))
3533               || WORD_SWITCH_TAKES_ARG (p))
3534             {
3535               int j = 0;
3536               int n_args = WORD_SWITCH_TAKES_ARG (p);
3537
3538               if (n_args == 0)
3539                 {
3540                   /* Count only the option arguments in separate argv elements.  */
3541                   n_args = SWITCH_TAKES_ARG (c) - (p[1] != 0);
3542                 }
3543               if (i + n_args >= argc)
3544                 fatal ("argument to `-%s' is missing", p);
3545               switches[n_switches].args
3546                 = (const char **) xmalloc ((n_args + 1) * sizeof(const char *));
3547               while (j < n_args)
3548                 switches[n_switches].args[j++] = argv[++i];
3549               /* Null-terminate the vector.  */
3550               switches[n_switches].args[j] = 0;
3551             }
3552           else if (index (switches_need_spaces, c))
3553             {
3554               /* On some systems, ld cannot handle some options without
3555                  a space.  So split the option from its argument.  */
3556               char *part1 = (char *) xmalloc (2);
3557               char *tmp;
3558               part1[0] = c;
3559               part1[1] = '\0';
3560
3561               switches[n_switches].part1 = part1;
3562               switches[n_switches].args
3563                 = (const char **) xmalloc (2 * sizeof (const char *));
3564               switches[n_switches].args[0] = tmp = xmalloc (strlen (p));
3565               strcpy (tmp, &p[1]);
3566               switches[n_switches].args[1] = 0;
3567             }
3568           else
3569             switches[n_switches].args = 0;
3570
3571           switches[n_switches].live_cond = SWITCH_OK;
3572           switches[n_switches].validated = 0;
3573           /* This is always valid, since gcc.c itself understands it.  */
3574           if (!strcmp (p, "save-temps"))
3575             switches[n_switches].validated = 1;
3576           else
3577             {
3578               char ch = switches[n_switches].part1[0];
3579               if (ch == 'V' || ch == 'b' || ch == 'B')
3580                 switches[n_switches].validated = 1;
3581             }
3582           n_switches++;
3583         }
3584       else
3585         {
3586 #ifdef HAVE_OBJECT_SUFFIX
3587           argv[i] = convert_filename (argv[i], 0);
3588 #endif
3589
3590           if (strcmp (argv[i], "-") != 0 && access (argv[i], R_OK) < 0)
3591             {
3592               perror_with_name (argv[i]);
3593               error_count++;
3594             }
3595           else
3596             {
3597               infiles[n_infiles].language = spec_lang;
3598               infiles[n_infiles++].name = argv[i];
3599             }
3600         }
3601     }
3602
3603   if (n_infiles == last_language_n_infiles && spec_lang != 0)
3604     error ("Warning: `-x %s' after last input file has no effect", spec_lang);
3605
3606   switches[n_switches].part1 = 0;
3607   infiles[n_infiles].name = 0;
3608 }
3609 \f
3610 /* Process a spec string, accumulating and running commands.  */
3611
3612 /* These variables describe the input file name.
3613    input_file_number is the index on outfiles of this file,
3614    so that the output file name can be stored for later use by %o.
3615    input_basename is the start of the part of the input file
3616    sans all directory names, and basename_length is the number
3617    of characters starting there excluding the suffix .c or whatever.  */
3618
3619 const char *input_filename;
3620 static int input_file_number;
3621 size_t input_filename_length;
3622 static int basename_length;
3623 static int suffixed_basename_length;
3624 static const char *input_basename;
3625 static const char *input_suffix;
3626
3627 /* These are variables used within do_spec and do_spec_1.  */
3628
3629 /* Nonzero if an arg has been started and not yet terminated
3630    (with space, tab or newline).  */
3631 static int arg_going;
3632
3633 /* Nonzero means %d or %g has been seen; the next arg to be terminated
3634    is a temporary file name.  */
3635 static int delete_this_arg;
3636
3637 /* Nonzero means %w has been seen; the next arg to be terminated
3638    is the output file name of this compilation.  */
3639 static int this_is_output_file;
3640
3641 /* Nonzero means %s has been seen; the next arg to be terminated
3642    is the name of a library file and we should try the standard
3643    search dirs for it.  */
3644 static int this_is_library_file;
3645
3646 /* Nonzero means that the input of this command is coming from a pipe.  */
3647 static int input_from_pipe;
3648
3649 /* Process the spec SPEC and run the commands specified therein.
3650    Returns 0 if the spec is successfully processed; -1 if failed.  */
3651
3652 int
3653 do_spec (spec)
3654      const char *spec;
3655 {
3656   int value;
3657
3658   clear_args ();
3659   arg_going = 0;
3660   delete_this_arg = 0;
3661   this_is_output_file = 0;
3662   this_is_library_file = 0;
3663   input_from_pipe = 0;
3664
3665   value = do_spec_1 (spec, 0, NULL_PTR);
3666
3667   /* Force out any unfinished command.
3668      If -pipe, this forces out the last command if it ended in `|'.  */
3669   if (value == 0)
3670     {
3671       if (argbuf_index > 0 && !strcmp (argbuf[argbuf_index - 1], "|"))
3672         argbuf_index--;
3673
3674       if (argbuf_index > 0)
3675         value = execute ();
3676     }
3677
3678   return value;
3679 }
3680
3681 /* Process the sub-spec SPEC as a portion of a larger spec.
3682    This is like processing a whole spec except that we do
3683    not initialize at the beginning and we do not supply a
3684    newline by default at the end.
3685    INSWITCH nonzero means don't process %-sequences in SPEC;
3686    in this case, % is treated as an ordinary character.
3687    This is used while substituting switches.
3688    INSWITCH nonzero also causes SPC not to terminate an argument.
3689
3690    Value is zero unless a line was finished
3691    and the command on that line reported an error.  */
3692
3693 static int
3694 do_spec_1 (spec, inswitch, soft_matched_part)
3695      const char *spec;
3696      int inswitch;
3697      const char *soft_matched_part;
3698 {
3699   register const char *p = spec;
3700   register int c;
3701   int i;
3702   const char *string;
3703   int value;
3704
3705   while ((c = *p++))
3706     /* If substituting a switch, treat all chars like letters.
3707        Otherwise, NL, SPC, TAB and % are special.  */
3708     switch (inswitch ? 'a' : c)
3709       {
3710       case '\n':
3711         /* End of line: finish any pending argument,
3712            then run the pending command if one has been started.  */
3713         if (arg_going)
3714           {
3715             obstack_1grow (&obstack, 0);
3716             string = obstack_finish (&obstack);
3717             if (this_is_library_file)
3718               string = find_file (string);
3719             store_arg (string, delete_this_arg, this_is_output_file);
3720             if (this_is_output_file)
3721               outfiles[input_file_number] = string;
3722           }
3723         arg_going = 0;
3724
3725         if (argbuf_index > 0 && !strcmp (argbuf[argbuf_index - 1], "|"))
3726           {
3727             for (i = 0; i < n_switches; i++)
3728               if (!strcmp (switches[i].part1, "pipe"))
3729                 break;
3730
3731             /* A `|' before the newline means use a pipe here,
3732                but only if -pipe was specified.
3733                Otherwise, execute now and don't pass the `|' as an arg.  */
3734             if (i < n_switches)
3735               {
3736                 input_from_pipe = 1;
3737                 switches[i].validated = 1;
3738                 break;
3739               }
3740             else
3741               argbuf_index--;
3742           }
3743
3744         if (argbuf_index > 0)
3745           {
3746             value = execute ();
3747             if (value)
3748               return value;
3749           }
3750         /* Reinitialize for a new command, and for a new argument.  */
3751         clear_args ();
3752         arg_going = 0;
3753         delete_this_arg = 0;
3754         this_is_output_file = 0;
3755         this_is_library_file = 0;
3756         input_from_pipe = 0;
3757         break;
3758
3759       case '|':
3760         /* End any pending argument.  */
3761         if (arg_going)
3762           {
3763             obstack_1grow (&obstack, 0);
3764             string = obstack_finish (&obstack);
3765             if (this_is_library_file)
3766               string = find_file (string);
3767             store_arg (string, delete_this_arg, this_is_output_file);
3768             if (this_is_output_file)
3769               outfiles[input_file_number] = string;
3770           }
3771
3772         /* Use pipe */
3773         obstack_1grow (&obstack, c);
3774         arg_going = 1;
3775         break;
3776
3777       case '\t':
3778       case ' ':
3779         /* Space or tab ends an argument if one is pending.  */
3780         if (arg_going)
3781           {
3782             obstack_1grow (&obstack, 0);
3783             string = obstack_finish (&obstack);
3784             if (this_is_library_file)
3785               string = find_file (string);
3786             store_arg (string, delete_this_arg, this_is_output_file);
3787             if (this_is_output_file)
3788               outfiles[input_file_number] = string;
3789           }
3790         /* Reinitialize for a new argument.  */
3791         arg_going = 0;
3792         delete_this_arg = 0;
3793         this_is_output_file = 0;
3794         this_is_library_file = 0;
3795         break;
3796
3797       case '%':
3798         switch (c = *p++)
3799           {
3800           case 0:
3801             fatal ("Invalid specification!  Bug in cc.");
3802
3803           case 'b':
3804             obstack_grow (&obstack, input_basename, basename_length);
3805             arg_going = 1;
3806             break;
3807
3808           case 'B':
3809             obstack_grow (&obstack, input_basename, suffixed_basename_length);
3810             arg_going = 1;
3811             break;
3812
3813           case 'd':
3814             delete_this_arg = 2;
3815             break;
3816
3817           /* Dump out the directories specified with LIBRARY_PATH,
3818              followed by the absolute directories
3819              that we search for startfiles.  */
3820           case 'D':
3821             {
3822               struct prefix_list *pl = startfile_prefixes.plist;
3823               size_t bufsize = 100;
3824               char *buffer = (char *) xmalloc (bufsize);
3825               int idx;
3826
3827               for (; pl; pl = pl->next)
3828                 {
3829 #ifdef RELATIVE_PREFIX_NOT_LINKDIR
3830                   /* Used on systems which record the specified -L dirs
3831                      and use them to search for dynamic linking.  */
3832                   /* Relative directories always come from -B,
3833                      and it is better not to use them for searching
3834                      at run time.  In particular, stage1 loses.  */
3835                   if (!IS_DIR_SEPARATOR (pl->prefix[0]))
3836                     continue;
3837 #endif
3838                   /* Try subdirectory if there is one.  */
3839                   if (multilib_dir != NULL)
3840                     {
3841                       if (machine_suffix)
3842                         {
3843                           if (strlen (pl->prefix) + strlen (machine_suffix)
3844                               >= bufsize)
3845                             bufsize = (strlen (pl->prefix)
3846                                        + strlen (machine_suffix)) * 2 + 1;
3847                           buffer = (char *) xrealloc (buffer, bufsize);
3848                           strcpy (buffer, pl->prefix);
3849                           strcat (buffer, machine_suffix);
3850                           if (is_directory (buffer, multilib_dir, 1))
3851                             {
3852                               do_spec_1 ("-L", 0, NULL_PTR);
3853 #ifdef SPACE_AFTER_L_OPTION
3854                               do_spec_1 (" ", 0, NULL_PTR);
3855 #endif
3856                               do_spec_1 (buffer, 1, NULL_PTR);
3857                               do_spec_1 (multilib_dir, 1, NULL_PTR);
3858                               /* Make this a separate argument.  */
3859                               do_spec_1 (" ", 0, NULL_PTR);
3860                             }
3861                         }
3862                       if (!pl->require_machine_suffix)
3863                         {
3864                           if (is_directory (pl->prefix, multilib_dir, 1))
3865                             {
3866                               do_spec_1 ("-L", 0, NULL_PTR);
3867 #ifdef SPACE_AFTER_L_OPTION
3868                               do_spec_1 (" ", 0, NULL_PTR);
3869 #endif
3870                               do_spec_1 (pl->prefix, 1, NULL_PTR);
3871                               do_spec_1 (multilib_dir, 1, NULL_PTR);
3872                               /* Make this a separate argument.  */
3873                               do_spec_1 (" ", 0, NULL_PTR);
3874                             }
3875                         }
3876                     }
3877                   if (machine_suffix)
3878                     {
3879                       if (is_directory (pl->prefix, machine_suffix, 1))
3880                         {
3881                           do_spec_1 ("-L", 0, NULL_PTR);
3882 #ifdef SPACE_AFTER_L_OPTION
3883                           do_spec_1 (" ", 0, NULL_PTR);
3884 #endif
3885                           do_spec_1 (pl->prefix, 1, NULL_PTR);
3886                           /* Remove slash from machine_suffix.  */
3887                           if (strlen (machine_suffix) >= bufsize)
3888                             bufsize = strlen (machine_suffix) * 2 + 1;
3889                           buffer = (char *) xrealloc (buffer, bufsize);
3890                           strcpy (buffer, machine_suffix);
3891                           idx = strlen (buffer);
3892                           if (IS_DIR_SEPARATOR (buffer[idx - 1]))
3893                             buffer[idx - 1] = 0;
3894                           do_spec_1 (buffer, 1, NULL_PTR);
3895                           /* Make this a separate argument.  */
3896                           do_spec_1 (" ", 0, NULL_PTR);
3897                         }
3898                     }
3899                   if (!pl->require_machine_suffix)
3900                     {
3901                       if (is_directory (pl->prefix, "", 1))
3902                         {
3903                           do_spec_1 ("-L", 0, NULL_PTR);
3904 #ifdef SPACE_AFTER_L_OPTION
3905                           do_spec_1 (" ", 0, NULL_PTR);
3906 #endif
3907                           /* Remove slash from pl->prefix.  */
3908                           if (strlen (pl->prefix) >= bufsize)
3909                             bufsize = strlen (pl->prefix) * 2 + 1;
3910                           buffer = (char *) xrealloc (buffer, bufsize);
3911                           strcpy (buffer, pl->prefix);
3912                           idx = strlen (buffer);
3913                           if (IS_DIR_SEPARATOR (buffer[idx - 1]))
3914                             buffer[idx - 1] = 0;
3915                           do_spec_1 (buffer, 1, NULL_PTR);
3916                           /* Make this a separate argument.  */
3917                           do_spec_1 (" ", 0, NULL_PTR);
3918                         }
3919                     }
3920                 }
3921               free (buffer);
3922             }
3923             break;
3924
3925           case 'e':
3926             /* %efoo means report an error with `foo' as error message
3927                and don't execute any more commands for this file.  */
3928             {
3929               const char *q = p;
3930               char *buf;
3931               while (*p != 0 && *p != '\n')
3932                 p++;
3933               buf = (char *) alloca (p - q + 1);
3934               strncpy (buf, q, p - q);
3935               buf[p - q] = 0;
3936               error ("%s", buf);
3937               return -1;
3938             }
3939             break;
3940
3941           case 'j':
3942             {
3943               struct stat st;
3944
3945               /* If save_temps_flag is off, and the HOST_BIT_BUCKET is defined,
3946                  and it is not a directory, and it is writable, use it.
3947                  Otherwise, fall through and treat this like any other
3948                  temporary file.  */
3949
3950               if ((!save_temps_flag)
3951                   && (stat (HOST_BIT_BUCKET, &st) == 0) && (!S_ISDIR (st.st_mode))
3952                   && (access (HOST_BIT_BUCKET, W_OK) == 0))
3953                 {
3954                   obstack_grow (&obstack, HOST_BIT_BUCKET,
3955                                 strlen (HOST_BIT_BUCKET));
3956                   delete_this_arg = 0;
3957                   arg_going = 1;
3958                   break;
3959                 }
3960             }
3961           case 'g':
3962           case 'u':
3963           case 'U':
3964             if (save_temps_flag)
3965               {
3966                 obstack_grow (&obstack, input_basename, basename_length);
3967                 delete_this_arg = 0;
3968               }
3969             else
3970               {
3971                 struct temp_name *t;
3972                 int suffix_length;
3973                 const char *suffix = p;
3974                 char *saved_suffix = NULL;
3975
3976                 while (*p == '.' || ISALPHA ((unsigned char) *p))
3977                   p++;
3978                 suffix_length = p - suffix;
3979                 if (p[0] == '%' && p[1] == 'O')
3980                   {
3981                     p += 2;
3982                     /* We don't support extra suffix characters after %O.  */
3983                     if (*p == '.' || ISALPHA ((unsigned char) *p))
3984                       abort ();
3985                     if (suffix_length == 0)
3986                       suffix = OBJECT_SUFFIX;
3987                     else
3988                       {
3989                         saved_suffix
3990                           = (char *) xmalloc (suffix_length
3991                                               + strlen (OBJECT_SUFFIX));
3992                         strncpy (saved_suffix, suffix, suffix_length);
3993                         strcpy (saved_suffix + suffix_length,
3994                                 OBJECT_SUFFIX);
3995                       }
3996                     suffix_length += strlen (OBJECT_SUFFIX);
3997                   }
3998
3999                 /* See if we already have an association of %g/%u/%U and
4000                    suffix.  */
4001                 for (t = temp_names; t; t = t->next)
4002                   if (t->length == suffix_length
4003                       && strncmp (t->suffix, suffix, suffix_length) == 0
4004                       && t->unique == (c != 'g'))
4005                     break;
4006
4007                 /* Make a new association if needed.  %u and %j require one.  */
4008                 if (t == 0 || c == 'u' || c == 'j')
4009                   {
4010                     if (t == 0)
4011                       {
4012                         t = (struct temp_name *) xmalloc (sizeof (struct temp_name));
4013                         t->next = temp_names;
4014                         temp_names = t;
4015                       }
4016                     t->length = suffix_length;
4017                     t->suffix = save_string (suffix, suffix_length);
4018                     t->unique = (c != 'g');
4019                     temp_filename = make_temp_file (t->suffix);
4020                     temp_filename_length = strlen (temp_filename);
4021                     t->filename = temp_filename;
4022                     t->filename_length = temp_filename_length;
4023                   }
4024
4025                 if (saved_suffix)
4026                   free (saved_suffix);
4027
4028                 obstack_grow (&obstack, t->filename, t->filename_length);
4029                 delete_this_arg = 1;
4030               }
4031             arg_going = 1;
4032             break;
4033
4034           case 'i':
4035             obstack_grow (&obstack, input_filename, input_filename_length);
4036             arg_going = 1;
4037             break;
4038
4039           case 'I':
4040             {
4041               struct prefix_list *pl = include_prefixes.plist;
4042
4043               if (gcc_exec_prefix)
4044                 {
4045                   do_spec_1 ("-iprefix", 1, NULL_PTR);
4046                   /* Make this a separate argument.  */
4047                   do_spec_1 (" ", 0, NULL_PTR);
4048                   do_spec_1 (gcc_exec_prefix, 1, NULL_PTR);
4049                   do_spec_1 (" ", 0, NULL_PTR);
4050                 }
4051
4052               for (; pl; pl = pl->next)
4053                 {
4054                   do_spec_1 ("-isystem", 1, NULL_PTR);
4055                   /* Make this a separate argument.  */
4056                   do_spec_1 (" ", 0, NULL_PTR);
4057                   do_spec_1 (pl->prefix, 1, NULL_PTR);
4058                   do_spec_1 (" ", 0, NULL_PTR);
4059                 }
4060             }
4061             break;
4062
4063           case 'o':
4064             {
4065               int max = n_infiles;
4066               max += lang_specific_extra_outfiles;
4067
4068               for (i = 0; i < max; i++)
4069                 if (outfiles[i])
4070                   store_arg (outfiles[i], 0, 0);
4071               break;
4072             }
4073
4074           case 'O':
4075             obstack_grow (&obstack, OBJECT_SUFFIX, strlen (OBJECT_SUFFIX));
4076             arg_going = 1;
4077             break;
4078
4079           case 's':
4080             this_is_library_file = 1;
4081             break;
4082
4083           case 'w':
4084             this_is_output_file = 1;
4085             break;
4086
4087           case 'W':
4088             {
4089               int cur_index = argbuf_index;
4090               /* Handle the {...} following the %W.  */
4091               if (*p != '{')
4092                 abort ();
4093               p = handle_braces (p + 1);
4094               if (p == 0)
4095                 return -1;
4096               /* If any args were output, mark the last one for deletion
4097                  on failure.  */
4098               if (argbuf_index != cur_index)
4099                 record_temp_file (argbuf[argbuf_index - 1], 0, 1);
4100               break;
4101             }
4102
4103           /* %x{OPTION} records OPTION for %X to output.  */
4104           case 'x':
4105             {
4106               const char *p1 = p;
4107               char *string;
4108
4109               /* Skip past the option value and make a copy.  */
4110               if (*p != '{')
4111                 abort ();
4112               while (*p++ != '}')
4113                 ;
4114               string = save_string (p1 + 1, p - p1 - 2);
4115
4116               /* See if we already recorded this option.  */
4117               for (i = 0; i < n_linker_options; i++)
4118                 if (! strcmp (string, linker_options[i]))
4119                   {
4120                     free (string);
4121                     return 0;
4122                   }
4123
4124               /* This option is new; add it.  */
4125               add_linker_option (string, strlen (string));
4126             }
4127             break;
4128
4129           /* Dump out the options accumulated previously using %x.  */
4130           case 'X':
4131             for (i = 0; i < n_linker_options; i++)
4132               {
4133                 do_spec_1 (linker_options[i], 1, NULL_PTR);
4134                 /* Make each accumulated option a separate argument.  */
4135                 do_spec_1 (" ", 0, NULL_PTR);
4136               }
4137             break;
4138
4139           /* Dump out the options accumulated previously using -Wa,.  */
4140           case 'Y':
4141             for (i = 0; i < n_assembler_options; i++)
4142               {
4143                 do_spec_1 (assembler_options[i], 1, NULL_PTR);
4144                 /* Make each accumulated option a separate argument.  */
4145                 do_spec_1 (" ", 0, NULL_PTR);
4146               }
4147             break;
4148
4149           /* Dump out the options accumulated previously using -Wp,.  */
4150           case 'Z':
4151             for (i = 0; i < n_preprocessor_options; i++)
4152               {
4153                 do_spec_1 (preprocessor_options[i], 1, NULL_PTR);
4154                 /* Make each accumulated option a separate argument.  */
4155                 do_spec_1 (" ", 0, NULL_PTR);
4156               }
4157             break;
4158
4159             /* Here are digits and numbers that just process
4160                a certain constant string as a spec.  */
4161
4162           case '1':
4163             value = do_spec_1 (cc1_spec, 0, NULL_PTR);
4164             if (value != 0)
4165               return value;
4166             break;
4167
4168           case '2':
4169             value = do_spec_1 (cc1plus_spec, 0, NULL_PTR);
4170             if (value != 0)
4171               return value;
4172             break;
4173
4174           case 'a':
4175             value = do_spec_1 (asm_spec, 0, NULL_PTR);
4176             if (value != 0)
4177               return value;
4178             break;
4179
4180           case 'A':
4181             value = do_spec_1 (asm_final_spec, 0, NULL_PTR);
4182             if (value != 0)
4183               return value;
4184             break;
4185
4186           case 'c':
4187             value = do_spec_1 (signed_char_spec, 0, NULL_PTR);
4188             if (value != 0)
4189               return value;
4190             break;
4191
4192           case 'C':
4193             value = do_spec_1 (cpp_spec, 0, NULL_PTR);
4194             if (value != 0)
4195               return value;
4196             break;
4197
4198           case 'E':
4199             value = do_spec_1 (endfile_spec, 0, NULL_PTR);
4200             if (value != 0)
4201               return value;
4202             break;
4203
4204           case 'l':
4205             value = do_spec_1 (link_spec, 0, NULL_PTR);
4206             if (value != 0)
4207               return value;
4208             break;
4209
4210           case 'L':
4211             value = do_spec_1 (lib_spec, 0, NULL_PTR);
4212             if (value != 0)
4213               return value;
4214             break;
4215
4216           case 'G':
4217             value = do_spec_1 (libgcc_spec, 0, NULL_PTR);
4218             if (value != 0)
4219               return value;
4220             break;
4221
4222           case 'p':
4223             {
4224               char *x = (char *) alloca (strlen (cpp_predefines) + 1);
4225               char *buf = x;
4226               const char *y;
4227
4228               /* Copy all of the -D options in CPP_PREDEFINES into BUF.  */
4229               y = cpp_predefines;
4230               while (*y != 0)
4231                 {
4232                   if (! strncmp (y, "-D", 2))
4233                     /* Copy the whole option.  */
4234                     while (*y && *y != ' ' && *y != '\t')
4235                       *x++ = *y++;
4236                   else if (*y == ' ' || *y == '\t')
4237                     /* Copy whitespace to the result.  */
4238                     *x++ = *y++;
4239                   /* Don't copy other options.  */
4240                   else
4241                     y++;
4242                 }
4243
4244               *x = 0;
4245
4246               value = do_spec_1 (buf, 0, NULL_PTR);
4247               if (value != 0)
4248                 return value;
4249             }
4250             break;
4251
4252           case 'P':
4253             {
4254               char *x = (char *) alloca (strlen (cpp_predefines) * 4 + 1);
4255               char *buf = x;
4256               const char *y;
4257
4258               /* Copy all of CPP_PREDEFINES into BUF,
4259                  but force them all into the reserved name space if they
4260                  aren't already there.  The reserved name space is all
4261                  identifiers beginning with two underscores or with one
4262                  underscore and a capital letter.  We do the forcing by
4263                  adding up to two underscores to the beginning and end
4264                  of each symbol. e.g. mips, _mips, mips_, and _mips_ all
4265                  become __mips__.  */
4266               y = cpp_predefines;
4267               while (*y != 0)
4268                 {
4269                   if (! strncmp (y, "-D", 2))
4270                     {
4271                       int flag = 0;
4272
4273                       *x++ = *y++;
4274                       *x++ = *y++;
4275
4276                       if (*y != '_'
4277                           || (*(y + 1) != '_'
4278                               && ! ISUPPER ((unsigned char) *(y + 1))))
4279                         {
4280                           /* Stick __ at front of macro name.  */
4281                           if (*y != '_')
4282                             *x++ = '_';
4283                           *x++ = '_';
4284                           /* Arrange to stick __ at the end as well.  */
4285                           flag = 1;
4286                         }
4287
4288                       /* Copy the macro name.  */
4289                       while (*y && *y != '=' && *y != ' ' && *y != '\t')
4290                         *x++ = *y++;
4291
4292                       if (flag)
4293                         {
4294                           if (x[-1] != '_')
4295                             {
4296                               if (x[-2] != '_')
4297                                 *x++ = '_';
4298                               *x++ = '_';
4299                             }
4300                         }
4301
4302                       /* Copy the value given, if any.  */
4303                       while (*y && *y != ' ' && *y != '\t')
4304                         *x++ = *y++;
4305                     }
4306                   else if (*y == ' ' || *y == '\t')
4307                     /* Copy whitespace to the result.  */
4308                     *x++ = *y++;
4309                   /* Don't copy -A options  */
4310                   else
4311                     y++;
4312                 }
4313               *x++ = ' ';
4314
4315               /* Copy all of CPP_PREDEFINES into BUF,
4316                  but put __ after every -D.  */
4317               y = cpp_predefines;
4318               while (*y != 0)
4319                 {
4320                   if (! strncmp (y, "-D", 2))
4321                     {
4322                       y += 2;
4323
4324                       if (*y != '_'
4325                           || (*(y + 1) != '_'
4326                               && ! ISUPPER ((unsigned char) *(y + 1))))
4327                         {
4328                           /* Stick -D__ at front of macro name.  */
4329                           *x++ = '-';
4330                           *x++ = 'D';
4331                           if (*y != '_')
4332                             *x++ = '_';
4333                           *x++ = '_';
4334
4335                           /* Copy the macro name.  */
4336                           while (*y && *y != '=' && *y != ' ' && *y != '\t')
4337                             *x++ = *y++;
4338
4339                           /* Copy the value given, if any.  */
4340                           while (*y && *y != ' ' && *y != '\t')
4341                             *x++ = *y++;
4342                         }
4343                       else
4344                         {
4345                           /* Do not copy this macro - we have just done it before */
4346                           while (*y && *y != ' ' && *y != '\t')
4347                             y++;
4348                         }
4349                     }
4350                   else if (*y == ' ' || *y == '\t')
4351                     /* Copy whitespace to the result.  */
4352                     *x++ = *y++;
4353                   /* Don't copy -A options.  */
4354                   else
4355                     y++;
4356                 }
4357               *x++ = ' ';
4358
4359               /* Copy all of the -A options in CPP_PREDEFINES into BUF.  */
4360               y = cpp_predefines;
4361               while (*y != 0)
4362                 {
4363                   if (! strncmp (y, "-A", 2))
4364                     /* Copy the whole option.  */
4365                     while (*y && *y != ' ' && *y != '\t')
4366                       *x++ = *y++;
4367                   else if (*y == ' ' || *y == '\t')
4368                     /* Copy whitespace to the result.  */
4369                     *x++ = *y++;
4370                   /* Don't copy other options.  */
4371                   else
4372                     y++;
4373                 }
4374
4375               *x = 0;
4376
4377               value = do_spec_1 (buf, 0, NULL_PTR);
4378               if (value != 0)
4379                 return value;
4380             }
4381             break;
4382
4383           case 'S':
4384             value = do_spec_1 (startfile_spec, 0, NULL_PTR);
4385             if (value != 0)
4386               return value;
4387             break;
4388
4389             /* Here we define characters other than letters and digits.  */
4390
4391           case '{':
4392             p = handle_braces (p);
4393             if (p == 0)
4394               return -1;
4395             break;
4396
4397           case '%':
4398             obstack_1grow (&obstack, '%');
4399             break;
4400
4401           case '*':
4402             if (soft_matched_part)
4403               {
4404                 do_spec_1 (soft_matched_part, 1, NULL_PTR);
4405                 do_spec_1 (" ", 0, NULL_PTR);
4406               }
4407             else
4408               /* Catch the case where a spec string contains something like
4409                  '%{foo:%*}'.  ie there is no * in the pattern on the left
4410                  hand side of the :.  */
4411               error ("Spec failure: '%%*' has not been initialised by pattern match");
4412             break;
4413
4414             /* Process a string found as the value of a spec given by name.
4415                This feature allows individual machine descriptions
4416                to add and use their own specs.
4417                %[...] modifies -D options the way %P does;
4418                %(...) uses the spec unmodified.  */
4419           case '[':
4420             error ("Warning: use of obsolete %%[ operator in specs");
4421           case '(':
4422             {
4423               const char *name = p;
4424               struct spec_list *sl;
4425               int len;
4426
4427               /* The string after the S/P is the name of a spec that is to be
4428                  processed.  */
4429               while (*p && *p != ')' && *p != ']')
4430                 p++;
4431
4432               /* See if it's in the list.  */
4433               for (len = p - name, sl = specs; sl; sl = sl->next)
4434                 if (sl->name_len == len && !strncmp (sl->name, name, len))
4435                   {
4436                     name = *(sl->ptr_spec);
4437 #ifdef DEBUG_SPECS
4438                     notice ("Processing spec %c%s%c, which is '%s'\n",
4439                             c, sl->name, (c == '(') ? ')' : ']', name);
4440 #endif
4441                     break;
4442                   }
4443
4444               if (sl)
4445                 {
4446                   if (c == '(')
4447                     {
4448                       value = do_spec_1 (name, 0, NULL_PTR);
4449                       if (value != 0)
4450                         return value;
4451                     }
4452                   else
4453                     {
4454                       char *x = (char *) alloca (strlen (name) * 2 + 1);
4455                       char *buf = x;
4456                       const char *y = name;
4457                       int flag = 0;
4458
4459                       /* Copy all of NAME into BUF, but put __ after
4460                          every -D and at the end of each arg.  */
4461                       while (1)
4462                         {
4463                           if (! strncmp (y, "-D", 2))
4464                             {
4465                               *x++ = '-';
4466                               *x++ = 'D';
4467                               *x++ = '_';
4468                               *x++ = '_';
4469                               y += 2;
4470                               flag = 1;
4471                               continue;
4472                             }
4473                           else if (flag
4474                                    && (*y == ' ' || *y == '\t' || *y == '='
4475                                        || *y == '}' || *y == 0))
4476                             {
4477                               *x++ = '_';
4478                               *x++ = '_';
4479                               flag = 0;
4480                             }
4481                           if (*y == 0)
4482                             break;
4483                           else
4484                             *x++ = *y++;
4485                         }
4486                       *x = 0;
4487
4488                       value = do_spec_1 (buf, 0, NULL_PTR);
4489                       if (value != 0)
4490                         return value;
4491                     }
4492                 }
4493
4494               /* Discard the closing paren or bracket.  */
4495               if (*p)
4496                 p++;
4497             }
4498             break;
4499
4500           case 'v':
4501             {
4502               int c1 = *p++;  /* Select first or second version number.  */
4503               const char *v = compiler_version;
4504               const char *q;
4505               static const char zeroc = '0';
4506
4507               /* The format of the version string is
4508                  ([^0-9]*-)?[0-9]+[.][0-9]+([.][0-9]+)?([- ].*)?  */
4509
4510               /* Ignore leading non-digits.  i.e. "foo-" in "foo-2.7.2".  */
4511               while (! ISDIGIT (*v))
4512                 v++;
4513               if (v > compiler_version && v[-1] != '-')
4514                 abort ();
4515
4516               /* If desired, advance to second version number.  */
4517               if (c1 >= '2')
4518                 {
4519                   /* Set V after the first period.  */
4520                   while (ISDIGIT (*v))
4521                     v++;
4522                   if (*v != '.')
4523                     abort ();
4524                   v++;
4525                 }
4526
4527               /* If desired, advance to third version number.
4528                  But don't complain if it's not present */
4529               if (c1 == '3')
4530                 {
4531                   /* Set V after the second period.  */
4532                   while (ISDIGIT (*v))
4533                     v++;
4534                   if ((*v != 0) && (*v != ' ') && (*v != '.') && (*v != '-'))
4535                     abort ();
4536                   if (*v != 0)
4537                     v++;
4538                 }
4539
4540               /* Set Q at the next period or at the end.  */
4541               q = v;
4542               while (ISDIGIT (*q))
4543                 q++;
4544               if (*q != 0 && q > v && *q != ' ' && *q != '.' && *q != '-')
4545                 abort ();
4546
4547               if (q > v)
4548                 /* Put that part into the command.  */
4549                 obstack_grow (&obstack, v, q - v);
4550               else
4551                 /* Default to "0" */
4552                 obstack_grow (&obstack, &zeroc, 1);
4553               arg_going = 1;
4554             }
4555             break;
4556
4557           case '|':
4558             if (input_from_pipe)
4559               do_spec_1 ("-", 0, NULL_PTR);
4560             break;
4561
4562           default:
4563             error ("Spec failure: Unrecognised spec option '%c'", c);
4564             break;
4565           }
4566         break;
4567
4568       case '\\':
4569         /* Backslash: treat next character as ordinary.  */
4570         c = *p++;
4571
4572         /* fall through */
4573       default:
4574         /* Ordinary character: put it into the current argument.  */
4575         obstack_1grow (&obstack, c);
4576         arg_going = 1;
4577       }
4578
4579   /* End of string.  */
4580   return 0;
4581 }
4582
4583 /* Return 0 if we call do_spec_1 and that returns -1.  */
4584
4585 static const char *
4586 handle_braces (p)
4587      register const char *p;
4588 {
4589   const char *filter, *body = NULL, *endbody = NULL;
4590   int pipe_p = 0;
4591   int negate;
4592   int suffix;
4593   int include_blanks = 1;
4594   int elide_switch = 0;
4595
4596   if (*p == '^')
4597     {
4598       /* A '^' after the open-brace means to not give blanks before args.  */
4599       include_blanks = 0;
4600       ++p;
4601     }
4602
4603   if (*p == '|')
4604     {
4605       /* A `|' after the open-brace means,
4606          if the test fails, output a single minus sign rather than nothing.
4607          This is used in %{|!pipe:...}.  */
4608       pipe_p = 1;
4609       ++p;
4610     }
4611
4612   if (*p == '<')
4613     {
4614       /* A `<' after the open-brace means that the switch should be
4615          removed from the command-line.  */
4616       elide_switch = 1;
4617       ++p;
4618     }
4619
4620 next_member:
4621   negate = suffix = 0;
4622
4623   if (*p == '!')
4624     /* A `!' after the open-brace negates the condition:
4625        succeed if the specified switch is not present.  */
4626     negate = 1, ++p;
4627
4628   if (*p == '.')
4629     /* A `.' after the open-brace means test against the current suffix.  */
4630     {
4631       if (pipe_p)
4632         abort ();
4633
4634       suffix = 1;
4635       ++p;
4636     }
4637
4638   if (elide_switch && (negate || pipe_p || suffix))
4639     {
4640       /* It doesn't make sense to mix elision with other flags.  We
4641          could fatal() here, but the standard seems to be to abort.  */
4642       abort ();
4643     }
4644
4645   filter = p;
4646   while (*p != ':' && *p != '}' && *p != '|')
4647     p++;
4648
4649   if (*p == '|' && pipe_p)
4650     abort ();
4651
4652   if (!body)
4653     {
4654       if (*p != '}')
4655         {
4656           register int count = 1;
4657           register const char *q = p;
4658
4659           while (*q++ != ':')
4660             continue;
4661           body = q;
4662
4663           while (count > 0)
4664             {
4665               if (*q == '{')
4666                 count++;
4667               else if (*q == '}')
4668                 count--;
4669               else if (*q == 0)
4670                 abort ();
4671               q++;
4672             }
4673           endbody = q;
4674         }
4675       else
4676         body = p, endbody = p + 1;
4677     }
4678
4679   if (suffix)
4680     {
4681       int found = (input_suffix != 0
4682                    && (long) strlen (input_suffix) == (long) (p - filter)
4683                    && strncmp (input_suffix, filter, p - filter) == 0);
4684
4685       if (body[0] == '}')
4686         abort ();
4687
4688       if (negate != found
4689           && do_spec_1 (save_string (body, endbody-body-1), 0, NULL_PTR) < 0)
4690         return 0;
4691     }
4692   else if (p[-1] == '*' && p[0] == '}')
4693     {
4694       /* Substitute all matching switches as separate args.  */
4695       register int i;
4696       --p;
4697       for (i = 0; i < n_switches; i++)
4698         if (!strncmp (switches[i].part1, filter, p - filter)
4699             && check_live_switch (i, p - filter))
4700           give_switch (i, 0, include_blanks);
4701     }
4702   else
4703     {
4704       /* Test for presence of the specified switch.  */
4705       register int i;
4706       int present = 0;
4707
4708       /* If name specified ends in *, as in {x*:...},
4709          check for %* and handle that case.  */
4710       if (p[-1] == '*' && !negate)
4711         {
4712           int substitution;
4713           const char *r = body;
4714
4715           /* First see whether we have %*.  */
4716           substitution = 0;
4717           while (r < endbody)
4718             {
4719               if (*r == '%' && r[1] == '*')
4720                 substitution = 1;
4721               r++;
4722             }
4723           /* If we do, handle that case.  */
4724           if (substitution)
4725             {
4726               /* Substitute all matching switches as separate args.
4727                  But do this by substituting for %*
4728                  in the text that follows the colon.  */
4729
4730               unsigned hard_match_len = p - filter - 1;
4731               char *string = save_string (body, endbody - body - 1);
4732
4733               for (i = 0; i < n_switches; i++)
4734                 if (!strncmp (switches[i].part1, filter, hard_match_len)
4735                     && check_live_switch (i, -1))
4736                   {
4737                     do_spec_1 (string, 0, &switches[i].part1[hard_match_len]);
4738                     /* Pass any arguments this switch has.  */
4739                     give_switch (i, 1, 1);
4740                   }
4741
4742               /* We didn't match.  Try again.  */
4743               if (*p++ == '|')
4744                 goto next_member;
4745               return endbody;
4746             }
4747         }
4748
4749       /* If name specified ends in *, as in {x*:...},
4750          check for presence of any switch name starting with x.  */
4751       if (p[-1] == '*')
4752         {
4753           for (i = 0; i < n_switches; i++)
4754             {
4755               unsigned hard_match_len = p - filter - 1;
4756
4757               if (!strncmp (switches[i].part1, filter, hard_match_len)
4758                   && check_live_switch (i, hard_match_len))
4759                 {
4760                   present = 1;
4761                   break;
4762                 }
4763             }
4764         }
4765       /* Otherwise, check for presence of exact name specified.  */
4766       else
4767         {
4768           for (i = 0; i < n_switches; i++)
4769             {
4770               if (!strncmp (switches[i].part1, filter, p - filter)
4771                   && switches[i].part1[p - filter] == 0
4772                   && check_live_switch (i, -1))
4773                 {
4774                   present = 1;
4775                   break;
4776                 }
4777             }
4778         }
4779
4780       /* If it is as desired (present for %{s...}, absent for %{!s...})
4781          then substitute either the switch or the specified
4782          conditional text.  */
4783       if (present != negate)
4784         {
4785           if (elide_switch)
4786             {
4787               switches[i].live_cond = SWITCH_IGNORE;
4788               switches[i].validated = 1;
4789             }
4790           else if (*p == '}')
4791             {
4792               give_switch (i, 0, include_blanks);
4793             }
4794           else
4795             {
4796               if (do_spec_1 (save_string (body, endbody - body - 1),
4797                              0, NULL_PTR) < 0)
4798                 return 0;
4799             }
4800         }
4801       else if (pipe_p)
4802         {
4803           /* Here if a %{|...} conditional fails: output a minus sign,
4804              which means "standard output" or "standard input".  */
4805           do_spec_1 ("-", 0, NULL_PTR);
4806           return endbody;
4807         }
4808     }
4809
4810   /* We didn't match; try again.  */
4811   if (*p++ == '|')
4812     goto next_member;
4813
4814   return endbody;
4815 }
4816 \f
4817 /* Return 0 iff switch number SWITCHNUM is obsoleted by a later switch
4818    on the command line.  PREFIX_LENGTH is the length of XXX in an {XXX*}
4819    spec, or -1 if either exact match or %* is used.
4820
4821    A -O switch is obsoleted by a later -O switch.  A -f, -m, or -W switch
4822    whose value does not begin with "no-" is obsoleted by the same value
4823    with the "no-", similarly for a switch with the "no-" prefix.  */
4824
4825 static int
4826 check_live_switch (switchnum, prefix_length)
4827      int switchnum;
4828      int prefix_length;
4829 {
4830   const char *name = switches[switchnum].part1;
4831   int i;
4832
4833   /* In the common case of {<at-most-one-letter>*}, a negating
4834      switch would always match, so ignore that case.  We will just
4835      send the conflicting switches to the compiler phase.  */
4836   if (prefix_length >= 0 && prefix_length <= 1)
4837     return 1;
4838
4839   /* If we already processed this switch and determined if it was
4840      live or not, return our past determination.  */
4841   if (switches[switchnum].live_cond != 0)
4842     return switches[switchnum].live_cond > 0;
4843
4844   /* Now search for duplicate in a manner that depends on the name.  */
4845   switch (*name)
4846     {
4847     case 'O':
4848       for (i = switchnum + 1; i < n_switches; i++)
4849         if (switches[i].part1[0] == 'O')
4850           {
4851             switches[switchnum].validated = 1;
4852             switches[switchnum].live_cond = SWITCH_FALSE;
4853             return 0;
4854           }
4855       break;
4856
4857     case 'W':  case 'f':  case 'm':
4858       if (! strncmp (name + 1, "no-", 3))
4859         {
4860           /* We have Xno-YYY, search for XYYY.  */
4861           for (i = switchnum + 1; i < n_switches; i++)
4862             if (switches[i].part1[0] == name[0]
4863                 && ! strcmp (&switches[i].part1[1], &name[4]))
4864               {
4865                 switches[switchnum].validated = 1;
4866                 switches[switchnum].live_cond = SWITCH_FALSE;
4867                 return 0;
4868               }
4869         }
4870       else
4871         {
4872           /* We have XYYY, search for Xno-YYY.  */
4873           for (i = switchnum + 1; i < n_switches; i++)
4874             if (switches[i].part1[0] == name[0]
4875                 && switches[i].part1[1] == 'n'
4876                 && switches[i].part1[2] == 'o'
4877                 && switches[i].part1[3] == '-'
4878                 && !strcmp (&switches[i].part1[4], &name[1]))
4879               {
4880                 switches[switchnum].validated = 1;
4881                 switches[switchnum].live_cond = SWITCH_FALSE;
4882                 return 0;
4883               }
4884         }
4885       break;
4886     }
4887
4888   /* Otherwise the switch is live.  */
4889   switches[switchnum].live_cond = SWITCH_LIVE;
4890   return 1;
4891 }
4892 \f
4893 /* Pass a switch to the current accumulating command
4894    in the same form that we received it.
4895    SWITCHNUM identifies the switch; it is an index into
4896    the vector of switches gcc received, which is `switches'.
4897    This cannot fail since it never finishes a command line.
4898
4899    If OMIT_FIRST_WORD is nonzero, then we omit .part1 of the argument.
4900
4901    If INCLUDE_BLANKS is nonzero, then we include blanks before each argument
4902    of the switch.  */
4903
4904 static void
4905 give_switch (switchnum, omit_first_word, include_blanks)
4906      int switchnum;
4907      int omit_first_word;
4908      int include_blanks;
4909 {
4910   if (switches[switchnum].live_cond == SWITCH_IGNORE)
4911     return;
4912
4913   if (!omit_first_word)
4914     {
4915       do_spec_1 ("-", 0, NULL_PTR);
4916       do_spec_1 (switches[switchnum].part1, 1, NULL_PTR);
4917     }
4918
4919   if (switches[switchnum].args != 0)
4920     {
4921       const char **p;
4922       for (p = switches[switchnum].args; *p; p++)
4923         {
4924           if (include_blanks)
4925             do_spec_1 (" ", 0, NULL_PTR);
4926           do_spec_1 (*p, 1, NULL_PTR);
4927         }
4928     }
4929
4930   do_spec_1 (" ", 0, NULL_PTR);
4931   switches[switchnum].validated = 1;
4932 }
4933 \f
4934 /* Search for a file named NAME trying various prefixes including the
4935    user's -B prefix and some standard ones.
4936    Return the absolute file name found.  If nothing is found, return NAME.  */
4937
4938 static const char *
4939 find_file (name)
4940      const char *name;
4941 {
4942   char *newname;
4943
4944   /* Try multilib_dir if it is defined.  */
4945   if (multilib_dir != NULL)
4946     {
4947       char *try;
4948
4949       try = (char *) alloca (strlen (multilib_dir) + strlen (name) + 2);
4950       strcpy (try, multilib_dir);
4951       strcat (try, dir_separator_str);
4952       strcat (try, name);
4953
4954       newname = find_a_file (&startfile_prefixes, try, R_OK);
4955
4956       /* If we don't find it in the multi library dir, then fall
4957          through and look for it in the normal places.  */
4958       if (newname != NULL)
4959         return newname;
4960     }
4961
4962   newname = find_a_file (&startfile_prefixes, name, R_OK);
4963   return newname ? newname : name;
4964 }
4965
4966 /* Determine whether a directory exists.  If LINKER, return 0 for
4967    certain fixed names not needed by the linker.  If not LINKER, it is
4968    only important to return 0 if the host machine has a small ARG_MAX
4969    limit.  */
4970
4971 static int
4972 is_directory (path1, path2, linker)
4973      const char *path1;
4974      const char *path2;
4975      int linker;
4976 {
4977   int len1 = strlen (path1);
4978   int len2 = strlen (path2);
4979   char *path = (char *) alloca (3 + len1 + len2);
4980   char *cp;
4981   struct stat st;
4982
4983 #ifndef SMALL_ARG_MAX
4984   if (! linker)
4985     return 1;
4986 #endif
4987
4988   /* Construct the path from the two parts.  Ensure the string ends with "/.".
4989      The resulting path will be a directory even if the given path is a
4990      symbolic link.  */
4991   memcpy (path, path1, len1);
4992   memcpy (path + len1, path2, len2);
4993   cp = path + len1 + len2;
4994   if (!IS_DIR_SEPARATOR (cp[-1]))
4995     *cp++ = DIR_SEPARATOR;
4996   *cp++ = '.';
4997   *cp = '\0';
4998
4999   /* Exclude directories that the linker is known to search.  */
5000   if (linker
5001       && ((cp - path == 6
5002            && strcmp (path, concat (dir_separator_str, "lib",
5003                                     dir_separator_str, ".", NULL_PTR)) == 0)
5004           || (cp - path == 10
5005               && strcmp (path, concat (dir_separator_str, "usr",
5006                                        dir_separator_str, "lib",
5007                                        dir_separator_str, ".", NULL_PTR)) == 0)))
5008     return 0;
5009
5010   return (stat (path, &st) >= 0 && S_ISDIR (st.st_mode));
5011 }
5012
5013 /* Set up the various global variables to indicate that we're processing
5014    the input file named FILENAME.  */
5015
5016 static void
5017 set_input (filename)
5018      const char *filename;
5019 {
5020   register const char *p;
5021
5022   input_filename = filename;
5023   input_filename_length = strlen (input_filename);
5024
5025   input_basename = input_filename;
5026 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
5027   /* Skip drive name so 'x:foo' is handled properly.  */
5028   if (input_basename[1] == ':')
5029     input_basename += 2;
5030 #endif
5031   for (p = input_basename; *p; p++)
5032     if (IS_DIR_SEPARATOR (*p))
5033       input_basename = p + 1;
5034
5035   /* Find a suffix starting with the last period,
5036      and set basename_length to exclude that suffix.  */
5037   basename_length = strlen (input_basename);
5038   suffixed_basename_length = basename_length;
5039   p = input_basename + basename_length;
5040   while (p != input_basename && *p != '.')
5041     --p;
5042   if (*p == '.' && p != input_basename)
5043     {
5044       basename_length = p - input_basename;
5045       input_suffix = p + 1;
5046     }
5047   else
5048     input_suffix = "";
5049 }
5050 \f
5051 /* On fatal signals, delete all the temporary files.  */
5052
5053 static void
5054 fatal_error (signum)
5055      int signum;
5056 {
5057   signal (signum, SIG_DFL);
5058   delete_failure_queue ();
5059   delete_temp_files ();
5060   /* Get the same signal again, this time not handled,
5061      so its normal effect occurs.  */
5062   kill (getpid (), signum);
5063 }
5064
5065 extern int main PARAMS ((int, const char *const *));
5066
5067 int
5068 main (argc, argv)
5069      int argc;
5070      const char *const *argv;
5071 {
5072   size_t i;
5073   int value;
5074   int linker_was_run = 0;
5075   char *explicit_link_files;
5076   char *specs_file;
5077   const char *p;
5078   struct user_specs *uptr;
5079
5080   p = argv[0] + strlen (argv[0]);
5081   while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
5082     --p;
5083   programname = p;
5084
5085 #ifdef GCC_DRIVER_HOST_INITIALIZATION
5086   /* Perform host dependant initialization when needed.  */
5087   GCC_DRIVER_HOST_INITIALIZATION;
5088 #endif
5089
5090 #ifdef HAVE_LC_MESSAGES
5091   setlocale (LC_MESSAGES, "");
5092 #endif
5093   (void) bindtextdomain (PACKAGE, localedir);
5094   (void) textdomain (PACKAGE);
5095
5096   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
5097     signal (SIGINT, fatal_error);
5098 #ifdef SIGHUP
5099   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
5100     signal (SIGHUP, fatal_error);
5101 #endif
5102   if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
5103     signal (SIGTERM, fatal_error);
5104 #ifdef SIGPIPE
5105   if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
5106     signal (SIGPIPE, fatal_error);
5107 #endif
5108
5109   argbuf_length = 10;
5110   argbuf = (const char **) xmalloc (argbuf_length * sizeof (const char *));
5111
5112   obstack_init (&obstack);
5113
5114   /* Build multilib_select, et. al from the separate lines that make up each
5115      multilib selection.  */
5116   {
5117     const char *const *q = multilib_raw;
5118     int need_space;
5119
5120     obstack_init (&multilib_obstack);
5121     while ((p = *q++) != (char *) 0)
5122       obstack_grow (&multilib_obstack, p, strlen (p));
5123
5124     obstack_1grow (&multilib_obstack, 0);
5125     multilib_select = obstack_finish (&multilib_obstack);
5126
5127     q = multilib_matches_raw;
5128     while ((p = *q++) != (char *) 0)
5129       obstack_grow (&multilib_obstack, p, strlen (p));
5130
5131     obstack_1grow (&multilib_obstack, 0);
5132     multilib_matches = obstack_finish (&multilib_obstack);
5133
5134     q = multilib_exclusions_raw;
5135     while ((p = *q++) != (char *) 0)
5136       obstack_grow (&multilib_obstack, p, strlen (p));
5137
5138     obstack_1grow (&multilib_obstack, 0);
5139     multilib_exclusions = obstack_finish (&multilib_obstack);
5140
5141     need_space = FALSE;
5142     for (i = 0; i < ARRAY_SIZE (multilib_defaults_raw); i++)
5143       {
5144         if (need_space)
5145           obstack_1grow (&multilib_obstack, ' ');
5146         obstack_grow (&multilib_obstack,
5147                       multilib_defaults_raw[i],
5148                       strlen (multilib_defaults_raw[i]));
5149         need_space = TRUE;
5150       }
5151
5152     obstack_1grow (&multilib_obstack, 0);
5153     multilib_defaults = obstack_finish (&multilib_obstack);
5154   }
5155
5156   /* Set up to remember the pathname of gcc and any options
5157      needed for collect.  We use argv[0] instead of programname because
5158      we need the complete pathname.  */
5159   obstack_init (&collect_obstack);
5160   obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);
5161   obstack_grow (&collect_obstack, argv[0], strlen (argv[0]) + 1);
5162   putenv (obstack_finish (&collect_obstack));
5163
5164 #ifdef INIT_ENVIRONMENT
5165   /* Set up any other necessary machine specific environment variables.  */
5166   putenv (INIT_ENVIRONMENT);
5167 #endif
5168
5169   /* Make a table of what switches there are (switches, n_switches).
5170      Make a table of specified input files (infiles, n_infiles).
5171      Decode switches that are handled locally.  */
5172
5173   process_command (argc, argv);
5174
5175   {
5176     int first_time;
5177
5178     /* Build COLLECT_GCC_OPTIONS to have all of the options specified to
5179        the compiler.  */
5180     obstack_grow (&collect_obstack, "COLLECT_GCC_OPTIONS=",
5181                   sizeof ("COLLECT_GCC_OPTIONS=") - 1);
5182
5183     first_time = TRUE;
5184     for (i = 0; (int) i < n_switches; i++)
5185       {
5186         const char *const *args;
5187         const char *p, *q;
5188         if (!first_time)
5189           obstack_grow (&collect_obstack, " ", 1);
5190
5191         first_time = FALSE;
5192         obstack_grow (&collect_obstack, "'-", 2);
5193         q = switches[i].part1;
5194         while ((p = index (q, '\'')))
5195           {
5196             obstack_grow (&collect_obstack, q, p - q);
5197             obstack_grow (&collect_obstack, "'\\''", 4);
5198             q = ++p;
5199           }
5200         obstack_grow (&collect_obstack, q, strlen (q));
5201         obstack_grow (&collect_obstack, "'", 1);
5202
5203         for (args = switches[i].args; args && *args; args++)
5204           {
5205             obstack_grow (&collect_obstack, " '", 2);
5206             q = *args;
5207             while ((p = index (q, '\'')))
5208               {
5209                 obstack_grow (&collect_obstack, q, p - q);
5210                 obstack_grow (&collect_obstack, "'\\''", 4);
5211                 q = ++p;
5212               }
5213             obstack_grow (&collect_obstack, q, strlen (q));
5214             obstack_grow (&collect_obstack, "'", 1);
5215           }
5216       }
5217     obstack_grow (&collect_obstack, "\0", 1);
5218     putenv (obstack_finish (&collect_obstack));
5219   }
5220
5221   /* Initialize the vector of specs to just the default.
5222      This means one element containing 0s, as a terminator.  */
5223
5224   compilers = (struct compiler *) xmalloc (sizeof default_compilers);
5225   bcopy ((char *) default_compilers, (char *) compilers,
5226          sizeof default_compilers);
5227   n_compilers = n_default_compilers;
5228
5229   /* Read specs from a file if there is one.  */
5230
5231   machine_suffix = concat (spec_machine, dir_separator_str,
5232                            spec_version, dir_separator_str, NULL_PTR);
5233   just_machine_suffix = concat (spec_machine, dir_separator_str, NULL_PTR);
5234
5235   specs_file = find_a_file (&startfile_prefixes, "specs", R_OK);
5236   /* Read the specs file unless it is a default one.  */
5237   if (specs_file != 0 && strcmp (specs_file, "specs"))
5238     read_specs (specs_file, TRUE);
5239   else
5240     init_spec ();
5241
5242   /* We need to check standard_exec_prefix/just_machine_suffix/specs
5243      for any override of as, ld and libraries.  */
5244   specs_file = (char *) alloca (strlen (standard_exec_prefix)
5245                                 + strlen (just_machine_suffix)
5246                                 + sizeof ("specs"));
5247
5248   strcpy (specs_file, standard_exec_prefix);
5249   strcat (specs_file, just_machine_suffix);
5250   strcat (specs_file, "specs");
5251   if (access (specs_file, R_OK) == 0)
5252     read_specs (specs_file, TRUE);
5253
5254   /* If not cross-compiling, look for startfiles in the standard places.  */
5255   if (*cross_compile == '0')
5256     {
5257 #ifdef MD_EXEC_PREFIX
5258       add_prefix (&exec_prefixes, md_exec_prefix, "GCC",
5259                   PREFIX_PRIORITY_LAST, 0, NULL_PTR);
5260       add_prefix (&startfile_prefixes, md_exec_prefix, "GCC",
5261                   PREFIX_PRIORITY_LAST, 0, NULL_PTR);
5262 #endif
5263
5264 #ifdef MD_STARTFILE_PREFIX
5265       add_prefix (&startfile_prefixes, md_startfile_prefix, "GCC",
5266                   PREFIX_PRIORITY_LAST, 0, NULL_PTR);
5267 #endif
5268
5269 #ifdef MD_STARTFILE_PREFIX_1
5270       add_prefix (&startfile_prefixes, md_startfile_prefix_1, "GCC",
5271                   PREFIX_PRIORITY_LAST, 0, NULL_PTR);
5272 #endif
5273
5274       /* If standard_startfile_prefix is relative, base it on
5275          standard_exec_prefix.  This lets us move the installed tree
5276          as a unit.  If GCC_EXEC_PREFIX is defined, base
5277          standard_startfile_prefix on that as well.  */
5278       if (IS_DIR_SEPARATOR (*standard_startfile_prefix)
5279             || *standard_startfile_prefix == '$'
5280 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
5281             /* Check for disk name on MS-DOS-based systems.  */
5282           || (standard_startfile_prefix[1] == ':'
5283               && (IS_DIR_SEPARATOR (standard_startfile_prefix[2])))
5284 #endif
5285           )
5286         add_prefix (&startfile_prefixes, standard_startfile_prefix, "BINUTILS",
5287                     PREFIX_PRIORITY_LAST, 0, NULL_PTR);
5288       else
5289         {
5290           if (gcc_exec_prefix)
5291             add_prefix (&startfile_prefixes,
5292                         concat (gcc_exec_prefix, machine_suffix,
5293                                 standard_startfile_prefix, NULL_PTR),
5294                         NULL_PTR, PREFIX_PRIORITY_LAST, 0, NULL_PTR);
5295           add_prefix (&startfile_prefixes,
5296                       concat (standard_exec_prefix,
5297                               machine_suffix,
5298                               standard_startfile_prefix, NULL_PTR),
5299                       NULL_PTR, PREFIX_PRIORITY_LAST, 0, NULL_PTR);
5300         }
5301
5302       add_prefix (&startfile_prefixes, standard_startfile_prefix_1,
5303                   "BINUTILS", PREFIX_PRIORITY_LAST, 0, NULL_PTR);
5304       add_prefix (&startfile_prefixes, standard_startfile_prefix_2,
5305                   "BINUTILS", PREFIX_PRIORITY_LAST, 0, NULL_PTR);
5306 #if 0 /* Can cause surprises, and one can use -B./ instead.  */
5307       add_prefix (&startfile_prefixes, "./", NULL_PTR,
5308                   PREFIX_PRIORITY_LAST, 1, NULL_PTR);
5309 #endif
5310     }
5311   else
5312     {
5313       if (!IS_DIR_SEPARATOR (*standard_startfile_prefix) && gcc_exec_prefix)
5314         add_prefix (&startfile_prefixes,
5315                     concat (gcc_exec_prefix, machine_suffix,
5316                             standard_startfile_prefix, NULL_PTR),
5317                     "BINUTILS", PREFIX_PRIORITY_LAST, 0, NULL_PTR);
5318     }
5319
5320   /* Process any user specified specs in the order given on the command
5321      line.  */
5322   for (uptr = user_specs_head; uptr; uptr = uptr->next)
5323     {
5324       char *filename = find_a_file (&startfile_prefixes, uptr->filename, R_OK);
5325       read_specs (filename ? filename : uptr->filename, FALSE);
5326     }
5327
5328   /* If we have a GCC_EXEC_PREFIX envvar, modify it for cpp's sake.  */
5329   if (gcc_exec_prefix)
5330     {
5331       char *temp = (char *) xmalloc (strlen (gcc_exec_prefix)
5332                                      + strlen (spec_version)
5333                                      + strlen (spec_machine) + 3);
5334       strcpy (temp, gcc_exec_prefix);
5335       strcat (temp, spec_machine);
5336       strcat (temp, dir_separator_str);
5337       strcat (temp, spec_version);
5338       strcat (temp, dir_separator_str);
5339       gcc_exec_prefix = temp;
5340     }
5341
5342   /* Now we have the specs.
5343      Set the `valid' bits for switches that match anything in any spec.  */
5344
5345   validate_all_switches ();
5346
5347   /* Now that we have the switches and the specs, set
5348      the subdirectory based on the options.  */
5349   set_multilib_dir ();
5350
5351   /* Warn about any switches that no pass was interested in.  */
5352
5353   for (i = 0; (int) i < n_switches; i++)
5354     if (! switches[i].validated)
5355       error ("unrecognized option `-%s'", switches[i].part1);
5356
5357   /* Obey some of the options.  */
5358
5359   if (print_search_dirs)
5360     {
5361       printf (_("install: %s%s\n"), standard_exec_prefix, machine_suffix);
5362       printf (_("programs: %s\n"), build_search_list (&exec_prefixes, "", 0));
5363       printf (_("libraries: %s\n"), build_search_list (&startfile_prefixes, "", 0));
5364       return (0);
5365     }
5366
5367   if (print_file_name)
5368     {
5369       printf ("%s\n", find_file (print_file_name));
5370       return (0);
5371     }
5372
5373   if (print_prog_name)
5374     {
5375       char *newname = find_a_file (&exec_prefixes, print_prog_name, X_OK);
5376       printf ("%s\n", (newname ? newname : print_prog_name));
5377       return (0);
5378     }
5379
5380   if (print_multi_lib)
5381     {
5382       print_multilib_info ();
5383       return (0);
5384     }
5385
5386   if (print_multi_directory)
5387     {
5388       if (multilib_dir == NULL)
5389         printf (".\n");
5390       else
5391         printf ("%s\n", multilib_dir);
5392       return (0);
5393     }
5394
5395   if (print_help_list)
5396     {
5397       display_help ();
5398
5399       if (! verbose_flag)
5400         {
5401           printf (_("\nFor bug reporting instructions, please see:\n"));
5402           printf ("%s.\n", GCCBUGURL);
5403
5404           return (0);
5405         }
5406
5407       /* We do not exit here.  Instead we have created a fake input file
5408          called 'help-dummy' which needs to be compiled, and we pass this
5409          on the the various sub-processes, along with the --help switch.  */
5410     }
5411
5412   if (verbose_flag)
5413     {
5414       int n;
5415
5416       /* compiler_version is truncated at the first space when initialized
5417          from version string, so truncate version_string at the first space
5418          before comparing.  */
5419       for (n = 0; version_string[n]; n++)
5420         if (version_string[n] == ' ')
5421           break;
5422
5423       if (! strncmp (version_string, compiler_version, n)
5424           && compiler_version[n] == 0)
5425         notice ("gcc version %s\n", version_string);
5426       else
5427         notice ("gcc driver version %s executing gcc version %s\n",
5428                 version_string, compiler_version);
5429
5430       if (n_infiles == 0)
5431         return (0);
5432     }
5433
5434   if (n_infiles == added_libraries)
5435     fatal ("No input files");
5436
5437   /* Make a place to record the compiler output file names
5438      that correspond to the input files.  */
5439
5440   i = n_infiles;
5441   i += lang_specific_extra_outfiles;
5442   outfiles = (const char **) xcalloc (i, sizeof (char *));
5443
5444   /* Record which files were specified explicitly as link input.  */
5445
5446   explicit_link_files = xcalloc (1, n_infiles);
5447
5448   for (i = 0; (int) i < n_infiles; i++)
5449     {
5450       register struct compiler *cp = 0;
5451       int this_file_error = 0;
5452
5453       /* Tell do_spec what to substitute for %i.  */
5454
5455       input_file_number = i;
5456       set_input (infiles[i].name);
5457
5458       /* Use the same thing in %o, unless cp->spec says otherwise.  */
5459
5460       outfiles[i] = input_filename;
5461
5462       /* Figure out which compiler from the file's suffix.  */
5463
5464       cp = lookup_compiler (infiles[i].name, input_filename_length,
5465                             infiles[i].language);
5466
5467       if (cp)
5468         {
5469           /* Ok, we found an applicable compiler.  Run its spec.  */
5470
5471           if (cp->spec[0] == '#')
5472             error ("%s: %s compiler not installed on this system",
5473                    input_filename, &cp->spec[1]);
5474           value = do_spec (cp->spec);
5475           if (value < 0)
5476             this_file_error = 1;
5477         }
5478
5479       /* If this file's name does not contain a recognized suffix,
5480          record it as explicit linker input.  */
5481
5482       else
5483         explicit_link_files[i] = 1;
5484
5485       /* Clear the delete-on-failure queue, deleting the files in it
5486          if this compilation failed.  */
5487
5488       if (this_file_error)
5489         {
5490           delete_failure_queue ();
5491           error_count++;
5492         }
5493       /* If this compilation succeeded, don't delete those files later.  */
5494       clear_failure_queue ();
5495     }
5496
5497   /* Reset the output file name to the first input file name, for use
5498      with %b in LINK_SPEC on a target that prefers not to emit a.out
5499      by default.  */
5500   if (n_infiles > 0)
5501     set_input (infiles[0].name);
5502
5503   if (error_count == 0)
5504     {
5505       /* Make sure INPUT_FILE_NUMBER points to first available open
5506          slot.  */
5507       input_file_number = n_infiles;
5508       if (lang_specific_pre_link ())
5509         error_count++;
5510     }
5511
5512   /* Run ld to link all the compiler output files.  */
5513
5514   if (error_count == 0)
5515     {
5516       int tmp = execution_count;
5517
5518       /* We'll use ld if we can't find collect2.  */
5519       if (! strcmp (linker_name_spec, "collect2"))
5520         {
5521           char *s = find_a_file (&exec_prefixes, "collect2", X_OK);
5522           if (s == NULL)
5523             linker_name_spec = "ld";
5524         }
5525       /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
5526          for collect.  */
5527       putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH");
5528       putenv_from_prefixes (&startfile_prefixes, LIBRARY_PATH_ENV);
5529
5530       value = do_spec (link_command_spec);
5531       if (value < 0)
5532         error_count = 1;
5533       linker_was_run = (tmp != execution_count);
5534     }
5535
5536   /* If options said don't run linker,
5537      complain about input files to be given to the linker.  */
5538
5539   if (! linker_was_run && error_count == 0)
5540     for (i = 0; (int) i < n_infiles; i++)
5541       if (explicit_link_files[i])
5542         error ("%s: linker input file unused since linking not done",
5543                outfiles[i]);
5544
5545   /* Delete some or all of the temporary files we made.  */
5546
5547   if (error_count)
5548     delete_failure_queue ();
5549   delete_temp_files ();
5550
5551   if (print_help_list)
5552     {
5553       printf (("\nFor bug reporting instructions, please see:\n"));
5554       printf ("%s\n", GCCBUGURL);
5555     }
5556
5557   return (signal_count != 0 ? 2
5558           : error_count > 0 ? (pass_exit_codes ? greatest_status : 1)
5559           : 0);
5560 }
5561
5562 /* Find the proper compilation spec for the file name NAME,
5563    whose length is LENGTH.  LANGUAGE is the specified language,
5564    or 0 if this file is to be passed to the linker.  */
5565
5566 static struct compiler *
5567 lookup_compiler (name, length, language)
5568      const char *name;
5569      size_t length;
5570      const char *language;
5571 {
5572   struct compiler *cp;
5573
5574   /* If this was specified by the user to be a linker input, indicate that.  */
5575   if (language != 0 && language[0] == '*')
5576     return 0;
5577
5578   /* Otherwise, look for the language, if one is spec'd.  */
5579   if (language != 0)
5580     {
5581       for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
5582         if (cp->suffix[0] == '@' && !strcmp (cp->suffix + 1, language))
5583           return cp;
5584
5585       error ("language %s not recognized", language);
5586       return 0;
5587     }
5588
5589   /* Look for a suffix.  */
5590   for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
5591     {
5592       if (/* The suffix `-' matches only the file name `-'.  */
5593           (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
5594           || (strlen (cp->suffix) < length
5595               /* See if the suffix matches the end of NAME.  */
5596               && !strcmp (cp->suffix,
5597                           name + length - strlen (cp->suffix))
5598          ))
5599         break;
5600     }
5601
5602 #if defined (OS2) ||defined (HAVE_DOS_BASED_FILE_SYSTEM)
5603   /* look again, but case-insensitively this time.  */
5604   if (cp < compilers)
5605     for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
5606       {
5607         if (/* The suffix `-' matches only the file name `-'.  */
5608             (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
5609             || (strlen (cp->suffix) < length
5610                 /* See if the suffix matches the end of NAME.  */
5611                 && ((!strcmp (cp->suffix,
5612                              name + length - strlen (cp->suffix))
5613                      || !strpbrk (cp->suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
5614                     && !strcasecmp (cp->suffix,
5615                                     name + length - strlen (cp->suffix)))
5616            ))
5617           break;
5618       }
5619 #endif
5620
5621   if (cp >= compilers)
5622     {
5623       if (cp->spec[0] != '@')
5624         /* A non-alias entry: return it.  */
5625         return cp;
5626
5627       /* An alias entry maps a suffix to a language.
5628          Search for the language; pass 0 for NAME and LENGTH
5629          to avoid infinite recursion if language not found.  */
5630       return lookup_compiler (NULL_PTR, 0, cp->spec + 1);
5631     }
5632   return 0;
5633 }
5634 \f
5635 static char *
5636 save_string (s, len)
5637      const char *s;
5638      int len;
5639 {
5640   register char *result = xmalloc (len + 1);
5641
5642   bcopy (s, result, len);
5643   result[len] = 0;
5644   return result;
5645 }
5646
5647 static void
5648 pfatal_with_name (name)
5649      const char *name;
5650 {
5651   perror_with_name (name);
5652   delete_temp_files ();
5653   exit (1);
5654 }
5655
5656 static void
5657 perror_with_name (name)
5658      const char *name;
5659 {
5660   error ("%s: %s", name, xstrerror (errno));
5661 }
5662
5663 static void
5664 pfatal_pexecute (errmsg_fmt, errmsg_arg)
5665      const char *errmsg_fmt;
5666      const char *errmsg_arg;
5667 {
5668   if (errmsg_arg)
5669     {
5670       int save_errno = errno;
5671
5672       /* Space for trailing '\0' is in %s.  */
5673       char *msg = xmalloc (strlen (errmsg_fmt) + strlen (errmsg_arg));
5674       sprintf (msg, errmsg_fmt, errmsg_arg);
5675       errmsg_fmt = msg;
5676
5677       errno = save_errno;
5678     }
5679
5680   pfatal_with_name (errmsg_fmt);
5681 }
5682
5683 /* Output an error message and exit */
5684
5685 void
5686 fancy_abort ()
5687 {
5688   fatal ("Internal gcc abort.");
5689 }
5690 \f
5691 /* Output an error message and exit */
5692
5693 void
5694 fatal VPARAMS ((const char *msgid, ...))
5695 {
5696 #ifndef ANSI_PROTOTYPES
5697   const char *msgid;
5698 #endif
5699   va_list ap;
5700
5701   VA_START (ap, msgid);
5702
5703 #ifndef ANSI_PROTOTYPES
5704   msgid = va_arg (ap, const char *);
5705 #endif
5706
5707   fprintf (stderr, "%s: ", programname);
5708   vfprintf (stderr, _(msgid), ap);
5709   va_end (ap);
5710   fprintf (stderr, "\n");
5711   delete_temp_files ();
5712   exit (1);
5713 }
5714
5715 static void
5716 error VPARAMS ((const char *msgid, ...))
5717 {
5718 #ifndef ANSI_PROTOTYPES
5719   const char *msgid;
5720 #endif
5721   va_list ap;
5722
5723   VA_START (ap, msgid);
5724
5725 #ifndef ANSI_PROTOTYPES
5726   msgid = va_arg (ap, const char *);
5727 #endif
5728
5729   fprintf (stderr, "%s: ", programname);
5730   vfprintf (stderr, _(msgid), ap);
5731   va_end (ap);
5732
5733   fprintf (stderr, "\n");
5734 }
5735
5736 static void
5737 notice VPARAMS ((const char *msgid, ...))
5738 {
5739 #ifndef ANSI_PROTOTYPES
5740   const char *msgid;
5741 #endif
5742   va_list ap;
5743
5744   VA_START (ap, msgid);
5745
5746 #ifndef ANSI_PROTOTYPES
5747   msgid = va_arg (ap, const char *);
5748 #endif
5749
5750   vfprintf (stderr, _(msgid), ap);
5751   va_end (ap);
5752 }
5753 \f
5754 static void
5755 validate_all_switches ()
5756 {
5757   struct compiler *comp;
5758   register const char *p;
5759   register char c;
5760   struct spec_list *spec;
5761
5762   for (comp = compilers; comp->spec; comp++)
5763     {
5764       p = comp->spec;
5765       while ((c = *p++))
5766         if (c == '%' && *p == '{')
5767           /* We have a switch spec.  */
5768           validate_switches (p + 1);
5769     }
5770
5771   /* Look through the linked list of specs read from the specs file.  */
5772   for (spec = specs; spec; spec = spec->next)
5773     {
5774       p = *(spec->ptr_spec);
5775       while ((c = *p++))
5776         if (c == '%' && *p == '{')
5777           /* We have a switch spec.  */
5778           validate_switches (p + 1);
5779     }
5780
5781   p = link_command_spec;
5782   while ((c = *p++))
5783     if (c == '%' && *p == '{')
5784       /* We have a switch spec.  */
5785       validate_switches (p + 1);
5786 }
5787
5788 /* Look at the switch-name that comes after START
5789    and mark as valid all supplied switches that match it.  */
5790
5791 static void
5792 validate_switches (start)
5793      const char *start;
5794 {
5795   register const char *p = start;
5796   const char *filter;
5797   register int i;
5798   int suffix = 0;
5799
5800   if (*p == '|')
5801     ++p;
5802
5803   if (*p == '!')
5804     ++p;
5805
5806   if (*p == '.')
5807     suffix = 1, ++p;
5808
5809   filter = p;
5810   while (*p != ':' && *p != '}')
5811     p++;
5812
5813   if (suffix)
5814     ;
5815   else if (p[-1] == '*')
5816     {
5817       /* Mark all matching switches as valid.  */
5818       --p;
5819       for (i = 0; i < n_switches; i++)
5820         if (!strncmp (switches[i].part1, filter, p - filter))
5821           switches[i].validated = 1;
5822     }
5823   else
5824     {
5825       /* Mark an exact matching switch as valid.  */
5826       for (i = 0; i < n_switches; i++)
5827         {
5828           if (!strncmp (switches[i].part1, filter, p - filter)
5829               && switches[i].part1[p - filter] == 0)
5830             switches[i].validated = 1;
5831         }
5832     }
5833 }
5834 \f
5835 /* Check whether a particular argument was used.  The first time we
5836    canonicalize the switches to keep only the ones we care about.  */
5837
5838 static int
5839 used_arg (p, len)
5840      const char *p;
5841      int len;
5842 {
5843   struct mswitchstr
5844   {
5845     const char *str;
5846     const char *replace;
5847     int len;
5848     int rep_len;
5849   };
5850
5851   static struct mswitchstr *mswitches;
5852   static int n_mswitches;
5853   int i, j;
5854
5855   if (!mswitches)
5856     {
5857       struct mswitchstr *matches;
5858       const char *q;
5859       int cnt = 0;
5860
5861       /* Break multilib_matches into the component strings of string
5862          and replacement string.  */
5863       for (q = multilib_matches; *q != '\0'; q++)
5864         if (*q == ';')
5865           cnt++;
5866
5867       matches =
5868         (struct mswitchstr *) alloca ((sizeof (struct mswitchstr)) * cnt);
5869       i = 0;
5870       q = multilib_matches;
5871       while (*q != '\0')
5872         {
5873           matches[i].str = q;
5874           while (*q != ' ')
5875             {
5876               if (*q == '\0')
5877                 abort ();
5878               q++;
5879             }
5880           matches[i].len = q - matches[i].str;
5881
5882           matches[i].replace = ++q;
5883           while (*q != ';' && *q != '\0')
5884             {
5885               if (*q == ' ')
5886                 abort ();
5887               q++;
5888             }
5889           matches[i].rep_len = q - matches[i].replace;
5890           i++;
5891           if (*q == ';')
5892             q++;
5893         }
5894
5895       /* Now build a list of the replacement string for switches that we care
5896          about.  Make sure we allocate at least one entry.  This prevents
5897          xmalloc from calling fatal, and prevents us from re-executing this
5898          block of code.  */
5899       mswitches
5900         = (struct mswitchstr *) xmalloc ((sizeof (struct mswitchstr))
5901                                          * (n_switches ? n_switches : 1));
5902       for (i = 0; i < n_switches; i++)
5903         {
5904           int xlen = strlen (switches[i].part1);
5905           for (j = 0; j < cnt; j++)
5906             if (xlen == matches[j].len
5907                 && ! strncmp (switches[i].part1, matches[j].str, xlen))
5908               {
5909                 mswitches[n_mswitches].str = matches[j].replace;
5910                 mswitches[n_mswitches].len = matches[j].rep_len;
5911                 mswitches[n_mswitches].replace = (char *) 0;
5912                 mswitches[n_mswitches].rep_len = 0;
5913                 n_mswitches++;
5914                 break;
5915               }
5916         }
5917     }
5918
5919   for (i = 0; i < n_mswitches; i++)
5920     if (len == mswitches[i].len && ! strncmp (p, mswitches[i].str, len))
5921       return 1;
5922
5923   return 0;
5924 }
5925
5926 static int
5927 default_arg (p, len)
5928      const char *p;
5929      int len;
5930 {
5931   const char *start, *end;
5932
5933   for (start = multilib_defaults; *start != '\0'; start = end + 1)
5934     {
5935       while (*start == ' ' || *start == '\t')
5936         start++;
5937
5938       if (*start == '\0')
5939         break;
5940
5941       for (end = start + 1; *end != ' ' && *end != '\t' && *end != '\0'; end++)
5942         ;
5943
5944       if ((end - start) == len && strncmp (p, start, len) == 0)
5945         return 1;
5946
5947       if (*end == '\0')
5948         break;
5949     }
5950
5951   return 0;
5952 }
5953
5954 /* Work out the subdirectory to use based on the options. The format of
5955    multilib_select is a list of elements. Each element is a subdirectory
5956    name followed by a list of options followed by a semicolon. The format
5957    of multilib_exclusions is the same, but without the preceding
5958    directory. First gcc will check the exclusions, if none of the options
5959    beginning with an exclamation point are present, and all of the other
5960    options are present, then we will ignore this completely. Passing
5961    that, gcc will consider each multilib_select in turn using the same
5962    rules for matching the options. If a match is found, that subdirectory
5963    will be used.  */
5964
5965 static void
5966 set_multilib_dir ()
5967 {
5968   const char *p;
5969   unsigned int this_path_len;
5970   const char *this_path, *this_arg;
5971   int not_arg;
5972   int ok;
5973
5974   p = multilib_exclusions;
5975   while (*p != '\0')
5976     {
5977       /* Ignore newlines.  */
5978       if (*p == '\n')
5979         {
5980           ++p;
5981           continue;
5982         }
5983
5984       /* Check the arguments.  */
5985       ok = 1;
5986       while (*p != ';')
5987         {
5988           if (*p == '\0')
5989             abort ();
5990
5991           if (! ok)
5992             {
5993               ++p;
5994               continue;
5995             }
5996
5997           this_arg = p;
5998           while (*p != ' ' && *p != ';')
5999             {
6000               if (*p == '\0')
6001                 abort ();
6002               ++p;
6003             }
6004
6005           if (*this_arg != '!')
6006             not_arg = 0;
6007           else
6008             {
6009               not_arg = 1;
6010               ++this_arg;
6011             }
6012
6013           ok = used_arg (this_arg, p - this_arg);
6014           if (not_arg)
6015             ok = ! ok;
6016
6017           if (*p == ' ')
6018             ++p;
6019         }
6020
6021       if (ok)
6022         return;
6023
6024       ++p;
6025     }
6026
6027   p = multilib_select;
6028   while (*p != '\0')
6029     {
6030       /* Ignore newlines.  */
6031       if (*p == '\n')
6032         {
6033           ++p;
6034           continue;
6035         }
6036
6037       /* Get the initial path.  */
6038       this_path = p;
6039       while (*p != ' ')
6040         {
6041           if (*p == '\0')
6042             abort ();
6043           ++p;
6044         }
6045       this_path_len = p - this_path;
6046
6047       /* Check the arguments.  */
6048       ok = 1;
6049       ++p;
6050       while (*p != ';')
6051         {
6052           if (*p == '\0')
6053             abort ();
6054
6055           if (! ok)
6056             {
6057               ++p;
6058               continue;
6059             }
6060
6061           this_arg = p;
6062           while (*p != ' ' && *p != ';')
6063             {
6064               if (*p == '\0')
6065                 abort ();
6066               ++p;
6067             }
6068
6069           if (*this_arg != '!')
6070             not_arg = 0;
6071           else
6072             {
6073               not_arg = 1;
6074               ++this_arg;
6075             }
6076
6077           /* If this is a default argument, we can just ignore it.
6078              This is true even if this_arg begins with '!'.  Beginning
6079              with '!' does not mean that this argument is necessarily
6080              inappropriate for this library: it merely means that
6081              there is a more specific library which uses this
6082              argument.  If this argument is a default, we need not
6083              consider that more specific library.  */
6084           if (! default_arg (this_arg, p - this_arg))
6085             {
6086               ok = used_arg (this_arg, p - this_arg);
6087               if (not_arg)
6088                 ok = ! ok;
6089             }
6090
6091           if (*p == ' ')
6092             ++p;
6093         }
6094
6095       if (ok)
6096         {
6097           if (this_path_len != 1
6098               || this_path[0] != '.')
6099             {
6100               char *new_multilib_dir = xmalloc (this_path_len + 1);
6101               strncpy (new_multilib_dir, this_path, this_path_len);
6102               new_multilib_dir[this_path_len] = '\0';
6103               multilib_dir = new_multilib_dir;
6104             }
6105           break;
6106         }
6107
6108       ++p;
6109     }
6110 }
6111
6112 /* Print out the multiple library subdirectory selection
6113    information.  This prints out a series of lines.  Each line looks
6114    like SUBDIRECTORY;@OPTION@OPTION, with as many options as is
6115    required.  Only the desired options are printed out, the negative
6116    matches.  The options are print without a leading dash.  There are
6117    no spaces to make it easy to use the information in the shell.
6118    Each subdirectory is printed only once.  This assumes the ordering
6119    generated by the genmultilib script. Also, we leave out ones that match
6120    the exclusions.  */
6121
6122 static void
6123 print_multilib_info ()
6124 {
6125   const char *p = multilib_select;
6126   const char *last_path = 0, *this_path;
6127   int skip;
6128   unsigned int last_path_len = 0;
6129
6130   while (*p != '\0')
6131     {
6132       skip = 0;
6133       /* Ignore newlines.  */
6134       if (*p == '\n')
6135         {
6136           ++p;
6137           continue;
6138         }
6139
6140       /* Get the initial path.  */
6141       this_path = p;
6142       while (*p != ' ')
6143         {
6144           if (*p == '\0')
6145             abort ();
6146           ++p;
6147         }
6148
6149       /* Check for matches with the multilib_exclusions. We don't bother
6150          with the '!' in either list. If any of the exclusion rules match
6151          all of its options with the select rule, we skip it.  */
6152       {
6153         const char *e = multilib_exclusions;
6154         const char *this_arg;
6155
6156         while (*e != '\0')
6157           {
6158             int m = 1;
6159             /* Ignore newlines.  */
6160             if (*e == '\n')
6161               {
6162                 ++e;
6163                 continue;
6164               }
6165
6166             /* Check the arguments.  */
6167             while (*e != ';')
6168               {
6169                 const char *q;
6170                 int mp = 0;
6171
6172                 if (*e == '\0')
6173                   abort ();
6174
6175                 if (! m)
6176                   {
6177                     ++e;
6178                     continue;
6179                   }
6180
6181                 this_arg = e;
6182
6183                 while (*e != ' ' && *e != ';')
6184                   {
6185                     if (*e == '\0')
6186                       abort ();
6187                     ++e;
6188                   }
6189
6190                 q = p + 1;
6191                 while (*q != ';')
6192                   {
6193                     const char *arg;
6194                     int len = e - this_arg;
6195
6196                     if (*q == '\0')
6197                       abort ();
6198
6199                     arg = q;
6200
6201                     while (*q != ' ' && *q != ';')
6202                       {
6203                         if (*q == '\0')
6204                           abort ();
6205                         ++q;
6206                       }
6207
6208                     if (! strncmp (arg, this_arg, (len < q - arg) ? q - arg : len) ||
6209                         default_arg (this_arg, e - this_arg))
6210                       {
6211                         mp = 1;
6212                         break;
6213                       }
6214
6215                     if (*q == ' ')
6216                       ++q;
6217                   }
6218
6219                 if (! mp)
6220                   m = 0;
6221
6222                 if (*e == ' ')
6223                   ++e;
6224               }
6225
6226             if (m)
6227               {
6228                 skip = 1;
6229                 break;
6230               }
6231
6232             if (*e != '\0')
6233               ++e;
6234           }
6235       }
6236
6237       if (! skip)
6238         {
6239           /* If this is a duplicate, skip it.  */
6240           skip = (last_path != 0 && (unsigned int) (p - this_path) == last_path_len
6241                   && ! strncmp (last_path, this_path, last_path_len));
6242
6243           last_path = this_path;
6244           last_path_len = p - this_path;
6245         }
6246
6247       /* If this directory requires any default arguments, we can skip
6248          it.  We will already have printed a directory identical to
6249          this one which does not require that default argument.  */
6250       if (! skip)
6251         {
6252           const char *q;
6253
6254           q = p + 1;
6255           while (*q != ';')
6256             {
6257               const char *arg;
6258
6259               if (*q == '\0')
6260                 abort ();
6261
6262               if (*q == '!')
6263                 arg = NULL;
6264               else
6265                 arg = q;
6266
6267               while (*q != ' ' && *q != ';')
6268                 {
6269                   if (*q == '\0')
6270                     abort ();
6271                   ++q;
6272                 }
6273
6274               if (arg != NULL
6275                   && default_arg (arg, q - arg))
6276                 {
6277                   skip = 1;
6278                   break;
6279                 }
6280
6281               if (*q == ' ')
6282                 ++q;
6283             }
6284         }
6285
6286       if (! skip)
6287         {
6288           const char *p1;
6289
6290           for (p1 = last_path; p1 < p; p1++)
6291             putchar (*p1);
6292           putchar (';');
6293         }
6294
6295       ++p;
6296       while (*p != ';')
6297         {
6298           int use_arg;
6299
6300           if (*p == '\0')
6301             abort ();
6302
6303           if (skip)
6304             {
6305               ++p;
6306               continue;
6307             }
6308
6309           use_arg = *p != '!';
6310
6311           if (use_arg)
6312             putchar ('@');
6313
6314           while (*p != ' ' && *p != ';')
6315             {
6316               if (*p == '\0')
6317                 abort ();
6318               if (use_arg)
6319                 putchar (*p);
6320               ++p;
6321             }
6322
6323           if (*p == ' ')
6324             ++p;
6325         }
6326
6327       if (! skip)
6328         {
6329           /* If there are extra options, print them now.  */
6330           if (multilib_extra && *multilib_extra)
6331             {
6332               int print_at = TRUE;
6333               const char *q;
6334
6335               for (q = multilib_extra; *q != '\0'; q++)
6336                 {
6337                   if (*q == ' ')
6338                     print_at = TRUE;
6339                   else
6340                     {
6341                       if (print_at)
6342                         putchar ('@');
6343                       putchar (*q);
6344                       print_at = FALSE;
6345                     }
6346                 }
6347             }
6348
6349           putchar ('\n');
6350         }
6351
6352       ++p;
6353     }
6354 }