OSDN Git Service

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