OSDN Git Service

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