OSDN Git Service

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