OSDN Git Service

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