OSDN Git Service

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