OSDN Git Service

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