OSDN Git Service

include/
[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, 2002 Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 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 #if ! defined( SIGCHLD ) && defined( SIGCLD )
77 #  define SIGCHLD SIGCLD
78 #endif
79 #include "obstack.h"
80 #include "intl.h"
81 #include "prefix.h"
82 #include "gcc.h"
83 #include "flags.h"
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 target executables.  */
93 /* FIXME: when autoconf is fixed, remove the host check - dj */
94 #if defined(TARGET_EXECUTABLE_SUFFIX) && defined(HOST_EXECUTABLE_SUFFIX)
95 #define HAVE_TARGET_EXECUTABLE_SUFFIX
96 #endif
97
98 /* By default there is no special suffix for host executables.  */
99 #ifdef HOST_EXECUTABLE_SUFFIX
100 #define HAVE_HOST_EXECUTABLE_SUFFIX
101 #else
102 #define HOST_EXECUTABLE_SUFFIX ""
103 #endif
104
105 /* By default, the suffix for target object files is ".o".  */
106 #ifdef TARGET_OBJECT_SUFFIX
107 #define HAVE_TARGET_OBJECT_SUFFIX
108 #else
109 #define TARGET_OBJECT_SUFFIX ".o"
110 #endif
111
112 #ifndef VMS
113 /* FIXME: the location independence code for VMS is hairier than this,
114    and hasn't been written.  */
115 #ifndef DIR_UP
116 #define DIR_UP ".."
117 #endif /* DIR_UP */
118 #endif /* VMS */
119
120 static const char dir_separator_str[] = { DIR_SEPARATOR, 0 };
121
122 /* Most every one is fine with LIBRARY_PATH.  For some, it conflicts.  */
123 #ifndef LIBRARY_PATH_ENV
124 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
125 #endif
126
127 #ifndef HAVE_KILL
128 #define kill(p,s) raise(s)
129 #endif
130
131 /* If a stage of compilation returns an exit status >= 1,
132    compilation of that file ceases.  */
133
134 #define MIN_FATAL_STATUS 1
135
136 /* Flag set by cppspec.c to 1.  */
137 int is_cpp_driver;
138
139 /* Flag saying to pass the greatest exit code returned by a sub-process
140    to the calling program.  */
141 static int pass_exit_codes;
142
143 /* Definition of string containing the arguments given to configure.  */
144 #include "configargs.h"
145
146 /* Flag saying to print the directories gcc will search through looking for
147    programs, libraries, etc.  */
148
149 static int print_search_dirs;
150
151 /* Flag saying to print the full filename of this file
152    as found through our usual search mechanism.  */
153
154 static const char *print_file_name = NULL;
155
156 /* As print_file_name, but search for executable file.  */
157
158 static const char *print_prog_name = NULL;
159
160 /* Flag saying to print the relative path we'd use to
161    find libgcc.a given the current compiler flags.  */
162
163 static int print_multi_directory;
164
165 /* Flag saying to print the relative path we'd use to
166    find OS libraries given the current compiler flags.  */
167
168 static int print_multi_os_directory;
169
170 /* Flag saying to print the list of subdirectories and
171    compiler flags used to select them in a standard form.  */
172
173 static int print_multi_lib;
174
175 /* Flag saying to print the command line options understood by gcc and its
176    sub-processes.  */
177
178 static int print_help_list;
179
180 /* Flag indicating whether we should print the command and arguments */
181
182 static int verbose_flag;
183
184 /* Flag indicating whether we should ONLY print the command and
185    arguments (like verbose_flag) without executing the command.
186    Displayed arguments are quoted so that the generated command
187    line is suitable for execution.  This is intended for use in
188    shell scripts to capture the driver-generated command line.  */
189 static int verbose_only_flag;
190
191 /* Flag indicating to print target specific command line options.  */
192
193 static int target_help_flag;
194
195 /* Flag indicating whether we should report subprocess execution times
196    (if this is supported by the system - see pexecute.c).  */
197
198 static int report_times;
199
200 /* Nonzero means write "temp" files in source directory
201    and use the source file's name in them, and don't delete them.  */
202
203 static int save_temps_flag;
204
205 /* The compiler version.  */
206
207 static const char *compiler_version;
208
209 /* The target version specified with -V */
210
211 static const char *const spec_version = DEFAULT_TARGET_VERSION;
212
213 /* The target machine specified with -b.  */
214
215 static const char *spec_machine = DEFAULT_TARGET_MACHINE;
216
217 /* Nonzero if cross-compiling.
218    When -b is used, the value comes from the `specs' file.  */
219
220 #ifdef CROSS_COMPILE
221 static const char *cross_compile = "1";
222 #else
223 static const char *cross_compile = "0";
224 #endif
225
226 #ifdef MODIFY_TARGET_NAME
227
228 /* Information on how to alter the target name based on a command-line
229    switch.  The only case we support now is simply appending or deleting a
230    string to or from the end of the first part of the configuration name.  */
231
232 static const struct modify_target
233 {
234   const char *const sw;
235   const enum add_del {ADD, DELETE} add_del;
236   const char *const str;
237 }
238 modify_target[] = MODIFY_TARGET_NAME;
239 #endif
240
241 /* The number of errors that have occurred; the link phase will not be
242    run if this is nonzero.  */
243 static int error_count = 0;
244
245 /* Greatest exit code of sub-processes that has been encountered up to
246    now.  */
247 static int greatest_status = 1;
248
249 /* This is the obstack which we use to allocate many strings.  */
250
251 static struct obstack obstack;
252
253 /* This is the obstack to build an environment variable to pass to
254    collect2 that describes all of the relevant switches of what to
255    pass the compiler in building the list of pointers to constructors
256    and destructors.  */
257
258 static struct obstack collect_obstack;
259
260 /* These structs are used to collect resource usage information for
261    subprocesses.  */
262 #ifdef HAVE_GETRUSAGE
263 static struct rusage rus, prus;
264 #endif
265
266 /* Forward declaration for prototypes.  */
267 struct path_prefix;
268
269 static void init_spec           PARAMS ((void));
270 static void store_arg           PARAMS ((const char *, int, int));
271 static char *load_specs         PARAMS ((const char *));
272 static void read_specs          PARAMS ((const char *, int));
273 static void set_spec            PARAMS ((const char *, const char *));
274 static struct compiler *lookup_compiler PARAMS ((const char *, size_t, const char *));
275 static char *build_search_list  PARAMS ((struct path_prefix *, const char *, int));
276 static void putenv_from_prefixes PARAMS ((struct path_prefix *, const char *));
277 static int access_check         PARAMS ((const char *, int));
278 static char *find_a_file        PARAMS ((struct path_prefix *, const char *,
279                                          int, int));
280 static void add_prefix          PARAMS ((struct path_prefix *, const char *,
281                                          const char *, int, int, int *, int));
282 static void translate_options   PARAMS ((int *, const char *const **));
283 static char *skip_whitespace    PARAMS ((char *));
284 static void delete_if_ordinary  PARAMS ((const char *));
285 static void delete_temp_files   PARAMS ((void));
286 static void delete_failure_queue PARAMS ((void));
287 static void clear_failure_queue PARAMS ((void));
288 static int check_live_switch    PARAMS ((int, int));
289 static const char *handle_braces PARAMS ((const char *));
290 static const struct spec_function *lookup_spec_function PARAMS ((const char *));
291 static const char *eval_spec_function   PARAMS ((const char *, const char *));
292 static const char *handle_spec_function PARAMS ((const char *));
293 static char *save_string        PARAMS ((const char *, int));
294 static void set_collect_gcc_options PARAMS ((void));
295 static int do_spec_1            PARAMS ((const char *, int, const char *));
296 static int do_spec_2            PARAMS ((const char *));
297 static void do_self_spec        PARAMS ((const char *));
298 static const char *find_file    PARAMS ((const char *));
299 static int is_directory         PARAMS ((const char *, const char *, int));
300 static void validate_switches   PARAMS ((const char *));
301 static void validate_all_switches PARAMS ((void));
302 static void give_switch         PARAMS ((int, int, int));
303 static int used_arg             PARAMS ((const char *, int));
304 static int default_arg          PARAMS ((const char *, int));
305 static void set_multilib_dir    PARAMS ((void));
306 static void print_multilib_info PARAMS ((void));
307 static void perror_with_name    PARAMS ((const char *));
308 static void pfatal_pexecute     PARAMS ((const char *, const char *))
309   ATTRIBUTE_NORETURN;
310 static void notice              PARAMS ((const char *, ...))
311   ATTRIBUTE_PRINTF_1;
312 static void display_help        PARAMS ((void));
313 static void add_preprocessor_option     PARAMS ((const char *, int));
314 static void add_assembler_option        PARAMS ((const char *, int));
315 static void add_linker_option           PARAMS ((const char *, int));
316 static void process_command             PARAMS ((int, const char *const *));
317 static int execute                      PARAMS ((void));
318 static void alloc_args                  PARAMS ((void));
319 static void clear_args                  PARAMS ((void));
320 static void fatal_error                 PARAMS ((int));
321 #ifdef ENABLE_SHARED_LIBGCC
322 static void init_gcc_specs              PARAMS ((struct obstack *,
323                                                  const char *, const char *,
324                                                  const char *));
325 #endif
326 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
327 static const char *convert_filename     PARAMS ((const char *, int, int));
328 #endif
329
330 static const char *if_exists_spec_function PARAMS ((int, const char **));
331 \f
332 /* The Specs Language
333
334 Specs are strings containing lines, each of which (if not blank)
335 is made up of a program name, and arguments separated by spaces.
336 The program name must be exact and start from root, since no path
337 is searched and it is unreliable to depend on the current working directory.
338 Redirection of input or output is not supported; the subprograms must
339 accept filenames saying what files to read and write.
340
341 In addition, the specs can contain %-sequences to substitute variable text
342 or for conditional text.  Here is a table of all defined %-sequences.
343 Note that spaces are not generated automatically around the results of
344 expanding these sequences; therefore, you can concatenate them together
345 or with constant text in a single argument.
346
347  %%     substitute one % into the program name or argument.
348  %i     substitute the name of the input file being processed.
349  %b     substitute the basename of the input file being processed.
350         This is the substring up to (and not including) the last period
351         and not including the directory.
352  %B     same as %b, but include the file suffix (text after the last period).
353  %gSUFFIX
354         substitute a file name that has suffix SUFFIX and is chosen
355         once per compilation, and mark the argument a la %d.  To reduce
356         exposure to denial-of-service attacks, the file name is now
357         chosen in a way that is hard to predict even when previously
358         chosen file names are known.  For example, `%g.s ... %g.o ... %g.s'
359         might turn into `ccUVUUAU.s ccXYAXZ12.o ccUVUUAU.s'.  SUFFIX matches
360         the regexp "[.A-Za-z]*%O"; "%O" is treated exactly as if it
361         had been pre-processed.  Previously, %g was simply substituted
362         with a file name chosen once per compilation, without regard
363         to any appended suffix (which was therefore treated just like
364         ordinary text), making such attacks more likely to succeed.
365  %uSUFFIX
366         like %g, but generates a new temporary file name even if %uSUFFIX
367         was already seen.
368  %USUFFIX
369         substitutes the last file name generated with %uSUFFIX, generating a
370         new one if there is no such last file name.  In the absence of any
371         %uSUFFIX, this is just like %gSUFFIX, except they don't share
372         the same suffix "space", so `%g.s ... %U.s ... %g.s ... %U.s'
373         would involve the generation of two distinct file names, one
374         for each `%g.s' and another for each `%U.s'.  Previously, %U was
375         simply substituted with a file name chosen for the previous %u,
376         without regard to any appended suffix.
377  %jSUFFIX
378         substitutes the name of the HOST_BIT_BUCKET, if any, and if it is
379         writable, and if save-temps is off; otherwise, substitute the name
380         of a temporary file, just like %u.  This temporary file is not
381         meant for communication between processes, but rather as a junk
382         disposal mechanism.
383  %.SUFFIX
384         substitutes .SUFFIX for the suffixes of a matched switch's args when
385         it is subsequently output with %*. SUFFIX is terminated by the next
386         space or %.
387  %d     marks the argument containing or following the %d as a
388         temporary file name, so that that file will be deleted if CC exits
389         successfully.  Unlike %g, this contributes no text to the argument.
390  %w     marks the argument containing or following the %w as the
391         "output file" of this compilation.  This puts the argument
392         into the sequence of arguments that %o will substitute later.
393  %W{...}
394         like %{...} but mark last argument supplied within
395         as a file to be deleted on failure.
396  %o     substitutes the names of all the output files, with spaces
397         automatically placed around them.  You should write spaces
398         around the %o as well or the results are undefined.
399         %o is for use in the specs for running the linker.
400         Input files whose names have no recognized suffix are not compiled
401         at all, but they are included among the output files, so they will
402         be linked.
403  %O     substitutes the suffix for object files.  Note that this is
404         handled specially when it immediately follows %g, %u, or %U
405         (with or without a suffix argument) because of the need for
406         those to form complete file names.  The handling is such that
407         %O is treated exactly as if it had already been substituted,
408         except that %g, %u, and %U do not currently support additional
409         SUFFIX characters following %O as they would following, for
410         example, `.o'.
411  %p     substitutes the standard macro predefinitions for the
412         current target machine.  Use this when running cpp.
413  %P     like %p, but puts `__' before and after the name of each macro.
414         (Except macros that already have __.)
415         This is for ANSI C.
416  %I     Substitute a -iprefix option made from GCC_EXEC_PREFIX.
417  %s     current argument is the name of a library or startup file of some sort.
418         Search for that file in a standard list of directories
419         and substitute the full name found.
420  %eSTR  Print STR as an error message.  STR is terminated by a newline.
421         Use this when inconsistent options are detected.
422  %nSTR  Print STR as an notice.  STR is terminated by a newline.
423  %x{OPTION}     Accumulate an option for %X.
424  %X     Output the accumulated linker options specified by compilations.
425  %Y     Output the accumulated assembler options specified by compilations.
426  %Z     Output the accumulated preprocessor options specified by compilations.
427  %v1    Substitute the major version number of GCC.
428         (For version 2.5.3, this is 2.)
429  %v2    Substitute the minor version number of GCC.
430         (For version 2.5.3, this is 5.)
431  %v3    Substitute the patch level number of GCC.
432         (For version 2.5.3, this is 3.)
433  %a     process ASM_SPEC as a spec.
434         This allows config.h to specify part of the spec for running as.
435  %A     process ASM_FINAL_SPEC as a spec.  A capital A is actually
436         used here.  This can be used to run a post-processor after the
437         assembler has done its job.
438  %D     Dump out a -L option for each directory in startfile_prefixes.
439         If multilib_dir is set, extra entries are generated with it affixed.
440  %l     process LINK_SPEC as a spec.
441  %L     process LIB_SPEC as a spec.
442  %G     process LIBGCC_SPEC as a spec.
443  %M     output multilib_dir with directory separators replaced with "_";
444         if multilib_dir is not set or is ".", output "".
445  %S     process STARTFILE_SPEC as a spec.  A capital S is actually used here.
446  %E     process ENDFILE_SPEC as a spec.  A capital E is actually used here.
447  %C     process CPP_SPEC as a spec.
448  %1     process CC1_SPEC as a spec.
449  %2     process CC1PLUS_SPEC as a spec.
450  %|     output "-" if the input for the current command is coming from a pipe.
451  %*     substitute the variable part of a matched option.  (See below.)
452         Note that each comma in the substituted string is replaced by
453         a single space.
454  %:function(args)
455         Call the named function FUNCTION, passing it ARGS.  ARGS is
456         first processed as a nested spec string, then split into an
457         argument vector in the usual fashion.  The function returns
458         a string which is processed as if it had appeared literally
459         as part of the current spec.
460  %{S}   substitutes the -S switch, if that switch was given to CC.
461         If that switch was not specified, this substitutes nothing.
462         Here S is a metasyntactic variable.
463  %{S*}  substitutes all the switches specified to CC whose names start
464         with -S.  This is used for -o, -I, etc; switches that take
465         arguments.  CC considers `-o foo' as being one switch whose
466         name starts with `o'.  %{o*} would substitute this text,
467         including the space; thus, two arguments would be generated.
468  %{^S*} likewise, but don't put a blank between a switch and any args.
469  %{S*&T*} likewise, but preserve order of S and T options (the order
470         of S and T in the spec is not significant).  Can be any number
471         of ampersand-separated variables; for each the wild card is
472         optional.  Useful for CPP as %{D*&U*&A*}.
473  %{S*:X} substitutes X if one or more switches whose names start with -S are
474         specified to CC.  Note that the tail part of the -S option
475         (i.e. the part matched by the `*') will be substituted for each
476         occurrence of %* within X.
477  %{<S}  remove all occurrences of -S from the command line.
478         Note - this option is position dependent.  % commands in the
479         spec string before this option will see -S, % commands in the
480         spec string after this option will not.
481  %{S:X} substitutes X, but only if the -S switch was given to CC.
482  %{!S:X} substitutes X, but only if the -S switch was NOT given to CC.
483  %{|S:X} like %{S:X}, but if no S switch, substitute `-'.
484  %{|!S:X} like %{!S:X}, but if there is an S switch, substitute `-'.
485  %{.S:X} substitutes X, but only if processing a file with suffix S.
486  %{!.S:X} substitutes X, but only if NOT processing a file with suffix S.
487  %{S|P:X} substitutes X if either -S or -P was given to CC.  This may be
488           combined with ! and . as above binding stronger than the OR.
489  %(Spec) processes a specification defined in a specs file as *Spec:
490  %[Spec] as above, but put __ around -D arguments
491
492 The conditional text X in a %{S:X} or %{!S:X} construct may contain
493 other nested % constructs or spaces, or even newlines.  They are
494 processed as usual, as described above.
495
496 The -O, -f, -m, and -W switches are handled specifically in these
497 constructs.  If another value of -O or the negated form of a -f, -m, or
498 -W switch is found later in the command line, the earlier switch
499 value is ignored, except with {S*} where S is just one letter; this
500 passes all matching options.
501
502 The character | at the beginning of the predicate text is used to indicate
503 that a command should be piped to the following command, but only if -pipe
504 is specified.
505
506 Note that it is built into CC which switches take arguments and which
507 do not.  You might think it would be useful to generalize this to
508 allow each compiler's spec to say which switches take arguments.  But
509 this cannot be done in a consistent fashion.  CC cannot even decide
510 which input files have been specified without knowing which switches
511 take arguments, and it must know which input files to compile in order
512 to tell which compilers to run.
513
514 CC also knows implicitly that arguments starting in `-l' are to be
515 treated as compiler output files, and passed to the linker in their
516 proper position among the other output files.  */
517 \f
518 /* Define the macros used for specs %a, %l, %L, %S, %C, %1.  */
519
520 /* config.h can define ASM_SPEC to provide extra args to the assembler
521    or extra switch-translations.  */
522 #ifndef ASM_SPEC
523 #define ASM_SPEC ""
524 #endif
525
526 /* config.h can define ASM_FINAL_SPEC to run a post processor after
527    the assembler has run.  */
528 #ifndef ASM_FINAL_SPEC
529 #define ASM_FINAL_SPEC ""
530 #endif
531
532 /* config.h can define CPP_SPEC to provide extra args to the C preprocessor
533    or extra switch-translations.  */
534 #ifndef CPP_SPEC
535 #define CPP_SPEC ""
536 #endif
537
538 /* config.h can define CC1_SPEC to provide extra args to cc1 and cc1plus
539    or extra switch-translations.  */
540 #ifndef CC1_SPEC
541 #define CC1_SPEC ""
542 #endif
543
544 /* config.h can define CC1PLUS_SPEC to provide extra args to cc1plus
545    or extra switch-translations.  */
546 #ifndef CC1PLUS_SPEC
547 #define CC1PLUS_SPEC ""
548 #endif
549
550 /* config.h can define LINK_SPEC to provide extra args to the linker
551    or extra switch-translations.  */
552 #ifndef LINK_SPEC
553 #define LINK_SPEC ""
554 #endif
555
556 /* config.h can define LIB_SPEC to override the default libraries.  */
557 #ifndef LIB_SPEC
558 #define LIB_SPEC "%{!shared:%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}}"
559 #endif
560
561 /* config.h can define LIBGCC_SPEC to override how and when libgcc.a is
562    included.  */
563 #ifndef LIBGCC_SPEC
564 #if defined(LINK_LIBGCC_SPECIAL) || defined(LINK_LIBGCC_SPECIAL_1)
565 /* Have gcc do the search for libgcc.a.  */
566 #define LIBGCC_SPEC "libgcc.a%s"
567 #else
568 #define LIBGCC_SPEC "-lgcc"
569 #endif
570 #endif
571
572 /* config.h can define STARTFILE_SPEC to override the default crt0 files.  */
573 #ifndef STARTFILE_SPEC
574 #define STARTFILE_SPEC  \
575   "%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
576 #endif
577
578 /* config.h can define SWITCHES_NEED_SPACES to control which options
579    require spaces between the option and the argument.  */
580 #ifndef SWITCHES_NEED_SPACES
581 #define SWITCHES_NEED_SPACES ""
582 #endif
583
584 /* config.h can define ENDFILE_SPEC to override the default crtn files.  */
585 #ifndef ENDFILE_SPEC
586 #define ENDFILE_SPEC ""
587 #endif
588
589 #ifndef LINKER_NAME
590 #define LINKER_NAME "collect2"
591 #endif
592
593 /* Define ASM_DEBUG_SPEC to be a spec suitable for translating '-g'
594    to the assembler.  */
595 #ifndef ASM_DEBUG_SPEC
596 # if defined(DBX_DEBUGGING_INFO) && defined(DWARF2_DEBUGGING_INFO) \
597      && defined(HAVE_AS_GDWARF2_DEBUG_FLAG) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
598 #  define ASM_DEBUG_SPEC                                        \
599       (PREFERRED_DEBUGGING_TYPE == DBX_DEBUG                    \
600        ? "%{gdwarf-2*:--gdwarf2}%{!gdwarf-2*:%{g*:--gstabs}}"   \
601        : "%{gstabs*:--gstabs}%{!gstabs*:%{g*:--gdwarf2}}")
602 # else
603 #  if defined(DBX_DEBUGGING_INFO) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
604 #   define ASM_DEBUG_SPEC "%{g*:--gstabs}"
605 #  endif
606 #  if defined(DWARF2_DEBUGGING_INFO) && defined(HAVE_AS_GDWARF2_DEBUG_FLAG)
607 #   define ASM_DEBUG_SPEC "%{g*:--gdwarf2}"
608 #  endif
609 # endif
610 #endif
611 #ifndef ASM_DEBUG_SPEC
612 # define ASM_DEBUG_SPEC ""
613 #endif
614
615 /* Here is the spec for running the linker, after compiling all files.  */
616
617 /* This is overridable by the target in case they need to specify the
618    -lgcc and -lc order specially, yet not require them to override all
619    of LINK_COMMAND_SPEC.  */
620 #ifndef LINK_GCC_C_SEQUENCE_SPEC
621 #define LINK_GCC_C_SEQUENCE_SPEC "%G %L %G"
622 #endif
623
624 /* -u* was put back because both BSD and SysV seem to support it.  */
625 /* %{static:} simply prevents an error message if the target machine
626    doesn't handle -static.  */
627 /* We want %{T*} after %{L*} and %D so that it can be used to specify linker
628    scripts which exist in user specified directories, or in standard
629    directories.  */
630 #ifndef LINK_COMMAND_SPEC
631 #define LINK_COMMAND_SPEC "\
632 %{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
633     %(linker) %l %X %{o*} %{A} %{d} %{e*} %{m} %{N} %{n} %{r} %{s} %{t}\
634     %{u*} %{x} %{z} %{Z} %{!A:%{!nostdlib:%{!nostartfiles:%S}}}\
635     %{static:} %{L*} %(link_libgcc) %o %{!nostdlib:%{!nodefaultlibs:%(link_gcc_c_sequence)}}\
636     %{!A:%{!nostdlib:%{!nostartfiles:%E}}} %{T*} }}}}}}"
637 #endif
638
639 #ifndef LINK_LIBGCC_SPEC
640 # ifdef LINK_LIBGCC_SPECIAL
641 /* Don't generate -L options for startfile prefix list.  */
642 #  define LINK_LIBGCC_SPEC ""
643 # else
644 /* Do generate them.  */
645 #  define LINK_LIBGCC_SPEC "%D"
646 # endif
647 #endif
648
649 #ifndef STARTFILE_PREFIX_SPEC
650 # define STARTFILE_PREFIX_SPEC ""
651 #endif
652
653 static const char *asm_debug;
654 static const char *cpp_spec = CPP_SPEC;
655 static const char *cpp_predefines = CPP_PREDEFINES;
656 static const char *cc1_spec = CC1_SPEC;
657 static const char *cc1plus_spec = CC1PLUS_SPEC;
658 static const char *link_gcc_c_sequence_spec = LINK_GCC_C_SEQUENCE_SPEC;
659 static const char *asm_spec = ASM_SPEC;
660 static const char *asm_final_spec = ASM_FINAL_SPEC;
661 static const char *link_spec = LINK_SPEC;
662 static const char *lib_spec = LIB_SPEC;
663 static const char *libgcc_spec = LIBGCC_SPEC;
664 static const char *endfile_spec = ENDFILE_SPEC;
665 static const char *startfile_spec = STARTFILE_SPEC;
666 static const char *switches_need_spaces = SWITCHES_NEED_SPACES;
667 static const char *linker_name_spec = LINKER_NAME;
668 static const char *link_command_spec = LINK_COMMAND_SPEC;
669 static const char *link_libgcc_spec = LINK_LIBGCC_SPEC;
670 static const char *startfile_prefix_spec = STARTFILE_PREFIX_SPEC;
671
672 /* Standard options to cpp, cc1, and as, to reduce duplication in specs.
673    There should be no need to override these in target dependent files,
674    but we need to copy them to the specs file so that newer versions
675    of the GCC driver can correctly drive older tool chains with the
676    appropriate -B options.  */
677
678 /* When cpplib handles traditional preprocessing, get rid of this, and
679    call cc1 (or cc1obj in objc/lang-specs.h) from the main specs so
680    that we default the front end language better.  */
681 static const char *trad_capable_cpp =
682 "cc1 -E %{traditional|ftraditional|traditional-cpp:-traditional-cpp}";
683
684 /* We don't wrap .d files in %W{} since a missing .d file, and
685    therefore no dependency entry, confuses make into thinking a .o
686    file that happens to exist is up-to-date.  */
687 static const char *cpp_unique_options =
688 "%{C:%{!E:%eGNU C does not support -C without using -E}}\
689  %{CC:%{!E:%eGNU C does not support -CC without using -E}}\
690  %{!Q:-quiet} %{nostdinc*} %{C} %{CC} %{v} %{I*} %{P} %I\
691  %{MD:-MD %{!o:%b.d}%{o*:%.d%*}}\
692  %{MMD:-MMD %{!o:%b.d}%{o*:%.d%*}}\
693  %{M} %{MM} %{MF*} %{MG} %{MP} %{MQ*} %{MT*}\
694  %{!E:%{!M:%{!MM:%{MD|MMD:%{o*:-MQ %*}}}}}\
695  %{!no-gcc:-D__GNUC__=%v1 -D__GNUC_MINOR__=%v2 -D__GNUC_PATCHLEVEL__=%v3}\
696  %{!undef:%{!ansi:%{!std=*:%p}%{std=gnu*:%p}} %P} %{trigraphs}\
697  %{remap} %{g3:-dD} %{H} %C %{D*&U*&A*} %{i*} %Z %i\
698  %{E|M|MM:%W{o*}}";
699
700 /* This contains cpp options which are common with cc1_options and are passed
701    only when preprocessing only to avoid duplication.  We pass the cc1 spec
702    options to the preprocessor so that it the cc1 spec may manipulate
703    options used to set target flags.  Those special target flags settings may
704    in turn cause preprocessor symbols to be defined specially.  */
705 static const char *cpp_options =
706 "%(cpp_unique_options) %1 %{m*} %{std*} %{ansi} %{W*&pedantic*} %{w} %{f*}\
707  %{O*} %{undef}";
708
709 /* This contains cpp options which are not passed when the preprocessor
710    output will be used by another program.  */
711 static const char *cpp_debug_options = "%{d*}";
712
713 /* NB: This is shared amongst all front-ends.  */
714 static const char *cc1_options =
715 "%{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
716  %1 %{!Q:-quiet} -dumpbase %B %{d*} %{m*} %{a*}\
717  -auxbase%{c|S:%{o*:-strip %*}%{!o*: %b}}%{!c:%{!S: %b}}\
718  %{g*} %{O*} %{W*&pedantic*} %{w} %{std*} %{ansi}\
719  %{v:-version} %{pg:-p} %{p} %{f*} %{undef}\
720  %{Qn:-fno-ident} %{--help:--help}\
721  %{--target-help:--target-help}\
722  %{!fsyntax-only:%{S:%W{o*}%{!o*:-o %b.s}}}\
723  %{fsyntax-only:-o %j} %{-param*}";
724
725 static const char *asm_options =
726 "%a %Y %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}";
727
728 static const char *invoke_as =
729 "%{!S:-o %{|!pipe:%g.s} |\n as %(asm_options) %{!pipe:%g.s} %A }";
730
731 /* Some compilers have limits on line lengths, and the multilib_select
732    and/or multilib_matches strings can be very long, so we build them at
733    run time.  */
734 static struct obstack multilib_obstack;
735 static const char *multilib_select;
736 static const char *multilib_matches;
737 static const char *multilib_defaults;
738 static const char *multilib_exclusions;
739 #include "multilib.h"
740
741 /* Check whether a particular argument is a default argument.  */
742
743 #ifndef MULTILIB_DEFAULTS
744 #define MULTILIB_DEFAULTS { "" }
745 #endif
746
747 static const char *const multilib_defaults_raw[] = MULTILIB_DEFAULTS;
748
749 #ifndef DRIVER_SELF_SPECS
750 #define DRIVER_SELF_SPECS ""
751 #endif
752
753 static const char *const driver_self_specs[] = { DRIVER_SELF_SPECS };
754
755 struct user_specs
756 {
757   struct user_specs *next;
758   const char *filename;
759 };
760
761 static struct user_specs *user_specs_head, *user_specs_tail;
762
763 /* This defines which switch letters take arguments.  */
764
765 #define DEFAULT_SWITCH_TAKES_ARG(CHAR) \
766   ((CHAR) == 'D' || (CHAR) == 'U' || (CHAR) == 'o' \
767    || (CHAR) == 'e' || (CHAR) == 'T' || (CHAR) == 'u' \
768    || (CHAR) == 'I' || (CHAR) == 'm' || (CHAR) == 'x' \
769    || (CHAR) == 'L' || (CHAR) == 'A' || (CHAR) == 'B' || (CHAR) == 'b')
770
771 #ifndef SWITCH_TAKES_ARG
772 #define SWITCH_TAKES_ARG(CHAR) DEFAULT_SWITCH_TAKES_ARG(CHAR)
773 #endif
774
775 /* This defines which multi-letter switches take arguments.  */
776
777 #define DEFAULT_WORD_SWITCH_TAKES_ARG(STR)              \
778  (!strcmp (STR, "Tdata") || !strcmp (STR, "Ttext")      \
779   || !strcmp (STR, "Tbss") || !strcmp (STR, "include")  \
780   || !strcmp (STR, "imacros") || !strcmp (STR, "aux-info") \
781   || !strcmp (STR, "idirafter") || !strcmp (STR, "iprefix") \
782   || !strcmp (STR, "iwithprefix") || !strcmp (STR, "iwithprefixbefore") \
783   || !strcmp (STR, "isystem") || !strcmp (STR, "-param") \
784   || !strcmp (STR, "specs") \
785   || !strcmp (STR, "MF") || !strcmp (STR, "MT") || !strcmp (STR, "MQ"))
786
787 #ifndef WORD_SWITCH_TAKES_ARG
788 #define WORD_SWITCH_TAKES_ARG(STR) DEFAULT_WORD_SWITCH_TAKES_ARG (STR)
789 #endif
790 \f
791 #ifdef HAVE_TARGET_EXECUTABLE_SUFFIX
792 /* This defines which switches stop a full compilation.  */
793 #define DEFAULT_SWITCH_CURTAILS_COMPILATION(CHAR) \
794   ((CHAR) == 'c' || (CHAR) == 'S')
795
796 #ifndef SWITCH_CURTAILS_COMPILATION
797 #define SWITCH_CURTAILS_COMPILATION(CHAR) \
798   DEFAULT_SWITCH_CURTAILS_COMPILATION(CHAR)
799 #endif
800 #endif
801
802 /* Record the mapping from file suffixes for compilation specs.  */
803
804 struct compiler
805 {
806   const char *suffix;           /* Use this compiler for input files
807                                    whose names end in this suffix.  */
808
809   const char *spec;             /* To use this compiler, run this spec.  */
810
811   const char *cpp_spec;         /* If non-NULL, substitute this spec
812                                    for `%C', rather than the usual
813                                    cpp_spec.  */
814 };
815
816 /* Pointer to a vector of `struct compiler' that gives the spec for
817    compiling a file, based on its suffix.
818    A file that does not end in any of these suffixes will be passed
819    unchanged to the loader and nothing else will be done to it.
820
821    An entry containing two 0s is used to terminate the vector.
822
823    If multiple entries match a file, the last matching one is used.  */
824
825 static struct compiler *compilers;
826
827 /* Number of entries in `compilers', not counting the null terminator.  */
828
829 static int n_compilers;
830
831 /* The default list of file name suffixes and their compilation specs.  */
832
833 static const struct compiler default_compilers[] =
834 {
835   /* Add lists of suffixes of known languages here.  If those languages
836      were not present when we built the driver, we will hit these copies
837      and be given a more meaningful error than "file not used since
838      linking is not done".  */
839   {".m",  "#Objective-C", 0}, {".mi",  "#Objective-C", 0},
840   {".cc", "#C++", 0}, {".cxx", "#C++", 0}, {".cpp", "#C++", 0},
841   {".cp", "#C++", 0}, {".c++", "#C++", 0}, {".C", "#C++", 0},
842   {".ii", "#C++", 0},
843   {".ads", "#Ada", 0}, {".adb", "#Ada", 0},
844   {".f", "#Fortran", 0}, {".for", "#Fortran", 0}, {".fpp", "#Fortran", 0},
845   {".F", "#Fortran", 0}, {".FOR", "#Fortran", 0}, {".FPP", "#Fortran", 0},
846   {".r", "#Ratfor", 0},
847   {".p", "#Pascal", 0}, {".pas", "#Pascal", 0},
848   {".java", "#Java", 0}, {".class", "#Java", 0},
849   {".zip", "#Java", 0}, {".jar", "#Java", 0},
850   /* Next come the entries for C.  */
851   {".c", "@c", 0},
852   {"@c",
853    /* cc1 has an integrated ISO C preprocessor.  We should invoke the
854       external preprocessor if -save-temps is given.  */
855      "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
856       %{!E:%{!M:%{!MM:\
857           %{traditional|ftraditional:\
858 %eGNU C no longer supports -traditional without -E}\
859           %{save-temps|traditional-cpp:%(trad_capable_cpp) \
860                 %(cpp_options) %b.i \n\
861                     cc1 -fpreprocessed %b.i %(cc1_options)}\
862           %{!save-temps:%{!traditional-cpp:\
863                 cc1 %(cpp_unique_options) %(cc1_options)}}\
864         %{!fsyntax-only:%(invoke_as)}}}}", 0},
865   {"-",
866    "%{!E:%e-E required when input is from standard input}\
867     %(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)", 0},
868   {".h", "@c-header", 0},
869   {"@c-header",
870    "%{!E:%ecompilation of header file requested} \
871     %(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)",
872    0},
873   {".i", "@cpp-output", 0},
874   {"@cpp-output",
875    "%{!M:%{!MM:%{!E:cc1 -fpreprocessed %i %(cc1_options) %{!fsyntax-only:%(invoke_as)}}}}", 0},
876   {".s", "@assembler", 0},
877   {"@assembler",
878    "%{!M:%{!MM:%{!E:%{!S:as %(asm_debug) %(asm_options) %i %A }}}}", 0},
879   {".S", "@assembler-with-cpp", 0},
880   {"@assembler-with-cpp",
881    "%(trad_capable_cpp) -lang-asm %(cpp_options)\
882       %{E|M|MM:%(cpp_debug_options)}\
883       %{!M:%{!MM:%{!E:%{!S:-o %{|!pipe:%g.s} |\n\
884        as %(asm_debug) %(asm_options) %{!pipe:%g.s} %A }}}}", 0},
885 #include "specs.h"
886   /* Mark end of table */
887   {0, 0, 0}
888 };
889
890 /* Number of elements in default_compilers, not counting the terminator.  */
891
892 static const int n_default_compilers = ARRAY_SIZE (default_compilers) - 1;
893
894 /* A vector of options to give to the linker.
895    These options are accumulated by %x,
896    and substituted into the linker command with %X.  */
897 static int n_linker_options;
898 static char **linker_options;
899
900 /* A vector of options to give to the assembler.
901    These options are accumulated by -Wa,
902    and substituted into the assembler command with %Y.  */
903 static int n_assembler_options;
904 static char **assembler_options;
905
906 /* A vector of options to give to the preprocessor.
907    These options are accumulated by -Wp,
908    and substituted into the preprocessor command with %Z.  */
909 static int n_preprocessor_options;
910 static char **preprocessor_options;
911 \f
912 /* Define how to map long options into short ones.  */
913
914 /* This structure describes one mapping.  */
915 struct option_map
916 {
917   /* The long option's name.  */
918   const char *const name;
919   /* The equivalent short option.  */
920   const char *const equivalent;
921   /* Argument info.  A string of flag chars; NULL equals no options.
922      a => argument required.
923      o => argument optional.
924      j => join argument to equivalent, making one word.
925      * => require other text after NAME as an argument.  */
926   const char *const arg_info;
927 };
928
929 /* This is the table of mappings.  Mappings are tried sequentially
930    for each option encountered; the first one that matches, wins.  */
931
932 static const struct option_map option_map[] =
933  {
934    {"--all-warnings", "-Wall", 0},
935    {"--ansi", "-ansi", 0},
936    {"--assemble", "-S", 0},
937    {"--assert", "-A", "a"},
938    {"--classpath", "-fclasspath=", "aj"},
939    {"--bootclasspath", "-fbootclasspath=", "aj"},
940    {"--CLASSPATH", "-fclasspath=", "aj"},
941    {"--comments", "-C", 0},
942    {"--comments-in-macros", "-CC", 0},
943    {"--compile", "-c", 0},
944    {"--debug", "-g", "oj"},
945    {"--define-macro", "-D", "aj"},
946    {"--dependencies", "-M", 0},
947    {"--dump", "-d", "a"},
948    {"--dumpbase", "-dumpbase", "a"},
949    {"--entry", "-e", 0},
950    {"--extra-warnings", "-W", 0},
951    {"--for-assembler", "-Wa", "a"},
952    {"--for-linker", "-Xlinker", "a"},
953    {"--force-link", "-u", "a"},
954    {"--imacros", "-imacros", "a"},
955    {"--include", "-include", "a"},
956    {"--include-barrier", "-I-", 0},
957    {"--include-directory", "-I", "aj"},
958    {"--include-directory-after", "-idirafter", "a"},
959    {"--include-prefix", "-iprefix", "a"},
960    {"--include-with-prefix", "-iwithprefix", "a"},
961    {"--include-with-prefix-before", "-iwithprefixbefore", "a"},
962    {"--include-with-prefix-after", "-iwithprefix", "a"},
963    {"--language", "-x", "a"},
964    {"--library-directory", "-L", "a"},
965    {"--machine", "-m", "aj"},
966    {"--machine-", "-m", "*j"},
967    {"--no-line-commands", "-P", 0},
968    {"--no-precompiled-includes", "-noprecomp", 0},
969    {"--no-standard-includes", "-nostdinc", 0},
970    {"--no-standard-libraries", "-nostdlib", 0},
971    {"--no-warnings", "-w", 0},
972    {"--optimize", "-O", "oj"},
973    {"--output", "-o", "a"},
974    {"--output-class-directory", "-foutput-class-dir=", "ja"},
975    {"--param", "--param", "a"},
976    {"--pedantic", "-pedantic", 0},
977    {"--pedantic-errors", "-pedantic-errors", 0},
978    {"--pipe", "-pipe", 0},
979    {"--prefix", "-B", "a"},
980    {"--preprocess", "-E", 0},
981    {"--print-search-dirs", "-print-search-dirs", 0},
982    {"--print-file-name", "-print-file-name=", "aj"},
983    {"--print-libgcc-file-name", "-print-libgcc-file-name", 0},
984    {"--print-missing-file-dependencies", "-MG", 0},
985    {"--print-multi-lib", "-print-multi-lib", 0},
986    {"--print-multi-directory", "-print-multi-directory", 0},
987    {"--print-multi-os-directory", "-print-multi-os-directory", 0},
988    {"--print-prog-name", "-print-prog-name=", "aj"},
989    {"--profile", "-p", 0},
990    {"--profile-blocks", "-a", 0},
991    {"--quiet", "-q", 0},
992    {"--resource", "-fcompile-resource=", "aj"},
993    {"--save-temps", "-save-temps", 0},
994    {"--shared", "-shared", 0},
995    {"--silent", "-q", 0},
996    {"--specs", "-specs=", "aj"},
997    {"--static", "-static", 0},
998    {"--std", "-std=", "aj"},
999    {"--symbolic", "-symbolic", 0},
1000    {"--target", "-b", "a"},
1001    {"--time", "-time", 0},
1002    {"--trace-includes", "-H", 0},
1003    {"--traditional", "-traditional", 0},
1004    {"--traditional-cpp", "-traditional-cpp", 0},
1005    {"--trigraphs", "-trigraphs", 0},
1006    {"--undefine-macro", "-U", "aj"},
1007    {"--use-version", "-V", "a"},
1008    {"--user-dependencies", "-MM", 0},
1009    {"--verbose", "-v", 0},
1010    {"--warn-", "-W", "*j"},
1011    {"--write-dependencies", "-MD", 0},
1012    {"--write-user-dependencies", "-MMD", 0},
1013    {"--", "-f", "*j"}
1014  };
1015 \f
1016
1017 #ifdef TARGET_OPTION_TRANSLATE_TABLE
1018 static const struct {
1019   const char *const option_found;
1020   const char *const replacements;
1021 } target_option_translations[] =
1022 {
1023   TARGET_OPTION_TRANSLATE_TABLE,
1024   { 0, 0 }
1025 };
1026 #endif
1027
1028 /* Translate the options described by *ARGCP and *ARGVP.
1029    Make a new vector and store it back in *ARGVP,
1030    and store its length in *ARGVC.  */
1031
1032 static void
1033 translate_options (argcp, argvp)
1034      int *argcp;
1035      const char *const **argvp;
1036 {
1037   int i;
1038   int argc = *argcp;
1039   const char *const *argv = *argvp;
1040   int newvsize = (argc + 2) * 2 * sizeof (const char *);
1041   const char **newv =
1042     (const char **) xmalloc (newvsize);
1043   int newindex = 0;
1044
1045   i = 0;
1046   newv[newindex++] = argv[i++];
1047
1048   while (i < argc)
1049     {
1050 #ifdef TARGET_OPTION_TRANSLATE_TABLE
1051       int tott_idx;
1052
1053       for (tott_idx = 0;
1054            target_option_translations[tott_idx].option_found;
1055            tott_idx++)
1056         {
1057           if (strcmp (target_option_translations[tott_idx].option_found,
1058                       argv[i]) == 0)
1059             {
1060               int spaces = 1;
1061               const char *sp;
1062               char *np;
1063
1064               for (sp = target_option_translations[tott_idx].replacements;
1065                    *sp; sp++)
1066                 {
1067                   if (*sp == ' ')
1068                     spaces ++;
1069                 }
1070
1071               newvsize += spaces * sizeof (const char *);
1072               newv = (const char **) xrealloc (newv, newvsize);
1073
1074               sp = target_option_translations[tott_idx].replacements;
1075               np = xstrdup (sp);
1076
1077               while (1)
1078                 {
1079                   while (*np == ' ')
1080                     np++;
1081                   if (*np == 0)
1082                     break;
1083                   newv[newindex++] = np;
1084                   while (*np != ' ' && *np)
1085                     np++;
1086                   if (*np == 0)
1087                     break;
1088                   *np++ = 0;
1089                 }
1090
1091               i ++;
1092               break;
1093             }
1094         }
1095       if (target_option_translations[tott_idx].option_found)
1096         continue;
1097 #endif
1098
1099       /* Translate -- options.  */
1100       if (argv[i][0] == '-' && argv[i][1] == '-')
1101         {
1102           size_t j;
1103           /* Find a mapping that applies to this option.  */
1104           for (j = 0; j < ARRAY_SIZE (option_map); j++)
1105             {
1106               size_t optlen = strlen (option_map[j].name);
1107               size_t arglen = strlen (argv[i]);
1108               size_t complen = arglen > optlen ? optlen : arglen;
1109               const char *arginfo = option_map[j].arg_info;
1110
1111               if (arginfo == 0)
1112                 arginfo = "";
1113
1114               if (!strncmp (argv[i], option_map[j].name, complen))
1115                 {
1116                   const char *arg = 0;
1117
1118                   if (arglen < optlen)
1119                     {
1120                       size_t k;
1121                       for (k = j + 1; k < ARRAY_SIZE (option_map); k++)
1122                         if (strlen (option_map[k].name) >= arglen
1123                             && !strncmp (argv[i], option_map[k].name, arglen))
1124                           {
1125                             error ("ambiguous abbreviation %s", argv[i]);
1126                             break;
1127                           }
1128
1129                       if (k != ARRAY_SIZE (option_map))
1130                         break;
1131                     }
1132
1133                   if (arglen > optlen)
1134                     {
1135                       /* If the option has an argument, accept that.  */
1136                       if (argv[i][optlen] == '=')
1137                         arg = argv[i] + optlen + 1;
1138
1139                       /* If this mapping requires extra text at end of name,
1140                          accept that as "argument".  */
1141                       else if (strchr (arginfo, '*') != 0)
1142                         arg = argv[i] + optlen;
1143
1144                       /* Otherwise, extra text at end means mismatch.
1145                          Try other mappings.  */
1146                       else
1147                         continue;
1148                     }
1149
1150                   else if (strchr (arginfo, '*') != 0)
1151                     {
1152                       error ("incomplete `%s' option", option_map[j].name);
1153                       break;
1154                     }
1155
1156                   /* Handle arguments.  */
1157                   if (strchr (arginfo, 'a') != 0)
1158                     {
1159                       if (arg == 0)
1160                         {
1161                           if (i + 1 == argc)
1162                             {
1163                               error ("missing argument to `%s' option",
1164                                      option_map[j].name);
1165                               break;
1166                             }
1167
1168                           arg = argv[++i];
1169                         }
1170                     }
1171                   else if (strchr (arginfo, '*') != 0)
1172                     ;
1173                   else if (strchr (arginfo, 'o') == 0)
1174                     {
1175                       if (arg != 0)
1176                         error ("extraneous argument to `%s' option",
1177                                option_map[j].name);
1178                       arg = 0;
1179                     }
1180
1181                   /* Store the translation as one argv elt or as two.  */
1182                   if (arg != 0 && strchr (arginfo, 'j') != 0)
1183                     newv[newindex++] = concat (option_map[j].equivalent, arg,
1184                                                NULL);
1185                   else if (arg != 0)
1186                     {
1187                       newv[newindex++] = option_map[j].equivalent;
1188                       newv[newindex++] = arg;
1189                     }
1190                   else
1191                     newv[newindex++] = option_map[j].equivalent;
1192
1193                   break;
1194                 }
1195             }
1196           i++;
1197         }
1198
1199       /* Handle old-fashioned options--just copy them through,
1200          with their arguments.  */
1201       else if (argv[i][0] == '-')
1202         {
1203           const char *p = argv[i] + 1;
1204           int c = *p;
1205           int nskip = 1;
1206
1207           if (SWITCH_TAKES_ARG (c) > (p[1] != 0))
1208             nskip += SWITCH_TAKES_ARG (c) - (p[1] != 0);
1209           else if (WORD_SWITCH_TAKES_ARG (p))
1210             nskip += WORD_SWITCH_TAKES_ARG (p);
1211           else if ((c == 'B' || c == 'b' || c == 'x')
1212                    && p[1] == 0)
1213             nskip += 1;
1214           else if (! strcmp (p, "Xlinker"))
1215             nskip += 1;
1216
1217           /* Watch out for an option at the end of the command line that
1218              is missing arguments, and avoid skipping past the end of the
1219              command line.  */
1220           if (nskip + i > argc)
1221             nskip = argc - i;
1222
1223           while (nskip > 0)
1224             {
1225               newv[newindex++] = argv[i++];
1226               nskip--;
1227             }
1228         }
1229       else
1230         /* Ordinary operands, or +e options.  */
1231         newv[newindex++] = argv[i++];
1232     }
1233
1234   newv[newindex] = 0;
1235
1236   *argvp = newv;
1237   *argcp = newindex;
1238 }
1239 \f
1240 static char *
1241 skip_whitespace (p)
1242      char *p;
1243 {
1244   while (1)
1245     {
1246       /* A fully-blank line is a delimiter in the SPEC file and shouldn't
1247          be considered whitespace.  */
1248       if (p[0] == '\n' && p[1] == '\n' && p[2] == '\n')
1249         return p + 1;
1250       else if (*p == '\n' || *p == ' ' || *p == '\t')
1251         p++;
1252       else if (*p == '#')
1253         {
1254           while (*p != '\n')
1255             p++;
1256           p++;
1257         }
1258       else
1259         break;
1260     }
1261
1262   return p;
1263 }
1264 /* Structures to keep track of prefixes to try when looking for files.  */
1265
1266 struct prefix_list
1267 {
1268   const char *prefix;         /* String to prepend to the path.  */
1269   struct prefix_list *next;   /* Next in linked list.  */
1270   int require_machine_suffix; /* Don't use without machine_suffix.  */
1271   /* 2 means try both machine_suffix and just_machine_suffix.  */
1272   int *used_flag_ptr;         /* 1 if a file was found with this prefix.  */
1273   int priority;               /* Sort key - priority within list.  */
1274   int os_multilib;            /* 1 if OS multilib scheme should be used,
1275                                  0 for GCC multilib scheme.  */
1276 };
1277
1278 struct path_prefix
1279 {
1280   struct prefix_list *plist;  /* List of prefixes to try */
1281   int max_len;                /* Max length of a prefix in PLIST */
1282   const char *name;           /* Name of this list (used in config stuff) */
1283 };
1284
1285 /* List of prefixes to try when looking for executables.  */
1286
1287 static struct path_prefix exec_prefixes = { 0, 0, "exec" };
1288
1289 /* List of prefixes to try when looking for startup (crt0) files.  */
1290
1291 static struct path_prefix startfile_prefixes = { 0, 0, "startfile" };
1292
1293 /* List of prefixes to try when looking for include files.  */
1294
1295 static struct path_prefix include_prefixes = { 0, 0, "include" };
1296
1297 /* Suffix to attach to directories searched for commands.
1298    This looks like `MACHINE/VERSION/'.  */
1299
1300 static const char *machine_suffix = 0;
1301
1302 /* Suffix to attach to directories searched for commands.
1303    This is just `MACHINE/'.  */
1304
1305 static const char *just_machine_suffix = 0;
1306
1307 /* Adjusted value of GCC_EXEC_PREFIX envvar.  */
1308
1309 static const char *gcc_exec_prefix;
1310
1311 /* Default prefixes to attach to command names.  */
1312
1313 #ifdef CROSS_COMPILE  /* Don't use these prefixes for a cross compiler.  */
1314 #undef MD_EXEC_PREFIX
1315 #undef MD_STARTFILE_PREFIX
1316 #undef MD_STARTFILE_PREFIX_1
1317 #endif
1318
1319 /* If no prefixes defined, use the null string, which will disable them.  */
1320 #ifndef MD_EXEC_PREFIX
1321 #define MD_EXEC_PREFIX ""
1322 #endif
1323 #ifndef MD_STARTFILE_PREFIX
1324 #define MD_STARTFILE_PREFIX ""
1325 #endif
1326 #ifndef MD_STARTFILE_PREFIX_1
1327 #define MD_STARTFILE_PREFIX_1 ""
1328 #endif
1329
1330 /* Supply defaults for the standard prefixes.  */
1331
1332 #ifndef STANDARD_EXEC_PREFIX
1333 #define STANDARD_EXEC_PREFIX "/usr/local/lib/gcc-lib/"
1334 #endif
1335 #ifndef STANDARD_STARTFILE_PREFIX
1336 #define STANDARD_STARTFILE_PREFIX "/usr/local/lib/"
1337 #endif
1338 #ifndef TOOLDIR_BASE_PREFIX
1339 #define TOOLDIR_BASE_PREFIX "/usr/local/"
1340 #endif
1341 #ifndef STANDARD_BINDIR_PREFIX
1342 #define STANDARD_BINDIR_PREFIX "/usr/local/bin"
1343 #endif
1344
1345 static const char *const standard_exec_prefix = STANDARD_EXEC_PREFIX;
1346 static const char *const standard_exec_prefix_1 = "/usr/lib/gcc/";
1347 static const char *md_exec_prefix = MD_EXEC_PREFIX;
1348
1349 static const char *md_startfile_prefix = MD_STARTFILE_PREFIX;
1350 static const char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
1351 static const char *const standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
1352 static const char *const standard_startfile_prefix_1 = "/lib/";
1353 static const char *const standard_startfile_prefix_2 = "/usr/lib/";
1354
1355 static const char *const tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
1356 static const char *tooldir_prefix;
1357
1358 static const char *const standard_bindir_prefix = STANDARD_BINDIR_PREFIX;
1359
1360 /* Subdirectory to use for locating libraries.  Set by
1361    set_multilib_dir based on the compilation options.  */
1362
1363 static const char *multilib_dir;
1364
1365 /* Subdirectory to use for locating libraries in OS conventions.  Set by
1366    set_multilib_dir based on the compilation options.  */
1367
1368 static const char *multilib_os_dir;
1369 \f
1370 /* Structure to keep track of the specs that have been defined so far.
1371    These are accessed using %(specname) or %[specname] in a compiler
1372    or link spec.  */
1373
1374 struct spec_list
1375 {
1376                                 /* The following 2 fields must be first */
1377                                 /* to allow EXTRA_SPECS to be initialized */
1378   const char *name;             /* name of the spec.  */
1379   const char *ptr;              /* available ptr if no static pointer */
1380
1381                                 /* The following fields are not initialized */
1382                                 /* by EXTRA_SPECS */
1383   const char **ptr_spec;        /* pointer to the spec itself.  */
1384   struct spec_list *next;       /* Next spec in linked list.  */
1385   int name_len;                 /* length of the name */
1386   int alloc_p;                  /* whether string was allocated */
1387 };
1388
1389 #define INIT_STATIC_SPEC(NAME,PTR) \
1390 { NAME, NULL, PTR, (struct spec_list *) 0, sizeof (NAME) - 1, 0 }
1391
1392 /* List of statically defined specs.  */
1393 static struct spec_list static_specs[] =
1394 {
1395   INIT_STATIC_SPEC ("asm",                      &asm_spec),
1396   INIT_STATIC_SPEC ("asm_debug",                &asm_debug),
1397   INIT_STATIC_SPEC ("asm_final",                &asm_final_spec),
1398   INIT_STATIC_SPEC ("asm_options",              &asm_options),
1399   INIT_STATIC_SPEC ("invoke_as",                &invoke_as),
1400   INIT_STATIC_SPEC ("cpp",                      &cpp_spec),
1401   INIT_STATIC_SPEC ("cpp_options",              &cpp_options),
1402   INIT_STATIC_SPEC ("cpp_debug_options",        &cpp_debug_options),
1403   INIT_STATIC_SPEC ("cpp_unique_options",       &cpp_unique_options),
1404   INIT_STATIC_SPEC ("trad_capable_cpp",         &trad_capable_cpp),
1405   INIT_STATIC_SPEC ("cc1",                      &cc1_spec),
1406   INIT_STATIC_SPEC ("cc1_options",              &cc1_options),
1407   INIT_STATIC_SPEC ("cc1plus",                  &cc1plus_spec),
1408   INIT_STATIC_SPEC ("link_gcc_c_sequence",      &link_gcc_c_sequence_spec),
1409   INIT_STATIC_SPEC ("endfile",                  &endfile_spec),
1410   INIT_STATIC_SPEC ("link",                     &link_spec),
1411   INIT_STATIC_SPEC ("lib",                      &lib_spec),
1412   INIT_STATIC_SPEC ("libgcc",                   &libgcc_spec),
1413   INIT_STATIC_SPEC ("startfile",                &startfile_spec),
1414   INIT_STATIC_SPEC ("switches_need_spaces",     &switches_need_spaces),
1415   INIT_STATIC_SPEC ("predefines",               &cpp_predefines),
1416   INIT_STATIC_SPEC ("cross_compile",            &cross_compile),
1417   INIT_STATIC_SPEC ("version",                  &compiler_version),
1418   INIT_STATIC_SPEC ("multilib",                 &multilib_select),
1419   INIT_STATIC_SPEC ("multilib_defaults",        &multilib_defaults),
1420   INIT_STATIC_SPEC ("multilib_extra",           &multilib_extra),
1421   INIT_STATIC_SPEC ("multilib_matches",         &multilib_matches),
1422   INIT_STATIC_SPEC ("multilib_exclusions",      &multilib_exclusions),
1423   INIT_STATIC_SPEC ("multilib_options",         &multilib_options),
1424   INIT_STATIC_SPEC ("linker",                   &linker_name_spec),
1425   INIT_STATIC_SPEC ("link_libgcc",              &link_libgcc_spec),
1426   INIT_STATIC_SPEC ("md_exec_prefix",           &md_exec_prefix),
1427   INIT_STATIC_SPEC ("md_startfile_prefix",      &md_startfile_prefix),
1428   INIT_STATIC_SPEC ("md_startfile_prefix_1",    &md_startfile_prefix_1),
1429   INIT_STATIC_SPEC ("startfile_prefix_spec",    &startfile_prefix_spec),
1430 };
1431
1432 #ifdef EXTRA_SPECS              /* additional specs needed */
1433 /* Structure to keep track of just the first two args of a spec_list.
1434    That is all that the EXTRA_SPECS macro gives us.  */
1435 struct spec_list_1
1436 {
1437   const char *const name;
1438   const char *const ptr;
1439 };
1440
1441 static const struct spec_list_1 extra_specs_1[] = { EXTRA_SPECS };
1442 static struct spec_list *extra_specs = (struct spec_list *) 0;
1443 #endif
1444
1445 /* List of dynamically allocates specs that have been defined so far.  */
1446
1447 static struct spec_list *specs = (struct spec_list *) 0;
1448 \f
1449 /* List of static spec functions.  */
1450
1451 static const struct spec_function static_spec_functions[] =
1452 {
1453   { "if-exists",                if_exists_spec_function },
1454   { 0, 0 }
1455 };
1456
1457 static int processing_spec_function;
1458 \f
1459 /* Add appropriate libgcc specs to OBSTACK, taking into account
1460    various permutations of -shared-libgcc, -shared, and such.  */
1461
1462 #ifdef ENABLE_SHARED_LIBGCC
1463 static void
1464 init_gcc_specs (obstack, shared_name, static_name, eh_name)
1465      struct obstack *obstack;
1466      const char *shared_name;
1467      const char *static_name;
1468      const char *eh_name;
1469 {
1470   char *buf;
1471
1472   buf = concat ("%{static|static-libgcc:", static_name, " ", eh_name,
1473                 "}%{!static:%{!static-libgcc:",
1474                 "%{!shared:%{!shared-libgcc:", static_name, " ",
1475                 eh_name, "}%{shared-libgcc:", shared_name, " ",
1476                 static_name, "}}%{shared:",
1477 #ifdef LINK_EH_SPEC
1478                 "%{shared-libgcc:", shared_name,
1479                 "}%{!shared-libgcc:", static_name, "}",
1480 #else
1481                 shared_name,
1482 #endif
1483                 "}}}", NULL);
1484
1485   obstack_grow (obstack, buf, strlen (buf));
1486   free (buf);
1487 }
1488 #endif /* ENABLE_SHARED_LIBGCC */
1489
1490 /* Initialize the specs lookup routines.  */
1491
1492 static void
1493 init_spec ()
1494 {
1495   struct spec_list *next = (struct spec_list *) 0;
1496   struct spec_list *sl   = (struct spec_list *) 0;
1497   int i;
1498
1499   if (specs)
1500     return;                     /* Already initialized.  */
1501
1502   if (verbose_flag)
1503     notice ("Using built-in specs.\n");
1504
1505 #ifdef EXTRA_SPECS
1506   extra_specs = (struct spec_list *)
1507     xcalloc (sizeof (struct spec_list), ARRAY_SIZE (extra_specs_1));
1508
1509   for (i = ARRAY_SIZE (extra_specs_1) - 1; i >= 0; i--)
1510     {
1511       sl = &extra_specs[i];
1512       sl->name = extra_specs_1[i].name;
1513       sl->ptr = extra_specs_1[i].ptr;
1514       sl->next = next;
1515       sl->name_len = strlen (sl->name);
1516       sl->ptr_spec = &sl->ptr;
1517       next = sl;
1518     }
1519 #endif
1520
1521   /* Initialize here, not in definition.  The IRIX 6 O32 cc sometimes chokes
1522      on ?: in file-scope variable initializations.  */
1523   asm_debug = ASM_DEBUG_SPEC;
1524
1525   for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1526     {
1527       sl = &static_specs[i];
1528       sl->next = next;
1529       next = sl;
1530     }
1531
1532 #ifdef ENABLE_SHARED_LIBGCC
1533   /* ??? If neither -shared-libgcc nor --static-libgcc was
1534      seen, then we should be making an educated guess.  Some proposed
1535      heuristics for ELF include:
1536
1537         (1) If "-Wl,--export-dynamic", then it's a fair bet that the
1538             program will be doing dynamic loading, which will likely
1539             need the shared libgcc.
1540
1541         (2) If "-ldl", then it's also a fair bet that we're doing
1542             dynamic loading.
1543
1544         (3) For each ET_DYN we're linking against (either through -lfoo
1545             or /some/path/foo.so), check to see whether it or one of
1546             its dependencies depends on a shared libgcc.
1547
1548         (4) If "-shared"
1549
1550             If the runtime is fixed to look for program headers instead
1551             of calling __register_frame_info at all, for each object,
1552             use the shared libgcc if any EH symbol referenced.
1553
1554             If crtstuff is fixed to not invoke __register_frame_info
1555             automatically, for each object, use the shared libgcc if
1556             any non-empty unwind section found.
1557
1558      Doing any of this probably requires invoking an external program to
1559      do the actual object file scanning.  */
1560   {
1561     const char *p = libgcc_spec;
1562     int in_sep = 1;
1563
1564     /* Transform the extant libgcc_spec into one that uses the shared libgcc
1565        when given the proper command line arguments.  */
1566     while (*p)
1567       {
1568         if (in_sep && *p == '-' && strncmp (p, "-lgcc", 5) == 0)
1569           {
1570             init_gcc_specs (&obstack,
1571 #ifdef NO_SHARED_LIBGCC_MULTILIB
1572                             "-lgcc_s"
1573 #else
1574                             "-lgcc_s%M"
1575 #endif
1576                             ,
1577                             "-lgcc",
1578                             "-lgcc_eh");
1579             p += 5;
1580             in_sep = 0;
1581           }
1582         else if (in_sep && *p == 'l' && strncmp (p, "libgcc.a%s", 10) == 0)
1583           {
1584             /* Ug.  We don't know shared library extensions.  Hope that
1585                systems that use this form don't do shared libraries.  */
1586             init_gcc_specs (&obstack,
1587 #ifdef NO_SHARED_LIBGCC_MULTILIB
1588                             "-lgcc_s"
1589 #else
1590                             "-lgcc_s%M"
1591 #endif
1592                             ,
1593                             "libgcc.a%s",
1594                             "libgcc_eh.a%s");
1595             p += 10;
1596             in_sep = 0;
1597           }
1598         else
1599           {
1600             obstack_1grow (&obstack, *p);
1601             in_sep = (*p == ' ');
1602             p += 1;
1603           }
1604       }
1605
1606     obstack_1grow (&obstack, '\0');
1607     libgcc_spec = obstack_finish (&obstack);
1608   }
1609 #endif
1610 #ifdef USE_AS_TRADITIONAL_FORMAT
1611   /* Prepend "--traditional-format" to whatever asm_spec we had before.  */
1612   {
1613     static const char tf[] = "--traditional-format ";
1614     obstack_grow (&obstack, tf, sizeof(tf) - 1);
1615     obstack_grow0 (&obstack, asm_spec, strlen (asm_spec));
1616     asm_spec = obstack_finish (&obstack);
1617   }
1618 #endif
1619 #ifdef LINK_EH_SPEC
1620   /* Prepend LINK_EH_SPEC to whatever link_spec we had before.  */
1621   obstack_grow (&obstack, LINK_EH_SPEC, sizeof(LINK_EH_SPEC) - 1);
1622   obstack_grow0 (&obstack, link_spec, strlen (link_spec));
1623   link_spec = obstack_finish (&obstack);
1624 #endif
1625
1626   specs = sl;
1627 }
1628 \f
1629 /* Change the value of spec NAME to SPEC.  If SPEC is empty, then the spec is
1630    removed; If the spec starts with a + then SPEC is added to the end of the
1631    current spec.  */
1632
1633 static void
1634 set_spec (name, spec)
1635      const char *name;
1636      const char *spec;
1637 {
1638   struct spec_list *sl;
1639   const char *old_spec;
1640   int name_len = strlen (name);
1641   int i;
1642
1643   /* If this is the first call, initialize the statically allocated specs.  */
1644   if (!specs)
1645     {
1646       struct spec_list *next = (struct spec_list *) 0;
1647       for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1648         {
1649           sl = &static_specs[i];
1650           sl->next = next;
1651           next = sl;
1652         }
1653       specs = sl;
1654     }
1655
1656   /* See if the spec already exists.  */
1657   for (sl = specs; sl; sl = sl->next)
1658     if (name_len == sl->name_len && !strcmp (sl->name, name))
1659       break;
1660
1661   if (!sl)
1662     {
1663       /* Not found - make it.  */
1664       sl = (struct spec_list *) xmalloc (sizeof (struct spec_list));
1665       sl->name = xstrdup (name);
1666       sl->name_len = name_len;
1667       sl->ptr_spec = &sl->ptr;
1668       sl->alloc_p = 0;
1669       *(sl->ptr_spec) = "";
1670       sl->next = specs;
1671       specs = sl;
1672     }
1673
1674   old_spec = *(sl->ptr_spec);
1675   *(sl->ptr_spec) = ((spec[0] == '+' && ISSPACE ((unsigned char)spec[1]))
1676                      ? concat (old_spec, spec + 1, NULL)
1677                      : xstrdup (spec));
1678
1679 #ifdef DEBUG_SPECS
1680   if (verbose_flag)
1681     notice ("Setting spec %s to '%s'\n\n", name, *(sl->ptr_spec));
1682 #endif
1683
1684   /* Free the old spec.  */
1685   if (old_spec && sl->alloc_p)
1686     free ((PTR) old_spec);
1687
1688   sl->alloc_p = 1;
1689 }
1690 \f
1691 /* Accumulate a command (program name and args), and run it.  */
1692
1693 /* Vector of pointers to arguments in the current line of specifications.  */
1694
1695 static const char **argbuf;
1696
1697 /* Number of elements allocated in argbuf.  */
1698
1699 static int argbuf_length;
1700
1701 /* Number of elements in argbuf currently in use (containing args).  */
1702
1703 static int argbuf_index;
1704
1705 /* This is the list of suffixes and codes (%g/%u/%U/%j) and the associated
1706    temp file.  If the HOST_BIT_BUCKET is used for %j, no entry is made for
1707    it here.  */
1708
1709 static struct temp_name {
1710   const char *suffix;   /* suffix associated with the code.  */
1711   int length;           /* strlen (suffix).  */
1712   int unique;           /* Indicates whether %g or %u/%U was used.  */
1713   const char *filename; /* associated filename.  */
1714   int filename_length;  /* strlen (filename).  */
1715   struct temp_name *next;
1716 } *temp_names;
1717
1718 /* Number of commands executed so far.  */
1719
1720 static int execution_count;
1721
1722 /* Number of commands that exited with a signal.  */
1723
1724 static int signal_count;
1725
1726 /* Name with which this program was invoked.  */
1727
1728 static const char *programname;
1729 \f
1730 /* Allocate the argument vector.  */
1731
1732 static void
1733 alloc_args ()
1734 {
1735   argbuf_length = 10;
1736   argbuf = (const char **) xmalloc (argbuf_length * sizeof (const char *));
1737 }
1738
1739 /* Clear out the vector of arguments (after a command is executed).  */
1740
1741 static void
1742 clear_args ()
1743 {
1744   argbuf_index = 0;
1745 }
1746
1747 /* Add one argument to the vector at the end.
1748    This is done when a space is seen or at the end of the line.
1749    If DELETE_ALWAYS is nonzero, the arg is a filename
1750     and the file should be deleted eventually.
1751    If DELETE_FAILURE is nonzero, the arg is a filename
1752     and the file should be deleted if this compilation fails.  */
1753
1754 static void
1755 store_arg (arg, delete_always, delete_failure)
1756      const char *arg;
1757      int delete_always, delete_failure;
1758 {
1759   if (argbuf_index + 1 == argbuf_length)
1760     argbuf
1761       = (const char **) xrealloc (argbuf,
1762                                   (argbuf_length *= 2) * sizeof (const char *));
1763
1764   argbuf[argbuf_index++] = arg;
1765   argbuf[argbuf_index] = 0;
1766
1767   if (delete_always || delete_failure)
1768     record_temp_file (arg, delete_always, delete_failure);
1769 }
1770 \f
1771 /* Load specs from a file name named FILENAME, replacing occurrences of
1772    various different types of line-endings, \r\n, \n\r and just \r, with
1773    a single \n.  */
1774
1775 static char *
1776 load_specs (filename)
1777      const char *filename;
1778 {
1779   int desc;
1780   int readlen;
1781   struct stat statbuf;
1782   char *buffer;
1783   char *buffer_p;
1784   char *specs;
1785   char *specs_p;
1786
1787   if (verbose_flag)
1788     notice ("Reading specs from %s\n", filename);
1789
1790   /* Open and stat the file.  */
1791   desc = open (filename, O_RDONLY, 0);
1792   if (desc < 0)
1793     pfatal_with_name (filename);
1794   if (stat (filename, &statbuf) < 0)
1795     pfatal_with_name (filename);
1796
1797   /* Read contents of file into BUFFER.  */
1798   buffer = xmalloc ((unsigned) statbuf.st_size + 1);
1799   readlen = read (desc, buffer, (unsigned) statbuf.st_size);
1800   if (readlen < 0)
1801     pfatal_with_name (filename);
1802   buffer[readlen] = 0;
1803   close (desc);
1804
1805   specs = xmalloc (readlen + 1);
1806   specs_p = specs;
1807   for (buffer_p = buffer; buffer_p && *buffer_p; buffer_p++)
1808     {
1809       int skip = 0;
1810       char c = *buffer_p;
1811       if (c == '\r')
1812         {
1813           if (buffer_p > buffer && *(buffer_p - 1) == '\n')     /* \n\r */
1814             skip = 1;
1815           else if (*(buffer_p + 1) == '\n')                     /* \r\n */
1816             skip = 1;
1817           else                                                  /* \r */
1818             c = '\n';
1819         }
1820       if (! skip)
1821         *specs_p++ = c;
1822     }
1823   *specs_p = '\0';
1824
1825   free (buffer);
1826   return (specs);
1827 }
1828
1829 /* Read compilation specs from a file named FILENAME,
1830    replacing the default ones.
1831
1832    A suffix which starts with `*' is a definition for
1833    one of the machine-specific sub-specs.  The "suffix" should be
1834    *asm, *cc1, *cpp, *link, *startfile, etc.
1835    The corresponding spec is stored in asm_spec, etc.,
1836    rather than in the `compilers' vector.
1837
1838    Anything invalid in the file is a fatal error.  */
1839
1840 static void
1841 read_specs (filename, main_p)
1842      const char *filename;
1843      int main_p;
1844 {
1845   char *buffer;
1846   char *p;
1847
1848   buffer = load_specs (filename);
1849
1850   /* Scan BUFFER for specs, putting them in the vector.  */
1851   p = buffer;
1852   while (1)
1853     {
1854       char *suffix;
1855       char *spec;
1856       char *in, *out, *p1, *p2, *p3;
1857
1858       /* Advance P in BUFFER to the next nonblank nocomment line.  */
1859       p = skip_whitespace (p);
1860       if (*p == 0)
1861         break;
1862
1863       /* Is this a special command that starts with '%'? */
1864       /* Don't allow this for the main specs file, since it would
1865          encourage people to overwrite it.  */
1866       if (*p == '%' && !main_p)
1867         {
1868           p1 = p;
1869           while (*p && *p != '\n')
1870             p++;
1871
1872           /* Skip '\n'.  */
1873           p++;
1874
1875           if (!strncmp (p1, "%include", sizeof ("%include") - 1)
1876               && (p1[sizeof "%include" - 1] == ' '
1877                   || p1[sizeof "%include" - 1] == '\t'))
1878             {
1879               char *new_filename;
1880
1881               p1 += sizeof ("%include");
1882               while (*p1 == ' ' || *p1 == '\t')
1883                 p1++;
1884
1885               if (*p1++ != '<' || p[-2] != '>')
1886                 fatal ("specs %%include syntax malformed after %ld characters",
1887                        (long) (p1 - buffer + 1));
1888
1889               p[-2] = '\0';
1890               new_filename = find_a_file (&startfile_prefixes, p1, R_OK, 0);
1891               read_specs (new_filename ? new_filename : p1, FALSE);
1892               continue;
1893             }
1894           else if (!strncmp (p1, "%include_noerr", sizeof "%include_noerr" - 1)
1895                    && (p1[sizeof "%include_noerr" - 1] == ' '
1896                        || p1[sizeof "%include_noerr" - 1] == '\t'))
1897             {
1898               char *new_filename;
1899
1900               p1 += sizeof "%include_noerr";
1901               while (*p1 == ' ' || *p1 == '\t')
1902                 p1++;
1903
1904               if (*p1++ != '<' || p[-2] != '>')
1905                 fatal ("specs %%include syntax malformed after %ld characters",
1906                        (long) (p1 - buffer + 1));
1907
1908               p[-2] = '\0';
1909               new_filename = find_a_file (&startfile_prefixes, p1, R_OK, 0);
1910               if (new_filename)
1911                 read_specs (new_filename, FALSE);
1912               else if (verbose_flag)
1913                 notice ("could not find specs file %s\n", p1);
1914               continue;
1915             }
1916           else if (!strncmp (p1, "%rename", sizeof "%rename" - 1)
1917                    && (p1[sizeof "%rename" - 1] == ' '
1918                        || p1[sizeof "%rename" - 1] == '\t'))
1919             {
1920               int name_len;
1921               struct spec_list *sl;
1922               struct spec_list *newsl;
1923
1924               /* Get original name.  */
1925               p1 += sizeof "%rename";
1926               while (*p1 == ' ' || *p1 == '\t')
1927                 p1++;
1928
1929               if (! ISALPHA ((unsigned char) *p1))
1930                 fatal ("specs %%rename syntax malformed after %ld characters",
1931                        (long) (p1 - buffer));
1932
1933               p2 = p1;
1934               while (*p2 && !ISSPACE ((unsigned char) *p2))
1935                 p2++;
1936
1937               if (*p2 != ' ' && *p2 != '\t')
1938                 fatal ("specs %%rename syntax malformed after %ld characters",
1939                        (long) (p2 - buffer));
1940
1941               name_len = p2 - p1;
1942               *p2++ = '\0';
1943               while (*p2 == ' ' || *p2 == '\t')
1944                 p2++;
1945
1946               if (! ISALPHA ((unsigned char) *p2))
1947                 fatal ("specs %%rename syntax malformed after %ld characters",
1948                        (long) (p2 - buffer));
1949
1950               /* Get new spec name.  */
1951               p3 = p2;
1952               while (*p3 && !ISSPACE ((unsigned char) *p3))
1953                 p3++;
1954
1955               if (p3 != p - 1)
1956                 fatal ("specs %%rename syntax malformed after %ld characters",
1957                        (long) (p3 - buffer));
1958               *p3 = '\0';
1959
1960               for (sl = specs; sl; sl = sl->next)
1961                 if (name_len == sl->name_len && !strcmp (sl->name, p1))
1962                   break;
1963
1964               if (!sl)
1965                 fatal ("specs %s spec was not found to be renamed", p1);
1966
1967               if (strcmp (p1, p2) == 0)
1968                 continue;
1969
1970               for (newsl = specs; newsl; newsl = newsl->next)
1971                 if (strcmp (newsl->name, p2) == 0)
1972                   fatal ("%s: attempt to rename spec '%s' to already defined spec '%s'",
1973                     filename, p1, p2);
1974
1975               if (verbose_flag)
1976                 {
1977                   notice ("rename spec %s to %s\n", p1, p2);
1978 #ifdef DEBUG_SPECS
1979                   notice ("spec is '%s'\n\n", *(sl->ptr_spec));
1980 #endif
1981                 }
1982
1983               set_spec (p2, *(sl->ptr_spec));
1984               if (sl->alloc_p)
1985                 free ((PTR) *(sl->ptr_spec));
1986
1987               *(sl->ptr_spec) = "";
1988               sl->alloc_p = 0;
1989               continue;
1990             }
1991           else
1992             fatal ("specs unknown %% command after %ld characters",
1993                    (long) (p1 - buffer));
1994         }
1995
1996       /* Find the colon that should end the suffix.  */
1997       p1 = p;
1998       while (*p1 && *p1 != ':' && *p1 != '\n')
1999         p1++;
2000
2001       /* The colon shouldn't be missing.  */
2002       if (*p1 != ':')
2003         fatal ("specs file malformed after %ld characters",
2004                (long) (p1 - buffer));
2005
2006       /* Skip back over trailing whitespace.  */
2007       p2 = p1;
2008       while (p2 > buffer && (p2[-1] == ' ' || p2[-1] == '\t'))
2009         p2--;
2010
2011       /* Copy the suffix to a string.  */
2012       suffix = save_string (p, p2 - p);
2013       /* Find the next line.  */
2014       p = skip_whitespace (p1 + 1);
2015       if (p[1] == 0)
2016         fatal ("specs file malformed after %ld characters",
2017                (long) (p - buffer));
2018
2019       p1 = p;
2020       /* Find next blank line or end of string.  */
2021       while (*p1 && !(*p1 == '\n' && (p1[1] == '\n' || p1[1] == '\0')))
2022         p1++;
2023
2024       /* Specs end at the blank line and do not include the newline.  */
2025       spec = save_string (p, p1 - p);
2026       p = p1;
2027
2028       /* Delete backslash-newline sequences from the spec.  */
2029       in = spec;
2030       out = spec;
2031       while (*in != 0)
2032         {
2033           if (in[0] == '\\' && in[1] == '\n')
2034             in += 2;
2035           else if (in[0] == '#')
2036             while (*in && *in != '\n')
2037               in++;
2038
2039           else
2040             *out++ = *in++;
2041         }
2042       *out = 0;
2043
2044       if (suffix[0] == '*')
2045         {
2046           if (! strcmp (suffix, "*link_command"))
2047             link_command_spec = spec;
2048           else
2049             set_spec (suffix + 1, spec);
2050         }
2051       else
2052         {
2053           /* Add this pair to the vector.  */
2054           compilers
2055             = ((struct compiler *)
2056                xrealloc (compilers,
2057                          (n_compilers + 2) * sizeof (struct compiler)));
2058
2059           compilers[n_compilers].suffix = suffix;
2060           compilers[n_compilers].spec = spec;
2061           n_compilers++;
2062           memset (&compilers[n_compilers], 0, sizeof compilers[n_compilers]);
2063         }
2064
2065       if (*suffix == 0)
2066         link_command_spec = spec;
2067     }
2068
2069   if (link_command_spec == 0)
2070     fatal ("spec file has no spec for linking");
2071 }
2072 \f
2073 /* Record the names of temporary files we tell compilers to write,
2074    and delete them at the end of the run.  */
2075
2076 /* This is the common prefix we use to make temp file names.
2077    It is chosen once for each run of this program.
2078    It is substituted into a spec by %g or %j.
2079    Thus, all temp file names contain this prefix.
2080    In practice, all temp file names start with this prefix.
2081
2082    This prefix comes from the envvar TMPDIR if it is defined;
2083    otherwise, from the P_tmpdir macro if that is defined;
2084    otherwise, in /usr/tmp or /tmp;
2085    or finally the current directory if all else fails.  */
2086
2087 static const char *temp_filename;
2088
2089 /* Length of the prefix.  */
2090
2091 static int temp_filename_length;
2092
2093 /* Define the list of temporary files to delete.  */
2094
2095 struct temp_file
2096 {
2097   const char *name;
2098   struct temp_file *next;
2099 };
2100
2101 /* Queue of files to delete on success or failure of compilation.  */
2102 static struct temp_file *always_delete_queue;
2103 /* Queue of files to delete on failure of compilation.  */
2104 static struct temp_file *failure_delete_queue;
2105
2106 /* Record FILENAME as a file to be deleted automatically.
2107    ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
2108    otherwise delete it in any case.
2109    FAIL_DELETE nonzero means delete it if a compilation step fails;
2110    otherwise delete it in any case.  */
2111
2112 void
2113 record_temp_file (filename, always_delete, fail_delete)
2114      const char *filename;
2115      int always_delete;
2116      int fail_delete;
2117 {
2118   char *const name = xstrdup (filename);
2119
2120   if (always_delete)
2121     {
2122       struct temp_file *temp;
2123       for (temp = always_delete_queue; temp; temp = temp->next)
2124         if (! strcmp (name, temp->name))
2125           goto already1;
2126
2127       temp = (struct temp_file *) xmalloc (sizeof (struct temp_file));
2128       temp->next = always_delete_queue;
2129       temp->name = name;
2130       always_delete_queue = temp;
2131
2132     already1:;
2133     }
2134
2135   if (fail_delete)
2136     {
2137       struct temp_file *temp;
2138       for (temp = failure_delete_queue; temp; temp = temp->next)
2139         if (! strcmp (name, temp->name))
2140           goto already2;
2141
2142       temp = (struct temp_file *) xmalloc (sizeof (struct temp_file));
2143       temp->next = failure_delete_queue;
2144       temp->name = name;
2145       failure_delete_queue = temp;
2146
2147     already2:;
2148     }
2149 }
2150
2151 /* Delete all the temporary files whose names we previously recorded.  */
2152
2153 static void
2154 delete_if_ordinary (name)
2155      const char *name;
2156 {
2157   struct stat st;
2158 #ifdef DEBUG
2159   int i, c;
2160
2161   printf ("Delete %s? (y or n) ", name);
2162   fflush (stdout);
2163   i = getchar ();
2164   if (i != '\n')
2165     while ((c = getchar ()) != '\n' && c != EOF)
2166       ;
2167
2168   if (i == 'y' || i == 'Y')
2169 #endif /* DEBUG */
2170     if (stat (name, &st) >= 0 && S_ISREG (st.st_mode))
2171       if (unlink (name) < 0)
2172         if (verbose_flag)
2173           perror_with_name (name);
2174 }
2175
2176 static void
2177 delete_temp_files ()
2178 {
2179   struct temp_file *temp;
2180
2181   for (temp = always_delete_queue; temp; temp = temp->next)
2182     delete_if_ordinary (temp->name);
2183   always_delete_queue = 0;
2184 }
2185
2186 /* Delete all the files to be deleted on error.  */
2187
2188 static void
2189 delete_failure_queue ()
2190 {
2191   struct temp_file *temp;
2192
2193   for (temp = failure_delete_queue; temp; temp = temp->next)
2194     delete_if_ordinary (temp->name);
2195 }
2196
2197 static void
2198 clear_failure_queue ()
2199 {
2200   failure_delete_queue = 0;
2201 }
2202 \f
2203 /* Build a list of search directories from PATHS.
2204    PREFIX is a string to prepend to the list.
2205    If CHECK_DIR_P is nonzero we ensure the directory exists.
2206    This is used mostly by putenv_from_prefixes so we use `collect_obstack'.
2207    It is also used by the --print-search-dirs flag.  */
2208
2209 static char *
2210 build_search_list (paths, prefix, check_dir_p)
2211      struct path_prefix *paths;
2212      const char *prefix;
2213      int check_dir_p;
2214 {
2215   int suffix_len = (machine_suffix) ? strlen (machine_suffix) : 0;
2216   int just_suffix_len
2217     = (just_machine_suffix) ? strlen (just_machine_suffix) : 0;
2218   int first_time = TRUE;
2219   struct prefix_list *pprefix;
2220
2221   obstack_grow (&collect_obstack, prefix, strlen (prefix));
2222   obstack_1grow (&collect_obstack, '=');
2223
2224   for (pprefix = paths->plist; pprefix != 0; pprefix = pprefix->next)
2225     {
2226       int len = strlen (pprefix->prefix);
2227
2228       if (machine_suffix
2229           && (! check_dir_p
2230               || is_directory (pprefix->prefix, machine_suffix, 0)))
2231         {
2232           if (!first_time)
2233             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
2234
2235           first_time = FALSE;
2236           obstack_grow (&collect_obstack, pprefix->prefix, len);
2237           obstack_grow (&collect_obstack, machine_suffix, suffix_len);
2238         }
2239
2240       if (just_machine_suffix
2241           && pprefix->require_machine_suffix == 2
2242           && (! check_dir_p
2243               || is_directory (pprefix->prefix, just_machine_suffix, 0)))
2244         {
2245           if (! first_time)
2246             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
2247
2248           first_time = FALSE;
2249           obstack_grow (&collect_obstack, pprefix->prefix, len);
2250           obstack_grow (&collect_obstack, just_machine_suffix,
2251                         just_suffix_len);
2252         }
2253
2254       if (! pprefix->require_machine_suffix)
2255         {
2256           if (! first_time)
2257             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
2258
2259           first_time = FALSE;
2260           obstack_grow (&collect_obstack, pprefix->prefix, len);
2261         }
2262     }
2263
2264   obstack_1grow (&collect_obstack, '\0');
2265   return obstack_finish (&collect_obstack);
2266 }
2267
2268 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
2269    for collect.  */
2270
2271 static void
2272 putenv_from_prefixes (paths, env_var)
2273      struct path_prefix *paths;
2274      const char *env_var;
2275 {
2276   putenv (build_search_list (paths, env_var, 1));
2277 }
2278 \f
2279 /* Check whether NAME can be accessed in MODE.  This is like access,
2280    except that it never considers directories to be executable.  */
2281
2282 static int
2283 access_check (name, mode)
2284      const char *name;
2285      int mode;
2286 {
2287   if (mode == X_OK)
2288     {
2289       struct stat st;
2290
2291       if (stat (name, &st) < 0
2292           || S_ISDIR (st.st_mode))
2293         return -1;
2294     }
2295
2296   return access (name, mode);
2297 }
2298
2299 /* Search for NAME using the prefix list PREFIXES.  MODE is passed to
2300    access to check permissions.
2301    Return 0 if not found, otherwise return its name, allocated with malloc.  */
2302
2303 static char *
2304 find_a_file (pprefix, name, mode, multilib)
2305      struct path_prefix *pprefix;
2306      const char *name;
2307      int mode, multilib;
2308 {
2309   char *temp;
2310   const char *const file_suffix =
2311     ((mode & X_OK) != 0 ? HOST_EXECUTABLE_SUFFIX : "");
2312   struct prefix_list *pl;
2313   int len = pprefix->max_len + strlen (name) + strlen (file_suffix) + 1;
2314   const char *multilib_name, *multilib_os_name;
2315
2316 #ifdef DEFAULT_ASSEMBLER
2317   if (! strcmp (name, "as") && access (DEFAULT_ASSEMBLER, mode) == 0)
2318     return xstrdup (DEFAULT_ASSEMBLER);
2319 #endif
2320
2321 #ifdef DEFAULT_LINKER
2322   if (! strcmp(name, "ld") && access (DEFAULT_LINKER, mode) == 0)
2323     return xstrdup (DEFAULT_LINKER);
2324 #endif
2325
2326   if (machine_suffix)
2327     len += strlen (machine_suffix);
2328
2329   multilib_name = name;
2330   multilib_os_name = name;
2331   if (multilib && multilib_os_dir)
2332     {
2333       int len1 = multilib_dir ? strlen (multilib_dir) + 1 : 0;
2334       int len2 = strlen (multilib_os_dir) + 1;
2335
2336       len += len1 > len2 ? len1 : len2;
2337       if (multilib_dir)
2338         multilib_name = ACONCAT ((multilib_dir, dir_separator_str, name,
2339                                   NULL));
2340       if (strcmp (multilib_os_dir, ".") != 0)
2341         multilib_os_name = ACONCAT ((multilib_os_dir, dir_separator_str, name,
2342                                     NULL));
2343     }
2344
2345   temp = xmalloc (len);
2346
2347   /* Determine the filename to execute (special case for absolute paths).  */
2348
2349   if (IS_ABSOLUTE_PATHNAME (name))
2350     {
2351       if (access (name, mode) == 0)
2352         {
2353           strcpy (temp, name);
2354           return temp;
2355         }
2356     }
2357   else
2358     for (pl = pprefix->plist; pl; pl = pl->next)
2359       {
2360         const char *this_name
2361           = pl->os_multilib ? multilib_os_name : multilib_name;
2362
2363         if (machine_suffix)
2364           {
2365             /* Some systems have a suffix for executable files.
2366                So try appending that first.  */
2367             if (file_suffix[0] != 0)
2368               {
2369                 strcpy (temp, pl->prefix);
2370                 strcat (temp, machine_suffix);
2371                 strcat (temp, multilib_name);
2372                 strcat (temp, file_suffix);
2373                 if (access_check (temp, mode) == 0)
2374                   {
2375                     if (pl->used_flag_ptr != 0)
2376                       *pl->used_flag_ptr = 1;
2377                     return temp;
2378                   }
2379               }
2380
2381             /* Now try just the multilib_name.  */
2382             strcpy (temp, pl->prefix);
2383             strcat (temp, machine_suffix);
2384             strcat (temp, multilib_name);
2385             if (access_check (temp, mode) == 0)
2386               {
2387                 if (pl->used_flag_ptr != 0)
2388                   *pl->used_flag_ptr = 1;
2389                 return temp;
2390               }
2391           }
2392
2393         /* Certain prefixes are tried with just the machine type,
2394            not the version.  This is used for finding as, ld, etc.  */
2395         if (just_machine_suffix && pl->require_machine_suffix == 2)
2396           {
2397             /* Some systems have a suffix for executable files.
2398                So try appending that first.  */
2399             if (file_suffix[0] != 0)
2400               {
2401                 strcpy (temp, pl->prefix);
2402                 strcat (temp, just_machine_suffix);
2403                 strcat (temp, multilib_name);
2404                 strcat (temp, file_suffix);
2405                 if (access_check (temp, mode) == 0)
2406                   {
2407                     if (pl->used_flag_ptr != 0)
2408                       *pl->used_flag_ptr = 1;
2409                     return temp;
2410                   }
2411               }
2412
2413             strcpy (temp, pl->prefix);
2414             strcat (temp, just_machine_suffix);
2415             strcat (temp, multilib_name);
2416             if (access_check (temp, mode) == 0)
2417               {
2418                 if (pl->used_flag_ptr != 0)
2419                   *pl->used_flag_ptr = 1;
2420                 return temp;
2421               }
2422           }
2423
2424         /* Certain prefixes can't be used without the machine suffix
2425            when the machine or version is explicitly specified.  */
2426         if (! pl->require_machine_suffix)
2427           {
2428             /* Some systems have a suffix for executable files.
2429                So try appending that first.  */
2430             if (file_suffix[0] != 0)
2431               {
2432                 strcpy (temp, pl->prefix);
2433                 strcat (temp, this_name);
2434                 strcat (temp, file_suffix);
2435                 if (access_check (temp, mode) == 0)
2436                   {
2437                     if (pl->used_flag_ptr != 0)
2438                       *pl->used_flag_ptr = 1;
2439                     return temp;
2440                   }
2441               }
2442
2443             strcpy (temp, pl->prefix);
2444             strcat (temp, this_name);
2445             if (access_check (temp, mode) == 0)
2446               {
2447                 if (pl->used_flag_ptr != 0)
2448                   *pl->used_flag_ptr = 1;
2449                 return temp;
2450               }
2451           }
2452       }
2453
2454   free (temp);
2455   return 0;
2456 }
2457
2458 /* Ranking of prefixes in the sort list. -B prefixes are put before
2459    all others.  */
2460
2461 enum path_prefix_priority
2462 {
2463   PREFIX_PRIORITY_B_OPT,
2464   PREFIX_PRIORITY_LAST
2465 };
2466
2467 /* Add an entry for PREFIX in PLIST.  The PLIST is kept in assending
2468    order according to PRIORITY.  Within each PRIORITY, new entries are
2469    appended.
2470
2471    If WARN is nonzero, we will warn if no file is found
2472    through this prefix.  WARN should point to an int
2473    which will be set to 1 if this entry is used.
2474
2475    COMPONENT is the value to be passed to update_path.
2476
2477    REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
2478    the complete value of machine_suffix.
2479    2 means try both machine_suffix and just_machine_suffix.  */
2480
2481 static void
2482 add_prefix (pprefix, prefix, component, priority, require_machine_suffix,
2483             warn, os_multilib)
2484      struct path_prefix *pprefix;
2485      const char *prefix;
2486      const char *component;
2487      /* enum prefix_priority */ int priority;
2488      int require_machine_suffix;
2489      int *warn;
2490      int os_multilib;
2491 {
2492   struct prefix_list *pl, **prev;
2493   int len;
2494
2495   for (prev = &pprefix->plist;
2496        (*prev) != NULL && (*prev)->priority <= priority;
2497        prev = &(*prev)->next)
2498     ;
2499
2500   /* Keep track of the longest prefix */
2501
2502   prefix = update_path (prefix, component);
2503   len = strlen (prefix);
2504   if (len > pprefix->max_len)
2505     pprefix->max_len = len;
2506
2507   pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
2508   pl->prefix = prefix;
2509   pl->require_machine_suffix = require_machine_suffix;
2510   pl->used_flag_ptr = warn;
2511   pl->priority = priority;
2512   pl->os_multilib = os_multilib;
2513   if (warn)
2514     *warn = 0;
2515
2516   /* Insert after PREV */
2517   pl->next = (*prev);
2518   (*prev) = pl;
2519 }
2520 \f
2521 /* Execute the command specified by the arguments on the current line of spec.
2522    When using pipes, this includes several piped-together commands
2523    with `|' between them.
2524
2525    Return 0 if successful, -1 if failed.  */
2526
2527 static int
2528 execute ()
2529 {
2530   int i;
2531   int n_commands;               /* # of command.  */
2532   char *string;
2533   struct command
2534   {
2535     const char *prog;           /* program name.  */
2536     const char **argv;          /* vector of args.  */
2537     int pid;                    /* pid of process for this command.  */
2538   };
2539
2540   struct command *commands;     /* each command buffer with above info.  */
2541
2542   if (processing_spec_function)
2543     abort ();
2544
2545   /* Count # of piped commands.  */
2546   for (n_commands = 1, i = 0; i < argbuf_index; i++)
2547     if (strcmp (argbuf[i], "|") == 0)
2548       n_commands++;
2549
2550   /* Get storage for each command.  */
2551   commands = (struct command *) alloca (n_commands * sizeof (struct command));
2552
2553   /* Split argbuf into its separate piped processes,
2554      and record info about each one.
2555      Also search for the programs that are to be run.  */
2556
2557   commands[0].prog = argbuf[0]; /* first command.  */
2558   commands[0].argv = &argbuf[0];
2559   string = find_a_file (&exec_prefixes, commands[0].prog, X_OK, 0);
2560
2561   if (string)
2562     commands[0].argv[0] = string;
2563
2564   for (n_commands = 1, i = 0; i < argbuf_index; i++)
2565     if (strcmp (argbuf[i], "|") == 0)
2566       {                         /* each command.  */
2567 #if defined (__MSDOS__) || defined (OS2) || defined (VMS)
2568         fatal ("-pipe not supported");
2569 #endif
2570         argbuf[i] = 0;  /* termination of command args.  */
2571         commands[n_commands].prog = argbuf[i + 1];
2572         commands[n_commands].argv = &argbuf[i + 1];
2573         string = find_a_file (&exec_prefixes, commands[n_commands].prog,
2574                               X_OK, 0);
2575         if (string)
2576           commands[n_commands].argv[0] = string;
2577         n_commands++;
2578       }
2579
2580   argbuf[argbuf_index] = 0;
2581
2582   /* If -v, print what we are about to do, and maybe query.  */
2583
2584   if (verbose_flag)
2585     {
2586       /* For help listings, put a blank line between sub-processes.  */
2587       if (print_help_list)
2588         fputc ('\n', stderr);
2589
2590       /* Print each piped command as a separate line.  */
2591       for (i = 0; i < n_commands; i++)
2592         {
2593           const char *const *j;
2594
2595           if (verbose_only_flag)
2596             {
2597               for (j = commands[i].argv; *j; j++)
2598                 {
2599                   const char *p;
2600                   fprintf (stderr, " \"");
2601                   for (p = *j; *p; ++p)
2602                     {
2603                       if (*p == '"' || *p == '\\' || *p == '$')
2604                         fputc ('\\', stderr);
2605                       fputc (*p, stderr);
2606                     }
2607                   fputc ('"', stderr);
2608                 }
2609             }
2610           else
2611             for (j = commands[i].argv; *j; j++)
2612               fprintf (stderr, " %s", *j);
2613
2614           /* Print a pipe symbol after all but the last command.  */
2615           if (i + 1 != n_commands)
2616             fprintf (stderr, " |");
2617           fprintf (stderr, "\n");
2618         }
2619       fflush (stderr);
2620       if (verbose_only_flag != 0)
2621         return 0;
2622 #ifdef DEBUG
2623       notice ("\nGo ahead? (y or n) ");
2624       fflush (stderr);
2625       i = getchar ();
2626       if (i != '\n')
2627         while (getchar () != '\n')
2628           ;
2629
2630       if (i != 'y' && i != 'Y')
2631         return 0;
2632 #endif /* DEBUG */
2633     }
2634
2635 #ifdef ENABLE_VALGRIND_CHECKING
2636   /* Run the each command through valgrind.  To simplifiy prepending the
2637      path to valgrind and the option "-q" (for quiet operation unless
2638      something triggers), we allocate a separate argv array.  */
2639
2640   for (i = 0; i < n_commands; i++)
2641     {
2642       const char **argv;
2643       int argc;
2644       int j;
2645
2646       for (argc = 0; commands[i].argv[argc] != NULL; argc++)
2647         ;
2648
2649       argv = alloca ((argc + 3) * sizeof (char *));
2650
2651       argv[0] = VALGRIND_PATH;
2652       argv[1] = "-q";
2653       for (j = 2; j < argc + 2; j++)
2654         argv[j] = commands[i].argv[j - 2];
2655       argv[j] = NULL;
2656
2657       commands[i].argv = argv;
2658       commands[i].prog = argv[0];
2659     }
2660 #endif
2661
2662   /* Run each piped subprocess.  */
2663
2664   for (i = 0; i < n_commands; i++)
2665     {
2666       char *errmsg_fmt, *errmsg_arg;
2667       const char *string = commands[i].argv[0];
2668
2669       /* For some bizarre reason, the second argument of execvp() is
2670          char *const *, not const char *const *.  */
2671       commands[i].pid = pexecute (string, (char *const *) commands[i].argv,
2672                                   programname, temp_filename,
2673                                   &errmsg_fmt, &errmsg_arg,
2674                                   ((i == 0 ? PEXECUTE_FIRST : 0)
2675                                    | (i + 1 == n_commands ? PEXECUTE_LAST : 0)
2676                                    | (string == commands[i].prog
2677                                       ? PEXECUTE_SEARCH : 0)
2678                                    | (verbose_flag ? PEXECUTE_VERBOSE : 0)));
2679
2680       if (commands[i].pid == -1)
2681         pfatal_pexecute (errmsg_fmt, errmsg_arg);
2682
2683       if (string != commands[i].prog)
2684         free ((PTR) string);
2685     }
2686
2687   execution_count++;
2688
2689   /* Wait for all the subprocesses to finish.
2690      We don't care what order they finish in;
2691      we know that N_COMMANDS waits will get them all.
2692      Ignore subprocesses that we don't know about,
2693      since they can be spawned by the process that exec'ed us.  */
2694
2695   {
2696     int ret_code = 0;
2697 #ifdef HAVE_GETRUSAGE
2698     struct timeval d;
2699     double ut = 0.0, st = 0.0;
2700 #endif
2701
2702     for (i = 0; i < n_commands;)
2703       {
2704         int j;
2705         int status;
2706         int pid;
2707
2708         pid = pwait (commands[i].pid, &status, 0);
2709         if (pid < 0)
2710           abort ();
2711
2712 #ifdef HAVE_GETRUSAGE
2713         if (report_times)
2714           {
2715             /* getrusage returns the total resource usage of all children
2716                up to now.  Copy the previous values into prus, get the
2717                current statistics, then take the difference.  */
2718
2719             prus = rus;
2720             getrusage (RUSAGE_CHILDREN, &rus);
2721             d.tv_sec = rus.ru_utime.tv_sec - prus.ru_utime.tv_sec;
2722             d.tv_usec = rus.ru_utime.tv_usec - prus.ru_utime.tv_usec;
2723             ut = (double) d.tv_sec + (double) d.tv_usec / 1.0e6;
2724
2725             d.tv_sec = rus.ru_stime.tv_sec - prus.ru_stime.tv_sec;
2726             d.tv_usec = rus.ru_stime.tv_usec - prus.ru_stime.tv_usec;
2727             st = (double) d.tv_sec + (double) d.tv_usec / 1.0e6;
2728           }
2729 #endif
2730
2731         for (j = 0; j < n_commands; j++)
2732           if (commands[j].pid == pid)
2733             {
2734               i++;
2735               if (WIFSIGNALED (status))
2736                 {
2737 #ifdef SIGPIPE
2738                   /* SIGPIPE is a special case.  It happens in -pipe mode
2739                      when the compiler dies before the preprocessor is
2740                      done, or the assembler dies before the compiler is
2741                      done.  There's generally been an error already, and
2742                      this is just fallout.  So don't generate another error
2743                      unless we would otherwise have succeeded.  */
2744                   if (WTERMSIG (status) == SIGPIPE
2745                       && (signal_count || greatest_status >= MIN_FATAL_STATUS))
2746                     ;
2747                   else
2748 #endif
2749                     fatal ("\
2750 Internal error: %s (program %s)\n\
2751 Please submit a full bug report.\n\
2752 See %s for instructions.",
2753                            strsignal (WTERMSIG (status)), commands[j].prog,
2754                            bug_report_url);
2755                   signal_count++;
2756                   ret_code = -1;
2757                 }
2758               else if (WIFEXITED (status)
2759                        && WEXITSTATUS (status) >= MIN_FATAL_STATUS)
2760                 {
2761                   if (WEXITSTATUS (status) > greatest_status)
2762                     greatest_status = WEXITSTATUS (status);
2763                   ret_code = -1;
2764                 }
2765 #ifdef HAVE_GETRUSAGE
2766               if (report_times && ut + st != 0)
2767                 notice ("# %s %.2f %.2f\n", commands[j].prog, ut, st);
2768 #endif
2769               break;
2770             }
2771       }
2772     return ret_code;
2773   }
2774 }
2775 \f
2776 /* Find all the switches given to us
2777    and make a vector describing them.
2778    The elements of the vector are strings, one per switch given.
2779    If a switch uses following arguments, then the `part1' field
2780    is the switch itself and the `args' field
2781    is a null-terminated vector containing the following arguments.
2782    The `live_cond' field is:
2783    0 when initialized
2784    1 if the switch is true in a conditional spec,
2785    -1 if false (overridden by a later switch)
2786    -2 if this switch should be ignored (used in %{<S})
2787    The `validated' field is nonzero if any spec has looked at this switch;
2788    if it remains zero at the end of the run, it must be meaningless.  */
2789
2790 #define SWITCH_OK       0
2791 #define SWITCH_FALSE   -1
2792 #define SWITCH_IGNORE  -2
2793 #define SWITCH_LIVE     1
2794
2795 struct switchstr
2796 {
2797   const char *part1;
2798   const char **args;
2799   int live_cond;
2800   unsigned char validated;
2801   unsigned char ordering;
2802 };
2803
2804 static struct switchstr *switches;
2805
2806 static int n_switches;
2807
2808 struct infile
2809 {
2810   const char *name;
2811   const char *language;
2812 };
2813
2814 /* Also a vector of input files specified.  */
2815
2816 static struct infile *infiles;
2817
2818 int n_infiles;
2819
2820 /* This counts the number of libraries added by lang_specific_driver, so that
2821    we can tell if there were any user supplied any files or libraries.  */
2822
2823 static int added_libraries;
2824
2825 /* And a vector of corresponding output files is made up later.  */
2826
2827 const char **outfiles;
2828
2829 /* Used to track if none of the -B paths are used.  */
2830 static int warn_B;
2831
2832 /* Gives value to pass as "warn" to add_prefix for standard prefixes.  */
2833 static int *warn_std_ptr = 0;
2834 \f
2835 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
2836
2837 /* Convert NAME to a new name if it is the standard suffix.  DO_EXE
2838    is true if we should look for an executable suffix.  DO_OBJ
2839    is true if we should look for an object suffix.  */
2840
2841 static const char *
2842 convert_filename (name, do_exe, do_obj)
2843      const char *name;
2844      int do_exe ATTRIBUTE_UNUSED;
2845      int do_obj ATTRIBUTE_UNUSED;
2846 {
2847 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
2848   int i;
2849 #endif
2850   int len;
2851
2852   if (name == NULL)
2853     return NULL;
2854
2855   len = strlen (name);
2856
2857 #ifdef HAVE_TARGET_OBJECT_SUFFIX
2858   /* Convert x.o to x.obj if TARGET_OBJECT_SUFFIX is ".obj".  */
2859   if (do_obj && len > 2
2860       && name[len - 2] == '.'
2861       && name[len - 1] == 'o')
2862     {
2863       obstack_grow (&obstack, name, len - 2);
2864       obstack_grow0 (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
2865       name = obstack_finish (&obstack);
2866     }
2867 #endif
2868
2869 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
2870   /* If there is no filetype, make it the executable suffix (which includes
2871      the ".").  But don't get confused if we have just "-o".  */
2872   if (! do_exe || TARGET_EXECUTABLE_SUFFIX[0] == 0 || (len == 2 && name[0] == '-'))
2873     return name;
2874
2875   for (i = len - 1; i >= 0; i--)
2876     if (IS_DIR_SEPARATOR (name[i]))
2877       break;
2878
2879   for (i++; i < len; i++)
2880     if (name[i] == '.')
2881       return name;
2882
2883   obstack_grow (&obstack, name, len);
2884   obstack_grow0 (&obstack, TARGET_EXECUTABLE_SUFFIX,
2885                  strlen (TARGET_EXECUTABLE_SUFFIX));
2886   name = obstack_finish (&obstack);
2887 #endif
2888
2889   return name;
2890 }
2891 #endif
2892 \f
2893 /* Display the command line switches accepted by gcc.  */
2894 static void
2895 display_help ()
2896 {
2897   printf (_("Usage: %s [options] file...\n"), programname);
2898   fputs (_("Options:\n"), stdout);
2899
2900   fputs (_("  -pass-exit-codes         Exit with highest error code from a phase\n"), stdout);
2901   fputs (_("  --help                   Display this information\n"), stdout);
2902   fputs (_("  --target-help            Display target specific command line options\n"), stdout);
2903   if (! verbose_flag)
2904     fputs (_("  (Use '-v --help' to display command line options of sub-processes)\n"), stdout);
2905   fputs (_("  -dumpspecs               Display all of the built in spec strings\n"), stdout);
2906   fputs (_("  -dumpversion             Display the version of the compiler\n"), stdout);
2907   fputs (_("  -dumpmachine             Display the compiler's target processor\n"), stdout);
2908   fputs (_("  -print-search-dirs       Display the directories in the compiler's search path\n"), stdout);
2909   fputs (_("  -print-libgcc-file-name  Display the name of the compiler's companion library\n"), stdout);
2910   fputs (_("  -print-file-name=<lib>   Display the full path to library <lib>\n"), stdout);
2911   fputs (_("  -print-prog-name=<prog>  Display the full path to compiler component <prog>\n"), stdout);
2912   fputs (_("  -print-multi-directory   Display the root directory for versions of libgcc\n"), stdout);
2913   fputs (_("\
2914   -print-multi-lib         Display the mapping between command line options and\n\
2915                            multiple library search directories\n"), stdout);
2916   fputs (_("  -print-multi-os-directory Display the relative path to OS libraries\n"), stdout);
2917   fputs (_("  -Wa,<options>            Pass comma-separated <options> on to the assembler\n"), stdout);
2918   fputs (_("  -Wp,<options>            Pass comma-separated <options> on to the preprocessor\n"), stdout);
2919   fputs (_("  -Wl,<options>            Pass comma-separated <options> on to the linker\n"), stdout);
2920   fputs (_("  -Xlinker <arg>           Pass <arg> on to the linker\n"), stdout);
2921   fputs (_("  -save-temps              Do not delete intermediate files\n"), stdout);
2922   fputs (_("  -pipe                    Use pipes rather than intermediate files\n"), stdout);
2923   fputs (_("  -time                    Time the execution of each subprocess\n"), stdout);
2924   fputs (_("  -specs=<file>            Override built-in specs with the contents of <file>\n"), stdout);
2925   fputs (_("  -std=<standard>          Assume that the input sources are for <standard>\n"), stdout);
2926   fputs (_("  -B <directory>           Add <directory> to the compiler's search paths\n"), stdout);
2927   fputs (_("  -b <machine>             Run gcc for target <machine>, if installed\n"), stdout);
2928   fputs (_("  -V <version>             Run gcc version number <version>, if installed\n"), stdout);
2929   fputs (_("  -v                       Display the programs invoked by the compiler\n"), stdout);
2930   fputs (_("  -###                     Like -v but options quoted and commands not executed\n"), stdout);
2931   fputs (_("  -E                       Preprocess only; do not compile, assemble or link\n"), stdout);
2932   fputs (_("  -S                       Compile only; do not assemble or link\n"), stdout);
2933   fputs (_("  -c                       Compile and assemble, but do not link\n"), stdout);
2934   fputs (_("  -o <file>                Place the output into <file>\n"), stdout);
2935   fputs (_("\
2936   -x <language>            Specify the language of the following input files\n\
2937                            Permissable languages include: c c++ assembler none\n\
2938                            'none' means revert to the default behavior of\n\
2939                            guessing the language based on the file's extension\n\
2940 "), stdout);
2941
2942   printf (_("\
2943 \nOptions starting with -g, -f, -m, -O, -W, or --param are automatically\n\
2944  passed on to the various sub-processes invoked by %s.  In order to pass\n\
2945  other options on to these processes the -W<letter> options must be used.\n\
2946 "), programname);
2947
2948   /* The rest of the options are displayed by invocations of the various
2949      sub-processes.  */
2950 }
2951
2952 static void
2953 add_preprocessor_option (option, len)
2954      const char *option;
2955      int len;
2956 {
2957   n_preprocessor_options++;
2958
2959   if (! preprocessor_options)
2960     preprocessor_options
2961       = (char **) xmalloc (n_preprocessor_options * sizeof (char *));
2962   else
2963     preprocessor_options
2964       = (char **) xrealloc (preprocessor_options,
2965                             n_preprocessor_options * sizeof (char *));
2966
2967   preprocessor_options [n_preprocessor_options - 1] =
2968     save_string (option, len);
2969 }
2970
2971 static void
2972 add_assembler_option (option, len)
2973      const char *option;
2974      int len;
2975 {
2976   n_assembler_options++;
2977
2978   if (! assembler_options)
2979     assembler_options
2980       = (char **) xmalloc (n_assembler_options * sizeof (char *));
2981   else
2982     assembler_options
2983       = (char **) xrealloc (assembler_options,
2984                             n_assembler_options * sizeof (char *));
2985
2986   assembler_options [n_assembler_options - 1] = save_string (option, len);
2987 }
2988
2989 static void
2990 add_linker_option (option, len)
2991      const char *option;
2992      int len;
2993 {
2994   n_linker_options++;
2995
2996   if (! linker_options)
2997     linker_options
2998       = (char **) xmalloc (n_linker_options * sizeof (char *));
2999   else
3000     linker_options
3001       = (char **) xrealloc (linker_options,
3002                             n_linker_options * sizeof (char *));
3003
3004   linker_options [n_linker_options - 1] = save_string (option, len);
3005 }
3006 \f
3007 /* Create the vector `switches' and its contents.
3008    Store its length in `n_switches'.  */
3009
3010 static void
3011 process_command (argc, argv)
3012      int argc;
3013      const char *const *argv;
3014 {
3015   int i;
3016   const char *temp;
3017   char *temp1;
3018   const char *spec_lang = 0;
3019   int last_language_n_infiles;
3020   int have_c = 0;
3021   int have_o = 0;
3022   int lang_n_infiles = 0;
3023 #ifdef MODIFY_TARGET_NAME
3024   int is_modify_target_name;
3025   int j;
3026 #endif
3027
3028   GET_ENVIRONMENT (gcc_exec_prefix, "GCC_EXEC_PREFIX");
3029
3030   n_switches = 0;
3031   n_infiles = 0;
3032   added_libraries = 0;
3033
3034   /* Figure compiler version from version string.  */
3035
3036   compiler_version = temp1 = xstrdup (version_string);
3037
3038   for (; *temp1; ++temp1)
3039     {
3040       if (*temp1 == ' ')
3041         {
3042           *temp1 = '\0';
3043           break;
3044         }
3045     }
3046
3047   /* If there is a -V or -b option (or both), process it now, before
3048      trying to interpret the rest of the command line.  */
3049   if (argc > 1 && argv[1][0] == '-'
3050       && (argv[1][1] == 'V' || argv[1][1] == 'b'))
3051     {
3052       const char *new_version = DEFAULT_TARGET_VERSION;
3053       const char *new_machine = DEFAULT_TARGET_MACHINE;
3054       const char *progname = argv[0];
3055       char **new_argv;
3056       char *new_argv0;
3057       int baselen;
3058       
3059       while (argc > 1 && argv[1][0] == '-'
3060              && (argv[1][1] == 'V' || argv[1][1] == 'b'))
3061         {
3062           char opt = argv[1][1];
3063           const char *arg;
3064           if (argv[1][2] != '\0')
3065             {
3066               arg = argv[1] + 2;
3067               argc -= 1;
3068               argv += 1;
3069             }
3070           else if (argc > 2)
3071             {
3072               arg = argv[2];
3073               argc -= 2;
3074               argv += 2;
3075             }
3076           else
3077             fatal ("`-%c' option must have argument", opt);
3078           if (opt == 'V')
3079             new_version = arg;
3080           else
3081             new_machine = arg;
3082         }
3083
3084       for (baselen = strlen (progname); baselen > 0; baselen--)
3085         if (IS_DIR_SEPARATOR (progname[baselen-1]))
3086           break;
3087       new_argv0 = xmemdup (progname, baselen, 
3088                            baselen + concat_length (new_version, new_machine,
3089                                                     "-gcc-", NULL) + 1);
3090       strcpy (new_argv0 + baselen, new_machine);
3091       strcat (new_argv0, "-gcc-");
3092       strcat (new_argv0, new_version);
3093
3094       new_argv = xmemdup (argv, (argc + 1) * sizeof (argv[0]),
3095                           (argc + 1) * sizeof (argv[0]));
3096       new_argv[0] = new_argv0;
3097
3098       execvp (new_argv0, new_argv);
3099       fatal ("couldn't run `%s': %s", new_argv0, xstrerror (errno));
3100     }
3101
3102   /* Set up the default search paths.  If there is no GCC_EXEC_PREFIX,
3103      see if we can create it from the pathname specified in argv[0].  */
3104
3105 #ifndef VMS
3106   /* FIXME: make_relative_prefix doesn't yet work for VMS.  */
3107   if (!gcc_exec_prefix)
3108     {
3109       gcc_exec_prefix = make_relative_prefix (argv[0], standard_bindir_prefix,
3110                                               standard_exec_prefix);
3111       if (gcc_exec_prefix)
3112         putenv (concat ("GCC_EXEC_PREFIX=", gcc_exec_prefix, NULL));
3113     }
3114 #endif
3115
3116   if (gcc_exec_prefix)
3117     {
3118       int len = strlen (gcc_exec_prefix);
3119
3120       if (len > (int) sizeof ("/lib/gcc-lib/") - 1
3121           && (IS_DIR_SEPARATOR (gcc_exec_prefix[len-1])))
3122         {
3123           temp = gcc_exec_prefix + len - sizeof ("/lib/gcc-lib/") + 1;
3124           if (IS_DIR_SEPARATOR (*temp)
3125               && strncmp (temp + 1, "lib", 3) == 0
3126               && IS_DIR_SEPARATOR (temp[4])
3127               && strncmp (temp + 5, "gcc-lib", 7) == 0)
3128             len -= sizeof ("/lib/gcc-lib/") - 1;
3129         }
3130
3131       set_std_prefix (gcc_exec_prefix, len);
3132       add_prefix (&exec_prefixes, gcc_exec_prefix, "GCC",
3133                   PREFIX_PRIORITY_LAST, 0, NULL, 0);
3134       add_prefix (&startfile_prefixes, gcc_exec_prefix, "GCC",
3135                   PREFIX_PRIORITY_LAST, 0, NULL, 0);
3136     }
3137
3138   /* COMPILER_PATH and LIBRARY_PATH have values
3139      that are lists of directory names with colons.  */
3140
3141   GET_ENVIRONMENT (temp, "COMPILER_PATH");
3142   if (temp)
3143     {
3144       const char *startp, *endp;
3145       char *nstore = (char *) alloca (strlen (temp) + 3);
3146
3147       startp = endp = temp;
3148       while (1)
3149         {
3150           if (*endp == PATH_SEPARATOR || *endp == 0)
3151             {
3152               strncpy (nstore, startp, endp - startp);
3153               if (endp == startp)
3154                 strcpy (nstore, concat (".", dir_separator_str, NULL));
3155               else if (!IS_DIR_SEPARATOR (endp[-1]))
3156                 {
3157                   nstore[endp - startp] = DIR_SEPARATOR;
3158                   nstore[endp - startp + 1] = 0;
3159                 }
3160               else
3161                 nstore[endp - startp] = 0;
3162               add_prefix (&exec_prefixes, nstore, 0,
3163                           PREFIX_PRIORITY_LAST, 0, NULL, 0);
3164               add_prefix (&include_prefixes,
3165                           concat (nstore, "include", NULL),
3166                           0, PREFIX_PRIORITY_LAST, 0, NULL, 0);
3167               if (*endp == 0)
3168                 break;
3169               endp = startp = endp + 1;
3170             }
3171           else
3172             endp++;
3173         }
3174     }
3175
3176   GET_ENVIRONMENT (temp, LIBRARY_PATH_ENV);
3177   if (temp && *cross_compile == '0')
3178     {
3179       const char *startp, *endp;
3180       char *nstore = (char *) alloca (strlen (temp) + 3);
3181
3182       startp = endp = temp;
3183       while (1)
3184         {
3185           if (*endp == PATH_SEPARATOR || *endp == 0)
3186             {
3187               strncpy (nstore, startp, endp - startp);
3188               if (endp == startp)
3189                 strcpy (nstore, concat (".", dir_separator_str, NULL));
3190               else if (!IS_DIR_SEPARATOR (endp[-1]))
3191                 {
3192                   nstore[endp - startp] = DIR_SEPARATOR;
3193                   nstore[endp - startp + 1] = 0;
3194                 }
3195               else
3196                 nstore[endp - startp] = 0;
3197               add_prefix (&startfile_prefixes, nstore, NULL,
3198                           PREFIX_PRIORITY_LAST, 0, NULL, 1);
3199               if (*endp == 0)
3200                 break;
3201               endp = startp = endp + 1;
3202             }
3203           else
3204             endp++;
3205         }
3206     }
3207
3208   /* Use LPATH like LIBRARY_PATH (for the CMU build program).  */
3209   GET_ENVIRONMENT (temp, "LPATH");
3210   if (temp && *cross_compile == '0')
3211     {
3212       const char *startp, *endp;
3213       char *nstore = (char *) alloca (strlen (temp) + 3);
3214
3215       startp = endp = temp;
3216       while (1)
3217         {
3218           if (*endp == PATH_SEPARATOR || *endp == 0)
3219             {
3220               strncpy (nstore, startp, endp - startp);
3221               if (endp == startp)
3222                 strcpy (nstore, concat (".", dir_separator_str, NULL));
3223               else if (!IS_DIR_SEPARATOR (endp[-1]))
3224                 {
3225                   nstore[endp - startp] = DIR_SEPARATOR;
3226                   nstore[endp - startp + 1] = 0;
3227                 }
3228               else
3229                 nstore[endp - startp] = 0;
3230               add_prefix (&startfile_prefixes, nstore, NULL,
3231                           PREFIX_PRIORITY_LAST, 0, NULL, 1);
3232               if (*endp == 0)
3233                 break;
3234               endp = startp = endp + 1;
3235             }
3236           else
3237             endp++;
3238         }
3239     }
3240
3241   /* Convert new-style -- options to old-style.  */
3242   translate_options (&argc, &argv);
3243
3244   /* Do language-specific adjustment/addition of flags.  */
3245   lang_specific_driver (&argc, &argv, &added_libraries);
3246
3247   /* Scan argv twice.  Here, the first time, just count how many switches
3248      there will be in their vector, and how many input files in theirs.
3249      Here we also parse the switches that cc itself uses (e.g. -v).  */
3250
3251   for (i = 1; i < argc; i++)
3252     {
3253       if (! strcmp (argv[i], "-dumpspecs"))
3254         {
3255           struct spec_list *sl;
3256           init_spec ();
3257           for (sl = specs; sl; sl = sl->next)
3258             printf ("*%s:\n%s\n\n", sl->name, *(sl->ptr_spec));
3259           if (link_command_spec)
3260             printf ("*link_command:\n%s\n\n", link_command_spec);
3261           exit (0);
3262         }
3263       else if (! strcmp (argv[i], "-dumpversion"))
3264         {
3265           printf ("%s\n", spec_version);
3266           exit (0);
3267         }
3268       else if (! strcmp (argv[i], "-dumpmachine"))
3269         {
3270           printf ("%s\n", spec_machine);
3271           exit (0);
3272         }
3273       else if (strcmp (argv[i], "-fversion") == 0)
3274         {
3275           /* translate_options () has turned --version into -fversion.  */
3276           printf (_("%s (GCC) %s\n"), programname, version_string);
3277           fputs (_("Copyright (C) 2002 Free Software Foundation, Inc.\n"),
3278                  stdout);
3279           fputs (_("This is free software; see the source for copying conditions.  There is NO\n\
3280 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"),
3281                  stdout);
3282           exit (0);
3283         }
3284       else if (strcmp (argv[i], "-fhelp") == 0)
3285         {
3286           /* translate_options () has turned --help into -fhelp.  */
3287           print_help_list = 1;
3288
3289           /* We will be passing a dummy file on to the sub-processes.  */
3290           n_infiles++;
3291           n_switches++;
3292
3293           /* CPP driver cannot obtain switch from cc1_options.  */
3294           if (is_cpp_driver)
3295             add_preprocessor_option ("--help", 6);
3296           add_assembler_option ("--help", 6);
3297           add_linker_option ("--help", 6);
3298         }
3299       else if (strcmp (argv[i], "-ftarget-help") == 0)
3300         {
3301           /* translate_options() has turned --target-help into -ftarget-help.  */
3302           target_help_flag = 1;
3303
3304           /* We will be passing a dummy file on to the sub-processes.  */
3305           n_infiles++;
3306           n_switches++;
3307
3308           /* CPP driver cannot obtain switch from cc1_options.  */
3309           if (is_cpp_driver)
3310             add_preprocessor_option ("--target-help", 13);
3311           add_assembler_option ("--target-help", 13);
3312           add_linker_option ("--target-help", 13);
3313         }
3314       else if (! strcmp (argv[i], "-pass-exit-codes"))
3315         {
3316           pass_exit_codes = 1;
3317           n_switches++;
3318         }
3319       else if (! strcmp (argv[i], "-print-search-dirs"))
3320         print_search_dirs = 1;
3321       else if (! strcmp (argv[i], "-print-libgcc-file-name"))
3322         print_file_name = "libgcc.a";
3323       else if (! strncmp (argv[i], "-print-file-name=", 17))
3324         print_file_name = argv[i] + 17;
3325       else if (! strncmp (argv[i], "-print-prog-name=", 17))
3326         print_prog_name = argv[i] + 17;
3327       else if (! strcmp (argv[i], "-print-multi-lib"))
3328         print_multi_lib = 1;
3329       else if (! strcmp (argv[i], "-print-multi-directory"))
3330         print_multi_directory = 1;
3331       else if (! strcmp (argv[i], "-print-multi-os-directory"))
3332         print_multi_os_directory = 1;
3333       else if (! strncmp (argv[i], "-Wa,", 4))
3334         {
3335           int prev, j;
3336           /* Pass the rest of this option to the assembler.  */
3337
3338           /* Split the argument at commas.  */
3339           prev = 4;
3340           for (j = 4; argv[i][j]; j++)
3341             if (argv[i][j] == ',')
3342               {
3343                 add_assembler_option (argv[i] + prev, j - prev);
3344                 prev = j + 1;
3345               }
3346
3347           /* Record the part after the last comma.  */
3348           add_assembler_option (argv[i] + prev, j - prev);
3349         }
3350       else if (! strncmp (argv[i], "-Wp,", 4))
3351         {
3352           int prev, j;
3353           /* Pass the rest of this option to the preprocessor.  */
3354
3355           /* Split the argument at commas.  */
3356           prev = 4;
3357           for (j = 4; argv[i][j]; j++)
3358             if (argv[i][j] == ',')
3359               {
3360                 add_preprocessor_option (argv[i] + prev, j - prev);
3361                 prev = j + 1;
3362               }
3363
3364           /* Record the part after the last comma.  */
3365           add_preprocessor_option (argv[i] + prev, j - prev);
3366         }
3367       else if (argv[i][0] == '+' && argv[i][1] == 'e')
3368         /* The +e options to the C++ front-end.  */
3369         n_switches++;
3370       else if (strncmp (argv[i], "-Wl,", 4) == 0)
3371         {
3372           int j;
3373           /* Split the argument at commas.  */
3374           for (j = 3; argv[i][j]; j++)
3375             n_infiles += (argv[i][j] == ',');
3376         }
3377       else if (strcmp (argv[i], "-Xlinker") == 0)
3378         {
3379           if (i + 1 == argc)
3380             fatal ("argument to `-Xlinker' is missing");
3381
3382           n_infiles++;
3383           i++;
3384         }
3385       else if (strcmp (argv[i], "-l") == 0)
3386         {
3387           if (i + 1 == argc)
3388             fatal ("argument to `-l' is missing");
3389
3390           n_infiles++;
3391           i++;
3392         }
3393       else if (strncmp (argv[i], "-l", 2) == 0)
3394         n_infiles++;
3395       else if (strcmp (argv[i], "-save-temps") == 0)
3396         {
3397           save_temps_flag = 1;
3398           n_switches++;
3399         }
3400       else if (strcmp (argv[i], "-specs") == 0)
3401         {
3402           struct user_specs *user = (struct user_specs *)
3403             xmalloc (sizeof (struct user_specs));
3404           if (++i >= argc)
3405             fatal ("argument to `-specs' is missing");
3406
3407           user->next = (struct user_specs *) 0;
3408           user->filename = argv[i];
3409           if (user_specs_tail)
3410             user_specs_tail->next = user;
3411           else
3412             user_specs_head = user;
3413           user_specs_tail = user;
3414         }
3415       else if (strncmp (argv[i], "-specs=", 7) == 0)
3416         {
3417           struct user_specs *user = (struct user_specs *)
3418             xmalloc (sizeof (struct user_specs));
3419           if (strlen (argv[i]) == 7)
3420             fatal ("argument to `-specs=' is missing");
3421
3422           user->next = (struct user_specs *) 0;
3423           user->filename = argv[i] + 7;
3424           if (user_specs_tail)
3425             user_specs_tail->next = user;
3426           else
3427             user_specs_head = user;
3428           user_specs_tail = user;
3429         }
3430       else if (strcmp (argv[i], "-time") == 0)
3431         report_times = 1;
3432       else if (strcmp (argv[i], "-###") == 0)
3433         {
3434           /* This is similar to -v except that there is no execution
3435              of the commands and the echoed arguments are quoted.  It
3436              is intended for use in shell scripts to capture the
3437              driver-generated command line.  */
3438           verbose_only_flag++;
3439           verbose_flag++;
3440         }
3441       else if (argv[i][0] == '-' && argv[i][1] != 0)
3442         {
3443           const char *p = &argv[i][1];
3444           int c = *p;
3445
3446           switch (c)
3447             {
3448             case 'b':
3449             case 'V':
3450               fatal ("`-%c' must come at the start of the command line", c);
3451               break;
3452
3453             case 'B':
3454               {
3455                 const char *value;
3456                 int len;
3457
3458                 if (p[1] == 0 && i + 1 == argc)
3459                   fatal ("argument to `-B' is missing");
3460                 if (p[1] == 0)
3461                   value = argv[++i];
3462                 else
3463                   value = p + 1;
3464
3465                 len = strlen (value);
3466
3467                 /* Catch the case where the user has forgotten to append a
3468                    directory separator to the path.  Note, they may be using
3469                    -B to add an executable name prefix, eg "i386-elf-", in
3470                    order to distinguish between multiple installations of
3471                    GCC in the same directory.  Hence we must check to see
3472                    if appending a directory separator actually makes a
3473                    valid directory name.  */
3474                 if (! IS_DIR_SEPARATOR (value [len - 1])
3475                     && is_directory (value, "", 0))
3476                   {
3477                     char *tmp = xmalloc (len + 2);
3478                     strcpy (tmp, value);
3479                     tmp[len] = DIR_SEPARATOR;
3480                     tmp[++ len] = 0;
3481                     value = tmp;
3482                   }
3483
3484                 /* As a kludge, if the arg is "[foo/]stageN/", just
3485                    add "[foo/]include" to the include prefix.  */
3486                 if ((len == 7
3487                      || (len > 7
3488                          && (IS_DIR_SEPARATOR (value[len - 8]))))
3489                     && strncmp (value + len - 7, "stage", 5) == 0
3490                     && ISDIGIT (value[len - 2])
3491                     && (IS_DIR_SEPARATOR (value[len - 1])))
3492                   {
3493                     if (len == 7)
3494                       add_prefix (&include_prefixes, "include", NULL,
3495                                   PREFIX_PRIORITY_B_OPT, 0, NULL, 0);
3496                     else
3497                       {
3498                         char * string = xmalloc (len + 1);
3499
3500                         strncpy (string, value, len - 7);
3501                         strcpy (string + len - 7, "include");
3502                         add_prefix (&include_prefixes, string, NULL,
3503                                     PREFIX_PRIORITY_B_OPT, 0, NULL, 0);
3504                       }
3505                   }
3506
3507                 add_prefix (&exec_prefixes, value, NULL,
3508                             PREFIX_PRIORITY_B_OPT, 0, &warn_B, 0);
3509                 add_prefix (&startfile_prefixes, value, NULL,
3510                             PREFIX_PRIORITY_B_OPT, 0, &warn_B, 0);
3511                 add_prefix (&include_prefixes, concat (value, "include", NULL),
3512                             NULL, PREFIX_PRIORITY_B_OPT, 0, NULL, 0);
3513