OSDN Git Service

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