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