OSDN Git Service

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