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