OSDN Git Service

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