OSDN Git Service

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