OSDN Git Service

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