OSDN Git Service

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