OSDN Git Service

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