OSDN Git Service

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