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