OSDN Git Service

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