OSDN Git Service

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