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