OSDN Git Service

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