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