OSDN Git Service

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