OSDN Git Service

Add missing \ before return inside string.
[pf3gnuchains/gcc-fork.git] / gcc / gcc.c
1 /* Compiler driver program that can handle many languages.
2    Copyright (C) 1987, 1989, 1992 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, 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 This paragraph is here to try to keep Sun CC from dying.
21 The number of chars here seems crucial!!!!  */
22
23 /* This program is the user interface to the C compiler and possibly to
24 other compilers.  It is used because compilation is a complicated procedure
25 which involves running several programs and passing temporary files between
26 them, forwarding the users switches to those programs selectively,
27 and deleting the temporary files at the end.
28
29 CC recognizes how to compile each input file by suffixes in the file names.
30 Once it knows which kind of compilation to perform, the procedure for
31 compilation is specified by a string called a "spec".  */
32 \f
33 #include <sys/types.h>
34 #include <ctype.h>
35 #include <signal.h>
36 #include <sys/stat.h>
37 #include <sys/file.h>   /* May get R_OK, etc. on some systems.  */
38
39 #include "config.h"
40 #include "obstack.h"
41 #include "gvarargs.h"
42 #include <stdio.h>
43
44 #ifndef R_OK
45 #define R_OK 4
46 #define W_OK 2
47 #define X_OK 1
48 #endif
49
50 /* Define a generic NULL if one hasn't already been defined.  */
51
52 #ifndef NULL
53 #define NULL 0
54 #endif
55
56 #ifndef GENERIC_PTR
57 #if defined (USE_PROTOTYPES) ? USE_PROTOTYPES : defined (__STDC__)
58 #define GENERIC_PTR void *
59 #else
60 #define GENERIC_PTR char *
61 #endif
62 #endif
63
64 #ifndef NULL_PTR
65 #define NULL_PTR ((GENERIC_PTR)0)
66 #endif
67
68 #ifdef USG
69 #define vfork fork
70 #endif /* USG */
71
72 /* On MSDOS, write temp files in current dir
73    because there's no place else we can expect to use.  */
74 #if __MSDOS__
75 #ifndef P_tmpdir
76 #define P_tmpdir "./"
77 #endif
78 #endif
79
80 /* Test if something is a normal file.  */
81 #ifndef S_ISREG
82 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
83 #endif
84
85 /* Test if something is a directory.  */
86 #ifndef S_ISDIR
87 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
88 #endif
89
90 /* By default there is no special suffix for executables.  */
91 #ifndef EXECUTABLE_SUFFIX
92 #define EXECUTABLE_SUFFIX ""
93 #endif
94
95 /* By default, colon separates directories in a path.  */
96 #ifndef PATH_SEPARATOR
97 #define PATH_SEPARATOR ':'
98 #endif
99
100 #define obstack_chunk_alloc xmalloc
101 #define obstack_chunk_free free
102
103 extern void free ();
104 extern char *getenv ();
105
106 extern int errno, sys_nerr;
107 extern char *sys_errlist[];
108
109 extern int execv (), execvp ();
110
111 /* If a stage of compilation returns an exit status >= 1,
112    compilation of that file ceases.  */
113
114 #define MIN_FATAL_STATUS 1
115
116 /* Flag saying to print the full filename of libgcc.a
117    as found through our usual search mechanism.  */
118
119 static int print_libgcc_file_name;
120
121 /* Flag indicating whether we should print the command and arguments */
122
123 static int verbose_flag;
124
125 /* Nonzero means write "temp" files in source directory
126    and use the source file's name in them, and don't delete them.  */
127
128 static int save_temps_flag;
129
130 /* The compiler version specified with -V */
131
132 static char *spec_version;
133
134 /* The target machine specified with -b.  */
135
136 static char *spec_machine = DEFAULT_TARGET_MACHINE;
137
138 /* Nonzero if cross-compiling.
139    When -b is used, the value comes from the `specs' file.  */
140
141 #ifdef CROSS_COMPILE
142 static int cross_compile = 1;
143 #else
144 static int cross_compile = 0;
145 #endif
146
147 /* The number of errors that have occurred; the link phase will not be
148    run if this is non-zero.  */
149 static int error_count = 0;
150
151 /* This is the obstack which we use to allocate many strings.  */
152
153 static struct obstack obstack;
154
155 /* This is the obstack to build an environment variable to pass to
156    collect2 that describes all of the relevant switches of what to
157    pass the compiler in building the list of pointers to constructors
158    and destructors.  */
159
160 static struct obstack collect_obstack;
161
162 extern char *version_string;
163
164 static void set_spec ();
165 static struct compiler *lookup_compiler ();
166 static char *find_a_file ();
167 static void add_prefix ();
168 static char *skip_whitespace ();
169 static void record_temp_file ();
170 static char *handle_braces ();
171 static char *save_string ();
172 static char *concat ();
173 static int do_spec ();
174 static int do_spec_1 ();
175 static char *find_file ();
176 static int is_linker_dir ();
177 static void validate_switches ();
178 static void validate_all_switches ();
179 static void give_switch ();
180 static void pfatal_with_name ();
181 static void perror_with_name ();
182 static void perror_exec ();
183 static void fatal ();
184 static void error ();
185 void fancy_abort ();
186 char *xmalloc ();
187 char *xrealloc ();
188 \f
189 /* Specs are strings containing lines, each of which (if not blank)
190 is made up of a program name, and arguments separated by spaces.
191 The program name must be exact and start from root, since no path
192 is searched and it is unreliable to depend on the current working directory.
193 Redirection of input or output is not supported; the subprograms must
194 accept filenames saying what files to read and write.
195
196 In addition, the specs can contain %-sequences to substitute variable text
197 or for conditional text.  Here is a table of all defined %-sequences.
198 Note that spaces are not generated automatically around the results of
199 expanding these sequences; therefore, you can concatenate them together
200 or with constant text in a single argument.
201
202  %%     substitute one % into the program name or argument.
203  %i     substitute the name of the input file being processed.
204  %b     substitute the basename of the input file being processed.
205         This is the substring up to (and not including) the last period
206         and not including the directory.
207  %g     substitute the temporary-file-name-base.  This is a string chosen
208         once per compilation.  Different temporary file names are made by
209         concatenation of constant strings on the end, as in `%g.s'.
210         %g also has the same effect of %d.
211  %u     like %g, but make the temporary file name unique.
212  %U     returns the last file name generated with %u.
213  %d     marks the argument containing or following the %d as a
214         temporary file name, so that that file will be deleted if CC exits
215         successfully.  Unlike %g, this contributes no text to the argument.
216  %w     marks the argument containing or following the %w as the
217         "output file" of this compilation.  This puts the argument
218         into the sequence of arguments that %o will substitute later.
219  %W{...}
220         like %{...} but mark last argument supplied within
221         as a file to be deleted on failure.
222  %o     substitutes the names of all the output files, with spaces
223         automatically placed around them.  You should write spaces
224         around the %o as well or the results are undefined.
225         %o is for use in the specs for running the linker.
226         Input files whose names have no recognized suffix are not compiled
227         at all, but they are included among the output files, so they will
228         be linked.
229  %p     substitutes the standard macro predefinitions for the
230         current target machine.  Use this when running cpp.
231  %P     like %p, but puts `__' before and after the name of each macro.
232         (Except macros that already have __.)
233         This is for ANSI C.
234  %I     Substitute a -iprefix option made from GCC_EXEC_PREFIX.
235  %s     current argument is the name of a library or startup file of some sort.
236         Search for that file in a standard list of directories
237         and substitute the full name found.
238  %eSTR  Print STR as an error message.  STR is terminated by a newline.
239         Use this when inconsistent options are detected.
240  %x{OPTION}     Accumulate an option for %X.
241  %X     Output the accumulated linker options specified by compilations.
242  %Y     Output the accumulated assembler options specified by compilations.
243  %a     process ASM_SPEC as a spec.
244         This allows config.h to specify part of the spec for running as.
245  %A     process ASM_FINAL_SPEC as a spec.  A capital A is actually
246         used here.  This can be used to run a post-processor after the
247         assembler has done it's job.
248  %D     Dump out a -L option for each directory in library_prefix,
249         followed by a -L option for each directory in startfile_prefix.
250  %l     process LINK_SPEC as a spec.
251  %L     process LIB_SPEC as a spec.
252  %S     process STARTFILE_SPEC as a spec.  A capital S is actually used here.
253  %E     process ENDFILE_SPEC as a spec.  A capital E is actually used here.
254  %c     process SIGNED_CHAR_SPEC as a spec.
255  %C     process CPP_SPEC as a spec.  A capital C is actually used here.
256  %1     process CC1_SPEC as a spec.
257  %2     process CC1PLUS_SPEC as a spec.
258  %|     output "-" if the input for the current command is coming from a pipe.
259  %*     substitute the variable part of a matched option.  (See below.)
260         Note that each comma in the substituted string is replaced by
261         a single space.
262  %{S}   substitutes the -S switch, if that switch was given to CC.
263         If that switch was not specified, this substitutes nothing.
264         Here S is a metasyntactic variable.
265  %{S*}  substitutes all the switches specified to CC whose names start
266         with -S.  This is used for -o, -D, -I, etc; switches that take
267         arguments.  CC considers `-o foo' as being one switch whose
268         name starts with `o'.  %{o*} would substitute this text,
269         including the space; thus, two arguments would be generated.
270  %{S*:X} substitutes X if one or more switches whose names start with -S are
271         specified to CC.  Note that the tail part of the -S option
272         (i.e. the part matched by the `*') will be substituted for each
273         occurrence of %* within X.
274  %{S:X} substitutes X, but only if the -S switch was given to CC.
275  %{!S:X} substitutes X, but only if the -S switch was NOT given to CC.
276  %{|S:X} like %{S:X}, but if no S switch, substitute `-'.
277  %{|!S:X} like %{!S:X}, but if there is an S switch, substitute `-'.
278  %{.S:X} substitutes X, but only if processing a file with suffix S.
279  %{!.S:X} substitutes X, but only if NOT processing a file with suffix S.
280  %(Spec) processes a specification defined in a specs file as *Spec:
281  %[Spec] as above, but put __ around -D arguments
282
283 The conditional text X in a %{S:X} or %{!S:X} construct may contain
284 other nested % constructs or spaces, or even newlines.  They are
285 processed as usual, as described above.
286
287 The character | is used to indicate that a command should be piped to
288 the following command, but only if -pipe is specified.
289
290 Note that it is built into CC which switches take arguments and which
291 do not.  You might think it would be useful to generalize this to
292 allow each compiler's spec to say which switches take arguments.  But
293 this cannot be done in a consistent fashion.  CC cannot even decide
294 which input files have been specified without knowing which switches
295 take arguments, and it must know which input files to compile in order
296 to tell which compilers to run.
297
298 CC also knows implicitly that arguments starting in `-l' are to be
299 treated as compiler output files, and passed to the linker in their
300 proper position among the other output files.  */
301 \f
302 /* Define the macros used for specs %a, %l, %L, %S, %c, %C, %1.  */
303
304 /* config.h can define ASM_SPEC to provide extra args to the assembler
305    or extra switch-translations.  */
306 #ifndef ASM_SPEC
307 #define ASM_SPEC ""
308 #endif
309
310 /* config.h can define ASM_FINAL_SPEC to run a post processor after
311    the assembler has run.  */
312 #ifndef ASM_FINAL_SPEC
313 #define ASM_FINAL_SPEC ""
314 #endif
315
316 /* config.h can define CPP_SPEC to provide extra args to the C preprocessor
317    or extra switch-translations.  */
318 #ifndef CPP_SPEC
319 #define CPP_SPEC ""
320 #endif
321
322 /* config.h can define CC1_SPEC to provide extra args to cc1 and cc1plus
323    or extra switch-translations.  */
324 #ifndef CC1_SPEC
325 #define CC1_SPEC ""
326 #endif
327
328 /* config.h can define CC1PLUS_SPEC to provide extra args to cc1plus
329    or extra switch-translations.  */
330 #ifndef CC1PLUS_SPEC
331 #define CC1PLUS_SPEC ""
332 #endif
333
334 /* config.h can define LINK_SPEC to provide extra args to the linker
335    or extra switch-translations.  */
336 #ifndef LINK_SPEC
337 #define LINK_SPEC ""
338 #endif
339
340 /* config.h can define LIB_SPEC to override the default libraries.  */
341 #ifndef LIB_SPEC
342 #define LIB_SPEC "%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}"
343 #endif
344
345 /* config.h can define STARTFILE_SPEC to override the default crt0 files.  */
346 #ifndef STARTFILE_SPEC
347 #define STARTFILE_SPEC  \
348   "%{pg:gcrt0.o%s}%{!pg:%{p:mcrt0.o%s}%{!p:crt0.o%s}}"
349 #endif
350
351 /* config.h can define SWITCHES_NEED_SPACES to control passing -o and -L.
352    Make the string nonempty to require spaces there.  */
353 #ifndef SWITCHES_NEED_SPACES
354 #define SWITCHES_NEED_SPACES ""
355 #endif
356
357 /* config.h can define ENDFILE_SPEC to override the default crtn files.  */
358 #ifndef ENDFILE_SPEC
359 #define ENDFILE_SPEC ""
360 #endif
361
362 /* This spec is used for telling cpp whether char is signed or not.  */
363 #ifndef SIGNED_CHAR_SPEC
364 /* Use #if rather than ?:
365    because MIPS C compiler rejects like ?: in initializers.  */
366 #if DEFAULT_SIGNED_CHAR
367 #define SIGNED_CHAR_SPEC "%{funsigned-char:-D__CHAR_UNSIGNED__}"
368 #else
369 #define SIGNED_CHAR_SPEC "%{!fsigned-char:-D__CHAR_UNSIGNED__}"
370 #endif
371 #endif
372
373 static char *cpp_spec = CPP_SPEC;
374 static char *cpp_predefines = CPP_PREDEFINES;
375 static char *cc1_spec = CC1_SPEC;
376 static char *cc1plus_spec = CC1PLUS_SPEC;
377 static char *signed_char_spec = SIGNED_CHAR_SPEC;
378 static char *asm_spec = ASM_SPEC;
379 static char *asm_final_spec = ASM_FINAL_SPEC;
380 static char *link_spec = LINK_SPEC;
381 static char *lib_spec = LIB_SPEC;
382 static char *endfile_spec = ENDFILE_SPEC;
383 static char *startfile_spec = STARTFILE_SPEC;
384 static char *switches_need_spaces = SWITCHES_NEED_SPACES;
385
386 /* This defines which switch letters take arguments.  */
387
388 #ifndef SWITCH_TAKES_ARG
389 #define SWITCH_TAKES_ARG(CHAR)      \
390   ((CHAR) == 'D' || (CHAR) == 'U' || (CHAR) == 'o' \
391    || (CHAR) == 'e' || (CHAR) == 'T' || (CHAR) == 'u' \
392    || (CHAR) == 'I' || (CHAR) == 'm' \
393    || (CHAR) == 'L' || (CHAR) == 'A')
394 #endif
395
396 /* This defines which multi-letter switches take arguments.  */
397
398 #ifndef WORD_SWITCH_TAKES_ARG
399 #define WORD_SWITCH_TAKES_ARG(STR)                      \
400  (!strcmp (STR, "Tdata") || !strcmp (STR, "Ttext")      \
401   || !strcmp (STR, "Tbss") || !strcmp (STR, "include")  \
402   || !strcmp (STR, "imacros") || !strcmp (STR, "aux-info"))
403 #endif
404 \f
405 /* Record the mapping from file suffixes for compilation specs.  */
406
407 struct compiler
408 {
409   char *suffix;                 /* Use this compiler for input files
410                                    whose names end in this suffix.  */
411
412   char *spec[4];                /* To use this compiler, concatenate these
413                                    specs and pass to do_spec.  */
414 };
415
416 /* Pointer to a vector of `struct compiler' that gives the spec for
417    compiling a file, based on its suffix.
418    A file that does not end in any of these suffixes will be passed
419    unchanged to the loader and nothing else will be done to it.
420
421    An entry containing two 0s is used to terminate the vector.
422
423    If multiple entries match a file, the last matching one is used.  */
424
425 static struct compiler *compilers;
426
427 /* Number of entries in `compilers', not counting the null terminator.  */
428
429 static int n_compilers;
430
431 /* The default list of file name suffixes and their compilation specs.  */
432
433 static struct compiler default_compilers[] =
434 {
435   {".c", "@c"},
436   {"@c",
437    "cpp -lang-c %{nostdinc*} %{C} %{v} %{A*} %{I*} %{P} %I\
438         %{C:%{!E:%eGNU C does not support -C without using -E}}\
439         %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d}\
440         -undef -D__GNUC__=2 %{ansi:-trigraphs -$ -D__STRICT_ANSI__}\
441         %{!undef:%{!ansi:%p} %P} %{trigraphs} \
442         %c %{O*:-D__OPTIMIZE__} %{traditional} %{ftraditional:-traditional}\
443         %{traditional-cpp:-traditional}\
444         %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{D*} %{U*} %{i*}\
445         %i %{!M:%{!MM:%{!E:%{!pipe:%g.i}}}}%{E:%W{o*}}%{M:%W{o*}}%{MM:%W{o*}} |\n",
446    "%{!M:%{!MM:%{!E:cc1 %{!pipe:%g.i} %1 \
447                    %{!Q:-quiet} -dumpbase %b.c %{d*} %{m*} %{a}\
448                    %{g*} %{O*} %{W*} %{w} %{pedantic*} %{ansi} \
449                    %{traditional} %{v:-version} %{pg:-p} %{p} %{f*}\
450                    %{aux-info*}\
451                    %{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
452                    %{S:%W{o*}%{!o*:-o %b.s}}%{!S:-o %{|!pipe:%g.s}} |\n\
453               %{!S:as %{R} %{j} %{J} %{h} %{d2} %a %Y\
454                       %{c:%W{o*}%{!o*:-o %w%b.o}}%{!c:-o %d%w%u.o}\
455                       %{!pipe:%g.s} %A\n }}}}"},
456   {"-",
457    "%{E:cpp -lang-c %{nostdinc*} %{C} %{v} %{A*} %{I*} %{P} %I\
458         %{C:%{!E:%eGNU C does not support -C without using -E}}\
459         %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d}\
460         -undef -D__GNUC__=2 %{ansi:-trigraphs -$ -D__STRICT_ANSI__}\
461         %{!undef:%{!ansi:%p} %P} %{trigraphs}\
462         %c %{O*:-D__OPTIMIZE__} %{traditional} %{ftraditional:-traditional}\
463         %{traditional-cpp:-traditional}\
464         %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{D*} %{U*} %{i*}\
465         %i %W{o*}}\
466     %{!E:%e-E required when input is from standard input}"},
467   {".m", "@objective-c"},
468   {"@objective-c",
469    "cpp -lang-objc %{nostdinc*} %{C} %{v} %{A*} %{I*} %{P} %I\
470         %{C:%{!E:%eGNU C does not support -C without using -E}}\
471         %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d}\
472         -undef -D__OBJC__ -D__GNUC__=2 %{ansi:-trigraphs -$ -D__STRICT_ANSI__}\
473         %{!undef:%{!ansi:%p} %P} %{trigraphs}\
474         %c %{O*:-D__OPTIMIZE__} %{traditional} %{ftraditional:-traditional}\
475         %{traditional-cpp:-traditional}\
476         %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{D*} %{U*} %{i*}\
477         %i %{!M:%{!MM:%{!E:%{!pipe:%g.i}}}}%{E:%W{o*}}%{M:%W{o*}}%{MM:%W{o*}} |\n",
478    "%{!M:%{!MM:%{!E:cc1obj %{!pipe:%g.i} %1 \
479                    %{!Q:-quiet} -dumpbase %b.m %{d*} %{m*} %{a}\
480                    %{g*} %{O*} %{W*} %{w} %{pedantic*} %{ansi} \
481                    %{traditional} %{v:-version} %{pg:-p} %{p} %{f*} \
482                    -lang-objc %{gen-decls} \
483                    %{aux-info*}\
484                    %{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
485                    %{S:%W{o*}%{!o*:-o %b.s}}%{!S:-o %{|!pipe:%g.s}} |\n\
486               %{!S:as %{R} %{j} %{J} %{h} %{d2} %a %Y\
487                       %{c:%W{o*}%{!o*:-o %w%b.o}}%{!c:-o %d%w%u.o}\
488                       %{!pipe:%g.s} %A\n }}}}"},
489   {".h", "@c-header"},
490   {"@c-header",
491    "%{!E:%eCompilation of header file requested} \
492     cpp %{nostdinc*} %{C} %{v} %{A*} %{I*} %{P} %I\
493         %{C:%{!E:%eGNU C does not support -C without using -E}}\
494          %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d} \
495         -undef -D__GNUC__=2 %{ansi:-trigraphs -$ -D__STRICT_ANSI__}\
496         %{!undef:%{!ansi:%p} %P} %{trigraphs}\
497         %c %{O*:-D__OPTIMIZE__} %{traditional} %{ftraditional:-traditional}\
498         %{traditional-cpp:-traditional}\
499         %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{D*} %{U*} %{i*}\
500         %i %W{o*}"},
501   {".cc", "@c++"},
502   {".cxx", "@c++"},
503   {".C", "@c++"},
504   {"@c++",
505    "cpp -lang-c++ %{nostdinc*} %{C} %{v} %{A*} %{I*} %{P} %I\
506         %{C:%{!E:%eGNU C++ does not support -C without using -E}}\
507         %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d} \
508         -undef -D__GNUC__=2 -D__GNUG__=2 -D__cplusplus \
509         %{ansi:-trigraphs -$ -D__STRICT_ANSI__} %{!undef:%{!ansi:%p} %P}\
510         %c %{O*:-D__OPTIMIZE__} %{traditional} %{ftraditional:-traditional}\
511         %{traditional-cpp:-traditional} %{trigraphs}\
512         %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{D*} %{U*} %{i*}\
513         %i %{!M:%{!MM:%{!E:%{!pipe:%g.i}}}}%{E:%W{o*}}%{M:%W{o*}}%{MM:%W{o*}} |\n",
514    "%{!M:%{!MM:%{!E:cc1plus %{!pipe:%g.i} %1 %2\
515                    %{!Q:-quiet} -dumpbase %b.cc %{d*} %{m*} %{a}\
516                    %{g*} %{O*} %{W*} %{w} %{pedantic*} %{ansi} %{traditional}\
517                    %{v:-version} %{pg:-p} %{p} %{f*} %{+e*}\
518                    %{aux-info*}\
519                    %{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
520                    %{S:%W{o*}%{!o*:-o %b.s}}%{!S:-o %{|!pipe:%g.s}} |\n\
521               %{!S:as %{R} %{j} %{J} %{h} %{d2} %a %Y\
522                       %{c:%W{o*}%{!o*:-o %w%b.o}}%{!c:-o %d%w%u.o}\
523                       %{!pipe:%g.s} %A\n }}}}"},
524   {".i", "@cpp-output"},
525   {"@cpp-output",
526    "cc1 %i %1 %{!Q:-quiet} %{d*} %{m*} %{a}\
527         %{g*} %{O*} %{W*} %{w} %{pedantic*} %{ansi} %{traditional}\
528         %{v:-version} %{pg:-p} %{p} %{f*}\
529         %{aux-info*}\
530         %{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
531         %{S:%W{o*}%{!o*:-o %b.s}}%{!S:-o %{|!pipe:%g.s}} |\n\
532     %{!S:as %{R} %{j} %{J} %{h} %{d2} %a %Y\
533             %{c:%W{o*}%{!o*:-o %w%b.o}}%{!c:-o %d%w%u.o} %{!pipe:%g.s} %A\n }"},
534   {".ii", "@c++-cpp-output"},
535   {"@c++-cpp-output",
536    "cc1plus %i %1 %2 %{!Q:-quiet} %{d*} %{m*} %{a}\
537             %{g*} %{O*} %{W*} %{w} %{pedantic*} %{ansi} %{traditional}\
538             %{v:-version} %{pg:-p} %{p} %{f*} %{+e*}\
539             %{aux-info*}\
540             %{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
541             %{S:%W{o*}%{!o*:-o %b.s}}%{!S:-o %{|!pipe:%g.s}} |\n\
542        %{!S:as %{R} %{j} %{J} %{h} %{d2} %a %Y\
543                %{c:%W{o*}%{!o*:-o %w%b.o}}%{!c:-o %d%w%u.o}\
544                %{!pipe:%g.s} %A\n }"},
545   {".s", "@assembler"},
546   {"@assembler",
547    "%{!S:as %{R} %{j} %{J} %{h} %{d2} %a %Y\
548             %{c:%W{o*}%{!o*:-o %w%b.o}}%{!c:-o %d%w%u.o} %i %A\n }"},
549   {".S", "@assembler-with-cpp"},
550   {"@assembler-with-cpp",
551    "cpp -lang-asm %{nostdinc*} %{C} %{v} %{A*} %{I*} %{P} %I\
552         %{C:%{!E:%eGNU C does not support -C without using -E}}\
553         %{M} %{MM} %{MD:-MD %b.d} %{MMD:-MMD %b.d} %{trigraphs} \
554         -undef -$ %{!undef:%p %P} -D__ASSEMBLER__ \
555         %c %{O*:-D__OPTIMIZE__} %{traditional} %{ftraditional:-traditional}\
556         %{traditional-cpp:-traditional}\
557         %{g*} %{W*} %{w} %{pedantic*} %{H} %{d*} %C %{D*} %{U*} %{i*}\
558         %i %{!M:%{!MM:%{!E:%{!pipe:%g.s}}}}%{E:%W{o*}}%{M:%W{o*}}%{MM:%W{o*}} |\n",
559    "%{!M:%{!MM:%{!E:%{!S:as %{R} %{j} %{J} %{h} %{d2} %a %Y\
560                     %{c:%W{o*}%{!o*:-o %w%b.o}}%{!c:-o %d%w%u.o}\
561                     %{!pipe:%g.s} %A\n }}}}"},
562   /* Mark end of table */
563   {0, 0}
564 };
565
566 /* Number of elements in default_compilers, not counting the terminator.  */
567
568 static int n_default_compilers
569   = (sizeof default_compilers / sizeof (struct compiler)) - 1;
570
571 /* Here is the spec for running the linker, after compiling all files.  */
572
573 /* -u* was put back because both BSD and SysV seem to support it.  */
574 /* %{static:} simply prevents an error message if the target machine
575    doesn't handle -static.  */
576 #ifdef LINK_LIBGCC_SPECIAL_1
577 /* Have gcc do the search for libgcc.a, but generate -L options as usual.  */
578 static char *link_command_spec = "\
579 %{!fsyntax-only: \
580  %{!c:%{!M:%{!MM:%{!E:%{!S:ld %l %X %{o*} %{A} %{d} %{e*} %{m} %{N} %{n} \
581                         %{r} %{s} %{T*} %{t} %{u*} %{x} %{z}\
582                         %{!A:%{!nostdlib:%S}} %{static:}\
583                         %{L*} %D %o %{!nostdlib:libgcc.a%s %L libgcc.a%s %{!A:%E}}\n }}}}}}";
584 #else
585 #ifdef LINK_LIBGCC_SPECIAL
586 /* Have gcc do the search for libgcc.a, and don't generate -L options.  */
587 static char *link_command_spec = "\
588 %{!fsyntax-only: \
589  %{!c:%{!M:%{!MM:%{!E:%{!S:ld %l %X %{o*} %{A} %{d} %{e*} %{m} %{N} %{n} \
590                         %{r} %{s} %{T*} %{t} %{u*} %{x} %{z}\
591                         %{!A:%{!nostdlib:%S}} %{static:}\
592                         %{L*} %o %{!nostdlib:libgcc.a%s %L libgcc.a%s %{!A:%E}}\n }}}}}}";
593 #else
594 /* Use -L and have the linker do the search for -lgcc.  */
595 static char *link_command_spec = "\
596 %{!fsyntax-only: \
597  %{!c:%{!M:%{!MM:%{!E:%{!S:ld %l %X %{o*} %{A} %{d} %{e*} %{m} %{N} %{n} \
598                         %{r} %{s} %{T*} %{t} %{u*} %{x} %{z}\
599                         %{!A:%{!nostdlib:%S}} %{static:}\
600                         %{L*} %D %o %{!nostdlib:-lgcc %L -lgcc %{!A:%E}}\n }}}}}}";
601 #endif
602 #endif
603
604 /* A vector of options to give to the linker.
605    These options are accumulated by -Xlinker and -Wl,
606    and substituted into the linker command with %X.  */
607 static int n_linker_options;
608 static char **linker_options;
609
610 /* A vector of options to give to the assembler.
611    These options are accumulated by -Wa,
612    and substituted into the assembler command with %X.  */
613 static int n_assembler_options;
614 static char **assembler_options;
615 \f
616 /* Read compilation specs from a file named FILENAME,
617    replacing the default ones.
618
619    A suffix which starts with `*' is a definition for
620    one of the machine-specific sub-specs.  The "suffix" should be
621    *asm, *cc1, *cpp, *link, *startfile, *signed_char, etc.
622    The corresponding spec is stored in asm_spec, etc.,
623    rather than in the `compilers' vector.
624
625    Anything invalid in the file is a fatal error.  */
626
627 static void
628 read_specs (filename)
629      char *filename;
630 {
631   int desc;
632   struct stat statbuf;
633   char *buffer;
634   register char *p;
635
636   if (verbose_flag)
637     fprintf (stderr, "Reading specs from %s\n", filename);
638
639   /* Open and stat the file.  */
640   desc = open (filename, 0, 0);
641   if (desc < 0)
642     pfatal_with_name (filename);
643   if (stat (filename, &statbuf) < 0)
644     pfatal_with_name (filename);
645
646   /* Read contents of file into BUFFER.  */
647   buffer = xmalloc ((unsigned) statbuf.st_size + 1);
648   read (desc, buffer, (unsigned) statbuf.st_size);
649   buffer[statbuf.st_size] = 0;
650   close (desc);
651
652   /* Scan BUFFER for specs, putting them in the vector.  */
653   p = buffer;
654   while (1)
655     {
656       char *suffix;
657       char *spec;
658       char *in, *out, *p1, *p2;
659
660       /* Advance P in BUFFER to the next nonblank nocomment line.  */
661       p = skip_whitespace (p);
662       if (*p == 0)
663         break;
664
665       /* Find the colon that should end the suffix.  */
666       p1 = p;
667       while (*p1 && *p1 != ':' && *p1 != '\n') p1++;
668       /* The colon shouldn't be missing.  */
669       if (*p1 != ':')
670         fatal ("specs file malformed after %d characters", p1 - buffer);
671       /* Skip back over trailing whitespace.  */
672       p2 = p1;
673       while (p2 > buffer && (p2[-1] == ' ' || p2[-1] == '\t')) p2--;
674       /* Copy the suffix to a string.  */
675       suffix = save_string (p, p2 - p);
676       /* Find the next line.  */
677       p = skip_whitespace (p1 + 1);
678       if (p[1] == 0)
679         fatal ("specs file malformed after %d characters", p - buffer);
680       p1 = p;
681       /* Find next blank line.  */
682       while (*p1 && !(*p1 == '\n' && p1[1] == '\n')) p1++;
683       /* Specs end at the blank line and do not include the newline.  */
684       spec = save_string (p, p1 - p);
685       p = p1;
686
687       /* Delete backslash-newline sequences from the spec.  */
688       in = spec;
689       out = spec;
690       while (*in != 0)
691         {
692           if (in[0] == '\\' && in[1] == '\n')
693             in += 2;
694           else if (in[0] == '#')
695             {
696               while (*in && *in != '\n') in++;
697             }
698           else
699             *out++ = *in++;
700         }
701       *out = 0;
702
703       if (suffix[0] == '*')
704         {
705           if (! strcmp (suffix, "*link_command"))
706             link_command_spec = spec;
707           else
708             set_spec (suffix + 1, spec);
709         }
710       else
711         {
712           /* Add this pair to the vector.  */
713           compilers
714             = ((struct compiler *)
715                xrealloc (compilers, (n_compilers + 2) * sizeof (struct compiler)));
716           compilers[n_compilers].suffix = suffix;
717           bzero (compilers[n_compilers].spec,
718                  sizeof compilers[n_compilers].spec);
719           compilers[n_compilers].spec[0] = spec;
720           n_compilers++;
721         }
722
723       if (*suffix == 0)
724         link_command_spec = spec;
725     }
726
727   if (link_command_spec == 0)
728     fatal ("spec file has no spec for linking");
729 }
730
731 static char *
732 skip_whitespace (p)
733      char *p;
734 {
735   while (1)
736     {
737       /* A fully-blank line is a delimiter in the SPEC file and shouldn't
738          be considered whitespace.  */
739       if (p[0] == '\n' && p[1] == '\n' && p[2] == '\n')
740         return p + 1;
741       else if (*p == '\n' || *p == ' ' || *p == '\t')
742         p++;
743       else if (*p == '#')
744         {
745           while (*p != '\n') p++;
746           p++;
747         }
748       else
749         break;
750     }
751
752   return p;
753 }
754 \f
755 /* Structure to keep track of the specs that have been defined so far.  These
756    are accessed using %(specname) or %[specname] in a compiler or link spec. */
757
758 struct spec_list
759 {
760   char *name;                 /* Name of the spec. */
761   char *spec;                 /* The spec itself. */
762   struct spec_list *next;     /* Next spec in linked list. */
763 };
764
765 /* List of specs that have been defined so far. */
766
767 static struct spec_list *specs = (struct spec_list *) 0;
768 \f
769 /* Change the value of spec NAME to SPEC.  If SPEC is empty, then the spec is
770    removed; If the spec starts with a + then SPEC is added to the end of the
771    current spec. */
772
773 static void
774 set_spec (name, spec)
775      char *name;
776      char *spec;
777 {
778   struct spec_list *sl;
779   char *old_spec;
780
781   /* See if the spec already exists */
782   for (sl = specs; sl; sl = sl->next)
783     if (strcmp (sl->name, name) == 0)
784       break;
785
786   if (!sl)
787     {
788       /* Not found - make it */
789       sl = (struct spec_list *) xmalloc (sizeof (struct spec_list));
790       sl->name = save_string (name, strlen (name));
791       sl->spec = save_string ("", 0);
792       sl->next = specs;
793       specs = sl;
794     }
795
796   old_spec = sl->spec;
797   if (name && spec[0] == '+' && isspace (spec[1]))
798     sl->spec = concat (old_spec, spec + 1, "");
799   else
800     sl->spec = save_string (spec, strlen (spec));
801
802   if (! strcmp (name, "asm"))
803     asm_spec = sl->spec;
804   else if (! strcmp (name, "asm_final"))
805     asm_final_spec = sl->spec;
806   else if (! strcmp (name, "cc1"))
807     cc1_spec = sl->spec;
808   else if (! strcmp (name, "cc1plus"))
809     cc1plus_spec = sl->spec;
810   else if (! strcmp (name, "cpp"))
811     cpp_spec = sl->spec;
812   else if (! strcmp (name, "endfile"))
813     endfile_spec = sl->spec;
814   else if (! strcmp (name, "lib"))
815     lib_spec = sl->spec;
816   else if (! strcmp (name, "link"))
817     link_spec = sl->spec;
818   else if (! strcmp (name, "predefines"))
819     cpp_predefines = sl->spec;
820   else if (! strcmp (name, "signed_char"))
821     signed_char_spec = sl->spec;
822   else if (! strcmp (name, "startfile"))
823     startfile_spec = sl->spec;
824   else if (! strcmp (name, "switches_need_spaces"))
825     switches_need_spaces = sl->spec;
826   else if (! strcmp (name, "cross_compile"))
827     cross_compile = atoi (sl->spec);
828   /* Free the old spec */
829   if (old_spec)
830     free (old_spec);
831 }
832 \f
833 /* Accumulate a command (program name and args), and run it.  */
834
835 /* Vector of pointers to arguments in the current line of specifications.  */
836
837 static char **argbuf;
838
839 /* Number of elements allocated in argbuf.  */
840
841 static int argbuf_length;
842
843 /* Number of elements in argbuf currently in use (containing args).  */
844
845 static int argbuf_index;
846
847 /* This is the list of suffixes and codes (%g/%u/%U) and the associated
848    temp file.  Used only if MKTEMP_EACH_FILE.  */
849
850 static struct temp_name {
851   char *suffix;         /* suffix associated with the code.  */
852   int length;           /* strlen (suffix).  */
853   int unique;           /* Indicates whether %g or %u/%U was used.  */
854   char *filename;       /* associated filename.  */
855   int filename_length;  /* strlen (filename).  */
856   struct temp_name *next;
857 } *temp_names;
858
859 /* Number of commands executed so far.  */
860
861 static int execution_count;
862
863 /* Number of commands that exited with a signal.  */
864
865 static int signal_count;
866
867 /* Name with which this program was invoked.  */
868
869 static char *programname;
870 \f
871 /* Structures to keep track of prefixes to try when looking for files. */
872
873 struct prefix_list
874 {
875   char *prefix;               /* String to prepend to the path. */
876   struct prefix_list *next;   /* Next in linked list. */
877   int require_machine_suffix; /* Don't use without machine_suffix.  */
878   /* 2 means try both machine_suffix and just_machine_suffix.  */
879   int *used_flag_ptr;         /* 1 if a file was found with this prefix.  */
880 };
881
882 struct path_prefix
883 {
884   struct prefix_list *plist;  /* List of prefixes to try */
885   int max_len;                /* Max length of a prefix in PLIST */
886   char *name;                 /* Name of this list (used in config stuff) */
887 };
888
889 /* List of prefixes to try when looking for executables. */
890
891 static struct path_prefix exec_prefix = { 0, 0, "exec" };
892
893 /* List of prefixes to try when looking for startup (crt0) files. */
894
895 static struct path_prefix startfile_prefix = { 0, 0, "startfile" };
896
897 /* List of prefixes to try when looking for libraries. */
898
899 static struct path_prefix library_prefix = { 0, 0, "libraryfile" };
900
901 /* Suffix to attach to directories searched for commands.
902    This looks like `MACHINE/VERSION/'.  */
903
904 static char *machine_suffix = 0;
905
906 /* Suffix to attach to directories searched for commands.
907    This is just `MACHINE/'.  */
908
909 static char *just_machine_suffix = 0;
910
911 /* Adjusted value of GCC_EXEC_PREFIX envvar.  */
912
913 static char *gcc_exec_prefix;
914
915 /* Default prefixes to attach to command names.  */
916
917 #ifdef CROSS_COMPILE  /* Don't use these prefixes for a cross compiler.  */
918 #undef MD_EXEC_PREFIX
919 #undef MD_STARTFILE_PREFIX
920 #undef MD_STARTFILE_PREFIX_1
921 #endif
922
923 #ifndef STANDARD_EXEC_PREFIX
924 #define STANDARD_EXEC_PREFIX "/usr/local/lib/gcc-lib/"
925 #endif /* !defined STANDARD_EXEC_PREFIX */
926
927 static char *standard_exec_prefix = STANDARD_EXEC_PREFIX;
928 static char *standard_exec_prefix_1 = "/usr/lib/gcc/";
929 #ifdef MD_EXEC_PREFIX
930 static char *md_exec_prefix = MD_EXEC_PREFIX;
931 #endif
932
933 #ifndef STANDARD_STARTFILE_PREFIX
934 #define STANDARD_STARTFILE_PREFIX "/usr/local/lib/"
935 #endif /* !defined STANDARD_STARTFILE_PREFIX */
936
937 #ifdef MD_STARTFILE_PREFIX
938 static char *md_startfile_prefix = MD_STARTFILE_PREFIX;
939 #endif
940 #ifdef MD_STARTFILE_PREFIX_1
941 static char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
942 #endif
943 static char *standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
944 static char *standard_startfile_prefix_1 = "/lib/";
945 static char *standard_startfile_prefix_2 = "/usr/lib/";
946
947 #ifndef TOOLDIR_BASE_PREFIX
948 #define TOOLDIR_BASE_PREFIX "/usr/local/"
949 #endif
950 static char *tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
951 static char *tooldir_prefix;
952
953 /* Clear out the vector of arguments (after a command is executed).  */
954
955 static void
956 clear_args ()
957 {
958   argbuf_index = 0;
959 }
960
961 /* Add one argument to the vector at the end.
962    This is done when a space is seen or at the end of the line.
963    If DELETE_ALWAYS is nonzero, the arg is a filename
964     and the file should be deleted eventually.
965    If DELETE_FAILURE is nonzero, the arg is a filename
966     and the file should be deleted if this compilation fails.  */
967
968 static void
969 store_arg (arg, delete_always, delete_failure)
970      char *arg;
971      int delete_always, delete_failure;
972 {
973   if (argbuf_index + 1 == argbuf_length)
974     {
975       argbuf = (char **) xrealloc (argbuf, (argbuf_length *= 2) * sizeof (char *));
976     }
977
978   argbuf[argbuf_index++] = arg;
979   argbuf[argbuf_index] = 0;
980
981   if (delete_always || delete_failure)
982     record_temp_file (arg, delete_always, delete_failure);
983 }
984 \f
985 /* Record the names of temporary files we tell compilers to write,
986    and delete them at the end of the run.  */
987
988 /* This is the common prefix we use to make temp file names.
989    It is chosen once for each run of this program.
990    It is substituted into a spec by %g.
991    Thus, all temp file names contain this prefix.
992    In practice, all temp file names start with this prefix.
993
994    This prefix comes from the envvar TMPDIR if it is defined;
995    otherwise, from the P_tmpdir macro if that is defined;
996    otherwise, in /usr/tmp or /tmp.  */
997
998 static char *temp_filename;
999
1000 /* Length of the prefix.  */
1001
1002 static int temp_filename_length;
1003
1004 /* Define the list of temporary files to delete.  */
1005
1006 struct temp_file
1007 {
1008   char *name;
1009   struct temp_file *next;
1010 };
1011
1012 /* Queue of files to delete on success or failure of compilation.  */
1013 static struct temp_file *always_delete_queue;
1014 /* Queue of files to delete on failure of compilation.  */
1015 static struct temp_file *failure_delete_queue;
1016
1017 /* Record FILENAME as a file to be deleted automatically.
1018    ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
1019    otherwise delete it in any case.
1020    FAIL_DELETE nonzero means delete it if a compilation step fails;
1021    otherwise delete it in any case.  */
1022
1023 static void
1024 record_temp_file (filename, always_delete, fail_delete)
1025      char *filename;
1026      int always_delete;
1027      int fail_delete;
1028 {
1029   register char *name;
1030   name = xmalloc (strlen (filename) + 1);
1031   strcpy (name, filename);
1032
1033   if (always_delete)
1034     {
1035       register struct temp_file *temp;
1036       for (temp = always_delete_queue; temp; temp = temp->next)
1037         if (! strcmp (name, temp->name))
1038           goto already1;
1039       temp = (struct temp_file *) xmalloc (sizeof (struct temp_file));
1040       temp->next = always_delete_queue;
1041       temp->name = name;
1042       always_delete_queue = temp;
1043     already1:;
1044     }
1045
1046   if (fail_delete)
1047     {
1048       register struct temp_file *temp;
1049       for (temp = failure_delete_queue; temp; temp = temp->next)
1050         if (! strcmp (name, temp->name))
1051           goto already2;
1052       temp = (struct temp_file *) xmalloc (sizeof (struct temp_file));
1053       temp->next = failure_delete_queue;
1054       temp->name = name;
1055       failure_delete_queue = temp;
1056     already2:;
1057     }
1058 }
1059
1060 /* Delete all the temporary files whose names we previously recorded.  */
1061
1062 static void
1063 delete_temp_files ()
1064 {
1065   register struct temp_file *temp;
1066
1067   for (temp = always_delete_queue; temp; temp = temp->next)
1068     {
1069 #ifdef DEBUG
1070       int i;
1071       printf ("Delete %s? (y or n) ", temp->name);
1072       fflush (stdout);
1073       i = getchar ();
1074       if (i != '\n')
1075         while (getchar () != '\n') ;
1076       if (i == 'y' || i == 'Y')
1077 #endif /* DEBUG */
1078         {
1079           struct stat st;
1080           if (stat (temp->name, &st) >= 0)
1081             {
1082               /* Delete only ordinary files.  */
1083               if (S_ISREG (st.st_mode))
1084                 if (unlink (temp->name) < 0)
1085                   if (verbose_flag)
1086                     perror_with_name (temp->name);
1087             }
1088         }
1089     }
1090
1091   always_delete_queue = 0;
1092 }
1093
1094 /* Delete all the files to be deleted on error.  */
1095
1096 static void
1097 delete_failure_queue ()
1098 {
1099   register struct temp_file *temp;
1100
1101   for (temp = failure_delete_queue; temp; temp = temp->next)
1102     {
1103 #ifdef DEBUG
1104       int i;
1105       printf ("Delete %s? (y or n) ", temp->name);
1106       fflush (stdout);
1107       i = getchar ();
1108       if (i != '\n')
1109         while (getchar () != '\n') ;
1110       if (i == 'y' || i == 'Y')
1111 #endif /* DEBUG */
1112         {
1113           if (unlink (temp->name) < 0)
1114             if (verbose_flag)
1115               perror_with_name (temp->name);
1116         }
1117     }
1118 }
1119
1120 static void
1121 clear_failure_queue ()
1122 {
1123   failure_delete_queue = 0;
1124 }
1125
1126 /* Compute a string to use as the base of all temporary file names.
1127    It is substituted for %g.  */
1128
1129 static void
1130 choose_temp_base ()
1131 {
1132   char *base = getenv ("TMPDIR");
1133   int len;
1134
1135   if (base == (char *)0)
1136     {
1137 #ifdef P_tmpdir
1138       if (access (P_tmpdir, R_OK | W_OK) == 0)
1139         base = P_tmpdir;
1140 #endif
1141       if (base == (char *)0)
1142         {
1143           if (access ("/usr/tmp", R_OK | W_OK) == 0)
1144             base = "/usr/tmp/";
1145           else
1146             base = "/tmp/";
1147         }
1148     }
1149
1150   len = strlen (base);
1151   temp_filename = xmalloc (len + sizeof("/ccXXXXXX"));
1152   strcpy (temp_filename, base);
1153   if (len > 0 && temp_filename[len-1] != '/')
1154     temp_filename[len++] = '/';
1155   strcpy (temp_filename + len, "ccXXXXXX");
1156
1157   mktemp (temp_filename);
1158   temp_filename_length = strlen (temp_filename);
1159   if (temp_filename_length == 0)
1160     abort ();
1161 }
1162 \f
1163
1164 /* Routine to add variables to the environment.  We do this to pass
1165    the pathname of the gcc driver, and the directories search to the
1166    collect2 program, which is being run as ld.  This way, we can be
1167    sure of executing the right compiler when collect2 wants to build
1168    constructors and destructors.  Since the environment variables we
1169    use come from an obstack, we don't have to worry about allocating
1170    space for them.  */
1171
1172 #ifndef HAVE_PUTENV
1173
1174 putenv (str)
1175      char *str;
1176 {
1177 #ifndef VMS                     /* nor about VMS */
1178
1179   extern char **environ;
1180   char **old_environ = environ;
1181   char **envp;
1182   int num_envs = 0;
1183   int name_len = 1;
1184   int str_len = strlen (str);
1185   char *p = str;
1186   int ch;
1187
1188   while ((ch = *p++) != '\0' && ch != '=')
1189     name_len++;
1190
1191   if (!ch)
1192     abort ();
1193
1194   /* Search for replacing an existing environment variable, and
1195      count the number of total environment variables.  */
1196   for (envp = old_environ; *envp; envp++)
1197     {
1198       num_envs++;
1199       if (!strncmp (str, *envp, name_len))
1200         {
1201           *envp = str;
1202           return;
1203         }
1204     }
1205
1206   /* Add a new environment variable */
1207   environ = (char **) xmalloc (sizeof (char *) * (num_envs+2));
1208   *environ = str;
1209   bcopy (old_environ, environ+1, sizeof (char *) * (num_envs+1));
1210
1211 #endif  /* VMS */
1212 }
1213
1214 #endif  /* HAVE_PUTENV */
1215
1216 \f
1217 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables for collect.  */
1218
1219 static void
1220 putenv_from_prefixes (paths, env_var)
1221      struct path_prefix *paths;
1222      char *env_var;
1223 {
1224   int suffix_len = (machine_suffix) ? strlen (machine_suffix) : 0;
1225   int just_suffix_len
1226     = (just_machine_suffix) ? strlen (just_machine_suffix) : 0;
1227   int first_time = TRUE;
1228   struct prefix_list *pprefix;
1229
1230   obstack_grow (&collect_obstack, env_var, strlen (env_var));
1231
1232   for (pprefix = paths->plist; pprefix != 0; pprefix = pprefix->next)
1233     {
1234       int len = strlen (pprefix->prefix);
1235
1236       if (machine_suffix)
1237         {
1238           if (!first_time)
1239             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1240             
1241           first_time = FALSE;
1242           obstack_grow (&collect_obstack, pprefix->prefix, len);
1243           obstack_grow (&collect_obstack, machine_suffix, suffix_len);
1244         }
1245
1246       if (just_machine_suffix && pprefix->require_machine_suffix == 2)
1247         {
1248           if (!first_time)
1249             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1250             
1251           first_time = FALSE;
1252           obstack_grow (&collect_obstack, pprefix->prefix, len);
1253           obstack_grow (&collect_obstack, just_machine_suffix,
1254                         just_suffix_len);
1255         }
1256
1257       if (!pprefix->require_machine_suffix)
1258         {
1259           if (!first_time)
1260             obstack_1grow (&collect_obstack, PATH_SEPARATOR);
1261
1262           first_time = FALSE;
1263           obstack_grow (&collect_obstack, pprefix->prefix, len);
1264         }
1265     }
1266   obstack_1grow (&collect_obstack, '\0');
1267   putenv (obstack_finish (&collect_obstack));
1268 }
1269
1270 \f
1271 /* Search for NAME using the prefix list PREFIXES.  MODE is passed to
1272    access to check permissions.
1273    Return 0 if not found, otherwise return its name, allocated with malloc. */
1274
1275 static char *
1276 find_a_file (pprefix, name, mode)
1277      struct path_prefix *pprefix;
1278      char *name;
1279      int mode;
1280 {
1281   char *temp;
1282   char *file_suffix = ((mode & X_OK) != 0 ? EXECUTABLE_SUFFIX : "");
1283   struct prefix_list *pl;
1284   int len = pprefix->max_len + strlen (name) + strlen (file_suffix) + 1;
1285
1286   if (machine_suffix)
1287     len += strlen (machine_suffix);
1288
1289   temp = xmalloc (len);
1290
1291   /* Determine the filename to execute (special case for absolute paths).  */
1292
1293   if (*name == '/')
1294     {
1295       if (access (name, mode))
1296         {
1297           strcpy (temp, name);
1298           return temp;
1299         }
1300     }
1301   else
1302     for (pl = pprefix->plist; pl; pl = pl->next)
1303       {
1304         if (machine_suffix)
1305           {
1306             strcpy (temp, pl->prefix);
1307             strcat (temp, machine_suffix);
1308             strcat (temp, name);
1309             if (access (temp, mode) == 0)
1310               {
1311                 if (pl->used_flag_ptr != 0)
1312                   *pl->used_flag_ptr = 1;
1313                 return temp;
1314               }
1315             /* Some systems have a suffix for executable files.
1316                So try appending that.  */
1317             if (file_suffix[0] != 0)
1318               {
1319                 strcat (temp, file_suffix);
1320                 if (access (temp, mode) == 0)
1321                   {
1322                     if (pl->used_flag_ptr != 0)
1323                       *pl->used_flag_ptr = 1;
1324                     return temp;
1325                   }
1326               }
1327           }
1328         /* Certain prefixes are tried with just the machine type,
1329            not the version.  This is used for finding as, ld, etc.  */
1330         if (just_machine_suffix && pl->require_machine_suffix == 2)
1331           {
1332             strcpy (temp, pl->prefix);
1333             strcat (temp, just_machine_suffix);
1334             strcat (temp, name);
1335             if (access (temp, mode) == 0)
1336               {
1337                 if (pl->used_flag_ptr != 0)
1338                   *pl->used_flag_ptr = 1;
1339                 return temp;
1340               }
1341             /* Some systems have a suffix for executable files.
1342                So try appending that.  */
1343             if (file_suffix[0] != 0)
1344               {
1345                 strcat (temp, file_suffix);
1346                 if (access (temp, mode) == 0)
1347                   {
1348                     if (pl->used_flag_ptr != 0)
1349                       *pl->used_flag_ptr = 1;
1350                     return temp;
1351                   }
1352               }
1353           }
1354         /* Certain prefixes can't be used without the machine suffix
1355            when the machine or version is explicitly specified.  */
1356         if (!pl->require_machine_suffix)
1357           {
1358             strcpy (temp, pl->prefix);
1359             strcat (temp, name);
1360             if (access (temp, mode) == 0)
1361               {
1362                 if (pl->used_flag_ptr != 0)
1363                   *pl->used_flag_ptr = 1;
1364                 return temp;
1365               }
1366             /* Some systems have a suffix for executable files.
1367                So try appending that.  */
1368             if (file_suffix[0] != 0)
1369               {
1370                 strcat (temp, file_suffix);
1371                 if (access (temp, mode) == 0)
1372                   {
1373                     if (pl->used_flag_ptr != 0)
1374                       *pl->used_flag_ptr = 1;
1375                     return temp;
1376                   }
1377               }
1378           }
1379       }
1380
1381   free (temp);
1382   return 0;
1383 }
1384
1385 /* Add an entry for PREFIX in PLIST.  If FIRST is set, it goes
1386    at the start of the list, otherwise it goes at the end.
1387
1388    If WARN is nonzero, we will warn if no file is found
1389    through this prefix.  WARN should point to an int
1390    which will be set to 1 if this entry is used.
1391
1392    REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
1393    the complete value of machine_suffix.
1394    2 means try both machine_suffix and just_machine_suffix.  */
1395
1396 static void
1397 add_prefix (pprefix, prefix, first, require_machine_suffix, warn)
1398      struct path_prefix *pprefix;
1399      char *prefix;
1400      int first;
1401      int require_machine_suffix;
1402      int *warn;
1403 {
1404   struct prefix_list *pl, **prev;
1405   int len;
1406
1407   if (!first && pprefix->plist)
1408     {
1409       for (pl = pprefix->plist; pl->next; pl = pl->next)
1410         ;
1411       prev = &pl->next;
1412     }
1413   else
1414     prev = &pprefix->plist;
1415
1416   /* Keep track of the longest prefix */
1417
1418   len = strlen (prefix);
1419   if (len > pprefix->max_len)
1420     pprefix->max_len = len;
1421
1422   pl = (struct prefix_list *) xmalloc (sizeof (struct prefix_list));
1423   pl->prefix = save_string (prefix, len);
1424   pl->require_machine_suffix = require_machine_suffix;
1425   pl->used_flag_ptr = warn;
1426   if (warn)
1427     *warn = 0;
1428
1429   if (*prev)
1430     pl->next = *prev;
1431   else
1432     pl->next = (struct prefix_list *) 0;
1433   *prev = pl;
1434 }
1435
1436 /* Print warnings for any prefixes in the list PPREFIX that were not used.  */
1437
1438 static void
1439 unused_prefix_warnings (pprefix)
1440      struct path_prefix *pprefix;
1441 {
1442   struct prefix_list *pl = pprefix->plist;
1443
1444   while (pl)
1445     {
1446       if (pl->used_flag_ptr != 0 && !*pl->used_flag_ptr)
1447         {
1448           error ("file path prefix `%s' never used",
1449                  pl->prefix);
1450           /* Prevent duplicate warnings.  */
1451           *pl->used_flag_ptr = 1;
1452         }
1453       pl = pl->next;
1454     }
1455 }
1456
1457 /* Get rid of all prefixes built up so far in *PLISTP. */
1458
1459 static void
1460 free_path_prefix (pprefix)
1461      struct path_prefix *pprefix;
1462 {
1463   struct prefix_list *pl = pprefix->plist;
1464   struct prefix_list *temp;
1465
1466   while (pl)
1467     {
1468       temp = pl;
1469       pl = pl->next;
1470       free (temp->prefix);
1471       free ((char *) temp);
1472     }
1473   pprefix->plist = (struct prefix_list *) 0;
1474 }
1475 \f
1476 /* stdin file number.  */
1477 #define STDIN_FILE_NO 0
1478
1479 /* stdout file number.  */
1480 #define STDOUT_FILE_NO 1
1481
1482 /* value of `pipe': port index for reading.  */
1483 #define READ_PORT 0
1484
1485 /* value of `pipe': port index for writing.  */
1486 #define WRITE_PORT 1
1487
1488 /* Pipe waiting from last process, to be used as input for the next one.
1489    Value is STDIN_FILE_NO if no pipe is waiting
1490    (i.e. the next command is the first of a group).  */
1491
1492 static int last_pipe_input;
1493
1494 /* Fork one piped subcommand.  FUNC is the system call to use
1495    (either execv or execvp).  ARGV is the arg vector to use.
1496    NOT_LAST is nonzero if this is not the last subcommand
1497    (i.e. its output should be piped to the next one.)  */
1498
1499 #ifndef OS2
1500 #ifdef __MSDOS__
1501
1502 /* Declare these to avoid compilation error.  They won't be called.  */
1503 int execv(const char *a, const char **b){}
1504 int execvp(const char *a, const char **b){}
1505
1506 static int
1507 pexecute (search_flag, program, argv, not_last)
1508      int search_flag;
1509      char *program;
1510      char *argv[];
1511      int not_last;
1512 {
1513   char *scmd;
1514   FILE *argfile;
1515   int i;
1516
1517   scmd = (char *)malloc (strlen (program) + strlen (temp_filename) + 6);
1518   sprintf (scmd, "%s @%s.gp", program, temp_filename);
1519   argfile = fopen (scmd+strlen (program) + 2, "w");
1520   if (argfile == 0)
1521     pfatal_with_name (scmd + strlen (program) + 2);
1522
1523   for (i=1; argv[i]; i++)
1524   {
1525     char *cp;
1526     for (cp = argv[i]; *cp; cp++)
1527       {
1528         if (*cp == '"' || *cp == '\'' || *cp == '\\' || isspace (*cp))
1529           fputc ('\\', argfile);
1530         fputc (*cp, argfile);
1531       }
1532     fputc ('\n', argfile);
1533   }
1534   fclose (argfile);
1535
1536   i = system (scmd);
1537
1538   remove (scmd + strlen (program) + 2);
1539   return i << 8;
1540 }
1541
1542 #else /* not __MSDOS__ */
1543
1544 static int
1545 pexecute (search_flag, program, argv, not_last)
1546      int search_flag;
1547      char *program;
1548      char *argv[];
1549      int not_last;
1550 {
1551   int (*func)() = (search_flag ? execv : execvp);
1552   int pid;
1553   int pdes[2];
1554   int input_desc = last_pipe_input;
1555   int output_desc = STDOUT_FILE_NO;
1556   int retries, sleep_interval;
1557
1558   /* If this isn't the last process, make a pipe for its output,
1559      and record it as waiting to be the input to the next process.  */
1560
1561   if (not_last)
1562     {
1563       if (pipe (pdes) < 0)
1564         pfatal_with_name ("pipe");
1565       output_desc = pdes[WRITE_PORT];
1566       last_pipe_input = pdes[READ_PORT];
1567     }
1568   else
1569     last_pipe_input = STDIN_FILE_NO;
1570
1571   /* Fork a subprocess; wait and retry if it fails.  */
1572   sleep_interval = 1;
1573   for (retries = 0; retries < 4; retries++)
1574     {
1575       pid = vfork ();
1576       if (pid >= 0)
1577         break;
1578       sleep (sleep_interval);
1579       sleep_interval *= 2;
1580     }
1581
1582   switch (pid)
1583     {
1584     case -1:
1585 #ifdef vfork
1586       pfatal_with_name ("fork");
1587 #else
1588       pfatal_with_name ("vfork");
1589 #endif
1590       /* NOTREACHED */
1591       return 0;
1592
1593     case 0: /* child */
1594       /* Move the input and output pipes into place, if nec.  */
1595       if (input_desc != STDIN_FILE_NO)
1596         {
1597           close (STDIN_FILE_NO);
1598           dup (input_desc);
1599           close (input_desc);
1600         }
1601       if (output_desc != STDOUT_FILE_NO)
1602         {
1603           close (STDOUT_FILE_NO);
1604           dup (output_desc);
1605           close (output_desc);
1606         }
1607
1608       /* Close the parent's descs that aren't wanted here.  */
1609       if (last_pipe_input != STDIN_FILE_NO)
1610         close (last_pipe_input);
1611
1612       /* Exec the program.  */
1613       (*func) (program, argv);
1614       perror_exec (program);
1615       exit (-1);
1616       /* NOTREACHED */
1617       return 0;
1618
1619     default:
1620       /* In the parent, after forking.
1621          Close the descriptors that we made for this child.  */
1622       if (input_desc != STDIN_FILE_NO)
1623         close (input_desc);
1624       if (output_desc != STDOUT_FILE_NO)
1625         close (output_desc);
1626
1627       /* Return child's process number.  */
1628       return pid;
1629     }
1630 }
1631
1632 #endif /* not __MSDOS__ */
1633 #else /* not OS2 */
1634
1635 static int
1636 pexecute (search_flag, program, argv, not_last)
1637      int search_flag;
1638      char *program;
1639      char *argv[];
1640      int not_last;
1641 {
1642   return (search_flag ? spawnv : spawnvp) (1, program, argv);
1643 }
1644 #endif /* not OS2 */
1645 \f
1646 /* Execute the command specified by the arguments on the current line of spec.
1647    When using pipes, this includes several piped-together commands
1648    with `|' between them.
1649
1650    Return 0 if successful, -1 if failed.  */
1651
1652 static int
1653 execute ()
1654 {
1655   int i;
1656   int n_commands;               /* # of command.  */
1657   char *string;
1658   struct command
1659     {
1660       char *prog;               /* program name.  */
1661       char **argv;              /* vector of args.  */
1662       int pid;                  /* pid of process for this command.  */
1663     };
1664
1665   struct command *commands;     /* each command buffer with above info.  */
1666
1667   /* Count # of piped commands.  */
1668   for (n_commands = 1, i = 0; i < argbuf_index; i++)
1669     if (strcmp (argbuf[i], "|") == 0)
1670       n_commands++;
1671
1672   /* Get storage for each command.  */
1673   commands
1674     = (struct command *) alloca (n_commands * sizeof (struct command));
1675
1676   /* Split argbuf into its separate piped processes,
1677      and record info about each one.
1678      Also search for the programs that are to be run.  */
1679
1680   commands[0].prog = argbuf[0]; /* first command.  */
1681   commands[0].argv = &argbuf[0];
1682   string = find_a_file (&exec_prefix, commands[0].prog, X_OK);
1683   if (string)
1684     commands[0].argv[0] = string;
1685
1686   for (n_commands = 1, i = 0; i < argbuf_index; i++)
1687     if (strcmp (argbuf[i], "|") == 0)
1688       {                         /* each command.  */
1689 #ifdef __MSDOS__
1690         fatal ("-pipe not supported under MS-DOS");
1691 #endif
1692         argbuf[i] = 0;  /* termination of command args.  */
1693         commands[n_commands].prog = argbuf[i + 1];
1694         commands[n_commands].argv = &argbuf[i + 1];
1695         string = find_a_file (&exec_prefix, commands[n_commands].prog, X_OK);
1696         if (string)
1697           commands[n_commands].argv[0] = string;
1698         n_commands++;
1699       }
1700
1701   argbuf[argbuf_index] = 0;
1702
1703   /* If -v, print what we are about to do, and maybe query.  */
1704
1705   if (verbose_flag)
1706     {
1707       /* Print each piped command as a separate line.  */
1708       for (i = 0; i < n_commands ; i++)
1709         {
1710           char **j;
1711
1712           for (j = commands[i].argv; *j; j++)
1713             fprintf (stderr, " %s", *j);
1714
1715           /* Print a pipe symbol after all but the last command.  */
1716           if (i + 1 != n_commands)
1717             fprintf (stderr, " |");
1718           fprintf (stderr, "\n");
1719         }
1720       fflush (stderr);
1721 #ifdef DEBUG
1722       fprintf (stderr, "\nGo ahead? (y or n) ");
1723       fflush (stderr);
1724       i = getchar ();
1725       if (i != '\n')
1726         while (getchar () != '\n') ;
1727       if (i != 'y' && i != 'Y')
1728         return 0;
1729 #endif /* DEBUG */
1730     }
1731
1732   /* Run each piped subprocess.  */
1733
1734   last_pipe_input = STDIN_FILE_NO;
1735   for (i = 0; i < n_commands; i++)
1736     {
1737       char *string = commands[i].argv[0];
1738
1739       commands[i].pid = pexecute (string != commands[i].prog,
1740                                   string, commands[i].argv,
1741                                   i + 1 < n_commands);
1742
1743       if (string != commands[i].prog)
1744         free (string);
1745     }
1746
1747   execution_count++;
1748
1749   /* Wait for all the subprocesses to finish.
1750      We don't care what order they finish in;
1751      we know that N_COMMANDS waits will get them all.  */
1752
1753   {
1754     int ret_code = 0;
1755
1756     for (i = 0; i < n_commands; i++)
1757       {
1758         int status;
1759         int pid;
1760         char *prog;
1761
1762 #ifdef __MSDOS__
1763         status = pid = commands[i].pid;
1764 #else
1765         pid = wait (&status);
1766 #endif
1767         if (pid < 0)
1768           abort ();
1769
1770         if (status != 0)
1771           {
1772             int j;
1773             for (j = 0; j < n_commands; j++)
1774               if (commands[j].pid == pid)
1775                 prog = commands[j].prog;
1776
1777             if ((status & 0x7F) != 0)
1778               {
1779                 fatal ("Internal compiler error: program %s got fatal signal %d",
1780                        prog, (status & 0x7F));
1781                 signal_count++;
1782               }
1783             if (((status & 0xFF00) >> 8) >= MIN_FATAL_STATUS)
1784               ret_code = -1;
1785           }
1786       }
1787     return ret_code;
1788   }
1789 }
1790 \f
1791 /* Find all the switches given to us
1792    and make a vector describing them.
1793    The elements of the vector are strings, one per switch given.
1794    If a switch uses following arguments, then the `part1' field
1795    is the switch itself and the `args' field
1796    is a null-terminated vector containing the following arguments.
1797    The `valid' field is nonzero if any spec has looked at this switch;
1798    if it remains zero at the end of the run, it must be meaningless.  */
1799
1800 struct switchstr
1801 {
1802   char *part1;
1803   char **args;
1804   int valid;
1805 };
1806
1807 static struct switchstr *switches;
1808
1809 static int n_switches;
1810
1811 struct infile
1812 {
1813   char *name;
1814   char *language;
1815 };
1816
1817 /* Also a vector of input files specified.  */
1818
1819 static struct infile *infiles;
1820
1821 static int n_infiles;
1822
1823 /* And a vector of corresponding output files is made up later.  */
1824
1825 static char **outfiles;
1826
1827 /* Create the vector `switches' and its contents.
1828    Store its length in `n_switches'.  */
1829
1830 static void
1831 process_command (argc, argv)
1832      int argc;
1833      char **argv;
1834 {
1835   register int i;
1836   char *temp;
1837   char *spec_lang = 0;
1838   int last_language_n_infiles;
1839
1840   gcc_exec_prefix = getenv ("GCC_EXEC_PREFIX");
1841
1842   n_switches = 0;
1843   n_infiles = 0;
1844
1845   /* Default for -V is our version number, ending at first space.  */
1846   spec_version = save_string (version_string, strlen (version_string));
1847   for (temp = spec_version; *temp && *temp != ' '; temp++);
1848   if (*temp) *temp = '\0';
1849
1850   /* Set up the default search paths.  */
1851
1852   if (gcc_exec_prefix)
1853     {
1854       add_prefix (&exec_prefix, gcc_exec_prefix, 0, 0, NULL_PTR);
1855       add_prefix (&startfile_prefix, gcc_exec_prefix, 0, 0, NULL_PTR);
1856     }
1857
1858   /* COMPILER_PATH and LIBRARY_PATH have values
1859      that are lists of directory names with colons.  */
1860
1861   temp = getenv ("COMPILER_PATH");
1862   if (temp)
1863     {
1864       char *startp, *endp;
1865       char *nstore = (char *) alloca (strlen (temp) + 3);
1866
1867       startp = endp = temp;
1868       while (1)
1869         {
1870           if (*endp == PATH_SEPARATOR || *endp == 0)
1871             {
1872               strncpy (nstore, startp, endp-startp);
1873               if (endp == startp)
1874                 {
1875                   strcpy (nstore, "./");
1876                 }
1877               else if (endp[-1] != '/')
1878                 {
1879                   nstore[endp-startp] = '/';
1880                   nstore[endp-startp+1] = 0;
1881                 }
1882               else
1883                 nstore[endp-startp] = 0;
1884               add_prefix (&exec_prefix, nstore, 0, 0, NULL_PTR);
1885               if (*endp == 0)
1886                 break;
1887               endp = startp = endp + 1;
1888             }
1889           else
1890             endp++;
1891         }
1892     }
1893
1894   temp = getenv ("LIBRARY_PATH");
1895   if (temp)
1896     {
1897       char *startp, *endp;
1898       char *nstore = (char *) alloca (strlen (temp) + 3);
1899
1900       startp = endp = temp;
1901       while (1)
1902         {
1903           if (*endp == PATH_SEPARATOR || *endp == 0)
1904             {
1905               strncpy (nstore, startp, endp-startp);
1906               if (endp == startp)
1907                 {
1908                   strcpy (nstore, "./");
1909                 }
1910               else if (endp[-1] != '/')
1911                 {
1912                   nstore[endp-startp] = '/';
1913                   nstore[endp-startp+1] = 0;
1914                 }
1915               else
1916                 nstore[endp-startp] = 0;
1917               add_prefix (&startfile_prefix, nstore, 0, 0, NULL_PTR);
1918               /* Make separate list of dirs that came from LIBRARY_PATH.  */
1919               add_prefix (&library_prefix, nstore, 0, 0, NULL_PTR);
1920               if (*endp == 0)
1921                 break;
1922               endp = startp = endp + 1;
1923             }
1924           else
1925             endp++;
1926         }
1927     }
1928
1929   /* Use LPATH like LIBRARY_PATH (for the CMU build program).  */
1930   temp = getenv ("LPATH");
1931   if (temp)
1932     {
1933       char *startp, *endp;
1934       char *nstore = (char *) alloca (strlen (temp) + 3);
1935
1936       startp = endp = temp;
1937       while (1)
1938         {
1939           if (*endp == PATH_SEPARATOR || *endp == 0)
1940             {
1941               strncpy (nstore, startp, endp-startp);
1942               if (endp == startp)
1943                 {
1944                   strcpy (nstore, "./");
1945                 }
1946               else if (endp[-1] != '/')
1947                 {
1948                   nstore[endp-startp] = '/';
1949                   nstore[endp-startp+1] = 0;
1950                 }
1951               else
1952                 nstore[endp-startp] = 0;
1953               add_prefix (&startfile_prefix, nstore, 0, 0, NULL_PTR);
1954               /* Make separate list of dirs that came from LIBRARY_PATH.  */
1955               add_prefix (&library_prefix, nstore, 0, 0, NULL_PTR);
1956               if (*endp == 0)
1957                 break;
1958               endp = startp = endp + 1;
1959             }
1960           else
1961             endp++;
1962         }
1963     }
1964
1965   /* Scan argv twice.  Here, the first time, just count how many switches
1966      there will be in their vector, and how many input files in theirs.
1967      Here we also parse the switches that cc itself uses (e.g. -v).  */
1968
1969   for (i = 1; i < argc; i++)
1970     {
1971       if (! strcmp (argv[i], "-dumpspecs"))
1972         {
1973           printf ("*asm:\n%s\n\n", asm_spec);
1974           printf ("*asm_final:\n%s\n\n", asm_final_spec);
1975           printf ("*cpp:\n%s\n\n", cpp_spec);
1976           printf ("*cc1:\n%s\n\n", cc1_spec);
1977           printf ("*cc1plus:\n%s\n\n", cc1plus_spec);
1978           printf ("*endfile:\n%s\n\n", endfile_spec);
1979           printf ("*link:\n%s\n\n", link_spec);
1980           printf ("*lib:\n%s\n\n", lib_spec);
1981           printf ("*startfile:\n%s\n\n", startfile_spec);
1982           printf ("*switches_need_spaces:\n%s\n\n", switches_need_spaces);
1983           printf ("*signed_char:\n%s\n\n", signed_char_spec);
1984           printf ("*predefines:\n%s\n\n", cpp_predefines);
1985           printf ("*cross_compile:\n%d\n\n", cross_compile);
1986
1987           exit (0);
1988         }
1989       else if (! strcmp (argv[i], "-dumpversion"))
1990         {
1991           printf ("%s\n", version_string);
1992           exit (0);
1993         }
1994       else if (! strcmp (argv[i], "-print-libgcc-file-name"))
1995         {
1996           print_libgcc_file_name = 1;
1997         }
1998       else if (! strcmp (argv[i], "-Xlinker"))
1999         {
2000           /* Pass the argument of this option to the linker when we link.  */
2001
2002           if (i + 1 == argc)
2003             fatal ("argument to `-Xlinker' is missing");
2004
2005           n_linker_options++;
2006           if (!linker_options)
2007             linker_options
2008               = (char **) xmalloc (n_linker_options * sizeof (char **));
2009           else
2010             linker_options
2011               = (char **) xrealloc (linker_options,
2012                                     n_linker_options * sizeof (char **));
2013
2014           linker_options[n_linker_options - 1] = argv[++i];
2015         }
2016       else if (! strncmp (argv[i], "-Wl,", 4))
2017         {
2018           int prev, j;
2019           /* Pass the rest of this option to the linker when we link.  */
2020
2021           n_linker_options++;
2022           if (!linker_options)
2023             linker_options
2024               = (char **) xmalloc (n_linker_options * sizeof (char **));
2025           else
2026             linker_options
2027               = (char **) xrealloc (linker_options,
2028                                     n_linker_options * sizeof (char **));
2029
2030           /* Split the argument at commas.  */
2031           prev = 4;
2032           for (j = 4; argv[i][j]; j++)
2033             if (argv[i][j] == ',')
2034               {
2035                 linker_options[n_linker_options - 1]
2036                   = save_string (argv[i] + prev, j - prev);
2037                 n_linker_options++;
2038                 linker_options
2039                   = (char **) xrealloc (linker_options,
2040                                         n_linker_options * sizeof (char **));
2041                 prev = j + 1;
2042               }
2043           /* Record the part after the last comma.  */
2044           linker_options[n_linker_options - 1] = argv[i] + prev;
2045         }
2046       else if (! strncmp (argv[i], "-Wa,", 4))
2047         {
2048           int prev, j;
2049           /* Pass the rest of this option to the assembler.  */
2050
2051           n_assembler_options++;
2052           if (!assembler_options)
2053             assembler_options
2054               = (char **) xmalloc (n_assembler_options * sizeof (char **));
2055           else
2056             assembler_options
2057               = (char **) xrealloc (assembler_options,
2058                                     n_assembler_options * sizeof (char **));
2059
2060           /* Split the argument at commas.  */
2061           prev = 4;
2062           for (j = 4; argv[i][j]; j++)
2063             if (argv[i][j] == ',')
2064               {
2065                 assembler_options[n_assembler_options - 1]
2066                   = save_string (argv[i] + prev, j - prev);
2067                 n_assembler_options++;
2068                 assembler_options
2069                   = (char **) xrealloc (assembler_options,
2070                                         n_assembler_options * sizeof (char **));
2071                 prev = j + 1;
2072               }
2073           /* Record the part after the last comma.  */
2074           assembler_options[n_assembler_options - 1] = argv[i] + prev;
2075         }
2076       else if (argv[i][0] == '+' && argv[i][1] == 'e')
2077         /* Compensate for the +e options to the C++ front-end.  */
2078         n_switches++;
2079       else if (argv[i][0] == '-' && argv[i][1] != 0 && argv[i][1] != 'l')
2080         {
2081           register char *p = &argv[i][1];
2082           register int c = *p;
2083
2084           switch (c)
2085             {
2086             case 'b':
2087               if (p[1] == 0 && i + 1 == argc)
2088                 fatal ("argument to `-b' is missing");
2089               if (p[1] == 0)
2090                 spec_machine = argv[++i];
2091               else
2092                 spec_machine = p + 1;
2093               break;
2094
2095             case 'B':
2096               {
2097                 int *temp = (int *) xmalloc (sizeof (int));
2098                 char *value;
2099                 if (p[1] == 0 && i + 1 == argc)
2100                   fatal ("argument to `-B' is missing");
2101                 if (p[1] == 0)
2102                   value = argv[++i];
2103                 else
2104                   value = p + 1;
2105                 add_prefix (&exec_prefix, value, 1, 0, temp);
2106                 add_prefix (&startfile_prefix, value, 1, 0, temp);
2107               }
2108               break;
2109
2110             case 'v':   /* Print our subcommands and print versions.  */
2111               n_switches++;
2112               /* If they do anything other than exactly `-v', don't set
2113                  verbose_flag; rather, continue on to give the error.  */
2114               if (p[1] != 0)
2115                 break;
2116               verbose_flag++;
2117               break;
2118
2119             case 'V':
2120               if (p[1] == 0 && i + 1 == argc)
2121                 fatal ("argument to `-V' is missing");
2122               if (p[1] == 0)
2123                 spec_version = argv[++i];
2124               else
2125                 spec_version = p + 1;
2126               break;
2127
2128             case 's':
2129               if (!strcmp (p, "save-temps"))
2130                 {
2131                   save_temps_flag = 1;
2132                   n_switches++;
2133                   break;
2134                 }
2135             default:
2136               n_switches++;
2137
2138               if (SWITCH_TAKES_ARG (c) > (p[1] != 0))
2139                 i += SWITCH_TAKES_ARG (c) - (p[1] != 0);
2140               else if (WORD_SWITCH_TAKES_ARG (p))
2141                 i += WORD_SWITCH_TAKES_ARG (p);
2142             }
2143         }
2144       else
2145         n_infiles++;
2146     }
2147
2148   tooldir_prefix = concat (tooldir_base_prefix, spec_machine, "/");
2149
2150   /* If tooldir is relative, base it on exec_prefix.  A relative
2151      tooldir lets us move the installed tree as a unit.  */
2152
2153   if (*tooldir_prefix != '/')
2154     {
2155       if (gcc_exec_prefix)
2156         tooldir_prefix = concat (concat (gcc_exec_prefix, spec_machine, "/"),
2157                                  concat (spec_version, "/", tooldir_prefix),
2158                                  "");
2159       else
2160         tooldir_prefix = concat (concat (standard_exec_prefix, spec_machine, "/"),
2161                                  concat (spec_version, "/", tooldir_prefix),
2162                                  "");
2163     }
2164
2165
2166   /* Set up the search paths before we go looking for config files.  */
2167
2168   /* These come before the md prefixes so that we will find gcc's subcommands
2169      (such as cpp) rather than those of the host system.  */
2170   /* Use 2 as fourth arg meaning try just the machine as a suffix,
2171      as well as trying the machine and the version.  */
2172   add_prefix (&exec_prefix, standard_exec_prefix, 0, 2, NULL_PTR);
2173   add_prefix (&exec_prefix, standard_exec_prefix_1, 0, 2, NULL_PTR);
2174
2175   add_prefix (&startfile_prefix, standard_exec_prefix, 0, 1, NULL_PTR);
2176   add_prefix (&startfile_prefix, standard_exec_prefix_1, 0, 1, NULL_PTR);
2177
2178   add_prefix (&exec_prefix, concat (tooldir_prefix, "bin", "/"),
2179               0, 0, NULL_PTR);
2180   add_prefix (&startfile_prefix, concat (tooldir_prefix, "lib", "/"),
2181               0, 0, NULL_PTR);
2182
2183   /* More prefixes are enabled in main, after we read the specs file
2184      and determine whether this is cross-compilation or not.  */
2185
2186
2187   /* Then create the space for the vectors and scan again.  */
2188
2189   switches = ((struct switchstr *)
2190               xmalloc ((n_switches + 1) * sizeof (struct switchstr)));
2191   infiles = (struct infile *) xmalloc ((n_infiles + 1) * sizeof (struct infile));
2192   n_switches = 0;
2193   n_infiles = 0;
2194   last_language_n_infiles = -1;
2195
2196   /* This, time, copy the text of each switch and store a pointer
2197      to the copy in the vector of switches.
2198      Store all the infiles in their vector.  */
2199
2200   for (i = 1; i < argc; i++)
2201     {
2202       /* Just skip the switches that were handled by the preceding loop.  */
2203       if (!strcmp (argv[i], "-Xlinker"))
2204         i++;
2205       else if (! strncmp (argv[i], "-Wl,", 4))
2206         ;
2207       else if (! strncmp (argv[i], "-Wa,", 4))
2208         ;
2209       else if (! strcmp (argv[i], "-print-libgcc-file-name"))
2210         ;
2211       else if (argv[i][0] == '+' && argv[i][1] == 'e')
2212         {
2213           /* Compensate for the +e options to the C++ front-end;
2214              they're there simply for cfront call-compatibility.  We do
2215              some magic in default_compilers to pass them down properly.
2216              Note we deliberately start at the `+' here, to avoid passing
2217              -e0 or -e1 down into the linker.  */
2218           switches[n_switches].part1 = &argv[i][0];
2219           switches[n_switches].args = 0;
2220           switches[n_switches].valid = 0;
2221           n_switches++;
2222         }
2223       else if (argv[i][0] == '-' && argv[i][1] != 0 && argv[i][1] != 'l')
2224         {
2225           register char *p = &argv[i][1];
2226           register int c = *p;
2227
2228           if (c == 'B' || c == 'b' || c == 'V')
2229             {
2230               /* Skip a separate arg, if any.  */
2231               if (p[1] == 0)
2232                 i++;
2233               continue;
2234             }
2235           if (c == 'x')
2236             {
2237               if (p[1] == 0 && i + 1 == argc)
2238                 fatal ("argument to `-x' is missing");
2239               if (p[1] == 0)
2240                 spec_lang = argv[++i];
2241               else
2242                 spec_lang = p + 1;
2243               if (! strcmp (spec_lang, "none"))
2244                 /* Suppress the warning if -xnone comes after the last input file,
2245                    because alternate command interfaces like g++ might find it
2246                    useful to place -xnone after each input file.  */
2247                 spec_lang = 0;
2248               else
2249                 last_language_n_infiles = n_infiles;
2250               continue;
2251             }
2252           switches[n_switches].part1 = p;
2253           /* Deal with option arguments in separate argv elements.  */
2254           if ((SWITCH_TAKES_ARG (c) > (p[1] != 0))
2255               || WORD_SWITCH_TAKES_ARG (p)) {
2256             int j = 0;
2257             int n_args = WORD_SWITCH_TAKES_ARG (p);
2258
2259             if (n_args == 0) {
2260               /* Count only the option arguments in separate argv elements.  */
2261               n_args = SWITCH_TAKES_ARG (c) - (p[1] != 0);
2262             }
2263             if (i + n_args >= argc)
2264               fatal ("argument to `-%s' is missing", p);
2265             switches[n_switches].args
2266               = (char **) xmalloc ((n_args + 1) * sizeof (char *));
2267             while (j < n_args)
2268               switches[n_switches].args[j++] = argv[++i];
2269             /* Null-terminate the vector.  */
2270             switches[n_switches].args[j] = 0;
2271           } else if (*switches_need_spaces != 0 && (c == 'o' || c == 'L')) {
2272             /* On some systems, ld cannot handle -o or -L without space.
2273                So split the -o or -L from its argument.  */
2274             switches[n_switches].part1 = (c == 'o' ? "o" : "L");
2275             switches[n_switches].args = (char **) xmalloc (2 * sizeof (char *));
2276             switches[n_switches].args[0] = xmalloc (strlen (p));
2277             strcpy (switches[n_switches].args[0], &p[1]);
2278             switches[n_switches].args[1] = 0;
2279           } else
2280             switches[n_switches].args = 0;
2281           switches[n_switches].valid = 0;
2282           /* This is always valid, since gcc.c itself understands it.  */
2283           if (!strcmp (p, "save-temps"))
2284             switches[n_switches].valid = 1;
2285           n_switches++;
2286         }
2287       else
2288         {
2289           if ((argv[i][0] != '-' || argv[i][1] != 'l')
2290               && access (argv[i], R_OK) < 0)
2291             {
2292               perror_with_name (argv[i]);
2293               error_count++;
2294             }
2295           else
2296             {
2297               infiles[n_infiles].language = spec_lang;
2298               infiles[n_infiles++].name = argv[i];
2299             }
2300         }
2301     }
2302
2303   if (n_infiles == last_language_n_infiles)
2304     error ("Warning: `-x %s' after last input file has no effect", spec_lang);
2305
2306   switches[n_switches].part1 = 0;
2307   infiles[n_infiles].name = 0;
2308
2309   /* If we have a GCC_EXEC_PREFIX envvar, modify it for cpp's sake.  */
2310   if (gcc_exec_prefix)
2311     {
2312       temp = (char *) xmalloc (strlen (gcc_exec_prefix) + strlen (spec_version)
2313                                + strlen (spec_machine) + 3);
2314       strcpy (temp, gcc_exec_prefix);
2315       strcat (temp, spec_machine);
2316       strcat (temp, "/");
2317       strcat (temp, spec_version);
2318       strcat (temp, "/");
2319       gcc_exec_prefix = temp;
2320     }
2321 }
2322 \f
2323 /* Process a spec string, accumulating and running commands.  */
2324
2325 /* These variables describe the input file name.
2326    input_file_number is the index on outfiles of this file,
2327    so that the output file name can be stored for later use by %o.
2328    input_basename is the start of the part of the input file
2329    sans all directory names, and basename_length is the number
2330    of characters starting there excluding the suffix .c or whatever.  */
2331
2332 static char *input_filename;
2333 static int input_file_number;
2334 static int input_filename_length;
2335 static int basename_length;
2336 static char *input_basename;
2337 static char *input_suffix;
2338
2339 /* These are variables used within do_spec and do_spec_1.  */
2340
2341 /* Nonzero if an arg has been started and not yet terminated
2342    (with space, tab or newline).  */
2343 static int arg_going;
2344
2345 /* Nonzero means %d or %g has been seen; the next arg to be terminated
2346    is a temporary file name.  */
2347 static int delete_this_arg;
2348
2349 /* Nonzero means %w has been seen; the next arg to be terminated
2350    is the output file name of this compilation.  */
2351 static int this_is_output_file;
2352
2353 /* Nonzero means %s has been seen; the next arg to be terminated
2354    is the name of a library file and we should try the standard
2355    search dirs for it.  */
2356 static int this_is_library_file;
2357
2358 /* Nonzero means that the input of this command is coming from a pipe.  */
2359 static int input_from_pipe;
2360
2361 /* Process the spec SPEC and run the commands specified therein.
2362    Returns 0 if the spec is successfully processed; -1 if failed.  */
2363
2364 static int
2365 do_spec (spec)
2366      char *spec;
2367 {
2368   int value;
2369
2370   clear_args ();
2371   arg_going = 0;
2372   delete_this_arg = 0;
2373   this_is_output_file = 0;
2374   this_is_library_file = 0;
2375   input_from_pipe = 0;
2376
2377   value = do_spec_1 (spec, 0, NULL_PTR);
2378
2379   /* Force out any unfinished command.
2380      If -pipe, this forces out the last command if it ended in `|'.  */
2381   if (value == 0)
2382     {
2383       if (argbuf_index > 0 && !strcmp (argbuf[argbuf_index - 1], "|"))
2384         argbuf_index--;
2385
2386       if (argbuf_index > 0)
2387         value = execute ();
2388     }
2389
2390   return value;
2391 }
2392
2393 /* Process the sub-spec SPEC as a portion of a larger spec.
2394    This is like processing a whole spec except that we do
2395    not initialize at the beginning and we do not supply a
2396    newline by default at the end.
2397    INSWITCH nonzero means don't process %-sequences in SPEC;
2398    in this case, % is treated as an ordinary character.
2399    This is used while substituting switches.
2400    INSWITCH nonzero also causes SPC not to terminate an argument.
2401
2402    Value is zero unless a line was finished
2403    and the command on that line reported an error.  */
2404
2405 static int
2406 do_spec_1 (spec, inswitch, soft_matched_part)
2407      char *spec;
2408      int inswitch;
2409      char *soft_matched_part;
2410 {
2411   register char *p = spec;
2412   register int c;
2413   int i;
2414   char *string;
2415   int value;
2416
2417   while (c = *p++)
2418     /* If substituting a switch, treat all chars like letters.
2419        Otherwise, NL, SPC, TAB and % are special.  */
2420     switch (inswitch ? 'a' : c)
2421       {
2422       case '\n':
2423         /* End of line: finish any pending argument,
2424            then run the pending command if one has been started.  */
2425         if (arg_going)
2426           {
2427             obstack_1grow (&obstack, 0);
2428             string = obstack_finish (&obstack);
2429             if (this_is_library_file)
2430               string = find_file (string);
2431             store_arg (string, delete_this_arg, this_is_output_file);
2432             if (this_is_output_file)
2433               outfiles[input_file_number] = string;
2434           }
2435         arg_going = 0;
2436
2437         if (argbuf_index > 0 && !strcmp (argbuf[argbuf_index - 1], "|"))
2438           {
2439             int i;
2440             for (i = 0; i < n_switches; i++)
2441               if (!strcmp (switches[i].part1, "pipe"))
2442                 break;
2443
2444             /* A `|' before the newline means use a pipe here,
2445                but only if -pipe was specified.
2446                Otherwise, execute now and don't pass the `|' as an arg.  */
2447             if (i < n_switches)
2448               {
2449                 input_from_pipe = 1;
2450                 switches[i].valid = 1;
2451                 break;
2452               }
2453             else
2454               argbuf_index--;
2455           }
2456
2457         if (argbuf_index > 0)
2458           {
2459             value = execute ();
2460             if (value)
2461               return value;
2462           }
2463         /* Reinitialize for a new command, and for a new argument.  */
2464         clear_args ();
2465         arg_going = 0;
2466         delete_this_arg = 0;
2467         this_is_output_file = 0;
2468         this_is_library_file = 0;
2469         input_from_pipe = 0;
2470         break;
2471
2472       case '|':
2473         /* End any pending argument.  */
2474         if (arg_going)
2475           {
2476             obstack_1grow (&obstack, 0);
2477             string = obstack_finish (&obstack);
2478             if (this_is_library_file)
2479               string = find_file (string);
2480             store_arg (string, delete_this_arg, this_is_output_file);
2481             if (this_is_output_file)
2482               outfiles[input_file_number] = string;
2483           }
2484
2485         /* Use pipe */
2486         obstack_1grow (&obstack, c);
2487         arg_going = 1;
2488         break;
2489
2490       case '\t':
2491       case ' ':
2492         /* Space or tab ends an argument if one is pending.  */
2493         if (arg_going)
2494           {
2495             obstack_1grow (&obstack, 0);
2496             string = obstack_finish (&obstack);
2497             if (this_is_library_file)
2498               string = find_file (string);
2499             store_arg (string, delete_this_arg, this_is_output_file);
2500             if (this_is_output_file)
2501               outfiles[input_file_number] = string;
2502           }
2503         /* Reinitialize for a new argument.  */
2504         arg_going = 0;
2505         delete_this_arg = 0;
2506         this_is_output_file = 0;
2507         this_is_library_file = 0;
2508         break;
2509
2510       case '%':
2511         switch (c = *p++)
2512           {
2513           case 0:
2514             fatal ("Invalid specification!  Bug in cc.");
2515
2516           case 'b':
2517             obstack_grow (&obstack, input_basename, basename_length);
2518             arg_going = 1;
2519             break;
2520
2521           case 'd':
2522             delete_this_arg = 2;
2523             break;
2524
2525           /* Dump out the directories specified with LIBRARY_PATH,
2526              followed by the absolute directories
2527              that we search for startfiles.  */
2528           case 'D':
2529             for (i = 0; i < 2; i++)
2530               {
2531                 struct prefix_list *pl
2532                   = (i == 0 ? library_prefix.plist : startfile_prefix.plist);
2533                 int bufsize = 100;
2534                 char *buffer = (char *) xmalloc (bufsize);
2535                 int idx;
2536
2537                 for (; pl; pl = pl->next)
2538                   {
2539 #ifdef RELATIVE_PREFIX_NOT_LINKDIR
2540                     /* Used on systems which record the specified -L dirs
2541                        and use them to search for dynamic linking.  */
2542                     /* Relative directories always come from -B,
2543                        and it is better not to use them for searching
2544                        at run time.  In particular, stage1 loses  */
2545                     if (pl->prefix[0] != '/')
2546                       continue;
2547 #endif
2548                     if (machine_suffix)
2549                       {
2550                         if (is_linker_dir (pl->prefix, machine_suffix))
2551                           {
2552                             do_spec_1 ("-L", 0, NULL_PTR);
2553 #ifdef SPACE_AFTER_L_OPTION
2554                             do_spec_1 (" ", 0, NULL_PTR);
2555 #endif
2556                             do_spec_1 (pl->prefix, 1, NULL_PTR);
2557                             /* Remove slash from machine_suffix.  */
2558                             if (strlen (machine_suffix) >= bufsize)
2559                               bufsize = strlen (machine_suffix) * 2 + 1;
2560                             buffer = (char *) xrealloc (buffer, bufsize);
2561                             strcpy (buffer, machine_suffix);
2562                             idx = strlen (buffer);
2563                             if (buffer[idx - 1] == '/')
2564                               buffer[idx - 1] = 0;
2565                             do_spec_1 (buffer, 1, NULL_PTR);
2566                             /* Make this a separate argument.  */
2567                             do_spec_1 (" ", 0, NULL_PTR);
2568                           }
2569                       }
2570                     if (!pl->require_machine_suffix)
2571                       {
2572                         if (is_linker_dir (pl->prefix, ""))
2573                           {
2574                             do_spec_1 ("-L", 0, NULL_PTR);
2575 #ifdef SPACE_AFTER_L_OPTION
2576                             do_spec_1 (" ", 0, NULL_PTR);
2577 #endif
2578                             /* Remove slash from pl->prefix.  */
2579                             if (strlen (pl->prefix) >= bufsize)
2580                               bufsize = strlen (pl->prefix) * 2 + 1;
2581                             buffer = (char *) xrealloc (buffer, bufsize);
2582                             strcpy (buffer, pl->prefix);
2583                             idx = strlen (buffer);
2584                             if (buffer[idx - 1] == '/')
2585                               buffer[idx - 1] = 0;
2586                             do_spec_1 (buffer, 1, NULL_PTR);
2587                             /* Make this a separate argument.  */
2588                             do_spec_1 (" ", 0, NULL_PTR);
2589                           }
2590                       }
2591                   }
2592                 free (buffer);
2593               }
2594             break;
2595
2596           case 'e':
2597             /* {...:%efoo} means report an error with `foo' as error message
2598                and don't execute any more commands for this file.  */
2599             {
2600               char *q = p;
2601               char *buf;
2602               while (*p != 0 && *p != '\n') p++;
2603               buf = (char *) alloca (p - q + 1);
2604               strncpy (buf, q, p - q);
2605               buf[p - q] = 0;
2606               error ("%s", buf);
2607               return -1;
2608             }
2609             break;
2610
2611           case 'g':
2612           case 'u':
2613           case 'U':
2614             if (save_temps_flag)
2615               obstack_grow (&obstack, input_basename, basename_length);
2616             else
2617               {
2618 #ifdef MKTEMP_EACH_FILE
2619                 /* ??? This has a problem: the total number of
2620                    values mktemp can return is limited.
2621                    That matters for the names of object files.
2622                    In 2.4, do something about that.  */
2623                 struct temp_name *t;
2624                 char *suffix = p;
2625                 while (*p == '.' || isalpha (*p))
2626                   p++;
2627
2628                 /* See if we already have an association of %g/%u/%U and
2629                    suffix.  */
2630                 for (t = temp_names; t; t = t->next)
2631                   if (t->length == p - suffix
2632                       && strncmp (t->suffix, suffix, p - suffix) == 0
2633                       && t->unique == (c != 'g'))
2634                     break;
2635
2636                 /* Make a new association if needed.  %u requires one.  */
2637                 if (t == 0 || c == 'u')
2638                   {
2639                     if (t == 0)
2640                       {
2641                         t = (struct temp_name *) xmalloc (sizeof (struct temp_name));
2642                         t->next = temp_names;
2643                         temp_names = t;
2644                       }
2645                     t->length = p - suffix;
2646                     t->suffix = save_string (suffix, p - suffix);
2647                     t->unique = (c != 'g');
2648                     choose_temp_base ();
2649                     t->filename = temp_filename;
2650                     t->filename_length = temp_filename_length;
2651                   }
2652
2653                 obstack_grow (&obstack, t->filename, t->filename_length);
2654                 delete_this_arg = 1;
2655 #else
2656                 obstack_grow (&obstack, temp_filename, temp_filename_length);
2657                 if (c == 'u' || c == 'U')
2658                   {
2659                     static int unique;
2660                     char buff[9];
2661                     if (c == 'u')
2662                       unique++;
2663                     sprintf (buff, "%d", unique);
2664                     obstack_grow (&obstack, buff, strlen (buff));
2665                   }
2666 #endif
2667                 delete_this_arg = 1;
2668               }
2669             arg_going = 1;
2670             break;
2671
2672           case 'i':
2673             obstack_grow (&obstack, input_filename, input_filename_length);
2674             arg_going = 1;
2675             break;
2676
2677           case 'I':
2678             if (gcc_exec_prefix)
2679               {
2680                 do_spec_1 ("-iprefix", 1, NULL_PTR);
2681                 /* Make this a separate argument.  */
2682                 do_spec_1 (" ", 0, NULL_PTR);
2683                 do_spec_1 (gcc_exec_prefix, 1, NULL_PTR);
2684                 do_spec_1 (" ", 0, NULL_PTR);
2685               }
2686             break;
2687
2688           case 'o':
2689             {
2690               register int f;
2691               for (f = 0; f < n_infiles; f++)
2692                 store_arg (outfiles[f], 0, 0);
2693             }
2694             break;
2695
2696           case 's':
2697             this_is_library_file = 1;
2698             break;
2699
2700           case 'w':
2701             this_is_output_file = 1;
2702             break;
2703
2704           case 'W':
2705             {
2706               int index = argbuf_index;
2707               /* Handle the {...} following the %W.  */
2708               if (*p != '{')
2709                 abort ();
2710               p = handle_braces (p + 1);
2711               if (p == 0)
2712                 return -1;
2713               /* If any args were output, mark the last one for deletion
2714                  on failure.  */
2715               if (argbuf_index != index)
2716                 record_temp_file (argbuf[argbuf_index - 1], 0, 1);
2717               break;
2718             }
2719
2720           /* %x{OPTION} records OPTION for %X to output.  */
2721           case 'x':
2722             {
2723               char *p1 = p;
2724               char *string;
2725
2726               /* Skip past the option value and make a copy.  */
2727               if (*p != '{')
2728                 abort ();
2729               while (*p++ != '}')
2730                 ;
2731               string = save_string (p1 + 1, p - p1 - 2);
2732
2733               /* See if we already recorded this option.  */
2734               for (i = 0; i < n_linker_options; i++)
2735                 if (! strcmp (string, linker_options[i]))
2736                   {
2737                     free (string);
2738                     return 0;
2739                   }
2740
2741               /* This option is new; add it.  */
2742               n_linker_options++;
2743               if (!linker_options)
2744                 linker_options
2745                   = (char **) xmalloc (n_linker_options * sizeof (char **));
2746               else
2747                 linker_options
2748                   = (char **) xrealloc (linker_options,
2749                                         n_linker_options * sizeof (char **));
2750
2751               linker_options[n_linker_options - 1] = string;
2752             }
2753             break;
2754
2755           /* Dump out the options accumulated previously using %x,
2756              -Xlinker and -Wl,.  */
2757           case 'X':
2758             for (i = 0; i < n_linker_options; i++)
2759               {
2760                 do_spec_1 (linker_options[i], 1, NULL_PTR);
2761                 /* Make each accumulated option a separate argument.  */
2762                 do_spec_1 (" ", 0, NULL_PTR);
2763               }
2764             break;
2765
2766           /* Dump out the options accumulated previously using -Wa,.  */
2767           case 'Y':
2768             for (i = 0; i < n_assembler_options; i++)
2769               {
2770                 do_spec_1 (assembler_options[i], 1, NULL_PTR);
2771                 /* Make each accumulated option a separate argument.  */
2772                 do_spec_1 (" ", 0, NULL_PTR);
2773               }
2774             break;
2775
2776             /* Here are digits and numbers that just process
2777                a certain constant string as a spec.
2778             /* Here are digits and numbers that just process
2779                a certain constant string as a spec.  */
2780
2781           case '1':
2782             value = do_spec_1 (cc1_spec, 0, NULL_PTR);
2783             if (value != 0)
2784               return value;
2785             break;
2786
2787           case '2':
2788             value = do_spec_1 (cc1plus_spec, 0, NULL_PTR);
2789             if (value != 0)
2790               return value;
2791             break;
2792
2793           case 'a':
2794             value = do_spec_1 (asm_spec, 0, NULL_PTR);
2795             if (value != 0)
2796               return value;
2797             break;
2798
2799           case 'A':
2800             value = do_spec_1 (asm_final_spec, 0, NULL_PTR);
2801             if (value != 0)
2802               return value;
2803             break;
2804
2805           case 'c':
2806             value = do_spec_1 (signed_char_spec, 0, NULL_PTR);
2807             if (value != 0)
2808               return value;
2809             break;
2810
2811           case 'C':
2812             value = do_spec_1 (cpp_spec, 0, NULL_PTR);
2813             if (value != 0)
2814               return value;
2815             break;
2816
2817           case 'E':
2818             value = do_spec_1 (endfile_spec, 0, NULL_PTR);
2819             if (value != 0)
2820               return value;
2821             break;
2822
2823           case 'l':
2824             value = do_spec_1 (link_spec, 0, NULL_PTR);
2825             if (value != 0)
2826               return value;
2827             break;
2828
2829           case 'L':
2830             value = do_spec_1 (lib_spec, 0, NULL_PTR);
2831             if (value != 0)
2832               return value;
2833             break;
2834
2835           case 'p':
2836             {
2837               char *x = (char *) alloca (strlen (cpp_predefines) + 1);
2838               char *buf = x;
2839               char *y;
2840
2841               /* Copy all of the -D options in CPP_PREDEFINES into BUF.  */
2842               y = cpp_predefines;
2843               while (*y != 0)
2844                 {
2845                   if (! strncmp (y, "-D", 2))
2846                     /* Copy the whole option.  */
2847                     while (*y && *y != ' ' && *y != '\t')
2848                       *x++ = *y++;
2849                   else if (*y == ' ' || *y == '\t')
2850                     /* Copy whitespace to the result.  */
2851                     *x++ = *y++;
2852                   /* Don't copy other options.  */
2853                   else
2854                     y++;
2855                 }
2856
2857               *x = 0;
2858
2859               value = do_spec_1 (buf, 0, NULL_PTR);
2860               if (value != 0)
2861                 return value;
2862             }
2863             break;
2864
2865           case 'P':
2866             {
2867               char *x = (char *) alloca (strlen (cpp_predefines) * 4 + 1);
2868               char *buf = x;
2869               char *y;
2870
2871               /* Copy all of CPP_PREDEFINES into BUF,
2872                  but put __ after every -D and at the end of each arg.  */
2873               y = cpp_predefines;
2874               while (*y != 0)
2875                 {
2876                   if (! strncmp (y, "-D", 2))
2877                     {
2878                       int flag = 0;
2879
2880                       *x++ = *y++;
2881                       *x++ = *y++;
2882
2883                       if (strncmp (y, "__", 2))
2884                         {
2885                           /* Stick __ at front of macro name.  */
2886                           *x++ = '_';
2887                           *x++ = '_';
2888                           /* Arrange to stick __ at the end as well.  */
2889                           flag = 1;
2890                         }
2891
2892                       /* Copy the macro name.  */
2893                       while (*y && *y != '=' && *y != ' ' && *y != '\t')
2894                         *x++ = *y++;
2895
2896                       if (flag)
2897                         {
2898                           *x++ = '_';
2899                           *x++ = '_';
2900                         }
2901
2902                       /* Copy the value given, if any.  */
2903                       while (*y && *y != ' ' && *y != '\t')
2904                         *x++ = *y++;
2905                     }
2906                   else if (*y == ' ' || *y == '\t')
2907                     /* Copy whitespace to the result.  */
2908                     *x++ = *y++;
2909                   /* Don't copy -A options  */
2910                   else
2911                     y++;
2912                 }
2913               *x++ = ' ';
2914
2915               /* Copy all of CPP_PREDEFINES into BUF,
2916                  but put __ after every -D.  */
2917               y = cpp_predefines;
2918               while (*y != 0)
2919                 {
2920                   if (! strncmp (y, "-D", 2))
2921                     {
2922                       *x++ = *y++;
2923                       *x++ = *y++;
2924
2925                       if (strncmp (y, "__", 2))
2926                         {
2927                           /* Stick __ at front of macro name.  */
2928                           *x++ = '_';
2929                           *x++ = '_';
2930                         }
2931
2932                       /* Copy the macro name.  */
2933                       while (*y && *y != '=' && *y != ' ' && *y != '\t')
2934                         *x++ = *y++;
2935
2936                       /* Copy the value given, if any.  */
2937                       while (*y && *y != ' ' && *y != '\t')
2938                         *x++ = *y++;
2939                     }
2940                   else if (*y == ' ' || *y == '\t')
2941                     /* Copy whitespace to the result.  */
2942                     *x++ = *y++;
2943                   /* Don't copy -A options  */
2944                   else
2945                     y++;
2946                 }
2947               *x++ = ' ';
2948
2949               /* Copy all of the -A options in CPP_PREDEFINES into BUF.  */
2950               y = cpp_predefines;
2951               while (*y != 0)
2952                 {
2953                   if (! strncmp (y, "-A", 2))
2954                     /* Copy the whole option.  */
2955                     while (*y && *y != ' ' && *y != '\t')
2956                       *x++ = *y++;
2957                   else if (*y == ' ' || *y == '\t')
2958                     /* Copy whitespace to the result.  */
2959                     *x++ = *y++;
2960                   /* Don't copy other options.  */
2961                   else
2962                     y++;
2963                 }
2964
2965               *x = 0;
2966
2967               value = do_spec_1 (buf, 0, NULL_PTR);
2968               if (value != 0)
2969                 return value;
2970             }
2971             break;
2972
2973           case 'S':
2974             value = do_spec_1 (startfile_spec, 0, NULL_PTR);
2975             if (value != 0)
2976               return value;
2977             break;
2978
2979             /* Here we define characters other than letters and digits.  */
2980
2981           case '{':
2982             p = handle_braces (p);
2983             if (p == 0)
2984               return -1;
2985             break;
2986
2987           case '%':
2988             obstack_1grow (&obstack, '%');
2989             break;
2990
2991           case '*':
2992             do_spec_1 (soft_matched_part, 1, NULL_PTR);
2993             do_spec_1 (" ", 0, NULL_PTR);
2994             break;
2995
2996             /* Process a string found as the value of a spec given by name.
2997                This feature allows individual machine descriptions
2998                to add and use their own specs.
2999                %[...] modifies -D options the way %P does;
3000                %(...) uses the spec unmodified.  */
3001           case '(':
3002           case '[':
3003             {
3004               char *name = p;
3005               struct spec_list *sl;
3006               int len;
3007
3008               /* The string after the S/P is the name of a spec that is to be
3009                  processed. */
3010               while (*p && *p != ')' && *p != ']')
3011                 p++;
3012
3013               /* See if it's in the list */
3014               for (len = p - name, sl = specs; sl; sl = sl->next)
3015                 if (strncmp (sl->name, name, len) == 0 && !sl->name[len])
3016                   {
3017                     name = sl->spec;
3018                     break;
3019                   }
3020
3021               if (sl)
3022                 {
3023                   if (c == '(')
3024                     {
3025                       value = do_spec_1 (name, 0, NULL_PTR);
3026                       if (value != 0)
3027                         return value;
3028                     }
3029                   else
3030                     {
3031                       char *x = (char *) alloca (strlen (name) * 2 + 1);
3032                       char *buf = x;
3033                       char *y = name;
3034
3035                       /* Copy all of NAME into BUF, but put __ after
3036                          every -D and at the end of each arg,  */
3037                       while (1)
3038                         {
3039                           if (! strncmp (y, "-D", 2))
3040                             {
3041                               *x++ = '-';
3042                               *x++ = 'D';
3043                               *x++ = '_';
3044                               *x++ = '_';
3045                               y += 2;
3046                             }
3047                           else if (*y == ' ' || *y == 0)
3048                             {
3049                               *x++ = '_';
3050                               *x++ = '_';
3051                               if (*y == 0)
3052                                 break;
3053                               else
3054                                 *x++ = *y++;
3055                             }
3056                           else
3057                             *x++ = *y++;
3058                         }
3059                       *x = 0;
3060
3061                       value = do_spec_1 (buf, 0, NULL_PTR);
3062                       if (value != 0)
3063                         return value;
3064                     }
3065                 }
3066
3067               /* Discard the closing paren or bracket.  */
3068               if (*p)
3069                 p++;
3070             }
3071             break;
3072
3073           case '|':
3074             if (input_from_pipe)
3075               do_spec_1 ("-", 0, NULL_PTR);
3076             break;
3077
3078           default:
3079             abort ();
3080           }
3081         break;
3082
3083       case '\\':
3084         /* Backslash: treat next character as ordinary.  */
3085         c = *p++;
3086
3087         /* fall through */
3088       default:
3089         /* Ordinary character: put it into the current argument.  */
3090         obstack_1grow (&obstack, c);
3091         arg_going = 1;
3092       }
3093
3094   return 0;             /* End of string */
3095 }
3096
3097 /* Return 0 if we call do_spec_1 and that returns -1.  */
3098
3099 static char *
3100 handle_braces (p)
3101      register char *p;
3102 {
3103   register char *q;
3104   char *filter;
3105   int pipe = 0;
3106   int negate = 0;
3107   int suffix = 0;
3108
3109   if (*p == '|')
3110     /* A `|' after the open-brace means,
3111        if the test fails, output a single minus sign rather than nothing.
3112        This is used in %{|!pipe:...}.  */
3113     pipe = 1, ++p;
3114
3115   if (*p == '!')
3116     /* A `!' after the open-brace negates the condition:
3117        succeed if the specified switch is not present.  */
3118     negate = 1, ++p;
3119
3120   if (*p == '.')
3121     /* A `.' after the open-brace means test against the current suffix.  */
3122     {
3123       if (pipe)
3124         abort ();
3125
3126       suffix = 1;
3127       ++p;
3128     }
3129
3130   filter = p;
3131   while (*p != ':' && *p != '}') p++;
3132   if (*p != '}')
3133     {
3134       register int count = 1;
3135       q = p + 1;
3136       while (count > 0)
3137         {
3138           if (*q == '{')
3139             count++;
3140           else if (*q == '}')
3141             count--;
3142           else if (*q == 0)
3143             abort ();
3144           q++;
3145         }
3146     }
3147   else
3148     q = p + 1;
3149
3150   if (suffix)
3151     {
3152       int found = (input_suffix != 0
3153                    && strlen (input_suffix) == p - filter
3154                    && strncmp (input_suffix, filter, p - filter) == 0);
3155
3156       if (p[0] == '}')
3157         abort ();
3158
3159       if (negate != found
3160           && do_spec_1 (save_string (p + 1, q - p - 2), 0, NULL_PTR) < 0)
3161         return 0;
3162
3163       return q;
3164     }
3165   else if (p[-1] == '*' && p[0] == '}')
3166     {
3167       /* Substitute all matching switches as separate args.  */
3168       register int i;
3169       --p;
3170       for (i = 0; i < n_switches; i++)
3171         if (!strncmp (switches[i].part1, filter, p - filter))
3172           give_switch (i, 0);
3173     }
3174   else
3175     {
3176       /* Test for presence of the specified switch.  */
3177       register int i;
3178       int present = 0;
3179
3180       /* If name specified ends in *, as in {x*:...},
3181          check for %* and handle that case.  */
3182       if (p[-1] == '*' && !negate)
3183         {
3184           int substitution;
3185           char *r = p;
3186
3187           /* First see whether we have %*.  */
3188           substitution = 0;
3189           while (r < q)
3190             {
3191               if (*r == '%' && r[1] == '*')
3192                 substitution = 1;
3193               r++;
3194             }
3195           /* If we do, handle that case.  */
3196           if (substitution)
3197             {
3198               /* Substitute all matching switches as separate args.
3199                  But do this by substituting for %*
3200                  in the text that follows the colon.  */
3201
3202               unsigned hard_match_len = p - filter - 1;
3203               char *string = save_string (p + 1, q - p - 2);
3204
3205               for (i = 0; i < n_switches; i++)
3206                 if (!strncmp (switches[i].part1, filter, hard_match_len))
3207                   {
3208                     do_spec_1 (string, 0, &switches[i].part1[hard_match_len]);
3209                     /* Pass any arguments this switch has.  */
3210                     give_switch (i, 1);
3211                   }
3212
3213               return q;
3214             }
3215         }
3216
3217       /* If name specified ends in *, as in {x*:...},
3218          check for presence of any switch name starting with x.  */
3219       if (p[-1] == '*')
3220         {
3221           for (i = 0; i < n_switches; i++)
3222             {
3223               unsigned hard_match_len = p - filter - 1;
3224
3225               if (!strncmp (switches[i].part1, filter, hard_match_len))
3226                 {
3227                   switches[i].valid = 1;
3228                   present = 1;
3229                 }
3230             }
3231         }
3232       /* Otherwise, check for presence of exact name specified.  */
3233       else
3234         {
3235           for (i = 0; i < n_switches; i++)
3236             {
3237               if (!strncmp (switches[i].part1, filter, p - filter)
3238                   && switches[i].part1[p - filter] == 0)
3239                 {
3240                   switches[i].valid = 1;
3241                   present = 1;
3242                   break;
3243                 }
3244             }
3245         }
3246
3247       /* If it is as desired (present for %{s...}, absent for %{-s...})
3248          then substitute either the switch or the specified
3249          conditional text.  */
3250       if (present != negate)
3251         {
3252           if (*p == '}')
3253             {
3254               give_switch (i, 0);
3255             }
3256           else
3257             {
3258               if (do_spec_1 (save_string (p + 1, q - p - 2), 0, NULL_PTR) < 0)
3259                 return 0;
3260             }
3261         }
3262       else if (pipe)
3263         {
3264           /* Here if a %{|...} conditional fails: output a minus sign,
3265              which means "standard output" or "standard input".  */
3266           do_spec_1 ("-", 0, NULL_PTR);
3267         }
3268     }
3269
3270   return q;
3271 }
3272
3273 /* Pass a switch to the current accumulating command
3274    in the same form that we received it.
3275    SWITCHNUM identifies the switch; it is an index into
3276    the vector of switches gcc received, which is `switches'.
3277    This cannot fail since it never finishes a command line.
3278
3279    If OMIT_FIRST_WORD is nonzero, then we omit .part1 of the argument.  */
3280
3281 static void
3282 give_switch (switchnum, omit_first_word)
3283      int switchnum;
3284      int omit_first_word;
3285 {
3286   if (!omit_first_word)
3287     {
3288       do_spec_1 ("-", 0, NULL_PTR);
3289       do_spec_1 (switches[switchnum].part1, 1, NULL_PTR);
3290     }
3291   do_spec_1 (" ", 0, NULL_PTR);
3292   if (switches[switchnum].args != 0)
3293     {
3294       char **p;
3295       for (p = switches[switchnum].args; *p; p++)
3296         {
3297           do_spec_1 (*p, 1, NULL_PTR);
3298           do_spec_1 (" ", 0, NULL_PTR);
3299         }
3300     }
3301   switches[switchnum].valid = 1;
3302 }
3303 \f
3304 /* Search for a file named NAME trying various prefixes including the
3305    user's -B prefix and some standard ones.
3306    Return the absolute file name found.  If nothing is found, return NAME.  */
3307
3308 static char *
3309 find_file (name)
3310      char *name;
3311 {
3312   char *newname;
3313
3314   newname = find_a_file (&startfile_prefix, name, R_OK);
3315   return newname ? newname : name;
3316 }
3317
3318 /* Determine whether a -L option is relevant.  Not required for certain
3319    fixed names and for directories that don't exist.  */
3320
3321 static int
3322 is_linker_dir (path1, path2)
3323      char *path1;
3324      char *path2;
3325 {
3326   int len1 = strlen (path1);
3327   int len2 = strlen (path2);
3328   char *path = (char *) alloca (3 + len1 + len2);
3329   char *cp;
3330   struct stat st;
3331
3332   /* Construct the path from the two parts.  Ensure the string ends with "/.".
3333      The resulting path will be a directory even if the given path is a
3334      symbolic link.  */
3335   bcopy (path1, path, len1);
3336   bcopy (path2, path + len1, len2);
3337   cp = path + len1 + len2;
3338   if (cp[-1] != '/')
3339     *cp++ = '/';
3340   *cp++ = '.';
3341   *cp = '\0';
3342
3343   /* Exclude directories that the linker is known to search.  */
3344   if ((cp - path == 6 && strcmp (path, "/lib/.") == 0)
3345       || (cp - path == 10 && strcmp (path, "/usr/lib/.") == 0))
3346     return 0;
3347
3348   return (stat (path, &st) >= 0 && S_ISDIR (st.st_mode));
3349 }
3350 \f
3351 /* On fatal signals, delete all the temporary files.  */
3352
3353 static void
3354 fatal_error (signum)
3355      int signum;
3356 {
3357   signal (signum, SIG_DFL);
3358   delete_failure_queue ();
3359   delete_temp_files ();
3360   /* Get the same signal again, this time not handled,
3361      so its normal effect occurs.  */
3362   kill (getpid (), signum);
3363 }
3364
3365 int
3366 main (argc, argv)
3367      int argc;
3368      char **argv;
3369 {
3370   register int i;
3371   int j;
3372   int value;
3373   int linker_was_run = 0;
3374   char *explicit_link_files;
3375   char *specs_file;
3376   char *p;
3377
3378   p = argv[0] + strlen (argv[0]);
3379   while (p != argv[0] && p[-1] != '/') --p;
3380   programname = p;
3381
3382   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
3383     signal (SIGINT, fatal_error);
3384   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
3385     signal (SIGHUP, fatal_error);
3386   if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
3387     signal (SIGTERM, fatal_error);
3388 #ifdef SIGPIPE
3389   if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
3390     signal (SIGPIPE, fatal_error);
3391 #endif
3392
3393   argbuf_length = 10;
3394   argbuf = (char **) xmalloc (argbuf_length * sizeof (char *));
3395
3396   obstack_init (&obstack);
3397
3398   /* Set up to remember the pathname of gcc and any options
3399      needed for collect.  */
3400   obstack_init (&collect_obstack);
3401   obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=")-1);
3402   obstack_grow (&collect_obstack, programname, strlen (programname)+1);
3403   putenv (obstack_finish (&collect_obstack));
3404
3405   /* Choose directory for temp files.  */
3406
3407   choose_temp_base ();
3408
3409   /* Make a table of what switches there are (switches, n_switches).
3410      Make a table of specified input files (infiles, n_infiles).
3411      Decode switches that are handled locally.  */
3412
3413   process_command (argc, argv);
3414
3415   /* Initialize the vector of specs to just the default.
3416      This means one element containing 0s, as a terminator.  */
3417
3418   compilers = (struct compiler *) xmalloc (sizeof default_compilers);
3419   bcopy (default_compilers, compilers, sizeof default_compilers);
3420   n_compilers = n_default_compilers;
3421
3422   /* Read specs from a file if there is one.  */
3423
3424   machine_suffix = concat (spec_machine, "/", concat (spec_version, "/", ""));
3425   just_machine_suffix = concat (spec_machine, "/", "");
3426
3427   specs_file = find_a_file (&startfile_prefix, "specs", R_OK);
3428   /* Read the specs file unless it is a default one.  */
3429   if (specs_file != 0 && strcmp (specs_file, "specs"))
3430     read_specs (specs_file);
3431
3432   /* If not cross-compiling, look for startfiles in the standard places.  */
3433   /* The fact that these are done here, after reading the specs file,
3434      means that it cannot be found in these directories.
3435      But that's okay.  It should never be there anyway.  */
3436   if (!cross_compile)
3437     {
3438 #ifdef MD_EXEC_PREFIX
3439       add_prefix (&exec_prefix, md_exec_prefix, 0, 0, NULL_PTR);
3440       add_prefix (&startfile_prefix, md_exec_prefix, 0, 0, NULL_PTR);
3441 #endif
3442
3443 #ifdef MD_STARTFILE_PREFIX
3444       add_prefix (&startfile_prefix, md_startfile_prefix, 0, 0, NULL_PTR);
3445 #endif
3446
3447 #ifdef MD_STARTFILE_PREFIX_1
3448       add_prefix (&startfile_prefix, md_startfile_prefix_1, 0, 0, NULL_PTR);
3449 #endif
3450
3451       add_prefix (&startfile_prefix, standard_startfile_prefix, 0, 0,
3452                   NULL_PTR);
3453       add_prefix (&startfile_prefix, standard_startfile_prefix_1, 0, 0,
3454                   NULL_PTR);
3455       add_prefix (&startfile_prefix, standard_startfile_prefix_2, 0, 0,
3456                   NULL_PTR);
3457 #if 0 /* Can cause surprises, and one can use -B./ instead.  */
3458       add_prefix (&startfile_prefix, "./", 0, 1, NULL_PTR);
3459 #endif
3460     }
3461
3462   /* Now we have the specs.
3463      Set the `valid' bits for switches that match anything in any spec.  */
3464
3465   validate_all_switches ();
3466
3467   /* Warn about any switches that no pass was interested in.  */
3468
3469   for (i = 0; i < n_switches; i++)
3470     if (! switches[i].valid)
3471       error ("unrecognized option `-%s'", switches[i].part1);
3472
3473   if (print_libgcc_file_name)
3474     {
3475       printf ("%s\n", find_file ("libgcc.a"));
3476       exit (0);
3477     }
3478
3479   /* Obey some of the options.  */
3480
3481   if (verbose_flag)
3482     {
3483       fprintf (stderr, "gcc version %s\n", version_string);
3484       if (n_infiles == 0)
3485         exit (0);
3486     }
3487
3488   if (n_infiles == 0)
3489     fatal ("No input files specified.");
3490
3491   /* Make a place to record the compiler output file names
3492      that correspond to the input files.  */
3493
3494   outfiles = (char **) xmalloc (n_infiles * sizeof (char *));
3495   bzero (outfiles, n_infiles * sizeof (char *));
3496
3497   /* Record which files were specified explicitly as link input.  */
3498
3499   explicit_link_files = xmalloc (n_infiles);
3500   bzero (explicit_link_files, n_infiles);
3501
3502   for (i = 0; i < n_infiles; i++)
3503     {
3504       register struct compiler *cp = 0;
3505       int this_file_error = 0;
3506
3507       /* Tell do_spec what to substitute for %i.  */
3508
3509       input_filename = infiles[i].name;
3510       input_filename_length = strlen (input_filename);
3511       input_file_number = i;
3512
3513       /* Use the same thing in %o, unless cp->spec says otherwise.  */
3514
3515       outfiles[i] = input_filename;
3516
3517       /* Figure out which compiler from the file's suffix.  */
3518
3519       cp = lookup_compiler (infiles[i].name, input_filename_length,
3520                             infiles[i].language);
3521
3522       if (cp)
3523         {
3524           /* Ok, we found an applicable compiler.  Run its spec.  */
3525           /* First say how much of input_filename to substitute for %b  */
3526           register char *p;
3527           int len;
3528
3529           input_basename = input_filename;
3530           for (p = input_filename; *p; p++)
3531             if (*p == '/')
3532               input_basename = p + 1;
3533
3534           /* Find a suffix starting with the last period,
3535              and set basename_length to exclude that suffix.  */
3536           basename_length = strlen (input_basename);
3537           p = input_basename + basename_length;
3538           while (p != input_basename && *p != '.') --p;
3539           if (*p == '.' && p != input_basename)
3540             {
3541               basename_length = p - input_basename;
3542               input_suffix = p + 1;
3543             }
3544           else
3545             input_suffix = "";
3546
3547           len = 0;
3548           for (j = 0; j < sizeof cp->spec / sizeof cp->spec[0]; j++)
3549             if (cp->spec[j])
3550               len += strlen (cp->spec[j]);
3551
3552           p = (char *) xmalloc (len + 1);
3553
3554           len = 0;
3555           for (j = 0; j < sizeof cp->spec / sizeof cp->spec[0]; j++)
3556             if (cp->spec[j])
3557               {
3558                 strcpy (p + len, cp->spec[j]);
3559                 len += strlen (cp->spec[j]);
3560               }
3561
3562           value = do_spec (p);
3563           free (p);
3564           if (value < 0)
3565             this_file_error = 1;
3566         }
3567
3568       /* If this file's name does not contain a recognized suffix,
3569          record it as explicit linker input.  */
3570
3571       else
3572         explicit_link_files[i] = 1;
3573
3574       /* Clear the delete-on-failure queue, deleting the files in it
3575          if this compilation failed.  */
3576
3577       if (this_file_error)
3578         {
3579           delete_failure_queue ();
3580           error_count++;
3581         }
3582       /* If this compilation succeeded, don't delete those files later.  */
3583       clear_failure_queue ();
3584     }
3585
3586   /* Run ld to link all the compiler output files.  */
3587
3588   if (error_count == 0)
3589     {
3590       int tmp = execution_count;
3591       int i;
3592       int first_time;
3593
3594       /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
3595          for collect.  */
3596       putenv_from_prefixes (&exec_prefix, "COMPILER_PATH=");
3597       putenv_from_prefixes (&startfile_prefix, "LIBRARY_PATH=");
3598
3599       /* Build COLLECT_GCC_OPTIONS to have all of the options specified to
3600          the compiler.  */
3601       obstack_grow (&collect_obstack, "COLLECT_GCC_OPTIONS=",
3602                     sizeof ("COLLECT_GCC_OPTIONS=")-1);
3603
3604       first_time = TRUE;
3605       for (i = 0; i < n_switches; i++)
3606         {
3607           char **args;
3608           if (!first_time)
3609             obstack_grow (&collect_obstack, " ", 1);
3610
3611           first_time = FALSE;
3612           obstack_grow (&collect_obstack, "-", 1);
3613           obstack_grow (&collect_obstack, switches[i].part1,
3614                         strlen (switches[i].part1));
3615
3616           for (args = switches[i].args; args && *args; args++)
3617             {
3618               obstack_grow (&collect_obstack, " ", 1);
3619               obstack_grow (&collect_obstack, *args, strlen (*args));
3620             }
3621         }
3622       obstack_grow (&collect_obstack, "\0", 1);
3623       putenv (obstack_finish (&collect_obstack));
3624
3625       value = do_spec (link_command_spec);
3626       if (value < 0)
3627         error_count = 1;
3628       linker_was_run = (tmp != execution_count);
3629     }
3630
3631   /* Warn if a -B option was specified but the prefix was never used.  */
3632   unused_prefix_warnings (&exec_prefix);
3633   unused_prefix_warnings (&startfile_prefix);
3634
3635   /* If options said don't run linker,
3636      complain about input files to be given to the linker.  */
3637
3638   if (! linker_was_run && error_count == 0)
3639     for (i = 0; i < n_infiles; i++)
3640       if (explicit_link_files[i])
3641         error ("%s: linker input file unused since linking not done",
3642                outfiles[i]);
3643
3644   /* Delete some or all of the temporary files we made.  */
3645
3646   if (error_count)
3647     delete_failure_queue ();
3648   delete_temp_files ();
3649
3650   exit (error_count > 0 ? (signal_count ? 2 : 1) : 0);
3651   /* NOTREACHED */
3652   return 0;
3653 }
3654
3655 /* Find the proper compilation spec for the file name NAME,
3656    whose length is LENGTH.  LANGUAGE is the specified language,
3657    or 0 if none specified.  */
3658
3659 static struct compiler *
3660 lookup_compiler (name, length, language)
3661      char *name;
3662      int length;
3663      char *language;
3664 {
3665   struct compiler *cp;
3666
3667   /* Look for the language, if one is spec'd.  */
3668   if (language != 0)
3669     {
3670       for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
3671         {
3672           if (language != 0)
3673             {
3674               if (cp->suffix[0] == '@'
3675                   && !strcmp (cp->suffix + 1, language))
3676                 return cp;
3677             }
3678         }
3679       error ("language %s not recognized", language);
3680     }
3681
3682   /* Look for a suffix.  */
3683   for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
3684     {
3685       if (/* The suffix `-' matches only the file name `-'.  */
3686           (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
3687           ||
3688           (strlen (cp->suffix) < length
3689            /* See if the suffix matches the end of NAME.  */
3690            && !strcmp (cp->suffix,
3691                        name + length - strlen (cp->suffix))))
3692         {
3693           if (cp->spec[0][0] == '@')
3694             {
3695               struct compiler *new;
3696               /* An alias entry maps a suffix to a language.
3697                  Search for the language; pass 0 for NAME and LENGTH
3698                  to avoid infinite recursion if language not found.
3699                  Construct the new compiler spec.  */
3700               language = cp->spec[0] + 1;
3701               new = (struct compiler *) xmalloc (sizeof (struct compiler));
3702               new->suffix = cp->suffix;
3703               bcopy (lookup_compiler (NULL_PTR, 0, language)->spec,
3704                      new->spec, sizeof new->spec);
3705               return new;
3706             }
3707           /* A non-alias entry: return it.  */
3708           return cp;
3709         }
3710     }
3711
3712   return 0;
3713 }
3714 \f
3715 char *
3716 xmalloc (size)
3717      unsigned size;
3718 {
3719   register char *value = (char *) malloc (size);
3720   if (value == 0)
3721     fatal ("virtual memory exhausted");
3722   return value;
3723 }
3724
3725 char *
3726 xrealloc (ptr, size)
3727      char *ptr;
3728      unsigned size;
3729 {
3730   register char *value = (char *) realloc (ptr, size);
3731   if (value == 0)
3732     fatal ("virtual memory exhausted");
3733   return value;
3734 }
3735
3736 /* Return a newly-allocated string whose contents concatenate those of s1, s2, s3.  */
3737
3738 static char *
3739 concat (s1, s2, s3)
3740      char *s1, *s2, *s3;
3741 {
3742   int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
3743   char *result = xmalloc (len1 + len2 + len3 + 1);
3744
3745   strcpy (result, s1);
3746   strcpy (result + len1, s2);
3747   strcpy (result + len1 + len2, s3);
3748   *(result + len1 + len2 + len3) = 0;
3749
3750   return result;
3751 }
3752
3753 static char *
3754 save_string (s, len)
3755      char *s;
3756      int len;
3757 {
3758   register char *result = xmalloc (len + 1);
3759
3760   bcopy (s, result, len);
3761   result[len] = 0;
3762   return result;
3763 }
3764
3765 static void
3766 pfatal_with_name (name)
3767      char *name;
3768 {
3769   char *s;
3770
3771   if (errno < sys_nerr)
3772     s = concat ("%s: ", sys_errlist[errno], "");
3773   else
3774     s = "cannot open %s";
3775   fatal (s, name);
3776 }
3777
3778 static void
3779 perror_with_name (name)
3780      char *name;
3781 {
3782   char *s;
3783
3784   if (errno < sys_nerr)
3785     s = concat ("%s: ", sys_errlist[errno], "");
3786   else
3787     s = "cannot open %s";
3788   error (s, name);
3789 }
3790
3791 static void
3792 perror_exec (name)
3793      char *name;
3794 {
3795   char *s;
3796
3797   if (errno < sys_nerr)
3798     s = concat ("installation problem, cannot exec %s: ",
3799                 sys_errlist[errno], "");
3800   else
3801     s = "installation problem, cannot exec %s";
3802   error (s, name);
3803 }
3804
3805 /* More 'friendly' abort that prints the line and file.
3806    config.h can #define abort fancy_abort if you like that sort of thing.  */
3807
3808 void
3809 fancy_abort ()
3810 {
3811   fatal ("Internal gcc abort.");
3812 }
3813 \f
3814 #ifdef HAVE_VPRINTF
3815
3816 /* Output an error message and exit */
3817
3818 static void
3819 fatal (va_alist)
3820      va_dcl
3821 {
3822   va_list ap;
3823   char *format;
3824
3825   va_start (ap);
3826   format = va_arg (ap, char *);
3827   fprintf (stderr, "%s: ", programname);
3828   vfprintf (stderr, format, ap);
3829   va_end (ap);
3830   fprintf (stderr, "\n");
3831   delete_temp_files ();
3832   exit (1);
3833 }
3834
3835 static void
3836 error (va_alist)
3837      va_dcl
3838 {
3839   va_list ap;
3840   char *format;
3841
3842   va_start (ap);
3843   format = va_arg (ap, char *);
3844   fprintf (stderr, "%s: ", programname);
3845   vfprintf (stderr, format, ap);
3846   va_end (ap);
3847
3848   fprintf (stderr, "\n");
3849 }
3850
3851 #else /* not HAVE_VPRINTF */
3852
3853 static void
3854 fatal (msg, arg1, arg2)
3855      char *msg, *arg1, *arg2;
3856 {
3857   error (msg, arg1, arg2);
3858   delete_temp_files ();
3859   exit (1);
3860 }
3861
3862 static void
3863 error (msg, arg1, arg2)
3864      char *msg, *arg1, *arg2;
3865 {
3866   fprintf (stderr, "%s: ", programname);
3867   fprintf (stderr, msg, arg1, arg2);
3868   fprintf (stderr, "\n");
3869 }
3870
3871 #endif /* not HAVE_VPRINTF */
3872
3873 \f
3874 static void
3875 validate_all_switches ()
3876 {
3877   struct compiler *comp;
3878   register char *p;
3879   register char c;
3880   struct spec_list *spec;
3881
3882   for (comp = compilers; comp->spec[0]; comp++)
3883     {
3884       int i;
3885       for (i = 0; i < sizeof comp->spec / sizeof comp->spec[0] && comp->spec[i]; i++)
3886         {
3887           p = comp->spec[i];
3888           while (c = *p++)
3889             if (c == '%' && *p == '{')
3890               /* We have a switch spec.  */
3891               validate_switches (p + 1);
3892         }
3893     }
3894
3895   /* look through the linked list of extra specs read from the specs file */
3896   for (spec = specs; spec ; spec = spec->next)
3897     {
3898       p = spec->spec;
3899       while (c = *p++)
3900         if (c == '%' && *p == '{')
3901           /* We have a switch spec.  */
3902           validate_switches (p + 1);
3903     }
3904
3905   p = link_command_spec;
3906   while (c = *p++)
3907     if (c == '%' && *p == '{')
3908       /* We have a switch spec.  */
3909       validate_switches (p + 1);
3910
3911   /* Now notice switches mentioned in the machine-specific specs.  */
3912
3913   p = asm_spec;
3914   while (c = *p++)
3915     if (c == '%' && *p == '{')
3916       /* We have a switch spec.  */
3917       validate_switches (p + 1);
3918
3919   p = asm_final_spec;
3920   while (c = *p++)
3921     if (c == '%' && *p == '{')
3922       /* We have a switch spec.  */
3923       validate_switches (p + 1);
3924
3925   p = cpp_spec;
3926   while (c = *p++)
3927     if (c == '%' && *p == '{')
3928       /* We have a switch spec.  */
3929       validate_switches (p + 1);
3930
3931   p = signed_char_spec;
3932   while (c = *p++)
3933     if (c == '%' && *p == '{')
3934       /* We have a switch spec.  */
3935       validate_switches (p + 1);
3936
3937   p = cc1_spec;
3938   while (c = *p++)
3939     if (c == '%' && *p == '{')
3940       /* We have a switch spec.  */
3941       validate_switches (p + 1);
3942
3943   p = cc1plus_spec;
3944   while (c = *p++)
3945     if (c == '%' && *p == '{')
3946       /* We have a switch spec.  */
3947       validate_switches (p + 1);
3948
3949   p = link_spec;
3950   while (c = *p++)
3951     if (c == '%' && *p == '{')
3952       /* We have a switch spec.  */
3953       validate_switches (p + 1);
3954
3955   p = lib_spec;
3956   while (c = *p++)
3957     if (c == '%' && *p == '{')
3958       /* We have a switch spec.  */
3959       validate_switches (p + 1);
3960
3961   p = startfile_spec;
3962   while (c = *p++)
3963     if (c == '%' && *p == '{')
3964       /* We have a switch spec.  */
3965       validate_switches (p + 1);
3966 }
3967
3968 /* Look at the switch-name that comes after START
3969    and mark as valid all supplied switches that match it.  */
3970
3971 static void
3972 validate_switches (start)
3973      char *start;
3974 {
3975   register char *p = start;
3976   char *filter;
3977   register int i;
3978   int suffix = 0;
3979
3980   if (*p == '|')
3981     ++p;
3982
3983   if (*p == '!')
3984     ++p;
3985
3986   if (*p == '.')
3987     suffix = 1, ++p;
3988
3989   filter = p;
3990   while (*p != ':' && *p != '}') p++;
3991
3992   if (suffix)
3993     ;
3994   else if (p[-1] == '*')
3995     {
3996       /* Mark all matching switches as valid.  */
3997       --p;
3998       for (i = 0; i < n_switches; i++)
3999         if (!strncmp (switches[i].part1, filter, p - filter))
4000           switches[i].valid = 1;
4001     }
4002   else
4003     {
4004       /* Mark an exact matching switch as valid.  */
4005       for (i = 0; i < n_switches; i++)
4006         {
4007           if (!strncmp (switches[i].part1, filter, p - filter)
4008               && switches[i].part1[p - filter] == 0)
4009             switches[i].valid = 1;
4010         }
4011     }
4012 }