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