OSDN Git Service

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