OSDN Git Service

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