OSDN Git Service

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