OSDN Git Service

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