OSDN Git Service

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