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