OSDN Git Service

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