OSDN Git Service

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