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