Just enumerate all GF_OMP_FOR_KIND_* and GF_OMP_TARGET_KIND_*.
[official-gcc.git] / gcc / gcc.c
blob89400adc80b70e676fb81f202bbdbd98675722a3
1 /* Compiler driver program that can handle many languages.
2 Copyright (C) 1987-2014 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* This program is the user interface to the C compiler and possibly to
21 other compilers. It is used because compilation is a complicated procedure
22 which involves running several programs and passing temporary files between
23 them, forwarding the users switches to those programs selectively,
24 and deleting the temporary files at the end.
26 CC recognizes how to compile each input file by suffixes in the file names.
27 Once it knows which kind of compilation to perform, the procedure for
28 compilation is specified by a string called a "spec". */
30 #include "config.h"
31 #include "system.h"
32 #include "coretypes.h"
33 #include "multilib.h" /* before tm.h */
34 #include "tm.h"
35 #include "xregex.h"
36 #include "obstack.h"
37 #include "intl.h"
38 #include "prefix.h"
39 #include "gcc.h"
40 #include "diagnostic.h"
41 #include "flags.h"
42 #include "opts.h"
43 #include "params.h"
44 #include "vec.h"
45 #include "filenames.h"
47 /* By default there is no special suffix for target executables. */
48 /* FIXME: when autoconf is fixed, remove the host check - dj */
49 #if defined(TARGET_EXECUTABLE_SUFFIX) && defined(HOST_EXECUTABLE_SUFFIX)
50 #define HAVE_TARGET_EXECUTABLE_SUFFIX
51 #endif
53 /* By default there is no special suffix for host executables. */
54 #ifdef HOST_EXECUTABLE_SUFFIX
55 #define HAVE_HOST_EXECUTABLE_SUFFIX
56 #else
57 #define HOST_EXECUTABLE_SUFFIX ""
58 #endif
60 /* By default, the suffix for target object files is ".o". */
61 #ifdef TARGET_OBJECT_SUFFIX
62 #define HAVE_TARGET_OBJECT_SUFFIX
63 #else
64 #define TARGET_OBJECT_SUFFIX ".o"
65 #endif
67 static const char dir_separator_str[] = { DIR_SEPARATOR, 0 };
69 /* Most every one is fine with LIBRARY_PATH. For some, it conflicts. */
70 #ifndef LIBRARY_PATH_ENV
71 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
72 #endif
74 /* If a stage of compilation returns an exit status >= 1,
75 compilation of that file ceases. */
77 #define MIN_FATAL_STATUS 1
79 /* Flag set by cppspec.c to 1. */
80 int is_cpp_driver;
82 /* Flag set to nonzero if an @file argument has been supplied to gcc. */
83 static bool at_file_supplied;
85 /* Definition of string containing the arguments given to configure. */
86 #include "configargs.h"
88 /* Flag saying to print the command line options understood by gcc and its
89 sub-processes. */
91 static int print_help_list;
93 /* Flag saying to print the version of gcc and its sub-processes. */
95 static int print_version;
97 /* Flag indicating whether we should ONLY print the command and
98 arguments (like verbose_flag) without executing the command.
99 Displayed arguments are quoted so that the generated command
100 line is suitable for execution. This is intended for use in
101 shell scripts to capture the driver-generated command line. */
102 static int verbose_only_flag;
104 /* Flag indicating how to print command line options of sub-processes. */
106 static int print_subprocess_help;
108 /* Linker suffix passed to -fuse-ld=... */
109 static const char *use_ld;
111 /* Whether we should report subprocess execution times to a file. */
113 FILE *report_times_to_file = NULL;
115 /* Nonzero means place this string before uses of /, so that include
116 and library files can be found in an alternate location. */
118 #ifdef TARGET_SYSTEM_ROOT
119 static const char *target_system_root = TARGET_SYSTEM_ROOT;
120 #else
121 static const char *target_system_root = 0;
122 #endif
124 /* Nonzero means pass the updated target_system_root to the compiler. */
126 static int target_system_root_changed;
128 /* Nonzero means append this string to target_system_root. */
130 static const char *target_sysroot_suffix = 0;
132 /* Nonzero means append this string to target_system_root for headers. */
134 static const char *target_sysroot_hdrs_suffix = 0;
136 /* Nonzero means write "temp" files in source directory
137 and use the source file's name in them, and don't delete them. */
139 static enum save_temps {
140 SAVE_TEMPS_NONE, /* no -save-temps */
141 SAVE_TEMPS_CWD, /* -save-temps in current directory */
142 SAVE_TEMPS_OBJ /* -save-temps in object directory */
143 } save_temps_flag;
145 /* Output file to use to get the object directory for -save-temps=obj */
146 static char *save_temps_prefix = 0;
147 static size_t save_temps_length = 0;
149 /* The compiler version. */
151 static const char *compiler_version;
153 /* The target version. */
155 static const char *const spec_version = DEFAULT_TARGET_VERSION;
157 /* The target machine. */
159 static const char *spec_machine = DEFAULT_TARGET_MACHINE;
161 /* Nonzero if cross-compiling.
162 When -b is used, the value comes from the `specs' file. */
164 #ifdef CROSS_DIRECTORY_STRUCTURE
165 static const char *cross_compile = "1";
166 #else
167 static const char *cross_compile = "0";
168 #endif
170 /* Greatest exit code of sub-processes that has been encountered up to
171 now. */
172 static int greatest_status = 1;
174 /* This is the obstack which we use to allocate many strings. */
176 static struct obstack obstack;
178 /* This is the obstack to build an environment variable to pass to
179 collect2 that describes all of the relevant switches of what to
180 pass the compiler in building the list of pointers to constructors
181 and destructors. */
183 static struct obstack collect_obstack;
185 /* Forward declaration for prototypes. */
186 struct path_prefix;
187 struct prefix_list;
189 static void init_spec (void);
190 static void store_arg (const char *, int, int);
191 static void insert_wrapper (const char *);
192 static char *load_specs (const char *);
193 static void read_specs (const char *, bool, bool);
194 static void set_spec (const char *, const char *, bool);
195 static struct compiler *lookup_compiler (const char *, size_t, const char *);
196 static char *build_search_list (const struct path_prefix *, const char *,
197 bool, bool);
198 static void xputenv (const char *);
199 static void putenv_from_prefixes (const struct path_prefix *, const char *,
200 bool);
201 static int access_check (const char *, int);
202 static char *find_a_file (const struct path_prefix *, const char *, int, bool);
203 static void add_prefix (struct path_prefix *, const char *, const char *,
204 int, int, int);
205 static void add_sysrooted_prefix (struct path_prefix *, const char *,
206 const char *, int, int, int);
207 static char *skip_whitespace (char *);
208 static void delete_if_ordinary (const char *);
209 static void delete_temp_files (void);
210 static void delete_failure_queue (void);
211 static void clear_failure_queue (void);
212 static int check_live_switch (int, int);
213 static const char *handle_braces (const char *);
214 static inline bool input_suffix_matches (const char *, const char *);
215 static inline bool switch_matches (const char *, const char *, int);
216 static inline void mark_matching_switches (const char *, const char *, int);
217 static inline void process_marked_switches (void);
218 static const char *process_brace_body (const char *, const char *, const char *, int, int);
219 static const struct spec_function *lookup_spec_function (const char *);
220 static const char *eval_spec_function (const char *, const char *);
221 static const char *handle_spec_function (const char *, bool *);
222 static char *save_string (const char *, int);
223 static void set_collect_gcc_options (void);
224 static int do_spec_1 (const char *, int, const char *);
225 static int do_spec_2 (const char *);
226 static void do_option_spec (const char *, const char *);
227 static void do_self_spec (const char *);
228 static const char *find_file (const char *);
229 static int is_directory (const char *, bool);
230 static const char *validate_switches (const char *, bool);
231 static void validate_all_switches (void);
232 static inline void validate_switches_from_spec (const char *, bool);
233 static void give_switch (int, int);
234 static int used_arg (const char *, int);
235 static int default_arg (const char *, int);
236 static void set_multilib_dir (void);
237 static void print_multilib_info (void);
238 static void perror_with_name (const char *);
239 static void display_help (void);
240 static void add_preprocessor_option (const char *, int);
241 static void add_assembler_option (const char *, int);
242 static void add_linker_option (const char *, int);
243 static void process_command (unsigned int, struct cl_decoded_option *);
244 static int execute (void);
245 static void alloc_args (void);
246 static void clear_args (void);
247 static void fatal_signal (int);
248 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
249 static void init_gcc_specs (struct obstack *, const char *, const char *,
250 const char *);
251 #endif
252 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
253 static const char *convert_filename (const char *, int, int);
254 #endif
256 static const char *getenv_spec_function (int, const char **);
257 static const char *if_exists_spec_function (int, const char **);
258 static const char *if_exists_else_spec_function (int, const char **);
259 static const char *sanitize_spec_function (int, const char **);
260 static const char *replace_outfile_spec_function (int, const char **);
261 static const char *remove_outfile_spec_function (int, const char **);
262 static const char *version_compare_spec_function (int, const char **);
263 static const char *include_spec_function (int, const char **);
264 static const char *find_file_spec_function (int, const char **);
265 static const char *find_plugindir_spec_function (int, const char **);
266 static const char *print_asm_header_spec_function (int, const char **);
267 static const char *compare_debug_dump_opt_spec_function (int, const char **);
268 static const char *compare_debug_self_opt_spec_function (int, const char **);
269 static const char *compare_debug_auxbase_opt_spec_function (int, const char **);
270 static const char *pass_through_libs_spec_func (int, const char **);
271 static const char *replace_extension_spec_func (int, const char **);
272 static char *convert_white_space (char *);
274 /* The Specs Language
276 Specs are strings containing lines, each of which (if not blank)
277 is made up of a program name, and arguments separated by spaces.
278 The program name must be exact and start from root, since no path
279 is searched and it is unreliable to depend on the current working directory.
280 Redirection of input or output is not supported; the subprograms must
281 accept filenames saying what files to read and write.
283 In addition, the specs can contain %-sequences to substitute variable text
284 or for conditional text. Here is a table of all defined %-sequences.
285 Note that spaces are not generated automatically around the results of
286 expanding these sequences; therefore, you can concatenate them together
287 or with constant text in a single argument.
289 %% substitute one % into the program name or argument.
290 %i substitute the name of the input file being processed.
291 %b substitute the basename of the input file being processed.
292 This is the substring up to (and not including) the last period
293 and not including the directory unless -save-temps was specified
294 to put temporaries in a different location.
295 %B same as %b, but include the file suffix (text after the last period).
296 %gSUFFIX
297 substitute a file name that has suffix SUFFIX and is chosen
298 once per compilation, and mark the argument a la %d. To reduce
299 exposure to denial-of-service attacks, the file name is now
300 chosen in a way that is hard to predict even when previously
301 chosen file names are known. For example, `%g.s ... %g.o ... %g.s'
302 might turn into `ccUVUUAU.s ccXYAXZ12.o ccUVUUAU.s'. SUFFIX matches
303 the regexp "[.0-9A-Za-z]*%O"; "%O" is treated exactly as if it
304 had been pre-processed. Previously, %g was simply substituted
305 with a file name chosen once per compilation, without regard
306 to any appended suffix (which was therefore treated just like
307 ordinary text), making such attacks more likely to succeed.
308 %|SUFFIX
309 like %g, but if -pipe is in effect, expands simply to "-".
310 %mSUFFIX
311 like %g, but if -pipe is in effect, expands to nothing. (We have both
312 %| and %m to accommodate differences between system assemblers; see
313 the AS_NEEDS_DASH_FOR_PIPED_INPUT target macro.)
314 %uSUFFIX
315 like %g, but generates a new temporary file name even if %uSUFFIX
316 was already seen.
317 %USUFFIX
318 substitutes the last file name generated with %uSUFFIX, generating a
319 new one if there is no such last file name. In the absence of any
320 %uSUFFIX, this is just like %gSUFFIX, except they don't share
321 the same suffix "space", so `%g.s ... %U.s ... %g.s ... %U.s'
322 would involve the generation of two distinct file names, one
323 for each `%g.s' and another for each `%U.s'. Previously, %U was
324 simply substituted with a file name chosen for the previous %u,
325 without regard to any appended suffix.
326 %jSUFFIX
327 substitutes the name of the HOST_BIT_BUCKET, if any, and if it is
328 writable, and if save-temps is off; otherwise, substitute the name
329 of a temporary file, just like %u. This temporary file is not
330 meant for communication between processes, but rather as a junk
331 disposal mechanism.
332 %.SUFFIX
333 substitutes .SUFFIX for the suffixes of a matched switch's args when
334 it is subsequently output with %*. SUFFIX is terminated by the next
335 space or %.
336 %d marks the argument containing or following the %d as a
337 temporary file name, so that that file will be deleted if GCC exits
338 successfully. Unlike %g, this contributes no text to the argument.
339 %w marks the argument containing or following the %w as the
340 "output file" of this compilation. This puts the argument
341 into the sequence of arguments that %o will substitute later.
342 %V indicates that this compilation produces no "output file".
343 %W{...}
344 like %{...} but mark last argument supplied within
345 as a file to be deleted on failure.
346 %o substitutes the names of all the output files, with spaces
347 automatically placed around them. You should write spaces
348 around the %o as well or the results are undefined.
349 %o is for use in the specs for running the linker.
350 Input files whose names have no recognized suffix are not compiled
351 at all, but they are included among the output files, so they will
352 be linked.
353 %O substitutes the suffix for object files. Note that this is
354 handled specially when it immediately follows %g, %u, or %U
355 (with or without a suffix argument) because of the need for
356 those to form complete file names. The handling is such that
357 %O is treated exactly as if it had already been substituted,
358 except that %g, %u, and %U do not currently support additional
359 SUFFIX characters following %O as they would following, for
360 example, `.o'.
361 %I Substitute any of -iprefix (made from GCC_EXEC_PREFIX), -isysroot
362 (made from TARGET_SYSTEM_ROOT), -isystem (made from COMPILER_PATH
363 and -B options) and -imultilib as necessary.
364 %s current argument is the name of a library or startup file of some sort.
365 Search for that file in a standard list of directories
366 and substitute the full name found.
367 %eSTR Print STR as an error message. STR is terminated by a newline.
368 Use this when inconsistent options are detected.
369 %nSTR Print STR as a notice. STR is terminated by a newline.
370 %x{OPTION} Accumulate an option for %X.
371 %X Output the accumulated linker options specified by compilations.
372 %Y Output the accumulated assembler options specified by compilations.
373 %Z Output the accumulated preprocessor options specified by compilations.
374 %a process ASM_SPEC as a spec.
375 This allows config.h to specify part of the spec for running as.
376 %A process ASM_FINAL_SPEC as a spec. A capital A is actually
377 used here. This can be used to run a post-processor after the
378 assembler has done its job.
379 %D Dump out a -L option for each directory in startfile_prefixes.
380 If multilib_dir is set, extra entries are generated with it affixed.
381 %l process LINK_SPEC as a spec.
382 %L process LIB_SPEC as a spec.
383 %M Output multilib_os_dir.
384 %G process LIBGCC_SPEC as a spec.
385 %R Output the concatenation of target_system_root and
386 target_sysroot_suffix.
387 %S process STARTFILE_SPEC as a spec. A capital S is actually used here.
388 %E process ENDFILE_SPEC as a spec. A capital E is actually used here.
389 %C process CPP_SPEC as a spec.
390 %1 process CC1_SPEC as a spec.
391 %2 process CC1PLUS_SPEC as a spec.
392 %* substitute the variable part of a matched option. (See below.)
393 Note that each comma in the substituted string is replaced by
394 a single space. A space is appended after the last substition
395 unless there is more text in current sequence.
396 %<S remove all occurrences of -S from the command line.
397 Note - this command is position dependent. % commands in the
398 spec string before this one will see -S, % commands in the
399 spec string after this one will not.
400 %>S Similar to "%<S", but keep it in the GCC command line.
401 %<S* remove all occurrences of all switches beginning with -S from the
402 command line.
403 %:function(args)
404 Call the named function FUNCTION, passing it ARGS. ARGS is
405 first processed as a nested spec string, then split into an
406 argument vector in the usual fashion. The function returns
407 a string which is processed as if it had appeared literally
408 as part of the current spec.
409 %{S} substitutes the -S switch, if that switch was given to GCC.
410 If that switch was not specified, this substitutes nothing.
411 Here S is a metasyntactic variable.
412 %{S*} substitutes all the switches specified to GCC whose names start
413 with -S. This is used for -o, -I, etc; switches that take
414 arguments. GCC considers `-o foo' as being one switch whose
415 name starts with `o'. %{o*} would substitute this text,
416 including the space; thus, two arguments would be generated.
417 %{S*&T*} likewise, but preserve order of S and T options (the order
418 of S and T in the spec is not significant). Can be any number
419 of ampersand-separated variables; for each the wild card is
420 optional. Useful for CPP as %{D*&U*&A*}.
422 %{S:X} substitutes X, if the -S switch was given to GCC.
423 %{!S:X} substitutes X, if the -S switch was NOT given to GCC.
424 %{S*:X} substitutes X if one or more switches whose names start
425 with -S was given to GCC. Normally X is substituted only
426 once, no matter how many such switches appeared. However,
427 if %* appears somewhere in X, then X will be substituted
428 once for each matching switch, with the %* replaced by the
429 part of that switch that matched the '*'. A space will be
430 appended after the last substition unless there is more
431 text in current sequence.
432 %{.S:X} substitutes X, if processing a file with suffix S.
433 %{!.S:X} substitutes X, if NOT processing a file with suffix S.
434 %{,S:X} substitutes X, if processing a file which will use spec S.
435 %{!,S:X} substitutes X, if NOT processing a file which will use spec S.
437 %{S|T:X} substitutes X if either -S or -T was given to GCC. This may be
438 combined with '!', '.', ',', and '*' as above binding stronger
439 than the OR.
440 If %* appears in X, all of the alternatives must be starred, and
441 only the first matching alternative is substituted.
442 %{%:function(args):X}
443 Call function named FUNCTION with args ARGS. If the function
444 returns non-NULL, then X is substituted, if it returns
445 NULL, it isn't substituted.
446 %{S:X; if S was given to GCC, substitutes X;
447 T:Y; else if T was given to GCC, substitutes Y;
448 :D} else substitutes D. There can be as many clauses as you need.
449 This may be combined with '.', '!', ',', '|', and '*' as above.
451 %(Spec) processes a specification defined in a specs file as *Spec:
453 The conditional text X in a %{S:X} or similar construct may contain
454 other nested % constructs or spaces, or even newlines. They are
455 processed as usual, as described above. Trailing white space in X is
456 ignored. White space may also appear anywhere on the left side of the
457 colon in these constructs, except between . or * and the corresponding
458 word.
460 The -O, -f, -g, -m, and -W switches are handled specifically in these
461 constructs. If another value of -O or the negated form of a -f, -m, or
462 -W switch is found later in the command line, the earlier switch
463 value is ignored, except with {S*} where S is just one letter; this
464 passes all matching options.
466 The character | at the beginning of the predicate text is used to indicate
467 that a command should be piped to the following command, but only if -pipe
468 is specified.
470 Note that it is built into GCC which switches take arguments and which
471 do not. You might think it would be useful to generalize this to
472 allow each compiler's spec to say which switches take arguments. But
473 this cannot be done in a consistent fashion. GCC cannot even decide
474 which input files have been specified without knowing which switches
475 take arguments, and it must know which input files to compile in order
476 to tell which compilers to run.
478 GCC also knows implicitly that arguments starting in `-l' are to be
479 treated as compiler output files, and passed to the linker in their
480 proper position among the other output files. */
482 /* Define the macros used for specs %a, %l, %L, %S, %C, %1. */
484 /* config.h can define ASM_SPEC to provide extra args to the assembler
485 or extra switch-translations. */
486 #ifndef ASM_SPEC
487 #define ASM_SPEC ""
488 #endif
490 /* config.h can define ASM_FINAL_SPEC to run a post processor after
491 the assembler has run. */
492 #ifndef ASM_FINAL_SPEC
493 #define ASM_FINAL_SPEC \
494 "%{gsplit-dwarf: \n\
495 objcopy --extract-dwo \
496 %{c:%{o*:%*}%{!o*:%b%O}}%{!c:%U%O} \
497 %{c:%{o*:%:replace-extension(%{o*:%*} .dwo)}%{!o*:%b.dwo}}%{!c:%b.dwo} \n\
498 objcopy --strip-dwo \
499 %{c:%{o*:%*}%{!o*:%b%O}}%{!c:%U%O} \
501 #endif
503 /* config.h can define CPP_SPEC to provide extra args to the C preprocessor
504 or extra switch-translations. */
505 #ifndef CPP_SPEC
506 #define CPP_SPEC ""
507 #endif
509 /* config.h can define CC1_SPEC to provide extra args to cc1 and cc1plus
510 or extra switch-translations. */
511 #ifndef CC1_SPEC
512 #define CC1_SPEC ""
513 #endif
515 /* config.h can define CC1PLUS_SPEC to provide extra args to cc1plus
516 or extra switch-translations. */
517 #ifndef CC1PLUS_SPEC
518 #define CC1PLUS_SPEC ""
519 #endif
521 /* config.h can define LINK_SPEC to provide extra args to the linker
522 or extra switch-translations. */
523 #ifndef LINK_SPEC
524 #define LINK_SPEC ""
525 #endif
527 /* config.h can define LIB_SPEC to override the default libraries. */
528 #ifndef LIB_SPEC
529 #define LIB_SPEC "%{!shared:%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}}"
530 #endif
532 /* When using -fsplit-stack we need to wrap pthread_create, in order
533 to initialize the stack guard. We always use wrapping, rather than
534 shared library ordering, and we keep the wrapper function in
535 libgcc. This is not yet a real spec, though it could become one;
536 it is currently just stuffed into LINK_SPEC. FIXME: This wrapping
537 only works with GNU ld and gold. */
538 #define STACK_SPLIT_SPEC " %{fsplit-stack: --wrap=pthread_create}"
540 #ifndef LIBASAN_SPEC
541 #define STATIC_LIBASAN_LIBS \
542 " %{static-libasan:%:include(libsanitizer.spec)%(link_libasan)}"
543 #ifdef LIBASAN_EARLY_SPEC
544 #define LIBASAN_SPEC STATIC_LIBASAN_LIBS
545 #elif defined(HAVE_LD_STATIC_DYNAMIC)
546 #define LIBASAN_SPEC "%{static-libasan:" LD_STATIC_OPTION \
547 "} -lasan %{static-libasan:" LD_DYNAMIC_OPTION "}" \
548 STATIC_LIBASAN_LIBS
549 #else
550 #define LIBASAN_SPEC "-lasan" STATIC_LIBASAN_LIBS
551 #endif
552 #endif
554 #ifndef LIBASAN_EARLY_SPEC
555 #define LIBASAN_EARLY_SPEC ""
556 #endif
558 #ifndef LIBTSAN_SPEC
559 #define STATIC_LIBTSAN_LIBS \
560 " %{static-libtsan:%:include(libsanitizer.spec)%(link_libtsan)}"
561 #ifdef LIBTSAN_EARLY_SPEC
562 #define LIBTSAN_SPEC STATIC_LIBTSAN_LIBS
563 #elif defined(HAVE_LD_STATIC_DYNAMIC)
564 #define LIBTSAN_SPEC "%{static-libtsan:" LD_STATIC_OPTION \
565 "} -ltsan %{static-libtsan:" LD_DYNAMIC_OPTION "}" \
566 STATIC_LIBTSAN_LIBS
567 #else
568 #define LIBTSAN_SPEC "-ltsan" STATIC_LIBTSAN_LIBS
569 #endif
570 #endif
572 #ifndef LIBTSAN_EARLY_SPEC
573 #define LIBTSAN_EARLY_SPEC ""
574 #endif
576 #ifndef LIBLSAN_SPEC
577 #define STATIC_LIBLSAN_LIBS \
578 " %{static-liblsan:%:include(libsanitizer.spec)%(link_liblsan)}"
579 #ifdef HAVE_LD_STATIC_DYNAMIC
580 #define LIBLSAN_SPEC "%{!shared:%{static-liblsan:" LD_STATIC_OPTION \
581 "} -llsan %{static-liblsan:" LD_DYNAMIC_OPTION "}" \
582 STATIC_LIBLSAN_LIBS "}"
583 #else
584 #define LIBLSAN_SPEC "%{!shared:-llsan" STATIC_LIBLSAN_LIBS "}"
585 #endif
586 #endif
588 #ifndef LIBUBSAN_SPEC
589 #define STATIC_LIBUBSAN_LIBS \
590 " %{static-libubsan:%:include(libsanitizer.spec)%(link_libubsan)}"
591 #ifdef HAVE_LD_STATIC_DYNAMIC
592 #define LIBUBSAN_SPEC "%{static-libubsan:" LD_STATIC_OPTION \
593 "} -lubsan %{static-libubsan:" LD_DYNAMIC_OPTION "}" \
594 STATIC_LIBUBSAN_LIBS
595 #else
596 #define LIBUBSAN_SPEC "-lubsan" STATIC_LIBUBSAN_LIBS
597 #endif
598 #endif
600 /* config.h can define LIBGCC_SPEC to override how and when libgcc.a is
601 included. */
602 #ifndef LIBGCC_SPEC
603 #if defined(REAL_LIBGCC_SPEC)
604 #define LIBGCC_SPEC REAL_LIBGCC_SPEC
605 #elif defined(LINK_LIBGCC_SPECIAL_1)
606 /* Have gcc do the search for libgcc.a. */
607 #define LIBGCC_SPEC "libgcc.a%s"
608 #else
609 #define LIBGCC_SPEC "-lgcc"
610 #endif
611 #endif
613 /* config.h can define STARTFILE_SPEC to override the default crt0 files. */
614 #ifndef STARTFILE_SPEC
615 #define STARTFILE_SPEC \
616 "%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
617 #endif
619 /* config.h can define ENDFILE_SPEC to override the default crtn files. */
620 #ifndef ENDFILE_SPEC
621 #define ENDFILE_SPEC ""
622 #endif
624 #ifndef LINKER_NAME
625 #define LINKER_NAME "collect2"
626 #endif
628 #ifdef HAVE_AS_DEBUG_PREFIX_MAP
629 #define ASM_MAP " %{fdebug-prefix-map=*:--debug-prefix-map %*}"
630 #else
631 #define ASM_MAP ""
632 #endif
634 /* Define ASM_DEBUG_SPEC to be a spec suitable for translating '-g'
635 to the assembler. */
636 #ifndef ASM_DEBUG_SPEC
637 # if defined(DBX_DEBUGGING_INFO) && defined(DWARF2_DEBUGGING_INFO) \
638 && defined(HAVE_AS_GDWARF2_DEBUG_FLAG) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
639 # define ASM_DEBUG_SPEC \
640 (PREFERRED_DEBUGGING_TYPE == DBX_DEBUG \
641 ? "%{!g0:%{gdwarf*:--gdwarf2}%{!gdwarf*:%{g*:--gstabs}}}" ASM_MAP \
642 : "%{!g0:%{gstabs*:--gstabs}%{!gstabs*:%{g*:--gdwarf2}}}" ASM_MAP)
643 # else
644 # if defined(DBX_DEBUGGING_INFO) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
645 # define ASM_DEBUG_SPEC "%{g*:%{!g0:--gstabs}}" ASM_MAP
646 # endif
647 # if defined(DWARF2_DEBUGGING_INFO) && defined(HAVE_AS_GDWARF2_DEBUG_FLAG)
648 # define ASM_DEBUG_SPEC "%{g*:%{!g0:--gdwarf2}}" ASM_MAP
649 # endif
650 # endif
651 #endif
652 #ifndef ASM_DEBUG_SPEC
653 # define ASM_DEBUG_SPEC ""
654 #endif
656 /* Here is the spec for running the linker, after compiling all files. */
658 /* This is overridable by the target in case they need to specify the
659 -lgcc and -lc order specially, yet not require them to override all
660 of LINK_COMMAND_SPEC. */
661 #ifndef LINK_GCC_C_SEQUENCE_SPEC
662 #define LINK_GCC_C_SEQUENCE_SPEC "%G %L %G"
663 #endif
665 #ifndef LINK_SSP_SPEC
666 #ifdef TARGET_LIBC_PROVIDES_SSP
667 #define LINK_SSP_SPEC "%{fstack-protector:}"
668 #else
669 #define LINK_SSP_SPEC "%{fstack-protector|fstack-protector-strong|fstack-protector-all:-lssp_nonshared -lssp}"
670 #endif
671 #endif
673 #ifndef LINK_PIE_SPEC
674 #ifdef HAVE_LD_PIE
675 #define LINK_PIE_SPEC "%{pie:-pie} "
676 #else
677 #define LINK_PIE_SPEC "%{pie:} "
678 #endif
679 #endif
681 #ifndef LINK_BUILDID_SPEC
682 # if defined(HAVE_LD_BUILDID) && defined(ENABLE_LD_BUILDID)
683 # define LINK_BUILDID_SPEC "%{!r:--build-id} "
684 # endif
685 #endif
687 /* Conditional to test whether the LTO plugin is used or not.
688 FIXME: For slim LTO we will need to enable plugin unconditionally. This
689 still cause problems with PLUGIN_LD != LD and when plugin is built but
690 not useable. For GCC 4.6 we don't support slim LTO and thus we can enable
691 plugin only when LTO is enabled. We still honor explicit
692 -fuse-linker-plugin if the linker used understands -plugin. */
694 /* The linker has some plugin support. */
695 #if HAVE_LTO_PLUGIN > 0
696 /* The linker used has full plugin support, use LTO plugin by default. */
697 #if HAVE_LTO_PLUGIN == 2
698 #define PLUGIN_COND "!fno-use-linker-plugin:%{flto|flto=*|fuse-linker-plugin"
699 #define PLUGIN_COND_CLOSE "}"
700 #else
701 /* The linker used has limited plugin support, use LTO plugin with explicit
702 -fuse-linker-plugin. */
703 #define PLUGIN_COND "fuse-linker-plugin"
704 #define PLUGIN_COND_CLOSE ""
705 #endif
706 #define LINK_PLUGIN_SPEC \
707 "%{"PLUGIN_COND": \
708 -plugin %(linker_plugin_file) \
709 -plugin-opt=%(lto_wrapper) \
710 -plugin-opt=-fresolution=%u.res \
711 %{!nostdlib:%{!nodefaultlibs:%:pass-through-libs(%(link_gcc_c_sequence))}} \
712 }"PLUGIN_COND_CLOSE
713 #else
714 /* The linker used doesn't support -plugin, reject -fuse-linker-plugin. */
715 #define LINK_PLUGIN_SPEC "%{fuse-linker-plugin:\
716 %e-fuse-linker-plugin is not supported in this configuration}"
717 #endif
719 /* Linker command line options for -fsanitize= early on the command line. */
720 #ifndef SANITIZER_EARLY_SPEC
721 #define SANITIZER_EARLY_SPEC "\
722 %{!nostdlib:%{!nodefaultlibs:%{%:sanitize(address):" LIBASAN_EARLY_SPEC "} \
723 %{%:sanitize(thread):" LIBTSAN_EARLY_SPEC "}}}"
724 #endif
726 /* Linker command line options for -fsanitize= late on the command line. */
727 #ifndef SANITIZER_SPEC
728 #define SANITIZER_SPEC "\
729 %{!nostdlib:%{!nodefaultlibs:%{%:sanitize(address):" LIBASAN_SPEC "\
730 %{static:%ecannot specify -static with -fsanitize=address}\
731 %{%:sanitize(thread):%e-fsanitize=address is incompatible with -fsanitize=thread}}\
732 %{%:sanitize(thread):" LIBTSAN_SPEC "\
733 %{!pie:%{!shared:%e-fsanitize=thread linking must be done with -pie or -shared}}}\
734 %{%:sanitize(undefined):" LIBUBSAN_SPEC "}\
735 %{%:sanitize(leak):" LIBLSAN_SPEC "}}}"
736 #endif
738 /* This is the spec to use, once the code for creating the vtable
739 verification runtime library, libvtv.so, has been created. Currently
740 the vtable verification runtime functions are in libstdc++, so we use
741 the spec just below this one. */
742 #ifndef VTABLE_VERIFICATION_SPEC
743 #define VTABLE_VERIFICATION_SPEC "\
744 %{!nostdlib:%{fvtable-verify=std: -lvtv -u_vtable_map_vars_start -u_vtable_map_vars_end}\
745 %{fvtable-verify=preinit: -lvtv -u_vtable_map_vars_start -u_vtable_map_vars_end}}"
746 #endif
748 /* -u* was put back because both BSD and SysV seem to support it. */
749 /* %{static:} simply prevents an error message if the target machine
750 doesn't handle -static. */
751 /* We want %{T*} after %{L*} and %D so that it can be used to specify linker
752 scripts which exist in user specified directories, or in standard
753 directories. */
754 /* We pass any -flto flags on to the linker, which is expected
755 to understand them. In practice, this means it had better be collect2. */
756 /* %{e*} includes -export-dynamic; see comment in common.opt. */
757 #ifndef LINK_COMMAND_SPEC
758 #define LINK_COMMAND_SPEC "\
759 %{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
760 %(linker) " \
761 LINK_PLUGIN_SPEC \
762 "%{flto|flto=*:%<fcompare-debug*} \
763 %{flto} %{flto=*} %l " LINK_PIE_SPEC \
764 "%{fuse-ld=*:-fuse-ld=%*}\
765 %X %{o*} %{e*} %{N} %{n} %{r}\
766 %{s} %{t} %{u*} %{z} %{Z} %{!nostdlib:%{!nostartfiles:%S}} " VTABLE_VERIFICATION_SPEC " \
767 %{static:} %{L*} %(mfwrap) %(link_libgcc) " SANITIZER_EARLY_SPEC " %o\
768 %{fopenacc|fopenmp|ftree-parallelize-loops=*:%:include(libgomp.spec)%(link_gomp)}\
769 %{fgnu-tm:%:include(libitm.spec)%(link_itm)}\
770 %(mflib) " STACK_SPLIT_SPEC "\
771 %{fprofile-arcs|fprofile-generate*|coverage:-lgcov} " SANITIZER_SPEC " \
772 %{!nostdlib:%{!nodefaultlibs:%(link_ssp) %(link_gcc_c_sequence)}}\
773 %{!nostdlib:%{!nostartfiles:%E}} %{T*} }}}}}}"
774 #endif
776 #ifndef LINK_LIBGCC_SPEC
777 /* Generate -L options for startfile prefix list. */
778 # define LINK_LIBGCC_SPEC "%D"
779 #endif
781 #ifndef STARTFILE_PREFIX_SPEC
782 # define STARTFILE_PREFIX_SPEC ""
783 #endif
785 #ifndef SYSROOT_SPEC
786 # define SYSROOT_SPEC "--sysroot=%R"
787 #endif
789 #ifndef SYSROOT_SUFFIX_SPEC
790 # define SYSROOT_SUFFIX_SPEC ""
791 #endif
793 #ifndef SYSROOT_HEADERS_SUFFIX_SPEC
794 # define SYSROOT_HEADERS_SUFFIX_SPEC ""
795 #endif
797 static const char *asm_debug = ASM_DEBUG_SPEC;
798 static const char *cpp_spec = CPP_SPEC;
799 static const char *cc1_spec = CC1_SPEC;
800 static const char *cc1plus_spec = CC1PLUS_SPEC;
801 static const char *link_gcc_c_sequence_spec = LINK_GCC_C_SEQUENCE_SPEC;
802 static const char *link_ssp_spec = LINK_SSP_SPEC;
803 static const char *asm_spec = ASM_SPEC;
804 static const char *asm_final_spec = ASM_FINAL_SPEC;
805 static const char *link_spec = LINK_SPEC;
806 static const char *lib_spec = LIB_SPEC;
807 static const char *link_gomp_spec = "";
808 static const char *libgcc_spec = LIBGCC_SPEC;
809 static const char *endfile_spec = ENDFILE_SPEC;
810 static const char *startfile_spec = STARTFILE_SPEC;
811 static const char *linker_name_spec = LINKER_NAME;
812 static const char *linker_plugin_file_spec = "";
813 static const char *lto_wrapper_spec = "";
814 static const char *lto_gcc_spec = "";
815 static const char *link_command_spec = LINK_COMMAND_SPEC;
816 static const char *link_libgcc_spec = LINK_LIBGCC_SPEC;
817 static const char *startfile_prefix_spec = STARTFILE_PREFIX_SPEC;
818 static const char *sysroot_spec = SYSROOT_SPEC;
819 static const char *sysroot_suffix_spec = SYSROOT_SUFFIX_SPEC;
820 static const char *sysroot_hdrs_suffix_spec = SYSROOT_HEADERS_SUFFIX_SPEC;
821 static const char *self_spec = "";
823 /* Standard options to cpp, cc1, and as, to reduce duplication in specs.
824 There should be no need to override these in target dependent files,
825 but we need to copy them to the specs file so that newer versions
826 of the GCC driver can correctly drive older tool chains with the
827 appropriate -B options. */
829 /* When cpplib handles traditional preprocessing, get rid of this, and
830 call cc1 (or cc1obj in objc/lang-specs.h) from the main specs so
831 that we default the front end language better. */
832 static const char *trad_capable_cpp =
833 "cc1 -E %{traditional|traditional-cpp:-traditional-cpp}";
835 /* We don't wrap .d files in %W{} since a missing .d file, and
836 therefore no dependency entry, confuses make into thinking a .o
837 file that happens to exist is up-to-date. */
838 static const char *cpp_unique_options =
839 "%{!Q:-quiet} %{nostdinc*} %{C} %{CC} %{v} %{I*&F*} %{P} %I\
840 %{MD:-MD %{!o:%b.d}%{o*:%.d%*}}\
841 %{MMD:-MMD %{!o:%b.d}%{o*:%.d%*}}\
842 %{M} %{MM} %{MF*} %{MG} %{MP} %{MQ*} %{MT*}\
843 %{!E:%{!M:%{!MM:%{!MT:%{!MQ:%{MD|MMD:%{o*:-MQ %*}}}}}}}\
844 %{remap} %{g3|ggdb3|gstabs3|gcoff3|gxcoff3|gvms3:-dD}\
845 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
846 %{H} %C %{D*&U*&A*} %{i*} %Z %i\
847 %{E|M|MM:%W{o*}}";
849 /* This contains cpp options which are common with cc1_options and are passed
850 only when preprocessing only to avoid duplication. We pass the cc1 spec
851 options to the preprocessor so that it the cc1 spec may manipulate
852 options used to set target flags. Those special target flags settings may
853 in turn cause preprocessor symbols to be defined specially. */
854 static const char *cpp_options =
855 "%(cpp_unique_options) %1 %{m*} %{std*&ansi&trigraphs} %{W*&pedantic*} %{w}\
856 %{f*} %{g*:%{!g0:%{g*} %{!fno-working-directory:-fworking-directory}}} %{O*}\
857 %{undef} %{save-temps*:-fpch-preprocess}";
859 /* This contains cpp options which are not passed when the preprocessor
860 output will be used by another program. */
861 static const char *cpp_debug_options = "%{d*}";
863 /* NB: This is shared amongst all front-ends, except for Ada. */
864 static const char *cc1_options =
865 "%{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
866 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
867 %1 %{!Q:-quiet} %{!dumpbase:-dumpbase %B} %{d*} %{m*} %{aux-info*}\
868 %{fcompare-debug-second:%:compare-debug-auxbase-opt(%b)} \
869 %{!fcompare-debug-second:%{c|S:%{o*:-auxbase-strip %*}%{!o*:-auxbase %b}}}%{!c:%{!S:-auxbase %b}} \
870 %{g*} %{O*} %{W*&pedantic*} %{w} %{std*&ansi&trigraphs}\
871 %{v:-version} %{pg:-p} %{p} %{f*} %{undef}\
872 %{Qn:-fno-ident} %{Qy:} %{-help:--help}\
873 %{-target-help:--target-help}\
874 %{-version:--version}\
875 %{-help=*:--help=%*}\
876 %{!fsyntax-only:%{S:%W{o*}%{!o*:-o %b.s}}}\
877 %{fsyntax-only:-o %j} %{-param*}\
878 %{coverage:-fprofile-arcs -ftest-coverage}";
880 static const char *asm_options =
881 "%{-target-help:%:print-asm-header()} "
882 #if HAVE_GNU_AS
883 /* If GNU AS is used, then convert -w (no warnings), -I, and -v
884 to the assembler equivalents. */
885 "%{v} %{w:-W} %{I*} "
886 #endif
887 "%a %Y %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}";
889 static const char *invoke_as =
890 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
891 "%{!fwpa*:\
892 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
893 %{!S:-o %|.s |\n as %(asm_options) %|.s %A }\
895 #else
896 "%{!fwpa*:\
897 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
898 %{!S:-o %|.s |\n as %(asm_options) %m.s %A }\
900 #endif
902 /* Some compilers have limits on line lengths, and the multilib_select
903 and/or multilib_matches strings can be very long, so we build them at
904 run time. */
905 static struct obstack multilib_obstack;
906 static const char *multilib_select;
907 static const char *multilib_matches;
908 static const char *multilib_defaults;
909 static const char *multilib_exclusions;
910 static const char *multilib_reuse;
912 /* Check whether a particular argument is a default argument. */
914 #ifndef MULTILIB_DEFAULTS
915 #define MULTILIB_DEFAULTS { "" }
916 #endif
918 static const char *const multilib_defaults_raw[] = MULTILIB_DEFAULTS;
920 #ifndef DRIVER_SELF_SPECS
921 #define DRIVER_SELF_SPECS ""
922 #endif
924 /* Linking to libgomp implies pthreads. This is particularly important
925 for targets that use different start files and suchlike. */
926 #ifndef GOMP_SELF_SPECS
927 #define GOMP_SELF_SPECS "%{fopenacc|fopenmp|ftree-parallelize-loops=*: " \
928 "-pthread}"
929 #endif
931 /* Likewise for -fgnu-tm. */
932 #ifndef GTM_SELF_SPECS
933 #define GTM_SELF_SPECS "%{fgnu-tm: -pthread}"
934 #endif
936 static const char *const driver_self_specs[] = {
937 "%{fdump-final-insns:-fdump-final-insns=.} %<fdump-final-insns",
938 DRIVER_SELF_SPECS, CONFIGURE_SPECS, GOMP_SELF_SPECS, GTM_SELF_SPECS
941 #ifndef OPTION_DEFAULT_SPECS
942 #define OPTION_DEFAULT_SPECS { "", "" }
943 #endif
945 struct default_spec
947 const char *name;
948 const char *spec;
951 static const struct default_spec
952 option_default_specs[] = { OPTION_DEFAULT_SPECS };
954 struct user_specs
956 struct user_specs *next;
957 const char *filename;
960 static struct user_specs *user_specs_head, *user_specs_tail;
963 /* Record the mapping from file suffixes for compilation specs. */
965 struct compiler
967 const char *suffix; /* Use this compiler for input files
968 whose names end in this suffix. */
970 const char *spec; /* To use this compiler, run this spec. */
972 const char *cpp_spec; /* If non-NULL, substitute this spec
973 for `%C', rather than the usual
974 cpp_spec. */
975 const int combinable; /* If nonzero, compiler can deal with
976 multiple source files at once (IMA). */
977 const int needs_preprocessing; /* If nonzero, source files need to
978 be run through a preprocessor. */
981 /* Pointer to a vector of `struct compiler' that gives the spec for
982 compiling a file, based on its suffix.
983 A file that does not end in any of these suffixes will be passed
984 unchanged to the loader and nothing else will be done to it.
986 An entry containing two 0s is used to terminate the vector.
988 If multiple entries match a file, the last matching one is used. */
990 static struct compiler *compilers;
992 /* Number of entries in `compilers', not counting the null terminator. */
994 static int n_compilers;
996 /* The default list of file name suffixes and their compilation specs. */
998 static const struct compiler default_compilers[] =
1000 /* Add lists of suffixes of known languages here. If those languages
1001 were not present when we built the driver, we will hit these copies
1002 and be given a more meaningful error than "file not used since
1003 linking is not done". */
1004 {".m", "#Objective-C", 0, 0, 0}, {".mi", "#Objective-C", 0, 0, 0},
1005 {".mm", "#Objective-C++", 0, 0, 0}, {".M", "#Objective-C++", 0, 0, 0},
1006 {".mii", "#Objective-C++", 0, 0, 0},
1007 {".cc", "#C++", 0, 0, 0}, {".cxx", "#C++", 0, 0, 0},
1008 {".cpp", "#C++", 0, 0, 0}, {".cp", "#C++", 0, 0, 0},
1009 {".c++", "#C++", 0, 0, 0}, {".C", "#C++", 0, 0, 0},
1010 {".CPP", "#C++", 0, 0, 0}, {".ii", "#C++", 0, 0, 0},
1011 {".ads", "#Ada", 0, 0, 0}, {".adb", "#Ada", 0, 0, 0},
1012 {".f", "#Fortran", 0, 0, 0}, {".F", "#Fortran", 0, 0, 0},
1013 {".for", "#Fortran", 0, 0, 0}, {".FOR", "#Fortran", 0, 0, 0},
1014 {".ftn", "#Fortran", 0, 0, 0}, {".FTN", "#Fortran", 0, 0, 0},
1015 {".fpp", "#Fortran", 0, 0, 0}, {".FPP", "#Fortran", 0, 0, 0},
1016 {".f90", "#Fortran", 0, 0, 0}, {".F90", "#Fortran", 0, 0, 0},
1017 {".f95", "#Fortran", 0, 0, 0}, {".F95", "#Fortran", 0, 0, 0},
1018 {".f03", "#Fortran", 0, 0, 0}, {".F03", "#Fortran", 0, 0, 0},
1019 {".f08", "#Fortran", 0, 0, 0}, {".F08", "#Fortran", 0, 0, 0},
1020 {".r", "#Ratfor", 0, 0, 0},
1021 {".p", "#Pascal", 0, 0, 0}, {".pas", "#Pascal", 0, 0, 0},
1022 {".java", "#Java", 0, 0, 0}, {".class", "#Java", 0, 0, 0},
1023 {".zip", "#Java", 0, 0, 0}, {".jar", "#Java", 0, 0, 0},
1024 {".go", "#Go", 0, 1, 0},
1025 /* Next come the entries for C. */
1026 {".c", "@c", 0, 0, 1},
1027 {"@c",
1028 /* cc1 has an integrated ISO C preprocessor. We should invoke the
1029 external preprocessor if -save-temps is given. */
1030 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
1031 %{!E:%{!M:%{!MM:\
1032 %{traditional:\
1033 %eGNU C no longer supports -traditional without -E}\
1034 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
1035 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
1036 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
1037 %(cc1_options)}\
1038 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
1039 cc1 %(cpp_unique_options) %(cc1_options)}}}\
1040 %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 1},
1041 {"-",
1042 "%{!E:%e-E or -x required when input is from standard input}\
1043 %(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)", 0, 0, 0},
1044 {".h", "@c-header", 0, 0, 0},
1045 {"@c-header",
1046 /* cc1 has an integrated ISO C preprocessor. We should invoke the
1047 external preprocessor if -save-temps is given. */
1048 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
1049 %{!E:%{!M:%{!MM:\
1050 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
1051 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
1052 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
1053 %(cc1_options)\
1054 %{!fdump-ada-spec*:-o %g.s %{!o*:--output-pch=%i.gch}\
1055 %W{o*:--output-pch=%*}}%V}\
1056 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
1057 cc1 %(cpp_unique_options) %(cc1_options)\
1058 %{!fdump-ada-spec*:-o %g.s %{!o*:--output-pch=%i.gch}\
1059 %W{o*:--output-pch=%*}}%V}}}}}}", 0, 0, 0},
1060 {".i", "@cpp-output", 0, 0, 0},
1061 {"@cpp-output",
1062 "%{!M:%{!MM:%{!E:cc1 -fpreprocessed %i %(cc1_options) %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 0},
1063 {".s", "@assembler", 0, 0, 0},
1064 {"@assembler",
1065 "%{!M:%{!MM:%{!E:%{!S:as %(asm_debug) %(asm_options) %i %A }}}}", 0, 0, 0},
1066 {".sx", "@assembler-with-cpp", 0, 0, 0},
1067 {".S", "@assembler-with-cpp", 0, 0, 0},
1068 {"@assembler-with-cpp",
1069 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
1070 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
1071 %{E|M|MM:%(cpp_debug_options)}\
1072 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
1073 as %(asm_debug) %(asm_options) %|.s %A }}}}"
1074 #else
1075 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
1076 %{E|M|MM:%(cpp_debug_options)}\
1077 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
1078 as %(asm_debug) %(asm_options) %m.s %A }}}}"
1079 #endif
1080 , 0, 0, 0},
1082 #include "specs.h"
1083 /* Mark end of table. */
1084 {0, 0, 0, 0, 0}
1087 /* Number of elements in default_compilers, not counting the terminator. */
1089 static const int n_default_compilers = ARRAY_SIZE (default_compilers) - 1;
1091 typedef char *char_p; /* For DEF_VEC_P. */
1093 /* A vector of options to give to the linker.
1094 These options are accumulated by %x,
1095 and substituted into the linker command with %X. */
1096 static vec<char_p> linker_options;
1098 /* A vector of options to give to the assembler.
1099 These options are accumulated by -Wa,
1100 and substituted into the assembler command with %Y. */
1101 static vec<char_p> assembler_options;
1103 /* A vector of options to give to the preprocessor.
1104 These options are accumulated by -Wp,
1105 and substituted into the preprocessor command with %Z. */
1106 static vec<char_p> preprocessor_options;
1108 static char *
1109 skip_whitespace (char *p)
1111 while (1)
1113 /* A fully-blank line is a delimiter in the SPEC file and shouldn't
1114 be considered whitespace. */
1115 if (p[0] == '\n' && p[1] == '\n' && p[2] == '\n')
1116 return p + 1;
1117 else if (*p == '\n' || *p == ' ' || *p == '\t')
1118 p++;
1119 else if (*p == '#')
1121 while (*p != '\n')
1122 p++;
1123 p++;
1125 else
1126 break;
1129 return p;
1131 /* Structures to keep track of prefixes to try when looking for files. */
1133 struct prefix_list
1135 const char *prefix; /* String to prepend to the path. */
1136 struct prefix_list *next; /* Next in linked list. */
1137 int require_machine_suffix; /* Don't use without machine_suffix. */
1138 /* 2 means try both machine_suffix and just_machine_suffix. */
1139 int priority; /* Sort key - priority within list. */
1140 int os_multilib; /* 1 if OS multilib scheme should be used,
1141 0 for GCC multilib scheme. */
1144 struct path_prefix
1146 struct prefix_list *plist; /* List of prefixes to try */
1147 int max_len; /* Max length of a prefix in PLIST */
1148 const char *name; /* Name of this list (used in config stuff) */
1151 /* List of prefixes to try when looking for executables. */
1153 static struct path_prefix exec_prefixes = { 0, 0, "exec" };
1155 /* List of prefixes to try when looking for startup (crt0) files. */
1157 static struct path_prefix startfile_prefixes = { 0, 0, "startfile" };
1159 /* List of prefixes to try when looking for include files. */
1161 static struct path_prefix include_prefixes = { 0, 0, "include" };
1163 /* Suffix to attach to directories searched for commands.
1164 This looks like `MACHINE/VERSION/'. */
1166 static const char *machine_suffix = 0;
1168 /* Suffix to attach to directories searched for commands.
1169 This is just `MACHINE/'. */
1171 static const char *just_machine_suffix = 0;
1173 /* Adjusted value of GCC_EXEC_PREFIX envvar. */
1175 static const char *gcc_exec_prefix;
1177 /* Adjusted value of standard_libexec_prefix. */
1179 static const char *gcc_libexec_prefix;
1181 /* Default prefixes to attach to command names. */
1183 #ifndef STANDARD_STARTFILE_PREFIX_1
1184 #define STANDARD_STARTFILE_PREFIX_1 "/lib/"
1185 #endif
1186 #ifndef STANDARD_STARTFILE_PREFIX_2
1187 #define STANDARD_STARTFILE_PREFIX_2 "/usr/lib/"
1188 #endif
1190 #ifdef CROSS_DIRECTORY_STRUCTURE /* Don't use these prefixes for a cross compiler. */
1191 #undef MD_EXEC_PREFIX
1192 #undef MD_STARTFILE_PREFIX
1193 #undef MD_STARTFILE_PREFIX_1
1194 #endif
1196 /* If no prefixes defined, use the null string, which will disable them. */
1197 #ifndef MD_EXEC_PREFIX
1198 #define MD_EXEC_PREFIX ""
1199 #endif
1200 #ifndef MD_STARTFILE_PREFIX
1201 #define MD_STARTFILE_PREFIX ""
1202 #endif
1203 #ifndef MD_STARTFILE_PREFIX_1
1204 #define MD_STARTFILE_PREFIX_1 ""
1205 #endif
1207 /* These directories are locations set at configure-time based on the
1208 --prefix option provided to configure. Their initializers are
1209 defined in Makefile.in. These paths are not *directly* used when
1210 gcc_exec_prefix is set because, in that case, we know where the
1211 compiler has been installed, and use paths relative to that
1212 location instead. */
1213 static const char *const standard_exec_prefix = STANDARD_EXEC_PREFIX;
1214 static const char *const standard_libexec_prefix = STANDARD_LIBEXEC_PREFIX;
1215 static const char *const standard_bindir_prefix = STANDARD_BINDIR_PREFIX;
1216 static const char *const standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
1218 /* For native compilers, these are well-known paths containing
1219 components that may be provided by the system. For cross
1220 compilers, these paths are not used. */
1221 static const char *md_exec_prefix = MD_EXEC_PREFIX;
1222 static const char *md_startfile_prefix = MD_STARTFILE_PREFIX;
1223 static const char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
1224 static const char *const standard_startfile_prefix_1
1225 = STANDARD_STARTFILE_PREFIX_1;
1226 static const char *const standard_startfile_prefix_2
1227 = STANDARD_STARTFILE_PREFIX_2;
1229 /* A relative path to be used in finding the location of tools
1230 relative to the driver. */
1231 static const char *const tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
1233 /* Subdirectory to use for locating libraries. Set by
1234 set_multilib_dir based on the compilation options. */
1236 static const char *multilib_dir;
1238 /* Subdirectory to use for locating libraries in OS conventions. Set by
1239 set_multilib_dir based on the compilation options. */
1241 static const char *multilib_os_dir;
1243 /* Subdirectory to use for locating libraries in multiarch conventions. Set by
1244 set_multilib_dir based on the compilation options. */
1246 static const char *multiarch_dir;
1248 /* Structure to keep track of the specs that have been defined so far.
1249 These are accessed using %(specname) in a compiler or link
1250 spec. */
1252 struct spec_list
1254 /* The following 2 fields must be first */
1255 /* to allow EXTRA_SPECS to be initialized */
1256 const char *name; /* name of the spec. */
1257 const char *ptr; /* available ptr if no static pointer */
1259 /* The following fields are not initialized */
1260 /* by EXTRA_SPECS */
1261 const char **ptr_spec; /* pointer to the spec itself. */
1262 struct spec_list *next; /* Next spec in linked list. */
1263 int name_len; /* length of the name */
1264 bool user_p; /* whether string come from file spec. */
1265 bool alloc_p; /* whether string was allocated */
1268 #define INIT_STATIC_SPEC(NAME,PTR) \
1269 { NAME, NULL, PTR, (struct spec_list *) 0, sizeof (NAME) - 1, false, false }
1271 /* List of statically defined specs. */
1272 static struct spec_list static_specs[] =
1274 INIT_STATIC_SPEC ("asm", &asm_spec),
1275 INIT_STATIC_SPEC ("asm_debug", &asm_debug),
1276 INIT_STATIC_SPEC ("asm_final", &asm_final_spec),
1277 INIT_STATIC_SPEC ("asm_options", &asm_options),
1278 INIT_STATIC_SPEC ("invoke_as", &invoke_as),
1279 INIT_STATIC_SPEC ("cpp", &cpp_spec),
1280 INIT_STATIC_SPEC ("cpp_options", &cpp_options),
1281 INIT_STATIC_SPEC ("cpp_debug_options", &cpp_debug_options),
1282 INIT_STATIC_SPEC ("cpp_unique_options", &cpp_unique_options),
1283 INIT_STATIC_SPEC ("trad_capable_cpp", &trad_capable_cpp),
1284 INIT_STATIC_SPEC ("cc1", &cc1_spec),
1285 INIT_STATIC_SPEC ("cc1_options", &cc1_options),
1286 INIT_STATIC_SPEC ("cc1plus", &cc1plus_spec),
1287 INIT_STATIC_SPEC ("link_gcc_c_sequence", &link_gcc_c_sequence_spec),
1288 INIT_STATIC_SPEC ("link_ssp", &link_ssp_spec),
1289 INIT_STATIC_SPEC ("endfile", &endfile_spec),
1290 INIT_STATIC_SPEC ("link", &link_spec),
1291 INIT_STATIC_SPEC ("lib", &lib_spec),
1292 INIT_STATIC_SPEC ("link_gomp", &link_gomp_spec),
1293 INIT_STATIC_SPEC ("libgcc", &libgcc_spec),
1294 INIT_STATIC_SPEC ("startfile", &startfile_spec),
1295 INIT_STATIC_SPEC ("cross_compile", &cross_compile),
1296 INIT_STATIC_SPEC ("version", &compiler_version),
1297 INIT_STATIC_SPEC ("multilib", &multilib_select),
1298 INIT_STATIC_SPEC ("multilib_defaults", &multilib_defaults),
1299 INIT_STATIC_SPEC ("multilib_extra", &multilib_extra),
1300 INIT_STATIC_SPEC ("multilib_matches", &multilib_matches),
1301 INIT_STATIC_SPEC ("multilib_exclusions", &multilib_exclusions),
1302 INIT_STATIC_SPEC ("multilib_options", &multilib_options),
1303 INIT_STATIC_SPEC ("multilib_reuse", &multilib_reuse),
1304 INIT_STATIC_SPEC ("linker", &linker_name_spec),
1305 INIT_STATIC_SPEC ("linker_plugin_file", &linker_plugin_file_spec),
1306 INIT_STATIC_SPEC ("lto_wrapper", &lto_wrapper_spec),
1307 INIT_STATIC_SPEC ("lto_gcc", &lto_gcc_spec),
1308 INIT_STATIC_SPEC ("link_libgcc", &link_libgcc_spec),
1309 INIT_STATIC_SPEC ("md_exec_prefix", &md_exec_prefix),
1310 INIT_STATIC_SPEC ("md_startfile_prefix", &md_startfile_prefix),
1311 INIT_STATIC_SPEC ("md_startfile_prefix_1", &md_startfile_prefix_1),
1312 INIT_STATIC_SPEC ("startfile_prefix_spec", &startfile_prefix_spec),
1313 INIT_STATIC_SPEC ("sysroot_spec", &sysroot_spec),
1314 INIT_STATIC_SPEC ("sysroot_suffix_spec", &sysroot_suffix_spec),
1315 INIT_STATIC_SPEC ("sysroot_hdrs_suffix_spec", &sysroot_hdrs_suffix_spec),
1316 INIT_STATIC_SPEC ("self_spec", &self_spec),
1319 #ifdef EXTRA_SPECS /* additional specs needed */
1320 /* Structure to keep track of just the first two args of a spec_list.
1321 That is all that the EXTRA_SPECS macro gives us. */
1322 struct spec_list_1
1324 const char *const name;
1325 const char *const ptr;
1328 static const struct spec_list_1 extra_specs_1[] = { EXTRA_SPECS };
1329 static struct spec_list *extra_specs = (struct spec_list *) 0;
1330 #endif
1332 /* List of dynamically allocates specs that have been defined so far. */
1334 static struct spec_list *specs = (struct spec_list *) 0;
1336 /* List of static spec functions. */
1338 static const struct spec_function static_spec_functions[] =
1340 { "getenv", getenv_spec_function },
1341 { "if-exists", if_exists_spec_function },
1342 { "if-exists-else", if_exists_else_spec_function },
1343 { "sanitize", sanitize_spec_function },
1344 { "replace-outfile", replace_outfile_spec_function },
1345 { "remove-outfile", remove_outfile_spec_function },
1346 { "version-compare", version_compare_spec_function },
1347 { "include", include_spec_function },
1348 { "find-file", find_file_spec_function },
1349 { "find-plugindir", find_plugindir_spec_function },
1350 { "print-asm-header", print_asm_header_spec_function },
1351 { "compare-debug-dump-opt", compare_debug_dump_opt_spec_function },
1352 { "compare-debug-self-opt", compare_debug_self_opt_spec_function },
1353 { "compare-debug-auxbase-opt", compare_debug_auxbase_opt_spec_function },
1354 { "pass-through-libs", pass_through_libs_spec_func },
1355 { "replace-extension", replace_extension_spec_func },
1356 #ifdef EXTRA_SPEC_FUNCTIONS
1357 EXTRA_SPEC_FUNCTIONS
1358 #endif
1359 { 0, 0 }
1362 static int processing_spec_function;
1364 /* Add appropriate libgcc specs to OBSTACK, taking into account
1365 various permutations of -shared-libgcc, -shared, and such. */
1367 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1369 #ifndef USE_LD_AS_NEEDED
1370 #define USE_LD_AS_NEEDED 0
1371 #endif
1373 static void
1374 init_gcc_specs (struct obstack *obstack, const char *shared_name,
1375 const char *static_name, const char *eh_name)
1377 char *buf;
1379 buf = concat ("%{static|static-libgcc:", static_name, " ", eh_name, "}"
1380 "%{!static:%{!static-libgcc:"
1381 #if USE_LD_AS_NEEDED
1382 "%{!shared-libgcc:",
1383 static_name, " " LD_AS_NEEDED_OPTION " ",
1384 shared_name, " " LD_NO_AS_NEEDED_OPTION
1386 "%{shared-libgcc:",
1387 shared_name, "%{!shared: ", static_name, "}"
1389 #else
1390 "%{!shared:"
1391 "%{!shared-libgcc:", static_name, " ", eh_name, "}"
1392 "%{shared-libgcc:", shared_name, " ", static_name, "}"
1394 #ifdef LINK_EH_SPEC
1395 "%{shared:"
1396 "%{shared-libgcc:", shared_name, "}"
1397 "%{!shared-libgcc:", static_name, "}"
1399 #else
1400 "%{shared:", shared_name, "}"
1401 #endif
1402 #endif
1403 "}}", NULL);
1405 obstack_grow (obstack, buf, strlen (buf));
1406 free (buf);
1408 #endif /* ENABLE_SHARED_LIBGCC */
1410 /* Initialize the specs lookup routines. */
1412 static void
1413 init_spec (void)
1415 struct spec_list *next = (struct spec_list *) 0;
1416 struct spec_list *sl = (struct spec_list *) 0;
1417 int i;
1419 if (specs)
1420 return; /* Already initialized. */
1422 if (verbose_flag)
1423 fnotice (stderr, "Using built-in specs.\n");
1425 #ifdef EXTRA_SPECS
1426 extra_specs = XCNEWVEC (struct spec_list, ARRAY_SIZE (extra_specs_1));
1428 for (i = ARRAY_SIZE (extra_specs_1) - 1; i >= 0; i--)
1430 sl = &extra_specs[i];
1431 sl->name = extra_specs_1[i].name;
1432 sl->ptr = extra_specs_1[i].ptr;
1433 sl->next = next;
1434 sl->name_len = strlen (sl->name);
1435 sl->ptr_spec = &sl->ptr;
1436 next = sl;
1438 #endif
1440 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1442 sl = &static_specs[i];
1443 sl->next = next;
1444 next = sl;
1447 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1448 /* ??? If neither -shared-libgcc nor --static-libgcc was
1449 seen, then we should be making an educated guess. Some proposed
1450 heuristics for ELF include:
1452 (1) If "-Wl,--export-dynamic", then it's a fair bet that the
1453 program will be doing dynamic loading, which will likely
1454 need the shared libgcc.
1456 (2) If "-ldl", then it's also a fair bet that we're doing
1457 dynamic loading.
1459 (3) For each ET_DYN we're linking against (either through -lfoo
1460 or /some/path/foo.so), check to see whether it or one of
1461 its dependencies depends on a shared libgcc.
1463 (4) If "-shared"
1465 If the runtime is fixed to look for program headers instead
1466 of calling __register_frame_info at all, for each object,
1467 use the shared libgcc if any EH symbol referenced.
1469 If crtstuff is fixed to not invoke __register_frame_info
1470 automatically, for each object, use the shared libgcc if
1471 any non-empty unwind section found.
1473 Doing any of this probably requires invoking an external program to
1474 do the actual object file scanning. */
1476 const char *p = libgcc_spec;
1477 int in_sep = 1;
1479 /* Transform the extant libgcc_spec into one that uses the shared libgcc
1480 when given the proper command line arguments. */
1481 while (*p)
1483 if (in_sep && *p == '-' && strncmp (p, "-lgcc", 5) == 0)
1485 init_gcc_specs (&obstack,
1486 "-lgcc_s"
1487 #ifdef USE_LIBUNWIND_EXCEPTIONS
1488 " -lunwind"
1489 #endif
1491 "-lgcc",
1492 "-lgcc_eh"
1493 #ifdef USE_LIBUNWIND_EXCEPTIONS
1494 # ifdef HAVE_LD_STATIC_DYNAMIC
1495 " %{!static:" LD_STATIC_OPTION "} -lunwind"
1496 " %{!static:" LD_DYNAMIC_OPTION "}"
1497 # else
1498 " -lunwind"
1499 # endif
1500 #endif
1503 p += 5;
1504 in_sep = 0;
1506 else if (in_sep && *p == 'l' && strncmp (p, "libgcc.a%s", 10) == 0)
1508 /* Ug. We don't know shared library extensions. Hope that
1509 systems that use this form don't do shared libraries. */
1510 init_gcc_specs (&obstack,
1511 "-lgcc_s",
1512 "libgcc.a%s",
1513 "libgcc_eh.a%s"
1514 #ifdef USE_LIBUNWIND_EXCEPTIONS
1515 " -lunwind"
1516 #endif
1518 p += 10;
1519 in_sep = 0;
1521 else
1523 obstack_1grow (&obstack, *p);
1524 in_sep = (*p == ' ');
1525 p += 1;
1529 obstack_1grow (&obstack, '\0');
1530 libgcc_spec = XOBFINISH (&obstack, const char *);
1532 #endif
1533 #ifdef USE_AS_TRADITIONAL_FORMAT
1534 /* Prepend "--traditional-format" to whatever asm_spec we had before. */
1536 static const char tf[] = "--traditional-format ";
1537 obstack_grow (&obstack, tf, sizeof (tf) - 1);
1538 obstack_grow0 (&obstack, asm_spec, strlen (asm_spec));
1539 asm_spec = XOBFINISH (&obstack, const char *);
1541 #endif
1543 #if defined LINK_EH_SPEC || defined LINK_BUILDID_SPEC || \
1544 defined LINKER_HASH_STYLE
1545 # ifdef LINK_BUILDID_SPEC
1546 /* Prepend LINK_BUILDID_SPEC to whatever link_spec we had before. */
1547 obstack_grow (&obstack, LINK_BUILDID_SPEC, sizeof (LINK_BUILDID_SPEC) - 1);
1548 # endif
1549 # ifdef LINK_EH_SPEC
1550 /* Prepend LINK_EH_SPEC to whatever link_spec we had before. */
1551 obstack_grow (&obstack, LINK_EH_SPEC, sizeof (LINK_EH_SPEC) - 1);
1552 # endif
1553 # ifdef LINKER_HASH_STYLE
1554 /* Prepend --hash-style=LINKER_HASH_STYLE to whatever link_spec we had
1555 before. */
1557 static const char hash_style[] = "--hash-style=";
1558 obstack_grow (&obstack, hash_style, sizeof (hash_style) - 1);
1559 obstack_grow (&obstack, LINKER_HASH_STYLE, sizeof (LINKER_HASH_STYLE) - 1);
1560 obstack_1grow (&obstack, ' ');
1562 # endif
1563 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
1564 link_spec = XOBFINISH (&obstack, const char *);
1565 #endif
1567 specs = sl;
1570 /* Change the value of spec NAME to SPEC. If SPEC is empty, then the spec is
1571 removed; If the spec starts with a + then SPEC is added to the end of the
1572 current spec. */
1574 static void
1575 set_spec (const char *name, const char *spec, bool user_p)
1577 struct spec_list *sl;
1578 const char *old_spec;
1579 int name_len = strlen (name);
1580 int i;
1582 /* If this is the first call, initialize the statically allocated specs. */
1583 if (!specs)
1585 struct spec_list *next = (struct spec_list *) 0;
1586 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1588 sl = &static_specs[i];
1589 sl->next = next;
1590 next = sl;
1592 specs = sl;
1595 /* See if the spec already exists. */
1596 for (sl = specs; sl; sl = sl->next)
1597 if (name_len == sl->name_len && !strcmp (sl->name, name))
1598 break;
1600 if (!sl)
1602 /* Not found - make it. */
1603 sl = XNEW (struct spec_list);
1604 sl->name = xstrdup (name);
1605 sl->name_len = name_len;
1606 sl->ptr_spec = &sl->ptr;
1607 sl->alloc_p = 0;
1608 *(sl->ptr_spec) = "";
1609 sl->next = specs;
1610 specs = sl;
1613 old_spec = *(sl->ptr_spec);
1614 *(sl->ptr_spec) = ((spec[0] == '+' && ISSPACE ((unsigned char)spec[1]))
1615 ? concat (old_spec, spec + 1, NULL)
1616 : xstrdup (spec));
1618 #ifdef DEBUG_SPECS
1619 if (verbose_flag)
1620 fnotice (stderr, "Setting spec %s to '%s'\n\n", name, *(sl->ptr_spec));
1621 #endif
1623 /* Free the old spec. */
1624 if (old_spec && sl->alloc_p)
1625 free (CONST_CAST (char *, old_spec));
1627 sl->user_p = user_p;
1628 sl->alloc_p = true;
1631 /* Accumulate a command (program name and args), and run it. */
1633 typedef const char *const_char_p; /* For DEF_VEC_P. */
1635 /* Vector of pointers to arguments in the current line of specifications. */
1637 static vec<const_char_p> argbuf;
1639 /* Position in the argbuf vector containing the name of the output file
1640 (the value associated with the "-o" flag). */
1642 static int have_o_argbuf_index = 0;
1644 /* Were the options -c, -S or -E passed. */
1645 static int have_c = 0;
1647 /* Was the option -o passed. */
1648 static int have_o = 0;
1650 /* This is the list of suffixes and codes (%g/%u/%U/%j) and the associated
1651 temp file. If the HOST_BIT_BUCKET is used for %j, no entry is made for
1652 it here. */
1654 static struct temp_name {
1655 const char *suffix; /* suffix associated with the code. */
1656 int length; /* strlen (suffix). */
1657 int unique; /* Indicates whether %g or %u/%U was used. */
1658 const char *filename; /* associated filename. */
1659 int filename_length; /* strlen (filename). */
1660 struct temp_name *next;
1661 } *temp_names;
1663 /* Number of commands executed so far. */
1665 static int execution_count;
1667 /* Number of commands that exited with a signal. */
1669 static int signal_count;
1671 /* Allocate the argument vector. */
1673 static void
1674 alloc_args (void)
1676 argbuf.create (10);
1679 /* Clear out the vector of arguments (after a command is executed). */
1681 static void
1682 clear_args (void)
1684 argbuf.truncate (0);
1687 /* Add one argument to the vector at the end.
1688 This is done when a space is seen or at the end of the line.
1689 If DELETE_ALWAYS is nonzero, the arg is a filename
1690 and the file should be deleted eventually.
1691 If DELETE_FAILURE is nonzero, the arg is a filename
1692 and the file should be deleted if this compilation fails. */
1694 static void
1695 store_arg (const char *arg, int delete_always, int delete_failure)
1697 argbuf.safe_push (arg);
1699 if (strcmp (arg, "-o") == 0)
1700 have_o_argbuf_index = argbuf.length ();
1701 if (delete_always || delete_failure)
1703 const char *p;
1704 /* If the temporary file we should delete is specified as
1705 part of a joined argument extract the filename. */
1706 if (arg[0] == '-'
1707 && (p = strrchr (arg, '=')))
1708 arg = p + 1;
1709 record_temp_file (arg, delete_always, delete_failure);
1713 /* Load specs from a file name named FILENAME, replacing occurrences of
1714 various different types of line-endings, \r\n, \n\r and just \r, with
1715 a single \n. */
1717 static char *
1718 load_specs (const char *filename)
1720 int desc;
1721 int readlen;
1722 struct stat statbuf;
1723 char *buffer;
1724 char *buffer_p;
1725 char *specs;
1726 char *specs_p;
1728 if (verbose_flag)
1729 fnotice (stderr, "Reading specs from %s\n", filename);
1731 /* Open and stat the file. */
1732 desc = open (filename, O_RDONLY, 0);
1733 if (desc < 0)
1734 pfatal_with_name (filename);
1735 if (stat (filename, &statbuf) < 0)
1736 pfatal_with_name (filename);
1738 /* Read contents of file into BUFFER. */
1739 buffer = XNEWVEC (char, statbuf.st_size + 1);
1740 readlen = read (desc, buffer, (unsigned) statbuf.st_size);
1741 if (readlen < 0)
1742 pfatal_with_name (filename);
1743 buffer[readlen] = 0;
1744 close (desc);
1746 specs = XNEWVEC (char, readlen + 1);
1747 specs_p = specs;
1748 for (buffer_p = buffer; buffer_p && *buffer_p; buffer_p++)
1750 int skip = 0;
1751 char c = *buffer_p;
1752 if (c == '\r')
1754 if (buffer_p > buffer && *(buffer_p - 1) == '\n') /* \n\r */
1755 skip = 1;
1756 else if (*(buffer_p + 1) == '\n') /* \r\n */
1757 skip = 1;
1758 else /* \r */
1759 c = '\n';
1761 if (! skip)
1762 *specs_p++ = c;
1764 *specs_p = '\0';
1766 free (buffer);
1767 return (specs);
1770 /* Read compilation specs from a file named FILENAME,
1771 replacing the default ones.
1773 A suffix which starts with `*' is a definition for
1774 one of the machine-specific sub-specs. The "suffix" should be
1775 *asm, *cc1, *cpp, *link, *startfile, etc.
1776 The corresponding spec is stored in asm_spec, etc.,
1777 rather than in the `compilers' vector.
1779 Anything invalid in the file is a fatal error. */
1781 static void
1782 read_specs (const char *filename, bool main_p, bool user_p)
1784 char *buffer;
1785 char *p;
1787 buffer = load_specs (filename);
1789 /* Scan BUFFER for specs, putting them in the vector. */
1790 p = buffer;
1791 while (1)
1793 char *suffix;
1794 char *spec;
1795 char *in, *out, *p1, *p2, *p3;
1797 /* Advance P in BUFFER to the next nonblank nocomment line. */
1798 p = skip_whitespace (p);
1799 if (*p == 0)
1800 break;
1802 /* Is this a special command that starts with '%'? */
1803 /* Don't allow this for the main specs file, since it would
1804 encourage people to overwrite it. */
1805 if (*p == '%' && !main_p)
1807 p1 = p;
1808 while (*p && *p != '\n')
1809 p++;
1811 /* Skip '\n'. */
1812 p++;
1814 if (!strncmp (p1, "%include", sizeof ("%include") - 1)
1815 && (p1[sizeof "%include" - 1] == ' '
1816 || p1[sizeof "%include" - 1] == '\t'))
1818 char *new_filename;
1820 p1 += sizeof ("%include");
1821 while (*p1 == ' ' || *p1 == '\t')
1822 p1++;
1824 if (*p1++ != '<' || p[-2] != '>')
1825 fatal_error ("specs %%include syntax malformed after "
1826 "%ld characters",
1827 (long) (p1 - buffer + 1));
1829 p[-2] = '\0';
1830 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
1831 read_specs (new_filename ? new_filename : p1, false, user_p);
1832 continue;
1834 else if (!strncmp (p1, "%include_noerr", sizeof "%include_noerr" - 1)
1835 && (p1[sizeof "%include_noerr" - 1] == ' '
1836 || p1[sizeof "%include_noerr" - 1] == '\t'))
1838 char *new_filename;
1840 p1 += sizeof "%include_noerr";
1841 while (*p1 == ' ' || *p1 == '\t')
1842 p1++;
1844 if (*p1++ != '<' || p[-2] != '>')
1845 fatal_error ("specs %%include syntax malformed after "
1846 "%ld characters",
1847 (long) (p1 - buffer + 1));
1849 p[-2] = '\0';
1850 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
1851 if (new_filename)
1852 read_specs (new_filename, false, user_p);
1853 else if (verbose_flag)
1854 fnotice (stderr, "could not find specs file %s\n", p1);
1855 continue;
1857 else if (!strncmp (p1, "%rename", sizeof "%rename" - 1)
1858 && (p1[sizeof "%rename" - 1] == ' '
1859 || p1[sizeof "%rename" - 1] == '\t'))
1861 int name_len;
1862 struct spec_list *sl;
1863 struct spec_list *newsl;
1865 /* Get original name. */
1866 p1 += sizeof "%rename";
1867 while (*p1 == ' ' || *p1 == '\t')
1868 p1++;
1870 if (! ISALPHA ((unsigned char) *p1))
1871 fatal_error ("specs %%rename syntax malformed after "
1872 "%ld characters",
1873 (long) (p1 - buffer));
1875 p2 = p1;
1876 while (*p2 && !ISSPACE ((unsigned char) *p2))
1877 p2++;
1879 if (*p2 != ' ' && *p2 != '\t')
1880 fatal_error ("specs %%rename syntax malformed after "
1881 "%ld characters",
1882 (long) (p2 - buffer));
1884 name_len = p2 - p1;
1885 *p2++ = '\0';
1886 while (*p2 == ' ' || *p2 == '\t')
1887 p2++;
1889 if (! ISALPHA ((unsigned char) *p2))
1890 fatal_error ("specs %%rename syntax malformed after "
1891 "%ld characters",
1892 (long) (p2 - buffer));
1894 /* Get new spec name. */
1895 p3 = p2;
1896 while (*p3 && !ISSPACE ((unsigned char) *p3))
1897 p3++;
1899 if (p3 != p - 1)
1900 fatal_error ("specs %%rename syntax malformed after "
1901 "%ld characters",
1902 (long) (p3 - buffer));
1903 *p3 = '\0';
1905 for (sl = specs; sl; sl = sl->next)
1906 if (name_len == sl->name_len && !strcmp (sl->name, p1))
1907 break;
1909 if (!sl)
1910 fatal_error ("specs %s spec was not found to be renamed", p1);
1912 if (strcmp (p1, p2) == 0)
1913 continue;
1915 for (newsl = specs; newsl; newsl = newsl->next)
1916 if (strcmp (newsl->name, p2) == 0)
1917 fatal_error ("%s: attempt to rename spec %qs to "
1918 "already defined spec %qs",
1919 filename, p1, p2);
1921 if (verbose_flag)
1923 fnotice (stderr, "rename spec %s to %s\n", p1, p2);
1924 #ifdef DEBUG_SPECS
1925 fnotice (stderr, "spec is '%s'\n\n", *(sl->ptr_spec));
1926 #endif
1929 set_spec (p2, *(sl->ptr_spec), user_p);
1930 if (sl->alloc_p)
1931 free (CONST_CAST (char *, *(sl->ptr_spec)));
1933 *(sl->ptr_spec) = "";
1934 sl->alloc_p = 0;
1935 continue;
1937 else
1938 fatal_error ("specs unknown %% command after %ld characters",
1939 (long) (p1 - buffer));
1942 /* Find the colon that should end the suffix. */
1943 p1 = p;
1944 while (*p1 && *p1 != ':' && *p1 != '\n')
1945 p1++;
1947 /* The colon shouldn't be missing. */
1948 if (*p1 != ':')
1949 fatal_error ("specs file malformed after %ld characters",
1950 (long) (p1 - buffer));
1952 /* Skip back over trailing whitespace. */
1953 p2 = p1;
1954 while (p2 > buffer && (p2[-1] == ' ' || p2[-1] == '\t'))
1955 p2--;
1957 /* Copy the suffix to a string. */
1958 suffix = save_string (p, p2 - p);
1959 /* Find the next line. */
1960 p = skip_whitespace (p1 + 1);
1961 if (p[1] == 0)
1962 fatal_error ("specs file malformed after %ld characters",
1963 (long) (p - buffer));
1965 p1 = p;
1966 /* Find next blank line or end of string. */
1967 while (*p1 && !(*p1 == '\n' && (p1[1] == '\n' || p1[1] == '\0')))
1968 p1++;
1970 /* Specs end at the blank line and do not include the newline. */
1971 spec = save_string (p, p1 - p);
1972 p = p1;
1974 /* Delete backslash-newline sequences from the spec. */
1975 in = spec;
1976 out = spec;
1977 while (*in != 0)
1979 if (in[0] == '\\' && in[1] == '\n')
1980 in += 2;
1981 else if (in[0] == '#')
1982 while (*in && *in != '\n')
1983 in++;
1985 else
1986 *out++ = *in++;
1988 *out = 0;
1990 if (suffix[0] == '*')
1992 if (! strcmp (suffix, "*link_command"))
1993 link_command_spec = spec;
1994 else
1995 set_spec (suffix + 1, spec, user_p);
1997 else
1999 /* Add this pair to the vector. */
2000 compilers
2001 = XRESIZEVEC (struct compiler, compilers, n_compilers + 2);
2003 compilers[n_compilers].suffix = suffix;
2004 compilers[n_compilers].spec = spec;
2005 n_compilers++;
2006 memset (&compilers[n_compilers], 0, sizeof compilers[n_compilers]);
2009 if (*suffix == 0)
2010 link_command_spec = spec;
2013 if (link_command_spec == 0)
2014 fatal_error ("spec file has no spec for linking");
2017 /* Record the names of temporary files we tell compilers to write,
2018 and delete them at the end of the run. */
2020 /* This is the common prefix we use to make temp file names.
2021 It is chosen once for each run of this program.
2022 It is substituted into a spec by %g or %j.
2023 Thus, all temp file names contain this prefix.
2024 In practice, all temp file names start with this prefix.
2026 This prefix comes from the envvar TMPDIR if it is defined;
2027 otherwise, from the P_tmpdir macro if that is defined;
2028 otherwise, in /usr/tmp or /tmp;
2029 or finally the current directory if all else fails. */
2031 static const char *temp_filename;
2033 /* Length of the prefix. */
2035 static int temp_filename_length;
2037 /* Define the list of temporary files to delete. */
2039 struct temp_file
2041 const char *name;
2042 struct temp_file *next;
2045 /* Queue of files to delete on success or failure of compilation. */
2046 static struct temp_file *always_delete_queue;
2047 /* Queue of files to delete on failure of compilation. */
2048 static struct temp_file *failure_delete_queue;
2050 /* Record FILENAME as a file to be deleted automatically.
2051 ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
2052 otherwise delete it in any case.
2053 FAIL_DELETE nonzero means delete it if a compilation step fails;
2054 otherwise delete it in any case. */
2056 void
2057 record_temp_file (const char *filename, int always_delete, int fail_delete)
2059 char *const name = xstrdup (filename);
2061 if (always_delete)
2063 struct temp_file *temp;
2064 for (temp = always_delete_queue; temp; temp = temp->next)
2065 if (! filename_cmp (name, temp->name))
2066 goto already1;
2068 temp = XNEW (struct temp_file);
2069 temp->next = always_delete_queue;
2070 temp->name = name;
2071 always_delete_queue = temp;
2073 already1:;
2076 if (fail_delete)
2078 struct temp_file *temp;
2079 for (temp = failure_delete_queue; temp; temp = temp->next)
2080 if (! filename_cmp (name, temp->name))
2082 free (name);
2083 goto already2;
2086 temp = XNEW (struct temp_file);
2087 temp->next = failure_delete_queue;
2088 temp->name = name;
2089 failure_delete_queue = temp;
2091 already2:;
2095 /* Delete all the temporary files whose names we previously recorded. */
2097 #ifndef DELETE_IF_ORDINARY
2098 #define DELETE_IF_ORDINARY(NAME,ST,VERBOSE_FLAG) \
2099 do \
2101 if (stat (NAME, &ST) >= 0 && S_ISREG (ST.st_mode)) \
2102 if (unlink (NAME) < 0) \
2103 if (VERBOSE_FLAG) \
2104 perror_with_name (NAME); \
2105 } while (0)
2106 #endif
2108 static void
2109 delete_if_ordinary (const char *name)
2111 struct stat st;
2112 #ifdef DEBUG
2113 int i, c;
2115 printf ("Delete %s? (y or n) ", name);
2116 fflush (stdout);
2117 i = getchar ();
2118 if (i != '\n')
2119 while ((c = getchar ()) != '\n' && c != EOF)
2122 if (i == 'y' || i == 'Y')
2123 #endif /* DEBUG */
2124 DELETE_IF_ORDINARY (name, st, verbose_flag);
2127 static void
2128 delete_temp_files (void)
2130 struct temp_file *temp;
2132 for (temp = always_delete_queue; temp; temp = temp->next)
2133 delete_if_ordinary (temp->name);
2134 always_delete_queue = 0;
2137 /* Delete all the files to be deleted on error. */
2139 static void
2140 delete_failure_queue (void)
2142 struct temp_file *temp;
2144 for (temp = failure_delete_queue; temp; temp = temp->next)
2145 delete_if_ordinary (temp->name);
2148 static void
2149 clear_failure_queue (void)
2151 failure_delete_queue = 0;
2154 /* Call CALLBACK for each path in PATHS, breaking out early if CALLBACK
2155 returns non-NULL.
2156 If DO_MULTI is true iterate over the paths twice, first with multilib
2157 suffix then without, otherwise iterate over the paths once without
2158 adding a multilib suffix. When DO_MULTI is true, some attempt is made
2159 to avoid visiting the same path twice, but we could do better. For
2160 instance, /usr/lib/../lib is considered different from /usr/lib.
2161 At least EXTRA_SPACE chars past the end of the path passed to
2162 CALLBACK are available for use by the callback.
2163 CALLBACK_INFO allows extra parameters to be passed to CALLBACK.
2165 Returns the value returned by CALLBACK. */
2167 static void *
2168 for_each_path (const struct path_prefix *paths,
2169 bool do_multi,
2170 size_t extra_space,
2171 void *(*callback) (char *, void *),
2172 void *callback_info)
2174 struct prefix_list *pl;
2175 const char *multi_dir = NULL;
2176 const char *multi_os_dir = NULL;
2177 const char *multiarch_suffix = NULL;
2178 const char *multi_suffix;
2179 const char *just_multi_suffix;
2180 char *path = NULL;
2181 void *ret = NULL;
2182 bool skip_multi_dir = false;
2183 bool skip_multi_os_dir = false;
2185 multi_suffix = machine_suffix;
2186 just_multi_suffix = just_machine_suffix;
2187 if (do_multi && multilib_dir && strcmp (multilib_dir, ".") != 0)
2189 multi_dir = concat (multilib_dir, dir_separator_str, NULL);
2190 multi_suffix = concat (multi_suffix, multi_dir, NULL);
2191 just_multi_suffix = concat (just_multi_suffix, multi_dir, NULL);
2193 if (do_multi && multilib_os_dir && strcmp (multilib_os_dir, ".") != 0)
2194 multi_os_dir = concat (multilib_os_dir, dir_separator_str, NULL);
2195 if (multiarch_dir)
2196 multiarch_suffix = concat (multiarch_dir, dir_separator_str, NULL);
2198 while (1)
2200 size_t multi_dir_len = 0;
2201 size_t multi_os_dir_len = 0;
2202 size_t multiarch_len = 0;
2203 size_t suffix_len;
2204 size_t just_suffix_len;
2205 size_t len;
2207 if (multi_dir)
2208 multi_dir_len = strlen (multi_dir);
2209 if (multi_os_dir)
2210 multi_os_dir_len = strlen (multi_os_dir);
2211 if (multiarch_suffix)
2212 multiarch_len = strlen (multiarch_suffix);
2213 suffix_len = strlen (multi_suffix);
2214 just_suffix_len = strlen (just_multi_suffix);
2216 if (path == NULL)
2218 len = paths->max_len + extra_space + 1;
2219 len += MAX (MAX (suffix_len, multi_os_dir_len), multiarch_len);
2220 path = XNEWVEC (char, len);
2223 for (pl = paths->plist; pl != 0; pl = pl->next)
2225 len = strlen (pl->prefix);
2226 memcpy (path, pl->prefix, len);
2228 /* Look first in MACHINE/VERSION subdirectory. */
2229 if (!skip_multi_dir)
2231 memcpy (path + len, multi_suffix, suffix_len + 1);
2232 ret = callback (path, callback_info);
2233 if (ret)
2234 break;
2237 /* Some paths are tried with just the machine (ie. target)
2238 subdir. This is used for finding as, ld, etc. */
2239 if (!skip_multi_dir
2240 && pl->require_machine_suffix == 2)
2242 memcpy (path + len, just_multi_suffix, just_suffix_len + 1);
2243 ret = callback (path, callback_info);
2244 if (ret)
2245 break;
2248 /* Now try the multiarch path. */
2249 if (!skip_multi_dir
2250 && !pl->require_machine_suffix && multiarch_dir)
2252 memcpy (path + len, multiarch_suffix, multiarch_len + 1);
2253 ret = callback (path, callback_info);
2254 if (ret)
2255 break;
2258 /* Now try the base path. */
2259 if (!pl->require_machine_suffix
2260 && !(pl->os_multilib ? skip_multi_os_dir : skip_multi_dir))
2262 const char *this_multi;
2263 size_t this_multi_len;
2265 if (pl->os_multilib)
2267 this_multi = multi_os_dir;
2268 this_multi_len = multi_os_dir_len;
2270 else
2272 this_multi = multi_dir;
2273 this_multi_len = multi_dir_len;
2276 if (this_multi_len)
2277 memcpy (path + len, this_multi, this_multi_len + 1);
2278 else
2279 path[len] = '\0';
2281 ret = callback (path, callback_info);
2282 if (ret)
2283 break;
2286 if (pl)
2287 break;
2289 if (multi_dir == NULL && multi_os_dir == NULL)
2290 break;
2292 /* Run through the paths again, this time without multilibs.
2293 Don't repeat any we have already seen. */
2294 if (multi_dir)
2296 free (CONST_CAST (char *, multi_dir));
2297 multi_dir = NULL;
2298 free (CONST_CAST (char *, multi_suffix));
2299 multi_suffix = machine_suffix;
2300 free (CONST_CAST (char *, just_multi_suffix));
2301 just_multi_suffix = just_machine_suffix;
2303 else
2304 skip_multi_dir = true;
2305 if (multi_os_dir)
2307 free (CONST_CAST (char *, multi_os_dir));
2308 multi_os_dir = NULL;
2310 else
2311 skip_multi_os_dir = true;
2314 if (multi_dir)
2316 free (CONST_CAST (char *, multi_dir));
2317 free (CONST_CAST (char *, multi_suffix));
2318 free (CONST_CAST (char *, just_multi_suffix));
2320 if (multi_os_dir)
2321 free (CONST_CAST (char *, multi_os_dir));
2322 if (ret != path)
2323 free (path);
2324 return ret;
2327 /* Callback for build_search_list. Adds path to obstack being built. */
2329 struct add_to_obstack_info {
2330 struct obstack *ob;
2331 bool check_dir;
2332 bool first_time;
2335 static void *
2336 add_to_obstack (char *path, void *data)
2338 struct add_to_obstack_info *info = (struct add_to_obstack_info *) data;
2340 if (info->check_dir && !is_directory (path, false))
2341 return NULL;
2343 if (!info->first_time)
2344 obstack_1grow (info->ob, PATH_SEPARATOR);
2346 obstack_grow (info->ob, path, strlen (path));
2348 info->first_time = false;
2349 return NULL;
2352 /* Add or change the value of an environment variable, outputting the
2353 change to standard error if in verbose mode. */
2354 static void
2355 xputenv (const char *string)
2357 if (verbose_flag)
2358 fnotice (stderr, "%s\n", string);
2359 putenv (CONST_CAST (char *, string));
2362 /* Build a list of search directories from PATHS.
2363 PREFIX is a string to prepend to the list.
2364 If CHECK_DIR_P is true we ensure the directory exists.
2365 If DO_MULTI is true, multilib paths are output first, then
2366 non-multilib paths.
2367 This is used mostly by putenv_from_prefixes so we use `collect_obstack'.
2368 It is also used by the --print-search-dirs flag. */
2370 static char *
2371 build_search_list (const struct path_prefix *paths, const char *prefix,
2372 bool check_dir, bool do_multi)
2374 struct add_to_obstack_info info;
2376 info.ob = &collect_obstack;
2377 info.check_dir = check_dir;
2378 info.first_time = true;
2380 obstack_grow (&collect_obstack, prefix, strlen (prefix));
2381 obstack_1grow (&collect_obstack, '=');
2383 for_each_path (paths, do_multi, 0, add_to_obstack, &info);
2385 obstack_1grow (&collect_obstack, '\0');
2386 return XOBFINISH (&collect_obstack, char *);
2389 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
2390 for collect. */
2392 static void
2393 putenv_from_prefixes (const struct path_prefix *paths, const char *env_var,
2394 bool do_multi)
2396 xputenv (build_search_list (paths, env_var, true, do_multi));
2399 /* Check whether NAME can be accessed in MODE. This is like access,
2400 except that it never considers directories to be executable. */
2402 static int
2403 access_check (const char *name, int mode)
2405 if (mode == X_OK)
2407 struct stat st;
2409 if (stat (name, &st) < 0
2410 || S_ISDIR (st.st_mode))
2411 return -1;
2414 return access (name, mode);
2417 /* Callback for find_a_file. Appends the file name to the directory
2418 path. If the resulting file exists in the right mode, return the
2419 full pathname to the file. */
2421 struct file_at_path_info {
2422 const char *name;
2423 const char *suffix;
2424 int name_len;
2425 int suffix_len;
2426 int mode;
2429 static void *
2430 file_at_path (char *path, void *data)
2432 struct file_at_path_info *info = (struct file_at_path_info *) data;
2433 size_t len = strlen (path);
2435 memcpy (path + len, info->name, info->name_len);
2436 len += info->name_len;
2438 /* Some systems have a suffix for executable files.
2439 So try appending that first. */
2440 if (info->suffix_len)
2442 memcpy (path + len, info->suffix, info->suffix_len + 1);
2443 if (access_check (path, info->mode) == 0)
2444 return path;
2447 path[len] = '\0';
2448 if (access_check (path, info->mode) == 0)
2449 return path;
2451 return NULL;
2454 /* Search for NAME using the prefix list PREFIXES. MODE is passed to
2455 access to check permissions. If DO_MULTI is true, search multilib
2456 paths then non-multilib paths, otherwise do not search multilib paths.
2457 Return 0 if not found, otherwise return its name, allocated with malloc. */
2459 static char *
2460 find_a_file (const struct path_prefix *pprefix, const char *name, int mode,
2461 bool do_multi)
2463 struct file_at_path_info info;
2465 #ifdef DEFAULT_ASSEMBLER
2466 if (! strcmp (name, "as") && access (DEFAULT_ASSEMBLER, mode) == 0)
2467 return xstrdup (DEFAULT_ASSEMBLER);
2468 #endif
2470 #ifdef DEFAULT_LINKER
2471 if (! strcmp (name, "ld") && access (DEFAULT_LINKER, mode) == 0)
2472 return xstrdup (DEFAULT_LINKER);
2473 #endif
2475 /* Determine the filename to execute (special case for absolute paths). */
2477 if (IS_ABSOLUTE_PATH (name))
2479 if (access (name, mode) == 0)
2480 return xstrdup (name);
2482 return NULL;
2485 info.name = name;
2486 info.suffix = (mode & X_OK) != 0 ? HOST_EXECUTABLE_SUFFIX : "";
2487 info.name_len = strlen (info.name);
2488 info.suffix_len = strlen (info.suffix);
2489 info.mode = mode;
2491 return (char*) for_each_path (pprefix, do_multi,
2492 info.name_len + info.suffix_len,
2493 file_at_path, &info);
2496 /* Ranking of prefixes in the sort list. -B prefixes are put before
2497 all others. */
2499 enum path_prefix_priority
2501 PREFIX_PRIORITY_B_OPT,
2502 PREFIX_PRIORITY_LAST
2505 /* Add an entry for PREFIX in PLIST. The PLIST is kept in ascending
2506 order according to PRIORITY. Within each PRIORITY, new entries are
2507 appended.
2509 If WARN is nonzero, we will warn if no file is found
2510 through this prefix. WARN should point to an int
2511 which will be set to 1 if this entry is used.
2513 COMPONENT is the value to be passed to update_path.
2515 REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
2516 the complete value of machine_suffix.
2517 2 means try both machine_suffix and just_machine_suffix. */
2519 static void
2520 add_prefix (struct path_prefix *pprefix, const char *prefix,
2521 const char *component, /* enum prefix_priority */ int priority,
2522 int require_machine_suffix, int os_multilib)
2524 struct prefix_list *pl, **prev;
2525 int len;
2527 for (prev = &pprefix->plist;
2528 (*prev) != NULL && (*prev)->priority <= priority;
2529 prev = &(*prev)->next)
2532 /* Keep track of the longest prefix. */
2534 prefix = update_path (prefix, component);
2535 len = strlen (prefix);
2536 if (len > pprefix->max_len)
2537 pprefix->max_len = len;
2539 pl = XNEW (struct prefix_list);
2540 pl->prefix = prefix;
2541 pl->require_machine_suffix = require_machine_suffix;
2542 pl->priority = priority;
2543 pl->os_multilib = os_multilib;
2545 /* Insert after PREV. */
2546 pl->next = (*prev);
2547 (*prev) = pl;
2550 /* Same as add_prefix, but prepending target_system_root to prefix. */
2551 /* The target_system_root prefix has been relocated by gcc_exec_prefix. */
2552 static void
2553 add_sysrooted_prefix (struct path_prefix *pprefix, const char *prefix,
2554 const char *component,
2555 /* enum prefix_priority */ int priority,
2556 int require_machine_suffix, int os_multilib)
2558 if (!IS_ABSOLUTE_PATH (prefix))
2559 fatal_error ("system path %qs is not absolute", prefix);
2561 if (target_system_root)
2563 char *sysroot_no_trailing_dir_separator = xstrdup (target_system_root);
2564 size_t sysroot_len = strlen (target_system_root);
2566 if (sysroot_len > 0
2567 && target_system_root[sysroot_len - 1] == DIR_SEPARATOR)
2568 sysroot_no_trailing_dir_separator[sysroot_len - 1] = '\0';
2570 if (target_sysroot_suffix)
2571 prefix = concat (sysroot_no_trailing_dir_separator,
2572 target_sysroot_suffix, prefix, NULL);
2573 else
2574 prefix = concat (sysroot_no_trailing_dir_separator, prefix, NULL);
2576 free (sysroot_no_trailing_dir_separator);
2578 /* We have to override this because GCC's notion of sysroot
2579 moves along with GCC. */
2580 component = "GCC";
2583 add_prefix (pprefix, prefix, component, priority,
2584 require_machine_suffix, os_multilib);
2587 /* Execute the command specified by the arguments on the current line of spec.
2588 When using pipes, this includes several piped-together commands
2589 with `|' between them.
2591 Return 0 if successful, -1 if failed. */
2593 static int
2594 execute (void)
2596 int i;
2597 int n_commands; /* # of command. */
2598 char *string;
2599 struct pex_obj *pex;
2600 struct command
2602 const char *prog; /* program name. */
2603 const char **argv; /* vector of args. */
2605 const char *arg;
2607 struct command *commands; /* each command buffer with above info. */
2609 gcc_assert (!processing_spec_function);
2611 if (wrapper_string)
2613 string = find_a_file (&exec_prefixes,
2614 argbuf[0], X_OK, false);
2615 if (string)
2616 argbuf[0] = string;
2617 insert_wrapper (wrapper_string);
2620 /* Count # of piped commands. */
2621 for (n_commands = 1, i = 0; argbuf.iterate (i, &arg); i++)
2622 if (strcmp (arg, "|") == 0)
2623 n_commands++;
2625 /* Get storage for each command. */
2626 commands = (struct command *) alloca (n_commands * sizeof (struct command));
2628 /* Split argbuf into its separate piped processes,
2629 and record info about each one.
2630 Also search for the programs that are to be run. */
2632 argbuf.safe_push (0);
2634 commands[0].prog = argbuf[0]; /* first command. */
2635 commands[0].argv = argbuf.address ();
2637 if (!wrapper_string)
2639 string = find_a_file (&exec_prefixes, commands[0].prog, X_OK, false);
2640 commands[0].argv[0] = (string) ? string : commands[0].argv[0];
2643 for (n_commands = 1, i = 0; argbuf.iterate (i, &arg); i++)
2644 if (arg && strcmp (arg, "|") == 0)
2645 { /* each command. */
2646 #if defined (__MSDOS__) || defined (OS2) || defined (VMS)
2647 fatal_error ("-pipe not supported");
2648 #endif
2649 argbuf[i] = 0; /* Termination of
2650 command args. */
2651 commands[n_commands].prog = argbuf[i + 1];
2652 commands[n_commands].argv
2653 = &(argbuf.address ())[i + 1];
2654 string = find_a_file (&exec_prefixes, commands[n_commands].prog,
2655 X_OK, false);
2656 if (string)
2657 commands[n_commands].argv[0] = string;
2658 n_commands++;
2661 /* If -v, print what we are about to do, and maybe query. */
2663 if (verbose_flag)
2665 /* For help listings, put a blank line between sub-processes. */
2666 if (print_help_list)
2667 fputc ('\n', stderr);
2669 /* Print each piped command as a separate line. */
2670 for (i = 0; i < n_commands; i++)
2672 const char *const *j;
2674 if (verbose_only_flag)
2676 for (j = commands[i].argv; *j; j++)
2678 const char *p;
2679 for (p = *j; *p; ++p)
2680 if (!ISALNUM ((unsigned char) *p)
2681 && *p != '_' && *p != '/' && *p != '-' && *p != '.')
2682 break;
2683 if (*p || !*j)
2685 fprintf (stderr, " \"");
2686 for (p = *j; *p; ++p)
2688 if (*p == '"' || *p == '\\' || *p == '$')
2689 fputc ('\\', stderr);
2690 fputc (*p, stderr);
2692 fputc ('"', stderr);
2694 /* If it's empty, print "". */
2695 else if (!**j)
2696 fprintf (stderr, " \"\"");
2697 else
2698 fprintf (stderr, " %s", *j);
2701 else
2702 for (j = commands[i].argv; *j; j++)
2703 /* If it's empty, print "". */
2704 if (!**j)
2705 fprintf (stderr, " \"\"");
2706 else
2707 fprintf (stderr, " %s", *j);
2709 /* Print a pipe symbol after all but the last command. */
2710 if (i + 1 != n_commands)
2711 fprintf (stderr, " |");
2712 fprintf (stderr, "\n");
2714 fflush (stderr);
2715 if (verbose_only_flag != 0)
2717 /* verbose_only_flag should act as if the spec was
2718 executed, so increment execution_count before
2719 returning. This prevents spurious warnings about
2720 unused linker input files, etc. */
2721 execution_count++;
2722 return 0;
2724 #ifdef DEBUG
2725 fnotice (stderr, "\nGo ahead? (y or n) ");
2726 fflush (stderr);
2727 i = getchar ();
2728 if (i != '\n')
2729 while (getchar () != '\n')
2732 if (i != 'y' && i != 'Y')
2733 return 0;
2734 #endif /* DEBUG */
2737 #ifdef ENABLE_VALGRIND_CHECKING
2738 /* Run the each command through valgrind. To simplify prepending the
2739 path to valgrind and the option "-q" (for quiet operation unless
2740 something triggers), we allocate a separate argv array. */
2742 for (i = 0; i < n_commands; i++)
2744 const char **argv;
2745 int argc;
2746 int j;
2748 for (argc = 0; commands[i].argv[argc] != NULL; argc++)
2751 argv = XALLOCAVEC (const char *, argc + 3);
2753 argv[0] = VALGRIND_PATH;
2754 argv[1] = "-q";
2755 for (j = 2; j < argc + 2; j++)
2756 argv[j] = commands[i].argv[j - 2];
2757 argv[j] = NULL;
2759 commands[i].argv = argv;
2760 commands[i].prog = argv[0];
2762 #endif
2764 /* Run each piped subprocess. */
2766 pex = pex_init (PEX_USE_PIPES | ((report_times || report_times_to_file)
2767 ? PEX_RECORD_TIMES : 0),
2768 progname, temp_filename);
2769 if (pex == NULL)
2770 fatal_error ("pex_init failed: %m");
2772 for (i = 0; i < n_commands; i++)
2774 const char *errmsg;
2775 int err;
2776 const char *string = commands[i].argv[0];
2778 errmsg = pex_run (pex,
2779 ((i + 1 == n_commands ? PEX_LAST : 0)
2780 | (string == commands[i].prog ? PEX_SEARCH : 0)),
2781 string, CONST_CAST (char **, commands[i].argv),
2782 NULL, NULL, &err);
2783 if (errmsg != NULL)
2785 if (err == 0)
2786 fatal_error (errmsg);
2787 else
2789 errno = err;
2790 pfatal_with_name (errmsg);
2794 if (string != commands[i].prog)
2795 free (CONST_CAST (char *, string));
2798 execution_count++;
2800 /* Wait for all the subprocesses to finish. */
2803 int *statuses;
2804 struct pex_time *times = NULL;
2805 int ret_code = 0;
2807 statuses = (int *) alloca (n_commands * sizeof (int));
2808 if (!pex_get_status (pex, n_commands, statuses))
2809 fatal_error ("failed to get exit status: %m");
2811 if (report_times || report_times_to_file)
2813 times = (struct pex_time *) alloca (n_commands * sizeof (struct pex_time));
2814 if (!pex_get_times (pex, n_commands, times))
2815 fatal_error ("failed to get process times: %m");
2818 pex_free (pex);
2820 for (i = 0; i < n_commands; ++i)
2822 int status = statuses[i];
2824 if (WIFSIGNALED (status))
2826 #ifdef SIGPIPE
2827 /* SIGPIPE is a special case. It happens in -pipe mode
2828 when the compiler dies before the preprocessor is done,
2829 or the assembler dies before the compiler is done.
2830 There's generally been an error already, and this is
2831 just fallout. So don't generate another error unless
2832 we would otherwise have succeeded. */
2833 if (WTERMSIG (status) == SIGPIPE
2834 && (signal_count || greatest_status >= MIN_FATAL_STATUS))
2836 signal_count++;
2837 ret_code = -1;
2839 else
2840 #endif
2841 internal_error ("%s (program %s)",
2842 strsignal (WTERMSIG (status)), commands[i].prog);
2844 else if (WIFEXITED (status)
2845 && WEXITSTATUS (status) >= MIN_FATAL_STATUS)
2847 if (WEXITSTATUS (status) > greatest_status)
2848 greatest_status = WEXITSTATUS (status);
2849 ret_code = -1;
2852 if (report_times || report_times_to_file)
2854 struct pex_time *pt = &times[i];
2855 double ut, st;
2857 ut = ((double) pt->user_seconds
2858 + (double) pt->user_microseconds / 1.0e6);
2859 st = ((double) pt->system_seconds
2860 + (double) pt->system_microseconds / 1.0e6);
2862 if (ut + st != 0)
2864 if (report_times)
2865 fnotice (stderr, "# %s %.2f %.2f\n",
2866 commands[i].prog, ut, st);
2868 if (report_times_to_file)
2870 int c = 0;
2871 const char *const *j;
2873 fprintf (report_times_to_file, "%g %g", ut, st);
2875 for (j = &commands[i].prog; *j; j = &commands[i].argv[++c])
2877 const char *p;
2878 for (p = *j; *p; ++p)
2879 if (*p == '"' || *p == '\\' || *p == '$'
2880 || ISSPACE (*p))
2881 break;
2883 if (*p)
2885 fprintf (report_times_to_file, " \"");
2886 for (p = *j; *p; ++p)
2888 if (*p == '"' || *p == '\\' || *p == '$')
2889 fputc ('\\', report_times_to_file);
2890 fputc (*p, report_times_to_file);
2892 fputc ('"', report_times_to_file);
2894 else
2895 fprintf (report_times_to_file, " %s", *j);
2898 fputc ('\n', report_times_to_file);
2904 return ret_code;
2908 /* Find all the switches given to us
2909 and make a vector describing them.
2910 The elements of the vector are strings, one per switch given.
2911 If a switch uses following arguments, then the `part1' field
2912 is the switch itself and the `args' field
2913 is a null-terminated vector containing the following arguments.
2914 Bits in the `live_cond' field are:
2915 SWITCH_LIVE to indicate this switch is true in a conditional spec.
2916 SWITCH_FALSE to indicate this switch is overridden by a later switch.
2917 SWITCH_IGNORE to indicate this switch should be ignored (used in %<S).
2918 SWITCH_IGNORE_PERMANENTLY to indicate this switch should be ignored
2919 in all do_spec calls afterwards. Used for %<S from self specs.
2920 The `validated' field is nonzero if any spec has looked at this switch;
2921 if it remains zero at the end of the run, it must be meaningless. */
2923 #define SWITCH_LIVE (1 << 0)
2924 #define SWITCH_FALSE (1 << 1)
2925 #define SWITCH_IGNORE (1 << 2)
2926 #define SWITCH_IGNORE_PERMANENTLY (1 << 3)
2927 #define SWITCH_KEEP_FOR_GCC (1 << 4)
2929 struct switchstr
2931 const char *part1;
2932 const char **args;
2933 unsigned int live_cond;
2934 bool known;
2935 bool validated;
2936 bool ordering;
2939 static struct switchstr *switches;
2941 static int n_switches;
2943 static int n_switches_alloc;
2945 /* Set to zero if -fcompare-debug is disabled, positive if it's
2946 enabled and we're running the first compilation, negative if it's
2947 enabled and we're running the second compilation. For most of the
2948 time, it's in the range -1..1, but it can be temporarily set to 2
2949 or 3 to indicate that the -fcompare-debug flags didn't come from
2950 the command-line, but rather from the GCC_COMPARE_DEBUG environment
2951 variable, until a synthesized -fcompare-debug flag is added to the
2952 command line. */
2953 int compare_debug;
2955 /* Set to nonzero if we've seen the -fcompare-debug-second flag. */
2956 int compare_debug_second;
2958 /* Set to the flags that should be passed to the second compilation in
2959 a -fcompare-debug compilation. */
2960 const char *compare_debug_opt;
2962 static struct switchstr *switches_debug_check[2];
2964 static int n_switches_debug_check[2];
2966 static int n_switches_alloc_debug_check[2];
2968 static char *debug_check_temp_file[2];
2970 /* Language is one of three things:
2972 1) The name of a real programming language.
2973 2) NULL, indicating that no one has figured out
2974 what it is yet.
2975 3) '*', indicating that the file should be passed
2976 to the linker. */
2977 struct infile
2979 const char *name;
2980 const char *language;
2981 struct compiler *incompiler;
2982 bool compiled;
2983 bool preprocessed;
2986 /* Also a vector of input files specified. */
2988 static struct infile *infiles;
2990 int n_infiles;
2992 static int n_infiles_alloc;
2994 /* True if multiple input files are being compiled to a single
2995 assembly file. */
2997 static bool combine_inputs;
2999 /* This counts the number of libraries added by lang_specific_driver, so that
3000 we can tell if there were any user supplied any files or libraries. */
3002 static int added_libraries;
3004 /* And a vector of corresponding output files is made up later. */
3006 const char **outfiles;
3008 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3010 /* Convert NAME to a new name if it is the standard suffix. DO_EXE
3011 is true if we should look for an executable suffix. DO_OBJ
3012 is true if we should look for an object suffix. */
3014 static const char *
3015 convert_filename (const char *name, int do_exe ATTRIBUTE_UNUSED,
3016 int do_obj ATTRIBUTE_UNUSED)
3018 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3019 int i;
3020 #endif
3021 int len;
3023 if (name == NULL)
3024 return NULL;
3026 len = strlen (name);
3028 #ifdef HAVE_TARGET_OBJECT_SUFFIX
3029 /* Convert x.o to x.obj if TARGET_OBJECT_SUFFIX is ".obj". */
3030 if (do_obj && len > 2
3031 && name[len - 2] == '.'
3032 && name[len - 1] == 'o')
3034 obstack_grow (&obstack, name, len - 2);
3035 obstack_grow0 (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
3036 name = XOBFINISH (&obstack, const char *);
3038 #endif
3040 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3041 /* If there is no filetype, make it the executable suffix (which includes
3042 the "."). But don't get confused if we have just "-o". */
3043 if (! do_exe || TARGET_EXECUTABLE_SUFFIX[0] == 0 || (len == 2 && name[0] == '-'))
3044 return name;
3046 for (i = len - 1; i >= 0; i--)
3047 if (IS_DIR_SEPARATOR (name[i]))
3048 break;
3050 for (i++; i < len; i++)
3051 if (name[i] == '.')
3052 return name;
3054 obstack_grow (&obstack, name, len);
3055 obstack_grow0 (&obstack, TARGET_EXECUTABLE_SUFFIX,
3056 strlen (TARGET_EXECUTABLE_SUFFIX));
3057 name = XOBFINISH (&obstack, const char *);
3058 #endif
3060 return name;
3062 #endif
3064 /* Display the command line switches accepted by gcc. */
3065 static void
3066 display_help (void)
3068 printf (_("Usage: %s [options] file...\n"), progname);
3069 fputs (_("Options:\n"), stdout);
3071 fputs (_(" -pass-exit-codes Exit with highest error code from a phase\n"), stdout);
3072 fputs (_(" --help Display this information\n"), stdout);
3073 fputs (_(" --target-help Display target specific command line options\n"), stdout);
3074 fputs (_(" --help={common|optimizers|params|target|warnings|[^]{joined|separate|undocumented}}[,...]\n"), stdout);
3075 fputs (_(" Display specific types of command line options\n"), stdout);
3076 if (! verbose_flag)
3077 fputs (_(" (Use '-v --help' to display command line options of sub-processes)\n"), stdout);
3078 fputs (_(" --version Display compiler version information\n"), stdout);
3079 fputs (_(" -dumpspecs Display all of the built in spec strings\n"), stdout);
3080 fputs (_(" -dumpversion Display the version of the compiler\n"), stdout);
3081 fputs (_(" -dumpmachine Display the compiler's target processor\n"), stdout);
3082 fputs (_(" -print-search-dirs Display the directories in the compiler's search path\n"), stdout);
3083 fputs (_(" -print-libgcc-file-name Display the name of the compiler's companion library\n"), stdout);
3084 fputs (_(" -print-file-name=<lib> Display the full path to library <lib>\n"), stdout);
3085 fputs (_(" -print-prog-name=<prog> Display the full path to compiler component <prog>\n"), stdout);
3086 fputs (_("\
3087 -print-multiarch Display the target's normalized GNU triplet, used as\n\
3088 a component in the library path\n"), stdout);
3089 fputs (_(" -print-multi-directory Display the root directory for versions of libgcc\n"), stdout);
3090 fputs (_("\
3091 -print-multi-lib Display the mapping between command line options and\n\
3092 multiple library search directories\n"), stdout);
3093 fputs (_(" -print-multi-os-directory Display the relative path to OS libraries\n"), stdout);
3094 fputs (_(" -print-sysroot Display the target libraries directory\n"), stdout);
3095 fputs (_(" -print-sysroot-headers-suffix Display the sysroot suffix used to find headers\n"), stdout);
3096 fputs (_(" -Wa,<options> Pass comma-separated <options> on to the assembler\n"), stdout);
3097 fputs (_(" -Wp,<options> Pass comma-separated <options> on to the preprocessor\n"), stdout);
3098 fputs (_(" -Wl,<options> Pass comma-separated <options> on to the linker\n"), stdout);
3099 fputs (_(" -Xassembler <arg> Pass <arg> on to the assembler\n"), stdout);
3100 fputs (_(" -Xpreprocessor <arg> Pass <arg> on to the preprocessor\n"), stdout);
3101 fputs (_(" -Xlinker <arg> Pass <arg> on to the linker\n"), stdout);
3102 fputs (_(" -save-temps Do not delete intermediate files\n"), stdout);
3103 fputs (_(" -save-temps=<arg> Do not delete intermediate files\n"), stdout);
3104 fputs (_("\
3105 -no-canonical-prefixes Do not canonicalize paths when building relative\n\
3106 prefixes to other gcc components\n"), stdout);
3107 fputs (_(" -pipe Use pipes rather than intermediate files\n"), stdout);
3108 fputs (_(" -time Time the execution of each subprocess\n"), stdout);
3109 fputs (_(" -specs=<file> Override built-in specs with the contents of <file>\n"), stdout);
3110 fputs (_(" -std=<standard> Assume that the input sources are for <standard>\n"), stdout);
3111 fputs (_("\
3112 --sysroot=<directory> Use <directory> as the root directory for headers\n\
3113 and libraries\n"), stdout);
3114 fputs (_(" -B <directory> Add <directory> to the compiler's search paths\n"), stdout);
3115 fputs (_(" -v Display the programs invoked by the compiler\n"), stdout);
3116 fputs (_(" -### Like -v but options quoted and commands not executed\n"), stdout);
3117 fputs (_(" -E Preprocess only; do not compile, assemble or link\n"), stdout);
3118 fputs (_(" -S Compile only; do not assemble or link\n"), stdout);
3119 fputs (_(" -c Compile and assemble, but do not link\n"), stdout);
3120 fputs (_(" -o <file> Place the output into <file>\n"), stdout);
3121 fputs (_(" -pie Create a position independent executable\n"), stdout);
3122 fputs (_(" -shared Create a shared library\n"), stdout);
3123 fputs (_("\
3124 -x <language> Specify the language of the following input files\n\
3125 Permissible languages include: c c++ assembler none\n\
3126 'none' means revert to the default behavior of\n\
3127 guessing the language based on the file's extension\n\
3128 "), stdout);
3130 printf (_("\
3131 \nOptions starting with -g, -f, -m, -O, -W, or --param are automatically\n\
3132 passed on to the various sub-processes invoked by %s. In order to pass\n\
3133 other options on to these processes the -W<letter> options must be used.\n\
3134 "), progname);
3136 /* The rest of the options are displayed by invocations of the various
3137 sub-processes. */
3140 static void
3141 add_preprocessor_option (const char *option, int len)
3143 preprocessor_options.safe_push (save_string (option, len));
3146 static void
3147 add_assembler_option (const char *option, int len)
3149 assembler_options.safe_push (save_string (option, len));
3152 static void
3153 add_linker_option (const char *option, int len)
3155 linker_options.safe_push (save_string (option, len));
3158 /* Allocate space for an input file in infiles. */
3160 static void
3161 alloc_infile (void)
3163 if (n_infiles_alloc == 0)
3165 n_infiles_alloc = 16;
3166 infiles = XNEWVEC (struct infile, n_infiles_alloc);
3168 else if (n_infiles_alloc == n_infiles)
3170 n_infiles_alloc *= 2;
3171 infiles = XRESIZEVEC (struct infile, infiles, n_infiles_alloc);
3175 /* Store an input file with the given NAME and LANGUAGE in
3176 infiles. */
3178 static void
3179 add_infile (const char *name, const char *language)
3181 alloc_infile ();
3182 infiles[n_infiles].name = name;
3183 infiles[n_infiles++].language = language;
3186 /* Allocate space for a switch in switches. */
3188 static void
3189 alloc_switch (void)
3191 if (n_switches_alloc == 0)
3193 n_switches_alloc = 16;
3194 switches = XNEWVEC (struct switchstr, n_switches_alloc);
3196 else if (n_switches_alloc == n_switches)
3198 n_switches_alloc *= 2;
3199 switches = XRESIZEVEC (struct switchstr, switches, n_switches_alloc);
3203 /* Save an option OPT with N_ARGS arguments in array ARGS, marking it
3204 as validated if VALIDATED and KNOWN if it is an internal switch. */
3206 static void
3207 save_switch (const char *opt, size_t n_args, const char *const *args,
3208 bool validated, bool known)
3210 alloc_switch ();
3211 switches[n_switches].part1 = opt + 1;
3212 if (n_args == 0)
3213 switches[n_switches].args = 0;
3214 else
3216 switches[n_switches].args = XNEWVEC (const char *, n_args + 1);
3217 memcpy (switches[n_switches].args, args, n_args * sizeof (const char *));
3218 switches[n_switches].args[n_args] = NULL;
3221 switches[n_switches].live_cond = 0;
3222 switches[n_switches].validated = validated;
3223 switches[n_switches].known = known;
3224 switches[n_switches].ordering = 0;
3225 n_switches++;
3228 /* Handle an option DECODED that is unknown to the option-processing
3229 machinery. */
3231 static bool
3232 driver_unknown_option_callback (const struct cl_decoded_option *decoded)
3234 const char *opt = decoded->arg;
3235 if (opt[1] == 'W' && opt[2] == 'n' && opt[3] == 'o' && opt[4] == '-'
3236 && !(decoded->errors & CL_ERR_NEGATIVE))
3238 /* Leave unknown -Wno-* options for the compiler proper, to be
3239 diagnosed only if there are warnings. */
3240 save_switch (decoded->canonical_option[0],
3241 decoded->canonical_option_num_elements - 1,
3242 &decoded->canonical_option[1], false, true);
3243 return false;
3245 if (decoded->opt_index == OPT_SPECIAL_unknown)
3247 /* Give it a chance to define it a a spec file. */
3248 save_switch (decoded->canonical_option[0],
3249 decoded->canonical_option_num_elements - 1,
3250 &decoded->canonical_option[1], false, false);
3251 return false;
3253 else
3254 return true;
3257 /* Handle an option DECODED that is not marked as CL_DRIVER.
3258 LANG_MASK will always be CL_DRIVER. */
3260 static void
3261 driver_wrong_lang_callback (const struct cl_decoded_option *decoded,
3262 unsigned int lang_mask ATTRIBUTE_UNUSED)
3264 /* At this point, non-driver options are accepted (and expected to
3265 be passed down by specs) unless marked to be rejected by the
3266 driver. Options to be rejected by the driver but accepted by the
3267 compilers proper are treated just like completely unknown
3268 options. */
3269 const struct cl_option *option = &cl_options[decoded->opt_index];
3271 if (option->cl_reject_driver)
3272 error ("unrecognized command line option %qs",
3273 decoded->orig_option_with_args_text);
3274 else
3275 save_switch (decoded->canonical_option[0],
3276 decoded->canonical_option_num_elements - 1,
3277 &decoded->canonical_option[1], false, true);
3280 static const char *spec_lang = 0;
3281 static int last_language_n_infiles;
3283 /* Handle a driver option; arguments and return value as for
3284 handle_option. */
3286 static bool
3287 driver_handle_option (struct gcc_options *opts,
3288 struct gcc_options *opts_set,
3289 const struct cl_decoded_option *decoded,
3290 unsigned int lang_mask ATTRIBUTE_UNUSED, int kind,
3291 location_t loc,
3292 const struct cl_option_handlers *handlers ATTRIBUTE_UNUSED,
3293 diagnostic_context *dc)
3295 size_t opt_index = decoded->opt_index;
3296 const char *arg = decoded->arg;
3297 const char *compare_debug_replacement_opt;
3298 int value = decoded->value;
3299 bool validated = false;
3300 bool do_save = true;
3302 gcc_assert (opts == &global_options);
3303 gcc_assert (opts_set == &global_options_set);
3304 gcc_assert (kind == DK_UNSPECIFIED);
3305 gcc_assert (loc == UNKNOWN_LOCATION);
3306 gcc_assert (dc == global_dc);
3308 switch (opt_index)
3310 case OPT_dumpspecs:
3312 struct spec_list *sl;
3313 init_spec ();
3314 for (sl = specs; sl; sl = sl->next)
3315 printf ("*%s:\n%s\n\n", sl->name, *(sl->ptr_spec));
3316 if (link_command_spec)
3317 printf ("*link_command:\n%s\n\n", link_command_spec);
3318 exit (0);
3321 case OPT_dumpversion:
3322 printf ("%s\n", spec_version);
3323 exit (0);
3325 case OPT_dumpmachine:
3326 printf ("%s\n", spec_machine);
3327 exit (0);
3329 case OPT__version:
3330 print_version = 1;
3332 /* CPP driver cannot obtain switch from cc1_options. */
3333 if (is_cpp_driver)
3334 add_preprocessor_option ("--version", strlen ("--version"));
3335 add_assembler_option ("--version", strlen ("--version"));
3336 add_linker_option ("--version", strlen ("--version"));
3337 break;
3339 case OPT__help:
3340 print_help_list = 1;
3342 /* CPP driver cannot obtain switch from cc1_options. */
3343 if (is_cpp_driver)
3344 add_preprocessor_option ("--help", 6);
3345 add_assembler_option ("--help", 6);
3346 add_linker_option ("--help", 6);
3347 break;
3349 case OPT__help_:
3350 print_subprocess_help = 2;
3351 break;
3353 case OPT__target_help:
3354 print_subprocess_help = 1;
3356 /* CPP driver cannot obtain switch from cc1_options. */
3357 if (is_cpp_driver)
3358 add_preprocessor_option ("--target-help", 13);
3359 add_assembler_option ("--target-help", 13);
3360 add_linker_option ("--target-help", 13);
3361 break;
3363 case OPT__no_sysroot_suffix:
3364 case OPT_pass_exit_codes:
3365 case OPT_print_search_dirs:
3366 case OPT_print_file_name_:
3367 case OPT_print_prog_name_:
3368 case OPT_print_multi_lib:
3369 case OPT_print_multi_directory:
3370 case OPT_print_sysroot:
3371 case OPT_print_multi_os_directory:
3372 case OPT_print_multiarch:
3373 case OPT_print_sysroot_headers_suffix:
3374 case OPT_time:
3375 case OPT_wrapper:
3376 /* These options set the variables specified in common.opt
3377 automatically, and do not need to be saved for spec
3378 processing. */
3379 do_save = false;
3380 break;
3382 case OPT_print_libgcc_file_name:
3383 print_file_name = "libgcc.a";
3384 do_save = false;
3385 break;
3387 case OPT_fuse_ld_bfd:
3388 use_ld = ".bfd";
3389 break;
3391 case OPT_fuse_ld_gold:
3392 use_ld = ".gold";
3393 break;
3395 case OPT_fcompare_debug_second:
3396 compare_debug_second = 1;
3397 break;
3399 case OPT_fcompare_debug:
3400 switch (value)
3402 case 0:
3403 compare_debug_replacement_opt = "-fcompare-debug=";
3404 arg = "";
3405 goto compare_debug_with_arg;
3407 case 1:
3408 compare_debug_replacement_opt = "-fcompare-debug=-gtoggle";
3409 arg = "-gtoggle";
3410 goto compare_debug_with_arg;
3412 default:
3413 gcc_unreachable ();
3415 break;
3417 case OPT_fcompare_debug_:
3418 compare_debug_replacement_opt = decoded->canonical_option[0];
3419 compare_debug_with_arg:
3420 gcc_assert (decoded->canonical_option_num_elements == 1);
3421 gcc_assert (arg != NULL);
3422 if (*arg)
3423 compare_debug = 1;
3424 else
3425 compare_debug = -1;
3426 if (compare_debug < 0)
3427 compare_debug_opt = NULL;
3428 else
3429 compare_debug_opt = arg;
3430 save_switch (compare_debug_replacement_opt, 0, NULL, validated, true);
3431 return true;
3433 case OPT_Wa_:
3435 int prev, j;
3436 /* Pass the rest of this option to the assembler. */
3438 /* Split the argument at commas. */
3439 prev = 0;
3440 for (j = 0; arg[j]; j++)
3441 if (arg[j] == ',')
3443 add_assembler_option (arg + prev, j - prev);
3444 prev = j + 1;
3447 /* Record the part after the last comma. */
3448 add_assembler_option (arg + prev, j - prev);
3450 do_save = false;
3451 break;
3453 case OPT_Wp_:
3455 int prev, j;
3456 /* Pass the rest of this option to the preprocessor. */
3458 /* Split the argument at commas. */
3459 prev = 0;
3460 for (j = 0; arg[j]; j++)
3461 if (arg[j] == ',')
3463 add_preprocessor_option (arg + prev, j - prev);
3464 prev = j + 1;
3467 /* Record the part after the last comma. */
3468 add_preprocessor_option (arg + prev, j - prev);
3470 do_save = false;
3471 break;
3473 case OPT_Wl_:
3475 int prev, j;
3476 /* Split the argument at commas. */
3477 prev = 0;
3478 for (j = 0; arg[j]; j++)
3479 if (arg[j] == ',')
3481 add_infile (save_string (arg + prev, j - prev), "*");
3482 prev = j + 1;
3484 /* Record the part after the last comma. */
3485 add_infile (arg + prev, "*");
3487 do_save = false;
3488 break;
3490 case OPT_Xlinker:
3491 add_infile (arg, "*");
3492 do_save = false;
3493 break;
3495 case OPT_Xpreprocessor:
3496 add_preprocessor_option (arg, strlen (arg));
3497 do_save = false;
3498 break;
3500 case OPT_Xassembler:
3501 add_assembler_option (arg, strlen (arg));
3502 do_save = false;
3503 break;
3505 case OPT_l:
3506 /* POSIX allows separation of -l and the lib arg; canonicalize
3507 by concatenating -l with its arg */
3508 add_infile (concat ("-l", arg, NULL), "*");
3509 do_save = false;
3510 break;
3512 case OPT_L:
3513 /* Similarly, canonicalize -L for linkers that may not accept
3514 separate arguments. */
3515 save_switch (concat ("-L", arg, NULL), 0, NULL, validated, true);
3516 return true;
3518 case OPT_F:
3519 /* Likewise -F. */
3520 save_switch (concat ("-F", arg, NULL), 0, NULL, validated, true);
3521 return true;
3523 case OPT_save_temps:
3524 save_temps_flag = SAVE_TEMPS_CWD;
3525 validated = true;
3526 break;
3528 case OPT_save_temps_:
3529 if (strcmp (arg, "cwd") == 0)
3530 save_temps_flag = SAVE_TEMPS_CWD;
3531 else if (strcmp (arg, "obj") == 0
3532 || strcmp (arg, "object") == 0)
3533 save_temps_flag = SAVE_TEMPS_OBJ;
3534 else
3535 fatal_error ("%qs is an unknown -save-temps option",
3536 decoded->orig_option_with_args_text);
3537 break;
3539 case OPT_no_canonical_prefixes:
3540 /* Already handled as a special case, so ignored here. */
3541 do_save = false;
3542 break;
3544 case OPT_pipe:
3545 validated = true;
3546 /* These options set the variables specified in common.opt
3547 automatically, but do need to be saved for spec
3548 processing. */
3549 break;
3551 case OPT_specs_:
3553 struct user_specs *user = XNEW (struct user_specs);
3555 user->next = (struct user_specs *) 0;
3556 user->filename = arg;
3557 if (user_specs_tail)
3558 user_specs_tail->next = user;
3559 else
3560 user_specs_head = user;
3561 user_specs_tail = user;
3563 validated = true;
3564 break;
3566 case OPT__sysroot_:
3567 target_system_root = arg;
3568 target_system_root_changed = 1;
3569 do_save = false;
3570 break;
3572 case OPT_time_:
3573 if (report_times_to_file)
3574 fclose (report_times_to_file);
3575 report_times_to_file = fopen (arg, "a");
3576 do_save = false;
3577 break;
3579 case OPT____:
3580 /* "-###"
3581 This is similar to -v except that there is no execution
3582 of the commands and the echoed arguments are quoted. It
3583 is intended for use in shell scripts to capture the
3584 driver-generated command line. */
3585 verbose_only_flag++;
3586 verbose_flag = 1;
3587 do_save = false;
3588 break;
3590 case OPT_B:
3592 size_t len = strlen (arg);
3594 /* Catch the case where the user has forgotten to append a
3595 directory separator to the path. Note, they may be using
3596 -B to add an executable name prefix, eg "i386-elf-", in
3597 order to distinguish between multiple installations of
3598 GCC in the same directory. Hence we must check to see
3599 if appending a directory separator actually makes a
3600 valid directory name. */
3601 if (!IS_DIR_SEPARATOR (arg[len - 1])
3602 && is_directory (arg, false))
3604 char *tmp = XNEWVEC (char, len + 2);
3605 strcpy (tmp, arg);
3606 tmp[len] = DIR_SEPARATOR;
3607 tmp[++len] = 0;
3608 arg = tmp;
3611 add_prefix (&exec_prefixes, arg, NULL,
3612 PREFIX_PRIORITY_B_OPT, 0, 0);
3613 add_prefix (&startfile_prefixes, arg, NULL,
3614 PREFIX_PRIORITY_B_OPT, 0, 0);
3615 add_prefix (&include_prefixes, arg, NULL,
3616 PREFIX_PRIORITY_B_OPT, 0, 0);
3618 validated = true;
3619 break;
3621 case OPT_x:
3622 spec_lang = arg;
3623 if (!strcmp (spec_lang, "none"))
3624 /* Suppress the warning if -xnone comes after the last input
3625 file, because alternate command interfaces like g++ might
3626 find it useful to place -xnone after each input file. */
3627 spec_lang = 0;
3628 else
3629 last_language_n_infiles = n_infiles;
3630 do_save = false;
3631 break;
3633 case OPT_o:
3634 have_o = 1;
3635 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX) || defined(HAVE_TARGET_OBJECT_SUFFIX)
3636 arg = convert_filename (arg, ! have_c, 0);
3637 #endif
3638 /* Save the output name in case -save-temps=obj was used. */
3639 save_temps_prefix = xstrdup (arg);
3640 /* On some systems, ld cannot handle "-o" without a space. So
3641 split the option from its argument. */
3642 save_switch ("-o", 1, &arg, validated, true);
3643 return true;
3645 case OPT_static_libgcc:
3646 case OPT_shared_libgcc:
3647 case OPT_static_libgfortran:
3648 case OPT_static_libstdc__:
3649 /* These are always valid, since gcc.c itself understands the
3650 first two, gfortranspec.c understands -static-libgfortran and
3651 g++spec.c understands -static-libstdc++ */
3652 validated = true;
3653 break;
3655 case OPT_fwpa:
3656 flag_wpa = "";
3657 break;
3659 default:
3660 /* Various driver options need no special processing at this
3661 point, having been handled in a prescan above or being
3662 handled by specs. */
3663 break;
3666 if (do_save)
3667 save_switch (decoded->canonical_option[0],
3668 decoded->canonical_option_num_elements - 1,
3669 &decoded->canonical_option[1], validated, true);
3670 return true;
3673 /* Put the driver's standard set of option handlers in *HANDLERS. */
3675 static void
3676 set_option_handlers (struct cl_option_handlers *handlers)
3678 handlers->unknown_option_callback = driver_unknown_option_callback;
3679 handlers->wrong_lang_callback = driver_wrong_lang_callback;
3680 handlers->num_handlers = 3;
3681 handlers->handlers[0].handler = driver_handle_option;
3682 handlers->handlers[0].mask = CL_DRIVER;
3683 handlers->handlers[1].handler = common_handle_option;
3684 handlers->handlers[1].mask = CL_COMMON;
3685 handlers->handlers[2].handler = target_handle_option;
3686 handlers->handlers[2].mask = CL_TARGET;
3689 /* Create the vector `switches' and its contents.
3690 Store its length in `n_switches'. */
3692 static void
3693 process_command (unsigned int decoded_options_count,
3694 struct cl_decoded_option *decoded_options)
3696 const char *temp;
3697 char *temp1;
3698 char *tooldir_prefix, *tooldir_prefix2;
3699 char *(*get_relative_prefix) (const char *, const char *,
3700 const char *) = NULL;
3701 struct cl_option_handlers handlers;
3702 unsigned int j;
3704 gcc_exec_prefix = getenv ("GCC_EXEC_PREFIX");
3706 n_switches = 0;
3707 n_infiles = 0;
3708 added_libraries = 0;
3710 /* Figure compiler version from version string. */
3712 compiler_version = temp1 = xstrdup (version_string);
3714 for (; *temp1; ++temp1)
3716 if (*temp1 == ' ')
3718 *temp1 = '\0';
3719 break;
3723 /* Handle any -no-canonical-prefixes flag early, to assign the function
3724 that builds relative prefixes. This function creates default search
3725 paths that are needed later in normal option handling. */
3727 for (j = 1; j < decoded_options_count; j++)
3729 if (decoded_options[j].opt_index == OPT_no_canonical_prefixes)
3731 get_relative_prefix = make_relative_prefix_ignore_links;
3732 break;
3735 if (! get_relative_prefix)
3736 get_relative_prefix = make_relative_prefix;
3738 /* Set up the default search paths. If there is no GCC_EXEC_PREFIX,
3739 see if we can create it from the pathname specified in
3740 decoded_options[0].arg. */
3742 gcc_libexec_prefix = standard_libexec_prefix;
3743 #ifndef VMS
3744 /* FIXME: make_relative_prefix doesn't yet work for VMS. */
3745 if (!gcc_exec_prefix)
3747 gcc_exec_prefix = get_relative_prefix (decoded_options[0].arg,
3748 standard_bindir_prefix,
3749 standard_exec_prefix);
3750 gcc_libexec_prefix = get_relative_prefix (decoded_options[0].arg,
3751 standard_bindir_prefix,
3752 standard_libexec_prefix);
3753 if (gcc_exec_prefix)
3754 xputenv (concat ("GCC_EXEC_PREFIX=", gcc_exec_prefix, NULL));
3756 else
3758 /* make_relative_prefix requires a program name, but
3759 GCC_EXEC_PREFIX is typically a directory name with a trailing
3760 / (which is ignored by make_relative_prefix), so append a
3761 program name. */
3762 char *tmp_prefix = concat (gcc_exec_prefix, "gcc", NULL);
3763 gcc_libexec_prefix = get_relative_prefix (tmp_prefix,
3764 standard_exec_prefix,
3765 standard_libexec_prefix);
3767 /* The path is unrelocated, so fallback to the original setting. */
3768 if (!gcc_libexec_prefix)
3769 gcc_libexec_prefix = standard_libexec_prefix;
3771 free (tmp_prefix);
3773 #else
3774 #endif
3775 /* From this point onward, gcc_exec_prefix is non-null if the toolchain
3776 is relocated. The toolchain was either relocated using GCC_EXEC_PREFIX
3777 or an automatically created GCC_EXEC_PREFIX from
3778 decoded_options[0].arg. */
3780 /* Do language-specific adjustment/addition of flags. */
3781 lang_specific_driver (&decoded_options, &decoded_options_count,
3782 &added_libraries);
3784 if (gcc_exec_prefix)
3786 int len = strlen (gcc_exec_prefix);
3788 if (len > (int) sizeof ("/lib/gcc/") - 1
3789 && (IS_DIR_SEPARATOR (gcc_exec_prefix[len-1])))
3791 temp = gcc_exec_prefix + len - sizeof ("/lib/gcc/") + 1;
3792 if (IS_DIR_SEPARATOR (*temp)
3793 && filename_ncmp (temp + 1, "lib", 3) == 0
3794 && IS_DIR_SEPARATOR (temp[4])
3795 && filename_ncmp (temp + 5, "gcc", 3) == 0)
3796 len -= sizeof ("/lib/gcc/") - 1;
3799 set_std_prefix (gcc_exec_prefix, len);
3800 add_prefix (&exec_prefixes, gcc_libexec_prefix, "GCC",
3801 PREFIX_PRIORITY_LAST, 0, 0);
3802 add_prefix (&startfile_prefixes, gcc_exec_prefix, "GCC",
3803 PREFIX_PRIORITY_LAST, 0, 0);
3806 /* COMPILER_PATH and LIBRARY_PATH have values
3807 that are lists of directory names with colons. */
3809 temp = getenv ("COMPILER_PATH");
3810 if (temp)
3812 const char *startp, *endp;
3813 char *nstore = (char *) alloca (strlen (temp) + 3);
3815 startp = endp = temp;
3816 while (1)
3818 if (*endp == PATH_SEPARATOR || *endp == 0)
3820 strncpy (nstore, startp, endp - startp);
3821 if (endp == startp)
3822 strcpy (nstore, concat (".", dir_separator_str, NULL));
3823 else if (!IS_DIR_SEPARATOR (endp[-1]))
3825 nstore[endp - startp] = DIR_SEPARATOR;
3826 nstore[endp - startp + 1] = 0;
3828 else
3829 nstore[endp - startp] = 0;
3830 add_prefix (&exec_prefixes, nstore, 0,
3831 PREFIX_PRIORITY_LAST, 0, 0);
3832 add_prefix (&include_prefixes, nstore, 0,
3833 PREFIX_PRIORITY_LAST, 0, 0);
3834 if (*endp == 0)
3835 break;
3836 endp = startp = endp + 1;
3838 else
3839 endp++;
3843 temp = getenv (LIBRARY_PATH_ENV);
3844 if (temp && *cross_compile == '0')
3846 const char *startp, *endp;
3847 char *nstore = (char *) alloca (strlen (temp) + 3);
3849 startp = endp = temp;
3850 while (1)
3852 if (*endp == PATH_SEPARATOR || *endp == 0)
3854 strncpy (nstore, startp, endp - startp);
3855 if (endp == startp)
3856 strcpy (nstore, concat (".", dir_separator_str, NULL));
3857 else if (!IS_DIR_SEPARATOR (endp[-1]))
3859 nstore[endp - startp] = DIR_SEPARATOR;
3860 nstore[endp - startp + 1] = 0;
3862 else
3863 nstore[endp - startp] = 0;
3864 add_prefix (&startfile_prefixes, nstore, NULL,
3865 PREFIX_PRIORITY_LAST, 0, 1);
3866 if (*endp == 0)
3867 break;
3868 endp = startp = endp + 1;
3870 else
3871 endp++;
3875 /* Use LPATH like LIBRARY_PATH (for the CMU build program). */
3876 temp = getenv ("LPATH");
3877 if (temp && *cross_compile == '0')
3879 const char *startp, *endp;
3880 char *nstore = (char *) alloca (strlen (temp) + 3);
3882 startp = endp = temp;
3883 while (1)
3885 if (*endp == PATH_SEPARATOR || *endp == 0)
3887 strncpy (nstore, startp, endp - startp);
3888 if (endp == startp)
3889 strcpy (nstore, concat (".", dir_separator_str, NULL));
3890 else if (!IS_DIR_SEPARATOR (endp[-1]))
3892 nstore[endp - startp] = DIR_SEPARATOR;
3893 nstore[endp - startp + 1] = 0;
3895 else
3896 nstore[endp - startp] = 0;
3897 add_prefix (&startfile_prefixes, nstore, NULL,
3898 PREFIX_PRIORITY_LAST, 0, 1);
3899 if (*endp == 0)
3900 break;
3901 endp = startp = endp + 1;
3903 else
3904 endp++;
3908 /* Process the options and store input files and switches in their
3909 vectors. */
3911 last_language_n_infiles = -1;
3913 set_option_handlers (&handlers);
3915 for (j = 1; j < decoded_options_count; j++)
3917 switch (decoded_options[j].opt_index)
3919 case OPT_S:
3920 case OPT_c:
3921 case OPT_E:
3922 have_c = 1;
3923 break;
3925 if (have_c)
3926 break;
3929 for (j = 1; j < decoded_options_count; j++)
3931 if (decoded_options[j].opt_index == OPT_SPECIAL_input_file)
3933 const char *arg = decoded_options[j].arg;
3934 const char *p = strrchr (arg, '@');
3935 char *fname;
3936 long offset;
3937 int consumed;
3938 #ifdef HAVE_TARGET_OBJECT_SUFFIX
3939 arg = convert_filename (arg, 0, access (arg, F_OK));
3940 #endif
3941 /* For LTO static archive support we handle input file
3942 specifications that are composed of a filename and
3943 an offset like FNAME@OFFSET. */
3944 if (p
3945 && p != arg
3946 && sscanf (p, "@%li%n", &offset, &consumed) >= 1
3947 && strlen (p) == (unsigned int)consumed)
3949 fname = (char *)xmalloc (p - arg + 1);
3950 memcpy (fname, arg, p - arg);
3951 fname[p - arg] = '\0';
3952 /* Only accept non-stdin and existing FNAME parts, otherwise
3953 try with the full name. */
3954 if (strcmp (fname, "-") == 0 || access (fname, F_OK) < 0)
3956 free (fname);
3957 fname = xstrdup (arg);
3960 else
3961 fname = xstrdup (arg);
3963 if (strcmp (fname, "-") != 0 && access (fname, F_OK) < 0)
3964 perror_with_name (fname);
3965 else
3966 add_infile (arg, spec_lang);
3968 free (fname);
3969 continue;
3972 read_cmdline_option (&global_options, &global_options_set,
3973 decoded_options + j, UNKNOWN_LOCATION,
3974 CL_DRIVER, &handlers, global_dc);
3977 /* If -save-temps=obj and -o name, create the prefix to use for %b.
3978 Otherwise just make -save-temps=obj the same as -save-temps=cwd. */
3979 if (save_temps_flag == SAVE_TEMPS_OBJ && save_temps_prefix != NULL)
3981 save_temps_length = strlen (save_temps_prefix);
3982 temp = strrchr (lbasename (save_temps_prefix), '.');
3983 if (temp)
3985 save_temps_length -= strlen (temp);
3986 save_temps_prefix[save_temps_length] = '\0';
3990 else if (save_temps_prefix != NULL)
3992 free (save_temps_prefix);
3993 save_temps_prefix = NULL;
3996 if (save_temps_flag && use_pipes)
3998 /* -save-temps overrides -pipe, so that temp files are produced */
3999 if (save_temps_flag)
4000 warning (0, "-pipe ignored because -save-temps specified");
4001 use_pipes = 0;
4004 if (!compare_debug)
4006 const char *gcd = getenv ("GCC_COMPARE_DEBUG");
4008 if (gcd && gcd[0] == '-')
4010 compare_debug = 2;
4011 compare_debug_opt = gcd;
4013 else if (gcd && *gcd && strcmp (gcd, "0"))
4015 compare_debug = 3;
4016 compare_debug_opt = "-gtoggle";
4019 else if (compare_debug < 0)
4021 compare_debug = 0;
4022 gcc_assert (!compare_debug_opt);
4025 /* Set up the search paths. We add directories that we expect to
4026 contain GNU Toolchain components before directories specified by
4027 the machine description so that we will find GNU components (like
4028 the GNU assembler) before those of the host system. */
4030 /* If we don't know where the toolchain has been installed, use the
4031 configured-in locations. */
4032 if (!gcc_exec_prefix)
4034 #ifndef OS2
4035 add_prefix (&exec_prefixes, standard_libexec_prefix, "GCC",
4036 PREFIX_PRIORITY_LAST, 1, 0);
4037 add_prefix (&exec_prefixes, standard_libexec_prefix, "BINUTILS",
4038 PREFIX_PRIORITY_LAST, 2, 0);
4039 add_prefix (&exec_prefixes, standard_exec_prefix, "BINUTILS",
4040 PREFIX_PRIORITY_LAST, 2, 0);
4041 #endif
4042 add_prefix (&startfile_prefixes, standard_exec_prefix, "BINUTILS",
4043 PREFIX_PRIORITY_LAST, 1, 0);
4046 gcc_assert (!IS_ABSOLUTE_PATH (tooldir_base_prefix));
4047 tooldir_prefix2 = concat (tooldir_base_prefix, spec_machine,
4048 dir_separator_str, NULL);
4050 /* Look for tools relative to the location from which the driver is
4051 running, or, if that is not available, the configured prefix. */
4052 tooldir_prefix
4053 = concat (gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
4054 spec_machine, dir_separator_str,
4055 spec_version, dir_separator_str, tooldir_prefix2, NULL);
4056 free (tooldir_prefix2);
4058 add_prefix (&exec_prefixes,
4059 concat (tooldir_prefix, "bin", dir_separator_str, NULL),
4060 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 0);
4061 add_prefix (&startfile_prefixes,
4062 concat (tooldir_prefix, "lib", dir_separator_str, NULL),
4063 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 1);
4064 free (tooldir_prefix);
4066 #if defined(TARGET_SYSTEM_ROOT_RELOCATABLE) && !defined(VMS)
4067 /* If the normal TARGET_SYSTEM_ROOT is inside of $exec_prefix,
4068 then consider it to relocate with the rest of the GCC installation
4069 if GCC_EXEC_PREFIX is set.
4070 ``make_relative_prefix'' is not compiled for VMS, so don't call it. */
4071 if (target_system_root && !target_system_root_changed && gcc_exec_prefix)
4073 char *tmp_prefix = get_relative_prefix (decoded_options[0].arg,
4074 standard_bindir_prefix,
4075 target_system_root);
4076 if (tmp_prefix && access_check (tmp_prefix, F_OK) == 0)
4078 target_system_root = tmp_prefix;
4079 target_system_root_changed = 1;
4082 #endif
4084 /* More prefixes are enabled in main, after we read the specs file
4085 and determine whether this is cross-compilation or not. */
4087 if (n_infiles == last_language_n_infiles && spec_lang != 0)
4088 warning (0, "%<-x %s%> after last input file has no effect", spec_lang);
4090 /* Synthesize -fcompare-debug flag from the GCC_COMPARE_DEBUG
4091 environment variable. */
4092 if (compare_debug == 2 || compare_debug == 3)
4094 const char *opt = concat ("-fcompare-debug=", compare_debug_opt, NULL);
4095 save_switch (opt, 0, NULL, false, true);
4096 compare_debug = 1;
4099 /* Ensure we only invoke each subprocess once. */
4100 if (print_subprocess_help || print_help_list || print_version)
4102 n_infiles = 0;
4104 /* Create a dummy input file, so that we can pass
4105 the help option on to the various sub-processes. */
4106 add_infile ("help-dummy", "c");
4109 alloc_switch ();
4110 switches[n_switches].part1 = 0;
4111 alloc_infile ();
4112 infiles[n_infiles].name = 0;
4115 /* Store switches not filtered out by %<S in spec in COLLECT_GCC_OPTIONS
4116 and place that in the environment. */
4118 static void
4119 set_collect_gcc_options (void)
4121 int i;
4122 int first_time;
4124 /* Build COLLECT_GCC_OPTIONS to have all of the options specified to
4125 the compiler. */
4126 obstack_grow (&collect_obstack, "COLLECT_GCC_OPTIONS=",
4127 sizeof ("COLLECT_GCC_OPTIONS=") - 1);
4129 first_time = TRUE;
4130 for (i = 0; (int) i < n_switches; i++)
4132 const char *const *args;
4133 const char *p, *q;
4134 if (!first_time)
4135 obstack_grow (&collect_obstack, " ", 1);
4137 first_time = FALSE;
4139 /* Ignore elided switches. */
4140 if ((switches[i].live_cond
4141 & (SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC))
4142 == SWITCH_IGNORE)
4143 continue;
4145 obstack_grow (&collect_obstack, "'-", 2);
4146 q = switches[i].part1;
4147 while ((p = strchr (q, '\'')))
4149 obstack_grow (&collect_obstack, q, p - q);
4150 obstack_grow (&collect_obstack, "'\\''", 4);
4151 q = ++p;
4153 obstack_grow (&collect_obstack, q, strlen (q));
4154 obstack_grow (&collect_obstack, "'", 1);
4156 for (args = switches[i].args; args && *args; args++)
4158 obstack_grow (&collect_obstack, " '", 2);
4159 q = *args;
4160 while ((p = strchr (q, '\'')))
4162 obstack_grow (&collect_obstack, q, p - q);
4163 obstack_grow (&collect_obstack, "'\\''", 4);
4164 q = ++p;
4166 obstack_grow (&collect_obstack, q, strlen (q));
4167 obstack_grow (&collect_obstack, "'", 1);
4170 obstack_grow (&collect_obstack, "\0", 1);
4171 xputenv (XOBFINISH (&collect_obstack, char *));
4174 /* Process a spec string, accumulating and running commands. */
4176 /* These variables describe the input file name.
4177 input_file_number is the index on outfiles of this file,
4178 so that the output file name can be stored for later use by %o.
4179 input_basename is the start of the part of the input file
4180 sans all directory names, and basename_length is the number
4181 of characters starting there excluding the suffix .c or whatever. */
4183 static const char *gcc_input_filename;
4184 static int input_file_number;
4185 size_t input_filename_length;
4186 static int basename_length;
4187 static int suffixed_basename_length;
4188 static const char *input_basename;
4189 static const char *input_suffix;
4190 #ifndef HOST_LACKS_INODE_NUMBERS
4191 static struct stat input_stat;
4192 #endif
4193 static int input_stat_set;
4195 /* The compiler used to process the current input file. */
4196 static struct compiler *input_file_compiler;
4198 /* These are variables used within do_spec and do_spec_1. */
4200 /* Nonzero if an arg has been started and not yet terminated
4201 (with space, tab or newline). */
4202 static int arg_going;
4204 /* Nonzero means %d or %g has been seen; the next arg to be terminated
4205 is a temporary file name. */
4206 static int delete_this_arg;
4208 /* Nonzero means %w has been seen; the next arg to be terminated
4209 is the output file name of this compilation. */
4210 static int this_is_output_file;
4212 /* Nonzero means %s has been seen; the next arg to be terminated
4213 is the name of a library file and we should try the standard
4214 search dirs for it. */
4215 static int this_is_library_file;
4217 /* Nonzero means %T has been seen; the next arg to be terminated
4218 is the name of a linker script and we should try all of the
4219 standard search dirs for it. If it is found insert a --script
4220 command line switch and then substitute the full path in place,
4221 otherwise generate an error message. */
4222 static int this_is_linker_script;
4224 /* Nonzero means that the input of this command is coming from a pipe. */
4225 static int input_from_pipe;
4227 /* Nonnull means substitute this for any suffix when outputting a switches
4228 arguments. */
4229 static const char *suffix_subst;
4231 /* If there is an argument being accumulated, terminate it and store it. */
4233 static void
4234 end_going_arg (void)
4236 if (arg_going)
4238 const char *string;
4240 obstack_1grow (&obstack, 0);
4241 string = XOBFINISH (&obstack, const char *);
4242 if (this_is_library_file)
4243 string = find_file (string);
4244 if (this_is_linker_script)
4246 char * full_script_path = find_a_file (&startfile_prefixes, string, R_OK, true);
4248 if (full_script_path == NULL)
4250 error ("unable to locate default linker script %qs in the library search paths", string);
4251 /* Script was not found on search path. */
4252 return;
4254 store_arg ("--script", false, false);
4255 string = full_script_path;
4257 store_arg (string, delete_this_arg, this_is_output_file);
4258 if (this_is_output_file)
4259 outfiles[input_file_number] = string;
4260 arg_going = 0;
4265 /* Parse the WRAPPER string which is a comma separated list of the command line
4266 and insert them into the beginning of argbuf. */
4268 static void
4269 insert_wrapper (const char *wrapper)
4271 int n = 0;
4272 int i;
4273 char *buf = xstrdup (wrapper);
4274 char *p = buf;
4275 unsigned int old_length = argbuf.length ();
4279 n++;
4280 while (*p == ',')
4281 p++;
4283 while ((p = strchr (p, ',')) != NULL);
4285 argbuf.safe_grow (old_length + n);
4286 memmove (argbuf.address () + n,
4287 argbuf.address (),
4288 old_length * sizeof (const_char_p));
4290 i = 0;
4291 p = buf;
4294 while (*p == ',')
4296 *p = 0;
4297 p++;
4299 argbuf[i] = p;
4300 i++;
4302 while ((p = strchr (p, ',')) != NULL);
4303 gcc_assert (i == n);
4306 /* Process the spec SPEC and run the commands specified therein.
4307 Returns 0 if the spec is successfully processed; -1 if failed. */
4310 do_spec (const char *spec)
4312 int value;
4314 value = do_spec_2 (spec);
4316 /* Force out any unfinished command.
4317 If -pipe, this forces out the last command if it ended in `|'. */
4318 if (value == 0)
4320 if (argbuf.length () > 0
4321 && !strcmp (argbuf.last (), "|"))
4322 argbuf.pop ();
4324 set_collect_gcc_options ();
4326 if (argbuf.length () > 0)
4327 value = execute ();
4330 return value;
4333 static int
4334 do_spec_2 (const char *spec)
4336 int result;
4338 clear_args ();
4339 arg_going = 0;
4340 delete_this_arg = 0;
4341 this_is_output_file = 0;
4342 this_is_library_file = 0;
4343 this_is_linker_script = 0;
4344 input_from_pipe = 0;
4345 suffix_subst = NULL;
4347 result = do_spec_1 (spec, 0, NULL);
4349 end_going_arg ();
4351 return result;
4355 /* Process the given spec string and add any new options to the end
4356 of the switches/n_switches array. */
4358 static void
4359 do_option_spec (const char *name, const char *spec)
4361 unsigned int i, value_count, value_len;
4362 const char *p, *q, *value;
4363 char *tmp_spec, *tmp_spec_p;
4365 if (configure_default_options[0].name == NULL)
4366 return;
4368 for (i = 0; i < ARRAY_SIZE (configure_default_options); i++)
4369 if (strcmp (configure_default_options[i].name, name) == 0)
4370 break;
4371 if (i == ARRAY_SIZE (configure_default_options))
4372 return;
4374 value = configure_default_options[i].value;
4375 value_len = strlen (value);
4377 /* Compute the size of the final spec. */
4378 value_count = 0;
4379 p = spec;
4380 while ((p = strstr (p, "%(VALUE)")) != NULL)
4382 p ++;
4383 value_count ++;
4386 /* Replace each %(VALUE) by the specified value. */
4387 tmp_spec = (char *) alloca (strlen (spec) + 1
4388 + value_count * (value_len - strlen ("%(VALUE)")));
4389 tmp_spec_p = tmp_spec;
4390 q = spec;
4391 while ((p = strstr (q, "%(VALUE)")) != NULL)
4393 memcpy (tmp_spec_p, q, p - q);
4394 tmp_spec_p = tmp_spec_p + (p - q);
4395 memcpy (tmp_spec_p, value, value_len);
4396 tmp_spec_p += value_len;
4397 q = p + strlen ("%(VALUE)");
4399 strcpy (tmp_spec_p, q);
4401 do_self_spec (tmp_spec);
4404 /* Process the given spec string and add any new options to the end
4405 of the switches/n_switches array. */
4407 static void
4408 do_self_spec (const char *spec)
4410 int i;
4412 do_spec_2 (spec);
4413 do_spec_1 (" ", 0, NULL);
4415 /* Mark %<S switches processed by do_self_spec to be ignored permanently.
4416 do_self_specs adds the replacements to switches array, so it shouldn't
4417 be processed afterwards. */
4418 for (i = 0; i < n_switches; i++)
4419 if ((switches[i].live_cond & SWITCH_IGNORE))
4420 switches[i].live_cond |= SWITCH_IGNORE_PERMANENTLY;
4422 if (argbuf.length () > 0)
4424 const char **argbuf_copy;
4425 struct cl_decoded_option *decoded_options;
4426 struct cl_option_handlers handlers;
4427 unsigned int decoded_options_count;
4428 unsigned int j;
4430 /* Create a copy of argbuf with a dummy argv[0] entry for
4431 decode_cmdline_options_to_array. */
4432 argbuf_copy = XNEWVEC (const char *,
4433 argbuf.length () + 1);
4434 argbuf_copy[0] = "";
4435 memcpy (argbuf_copy + 1, argbuf.address (),
4436 argbuf.length () * sizeof (const char *));
4438 decode_cmdline_options_to_array (argbuf.length () + 1,
4439 argbuf_copy,
4440 CL_DRIVER, &decoded_options,
4441 &decoded_options_count);
4442 free (argbuf_copy);
4444 set_option_handlers (&handlers);
4446 for (j = 1; j < decoded_options_count; j++)
4448 switch (decoded_options[j].opt_index)
4450 case OPT_SPECIAL_input_file:
4451 /* Specs should only generate options, not input
4452 files. */
4453 if (strcmp (decoded_options[j].arg, "-") != 0)
4454 fatal_error ("switch %qs does not start with %<-%>",
4455 decoded_options[j].arg);
4456 else
4457 fatal_error ("spec-generated switch is just %<-%>");
4458 break;
4460 case OPT_fcompare_debug_second:
4461 case OPT_fcompare_debug:
4462 case OPT_fcompare_debug_:
4463 case OPT_o:
4464 /* Avoid duplicate processing of some options from
4465 compare-debug specs; just save them here. */
4466 save_switch (decoded_options[j].canonical_option[0],
4467 (decoded_options[j].canonical_option_num_elements
4468 - 1),
4469 &decoded_options[j].canonical_option[1], false, true);
4470 break;
4472 default:
4473 read_cmdline_option (&global_options, &global_options_set,
4474 decoded_options + j, UNKNOWN_LOCATION,
4475 CL_DRIVER, &handlers, global_dc);
4476 break;
4480 alloc_switch ();
4481 switches[n_switches].part1 = 0;
4485 /* Callback for processing %D and %I specs. */
4487 struct spec_path_info {
4488 const char *option;
4489 const char *append;
4490 size_t append_len;
4491 bool omit_relative;
4492 bool separate_options;
4495 static void *
4496 spec_path (char *path, void *data)
4498 struct spec_path_info *info = (struct spec_path_info *) data;
4499 size_t len = 0;
4500 char save = 0;
4502 if (info->omit_relative && !IS_ABSOLUTE_PATH (path))
4503 return NULL;
4505 if (info->append_len != 0)
4507 len = strlen (path);
4508 memcpy (path + len, info->append, info->append_len + 1);
4511 if (!is_directory (path, true))
4512 return NULL;
4514 do_spec_1 (info->option, 1, NULL);
4515 if (info->separate_options)
4516 do_spec_1 (" ", 0, NULL);
4518 if (info->append_len == 0)
4520 len = strlen (path);
4521 save = path[len - 1];
4522 if (IS_DIR_SEPARATOR (path[len - 1]))
4523 path[len - 1] = '\0';
4526 do_spec_1 (path, 1, NULL);
4527 do_spec_1 (" ", 0, NULL);
4529 /* Must not damage the original path. */
4530 if (info->append_len == 0)
4531 path[len - 1] = save;
4533 return NULL;
4536 /* Create a temporary FILE with the contents of ARGV. Add @FILE to the
4537 argument list. */
4539 static void
4540 create_at_file (char **argv)
4542 char *temp_file = make_temp_file ("");
4543 char *at_argument = concat ("@", temp_file, NULL);
4544 FILE *f = fopen (temp_file, "w");
4545 int status;
4547 if (f == NULL)
4548 fatal_error ("could not open temporary response file %s",
4549 temp_file);
4551 status = writeargv (argv, f);
4553 if (status)
4554 fatal_error ("could not write to temporary response file %s",
4555 temp_file);
4557 status = fclose (f);
4559 if (EOF == status)
4560 fatal_error ("could not close temporary response file %s",
4561 temp_file);
4563 store_arg (at_argument, 0, 0);
4565 record_temp_file (temp_file, !save_temps_flag, !save_temps_flag);
4568 /* True if we should compile INFILE. */
4570 static bool
4571 compile_input_file_p (struct infile *infile)
4573 if ((!infile->language) || (infile->language[0] != '*'))
4574 if (infile->incompiler == input_file_compiler)
4575 return true;
4576 return false;
4579 /* Process each member of VEC as a spec. */
4581 static void
4582 do_specs_vec (vec<char_p> vec)
4584 unsigned ix;
4585 char *opt;
4587 FOR_EACH_VEC_ELT (vec, ix, opt)
4589 do_spec_1 (opt, 1, NULL);
4590 /* Make each accumulated option a separate argument. */
4591 do_spec_1 (" ", 0, NULL);
4595 /* Process the sub-spec SPEC as a portion of a larger spec.
4596 This is like processing a whole spec except that we do
4597 not initialize at the beginning and we do not supply a
4598 newline by default at the end.
4599 INSWITCH nonzero means don't process %-sequences in SPEC;
4600 in this case, % is treated as an ordinary character.
4601 This is used while substituting switches.
4602 INSWITCH nonzero also causes SPC not to terminate an argument.
4604 Value is zero unless a line was finished
4605 and the command on that line reported an error. */
4607 static int
4608 do_spec_1 (const char *spec, int inswitch, const char *soft_matched_part)
4610 const char *p = spec;
4611 int c;
4612 int i;
4613 int value;
4615 /* If it's an empty string argument to a switch, keep it as is. */
4616 if (inswitch && !*p)
4617 arg_going = 1;
4619 while ((c = *p++))
4620 /* If substituting a switch, treat all chars like letters.
4621 Otherwise, NL, SPC, TAB and % are special. */
4622 switch (inswitch ? 'a' : c)
4624 case '\n':
4625 end_going_arg ();
4627 if (argbuf.length () > 0
4628 && !strcmp (argbuf.last (), "|"))
4630 /* A `|' before the newline means use a pipe here,
4631 but only if -pipe was specified.
4632 Otherwise, execute now and don't pass the `|' as an arg. */
4633 if (use_pipes)
4635 input_from_pipe = 1;
4636 break;
4638 else
4639 argbuf.pop ();
4642 set_collect_gcc_options ();
4644 if (argbuf.length () > 0)
4646 value = execute ();
4647 if (value)
4648 return value;
4650 /* Reinitialize for a new command, and for a new argument. */
4651 clear_args ();
4652 arg_going = 0;
4653 delete_this_arg = 0;
4654 this_is_output_file = 0;
4655 this_is_library_file = 0;
4656 this_is_linker_script = 0;
4657 input_from_pipe = 0;
4658 break;
4660 case '|':
4661 end_going_arg ();
4663 /* Use pipe */
4664 obstack_1grow (&obstack, c);
4665 arg_going = 1;
4666 break;
4668 case '\t':
4669 case ' ':
4670 end_going_arg ();
4672 /* Reinitialize for a new argument. */
4673 delete_this_arg = 0;
4674 this_is_output_file = 0;
4675 this_is_library_file = 0;
4676 this_is_linker_script = 0;
4677 break;
4679 case '%':
4680 switch (c = *p++)
4682 case 0:
4683 fatal_error ("spec %qs invalid", spec);
4685 case 'b':
4686 if (save_temps_length)
4687 obstack_grow (&obstack, save_temps_prefix, save_temps_length);
4688 else
4689 obstack_grow (&obstack, input_basename, basename_length);
4690 if (compare_debug < 0)
4691 obstack_grow (&obstack, ".gk", 3);
4692 arg_going = 1;
4693 break;
4695 case 'B':
4696 if (save_temps_length)
4697 obstack_grow (&obstack, save_temps_prefix, save_temps_length);
4698 else
4699 obstack_grow (&obstack, input_basename, suffixed_basename_length);
4700 if (compare_debug < 0)
4701 obstack_grow (&obstack, ".gk", 3);
4702 arg_going = 1;
4703 break;
4705 case 'd':
4706 delete_this_arg = 2;
4707 break;
4709 /* Dump out the directories specified with LIBRARY_PATH,
4710 followed by the absolute directories
4711 that we search for startfiles. */
4712 case 'D':
4714 struct spec_path_info info;
4716 info.option = "-L";
4717 info.append_len = 0;
4718 #ifdef RELATIVE_PREFIX_NOT_LINKDIR
4719 /* Used on systems which record the specified -L dirs
4720 and use them to search for dynamic linking.
4721 Relative directories always come from -B,
4722 and it is better not to use them for searching
4723 at run time. In particular, stage1 loses. */
4724 info.omit_relative = true;
4725 #else
4726 info.omit_relative = false;
4727 #endif
4728 info.separate_options = false;
4730 for_each_path (&startfile_prefixes, true, 0, spec_path, &info);
4732 break;
4734 case 'e':
4735 /* %efoo means report an error with `foo' as error message
4736 and don't execute any more commands for this file. */
4738 const char *q = p;
4739 char *buf;
4740 while (*p != 0 && *p != '\n')
4741 p++;
4742 buf = (char *) alloca (p - q + 1);
4743 strncpy (buf, q, p - q);
4744 buf[p - q] = 0;
4745 error ("%s", _(buf));
4746 return -1;
4748 break;
4749 case 'n':
4750 /* %nfoo means report a notice with `foo' on stderr. */
4752 const char *q = p;
4753 char *buf;
4754 while (*p != 0 && *p != '\n')
4755 p++;
4756 buf = (char *) alloca (p - q + 1);
4757 strncpy (buf, q, p - q);
4758 buf[p - q] = 0;
4759 inform (0, "%s", _(buf));
4760 if (*p)
4761 p++;
4763 break;
4765 case 'j':
4767 struct stat st;
4769 /* If save_temps_flag is off, and the HOST_BIT_BUCKET is
4770 defined, and it is not a directory, and it is
4771 writable, use it. Otherwise, treat this like any
4772 other temporary file. */
4774 if ((!save_temps_flag)
4775 && (stat (HOST_BIT_BUCKET, &st) == 0) && (!S_ISDIR (st.st_mode))
4776 && (access (HOST_BIT_BUCKET, W_OK) == 0))
4778 obstack_grow (&obstack, HOST_BIT_BUCKET,
4779 strlen (HOST_BIT_BUCKET));
4780 delete_this_arg = 0;
4781 arg_going = 1;
4782 break;
4785 goto create_temp_file;
4786 case '|':
4787 if (use_pipes)
4789 obstack_1grow (&obstack, '-');
4790 delete_this_arg = 0;
4791 arg_going = 1;
4793 /* consume suffix */
4794 while (*p == '.' || ISALNUM ((unsigned char) *p))
4795 p++;
4796 if (p[0] == '%' && p[1] == 'O')
4797 p += 2;
4799 break;
4801 goto create_temp_file;
4802 case 'm':
4803 if (use_pipes)
4805 /* consume suffix */
4806 while (*p == '.' || ISALNUM ((unsigned char) *p))
4807 p++;
4808 if (p[0] == '%' && p[1] == 'O')
4809 p += 2;
4811 break;
4813 goto create_temp_file;
4814 case 'g':
4815 case 'u':
4816 case 'U':
4817 create_temp_file:
4819 struct temp_name *t;
4820 int suffix_length;
4821 const char *suffix = p;
4822 char *saved_suffix = NULL;
4824 while (*p == '.' || ISALNUM ((unsigned char) *p))
4825 p++;
4826 suffix_length = p - suffix;
4827 if (p[0] == '%' && p[1] == 'O')
4829 p += 2;
4830 /* We don't support extra suffix characters after %O. */
4831 if (*p == '.' || ISALNUM ((unsigned char) *p))
4832 fatal_error ("spec %qs has invalid %<%%0%c%>", spec, *p);
4833 if (suffix_length == 0)
4834 suffix = TARGET_OBJECT_SUFFIX;
4835 else
4837 saved_suffix
4838 = XNEWVEC (char, suffix_length
4839 + strlen (TARGET_OBJECT_SUFFIX));
4840 strncpy (saved_suffix, suffix, suffix_length);
4841 strcpy (saved_suffix + suffix_length,
4842 TARGET_OBJECT_SUFFIX);
4844 suffix_length += strlen (TARGET_OBJECT_SUFFIX);
4847 if (compare_debug < 0)
4849 suffix = concat (".gk", suffix, NULL);
4850 suffix_length += 3;
4853 /* If -save-temps=obj and -o were specified, use that for the
4854 temp file. */
4855 if (save_temps_length)
4857 char *tmp;
4858 temp_filename_length
4859 = save_temps_length + suffix_length + 1;
4860 tmp = (char *) alloca (temp_filename_length);
4861 memcpy (tmp, save_temps_prefix, save_temps_length);
4862 memcpy (tmp + save_temps_length, suffix, suffix_length);
4863 tmp[save_temps_length + suffix_length] = '\0';
4864 temp_filename = save_string (tmp, save_temps_length
4865 + suffix_length);
4866 obstack_grow (&obstack, temp_filename,
4867 temp_filename_length);
4868 arg_going = 1;
4869 delete_this_arg = 0;
4870 break;
4873 /* If the gcc_input_filename has the same suffix specified
4874 for the %g, %u, or %U, and -save-temps is specified,
4875 we could end up using that file as an intermediate
4876 thus clobbering the user's source file (.e.g.,
4877 gcc -save-temps foo.s would clobber foo.s with the
4878 output of cpp0). So check for this condition and
4879 generate a temp file as the intermediate. */
4881 if (save_temps_flag)
4883 char *tmp;
4884 temp_filename_length = basename_length + suffix_length + 1;
4885 tmp = (char *) alloca (temp_filename_length);
4886 memcpy (tmp, input_basename, basename_length);
4887 memcpy (tmp + basename_length, suffix, suffix_length);
4888 tmp[basename_length + suffix_length] = '\0';
4889 temp_filename = tmp;
4891 if (filename_cmp (temp_filename, gcc_input_filename) != 0)
4893 #ifndef HOST_LACKS_INODE_NUMBERS
4894 struct stat st_temp;
4896 /* Note, set_input() resets input_stat_set to 0. */
4897 if (input_stat_set == 0)
4899 input_stat_set = stat (gcc_input_filename,
4900 &input_stat);
4901 if (input_stat_set >= 0)
4902 input_stat_set = 1;
4905 /* If we have the stat for the gcc_input_filename
4906 and we can do the stat for the temp_filename
4907 then the they could still refer to the same
4908 file if st_dev/st_ino's are the same. */
4909 if (input_stat_set != 1
4910 || stat (temp_filename, &st_temp) < 0
4911 || input_stat.st_dev != st_temp.st_dev
4912 || input_stat.st_ino != st_temp.st_ino)
4913 #else
4914 /* Just compare canonical pathnames. */
4915 char* input_realname = lrealpath (gcc_input_filename);
4916 char* temp_realname = lrealpath (temp_filename);
4917 bool files_differ = filename_cmp (input_realname, temp_realname);
4918 free (input_realname);
4919 free (temp_realname);
4920 if (files_differ)
4921 #endif
4923 temp_filename = save_string (temp_filename,
4924 temp_filename_length + 1);
4925 obstack_grow (&obstack, temp_filename,
4926 temp_filename_length);
4927 arg_going = 1;
4928 delete_this_arg = 0;
4929 break;
4934 /* See if we already have an association of %g/%u/%U and
4935 suffix. */
4936 for (t = temp_names; t; t = t->next)
4937 if (t->length == suffix_length
4938 && strncmp (t->suffix, suffix, suffix_length) == 0
4939 && t->unique == (c == 'u' || c == 'U' || c == 'j'))
4940 break;
4942 /* Make a new association if needed. %u and %j
4943 require one. */
4944 if (t == 0 || c == 'u' || c == 'j')
4946 if (t == 0)
4948 t = XNEW (struct temp_name);
4949 t->next = temp_names;
4950 temp_names = t;
4952 t->length = suffix_length;
4953 if (saved_suffix)
4955 t->suffix = saved_suffix;
4956 saved_suffix = NULL;
4958 else
4959 t->suffix = save_string (suffix, suffix_length);
4960 t->unique = (c == 'u' || c == 'U' || c == 'j');
4961 temp_filename = make_temp_file (t->suffix);
4962 temp_filename_length = strlen (temp_filename);
4963 t->filename = temp_filename;
4964 t->filename_length = temp_filename_length;
4967 free (saved_suffix);
4969 obstack_grow (&obstack, t->filename, t->filename_length);
4970 delete_this_arg = 1;
4972 arg_going = 1;
4973 break;
4975 case 'i':
4976 if (combine_inputs)
4978 if (at_file_supplied)
4980 /* We are going to expand `%i' to `@FILE', where FILE
4981 is a newly-created temporary filename. The filenames
4982 that would usually be expanded in place of %o will be
4983 written to the temporary file. */
4984 char **argv;
4985 int n_files = 0;
4986 int j;
4988 for (i = 0; i < n_infiles; i++)
4989 if (compile_input_file_p (&infiles[i]))
4990 n_files++;
4992 argv = (char **) alloca (sizeof (char *) * (n_files + 1));
4994 /* Copy the strings over. */
4995 for (i = 0, j = 0; i < n_infiles; i++)
4996 if (compile_input_file_p (&infiles[i]))
4998 argv[j] = CONST_CAST (char *, infiles[i].name);
4999 infiles[i].compiled = true;
5000 j++;
5002 argv[j] = NULL;
5004 create_at_file (argv);
5006 else
5007 for (i = 0; (int) i < n_infiles; i++)
5008 if (compile_input_file_p (&infiles[i]))
5010 store_arg (infiles[i].name, 0, 0);
5011 infiles[i].compiled = true;
5014 else
5016 obstack_grow (&obstack, gcc_input_filename,
5017 input_filename_length);
5018 arg_going = 1;
5020 break;
5022 case 'I':
5024 struct spec_path_info info;
5026 if (multilib_dir)
5028 do_spec_1 ("-imultilib", 1, NULL);
5029 /* Make this a separate argument. */
5030 do_spec_1 (" ", 0, NULL);
5031 do_spec_1 (multilib_dir, 1, NULL);
5032 do_spec_1 (" ", 0, NULL);
5035 if (multiarch_dir)
5037 do_spec_1 ("-imultiarch", 1, NULL);
5038 /* Make this a separate argument. */
5039 do_spec_1 (" ", 0, NULL);
5040 do_spec_1 (multiarch_dir, 1, NULL);
5041 do_spec_1 (" ", 0, NULL);
5044 if (gcc_exec_prefix)
5046 do_spec_1 ("-iprefix", 1, NULL);
5047 /* Make this a separate argument. */
5048 do_spec_1 (" ", 0, NULL);
5049 do_spec_1 (gcc_exec_prefix, 1, NULL);
5050 do_spec_1 (" ", 0, NULL);
5053 if (target_system_root_changed ||
5054 (target_system_root && target_sysroot_hdrs_suffix))
5056 do_spec_1 ("-isysroot", 1, NULL);
5057 /* Make this a separate argument. */
5058 do_spec_1 (" ", 0, NULL);
5059 do_spec_1 (target_system_root, 1, NULL);
5060 if (target_sysroot_hdrs_suffix)
5061 do_spec_1 (target_sysroot_hdrs_suffix, 1, NULL);
5062 do_spec_1 (" ", 0, NULL);
5065 info.option = "-isystem";
5066 info.append = "include";
5067 info.append_len = strlen (info.append);
5068 info.omit_relative = false;
5069 info.separate_options = true;
5071 for_each_path (&include_prefixes, false, info.append_len,
5072 spec_path, &info);
5074 info.append = "include-fixed";
5075 if (*sysroot_hdrs_suffix_spec)
5076 info.append = concat (info.append, dir_separator_str,
5077 multilib_dir, NULL);
5078 info.append_len = strlen (info.append);
5079 for_each_path (&include_prefixes, false, info.append_len,
5080 spec_path, &info);
5082 break;
5084 case 'o':
5086 int max = n_infiles;
5087 max += lang_specific_extra_outfiles;
5089 if (HAVE_GNU_LD && at_file_supplied)
5091 /* We are going to expand `%o' to `@FILE', where FILE
5092 is a newly-created temporary filename. The filenames
5093 that would usually be expanded in place of %o will be
5094 written to the temporary file. */
5096 char **argv;
5097 int n_files, j;
5099 /* Convert OUTFILES into a form suitable for writeargv. */
5101 /* Determine how many are non-NULL. */
5102 for (n_files = 0, i = 0; i < max; i++)
5103 n_files += outfiles[i] != NULL;
5105 argv = (char **) alloca (sizeof (char *) * (n_files + 1));
5107 /* Copy the strings over. */
5108 for (i = 0, j = 0; i < max; i++)
5109 if (outfiles[i])
5111 argv[j] = CONST_CAST (char *, outfiles[i]);
5112 j++;
5114 argv[j] = NULL;
5116 create_at_file (argv);
5118 else
5119 for (i = 0; i < max; i++)
5120 if (outfiles[i])
5121 store_arg (outfiles[i], 0, 0);
5122 break;
5125 case 'O':
5126 obstack_grow (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
5127 arg_going = 1;
5128 break;
5130 case 's':
5131 this_is_library_file = 1;
5132 break;
5134 case 'T':
5135 this_is_linker_script = 1;
5136 break;
5138 case 'V':
5139 outfiles[input_file_number] = NULL;
5140 break;
5142 case 'w':
5143 this_is_output_file = 1;
5144 break;
5146 case 'W':
5148 unsigned int cur_index = argbuf.length ();
5149 /* Handle the {...} following the %W. */
5150 if (*p != '{')
5151 fatal_error ("spec %qs has invalid %<%%W%c%>", spec, *p);
5152 p = handle_braces (p + 1);
5153 if (p == 0)
5154 return -1;
5155 end_going_arg ();
5156 /* If any args were output, mark the last one for deletion
5157 on failure. */
5158 if (argbuf.length () != cur_index)
5159 record_temp_file (argbuf.last (), 0, 1);
5160 break;
5163 /* %x{OPTION} records OPTION for %X to output. */
5164 case 'x':
5166 const char *p1 = p;
5167 char *string;
5168 char *opt;
5169 unsigned ix;
5171 /* Skip past the option value and make a copy. */
5172 if (*p != '{')
5173 fatal_error ("spec %qs has invalid %<%%x%c%>", spec, *p);
5174 while (*p++ != '}')
5176 string = save_string (p1 + 1, p - p1 - 2);
5178 /* See if we already recorded this option. */
5179 FOR_EACH_VEC_ELT (linker_options, ix, opt)
5180 if (! strcmp (string, opt))
5182 free (string);
5183 return 0;
5186 /* This option is new; add it. */
5187 add_linker_option (string, strlen (string));
5188 free (string);
5190 break;
5192 /* Dump out the options accumulated previously using %x. */
5193 case 'X':
5194 do_specs_vec (linker_options);
5195 break;
5197 /* Dump out the options accumulated previously using -Wa,. */
5198 case 'Y':
5199 do_specs_vec (assembler_options);
5200 break;
5202 /* Dump out the options accumulated previously using -Wp,. */
5203 case 'Z':
5204 do_specs_vec (preprocessor_options);
5205 break;
5207 /* Here are digits and numbers that just process
5208 a certain constant string as a spec. */
5210 case '1':
5211 value = do_spec_1 (cc1_spec, 0, NULL);
5212 if (value != 0)
5213 return value;
5214 break;
5216 case '2':
5217 value = do_spec_1 (cc1plus_spec, 0, NULL);
5218 if (value != 0)
5219 return value;
5220 break;
5222 case 'a':
5223 value = do_spec_1 (asm_spec, 0, NULL);
5224 if (value != 0)
5225 return value;
5226 break;
5228 case 'A':
5229 value = do_spec_1 (asm_final_spec, 0, NULL);
5230 if (value != 0)
5231 return value;
5232 break;
5234 case 'C':
5236 const char *const spec
5237 = (input_file_compiler->cpp_spec
5238 ? input_file_compiler->cpp_spec
5239 : cpp_spec);
5240 value = do_spec_1 (spec, 0, NULL);
5241 if (value != 0)
5242 return value;
5244 break;
5246 case 'E':
5247 value = do_spec_1 (endfile_spec, 0, NULL);
5248 if (value != 0)
5249 return value;
5250 break;
5252 case 'l':
5253 value = do_spec_1 (link_spec, 0, NULL);
5254 if (value != 0)
5255 return value;
5256 break;
5258 case 'L':
5259 value = do_spec_1 (lib_spec, 0, NULL);
5260 if (value != 0)
5261 return value;
5262 break;
5264 case 'M':
5265 if (multilib_os_dir == NULL)
5266 obstack_1grow (&obstack, '.');
5267 else
5268 obstack_grow (&obstack, multilib_os_dir,
5269 strlen (multilib_os_dir));
5270 break;
5272 case 'G':
5273 value = do_spec_1 (libgcc_spec, 0, NULL);
5274 if (value != 0)
5275 return value;
5276 break;
5278 case 'R':
5279 /* We assume there is a directory
5280 separator at the end of this string. */
5281 if (target_system_root)
5283 obstack_grow (&obstack, target_system_root,
5284 strlen (target_system_root));
5285 if (target_sysroot_suffix)
5286 obstack_grow (&obstack, target_sysroot_suffix,
5287 strlen (target_sysroot_suffix));
5289 break;
5291 case 'S':
5292 value = do_spec_1 (startfile_spec, 0, NULL);
5293 if (value != 0)
5294 return value;
5295 break;
5297 /* Here we define characters other than letters and digits. */
5299 case '{':
5300 p = handle_braces (p);
5301 if (p == 0)
5302 return -1;
5303 break;
5305 case ':':
5306 p = handle_spec_function (p, NULL);
5307 if (p == 0)
5308 return -1;
5309 break;
5311 case '%':
5312 obstack_1grow (&obstack, '%');
5313 break;
5315 case '.':
5317 unsigned len = 0;
5319 while (p[len] && p[len] != ' ' && p[len] != '%')
5320 len++;
5321 suffix_subst = save_string (p - 1, len + 1);
5322 p += len;
5324 break;
5326 /* Henceforth ignore the option(s) matching the pattern
5327 after the %<. */
5328 case '<':
5329 case '>':
5331 unsigned len = 0;
5332 int have_wildcard = 0;
5333 int i;
5334 int switch_option;
5336 if (c == '>')
5337 switch_option = SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC;
5338 else
5339 switch_option = SWITCH_IGNORE;
5341 while (p[len] && p[len] != ' ' && p[len] != '\t')
5342 len++;
5344 if (p[len-1] == '*')
5345 have_wildcard = 1;
5347 for (i = 0; i < n_switches; i++)
5348 if (!strncmp (switches[i].part1, p, len - have_wildcard)
5349 && (have_wildcard || switches[i].part1[len] == '\0'))
5351 switches[i].live_cond |= switch_option;
5352 /* User switch be validated from validate_all_switches.
5353 when the definition is seen from the spec file.
5354 If not defined anywhere, will be rejected. */
5355 if (switches[i].known)
5356 switches[i].validated = true;
5359 p += len;
5361 break;
5363 case '*':
5364 if (soft_matched_part)
5366 if (soft_matched_part[0])
5367 do_spec_1 (soft_matched_part, 1, NULL);
5368 /* Only insert a space after the substitution if it is at the
5369 end of the current sequence. So if:
5371 "%{foo=*:bar%*}%{foo=*:one%*two}"
5373 matches -foo=hello then it will produce:
5375 barhello onehellotwo
5377 if (*p == 0 || *p == '}')
5378 do_spec_1 (" ", 0, NULL);
5380 else
5381 /* Catch the case where a spec string contains something like
5382 '%{foo:%*}'. i.e. there is no * in the pattern on the left
5383 hand side of the :. */
5384 error ("spec failure: %<%%*%> has not been initialized by pattern match");
5385 break;
5387 /* Process a string found as the value of a spec given by name.
5388 This feature allows individual machine descriptions
5389 to add and use their own specs. */
5390 case '(':
5392 const char *name = p;
5393 struct spec_list *sl;
5394 int len;
5396 /* The string after the S/P is the name of a spec that is to be
5397 processed. */
5398 while (*p && *p != ')')
5399 p++;
5401 /* See if it's in the list. */
5402 for (len = p - name, sl = specs; sl; sl = sl->next)
5403 if (sl->name_len == len && !strncmp (sl->name, name, len))
5405 name = *(sl->ptr_spec);
5406 #ifdef DEBUG_SPECS
5407 fnotice (stderr, "Processing spec (%s), which is '%s'\n",
5408 sl->name, name);
5409 #endif
5410 break;
5413 if (sl)
5415 value = do_spec_1 (name, 0, NULL);
5416 if (value != 0)
5417 return value;
5420 /* Discard the closing paren. */
5421 if (*p)
5422 p++;
5424 break;
5426 default:
5427 error ("spec failure: unrecognized spec option %qc", c);
5428 break;
5430 break;
5432 case '\\':
5433 /* Backslash: treat next character as ordinary. */
5434 c = *p++;
5436 /* Fall through. */
5437 default:
5438 /* Ordinary character: put it into the current argument. */
5439 obstack_1grow (&obstack, c);
5440 arg_going = 1;
5443 /* End of string. If we are processing a spec function, we need to
5444 end any pending argument. */
5445 if (processing_spec_function)
5446 end_going_arg ();
5448 return 0;
5451 /* Look up a spec function. */
5453 static const struct spec_function *
5454 lookup_spec_function (const char *name)
5456 const struct spec_function *sf;
5458 for (sf = static_spec_functions; sf->name != NULL; sf++)
5459 if (strcmp (sf->name, name) == 0)
5460 return sf;
5462 return NULL;
5465 /* Evaluate a spec function. */
5467 static const char *
5468 eval_spec_function (const char *func, const char *args)
5470 const struct spec_function *sf;
5471 const char *funcval;
5473 /* Saved spec processing context. */
5474 vec<const_char_p> save_argbuf;
5476 int save_arg_going;
5477 int save_delete_this_arg;
5478 int save_this_is_output_file;
5479 int save_this_is_library_file;
5480 int save_input_from_pipe;
5481 int save_this_is_linker_script;
5482 const char *save_suffix_subst;
5484 int save_growing_size;
5485 void *save_growing_value;
5487 sf = lookup_spec_function (func);
5488 if (sf == NULL)
5489 fatal_error ("unknown spec function %qs", func);
5491 /* Push the spec processing context. */
5492 save_argbuf = argbuf;
5494 save_arg_going = arg_going;
5495 save_delete_this_arg = delete_this_arg;
5496 save_this_is_output_file = this_is_output_file;
5497 save_this_is_library_file = this_is_library_file;
5498 save_this_is_linker_script = this_is_linker_script;
5499 save_input_from_pipe = input_from_pipe;
5500 save_suffix_subst = suffix_subst;
5502 /* If we have some object growing now, finalize it so the args and function
5503 eval proceed from a cleared context. This is needed to prevent the first
5504 constructed arg from mistakenly including the growing value. We'll push
5505 this value back on the obstack once the function evaluation is done, to
5506 restore a consistent processing context for our caller. This is fine as
5507 the address of growing objects isn't guaranteed to remain stable until
5508 they are finalized, and we expect this situation to be rare enough for
5509 the extra copy not to be an issue. */
5510 save_growing_size = obstack_object_size (&obstack);
5511 if (save_growing_size > 0)
5512 save_growing_value = obstack_finish (&obstack);
5514 /* Create a new spec processing context, and build the function
5515 arguments. */
5517 alloc_args ();
5518 if (do_spec_2 (args) < 0)
5519 fatal_error ("error in args to spec function %qs", func);
5521 /* argbuf_index is an index for the next argument to be inserted, and
5522 so contains the count of the args already inserted. */
5524 funcval = (*sf->func) (argbuf.length (),
5525 argbuf.address ());
5527 /* Pop the spec processing context. */
5528 argbuf.release ();
5529 argbuf = save_argbuf;
5531 arg_going = save_arg_going;
5532 delete_this_arg = save_delete_this_arg;
5533 this_is_output_file = save_this_is_output_file;
5534 this_is_library_file = save_this_is_library_file;
5535 this_is_linker_script = save_this_is_linker_script;
5536 input_from_pipe = save_input_from_pipe;
5537 suffix_subst = save_suffix_subst;
5539 if (save_growing_size > 0)
5540 obstack_grow (&obstack, save_growing_value, save_growing_size);
5542 return funcval;
5545 /* Handle a spec function call of the form:
5547 %:function(args)
5549 ARGS is processed as a spec in a separate context and split into an
5550 argument vector in the normal fashion. The function returns a string
5551 containing a spec which we then process in the caller's context, or
5552 NULL if no processing is required.
5554 If RETVAL_NONNULL is not NULL, then store a bool whether function
5555 returned non-NULL. */
5557 static const char *
5558 handle_spec_function (const char *p, bool *retval_nonnull)
5560 char *func, *args;
5561 const char *endp, *funcval;
5562 int count;
5564 processing_spec_function++;
5566 /* Get the function name. */
5567 for (endp = p; *endp != '\0'; endp++)
5569 if (*endp == '(') /* ) */
5570 break;
5571 /* Only allow [A-Za-z0-9], -, and _ in function names. */
5572 if (!ISALNUM (*endp) && !(*endp == '-' || *endp == '_'))
5573 fatal_error ("malformed spec function name");
5575 if (*endp != '(') /* ) */
5576 fatal_error ("no arguments for spec function");
5577 func = save_string (p, endp - p);
5578 p = ++endp;
5580 /* Get the arguments. */
5581 for (count = 0; *endp != '\0'; endp++)
5583 /* ( */
5584 if (*endp == ')')
5586 if (count == 0)
5587 break;
5588 count--;
5590 else if (*endp == '(') /* ) */
5591 count++;
5593 /* ( */
5594 if (*endp != ')')
5595 fatal_error ("malformed spec function arguments");
5596 args = save_string (p, endp - p);
5597 p = ++endp;
5599 /* p now points to just past the end of the spec function expression. */
5601 funcval = eval_spec_function (func, args);
5602 if (funcval != NULL && do_spec_1 (funcval, 0, NULL) < 0)
5603 p = NULL;
5604 if (retval_nonnull)
5605 *retval_nonnull = funcval != NULL;
5607 free (func);
5608 free (args);
5610 processing_spec_function--;
5612 return p;
5615 /* Inline subroutine of handle_braces. Returns true if the current
5616 input suffix matches the atom bracketed by ATOM and END_ATOM. */
5617 static inline bool
5618 input_suffix_matches (const char *atom, const char *end_atom)
5620 return (input_suffix
5621 && !strncmp (input_suffix, atom, end_atom - atom)
5622 && input_suffix[end_atom - atom] == '\0');
5625 /* Subroutine of handle_braces. Returns true if the current
5626 input file's spec name matches the atom bracketed by ATOM and END_ATOM. */
5627 static bool
5628 input_spec_matches (const char *atom, const char *end_atom)
5630 return (input_file_compiler
5631 && input_file_compiler->suffix
5632 && input_file_compiler->suffix[0] != '\0'
5633 && !strncmp (input_file_compiler->suffix + 1, atom,
5634 end_atom - atom)
5635 && input_file_compiler->suffix[end_atom - atom + 1] == '\0');
5638 /* Subroutine of handle_braces. Returns true if a switch
5639 matching the atom bracketed by ATOM and END_ATOM appeared on the
5640 command line. */
5641 static bool
5642 switch_matches (const char *atom, const char *end_atom, int starred)
5644 int i;
5645 int len = end_atom - atom;
5646 int plen = starred ? len : -1;
5648 for (i = 0; i < n_switches; i++)
5649 if (!strncmp (switches[i].part1, atom, len)
5650 && (starred || switches[i].part1[len] == '\0')
5651 && check_live_switch (i, plen))
5652 return true;
5654 /* Check if a switch with separated form matching the atom.
5655 We check -D and -U switches. */
5656 else if (switches[i].args != 0)
5658 if ((*switches[i].part1 == 'D' || *switches[i].part1 == 'U')
5659 && *switches[i].part1 == atom[0])
5661 if (!strncmp (switches[i].args[0], &atom[1], len - 1)
5662 && (starred || (switches[i].part1[1] == '\0'
5663 && switches[i].args[0][len - 1] == '\0'))
5664 && check_live_switch (i, (starred ? 1 : -1)))
5665 return true;
5669 return false;
5672 /* Inline subroutine of handle_braces. Mark all of the switches which
5673 match ATOM (extends to END_ATOM; STARRED indicates whether there
5674 was a star after the atom) for later processing. */
5675 static inline void
5676 mark_matching_switches (const char *atom, const char *end_atom, int starred)
5678 int i;
5679 int len = end_atom - atom;
5680 int plen = starred ? len : -1;
5682 for (i = 0; i < n_switches; i++)
5683 if (!strncmp (switches[i].part1, atom, len)
5684 && (starred || switches[i].part1[len] == '\0')
5685 && check_live_switch (i, plen))
5686 switches[i].ordering = 1;
5689 /* Inline subroutine of handle_braces. Process all the currently
5690 marked switches through give_switch, and clear the marks. */
5691 static inline void
5692 process_marked_switches (void)
5694 int i;
5696 for (i = 0; i < n_switches; i++)
5697 if (switches[i].ordering == 1)
5699 switches[i].ordering = 0;
5700 give_switch (i, 0);
5704 /* Handle a %{ ... } construct. P points just inside the leading {.
5705 Returns a pointer one past the end of the brace block, or 0
5706 if we call do_spec_1 and that returns -1. */
5708 static const char *
5709 handle_braces (const char *p)
5711 const char *atom, *end_atom;
5712 const char *d_atom = NULL, *d_end_atom = NULL;
5713 const char *orig = p;
5715 bool a_is_suffix;
5716 bool a_is_spectype;
5717 bool a_is_starred;
5718 bool a_is_negated;
5719 bool a_matched;
5721 bool a_must_be_last = false;
5722 bool ordered_set = false;
5723 bool disjunct_set = false;
5724 bool disj_matched = false;
5725 bool disj_starred = true;
5726 bool n_way_choice = false;
5727 bool n_way_matched = false;
5729 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
5733 if (a_must_be_last)
5734 goto invalid;
5736 /* Scan one "atom" (S in the description above of %{}, possibly
5737 with '!', '.', '@', ',', or '*' modifiers). */
5738 a_matched = false;
5739 a_is_suffix = false;
5740 a_is_starred = false;
5741 a_is_negated = false;
5742 a_is_spectype = false;
5744 SKIP_WHITE ();
5745 if (*p == '!')
5746 p++, a_is_negated = true;
5748 SKIP_WHITE ();
5749 if (*p == '%' && p[1] == ':')
5751 atom = NULL;
5752 end_atom = NULL;
5753 p = handle_spec_function (p + 2, &a_matched);
5755 else
5757 if (*p == '.')
5758 p++, a_is_suffix = true;
5759 else if (*p == ',')
5760 p++, a_is_spectype = true;
5762 atom = p;
5763 while (ISIDNUM (*p) || *p == '-' || *p == '+' || *p == '='
5764 || *p == ',' || *p == '.' || *p == '@')
5765 p++;
5766 end_atom = p;
5768 if (*p == '*')
5769 p++, a_is_starred = 1;
5772 SKIP_WHITE ();
5773 switch (*p)
5775 case '&': case '}':
5776 /* Substitute the switch(es) indicated by the current atom. */
5777 ordered_set = true;
5778 if (disjunct_set || n_way_choice || a_is_negated || a_is_suffix
5779 || a_is_spectype || atom == end_atom)
5780 goto invalid;
5782 mark_matching_switches (atom, end_atom, a_is_starred);
5784 if (*p == '}')
5785 process_marked_switches ();
5786 break;
5788 case '|': case ':':
5789 /* Substitute some text if the current atom appears as a switch
5790 or suffix. */
5791 disjunct_set = true;
5792 if (ordered_set)
5793 goto invalid;
5795 if (atom && atom == end_atom)
5797 if (!n_way_choice || disj_matched || *p == '|'
5798 || a_is_negated || a_is_suffix || a_is_spectype
5799 || a_is_starred)
5800 goto invalid;
5802 /* An empty term may appear as the last choice of an
5803 N-way choice set; it means "otherwise". */
5804 a_must_be_last = true;
5805 disj_matched = !n_way_matched;
5806 disj_starred = false;
5808 else
5810 if ((a_is_suffix || a_is_spectype) && a_is_starred)
5811 goto invalid;
5813 if (!a_is_starred)
5814 disj_starred = false;
5816 /* Don't bother testing this atom if we already have a
5817 match. */
5818 if (!disj_matched && !n_way_matched)
5820 if (atom == NULL)
5821 /* a_matched is already set by handle_spec_function. */;
5822 else if (a_is_suffix)
5823 a_matched = input_suffix_matches (atom, end_atom);
5824 else if (a_is_spectype)
5825 a_matched = input_spec_matches (atom, end_atom);
5826 else
5827 a_matched = switch_matches (atom, end_atom, a_is_starred);
5829 if (a_matched != a_is_negated)
5831 disj_matched = true;
5832 d_atom = atom;
5833 d_end_atom = end_atom;
5838 if (*p == ':')
5840 /* Found the body, that is, the text to substitute if the
5841 current disjunction matches. */
5842 p = process_brace_body (p + 1, d_atom, d_end_atom, disj_starred,
5843 disj_matched && !n_way_matched);
5844 if (p == 0)
5845 return 0;
5847 /* If we have an N-way choice, reset state for the next
5848 disjunction. */
5849 if (*p == ';')
5851 n_way_choice = true;
5852 n_way_matched |= disj_matched;
5853 disj_matched = false;
5854 disj_starred = true;
5855 d_atom = d_end_atom = NULL;
5858 break;
5860 default:
5861 goto invalid;
5864 while (*p++ != '}');
5866 return p;
5868 invalid:
5869 fatal_error ("braced spec %qs is invalid at %qc", orig, *p);
5871 #undef SKIP_WHITE
5874 /* Subroutine of handle_braces. Scan and process a brace substitution body
5875 (X in the description of %{} syntax). P points one past the colon;
5876 ATOM and END_ATOM bracket the first atom which was found to be true
5877 (present) in the current disjunction; STARRED indicates whether all
5878 the atoms in the current disjunction were starred (for syntax validation);
5879 MATCHED indicates whether the disjunction matched or not, and therefore
5880 whether or not the body is to be processed through do_spec_1 or just
5881 skipped. Returns a pointer to the closing } or ;, or 0 if do_spec_1
5882 returns -1. */
5884 static const char *
5885 process_brace_body (const char *p, const char *atom, const char *end_atom,
5886 int starred, int matched)
5888 const char *body, *end_body;
5889 unsigned int nesting_level;
5890 bool have_subst = false;
5892 /* Locate the closing } or ;, honoring nested braces.
5893 Trim trailing whitespace. */
5894 body = p;
5895 nesting_level = 1;
5896 for (;;)
5898 if (*p == '{')
5899 nesting_level++;
5900 else if (*p == '}')
5902 if (!--nesting_level)
5903 break;
5905 else if (*p == ';' && nesting_level == 1)
5906 break;
5907 else if (*p == '%' && p[1] == '*' && nesting_level == 1)
5908 have_subst = true;
5909 else if (*p == '\0')
5910 goto invalid;
5911 p++;
5914 end_body = p;
5915 while (end_body[-1] == ' ' || end_body[-1] == '\t')
5916 end_body--;
5918 if (have_subst && !starred)
5919 goto invalid;
5921 if (matched)
5923 /* Copy the substitution body to permanent storage and execute it.
5924 If have_subst is false, this is a simple matter of running the
5925 body through do_spec_1... */
5926 char *string = save_string (body, end_body - body);
5927 if (!have_subst)
5929 if (do_spec_1 (string, 0, NULL) < 0)
5930 return 0;
5932 else
5934 /* ... but if have_subst is true, we have to process the
5935 body once for each matching switch, with %* set to the
5936 variant part of the switch. */
5937 unsigned int hard_match_len = end_atom - atom;
5938 int i;
5940 for (i = 0; i < n_switches; i++)
5941 if (!strncmp (switches[i].part1, atom, hard_match_len)
5942 && check_live_switch (i, hard_match_len))
5944 if (do_spec_1 (string, 0,
5945 &switches[i].part1[hard_match_len]) < 0)
5946 return 0;
5947 /* Pass any arguments this switch has. */
5948 give_switch (i, 1);
5949 suffix_subst = NULL;
5954 return p;
5956 invalid:
5957 fatal_error ("braced spec body %qs is invalid", body);
5960 /* Return 0 iff switch number SWITCHNUM is obsoleted by a later switch
5961 on the command line. PREFIX_LENGTH is the length of XXX in an {XXX*}
5962 spec, or -1 if either exact match or %* is used.
5964 A -O switch is obsoleted by a later -O switch. A -f, -g, -m, or -W switch
5965 whose value does not begin with "no-" is obsoleted by the same value
5966 with the "no-", similarly for a switch with the "no-" prefix. */
5968 static int
5969 check_live_switch (int switchnum, int prefix_length)
5971 const char *name = switches[switchnum].part1;
5972 int i;
5974 /* If we already processed this switch and determined if it was
5975 live or not, return our past determination. */
5976 if (switches[switchnum].live_cond != 0)
5977 return ((switches[switchnum].live_cond & SWITCH_LIVE) != 0
5978 && (switches[switchnum].live_cond & SWITCH_FALSE) == 0
5979 && (switches[switchnum].live_cond & SWITCH_IGNORE_PERMANENTLY)
5980 == 0);
5982 /* In the common case of {<at-most-one-letter>*}, a negating
5983 switch would always match, so ignore that case. We will just
5984 send the conflicting switches to the compiler phase. */
5985 if (prefix_length >= 0 && prefix_length <= 1)
5986 return 1;
5988 /* Now search for duplicate in a manner that depends on the name. */
5989 switch (*name)
5991 case 'O':
5992 for (i = switchnum + 1; i < n_switches; i++)
5993 if (switches[i].part1[0] == 'O')
5995 switches[switchnum].validated = true;
5996 switches[switchnum].live_cond = SWITCH_FALSE;
5997 return 0;
5999 break;
6001 case 'W': case 'f': case 'm': case 'g':
6002 if (! strncmp (name + 1, "no-", 3))
6004 /* We have Xno-YYY, search for XYYY. */
6005 for (i = switchnum + 1; i < n_switches; i++)
6006 if (switches[i].part1[0] == name[0]
6007 && ! strcmp (&switches[i].part1[1], &name[4]))
6009 /* --specs are validated with the validate_switches mechanism. */
6010 if (switches[switchnum].known)
6011 switches[switchnum].validated = true;
6012 switches[switchnum].live_cond = SWITCH_FALSE;
6013 return 0;
6016 else
6018 /* We have XYYY, search for Xno-YYY. */
6019 for (i = switchnum + 1; i < n_switches; i++)
6020 if (switches[i].part1[0] == name[0]
6021 && switches[i].part1[1] == 'n'
6022 && switches[i].part1[2] == 'o'
6023 && switches[i].part1[3] == '-'
6024 && !strcmp (&switches[i].part1[4], &name[1]))
6026 /* --specs are validated with the validate_switches mechanism. */
6027 if (switches[switchnum].known)
6028 switches[switchnum].validated = true;
6029 switches[switchnum].live_cond = SWITCH_FALSE;
6030 return 0;
6033 break;
6036 /* Otherwise the switch is live. */
6037 switches[switchnum].live_cond |= SWITCH_LIVE;
6038 return 1;
6041 /* Pass a switch to the current accumulating command
6042 in the same form that we received it.
6043 SWITCHNUM identifies the switch; it is an index into
6044 the vector of switches gcc received, which is `switches'.
6045 This cannot fail since it never finishes a command line.
6047 If OMIT_FIRST_WORD is nonzero, then we omit .part1 of the argument. */
6049 static void
6050 give_switch (int switchnum, int omit_first_word)
6052 if ((switches[switchnum].live_cond & SWITCH_IGNORE) != 0)
6053 return;
6055 if (!omit_first_word)
6057 do_spec_1 ("-", 0, NULL);
6058 do_spec_1 (switches[switchnum].part1, 1, NULL);
6061 if (switches[switchnum].args != 0)
6063 const char **p;
6064 for (p = switches[switchnum].args; *p; p++)
6066 const char *arg = *p;
6068 do_spec_1 (" ", 0, NULL);
6069 if (suffix_subst)
6071 unsigned length = strlen (arg);
6072 int dot = 0;
6074 while (length-- && !IS_DIR_SEPARATOR (arg[length]))
6075 if (arg[length] == '.')
6077 (CONST_CAST (char *, arg))[length] = 0;
6078 dot = 1;
6079 break;
6081 do_spec_1 (arg, 1, NULL);
6082 if (dot)
6083 (CONST_CAST (char *, arg))[length] = '.';
6084 do_spec_1 (suffix_subst, 1, NULL);
6086 else
6087 do_spec_1 (arg, 1, NULL);
6091 do_spec_1 (" ", 0, NULL);
6092 switches[switchnum].validated = true;
6095 /* Search for a file named NAME trying various prefixes including the
6096 user's -B prefix and some standard ones.
6097 Return the absolute file name found. If nothing is found, return NAME. */
6099 static const char *
6100 find_file (const char *name)
6102 char *newname = find_a_file (&startfile_prefixes, name, R_OK, true);
6103 return newname ? newname : name;
6106 /* Determine whether a directory exists. If LINKER, return 0 for
6107 certain fixed names not needed by the linker. */
6109 static int
6110 is_directory (const char *path1, bool linker)
6112 int len1;
6113 char *path;
6114 char *cp;
6115 struct stat st;
6117 /* Ensure the string ends with "/.". The resulting path will be a
6118 directory even if the given path is a symbolic link. */
6119 len1 = strlen (path1);
6120 path = (char *) alloca (3 + len1);
6121 memcpy (path, path1, len1);
6122 cp = path + len1;
6123 if (!IS_DIR_SEPARATOR (cp[-1]))
6124 *cp++ = DIR_SEPARATOR;
6125 *cp++ = '.';
6126 *cp = '\0';
6128 /* Exclude directories that the linker is known to search. */
6129 if (linker
6130 && IS_DIR_SEPARATOR (path[0])
6131 && ((cp - path == 6
6132 && filename_ncmp (path + 1, "lib", 3) == 0)
6133 || (cp - path == 10
6134 && filename_ncmp (path + 1, "usr", 3) == 0
6135 && IS_DIR_SEPARATOR (path[4])
6136 && filename_ncmp (path + 5, "lib", 3) == 0)))
6137 return 0;
6139 return (stat (path, &st) >= 0 && S_ISDIR (st.st_mode));
6142 /* Set up the various global variables to indicate that we're processing
6143 the input file named FILENAME. */
6145 void
6146 set_input (const char *filename)
6148 const char *p;
6150 gcc_input_filename = filename;
6151 input_filename_length = strlen (gcc_input_filename);
6152 input_basename = lbasename (gcc_input_filename);
6154 /* Find a suffix starting with the last period,
6155 and set basename_length to exclude that suffix. */
6156 basename_length = strlen (input_basename);
6157 suffixed_basename_length = basename_length;
6158 p = input_basename + basename_length;
6159 while (p != input_basename && *p != '.')
6160 --p;
6161 if (*p == '.' && p != input_basename)
6163 basename_length = p - input_basename;
6164 input_suffix = p + 1;
6166 else
6167 input_suffix = "";
6169 /* If a spec for 'g', 'u', or 'U' is seen with -save-temps then
6170 we will need to do a stat on the gcc_input_filename. The
6171 INPUT_STAT_SET signals that the stat is needed. */
6172 input_stat_set = 0;
6175 /* On fatal signals, delete all the temporary files. */
6177 static void
6178 fatal_signal (int signum)
6180 signal (signum, SIG_DFL);
6181 delete_failure_queue ();
6182 delete_temp_files ();
6183 /* Get the same signal again, this time not handled,
6184 so its normal effect occurs. */
6185 kill (getpid (), signum);
6188 /* Compare the contents of the two files named CMPFILE[0] and
6189 CMPFILE[1]. Return zero if they're identical, nonzero
6190 otherwise. */
6192 static int
6193 compare_files (char *cmpfile[])
6195 int ret = 0;
6196 FILE *temp[2] = { NULL, NULL };
6197 int i;
6199 #if HAVE_MMAP_FILE
6201 size_t length[2];
6202 void *map[2] = { NULL, NULL };
6204 for (i = 0; i < 2; i++)
6206 struct stat st;
6208 if (stat (cmpfile[i], &st) < 0 || !S_ISREG (st.st_mode))
6210 error ("%s: could not determine length of compare-debug file %s",
6211 gcc_input_filename, cmpfile[i]);
6212 ret = 1;
6213 break;
6216 length[i] = st.st_size;
6219 if (!ret && length[0] != length[1])
6221 error ("%s: -fcompare-debug failure (length)", gcc_input_filename);
6222 ret = 1;
6225 if (!ret)
6226 for (i = 0; i < 2; i++)
6228 int fd = open (cmpfile[i], O_RDONLY);
6229 if (fd < 0)
6231 error ("%s: could not open compare-debug file %s",
6232 gcc_input_filename, cmpfile[i]);
6233 ret = 1;
6234 break;
6237 map[i] = mmap (NULL, length[i], PROT_READ, MAP_PRIVATE, fd, 0);
6238 close (fd);
6240 if (map[i] == (void *) MAP_FAILED)
6242 ret = -1;
6243 break;
6247 if (!ret)
6249 if (memcmp (map[0], map[1], length[0]) != 0)
6251 error ("%s: -fcompare-debug failure", gcc_input_filename);
6252 ret = 1;
6256 for (i = 0; i < 2; i++)
6257 if (map[i])
6258 munmap ((caddr_t) map[i], length[i]);
6260 if (ret >= 0)
6261 return ret;
6263 ret = 0;
6265 #endif
6267 for (i = 0; i < 2; i++)
6269 temp[i] = fopen (cmpfile[i], "r");
6270 if (!temp[i])
6272 error ("%s: could not open compare-debug file %s",
6273 gcc_input_filename, cmpfile[i]);
6274 ret = 1;
6275 break;
6279 if (!ret && temp[0] && temp[1])
6280 for (;;)
6282 int c0, c1;
6283 c0 = fgetc (temp[0]);
6284 c1 = fgetc (temp[1]);
6286 if (c0 != c1)
6288 error ("%s: -fcompare-debug failure",
6289 gcc_input_filename);
6290 ret = 1;
6291 break;
6294 if (c0 == EOF)
6295 break;
6298 for (i = 1; i >= 0; i--)
6300 if (temp[i])
6301 fclose (temp[i]);
6304 return ret;
6307 extern int main (int, char **);
6310 main (int argc, char **argv)
6312 size_t i;
6313 int value;
6314 int linker_was_run = 0;
6315 int lang_n_infiles = 0;
6316 int num_linker_inputs = 0;
6317 char *explicit_link_files;
6318 char *specs_file;
6319 char *lto_wrapper_file;
6320 const char *p;
6321 struct user_specs *uptr;
6322 char **old_argv = argv;
6323 struct cl_decoded_option *decoded_options;
6324 unsigned int decoded_options_count;
6326 p = argv[0] + strlen (argv[0]);
6327 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
6328 --p;
6329 progname = p;
6331 xmalloc_set_program_name (progname);
6333 expandargv (&argc, &argv);
6335 /* Determine if any expansions were made. */
6336 if (argv != old_argv)
6337 at_file_supplied = true;
6339 /* Register the language-independent parameters. */
6340 global_init_params ();
6341 finish_params ();
6343 init_options_struct (&global_options, &global_options_set);
6345 decode_cmdline_options_to_array (argc, CONST_CAST2 (const char **, char **,
6346 argv),
6347 CL_DRIVER,
6348 &decoded_options, &decoded_options_count);
6350 /* Unlock the stdio streams. */
6351 unlock_std_streams ();
6353 gcc_init_libintl ();
6355 diagnostic_initialize (global_dc, 0);
6357 #ifdef GCC_DRIVER_HOST_INITIALIZATION
6358 /* Perform host dependent initialization when needed. */
6359 GCC_DRIVER_HOST_INITIALIZATION;
6360 #endif
6362 if (atexit (delete_temp_files) != 0)
6363 fatal_error ("atexit failed");
6365 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
6366 signal (SIGINT, fatal_signal);
6367 #ifdef SIGHUP
6368 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
6369 signal (SIGHUP, fatal_signal);
6370 #endif
6371 if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
6372 signal (SIGTERM, fatal_signal);
6373 #ifdef SIGPIPE
6374 if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
6375 signal (SIGPIPE, fatal_signal);
6376 #endif
6377 #ifdef SIGCHLD
6378 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
6379 receive the signal. A different setting is inheritable */
6380 signal (SIGCHLD, SIG_DFL);
6381 #endif
6383 /* Parsing and gimplification sometimes need quite large stack.
6384 Increase stack size limits if possible. */
6385 stack_limit_increase (64 * 1024 * 1024);
6387 /* Allocate the argument vector. */
6388 alloc_args ();
6390 obstack_init (&obstack);
6392 /* Build multilib_select, et. al from the separate lines that make up each
6393 multilib selection. */
6395 const char *const *q = multilib_raw;
6396 int need_space;
6398 obstack_init (&multilib_obstack);
6399 while ((p = *q++) != (char *) 0)
6400 obstack_grow (&multilib_obstack, p, strlen (p));
6402 obstack_1grow (&multilib_obstack, 0);
6403 multilib_select = XOBFINISH (&multilib_obstack, const char *);
6405 q = multilib_matches_raw;
6406 while ((p = *q++) != (char *) 0)
6407 obstack_grow (&multilib_obstack, p, strlen (p));
6409 obstack_1grow (&multilib_obstack, 0);
6410 multilib_matches = XOBFINISH (&multilib_obstack, const char *);
6412 q = multilib_exclusions_raw;
6413 while ((p = *q++) != (char *) 0)
6414 obstack_grow (&multilib_obstack, p, strlen (p));
6416 obstack_1grow (&multilib_obstack, 0);
6417 multilib_exclusions = XOBFINISH (&multilib_obstack, const char *);
6419 q = multilib_reuse_raw;
6420 while ((p = *q++) != (char *) 0)
6421 obstack_grow (&multilib_obstack, p, strlen (p));
6423 obstack_1grow (&multilib_obstack, 0);
6424 multilib_reuse = XOBFINISH (&multilib_obstack, const char *);
6426 need_space = FALSE;
6427 for (i = 0; i < ARRAY_SIZE (multilib_defaults_raw); i++)
6429 if (need_space)
6430 obstack_1grow (&multilib_obstack, ' ');
6431 obstack_grow (&multilib_obstack,
6432 multilib_defaults_raw[i],
6433 strlen (multilib_defaults_raw[i]));
6434 need_space = TRUE;
6437 obstack_1grow (&multilib_obstack, 0);
6438 multilib_defaults = XOBFINISH (&multilib_obstack, const char *);
6441 #ifdef INIT_ENVIRONMENT
6442 /* Set up any other necessary machine specific environment variables. */
6443 xputenv (INIT_ENVIRONMENT);
6444 #endif
6446 /* Make a table of what switches there are (switches, n_switches).
6447 Make a table of specified input files (infiles, n_infiles).
6448 Decode switches that are handled locally. */
6450 process_command (decoded_options_count, decoded_options);
6452 /* Initialize the vector of specs to just the default.
6453 This means one element containing 0s, as a terminator. */
6455 compilers = XNEWVAR (struct compiler, sizeof default_compilers);
6456 memcpy (compilers, default_compilers, sizeof default_compilers);
6457 n_compilers = n_default_compilers;
6459 /* Read specs from a file if there is one. */
6461 machine_suffix = concat (spec_machine, dir_separator_str,
6462 spec_version, dir_separator_str, NULL);
6463 just_machine_suffix = concat (spec_machine, dir_separator_str, NULL);
6465 specs_file = find_a_file (&startfile_prefixes, "specs", R_OK, true);
6466 /* Read the specs file unless it is a default one. */
6467 if (specs_file != 0 && strcmp (specs_file, "specs"))
6468 read_specs (specs_file, true, false);
6469 else
6470 init_spec ();
6472 /* We need to check standard_exec_prefix/just_machine_suffix/specs
6473 for any override of as, ld and libraries. */
6474 specs_file = (char *) alloca (strlen (standard_exec_prefix)
6475 + strlen (just_machine_suffix) + sizeof ("specs"));
6477 strcpy (specs_file, standard_exec_prefix);
6478 strcat (specs_file, just_machine_suffix);
6479 strcat (specs_file, "specs");
6480 if (access (specs_file, R_OK) == 0)
6481 read_specs (specs_file, true, false);
6483 /* Process any configure-time defaults specified for the command line
6484 options, via OPTION_DEFAULT_SPECS. */
6485 for (i = 0; i < ARRAY_SIZE (option_default_specs); i++)
6486 do_option_spec (option_default_specs[i].name,
6487 option_default_specs[i].spec);
6489 /* Process DRIVER_SELF_SPECS, adding any new options to the end
6490 of the command line. */
6492 for (i = 0; i < ARRAY_SIZE (driver_self_specs); i++)
6493 do_self_spec (driver_self_specs[i]);
6495 /* If not cross-compiling, look for executables in the standard
6496 places. */
6497 if (*cross_compile == '0')
6499 if (*md_exec_prefix)
6501 add_prefix (&exec_prefixes, md_exec_prefix, "GCC",
6502 PREFIX_PRIORITY_LAST, 0, 0);
6506 /* Process sysroot_suffix_spec. */
6507 if (*sysroot_suffix_spec != 0
6508 && !no_sysroot_suffix
6509 && do_spec_2 (sysroot_suffix_spec) == 0)
6511 if (argbuf.length () > 1)
6512 error ("spec failure: more than one arg to SYSROOT_SUFFIX_SPEC");
6513 else if (argbuf.length () == 1)
6514 target_sysroot_suffix = xstrdup (argbuf.last ());
6517 #ifdef HAVE_LD_SYSROOT
6518 /* Pass the --sysroot option to the linker, if it supports that. If
6519 there is a sysroot_suffix_spec, it has already been processed by
6520 this point, so target_system_root really is the system root we
6521 should be using. */
6522 if (target_system_root)
6524 obstack_grow (&obstack, "%(sysroot_spec) ", strlen ("%(sysroot_spec) "));
6525 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
6526 set_spec ("link", XOBFINISH (&obstack, const char *), false);
6528 #endif
6530 /* Process sysroot_hdrs_suffix_spec. */
6531 if (*sysroot_hdrs_suffix_spec != 0
6532 && !no_sysroot_suffix
6533 && do_spec_2 (sysroot_hdrs_suffix_spec) == 0)
6535 if (argbuf.length () > 1)
6536 error ("spec failure: more than one arg to SYSROOT_HEADERS_SUFFIX_SPEC");
6537 else if (argbuf.length () == 1)
6538 target_sysroot_hdrs_suffix = xstrdup (argbuf.last ());
6541 /* Look for startfiles in the standard places. */
6542 if (*startfile_prefix_spec != 0
6543 && do_spec_2 (startfile_prefix_spec) == 0
6544 && do_spec_1 (" ", 0, NULL) == 0)
6546 const char *arg;
6547 int ndx;
6548 FOR_EACH_VEC_ELT (argbuf, ndx, arg)
6549 add_sysrooted_prefix (&startfile_prefixes, arg, "BINUTILS",
6550 PREFIX_PRIORITY_LAST, 0, 1);
6552 /* We should eventually get rid of all these and stick to
6553 startfile_prefix_spec exclusively. */
6554 else if (*cross_compile == '0' || target_system_root)
6556 if (*md_startfile_prefix)
6557 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix,
6558 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
6560 if (*md_startfile_prefix_1)
6561 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix_1,
6562 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
6564 /* If standard_startfile_prefix is relative, base it on
6565 standard_exec_prefix. This lets us move the installed tree
6566 as a unit. If GCC_EXEC_PREFIX is defined, base
6567 standard_startfile_prefix on that as well.
6569 If the prefix is relative, only search it for native compilers;
6570 otherwise we will search a directory containing host libraries. */
6571 if (IS_ABSOLUTE_PATH (standard_startfile_prefix))
6572 add_sysrooted_prefix (&startfile_prefixes,
6573 standard_startfile_prefix, "BINUTILS",
6574 PREFIX_PRIORITY_LAST, 0, 1);
6575 else if (*cross_compile == '0')
6577 add_prefix (&startfile_prefixes,
6578 concat (gcc_exec_prefix
6579 ? gcc_exec_prefix : standard_exec_prefix,
6580 machine_suffix,
6581 standard_startfile_prefix, NULL),
6582 NULL, PREFIX_PRIORITY_LAST, 0, 1);
6585 /* Sysrooted prefixes are relocated because target_system_root is
6586 also relocated by gcc_exec_prefix. */
6587 if (*standard_startfile_prefix_1)
6588 add_sysrooted_prefix (&startfile_prefixes,
6589 standard_startfile_prefix_1, "BINUTILS",
6590 PREFIX_PRIORITY_LAST, 0, 1);
6591 if (*standard_startfile_prefix_2)
6592 add_sysrooted_prefix (&startfile_prefixes,
6593 standard_startfile_prefix_2, "BINUTILS",
6594 PREFIX_PRIORITY_LAST, 0, 1);
6597 /* Process any user specified specs in the order given on the command
6598 line. */
6599 for (uptr = user_specs_head; uptr; uptr = uptr->next)
6601 char *filename = find_a_file (&startfile_prefixes, uptr->filename,
6602 R_OK, true);
6603 read_specs (filename ? filename : uptr->filename, false, true);
6606 /* Process any user self specs. */
6608 struct spec_list *sl;
6609 for (sl = specs; sl; sl = sl->next)
6610 if (sl->name_len == sizeof "self_spec" - 1
6611 && !strcmp (sl->name, "self_spec"))
6612 do_self_spec (*sl->ptr_spec);
6615 if (compare_debug)
6617 enum save_temps save;
6619 if (!compare_debug_second)
6621 n_switches_debug_check[1] = n_switches;
6622 n_switches_alloc_debug_check[1] = n_switches_alloc;
6623 switches_debug_check[1] = XDUPVEC (struct switchstr, switches,
6624 n_switches_alloc);
6626 do_self_spec ("%:compare-debug-self-opt()");
6627 n_switches_debug_check[0] = n_switches;
6628 n_switches_alloc_debug_check[0] = n_switches_alloc;
6629 switches_debug_check[0] = switches;
6631 n_switches = n_switches_debug_check[1];
6632 n_switches_alloc = n_switches_alloc_debug_check[1];
6633 switches = switches_debug_check[1];
6636 /* Avoid crash when computing %j in this early. */
6637 save = save_temps_flag;
6638 save_temps_flag = SAVE_TEMPS_NONE;
6640 compare_debug = -compare_debug;
6641 do_self_spec ("%:compare-debug-self-opt()");
6643 save_temps_flag = save;
6645 if (!compare_debug_second)
6647 n_switches_debug_check[1] = n_switches;
6648 n_switches_alloc_debug_check[1] = n_switches_alloc;
6649 switches_debug_check[1] = switches;
6650 compare_debug = -compare_debug;
6651 n_switches = n_switches_debug_check[0];
6652 n_switches_alloc = n_switches_debug_check[0];
6653 switches = switches_debug_check[0];
6658 /* If we have a GCC_EXEC_PREFIX envvar, modify it for cpp's sake. */
6659 if (gcc_exec_prefix)
6660 gcc_exec_prefix = concat (gcc_exec_prefix, spec_machine, dir_separator_str,
6661 spec_version, dir_separator_str, NULL);
6663 /* Now we have the specs.
6664 Set the `valid' bits for switches that match anything in any spec. */
6666 validate_all_switches ();
6668 /* Now that we have the switches and the specs, set
6669 the subdirectory based on the options. */
6670 set_multilib_dir ();
6672 /* Set up to remember the pathname of gcc and any options
6673 needed for collect. We use argv[0] instead of progname because
6674 we need the complete pathname. */
6675 obstack_init (&collect_obstack);
6676 obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);
6677 obstack_grow (&collect_obstack, argv[0], strlen (argv[0]) + 1);
6678 xputenv (XOBFINISH (&collect_obstack, char *));
6680 /* Set up to remember the pathname of the lto wrapper. */
6682 if (have_c)
6683 lto_wrapper_file = NULL;
6684 else
6685 lto_wrapper_file = find_a_file (&exec_prefixes, "lto-wrapper",
6686 X_OK, false);
6687 if (lto_wrapper_file)
6689 lto_wrapper_file = convert_white_space (lto_wrapper_file);
6690 lto_wrapper_spec = lto_wrapper_file;
6691 obstack_init (&collect_obstack);
6692 obstack_grow (&collect_obstack, "COLLECT_LTO_WRAPPER=",
6693 sizeof ("COLLECT_LTO_WRAPPER=") - 1);
6694 obstack_grow (&collect_obstack, lto_wrapper_spec,
6695 strlen (lto_wrapper_spec) + 1);
6696 xputenv (XOBFINISH (&collect_obstack, char *));
6699 /* Reject switches that no pass was interested in. */
6701 for (i = 0; (int) i < n_switches; i++)
6702 if (! switches[i].validated)
6703 error ("unrecognized command line option %<-%s%>", switches[i].part1);
6705 /* Obey some of the options. */
6707 if (print_search_dirs)
6709 printf (_("install: %s%s\n"),
6710 gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
6711 gcc_exec_prefix ? "" : machine_suffix);
6712 printf (_("programs: %s\n"),
6713 build_search_list (&exec_prefixes, "", false, false));
6714 printf (_("libraries: %s\n"),
6715 build_search_list (&startfile_prefixes, "", false, true));
6716 return (0);
6719 if (print_file_name)
6721 printf ("%s\n", find_file (print_file_name));
6722 return (0);
6725 if (print_prog_name)
6727 if (use_ld != NULL && ! strcmp (print_prog_name, "ld"))
6729 /* Append USE_LD to to the default linker. */
6730 #ifdef DEFAULT_LINKER
6731 char *ld;
6732 # ifdef HAVE_HOST_EXECUTABLE_SUFFIX
6733 int len = (sizeof (DEFAULT_LINKER)
6734 - sizeof (HOST_EXECUTABLE_SUFFIX));
6735 ld = NULL;
6736 if (len > 0)
6738 char *default_linker = xstrdup (DEFAULT_LINKER);
6739 /* Strip HOST_EXECUTABLE_SUFFIX if DEFAULT_LINKER contains
6740 HOST_EXECUTABLE_SUFFIX. */
6741 if (! strcmp (&default_linker[len], HOST_EXECUTABLE_SUFFIX))
6743 default_linker[len] = '\0';
6744 ld = concat (default_linker, use_ld,
6745 HOST_EXECUTABLE_SUFFIX, NULL);
6748 if (ld == NULL)
6749 # endif
6750 ld = concat (DEFAULT_LINKER, use_ld, NULL);
6751 if (access (ld, X_OK) == 0)
6753 printf ("%s\n", ld);
6754 return (0);
6756 #endif
6757 print_prog_name = concat (print_prog_name, use_ld, NULL);
6759 char *newname = find_a_file (&exec_prefixes, print_prog_name, X_OK, 0);
6760 printf ("%s\n", (newname ? newname : print_prog_name));
6761 return (0);
6764 if (print_multi_lib)
6766 print_multilib_info ();
6767 return (0);
6770 if (print_multi_directory)
6772 if (multilib_dir == NULL)
6773 printf (".\n");
6774 else
6775 printf ("%s\n", multilib_dir);
6776 return (0);
6779 if (print_multiarch)
6781 if (multiarch_dir == NULL)
6782 printf ("\n");
6783 else
6784 printf ("%s\n", multiarch_dir);
6785 return (0);
6788 if (print_sysroot)
6790 if (target_system_root)
6792 if (target_sysroot_suffix)
6793 printf ("%s%s\n", target_system_root, target_sysroot_suffix);
6794 else
6795 printf ("%s\n", target_system_root);
6797 return (0);
6800 if (print_multi_os_directory)
6802 if (multilib_os_dir == NULL)
6803 printf (".\n");
6804 else
6805 printf ("%s\n", multilib_os_dir);
6806 return (0);
6809 if (print_sysroot_headers_suffix)
6811 if (*sysroot_hdrs_suffix_spec)
6813 printf("%s\n", (target_sysroot_hdrs_suffix
6814 ? target_sysroot_hdrs_suffix
6815 : ""));
6816 return (0);
6818 else
6819 /* The error status indicates that only one set of fixed
6820 headers should be built. */
6821 fatal_error ("not configured with sysroot headers suffix");
6824 if (print_help_list)
6826 display_help ();
6828 if (! verbose_flag)
6830 printf (_("\nFor bug reporting instructions, please see:\n"));
6831 printf ("%s.\n", bug_report_url);
6833 return (0);
6836 /* We do not exit here. Instead we have created a fake input file
6837 called 'help-dummy' which needs to be compiled, and we pass this
6838 on the various sub-processes, along with the --help switch.
6839 Ensure their output appears after ours. */
6840 fputc ('\n', stdout);
6841 fflush (stdout);
6844 if (print_version)
6846 printf (_("%s %s%s\n"), progname, pkgversion_string,
6847 version_string);
6848 printf ("Copyright %s 2014 Free Software Foundation, Inc.\n",
6849 _("(C)"));
6850 fputs (_("This is free software; see the source for copying conditions. There is NO\n\
6851 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"),
6852 stdout);
6853 if (! verbose_flag)
6854 return 0;
6856 /* We do not exit here. We use the same mechanism of --help to print
6857 the version of the sub-processes. */
6858 fputc ('\n', stdout);
6859 fflush (stdout);
6862 if (verbose_flag)
6864 int n;
6865 const char *thrmod;
6867 fnotice (stderr, "Target: %s\n", spec_machine);
6868 fnotice (stderr, "Configured with: %s\n", configuration_arguments);
6870 #ifdef THREAD_MODEL_SPEC
6871 /* We could have defined THREAD_MODEL_SPEC to "%*" by default,
6872 but there's no point in doing all this processing just to get
6873 thread_model back. */
6874 obstack_init (&obstack);
6875 do_spec_1 (THREAD_MODEL_SPEC, 0, thread_model);
6876 obstack_1grow (&obstack, '\0');
6877 thrmod = XOBFINISH (&obstack, const char *);
6878 #else
6879 thrmod = thread_model;
6880 #endif
6882 fnotice (stderr, "Thread model: %s\n", thrmod);
6884 /* compiler_version is truncated at the first space when initialized
6885 from version string, so truncate version_string at the first space
6886 before comparing. */
6887 for (n = 0; version_string[n]; n++)
6888 if (version_string[n] == ' ')
6889 break;
6891 if (! strncmp (version_string, compiler_version, n)
6892 && compiler_version[n] == 0)
6893 fnotice (stderr, "gcc version %s %s\n", version_string,
6894 pkgversion_string);
6895 else
6896 fnotice (stderr, "gcc driver version %s %sexecuting gcc version %s\n",
6897 version_string, pkgversion_string, compiler_version);
6899 if (n_infiles == 0)
6900 return (0);
6903 if (n_infiles == added_libraries)
6904 fatal_error ("no input files");
6906 if (seen_error ())
6907 goto out;
6909 /* Make a place to record the compiler output file names
6910 that correspond to the input files. */
6912 i = n_infiles;
6913 i += lang_specific_extra_outfiles;
6914 outfiles = XCNEWVEC (const char *, i);
6916 /* Record which files were specified explicitly as link input. */
6918 explicit_link_files = XCNEWVEC (char, n_infiles);
6920 combine_inputs = have_o || flag_wpa;
6922 for (i = 0; (int) i < n_infiles; i++)
6924 const char *name = infiles[i].name;
6925 struct compiler *compiler = lookup_compiler (name,
6926 strlen (name),
6927 infiles[i].language);
6929 if (compiler && !(compiler->combinable))
6930 combine_inputs = false;
6932 if (lang_n_infiles > 0 && compiler != input_file_compiler
6933 && infiles[i].language && infiles[i].language[0] != '*')
6934 infiles[i].incompiler = compiler;
6935 else if (compiler)
6937 lang_n_infiles++;
6938 input_file_compiler = compiler;
6939 infiles[i].incompiler = compiler;
6941 else
6943 /* Since there is no compiler for this input file, assume it is a
6944 linker file. */
6945 explicit_link_files[i] = 1;
6946 infiles[i].incompiler = NULL;
6948 infiles[i].compiled = false;
6949 infiles[i].preprocessed = false;
6952 if (!combine_inputs && have_c && have_o && lang_n_infiles > 1)
6953 fatal_error ("cannot specify -o with -c, -S or -E with multiple files");
6955 for (i = 0; (int) i < n_infiles; i++)
6957 int this_file_error = 0;
6959 /* Tell do_spec what to substitute for %i. */
6961 input_file_number = i;
6962 set_input (infiles[i].name);
6964 if (infiles[i].compiled)
6965 continue;
6967 /* Use the same thing in %o, unless cp->spec says otherwise. */
6969 outfiles[i] = gcc_input_filename;
6971 /* Figure out which compiler from the file's suffix. */
6973 input_file_compiler
6974 = lookup_compiler (infiles[i].name, input_filename_length,
6975 infiles[i].language);
6977 if (input_file_compiler)
6979 /* Ok, we found an applicable compiler. Run its spec. */
6981 if (input_file_compiler->spec[0] == '#')
6983 error ("%s: %s compiler not installed on this system",
6984 gcc_input_filename, &input_file_compiler->spec[1]);
6985 this_file_error = 1;
6987 else
6989 if (compare_debug)
6991 free (debug_check_temp_file[0]);
6992 debug_check_temp_file[0] = NULL;
6994 free (debug_check_temp_file[1]);
6995 debug_check_temp_file[1] = NULL;
6998 value = do_spec (input_file_compiler->spec);
6999 infiles[i].compiled = true;
7000 if (value < 0)
7001 this_file_error = 1;
7002 else if (compare_debug && debug_check_temp_file[0])
7004 if (verbose_flag)
7005 inform (0, "recompiling with -fcompare-debug");
7007 compare_debug = -compare_debug;
7008 n_switches = n_switches_debug_check[1];
7009 n_switches_alloc = n_switches_alloc_debug_check[1];
7010 switches = switches_debug_check[1];
7012 value = do_spec (input_file_compiler->spec);
7014 compare_debug = -compare_debug;
7015 n_switches = n_switches_debug_check[0];
7016 n_switches_alloc = n_switches_alloc_debug_check[0];
7017 switches = switches_debug_check[0];
7019 if (value < 0)
7021 error ("during -fcompare-debug recompilation");
7022 this_file_error = 1;
7025 gcc_assert (debug_check_temp_file[1]
7026 && filename_cmp (debug_check_temp_file[0],
7027 debug_check_temp_file[1]));
7029 if (verbose_flag)
7030 inform (0, "comparing final insns dumps");
7032 if (compare_files (debug_check_temp_file))
7033 this_file_error = 1;
7036 if (compare_debug)
7038 free (debug_check_temp_file[0]);
7039 debug_check_temp_file[0] = NULL;
7041 free (debug_check_temp_file[1]);
7042 debug_check_temp_file[1] = NULL;
7047 /* If this file's name does not contain a recognized suffix,
7048 record it as explicit linker input. */
7050 else
7051 explicit_link_files[i] = 1;
7053 /* Clear the delete-on-failure queue, deleting the files in it
7054 if this compilation failed. */
7056 if (this_file_error)
7058 delete_failure_queue ();
7059 errorcount++;
7061 /* If this compilation succeeded, don't delete those files later. */
7062 clear_failure_queue ();
7065 /* Reset the input file name to the first compile/object file name, for use
7066 with %b in LINK_SPEC. We use the first input file that we can find
7067 a compiler to compile it instead of using infiles.language since for
7068 languages other than C we use aliases that we then lookup later. */
7069 if (n_infiles > 0)
7071 int i;
7073 for (i = 0; i < n_infiles ; i++)
7074 if (infiles[i].incompiler
7075 || (infiles[i].language && infiles[i].language[0] != '*'))
7077 set_input (infiles[i].name);
7078 break;
7082 if (!seen_error ())
7084 /* Make sure INPUT_FILE_NUMBER points to first available open
7085 slot. */
7086 input_file_number = n_infiles;
7087 if (lang_specific_pre_link ())
7088 errorcount++;
7091 /* Determine if there are any linker input files. */
7092 num_linker_inputs = 0;
7093 for (i = 0; (int) i < n_infiles; i++)
7094 if (explicit_link_files[i] || outfiles[i] != NULL)
7095 num_linker_inputs++;
7097 /* Run ld to link all the compiler output files. */
7099 if (num_linker_inputs > 0 && !seen_error () && print_subprocess_help < 2)
7101 int tmp = execution_count;
7103 if (! have_c)
7105 #if HAVE_LTO_PLUGIN > 0
7106 #if HAVE_LTO_PLUGIN == 2
7107 const char *fno_use_linker_plugin = "fno-use-linker-plugin";
7108 #else
7109 const char *fuse_linker_plugin = "fuse-linker-plugin";
7110 #endif
7111 #endif
7113 /* We'll use ld if we can't find collect2. */
7114 if (! strcmp (linker_name_spec, "collect2"))
7116 char *s = find_a_file (&exec_prefixes, "collect2", X_OK, false);
7117 if (s == NULL)
7118 linker_name_spec = "ld";
7121 #if HAVE_LTO_PLUGIN > 0
7122 #if HAVE_LTO_PLUGIN == 2
7123 if (!switch_matches (fno_use_linker_plugin,
7124 fno_use_linker_plugin
7125 + strlen (fno_use_linker_plugin), 0))
7126 #else
7127 if (switch_matches (fuse_linker_plugin,
7128 fuse_linker_plugin
7129 + strlen (fuse_linker_plugin), 0))
7130 #endif
7132 char *temp_spec = find_a_file (&exec_prefixes,
7133 LTOPLUGINSONAME, R_OK,
7134 false);
7135 if (!temp_spec)
7136 fatal_error ("-fuse-linker-plugin, but %s not found",
7137 LTOPLUGINSONAME);
7138 linker_plugin_file_spec = convert_white_space (temp_spec);
7140 #endif
7141 lto_gcc_spec = argv[0];
7144 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
7145 for collect. */
7146 putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH", false);
7147 putenv_from_prefixes (&startfile_prefixes, LIBRARY_PATH_ENV, true);
7149 if (print_subprocess_help == 1)
7151 printf (_("\nLinker options\n==============\n\n"));
7152 printf (_("Use \"-Wl,OPTION\" to pass \"OPTION\""
7153 " to the linker.\n\n"));
7154 fflush (stdout);
7156 value = do_spec (link_command_spec);
7157 if (value < 0)
7158 errorcount = 1;
7159 linker_was_run = (tmp != execution_count);
7162 /* If options said don't run linker,
7163 complain about input files to be given to the linker. */
7165 if (! linker_was_run && !seen_error ())
7166 for (i = 0; (int) i < n_infiles; i++)
7167 if (explicit_link_files[i]
7168 && !(infiles[i].language && infiles[i].language[0] == '*'))
7169 warning (0, "%s: linker input file unused because linking not done",
7170 outfiles[i]);
7172 /* Delete some or all of the temporary files we made. */
7174 if (seen_error ())
7175 delete_failure_queue ();
7176 delete_temp_files ();
7178 if (print_help_list)
7180 printf (("\nFor bug reporting instructions, please see:\n"));
7181 printf ("%s\n", bug_report_url);
7184 out:
7185 return (signal_count != 0 ? 2
7186 : seen_error () ? (pass_exit_codes ? greatest_status : 1)
7187 : 0);
7190 /* Find the proper compilation spec for the file name NAME,
7191 whose length is LENGTH. LANGUAGE is the specified language,
7192 or 0 if this file is to be passed to the linker. */
7194 static struct compiler *
7195 lookup_compiler (const char *name, size_t length, const char *language)
7197 struct compiler *cp;
7199 /* If this was specified by the user to be a linker input, indicate that. */
7200 if (language != 0 && language[0] == '*')
7201 return 0;
7203 /* Otherwise, look for the language, if one is spec'd. */
7204 if (language != 0)
7206 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7207 if (cp->suffix[0] == '@' && !strcmp (cp->suffix + 1, language))
7208 return cp;
7210 error ("language %s not recognized", language);
7211 return 0;
7214 /* Look for a suffix. */
7215 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7217 if (/* The suffix `-' matches only the file name `-'. */
7218 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
7219 || (strlen (cp->suffix) < length
7220 /* See if the suffix matches the end of NAME. */
7221 && !strcmp (cp->suffix,
7222 name + length - strlen (cp->suffix))
7224 break;
7227 #if defined (OS2) ||defined (HAVE_DOS_BASED_FILE_SYSTEM)
7228 /* Look again, but case-insensitively this time. */
7229 if (cp < compilers)
7230 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7232 if (/* The suffix `-' matches only the file name `-'. */
7233 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
7234 || (strlen (cp->suffix) < length
7235 /* See if the suffix matches the end of NAME. */
7236 && ((!strcmp (cp->suffix,
7237 name + length - strlen (cp->suffix))
7238 || !strpbrk (cp->suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
7239 && !strcasecmp (cp->suffix,
7240 name + length - strlen (cp->suffix)))
7242 break;
7244 #endif
7246 if (cp >= compilers)
7248 if (cp->spec[0] != '@')
7249 /* A non-alias entry: return it. */
7250 return cp;
7252 /* An alias entry maps a suffix to a language.
7253 Search for the language; pass 0 for NAME and LENGTH
7254 to avoid infinite recursion if language not found. */
7255 return lookup_compiler (NULL, 0, cp->spec + 1);
7257 return 0;
7260 static char *
7261 save_string (const char *s, int len)
7263 char *result = XNEWVEC (char, len + 1);
7265 memcpy (result, s, len);
7266 result[len] = 0;
7267 return result;
7270 void
7271 pfatal_with_name (const char *name)
7273 perror_with_name (name);
7274 delete_temp_files ();
7275 exit (1);
7278 static void
7279 perror_with_name (const char *name)
7281 error ("%s: %m", name);
7284 static inline void
7285 validate_switches_from_spec (const char *spec, bool user)
7287 const char *p = spec;
7288 char c;
7289 while ((c = *p++))
7290 if (c == '%' && (*p == '{' || *p == '<' || (*p == 'W' && *++p == '{')))
7291 /* We have a switch spec. */
7292 p = validate_switches (p + 1, user);
7295 static void
7296 validate_all_switches (void)
7298 struct compiler *comp;
7299 struct spec_list *spec;
7301 for (comp = compilers; comp->spec; comp++)
7302 validate_switches_from_spec (comp->spec, false);
7304 /* Look through the linked list of specs read from the specs file. */
7305 for (spec = specs; spec; spec = spec->next)
7306 validate_switches_from_spec (*spec->ptr_spec, spec->user_p);
7308 validate_switches_from_spec (link_command_spec, false);
7311 /* Look at the switch-name that comes after START
7312 and mark as valid all supplied switches that match it. */
7314 static const char *
7315 validate_switches (const char *start, bool user_spec)
7317 const char *p = start;
7318 const char *atom;
7319 size_t len;
7320 int i;
7321 bool suffix = false;
7322 bool starred = false;
7324 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
7326 next_member:
7327 SKIP_WHITE ();
7329 if (*p == '!')
7330 p++;
7332 SKIP_WHITE ();
7333 if (*p == '.' || *p == ',')
7334 suffix = true, p++;
7336 atom = p;
7337 while (ISIDNUM (*p) || *p == '-' || *p == '+' || *p == '='
7338 || *p == ',' || *p == '.' || *p == '@')
7339 p++;
7340 len = p - atom;
7342 if (*p == '*')
7343 starred = true, p++;
7345 SKIP_WHITE ();
7347 if (!suffix)
7349 /* Mark all matching switches as valid. */
7350 for (i = 0; i < n_switches; i++)
7351 if (!strncmp (switches[i].part1, atom, len)
7352 && (starred || switches[i].part1[len] == '\0')
7353 && (switches[i].known || user_spec))
7354 switches[i].validated = true;
7357 if (*p) p++;
7358 if (*p && (p[-1] == '|' || p[-1] == '&'))
7359 goto next_member;
7361 if (*p && p[-1] == ':')
7363 while (*p && *p != ';' && *p != '}')
7365 if (*p == '%')
7367 p++;
7368 if (*p == '{' || *p == '<')
7369 p = validate_switches (p+1, user_spec);
7370 else if (p[0] == 'W' && p[1] == '{')
7371 p = validate_switches (p+2, user_spec);
7373 else
7374 p++;
7377 if (*p) p++;
7378 if (*p && p[-1] == ';')
7379 goto next_member;
7382 return p;
7383 #undef SKIP_WHITE
7386 struct mdswitchstr
7388 const char *str;
7389 int len;
7392 static struct mdswitchstr *mdswitches;
7393 static int n_mdswitches;
7395 /* Check whether a particular argument was used. The first time we
7396 canonicalize the switches to keep only the ones we care about. */
7398 static int
7399 used_arg (const char *p, int len)
7401 struct mswitchstr
7403 const char *str;
7404 const char *replace;
7405 int len;
7406 int rep_len;
7409 static struct mswitchstr *mswitches;
7410 static int n_mswitches;
7411 int i, j;
7413 if (!mswitches)
7415 struct mswitchstr *matches;
7416 const char *q;
7417 int cnt = 0;
7419 /* Break multilib_matches into the component strings of string
7420 and replacement string. */
7421 for (q = multilib_matches; *q != '\0'; q++)
7422 if (*q == ';')
7423 cnt++;
7425 matches
7426 = (struct mswitchstr *) alloca ((sizeof (struct mswitchstr)) * cnt);
7427 i = 0;
7428 q = multilib_matches;
7429 while (*q != '\0')
7431 matches[i].str = q;
7432 while (*q != ' ')
7434 if (*q == '\0')
7436 invalid_matches:
7437 fatal_error ("multilib spec %qs is invalid",
7438 multilib_matches);
7440 q++;
7442 matches[i].len = q - matches[i].str;
7444 matches[i].replace = ++q;
7445 while (*q != ';' && *q != '\0')
7447 if (*q == ' ')
7448 goto invalid_matches;
7449 q++;
7451 matches[i].rep_len = q - matches[i].replace;
7452 i++;
7453 if (*q == ';')
7454 q++;
7457 /* Now build a list of the replacement string for switches that we care
7458 about. Make sure we allocate at least one entry. This prevents
7459 xmalloc from calling fatal, and prevents us from re-executing this
7460 block of code. */
7461 mswitches
7462 = XNEWVEC (struct mswitchstr, n_mdswitches + (n_switches ? n_switches : 1));
7463 for (i = 0; i < n_switches; i++)
7464 if ((switches[i].live_cond & SWITCH_IGNORE) == 0)
7466 int xlen = strlen (switches[i].part1);
7467 for (j = 0; j < cnt; j++)
7468 if (xlen == matches[j].len
7469 && ! strncmp (switches[i].part1, matches[j].str, xlen))
7471 mswitches[n_mswitches].str = matches[j].replace;
7472 mswitches[n_mswitches].len = matches[j].rep_len;
7473 mswitches[n_mswitches].replace = (char *) 0;
7474 mswitches[n_mswitches].rep_len = 0;
7475 n_mswitches++;
7476 break;
7480 /* Add MULTILIB_DEFAULTS switches too, as long as they were not present
7481 on the command line nor any options mutually incompatible with
7482 them. */
7483 for (i = 0; i < n_mdswitches; i++)
7485 const char *r;
7487 for (q = multilib_options; *q != '\0'; q++)
7489 while (*q == ' ')
7490 q++;
7492 r = q;
7493 while (strncmp (q, mdswitches[i].str, mdswitches[i].len) != 0
7494 || strchr (" /", q[mdswitches[i].len]) == NULL)
7496 while (*q != ' ' && *q != '/' && *q != '\0')
7497 q++;
7498 if (*q != '/')
7499 break;
7500 q++;
7503 if (*q != ' ' && *q != '\0')
7505 while (*r != ' ' && *r != '\0')
7507 q = r;
7508 while (*q != ' ' && *q != '/' && *q != '\0')
7509 q++;
7511 if (used_arg (r, q - r))
7512 break;
7514 if (*q != '/')
7516 mswitches[n_mswitches].str = mdswitches[i].str;
7517 mswitches[n_mswitches].len = mdswitches[i].len;
7518 mswitches[n_mswitches].replace = (char *) 0;
7519 mswitches[n_mswitches].rep_len = 0;
7520 n_mswitches++;
7521 break;
7524 r = q + 1;
7526 break;
7532 for (i = 0; i < n_mswitches; i++)
7533 if (len == mswitches[i].len && ! strncmp (p, mswitches[i].str, len))
7534 return 1;
7536 return 0;
7539 static int
7540 default_arg (const char *p, int len)
7542 int i;
7544 for (i = 0; i < n_mdswitches; i++)
7545 if (len == mdswitches[i].len && ! strncmp (p, mdswitches[i].str, len))
7546 return 1;
7548 return 0;
7551 /* Work out the subdirectory to use based on the options. The format of
7552 multilib_select is a list of elements. Each element is a subdirectory
7553 name followed by a list of options followed by a semicolon. The format
7554 of multilib_exclusions is the same, but without the preceding
7555 directory. First gcc will check the exclusions, if none of the options
7556 beginning with an exclamation point are present, and all of the other
7557 options are present, then we will ignore this completely. Passing
7558 that, gcc will consider each multilib_select in turn using the same
7559 rules for matching the options. If a match is found, that subdirectory
7560 will be used.
7561 A subdirectory name is optionally followed by a colon and the corresponding
7562 multiarch name. */
7564 static void
7565 set_multilib_dir (void)
7567 const char *p;
7568 unsigned int this_path_len;
7569 const char *this_path, *this_arg;
7570 const char *start, *end;
7571 int not_arg;
7572 int ok, ndfltok, first;
7574 n_mdswitches = 0;
7575 start = multilib_defaults;
7576 while (*start == ' ' || *start == '\t')
7577 start++;
7578 while (*start != '\0')
7580 n_mdswitches++;
7581 while (*start != ' ' && *start != '\t' && *start != '\0')
7582 start++;
7583 while (*start == ' ' || *start == '\t')
7584 start++;
7587 if (n_mdswitches)
7589 int i = 0;
7591 mdswitches = XNEWVEC (struct mdswitchstr, n_mdswitches);
7592 for (start = multilib_defaults; *start != '\0'; start = end + 1)
7594 while (*start == ' ' || *start == '\t')
7595 start++;
7597 if (*start == '\0')
7598 break;
7600 for (end = start + 1;
7601 *end != ' ' && *end != '\t' && *end != '\0'; end++)
7604 obstack_grow (&multilib_obstack, start, end - start);
7605 obstack_1grow (&multilib_obstack, 0);
7606 mdswitches[i].str = XOBFINISH (&multilib_obstack, const char *);
7607 mdswitches[i++].len = end - start;
7609 if (*end == '\0')
7610 break;
7614 p = multilib_exclusions;
7615 while (*p != '\0')
7617 /* Ignore newlines. */
7618 if (*p == '\n')
7620 ++p;
7621 continue;
7624 /* Check the arguments. */
7625 ok = 1;
7626 while (*p != ';')
7628 if (*p == '\0')
7630 invalid_exclusions:
7631 fatal_error ("multilib exclusions %qs is invalid",
7632 multilib_exclusions);
7635 if (! ok)
7637 ++p;
7638 continue;
7641 this_arg = p;
7642 while (*p != ' ' && *p != ';')
7644 if (*p == '\0')
7645 goto invalid_exclusions;
7646 ++p;
7649 if (*this_arg != '!')
7650 not_arg = 0;
7651 else
7653 not_arg = 1;
7654 ++this_arg;
7657 ok = used_arg (this_arg, p - this_arg);
7658 if (not_arg)
7659 ok = ! ok;
7661 if (*p == ' ')
7662 ++p;
7665 if (ok)
7666 return;
7668 ++p;
7671 first = 1;
7672 p = multilib_select;
7674 /* Append multilib reuse rules if any. With those rules, we can reuse
7675 one multilib for certain different options sets. */
7676 if (strlen (multilib_reuse) > 0)
7677 p = concat (p, multilib_reuse, NULL);
7679 while (*p != '\0')
7681 /* Ignore newlines. */
7682 if (*p == '\n')
7684 ++p;
7685 continue;
7688 /* Get the initial path. */
7689 this_path = p;
7690 while (*p != ' ')
7692 if (*p == '\0')
7694 invalid_select:
7695 fatal_error ("multilib select %qs %qs is invalid",
7696 multilib_select, multilib_reuse);
7698 ++p;
7700 this_path_len = p - this_path;
7702 /* Check the arguments. */
7703 ok = 1;
7704 ndfltok = 1;
7705 ++p;
7706 while (*p != ';')
7708 if (*p == '\0')
7709 goto invalid_select;
7711 if (! ok)
7713 ++p;
7714 continue;
7717 this_arg = p;
7718 while (*p != ' ' && *p != ';')
7720 if (*p == '\0')
7721 goto invalid_select;
7722 ++p;
7725 if (*this_arg != '!')
7726 not_arg = 0;
7727 else
7729 not_arg = 1;
7730 ++this_arg;
7733 /* If this is a default argument, we can just ignore it.
7734 This is true even if this_arg begins with '!'. Beginning
7735 with '!' does not mean that this argument is necessarily
7736 inappropriate for this library: it merely means that
7737 there is a more specific library which uses this
7738 argument. If this argument is a default, we need not
7739 consider that more specific library. */
7740 ok = used_arg (this_arg, p - this_arg);
7741 if (not_arg)
7742 ok = ! ok;
7744 if (! ok)
7745 ndfltok = 0;
7747 if (default_arg (this_arg, p - this_arg))
7748 ok = 1;
7750 if (*p == ' ')
7751 ++p;
7754 if (ok && first)
7756 if (this_path_len != 1
7757 || this_path[0] != '.')
7759 char *new_multilib_dir = XNEWVEC (char, this_path_len + 1);
7760 char *q;
7762 strncpy (new_multilib_dir, this_path, this_path_len);
7763 new_multilib_dir[this_path_len] = '\0';
7764 q = strchr (new_multilib_dir, ':');
7765 if (q != NULL)
7766 *q = '\0';
7767 multilib_dir = new_multilib_dir;
7769 first = 0;
7772 if (ndfltok)
7774 const char *q = this_path, *end = this_path + this_path_len;
7776 while (q < end && *q != ':')
7777 q++;
7778 if (q < end)
7780 const char *q2 = q + 1, *ml_end = end;
7781 char *new_multilib_os_dir;
7783 while (q2 < end && *q2 != ':')
7784 q2++;
7785 if (*q2 == ':')
7786 ml_end = q2;
7787 new_multilib_os_dir = XNEWVEC (char, ml_end - q);
7788 memcpy (new_multilib_os_dir, q + 1, ml_end - q - 1);
7789 new_multilib_os_dir[ml_end - q - 1] = '\0';
7790 multilib_os_dir = *new_multilib_os_dir ? new_multilib_os_dir : ".";
7792 if (q2 < end && *q2 == ':')
7794 char *new_multiarch_dir = XNEWVEC (char, end - q2);
7795 memcpy (new_multiarch_dir, q2 + 1, end - q2 - 1);
7796 new_multiarch_dir[end - q2 - 1] = '\0';
7797 multiarch_dir = new_multiarch_dir;
7799 break;
7803 ++p;
7806 if (multilib_dir == NULL && multilib_os_dir != NULL
7807 && strcmp (multilib_os_dir, ".") == 0)
7809 free (CONST_CAST (char *, multilib_os_dir));
7810 multilib_os_dir = NULL;
7812 else if (multilib_dir != NULL && multilib_os_dir == NULL)
7813 multilib_os_dir = multilib_dir;
7816 /* Print out the multiple library subdirectory selection
7817 information. This prints out a series of lines. Each line looks
7818 like SUBDIRECTORY;@OPTION@OPTION, with as many options as is
7819 required. Only the desired options are printed out, the negative
7820 matches. The options are print without a leading dash. There are
7821 no spaces to make it easy to use the information in the shell.
7822 Each subdirectory is printed only once. This assumes the ordering
7823 generated by the genmultilib script. Also, we leave out ones that match
7824 the exclusions. */
7826 static void
7827 print_multilib_info (void)
7829 const char *p = multilib_select;
7830 const char *last_path = 0, *this_path;
7831 int skip;
7832 unsigned int last_path_len = 0;
7834 while (*p != '\0')
7836 skip = 0;
7837 /* Ignore newlines. */
7838 if (*p == '\n')
7840 ++p;
7841 continue;
7844 /* Get the initial path. */
7845 this_path = p;
7846 while (*p != ' ')
7848 if (*p == '\0')
7850 invalid_select:
7851 fatal_error ("multilib select %qs is invalid", multilib_select);
7854 ++p;
7857 /* When --disable-multilib was used but target defines
7858 MULTILIB_OSDIRNAMES, entries starting with .: (and not starting
7859 with .:: for multiarch configurations) are there just to find
7860 multilib_os_dir, so skip them from output. */
7861 if (this_path[0] == '.' && this_path[1] == ':' && this_path[2] != ':')
7862 skip = 1;
7864 /* Check for matches with the multilib_exclusions. We don't bother
7865 with the '!' in either list. If any of the exclusion rules match
7866 all of its options with the select rule, we skip it. */
7868 const char *e = multilib_exclusions;
7869 const char *this_arg;
7871 while (*e != '\0')
7873 int m = 1;
7874 /* Ignore newlines. */
7875 if (*e == '\n')
7877 ++e;
7878 continue;
7881 /* Check the arguments. */
7882 while (*e != ';')
7884 const char *q;
7885 int mp = 0;
7887 if (*e == '\0')
7889 invalid_exclusion:
7890 fatal_error ("multilib exclusion %qs is invalid",
7891 multilib_exclusions);
7894 if (! m)
7896 ++e;
7897 continue;
7900 this_arg = e;
7902 while (*e != ' ' && *e != ';')
7904 if (*e == '\0')
7905 goto invalid_exclusion;
7906 ++e;
7909 q = p + 1;
7910 while (*q != ';')
7912 const char *arg;
7913 int len = e - this_arg;
7915 if (*q == '\0')
7916 goto invalid_select;
7918 arg = q;
7920 while (*q != ' ' && *q != ';')
7922 if (*q == '\0')
7923 goto invalid_select;
7924 ++q;
7927 if (! strncmp (arg, this_arg,
7928 (len < q - arg) ? q - arg : len)
7929 || default_arg (this_arg, e - this_arg))
7931 mp = 1;
7932 break;
7935 if (*q == ' ')
7936 ++q;
7939 if (! mp)
7940 m = 0;
7942 if (*e == ' ')
7943 ++e;
7946 if (m)
7948 skip = 1;
7949 break;
7952 if (*e != '\0')
7953 ++e;
7957 if (! skip)
7959 /* If this is a duplicate, skip it. */
7960 skip = (last_path != 0
7961 && (unsigned int) (p - this_path) == last_path_len
7962 && ! filename_ncmp (last_path, this_path, last_path_len));
7964 last_path = this_path;
7965 last_path_len = p - this_path;
7968 /* If this directory requires any default arguments, we can skip
7969 it. We will already have printed a directory identical to
7970 this one which does not require that default argument. */
7971 if (! skip)
7973 const char *q;
7975 q = p + 1;
7976 while (*q != ';')
7978 const char *arg;
7980 if (*q == '\0')
7981 goto invalid_select;
7983 if (*q == '!')
7984 arg = NULL;
7985 else
7986 arg = q;
7988 while (*q != ' ' && *q != ';')
7990 if (*q == '\0')
7991 goto invalid_select;
7992 ++q;
7995 if (arg != NULL
7996 && default_arg (arg, q - arg))
7998 skip = 1;
7999 break;
8002 if (*q == ' ')
8003 ++q;
8007 if (! skip)
8009 const char *p1;
8011 for (p1 = last_path; p1 < p && *p1 != ':'; p1++)
8012 putchar (*p1);
8013 putchar (';');
8016 ++p;
8017 while (*p != ';')
8019 int use_arg;
8021 if (*p == '\0')
8022 goto invalid_select;
8024 if (skip)
8026 ++p;
8027 continue;
8030 use_arg = *p != '!';
8032 if (use_arg)
8033 putchar ('@');
8035 while (*p != ' ' && *p != ';')
8037 if (*p == '\0')
8038 goto invalid_select;
8039 if (use_arg)
8040 putchar (*p);
8041 ++p;
8044 if (*p == ' ')
8045 ++p;
8048 if (! skip)
8050 /* If there are extra options, print them now. */
8051 if (multilib_extra && *multilib_extra)
8053 int print_at = TRUE;
8054 const char *q;
8056 for (q = multilib_extra; *q != '\0'; q++)
8058 if (*q == ' ')
8059 print_at = TRUE;
8060 else
8062 if (print_at)
8063 putchar ('@');
8064 putchar (*q);
8065 print_at = FALSE;
8070 putchar ('\n');
8073 ++p;
8077 /* getenv built-in spec function.
8079 Returns the value of the environment variable given by its first
8080 argument, concatenated with the second argument. If the
8081 environment variable is not defined, a fatal error is issued. */
8083 static const char *
8084 getenv_spec_function (int argc, const char **argv)
8086 char *value;
8087 char *result;
8088 char *ptr;
8089 size_t len;
8091 if (argc != 2)
8092 return NULL;
8094 value = getenv (argv[0]);
8095 if (!value)
8096 fatal_error ("environment variable %qs not defined", argv[0]);
8098 /* We have to escape every character of the environment variable so
8099 they are not interpreted as active spec characters. A
8100 particularly painful case is when we are reading a variable
8101 holding a windows path complete with \ separators. */
8102 len = strlen (value) * 2 + strlen (argv[1]) + 1;
8103 result = XNEWVAR (char, len);
8104 for (ptr = result; *value; ptr += 2)
8106 ptr[0] = '\\';
8107 ptr[1] = *value++;
8110 strcpy (ptr, argv[1]);
8112 return result;
8115 /* if-exists built-in spec function.
8117 Checks to see if the file specified by the absolute pathname in
8118 ARGS exists. Returns that pathname if found.
8120 The usual use for this function is to check for a library file
8121 (whose name has been expanded with %s). */
8123 static const char *
8124 if_exists_spec_function (int argc, const char **argv)
8126 /* Must have only one argument. */
8127 if (argc == 1 && IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
8128 return argv[0];
8130 return NULL;
8133 /* if-exists-else built-in spec function.
8135 This is like if-exists, but takes an additional argument which
8136 is returned if the first argument does not exist. */
8138 static const char *
8139 if_exists_else_spec_function (int argc, const char **argv)
8141 /* Must have exactly two arguments. */
8142 if (argc != 2)
8143 return NULL;
8145 if (IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
8146 return argv[0];
8148 return argv[1];
8151 /* sanitize built-in spec function.
8153 This returns non-NULL, if sanitizing address, thread or
8154 any of the undefined behavior sanitizers. */
8156 static const char *
8157 sanitize_spec_function (int argc, const char **argv)
8159 if (argc != 1)
8160 return NULL;
8162 if (strcmp (argv[0], "address") == 0)
8163 return (flag_sanitize & SANITIZE_ADDRESS) ? "" : NULL;
8164 if (strcmp (argv[0], "thread") == 0)
8165 return (flag_sanitize & SANITIZE_THREAD) ? "" : NULL;
8166 if (strcmp (argv[0], "undefined") == 0)
8167 return (flag_sanitize & SANITIZE_UNDEFINED) ? "" : NULL;
8168 if (strcmp (argv[0], "leak") == 0)
8169 return ((flag_sanitize
8170 & (SANITIZE_ADDRESS | SANITIZE_LEAK | SANITIZE_THREAD))
8171 == SANITIZE_LEAK) ? "" : NULL;
8172 return NULL;
8175 /* replace-outfile built-in spec function.
8177 This looks for the first argument in the outfiles array's name and
8178 replaces it with the second argument. */
8180 static const char *
8181 replace_outfile_spec_function (int argc, const char **argv)
8183 int i;
8184 /* Must have exactly two arguments. */
8185 if (argc != 2)
8186 abort ();
8188 for (i = 0; i < n_infiles; i++)
8190 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
8191 outfiles[i] = xstrdup (argv[1]);
8193 return NULL;
8196 /* remove-outfile built-in spec function.
8198 * This looks for the first argument in the outfiles array's name and
8199 * removes it. */
8201 static const char *
8202 remove_outfile_spec_function (int argc, const char **argv)
8204 int i;
8205 /* Must have exactly one argument. */
8206 if (argc != 1)
8207 abort ();
8209 for (i = 0; i < n_infiles; i++)
8211 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
8212 outfiles[i] = NULL;
8214 return NULL;
8217 /* Given two version numbers, compares the two numbers.
8218 A version number must match the regular expression
8219 ([1-9][0-9]*|0)(\.([1-9][0-9]*|0))*
8221 static int
8222 compare_version_strings (const char *v1, const char *v2)
8224 int rresult;
8225 regex_t r;
8227 if (regcomp (&r, "^([1-9][0-9]*|0)(\\.([1-9][0-9]*|0))*$",
8228 REG_EXTENDED | REG_NOSUB) != 0)
8229 abort ();
8230 rresult = regexec (&r, v1, 0, NULL, 0);
8231 if (rresult == REG_NOMATCH)
8232 fatal_error ("invalid version number %qs", v1);
8233 else if (rresult != 0)
8234 abort ();
8235 rresult = regexec (&r, v2, 0, NULL, 0);
8236 if (rresult == REG_NOMATCH)
8237 fatal_error ("invalid version number %qs", v2);
8238 else if (rresult != 0)
8239 abort ();
8241 return strverscmp (v1, v2);
8245 /* version_compare built-in spec function.
8247 This takes an argument of the following form:
8249 <comparison-op> <arg1> [<arg2>] <switch> <result>
8251 and produces "result" if the comparison evaluates to true,
8252 and nothing if it doesn't.
8254 The supported <comparison-op> values are:
8256 >= true if switch is a later (or same) version than arg1
8257 !> opposite of >=
8258 < true if switch is an earlier version than arg1
8259 !< opposite of <
8260 >< true if switch is arg1 or later, and earlier than arg2
8261 <> true if switch is earlier than arg1 or is arg2 or later
8263 If the switch is not present, the condition is false unless
8264 the first character of the <comparison-op> is '!'.
8266 For example,
8267 %:version-compare(>= 10.3 mmacosx-version-min= -lmx)
8268 adds -lmx if -mmacosx-version-min=10.3.9 was passed. */
8270 static const char *
8271 version_compare_spec_function (int argc, const char **argv)
8273 int comp1, comp2;
8274 size_t switch_len;
8275 const char *switch_value = NULL;
8276 int nargs = 1, i;
8277 bool result;
8279 if (argc < 3)
8280 fatal_error ("too few arguments to %%:version-compare");
8281 if (argv[0][0] == '\0')
8282 abort ();
8283 if ((argv[0][1] == '<' || argv[0][1] == '>') && argv[0][0] != '!')
8284 nargs = 2;
8285 if (argc != nargs + 3)
8286 fatal_error ("too many arguments to %%:version-compare");
8288 switch_len = strlen (argv[nargs + 1]);
8289 for (i = 0; i < n_switches; i++)
8290 if (!strncmp (switches[i].part1, argv[nargs + 1], switch_len)
8291 && check_live_switch (i, switch_len))
8292 switch_value = switches[i].part1 + switch_len;
8294 if (switch_value == NULL)
8295 comp1 = comp2 = -1;
8296 else
8298 comp1 = compare_version_strings (switch_value, argv[1]);
8299 if (nargs == 2)
8300 comp2 = compare_version_strings (switch_value, argv[2]);
8301 else
8302 comp2 = -1; /* This value unused. */
8305 switch (argv[0][0] << 8 | argv[0][1])
8307 case '>' << 8 | '=':
8308 result = comp1 >= 0;
8309 break;
8310 case '!' << 8 | '<':
8311 result = comp1 >= 0 || switch_value == NULL;
8312 break;
8313 case '<' << 8:
8314 result = comp1 < 0;
8315 break;
8316 case '!' << 8 | '>':
8317 result = comp1 < 0 || switch_value == NULL;
8318 break;
8319 case '>' << 8 | '<':
8320 result = comp1 >= 0 && comp2 < 0;
8321 break;
8322 case '<' << 8 | '>':
8323 result = comp1 < 0 || comp2 >= 0;
8324 break;
8326 default:
8327 fatal_error ("unknown operator %qs in %%:version-compare", argv[0]);
8329 if (! result)
8330 return NULL;
8332 return argv[nargs + 2];
8335 /* %:include builtin spec function. This differs from %include in that it
8336 can be nested inside a spec, and thus be conditionalized. It takes
8337 one argument, the filename, and looks for it in the startfile path.
8338 The result is always NULL, i.e. an empty expansion. */
8340 static const char *
8341 include_spec_function (int argc, const char **argv)
8343 char *file;
8345 if (argc != 1)
8346 abort ();
8348 file = find_a_file (&startfile_prefixes, argv[0], R_OK, true);
8349 read_specs (file ? file : argv[0], false, false);
8351 return NULL;
8354 /* %:find-file spec function. This function replaces its argument by
8355 the file found through find_file, that is the -print-file-name gcc
8356 program option. */
8357 static const char *
8358 find_file_spec_function (int argc, const char **argv)
8360 const char *file;
8362 if (argc != 1)
8363 abort ();
8365 file = find_file (argv[0]);
8366 return file;
8370 /* %:find-plugindir spec function. This function replaces its argument
8371 by the -iplugindir=<dir> option. `dir' is found through find_file, that
8372 is the -print-file-name gcc program option. */
8373 static const char *
8374 find_plugindir_spec_function (int argc, const char **argv ATTRIBUTE_UNUSED)
8376 const char *option;
8378 if (argc != 0)
8379 abort ();
8381 option = concat ("-iplugindir=", find_file ("plugin"), NULL);
8382 return option;
8386 /* %:print-asm-header spec function. Print a banner to say that the
8387 following output is from the assembler. */
8389 static const char *
8390 print_asm_header_spec_function (int arg ATTRIBUTE_UNUSED,
8391 const char **argv ATTRIBUTE_UNUSED)
8393 printf (_("Assembler options\n=================\n\n"));
8394 printf (_("Use \"-Wa,OPTION\" to pass \"OPTION\" to the assembler.\n\n"));
8395 fflush (stdout);
8396 return NULL;
8399 /* Get a random number for -frandom-seed */
8401 static unsigned HOST_WIDE_INT
8402 get_random_number (void)
8404 unsigned HOST_WIDE_INT ret = 0;
8405 int fd;
8407 fd = open ("/dev/urandom", O_RDONLY);
8408 if (fd >= 0)
8410 read (fd, &ret, sizeof (HOST_WIDE_INT));
8411 close (fd);
8412 if (ret)
8413 return ret;
8416 /* Get some more or less random data. */
8417 #ifdef HAVE_GETTIMEOFDAY
8419 struct timeval tv;
8421 gettimeofday (&tv, NULL);
8422 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
8424 #else
8426 time_t now = time (NULL);
8428 if (now != (time_t)-1)
8429 ret = (unsigned) now;
8431 #endif
8433 return ret ^ getpid ();
8436 /* %:compare-debug-dump-opt spec function. Save the last argument,
8437 expected to be the last -fdump-final-insns option, or generate a
8438 temporary. */
8440 static const char *
8441 compare_debug_dump_opt_spec_function (int arg,
8442 const char **argv ATTRIBUTE_UNUSED)
8444 char *ret;
8445 char *name;
8446 int which;
8447 static char random_seed[HOST_BITS_PER_WIDE_INT / 4 + 3];
8449 if (arg != 0)
8450 fatal_error ("too many arguments to %%:compare-debug-dump-opt");
8452 do_spec_2 ("%{fdump-final-insns=*:%*}");
8453 do_spec_1 (" ", 0, NULL);
8455 if (argbuf.length () > 0
8456 && strcmp (argv[argbuf.length () - 1], "."))
8458 if (!compare_debug)
8459 return NULL;
8461 name = xstrdup (argv[argbuf.length () - 1]);
8462 ret = NULL;
8464 else
8466 const char *ext = NULL;
8468 if (argbuf.length () > 0)
8470 do_spec_2 ("%{o*:%*}%{!o:%{!S:%b%O}%{S:%b.s}}");
8471 ext = ".gkd";
8473 else if (!compare_debug)
8474 return NULL;
8475 else
8476 do_spec_2 ("%g.gkd");
8478 do_spec_1 (" ", 0, NULL);
8480 gcc_assert (argbuf.length () > 0);
8482 name = concat (argbuf.last (), ext, NULL);
8484 ret = concat ("-fdump-final-insns=", name, NULL);
8487 which = compare_debug < 0;
8488 debug_check_temp_file[which] = name;
8490 if (!which)
8492 unsigned HOST_WIDE_INT value = get_random_number ();
8494 sprintf (random_seed, HOST_WIDE_INT_PRINT_HEX, value);
8497 if (*random_seed)
8499 char *tmp = ret;
8500 ret = concat ("%{!frandom-seed=*:-frandom-seed=", random_seed, "} ",
8501 ret, NULL);
8502 free (tmp);
8505 if (which)
8506 *random_seed = 0;
8508 return ret;
8511 static const char *debug_auxbase_opt;
8513 /* %:compare-debug-self-opt spec function. Expands to the options
8514 that are to be passed in the second compilation of
8515 compare-debug. */
8517 static const char *
8518 compare_debug_self_opt_spec_function (int arg,
8519 const char **argv ATTRIBUTE_UNUSED)
8521 if (arg != 0)
8522 fatal_error ("too many arguments to %%:compare-debug-self-opt");
8524 if (compare_debug >= 0)
8525 return NULL;
8527 do_spec_2 ("%{c|S:%{o*:%*}}");
8528 do_spec_1 (" ", 0, NULL);
8530 if (argbuf.length () > 0)
8531 debug_auxbase_opt = concat ("-auxbase-strip ",
8532 argbuf.last (),
8533 NULL);
8534 else
8535 debug_auxbase_opt = NULL;
8537 return concat ("\
8538 %<o %<MD %<MMD %<MF* %<MG %<MP %<MQ* %<MT* \
8539 %<fdump-final-insns=* -w -S -o %j \
8540 %{!fcompare-debug-second:-fcompare-debug-second} \
8541 ", compare_debug_opt, NULL);
8544 /* %:compare-debug-auxbase-opt spec function. Expands to the auxbase
8545 options that are to be passed in the second compilation of
8546 compare-debug. It expects, as an argument, the basename of the
8547 current input file name, with the .gk suffix appended to it. */
8549 static const char *
8550 compare_debug_auxbase_opt_spec_function (int arg,
8551 const char **argv)
8553 char *name;
8554 int len;
8556 if (arg == 0)
8557 fatal_error ("too few arguments to %%:compare-debug-auxbase-opt");
8559 if (arg != 1)
8560 fatal_error ("too many arguments to %%:compare-debug-auxbase-opt");
8562 if (compare_debug >= 0)
8563 return NULL;
8565 len = strlen (argv[0]);
8566 if (len < 3 || strcmp (argv[0] + len - 3, ".gk") != 0)
8567 fatal_error ("argument to %%:compare-debug-auxbase-opt "
8568 "does not end in .gk");
8570 if (debug_auxbase_opt)
8571 return debug_auxbase_opt;
8573 #define OPT "-auxbase "
8575 len -= 3;
8576 name = (char*) xmalloc (sizeof (OPT) + len);
8577 memcpy (name, OPT, sizeof (OPT) - 1);
8578 memcpy (name + sizeof (OPT) - 1, argv[0], len);
8579 name[sizeof (OPT) - 1 + len] = '\0';
8581 #undef OPT
8583 return name;
8586 /* %:pass-through-libs spec function. Finds all -l options and input
8587 file names in the lib spec passed to it, and makes a list of them
8588 prepended with the plugin option to cause them to be passed through
8589 to the final link after all the new object files have been added. */
8591 const char *
8592 pass_through_libs_spec_func (int argc, const char **argv)
8594 char *prepended = xstrdup (" ");
8595 int n;
8596 /* Shlemiel the painter's algorithm. Innately horrible, but at least
8597 we know that there will never be more than a handful of strings to
8598 concat, and it's only once per run, so it's not worth optimising. */
8599 for (n = 0; n < argc; n++)
8601 char *old = prepended;
8602 /* Anything that isn't an option is a full path to an output
8603 file; pass it through if it ends in '.a'. Among options,
8604 pass only -l. */
8605 if (argv[n][0] == '-' && argv[n][1] == 'l')
8607 const char *lopt = argv[n] + 2;
8608 /* Handle both joined and non-joined -l options. If for any
8609 reason there's a trailing -l with no joined or following
8610 arg just discard it. */
8611 if (!*lopt && ++n >= argc)
8612 break;
8613 else if (!*lopt)
8614 lopt = argv[n];
8615 prepended = concat (prepended, "-plugin-opt=-pass-through=-l",
8616 lopt, " ", NULL);
8618 else if (!strcmp (".a", argv[n] + strlen (argv[n]) - 2))
8620 prepended = concat (prepended, "-plugin-opt=-pass-through=",
8621 argv[n], " ", NULL);
8623 if (prepended != old)
8624 free (old);
8626 return prepended;
8629 /* %:replace-extension spec function. Replaces the extension of the
8630 first argument with the second argument. */
8632 const char *
8633 replace_extension_spec_func (int argc, const char **argv)
8635 char *name;
8636 char *p;
8637 char *result;
8638 int i;
8640 if (argc != 2)
8641 fatal_error ("too few arguments to %%:replace-extension");
8643 name = xstrdup (argv[0]);
8645 for (i = strlen (name) - 1; i >= 0; i--)
8646 if (IS_DIR_SEPARATOR (name[i]))
8647 break;
8649 p = strrchr (name + i + 1, '.');
8650 if (p != NULL)
8651 *p = '\0';
8653 result = concat (name, argv[1], NULL);
8655 free (name);
8656 return result;
8659 /* Insert backslash before spaces in ORIG (usually a file path), to
8660 avoid being broken by spec parser.
8662 This function is needed as do_spec_1 treats white space (' ' and '\t')
8663 as the end of an argument. But in case of -plugin /usr/gcc install/xxx.so,
8664 the file name should be treated as a single argument rather than being
8665 broken into multiple. Solution is to insert '\\' before the space in a
8666 file name.
8668 This function converts and only converts all occurrence of ' '
8669 to '\\' + ' ' and '\t' to '\\' + '\t'. For example:
8670 "a b" -> "a\\ b"
8671 "a b" -> "a\\ \\ b"
8672 "a\tb" -> "a\\\tb"
8673 "a\\ b" -> "a\\\\ b"
8675 orig: input null-terminating string that was allocated by xalloc. The
8676 memory it points to might be freed in this function. Behavior undefined
8677 if ORIG wasn't xalloced or was freed already at entry.
8679 Return: ORIG if no conversion needed. Otherwise a newly allocated string
8680 that was converted from ORIG. */
8682 static char *
8683 convert_white_space (char *orig)
8685 int len, number_of_space = 0;
8687 for (len = 0; orig[len]; len++)
8688 if (orig[len] == ' ' || orig[len] == '\t') number_of_space++;
8690 if (number_of_space)
8692 char *new_spec = (char *) xmalloc (len + number_of_space + 1);
8693 int j, k;
8694 for (j = 0, k = 0; j <= len; j++, k++)
8696 if (orig[j] == ' ' || orig[j] == '\t')
8697 new_spec[k++] = '\\';
8698 new_spec[k] = orig[j];
8700 free (orig);
8701 return new_spec;
8703 else
8704 return orig;