OSDN Git Service

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