OSDN Git Service

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