OSDN Git Service

* pa.c (legitimize_pic_address): Use gcc_assert instead of abort.
[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, 2001, 2002, 2003, 2004, 2005 Free Software Foundation,
4    Inc.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to the Free
20 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
21 02110-1301, USA.
22
23 This paragraph is here to try to keep Sun CC from dying.
24 The number of chars here seems crucial!!!!  */
25
26 /* This program is the user interface to the C compiler and possibly to
27 other compilers.  It is used because compilation is a complicated procedure
28 which involves running several programs and passing temporary files between
29 them, forwarding the users switches to those programs selectively,
30 and deleting the temporary files at the end.
31
32 CC recognizes how to compile each input file by suffixes in the file names.
33 Once it knows which kind of compilation to perform, the procedure for
34 compilation is specified by a string called a "spec".  */
35
36 /* A Short Introduction to Adding a Command-Line Option.
37
38    Before adding a command-line option, consider if it is really
39    necessary.  Each additional command-line option adds complexity and
40    is difficult to remove in subsequent versions.
41
42    In the following, consider adding the command-line argument
43    `--bar'.
44
45    1. Each command-line option is specified in the specs file.  The
46    notation is described below in the comment entitled "The Specs
47    Language".  Read it.
48
49    2. In this file, add an entry to "option_map" equating the long
50    `--' argument version and any shorter, single letter version.  Read
51    the comments in the declaration of "struct option_map" for an
52    explanation.  Do not omit the first `-'.
53
54    3. Look in the "specs" file to determine which program or option
55    list should be given the argument, e.g., "cc1_options".  Add the
56    appropriate syntax for the shorter option version to the
57    corresponding "const char *" entry in this file.  Omit the first
58    `-' from the option.  For example, use `-bar', rather than `--bar'.
59
60    4. If the argument takes an argument, e.g., `--baz argument1',
61    modify either DEFAULT_SWITCH_TAKES_ARG or
62    DEFAULT_WORD_SWITCH_TAKES_ARG in gcc.h.  Omit the first `-'
63    from `--baz'.
64
65    5. Document the option in this file's display_help().  If the
66    option is passed to a subprogram, modify its corresponding
67    function, e.g., cppinit.c:print_help() or toplev.c:display_help(),
68    instead.
69
70    6. Compile and test.  Make sure that your new specs file is being
71    read.  For example, use a debugger to investigate the value of
72    "specs_file" in main().  */
73
74 #include "config.h"
75 #include "system.h"
76 #include "coretypes.h"
77 #include "multilib.h" /* before tm.h */
78 #include "tm.h"
79 #include <signal.h>
80 #if ! defined( SIGCHLD ) && defined( SIGCLD )
81 #  define SIGCHLD SIGCLD
82 #endif
83 #include "obstack.h"
84 #include "intl.h"
85 #include "prefix.h"
86 #include "gcc.h"
87 #include "flags.h"
88
89 /* By default there is no special suffix for target executables.  */
90 /* FIXME: when autoconf is fixed, remove the host check - dj */
91 #if defined(TARGET_EXECUTABLE_SUFFIX) && defined(HOST_EXECUTABLE_SUFFIX)
92 #define HAVE_TARGET_EXECUTABLE_SUFFIX
93 #endif
94
95 /* By default there is no special suffix for host executables.  */
96 #ifdef HOST_EXECUTABLE_SUFFIX
97 #define HAVE_HOST_EXECUTABLE_SUFFIX
98 #else
99 #define HOST_EXECUTABLE_SUFFIX ""
100 #endif
101
102 /* By default, the suffix for target object files is ".o".  */
103 #ifdef TARGET_OBJECT_SUFFIX
104 #define HAVE_TARGET_OBJECT_SUFFIX
105 #else
106 #define TARGET_OBJECT_SUFFIX ".o"
107 #endif
108
109 static const char dir_separator_str[] = { DIR_SEPARATOR, 0 };
110
111 /* Most every one is fine with LIBRARY_PATH.  For some, it conflicts.  */
112 #ifndef LIBRARY_PATH_ENV
113 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
114 #endif
115
116 #ifndef HAVE_KILL
117 #define kill(p,s) raise(s)
118 #endif
119
120 /* If a stage of compilation returns an exit status >= 1,
121    compilation of that file ceases.  */
122
123 #define MIN_FATAL_STATUS 1
124
125 /* Flag set by cppspec.c to 1.  */
126 int is_cpp_driver;
127
128 /* Flag saying to pass the greatest exit code returned by a sub-process
129    to the calling program.  */
130 static int pass_exit_codes;
131
132 /* Definition of string containing the arguments given to configure.  */
133 #include "configargs.h"
134
135 /* Flag saying to print the directories gcc will search through looking for
136    programs, libraries, etc.  */
137
138 static int print_search_dirs;
139
140 /* Flag saying to print the full filename of this file
141    as found through our usual search mechanism.  */
142
143 static const char *print_file_name = NULL;
144
145 /* As print_file_name, but search for executable file.  */
146
147 static const char *print_prog_name = NULL;
148
149 /* Flag saying to print the relative path we'd use to
150    find libgcc.a given the current compiler flags.  */
151
152 static int print_multi_directory;
153
154 /* Flag saying to print the relative path we'd use to
155    find OS libraries given the current compiler flags.  */
156
157 static int print_multi_os_directory;
158
159 /* Flag saying to print the list of subdirectories and
160    compiler flags used to select them in a standard form.  */
161
162 static int print_multi_lib;
163
164 /* Flag saying to print the command line options understood by gcc and its
165    sub-processes.  */
166
167 static int print_help_list;
168
169 /* Flag indicating whether we should print the command and arguments */
170
171 static int verbose_flag;
172
173 /* Flag indicating whether we should ONLY print the command and
174    arguments (like verbose_flag) without executing the command.
175    Displayed arguments are quoted so that the generated command
176    line is suitable for execution.  This is intended for use in
177    shell scripts to capture the driver-generated command line.  */
178 static int verbose_only_flag;
179
180 /* Flag indicating to print target specific command line options.  */
181
182 static int target_help_flag;
183
184 /* Flag indicating whether we should report subprocess execution times
185    (if this is supported by the system - see pexecute.c).  */
186
187 static int report_times;
188
189 /* Nonzero means place this string before uses of /, so that include
190    and library files can be found in an alternate location.  */
191
192 #ifdef TARGET_SYSTEM_ROOT
193 static const char *target_system_root = TARGET_SYSTEM_ROOT;
194 #else
195 static const char *target_system_root = 0;
196 #endif
197
198 /* Nonzero means pass the updated target_system_root to the compiler.  */
199
200 static int target_system_root_changed;
201
202 /* Nonzero means append this string to target_system_root.  */
203
204 static const char *target_sysroot_suffix = 0;
205
206 /* Nonzero means append this string to target_system_root for headers.  */
207
208 static const char *target_sysroot_hdrs_suffix = 0;
209
210 /* Nonzero means write "temp" files in source directory
211    and use the source file's name in them, and don't delete them.  */
212
213 static int save_temps_flag;
214
215 /* Nonzero means pass multiple source files to the compiler at one time.  */
216
217 static int combine_flag = 0;
218
219 /* Nonzero means use pipes to communicate between subprocesses.
220    Overridden by either of the above two flags.  */
221
222 static int use_pipes;
223
224 /* The compiler version.  */
225
226 static const char *compiler_version;
227
228 /* The target version specified with -V */
229
230 static const char *const spec_version = DEFAULT_TARGET_VERSION;
231
232 /* The target machine specified with -b.  */
233
234 static const char *spec_machine = DEFAULT_TARGET_MACHINE;
235
236 /* Nonzero if cross-compiling.
237    When -b is used, the value comes from the `specs' file.  */
238
239 #ifdef CROSS_COMPILE
240 static const char *cross_compile = "1";
241 #else
242 static const char *cross_compile = "0";
243 #endif
244
245 #ifdef MODIFY_TARGET_NAME
246
247 /* Information on how to alter the target name based on a command-line
248    switch.  The only case we support now is simply appending or deleting a
249    string to or from the end of the first part of the configuration name.  */
250
251 static const struct modify_target
252 {
253   const char *const sw;
254   const enum add_del {ADD, DELETE} add_del;
255   const char *const str;
256 }
257 modify_target[] = MODIFY_TARGET_NAME;
258 #endif
259
260 /* The number of errors that have occurred; the link phase will not be
261    run if this is nonzero.  */
262 static int error_count = 0;
263
264 /* Greatest exit code of sub-processes that has been encountered up to
265    now.  */
266 static int greatest_status = 1;
267
268 /* This is the obstack which we use to allocate many strings.  */
269
270 static struct obstack obstack;
271
272 /* This is the obstack to build an environment variable to pass to
273    collect2 that describes all of the relevant switches of what to
274    pass the compiler in building the list of pointers to constructors
275    and destructors.  */
276
277 static struct obstack collect_obstack;
278
279 /* Forward declaration for prototypes.  */
280 struct path_prefix;
281 struct prefix_list;
282
283 static void init_spec (void);
284 static void store_arg (const char *, int, int);
285 static char *load_specs (const char *);
286 static void read_specs (const char *, int);
287 static void set_spec (const char *, const char *);
288 static struct compiler *lookup_compiler (const char *, size_t, const char *);
289 static char *build_search_list (struct path_prefix *, const char *, int);
290 static void putenv_from_prefixes (struct path_prefix *, const char *);
291 static int access_check (const char *, int);
292 static char *find_a_file (struct path_prefix *, const char *, int, int);
293 static void add_prefix (struct path_prefix *, const char *, const char *,
294                         int, int, int);
295 static void add_sysrooted_prefix (struct path_prefix *, const char *,
296                                   const char *, int, int, int);
297 static void translate_options (int *, const char *const **);
298 static char *skip_whitespace (char *);
299 static void delete_if_ordinary (const char *);
300 static void delete_temp_files (void);
301 static void delete_failure_queue (void);
302 static void clear_failure_queue (void);
303 static int check_live_switch (int, int);
304 static const char *handle_braces (const char *);
305 static inline bool input_suffix_matches (const char *, const char *);
306 static inline bool switch_matches (const char *, const char *, int);
307 static inline void mark_matching_switches (const char *, const char *, int);
308 static inline void process_marked_switches (void);
309 static const char *process_brace_body (const char *, const char *, const char *, int, int);
310 static const struct spec_function *lookup_spec_function (const char *);
311 static const char *eval_spec_function (const char *, const char *);
312 static const char *handle_spec_function (const char *);
313 static char *save_string (const char *, int);
314 static void set_collect_gcc_options (void);
315 static void do_spec_path (struct prefix_list *, const char *, int, int, int, const char *, const char *);
316 static int do_spec_1 (const char *, int, const char *);
317 static int do_spec_2 (const char *);
318 static void do_option_spec (const char *, const char *);
319 static void do_self_spec (const char *);
320 static const char *find_file (const char *);
321 static int is_directory (const char *, const char *, int);
322 static const char *validate_switches (const char *);
323 static void validate_all_switches (void);
324 static inline void validate_switches_from_spec (const char *);
325 static void give_switch (int, int);
326 static int used_arg (const char *, int);
327 static int default_arg (const char *, int);
328 static void set_multilib_dir (void);
329 static void print_multilib_info (void);
330 static void perror_with_name (const char *);
331 static void notice (const char *, ...) ATTRIBUTE_PRINTF_1;
332 static void display_help (void);
333 static void add_preprocessor_option (const char *, int);
334 static void add_assembler_option (const char *, int);
335 static void add_linker_option (const char *, int);
336 static void process_command (int, const char **);
337 static int execute (void);
338 static void alloc_args (void);
339 static void clear_args (void);
340 static void fatal_error (int);
341 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
342 static void init_gcc_specs (struct obstack *, const char *, const char *,
343                             const char *);
344 #endif
345 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
346 static const char *convert_filename (const char *, int, int);
347 #endif
348
349 static const char *if_exists_spec_function (int, const char **);
350 static const char *if_exists_else_spec_function (int, const char **);
351 static const char *replace_outfile_spec_function (int, const char **);
352 \f
353 /* The Specs Language
354
355 Specs are strings containing lines, each of which (if not blank)
356 is made up of a program name, and arguments separated by spaces.
357 The program name must be exact and start from root, since no path
358 is searched and it is unreliable to depend on the current working directory.
359 Redirection of input or output is not supported; the subprograms must
360 accept filenames saying what files to read and write.
361
362 In addition, the specs can contain %-sequences to substitute variable text
363 or for conditional text.  Here is a table of all defined %-sequences.
364 Note that spaces are not generated automatically around the results of
365 expanding these sequences; therefore, you can concatenate them together
366 or with constant text in a single argument.
367
368  %%     substitute one % into the program name or argument.
369  %i     substitute the name of the input file being processed.
370  %b     substitute the basename of the input file being processed.
371         This is the substring up to (and not including) the last period
372         and not including the directory.
373  %B     same as %b, but include the file suffix (text after the last period).
374  %gSUFFIX
375         substitute a file name that has suffix SUFFIX and is chosen
376         once per compilation, and mark the argument a la %d.  To reduce
377         exposure to denial-of-service attacks, the file name is now
378         chosen in a way that is hard to predict even when previously
379         chosen file names are known.  For example, `%g.s ... %g.o ... %g.s'
380         might turn into `ccUVUUAU.s ccXYAXZ12.o ccUVUUAU.s'.  SUFFIX matches
381         the regexp "[.A-Za-z]*%O"; "%O" is treated exactly as if it
382         had been pre-processed.  Previously, %g was simply substituted
383         with a file name chosen once per compilation, without regard
384         to any appended suffix (which was therefore treated just like
385         ordinary text), making such attacks more likely to succeed.
386  %|SUFFIX
387         like %g, but if -pipe is in effect, expands simply to "-".
388  %mSUFFIX
389         like %g, but if -pipe is in effect, expands to nothing.  (We have both
390         %| and %m to accommodate differences between system assemblers; see
391         the AS_NEEDS_DASH_FOR_PIPED_INPUT target macro.)
392  %uSUFFIX
393         like %g, but generates a new temporary file name even if %uSUFFIX
394         was already seen.
395  %USUFFIX
396         substitutes the last file name generated with %uSUFFIX, generating a
397         new one if there is no such last file name.  In the absence of any
398         %uSUFFIX, this is just like %gSUFFIX, except they don't share
399         the same suffix "space", so `%g.s ... %U.s ... %g.s ... %U.s'
400         would involve the generation of two distinct file names, one
401         for each `%g.s' and another for each `%U.s'.  Previously, %U was
402         simply substituted with a file name chosen for the previous %u,
403         without regard to any appended suffix.
404  %jSUFFIX
405         substitutes the name of the HOST_BIT_BUCKET, if any, and if it is
406         writable, and if save-temps is off; otherwise, substitute the name
407         of a temporary file, just like %u.  This temporary file is not
408         meant for communication between processes, but rather as a junk
409         disposal mechanism.
410  %.SUFFIX
411         substitutes .SUFFIX for the suffixes of a matched switch's args when
412         it is subsequently output with %*. SUFFIX is terminated by the next
413         space or %.
414  %d     marks the argument containing or following the %d as a
415         temporary file name, so that that file will be deleted if CC exits
416         successfully.  Unlike %g, this contributes no text to the argument.
417  %w     marks the argument containing or following the %w as the
418         "output file" of this compilation.  This puts the argument
419         into the sequence of arguments that %o will substitute later.
420  %V     indicates that this compilation produces no "output file".
421  %W{...}
422         like %{...} but mark last argument supplied within
423         as a file to be deleted on failure.
424  %o     substitutes the names of all the output files, with spaces
425         automatically placed around them.  You should write spaces
426         around the %o as well or the results are undefined.
427         %o is for use in the specs for running the linker.
428         Input files whose names have no recognized suffix are not compiled
429         at all, but they are included among the output files, so they will
430         be linked.
431  %O     substitutes the suffix for object files.  Note that this is
432         handled specially when it immediately follows %g, %u, or %U
433         (with or without a suffix argument) because of the need for
434         those to form complete file names.  The handling is such that
435         %O is treated exactly as if it had already been substituted,
436         except that %g, %u, and %U do not currently support additional
437         SUFFIX characters following %O as they would following, for
438         example, `.o'.
439  %I     Substitute any of -iprefix (made from GCC_EXEC_PREFIX), -isysroot
440         (made from TARGET_SYSTEM_ROOT), and -isystem (made from COMPILER_PATH
441         and -B options) as necessary.
442  %s     current argument is the name of a library or startup file of some sort.
443         Search for that file in a standard list of directories
444         and substitute the full name found.
445  %eSTR  Print STR as an error message.  STR is terminated by a newline.
446         Use this when inconsistent options are detected.
447  %nSTR  Print STR as a notice.  STR is terminated by a newline.
448  %x{OPTION}     Accumulate an option for %X.
449  %X     Output the accumulated linker options specified by compilations.
450  %Y     Output the accumulated assembler options specified by compilations.
451  %Z     Output the accumulated preprocessor options specified by compilations.
452  %a     process ASM_SPEC as a spec.
453         This allows config.h to specify part of the spec for running as.
454  %A     process ASM_FINAL_SPEC as a spec.  A capital A is actually
455         used here.  This can be used to run a post-processor after the
456         assembler has done its job.
457  %D     Dump out a -L option for each directory in startfile_prefixes.
458         If multilib_dir is set, extra entries are generated with it affixed.
459  %l     process LINK_SPEC as a spec.
460  %L     process LIB_SPEC as a spec.
461  %G     process LIBGCC_SPEC as a spec.
462  %R     Output the concatenation of target_system_root and
463         target_sysroot_suffix.
464  %S     process STARTFILE_SPEC as a spec.  A capital S is actually used here.
465  %E     process ENDFILE_SPEC as a spec.  A capital E is actually used here.
466  %C     process CPP_SPEC as a spec.
467  %1     process CC1_SPEC as a spec.
468  %2     process CC1PLUS_SPEC as a spec.
469  %*     substitute the variable part of a matched option.  (See below.)
470         Note that each comma in the substituted string is replaced by
471         a single space.
472  %<S    remove all occurrences of -S from the command line.
473         Note - this command is position dependent.  % commands in the
474         spec string before this one will see -S, % commands in the
475         spec string after this one will not.
476  %<S*   remove all occurrences of all switches beginning with -S from the
477         command line.
478  %:function(args)
479         Call the named function FUNCTION, passing it ARGS.  ARGS is
480         first processed as a nested spec string, then split into an
481         argument vector in the usual fashion.  The function returns
482         a string which is processed as if it had appeared literally
483         as part of the current spec.
484  %{S}   substitutes the -S switch, if that switch was given to CC.
485         If that switch was not specified, this substitutes nothing.
486         Here S is a metasyntactic variable.
487  %{S*}  substitutes all the switches specified to CC whose names start
488         with -S.  This is used for -o, -I, etc; switches that take
489         arguments.  CC considers `-o foo' as being one switch whose
490         name starts with `o'.  %{o*} would substitute this text,
491         including the space; thus, two arguments would be generated.
492  %{S*&T*} likewise, but preserve order of S and T options (the order
493         of S and T in the spec is not significant).  Can be any number
494         of ampersand-separated variables; for each the wild card is
495         optional.  Useful for CPP as %{D*&U*&A*}.
496
497  %{S:X}   substitutes X, if the -S switch was given to CC.
498  %{!S:X}  substitutes X, if the -S switch was NOT given to CC.
499  %{S*:X}  substitutes X if one or more switches whose names start
500           with -S was given to CC.  Normally X is substituted only
501           once, no matter how many such switches appeared.  However,
502           if %* appears somewhere in X, then X will be substituted
503           once for each matching switch, with the %* replaced by the
504           part of that switch that matched the '*'.
505  %{.S:X}  substitutes X, if processing a file with suffix S.
506  %{!.S:X} substitutes X, if NOT processing a file with suffix S.
507
508  %{S|T:X} substitutes X if either -S or -T was given to CC.  This may be
509           combined with !, ., and * as above binding stronger than the OR.
510           If %* appears in X, all of the alternatives must be starred, and
511           only the first matching alternative is substituted.
512  %{S:X;   if S was given to CC, substitutes X;
513    T:Y;   else if T was given to CC, substitutes Y;
514     :D}   else substitutes D.  There can be as many clauses as you need.
515           This may be combined with ., !, |, and * as above.
516
517  %(Spec) processes a specification defined in a specs file as *Spec:
518  %[Spec] as above, but put __ around -D arguments
519
520 The conditional text X in a %{S:X} or similar construct may contain
521 other nested % constructs or spaces, or even newlines.  They are
522 processed as usual, as described above.  Trailing white space in X is
523 ignored.  White space may also appear anywhere on the left side of the
524 colon in these constructs, except between . or * and the corresponding
525 word.
526
527 The -O, -f, -m, and -W switches are handled specifically in these
528 constructs.  If another value of -O or the negated form of a -f, -m, or
529 -W switch is found later in the command line, the earlier switch
530 value is ignored, except with {S*} where S is just one letter; this
531 passes all matching options.
532
533 The character | at the beginning of the predicate text is used to indicate
534 that a command should be piped to the following command, but only if -pipe
535 is specified.
536
537 Note that it is built into CC which switches take arguments and which
538 do not.  You might think it would be useful to generalize this to
539 allow each compiler's spec to say which switches take arguments.  But
540 this cannot be done in a consistent fashion.  CC cannot even decide
541 which input files have been specified without knowing which switches
542 take arguments, and it must know which input files to compile in order
543 to tell which compilers to run.
544
545 CC also knows implicitly that arguments starting in `-l' are to be
546 treated as compiler output files, and passed to the linker in their
547 proper position among the other output files.  */
548 \f
549 /* Define the macros used for specs %a, %l, %L, %S, %C, %1.  */
550
551 /* config.h can define ASM_SPEC to provide extra args to the assembler
552    or extra switch-translations.  */
553 #ifndef ASM_SPEC
554 #define ASM_SPEC ""
555 #endif
556
557 /* config.h can define ASM_FINAL_SPEC to run a post processor after
558    the assembler has run.  */
559 #ifndef ASM_FINAL_SPEC
560 #define ASM_FINAL_SPEC ""
561 #endif
562
563 /* config.h can define CPP_SPEC to provide extra args to the C preprocessor
564    or extra switch-translations.  */
565 #ifndef CPP_SPEC
566 #define CPP_SPEC ""
567 #endif
568
569 /* config.h can define CC1_SPEC to provide extra args to cc1 and cc1plus
570    or extra switch-translations.  */
571 #ifndef CC1_SPEC
572 #define CC1_SPEC ""
573 #endif
574
575 /* config.h can define CC1PLUS_SPEC to provide extra args to cc1plus
576    or extra switch-translations.  */
577 #ifndef CC1PLUS_SPEC
578 #define CC1PLUS_SPEC ""
579 #endif
580
581 /* config.h can define LINK_SPEC to provide extra args to the linker
582    or extra switch-translations.  */
583 #ifndef LINK_SPEC
584 #define LINK_SPEC ""
585 #endif
586
587 /* config.h can define LIB_SPEC to override the default libraries.  */
588 #ifndef LIB_SPEC
589 #define LIB_SPEC "%{!shared:%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}}"
590 #endif
591
592 /* mudflap specs */
593 #ifndef MFWRAP_SPEC
594 /* XXX: valid only for GNU ld */
595 /* XXX: should exactly match hooks provided by libmudflap.a */
596 #define MFWRAP_SPEC " %{static: %{fmudflap|fmudflapth: \
597  --wrap=malloc --wrap=free --wrap=calloc --wrap=realloc\
598  --wrap=mmap --wrap=munmap --wrap=alloca\
599 } %{fmudflapth: --wrap=pthread_create --wrap=pthread_join --wrap=pthread_exit\
600 }} %{fmudflap|fmudflapth: --wrap=main}"
601 #endif
602 #ifndef MFLIB_SPEC
603 #define MFLIB_SPEC "%{fmudflap|fmudflapth: -export-dynamic}" 
604 #endif
605
606 /* config.h can define LIBGCC_SPEC to override how and when libgcc.a is
607    included.  */
608 #ifndef LIBGCC_SPEC
609 #if defined(REAL_LIBGCC_SPEC)
610 #define LIBGCC_SPEC REAL_LIBGCC_SPEC
611 #elif defined(LINK_LIBGCC_SPECIAL_1)
612 /* Have gcc do the search for libgcc.a.  */
613 #define LIBGCC_SPEC "libgcc.a%s"
614 #else
615 #define LIBGCC_SPEC "-lgcc"
616 #endif
617 #endif
618
619 /* config.h can define STARTFILE_SPEC to override the default crt0 files.  */
620 #ifndef STARTFILE_SPEC
621 #define STARTFILE_SPEC  \
622   "%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
623 #endif
624
625 /* config.h can define SWITCHES_NEED_SPACES to control which options
626    require spaces between the option and the argument.  */
627 #ifndef SWITCHES_NEED_SPACES
628 #define SWITCHES_NEED_SPACES ""
629 #endif
630
631 /* config.h can define ENDFILE_SPEC to override the default crtn files.  */
632 #ifndef ENDFILE_SPEC
633 #define ENDFILE_SPEC ""
634 #endif
635
636 #ifndef LINKER_NAME
637 #define LINKER_NAME "collect2"
638 #endif
639
640 /* Define ASM_DEBUG_SPEC to be a spec suitable for translating '-g'
641    to the assembler.  */
642 #ifndef ASM_DEBUG_SPEC
643 # if defined(DBX_DEBUGGING_INFO) && defined(DWARF2_DEBUGGING_INFO) \
644      && defined(HAVE_AS_GDWARF2_DEBUG_FLAG) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
645 #  define ASM_DEBUG_SPEC                                        \
646       (PREFERRED_DEBUGGING_TYPE == DBX_DEBUG                    \
647        ? "%{gdwarf-2*:--gdwarf2}%{!gdwarf-2*:%{g*:--gstabs}}"   \
648        : "%{gstabs*:--gstabs}%{!gstabs*:%{g*:--gdwarf2}}")
649 # else
650 #  if defined(DBX_DEBUGGING_INFO) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
651 #   define ASM_DEBUG_SPEC "%{g*:--gstabs}"
652 #  endif
653 #  if defined(DWARF2_DEBUGGING_INFO) && defined(HAVE_AS_GDWARF2_DEBUG_FLAG)
654 #   define ASM_DEBUG_SPEC "%{g*:--gdwarf2}"
655 #  endif
656 # endif
657 #endif
658 #ifndef ASM_DEBUG_SPEC
659 # define ASM_DEBUG_SPEC ""
660 #endif
661
662 /* Here is the spec for running the linker, after compiling all files.  */
663
664 /* This is overridable by the target in case they need to specify the
665    -lgcc and -lc order specially, yet not require them to override all
666    of LINK_COMMAND_SPEC.  */
667 #ifndef LINK_GCC_C_SEQUENCE_SPEC
668 #define LINK_GCC_C_SEQUENCE_SPEC "%G %L %G"
669 #endif
670
671 #ifndef LINK_SSP_SPEC
672 #ifdef TARGET_LIBC_PROVIDES_SSP
673 #define LINK_SSP_SPEC "%{fstack-protector:}"
674 #else
675 #define LINK_SSP_SPEC "%{fstack-protector:-lssp_nonshared -lssp }"
676 #endif
677 #endif
678
679 #ifndef LINK_PIE_SPEC
680 #ifdef HAVE_LD_PIE
681 #define LINK_PIE_SPEC "%{pie:-pie} "
682 #else
683 #define LINK_PIE_SPEC "%{pie:} "
684 #endif
685 #endif
686
687 /* -u* was put back because both BSD and SysV seem to support it.  */
688 /* %{static:} simply prevents an error message if the target machine
689    doesn't handle -static.  */
690 /* We want %{T*} after %{L*} and %D so that it can be used to specify linker
691    scripts which exist in user specified directories, or in standard
692    directories.  */
693 #ifndef LINK_COMMAND_SPEC
694 #define LINK_COMMAND_SPEC "\
695 %{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
696     %(linker) %l " LINK_PIE_SPEC "%X %{o*} %{A} %{d} %{e*} %{m} %{N} %{n} %{r}\
697     %{s} %{t} %{u*} %{x} %{z} %{Z} %{!A:%{!nostdlib:%{!nostartfiles:%S}}}\
698     %{static:} %{L*} %(mfwrap) %(link_libgcc) %o %(mflib)\
699     %{fprofile-arcs|fprofile-generate|coverage:-lgcov}\
700     %{!nostdlib:%{!nodefaultlibs:%(link_ssp)%(link_gcc_c_sequence)}}\
701     %{!A:%{!nostdlib:%{!nostartfiles:%E}}} %{T*} }}}}}}"
702 #endif
703
704 #ifndef LINK_LIBGCC_SPEC
705 /* Generate -L options for startfile prefix list.  */
706 # define LINK_LIBGCC_SPEC "%D"
707 #endif
708
709 #ifndef STARTFILE_PREFIX_SPEC
710 # define STARTFILE_PREFIX_SPEC ""
711 #endif
712
713 #ifndef SYSROOT_SPEC
714 # define SYSROOT_SPEC "--sysroot=%R"
715 #endif
716
717 #ifndef SYSROOT_SUFFIX_SPEC
718 # define SYSROOT_SUFFIX_SPEC ""
719 #endif
720
721 #ifndef SYSROOT_HEADERS_SUFFIX_SPEC
722 # define SYSROOT_HEADERS_SUFFIX_SPEC ""
723 #endif
724
725 static const char *asm_debug;
726 static const char *cpp_spec = CPP_SPEC;
727 static const char *cc1_spec = CC1_SPEC;
728 static const char *cc1plus_spec = CC1PLUS_SPEC;
729 static const char *link_gcc_c_sequence_spec = LINK_GCC_C_SEQUENCE_SPEC;
730 static const char *link_ssp_spec = LINK_SSP_SPEC;
731 static const char *asm_spec = ASM_SPEC;
732 static const char *asm_final_spec = ASM_FINAL_SPEC;
733 static const char *link_spec = LINK_SPEC;
734 static const char *lib_spec = LIB_SPEC;
735 static const char *mfwrap_spec = MFWRAP_SPEC;
736 static const char *mflib_spec = MFLIB_SPEC;
737 static const char *libgcc_spec = LIBGCC_SPEC;
738 static const char *endfile_spec = ENDFILE_SPEC;
739 static const char *startfile_spec = STARTFILE_SPEC;
740 static const char *switches_need_spaces = SWITCHES_NEED_SPACES;
741 static const char *linker_name_spec = LINKER_NAME;
742 static const char *link_command_spec = LINK_COMMAND_SPEC;
743 static const char *link_libgcc_spec = LINK_LIBGCC_SPEC;
744 static const char *startfile_prefix_spec = STARTFILE_PREFIX_SPEC;
745 static const char *sysroot_spec = SYSROOT_SPEC;
746 static const char *sysroot_suffix_spec = SYSROOT_SUFFIX_SPEC;
747 static const char *sysroot_hdrs_suffix_spec = SYSROOT_HEADERS_SUFFIX_SPEC;
748
749 /* Standard options to cpp, cc1, and as, to reduce duplication in specs.
750    There should be no need to override these in target dependent files,
751    but we need to copy them to the specs file so that newer versions
752    of the GCC driver can correctly drive older tool chains with the
753    appropriate -B options.  */
754
755 /* When cpplib handles traditional preprocessing, get rid of this, and
756    call cc1 (or cc1obj in objc/lang-specs.h) from the main specs so
757    that we default the front end language better.  */
758 static const char *trad_capable_cpp =
759 "cc1 -E %{traditional|ftraditional|traditional-cpp:-traditional-cpp}";
760
761 /* We don't wrap .d files in %W{} since a missing .d file, and
762    therefore no dependency entry, confuses make into thinking a .o
763    file that happens to exist is up-to-date.  */
764 static const char *cpp_unique_options =
765 "%{C|CC:%{!E:%eGCC does not support -C or -CC without -E}}\
766  %{!Q:-quiet} %{nostdinc*} %{C} %{CC} %{v} %{I*&F*} %{P} %I\
767  %{MD:-MD %{!o:%b.d}%{o*:%.d%*}}\
768  %{MMD:-MMD %{!o:%b.d}%{o*:%.d%*}}\
769  %{M} %{MM} %{MF*} %{MG} %{MP} %{MQ*} %{MT*}\
770  %{!E:%{!M:%{!MM:%{MD|MMD:%{o*:-MQ %*}}}}}\
771  %{remap} %{g3:-dD} %{H} %C %{D*&U*&A*} %{i*} %Z %i\
772  %{fmudflap:-D_MUDFLAP -include mf-runtime.h}\
773  %{fmudflapth:-D_MUDFLAP -D_MUDFLAPTH -include mf-runtime.h}\
774  %{E|M|MM:%W{o*}}";
775
776 /* This contains cpp options which are common with cc1_options and are passed
777    only when preprocessing only to avoid duplication.  We pass the cc1 spec
778    options to the preprocessor so that it the cc1 spec may manipulate
779    options used to set target flags.  Those special target flags settings may
780    in turn cause preprocessor symbols to be defined specially.  */
781 static const char *cpp_options =
782 "%(cpp_unique_options) %1 %{m*} %{std*&ansi&trigraphs} %{W*&pedantic*} %{w}\
783  %{f*} %{g*:%{!g0:%{!fno-working-directory:-fworking-directory}}} %{O*}\
784  %{undef} %{save-temps:-fpch-preprocess}";
785
786 /* This contains cpp options which are not passed when the preprocessor
787    output will be used by another program.  */
788 static const char *cpp_debug_options = "%{d*}";
789
790 /* NB: This is shared amongst all front-ends.  */
791 static const char *cc1_options =
792 "%{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
793  %1 %{!Q:-quiet} -dumpbase %B %{d*} %{m*} %{a*}\
794  %{c|S:%{o*:-auxbase-strip %*}%{!o*:-auxbase %b}}%{!c:%{!S:-auxbase %b}}\
795  %{g*} %{O*} %{W*&pedantic*} %{w} %{std*&ansi&trigraphs}\
796  %{v:-version} %{pg:-p} %{p} %{f*} %{undef}\
797  %{Qn:-fno-ident} %{--help:--help}\
798  %{--target-help:--target-help}\
799  %{!fsyntax-only:%{S:%W{o*}%{!o*:-o %b.s}}}\
800  %{fsyntax-only:-o %j} %{-param*}\
801  %{fmudflap|fmudflapth:-fno-builtin -fno-merge-constants}\
802  %{coverage:-fprofile-arcs -ftest-coverage}";
803
804 static const char *asm_options =
805 "%a %Y %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}";
806
807 static const char *invoke_as =
808 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
809 "%{!S:-o %|.s |\n as %(asm_options) %|.s %A }";
810 #else
811 "%{!S:-o %|.s |\n as %(asm_options) %m.s %A }";
812 #endif
813
814 /* Some compilers have limits on line lengths, and the multilib_select
815    and/or multilib_matches strings can be very long, so we build them at
816    run time.  */
817 static struct obstack multilib_obstack;
818 static const char *multilib_select;
819 static const char *multilib_matches;
820 static const char *multilib_defaults;
821 static const char *multilib_exclusions;
822
823 /* Check whether a particular argument is a default argument.  */
824
825 #ifndef MULTILIB_DEFAULTS
826 #define MULTILIB_DEFAULTS { "" }
827 #endif
828
829 static const char *const multilib_defaults_raw[] = MULTILIB_DEFAULTS;
830
831 #ifndef DRIVER_SELF_SPECS
832 #define DRIVER_SELF_SPECS ""
833 #endif
834
835 static const char *const driver_self_specs[] = { DRIVER_SELF_SPECS };
836
837 #ifndef OPTION_DEFAULT_SPECS
838 #define OPTION_DEFAULT_SPECS { "", "" }
839 #endif
840
841 struct default_spec
842 {
843   const char *name;
844   const char *spec;
845 };
846
847 static const struct default_spec
848   option_default_specs[] = { OPTION_DEFAULT_SPECS };
849
850 struct user_specs
851 {
852   struct user_specs *next;
853   const char *filename;
854 };
855
856 static struct user_specs *user_specs_head, *user_specs_tail;
857
858 #ifndef SWITCH_TAKES_ARG
859 #define SWITCH_TAKES_ARG(CHAR) DEFAULT_SWITCH_TAKES_ARG(CHAR)
860 #endif
861
862 #ifndef WORD_SWITCH_TAKES_ARG
863 #define WORD_SWITCH_TAKES_ARG(STR) DEFAULT_WORD_SWITCH_TAKES_ARG (STR)
864 #endif
865 \f
866 #ifdef HAVE_TARGET_EXECUTABLE_SUFFIX
867 /* This defines which switches stop a full compilation.  */
868 #define DEFAULT_SWITCH_CURTAILS_COMPILATION(CHAR) \
869   ((CHAR) == 'c' || (CHAR) == 'S')
870
871 #ifndef SWITCH_CURTAILS_COMPILATION
872 #define SWITCH_CURTAILS_COMPILATION(CHAR) \
873   DEFAULT_SWITCH_CURTAILS_COMPILATION(CHAR)
874 #endif
875 #endif
876
877 /* Record the mapping from file suffixes for compilation specs.  */
878
879 struct compiler
880 {
881   const char *suffix;           /* Use this compiler for input files
882                                    whose names end in this suffix.  */
883
884   const char *spec;             /* To use this compiler, run this spec.  */
885
886   const char *cpp_spec;         /* If non-NULL, substitute this spec
887                                    for `%C', rather than the usual
888                                    cpp_spec.  */
889   const int combinable;          /* If nonzero, compiler can deal with
890                                     multiple source files at once (IMA).  */
891   const int needs_preprocessing; /* If nonzero, source files need to
892                                     be run through a preprocessor.  */
893 };
894
895 /* Pointer to a vector of `struct compiler' that gives the spec for
896    compiling a file, based on its suffix.
897    A file that does not end in any of these suffixes will be passed
898    unchanged to the loader and nothing else will be done to it.
899
900    An entry containing two 0s is used to terminate the vector.
901
902    If multiple entries match a file, the last matching one is used.  */
903
904 static struct compiler *compilers;
905
906 /* Number of entries in `compilers', not counting the null terminator.  */
907
908 static int n_compilers;
909
910 /* The default list of file name suffixes and their compilation specs.  */
911
912 static const struct compiler default_compilers[] =
913 {
914   /* Add lists of suffixes of known languages here.  If those languages
915      were not present when we built the driver, we will hit these copies
916      and be given a more meaningful error than "file not used since
917      linking is not done".  */
918   {".m",  "#Objective-C", 0, 0, 0}, {".mi",  "#Objective-C", 0, 0, 0},
919   {".mm", "#Objective-C++", 0, 0, 0}, {".M", "#Objective-C++", 0, 0, 0},
920   {".mii", "#Objective-C++", 0, 0, 0},
921   {".cc", "#C++", 0, 0, 0}, {".cxx", "#C++", 0, 0, 0}, 
922   {".cpp", "#C++", 0, 0, 0}, {".cp", "#C++", 0, 0, 0}, 
923   {".c++", "#C++", 0, 0, 0}, {".C", "#C++", 0, 0, 0},
924   {".CPP", "#C++", 0, 0, 0}, {".ii", "#C++", 0, 0, 0},
925   {".ads", "#Ada", 0, 0, 0}, {".adb", "#Ada", 0, 0, 0},
926   {".f", "#Fortran", 0, 0, 0}, {".for", "#Fortran", 0, 0, 0}, 
927   {".F", "#Fortran", 0, 0, 0}, {".FOR", "#Fortran", 0, 0, 0},
928   {".FPP", "#Fortran", 0, 0, 0},
929   {".f90", "#Fortran 95", 0, 0, 0}, {".f95", "#Fortran 95", 0, 0, 0},
930   {".fpp", "#Fortran", 0, 0, 0}, {".F", "#Fortran", 0, 0, 0}, 
931   {".FOR", "#Fortran", 0, 0, 0}, {".FPP", "#Fortran", 0, 0, 0},
932   {".r", "#Ratfor", 0, 0, 0},
933   {".p", "#Pascal", 0, 0, 0}, {".pas", "#Pascal", 0, 0, 0},
934   {".java", "#Java", 0, 0, 0}, {".class", "#Java", 0, 0, 0},
935   {".zip", "#Java", 0, 0, 0}, {".jar", "#Java", 0, 0, 0},
936   /* Next come the entries for C.  */
937   {".c", "@c", 0, 1, 1},
938   {"@c",
939    /* cc1 has an integrated ISO C preprocessor.  We should invoke the
940       external preprocessor if -save-temps is given.  */
941      "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
942       %{!E:%{!M:%{!MM:\
943           %{traditional|ftraditional:\
944 %eGNU C no longer supports -traditional without -E}\
945        %{!combine:\
946           %{save-temps|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
947                 %(cpp_options) -o %{save-temps:%b.i} %{!save-temps:%g.i} \n\
948                     cc1 -fpreprocessed %{save-temps:%b.i} %{!save-temps:%g.i} \
949                         %(cc1_options)}\
950           %{!save-temps:%{!traditional-cpp:%{!no-integrated-cpp:\
951                 cc1 %(cpp_unique_options) %(cc1_options)}}}\
952           %{!fsyntax-only:%(invoke_as)}} \
953       %{combine:\
954           %{save-temps|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
955                 %(cpp_options) -o %{save-temps:%b.i} %{!save-temps:%g.i}}\
956           %{!save-temps:%{!traditional-cpp:%{!no-integrated-cpp:\
957                 cc1 %(cpp_unique_options) %(cc1_options)}}\
958                 %{!fsyntax-only:%(invoke_as)}}}}}}", 0, 1, 1},
959   {"-",
960    "%{!E:%e-E or -x required when input is from standard input}\
961     %(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)", 0, 0, 0},
962   {".h", "@c-header", 0, 0, 0},
963   {"@c-header",
964    /* cc1 has an integrated ISO C preprocessor.  We should invoke the
965       external preprocessor if -save-temps is given.  */
966      "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
967       %{!E:%{!M:%{!MM:\
968           %{save-temps|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
969                 %(cpp_options) -o %{save-temps:%b.i} %{!save-temps:%g.i} \n\
970                     cc1 -fpreprocessed %{save-temps:%b.i} %{!save-temps:%g.i} \
971                         %(cc1_options)\
972                         -o %g.s %{!o*:--output-pch=%i.gch}\
973                         %W{o*:--output-pch=%*}%V}\
974           %{!save-temps:%{!traditional-cpp:%{!no-integrated-cpp:\
975                 cc1 %(cpp_unique_options) %(cc1_options)\
976                     -o %g.s %{!o*:--output-pch=%i.gch}\
977                     %W{o*:--output-pch=%*}%V}}}}}}", 0, 0, 0},
978   {".i", "@cpp-output", 0, 1, 0},
979   {"@cpp-output",
980    "%{!M:%{!MM:%{!E:cc1 -fpreprocessed %i %(cc1_options) %{!fsyntax-only:%(invoke_as)}}}}", 0, 1, 0},
981   {".s", "@assembler", 0, 1, 0},
982   {"@assembler",
983    "%{!M:%{!MM:%{!E:%{!S:as %(asm_debug) %(asm_options) %i %A }}}}", 0, 1, 0},
984   {".S", "@assembler-with-cpp", 0, 1, 0},
985   {"@assembler-with-cpp",
986 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
987    "%(trad_capable_cpp) -lang-asm %(cpp_options)\
988       %{E|M|MM:%(cpp_debug_options)}\
989       %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
990        as %(asm_debug) %(asm_options) %|.s %A }}}}"
991 #else
992    "%(trad_capable_cpp) -lang-asm %(cpp_options)\
993       %{E|M|MM:%(cpp_debug_options)}\
994       %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
995        as %(asm_debug) %(asm_options) %m.s %A }}}}"
996 #endif
997    , 0, 1, 0},
998
999 #include "specs.h"
1000   /* Mark end of table.  */
1001   {0, 0, 0, 0, 0}
1002 };
1003
1004 /* Number of elements in default_compilers, not counting the terminator.  */
1005
1006 static const int n_default_compilers = ARRAY_SIZE (default_compilers) - 1;
1007
1008 /* A vector of options to give to the linker.
1009    These options are accumulated by %x,
1010    and substituted into the linker command with %X.  */
1011 static int n_linker_options;
1012 static char **linker_options;
1013
1014 /* A vector of options to give to the assembler.
1015    These options are accumulated by -Wa,
1016    and substituted into the assembler command with %Y.  */
1017 static int n_assembler_options;
1018 static char **assembler_options;
1019
1020 /* A vector of options to give to the preprocessor.
1021    These options are accumulated by -Wp,
1022    and substituted into the preprocessor command with %Z.  */
1023 static int n_preprocessor_options;
1024 static char **preprocessor_options;
1025 \f
1026 /* Define how to map long options into short ones.  */
1027
1028 /* This structure describes one mapping.  */
1029 struct option_map
1030 {
1031   /* The long option's name.  */
1032   const char *const name;
1033   /* The equivalent short option.  */
1034   const char *const equivalent;
1035   /* Argument info.  A string of flag chars; NULL equals no options.
1036      a => argument required.
1037      o => argument optional.
1038      j => join argument to equivalent, making one word.
1039      * => require other text after NAME as an argument.  */
1040   const char *const arg_info;
1041 };
1042
1043 /* This is the table of mappings.  Mappings are tried sequentially
1044    for each option encountered; the first one that matches, wins.  */
1045
1046 static const struct option_map option_map[] =
1047  {
1048    {"--all-warnings", "-Wall", 0},
1049    {"--ansi", "-ansi", 0},
1050    {"--assemble", "-S", 0},
1051    {"--assert", "-A", "a"},
1052    {"--classpath", "-fclasspath=", "aj"},
1053    {"--bootclasspath", "-fbootclasspath=", "aj"},
1054    {"--CLASSPATH", "-fclasspath=", "aj"},
1055    {"--combine", "-combine", 0},
1056    {"--comments", "-C", 0},
1057    {"--comments-in-macros", "-CC", 0},
1058    {"--compile", "-c", 0},
1059    {"--debug", "-g", "oj"},
1060    {"--define-macro", "-D", "aj"},
1061    {"--dependencies", "-M", 0},
1062    {"--dump", "-d", "a"},
1063    {"--dumpbase", "-dumpbase", "a"},
1064    {"--encoding", "-fencoding=", "aj"},
1065    {"--entry", "-e", 0},
1066    {"--extra-warnings", "-W", 0},
1067    {"--extdirs", "-fextdirs=", "aj"},
1068    {"--for-assembler", "-Wa", "a"},
1069    {"--for-linker", "-Xlinker", "a"},
1070    {"--force-link", "-u", "a"},
1071    {"--coverage", "-coverage", 0},
1072    {"--imacros", "-imacros", "a"},
1073    {"--include", "-include", "a"},
1074    {"--include-barrier", "-I-", 0},
1075    {"--include-directory", "-I", "aj"},
1076    {"--include-directory-after", "-idirafter", "a"},
1077    {"--include-prefix", "-iprefix", "a"},
1078    {"--include-with-prefix", "-iwithprefix", "a"},
1079    {"--include-with-prefix-before", "-iwithprefixbefore", "a"},
1080    {"--include-with-prefix-after", "-iwithprefix", "a"},
1081    {"--language", "-x", "a"},
1082    {"--library-directory", "-L", "a"},
1083    {"--machine", "-m", "aj"},
1084    {"--machine-", "-m", "*j"},
1085    {"--no-integrated-cpp", "-no-integrated-cpp", 0},
1086    {"--no-line-commands", "-P", 0},
1087    {"--no-precompiled-includes", "-noprecomp", 0},
1088    {"--no-standard-includes", "-nostdinc", 0},
1089    {"--no-standard-libraries", "-nostdlib", 0},
1090    {"--no-warnings", "-w", 0},
1091    {"--optimize", "-O", "oj"},
1092    {"--output", "-o", "a"},
1093    {"--output-class-directory", "-foutput-class-dir=", "ja"},
1094    {"--param", "--param", "a"},
1095    {"--pass-exit-codes", "-pass-exit-codes", 0},
1096    {"--pedantic", "-pedantic", 0},
1097    {"--pedantic-errors", "-pedantic-errors", 0},
1098    {"--pie", "-pie", 0},
1099    {"--pipe", "-pipe", 0},
1100    {"--prefix", "-B", "a"},
1101    {"--preprocess", "-E", 0},
1102    {"--print-search-dirs", "-print-search-dirs", 0},
1103    {"--print-file-name", "-print-file-name=", "aj"},
1104    {"--print-libgcc-file-name", "-print-libgcc-file-name", 0},
1105    {"--print-missing-file-dependencies", "-MG", 0},
1106    {"--print-multi-lib", "-print-multi-lib", 0},
1107    {"--print-multi-directory", "-print-multi-directory", 0},
1108    {"--print-multi-os-directory", "-print-multi-os-directory", 0},
1109    {"--print-prog-name", "-print-prog-name=", "aj"},
1110    {"--profile", "-p", 0},
1111    {"--profile-blocks", "-a", 0},
1112    {"--quiet", "-q", 0},
1113    {"--resource", "-fcompile-resource=", "aj"},
1114    {"--save-temps", "-save-temps", 0},
1115    {"--shared", "-shared", 0},
1116    {"--silent", "-q", 0},
1117    {"--specs", "-specs=", "aj"},
1118    {"--static", "-static", 0},
1119    {"--std", "-std=", "aj"},
1120    {"--symbolic", "-symbolic", 0},
1121    {"--time", "-time", 0},
1122    {"--trace-includes", "-H", 0},
1123    {"--traditional", "-traditional", 0},
1124    {"--traditional-cpp", "-traditional-cpp", 0},
1125    {"--trigraphs", "-trigraphs", 0},
1126    {"--undefine-macro", "-U", "aj"},
1127    {"--user-dependencies", "-MM", 0},
1128    {"--verbose", "-v", 0},
1129    {"--warn-", "-W", "*j"},
1130    {"--write-dependencies", "-MD", 0},
1131    {"--write-user-dependencies", "-MMD", 0},
1132    {"--", "-f", "*j"}
1133  };
1134 \f
1135
1136 #ifdef TARGET_OPTION_TRANSLATE_TABLE
1137 static const struct {
1138   const char *const option_found;
1139   const char *const replacements;
1140 } target_option_translations[] =
1141 {
1142   TARGET_OPTION_TRANSLATE_TABLE,
1143   { 0, 0 }
1144 };
1145 #endif
1146
1147 /* Translate the options described by *ARGCP and *ARGVP.
1148    Make a new vector and store it back in *ARGVP,
1149    and store its length in *ARGVC.  */
1150
1151 static void
1152 translate_options (int *argcp, const char *const **argvp)
1153 {
1154   int i;
1155   int argc = *argcp;
1156   const char *const *argv = *argvp;
1157   int newvsize = (argc + 2) * 2 * sizeof (const char *);
1158   const char **newv = xmalloc (newvsize);
1159   int newindex = 0;
1160
1161   i = 0;
1162   newv[newindex++] = argv[i++];
1163
1164   while (i < argc)
1165     {
1166 #ifdef TARGET_OPTION_TRANSLATE_TABLE
1167       int tott_idx;
1168
1169       for (tott_idx = 0;
1170            target_option_translations[tott_idx].option_found;
1171            tott_idx++)
1172         {
1173           if (strcmp (target_option_translations[tott_idx].option_found,
1174                       argv[i]) == 0)
1175             {
1176               int spaces = 1;
1177               const char *sp;
1178               char *np;
1179
1180               for (sp = target_option_translations[tott_idx].replacements;
1181                    *sp; sp++)
1182                 {
1183                   if (*sp == ' ')
1184                     spaces ++;
1185                 }
1186
1187               newvsize += spaces * sizeof (const char *);
1188               newv =  xrealloc (newv, newvsize);
1189
1190               sp = target_option_translations[tott_idx].replacements;
1191               np = xstrdup (sp);
1192
1193               while (1)
1194                 {
1195                   while (*np == ' ')
1196                     np++;
1197                   if (*np == 0)
1198                     break;
1199                   newv[newindex++] = np;
1200                   while (*np != ' ' && *np)
1201                     np++;
1202                   if (*np == 0)
1203                     break;
1204                   *np++ = 0;
1205                 }
1206
1207               i ++;
1208               break;
1209             }
1210         }
1211       if (target_option_translations[tott_idx].option_found)
1212         continue;
1213 #endif
1214
1215       /* Translate -- options.  */
1216       if (argv[i][0] == '-' && argv[i][1] == '-')
1217         {
1218           size_t j;
1219           /* Find a mapping that applies to this option.  */
1220           for (j = 0; j < ARRAY_SIZE (option_map); j++)
1221             {
1222               size_t optlen = strlen (option_map[j].name);
1223               size_t arglen = strlen (argv[i]);
1224               size_t complen = arglen > optlen ? optlen : arglen;
1225               const char *arginfo = option_map[j].arg_info;
1226
1227               if (arginfo == 0)
1228                 arginfo = "";
1229
1230               if (!strncmp (argv[i], option_map[j].name, complen))
1231                 {
1232                   const char *arg = 0;
1233
1234                   if (arglen < optlen)
1235                     {
1236                       size_t k;
1237                       for (k = j + 1; k < ARRAY_SIZE (option_map); k++)
1238                         if (strlen (option_map[k].name) >= arglen
1239                             && !strncmp (argv[i], option_map[k].name, arglen))
1240                           {
1241                             error ("ambiguous abbreviation %s", argv[i]);
1242                             break;
1243                           }
1244
1245                       if (k != ARRAY_SIZE (option_map))
1246                         break;
1247                     }
1248
1249                   if (arglen > optlen)
1250                     {
1251                       /* If the option has an argument, accept that.  */
1252                       if (argv[i][optlen] == '=')
1253                         arg = argv[i] + optlen + 1;
1254
1255                       /* If this mapping requires extra text at end of name,
1256                          accept that as "argument".  */
1257                       else if (strchr (arginfo, '*') != 0)
1258                         arg = argv[i] + optlen;
1259
1260                       /* Otherwise, extra text at end means mismatch.
1261                          Try other mappings.  */
1262                       else
1263                         continue;
1264                     }
1265
1266                   else if (strchr (arginfo, '*') != 0)
1267                     {
1268                       error ("incomplete '%s' option", option_map[j].name);
1269                       break;
1270                     }
1271
1272                   /* Handle arguments.  */
1273                   if (strchr (arginfo, 'a') != 0)
1274                     {
1275                       if (arg == 0)
1276                         {
1277                           if (i + 1 == argc)
1278                             {
1279                               error ("missing argument to '%s' option",
1280                                      option_map[j].name);
1281                               break;
1282                             }
1283
1284                           arg = argv[++i];
1285                         }
1286                     }
1287                   else if (strchr (arginfo, '*') != 0)
1288                     ;
1289                   else if (strchr (arginfo, 'o') == 0)
1290                     {
1291                       if (arg != 0)
1292                         error ("extraneous argument to '%s' option",
1293                                option_map[j].name);
1294                       arg = 0;
1295                     }
1296
1297                   /* Store the translation as one argv elt or as two.  */
1298                   if (arg != 0 && strchr (arginfo, 'j') != 0)
1299                     newv[newindex++] = concat (option_map[j].equivalent, arg,
1300                                                NULL);
1301                   else if (arg != 0)
1302                     {
1303                       newv[newindex++] = option_map[j].equivalent;
1304                       newv[newindex++] = arg;
1305                     }
1306                   else
1307                     newv[newindex++] = option_map[j].equivalent;
1308
1309                   break;
1310                 }
1311             }
1312           i++;
1313         }
1314
1315       /* Handle old-fashioned options--just copy them through,
1316          with their arguments.  */
1317       else if (argv[i][0] == '-')
1318         {
1319           const char *p = argv[i] + 1;
1320           int c = *p;
1321           int nskip = 1;
1322
1323           if (SWITCH_TAKES_ARG (c) > (p[1] != 0))
1324             nskip += SWITCH_TAKES_ARG (c) - (p[1] != 0);
1325           else if (WORD_SWITCH_TAKES_ARG (p))
1326             nskip += WORD_SWITCH_TAKES_ARG (p);
1327           else if ((c == 'B' || c == 'b' || c == 'x')
1328                    && p[1] == 0)
1329             nskip += 1;
1330           else if (! strcmp (p, "Xlinker"))
1331             nskip += 1;
1332           else if (! strcmp (p, "Xpreprocessor"))
1333             nskip += 1;
1334           else if (! strcmp (p, "Xassembler"))
1335             nskip += 1;
1336
1337           /* Watch out for an option at the end of the command line that
1338              is missing arguments, and avoid skipping past the end of the
1339              command line.  */
1340           if (nskip + i > argc)
1341             nskip = argc - i;
1342
1343           while (nskip > 0)
1344             {
1345               newv[newindex++] = argv[i++];
1346               nskip--;
1347             }
1348         }
1349       else
1350         /* Ordinary operands, or +e options.  */
1351         newv[newindex++] = argv[i++];
1352     }
1353
1354   newv[newindex] = 0;
1355
1356   *argvp = newv;
1357   *argcp = newindex;
1358 }
1359 \f
1360 static char *
1361 skip_whitespace (char *p)
1362 {
1363   while (1)
1364     {
1365       /* A fully-blank line is a delimiter in the SPEC file and shouldn't
1366          be considered whitespace.  */
1367       if (p[0] == '\n' && p[1] == '\n' && p[2] == '\n')
1368         return p + 1;
1369       else if (*p == '\n' || *p == ' ' || *p == '\t')
1370         p++;
1371       else if (*p == '#')
1372         {
1373           while (*p != '\n')
1374             p++;
1375           p++;
1376         }
1377       else
1378         break;
1379     }
1380
1381   return p;
1382 }
1383 /* Structures to keep track of prefixes to try when looking for files.  */
1384
1385 struct prefix_list
1386 {
1387   const char *prefix;         /* String to prepend to the path.  */
1388   struct prefix_list *next;   /* Next in linked list.  */
1389   int require_machine_suffix; /* Don't use without machine_suffix.  */
1390   /* 2 means try both machine_suffix and just_machine_suffix.  */
1391   int priority;               /* Sort key - priority within list.  */
1392   int os_multilib;            /* 1 if OS multilib scheme should be used,
1393                                  0 for GCC multilib scheme.  */
1394 };
1395
1396 struct path_prefix
1397 {
1398   struct prefix_list *plist;  /* List of prefixes to try */
1399   int max_len;                /* Max length of a prefix in PLIST */
1400   const char *name;           /* Name of this list (used in config stuff) */
1401 };
1402
1403 /* List of prefixes to try when looking for executables.  */
1404
1405 static struct path_prefix exec_prefixes = { 0, 0, "exec" };
1406
1407 /* List of prefixes to try when looking for startup (crt0) files.  */
1408
1409 static struct path_prefix startfile_prefixes = { 0, 0, "startfile" };
1410
1411 /* List of prefixes to try when looking for include files.  */
1412
1413 static struct path_prefix include_prefixes = { 0, 0, "include" };
1414
1415 /* Suffix to attach to directories searched for commands.
1416    This looks like `MACHINE/VERSION/'.  */
1417
1418 static const char *machine_suffix = 0;
1419
1420 /* Suffix to attach to directories searched for commands.
1421    This is just `MACHINE/'.  */
1422
1423 static const char *just_machine_suffix = 0;
1424
1425 /* Adjusted value of GCC_EXEC_PREFIX envvar.  */
1426
1427 static const char *gcc_exec_prefix;
1428
1429 /* Adjusted value of standard_libexec_prefix.  */
1430
1431 static const char *gcc_libexec_prefix;
1432
1433 /* Default prefixes to attach to command names.  */
1434
1435 #ifndef STANDARD_STARTFILE_PREFIX_1
1436 #define STANDARD_STARTFILE_PREFIX_1 "/lib/"
1437 #endif
1438 #ifndef STANDARD_STARTFILE_PREFIX_2
1439 #define STANDARD_STARTFILE_PREFIX_2 "/usr/lib/"
1440 #endif
1441  
1442 #ifdef CROSS_COMPILE  /* Don't use these prefixes for a cross compiler.  */
1443 #undef MD_EXEC_PREFIX
1444 #undef MD_STARTFILE_PREFIX
1445 #undef MD_STARTFILE_PREFIX_1
1446 #endif
1447
1448 /* If no prefixes defined, use the null string, which will disable them.  */
1449 #ifndef MD_EXEC_PREFIX
1450 #define MD_EXEC_PREFIX ""
1451 #endif
1452 #ifndef MD_STARTFILE_PREFIX
1453 #define MD_STARTFILE_PREFIX ""
1454 #endif
1455 #ifndef MD_STARTFILE_PREFIX_1
1456 #define MD_STARTFILE_PREFIX_1 ""
1457 #endif
1458
1459 static const char *const standard_exec_prefix = STANDARD_EXEC_PREFIX;
1460 static const char *const standard_exec_prefix_1 = "/usr/libexec/gcc/";
1461 static const char *const standard_exec_prefix_2 = "/usr/lib/gcc/";
1462 static const char *md_exec_prefix = MD_EXEC_PREFIX;
1463
1464 static const char *md_startfile_prefix = MD_STARTFILE_PREFIX;
1465 static const char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
1466 static const char *const standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
1467 static const char *const standard_startfile_prefix_1
1468   = STANDARD_STARTFILE_PREFIX_1;
1469 static const char *const standard_startfile_prefix_2
1470   = STANDARD_STARTFILE_PREFIX_2;
1471
1472 static const char *const tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
1473 static const char *tooldir_prefix;
1474
1475 static const char *const standard_bindir_prefix = STANDARD_BINDIR_PREFIX;
1476
1477 static const char *standard_libexec_prefix = STANDARD_LIBEXEC_PREFIX;
1478
1479 /* Subdirectory to use for locating libraries.  Set by
1480    set_multilib_dir based on the compilation options.  */
1481
1482 static const char *multilib_dir;
1483
1484 /* Subdirectory to use for locating libraries in OS conventions.  Set by
1485    set_multilib_dir based on the compilation options.  */
1486
1487 static const char *multilib_os_dir;
1488 \f
1489 /* Structure to keep track of the specs that have been defined so far.
1490    These are accessed using %(specname) or %[specname] in a compiler
1491    or link spec.  */
1492
1493 struct spec_list
1494 {
1495                                 /* The following 2 fields must be first */
1496                                 /* to allow EXTRA_SPECS to be initialized */
1497   const char *name;             /* name of the spec.  */
1498   const char *ptr;              /* available ptr if no static pointer */
1499
1500                                 /* The following fields are not initialized */
1501                                 /* by EXTRA_SPECS */
1502   const char **ptr_spec;        /* pointer to the spec itself.  */
1503   struct spec_list *next;       /* Next spec in linked list.  */
1504   int name_len;                 /* length of the name */
1505   int alloc_p;                  /* whether string was allocated */
1506 };
1507
1508 #define INIT_STATIC_SPEC(NAME,PTR) \
1509 { NAME, NULL, PTR, (struct spec_list *) 0, sizeof (NAME) - 1, 0 }
1510
1511 /* List of statically defined specs.  */
1512 static struct spec_list static_specs[] =
1513 {
1514   INIT_STATIC_SPEC ("asm",                      &asm_spec),
1515   INIT_STATIC_SPEC ("asm_debug",                &asm_debug),
1516   INIT_STATIC_SPEC ("asm_final",                &asm_final_spec),
1517   INIT_STATIC_SPEC ("asm_options",              &asm_options),
1518   INIT_STATIC_SPEC ("invoke_as",                &invoke_as),
1519   INIT_STATIC_SPEC ("cpp",                      &cpp_spec),
1520   INIT_STATIC_SPEC ("cpp_options",              &cpp_options),
1521   INIT_STATIC_SPEC ("cpp_debug_options",        &cpp_debug_options),
1522   INIT_STATIC_SPEC ("cpp_unique_options",       &cpp_unique_options),
1523   INIT_STATIC_SPEC ("trad_capable_cpp",         &trad_capable_cpp),
1524   INIT_STATIC_SPEC ("cc1",                      &cc1_spec),
1525   INIT_STATIC_SPEC ("cc1_options",              &cc1_options),
1526   INIT_STATIC_SPEC ("cc1plus",                  &cc1plus_spec),
1527   INIT_STATIC_SPEC ("link_gcc_c_sequence",      &link_gcc_c_sequence_spec),
1528   INIT_STATIC_SPEC ("link_ssp",                 &link_ssp_spec),
1529   INIT_STATIC_SPEC ("endfile",                  &endfile_spec),
1530   INIT_STATIC_SPEC ("link",                     &link_spec),
1531   INIT_STATIC_SPEC ("lib",                      &lib_spec),
1532   INIT_STATIC_SPEC ("mfwrap",                   &mfwrap_spec),
1533   INIT_STATIC_SPEC ("mflib",                    &mflib_spec),
1534   INIT_STATIC_SPEC ("libgcc",                   &libgcc_spec),
1535   INIT_STATIC_SPEC ("startfile",                &startfile_spec),
1536   INIT_STATIC_SPEC ("switches_need_spaces",     &switches_need_spaces),
1537   INIT_STATIC_SPEC ("cross_compile",            &cross_compile),
1538   INIT_STATIC_SPEC ("version",                  &compiler_version),
1539   INIT_STATIC_SPEC ("multilib",                 &multilib_select),
1540   INIT_STATIC_SPEC ("multilib_defaults",        &multilib_defaults),
1541   INIT_STATIC_SPEC ("multilib_extra",           &multilib_extra),
1542   INIT_STATIC_SPEC ("multilib_matches",         &multilib_matches),
1543   INIT_STATIC_SPEC ("multilib_exclusions",      &multilib_exclusions),
1544   INIT_STATIC_SPEC ("multilib_options",         &multilib_options),
1545   INIT_STATIC_SPEC ("linker",                   &linker_name_spec),
1546   INIT_STATIC_SPEC ("link_libgcc",              &link_libgcc_spec),
1547   INIT_STATIC_SPEC ("md_exec_prefix",           &md_exec_prefix),
1548   INIT_STATIC_SPEC ("md_startfile_prefix",      &md_startfile_prefix),
1549   INIT_STATIC_SPEC ("md_startfile_prefix_1",    &md_startfile_prefix_1),
1550   INIT_STATIC_SPEC ("startfile_prefix_spec",    &startfile_prefix_spec),
1551   INIT_STATIC_SPEC ("sysroot_spec",             &sysroot_spec),
1552   INIT_STATIC_SPEC ("sysroot_suffix_spec",      &sysroot_suffix_spec),
1553   INIT_STATIC_SPEC ("sysroot_hdrs_suffix_spec", &sysroot_hdrs_suffix_spec),
1554 };
1555
1556 #ifdef EXTRA_SPECS              /* additional specs needed */
1557 /* Structure to keep track of just the first two args of a spec_list.
1558    That is all that the EXTRA_SPECS macro gives us.  */
1559 struct spec_list_1
1560 {
1561   const char *const name;
1562   const char *const ptr;
1563 };
1564
1565 static const struct spec_list_1 extra_specs_1[] = { EXTRA_SPECS };
1566 static struct spec_list *extra_specs = (struct spec_list *) 0;
1567 #endif
1568
1569 /* List of dynamically allocates specs that have been defined so far.  */
1570
1571 static struct spec_list *specs = (struct spec_list *) 0;
1572 \f
1573 /* List of static spec functions.  */
1574
1575 static const struct spec_function static_spec_functions[] =
1576 {
1577   { "if-exists",                if_exists_spec_function },
1578   { "if-exists-else",           if_exists_else_spec_function },
1579   { "replace-outfile",          replace_outfile_spec_function },
1580   { 0, 0 }
1581 };
1582
1583 static int processing_spec_function;
1584 \f
1585 /* Add appropriate libgcc specs to OBSTACK, taking into account
1586    various permutations of -shared-libgcc, -shared, and such.  */
1587
1588 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1589
1590 #ifndef USE_LD_AS_NEEDED
1591 #define USE_LD_AS_NEEDED 0
1592 #endif
1593
1594 static void
1595 init_gcc_specs (struct obstack *obstack, const char *shared_name,
1596                 const char *static_name, const char *eh_name)
1597 {
1598   char *buf;
1599
1600   buf = concat ("%{static|static-libgcc:", static_name, " ", eh_name,
1601                 "}%{!static:%{!static-libgcc:",
1602 #if USE_LD_AS_NEEDED
1603                 "%{!shared-libgcc:", static_name,
1604                 " --as-needed ", shared_name, " --no-as-needed}"
1605                 "%{shared-libgcc:", shared_name, "%{!shared: ", static_name,
1606                 "}",
1607 #else
1608                 "%{!shared:%{!shared-libgcc:", static_name, " ",
1609                 eh_name, "}%{shared-libgcc:", shared_name, " ",
1610                 static_name, "}}%{shared:",
1611 #ifdef LINK_EH_SPEC
1612                 "%{shared-libgcc:", shared_name,
1613                 "}%{!shared-libgcc:", static_name, "}",
1614 #else
1615                 shared_name,
1616 #endif
1617 #endif
1618                 "}}}", NULL);
1619
1620   obstack_grow (obstack, buf, strlen (buf));
1621   free (buf);
1622 }
1623 #endif /* ENABLE_SHARED_LIBGCC */
1624
1625 /* Initialize the specs lookup routines.  */
1626
1627 static void
1628 init_spec (void)
1629 {
1630   struct spec_list *next = (struct spec_list *) 0;
1631   struct spec_list *sl   = (struct spec_list *) 0;
1632   int i;
1633
1634   if (specs)
1635     return;                     /* Already initialized.  */
1636
1637   if (verbose_flag)
1638     notice ("Using built-in specs.\n");
1639
1640 #ifdef EXTRA_SPECS
1641   extra_specs = xcalloc (sizeof (struct spec_list),
1642                          ARRAY_SIZE (extra_specs_1));
1643
1644   for (i = ARRAY_SIZE (extra_specs_1) - 1; i >= 0; i--)
1645     {
1646       sl = &extra_specs[i];
1647       sl->name = extra_specs_1[i].name;
1648       sl->ptr = extra_specs_1[i].ptr;
1649       sl->next = next;
1650       sl->name_len = strlen (sl->name);
1651       sl->ptr_spec = &sl->ptr;
1652       next = sl;
1653     }
1654 #endif
1655
1656   /* Initialize here, not in definition.  The IRIX 6 O32 cc sometimes chokes
1657      on ?: in file-scope variable initializations.  */
1658   asm_debug = ASM_DEBUG_SPEC;
1659
1660   for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1661     {
1662       sl = &static_specs[i];
1663       sl->next = next;
1664       next = sl;
1665     }
1666
1667 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1668   /* ??? If neither -shared-libgcc nor --static-libgcc was
1669      seen, then we should be making an educated guess.  Some proposed
1670      heuristics for ELF include:
1671
1672         (1) If "-Wl,--export-dynamic", then it's a fair bet that the
1673             program will be doing dynamic loading, which will likely
1674             need the shared libgcc.
1675
1676         (2) If "-ldl", then it's also a fair bet that we're doing
1677             dynamic loading.
1678
1679         (3) For each ET_DYN we're linking against (either through -lfoo
1680             or /some/path/foo.so), check to see whether it or one of
1681             its dependencies depends on a shared libgcc.
1682
1683         (4) If "-shared"
1684
1685             If the runtime is fixed to look for program headers instead
1686             of calling __register_frame_info at all, for each object,
1687             use the shared libgcc if any EH symbol referenced.
1688
1689             If crtstuff is fixed to not invoke __register_frame_info
1690             automatically, for each object, use the shared libgcc if
1691             any non-empty unwind section found.
1692
1693      Doing any of this probably requires invoking an external program to
1694      do the actual object file scanning.  */
1695   {
1696     const char *p = libgcc_spec;
1697     int in_sep = 1;
1698
1699     /* Transform the extant libgcc_spec into one that uses the shared libgcc
1700        when given the proper command line arguments.  */
1701     while (*p)
1702       {
1703         if (in_sep && *p == '-' && strncmp (p, "-lgcc", 5) == 0)
1704           {
1705             init_gcc_specs (&obstack,
1706                             "-lgcc_s"
1707 #ifdef USE_LIBUNWIND_EXCEPTIONS
1708                             " -lunwind"
1709 #endif
1710                             ,
1711                             "-lgcc",
1712                             "-lgcc_eh"
1713 #ifdef USE_LIBUNWIND_EXCEPTIONS
1714 # ifdef HAVE_LD_STATIC_DYNAMIC
1715                             " %{!static:-Bstatic} -lunwind %{!static:-Bdynamic}"
1716 # else
1717                             " -lunwind"
1718 # endif
1719 #endif
1720                             );
1721
1722             p += 5;
1723             in_sep = 0;
1724           }
1725         else if (in_sep && *p == 'l' && strncmp (p, "libgcc.a%s", 10) == 0)
1726           {
1727             /* Ug.  We don't know shared library extensions.  Hope that
1728                systems that use this form don't do shared libraries.  */
1729             init_gcc_specs (&obstack,
1730                             "-lgcc_s",
1731                             "libgcc.a%s",
1732                             "libgcc_eh.a%s"
1733 #ifdef USE_LIBUNWIND_EXCEPTIONS
1734                             " -lunwind"
1735 #endif
1736                             );
1737             p += 10;
1738             in_sep = 0;
1739           }
1740         else
1741           {
1742             obstack_1grow (&obstack, *p);
1743             in_sep = (*p == ' ');
1744             p += 1;
1745           }
1746       }
1747
1748     obstack_1grow (&obstack, '\0');
1749     libgcc_spec = XOBFINISH (&obstack, const char *);
1750   }
1751 #endif
1752 #ifdef USE_AS_TRADITIONAL_FORMAT
1753   /* Prepend "--traditional-format" to whatever asm_spec we had before.  */
1754   {
1755     static const char tf[] = "--traditional-format ";
1756     obstack_grow (&obstack, tf, sizeof(tf) - 1);
1757     obstack_grow0 (&obstack, asm_spec, strlen (asm_spec));
1758     asm_spec = XOBFINISH (&obstack, const char *);
1759   }
1760 #endif
1761 #ifdef LINK_EH_SPEC
1762   /* Prepend LINK_EH_SPEC to whatever link_spec we had before.  */
1763   obstack_grow (&obstack, LINK_EH_SPEC, sizeof(LINK_EH_SPEC) - 1);
1764   obstack_grow0 (&obstack, link_spec, strlen (link_spec));
1765   link_spec = XOBFINISH (&obstack, const char *);
1766 #endif
1767
1768   specs = sl;
1769 }
1770 \f
1771 /* Change the value of spec NAME to SPEC.  If SPEC is empty, then the spec is
1772    removed; If the spec starts with a + then SPEC is added to the end of the
1773    current spec.  */
1774
1775 static void
1776 set_spec (const char *name, const char *spec)
1777 {
1778   struct spec_list *sl;
1779   const char *old_spec;
1780   int name_len = strlen (name);
1781   int i;
1782
1783   /* If this is the first call, initialize the statically allocated specs.  */
1784   if (!specs)
1785     {
1786       struct spec_list *next = (struct spec_list *) 0;
1787       for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1788         {
1789           sl = &static_specs[i];
1790           sl->next = next;
1791           next = sl;
1792         }
1793       specs = sl;
1794     }
1795
1796   /* See if the spec already exists.  */
1797   for (sl = specs; sl; sl = sl->next)
1798     if (name_len == sl->name_len && !strcmp (sl->name, name))
1799       break;
1800
1801   if (!sl)
1802     {
1803       /* Not found - make it.  */
1804       sl = xmalloc (sizeof (struct spec_list));
1805       sl->name = xstrdup (name);
1806       sl->name_len = name_len;
1807       sl->ptr_spec = &sl->ptr;
1808       sl->alloc_p = 0;
1809       *(sl->ptr_spec) = "";
1810       sl->next = specs;
1811       specs = sl;
1812     }
1813
1814   old_spec = *(sl->ptr_spec);
1815   *(sl->ptr_spec) = ((spec[0] == '+' && ISSPACE ((unsigned char)spec[1]))
1816                      ? concat (old_spec, spec + 1, NULL)
1817                      : xstrdup (spec));
1818
1819 #ifdef DEBUG_SPECS
1820   if (verbose_flag)
1821     notice ("Setting spec %s to '%s'\n\n", name, *(sl->ptr_spec));
1822 #endif
1823
1824   /* Free the old spec.  */
1825   if (old_spec && sl->alloc_p)
1826     free ((void *) old_spec);
1827
1828   sl->alloc_p = 1;
1829 }
1830 \f
1831 /* Accumulate a command (program name and args), and run it.  */
1832
1833 /* Vector of pointers to arguments in the current line of specifications.  */
1834
1835 static const char **argbuf;
1836
1837 /* Number of elements allocated in argbuf.  */
1838
1839 static int argbuf_length;
1840
1841 /* Number of elements in argbuf currently in use (containing args).  */
1842
1843 static int argbuf_index;
1844
1845 /* Position in the argbuf array containing the name of the output file
1846    (the value associated with the "-o" flag).  */
1847
1848 static int have_o_argbuf_index = 0;
1849
1850 /* This is the list of suffixes and codes (%g/%u/%U/%j) and the associated
1851    temp file.  If the HOST_BIT_BUCKET is used for %j, no entry is made for
1852    it here.  */
1853
1854 static struct temp_name {
1855   const char *suffix;   /* suffix associated with the code.  */
1856   int length;           /* strlen (suffix).  */
1857   int unique;           /* Indicates whether %g or %u/%U was used.  */
1858   const char *filename; /* associated filename.  */
1859   int filename_length;  /* strlen (filename).  */
1860   struct temp_name *next;
1861 } *temp_names;
1862
1863 /* Number of commands executed so far.  */
1864
1865 static int execution_count;
1866
1867 /* Number of commands that exited with a signal.  */
1868
1869 static int signal_count;
1870
1871 /* Name with which this program was invoked.  */
1872
1873 static const char *programname;
1874 \f
1875 /* Allocate the argument vector.  */
1876
1877 static void
1878 alloc_args (void)
1879 {
1880   argbuf_length = 10;
1881   argbuf = xmalloc (argbuf_length * sizeof (const char *));
1882 }
1883
1884 /* Clear out the vector of arguments (after a command is executed).  */
1885
1886 static void
1887 clear_args (void)
1888 {
1889   argbuf_index = 0;
1890 }
1891
1892 /* Add one argument to the vector at the end.
1893    This is done when a space is seen or at the end of the line.
1894    If DELETE_ALWAYS is nonzero, the arg is a filename
1895     and the file should be deleted eventually.
1896    If DELETE_FAILURE is nonzero, the arg is a filename
1897     and the file should be deleted if this compilation fails.  */
1898
1899 static void
1900 store_arg (const char *arg, int delete_always, int delete_failure)
1901 {
1902   if (argbuf_index + 1 == argbuf_length)
1903     argbuf = xrealloc (argbuf, (argbuf_length *= 2) * sizeof (const char *));
1904
1905   argbuf[argbuf_index++] = arg;
1906   argbuf[argbuf_index] = 0;
1907
1908   if (strcmp (arg, "-o") == 0)
1909     have_o_argbuf_index = argbuf_index;
1910   if (delete_always || delete_failure)
1911     record_temp_file (arg, delete_always, delete_failure);
1912 }
1913 \f
1914 /* Load specs from a file name named FILENAME, replacing occurrences of
1915    various different types of line-endings, \r\n, \n\r and just \r, with
1916    a single \n.  */
1917
1918 static char *
1919 load_specs (const char *filename)
1920 {
1921   int desc;
1922   int readlen;
1923   struct stat statbuf;
1924   char *buffer;
1925   char *buffer_p;
1926   char *specs;
1927   char *specs_p;
1928
1929   if (verbose_flag)
1930     notice ("Reading specs from %s\n", filename);
1931
1932   /* Open and stat the file.  */
1933   desc = open (filename, O_RDONLY, 0);
1934   if (desc < 0)
1935     pfatal_with_name (filename);
1936   if (stat (filename, &statbuf) < 0)
1937     pfatal_with_name (filename);
1938
1939   /* Read contents of file into BUFFER.  */
1940   buffer = xmalloc ((unsigned) statbuf.st_size + 1);
1941   readlen = read (desc, buffer, (unsigned) statbuf.st_size);
1942   if (readlen < 0)
1943     pfatal_with_name (filename);
1944   buffer[readlen] = 0;
1945   close (desc);
1946
1947   specs = xmalloc (readlen + 1);
1948   specs_p = specs;
1949   for (buffer_p = buffer; buffer_p && *buffer_p; buffer_p++)
1950     {
1951       int skip = 0;
1952       char c = *buffer_p;
1953       if (c == '\r')
1954         {
1955           if (buffer_p > buffer && *(buffer_p - 1) == '\n')     /* \n\r */
1956             skip = 1;
1957           else if (*(buffer_p + 1) == '\n')                     /* \r\n */
1958             skip = 1;
1959           else                                                  /* \r */
1960             c = '\n';
1961         }
1962       if (! skip)
1963         *specs_p++ = c;
1964     }
1965   *specs_p = '\0';
1966
1967   free (buffer);
1968   return (specs);
1969 }
1970
1971 /* Read compilation specs from a file named FILENAME,
1972    replacing the default ones.
1973
1974    A suffix which starts with `*' is a definition for
1975    one of the machine-specific sub-specs.  The "suffix" should be
1976    *asm, *cc1, *cpp, *link, *startfile, etc.
1977    The corresponding spec is stored in asm_spec, etc.,
1978    rather than in the `compilers' vector.
1979
1980    Anything invalid in the file is a fatal error.  */
1981
1982 static void
1983 read_specs (const char *filename, int main_p)
1984 {
1985   char *buffer;
1986   char *p;
1987
1988   buffer = load_specs (filename);
1989
1990   /* Scan BUFFER for specs, putting them in the vector.  */
1991   p = buffer;
1992   while (1)
1993     {
1994       char *suffix;
1995       char *spec;
1996       char *in, *out, *p1, *p2, *p3;
1997
1998       /* Advance P in BUFFER to the next nonblank nocomment line.  */
1999       p = skip_whitespace (p);
2000       if (*p == 0)
2001         break;
2002
2003       /* Is this a special command that starts with '%'? */
2004       /* Don't allow this for the main specs file, since it would
2005          encourage people to overwrite it.  */
2006       if (*p == '%' && !main_p)
2007         {
2008           p1 = p;
2009           while (*p && *p != '\n')
2010             p++;
2011
2012           /* Skip '\n'.  */
2013           p++;
2014
2015           if (!strncmp (p1, "%include", sizeof ("%include") - 1)
2016               && (p1[sizeof "%include" - 1] == ' '
2017                   || p1[sizeof "%include" - 1] == '\t'))
2018             {
2019               char *new_filename;
2020
2021               p1 += sizeof ("%include");
2022               while (*p1 == ' ' || *p1 == '\t')
2023                 p1++;
2024
2025               if (*p1++ != '<' || p[-2] != '>')
2026                 fatal ("specs %%include syntax malformed after %ld characters",
2027                        (long) (p1 - buffer + 1));
2028
2029               p[-2] = '\0';
2030               new_filename = find_a_file (&startfile_prefixes, p1, R_OK, 0);
2031               read_specs (new_filename ? new_filename : p1, FALSE);
2032               continue;
2033             }
2034           else if (!strncmp (p1, "%include_noerr", sizeof "%include_noerr" - 1)
2035                    && (p1[sizeof "%include_noerr" - 1] == ' '
2036                        || p1[sizeof "%include_noerr" - 1] == '\t'))
2037             {
2038               char *new_filename;
2039
2040               p1 += sizeof "%include_noerr";
2041               while (*p1 == ' ' || *p1 == '\t')
2042                 p1++;
2043
2044               if (*p1++ != '<' || p[-2] != '>')
2045                 fatal ("specs %%include syntax malformed after %ld characters",
2046                        (long) (p1 - buffer + 1));
2047
2048               p[-2] = '\0';
2049               new_filename = find_a_file (&startfile_prefixes, p1, R_OK, 0);
2050               if (new_filename)
2051                 read_specs (new_filename, FALSE);
2052               else if (verbose_flag)
2053                 notice ("could not find specs file %s\n", p1);
2054               continue;
2055             }
2056           else if (!strncmp (p1, "%rename", sizeof "%rename" - 1)
2057                    && (p1[sizeof "%rename" - 1] == ' '
2058                        || p1[sizeof "%rename" - 1] == '\t'))
2059             {
2060               int name_len;
2061               struct spec_list *sl;
2062               struct spec_list *newsl;
2063
2064               /* Get original name.  */
2065               p1 += sizeof "%rename";
2066               while (*p1 == ' ' || *p1 == '\t')
2067                 p1++;
2068
2069               if (! ISALPHA ((unsigned char) *p1))
2070                 fatal ("specs %%rename syntax malformed after %ld characters",
2071                        (long) (p1 - buffer));
2072
2073               p2 = p1;
2074               while (*p2 && !ISSPACE ((unsigned char) *p2))
2075                 p2++;
2076
2077               if (*p2 != ' ' && *p2 != '\t')
2078                 fatal ("specs %%rename syntax malformed after %ld characters",
2079                        (long) (p2 - buffer));
2080
2081               name_len = p2 - p1;
2082               *p2++ = '\0';
2083               while (*p2 == ' ' || *p2 == '\t')
2084                 p2++;
2085
2086               if (! ISALPHA ((unsigned char) *p2))
2087                 fatal ("specs %%rename syntax malformed after %ld characters",
2088                        (long) (p2 - buffer));
2089
2090               /* Get new spec name.  */
2091               p3 = p2;
2092               while (*p3 && !ISSPACE ((unsigned char) *p3))
2093                 p3++;
2094
2095               if (p3 != p - 1)
2096                 fatal ("specs %%rename syntax malformed after %ld characters",
2097                        (long) (p3 - buffer));
2098               *p3 = '\0';
2099
2100               for (sl = specs; sl; sl = sl->next)
2101                 if (name_len == sl->name_len && !strcmp (sl->name, p1))
2102                   break;
2103
2104               if (!sl)
2105                 fatal ("specs %s spec was not found to be renamed", p1);
2106
2107               if (strcmp (p1, p2) == 0)
2108                 continue;
2109
2110               for (newsl = specs; newsl; newsl = newsl->next)
2111                 if (strcmp (newsl->name, p2) == 0)
2112                   fatal ("%s: attempt to rename spec '%s' to already defined spec '%s'",
2113                     filename, p1, p2);
2114
2115               if (verbose_flag)
2116                 {
2117                   notice ("rename spec %s to %s\n", p1, p2);
2118 #ifdef DEBUG_SPECS
2119                   notice ("spec is '%s'\n\n", *(sl->ptr_spec));
2120 #endif
2121                 }
2122
2123               set_spec (p2, *(sl->ptr_spec));
2124               if (sl->alloc_p)
2125                 free ((void *) *(sl->ptr_spec));
2126
2127               *(sl->ptr_spec) = "";
2128               sl->alloc_p = 0;
2129               continue;
2130             }
2131           else
2132             fatal ("specs unknown %% command after %ld characters",
2133                    (long) (p1 - buffer));
2134         }
2135
2136       /* Find the colon that should end the suffix.  */
2137       p1 = p;
2138       while (*p1 && *p1 != ':' && *p1 != '\n')
2139         p1++;
2140
2141       /* The colon shouldn't be missing.  */
2142       if (*p1 != ':')
2143         fatal ("specs file malformed after %ld characters",
2144                (long) (p1 - buffer));
2145
2146       /* Skip back over trailing whitespace.  */
2147       p2 = p1;
2148       while (p2 > buffer && (p2[-1] == ' ' || p2[-1] == '\t'))
2149         p2--;
2150
2151       /* Copy the suffix to a string.  */
2152       suffix = save_string (p, p2 - p);
2153       /* Find the next line.  */
2154       p = skip_whitespace (p1 + 1);
2155       if (p[1] == 0)
2156         fatal ("specs file malformed after %ld characters",
2157                (long) (p - buffer));
2158
2159       p1 = p;
2160       /* Find next blank line or end of string.  */
2161       while (*p1 && !(*p1 == '\n' && (p1[1] == '\n' || p1[1] == '\0')))
2162         p1++;
2163
2164       /* Specs end at the blank line and do not include the newline.  */
2165       spec = save_string (p, p1 - p);
2166       p = p1;
2167
2168       /* Delete backslash-newline sequences from the spec.  */
2169       in = spec;
2170       out = spec;
2171       while (*in != 0)
2172         {
2173           if (in[0] == '\\' && in[1] == '\n')
2174             in += 2;
2175           else if (in[0] == '#')
2176             while (*in && *in != '\n')
2177               in++;
2178
2179           else
2180             *out++ = *in++;
2181         }
2182       *out = 0;
2183
2184       if (suffix[0] == '*')
2185         {
2186           if (! strcmp (suffix, "*link_command"))
2187             link_command_spec = spec;
2188           else
2189             set_spec (suffix + 1, spec);
2190         }
2191       else
2192         {
2193           /* Add this pair to the vector.  */
2194           compilers
2195             = xrealloc (compilers,
2196                         (n_compilers + 2) * sizeof (struct compiler));
2197
2198           compilers[n_compilers].suffix = suffix;
2199           compilers[n_compilers].spec = spec;
2200           n_compilers++;
2201           memset (&compilers[n_compilers], 0, sizeof compilers[n_compilers]);
2202         }
2203
2204       if (*suffix == 0)
2205         link_command_spec = spec;
2206     }
2207
2208   if (link_command_spec == 0)
2209     fatal ("spec file has no spec for linking");
2210 }
2211 \f
2212 /* Record the names of temporary files we tell compilers to write,
2213    and delete them at the end of the run.  */
2214
2215 /* This is the common prefix we use to make temp file names.
2216    It is chosen once for each run of this program.
2217    It is substituted into a spec by %g or %j.
2218    Thus, all temp file names contain this prefix.
2219    In practice, all temp file names start with this prefix.
2220
2221    This prefix comes from the envvar TMPDIR if it is defined;
2222    otherwise, from the P_tmpdir macro if that is defined;
2223    otherwise, in /usr/tmp or /tmp;
2224    or finally the current directory if all else fails.  */
2225
2226 static const char *temp_filename;
2227
2228 /* Length of the prefix.  */
2229
2230 static int temp_filename_length;
2231
2232 /* Define the list of temporary files to delete.  */
2233
2234 struct temp_file
2235 {
2236   const char *name;
2237   struct temp_file *next;
2238 };
2239
2240 /* Queue of files to delete on success or failure of compilation.  */
2241 static struct temp_file *always_delete_queue;
2242 /* Queue of files to delete on failure of compilation.  */
2243 static struct temp_file *failure_delete_queue;
2244
2245 /* Record FILENAME as a file to be deleted automatically.
2246    ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
2247    otherwise delete it in any case.
2248    FAIL_DELETE nonzero means delete it if a compilation step fails;
2249    otherwise delete it in any case.  */
2250
2251 void
2252 record_temp_file (const char *filename, int always_delete, int fail_delete)
2253 {
2254   char *const name = xstrdup (filename);
2255
2256   if (always_delete)
2257     {
2258       struct temp_file *temp;
2259       for (temp = always_delete_queue; temp; temp = temp->next)
2260         if (! strcmp (name, temp->name))
2261           goto already1;
2262
2263       temp = xmalloc (sizeof (struct temp_file));
2264       temp->next = always_delete_queue;
2265       temp->name = name;
2266       always_delete_queue = temp;
2267
2268     already1:;
2269     }
2270
2271   if (fail_delete)
2272     {
2273       struct temp_file *temp;
2274       for (temp = failure_delete_queue; temp; temp = temp->next)
2275         if (! strcmp (name, temp->name))
2276           goto already2;
2277
2278       temp = xmalloc (sizeof (struct temp_file));
2279       temp->next = failure_delete_queue;
2280       temp->name = name;
2281       failure_delete_queue = temp;
2282
2283     already2:;
2284     }
2285 }
2286
2287 /* Delete all the temporary files whose names we previously recorded.  */
2288
2289 #ifndef DELETE_IF_ORDINARY
2290 #define DELETE_IF_ORDINARY(NAME,ST,VERBOSE_FLAG)        \
2291 do                                                      \
2292   {                                                     \
2293     if (stat (NAME, &ST) >= 0 && S_ISREG (ST.st_mode))  \
2294       if (unlink (NAME) < 0)                            \
2295         if (VERBOSE_FLAG)                               \
2296           perror_with_name (NAME);                      \
2297   } while (0)
2298 #endif
2299
2300 static void
2301 delete_if_ordinary (const char *name)
2302 {
2303   struct stat st;
2304 #ifdef DEBUG
2305   int i, c;
2306
2307   printf ("Delete %s? (y or n) ", name);
2308   fflush (stdout);
2309   i = getchar ();
2310   if (i != '\n')
2311     while ((c = getchar ()) != '\n' && c != EOF)
2312       ;
2313
2314   if (i == 'y' || i == 'Y')
2315 #endif /* DEBUG */
2316   DELETE_IF_ORDINARY (name, st, verbose_flag);
2317 }
2318
2319 static void
2320 delete_temp_files (void)
2321 {
2322   struct temp_file *temp;
2323
2324   for (temp = always_delete_queue; temp; temp = temp->next)
2325     delete_if_ordinary (temp->name);
2326   always_delete_queue = 0;
2327 }
2328
2329 /* Delete all the files to be deleted on error.  */
2330
2331 static void
2332 delete_failure_queue (void)
2333 {
2334   struct temp_file *temp;
2335
2336   for (temp = failure_delete_queue; temp; temp = temp->next)
2337     delete_if_ordinary (temp->name);
2338 }
2339
2340 static void
2341 clear_failure_queue (void)
2342 {
2343   failure_delete_queue = 0;
2344 }
2345 \f
2346 /* Build a list of search directories from PATHS.
2347    PREFIX is a string to prepend to the list.
2348    If CHECK_DIR_P is nonzero we ensure the directory exists.
2349    This is used mostly by putenv_from_prefixes so we use `collect_obstack'.
2350    It is also used by the --print-search-dirs flag.  */
2351
2352 static char *
2353 build_search_list (struct path_prefix *paths, const char *prefix,
2354                    int check_dir_p)
2355 {
2356   int suffix_len = (machine_suffix) ? strlen (machine_suffix) : 0;
2357   int just_suffix_len
2358     = (just_machine_suffix) ? strlen (just_machine_suffix) : 0;
2359   int first_time = TRUE;
2360   struct prefix_list *pprefix;
2361
2362   obstack_grow (&collect_obstack, prefix, strlen (prefix));
2363   obstack_1grow (&collect_obstack, '=');
2364
2365   for (pprefix = paths->plist; pprefix != 0; pprefix = pprefix->next)
2366     {
2367       int len = strlen (pprefix->prefix);
2368
2369       if (machine_suffix
2370           && (! check_dir_p
2371               || is_directory (pprefix->prefix, machine_suffix, 0)))
2372         {
2373           if (!first_time)
2374             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
2375
2376           first_time = FALSE;
2377           obstack_grow (&collect_obstack, pprefix->prefix, len);
2378           obstack_grow (&collect_obstack, machine_suffix, suffix_len);
2379         }
2380
2381       if (just_machine_suffix
2382           && pprefix->require_machine_suffix == 2
2383           && (! check_dir_p
2384               || is_directory (pprefix->prefix, just_machine_suffix, 0)))
2385         {
2386           if (! first_time)
2387             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
2388
2389           first_time = FALSE;
2390           obstack_grow (&collect_obstack, pprefix->prefix, len);
2391           obstack_grow (&collect_obstack, just_machine_suffix,
2392                         just_suffix_len);
2393         }
2394
2395       if (! pprefix->require_machine_suffix)
2396         {
2397           if (! first_time)
2398             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
2399
2400           first_time = FALSE;
2401           obstack_grow (&collect_obstack, pprefix->prefix, len);
2402         }
2403     }
2404
2405   obstack_1grow (&collect_obstack, '\0');
2406   return XOBFINISH (&collect_obstack, char *);
2407 }
2408
2409 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
2410    for collect.  */
2411
2412 static void
2413 putenv_from_prefixes (struct path_prefix *paths, const char *env_var)
2414 {
2415   putenv (build_search_list (paths, env_var, 1));
2416 }
2417 \f
2418 /* Check whether NAME can be accessed in MODE.  This is like access,
2419    except that it never considers directories to be executable.  */
2420
2421 static int
2422 access_check (const char *name, int mode)
2423 {
2424   if (mode == X_OK)
2425     {
2426       struct stat st;
2427
2428       if (stat (name, &st) < 0
2429           || S_ISDIR (st.st_mode))
2430         return -1;
2431     }
2432
2433   return access (name, mode);
2434 }
2435
2436 /* Search for NAME using the prefix list PREFIXES.  MODE is passed to
2437    access to check permissions.
2438    Return 0 if not found, otherwise return its name, allocated with malloc.  */
2439
2440 static char *
2441 find_a_file (struct path_prefix *pprefix, const char *name, int mode,
2442              int multilib)
2443 {
2444   char *temp;
2445   const char *const file_suffix =
2446     ((mode & X_OK) != 0 ? HOST_EXECUTABLE_SUFFIX : "");
2447   struct prefix_list *pl;
2448   int len = pprefix->max_len + strlen (name) + strlen (file_suffix) + 1;
2449   const char *multilib_name, *multilib_os_name;
2450
2451 #ifdef DEFAULT_ASSEMBLER
2452   if (! strcmp (name, "as") && access (DEFAULT_ASSEMBLER, mode) == 0)
2453     return xstrdup (DEFAULT_ASSEMBLER);
2454 #endif
2455
2456 #ifdef DEFAULT_LINKER
2457   if (! strcmp(name, "ld") && access (DEFAULT_LINKER, mode) == 0)
2458     return xstrdup (DEFAULT_LINKER);
2459 #endif
2460
2461   if (machine_suffix)
2462     len += strlen (machine_suffix);
2463
2464   multilib_name = name;
2465   multilib_os_name = name;
2466   if (multilib && multilib_os_dir)
2467     {
2468       int len1 = multilib_dir ? strlen (multilib_dir) + 1 : 0;
2469       int len2 = strlen (multilib_os_dir) + 1;
2470
2471       len += len1 > len2 ? len1 : len2;
2472       if (multilib_dir)
2473         multilib_name = ACONCAT ((multilib_dir, dir_separator_str, name,
2474                                   NULL));
2475       if (strcmp (multilib_os_dir, ".") != 0)
2476         multilib_os_name = ACONCAT ((multilib_os_dir, dir_separator_str, name,
2477                                     NULL));
2478     }
2479
2480   temp = xmalloc (len);
2481
2482   /* Determine the filename to execute (special case for absolute paths).  */
2483
2484   if (IS_ABSOLUTE_PATH (name))
2485     {
2486       if (access (name, mode) == 0)
2487         {
2488           strcpy (temp, name);
2489           return temp;
2490         }
2491     }
2492   else
2493     for (pl = pprefix->plist; pl; pl = pl->next)
2494       {
2495         const char *this_name
2496           = pl->os_multilib ? multilib_os_name : multilib_name;
2497
2498         if (machine_suffix)
2499           {
2500             /* Some systems have a suffix for executable files.
2501                So try appending that first.  */
2502             if (file_suffix[0] != 0)
2503               {
2504                 strcpy (temp, pl->prefix);
2505                 strcat (temp, machine_suffix);
2506                 strcat (temp, multilib_name);
2507                 strcat (temp, file_suffix);
2508                 if (access_check (temp, mode) == 0)
2509                   return temp;
2510               }
2511
2512             /* Now try just the multilib_name.  */
2513             strcpy (temp, pl->prefix);
2514             strcat (temp, machine_suffix);
2515             strcat (temp, multilib_name);
2516             if (access_check (temp, mode) == 0)
2517               return temp;
2518           }
2519
2520         /* Certain prefixes are tried with just the machine type,
2521            not the version.  This is used for finding as, ld, etc.  */
2522         if (just_machine_suffix && pl->require_machine_suffix == 2)
2523           {
2524             /* Some systems have a suffix for executable files.
2525                So try appending that first.  */
2526             if (file_suffix[0] != 0)
2527               {
2528                 strcpy (temp, pl->prefix);
2529                 strcat (temp, just_machine_suffix);
2530                 strcat (temp, multilib_name);
2531                 strcat (temp, file_suffix);
2532                 if (access_check (temp, mode) == 0)
2533                   return temp;
2534               }
2535
2536             strcpy (temp, pl->prefix);
2537             strcat (temp, just_machine_suffix);
2538             strcat (temp, multilib_name);
2539             if (access_check (temp, mode) == 0)
2540               return temp;
2541           }
2542
2543         /* Certain prefixes can't be used without the machine suffix
2544            when the machine or version is explicitly specified.  */
2545         if (! pl->require_machine_suffix)
2546           {
2547             /* Some systems have a suffix for executable files.
2548                So try appending that first.  */
2549             if (file_suffix[0] != 0)
2550               {
2551                 strcpy (temp, pl->prefix);
2552                 strcat (temp, this_name);
2553                 strcat (temp, file_suffix);
2554                 if (access_check (temp, mode) == 0)
2555                   return temp;
2556               }
2557
2558             strcpy (temp, pl->prefix);
2559             strcat (temp, this_name);
2560             if (access_check (temp, mode) == 0)
2561               return temp;
2562           }
2563       }
2564
2565   free (temp);
2566   return 0;
2567 }
2568
2569 /* Ranking of prefixes in the sort list. -B prefixes are put before
2570    all others.  */
2571
2572 enum path_prefix_priority
2573 {
2574   PREFIX_PRIORITY_B_OPT,
2575   PREFIX_PRIORITY_LAST
2576 };
2577
2578 /* Add an entry for PREFIX in PLIST.  The PLIST is kept in ascending
2579    order according to PRIORITY.  Within each PRIORITY, new entries are
2580    appended.
2581
2582    If WARN is nonzero, we will warn if no file is found
2583    through this prefix.  WARN should point to an int
2584    which will be set to 1 if this entry is used.
2585
2586    COMPONENT is the value to be passed to update_path.
2587
2588    REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
2589    the complete value of machine_suffix.
2590    2 means try both machine_suffix and just_machine_suffix.  */
2591
2592 static void
2593 add_prefix (struct path_prefix *pprefix, const char *prefix,
2594             const char *component, /* enum prefix_priority */ int priority,
2595             int require_machine_suffix, int os_multilib)
2596 {
2597   struct prefix_list *pl, **prev;
2598   int len;
2599
2600   for (prev = &pprefix->plist;
2601        (*prev) != NULL && (*prev)->priority <= priority;
2602        prev = &(*prev)->next)
2603     ;
2604
2605   /* Keep track of the longest prefix.  */
2606
2607   prefix = update_path (prefix, component);
2608   len = strlen (prefix);
2609   if (len > pprefix->max_len)
2610     pprefix->max_len = len;
2611
2612   pl = xmalloc (sizeof (struct prefix_list));
2613   pl->prefix = prefix;
2614   pl->require_machine_suffix = require_machine_suffix;
2615   pl->priority = priority;
2616   pl->os_multilib = os_multilib;
2617
2618   /* Insert after PREV.  */
2619   pl->next = (*prev);
2620   (*prev) = pl;
2621 }
2622
2623 /* Same as add_prefix, but prepending target_system_root to prefix.  */
2624 static void
2625 add_sysrooted_prefix (struct path_prefix *pprefix, const char *prefix,
2626                       const char *component,
2627                       /* enum prefix_priority */ int priority,
2628                       int require_machine_suffix, int os_multilib)
2629 {
2630   if (!IS_ABSOLUTE_PATH (prefix))
2631     fatal ("system path '%s' is not absolute", prefix);
2632
2633   if (target_system_root)
2634     {
2635       if (target_sysroot_suffix)
2636           prefix = concat (target_sysroot_suffix, prefix, NULL);
2637       prefix = concat (target_system_root, prefix, NULL);
2638
2639       /* We have to override this because GCC's notion of sysroot
2640          moves along with GCC.  */
2641       component = "GCC";
2642     }
2643
2644   add_prefix (pprefix, prefix, component, priority,
2645               require_machine_suffix, os_multilib);
2646 }
2647 \f
2648 /* Execute the command specified by the arguments on the current line of spec.
2649    When using pipes, this includes several piped-together commands
2650    with `|' between them.
2651
2652    Return 0 if successful, -1 if failed.  */
2653
2654 static int
2655 execute (void)
2656 {
2657   int i;
2658   int n_commands;               /* # of command.  */
2659   char *string;
2660   struct pex_obj *pex;
2661   struct command
2662   {
2663     const char *prog;           /* program name.  */
2664     const char **argv;          /* vector of args.  */
2665   };
2666
2667   struct command *commands;     /* each command buffer with above info.  */
2668
2669   gcc_assert (!processing_spec_function);
2670
2671   /* Count # of piped commands.  */
2672   for (n_commands = 1, i = 0; i < argbuf_index; i++)
2673     if (strcmp (argbuf[i], "|") == 0)
2674       n_commands++;
2675
2676   /* Get storage for each command.  */
2677   commands = alloca (n_commands * sizeof (struct command));
2678
2679   /* Split argbuf into its separate piped processes,
2680      and record info about each one.
2681      Also search for the programs that are to be run.  */
2682
2683   commands[0].prog = argbuf[0]; /* first command.  */
2684   commands[0].argv = &argbuf[0];
2685   string = find_a_file (&exec_prefixes, commands[0].prog, X_OK, 0);
2686
2687   if (string)
2688     commands[0].argv[0] = string;
2689
2690   for (n_commands = 1, i = 0; i < argbuf_index; i++)
2691     if (strcmp (argbuf[i], "|") == 0)
2692       {                         /* each command.  */
2693 #if defined (__MSDOS__) || defined (OS2) || defined (VMS)
2694         fatal ("-pipe not supported");
2695 #endif
2696         argbuf[i] = 0;  /* termination of command args.  */
2697         commands[n_commands].prog = argbuf[i + 1];
2698         commands[n_commands].argv = &argbuf[i + 1];
2699         string = find_a_file (&exec_prefixes, commands[n_commands].prog,
2700                               X_OK, 0);
2701         if (string)
2702           commands[n_commands].argv[0] = string;
2703         n_commands++;
2704       }
2705
2706   argbuf[argbuf_index] = 0;
2707
2708   /* If -v, print what we are about to do, and maybe query.  */
2709
2710   if (verbose_flag)
2711     {
2712       /* For help listings, put a blank line between sub-processes.  */
2713       if (print_help_list)
2714         fputc ('\n', stderr);
2715
2716       /* Print each piped command as a separate line.  */
2717       for (i = 0; i < n_commands; i++)
2718         {
2719           const char *const *j;
2720
2721           if (verbose_only_flag)
2722             {
2723               for (j = commands[i].argv; *j; j++)
2724                 {
2725                   const char *p;
2726                   fprintf (stderr, " \"");
2727                   for (p = *j; *p; ++p)
2728                     {
2729                       if (*p == '"' || *p == '\\' || *p == '$')
2730                         fputc ('\\', stderr);
2731                       fputc (*p, stderr);
2732                     }
2733                   fputc ('"', stderr);
2734                 }
2735             }
2736           else
2737             for (j = commands[i].argv; *j; j++)
2738               fprintf (stderr, " %s", *j);
2739
2740           /* Print a pipe symbol after all but the last command.  */
2741           if (i + 1 != n_commands)
2742             fprintf (stderr, " |");
2743           fprintf (stderr, "\n");
2744         }
2745       fflush (stderr);
2746       if (verbose_only_flag != 0)
2747         {
2748           /* verbose_only_flag should act as if the spec was
2749              executed, so increment execution_count before
2750              returning.  This prevents spurious warnings about
2751              unused linker input files, etc.  */
2752           execution_count++;
2753           return 0;
2754         }
2755 #ifdef DEBUG
2756       notice ("\nGo ahead? (y or n) ");
2757       fflush (stderr);
2758       i = getchar ();
2759       if (i != '\n')
2760         while (getchar () != '\n')
2761           ;
2762
2763       if (i != 'y' && i != 'Y')
2764         return 0;
2765 #endif /* DEBUG */
2766     }
2767
2768 #ifdef ENABLE_VALGRIND_CHECKING
2769   /* Run the each command through valgrind.  To simplify prepending the
2770      path to valgrind and the option "-q" (for quiet operation unless
2771      something triggers), we allocate a separate argv array.  */
2772
2773   for (i = 0; i < n_commands; i++)
2774     {
2775       const char **argv;
2776       int argc;
2777       int j;
2778
2779       for (argc = 0; commands[i].argv[argc] != NULL; argc++)
2780         ;
2781
2782       argv = alloca ((argc + 3) * sizeof (char *));
2783
2784       argv[0] = VALGRIND_PATH;
2785       argv[1] = "-q";
2786       for (j = 2; j < argc + 2; j++)
2787         argv[j] = commands[i].argv[j - 2];
2788       argv[j] = NULL;
2789
2790       commands[i].argv = argv;
2791       commands[i].prog = argv[0];
2792     }
2793 #endif
2794
2795   /* Run each piped subprocess.  */
2796
2797   pex = pex_init (PEX_USE_PIPES | (report_times ? PEX_RECORD_TIMES : 0),
2798                   programname, temp_filename);
2799   if (pex == NULL)
2800     pfatal_with_name (_("pex_init failed"));
2801
2802   for (i = 0; i < n_commands; i++)
2803     {
2804       const char *errmsg;
2805       int err;
2806       const char *string = commands[i].argv[0];
2807
2808       errmsg = pex_run (pex,
2809                         ((i + 1 == n_commands ? PEX_LAST : 0)
2810                          | (string == commands[i].prog ? PEX_SEARCH : 0)),
2811                         string, (char * const *) commands[i].argv,
2812                         NULL, NULL, &err);
2813       if (errmsg != NULL)
2814         {
2815           if (err == 0)
2816             fatal (errmsg);
2817           else
2818             {
2819               errno = err;
2820               pfatal_with_name (errmsg);
2821             }
2822         }
2823
2824       if (string != commands[i].prog)
2825         free ((void *) string);
2826     }
2827
2828   execution_count++;
2829
2830   /* Wait for all the subprocesses to finish.  */
2831
2832   {
2833     int *statuses;
2834     struct pex_time *times = NULL;
2835     int ret_code = 0;
2836
2837     statuses = alloca (n_commands * sizeof (int));
2838     if (!pex_get_status (pex, n_commands, statuses))
2839       pfatal_with_name (_("failed to get exit status"));
2840
2841     if (report_times)
2842       {
2843         times = alloca (n_commands * sizeof (struct pex_time));
2844         if (!pex_get_times (pex, n_commands, times))
2845           pfatal_with_name (_("failed to get process times"));
2846       }
2847
2848     pex_free (pex);
2849
2850     for (i = 0; i < n_commands; ++i)
2851       {
2852         int status = statuses[i];
2853
2854         if (WIFSIGNALED (status))
2855           {
2856 #ifdef SIGPIPE
2857             /* SIGPIPE is a special case.  It happens in -pipe mode
2858                when the compiler dies before the preprocessor is done,
2859                or the assembler dies before the compiler is done.
2860                There's generally been an error already, and this is
2861                just fallout.  So don't generate another error unless
2862                we would otherwise have succeeded.  */
2863             if (WTERMSIG (status) == SIGPIPE
2864                 && (signal_count || greatest_status >= MIN_FATAL_STATUS))
2865               ;
2866             else
2867 #endif
2868               fatal ("\
2869 Internal error: %s (program %s)\n\
2870 Please submit a full bug report.\n\
2871 See %s for instructions.",
2872                      strsignal (WTERMSIG (status)), commands[i].prog,
2873                      bug_report_url);
2874             signal_count++;
2875             ret_code = -1;
2876           }
2877         else if (WIFEXITED (status)
2878                  && WEXITSTATUS (status) >= MIN_FATAL_STATUS)
2879           {
2880             if (WEXITSTATUS (status) > greatest_status)
2881               greatest_status = WEXITSTATUS (status);
2882             ret_code = -1;
2883           }
2884
2885         if (report_times)
2886           {
2887             struct pex_time *pt = &times[i];
2888             double ut, st;
2889
2890             ut = ((double) pt->user_seconds
2891                   + (double) pt->user_microseconds / 1.0e6);
2892             st = ((double) pt->system_seconds
2893                   + (double) pt->system_microseconds / 1.0e6);
2894
2895             if (ut + st != 0)
2896               notice ("# %s %.2f %.2f\n", commands[i].prog, ut, st);
2897           }
2898       }
2899
2900     return ret_code;
2901   }
2902 }
2903 \f
2904 /* Find all the switches given to us
2905    and make a vector describing them.
2906    The elements of the vector are strings, one per switch given.
2907    If a switch uses following arguments, then the `part1' field
2908    is the switch itself and the `args' field
2909    is a null-terminated vector containing the following arguments.
2910    The `live_cond' field is:
2911    0 when initialized
2912    1 if the switch is true in a conditional spec,
2913    -1 if false (overridden by a later switch)
2914    -2 if this switch should be ignored (used in %<S)
2915    The `validated' field is nonzero if any spec has looked at this switch;
2916    if it remains zero at the end of the run, it must be meaningless.  */
2917
2918 #define SWITCH_OK       0
2919 #define SWITCH_FALSE   -1
2920 #define SWITCH_IGNORE  -2
2921 #define SWITCH_LIVE     1
2922
2923 struct switchstr
2924 {
2925   const char *part1;
2926   const char **args;
2927   int live_cond;
2928   unsigned char validated;
2929   unsigned char ordering;
2930 };
2931
2932 static struct switchstr *switches;
2933
2934 static int n_switches;
2935
2936 struct infile
2937 {
2938   const char *name;
2939   const char *language;
2940   struct compiler *incompiler;
2941   bool compiled;
2942   bool preprocessed;
2943 };
2944
2945 /* Also a vector of input files specified.  */
2946
2947 static struct infile *infiles;
2948
2949 int n_infiles;
2950
2951 /* True if multiple input files are being compiled to a single
2952    assembly file.  */
2953
2954 static bool combine_inputs;
2955
2956 /* This counts the number of libraries added by lang_specific_driver, so that
2957    we can tell if there were any user supplied any files or libraries.  */
2958
2959 static int added_libraries;
2960
2961 /* And a vector of corresponding output files is made up later.  */
2962
2963 const char **outfiles;
2964 \f
2965 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
2966
2967 /* Convert NAME to a new name if it is the standard suffix.  DO_EXE
2968    is true if we should look for an executable suffix.  DO_OBJ
2969    is true if we should look for an object suffix.  */
2970
2971 static const char *
2972 convert_filename (const char *name, int do_exe ATTRIBUTE_UNUSED,
2973                   int do_obj ATTRIBUTE_UNUSED)
2974 {
2975 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
2976   int i;
2977 #endif
2978   int len;
2979
2980   if (name == NULL)
2981     return NULL;
2982
2983   len = strlen (name);
2984
2985 #ifdef HAVE_TARGET_OBJECT_SUFFIX
2986   /* Convert x.o to x.obj if TARGET_OBJECT_SUFFIX is ".obj".  */
2987   if (do_obj && len > 2
2988       && name[len - 2] == '.'
2989       && name[len - 1] == 'o')
2990     {
2991       obstack_grow (&obstack, name, len - 2);
2992       obstack_grow0 (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
2993       name = XOBFINISH (&obstack, const char *);
2994     }
2995 #endif
2996
2997 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
2998   /* If there is no filetype, make it the executable suffix (which includes
2999      the ".").  But don't get confused if we have just "-o".  */
3000   if (! do_exe || TARGET_EXECUTABLE_SUFFIX[0] == 0 || (len == 2 && name[0] == '-'))
3001     return name;
3002
3003   for (i = len - 1; i >= 0; i--)
3004     if (IS_DIR_SEPARATOR (name[i]))
3005       break;
3006
3007   for (i++; i < len; i++)
3008     if (name[i] == '.')
3009       return name;
3010
3011   obstack_grow (&obstack, name, len);
3012   obstack_grow0 (&obstack, TARGET_EXECUTABLE_SUFFIX,
3013                  strlen (TARGET_EXECUTABLE_SUFFIX));
3014   name = XOBFINISH (&obstack, const char *);
3015 #endif
3016
3017   return name;
3018 }
3019 #endif
3020 \f
3021 /* Display the command line switches accepted by gcc.  */
3022 static void
3023 display_help (void)
3024 {
3025   printf (_("Usage: %s [options] file...\n"), programname);
3026   fputs (_("Options:\n"), stdout);
3027
3028   fputs (_("  -pass-exit-codes         Exit with highest error code from a phase\n"), stdout);
3029   fputs (_("  --help                   Display this information\n"), stdout);
3030   fputs (_("  --target-help            Display target specific command line options\n"), stdout);
3031   if (! verbose_flag)
3032     fputs (_("  (Use '-v --help' to display command line options of sub-processes)\n"), stdout);
3033   fputs (_("  -dumpspecs               Display all of the built in spec strings\n"), stdout);
3034   fputs (_("  -dumpversion             Display the version of the compiler\n"), stdout);
3035   fputs (_("  -dumpmachine             Display the compiler's target processor\n"), stdout);
3036   fputs (_("  -print-search-dirs       Display the directories in the compiler's search path\n"), stdout);
3037   fputs (_("  -print-libgcc-file-name  Display the name of the compiler's companion library\n"), stdout);
3038   fputs (_("  -print-file-name=<lib>   Display the full path to library <lib>\n"), stdout);
3039   fputs (_("  -print-prog-name=<prog>  Display the full path to compiler component <prog>\n"), stdout);
3040   fputs (_("  -print-multi-directory   Display the root directory for versions of libgcc\n"), stdout);
3041   fputs (_("\
3042   -print-multi-lib         Display the mapping between command line options and\n\
3043                            multiple library search directories\n"), stdout);
3044   fputs (_("  -print-multi-os-directory Display the relative path to OS libraries\n"), stdout);
3045   fputs (_("  -Wa,<options>            Pass comma-separated <options> on to the assembler\n"), stdout);
3046   fputs (_("  -Wp,<options>            Pass comma-separated <options> on to the preprocessor\n"), stdout);
3047   fputs (_("  -Wl,<options>            Pass comma-separated <options> on to the linker\n"), stdout);
3048   fputs (_("  -Xassembler <arg>        Pass <arg> on to the assembler\n"), stdout);
3049   fputs (_("  -Xpreprocessor <arg>     Pass <arg> on to the preprocessor\n"), stdout);
3050   fputs (_("  -Xlinker <arg>           Pass <arg> on to the linker\n"), stdout);
3051   fputs (_("  -combine                 Pass multiple source files to compiler at once\n"), stdout);
3052   fputs (_("  -save-temps              Do not delete intermediate files\n"), stdout);
3053   fputs (_("  -pipe                    Use pipes rather than intermediate files\n"), stdout);
3054   fputs (_("  -time                    Time the execution of each subprocess\n"), stdout);
3055   fputs (_("  -specs=<file>            Override built-in specs with the contents of <file>\n"), stdout);
3056   fputs (_("  -std=<standard>          Assume that the input sources are for <standard>\n"), stdout);
3057   fputs (_("  -B <directory>           Add <directory> to the compiler's search paths\n"), stdout);
3058   fputs (_("  -b <machine>             Run gcc for target <machine>, if installed\n"), stdout);
3059   fputs (_("  -V <version>             Run gcc version number <version>, if installed\n"), stdout);
3060   fputs (_("  -v                       Display the programs invoked by the compiler\n"), stdout);
3061   fputs (_("  -###                     Like -v but options quoted and commands not executed\n"), stdout);
3062   fputs (_("  -E                       Preprocess only; do not compile, assemble or link\n"), stdout);
3063   fputs (_("  -S                       Compile only; do not assemble or link\n"), stdout);
3064   fputs (_("  -c                       Compile and assemble, but do not link\n"), stdout);
3065   fputs (_("  -o <file>                Place the output into <file>\n"), stdout);
3066   fputs (_("\
3067   -x <language>            Specify the language of the following input files\n\
3068                            Permissible languages include: c c++ assembler none\n\
3069                            'none' means revert to the default behavior of\n\
3070                            guessing the language based on the file's extension\n\
3071 "), stdout);
3072
3073   printf (_("\
3074 \nOptions starting with -g, -f, -m, -O, -W, or --param are automatically\n\
3075  passed on to the various sub-processes invoked by %s.  In order to pass\n\
3076  other options on to these processes the -W<letter> options must be used.\n\
3077 "), programname);
3078
3079   /* The rest of the options are displayed by invocations of the various
3080      sub-processes.  */
3081 }
3082
3083 static void
3084 add_preprocessor_option (const char *option, int len)
3085 {
3086   n_preprocessor_options++;
3087
3088   if (! preprocessor_options)
3089     preprocessor_options = xmalloc (n_preprocessor_options * sizeof (char *));
3090   else
3091     preprocessor_options = xrealloc (preprocessor_options,
3092                                      n_preprocessor_options * sizeof (char *));
3093
3094   preprocessor_options [n_preprocessor_options - 1] =
3095     save_string (option, len);
3096 }
3097
3098 static void
3099 add_assembler_option (const char *option, int len)
3100 {
3101   n_assembler_options++;
3102
3103   if (! assembler_options)
3104     assembler_options = xmalloc (n_assembler_options * sizeof (char *));
3105   else
3106     assembler_options = xrealloc (assembler_options,
3107                                   n_assembler_options * sizeof (char *));
3108
3109   assembler_options [n_assembler_options - 1] = save_string (option, len);
3110 }
3111
3112 static void
3113 add_linker_option (const char *option, int len)
3114 {
3115   n_linker_options++;
3116
3117   if (! linker_options)
3118     linker_options = xmalloc (n_linker_options * sizeof (char *));
3119   else
3120     linker_options = xrealloc (linker_options,
3121                                n_linker_options * sizeof (char *));
3122
3123   linker_options [n_linker_options - 1] = save_string (option, len);
3124 }
3125 \f
3126 /* Create the vector `switches' and its contents.
3127    Store its length in `n_switches'.  */
3128
3129 static void
3130 process_command (int argc, const char **argv)
3131 {
3132   int i;
3133   const char *temp;
3134   char *temp1;
3135   const char *spec_lang = 0;
3136   int last_language_n_infiles;
3137   int have_c = 0;
3138   int lang_n_infiles = 0;
3139 #ifdef MODIFY_TARGET_NAME
3140   int is_modify_target_name;
3141   int j;
3142 #endif
3143
3144   GET_ENVIRONMENT (gcc_exec_prefix, "GCC_EXEC_PREFIX");
3145
3146   n_switches = 0;
3147   n_infiles = 0;
3148   added_libraries = 0;
3149
3150   /* Figure compiler version from version string.  */
3151
3152   compiler_version = temp1 = xstrdup (version_string);
3153
3154   for (; *temp1; ++temp1)
3155     {
3156       if (*temp1 == ' ')
3157         {
3158           *temp1 = '\0';
3159           break;
3160         }
3161     }
3162
3163   /* If there is a -V or -b option (or both), process it now, before
3164      trying to interpret the rest of the command line.  */
3165   if (argc > 1 && argv[1][0] == '-'
3166       && (argv[1][1] == 'V' || argv[1][1] == 'b'))
3167     {
3168       const char *new_version = DEFAULT_TARGET_VERSION;
3169       const char *new_machine = DEFAULT_TARGET_MACHINE;
3170       const char *progname = argv[0];
3171       char **new_argv;
3172       char *new_argv0;
3173       int baselen;
3174
3175       while (argc > 1 && argv[1][0] == '-'
3176              && (argv[1][1] == 'V' || argv[1][1] == 'b'))
3177         {
3178           char opt = argv[1][1];
3179           const char *arg;
3180           if (argv[1][2] != '\0')
3181             {
3182               arg = argv[1] + 2;
3183               argc -= 1;
3184               argv += 1;
3185             }
3186           else if (argc > 2)
3187             {
3188               arg = argv[2];
3189               argc -= 2;
3190               argv += 2;
3191             }
3192           else
3193             fatal ("'-%c' option must have argument", opt);
3194           if (opt == 'V')
3195             new_version = arg;
3196           else
3197             new_machine = arg;
3198         }
3199
3200       for (baselen = strlen (progname); baselen > 0; baselen--)
3201         if (IS_DIR_SEPARATOR (progname[baselen-1]))
3202           break;
3203       new_argv0 = xmemdup (progname, baselen,
3204                            baselen + concat_length (new_version, new_machine,
3205                                                     "-gcc-", NULL) + 1);
3206       strcpy (new_argv0 + baselen, new_machine);
3207       strcat (new_argv0, "-gcc-");
3208       strcat (new_argv0, new_version);
3209
3210       new_argv = xmemdup (argv, (argc + 1) * sizeof (argv[0]),
3211                           (argc + 1) * sizeof (argv[0]));
3212       new_argv[0] = new_argv0;
3213
3214       execvp (new_argv0, new_argv);
3215       fatal ("couldn't run '%s': %s", new_argv0, xstrerror (errno));
3216     }
3217
3218   /* Set up the default search paths.  If there is no GCC_EXEC_PREFIX,
3219      see if we can create it from the pathname specified in argv[0].  */
3220
3221   gcc_libexec_prefix = standard_libexec_prefix;
3222 #ifndef VMS
3223   /* FIXME: make_relative_prefix doesn't yet work for VMS.  */
3224   if (!gcc_exec_prefix)
3225     {
3226       gcc_exec_prefix = make_relative_prefix (argv[0], standard_bindir_prefix,
3227                                               standard_exec_prefix);
3228       gcc_libexec_prefix = make_relative_prefix (argv[0], 
3229                                                  standard_bindir_prefix,
3230                                                  standard_libexec_prefix);
3231       if (gcc_exec_prefix)
3232         putenv (concat ("GCC_EXEC_PREFIX=", gcc_exec_prefix, NULL));
3233     }
3234   else
3235     gcc_libexec_prefix = make_relative_prefix (gcc_exec_prefix,
3236                                                standard_exec_prefix,
3237                                                standard_libexec_prefix);
3238 #else
3239 #endif
3240
3241   if (gcc_exec_prefix)
3242     {
3243       int len = strlen (gcc_exec_prefix);
3244
3245       if (len > (int) sizeof ("/lib/gcc/") - 1
3246           && (IS_DIR_SEPARATOR (gcc_exec_prefix[len-1])))
3247         {
3248           temp = gcc_exec_prefix + len - sizeof ("/lib/gcc/") + 1;
3249           if (IS_DIR_SEPARATOR (*temp)
3250               && strncmp (temp + 1, "lib", 3) == 0
3251               && IS_DIR_SEPARATOR (temp[4])
3252               && strncmp (temp + 5, "gcc", 3) == 0)
3253             len -= sizeof ("/lib/gcc/") - 1;
3254         }
3255
3256       set_std_prefix (gcc_exec_prefix, len);
3257       add_prefix (&exec_prefixes, gcc_libexec_prefix, "GCC",
3258                   PREFIX_PRIORITY_LAST, 0, 0);
3259       add_prefix (&startfile_prefixes, gcc_exec_prefix, "GCC",
3260                   PREFIX_PRIORITY_LAST, 0, 0);
3261     }
3262
3263   /* COMPILER_PATH and LIBRARY_PATH have values
3264      that are lists of directory names with colons.  */
3265
3266   GET_ENVIRONMENT (temp, "COMPILER_PATH");
3267   if (temp)
3268     {
3269       const char *startp, *endp;
3270       char *nstore = alloca (strlen (temp) + 3);
3271
3272       startp = endp = temp;
3273       while (1)
3274         {
3275           if (*endp == PATH_SEPARATOR || *endp == 0)
3276             {
3277               strncpy (nstore, startp, endp - startp);
3278               if (endp == startp)
3279                 strcpy (nstore, concat (".", dir_separator_str, NULL));
3280               else if (!IS_DIR_SEPARATOR (endp[-1]))
3281                 {
3282                   nstore[endp - startp] = DIR_SEPARATOR;
3283                   nstore[endp - startp + 1] = 0;
3284                 }
3285               else
3286                 nstore[endp - startp] = 0;
3287               add_prefix (&exec_prefixes, nstore, 0,
3288                           PREFIX_PRIORITY_LAST, 0, 0);
3289               add_prefix (&include_prefixes, nstore, 0,
3290                           PREFIX_PRIORITY_LAST, 0, 0);
3291               if (*endp == 0)
3292                 break;
3293               endp = startp = endp + 1;
3294             }
3295           else
3296             endp++;
3297         }
3298     }
3299
3300   GET_ENVIRONMENT (temp, LIBRARY_PATH_ENV);
3301   if (temp && *cross_compile == '0')
3302     {
3303       const char *startp, *endp;
3304       char *nstore = alloca (strlen (temp) + 3);
3305
3306       startp = endp = temp;
3307       while (1)
3308         {
3309           if (*endp == PATH_SEPARATOR || *endp == 0)
3310             {
3311               strncpy (nstore, startp, endp - startp);
3312               if (endp == startp)
3313                 strcpy (nstore, concat (".", dir_separator_str, NULL));
3314               else if (!IS_DIR_SEPARATOR (endp[-1]))
3315                 {
3316                   nstore[endp - startp] = DIR_SEPARATOR;
3317                   nstore[endp - startp + 1] = 0;
3318                 }
3319               else
3320                 nstore[endp - startp] = 0;
3321               add_prefix (&startfile_prefixes, nstore, NULL,
3322                           PREFIX_PRIORITY_LAST, 0, 1);
3323               if (*endp == 0)
3324                 break;
3325               endp = startp = endp + 1;
3326             }
3327           else
3328             endp++;
3329         }
3330     }
3331
3332   /* Use LPATH like LIBRARY_PATH (for the CMU build program).  */
3333   GET_ENVIRONMENT (temp, "LPATH");
3334   if (temp && *cross_compile == '0')
3335     {
3336       const char *startp, *endp;
3337       char *nstore = alloca (strlen (temp) + 3);
3338
3339       startp = endp = temp;
3340       while (1)
3341         {
3342           if (*endp == PATH_SEPARATOR || *endp == 0)
3343             {
3344               strncpy (nstore, startp, endp - startp);
3345               if (endp == startp)
3346                 strcpy (nstore, concat (".", dir_separator_str, NULL));
3347               else if (!IS_DIR_SEPARATOR (endp[-1]))
3348                 {
3349                   nstore[endp - startp] = DIR_SEPARATOR;
3350                   nstore[endp - startp + 1] = 0;
3351                 }
3352               else
3353                 nstore[endp - startp] = 0;
3354               add_prefix (&startfile_prefixes, nstore, NULL,
3355                           PREFIX_PRIORITY_LAST, 0, 1);
3356               if (*endp == 0)
3357                 break;
3358               endp = startp = endp + 1;
3359             }
3360           else
3361             endp++;
3362         }
3363     }
3364
3365   /* Convert new-style -- options to old-style.  */
3366   translate_options (&argc, (const char *const **) &argv);
3367
3368   /* Do language-specific adjustment/addition of flags.  */
3369   lang_specific_driver (&argc, (const char *const **) &argv, &added_libraries);
3370
3371   /* Scan argv twice.  Here, the first time, just count how many switches
3372      there will be in their vector, and how many input files in theirs.
3373      Here we also parse the switches that cc itself uses (e.g. -v).  */
3374
3375   for (i = 1; i < argc; i++)
3376     {
3377       if (! strcmp (argv[i], "-dumpspecs"))
3378         {
3379           struct spec_list *sl;
3380           init_spec ();
3381           for (sl = specs; sl; sl = sl->next)
3382             printf ("*%s:\n%s\n\n", sl->name, *(sl->ptr_spec));
3383           if (link_command_spec)
3384             printf ("*link_command:\n%s\n\n", link_command_spec);
3385           exit (0);
3386         }
3387       else if (! strcmp (argv[i], "-dumpversion"))
3388         {
3389           printf ("%s\n", spec_version);
3390           exit (0);
3391         }
3392       else if (! strcmp (argv[i], "-dumpmachine"))
3393         {
3394           printf ("%s\n", spec_machine);
3395           exit (0);
3396         }
3397       else if (strcmp (argv[i], "-fversion") == 0)
3398         {
3399           /* translate_options () has turned --version into -fversion.  */
3400           printf (_("%s (GCC) %s\n"), programname, version_string);
3401           printf ("Copyright %s 2005 Free Software Foundation, Inc.\n",
3402                   _("(C)"));
3403           fputs (_("This is free software; see the source for copying conditions.  There is NO\n\
3404 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"),
3405                  stdout);
3406           exit (0);
3407         }
3408       else if (strcmp (argv[i], "-fhelp") == 0)
3409         {
3410           /* translate_options () has turned --help into -fhelp.  */
3411           print_help_list = 1;
3412
3413           /* We will be passing a dummy file on to the sub-processes.  */
3414           n_infiles++;
3415           n_switches++;
3416
3417           /* CPP driver cannot obtain switch from cc1_options.  */
3418           if (is_cpp_driver)
3419             add_preprocessor_option ("--help", 6);
3420           add_assembler_option ("--help", 6);
3421           add_linker_option ("--help", 6);
3422         }
3423       else if (strcmp (argv[i], "-ftarget-help") == 0)
3424         {
3425           /* translate_options() has turned --target-help into -ftarget-help.  */
3426           target_help_flag = 1;
3427
3428           /* We will be passing a dummy file on to the sub-processes.  */
3429           n_infiles++;
3430           n_switches++;
3431
3432           /* CPP driver cannot obtain switch from cc1_options.  */
3433           if (is_cpp_driver)
3434             add_preprocessor_option ("--target-help", 13);
3435           add_assembler_option ("--target-help", 13);
3436           add_linker_option ("--target-help", 13);
3437         }
3438       else if (! strcmp (argv[i], "-pass-exit-codes"))
3439         {
3440           pass_exit_codes = 1;
3441           n_switches++;
3442         }
3443       else if (! strcmp (argv[i], "-print-search-dirs"))
3444         print_search_dirs = 1;
3445       else if (! strcmp (argv[i], "-print-libgcc-file-name"))
3446         print_file_name = "libgcc.a";
3447       else if (! strncmp (argv[i], "-print-file-name=", 17))
3448         print_file_name = argv[i] + 17;
3449       else if (! strncmp (argv[i], "-print-prog-name=", 17))
3450         print_prog_name = argv[i] + 17;
3451       else if (! strcmp (argv[i], "-print-multi-lib"))
3452         print_multi_lib = 1;
3453       else if (! strcmp (argv[i], "-print-multi-directory"))
3454         print_multi_directory = 1;
3455       else if (! strcmp (argv[i], "-print-multi-os-directory"))
3456         print_multi_os_directory = 1;
3457       else if (! strncmp (argv[i], "-Wa,", 4))
3458         {
3459           int prev, j;
3460           /* Pass the rest of this option to the assembler.  */
3461
3462           /* Split the argument at commas.  */
3463           prev = 4;
3464           for (j = 4; argv[i][j]; j++)
3465             if (argv[i][j] == ',')
3466               {
3467                 add_assembler_option (argv[i] + prev, j - prev);
3468                 prev = j + 1;
3469               }
3470
3471           /* Record the part after the last comma.  */
3472           add_assembler_option (argv[i] + prev, j - prev);
3473         }
3474       else if (! strncmp (argv[i], "-Wp,", 4))
3475         {
3476           int prev, j;
3477           /* Pass the rest of this option to the preprocessor.  */
3478
3479           /* Split the argument at commas.  */
3480           prev = 4;
3481           for (j = 4; argv[i][j]; j++)
3482             if (argv[i][j] == ',')
3483               {
3484                 add_preprocessor_option (argv[i] + prev, j - prev);
3485                 prev = j + 1;
3486               }
3487
3488           /* Record the part after the last comma.  */
3489           add_preprocessor_option (argv[i] + prev, j - prev);
3490         }
3491       else if (argv[i][0] == '+' && argv[i][1] == 'e')
3492         /* The +e options to the C++ front-end.  */
3493         n_switches++;
3494       else if (strncmp (argv[i], "-Wl,", 4) == 0)
3495         {
3496           int j;
3497           /* Split the argument at commas.  */
3498           for (j = 3; argv[i][j]; j++)
3499             n_infiles += (argv[i][j] == ',');
3500         }
3501       else if (strcmp (argv[i], "-Xlinker") == 0)
3502         {
3503           if (i + 1 == argc)
3504             fatal ("argument to '-Xlinker' is missing");
3505
3506           n_infiles++;
3507           i++;
3508         }
3509       else if (strcmp (argv[i], "-Xpreprocessor") == 0)
3510         {
3511           if (i + 1 == argc)
3512             fatal ("argument to '-Xpreprocessor' is missing");
3513
3514           add_preprocessor_option (argv[i+1], strlen (argv[i+1]));
3515         }
3516       else if (strcmp (argv[i], "-Xassembler") == 0)
3517         {
3518           if (i + 1 == argc)
3519             fatal ("argument to '-Xassembler' is missing");
3520
3521           add_assembler_option (argv[i+1], strlen (argv[i+1]));
3522         }
3523       else if (strcmp (argv[i], "-l") == 0)
3524         {
3525           if (i + 1 == argc)
3526             fatal ("argument to '-l' is missing");
3527
3528           n_infiles++;
3529           i++;
3530         }
3531       else if (strncmp (argv[i], "-l", 2) == 0)
3532         n_infiles++;
3533       else if (strcmp (argv[i], "-save-temps") == 0)
3534         {
3535           save_temps_flag = 1;
3536           n_switches++;
3537         }
3538       else if (strcmp (argv[i], "-combine") == 0)
3539         {
3540           combine_flag = 1;
3541           n_switches++;
3542         }
3543       else if (strcmp (argv[i], "-specs") == 0)
3544         {
3545           struct user_specs *user = xmalloc (sizeof (struct user_specs));
3546           if (++i >= argc)
3547             fatal ("argument to '-specs' is missing");
3548
3549           user->next = (struct user_specs *) 0;
3550           user->filename = argv[i];
3551           if (user_specs_tail)
3552             user_specs_tail->next = user;
3553           else
3554             user_specs_head = user;
3555           user_specs_tail = user;
3556         }
3557       else if (strncmp (argv[i], "-specs=", 7) == 0)
3558         {
3559           struct user_specs *user = xmalloc (sizeof (struct user_specs));
3560           if (strlen (argv[i]) == 7)
3561             fatal ("argument to '-specs=' is missing");
3562
3563           user->next = (struct user_specs *) 0;
3564           user->filename = argv[i] + 7;
3565           if (user_specs_tail)
3566             user_specs_tail->next = user;
3567           else
3568             user_specs_head = user;
3569           user_specs_tail = user;
3570         }
3571       else if (strcmp (argv[i], "-time") == 0)
3572         report_times = 1;
3573       else if (strcmp (argv[i], "-pipe") == 0)
3574         {
3575           /* -pipe has to go into the switches array as well as
3576              setting a flag.  */
3577           use_pipes = 1;
3578           n_switches++;
3579         }
3580       else if (strcmp (argv[i], "-###") == 0)
3581         {
3582           /* This is similar to -v except that there is no execution
3583              of the commands and the echoed arguments are quoted.  It
3584              is intended for use in shell scripts to capture the
3585              driver-generated command line.  */
3586           verbose_only_flag++;
3587           verbose_flag++;
3588         }
3589       else if (argv[i][0] == '-' && argv[i][1] != 0)
3590         {
3591           const char *p = &argv[i][1];
3592           int c = *p;
3593
3594           switch (c)
3595             {
3596             case 'b':
3597             case 'V':
3598               fatal ("'-%c' must come at the start of the command line", c);
3599               break;
3600
3601             case 'B':
3602               {
3603                 const char *value;
3604                 int len;
3605
3606                 if (p[1] == 0 && i + 1 == argc)
3607                   fatal ("argument to '-B' is missing");
3608                 if (p[1] == 0)
3609                   value = argv[++i];
3610                 else
3611                   value = p + 1;
3612
3613                 len = strlen (value);
3614
3615                 /* Catch the case where the user has forgotten to append a
3616                    directory separator to the path.  Note, they may be using
3617                    -B to add an executable name prefix, eg "i386-elf-", in
3618                    order to distinguish between multiple installations of
3619                    GCC in the same directory.  Hence we must check to see
3620                    if appending a directory separator actually makes a
3621                    valid directory name.  */
3622                 if (! IS_DIR_SEPARATOR (value [len - 1])
3623                     && is_directory (value, "", 0))
3624                   {
3625                     char *tmp = xmalloc (len + 2);
3626                     strcpy (tmp, value);
3627                     tmp[len] = DIR_SEPARATOR;
3628                     tmp[++ len] = 0;
3629                     value = tmp;
3630                   }
3631
3632                 /* As a kludge, if the arg is "[foo/]stageN/", just
3633                    add "[foo/]include" to the include prefix.  */
3634                 if ((len == 7
3635                      || (len > 7
3636                          && (IS_DIR_SEPARATOR (value[len - 8]))))
3637                     && strncmp (value + len - 7, "stage", 5) == 0
3638                     && ISDIGIT (value[len - 2])
3639                     && (IS_DIR_SEPARATOR (value[len - 1])))
3640                   {
3641                     if (len == 7)
3642                       add_prefix (&include_prefixes, "./", NULL,
3643                                   PREFIX_PRIORITY_B_OPT, 0, 0);
3644                     else
3645                       {
3646                         char *string = xmalloc (len - 6);
3647                         memcpy (string, value, len - 7);
3648                         string[len - 7] = 0;
3649                         add_prefix (&include_prefixes, string, NULL,
3650                                     PREFIX_PRIORITY_B_OPT, 0, 0);
3651                       }
3652                   }
3653
3654                 add_prefix (&exec_prefixes, value, NULL,
3655                             PREFIX_PRIORITY_B_OPT, 0, 0);
3656                 add_prefix (&startfile_prefixes, value, NULL,
3657                             PREFIX_PRIORITY_B_OPT, 0, 0);
3658                 add_prefix (&include_prefixes, value, NULL,
3659                             PREFIX_PRIORITY_B_OPT, 0, 0);
3660                 n_switches++;
3661               }
3662               break;
3663
3664             case 'v':   /* Print our subcommands and print versions.  */
3665               n_switches++;
3666               /* If they do anything other than exactly `-v', don't set
3667                  verbose_flag; rather, continue on to give the error.  */
3668               if (p[1] != 0)
3669                 break;
3670               verbose_flag++;
3671               break;
3672
3673             case 'S':
3674             case 'c':
3675               if (p[1] == 0)
3676                 {
3677                   have_c = 1;
3678                   n_switches++;
3679                   break;
3680                 }
3681               goto normal_switch;
3682
3683             case 'o':
3684 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3685               if (! have_c)
3686                 {
3687                   int skip;
3688
3689                   /* Forward scan, just in case -S or -c is specified
3690                      after -o.  */
3691                   int j = i + 1;
3692                   if (p[1] == 0)
3693                     ++j;
3694                   while (j < argc)
3695                     {
3696                       if (argv[j][0] == '-')
3697                         {
3698                           if (SWITCH_CURTAILS_COMPILATION (argv[j][1])
3699                               && argv[j][2] == 0)
3700                             {
3701                               have_c = 1;
3702                               break;
3703                             }
3704                           else if ((skip = SWITCH_TAKES_ARG (argv[j][1])))
3705                             j += skip - (argv[j][2] != 0);
3706                           else if ((skip = WORD_SWITCH_TAKES_ARG (argv[j] + 1)))
3707                             j += skip;
3708                         }
3709                       j++;
3710                     }
3711                 }
3712 #endif
3713 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX) || defined(HAVE_TARGET_OBJECT_SUFFIX)
3714               if (p[1] == 0)
3715                 argv[i + 1] = convert_filename (argv[i + 1], ! have_c, 0);
3716               else
3717                 argv[i] = convert_filename (argv[i], ! have_c, 0);
3718 #endif
3719               goto normal_switch;
3720
3721             default:
3722             normal_switch:
3723
3724 #ifdef MODIFY_TARGET_NAME
3725               is_modify_target_name = 0;
3726
3727               for (j = 0; j < ARRAY_SIZE (modify_target); j++)
3728                 if (! strcmp (argv[i], modify_target[j].sw))
3729                   {
3730                     char *new_name = xmalloc (strlen (modify_target[j].str)
3731                                               + strlen (spec_machine));
3732                     const char *p, *r;
3733                     char *q;
3734                     int made_addition = 0;
3735
3736                     is_modify_target_name = 1;
3737                     for (p = spec_machine, q = new_name; *p != 0; )
3738                       {
3739                         if (modify_target[j].add_del == DELETE
3740                             && (! strncmp (q, modify_target[j].str,
3741                                            strlen (modify_target[j].str))))
3742                           p += strlen (modify_target[j].str);
3743                         else if (modify_target[j].add_del == ADD
3744                                  && ! made_addition && *p == '-')
3745                           {
3746                             for (r = modify_target[j].str; *r != 0; )
3747                               *q++ = *r++;
3748                             made_addition = 1;
3749                           }
3750
3751                         *q++ = *p++;
3752                       }
3753
3754                     spec_machine = new_name;
3755                   }
3756
3757               if (is_modify_target_name)
3758                 break;
3759 #endif
3760
3761               n_switches++;
3762
3763               if (SWITCH_TAKES_ARG (c) > (p[1] != 0))
3764                 i += SWITCH_TAKES_ARG (c) - (p[1] != 0);
3765               else if (WORD_SWITCH_TAKES_ARG (p))
3766                 i += WORD_SWITCH_TAKES_ARG (p);
3767             }
3768         }
3769       else
3770         {
3771           n_infiles++;
3772           lang_n_infiles++;
3773         }
3774     }
3775
3776   if (save_temps_flag && use_pipes)
3777     {
3778       /* -save-temps overrides -pipe, so that temp files are produced */
3779       if (save_temps_flag)
3780         error ("warning: -pipe ignored because -save-temps specified");
3781       use_pipes = 0;
3782     }
3783
3784   /* Set up the search paths before we go looking for config files.  */
3785
3786   /* These come before the md prefixes so that we will find gcc's subcommands
3787      (such as cpp) rather than those of the host system.  */
3788   /* Use 2 as fourth arg meaning try just the machine as a suffix,
3789      as well as trying the machine and the version.  */
3790 #ifndef OS2
3791   add_prefix (&exec_prefixes, standard_libexec_prefix, "GCC",
3792               PREFIX_PRIORITY_LAST, 1, 0);
3793   add_prefix (&exec_prefixes, standard_libexec_prefix, "BINUTILS",
3794               PREFIX_PRIORITY_LAST, 2, 0);
3795   add_prefix (&exec_prefixes, standard_exec_prefix, "BINUTILS",
3796               PREFIX_PRIORITY_LAST, 2, 0);
3797   add_prefix (&exec_prefixes, standard_exec_prefix_1, "BINUTILS",
3798               PREFIX_PRIORITY_LAST, 2, 0);
3799   add_prefix (&exec_prefixes, standard_exec_prefix_2, "BINUTILS",
3800               PREFIX_PRIORITY_LAST, 2, 0);
3801 #endif
3802
3803   add_prefix (&startfile_prefixes, standard_exec_prefix, "BINUTILS",
3804               PREFIX_PRIORITY_LAST, 1, 0);
3805   add_prefix (&startfile_prefixes, standard_exec_prefix_2, "BINUTILS",
3806               PREFIX_PRIORITY_LAST, 1, 0);
3807
3808   tooldir_prefix = concat (tooldir_base_prefix, spec_machine,
3809                            dir_separator_str, NULL);
3810
3811   /* If tooldir is relative, base it on exec_prefixes.  A relative
3812      tooldir lets us move the installed tree as a unit.
3813
3814      If GCC_EXEC_PREFIX is defined, then we want to add two relative
3815      directories, so that we can search both the user specified directory
3816      and the standard place.  */
3817
3818   if (!IS_ABSOLUTE_PATH (tooldir_prefix))
3819     {
3820       if (gcc_exec_prefix)
3821         {
3822           char *gcc_exec_tooldir_prefix
3823             = concat (gcc_exec_prefix, spec_machine, dir_separator_str,
3824                       spec_version, dir_separator_str, tooldir_prefix, NULL);
3825
3826           add_prefix (&exec_prefixes,
3827                       concat (gcc_exec_tooldir_prefix, "bin",
3828                               dir_separator_str, NULL),
3829                       NULL, PREFIX_PRIORITY_LAST, 0, 0);
3830           add_prefix (&startfile_prefixes,
3831                       concat (gcc_exec_tooldir_prefix, "lib",
3832                               dir_separator_str, NULL),
3833                       NULL, PREFIX_PRIORITY_LAST, 0, 1);
3834         }
3835
3836       tooldir_prefix = concat (standard_exec_prefix, spec_machine,
3837                                dir_separator_str, spec_version,
3838                                dir_separator_str, tooldir_prefix, NULL);
3839     }
3840
3841   add_prefix (&exec_prefixes,
3842               concat (tooldir_prefix, "bin", dir_separator_str, NULL),
3843               "BINUTILS", PREFIX_PRIORITY_LAST, 0, 0);
3844   add_prefix (&startfile_prefixes,
3845               concat (tooldir_prefix, "lib", dir_separator_str, NULL),
3846               "BINUTILS", PREFIX_PRIORITY_LAST, 0, 1);
3847
3848 #if defined(TARGET_SYSTEM_ROOT_RELOCATABLE) && !defined(VMS)
3849   /* If the normal TARGET_SYSTEM_ROOT is inside of $exec_prefix,
3850      then consider it to relocate with the rest of the GCC installation
3851      if GCC_EXEC_PREFIX is set.
3852      ``make_relative_prefix'' is not compiled for VMS, so don't call it.  */
3853   if (target_system_root && gcc_exec_prefix)
3854     {
3855       char *tmp_prefix = make_relative_prefix (argv[0],
3856                                                standard_bindir_prefix,
3857                                                target_system_root);
3858       if (tmp_prefix && access_check (tmp_prefix, F_OK) == 0)
3859         {
3860           target_system_root = tmp_prefix;
3861           target_system_root_changed = 1;
3862         }
3863     }
3864 #endif
3865
3866   /* More prefixes are enabled in main, after we read the specs file
3867      and determine whether this is cross-compilation or not.  */
3868
3869   /* Then create the space for the vectors and scan again.  */
3870
3871   switches = xmalloc ((n_switches + 1) * sizeof (struct switchstr));
3872   infiles = xmalloc ((n_infiles + 1) * sizeof (struct infile));
3873   n_switches = 0;
3874   n_infiles = 0;
3875   last_language_n_infiles = -1;
3876
3877   /* This, time, copy the text of each switch and store a pointer
3878      to the copy in the vector of switches.
3879      Store all the infiles in their vector.  */
3880
3881   for (i = 1; i < argc; i++)
3882     {
3883       /* Just skip the switches that were handled by the preceding loop.  */
3884 #ifdef MODIFY_TARGET_NAME
3885       is_modify_target_name = 0;
3886
3887       for (j = 0; j < ARRAY_SIZE (modify_target); j++)
3888         if (! strcmp (argv[i], modify_target[j].sw))
3889           is_modify_target_name = 1;
3890
3891       if (is_modify_target_name)
3892         ;
3893       else
3894 #endif
3895       if (! strncmp (argv[i], "-Wa,", 4))
3896         ;
3897       else if (! strncmp (argv[i], "-Wp,", 4))
3898         ;
3899       else if (! strcmp (argv[i], "-pass-exit-codes"))
3900         ;
3901       else if (! strcmp (argv[i], "-print-search-dirs"))
3902         ;
3903       else if (! strcmp (argv[i], "-print-libgcc-file-name"))
3904         ;
3905       else if (! strncmp (argv[i], "-print-file-name=", 17))
3906         ;
3907       else if (! strncmp (argv[i], "-print-prog-name=", 17))
3908         ;
3909       else if (! strcmp (argv[i], "-print-multi-lib"))
3910         ;
3911       else if (! strcmp (argv[i], "-print-multi-directory"))
3912         ;
3913       else if (! strcmp (argv[i], "-print-multi-os-directory"))
3914         ;
3915       else if (! strcmp (argv[i], "-ftarget-help"))
3916         ;
3917       else if (! strcmp (argv[i], "-fhelp"))
3918         ;
3919       else if (argv[i][0] == '+' && argv[i][1] == 'e')
3920         {
3921           /* Compensate for the +e options to the C++ front-end;
3922              they're there simply for cfront call-compatibility.  We do
3923              some magic in default_compilers to pass them down properly.
3924              Note we deliberately start at the `+' here, to avoid passing
3925              -e0 or -e1 down into the linker.  */
3926           switches[n_switches].part1 = &argv[i][0];
3927           switches[n_switches].args = 0;
3928           switches[n_switches].live_cond = SWITCH_OK;
3929           switches[n_switches].validated = 0;
3930           n_switches++;
3931         }
3932       else if (strncmp (argv[i], "-Wl,", 4) == 0)
3933         {
3934           int prev, j;
3935           /* Split the argument at commas.  */
3936           prev = 4;
3937           for (j = 4; argv[i][j]; j++)
3938             if (argv[i][j] == ',')
3939               {
3940                 infiles[n_infiles].language = "*";
3941                 infiles[n_infiles++].name
3942                   = save_string (argv[i] + prev, j - prev);
3943                 prev = j + 1;
3944               }
3945           /* Record the part after the last comma.  */
3946           infiles[n_infiles].language = "*";
3947           infiles[n_infiles++].name = argv[i] + prev;
3948         }
3949       else if (strcmp (argv[i], "-Xlinker") == 0)
3950         {
3951           infiles[n_infiles].language = "*";
3952           infiles[n_infiles++].name = argv[++i];
3953         }
3954       /* Xassembler and Xpreprocessor were already handled in the first argv
3955          scan, so all we need to do here is ignore them and their argument.  */
3956       else if (strcmp (argv[i], "-Xassembler") == 0)
3957         i++;
3958       else if (strcmp (argv[i], "-Xpreprocessor") == 0)
3959         i++;
3960       else if (strcmp (argv[i], "-l") == 0)
3961         { /* POSIX allows separation of -l and the lib arg;
3962              canonicalize by concatenating -l with its arg */
3963           infiles[n_infiles].language = "*";
3964           infiles[n_infiles++].name = concat ("-l", argv[++i], NULL);
3965         }
3966       else if (strncmp (argv[i], "-l", 2) == 0)
3967         {
3968           infiles[n_infiles].language = "*";
3969           infiles[n_infiles++].name = argv[i];
3970         }
3971       else if (strcmp (argv[i], "-specs") == 0)
3972         i++;
3973       else if (strncmp (argv[i], "-specs=", 7) == 0)
3974         ;
3975       else if (strcmp (argv[i], "-time") == 0)
3976         ;
3977       else if (strcmp (argv[i], "-###") == 0)
3978         ;
3979       else if (argv[i][0] == '-' && argv[i][1] != 0)
3980         {
3981           const char *p = &argv[i][1];
3982           int c = *p;
3983
3984           if (c == 'x')
3985             {
3986               if (p[1] == 0 && i + 1 == argc)
3987                 fatal ("argument to '-x' is missing");
3988               if (p[1] == 0)
3989                 spec_lang = argv[++i];
3990               else
3991                 spec_lang = p + 1;
3992               if (! strcmp (spec_lang, "none"))
3993                 /* Suppress the warning if -xnone comes after the last input
3994                    file, because alternate command interfaces like g++ might
3995                    find it useful to place -xnone after each input file.  */
3996                 spec_lang = 0;
3997               else
3998                 last_language_n_infiles = n_infiles;
3999               continue;
4000             }
4001           switches[n_switches].part1 = p;
4002           /* Deal with option arguments in separate argv elements.  */
4003           if ((SWITCH_TAKES_ARG (c) > (p[1] != 0))
4004               || WORD_SWITCH_TAKES_ARG (p))
4005             {
4006               int j = 0;
4007               int n_args = WORD_SWITCH_TAKES_ARG (p);
4008
4009               if (n_args == 0)
4010                 {
4011                   /* Count only the option arguments in separate argv elements.  */
4012                   n_args = SWITCH_TAKES_ARG (c) - (p[1] != 0);
4013                 }
4014               if (i + n_args >= argc)
4015                 fatal ("argument to '-%s' is missing", p);
4016               switches[n_switches].args
4017                 = xmalloc ((n_args + 1) * sizeof(const char *));
4018               while (j < n_args)
4019                 switches[n_switches].args[j++] = argv[++i];
4020               /* Null-terminate the vector.  */
4021               switches[n_switches].args[j] = 0;
4022             }
4023           else if (strchr (switches_need_spaces, c))
4024             {
4025               /* On some systems, ld cannot handle some options without
4026                  a space.  So split the option from its argument.  */
4027               char *part1 = xmalloc (2);
4028               part1[0] = c;
4029               part1[1] = '\0';
4030
4031               switches[n_switches].part1 = part1;
4032               switches[n_switches].args = xmalloc (2 * sizeof (const char *));
4033               switches[n_switches].args[0] = xstrdup (p+1);
4034               switches[n_switches].args[1] = 0;
4035             }
4036           else
4037             switches[n_switches].args = 0;
4038
4039           switches[n_switches].live_cond = SWITCH_OK;
4040           switches[n_switches].validated = 0;
4041           switches[n_switches].ordering = 0;
4042           /* These are always valid, since gcc.c itself understands them.  */
4043           if (!strcmp (p, "save-temps")
4044               || !strcmp (p, "static-libgcc")
4045               || !strcmp (p, "shared-libgcc")
4046               || !strcmp (p, "pipe"))
4047             switches[n_switches].validated = 1;
4048           else
4049             {
4050               char ch = switches[n_switches].part1[0];
4051               if (ch == 'B')
4052                 switches[n_switches].validated = 1;
4053             }
4054           n_switches++;
4055         }
4056       else
4057         {
4058 #ifdef HAVE_TARGET_OBJECT_SUFFIX
4059           argv[i] = convert_filename (argv[i], 0, access (argv[i], F_OK));
4060 #endif
4061
4062           if (strcmp (argv[i], "-") != 0 && access (argv[i], F_OK) < 0)
4063             {
4064               perror_with_name (argv[i]);
4065               error_count++;
4066             }
4067           else
4068             {
4069               infiles[n_infiles].language = spec_lang;
4070               infiles[n_infiles++].name = argv[i];
4071             }
4072         }
4073     }
4074
4075   if (n_infiles == last_language_n_infiles && spec_lang != 0)
4076     error ("warning: '-x %s' after last input file has no effect", spec_lang);
4077
4078   /* Ensure we only invoke each subprocess once.  */
4079   if (target_help_flag || print_help_list)
4080     {
4081       n_infiles = 1;
4082
4083       /* Create a dummy input file, so that we can pass --target-help on to
4084          the various sub-processes.  */
4085       infiles[0].language = "c";
4086       infiles[0].name   = "help-dummy";
4087
4088       if (target_help_flag)
4089         {
4090           switches[n_switches].part1     = "--target-help";
4091           switches[n_switches].args      = 0;
4092           switches[n_switches].live_cond = SWITCH_OK;
4093           switches[n_switches].validated = 0;
4094
4095           n_switches++;
4096         }
4097
4098       if (print_help_list)
4099         {
4100           switches[n_switches].part1     = "--help";
4101           switches[n_switches].args      = 0;
4102           switches[n_switches].live_cond = SWITCH_OK;
4103           switches[n_switches].validated = 0;
4104
4105           n_switches++;
4106         }
4107     }
4108
4109   switches[n_switches].part1 = 0;
4110   infiles[n_infiles].name = 0;
4111 }
4112
4113 /* Store switches not filtered out by %<S in spec in COLLECT_GCC_OPTIONS
4114    and place that in the environment.  */
4115
4116 static void
4117 set_collect_gcc_options (void)
4118 {
4119   int i;
4120   int first_time;
4121
4122   /* Build COLLECT_GCC_OPTIONS to have all of the options specified to
4123      the compiler.  */
4124   obstack_grow (&collect_obstack, "COLLECT_GCC_OPTIONS=",
4125                 sizeof ("COLLECT_GCC_OPTIONS=") - 1);
4126
4127   first_time = TRUE;
4128   for (i = 0; (int) i < n_switches; i++)
4129     {
4130       const char *const *args;
4131       const char *p, *q;
4132       if (!first_time)
4133         obstack_grow (&collect_obstack, " ", 1);
4134
4135       first_time = FALSE;
4136
4137       /* Ignore elided switches.  */
4138       if (switches[i].live_cond == SWITCH_IGNORE)
4139         continue;
4140
4141       obstack_grow (&collect_obstack, "'-", 2);
4142       q = switches[i].part1;
4143       while ((p = strchr (q, '\'')))
4144         {
4145           obstack_grow (&collect_obstack, q, p - q);
4146           obstack_grow (&collect_obstack, "'\\''", 4);
4147           q = ++p;
4148         }
4149       obstack_grow (&collect_obstack, q, strlen (q));
4150       obstack_grow (&collect_obstack, "'", 1);
4151
4152       for (args = switches[i].args; args && *args; args++)
4153         {
4154           obstack_grow (&collect_obstack, " '", 2);
4155           q = *args;
4156           while ((p = strchr (q, '\'')))
4157             {
4158               obstack_grow (&collect_obstack, q, p - q);
4159               obstack_grow (&collect_obstack, "'\\''", 4);
4160               q = ++p;
4161             }
4162           obstack_grow (&collect_obstack, q, strlen (q));
4163           obstack_grow (&collect_obstack, "'", 1);
4164         }
4165     }
4166   obstack_grow (&collect_obstack, "\0", 1);
4167   putenv (XOBFINISH (&collect_obstack, char *));
4168 }
4169 \f
4170 /* Process a spec string, accumulating and running commands.  */
4171
4172 /* These variables describe the input file name.
4173    input_file_number is the index on outfiles of this file,
4174    so that the output file name can be stored for later use by %o.
4175    input_basename is the start of the part of the input file
4176    sans all directory names, and basename_length is the number
4177    of characters starting there excluding the suffix .c or whatever.  */
4178
4179 static const char *input_filename;
4180 static int input_file_number;
4181 size_t input_filename_length;
4182 static int basename_length;
4183 static int suffixed_basename_length;
4184 static const char *input_basename;
4185 static const char *input_suffix;
4186 #ifndef HOST_LACKS_INODE_NUMBERS
4187 static struct stat input_stat;
4188 #endif
4189 static int input_stat_set;
4190
4191 /* The compiler used to process the current input file.  */
4192 static struct compiler *input_file_compiler;
4193
4194 /* These are variables used within do_spec and do_spec_1.  */
4195
4196 /* Nonzero if an arg has been started and not yet terminated
4197    (with space, tab or newline).  */
4198 static int arg_going;
4199
4200 /* Nonzero means %d or %g has been seen; the next arg to be terminated
4201    is a temporary file name.  */
4202 static int delete_this_arg;
4203
4204 /* Nonzero means %w has been seen; the next arg to be terminated
4205    is the output file name of this compilation.  */
4206 static int this_is_output_file;
4207
4208 /* Nonzero means %s has been seen; the next arg to be terminated
4209    is the name of a library file and we should try the standard
4210    search dirs for it.  */
4211 static int this_is_library_file;
4212
4213 /* Nonzero means that the input of this command is coming from a pipe.  */
4214 static int input_from_pipe;
4215
4216 /* Nonnull means substitute this for any suffix when outputting a switches
4217    arguments.  */
4218 static const char *suffix_subst;
4219
4220 /* Process the spec SPEC and run the commands specified therein.
4221    Returns 0 if the spec is successfully processed; -1 if failed.  */
4222
4223 int
4224 do_spec (const char *spec)
4225 {
4226   int value;
4227
4228   value = do_spec_2 (spec);
4229
4230   /* Force out any unfinished command.
4231      If -pipe, this forces out the last command if it ended in `|'.  */
4232   if (value == 0)
4233     {
4234       if (argbuf_index > 0 && !strcmp (argbuf[argbuf_index - 1], "|"))
4235         argbuf_index--;
4236
4237       set_collect_gcc_options ();
4238
4239       if (argbuf_index > 0)
4240         value = execute ();
4241     }
4242
4243   return value;
4244 }
4245
4246 static int
4247 do_spec_2 (const char *spec)
4248 {
4249   const char *string;
4250   int result;
4251
4252   clear_args ();
4253   arg_going = 0;
4254   delete_this_arg = 0;
4255   this_is_output_file = 0;
4256   this_is_library_file = 0;
4257   input_from_pipe = 0;
4258   suffix_subst = NULL;
4259
4260   result = do_spec_1 (spec, 0, NULL);
4261
4262   /* End any pending argument.  */
4263   if (arg_going)
4264     {
4265       obstack_1grow (&obstack, 0);
4266       string = XOBFINISH (&obstack, const char *);
4267       if (this_is_library_file)
4268         string = find_file (string);
4269       store_arg (string, delete_this_arg, this_is_output_file);
4270       if (this_is_output_file)
4271         outfiles[input_file_number] = string;
4272       arg_going = 0;
4273     }
4274
4275   return result;
4276 }
4277
4278
4279 /* Process the given spec string and add any new options to the end
4280    of the switches/n_switches array.  */
4281
4282 static void
4283 do_option_spec (const char *name, const char *spec)
4284 {
4285   unsigned int i, value_count, value_len;
4286   const char *p, *q, *value;
4287   char *tmp_spec, *tmp_spec_p;
4288
4289   if (configure_default_options[0].name == NULL)
4290     return;
4291
4292   for (i = 0; i < ARRAY_SIZE (configure_default_options); i++)
4293     if (strcmp (configure_default_options[i].name, name) == 0)
4294       break;
4295   if (i == ARRAY_SIZE (configure_default_options))
4296     return;
4297
4298   value = configure_default_options[i].value;
4299   value_len = strlen (value);
4300
4301   /* Compute the size of the final spec.  */
4302   value_count = 0;
4303   p = spec;
4304   while ((p = strstr (p, "%(VALUE)")) != NULL)
4305     {
4306       p ++;
4307       value_count ++;
4308     }
4309
4310   /* Replace each %(VALUE) by the specified value.  */
4311   tmp_spec = alloca (strlen (spec) + 1
4312                      + value_count * (value_len - strlen ("%(VALUE)")));
4313   tmp_spec_p = tmp_spec;
4314   q = spec;
4315   while ((p = strstr (q, "%(VALUE)")) != NULL)
4316     {
4317       memcpy (tmp_spec_p, q, p - q);
4318       tmp_spec_p = tmp_spec_p + (p - q);
4319       memcpy (tmp_spec_p, value, value_len);
4320       tmp_spec_p += value_len;
4321       q = p + strlen ("%(VALUE)");
4322     }
4323   strcpy (tmp_spec_p, q);
4324
4325   do_self_spec (tmp_spec);
4326 }
4327
4328 /* Process the given spec string and add any new options to the end
4329    of the switches/n_switches array.  */
4330
4331 static void
4332 do_self_spec (const char *spec)
4333 {
4334   do_spec_2 (spec);
4335   do_spec_1 (" ", 0, NULL);
4336
4337   if (argbuf_index > 0)
4338     {
4339       int i, first;
4340
4341       first = n_switches;
4342       n_switches += argbuf_index;
4343       switches = xrealloc (switches,
4344                            sizeof (struct switchstr) * (n_switches + 1));
4345
4346       switches[n_switches] = switches[first];
4347       for (i = 0; i < argbuf_index; i++)
4348         {
4349           struct switchstr *sw;
4350
4351           /* Each switch should start with '-'.  */
4352           if (argbuf[i][0] != '-')
4353             fatal ("switch '%s' does not start with '-'", argbuf[i]);
4354
4355           sw = &switches[i + first];
4356           sw->part1 = &argbuf[i][1];
4357           sw->args = 0;
4358           sw->live_cond = SWITCH_OK;
4359           sw->validated = 0;
4360           sw->ordering = 0;
4361         }
4362     }
4363 }
4364
4365 void
4366 do_spec_path (struct prefix_list *pl, const char *option,
4367               int omit_if_relative, int separate_options,
4368               int only_subdir,
4369               const char *dir_for_machine_suffix,
4370               const char *dir_for_no_suffix)
4371 {
4372   static size_t bufsize = 0;
4373   static char *buffer;
4374   int idx;
4375   bool multilib_p = false;
4376
4377   /* Used on systems which record the specified -L dirs
4378      and use them to search for dynamic linking.  */
4379   /* Relative directories always come from -B,
4380      and it is better not to use them for searching
4381      at run time.  In particular, stage1 loses.  */
4382   if (omit_if_relative
4383       && !IS_ABSOLUTE_PATH (pl->prefix))
4384     return;
4385
4386   /* Try subdirectory if there is one.  */
4387   if (machine_suffix && dir_for_machine_suffix)
4388     {
4389       if (strlen (pl->prefix) + strlen (machine_suffix)
4390           >= bufsize)
4391         bufsize = (strlen (pl->prefix)
4392                   + strlen (machine_suffix)) * 2 + 1;
4393       buffer = xrealloc (buffer, bufsize);
4394       strcpy (buffer, pl->prefix);
4395       strcat (buffer, machine_suffix);
4396       if (is_directory (buffer, dir_for_machine_suffix, 1))
4397         {
4398           multilib_p = true;
4399           do_spec_1 (option, separate_options, NULL);
4400           if (separate_options)
4401             do_spec_1 (" ", 0, NULL);
4402           do_spec_1 (buffer, 1, NULL);
4403           do_spec_1 (dir_for_machine_suffix, 1, NULL);
4404           /* Make this a separate argument.  */
4405           do_spec_1 (" ", 0, NULL);
4406         }
4407     }
4408   if (!pl->require_machine_suffix && dir_for_no_suffix)
4409     {
4410       if (is_directory (pl->prefix, dir_for_no_suffix, 1))
4411         {
4412           multilib_p = true;
4413           do_spec_1 (option, separate_options, NULL);
4414           if (separate_options)
4415             do_spec_1 (" ", 0, NULL);
4416           do_spec_1 (pl->prefix, 1, NULL);
4417           do_spec_1 (dir_for_no_suffix, 1, NULL);
4418           /* Make this a separate argument.  */
4419           do_spec_1 (" ", 0, NULL);
4420         }
4421     }
4422
4423   if (only_subdir || multilib_p)
4424     return;
4425
4426   if (machine_suffix)
4427     {
4428       if (is_directory (pl->prefix, machine_suffix, 1))
4429         {
4430           do_spec_1 (option, separate_options, NULL);
4431           if (separate_options)
4432             do_spec_1 (" ", 0, NULL);
4433           do_spec_1 (pl->prefix, 1, NULL);
4434           /* Remove slash from machine_suffix.  */
4435           if (strlen (machine_suffix) >= bufsize)
4436             bufsize = strlen (machine_suffix) * 2 + 1;
4437           buffer = xrealloc (buffer, bufsize);
4438           strcpy (buffer, machine_suffix);
4439           idx = strlen (buffer);
4440           if (IS_DIR_SEPARATOR (buffer[idx - 1]))
4441             buffer[idx - 1] = 0;
4442           do_spec_1 (buffer, 1, NULL);
4443           /* Make this a separate argument.  */
4444           do_spec_1 (" ", 0, NULL);
4445         }
4446     }
4447   if (!pl->require_machine_suffix)
4448     {
4449       if (is_directory (pl->prefix, "", 1))
4450         {
4451           do_spec_1 (option, separate_options, NULL);
4452           if (separate_options)
4453             do_spec_1 (" ", 0, NULL);
4454           /* Remove slash from pl->prefix.  */
4455           if (strlen (pl->prefix) >= bufsize)
4456             bufsize = strlen (pl->prefix) * 2 + 1;
4457           buffer = xrealloc (buffer, bufsize);
4458           strcpy (buffer, pl->prefix);
4459           idx = strlen (buffer);
4460           if (IS_DIR_SEPARATOR (buffer[idx - 1]))
4461             buffer[idx - 1] = 0;
4462           do_spec_1 (buffer, 1, NULL);
4463           /* Make this a separate argument.  */
4464           do_spec_1 (" ", 0, NULL);
4465         }
4466     }
4467 }
4468
4469 /* Process the sub-spec SPEC as a portion of a larger spec.
4470    This is like processing a whole spec except that we do
4471    not initialize at the beginning and we do not supply a
4472    newline by default at the end.
4473    INSWITCH nonzero means don't process %-sequences in SPEC;
4474    in this case, % is treated as an ordinary character.
4475    This is used while substituting switches.
4476    INSWITCH nonzero also causes SPC not to terminate an argument.
4477
4478    Value is zero unless a line was finished
4479    and the command on that line reported an error.  */
4480
4481 static int
4482 do_spec_1 (const char *spec, int inswitch, const char *soft_matched_part)
4483 {
4484   const char *p = spec;
4485   int c;
4486   int i;
4487   const char *string;
4488   int value;
4489
4490   while ((c = *p++))
4491     /* If substituting a switch, treat all chars like letters.
4492        Otherwise, NL, SPC, TAB and % are special.  */
4493     switch (inswitch ? 'a' : c)
4494       {
4495       case '\n':
4496         /* End of line: finish any pending argument,
4497            then run the pending command if one has been started.  */
4498         if (arg_going)
4499           {
4500             obstack_1grow (&obstack, 0);
4501             string = XOBFINISH (&obstack, const char *);
4502             if (this_is_library_file)
4503               string = find_file (string);
4504             store_arg (string, delete_this_arg, this_is_output_file);
4505             if (this_is_output_file)
4506               outfiles[input_file_number] = string;
4507           }
4508         arg_going = 0;
4509
4510         if (argbuf_index > 0 && !strcmp (argbuf[argbuf_index - 1], "|"))
4511           {
4512             /* A `|' before the newline means use a pipe here,
4513                but only if -pipe was specified.
4514                Otherwise, execute now and don't pass the `|' as an arg.  */
4515             if (use_pipes)
4516               {
4517                 input_from_pipe = 1;
4518                 break;
4519               }
4520             else
4521               argbuf_index--;
4522           }
4523
4524         set_collect_gcc_options ();
4525
4526         if (argbuf_index > 0)
4527           {
4528             value = execute ();
4529             if (value)
4530               return value;
4531           }
4532         /* Reinitialize for a new command, and for a new argument.  */
4533         clear_args ();
4534         arg_going = 0;
4535         delete_this_arg = 0;
4536         this_is_output_file = 0;
4537         this_is_library_file = 0;
4538         input_from_pipe = 0;
4539         break;
4540
4541       case '|':
4542         /* End any pending argument.  */
4543         if (arg_going)
4544           {
4545             obstack_1grow (&obstack, 0);
4546             string = XOBFINISH (&obstack, const char *);
4547             if (this_is_library_file)
4548               string = find_file (string);
4549             store_arg (string, delete_this_arg, this_is_output_file);
4550             if (this_is_output_file)
4551               outfiles[input_file_number] = string;
4552           }
4553
4554         /* Use pipe */
4555         obstack_1grow (&obstack, c);
4556         arg_going = 1;
4557         break;
4558
4559       case '\t':
4560       case ' ':
4561         /* Space or tab ends an argument if one is pending.  */
4562         if (arg_going)
4563           {
4564             obstack_1grow (&obstack, 0);
4565             string = XOBFINISH (&obstack, const char *);
4566             if (this_is_library_file)
4567               string = find_file (string);
4568             store_arg (string, delete_this_arg, this_is_output_file);
4569             if (this_is_output_file)
4570               outfiles[input_file_number] = string;
4571           }
4572         /* Reinitialize for a new argument.  */
4573         arg_going = 0;
4574         delete_this_arg = 0;
4575         this_is_output_file = 0;
4576         this_is_library_file = 0;
4577         break;
4578
4579       case '%':
4580         switch (c = *p++)
4581           {
4582           case 0:
4583             fatal ("spec '%s' invalid", spec);
4584
4585           case 'b':
4586             obstack_grow (&obstack, input_basename, basename_length);
4587             arg_going = 1;
4588             break;
4589
4590           case 'B':
4591             obstack_grow (&obstack, input_basename, suffixed_basename_length);
4592             arg_going = 1;
4593             break;
4594
4595           case 'd':
4596             delete_this_arg = 2;
4597             break;
4598
4599           /* Dump out the directories specified with LIBRARY_PATH,
4600              followed by the absolute directories
4601              that we search for startfiles.  */
4602           case 'D':
4603             {
4604               struct prefix_list *pl = startfile_prefixes.plist;
4605
4606               for (; pl; pl = pl->next)
4607                 {
4608                   const char *no_suffix_multilib_dir;
4609
4610                   no_suffix_multilib_dir = pl->os_multilib ? multilib_os_dir
4611                                            : multilib_dir;
4612                   /* Do not separate options, include non-multilibbed variant.  */
4613                   do_spec_path (pl, "-L",
4614 #ifdef RELATIVE_PREFIX_NOT_LINKDIR
4615                                 1,
4616 #else
4617                                 0,
4618 #endif
4619                                 0, 0, multilib_dir, no_suffix_multilib_dir);
4620                 }
4621             }
4622             break;
4623
4624           case 'e':
4625             /* %efoo means report an error with `foo' as error message
4626                and don't execute any more commands for this file.  */
4627             {
4628               const char *q = p;
4629               char *buf;
4630               while (*p != 0 && *p != '\n')
4631                 p++;
4632               buf = alloca (p - q + 1);
4633               strncpy (buf, q, p - q);
4634               buf[p - q] = 0;
4635               error ("%s", buf);
4636               return -1;
4637             }
4638             break;
4639           case 'n':
4640             /* %nfoo means report a notice with `foo' on stderr.  */
4641             {
4642               const char *q = p;
4643               char *buf;
4644               while (*p != 0 && *p != '\n')
4645                 p++;
4646               buf = alloca (p - q + 1);
4647               strncpy (buf, q, p - q);
4648               buf[p - q] = 0;
4649               notice ("%s\n", buf);
4650               if (*p)
4651                 p++;
4652             }
4653             break;
4654
4655           case 'j':
4656             {
4657               struct stat st;
4658
4659               /* If save_temps_flag is off, and the HOST_BIT_BUCKET is
4660                  defined, and it is not a directory, and it is
4661                  writable, use it.  Otherwise, treat this like any
4662                  other temporary file.  */
4663
4664               if ((!save_temps_flag)
4665                   && (stat (HOST_BIT_BUCKET, &st) == 0) && (!S_ISDIR (st.st_mode))
4666                   && (access (HOST_BIT_BUCKET, W_OK) == 0))
4667                 {
4668                   obstack_grow (&obstack, HOST_BIT_BUCKET,
4669                                 strlen (HOST_BIT_BUCKET));
4670                   delete_this_arg = 0;
4671                   arg_going = 1;
4672                   break;
4673                 }
4674             }
4675             goto create_temp_file;
4676           case '|':
4677             if (use_pipes)
4678               {
4679                 obstack_1grow (&obstack, '-');
4680                 delete_this_arg = 0;
4681                 arg_going = 1;
4682
4683                 /* consume suffix */
4684                 while (*p == '.' || ISALPHA ((unsigned char) *p))
4685                   p++;
4686                 if (p[0] == '%' && p[1] == 'O')
4687                   p += 2;
4688
4689                 break;
4690               }
4691             goto create_temp_file;
4692           case 'm':
4693             if (use_pipes)
4694               {
4695                 /* consume suffix */
4696                 while (*p == '.' || ISALPHA ((unsigned char) *p))
4697                   p++;
4698                 if (p[0] == '%' && p[1] == 'O')
4699                   p += 2;
4700
4701                 break;
4702               }
4703             goto create_temp_file;
4704           case 'g':
4705           case 'u':
4706           case 'U':
4707           create_temp_file:
4708               {
4709                 struct temp_name *t;
4710                 int suffix_length;
4711                 const char *suffix = p;
4712                 char *saved_suffix = NULL;
4713
4714                 while (*p == '.' || ISALPHA ((unsigned char) *p))
4715                   p++;
4716                 suffix_length = p - suffix;
4717                 if (p[0] == '%' && p[1] == 'O')
4718                   {
4719                     p += 2;
4720                     /* We don't support extra suffix characters after %O.  */
4721                     if (*p == '.' || ISALPHA ((unsigned char) *p))
4722                       fatal ("spec '%s' has invalid '%%0%c'", spec, *p);
4723                     if (suffix_length == 0)
4724                       suffix = TARGET_OBJECT_SUFFIX;
4725                     else
4726                       {
4727                         saved_suffix
4728                           = xmalloc (suffix_length
4729                                      + strlen (TARGET_OBJECT_SUFFIX));
4730                         strncpy (saved_suffix, suffix, suffix_length);
4731                         strcpy (saved_suffix + suffix_length,
4732                                 TARGET_OBJECT_SUFFIX);
4733                       }
4734                     suffix_length += strlen (TARGET_OBJECT_SUFFIX);
4735                   }
4736
4737                 /* If the input_filename has the same suffix specified
4738                    for the %g, %u, or %U, and -save-temps is specified,
4739                    we could end up using that file as an intermediate
4740                    thus clobbering the user's source file (.e.g.,
4741                    gcc -save-temps foo.s would clobber foo.s with the
4742                    output of cpp0).  So check for this condition and
4743                    generate a temp file as the intermediate.  */
4744
4745                 if (save_temps_flag)
4746                   {
4747                     temp_filename_length = basename_length + suffix_length;
4748                     temp_filename = alloca (temp_filename_length + 1);
4749                     strncpy ((char *) temp_filename, input_basename, basename_length);
4750                     strncpy ((char *) temp_filename + basename_length, suffix,
4751                              suffix_length);
4752                     *((char *) temp_filename + temp_filename_length) = '\0';
4753                     if (strcmp (temp_filename, input_filename) != 0)
4754                       {
4755 #ifndef HOST_LACKS_INODE_NUMBERS
4756                         struct stat st_temp;
4757
4758                         /* Note, set_input() resets input_stat_set to 0.  */
4759                         if (input_stat_set == 0)
4760                           {
4761                             input_stat_set = stat (input_filename, &input_stat);
4762                             if (input_stat_set >= 0)
4763                               input_stat_set = 1;
4764                           }
4765
4766                         /* If we have the stat for the input_filename
4767                            and we can do the stat for the temp_filename
4768                            then the they could still refer to the same
4769                            file if st_dev/st_ino's are the same.  */
4770                         if (input_stat_set != 1
4771                             || stat (temp_filename, &st_temp) < 0
4772                             || input_stat.st_dev != st_temp.st_dev
4773                             || input_stat.st_ino != st_temp.st_ino)
4774 #else
4775                         /* Just compare canonical pathnames.  */
4776                         char* input_realname = lrealpath (input_filename);
4777                         char* temp_realname = lrealpath (temp_filename);
4778                         bool files_differ = strcmp (input_realname, temp_realname);
4779                         free (input_realname);
4780                         free (temp_realname);
4781                         if (files_differ)       
4782 #endif
4783                           {
4784                             temp_filename = save_string (temp_filename,
4785                                                          temp_filename_length + 1);
4786                             obstack_grow (&obstack, temp_filename,
4787                                                     temp_filename_length);
4788                             arg_going = 1;
4789                             delete_this_arg = 0;
4790                             break;
4791                           }
4792                       }
4793                   }
4794
4795                 /* See if we already have an association of %g/%u/%U and
4796                    suffix.  */
4797                 for (t = temp_names; t; t = t->next)
4798                   if (t->length == suffix_length
4799                       && strncmp (t->suffix, suffix, suffix_length) == 0
4800                       && t->unique == (c == 'u' || c == 'U' || c == 'j'))
4801                     break;
4802
4803                 /* Make a new association if needed.  %u and %j
4804                    require one.  */
4805                 if (t == 0 || c == 'u' || c == 'j')
4806                   {
4807                     if (t == 0)
4808                       {
4809                         t = xmalloc (sizeof (struct temp_name));
4810                         t->next = temp_names;
4811                         temp_names = t;
4812                       }
4813                     t->length = suffix_length;
4814                     if (saved_suffix)
4815                       {
4816                         t->suffix = saved_suffix;
4817                         saved_suffix = NULL;
4818                       }
4819                     else
4820                       t->suffix = save_string (suffix, suffix_length);
4821                     t->unique = (c == 'u' || c == 'U' || c == 'j');
4822                     temp_filename = make_temp_file (t->suffix);
4823                     temp_filename_length = strlen (temp_filename);
4824                     t->filename = temp_filename;
4825                     t->filename_length = temp_filename_length;
4826                   }
4827
4828                 if (saved_suffix)
4829                   free (saved_suffix);
4830
4831                 obstack_grow (&obstack, t->filename, t->filename_length);
4832                 delete_this_arg = 1;
4833               }
4834             arg_going = 1;
4835             break;
4836
4837           case 'i':
4838             if (combine_inputs)
4839               {
4840                 for (i = 0; (int) i < n_infiles; i++)
4841                   if ((!infiles[i].language) || (infiles[i].language[0] != '*'))
4842                     if (infiles[i].incompiler == input_file_compiler)
4843                       {
4844                         store_arg (infiles[i].name, 0, 0);
4845                         infiles[i].compiled = true;
4846                       }
4847               }
4848             else
4849               {
4850                 obstack_grow (&obstack, input_filename, input_filename_length);
4851                 arg_going = 1;
4852               }
4853             break;
4854
4855           case 'I':
4856             {
4857               struct prefix_list *pl = include_prefixes.plist;
4858
4859               if (gcc_exec_prefix)
4860                 {
4861                   do_spec_1 ("-iprefix", 1, NULL);
4862                   /* Make this a separate argument.  */
4863                   do_spec_1 (" ", 0, NULL);
4864                   do_spec_1 (gcc_exec_prefix, 1, NULL);
4865                   do_spec_1 (" ", 0, NULL);
4866                 }
4867
4868               if (target_system_root_changed ||
4869                   (target_system_root && target_sysroot_hdrs_suffix))
4870                 {
4871                   do_spec_1 ("-isysroot", 1, NULL);
4872                   /* Make this a separate argument.  */
4873                   do_spec_1 (" ", 0, NULL);
4874                   do_spec_1 (target_system_root, 1, NULL);
4875                   if (target_sysroot_hdrs_suffix)
4876                     do_spec_1 (target_sysroot_hdrs_suffix, 1, NULL);
4877                   do_spec_1 (" ", 0, NULL);
4878                 }
4879
4880               for (; pl; pl = pl->next)
4881                 /* Separate options, don't include non-suffixed variant.  */
4882                 do_spec_path (pl, "-isystem", 0, 1, 1, "include", "include");
4883             }
4884             break;
4885
4886           case 'o':
4887             {
4888               int max = n_infiles;
4889               max += lang_specific_extra_outfiles;
4890
4891               for (i = 0; i < max; i++)
4892                 if (outfiles[i])
4893                   store_arg (outfiles[i], 0, 0);
4894               break;
4895             }
4896
4897           case 'O':
4898             obstack_grow (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
4899             arg_going = 1;
4900             break;
4901
4902           case 's':
4903             this_is_library_file = 1;
4904             break;
4905
4906           case 'V':
4907             outfiles[input_file_number] = NULL;
4908             break;
4909
4910           case 'w':
4911             this_is_output_file = 1;
4912             break;
4913
4914           case 'W':
4915             {
4916               int cur_index = argbuf_index;
4917               /* Handle the {...} following the %W.  */
4918               if (*p != '{')
4919                 fatal ("spec '%s' has invalid '%%W%c", spec, *p);
4920               p = handle_braces (p + 1);
4921               if (p == 0)
4922                 return -1;
4923               /* End any pending argument.  */
4924               if (arg_going)
4925                 {
4926                   obstack_1grow (&obstack, 0);
4927                   string = XOBFINISH (&obstack, const char *);
4928                   if (this_is_library_file)
4929                     string = find_file (string);
4930                   store_arg (string, delete_this_arg, this_is_output_file);
4931                   if (this_is_output_file)
4932                     outfiles[input_file_number] = string;
4933                   arg_going = 0;
4934                 }
4935               /* If any args were output, mark the last one for deletion
4936                  on failure.  */
4937               if (argbuf_index != cur_index)
4938                 record_temp_file (argbuf[argbuf_index - 1], 0, 1);
4939               break;
4940             }
4941
4942           /* %x{OPTION} records OPTION for %X to output.  */
4943           case 'x':
4944             {
4945               const char *p1 = p;
4946               char *string;
4947
4948               /* Skip past the option value and make a copy.  */
4949               if (*p != '{')
4950                 fatal ("spec '%s' has invalid '%%x%c'", spec, *p);
4951               while (*p++ != '}')
4952                 ;
4953               string = save_string (p1 + 1, p - p1 - 2);
4954
4955               /* See if we already recorded this option.  */
4956               for (i = 0; i < n_linker_options; i++)
4957                 if (! strcmp (string, linker_options[i]))
4958                   {
4959                     free (string);
4960                     return 0;
4961                   }
4962
4963               /* This option is new; add it.  */
4964               add_linker_option (string, strlen (string));
4965             }
4966             break;
4967
4968           /* Dump out the options accumulated previously using %x.  */
4969           case 'X':
4970             for (i = 0; i < n_linker_options; i++)
4971               {
4972                 do_spec_1 (linker_options[i], 1, NULL);
4973                 /* Make each accumulated option a separate argument.  */
4974                 do_spec_1 (" ", 0, NULL);
4975               }
4976             break;
4977
4978           /* Dump out the options accumulated previously using -Wa,.  */
4979           case 'Y':
4980             for (i = 0; i < n_assembler_options; i++)
4981               {
4982                 do_spec_1 (assembler_options[i], 1, NULL);
4983                 /* Make each accumulated option a separate argument.  */
4984                 do_spec_1 (" ", 0, NULL);
4985               }
4986             break;
4987
4988           /* Dump out the options accumulated previously using -Wp,.  */
4989           case 'Z':
4990             for (i = 0; i < n_preprocessor_options; i++)
4991               {
4992                 do_spec_1 (preprocessor_options[i], 1, NULL);
4993                 /* Make each accumulated option a separate argument.  */
4994                 do_spec_1 (" ", 0, NULL);
4995               }
4996             break;
4997
4998             /* Here are digits and numbers that just process
4999                a certain constant string as a spec.  */
5000
5001           case '1':
5002             value = do_spec_1 (cc1_spec, 0, NULL);
5003             if (value != 0)
5004               return value;
5005             break;
5006
5007           case '2':
5008             value = do_spec_1 (cc1plus_spec, 0, NULL);
5009             if (value != 0)
5010               return value;
5011             break;
5012
5013           case 'a':
5014             value = do_spec_1 (asm_spec, 0, NULL);
5015             if (value != 0)
5016               return value;
5017             break;
5018
5019           case 'A':
5020             value = do_spec_1 (asm_final_spec, 0, NULL);
5021             if (value != 0)
5022               return value;
5023             break;
5024
5025           case 'C':
5026             {
5027               const char *const spec
5028                 = (input_file_compiler->cpp_spec
5029                    ? input_file_compiler->cpp_spec
5030                    : cpp_spec);
5031               value = do_spec_1 (spec, 0, NULL);
5032               if (value != 0)
5033                 return value;
5034             }
5035             break;
5036
5037           case 'E':
5038             value = do_spec_1 (endfile_spec, 0, NULL);
5039             if (value != 0)
5040               return value;
5041             break;
5042
5043           case 'l':
5044             value = do_spec_1 (link_spec, 0, NULL);
5045             if (value != 0)
5046               return value;
5047             break;
5048
5049           case 'L':
5050             value = do_spec_1 (lib_spec, 0, NULL);
5051             if (value != 0)
5052               return value;
5053             break;
5054
5055           case 'G':
5056             value = do_spec_1 (libgcc_spec, 0, NULL);
5057             if (value != 0)
5058               return value;
5059             break;
5060
5061           case 'R':
5062             /* We assume there is a directory
5063                separator at the end of this string.  */
5064             if (target_system_root)
5065               {
5066                 obstack_grow (&obstack, target_system_root,
5067                               strlen (target_system_root));
5068                 if (target_sysroot_suffix)
5069                   obstack_grow (&obstack, target_sysroot_suffix,
5070                                 strlen (target_sysroot_suffix));
5071               }
5072             break;
5073
5074           case 'S':
5075             value = do_spec_1 (startfile_spec, 0, NULL);
5076             if (value != 0)
5077               return value;
5078             break;
5079
5080             /* Here we define characters other than letters and digits.  */
5081
5082           case '{':
5083             p = handle_braces (p);
5084             if (p == 0)
5085               return -1;
5086             break;
5087
5088           case ':':
5089             p = handle_spec_function (p);
5090             if (p == 0)
5091               return -1;
5092             break;
5093
5094           case '%':
5095             obstack_1grow (&obstack, '%');
5096             break;
5097
5098           case '.':
5099             {
5100               unsigned len = 0;
5101
5102               while (p[len] && p[len] != ' ' && p[len] != '%')
5103                 len++;
5104               suffix_subst = save_string (p - 1, len + 1);
5105               p += len;
5106             }
5107            break;
5108
5109            /* Henceforth ignore the option(s) matching the pattern
5110               after the %<.  */
5111           case '<':
5112             {
5113               unsigned len = 0;
5114               int have_wildcard = 0;
5115               int i;
5116
5117               while (p[len] && p[len] != ' ' && p[len] != '\t')
5118                 len++;
5119
5120               if (p[len-1] == '*')
5121                 have_wildcard = 1;
5122
5123               for (i = 0; i < n_switches; i++)
5124                 if (!strncmp (switches[i].part1, p, len - have_wildcard)
5125                     && (have_wildcard || switches[i].part1[len] == '\0'))
5126                   {
5127                     switches[i].live_cond = SWITCH_IGNORE;
5128                     switches[i].validated = 1;
5129                   }
5130
5131               p += len;
5132             }
5133             break;
5134
5135           case '*':
5136             if (soft_matched_part)
5137               {
5138                 do_spec_1 (soft_matched_part, 1, NULL);
5139                 do_spec_1 (" ", 0, NULL);
5140               }
5141             else
5142               /* Catch the case where a spec string contains something like
5143                  '%{foo:%*}'.  i.e. there is no * in the pattern on the left
5144                  hand side of the :.  */
5145               error ("spec failure: '%%*' has not been initialized by pattern match");
5146             break;
5147
5148             /* Process a string found as the value of a spec given by name.
5149                This feature allows individual machine descriptions
5150                to add and use their own specs.
5151                %[...] modifies -D options the way %P does;
5152                %(...) uses the spec unmodified.  */
5153           case '[':
5154             error ("warning: use of obsolete %%[ operator in specs");
5155           case '(':
5156             {
5157               const char *name = p;
5158               struct spec_list *sl;
5159               int len;
5160
5161               /* The string after the S/P is the name of a spec that is to be
5162                  processed.  */
5163               while (*p && *p != ')' && *p != ']')
5164                 p++;
5165
5166               /* See if it's in the list.  */
5167               for (len = p - name, sl = specs; sl; sl = sl->next)
5168                 if (sl->name_len == len && !strncmp (sl->name, name, len))
5169                   {
5170                     name = *(sl->ptr_spec);
5171 #ifdef DEBUG_SPECS
5172                     notice ("Processing spec %c%s%c, which is '%s'\n",
5173                             c, sl->name, (c == '(') ? ')' : ']', name);
5174 #endif
5175                     break;
5176                   }
5177
5178               if (sl)
5179                 {
5180                   if (c == '(')
5181                     {
5182                       value = do_spec_1 (name, 0, NULL);
5183                       if (value != 0)
5184                         return value;
5185                     }
5186                   else
5187                     {
5188                       char *x = alloca (strlen (name) * 2 + 1);
5189                       char *buf = x;
5190                       const char *y = name;
5191                       int flag = 0;
5192
5193                       /* Copy all of NAME into BUF, but put __ after
5194                          every -D and at the end of each arg.  */
5195                       while (1)
5196                         {
5197                           if (! strncmp (y, "-D", 2))
5198                             {
5199                               *x++ = '-';
5200                               *x++ = 'D';
5201                               *x++ = '_';
5202                               *x++ = '_';
5203                               y += 2;
5204                               flag = 1;
5205                               continue;
5206                             }
5207                           else if (flag
5208                                    && (*y == ' ' || *y == '\t' || *y == '='
5209                                        || *y == '}' || *y == 0))
5210                             {
5211                               *x++ = '_';
5212                               *x++ = '_';
5213                               flag = 0;
5214                             }
5215                           if (*y == 0)
5216                             break;
5217                           else
5218                             *x++ = *y++;
5219                         }
5220                       *x = 0;
5221
5222                       value = do_spec_1 (buf, 0, NULL);
5223                       if (value != 0)
5224                         return value;
5225                     }
5226                 }
5227
5228               /* Discard the closing paren or bracket.  */
5229               if (*p)
5230                 p++;
5231             }
5232             break;
5233
5234           default:
5235             error ("spec failure: unrecognized spec option '%c'", c);
5236             break;
5237           }
5238         break;
5239
5240       case '\\':
5241         /* Backslash: treat next character as ordinary.  */
5242         c = *p++;
5243
5244         /* Fall through.  */
5245       default:
5246         /* Ordinary character: put it into the current argument.  */
5247         obstack_1grow (&obstack, c);
5248         arg_going = 1;
5249       }
5250
5251   /* End of string.  If we are processing a spec function, we need to
5252      end any pending argument.  */
5253   if (processing_spec_function && arg_going)
5254     {
5255       obstack_1grow (&obstack, 0);
5256       string = XOBFINISH (&obstack, const char *);
5257       if (this_is_library_file)
5258         string = find_file (string);
5259       store_arg (string, delete_this_arg, this_is_output_file);
5260       if (this_is_output_file)
5261         outfiles[input_file_number] = string;
5262       arg_going = 0;
5263     }
5264
5265   return 0;
5266 }
5267
5268 /* Look up a spec function.  */
5269
5270 static const struct spec_function *
5271 lookup_spec_function (const char *name)
5272 {
5273   static const struct spec_function * const spec_function_tables[] =
5274   {
5275     static_spec_functions,
5276     lang_specific_spec_functions,
5277   };
5278   const struct spec_function *sf;
5279   unsigned int i;
5280
5281   for (i = 0; i < ARRAY_SIZE (spec_function_tables); i++)
5282     {
5283       for (sf = spec_function_tables[i]; sf->name != NULL; sf++)
5284         if (strcmp (sf->name, name) == 0)
5285           return sf;
5286     }
5287
5288   return NULL;
5289 }
5290
5291 /* Evaluate a spec function.  */
5292
5293 static const char *
5294 eval_spec_function (const char *func, const char *args)
5295 {
5296   const struct spec_function *sf;
5297   const char *funcval;
5298
5299   /* Saved spec processing context.  */
5300   int save_argbuf_index;
5301   int save_argbuf_length;
5302   const char **save_argbuf;
5303
5304   int save_arg_going;
5305   int save_delete_this_arg;
5306   int save_this_is_output_file;
5307   int save_this_is_library_file;
5308   int save_input_from_pipe;
5309   const char *save_suffix_subst;
5310
5311
5312   sf = lookup_spec_function (func);
5313   if (sf == NULL)
5314     fatal ("unknown spec function '%s'", func);
5315
5316   /* Push the spec processing context.  */
5317   save_argbuf_index = argbuf_index;
5318   save_argbuf_length = argbuf_length;
5319   save_argbuf = argbuf;
5320
5321   save_arg_going = arg_going;
5322   save_delete_this_arg = delete_this_arg;
5323   save_this_is_output_file = this_is_output_file;
5324   save_this_is_library_file = this_is_library_file;
5325   save_input_from_pipe = input_from_pipe;
5326   save_suffix_subst = suffix_subst;
5327
5328   /* Create a new spec processing context, and build the function
5329      arguments.  */
5330
5331   alloc_args ();
5332   if (do_spec_2 (args) < 0)
5333     fatal ("error in args to spec function '%s'", func);
5334
5335   /* argbuf_index is an index for the next argument to be inserted, and
5336      so contains the count of the args already inserted.  */
5337
5338   funcval = (*sf->func) (argbuf_index, argbuf);
5339
5340   /* Pop the spec processing context.  */
5341   argbuf_index = save_argbuf_index;
5342   argbuf_length = save_argbuf_length;
5343   free (argbuf);
5344   argbuf = save_argbuf;
5345
5346   arg_going = save_arg_going;
5347   delete_this_arg = save_delete_this_arg;
5348   this_is_output_file = save_this_is_output_file;
5349   this_is_library_file = save_this_is_library_file;
5350   input_from_pipe = save_input_from_pipe;
5351   suffix_subst = save_suffix_subst;
5352
5353   return funcval;
5354 }
5355
5356 /* Handle a spec function call of the form:
5357
5358    %:function(args)
5359
5360    ARGS is processed as a spec in a separate context and split into an
5361    argument vector in the normal fashion.  The function returns a string
5362    containing a spec which we then process in the caller's context, or
5363    NULL if no processing is required.  */
5364
5365 static const char *
5366 handle_spec_function (const char *p)
5367 {
5368   char *func, *args;
5369   const char *endp, *funcval;
5370   int count;
5371
5372   processing_spec_function++;
5373
5374   /* Get the function name.  */
5375   for (endp = p; *endp != '\0'; endp++)
5376     {
5377       if (*endp == '(')         /* ) */
5378         break;
5379       /* Only allow [A-Za-z0-9], -, and _ in function names.  */
5380       if (!ISALNUM (*endp) && !(*endp == '-' || *endp == '_'))
5381         fatal ("malformed spec function name");
5382     }
5383   if (*endp != '(')             /* ) */
5384     fatal ("no arguments for spec function");
5385   func = save_string (p, endp - p);
5386   p = ++endp;
5387
5388   /* Get the arguments.  */
5389   for (count = 0; *endp != '\0'; endp++)
5390     {
5391       /* ( */
5392       if (*endp == ')')
5393         {
5394           if (count == 0)
5395             break;
5396           count--;
5397         }
5398       else if (*endp == '(')    /* ) */
5399         count++;
5400     }
5401   /* ( */
5402   if (*endp != ')')
5403     fatal ("malformed spec function arguments");
5404   args = save_string (p, endp - p);
5405   p = ++endp;
5406
5407   /* p now points to just past the end of the spec function expression.  */
5408
5409   funcval = eval_spec_function (func, args);
5410   if (funcval != NULL && do_spec_1 (funcval, 0, NULL) < 0)
5411     p = NULL;
5412
5413   free (func);
5414   free (args);
5415
5416   processing_spec_function--;
5417
5418   return p;
5419 }
5420
5421 /* Inline subroutine of handle_braces.  Returns true if the current
5422    input suffix matches the atom bracketed by ATOM and END_ATOM.  */
5423 static inline bool
5424 input_suffix_matches (const char *atom, const char *end_atom)
5425 {
5426   /* We special case the semantics of {.s:...} and {.S:...} and their
5427      negative variants.  Instead of testing the input filename suffix,
5428      we test whether the input source file is an assembler file or an
5429      assembler-with-cpp file respectively.  This allows us to correctly
5430      handle the -x command line option.  */
5431
5432   if (atom + 1 == end_atom
5433       && input_file_compiler
5434       && input_file_compiler->suffix)
5435     {
5436       if (*atom == 's')
5437         return !strcmp (input_file_compiler->suffix, "@assembler");
5438       if (*atom == 'S')
5439         return !strcmp (input_file_compiler->suffix, "@assembler-with-cpp");
5440     }
5441
5442   return (input_suffix
5443           && !strncmp (input_suffix, atom, end_atom - atom)
5444           && input_suffix[end_atom - atom] == '\0');
5445 }
5446
5447 /* Inline subroutine of handle_braces.  Returns true if a switch
5448    matching the atom bracketed by ATOM and END_ATOM appeared on the
5449    command line.  */
5450 static inline bool
5451 switch_matches (const char *atom, const char *end_atom, int starred)
5452 {
5453   int i;
5454   int len = end_atom - atom;
5455   int plen = starred ? len : -1;
5456
5457   for (i = 0; i < n_switches; i++)
5458     if (!strncmp (switches[i].part1, atom, len)
5459         && (starred || switches[i].part1[len] == '\0')
5460         && check_live_switch (i, plen))
5461       return true;
5462
5463   return false;
5464 }
5465
5466 /* Inline subroutine of handle_braces.  Mark all of the switches which
5467    match ATOM (extends to END_ATOM; STARRED indicates whether there
5468    was a star after the atom) for later processing.  */
5469 static inline void
5470 mark_matching_switches (const char *atom, const char *end_atom, int starred)
5471 {
5472   int i;
5473   int len = end_atom - atom;
5474   int plen = starred ? len : -1;
5475
5476   for (i = 0; i < n_switches; i++)
5477     if (!strncmp (switches[i].part1, atom, len)
5478         && (starred || switches[i].part1[len] == '\0')
5479         && check_live_switch (i, plen))
5480       switches[i].ordering = 1;
5481 }
5482
5483 /* Inline subroutine of handle_braces.  Process all the currently
5484    marked switches through give_switch, and clear the marks.  */
5485 static inline void
5486 process_marked_switches (void)
5487 {
5488   int i;
5489
5490   for (i = 0; i < n_switches; i++)
5491     if (switches[i].ordering == 1)
5492       {
5493         switches[i].ordering = 0;
5494         give_switch (i, 0);
5495       }
5496 }
5497
5498 /* Handle a %{ ... } construct.  P points just inside the leading {.
5499    Returns a pointer one past the end of the brace block, or 0
5500    if we call do_spec_1 and that returns -1.  */
5501
5502 static const char *
5503 handle_braces (const char *p)
5504 {
5505   const char *atom, *end_atom;
5506   const char *d_atom = NULL, *d_end_atom = NULL;
5507   const char *orig = p;
5508
5509   bool a_is_suffix;
5510   bool a_is_starred;
5511   bool a_is_negated;
5512   bool a_matched;
5513
5514   bool a_must_be_last = false;
5515   bool ordered_set    = false;
5516   bool disjunct_set   = false;
5517   bool disj_matched   = false;
5518   bool disj_starred   = true;
5519   bool n_way_choice   = false;
5520   bool n_way_matched  = false;
5521
5522 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
5523
5524   do
5525     {
5526       if (a_must_be_last)
5527         goto invalid;
5528
5529       /* Scan one "atom" (S in the description above of %{}, possibly
5530          with !, ., or * modifiers).  */
5531       a_matched = a_is_suffix = a_is_starred = a_is_negated = false;
5532
5533       SKIP_WHITE();
5534       if (*p == '!')
5535         p++, a_is_negated = true;
5536
5537       SKIP_WHITE();
5538       if (*p == '.')
5539         p++, a_is_suffix = true;
5540
5541       atom = p;
5542       while (ISIDNUM(*p) || *p == '-' || *p == '+' || *p == '='
5543              || *p == ',' || *p == '.' || *p == '@')
5544         p++;
5545       end_atom = p;
5546
5547       if (*p == '*')
5548         p++, a_is_starred = 1;
5549
5550       SKIP_WHITE();
5551       switch (*p)
5552         {
5553         case '&': case '}':
5554           /* Substitute the switch(es) indicated by the current atom.  */
5555           ordered_set = true;
5556           if (disjunct_set || n_way_choice || a_is_negated || a_is_suffix
5557               || atom == end_atom)
5558             goto invalid;
5559
5560           mark_matching_switches (atom, end_atom, a_is_starred);
5561
5562           if (*p == '}')
5563             process_marked_switches ();
5564           break;
5565
5566         case '|': case ':':
5567           /* Substitute some text if the current atom appears as a switch
5568              or suffix.  */
5569           disjunct_set = true;
5570           if (ordered_set)
5571             goto invalid;
5572
5573           if (atom == end_atom)
5574             {
5575               if (!n_way_choice || disj_matched || *p == '|'
5576                   || a_is_negated || a_is_suffix || a_is_starred)
5577                 goto invalid;
5578
5579               /* An empty term may appear as the last choice of an
5580                  N-way choice set; it means "otherwise".  */
5581               a_must_be_last = true;
5582               disj_matched = !n_way_matched;
5583               disj_starred = false;
5584             }
5585           else
5586             {
5587                if (a_is_suffix && a_is_starred)
5588                  goto invalid;
5589
5590                if (!a_is_starred)
5591                  disj_starred = false;
5592
5593                /* Don't bother testing this atom if we already have a
5594                   match.  */
5595                if (!disj_matched && !n_way_matched)
5596                  {
5597                    if (a_is_suffix)
5598                      a_matched = input_suffix_matches (atom, end_atom);
5599                    else
5600                      a_matched = switch_matches (atom, end_atom, a_is_starred);
5601
5602                    if (a_matched != a_is_negated)
5603                      {
5604                        disj_matched = true;
5605                        d_atom = atom;
5606                        d_end_atom = end_atom;
5607                      }
5608                  }
5609             }
5610
5611           if (*p == ':')
5612             {
5613               /* Found the body, that is, the text to substitute if the
5614                  current disjunction matches.  */
5615               p = process_brace_body (p + 1, d_atom, d_end_atom, disj_starred,
5616                                       disj_matched && !n_way_matched);
5617               if (p == 0)
5618                 return 0;
5619
5620               /* If we have an N-way choice, reset state for the next
5621                  disjunction.  */
5622               if (*p == ';')
5623                 {
5624                   n_way_choice = true;
5625                   n_way_matched |= disj_matched;
5626                   disj_matched = false;
5627                   disj_starred = true;
5628                   d_atom = d_end_atom = NULL;
5629                 }
5630             }
5631           break;
5632
5633         default:
5634           goto invalid;
5635         }
5636     }
5637   while (*p++ != '}');
5638
5639   return p;
5640   
5641  invalid:
5642   fatal ("braced spec '%s' is invalid at '%c'", orig, *p);
5643   
5644 #undef SKIP_WHITE
5645 }
5646
5647 /* Subroutine of handle_braces.  Scan and process a brace substitution body
5648    (X in the description of %{} syntax).  P points one past the colon;
5649    ATOM and END_ATOM bracket the first atom which was found to be true
5650    (present) in the current disjunction; STARRED indicates whether all
5651    the atoms in the current disjunction were starred (for syntax validation);
5652    MATCHED indicates whether the disjunction matched or not, and therefore
5653    whether or not the body is to be processed through do_spec_1 or just
5654    skipped.  Returns a pointer to the closing } or ;, or 0 if do_spec_1
5655    returns -1.  */
5656
5657 static const char *
5658 process_brace_body (const char *p, const char *atom, const char *end_atom,
5659                     int starred, int matched)
5660 {
5661   const char *body, *end_body;
5662   unsigned int nesting_level;
5663   bool have_subst     = false;
5664
5665   /* Locate the closing } or ;, honoring nested braces.
5666      Trim trailing whitespace.  */
5667   body = p;
5668   nesting_level = 1;
5669   for (;;)
5670     {
5671       if (*p == '{')
5672         nesting_level++;
5673       else if (*p == '}')
5674         {
5675           if (!--nesting_level)
5676             break;
5677         }
5678       else if (*p == ';' && nesting_level == 1)
5679         break;
5680       else if (*p == '%' && p[1] == '*' && nesting_level == 1)
5681         have_subst = true;
5682       else if (*p == '\0')
5683         goto invalid;
5684       p++;
5685     }
5686
5687   end_body = p;
5688   while (end_body[-1] == ' ' || end_body[-1] == '\t')
5689     end_body--;
5690
5691   if (have_subst && !starred)
5692     goto invalid;
5693
5694   if (matched)
5695     {
5696       /* Copy the substitution body to permanent storage and execute it.
5697          If have_subst is false, this is a simple matter of running the
5698          body through do_spec_1...  */
5699       char *string = save_string (body, end_body - body);
5700       if (!have_subst)
5701         {
5702           if (do_spec_1 (string, 0, NULL) < 0)
5703             return 0;
5704         }
5705       else
5706         {
5707           /* ... but if have_subst is true, we have to process the
5708              body once for each matching switch, with %* set to the
5709              variant part of the switch.  */
5710           unsigned int hard_match_len = end_atom - atom;
5711           int i;
5712
5713           for (i = 0; i < n_switches; i++)
5714             if (!strncmp (switches[i].part1, atom, hard_match_len)
5715                 && check_live_switch (i, hard_match_len))
5716               {
5717                 if (do_spec_1 (string, 0,
5718                                &switches[i].part1[hard_match_len]) < 0)
5719                   return 0;
5720                 /* Pass any arguments this switch has.  */
5721                 give_switch (i, 1);
5722                 suffix_subst = NULL;
5723               }
5724         }
5725     }
5726
5727   return p;
5728
5729  invalid:
5730   fatal ("braced spec body '%s' is invalid", body);
5731 }
5732 \f
5733 /* Return 0 iff switch number SWITCHNUM is obsoleted by a later switch
5734    on the command line.  PREFIX_LENGTH is the length of XXX in an {XXX*}
5735    spec, or -1 if either exact match or %* is used.
5736
5737    A -O switch is obsoleted by a later -O switch.  A -f, -m, or -W switch
5738    whose value does not begin with "no-" is obsoleted by the same value
5739    with the "no-", similarly for a switch with the "no-" prefix.  */
5740
5741 static int
5742 check_live_switch (int switchnum, int prefix_length)
5743 {
5744   const char *name = switches[switchnum].part1;
5745   int i;
5746
5747   /* In the common case of {<at-most-one-letter>*}, a negating
5748      switch would always match, so ignore that case.  We will just
5749      send the conflicting switches to the compiler phase.  */
5750   if (prefix_length >= 0 && prefix_length <= 1)
5751     return 1;
5752
5753   /* If we already processed this switch and determined if it was
5754      live or not, return our past determination.  */
5755   if (switches[switchnum].live_cond != 0)
5756     return switches[switchnum].live_cond > 0;
5757
5758   /* Now search for duplicate in a manner that depends on the name.  */
5759   switch (*name)
5760     {
5761     case 'O':
5762       for (i = switchnum + 1; i < n_switches; i++)
5763         if (switches[i].part1[0] == 'O')
5764           {
5765             switches[switchnum].validated = 1;
5766             switches[switchnum].live_cond = SWITCH_FALSE;
5767             return 0;
5768           }
5769       break;
5770
5771     case 'W':  case 'f':  case 'm':
5772       if (! strncmp (name + 1, "no-", 3))
5773         {
5774           /* We have Xno-YYY, search for XYYY.  */
5775           for (i = switchnum + 1; i < n_switches; i++)
5776             if (switches[i].part1[0] == name[0]
5777                 && ! strcmp (&switches[i].part1[1], &name[4]))
5778               {
5779                 switches[switchnum].validated = 1;
5780                 switches[switchnum].live_cond = SWITCH_FALSE;
5781                 return 0;
5782               }
5783         }
5784       else
5785         {
5786           /* We have XYYY, search for Xno-YYY.  */
5787           for (i = switchnum + 1; i < n_switches; i++)
5788             if (switches[i].part1[0] == name[0]
5789                 && switches[i].part1[1] == 'n'
5790                 && switches[i].part1[2] == 'o'
5791                 && switches[i].part1[3] == '-'
5792                 && !strcmp (&switches[i].part1[4], &name[1]))
5793               {
5794                 switches[switchnum].validated = 1;
5795                 switches[switchnum].live_cond = SWITCH_FALSE;
5796                 return 0;
5797               }
5798         }
5799       break;
5800     }
5801
5802   /* Otherwise the switch is live.  */
5803   switches[switchnum].live_cond = SWITCH_LIVE;
5804   return 1;
5805 }
5806 \f
5807 /* Pass a switch to the current accumulating command
5808    in the same form that we received it.
5809    SWITCHNUM identifies the switch; it is an index into
5810    the vector of switches gcc received, which is `switches'.
5811    This cannot fail since it never finishes a command line.
5812
5813    If OMIT_FIRST_WORD is nonzero, then we omit .part1 of the argument.  */
5814
5815 static void
5816 give_switch (int switchnum, int omit_first_word)
5817 {
5818   if (switches[switchnum].live_cond == SWITCH_IGNORE)
5819     return;
5820
5821   if (!omit_first_word)
5822     {
5823       do_spec_1 ("-", 0, NULL);
5824       do_spec_1 (switches[switchnum].part1, 1, NULL);
5825     }
5826
5827   if (switches[switchnum].args != 0)
5828     {
5829       const char **p;
5830       for (p = switches[switchnum].args; *p; p++)
5831         {
5832           const char *arg = *p;
5833
5834           do_spec_1 (" ", 0, NULL);
5835           if (suffix_subst)
5836             {
5837               unsigned length = strlen (arg);
5838               int dot = 0;
5839
5840               while (length-- && !IS_DIR_SEPARATOR (arg[length]))
5841                 if (arg[length] == '.')
5842                   {
5843                     ((char *)arg)[length] = 0;
5844                     dot = 1;
5845                     break;
5846                   }
5847               do_spec_1 (arg, 1, NULL);
5848               if (dot)
5849                 ((char *)arg)[length] = '.';
5850               do_spec_1 (suffix_subst, 1, NULL);
5851             }
5852           else
5853             do_spec_1 (arg, 1, NULL);
5854         }
5855     }
5856
5857   do_spec_1 (" ", 0, NULL);
5858   switches[switchnum].validated = 1;
5859 }
5860 \f
5861 /* Search for a file named NAME trying various prefixes including the
5862    user's -B prefix and some standard ones.
5863    Return the absolute file name found.  If nothing is found, return NAME.  */
5864
5865 static const char *
5866 find_file (const char *name)
5867 {
5868   char *newname;
5869
5870   /* Try multilib_dir if it is defined.  */
5871   if (multilib_os_dir != NULL)
5872     {
5873       newname = find_a_file (&startfile_prefixes, name, R_OK, 1);
5874
5875       /* If we don't find it in the multi library dir, then fall
5876          through and look for it in the normal places.  */
5877       if (newname != NULL)
5878         return newname;
5879     }
5880
5881   newname = find_a_file (&startfile_prefixes, name, R_OK, 0);
5882   return newname ? newname : name;
5883 }
5884
5885 /* Determine whether a directory exists.  If LINKER, return 0 for
5886    certain fixed names not needed by the linker.  If not LINKER, it is
5887    only important to return 0 if the host machine has a small ARG_MAX
5888    limit.  */
5889
5890 static int
5891 is_directory (const char *path1, const char *path2, int linker)
5892 {
5893   int len1 = strlen (path1);
5894   int len2 = strlen (path2);
5895   char *path = alloca (3 + len1 + len2);
5896   char *cp;
5897   struct stat st;
5898
5899 #ifndef SMALL_ARG_MAX
5900   if (! linker)
5901     return 1;
5902 #endif
5903
5904   /* Construct the path from the two parts.  Ensure the string ends with "/.".
5905      The resulting path will be a directory even if the given path is a
5906      symbolic link.  */
5907   memcpy (path, path1, len1);
5908   memcpy (path + len1, path2, len2);
5909   cp = path + len1 + len2;
5910   if (!IS_DIR_SEPARATOR (cp[-1]))
5911     *cp++ = DIR_SEPARATOR;
5912   *cp++ = '.';
5913   *cp = '\0';
5914
5915   /* Exclude directories that the linker is known to search.  */
5916   if (linker
5917       && ((cp - path == 6
5918            && strcmp (path, concat (dir_separator_str, "lib",
5919                                     dir_separator_str, ".", NULL)) == 0)
5920           || (cp - path == 10
5921               && strcmp (path, concat (dir_separator_str, "usr",
5922                                        dir_separator_str, "lib",
5923                                        dir_separator_str, ".", NULL)) == 0)))
5924     return 0;
5925
5926   return (stat (path, &st) >= 0 && S_ISDIR (st.st_mode));
5927 }
5928
5929 /* Set up the various global variables to indicate that we're processing
5930    the input file named FILENAME.  */
5931
5932 void
5933 set_input (const char *filename)
5934 {
5935   const char *p;
5936
5937   input_filename = filename;
5938   input_filename_length = strlen (input_filename);
5939
5940   input_basename = input_filename;
5941 #ifdef HAVE_DOS_BASED_FILE_SYSTEM
5942   /* Skip drive name so 'x:foo' is handled properly.  */
5943   if (input_basename[1] == ':')
5944     input_basename += 2;
5945 #endif
5946   for (p = input_basename; *p; p++)
5947     if (IS_DIR_SEPARATOR (*p))
5948       input_basename = p + 1;
5949
5950   /* Find a suffix starting with the last period,
5951      and set basename_length to exclude that suffix.  */
5952   basename_length = strlen (input_basename);
5953   suffixed_basename_length = basename_length;
5954   p = input_basename + basename_length;
5955   while (p != input_basename && *p != '.')
5956     --p;
5957   if (*p == '.' && p != input_basename)
5958     {
5959       basename_length = p - input_basename;
5960       input_suffix = p + 1;
5961     }
5962   else
5963     input_suffix = "";
5964
5965   /* If a spec for 'g', 'u', or 'U' is seen with -save-temps then
5966      we will need to do a stat on the input_filename.  The
5967      INPUT_STAT_SET signals that the stat is needed.  */
5968   input_stat_set = 0;
5969 }
5970 \f
5971 /* On fatal signals, delete all the temporary files.  */
5972
5973 static void
5974 fatal_error (int signum)
5975 {
5976   signal (signum, SIG_DFL);
5977   delete_failure_queue ();
5978   delete_temp_files ();
5979   /* Get the same signal again, this time not handled,
5980      so its normal effect occurs.  */
5981   kill (getpid (), signum);
5982 }
5983
5984 extern int main (int, const char **);
5985
5986 int
5987 main (int argc, const char **argv)
5988 {
5989   size_t i;
5990   int value;
5991   int linker_was_run = 0;
5992   int lang_n_infiles = 0;
5993   int num_linker_inputs = 0;
5994   char *explicit_link_files;
5995   char *specs_file;
5996   const char *p;
5997   struct user_specs *uptr;
5998
5999   p = argv[0] + strlen (argv[0]);
6000   while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
6001     --p;
6002   programname = p;
6003
6004   xmalloc_set_program_name (programname);
6005
6006 #ifdef GCC_DRIVER_HOST_INITIALIZATION
6007   /* Perform host dependent initialization when needed.  */
6008   GCC_DRIVER_HOST_INITIALIZATION;
6009 #endif
6010
6011   /* Unlock the stdio streams.  */
6012   unlock_std_streams ();
6013
6014   gcc_init_libintl ();
6015
6016   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
6017     signal (SIGINT, fatal_error);
6018 #ifdef SIGHUP
6019   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
6020     signal (SIGHUP, fatal_error);
6021 #endif
6022   if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
6023     signal (SIGTERM, fatal_error);
6024 #ifdef SIGPIPE
6025   if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
6026     signal (SIGPIPE, fatal_error);
6027 #endif
6028 #ifdef SIGCHLD
6029   /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
6030      receive the signal.  A different setting is inheritable */
6031   signal (SIGCHLD, SIG_DFL);
6032 #endif
6033
6034   /* Allocate the argument vector.  */
6035   alloc_args ();
6036
6037   obstack_init (&obstack);
6038
6039   /* Build multilib_select, et. al from the separate lines that make up each
6040      multilib selection.  */
6041   {
6042     const char *const *q = multilib_raw;
6043     int need_space;
6044
6045     obstack_init (&multilib_obstack);
6046     while ((p = *q++) != (char *) 0)
6047       obstack_grow (&multilib_obstack, p, strlen (p));
6048
6049     obstack_1grow (&multilib_obstack, 0);
6050     multilib_select = XOBFINISH (&multilib_obstack, const char *);
6051
6052     q = multilib_matches_raw;
6053     while ((p = *q++) != (char *) 0)
6054       obstack_grow (&multilib_obstack, p, strlen (p));
6055
6056     obstack_1grow (&multilib_obstack, 0);
6057     multilib_matches = XOBFINISH (&multilib_obstack, const char *);
6058
6059     q = multilib_exclusions_raw;
6060     while ((p = *q++) != (char *) 0)
6061       obstack_grow (&multilib_obstack, p, strlen (p));
6062
6063     obstack_1grow (&multilib_obstack, 0);
6064     multilib_exclusions = XOBFINISH (&multilib_obstack, const char *);
6065
6066     need_space = FALSE;
6067     for (i = 0; i < ARRAY_SIZE (multilib_defaults_raw); i++)
6068       {
6069         if (need_space)
6070           obstack_1grow (&multilib_obstack, ' ');
6071         obstack_grow (&multilib_obstack,
6072                       multilib_defaults_raw[i],
6073                       strlen (multilib_defaults_raw[i]));
6074         need_space = TRUE;
6075       }
6076
6077     obstack_1grow (&multilib_obstack, 0);
6078     multilib_defaults = XOBFINISH (&multilib_obstack, const char *);
6079   }
6080
6081   /* Set up to remember the pathname of gcc and any options
6082      needed for collect.  We use argv[0] instead of programname because
6083      we need the complete pathname.  */
6084   obstack_init (&collect_obstack);
6085   obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);
6086   obstack_grow (&collect_obstack, argv[0], strlen (argv[0]) + 1);
6087   putenv (XOBFINISH (&collect_obstack, char *));
6088
6089 #ifdef INIT_ENVIRONMENT
6090   /* Set up any other necessary machine specific environment variables.  */
6091   putenv (INIT_ENVIRONMENT);
6092 #endif
6093
6094   /* Make a table of what switches there are (switches, n_switches).
6095      Make a table of specified input files (infiles, n_infiles).
6096      Decode switches that are handled locally.  */
6097
6098   process_command (argc, argv);
6099
6100   /* Initialize the vector of specs to just the default.
6101      This means one element containing 0s, as a terminator.  */
6102
6103   compilers = xmalloc (sizeof default_compilers);
6104   memcpy (compilers, default_compilers, sizeof default_compilers);
6105   n_compilers = n_default_compilers;
6106
6107   /* Read specs from a file if there is one.  */
6108
6109   machine_suffix = concat (spec_machine, dir_separator_str,
6110                            spec_version, dir_separator_str, NULL);
6111   just_machine_suffix = concat (spec_machine, dir_separator_str, NULL);
6112
6113   specs_file = find_a_file (&startfile_prefixes, "specs", R_OK, 0);
6114   /* Read the specs file unless it is a default one.  */
6115   if (specs_file != 0 && strcmp (specs_file, "specs"))
6116     read_specs (specs_file, TRUE);
6117   else
6118     init_spec ();
6119
6120   /* We need to check standard_exec_prefix/just_machine_suffix/specs
6121      for any override of as, ld and libraries.  */
6122   specs_file = alloca (strlen (standard_exec_prefix)
6123                        + strlen (just_machine_suffix) + sizeof ("specs"));
6124
6125   strcpy (specs_file, standard_exec_prefix);
6126   strcat (specs_file, just_machine_suffix);
6127   strcat (specs_file, "specs");
6128   if (access (specs_file, R_OK) == 0)
6129     read_specs (specs_file, TRUE);
6130
6131   /* Process any configure-time defaults specified for the command line
6132      options, via OPTION_DEFAULT_SPECS.  */
6133   for (i = 0; i < ARRAY_SIZE (option_default_specs); i++)
6134     do_option_spec (option_default_specs[i].name,
6135                     option_default_specs[i].spec);
6136
6137   /* Process DRIVER_SELF_SPECS, adding any new options to the end
6138      of the command line.  */
6139
6140   for (i = 0; i < ARRAY_SIZE (driver_self_specs); i++)
6141     do_self_spec (driver_self_specs[i]);
6142
6143   /* If not cross-compiling, look for executables in the standard
6144      places.  */
6145   if (*cross_compile == '0')
6146     {
6147       if (*md_exec_prefix)
6148         {
6149           add_prefix (&exec_prefixes, md_exec_prefix, "GCC",
6150                       PREFIX_PRIORITY_LAST, 0, 0);
6151         }
6152     }
6153
6154   /* Process sysroot_suffix_spec.  */
6155   if (*sysroot_suffix_spec != 0
6156       && do_spec_2 (sysroot_suffix_spec) == 0)
6157     {
6158       if (argbuf_index > 1)
6159         error ("spec failure: more than one arg to SYSROOT_SUFFIX_SPEC");
6160       else if (argbuf_index == 1)
6161         target_sysroot_suffix = xstrdup (argbuf[argbuf_index -1]);
6162     }
6163
6164 #ifdef HAVE_LD_SYSROOT
6165   /* Pass the --sysroot option to the linker, if it supports that.  If
6166      there is a sysroot_suffix_spec, it has already been processed by
6167      this point, so target_system_root really is the system root we
6168      should be using.  */
6169   if (target_system_root)
6170     {
6171       obstack_grow (&obstack, "%(sysroot_spec) ", strlen ("%(sysroot_spec) "));
6172       obstack_grow0 (&obstack, link_spec, strlen (link_spec));
6173       set_spec ("link", XOBFINISH (&obstack, const char *));
6174     }
6175 #endif
6176
6177   /* Process sysroot_hdrs_suffix_spec.  */
6178   if (*sysroot_hdrs_suffix_spec != 0
6179       && do_spec_2 (sysroot_hdrs_suffix_spec) == 0)
6180     {
6181       if (argbuf_index > 1)
6182         error ("spec failure: more than one arg to SYSROOT_HEADERS_SUFFIX_SPEC");
6183       else if (argbuf_index == 1)
6184         target_sysroot_hdrs_suffix = xstrdup (argbuf[argbuf_index -1]);
6185     }
6186
6187   /* Look for startfiles in the standard places.  */
6188   if (*startfile_prefix_spec != 0
6189       && do_spec_2 (startfile_prefix_spec) == 0
6190       && do_spec_1 (" ", 0, NULL) == 0)
6191     {
6192       int ndx;
6193       for (ndx = 0; ndx < argbuf_index; ndx++)
6194         add_sysrooted_prefix (&startfile_prefixes, argbuf[ndx], "BINUTILS",
6195                               PREFIX_PRIORITY_LAST, 0, 1);
6196     }
6197   /* We should eventually get rid of all these and stick to
6198      startfile_prefix_spec exclusively.  */
6199   else if (*cross_compile == '0' || target_system_root)
6200     {
6201       if (*md_startfile_prefix)
6202         add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix,
6203                               "GCC", PREFIX_PRIORITY_LAST, 0, 1);
6204
6205       if (*md_startfile_prefix_1)
6206         add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix_1,
6207                               "GCC", PREFIX_PRIORITY_LAST, 0, 1);
6208
6209       /* If standard_startfile_prefix is relative, base it on
6210          standard_exec_prefix.  This lets us move the installed tree
6211          as a unit.  If GCC_EXEC_PREFIX is defined, base
6212          standard_startfile_prefix on that as well.
6213
6214          If the prefix is relative, only search it for native compilers;
6215          otherwise we will search a directory containing host libraries.  */
6216       if (IS_ABSOLUTE_PATH (standard_startfile_prefix))
6217         add_sysrooted_prefix (&startfile_prefixes,
6218                               standard_startfile_prefix, "BINUTILS",
6219                               PREFIX_PRIORITY_LAST, 0, 1);
6220       else if (*cross_compile == '0')
6221         {
6222           if (gcc_exec_prefix)
6223             add_prefix (&startfile_prefixes,
6224                         concat (gcc_exec_prefix, machine_suffix,
6225                                 standard_startfile_prefix, NULL),
6226                         NULL, PREFIX_PRIORITY_LAST, 0, 1);
6227           add_prefix (&startfile_prefixes,
6228                       concat (standard_exec_prefix,
6229                               machine_suffix,
6230                               standard_startfile_prefix, NULL),
6231                       NULL, PREFIX_PRIORITY_LAST, 0, 1);
6232         }
6233
6234       if (*standard_startfile_prefix_1)
6235         add_sysrooted_prefix (&startfile_prefixes,
6236                               standard_startfile_prefix_1, "BINUTILS",
6237                               PREFIX_PRIORITY_LAST, 0, 1);
6238       if (*standard_startfile_prefix_2)
6239         add_sysrooted_prefix (&startfile_prefixes,
6240                               standard_startfile_prefix_2, "BINUTILS",
6241                               PREFIX_PRIORITY_LAST, 0, 1);
6242     }
6243
6244   /* Process any user specified specs in the order given on the command
6245      line.  */
6246   for (uptr = user_specs_head; uptr; uptr = uptr->next)
6247     {
6248       char *filename = find_a_file (&startfile_prefixes, uptr->filename,
6249                                     R_OK, 0);
6250       read_specs (filename ? filename : uptr->filename, FALSE);
6251     }
6252
6253   /* If we have a GCC_EXEC_PREFIX envvar, modify it for cpp's sake.  */
6254   if (gcc_exec_prefix)
6255     gcc_exec_prefix = concat (gcc_exec_prefix, spec_machine, dir_separator_str,
6256                               spec_version, dir_separator_str, NULL);
6257
6258   /* Now we have the specs.
6259      Set the `valid' bits for switches that match anything in any spec.  */
6260
6261   validate_all_switches ();
6262
6263   /* Now that we have the switches and the specs, set
6264      the subdirectory based on the options.  */
6265   set_multilib_dir ();
6266
6267   /* Warn about any switches that no pass was interested in.  */
6268
6269   for (i = 0; (int) i < n_switches; i++)
6270     if (! switches[i].validated)
6271       error ("unrecognized option '-%s'", switches[i].part1);
6272
6273   /* Obey some of the options.  */
6274
6275   if (print_search_dirs)
6276     {
6277       printf (_("install: %s%s\n"), standard_exec_prefix, machine_suffix);
6278       printf (_("programs: %s\n"), build_search_list (&exec_prefixes, "", 0));
6279       printf (_("libraries: %s\n"), build_search_list (&startfile_prefixes, "", 0));
6280       return (0);
6281     }
6282
6283   if (print_file_name)
6284     {
6285       printf ("%s\n", find_file (print_file_name));
6286       return (0);
6287     }
6288
6289   if (print_prog_name)
6290     {
6291       char *newname = find_a_file (&exec_prefixes, print_prog_name, X_OK, 0);
6292       printf ("%s\n", (newname ? newname : print_prog_name));
6293       return (0);
6294     }
6295
6296   if (print_multi_lib)
6297     {
6298       print_multilib_info ();
6299       return (0);
6300     }
6301
6302   if (print_multi_directory)
6303     {
6304       if (multilib_dir == NULL)
6305         printf (".\n");
6306       else
6307         printf ("%s\n", multilib_dir);
6308       return (0);
6309     }
6310
6311   if (print_multi_os_directory)
6312     {
6313       if (multilib_os_dir == NULL)
6314         printf (".\n");
6315       else
6316         printf ("%s\n", multilib_os_dir);
6317       return (0);
6318     }
6319
6320   if (target_help_flag)
6321    {
6322       /* Print if any target specific options.  */
6323
6324       /* We do not exit here. Instead we have created a fake input file
6325          called 'target-dummy' which needs to be compiled, and we pass this
6326          on to the various sub-processes, along with the --target-help
6327          switch.  */
6328     }
6329
6330   if (print_help_list)
6331     {
6332       display_help ();
6333
6334       if (! verbose_flag)
6335         {
6336           printf (_("\nFor bug reporting instructions, please see:\n"));
6337           printf ("%s.\n", bug_report_url);
6338
6339           return (0);
6340         }
6341
6342       /* We do not exit here.  Instead we have created a fake input file
6343          called 'help-dummy' which needs to be compiled, and we pass this
6344          on the various sub-processes, along with the --help switch.  */
6345     }
6346
6347   if (verbose_flag)
6348     {
6349       int n;
6350       const char *thrmod;
6351
6352       notice ("Target: %s\n", spec_machine);
6353       notice ("Configured with: %s\n", configuration_arguments);
6354
6355 #ifdef THREAD_MODEL_SPEC
6356       /* We could have defined THREAD_MODEL_SPEC to "%*" by default,
6357          but there's no point in doing all this processing just to get
6358          thread_model back.  */
6359       obstack_init (&obstack);
6360       do_spec_1 (THREAD_MODEL_SPEC, 0, thread_model);
6361       obstack_1grow (&obstack, '\0');
6362       thrmod = XOBFINISH (&obstack, const char *);
6363 #else
6364       thrmod = thread_model;
6365 #endif
6366
6367       notice ("Thread model: %s\n", thrmod);
6368
6369       /* compiler_version is truncated at the first space when initialized
6370          from version string, so truncate version_string at the first space
6371          before comparing.  */
6372       for (n = 0; version_string[n]; n++)
6373         if (version_string[n] == ' ')
6374           break;
6375
6376       if (! strncmp (version_string, compiler_version, n)
6377           && compiler_version[n] == 0)
6378         notice ("gcc version %s\n", version_string);
6379       else
6380         notice ("gcc driver version %s executing gcc version %s\n",
6381                 version_string, compiler_version);
6382
6383       if (n_infiles == 0)
6384         return (0);
6385     }
6386
6387   if (n_infiles == added_libraries)
6388     fatal ("no input files");
6389
6390   /* Make a place to record the compiler output file names
6391      that correspond to the input files.  */
6392
6393   i = n_infiles;
6394   i += lang_specific_extra_outfiles;
6395   outfiles = xcalloc (i, sizeof (char *));
6396
6397   /* Record which files were specified explicitly as link input.  */
6398
6399   explicit_link_files = xcalloc (1, n_infiles);
6400
6401   if (combine_flag)
6402     combine_inputs = true;
6403   else
6404     combine_inputs = false;
6405
6406   for (i = 0; (int) i < n_infiles; i++)
6407     {
6408       const char *name = infiles[i].name;
6409       struct compiler *compiler = lookup_compiler (name, 
6410                                                    strlen (name), 
6411                                                    infiles[i].language);
6412       
6413       if (compiler && !(compiler->combinable))
6414         combine_inputs = false;
6415       
6416       if (lang_n_infiles > 0 && compiler != input_file_compiler
6417           && infiles[i].language && infiles[i].language[0] != '*')
6418         infiles[i].incompiler = compiler;
6419       else if (compiler)
6420         {
6421           lang_n_infiles++;
6422           input_file_compiler = compiler;
6423           infiles[i].incompiler = compiler;
6424         }
6425       else
6426         {
6427           /* Since there is no compiler for this input file, assume it is a
6428              linker file.  */
6429           explicit_link_files[i] = 1;
6430           infiles[i].incompiler = NULL;
6431         }
6432       infiles[i].compiled = false;
6433       infiles[i].preprocessed = false;
6434     }
6435   
6436   if (combine_flag && save_temps_flag)
6437     {
6438       bool save_combine_inputs = combine_inputs;
6439       /* Must do a separate pre-processing pass for C & Objective-C files, to
6440          obtain individual .i files.  */
6441
6442       combine_inputs = false;
6443       for (i = 0; (int) i < n_infiles; i++)
6444         {
6445           int this_file_error = 0;
6446           
6447           input_file_number = i;
6448           set_input (infiles[i].name);
6449           if (infiles[i].incompiler
6450               && (infiles[i].incompiler)->needs_preprocessing)
6451             input_file_compiler = infiles[i].incompiler;
6452           else
6453             continue;
6454
6455           if (input_file_compiler)
6456             {
6457               if (input_file_compiler->spec[0] == '#')
6458                 {
6459                   error ("%s: %s compiler not installed on this system",
6460                          input_filename, &input_file_compiler->spec[1]);
6461                   this_file_error = 1;
6462                 }
6463               else
6464                 {
6465                   value = do_spec (input_file_compiler->spec);
6466                   infiles[i].preprocessed = true;
6467                   if (!have_o_argbuf_index)
6468                     fatal ("spec '%s' is invalid", input_file_compiler->spec);
6469                   infiles[i].name = argbuf[have_o_argbuf_index];
6470                   infiles[i].incompiler
6471                     = lookup_compiler (infiles[i].name,
6472                                        strlen (infiles[i].name),
6473                                        infiles[i].language);
6474
6475                   if (value < 0)
6476                     this_file_error = 1;
6477                 }
6478             }
6479
6480           if (this_file_error)
6481             {
6482               delete_failure_queue ();
6483               error_count++;
6484               break;
6485             }
6486           clear_failure_queue ();
6487         }
6488       combine_inputs = save_combine_inputs;
6489     }
6490
6491   for (i = 0; (int) i < n_infiles; i++)
6492     {
6493       int this_file_error = 0;
6494
6495       /* Tell do_spec what to substitute for %i.  */
6496
6497       input_file_number = i;
6498       set_input (infiles[i].name);
6499
6500       if (infiles[i].compiled)
6501         continue;
6502
6503       /* Use the same thing in %o, unless cp->spec says otherwise.  */
6504
6505       outfiles[i] = input_filename;
6506
6507       /* Figure out which compiler from the file's suffix.  */
6508
6509       if (! combine_inputs)
6510         input_file_compiler
6511           = lookup_compiler (infiles[i].name, input_filename_length,
6512                              infiles[i].language);
6513       else
6514         input_file_compiler = infiles[i].incompiler;
6515
6516       if (input_file_compiler)
6517         {
6518           /* Ok, we found an applicable compiler.  Run its spec.  */
6519
6520           if (input_file_compiler->spec[0] == '#')
6521             {
6522               error ("%s: %s compiler not installed on this system",
6523                      input_filename, &input_file_compiler->spec[1]);
6524               this_file_error = 1;
6525             }
6526           else
6527             {
6528               value = do_spec (input_file_compiler->spec);
6529               infiles[i].compiled = true;
6530               if (value < 0)
6531                 this_file_error = 1;
6532             }
6533         }
6534
6535       /* If this file's name does not contain a recognized suffix,
6536          record it as explicit linker input.  */
6537
6538       else
6539         explicit_link_files[i] = 1;
6540
6541       /* Clear the delete-on-failure queue, deleting the files in it
6542          if this compilation failed.  */
6543
6544       if (this_file_error)
6545         {
6546           delete_failure_queue ();
6547           error_count++;
6548         }
6549       /* If this compilation succeeded, don't delete those files later.  */
6550       clear_failure_queue ();
6551     }
6552
6553   /* Reset the output file name to the first input file name, for use
6554      with %b in LINK_SPEC on a target that prefers not to emit a.out
6555      by default.  */
6556   if (n_infiles > 0)
6557     set_input (infiles[0].name);
6558
6559   if (error_count == 0)
6560     {
6561       /* Make sure INPUT_FILE_NUMBER points to first available open
6562          slot.  */
6563       input_file_number = n_infiles;
6564       if (lang_specific_pre_link ())
6565         error_count++;
6566     }
6567
6568   /* Determine if there are any linker input files.  */
6569   num_linker_inputs = 0;
6570   for (i = 0; (int) i < n_infiles; i++)
6571     if (explicit_link_files[i] || outfiles[i] != NULL)
6572       num_linker_inputs++;
6573
6574   /* Run ld to link all the compiler output files.  */
6575
6576   if (num_linker_inputs > 0 && error_count == 0)
6577     {
6578       int tmp = execution_count;
6579
6580       /* We'll use ld if we can't find collect2.  */
6581       if (! strcmp (linker_name_spec, "collect2"))
6582         {
6583           char *s = find_a_file (&exec_prefixes, "collect2", X_OK, 0);
6584           if (s == NULL)
6585             linker_name_spec = "ld";
6586         }
6587       /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
6588          for collect.  */
6589       putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH");
6590       putenv_from_prefixes (&startfile_prefixes, LIBRARY_PATH_ENV);
6591
6592       value = do_spec (link_command_spec);
6593       if (value < 0)
6594         error_count = 1;
6595       linker_was_run = (tmp != execution_count);
6596     }
6597
6598   /* If options said don't run linker,
6599      complain about input files to be given to the linker.  */
6600
6601   if (! linker_was_run && error_count == 0)
6602     for (i = 0; (int) i < n_infiles; i++)
6603       if (explicit_link_files[i])
6604         error ("%s: linker input file unused because linking not done",
6605                outfiles[i]);
6606
6607   /* Delete some or all of the temporary files we made.  */
6608
6609   if (error_count)
6610     delete_failure_queue ();
6611   delete_temp_files ();
6612
6613   if (print_help_list)
6614     {
6615       printf (("\nFor bug reporting instructions, please see:\n"));
6616       printf ("%s\n", bug_report_url);
6617     }
6618
6619   return (signal_count != 0 ? 2
6620           : error_count > 0 ? (pass_exit_codes ? greatest_status : 1)
6621           : 0);
6622 }
6623
6624 /* Find the proper compilation spec for the file name NAME,
6625    whose length is LENGTH.  LANGUAGE is the specified language,
6626    or 0 if this file is to be passed to the linker.  */
6627
6628 static struct compiler *
6629 lookup_compiler (const char *name, size_t length, const char *language)
6630 {
6631   struct compiler *cp;
6632
6633   /* If this was specified by the user to be a linker input, indicate that.  */
6634   if (language != 0 && language[0] == '*')
6635     return 0;
6636
6637   /* Otherwise, look for the language, if one is spec'd.  */
6638   if (language != 0)
6639     {
6640       for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
6641         if (cp->suffix[0] == '@' && !strcmp (cp->suffix + 1, language))
6642           return cp;
6643
6644       error ("language %s not recognized", language);
6645       return 0;
6646     }
6647
6648   /* Look for a suffix.  */
6649   for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
6650     {
6651       if (/* The suffix `-' matches only the file name `-'.  */
6652           (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
6653           || (strlen (cp->suffix) < length
6654               /* See if the suffix matches the end of NAME.  */
6655               && !strcmp (cp->suffix,
6656                           name + length - strlen (cp->suffix))
6657          ))
6658         break;
6659     }
6660
6661 #if defined (OS2) ||defined (HAVE_DOS_BASED_FILE_SYSTEM)
6662   /* Look again, but case-insensitively this time.  */
6663   if (cp < compilers)
6664     for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
6665       {
6666         if (/* The suffix `-' matches only the file name `-'.  */
6667             (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
6668             || (strlen (cp->suffix) < length
6669                 /* See if the suffix matches the end of NAME.  */
6670                 && ((!strcmp (cp->suffix,
6671                              name + length - strlen (cp->suffix))
6672                      || !strpbrk (cp->suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
6673                     && !strcasecmp (cp->suffix,
6674                                     name + length - strlen (cp->suffix)))
6675            ))
6676           break;
6677       }
6678 #endif
6679
6680   if (cp >= compilers)
6681     {
6682       if (cp->spec[0] != '@')
6683         /* A non-alias entry: return it.  */
6684         return cp;
6685
6686       /* An alias entry maps a suffix to a language.
6687          Search for the language; pass 0 for NAME and LENGTH
6688          to avoid infinite recursion if language not found.  */
6689       return lookup_compiler (NULL, 0, cp->spec + 1);
6690     }
6691   return 0;
6692 }
6693 \f
6694 static char *
6695 save_string (const char *s, int len)
6696 {
6697   char *result = xmalloc (len + 1);
6698
6699   memcpy (result, s, len);
6700   result[len] = 0;
6701   return result;
6702 }
6703
6704 void
6705 pfatal_with_name (const char *name)
6706 {
6707   perror_with_name (name);
6708   delete_temp_files ();
6709   exit (1);
6710 }
6711
6712 static void
6713 perror_with_name (const char *name)
6714 {
6715   error ("%s: %s", name, xstrerror (errno));
6716 }
6717
6718 /* Output an error message and exit.  */
6719
6720 void
6721 fancy_abort (const char *file, int line, const char *func)
6722 {
6723   fatal ("internal gcc abort in %s, at %s:%d", func, file, line);
6724 }
6725 \f
6726 /* Output an error message and exit.  */
6727
6728 void
6729 fatal (const char *cmsgid, ...)
6730 {
6731   va_list ap;
6732
6733   va_start (ap, cmsgid);
6734
6735   fprintf (stderr, "%s: ", programname);
6736   vfprintf (stderr, _(cmsgid), ap);
6737   va_end (ap);
6738   fprintf (stderr, "\n");
6739   delete_temp_files ();
6740   exit (1);
6741 }
6742
6743 /* The argument is actually c-format, not gcc-internal-format,
6744    but because functions with identical names are used through
6745    the rest of the compiler with gcc-internal-format, we just
6746    need to hope all users of these functions use the common
6747    subset between c-format and gcc-internal-format.  */
6748
6749 void
6750 error (const char *gmsgid, ...)
6751 {
6752   va_list ap;
6753
6754   va_start (ap, gmsgid);
6755   fprintf (stderr, "%s: ", programname);
6756   vfprintf (stderr, _(gmsgid), ap);
6757   va_end (ap);
6758
6759   fprintf (stderr, "\n");
6760 }
6761
6762 static void
6763 notice (const char *cmsgid, ...)
6764 {
6765   va_list ap;
6766
6767   va_start (ap, cmsgid);
6768   vfprintf (stderr, _(cmsgid), ap);
6769   va_end (ap);
6770 }
6771 \f
6772 static inline void
6773 validate_switches_from_spec (const char *spec)
6774 {
6775   const char *p = spec;
6776   char c;
6777   while ((c = *p++))
6778     if (c == '%' && (*p == '{' || *p == '<' || (*p == 'W' && *++p == '{')))
6779       /* We have a switch spec.  */
6780       p = validate_switches (p + 1);
6781 }
6782
6783 static void
6784 validate_all_switches (void)
6785 {
6786   struct compiler *comp;
6787   struct spec_list *spec;
6788
6789   for (comp = compilers; comp->spec; comp++)
6790     validate_switches_from_spec (comp->spec);
6791
6792   /* Look through the linked list of specs read from the specs file.  */
6793   for (spec = specs; spec; spec = spec->next)
6794     validate_switches_from_spec (*spec->ptr_spec);
6795
6796   validate_switches_from_spec (link_command_spec);
6797 }
6798
6799 /* Look at the switch-name that comes after START
6800    and mark as valid all supplied switches that match it.  */
6801
6802 static const char *
6803 validate_switches (const char *start)
6804 {
6805   const char *p = start;
6806   const char *atom;
6807   size_t len;
6808   int i;
6809   bool suffix = false;
6810   bool starred = false;
6811
6812 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
6813
6814 next_member:
6815   SKIP_WHITE ();
6816
6817   if (*p == '!')
6818     p++;
6819
6820   SKIP_WHITE ();
6821   if (*p == '.')
6822     suffix = true, p++;
6823
6824   atom = p;
6825   while (ISIDNUM (*p) || *p == '-' || *p == '+' || *p == '='
6826          || *p == ',' || *p == '.' || *p == '@')
6827     p++;
6828   len = p - atom;
6829
6830   if (*p == '*')
6831     starred = true, p++;
6832
6833   SKIP_WHITE ();
6834
6835   if (!suffix)
6836     {
6837       /* Mark all matching switches as valid.  */
6838       for (i = 0; i < n_switches; i++)
6839         if (!strncmp (switches[i].part1, atom, len)
6840             && (starred || switches[i].part1[len] == 0))
6841           switches[i].validated = 1;
6842     }
6843
6844   if (*p) p++;
6845   if (*p && (p[-1] == '|' || p[-1] == '&'))
6846     goto next_member;
6847
6848   if (*p && p[-1] == ':')
6849     {
6850       while (*p && *p != ';' && *p != '}')
6851         {
6852           if (*p == '%')
6853             {
6854               p++;
6855               if (*p == '{' || *p == '<')
6856                 p = validate_switches (p+1);
6857               else if (p[0] == 'W' && p[1] == '{')
6858                 p = validate_switches (p+2);
6859             }
6860           else
6861             p++;
6862         }
6863
6864       if (*p) p++;
6865       if (*p && p[-1] == ';')
6866         goto next_member;
6867     }
6868
6869   return p;
6870 #undef SKIP_WHITE
6871 }
6872 \f
6873 struct mdswitchstr
6874 {
6875   const char *str;
6876   int len;
6877 };
6878
6879 static struct mdswitchstr *mdswitches;
6880 static int n_mdswitches;
6881
6882 /* Check whether a particular argument was used.  The first time we
6883    canonicalize the switches to keep only the ones we care about.  */
6884
6885 static int
6886 used_arg (const char *p, int len)
6887 {
6888   struct mswitchstr
6889   {
6890     const char *str;
6891     const char *replace;
6892     int len;
6893     int rep_len;
6894   };
6895
6896   static struct mswitchstr *mswitches;
6897   static int n_mswitches;
6898   int i, j;
6899
6900   if (!mswitches)
6901     {
6902       struct mswitchstr *matches;
6903       const char *q;
6904       int cnt = 0;
6905
6906       /* Break multilib_matches into the component strings of string
6907          and replacement string.  */
6908       for (q = multilib_matches; *q != '\0'; q++)
6909         if (*q == ';')
6910           cnt++;
6911
6912       matches = alloca ((sizeof (struct mswitchstr)) * cnt);
6913       i = 0;
6914       q = multilib_matches;
6915       while (*q != '\0')
6916         {
6917           matches[i].str = q;
6918           while (*q != ' ')
6919             {
6920               if (*q == '\0')
6921                 {
6922                 invalid_matches:
6923                   fatal ("multilib spec '%s' is invalid", multilib_matches);
6924                 }
6925               q++;
6926             }
6927           matches[i].len = q - matches[i].str;
6928
6929           matches[i].replace = ++q;
6930           while (*q != ';' && *q != '\0')
6931             {
6932               if (*q == ' ')
6933                 goto invalid_matches;
6934               q++;
6935             }
6936           matches[i].rep_len = q - matches[i].replace;
6937           i++;
6938           if (*q == ';')
6939             q++;
6940         }
6941
6942       /* Now build a list of the replacement string for switches that we care
6943          about.  Make sure we allocate at least one entry.  This prevents
6944          xmalloc from calling fatal, and prevents us from re-executing this
6945          block of code.  */
6946       mswitches
6947         = xmalloc (sizeof (struct mswitchstr)
6948                    * (n_mdswitches + (n_switches ? n_switches : 1)));
6949       for (i = 0; i < n_switches; i++)
6950         if (switches[i].live_cond != SWITCH_IGNORE)
6951           {
6952             int xlen = strlen (switches[i].part1);
6953             for (j = 0; j < cnt; j++)
6954               if (xlen == matches[j].len
6955                   && ! strncmp (switches[i].part1, matches[j].str, xlen))
6956                 {
6957                   mswitches[n_mswitches].str = matches[j].replace;
6958                   mswitches[n_mswitches].len = matches[j].rep_len;
6959                   mswitches[n_mswitches].replace = (char *) 0;
6960                   mswitches[n_mswitches].rep_len = 0;
6961                   n_mswitches++;
6962                   break;
6963                 }
6964           }
6965
6966       /* Add MULTILIB_DEFAULTS switches too, as long as they were not present
6967          on the command line nor any options mutually incompatible with
6968          them.  */
6969       for (i = 0; i < n_mdswitches; i++)
6970         {
6971           const char *r;
6972
6973           for (q = multilib_options; *q != '\0'; q++)
6974             {
6975               while (*q == ' ')
6976                 q++;
6977
6978               r = q;
6979               while (strncmp (q, mdswitches[i].str, mdswitches[i].len) != 0
6980                      || strchr (" /", q[mdswitches[i].len]) == NULL)
6981                 {
6982                   while (*q != ' ' && *q != '/' && *q != '\0')
6983                     q++;
6984                   if (*q != '/')
6985                     break;
6986                   q++;
6987                 }
6988
6989               if (*q != ' ' && *q != '\0')
6990                 {
6991                   while (*r != ' ' && *r != '\0')
6992                     {
6993                       q = r;
6994                       while (*q != ' ' && *q != '/' && *q != '\0')
6995                         q++;
6996
6997                       if (used_arg (r, q - r))
6998                         break;
6999
7000                       if (*q != '/')
7001                         {
7002                           mswitches[n_mswitches].str = mdswitches[i].str;
7003                           mswitches[n_mswitches].len = mdswitches[i].len;
7004                           mswitches[n_mswitches].replace = (char *) 0;
7005                           mswitches[n_mswitches].rep_len = 0;
7006                           n_mswitches++;
7007                           break;
7008                         }
7009
7010                       r = q + 1;
7011                     }
7012                   break;
7013                 }
7014             }
7015         }
7016     }
7017
7018   for (i = 0; i < n_mswitches; i++)
7019     if (len == mswitches[i].len && ! strncmp (p, mswitches[i].str, len))
7020       return 1;
7021
7022   return 0;
7023 }
7024
7025 static int
7026 default_arg (const char *p, int len)
7027 {
7028   int i;
7029
7030   for (i = 0; i < n_mdswitches; i++)
7031     if (len == mdswitches[i].len && ! strncmp (p, mdswitches[i].str, len))
7032       return 1;
7033
7034   return 0;
7035 }
7036
7037 /* Work out the subdirectory to use based on the options. The format of
7038    multilib_select is a list of elements. Each element is a subdirectory
7039    name followed by a list of options followed by a semicolon. The format
7040    of multilib_exclusions is the same, but without the preceding
7041    directory. First gcc will check the exclusions, if none of the options
7042    beginning with an exclamation point are present, and all of the other
7043    options are present, then we will ignore this completely. Passing
7044    that, gcc will consider each multilib_select in turn using the same
7045    rules for matching the options. If a match is found, that subdirectory
7046    will be used.  */
7047
7048 static void
7049 set_multilib_dir (void)
7050 {
7051   const char *p;
7052   unsigned int this_path_len;
7053   const char *this_path, *this_arg;
7054   const char *start, *end;
7055   int not_arg;
7056   int ok, ndfltok, first;
7057
7058   n_mdswitches = 0;
7059   start = multilib_defaults;
7060   while (*start == ' ' || *start == '\t')
7061     start++;
7062   while (*start != '\0')
7063     {
7064       n_mdswitches++;
7065       while (*start != ' ' && *start != '\t' && *start != '\0')
7066         start++;
7067       while (*start == ' ' || *start == '\t')
7068         start++;
7069     }
7070
7071   if (n_mdswitches)
7072     {
7073       int i = 0;
7074
7075       mdswitches = xmalloc (sizeof (struct mdswitchstr) * n_mdswitches);
7076       for (start = multilib_defaults; *start != '\0'; start = end + 1)
7077         {
7078           while (*start == ' ' || *start == '\t')
7079             start++;
7080
7081           if (*start == '\0')
7082             break;
7083
7084           for (end = start + 1;
7085                *end != ' ' && *end != '\t' && *end != '\0'; end++)
7086             ;
7087
7088           obstack_grow (&multilib_obstack, start, end - start);
7089           obstack_1grow (&multilib_obstack, 0);
7090           mdswitches[i].str = XOBFINISH (&multilib_obstack, const char *);
7091           mdswitches[i++].len = end - start;
7092
7093           if (*end == '\0')
7094             break;
7095         }
7096     }
7097
7098   p = multilib_exclusions;
7099   while (*p != '\0')
7100     {
7101       /* Ignore newlines.  */
7102       if (*p == '\n')
7103         {
7104           ++p;
7105           continue;
7106         }
7107
7108       /* Check the arguments.  */
7109       ok = 1;
7110       while (*p != ';')
7111         {
7112           if (*p == '\0')
7113             {
7114             invalid_exclusions:
7115               fatal ("multilib exclusions '%s' is invalid",
7116                      multilib_exclusions);
7117             }
7118
7119           if (! ok)
7120             {
7121               ++p;
7122               continue;
7123             }
7124
7125           this_arg = p;
7126           while (*p != ' ' && *p != ';')
7127             {
7128               if (*p == '\0')
7129                 goto invalid_exclusions;
7130               ++p;
7131             }
7132
7133           if (*this_arg != '!')
7134             not_arg = 0;
7135           else
7136             {
7137               not_arg = 1;
7138               ++this_arg;
7139             }
7140
7141           ok = used_arg (this_arg, p - this_arg);
7142           if (not_arg)
7143             ok = ! ok;
7144
7145           if (*p == ' ')
7146             ++p;
7147         }
7148
7149       if (ok)
7150         return;
7151
7152       ++p;
7153     }
7154
7155   first = 1;
7156   p = multilib_select;
7157   while (*p != '\0')
7158     {
7159       /* Ignore newlines.  */
7160       if (*p == '\n')
7161         {
7162           ++p;
7163           continue;
7164         }
7165
7166       /* Get the initial path.  */
7167       this_path = p;
7168       while (*p != ' ')
7169         {
7170           if (*p == '\0')
7171             {
7172             invalid_select:
7173               fatal ("multilib select '%s' is invalid",
7174                      multilib_select);
7175             }
7176           ++p;
7177         }
7178       this_path_len = p - this_path;
7179
7180       /* Check the arguments.  */
7181       ok = 1;
7182       ndfltok = 1;
7183       ++p;
7184       while (*p != ';')
7185         {
7186           if (*p == '\0')
7187             goto invalid_select;
7188
7189           if (! ok)
7190             {
7191               ++p;
7192               continue;
7193             }
7194
7195           this_arg = p;
7196           while (*p != ' ' && *p != ';')
7197             {
7198               if (*p == '\0')
7199                 goto invalid_select;
7200               ++p;
7201             }
7202
7203           if (*this_arg != '!')
7204             not_arg = 0;
7205           else
7206             {
7207               not_arg = 1;
7208               ++this_arg;
7209             }
7210
7211           /* If this is a default argument, we can just ignore it.
7212              This is true even if this_arg begins with '!'.  Beginning
7213              with '!' does not mean that this argument is necessarily
7214              inappropriate for this library: it merely means that
7215              there is a more specific library which uses this
7216              argument.  If this argument is a default, we need not
7217              consider that more specific library.  */
7218           ok = used_arg (this_arg, p - this_arg);
7219           if (not_arg)
7220             ok = ! ok;
7221
7222           if (! ok)
7223             ndfltok = 0;
7224
7225           if (default_arg (this_arg, p - this_arg))
7226             ok = 1;
7227
7228           if (*p == ' ')
7229             ++p;
7230         }
7231
7232       if (ok && first)
7233         {
7234           if (this_path_len != 1
7235               || this_path[0] != '.')
7236             {
7237               char *new_multilib_dir = xmalloc (this_path_len + 1);
7238               char *q;
7239
7240               strncpy (new_multilib_dir, this_path, this_path_len);
7241               new_multilib_dir[this_path_len] = '\0';
7242               q = strchr (new_multilib_dir, ':');
7243               if (q != NULL)
7244                 *q = '\0';
7245               multilib_dir = new_multilib_dir;
7246             }
7247           first = 0;
7248         }
7249
7250       if (ndfltok)
7251         {
7252           const char *q = this_path, *end = this_path + this_path_len;
7253
7254           while (q < end && *q != ':')
7255             q++;
7256           if (q < end)
7257             {
7258               char *new_multilib_os_dir = xmalloc (end - q);
7259               memcpy (new_multilib_os_dir, q + 1, end - q - 1);
7260               new_multilib_os_dir[end - q - 1] = '\0';
7261               multilib_os_dir = new_multilib_os_dir;
7262               break;
7263             }
7264         }
7265
7266       ++p;
7267     }
7268
7269   if (multilib_dir == NULL && multilib_os_dir != NULL
7270       && strcmp (multilib_os_dir, ".") == 0)
7271     {
7272       free ((char *) multilib_os_dir);
7273       multilib_os_dir = NULL;
7274     }
7275   else if (multilib_dir != NULL && multilib_os_dir == NULL)
7276     multilib_os_dir = multilib_dir;
7277 }
7278
7279 /* Print out the multiple library subdirectory selection
7280    information.  This prints out a series of lines.  Each line looks
7281    like SUBDIRECTORY;@OPTION@OPTION, with as many options as is
7282    required.  Only the desired options are printed out, the negative
7283    matches.  The options are print without a leading dash.  There are
7284    no spaces to make it easy to use the information in the shell.
7285    Each subdirectory is printed only once.  This assumes the ordering
7286    generated by the genmultilib script. Also, we leave out ones that match
7287    the exclusions.  */
7288
7289 static void
7290 print_multilib_info (void)
7291 {
7292   const char *p = multilib_select;
7293   const char *last_path = 0, *this_path;
7294   int skip;
7295   unsigned int last_path_len = 0;
7296
7297   while (*p != '\0')
7298     {
7299       skip = 0;
7300       /* Ignore newlines.  */
7301       if (*p == '\n')
7302         {
7303           ++p;
7304           continue;
7305         }
7306
7307       /* Get the initial path.  */
7308       this_path = p;
7309       while (*p != ' ')
7310         {
7311           if (*p == '\0')
7312             {
7313             invalid_select:
7314               fatal ("multilib select '%s' is invalid", multilib_select);
7315             }
7316           
7317           ++p;
7318         }
7319
7320       /* When --disable-multilib was used but target defines
7321          MULTILIB_OSDIRNAMES, entries starting with .: are there just
7322          to find multilib_os_dir, so skip them from output.  */
7323       if (this_path[0] == '.' && this_path[1] == ':')
7324         skip = 1;
7325
7326       /* Check for matches with the multilib_exclusions. We don't bother
7327          with the '!' in either list. If any of the exclusion rules match
7328          all of its options with the select rule, we skip it.  */
7329       {
7330         const char *e = multilib_exclusions;
7331         const char *this_arg;
7332
7333         while (*e != '\0')
7334           {
7335             int m = 1;
7336             /* Ignore newlines.  */
7337             if (*e == '\n')
7338               {
7339                 ++e;
7340                 continue;
7341               }
7342
7343             /* Check the arguments.  */
7344             while (*e != ';')
7345               {
7346                 const char *q;
7347                 int mp = 0;
7348
7349                 if (*e == '\0')
7350                   {
7351                   invalid_exclusion:
7352                     fatal ("multilib exclusion '%s' is invalid",
7353                            multilib_exclusions);
7354                   }
7355
7356                 if (! m)
7357                   {
7358                     ++e;
7359                     continue;
7360                   }
7361
7362                 this_arg = e;
7363
7364                 while (*e != ' ' && *e != ';')
7365                   {
7366                     if (*e == '\0')
7367                       goto invalid_exclusion;
7368                     ++e;
7369                   }
7370
7371                 q = p + 1;
7372                 while (*q != ';')
7373                   {
7374                     const char *arg;
7375                     int len = e - this_arg;
7376
7377                     if (*q == '\0')
7378                       goto invalid_select;
7379
7380                     arg = q;
7381
7382                     while (*q != ' ' && *q != ';')
7383                       {
7384                         if (*q == '\0')
7385                           goto invalid_select;
7386                         ++q;
7387                       }
7388
7389                     if (! strncmp (arg, this_arg,
7390                                    (len < q - arg) ? q - arg : len)
7391                         || default_arg (this_arg, e - this_arg))
7392                       {
7393                         mp = 1;
7394                         break;
7395                       }
7396
7397                     if (*q == ' ')
7398                       ++q;
7399                   }
7400
7401                 if (! mp)
7402                   m = 0;
7403
7404                 if (*e == ' ')
7405                   ++e;
7406               }
7407
7408             if (m)
7409               {
7410                 skip = 1;
7411                 break;
7412               }
7413
7414             if (*e != '\0')
7415               ++e;
7416           }
7417       }
7418
7419       if (! skip)
7420         {
7421           /* If this is a duplicate, skip it.  */
7422           skip = (last_path != 0
7423                   && (unsigned int) (p - this_path) == last_path_len
7424                   && ! strncmp (last_path, this_path, last_path_len));
7425
7426           last_path = this_path;
7427           last_path_len = p - this_path;
7428         }
7429
7430       /* If this directory requires any default arguments, we can skip
7431          it.  We will already have printed a directory identical to
7432          this one which does not require that default argument.  */
7433       if (! skip)
7434         {
7435           const char *q;
7436
7437           q = p + 1;
7438           while (*q != ';')
7439             {
7440               const char *arg;
7441
7442               if (*q == '\0')
7443                 goto invalid_select;
7444
7445               if (*q == '!')
7446                 arg = NULL;
7447               else
7448                 arg = q;
7449
7450               while (*q != ' ' && *q != ';')
7451                 {
7452                   if (*q == '\0')
7453                     goto invalid_select;
7454                   ++q;
7455                 }
7456
7457               if (arg != NULL
7458                   && default_arg (arg, q - arg))
7459                 {
7460                   skip = 1;
7461                   break;
7462                 }
7463
7464               if (*q == ' ')
7465                 ++q;
7466             }
7467         }
7468
7469       if (! skip)
7470         {
7471           const char *p1;
7472
7473           for (p1 = last_path; p1 < p && *p1 != ':'; p1++)
7474             putchar (*p1);
7475           putchar (';');
7476         }
7477
7478       ++p;
7479       while (*p != ';')
7480         {
7481           int use_arg;
7482
7483           if (*p == '\0')
7484             goto invalid_select;
7485
7486           if (skip)
7487             {
7488               ++p;
7489               continue;
7490             }
7491
7492           use_arg = *p != '!';
7493
7494           if (use_arg)
7495             putchar ('@');
7496
7497           while (*p != ' ' && *p != ';')
7498             {
7499               if (*p == '\0')
7500                 goto invalid_select;
7501               if (use_arg)
7502                 putchar (*p);
7503               ++p;
7504             }
7505
7506           if (*p == ' ')
7507             ++p;
7508         }
7509
7510       if (! skip)
7511         {
7512           /* If there are extra options, print them now.  */
7513           if (multilib_extra && *multilib_extra)
7514             {
7515               int print_at = TRUE;
7516               const char *q;
7517
7518               for (q = multilib_extra; *q != '\0'; q++)
7519                 {
7520                   if (*q == ' ')
7521                     print_at = TRUE;
7522                   else
7523                     {
7524                       if (print_at)
7525                         putchar ('@');
7526                       putchar (*q);
7527                       print_at = FALSE;
7528                     }
7529                 }
7530             }
7531
7532           putchar ('\n');
7533         }
7534
7535       ++p;
7536     }
7537 }
7538 \f
7539 /* if-exists built-in spec function.
7540
7541    Checks to see if the file specified by the absolute pathname in
7542    ARGS exists.  Returns that pathname if found.
7543
7544    The usual use for this function is to check for a library file
7545    (whose name has been expanded with %s).  */
7546
7547 static const char *
7548 if_exists_spec_function (int argc, const char **argv)
7549 {
7550   /* Must have only one argument.  */
7551   if (argc == 1 && IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
7552     return argv[0];
7553
7554   return NULL;
7555 }
7556
7557 /* if-exists-else built-in spec function.
7558
7559    This is like if-exists, but takes an additional argument which
7560    is returned if the first argument does not exist.  */
7561
7562 static const char *
7563 if_exists_else_spec_function (int argc, const char **argv)
7564 {
7565   /* Must have exactly two arguments.  */
7566   if (argc != 2)
7567     return NULL;
7568
7569   if (IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
7570     return argv[0];
7571
7572   return argv[1];
7573 }
7574
7575 /* replace-outfile built-in spec function.
7576    This looks for the first argument in the outfiles array's name and replaces it
7577    with the second argument.  */
7578
7579 static const char *
7580 replace_outfile_spec_function (int argc, const char **argv)
7581 {
7582   int i;
7583   /* Must have exactly two arguments.  */
7584   if (argc != 2)
7585     abort ();
7586   
7587   for (i = 0; i < n_infiles; i++)
7588     {
7589       if (outfiles[i] && !strcmp (outfiles[i], argv[0]))
7590         outfiles[i] = xstrdup (argv[1]);
7591     }
7592   return NULL;
7593 }
7594