OSDN Git Service

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