gcc/
[official-gcc.git] / gcc / gcc.c
blob9224bd85248439064d0f6e6321641c601e888f4e
1 /* Compiler driver program that can handle many languages.
2 Copyright (C) 1987-2015 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 "filenames.h"
46 /* By default there is no special suffix for target executables. */
47 /* FIXME: when autoconf is fixed, remove the host check - dj */
48 #if defined(TARGET_EXECUTABLE_SUFFIX) && defined(HOST_EXECUTABLE_SUFFIX)
49 #define HAVE_TARGET_EXECUTABLE_SUFFIX
50 #endif
52 /* By default there is no special suffix for host executables. */
53 #ifdef HOST_EXECUTABLE_SUFFIX
54 #define HAVE_HOST_EXECUTABLE_SUFFIX
55 #else
56 #define HOST_EXECUTABLE_SUFFIX ""
57 #endif
59 /* By default, the suffix for target object files is ".o". */
60 #ifdef TARGET_OBJECT_SUFFIX
61 #define HAVE_TARGET_OBJECT_SUFFIX
62 #else
63 #define TARGET_OBJECT_SUFFIX ".o"
64 #endif
66 static const char dir_separator_str[] = { DIR_SEPARATOR, 0 };
68 /* Most every one is fine with LIBRARY_PATH. For some, it conflicts. */
69 #ifndef LIBRARY_PATH_ENV
70 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
71 #endif
73 /* If a stage of compilation returns an exit status >= 1,
74 compilation of that file ceases. */
76 #define MIN_FATAL_STATUS 1
78 /* Flag set by cppspec.c to 1. */
79 int is_cpp_driver;
81 /* Flag set to nonzero if an @file argument has been supplied to gcc. */
82 static bool at_file_supplied;
84 /* Definition of string containing the arguments given to configure. */
85 #include "configargs.h"
87 /* Flag saying to print the command line options understood by gcc and its
88 sub-processes. */
90 static int print_help_list;
92 /* Flag saying to print the version of gcc and its sub-processes. */
94 static int print_version;
96 /* Flag indicating whether we should ONLY print the command and
97 arguments (like verbose_flag) without executing the command.
98 Displayed arguments are quoted so that the generated command
99 line is suitable for execution. This is intended for use in
100 shell scripts to capture the driver-generated command line. */
101 static int verbose_only_flag;
103 /* Flag indicating how to print command line options of sub-processes. */
105 static int print_subprocess_help;
107 /* Linker suffix passed to -fuse-ld=... */
108 static const char *use_ld;
110 /* Whether we should report subprocess execution times to a file. */
112 FILE *report_times_to_file = NULL;
114 /* Nonzero means place this string before uses of /, so that include
115 and library files can be found in an alternate location. */
117 #ifdef TARGET_SYSTEM_ROOT
118 static const char *target_system_root = TARGET_SYSTEM_ROOT;
119 #else
120 static const char *target_system_root = 0;
121 #endif
123 /* Nonzero means pass the updated target_system_root to the compiler. */
125 static int target_system_root_changed;
127 /* Nonzero means append this string to target_system_root. */
129 static const char *target_sysroot_suffix = 0;
131 /* Nonzero means append this string to target_system_root for headers. */
133 static const char *target_sysroot_hdrs_suffix = 0;
135 /* Nonzero means write "temp" files in source directory
136 and use the source file's name in them, and don't delete them. */
138 static enum save_temps {
139 SAVE_TEMPS_NONE, /* no -save-temps */
140 SAVE_TEMPS_CWD, /* -save-temps in current directory */
141 SAVE_TEMPS_OBJ /* -save-temps in object directory */
142 } save_temps_flag;
144 /* Output file to use to get the object directory for -save-temps=obj */
145 static char *save_temps_prefix = 0;
146 static size_t save_temps_length = 0;
148 /* The compiler version. */
150 static const char *compiler_version;
152 /* The target version. */
154 static const char *const spec_version = DEFAULT_TARGET_VERSION;
156 /* The target machine. */
158 static const char *spec_machine = DEFAULT_TARGET_MACHINE;
159 static const char *spec_host_machine = DEFAULT_REAL_TARGET_MACHINE;
161 /* List of offload targets. */
163 static char *offload_targets = NULL;
165 /* Nonzero if cross-compiling.
166 When -b is used, the value comes from the `specs' file. */
168 #ifdef CROSS_DIRECTORY_STRUCTURE
169 static const char *cross_compile = "1";
170 #else
171 static const char *cross_compile = "0";
172 #endif
174 /* Greatest exit code of sub-processes that has been encountered up to
175 now. */
176 static int greatest_status = 1;
178 /* This is the obstack which we use to allocate many strings. */
180 static struct obstack obstack;
182 /* This is the obstack to build an environment variable to pass to
183 collect2 that describes all of the relevant switches of what to
184 pass the compiler in building the list of pointers to constructors
185 and destructors. */
187 static struct obstack collect_obstack;
189 /* Forward declaration for prototypes. */
190 struct path_prefix;
191 struct prefix_list;
193 static void init_spec (void);
194 static void store_arg (const char *, int, int);
195 static void insert_wrapper (const char *);
196 static char *load_specs (const char *);
197 static void read_specs (const char *, bool, bool);
198 static void set_spec (const char *, const char *, bool);
199 static struct compiler *lookup_compiler (const char *, size_t, const char *);
200 static char *build_search_list (const struct path_prefix *, const char *,
201 bool, bool);
202 static void xputenv (const char *);
203 static void putenv_from_prefixes (const struct path_prefix *, const char *,
204 bool);
205 static int access_check (const char *, int);
206 static char *find_a_file (const struct path_prefix *, const char *, int, bool);
207 static void add_prefix (struct path_prefix *, const char *, const char *,
208 int, int, int);
209 static void add_sysrooted_prefix (struct path_prefix *, const char *,
210 const char *, int, int, int);
211 static char *skip_whitespace (char *);
212 static void delete_if_ordinary (const char *);
213 static void delete_temp_files (void);
214 static void delete_failure_queue (void);
215 static void clear_failure_queue (void);
216 static int check_live_switch (int, int);
217 static const char *handle_braces (const char *);
218 static inline bool input_suffix_matches (const char *, const char *);
219 static inline bool switch_matches (const char *, const char *, int);
220 static inline void mark_matching_switches (const char *, const char *, int);
221 static inline void process_marked_switches (void);
222 static const char *process_brace_body (const char *, const char *, const char *, int, int);
223 static const struct spec_function *lookup_spec_function (const char *);
224 static const char *eval_spec_function (const char *, const char *);
225 static const char *handle_spec_function (const char *, bool *);
226 static char *save_string (const char *, int);
227 static void set_collect_gcc_options (void);
228 static int do_spec_1 (const char *, int, const char *);
229 static int do_spec_2 (const char *);
230 static void do_option_spec (const char *, const char *);
231 static void do_self_spec (const char *);
232 static const char *find_file (const char *);
233 static int is_directory (const char *, bool);
234 static const char *validate_switches (const char *, bool);
235 static void validate_all_switches (void);
236 static inline void validate_switches_from_spec (const char *, bool);
237 static void give_switch (int, int);
238 static int used_arg (const char *, int);
239 static int default_arg (const char *, int);
240 static void set_multilib_dir (void);
241 static void print_multilib_info (void);
242 static void perror_with_name (const char *);
243 static void display_help (void);
244 static void add_preprocessor_option (const char *, int);
245 static void add_assembler_option (const char *, int);
246 static void add_linker_option (const char *, int);
247 static void process_command (unsigned int, struct cl_decoded_option *);
248 static int execute (void);
249 static void alloc_args (void);
250 static void clear_args (void);
251 static void fatal_signal (int);
252 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
253 static void init_gcc_specs (struct obstack *, const char *, const char *,
254 const char *);
255 #endif
256 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
257 static const char *convert_filename (const char *, int, int);
258 #endif
260 static void try_generate_repro (const char **argv);
261 static const char *getenv_spec_function (int, const char **);
262 static const char *if_exists_spec_function (int, const char **);
263 static const char *if_exists_else_spec_function (int, const char **);
264 static const char *sanitize_spec_function (int, const char **);
265 static const char *replace_outfile_spec_function (int, const char **);
266 static const char *remove_outfile_spec_function (int, const char **);
267 static const char *version_compare_spec_function (int, const char **);
268 static const char *include_spec_function (int, const char **);
269 static const char *find_file_spec_function (int, const char **);
270 static const char *find_plugindir_spec_function (int, const char **);
271 static const char *print_asm_header_spec_function (int, const char **);
272 static const char *compare_debug_dump_opt_spec_function (int, const char **);
273 static const char *compare_debug_self_opt_spec_function (int, const char **);
274 static const char *compare_debug_auxbase_opt_spec_function (int, const char **);
275 static const char *pass_through_libs_spec_func (int, const char **);
276 static const char *replace_extension_spec_func (int, const char **);
277 static char *convert_white_space (char *);
279 /* The Specs Language
281 Specs are strings containing lines, each of which (if not blank)
282 is made up of a program name, and arguments separated by spaces.
283 The program name must be exact and start from root, since no path
284 is searched and it is unreliable to depend on the current working directory.
285 Redirection of input or output is not supported; the subprograms must
286 accept filenames saying what files to read and write.
288 In addition, the specs can contain %-sequences to substitute variable text
289 or for conditional text. Here is a table of all defined %-sequences.
290 Note that spaces are not generated automatically around the results of
291 expanding these sequences; therefore, you can concatenate them together
292 or with constant text in a single argument.
294 %% substitute one % into the program name or argument.
295 %i substitute the name of the input file being processed.
296 %b substitute the basename of the input file being processed.
297 This is the substring up to (and not including) the last period
298 and not including the directory unless -save-temps was specified
299 to put temporaries in a different location.
300 %B same as %b, but include the file suffix (text after the last period).
301 %gSUFFIX
302 substitute a file name that has suffix SUFFIX and is chosen
303 once per compilation, and mark the argument a la %d. To reduce
304 exposure to denial-of-service attacks, the file name is now
305 chosen in a way that is hard to predict even when previously
306 chosen file names are known. For example, `%g.s ... %g.o ... %g.s'
307 might turn into `ccUVUUAU.s ccXYAXZ12.o ccUVUUAU.s'. SUFFIX matches
308 the regexp "[.0-9A-Za-z]*%O"; "%O" is treated exactly as if it
309 had been pre-processed. Previously, %g was simply substituted
310 with a file name chosen once per compilation, without regard
311 to any appended suffix (which was therefore treated just like
312 ordinary text), making such attacks more likely to succeed.
313 %|SUFFIX
314 like %g, but if -pipe is in effect, expands simply to "-".
315 %mSUFFIX
316 like %g, but if -pipe is in effect, expands to nothing. (We have both
317 %| and %m to accommodate differences between system assemblers; see
318 the AS_NEEDS_DASH_FOR_PIPED_INPUT target macro.)
319 %uSUFFIX
320 like %g, but generates a new temporary file name even if %uSUFFIX
321 was already seen.
322 %USUFFIX
323 substitutes the last file name generated with %uSUFFIX, generating a
324 new one if there is no such last file name. In the absence of any
325 %uSUFFIX, this is just like %gSUFFIX, except they don't share
326 the same suffix "space", so `%g.s ... %U.s ... %g.s ... %U.s'
327 would involve the generation of two distinct file names, one
328 for each `%g.s' and another for each `%U.s'. Previously, %U was
329 simply substituted with a file name chosen for the previous %u,
330 without regard to any appended suffix.
331 %jSUFFIX
332 substitutes the name of the HOST_BIT_BUCKET, if any, and if it is
333 writable, and if save-temps is off; otherwise, substitute the name
334 of a temporary file, just like %u. This temporary file is not
335 meant for communication between processes, but rather as a junk
336 disposal mechanism.
337 %.SUFFIX
338 substitutes .SUFFIX for the suffixes of a matched switch's args when
339 it is subsequently output with %*. SUFFIX is terminated by the next
340 space or %.
341 %d marks the argument containing or following the %d as a
342 temporary file name, so that that file will be deleted if GCC exits
343 successfully. Unlike %g, this contributes no text to the argument.
344 %w marks the argument containing or following the %w as the
345 "output file" of this compilation. This puts the argument
346 into the sequence of arguments that %o will substitute later.
347 %V indicates that this compilation produces no "output file".
348 %W{...}
349 like %{...} but mark last argument supplied within
350 as a file to be deleted on failure.
351 %o substitutes the names of all the output files, with spaces
352 automatically placed around them. You should write spaces
353 around the %o as well or the results are undefined.
354 %o is for use in the specs for running the linker.
355 Input files whose names have no recognized suffix are not compiled
356 at all, but they are included among the output files, so they will
357 be linked.
358 %O substitutes the suffix for object files. Note that this is
359 handled specially when it immediately follows %g, %u, or %U
360 (with or without a suffix argument) because of the need for
361 those to form complete file names. The handling is such that
362 %O is treated exactly as if it had already been substituted,
363 except that %g, %u, and %U do not currently support additional
364 SUFFIX characters following %O as they would following, for
365 example, `.o'.
366 %I Substitute any of -iprefix (made from GCC_EXEC_PREFIX), -isysroot
367 (made from TARGET_SYSTEM_ROOT), -isystem (made from COMPILER_PATH
368 and -B options) and -imultilib as necessary.
369 %s current argument is the name of a library or startup file of some sort.
370 Search for that file in a standard list of directories
371 and substitute the full name found.
372 %eSTR Print STR as an error message. STR is terminated by a newline.
373 Use this when inconsistent options are detected.
374 %nSTR Print STR as a notice. STR is terminated by a newline.
375 %x{OPTION} Accumulate an option for %X.
376 %X Output the accumulated linker options specified by compilations.
377 %Y Output the accumulated assembler options specified by compilations.
378 %Z Output the accumulated preprocessor options specified by compilations.
379 %a process ASM_SPEC as a spec.
380 This allows config.h to specify part of the spec for running as.
381 %A process ASM_FINAL_SPEC as a spec. A capital A is actually
382 used here. This can be used to run a post-processor after the
383 assembler has done its job.
384 %D Dump out a -L option for each directory in startfile_prefixes.
385 If multilib_dir is set, extra entries are generated with it affixed.
386 %l process LINK_SPEC as a spec.
387 %L process LIB_SPEC as a spec.
388 %M Output multilib_os_dir.
389 %G process LIBGCC_SPEC as a spec.
390 %R Output the concatenation of target_system_root and
391 target_sysroot_suffix.
392 %S process STARTFILE_SPEC as a spec. A capital S is actually used here.
393 %E process ENDFILE_SPEC as a spec. A capital E is actually used here.
394 %C process CPP_SPEC as a spec.
395 %1 process CC1_SPEC as a spec.
396 %2 process CC1PLUS_SPEC as a spec.
397 %* substitute the variable part of a matched option. (See below.)
398 Note that each comma in the substituted string is replaced by
399 a single space. A space is appended after the last substition
400 unless there is more text in current sequence.
401 %<S remove all occurrences of -S from the command line.
402 Note - this command is position dependent. % commands in the
403 spec string before this one will see -S, % commands in the
404 spec string after this one will not.
405 %>S Similar to "%<S", but keep it in the GCC command line.
406 %<S* remove all occurrences of all switches beginning with -S from the
407 command line.
408 %:function(args)
409 Call the named function FUNCTION, passing it ARGS. ARGS is
410 first processed as a nested spec string, then split into an
411 argument vector in the usual fashion. The function returns
412 a string which is processed as if it had appeared literally
413 as part of the current spec.
414 %{S} substitutes the -S switch, if that switch was given to GCC.
415 If that switch was not specified, this substitutes nothing.
416 Here S is a metasyntactic variable.
417 %{S*} substitutes all the switches specified to GCC whose names start
418 with -S. This is used for -o, -I, etc; switches that take
419 arguments. GCC considers `-o foo' as being one switch whose
420 name starts with `o'. %{o*} would substitute this text,
421 including the space; thus, two arguments would be generated.
422 %{S*&T*} likewise, but preserve order of S and T options (the order
423 of S and T in the spec is not significant). Can be any number
424 of ampersand-separated variables; for each the wild card is
425 optional. Useful for CPP as %{D*&U*&A*}.
427 %{S:X} substitutes X, if the -S switch was given to GCC.
428 %{!S:X} substitutes X, if the -S switch was NOT given to GCC.
429 %{S*:X} substitutes X if one or more switches whose names start
430 with -S was given to GCC. Normally X is substituted only
431 once, no matter how many such switches appeared. However,
432 if %* appears somewhere in X, then X will be substituted
433 once for each matching switch, with the %* replaced by the
434 part of that switch that matched the '*'. A space will be
435 appended after the last substition unless there is more
436 text in current sequence.
437 %{.S:X} substitutes X, if processing a file with suffix S.
438 %{!.S:X} substitutes X, if NOT processing a file with suffix S.
439 %{,S:X} substitutes X, if processing a file which will use spec S.
440 %{!,S:X} substitutes X, if NOT processing a file which will use spec S.
442 %{S|T:X} substitutes X if either -S or -T was given to GCC. This may be
443 combined with '!', '.', ',', and '*' as above binding stronger
444 than the OR.
445 If %* appears in X, all of the alternatives must be starred, and
446 only the first matching alternative is substituted.
447 %{%:function(args):X}
448 Call function named FUNCTION with args ARGS. If the function
449 returns non-NULL, then X is substituted, if it returns
450 NULL, it isn't substituted.
451 %{S:X; if S was given to GCC, substitutes X;
452 T:Y; else if T was given to GCC, substitutes Y;
453 :D} else substitutes D. There can be as many clauses as you need.
454 This may be combined with '.', '!', ',', '|', and '*' as above.
456 %(Spec) processes a specification defined in a specs file as *Spec:
458 The conditional text X in a %{S:X} or similar construct may contain
459 other nested % constructs or spaces, or even newlines. They are
460 processed as usual, as described above. Trailing white space in X is
461 ignored. White space may also appear anywhere on the left side of the
462 colon in these constructs, except between . or * and the corresponding
463 word.
465 The -O, -f, -g, -m, and -W switches are handled specifically in these
466 constructs. If another value of -O or the negated form of a -f, -m, or
467 -W switch is found later in the command line, the earlier switch
468 value is ignored, except with {S*} where S is just one letter; this
469 passes all matching options.
471 The character | at the beginning of the predicate text is used to indicate
472 that a command should be piped to the following command, but only if -pipe
473 is specified.
475 Note that it is built into GCC which switches take arguments and which
476 do not. You might think it would be useful to generalize this to
477 allow each compiler's spec to say which switches take arguments. But
478 this cannot be done in a consistent fashion. GCC cannot even decide
479 which input files have been specified without knowing which switches
480 take arguments, and it must know which input files to compile in order
481 to tell which compilers to run.
483 GCC also knows implicitly that arguments starting in `-l' are to be
484 treated as compiler output files, and passed to the linker in their
485 proper position among the other output files. */
487 /* Define the macros used for specs %a, %l, %L, %S, %C, %1. */
489 /* config.h can define ASM_SPEC to provide extra args to the assembler
490 or extra switch-translations. */
491 #ifndef ASM_SPEC
492 #define ASM_SPEC ""
493 #endif
495 /* config.h can define ASM_FINAL_SPEC to run a post processor after
496 the assembler has run. */
497 #ifndef ASM_FINAL_SPEC
498 #define ASM_FINAL_SPEC \
499 "%{gsplit-dwarf: \n\
500 objcopy --extract-dwo \
501 %{c:%{o*:%*}%{!o*:%b%O}}%{!c:%U%O} \
502 %{c:%{o*:%:replace-extension(%{o*:%*} .dwo)}%{!o*:%b.dwo}}%{!c:%b.dwo} \n\
503 objcopy --strip-dwo \
504 %{c:%{o*:%*}%{!o*:%b%O}}%{!c:%U%O} \
506 #endif
508 /* config.h can define CPP_SPEC to provide extra args to the C preprocessor
509 or extra switch-translations. */
510 #ifndef CPP_SPEC
511 #define CPP_SPEC ""
512 #endif
514 /* config.h can define CC1_SPEC to provide extra args to cc1 and cc1plus
515 or extra switch-translations. */
516 #ifndef CC1_SPEC
517 #define CC1_SPEC ""
518 #endif
520 /* config.h can define CC1PLUS_SPEC to provide extra args to cc1plus
521 or extra switch-translations. */
522 #ifndef CC1PLUS_SPEC
523 #define CC1PLUS_SPEC ""
524 #endif
526 /* config.h can define LINK_SPEC to provide extra args to the linker
527 or extra switch-translations. */
528 #ifndef LINK_SPEC
529 #define LINK_SPEC ""
530 #endif
532 /* config.h can define LIB_SPEC to override the default libraries. */
533 #ifndef LIB_SPEC
534 #define LIB_SPEC "%{!shared:%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}}"
535 #endif
537 /* When using -fsplit-stack we need to wrap pthread_create, in order
538 to initialize the stack guard. We always use wrapping, rather than
539 shared library ordering, and we keep the wrapper function in
540 libgcc. This is not yet a real spec, though it could become one;
541 it is currently just stuffed into LINK_SPEC. FIXME: This wrapping
542 only works with GNU ld and gold. */
543 #define STACK_SPLIT_SPEC " %{fsplit-stack: --wrap=pthread_create}"
545 #ifndef LIBASAN_SPEC
546 #define STATIC_LIBASAN_LIBS \
547 " %{static-libasan:%:include(libsanitizer.spec)%(link_libasan)}"
548 #ifdef LIBASAN_EARLY_SPEC
549 #define LIBASAN_SPEC STATIC_LIBASAN_LIBS
550 #elif defined(HAVE_LD_STATIC_DYNAMIC)
551 #define LIBASAN_SPEC "%{static-libasan:" LD_STATIC_OPTION \
552 "} -lasan %{static-libasan:" LD_DYNAMIC_OPTION "}" \
553 STATIC_LIBASAN_LIBS
554 #else
555 #define LIBASAN_SPEC "-lasan" STATIC_LIBASAN_LIBS
556 #endif
557 #endif
559 #ifndef LIBASAN_EARLY_SPEC
560 #define LIBASAN_EARLY_SPEC ""
561 #endif
563 #ifndef LIBTSAN_SPEC
564 #define STATIC_LIBTSAN_LIBS \
565 " %{static-libtsan:%:include(libsanitizer.spec)%(link_libtsan)}"
566 #ifdef LIBTSAN_EARLY_SPEC
567 #define LIBTSAN_SPEC STATIC_LIBTSAN_LIBS
568 #elif defined(HAVE_LD_STATIC_DYNAMIC)
569 #define LIBTSAN_SPEC "%{static-libtsan:" LD_STATIC_OPTION \
570 "} -ltsan %{static-libtsan:" LD_DYNAMIC_OPTION "}" \
571 STATIC_LIBTSAN_LIBS
572 #else
573 #define LIBTSAN_SPEC "-ltsan" STATIC_LIBTSAN_LIBS
574 #endif
575 #endif
577 #ifndef LIBTSAN_EARLY_SPEC
578 #define LIBTSAN_EARLY_SPEC ""
579 #endif
581 #ifndef LIBLSAN_SPEC
582 #define STATIC_LIBLSAN_LIBS \
583 " %{static-liblsan:%:include(libsanitizer.spec)%(link_liblsan)}"
584 #ifdef LIBLSAN_EARLY_SPEC
585 #define LIBLSAN_SPEC STATIC_LIBLSAN_LIBS
586 #elif defined(HAVE_LD_STATIC_DYNAMIC)
587 #define LIBLSAN_SPEC "%{static-liblsan:" LD_STATIC_OPTION \
588 "} -llsan %{static-liblsan:" LD_DYNAMIC_OPTION "}" \
589 STATIC_LIBLSAN_LIBS
590 #else
591 #define LIBLSAN_SPEC "-llsan" STATIC_LIBLSAN_LIBS
592 #endif
593 #endif
595 #ifndef LIBLSAN_EARLY_SPEC
596 #define LIBLSAN_EARLY_SPEC ""
597 #endif
599 #ifndef LIBUBSAN_SPEC
600 #define STATIC_LIBUBSAN_LIBS \
601 " %{static-libubsan:%:include(libsanitizer.spec)%(link_libubsan)}"
602 #ifdef HAVE_LD_STATIC_DYNAMIC
603 #define LIBUBSAN_SPEC "%{static-libubsan:" LD_STATIC_OPTION \
604 "} -lubsan %{static-libubsan:" LD_DYNAMIC_OPTION "}" \
605 STATIC_LIBUBSAN_LIBS
606 #else
607 #define LIBUBSAN_SPEC "-lubsan" STATIC_LIBUBSAN_LIBS
608 #endif
609 #endif
611 /* Linker options for compressed debug sections. */
612 #if HAVE_LD_COMPRESS_DEBUG == 0
613 /* No linker support. */
614 #define LINK_COMPRESS_DEBUG_SPEC \
615 " %{gz*:%e-gz is not supported in this configuration} "
616 #elif HAVE_LD_COMPRESS_DEBUG == 1
617 /* GNU style on input, GNU ld options. Reject, not useful. */
618 #define LINK_COMPRESS_DEBUG_SPEC \
619 " %{gz*:%e-gz is not supported in this configuration} "
620 #elif HAVE_LD_COMPRESS_DEBUG == 2
621 /* GNU style, GNU gold options. */
622 #define LINK_COMPRESS_DEBUG_SPEC \
623 " %{gz|gz=zlib-gnu:" LD_COMPRESS_DEBUG_OPTION "=zlib}" \
624 " %{gz=none:" LD_COMPRESS_DEBUG_OPTION "=none}" \
625 " %{gz=zlib:%e-gz=zlib is not supported in this configuration} "
626 #elif HAVE_LD_COMPRESS_DEBUG == 3
627 /* ELF gABI style. */
628 #define LINK_COMPRESS_DEBUG_SPEC \
629 " %{gz|gz=zlib:" LD_COMPRESS_DEBUG_OPTION "=zlib}" \
630 " %{gz=none:" LD_COMPRESS_DEBUG_OPTION "=none}" \
631 " %{gz=zlib-gnu:" LD_COMPRESS_DEBUG_OPTION "=zlib-gnu} "
632 #else
633 #error Unknown value for HAVE_LD_COMPRESS_DEBUG.
634 #endif
636 /* config.h can define LIBGCC_SPEC to override how and when libgcc.a is
637 included. */
638 #ifndef LIBGCC_SPEC
639 #if defined(REAL_LIBGCC_SPEC)
640 #define LIBGCC_SPEC REAL_LIBGCC_SPEC
641 #elif defined(LINK_LIBGCC_SPECIAL_1)
642 /* Have gcc do the search for libgcc.a. */
643 #define LIBGCC_SPEC "libgcc.a%s"
644 #else
645 #define LIBGCC_SPEC "-lgcc"
646 #endif
647 #endif
649 /* config.h can define STARTFILE_SPEC to override the default crt0 files. */
650 #ifndef STARTFILE_SPEC
651 #define STARTFILE_SPEC \
652 "%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
653 #endif
655 /* config.h can define ENDFILE_SPEC to override the default crtn files. */
656 #ifndef ENDFILE_SPEC
657 #define ENDFILE_SPEC ""
658 #endif
660 #ifndef LINKER_NAME
661 #define LINKER_NAME "collect2"
662 #endif
664 #ifdef HAVE_AS_DEBUG_PREFIX_MAP
665 #define ASM_MAP " %{fdebug-prefix-map=*:--debug-prefix-map %*}"
666 #else
667 #define ASM_MAP ""
668 #endif
670 /* Assembler options for compressed debug sections. */
671 #if HAVE_LD_COMPRESS_DEBUG < 2
672 /* Reject if the linker cannot write compressed debug sections. */
673 #define ASM_COMPRESS_DEBUG_SPEC \
674 " %{gz*:%e-gz is not supported in this configuration} "
675 #else /* HAVE_LD_COMPRESS_DEBUG >= 2 */
676 #if HAVE_AS_COMPRESS_DEBUG == 0
677 /* No assembler support. Ignore silently. */
678 #define ASM_COMPRESS_DEBUG_SPEC \
679 " %{gz*:} "
680 #elif HAVE_AS_COMPRESS_DEBUG == 1
681 /* GNU style, GNU as options. */
682 #define ASM_COMPRESS_DEBUG_SPEC \
683 " %{gz|gz=zlib-gnu:" AS_COMPRESS_DEBUG_OPTION "}" \
684 " %{gz=none:" AS_NO_COMPRESS_DEBUG_OPTION "}" \
685 " %{gz=zlib:%e-gz=zlib is not supported in this configuration} "
686 #elif HAVE_AS_COMPRESS_DEBUG == 2
687 /* ELF gABI style. */
688 #define ASM_COMPRESS_DEBUG_SPEC \
689 " %{gz|gz=zlib:" AS_COMPRESS_DEBUG_OPTION "=zlib}" \
690 " %{gz=none:" AS_COMPRESS_DEBUG_OPTION "=none}" \
691 " %{gz=zlib-gnu:" AS_COMPRESS_DEBUG_OPTION "=zlib-gnu} "
692 #else
693 #error Unknown value for HAVE_AS_COMPRESS_DEBUG.
694 #endif
695 #endif /* HAVE_LD_COMPRESS_DEBUG >= 2 */
697 /* Define ASM_DEBUG_SPEC to be a spec suitable for translating '-g'
698 to the assembler. */
699 #ifndef ASM_DEBUG_SPEC
700 # if defined(DBX_DEBUGGING_INFO) && defined(DWARF2_DEBUGGING_INFO) \
701 && defined(HAVE_AS_GDWARF2_DEBUG_FLAG) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
702 # define ASM_DEBUG_SPEC \
703 (PREFERRED_DEBUGGING_TYPE == DBX_DEBUG \
704 ? "%{!g0:%{gdwarf*:--gdwarf2}%{!gdwarf*:%{g*:--gstabs}}}" ASM_MAP \
705 : "%{!g0:%{gstabs*:--gstabs}%{!gstabs*:%{g*:--gdwarf2}}}" ASM_MAP)
706 # else
707 # if defined(DBX_DEBUGGING_INFO) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
708 # define ASM_DEBUG_SPEC "%{g*:%{!g0:--gstabs}}" ASM_MAP
709 # endif
710 # if defined(DWARF2_DEBUGGING_INFO) && defined(HAVE_AS_GDWARF2_DEBUG_FLAG)
711 # define ASM_DEBUG_SPEC "%{g*:%{!g0:--gdwarf2}}" ASM_MAP
712 # endif
713 # endif
714 #endif
715 #ifndef ASM_DEBUG_SPEC
716 # define ASM_DEBUG_SPEC ""
717 #endif
719 /* Here is the spec for running the linker, after compiling all files. */
721 /* This is overridable by the target in case they need to specify the
722 -lgcc and -lc order specially, yet not require them to override all
723 of LINK_COMMAND_SPEC. */
724 #ifndef LINK_GCC_C_SEQUENCE_SPEC
725 #define LINK_GCC_C_SEQUENCE_SPEC "%G %L %G"
726 #endif
728 #ifndef LINK_SSP_SPEC
729 #ifdef TARGET_LIBC_PROVIDES_SSP
730 #define LINK_SSP_SPEC "%{fstack-protector|fstack-protector-all" \
731 "|fstack-protector-strong|fstack-protector-explicit:}"
732 #else
733 #define LINK_SSP_SPEC "%{fstack-protector|fstack-protector-all" \
734 "|fstack-protector-strong|fstack-protector-explicit" \
735 ":-lssp_nonshared -lssp}"
736 #endif
737 #endif
739 #ifdef ENABLE_DEFAULT_PIE
740 #define NO_PIE_SPEC "no-pie|static"
741 #define PIE_SPEC NO_PIE_SPEC "|r|shared:;"
742 #define NO_FPIE1_SPEC "fno-pie"
743 #define FPIE1_SPEC NO_FPIE1_SPEC ":;"
744 #define NO_FPIE2_SPEC "fno-PIE"
745 #define FPIE2_SPEC NO_FPIE2_SPEC ":;"
746 #define NO_FPIE_SPEC NO_FPIE1_SPEC "|" NO_FPIE2_SPEC
747 #define FPIE_SPEC NO_FPIE_SPEC ":;"
748 #define NO_FPIC1_SPEC "fno-pic"
749 #define FPIC1_SPEC NO_FPIC1_SPEC ":;"
750 #define NO_FPIC2_SPEC "fno-PIC"
751 #define FPIC2_SPEC NO_FPIC2_SPEC ":;"
752 #define NO_FPIC_SPEC NO_FPIC1_SPEC "|" NO_FPIC2_SPEC
753 #define FPIC_SPEC NO_FPIC_SPEC ":;"
754 #define NO_FPIE1_AND_FPIC1_SPEC NO_FPIE1_SPEC "|" NO_FPIC1_SPEC
755 #define FPIE1_OR_FPIC1_SPEC NO_FPIE1_AND_FPIC1_SPEC ":;"
756 #define NO_FPIE2_AND_FPIC2_SPEC NO_FPIE2_SPEC "|" NO_FPIC2_SPEC
757 #define FPIE2_OR_FPIC2_SPEC NO_FPIE2_AND_FPIC2_SPEC ":;"
758 #define NO_FPIE_AND_FPIC_SPEC NO_FPIE_SPEC "|" NO_FPIC_SPEC
759 #define FPIE_OR_FPIC_SPEC NO_FPIE_AND_FPIC_SPEC ":;"
760 #else
761 #define PIE_SPEC "pie"
762 #define NO_PIE_SPEC PIE_SPEC "|r|shared:;"
763 #define FPIE1_SPEC "fpie"
764 #define NO_FPIE1_SPEC FPIE1_SPEC ":;"
765 #define FPIE2_SPEC "fPIE"
766 #define NO_FPIE2_SPEC FPIE2_SPEC ":;"
767 #define FPIE_SPEC FPIE1_SPEC "|" FPIE2_SPEC
768 #define NO_FPIE_SPEC FPIE_SPEC ":;"
769 #define FPIC1_SPEC "fpic"
770 #define NO_FPIC1_SPEC FPIC1_SPEC ":;"
771 #define FPIC2_SPEC "fPIC"
772 #define NO_FPIC2_SPEC FPIC2_SPEC ":;"
773 #define FPIC_SPEC FPIC1_SPEC "|" FPIC2_SPEC
774 #define NO_FPIC_SPEC FPIC_SPEC ":;"
775 #define FPIE1_OR_FPIC1_SPEC FPIE1_SPEC "|" FPIC1_SPEC
776 #define NO_FPIE1_AND_FPIC1_SPEC FPIE1_OR_FPIC1_SPEC ":;"
777 #define FPIE2_OR_FPIC2_SPEC FPIE2_SPEC "|" FPIC2_SPEC
778 #define NO_FPIE2_AND_FPIC2_SPEC FPIE1_OR_FPIC2_SPEC ":;"
779 #define FPIE_OR_FPIC_SPEC FPIE_SPEC "|" FPIC_SPEC
780 #define NO_FPIE_AND_FPIC_SPEC FPIE_OR_FPIC_SPEC ":;"
781 #endif
783 #ifndef LINK_PIE_SPEC
784 #ifdef HAVE_LD_PIE
785 #define LD_PIE_SPEC "-pie"
786 #else
787 #define LD_PIE_SPEC ""
788 #endif
789 #define LINK_PIE_SPEC "%{no-pie:} " "%{" PIE_SPEC ":" LD_PIE_SPEC "} "
790 #endif
792 #ifndef LINK_BUILDID_SPEC
793 # if defined(HAVE_LD_BUILDID) && defined(ENABLE_LD_BUILDID)
794 # define LINK_BUILDID_SPEC "%{!r:--build-id} "
795 # endif
796 #endif
798 /* Conditional to test whether the LTO plugin is used or not.
799 FIXME: For slim LTO we will need to enable plugin unconditionally. This
800 still cause problems with PLUGIN_LD != LD and when plugin is built but
801 not useable. For GCC 4.6 we don't support slim LTO and thus we can enable
802 plugin only when LTO is enabled. We still honor explicit
803 -fuse-linker-plugin if the linker used understands -plugin. */
805 /* The linker has some plugin support. */
806 #if HAVE_LTO_PLUGIN > 0
807 /* The linker used has full plugin support, use LTO plugin by default. */
808 #if HAVE_LTO_PLUGIN == 2
809 #define PLUGIN_COND "!fno-use-linker-plugin:%{!fno-lto"
810 #define PLUGIN_COND_CLOSE "}"
811 #else
812 /* The linker used has limited plugin support, use LTO plugin with explicit
813 -fuse-linker-plugin. */
814 #define PLUGIN_COND "fuse-linker-plugin"
815 #define PLUGIN_COND_CLOSE ""
816 #endif
817 #define LINK_PLUGIN_SPEC \
818 "%{" PLUGIN_COND": \
819 -plugin %(linker_plugin_file) \
820 -plugin-opt=%(lto_wrapper) \
821 -plugin-opt=-fresolution=%u.res \
822 %{!nostdlib:%{!nodefaultlibs:%:pass-through-libs(%(link_gcc_c_sequence))}} \
823 }" PLUGIN_COND_CLOSE
824 #else
825 /* The linker used doesn't support -plugin, reject -fuse-linker-plugin. */
826 #define LINK_PLUGIN_SPEC "%{fuse-linker-plugin:\
827 %e-fuse-linker-plugin is not supported in this configuration}"
828 #endif
830 /* Linker command line options for -fsanitize= early on the command line. */
831 #ifndef SANITIZER_EARLY_SPEC
832 #define SANITIZER_EARLY_SPEC "\
833 %{!nostdlib:%{!nodefaultlibs:%{%:sanitize(address):" LIBASAN_EARLY_SPEC "} \
834 %{%:sanitize(thread):" LIBTSAN_EARLY_SPEC "} \
835 %{%:sanitize(leak):" LIBLSAN_EARLY_SPEC "}}}"
836 #endif
838 /* Linker command line options for -fsanitize= late on the command line. */
839 #ifndef SANITIZER_SPEC
840 #define SANITIZER_SPEC "\
841 %{!nostdlib:%{!nodefaultlibs:%{%:sanitize(address):" LIBASAN_SPEC "\
842 %{static:%ecannot specify -static with -fsanitize=address}}\
843 %{%:sanitize(thread):" LIBTSAN_SPEC "\
844 %{static:%ecannot specify -static with -fsanitize=thread}}\
845 %{%:sanitize(undefined):" LIBUBSAN_SPEC "}\
846 %{%:sanitize(leak):" LIBLSAN_SPEC "}}}"
847 #endif
849 /* This is the spec to use, once the code for creating the vtable
850 verification runtime library, libvtv.so, has been created. Currently
851 the vtable verification runtime functions are in libstdc++, so we use
852 the spec just below this one. */
853 #ifndef VTABLE_VERIFICATION_SPEC
854 #define VTABLE_VERIFICATION_SPEC "\
855 %{!nostdlib:%{fvtable-verify=std: -lvtv -u_vtable_map_vars_start -u_vtable_map_vars_end}\
856 %{fvtable-verify=preinit: -lvtv -u_vtable_map_vars_start -u_vtable_map_vars_end}}"
857 #endif
859 #ifndef CHKP_SPEC
860 #define CHKP_SPEC ""
861 #endif
863 /* -u* was put back because both BSD and SysV seem to support it. */
864 /* %{static:} simply prevents an error message if the target machine
865 doesn't handle -static. */
866 /* We want %{T*} after %{L*} and %D so that it can be used to specify linker
867 scripts which exist in user specified directories, or in standard
868 directories. */
869 /* We pass any -flto flags on to the linker, which is expected
870 to understand them. In practice, this means it had better be collect2. */
871 /* %{e*} includes -export-dynamic; see comment in common.opt. */
872 #ifndef LINK_COMMAND_SPEC
873 #define LINK_COMMAND_SPEC "\
874 %{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
875 %(linker) " \
876 LINK_PLUGIN_SPEC \
877 "%{flto|flto=*:%<fcompare-debug*} \
878 %{flto} %{fno-lto} %{flto=*} %l " LINK_PIE_SPEC \
879 "%{fuse-ld=*:-fuse-ld=%*} " LINK_COMPRESS_DEBUG_SPEC \
880 "%X %{o*} %{e*} %{N} %{n} %{r}\
881 %{s} %{t} %{u*} %{z} %{Z} %{!nostdlib:%{!nostartfiles:%S}} " VTABLE_VERIFICATION_SPEC " \
882 %{static:} %{L*} %(mfwrap) %(link_libgcc) " SANITIZER_EARLY_SPEC " %o\
883 " CHKP_SPEC " \
884 %{fopenacc|fopenmp|ftree-parallelize-loops=*:%:include(libgomp.spec)%(link_gomp)}\
885 %{fcilkplus:%:include(libcilkrts.spec)%(link_cilkrts)}\
886 %{fgnu-tm:%:include(libitm.spec)%(link_itm)}\
887 %(mflib) " STACK_SPLIT_SPEC "\
888 %{fprofile-arcs|fprofile-generate*|coverage:-lgcov} " SANITIZER_SPEC " \
889 %{!nostdlib:%{!nodefaultlibs:%(link_ssp) %(link_gcc_c_sequence)}}\
890 %{!nostdlib:%{!nostartfiles:%E}} %{T*} }}}}}}"
891 #endif
893 #ifndef LINK_LIBGCC_SPEC
894 /* Generate -L options for startfile prefix list. */
895 # define LINK_LIBGCC_SPEC "%D"
896 #endif
898 #ifndef STARTFILE_PREFIX_SPEC
899 # define STARTFILE_PREFIX_SPEC ""
900 #endif
902 #ifndef SYSROOT_SPEC
903 # define SYSROOT_SPEC "--sysroot=%R"
904 #endif
906 #ifndef SYSROOT_SUFFIX_SPEC
907 # define SYSROOT_SUFFIX_SPEC ""
908 #endif
910 #ifndef SYSROOT_HEADERS_SUFFIX_SPEC
911 # define SYSROOT_HEADERS_SUFFIX_SPEC ""
912 #endif
914 static const char *asm_debug = ASM_DEBUG_SPEC;
915 static const char *cpp_spec = CPP_SPEC;
916 static const char *cc1_spec = CC1_SPEC;
917 static const char *cc1plus_spec = CC1PLUS_SPEC;
918 static const char *link_gcc_c_sequence_spec = LINK_GCC_C_SEQUENCE_SPEC;
919 static const char *link_ssp_spec = LINK_SSP_SPEC;
920 static const char *asm_spec = ASM_SPEC;
921 static const char *asm_final_spec = ASM_FINAL_SPEC;
922 static const char *link_spec = LINK_SPEC;
923 static const char *lib_spec = LIB_SPEC;
924 static const char *link_gomp_spec = "";
925 static const char *libgcc_spec = LIBGCC_SPEC;
926 static const char *endfile_spec = ENDFILE_SPEC;
927 static const char *startfile_spec = STARTFILE_SPEC;
928 static const char *linker_name_spec = LINKER_NAME;
929 static const char *linker_plugin_file_spec = "";
930 static const char *lto_wrapper_spec = "";
931 static const char *lto_gcc_spec = "";
932 static const char *link_command_spec = LINK_COMMAND_SPEC;
933 static const char *link_libgcc_spec = LINK_LIBGCC_SPEC;
934 static const char *startfile_prefix_spec = STARTFILE_PREFIX_SPEC;
935 static const char *sysroot_spec = SYSROOT_SPEC;
936 static const char *sysroot_suffix_spec = SYSROOT_SUFFIX_SPEC;
937 static const char *sysroot_hdrs_suffix_spec = SYSROOT_HEADERS_SUFFIX_SPEC;
938 static const char *self_spec = "";
940 /* Standard options to cpp, cc1, and as, to reduce duplication in specs.
941 There should be no need to override these in target dependent files,
942 but we need to copy them to the specs file so that newer versions
943 of the GCC driver can correctly drive older tool chains with the
944 appropriate -B options. */
946 /* When cpplib handles traditional preprocessing, get rid of this, and
947 call cc1 (or cc1obj in objc/lang-specs.h) from the main specs so
948 that we default the front end language better. */
949 static const char *trad_capable_cpp =
950 "cc1 -E %{traditional|traditional-cpp:-traditional-cpp}";
952 /* We don't wrap .d files in %W{} since a missing .d file, and
953 therefore no dependency entry, confuses make into thinking a .o
954 file that happens to exist is up-to-date. */
955 static const char *cpp_unique_options =
956 "%{!Q:-quiet} %{nostdinc*} %{C} %{CC} %{v} %{I*&F*} %{P} %I\
957 %{MD:-MD %{!o:%b.d}%{o*:%.d%*}}\
958 %{MMD:-MMD %{!o:%b.d}%{o*:%.d%*}}\
959 %{M} %{MM} %{MF*} %{MG} %{MP} %{MQ*} %{MT*}\
960 %{!E:%{!M:%{!MM:%{!MT:%{!MQ:%{MD|MMD:%{o*:-MQ %*}}}}}}}\
961 %{remap} %{g3|ggdb3|gstabs3|gcoff3|gxcoff3|gvms3:-dD}\
962 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
963 %{H} %C %{D*&U*&A*} %{i*} %Z %i\
964 %{E|M|MM:%W{o*}}";
966 /* This contains cpp options which are common with cc1_options and are passed
967 only when preprocessing only to avoid duplication. We pass the cc1 spec
968 options to the preprocessor so that it the cc1 spec may manipulate
969 options used to set target flags. Those special target flags settings may
970 in turn cause preprocessor symbols to be defined specially. */
971 static const char *cpp_options =
972 "%(cpp_unique_options) %1 %{m*} %{std*&ansi&trigraphs} %{W*&pedantic*} %{w}\
973 %{f*} %{g*:%{!g0:%{g*} %{!fno-working-directory:-fworking-directory}}} %{O*}\
974 %{undef} %{save-temps*:-fpch-preprocess}";
976 /* This contains cpp options which are not passed when the preprocessor
977 output will be used by another program. */
978 static const char *cpp_debug_options = "%{d*}";
980 /* NB: This is shared amongst all front-ends, except for Ada. */
981 static const char *cc1_options =
982 "%{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
983 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
984 %1 %{!Q:-quiet} %{!dumpbase:-dumpbase %B} %{d*} %{m*} %{aux-info*}\
985 %{fcompare-debug-second:%:compare-debug-auxbase-opt(%b)} \
986 %{!fcompare-debug-second:%{c|S:%{o*:-auxbase-strip %*}%{!o*:-auxbase %b}}}%{!c:%{!S:-auxbase %b}} \
987 %{g*} %{O*} %{W*&pedantic*} %{w} %{std*&ansi&trigraphs}\
988 %{v:-version} %{pg:-p} %{p} %{f*} %{undef}\
989 %{Qn:-fno-ident} %{Qy:} %{-help:--help}\
990 %{-target-help:--target-help}\
991 %{-version:--version}\
992 %{-help=*:--help=%*}\
993 %{!fsyntax-only:%{S:%W{o*}%{!o*:-o %b.s}}}\
994 %{fsyntax-only:-o %j} %{-param*}\
995 %{coverage:-fprofile-arcs -ftest-coverage}";
997 static const char *asm_options =
998 "%{-target-help:%:print-asm-header()} "
999 #if HAVE_GNU_AS
1000 /* If GNU AS is used, then convert -w (no warnings), -I, and -v
1001 to the assembler equivalents. */
1002 "%{v} %{w:-W} %{I*} "
1003 #endif
1004 ASM_COMPRESS_DEBUG_SPEC
1005 "%a %Y %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}";
1007 static const char *invoke_as =
1008 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
1009 "%{!fwpa*:\
1010 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
1011 %{!S:-o %|.s |\n as %(asm_options) %|.s %A }\
1013 #else
1014 "%{!fwpa*:\
1015 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
1016 %{!S:-o %|.s |\n as %(asm_options) %m.s %A }\
1018 #endif
1020 /* Some compilers have limits on line lengths, and the multilib_select
1021 and/or multilib_matches strings can be very long, so we build them at
1022 run time. */
1023 static struct obstack multilib_obstack;
1024 static const char *multilib_select;
1025 static const char *multilib_matches;
1026 static const char *multilib_defaults;
1027 static const char *multilib_exclusions;
1028 static const char *multilib_reuse;
1030 /* Check whether a particular argument is a default argument. */
1032 #ifndef MULTILIB_DEFAULTS
1033 #define MULTILIB_DEFAULTS { "" }
1034 #endif
1036 static const char *const multilib_defaults_raw[] = MULTILIB_DEFAULTS;
1038 #ifndef DRIVER_SELF_SPECS
1039 #define DRIVER_SELF_SPECS ""
1040 #endif
1042 /* Linking to libgomp implies pthreads. This is particularly important
1043 for targets that use different start files and suchlike. */
1044 #ifndef GOMP_SELF_SPECS
1045 #define GOMP_SELF_SPECS "%{fopenacc|fopenmp|ftree-parallelize-loops=*: " \
1046 "-pthread}"
1047 #endif
1049 /* Likewise for -fgnu-tm. */
1050 #ifndef GTM_SELF_SPECS
1051 #define GTM_SELF_SPECS "%{fgnu-tm: -pthread}"
1052 #endif
1054 /* Likewise for -fcilkplus. */
1055 #ifndef CILK_SELF_SPECS
1056 #define CILK_SELF_SPECS "%{fcilkplus: -pthread}"
1057 #endif
1059 static const char *const driver_self_specs[] = {
1060 "%{fdump-final-insns:-fdump-final-insns=.} %<fdump-final-insns",
1061 DRIVER_SELF_SPECS, CONFIGURE_SPECS, GOMP_SELF_SPECS, GTM_SELF_SPECS,
1062 CILK_SELF_SPECS
1065 #ifndef OPTION_DEFAULT_SPECS
1066 #define OPTION_DEFAULT_SPECS { "", "" }
1067 #endif
1069 struct default_spec
1071 const char *name;
1072 const char *spec;
1075 static const struct default_spec
1076 option_default_specs[] = { OPTION_DEFAULT_SPECS };
1078 struct user_specs
1080 struct user_specs *next;
1081 const char *filename;
1084 static struct user_specs *user_specs_head, *user_specs_tail;
1087 /* Record the mapping from file suffixes for compilation specs. */
1089 struct compiler
1091 const char *suffix; /* Use this compiler for input files
1092 whose names end in this suffix. */
1094 const char *spec; /* To use this compiler, run this spec. */
1096 const char *cpp_spec; /* If non-NULL, substitute this spec
1097 for `%C', rather than the usual
1098 cpp_spec. */
1099 const int combinable; /* If nonzero, compiler can deal with
1100 multiple source files at once (IMA). */
1101 const int needs_preprocessing; /* If nonzero, source files need to
1102 be run through a preprocessor. */
1105 /* Pointer to a vector of `struct compiler' that gives the spec for
1106 compiling a file, based on its suffix.
1107 A file that does not end in any of these suffixes will be passed
1108 unchanged to the loader and nothing else will be done to it.
1110 An entry containing two 0s is used to terminate the vector.
1112 If multiple entries match a file, the last matching one is used. */
1114 static struct compiler *compilers;
1116 /* Number of entries in `compilers', not counting the null terminator. */
1118 static int n_compilers;
1120 /* The default list of file name suffixes and their compilation specs. */
1122 static const struct compiler default_compilers[] =
1124 /* Add lists of suffixes of known languages here. If those languages
1125 were not present when we built the driver, we will hit these copies
1126 and be given a more meaningful error than "file not used since
1127 linking is not done". */
1128 {".m", "#Objective-C", 0, 0, 0}, {".mi", "#Objective-C", 0, 0, 0},
1129 {".mm", "#Objective-C++", 0, 0, 0}, {".M", "#Objective-C++", 0, 0, 0},
1130 {".mii", "#Objective-C++", 0, 0, 0},
1131 {".cc", "#C++", 0, 0, 0}, {".cxx", "#C++", 0, 0, 0},
1132 {".cpp", "#C++", 0, 0, 0}, {".cp", "#C++", 0, 0, 0},
1133 {".c++", "#C++", 0, 0, 0}, {".C", "#C++", 0, 0, 0},
1134 {".CPP", "#C++", 0, 0, 0}, {".ii", "#C++", 0, 0, 0},
1135 {".ads", "#Ada", 0, 0, 0}, {".adb", "#Ada", 0, 0, 0},
1136 {".f", "#Fortran", 0, 0, 0}, {".F", "#Fortran", 0, 0, 0},
1137 {".for", "#Fortran", 0, 0, 0}, {".FOR", "#Fortran", 0, 0, 0},
1138 {".ftn", "#Fortran", 0, 0, 0}, {".FTN", "#Fortran", 0, 0, 0},
1139 {".fpp", "#Fortran", 0, 0, 0}, {".FPP", "#Fortran", 0, 0, 0},
1140 {".f90", "#Fortran", 0, 0, 0}, {".F90", "#Fortran", 0, 0, 0},
1141 {".f95", "#Fortran", 0, 0, 0}, {".F95", "#Fortran", 0, 0, 0},
1142 {".f03", "#Fortran", 0, 0, 0}, {".F03", "#Fortran", 0, 0, 0},
1143 {".f08", "#Fortran", 0, 0, 0}, {".F08", "#Fortran", 0, 0, 0},
1144 {".r", "#Ratfor", 0, 0, 0},
1145 {".p", "#Pascal", 0, 0, 0}, {".pas", "#Pascal", 0, 0, 0},
1146 {".java", "#Java", 0, 0, 0}, {".class", "#Java", 0, 0, 0},
1147 {".zip", "#Java", 0, 0, 0}, {".jar", "#Java", 0, 0, 0},
1148 {".go", "#Go", 0, 1, 0},
1149 /* Next come the entries for C. */
1150 {".c", "@c", 0, 0, 1},
1151 {"@c",
1152 /* cc1 has an integrated ISO C preprocessor. We should invoke the
1153 external preprocessor if -save-temps is given. */
1154 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
1155 %{!E:%{!M:%{!MM:\
1156 %{traditional:\
1157 %eGNU C no longer supports -traditional without -E}\
1158 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
1159 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
1160 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
1161 %(cc1_options)}\
1162 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
1163 cc1 %(cpp_unique_options) %(cc1_options)}}}\
1164 %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 1},
1165 {"-",
1166 "%{!E:%e-E or -x required when input is from standard input}\
1167 %(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)", 0, 0, 0},
1168 {".h", "@c-header", 0, 0, 0},
1169 {"@c-header",
1170 /* cc1 has an integrated ISO C preprocessor. We should invoke the
1171 external preprocessor if -save-temps is given. */
1172 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
1173 %{!E:%{!M:%{!MM:\
1174 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
1175 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
1176 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
1177 %(cc1_options)\
1178 %{!fdump-ada-spec*:-o %g.s %{!o*:--output-pch=%i.gch}\
1179 %W{o*:--output-pch=%*}}%V}\
1180 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
1181 cc1 %(cpp_unique_options) %(cc1_options)\
1182 %{!fdump-ada-spec*:-o %g.s %{!o*:--output-pch=%i.gch}\
1183 %W{o*:--output-pch=%*}}%V}}}}}}", 0, 0, 0},
1184 {".i", "@cpp-output", 0, 0, 0},
1185 {"@cpp-output",
1186 "%{!M:%{!MM:%{!E:cc1 -fpreprocessed %i %(cc1_options) %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 0},
1187 {".s", "@assembler", 0, 0, 0},
1188 {"@assembler",
1189 "%{!M:%{!MM:%{!E:%{!S:as %(asm_debug) %(asm_options) %i %A }}}}", 0, 0, 0},
1190 {".sx", "@assembler-with-cpp", 0, 0, 0},
1191 {".S", "@assembler-with-cpp", 0, 0, 0},
1192 {"@assembler-with-cpp",
1193 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
1194 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
1195 %{E|M|MM:%(cpp_debug_options)}\
1196 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
1197 as %(asm_debug) %(asm_options) %|.s %A }}}}"
1198 #else
1199 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
1200 %{E|M|MM:%(cpp_debug_options)}\
1201 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
1202 as %(asm_debug) %(asm_options) %m.s %A }}}}"
1203 #endif
1204 , 0, 0, 0},
1206 #include "specs.h"
1207 /* Mark end of table. */
1208 {0, 0, 0, 0, 0}
1211 /* Number of elements in default_compilers, not counting the terminator. */
1213 static const int n_default_compilers = ARRAY_SIZE (default_compilers) - 1;
1215 typedef char *char_p; /* For DEF_VEC_P. */
1217 /* A vector of options to give to the linker.
1218 These options are accumulated by %x,
1219 and substituted into the linker command with %X. */
1220 static vec<char_p> linker_options;
1222 /* A vector of options to give to the assembler.
1223 These options are accumulated by -Wa,
1224 and substituted into the assembler command with %Y. */
1225 static vec<char_p> assembler_options;
1227 /* A vector of options to give to the preprocessor.
1228 These options are accumulated by -Wp,
1229 and substituted into the preprocessor command with %Z. */
1230 static vec<char_p> preprocessor_options;
1232 static char *
1233 skip_whitespace (char *p)
1235 while (1)
1237 /* A fully-blank line is a delimiter in the SPEC file and shouldn't
1238 be considered whitespace. */
1239 if (p[0] == '\n' && p[1] == '\n' && p[2] == '\n')
1240 return p + 1;
1241 else if (*p == '\n' || *p == ' ' || *p == '\t')
1242 p++;
1243 else if (*p == '#')
1245 while (*p != '\n')
1246 p++;
1247 p++;
1249 else
1250 break;
1253 return p;
1255 /* Structures to keep track of prefixes to try when looking for files. */
1257 struct prefix_list
1259 const char *prefix; /* String to prepend to the path. */
1260 struct prefix_list *next; /* Next in linked list. */
1261 int require_machine_suffix; /* Don't use without machine_suffix. */
1262 /* 2 means try both machine_suffix and just_machine_suffix. */
1263 int priority; /* Sort key - priority within list. */
1264 int os_multilib; /* 1 if OS multilib scheme should be used,
1265 0 for GCC multilib scheme. */
1268 struct path_prefix
1270 struct prefix_list *plist; /* List of prefixes to try */
1271 int max_len; /* Max length of a prefix in PLIST */
1272 const char *name; /* Name of this list (used in config stuff) */
1275 /* List of prefixes to try when looking for executables. */
1277 static struct path_prefix exec_prefixes = { 0, 0, "exec" };
1279 /* List of prefixes to try when looking for startup (crt0) files. */
1281 static struct path_prefix startfile_prefixes = { 0, 0, "startfile" };
1283 /* List of prefixes to try when looking for include files. */
1285 static struct path_prefix include_prefixes = { 0, 0, "include" };
1287 /* Suffix to attach to directories searched for commands.
1288 This looks like `MACHINE/VERSION/'. */
1290 static const char *machine_suffix = 0;
1292 /* Suffix to attach to directories searched for commands.
1293 This is just `MACHINE/'. */
1295 static const char *just_machine_suffix = 0;
1297 /* Adjusted value of GCC_EXEC_PREFIX envvar. */
1299 static const char *gcc_exec_prefix;
1301 /* Adjusted value of standard_libexec_prefix. */
1303 static const char *gcc_libexec_prefix;
1305 /* Default prefixes to attach to command names. */
1307 #ifndef STANDARD_STARTFILE_PREFIX_1
1308 #define STANDARD_STARTFILE_PREFIX_1 "/lib/"
1309 #endif
1310 #ifndef STANDARD_STARTFILE_PREFIX_2
1311 #define STANDARD_STARTFILE_PREFIX_2 "/usr/lib/"
1312 #endif
1314 #ifdef CROSS_DIRECTORY_STRUCTURE /* Don't use these prefixes for a cross compiler. */
1315 #undef MD_EXEC_PREFIX
1316 #undef MD_STARTFILE_PREFIX
1317 #undef MD_STARTFILE_PREFIX_1
1318 #endif
1320 /* If no prefixes defined, use the null string, which will disable them. */
1321 #ifndef MD_EXEC_PREFIX
1322 #define MD_EXEC_PREFIX ""
1323 #endif
1324 #ifndef MD_STARTFILE_PREFIX
1325 #define MD_STARTFILE_PREFIX ""
1326 #endif
1327 #ifndef MD_STARTFILE_PREFIX_1
1328 #define MD_STARTFILE_PREFIX_1 ""
1329 #endif
1331 /* These directories are locations set at configure-time based on the
1332 --prefix option provided to configure. Their initializers are
1333 defined in Makefile.in. These paths are not *directly* used when
1334 gcc_exec_prefix is set because, in that case, we know where the
1335 compiler has been installed, and use paths relative to that
1336 location instead. */
1337 static const char *const standard_exec_prefix = STANDARD_EXEC_PREFIX;
1338 static const char *const standard_libexec_prefix = STANDARD_LIBEXEC_PREFIX;
1339 static const char *const standard_bindir_prefix = STANDARD_BINDIR_PREFIX;
1340 static const char *const standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
1342 /* For native compilers, these are well-known paths containing
1343 components that may be provided by the system. For cross
1344 compilers, these paths are not used. */
1345 static const char *md_exec_prefix = MD_EXEC_PREFIX;
1346 static const char *md_startfile_prefix = MD_STARTFILE_PREFIX;
1347 static const char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
1348 static const char *const standard_startfile_prefix_1
1349 = STANDARD_STARTFILE_PREFIX_1;
1350 static const char *const standard_startfile_prefix_2
1351 = STANDARD_STARTFILE_PREFIX_2;
1353 /* A relative path to be used in finding the location of tools
1354 relative to the driver. */
1355 static const char *const tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
1357 /* A prefix to be used when this is an accelerator compiler. */
1358 static const char *const accel_dir_suffix = ACCEL_DIR_SUFFIX;
1360 /* Subdirectory to use for locating libraries. Set by
1361 set_multilib_dir based on the compilation options. */
1363 static const char *multilib_dir;
1365 /* Subdirectory to use for locating libraries in OS conventions. Set by
1366 set_multilib_dir based on the compilation options. */
1368 static const char *multilib_os_dir;
1370 /* Subdirectory to use for locating libraries in multiarch conventions. Set by
1371 set_multilib_dir based on the compilation options. */
1373 static const char *multiarch_dir;
1375 /* Structure to keep track of the specs that have been defined so far.
1376 These are accessed using %(specname) in a compiler or link
1377 spec. */
1379 struct spec_list
1381 /* The following 2 fields must be first */
1382 /* to allow EXTRA_SPECS to be initialized */
1383 const char *name; /* name of the spec. */
1384 const char *ptr; /* available ptr if no static pointer */
1386 /* The following fields are not initialized */
1387 /* by EXTRA_SPECS */
1388 const char **ptr_spec; /* pointer to the spec itself. */
1389 struct spec_list *next; /* Next spec in linked list. */
1390 int name_len; /* length of the name */
1391 bool user_p; /* whether string come from file spec. */
1392 bool alloc_p; /* whether string was allocated */
1395 #define INIT_STATIC_SPEC(NAME,PTR) \
1396 { NAME, NULL, PTR, (struct spec_list *) 0, sizeof (NAME) - 1, false, false }
1398 /* List of statically defined specs. */
1399 static struct spec_list static_specs[] =
1401 INIT_STATIC_SPEC ("asm", &asm_spec),
1402 INIT_STATIC_SPEC ("asm_debug", &asm_debug),
1403 INIT_STATIC_SPEC ("asm_final", &asm_final_spec),
1404 INIT_STATIC_SPEC ("asm_options", &asm_options),
1405 INIT_STATIC_SPEC ("invoke_as", &invoke_as),
1406 INIT_STATIC_SPEC ("cpp", &cpp_spec),
1407 INIT_STATIC_SPEC ("cpp_options", &cpp_options),
1408 INIT_STATIC_SPEC ("cpp_debug_options", &cpp_debug_options),
1409 INIT_STATIC_SPEC ("cpp_unique_options", &cpp_unique_options),
1410 INIT_STATIC_SPEC ("trad_capable_cpp", &trad_capable_cpp),
1411 INIT_STATIC_SPEC ("cc1", &cc1_spec),
1412 INIT_STATIC_SPEC ("cc1_options", &cc1_options),
1413 INIT_STATIC_SPEC ("cc1plus", &cc1plus_spec),
1414 INIT_STATIC_SPEC ("link_gcc_c_sequence", &link_gcc_c_sequence_spec),
1415 INIT_STATIC_SPEC ("link_ssp", &link_ssp_spec),
1416 INIT_STATIC_SPEC ("endfile", &endfile_spec),
1417 INIT_STATIC_SPEC ("link", &link_spec),
1418 INIT_STATIC_SPEC ("lib", &lib_spec),
1419 INIT_STATIC_SPEC ("link_gomp", &link_gomp_spec),
1420 INIT_STATIC_SPEC ("libgcc", &libgcc_spec),
1421 INIT_STATIC_SPEC ("startfile", &startfile_spec),
1422 INIT_STATIC_SPEC ("cross_compile", &cross_compile),
1423 INIT_STATIC_SPEC ("version", &compiler_version),
1424 INIT_STATIC_SPEC ("multilib", &multilib_select),
1425 INIT_STATIC_SPEC ("multilib_defaults", &multilib_defaults),
1426 INIT_STATIC_SPEC ("multilib_extra", &multilib_extra),
1427 INIT_STATIC_SPEC ("multilib_matches", &multilib_matches),
1428 INIT_STATIC_SPEC ("multilib_exclusions", &multilib_exclusions),
1429 INIT_STATIC_SPEC ("multilib_options", &multilib_options),
1430 INIT_STATIC_SPEC ("multilib_reuse", &multilib_reuse),
1431 INIT_STATIC_SPEC ("linker", &linker_name_spec),
1432 INIT_STATIC_SPEC ("linker_plugin_file", &linker_plugin_file_spec),
1433 INIT_STATIC_SPEC ("lto_wrapper", &lto_wrapper_spec),
1434 INIT_STATIC_SPEC ("lto_gcc", &lto_gcc_spec),
1435 INIT_STATIC_SPEC ("link_libgcc", &link_libgcc_spec),
1436 INIT_STATIC_SPEC ("md_exec_prefix", &md_exec_prefix),
1437 INIT_STATIC_SPEC ("md_startfile_prefix", &md_startfile_prefix),
1438 INIT_STATIC_SPEC ("md_startfile_prefix_1", &md_startfile_prefix_1),
1439 INIT_STATIC_SPEC ("startfile_prefix_spec", &startfile_prefix_spec),
1440 INIT_STATIC_SPEC ("sysroot_spec", &sysroot_spec),
1441 INIT_STATIC_SPEC ("sysroot_suffix_spec", &sysroot_suffix_spec),
1442 INIT_STATIC_SPEC ("sysroot_hdrs_suffix_spec", &sysroot_hdrs_suffix_spec),
1443 INIT_STATIC_SPEC ("self_spec", &self_spec),
1446 #ifdef EXTRA_SPECS /* additional specs needed */
1447 /* Structure to keep track of just the first two args of a spec_list.
1448 That is all that the EXTRA_SPECS macro gives us. */
1449 struct spec_list_1
1451 const char *const name;
1452 const char *const ptr;
1455 static const struct spec_list_1 extra_specs_1[] = { EXTRA_SPECS };
1456 static struct spec_list *extra_specs = (struct spec_list *) 0;
1457 #endif
1459 /* List of dynamically allocates specs that have been defined so far. */
1461 static struct spec_list *specs = (struct spec_list *) 0;
1463 /* List of static spec functions. */
1465 static const struct spec_function static_spec_functions[] =
1467 { "getenv", getenv_spec_function },
1468 { "if-exists", if_exists_spec_function },
1469 { "if-exists-else", if_exists_else_spec_function },
1470 { "sanitize", sanitize_spec_function },
1471 { "replace-outfile", replace_outfile_spec_function },
1472 { "remove-outfile", remove_outfile_spec_function },
1473 { "version-compare", version_compare_spec_function },
1474 { "include", include_spec_function },
1475 { "find-file", find_file_spec_function },
1476 { "find-plugindir", find_plugindir_spec_function },
1477 { "print-asm-header", print_asm_header_spec_function },
1478 { "compare-debug-dump-opt", compare_debug_dump_opt_spec_function },
1479 { "compare-debug-self-opt", compare_debug_self_opt_spec_function },
1480 { "compare-debug-auxbase-opt", compare_debug_auxbase_opt_spec_function },
1481 { "pass-through-libs", pass_through_libs_spec_func },
1482 { "replace-extension", replace_extension_spec_func },
1483 #ifdef EXTRA_SPEC_FUNCTIONS
1484 EXTRA_SPEC_FUNCTIONS
1485 #endif
1486 { 0, 0 }
1489 static int processing_spec_function;
1491 /* Add appropriate libgcc specs to OBSTACK, taking into account
1492 various permutations of -shared-libgcc, -shared, and such. */
1494 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1496 #ifndef USE_LD_AS_NEEDED
1497 #define USE_LD_AS_NEEDED 0
1498 #endif
1500 static void
1501 init_gcc_specs (struct obstack *obstack, const char *shared_name,
1502 const char *static_name, const char *eh_name)
1504 char *buf;
1506 buf = concat ("%{static|static-libgcc:", static_name, " ", eh_name, "}"
1507 "%{!static:%{!static-libgcc:"
1508 #if USE_LD_AS_NEEDED
1509 "%{!shared-libgcc:",
1510 static_name, " " LD_AS_NEEDED_OPTION " ",
1511 shared_name, " " LD_NO_AS_NEEDED_OPTION
1513 "%{shared-libgcc:",
1514 shared_name, "%{!shared: ", static_name, "}"
1516 #else
1517 "%{!shared:"
1518 "%{!shared-libgcc:", static_name, " ", eh_name, "}"
1519 "%{shared-libgcc:", shared_name, " ", static_name, "}"
1521 #ifdef LINK_EH_SPEC
1522 "%{shared:"
1523 "%{shared-libgcc:", shared_name, "}"
1524 "%{!shared-libgcc:", static_name, "}"
1526 #else
1527 "%{shared:", shared_name, "}"
1528 #endif
1529 #endif
1530 "}}", NULL);
1532 obstack_grow (obstack, buf, strlen (buf));
1533 free (buf);
1535 #endif /* ENABLE_SHARED_LIBGCC */
1537 /* Initialize the specs lookup routines. */
1539 static void
1540 init_spec (void)
1542 struct spec_list *next = (struct spec_list *) 0;
1543 struct spec_list *sl = (struct spec_list *) 0;
1544 int i;
1546 if (specs)
1547 return; /* Already initialized. */
1549 if (verbose_flag)
1550 fnotice (stderr, "Using built-in specs.\n");
1552 #ifdef EXTRA_SPECS
1553 extra_specs = XCNEWVEC (struct spec_list, ARRAY_SIZE (extra_specs_1));
1555 for (i = ARRAY_SIZE (extra_specs_1) - 1; i >= 0; i--)
1557 sl = &extra_specs[i];
1558 sl->name = extra_specs_1[i].name;
1559 sl->ptr = extra_specs_1[i].ptr;
1560 sl->next = next;
1561 sl->name_len = strlen (sl->name);
1562 sl->ptr_spec = &sl->ptr;
1563 next = sl;
1565 #endif
1567 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1569 sl = &static_specs[i];
1570 sl->next = next;
1571 next = sl;
1574 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1575 /* ??? If neither -shared-libgcc nor --static-libgcc was
1576 seen, then we should be making an educated guess. Some proposed
1577 heuristics for ELF include:
1579 (1) If "-Wl,--export-dynamic", then it's a fair bet that the
1580 program will be doing dynamic loading, which will likely
1581 need the shared libgcc.
1583 (2) If "-ldl", then it's also a fair bet that we're doing
1584 dynamic loading.
1586 (3) For each ET_DYN we're linking against (either through -lfoo
1587 or /some/path/foo.so), check to see whether it or one of
1588 its dependencies depends on a shared libgcc.
1590 (4) If "-shared"
1592 If the runtime is fixed to look for program headers instead
1593 of calling __register_frame_info at all, for each object,
1594 use the shared libgcc if any EH symbol referenced.
1596 If crtstuff is fixed to not invoke __register_frame_info
1597 automatically, for each object, use the shared libgcc if
1598 any non-empty unwind section found.
1600 Doing any of this probably requires invoking an external program to
1601 do the actual object file scanning. */
1603 const char *p = libgcc_spec;
1604 int in_sep = 1;
1606 /* Transform the extant libgcc_spec into one that uses the shared libgcc
1607 when given the proper command line arguments. */
1608 while (*p)
1610 if (in_sep && *p == '-' && strncmp (p, "-lgcc", 5) == 0)
1612 init_gcc_specs (&obstack,
1613 "-lgcc_s"
1614 #ifdef USE_LIBUNWIND_EXCEPTIONS
1615 " -lunwind"
1616 #endif
1618 "-lgcc",
1619 "-lgcc_eh"
1620 #ifdef USE_LIBUNWIND_EXCEPTIONS
1621 # ifdef HAVE_LD_STATIC_DYNAMIC
1622 " %{!static:" LD_STATIC_OPTION "} -lunwind"
1623 " %{!static:" LD_DYNAMIC_OPTION "}"
1624 # else
1625 " -lunwind"
1626 # endif
1627 #endif
1630 p += 5;
1631 in_sep = 0;
1633 else if (in_sep && *p == 'l' && strncmp (p, "libgcc.a%s", 10) == 0)
1635 /* Ug. We don't know shared library extensions. Hope that
1636 systems that use this form don't do shared libraries. */
1637 init_gcc_specs (&obstack,
1638 "-lgcc_s",
1639 "libgcc.a%s",
1640 "libgcc_eh.a%s"
1641 #ifdef USE_LIBUNWIND_EXCEPTIONS
1642 " -lunwind"
1643 #endif
1645 p += 10;
1646 in_sep = 0;
1648 else
1650 obstack_1grow (&obstack, *p);
1651 in_sep = (*p == ' ');
1652 p += 1;
1656 obstack_1grow (&obstack, '\0');
1657 libgcc_spec = XOBFINISH (&obstack, const char *);
1659 #endif
1660 #ifdef USE_AS_TRADITIONAL_FORMAT
1661 /* Prepend "--traditional-format" to whatever asm_spec we had before. */
1663 static const char tf[] = "--traditional-format ";
1664 obstack_grow (&obstack, tf, sizeof (tf) - 1);
1665 obstack_grow0 (&obstack, asm_spec, strlen (asm_spec));
1666 asm_spec = XOBFINISH (&obstack, const char *);
1668 #endif
1670 #if defined LINK_EH_SPEC || defined LINK_BUILDID_SPEC || \
1671 defined LINKER_HASH_STYLE
1672 # ifdef LINK_BUILDID_SPEC
1673 /* Prepend LINK_BUILDID_SPEC to whatever link_spec we had before. */
1674 obstack_grow (&obstack, LINK_BUILDID_SPEC, sizeof (LINK_BUILDID_SPEC) - 1);
1675 # endif
1676 # ifdef LINK_EH_SPEC
1677 /* Prepend LINK_EH_SPEC to whatever link_spec we had before. */
1678 obstack_grow (&obstack, LINK_EH_SPEC, sizeof (LINK_EH_SPEC) - 1);
1679 # endif
1680 # ifdef LINKER_HASH_STYLE
1681 /* Prepend --hash-style=LINKER_HASH_STYLE to whatever link_spec we had
1682 before. */
1684 static const char hash_style[] = "--hash-style=";
1685 obstack_grow (&obstack, hash_style, sizeof (hash_style) - 1);
1686 obstack_grow (&obstack, LINKER_HASH_STYLE, sizeof (LINKER_HASH_STYLE) - 1);
1687 obstack_1grow (&obstack, ' ');
1689 # endif
1690 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
1691 link_spec = XOBFINISH (&obstack, const char *);
1692 #endif
1694 specs = sl;
1697 /* Change the value of spec NAME to SPEC. If SPEC is empty, then the spec is
1698 removed; If the spec starts with a + then SPEC is added to the end of the
1699 current spec. */
1701 static void
1702 set_spec (const char *name, const char *spec, bool user_p)
1704 struct spec_list *sl;
1705 const char *old_spec;
1706 int name_len = strlen (name);
1707 int i;
1709 /* If this is the first call, initialize the statically allocated specs. */
1710 if (!specs)
1712 struct spec_list *next = (struct spec_list *) 0;
1713 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1715 sl = &static_specs[i];
1716 sl->next = next;
1717 next = sl;
1719 specs = sl;
1722 /* See if the spec already exists. */
1723 for (sl = specs; sl; sl = sl->next)
1724 if (name_len == sl->name_len && !strcmp (sl->name, name))
1725 break;
1727 if (!sl)
1729 /* Not found - make it. */
1730 sl = XNEW (struct spec_list);
1731 sl->name = xstrdup (name);
1732 sl->name_len = name_len;
1733 sl->ptr_spec = &sl->ptr;
1734 sl->alloc_p = 0;
1735 *(sl->ptr_spec) = "";
1736 sl->next = specs;
1737 specs = sl;
1740 old_spec = *(sl->ptr_spec);
1741 *(sl->ptr_spec) = ((spec[0] == '+' && ISSPACE ((unsigned char)spec[1]))
1742 ? concat (old_spec, spec + 1, NULL)
1743 : xstrdup (spec));
1745 #ifdef DEBUG_SPECS
1746 if (verbose_flag)
1747 fnotice (stderr, "Setting spec %s to '%s'\n\n", name, *(sl->ptr_spec));
1748 #endif
1750 /* Free the old spec. */
1751 if (old_spec && sl->alloc_p)
1752 free (CONST_CAST (char *, old_spec));
1754 sl->user_p = user_p;
1755 sl->alloc_p = true;
1758 /* Accumulate a command (program name and args), and run it. */
1760 typedef const char *const_char_p; /* For DEF_VEC_P. */
1762 /* Vector of pointers to arguments in the current line of specifications. */
1764 static vec<const_char_p> argbuf;
1766 /* Were the options -c, -S or -E passed. */
1767 static int have_c = 0;
1769 /* Was the option -o passed. */
1770 static int have_o = 0;
1772 /* Pointer to output file name passed in with -o. */
1773 static const char *output_file = 0;
1775 /* This is the list of suffixes and codes (%g/%u/%U/%j) and the associated
1776 temp file. If the HOST_BIT_BUCKET is used for %j, no entry is made for
1777 it here. */
1779 static struct temp_name {
1780 const char *suffix; /* suffix associated with the code. */
1781 int length; /* strlen (suffix). */
1782 int unique; /* Indicates whether %g or %u/%U was used. */
1783 const char *filename; /* associated filename. */
1784 int filename_length; /* strlen (filename). */
1785 struct temp_name *next;
1786 } *temp_names;
1788 /* Number of commands executed so far. */
1790 static int execution_count;
1792 /* Number of commands that exited with a signal. */
1794 static int signal_count;
1796 /* Allocate the argument vector. */
1798 static void
1799 alloc_args (void)
1801 argbuf.create (10);
1804 /* Clear out the vector of arguments (after a command is executed). */
1806 static void
1807 clear_args (void)
1809 argbuf.truncate (0);
1812 /* Add one argument to the vector at the end.
1813 This is done when a space is seen or at the end of the line.
1814 If DELETE_ALWAYS is nonzero, the arg is a filename
1815 and the file should be deleted eventually.
1816 If DELETE_FAILURE is nonzero, the arg is a filename
1817 and the file should be deleted if this compilation fails. */
1819 static void
1820 store_arg (const char *arg, int delete_always, int delete_failure)
1822 argbuf.safe_push (arg);
1824 if (delete_always || delete_failure)
1826 const char *p;
1827 /* If the temporary file we should delete is specified as
1828 part of a joined argument extract the filename. */
1829 if (arg[0] == '-'
1830 && (p = strrchr (arg, '=')))
1831 arg = p + 1;
1832 record_temp_file (arg, delete_always, delete_failure);
1836 /* Load specs from a file name named FILENAME, replacing occurrences of
1837 various different types of line-endings, \r\n, \n\r and just \r, with
1838 a single \n. */
1840 static char *
1841 load_specs (const char *filename)
1843 int desc;
1844 int readlen;
1845 struct stat statbuf;
1846 char *buffer;
1847 char *buffer_p;
1848 char *specs;
1849 char *specs_p;
1851 if (verbose_flag)
1852 fnotice (stderr, "Reading specs from %s\n", filename);
1854 /* Open and stat the file. */
1855 desc = open (filename, O_RDONLY, 0);
1856 if (desc < 0)
1857 pfatal_with_name (filename);
1858 if (stat (filename, &statbuf) < 0)
1859 pfatal_with_name (filename);
1861 /* Read contents of file into BUFFER. */
1862 buffer = XNEWVEC (char, statbuf.st_size + 1);
1863 readlen = read (desc, buffer, (unsigned) statbuf.st_size);
1864 if (readlen < 0)
1865 pfatal_with_name (filename);
1866 buffer[readlen] = 0;
1867 close (desc);
1869 specs = XNEWVEC (char, readlen + 1);
1870 specs_p = specs;
1871 for (buffer_p = buffer; buffer_p && *buffer_p; buffer_p++)
1873 int skip = 0;
1874 char c = *buffer_p;
1875 if (c == '\r')
1877 if (buffer_p > buffer && *(buffer_p - 1) == '\n') /* \n\r */
1878 skip = 1;
1879 else if (*(buffer_p + 1) == '\n') /* \r\n */
1880 skip = 1;
1881 else /* \r */
1882 c = '\n';
1884 if (! skip)
1885 *specs_p++ = c;
1887 *specs_p = '\0';
1889 free (buffer);
1890 return (specs);
1893 /* Read compilation specs from a file named FILENAME,
1894 replacing the default ones.
1896 A suffix which starts with `*' is a definition for
1897 one of the machine-specific sub-specs. The "suffix" should be
1898 *asm, *cc1, *cpp, *link, *startfile, etc.
1899 The corresponding spec is stored in asm_spec, etc.,
1900 rather than in the `compilers' vector.
1902 Anything invalid in the file is a fatal error. */
1904 static void
1905 read_specs (const char *filename, bool main_p, bool user_p)
1907 char *buffer;
1908 char *p;
1910 buffer = load_specs (filename);
1912 /* Scan BUFFER for specs, putting them in the vector. */
1913 p = buffer;
1914 while (1)
1916 char *suffix;
1917 char *spec;
1918 char *in, *out, *p1, *p2, *p3;
1920 /* Advance P in BUFFER to the next nonblank nocomment line. */
1921 p = skip_whitespace (p);
1922 if (*p == 0)
1923 break;
1925 /* Is this a special command that starts with '%'? */
1926 /* Don't allow this for the main specs file, since it would
1927 encourage people to overwrite it. */
1928 if (*p == '%' && !main_p)
1930 p1 = p;
1931 while (*p && *p != '\n')
1932 p++;
1934 /* Skip '\n'. */
1935 p++;
1937 if (!strncmp (p1, "%include", sizeof ("%include") - 1)
1938 && (p1[sizeof "%include" - 1] == ' '
1939 || p1[sizeof "%include" - 1] == '\t'))
1941 char *new_filename;
1943 p1 += sizeof ("%include");
1944 while (*p1 == ' ' || *p1 == '\t')
1945 p1++;
1947 if (*p1++ != '<' || p[-2] != '>')
1948 fatal_error (input_location,
1949 "specs %%include syntax malformed after "
1950 "%ld characters",
1951 (long) (p1 - buffer + 1));
1953 p[-2] = '\0';
1954 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
1955 read_specs (new_filename ? new_filename : p1, false, user_p);
1956 continue;
1958 else if (!strncmp (p1, "%include_noerr", sizeof "%include_noerr" - 1)
1959 && (p1[sizeof "%include_noerr" - 1] == ' '
1960 || p1[sizeof "%include_noerr" - 1] == '\t'))
1962 char *new_filename;
1964 p1 += sizeof "%include_noerr";
1965 while (*p1 == ' ' || *p1 == '\t')
1966 p1++;
1968 if (*p1++ != '<' || p[-2] != '>')
1969 fatal_error (input_location,
1970 "specs %%include syntax malformed after "
1971 "%ld characters",
1972 (long) (p1 - buffer + 1));
1974 p[-2] = '\0';
1975 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
1976 if (new_filename)
1977 read_specs (new_filename, false, user_p);
1978 else if (verbose_flag)
1979 fnotice (stderr, "could not find specs file %s\n", p1);
1980 continue;
1982 else if (!strncmp (p1, "%rename", sizeof "%rename" - 1)
1983 && (p1[sizeof "%rename" - 1] == ' '
1984 || p1[sizeof "%rename" - 1] == '\t'))
1986 int name_len;
1987 struct spec_list *sl;
1988 struct spec_list *newsl;
1990 /* Get original name. */
1991 p1 += sizeof "%rename";
1992 while (*p1 == ' ' || *p1 == '\t')
1993 p1++;
1995 if (! ISALPHA ((unsigned char) *p1))
1996 fatal_error (input_location,
1997 "specs %%rename syntax malformed after "
1998 "%ld characters",
1999 (long) (p1 - buffer));
2001 p2 = p1;
2002 while (*p2 && !ISSPACE ((unsigned char) *p2))
2003 p2++;
2005 if (*p2 != ' ' && *p2 != '\t')
2006 fatal_error (input_location,
2007 "specs %%rename syntax malformed after "
2008 "%ld characters",
2009 (long) (p2 - buffer));
2011 name_len = p2 - p1;
2012 *p2++ = '\0';
2013 while (*p2 == ' ' || *p2 == '\t')
2014 p2++;
2016 if (! ISALPHA ((unsigned char) *p2))
2017 fatal_error (input_location,
2018 "specs %%rename syntax malformed after "
2019 "%ld characters",
2020 (long) (p2 - buffer));
2022 /* Get new spec name. */
2023 p3 = p2;
2024 while (*p3 && !ISSPACE ((unsigned char) *p3))
2025 p3++;
2027 if (p3 != p - 1)
2028 fatal_error (input_location,
2029 "specs %%rename syntax malformed after "
2030 "%ld characters",
2031 (long) (p3 - buffer));
2032 *p3 = '\0';
2034 for (sl = specs; sl; sl = sl->next)
2035 if (name_len == sl->name_len && !strcmp (sl->name, p1))
2036 break;
2038 if (!sl)
2039 fatal_error (input_location,
2040 "specs %s spec was not found to be renamed", p1);
2042 if (strcmp (p1, p2) == 0)
2043 continue;
2045 for (newsl = specs; newsl; newsl = newsl->next)
2046 if (strcmp (newsl->name, p2) == 0)
2047 fatal_error (input_location,
2048 "%s: attempt to rename spec %qs to "
2049 "already defined spec %qs",
2050 filename, p1, p2);
2052 if (verbose_flag)
2054 fnotice (stderr, "rename spec %s to %s\n", p1, p2);
2055 #ifdef DEBUG_SPECS
2056 fnotice (stderr, "spec is '%s'\n\n", *(sl->ptr_spec));
2057 #endif
2060 set_spec (p2, *(sl->ptr_spec), user_p);
2061 if (sl->alloc_p)
2062 free (CONST_CAST (char *, *(sl->ptr_spec)));
2064 *(sl->ptr_spec) = "";
2065 sl->alloc_p = 0;
2066 continue;
2068 else
2069 fatal_error (input_location,
2070 "specs unknown %% command after %ld characters",
2071 (long) (p1 - buffer));
2074 /* Find the colon that should end the suffix. */
2075 p1 = p;
2076 while (*p1 && *p1 != ':' && *p1 != '\n')
2077 p1++;
2079 /* The colon shouldn't be missing. */
2080 if (*p1 != ':')
2081 fatal_error (input_location,
2082 "specs file malformed after %ld characters",
2083 (long) (p1 - buffer));
2085 /* Skip back over trailing whitespace. */
2086 p2 = p1;
2087 while (p2 > buffer && (p2[-1] == ' ' || p2[-1] == '\t'))
2088 p2--;
2090 /* Copy the suffix to a string. */
2091 suffix = save_string (p, p2 - p);
2092 /* Find the next line. */
2093 p = skip_whitespace (p1 + 1);
2094 if (p[1] == 0)
2095 fatal_error (input_location,
2096 "specs file malformed after %ld characters",
2097 (long) (p - buffer));
2099 p1 = p;
2100 /* Find next blank line or end of string. */
2101 while (*p1 && !(*p1 == '\n' && (p1[1] == '\n' || p1[1] == '\0')))
2102 p1++;
2104 /* Specs end at the blank line and do not include the newline. */
2105 spec = save_string (p, p1 - p);
2106 p = p1;
2108 /* Delete backslash-newline sequences from the spec. */
2109 in = spec;
2110 out = spec;
2111 while (*in != 0)
2113 if (in[0] == '\\' && in[1] == '\n')
2114 in += 2;
2115 else if (in[0] == '#')
2116 while (*in && *in != '\n')
2117 in++;
2119 else
2120 *out++ = *in++;
2122 *out = 0;
2124 if (suffix[0] == '*')
2126 if (! strcmp (suffix, "*link_command"))
2127 link_command_spec = spec;
2128 else
2129 set_spec (suffix + 1, spec, user_p);
2131 else
2133 /* Add this pair to the vector. */
2134 compilers
2135 = XRESIZEVEC (struct compiler, compilers, n_compilers + 2);
2137 compilers[n_compilers].suffix = suffix;
2138 compilers[n_compilers].spec = spec;
2139 n_compilers++;
2140 memset (&compilers[n_compilers], 0, sizeof compilers[n_compilers]);
2143 if (*suffix == 0)
2144 link_command_spec = spec;
2147 if (link_command_spec == 0)
2148 fatal_error (input_location, "spec file has no spec for linking");
2151 /* Record the names of temporary files we tell compilers to write,
2152 and delete them at the end of the run. */
2154 /* This is the common prefix we use to make temp file names.
2155 It is chosen once for each run of this program.
2156 It is substituted into a spec by %g or %j.
2157 Thus, all temp file names contain this prefix.
2158 In practice, all temp file names start with this prefix.
2160 This prefix comes from the envvar TMPDIR if it is defined;
2161 otherwise, from the P_tmpdir macro if that is defined;
2162 otherwise, in /usr/tmp or /tmp;
2163 or finally the current directory if all else fails. */
2165 static const char *temp_filename;
2167 /* Length of the prefix. */
2169 static int temp_filename_length;
2171 /* Define the list of temporary files to delete. */
2173 struct temp_file
2175 const char *name;
2176 struct temp_file *next;
2179 /* Queue of files to delete on success or failure of compilation. */
2180 static struct temp_file *always_delete_queue;
2181 /* Queue of files to delete on failure of compilation. */
2182 static struct temp_file *failure_delete_queue;
2184 /* Record FILENAME as a file to be deleted automatically.
2185 ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
2186 otherwise delete it in any case.
2187 FAIL_DELETE nonzero means delete it if a compilation step fails;
2188 otherwise delete it in any case. */
2190 void
2191 record_temp_file (const char *filename, int always_delete, int fail_delete)
2193 char *const name = xstrdup (filename);
2195 if (always_delete)
2197 struct temp_file *temp;
2198 for (temp = always_delete_queue; temp; temp = temp->next)
2199 if (! filename_cmp (name, temp->name))
2200 goto already1;
2202 temp = XNEW (struct temp_file);
2203 temp->next = always_delete_queue;
2204 temp->name = name;
2205 always_delete_queue = temp;
2207 already1:;
2210 if (fail_delete)
2212 struct temp_file *temp;
2213 for (temp = failure_delete_queue; temp; temp = temp->next)
2214 if (! filename_cmp (name, temp->name))
2216 free (name);
2217 goto already2;
2220 temp = XNEW (struct temp_file);
2221 temp->next = failure_delete_queue;
2222 temp->name = name;
2223 failure_delete_queue = temp;
2225 already2:;
2229 /* Delete all the temporary files whose names we previously recorded. */
2231 #ifndef DELETE_IF_ORDINARY
2232 #define DELETE_IF_ORDINARY(NAME,ST,VERBOSE_FLAG) \
2233 do \
2235 if (stat (NAME, &ST) >= 0 && S_ISREG (ST.st_mode)) \
2236 if (unlink (NAME) < 0) \
2237 if (VERBOSE_FLAG) \
2238 perror_with_name (NAME); \
2239 } while (0)
2240 #endif
2242 static void
2243 delete_if_ordinary (const char *name)
2245 struct stat st;
2246 #ifdef DEBUG
2247 int i, c;
2249 printf ("Delete %s? (y or n) ", name);
2250 fflush (stdout);
2251 i = getchar ();
2252 if (i != '\n')
2253 while ((c = getchar ()) != '\n' && c != EOF)
2256 if (i == 'y' || i == 'Y')
2257 #endif /* DEBUG */
2258 DELETE_IF_ORDINARY (name, st, verbose_flag);
2261 static void
2262 delete_temp_files (void)
2264 struct temp_file *temp;
2266 for (temp = always_delete_queue; temp; temp = temp->next)
2267 delete_if_ordinary (temp->name);
2268 always_delete_queue = 0;
2271 /* Delete all the files to be deleted on error. */
2273 static void
2274 delete_failure_queue (void)
2276 struct temp_file *temp;
2278 for (temp = failure_delete_queue; temp; temp = temp->next)
2279 delete_if_ordinary (temp->name);
2282 static void
2283 clear_failure_queue (void)
2285 failure_delete_queue = 0;
2288 /* Call CALLBACK for each path in PATHS, breaking out early if CALLBACK
2289 returns non-NULL.
2290 If DO_MULTI is true iterate over the paths twice, first with multilib
2291 suffix then without, otherwise iterate over the paths once without
2292 adding a multilib suffix. When DO_MULTI is true, some attempt is made
2293 to avoid visiting the same path twice, but we could do better. For
2294 instance, /usr/lib/../lib is considered different from /usr/lib.
2295 At least EXTRA_SPACE chars past the end of the path passed to
2296 CALLBACK are available for use by the callback.
2297 CALLBACK_INFO allows extra parameters to be passed to CALLBACK.
2299 Returns the value returned by CALLBACK. */
2301 static void *
2302 for_each_path (const struct path_prefix *paths,
2303 bool do_multi,
2304 size_t extra_space,
2305 void *(*callback) (char *, void *),
2306 void *callback_info)
2308 struct prefix_list *pl;
2309 const char *multi_dir = NULL;
2310 const char *multi_os_dir = NULL;
2311 const char *multiarch_suffix = NULL;
2312 const char *multi_suffix;
2313 const char *just_multi_suffix;
2314 char *path = NULL;
2315 void *ret = NULL;
2316 bool skip_multi_dir = false;
2317 bool skip_multi_os_dir = false;
2319 multi_suffix = machine_suffix;
2320 just_multi_suffix = just_machine_suffix;
2321 if (do_multi && multilib_dir && strcmp (multilib_dir, ".") != 0)
2323 multi_dir = concat (multilib_dir, dir_separator_str, NULL);
2324 multi_suffix = concat (multi_suffix, multi_dir, NULL);
2325 just_multi_suffix = concat (just_multi_suffix, multi_dir, NULL);
2327 if (do_multi && multilib_os_dir && strcmp (multilib_os_dir, ".") != 0)
2328 multi_os_dir = concat (multilib_os_dir, dir_separator_str, NULL);
2329 if (multiarch_dir)
2330 multiarch_suffix = concat (multiarch_dir, dir_separator_str, NULL);
2332 while (1)
2334 size_t multi_dir_len = 0;
2335 size_t multi_os_dir_len = 0;
2336 size_t multiarch_len = 0;
2337 size_t suffix_len;
2338 size_t just_suffix_len;
2339 size_t len;
2341 if (multi_dir)
2342 multi_dir_len = strlen (multi_dir);
2343 if (multi_os_dir)
2344 multi_os_dir_len = strlen (multi_os_dir);
2345 if (multiarch_suffix)
2346 multiarch_len = strlen (multiarch_suffix);
2347 suffix_len = strlen (multi_suffix);
2348 just_suffix_len = strlen (just_multi_suffix);
2350 if (path == NULL)
2352 len = paths->max_len + extra_space + 1;
2353 len += MAX (MAX (suffix_len, multi_os_dir_len), multiarch_len);
2354 path = XNEWVEC (char, len);
2357 for (pl = paths->plist; pl != 0; pl = pl->next)
2359 len = strlen (pl->prefix);
2360 memcpy (path, pl->prefix, len);
2362 /* Look first in MACHINE/VERSION subdirectory. */
2363 if (!skip_multi_dir)
2365 memcpy (path + len, multi_suffix, suffix_len + 1);
2366 ret = callback (path, callback_info);
2367 if (ret)
2368 break;
2371 /* Some paths are tried with just the machine (ie. target)
2372 subdir. This is used for finding as, ld, etc. */
2373 if (!skip_multi_dir
2374 && pl->require_machine_suffix == 2)
2376 memcpy (path + len, just_multi_suffix, just_suffix_len + 1);
2377 ret = callback (path, callback_info);
2378 if (ret)
2379 break;
2382 /* Now try the multiarch path. */
2383 if (!skip_multi_dir
2384 && !pl->require_machine_suffix && multiarch_dir)
2386 memcpy (path + len, multiarch_suffix, multiarch_len + 1);
2387 ret = callback (path, callback_info);
2388 if (ret)
2389 break;
2392 /* Now try the base path. */
2393 if (!pl->require_machine_suffix
2394 && !(pl->os_multilib ? skip_multi_os_dir : skip_multi_dir))
2396 const char *this_multi;
2397 size_t this_multi_len;
2399 if (pl->os_multilib)
2401 this_multi = multi_os_dir;
2402 this_multi_len = multi_os_dir_len;
2404 else
2406 this_multi = multi_dir;
2407 this_multi_len = multi_dir_len;
2410 if (this_multi_len)
2411 memcpy (path + len, this_multi, this_multi_len + 1);
2412 else
2413 path[len] = '\0';
2415 ret = callback (path, callback_info);
2416 if (ret)
2417 break;
2420 if (pl)
2421 break;
2423 if (multi_dir == NULL && multi_os_dir == NULL)
2424 break;
2426 /* Run through the paths again, this time without multilibs.
2427 Don't repeat any we have already seen. */
2428 if (multi_dir)
2430 free (CONST_CAST (char *, multi_dir));
2431 multi_dir = NULL;
2432 free (CONST_CAST (char *, multi_suffix));
2433 multi_suffix = machine_suffix;
2434 free (CONST_CAST (char *, just_multi_suffix));
2435 just_multi_suffix = just_machine_suffix;
2437 else
2438 skip_multi_dir = true;
2439 if (multi_os_dir)
2441 free (CONST_CAST (char *, multi_os_dir));
2442 multi_os_dir = NULL;
2444 else
2445 skip_multi_os_dir = true;
2448 if (multi_dir)
2450 free (CONST_CAST (char *, multi_dir));
2451 free (CONST_CAST (char *, multi_suffix));
2452 free (CONST_CAST (char *, just_multi_suffix));
2454 if (multi_os_dir)
2455 free (CONST_CAST (char *, multi_os_dir));
2456 if (ret != path)
2457 free (path);
2458 return ret;
2461 /* Callback for build_search_list. Adds path to obstack being built. */
2463 struct add_to_obstack_info {
2464 struct obstack *ob;
2465 bool check_dir;
2466 bool first_time;
2469 static void *
2470 add_to_obstack (char *path, void *data)
2472 struct add_to_obstack_info *info = (struct add_to_obstack_info *) data;
2474 if (info->check_dir && !is_directory (path, false))
2475 return NULL;
2477 if (!info->first_time)
2478 obstack_1grow (info->ob, PATH_SEPARATOR);
2480 obstack_grow (info->ob, path, strlen (path));
2482 info->first_time = false;
2483 return NULL;
2486 /* Add or change the value of an environment variable, outputting the
2487 change to standard error if in verbose mode. */
2488 static void
2489 xputenv (const char *string)
2491 if (verbose_flag)
2492 fnotice (stderr, "%s\n", string);
2493 putenv (CONST_CAST (char *, string));
2496 /* Build a list of search directories from PATHS.
2497 PREFIX is a string to prepend to the list.
2498 If CHECK_DIR_P is true we ensure the directory exists.
2499 If DO_MULTI is true, multilib paths are output first, then
2500 non-multilib paths.
2501 This is used mostly by putenv_from_prefixes so we use `collect_obstack'.
2502 It is also used by the --print-search-dirs flag. */
2504 static char *
2505 build_search_list (const struct path_prefix *paths, const char *prefix,
2506 bool check_dir, bool do_multi)
2508 struct add_to_obstack_info info;
2510 info.ob = &collect_obstack;
2511 info.check_dir = check_dir;
2512 info.first_time = true;
2514 obstack_grow (&collect_obstack, prefix, strlen (prefix));
2515 obstack_1grow (&collect_obstack, '=');
2517 for_each_path (paths, do_multi, 0, add_to_obstack, &info);
2519 obstack_1grow (&collect_obstack, '\0');
2520 return XOBFINISH (&collect_obstack, char *);
2523 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
2524 for collect. */
2526 static void
2527 putenv_from_prefixes (const struct path_prefix *paths, const char *env_var,
2528 bool do_multi)
2530 xputenv (build_search_list (paths, env_var, true, do_multi));
2533 /* Check whether NAME can be accessed in MODE. This is like access,
2534 except that it never considers directories to be executable. */
2536 static int
2537 access_check (const char *name, int mode)
2539 if (mode == X_OK)
2541 struct stat st;
2543 if (stat (name, &st) < 0
2544 || S_ISDIR (st.st_mode))
2545 return -1;
2548 return access (name, mode);
2551 /* Callback for find_a_file. Appends the file name to the directory
2552 path. If the resulting file exists in the right mode, return the
2553 full pathname to the file. */
2555 struct file_at_path_info {
2556 const char *name;
2557 const char *suffix;
2558 int name_len;
2559 int suffix_len;
2560 int mode;
2563 static void *
2564 file_at_path (char *path, void *data)
2566 struct file_at_path_info *info = (struct file_at_path_info *) data;
2567 size_t len = strlen (path);
2569 memcpy (path + len, info->name, info->name_len);
2570 len += info->name_len;
2572 /* Some systems have a suffix for executable files.
2573 So try appending that first. */
2574 if (info->suffix_len)
2576 memcpy (path + len, info->suffix, info->suffix_len + 1);
2577 if (access_check (path, info->mode) == 0)
2578 return path;
2581 path[len] = '\0';
2582 if (access_check (path, info->mode) == 0)
2583 return path;
2585 return NULL;
2588 /* Search for NAME using the prefix list PREFIXES. MODE is passed to
2589 access to check permissions. If DO_MULTI is true, search multilib
2590 paths then non-multilib paths, otherwise do not search multilib paths.
2591 Return 0 if not found, otherwise return its name, allocated with malloc. */
2593 static char *
2594 find_a_file (const struct path_prefix *pprefix, const char *name, int mode,
2595 bool do_multi)
2597 struct file_at_path_info info;
2599 #ifdef DEFAULT_ASSEMBLER
2600 if (! strcmp (name, "as") && access (DEFAULT_ASSEMBLER, mode) == 0)
2601 return xstrdup (DEFAULT_ASSEMBLER);
2602 #endif
2604 #ifdef DEFAULT_LINKER
2605 if (! strcmp (name, "ld") && access (DEFAULT_LINKER, mode) == 0)
2606 return xstrdup (DEFAULT_LINKER);
2607 #endif
2609 /* Determine the filename to execute (special case for absolute paths). */
2611 if (IS_ABSOLUTE_PATH (name))
2613 if (access (name, mode) == 0)
2614 return xstrdup (name);
2616 return NULL;
2619 info.name = name;
2620 info.suffix = (mode & X_OK) != 0 ? HOST_EXECUTABLE_SUFFIX : "";
2621 info.name_len = strlen (info.name);
2622 info.suffix_len = strlen (info.suffix);
2623 info.mode = mode;
2625 return (char*) for_each_path (pprefix, do_multi,
2626 info.name_len + info.suffix_len,
2627 file_at_path, &info);
2630 /* Ranking of prefixes in the sort list. -B prefixes are put before
2631 all others. */
2633 enum path_prefix_priority
2635 PREFIX_PRIORITY_B_OPT,
2636 PREFIX_PRIORITY_LAST
2639 /* Add an entry for PREFIX in PLIST. The PLIST is kept in ascending
2640 order according to PRIORITY. Within each PRIORITY, new entries are
2641 appended.
2643 If WARN is nonzero, we will warn if no file is found
2644 through this prefix. WARN should point to an int
2645 which will be set to 1 if this entry is used.
2647 COMPONENT is the value to be passed to update_path.
2649 REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
2650 the complete value of machine_suffix.
2651 2 means try both machine_suffix and just_machine_suffix. */
2653 static void
2654 add_prefix (struct path_prefix *pprefix, const char *prefix,
2655 const char *component, /* enum prefix_priority */ int priority,
2656 int require_machine_suffix, int os_multilib)
2658 struct prefix_list *pl, **prev;
2659 int len;
2661 for (prev = &pprefix->plist;
2662 (*prev) != NULL && (*prev)->priority <= priority;
2663 prev = &(*prev)->next)
2666 /* Keep track of the longest prefix. */
2668 prefix = update_path (prefix, component);
2669 len = strlen (prefix);
2670 if (len > pprefix->max_len)
2671 pprefix->max_len = len;
2673 pl = XNEW (struct prefix_list);
2674 pl->prefix = prefix;
2675 pl->require_machine_suffix = require_machine_suffix;
2676 pl->priority = priority;
2677 pl->os_multilib = os_multilib;
2679 /* Insert after PREV. */
2680 pl->next = (*prev);
2681 (*prev) = pl;
2684 /* Same as add_prefix, but prepending target_system_root to prefix. */
2685 /* The target_system_root prefix has been relocated by gcc_exec_prefix. */
2686 static void
2687 add_sysrooted_prefix (struct path_prefix *pprefix, const char *prefix,
2688 const char *component,
2689 /* enum prefix_priority */ int priority,
2690 int require_machine_suffix, int os_multilib)
2692 if (!IS_ABSOLUTE_PATH (prefix))
2693 fatal_error (input_location, "system path %qs is not absolute", prefix);
2695 if (target_system_root)
2697 char *sysroot_no_trailing_dir_separator = xstrdup (target_system_root);
2698 size_t sysroot_len = strlen (target_system_root);
2700 if (sysroot_len > 0
2701 && target_system_root[sysroot_len - 1] == DIR_SEPARATOR)
2702 sysroot_no_trailing_dir_separator[sysroot_len - 1] = '\0';
2704 if (target_sysroot_suffix)
2705 prefix = concat (sysroot_no_trailing_dir_separator,
2706 target_sysroot_suffix, prefix, NULL);
2707 else
2708 prefix = concat (sysroot_no_trailing_dir_separator, prefix, NULL);
2710 free (sysroot_no_trailing_dir_separator);
2712 /* We have to override this because GCC's notion of sysroot
2713 moves along with GCC. */
2714 component = "GCC";
2717 add_prefix (pprefix, prefix, component, priority,
2718 require_machine_suffix, os_multilib);
2721 /* Execute the command specified by the arguments on the current line of spec.
2722 When using pipes, this includes several piped-together commands
2723 with `|' between them.
2725 Return 0 if successful, -1 if failed. */
2727 static int
2728 execute (void)
2730 int i;
2731 int n_commands; /* # of command. */
2732 char *string;
2733 struct pex_obj *pex;
2734 struct command
2736 const char *prog; /* program name. */
2737 const char **argv; /* vector of args. */
2739 const char *arg;
2741 struct command *commands; /* each command buffer with above info. */
2743 gcc_assert (!processing_spec_function);
2745 if (wrapper_string)
2747 string = find_a_file (&exec_prefixes,
2748 argbuf[0], X_OK, false);
2749 if (string)
2750 argbuf[0] = string;
2751 insert_wrapper (wrapper_string);
2754 /* Count # of piped commands. */
2755 for (n_commands = 1, i = 0; argbuf.iterate (i, &arg); i++)
2756 if (strcmp (arg, "|") == 0)
2757 n_commands++;
2759 /* Get storage for each command. */
2760 commands = (struct command *) alloca (n_commands * sizeof (struct command));
2762 /* Split argbuf into its separate piped processes,
2763 and record info about each one.
2764 Also search for the programs that are to be run. */
2766 argbuf.safe_push (0);
2768 commands[0].prog = argbuf[0]; /* first command. */
2769 commands[0].argv = argbuf.address ();
2771 if (!wrapper_string)
2773 string = find_a_file (&exec_prefixes, commands[0].prog, X_OK, false);
2774 commands[0].argv[0] = (string) ? string : commands[0].argv[0];
2777 for (n_commands = 1, i = 0; argbuf.iterate (i, &arg); i++)
2778 if (arg && strcmp (arg, "|") == 0)
2779 { /* each command. */
2780 #if defined (__MSDOS__) || defined (OS2) || defined (VMS)
2781 fatal_error (input_location, "-pipe not supported");
2782 #endif
2783 argbuf[i] = 0; /* Termination of
2784 command args. */
2785 commands[n_commands].prog = argbuf[i + 1];
2786 commands[n_commands].argv
2787 = &(argbuf.address ())[i + 1];
2788 string = find_a_file (&exec_prefixes, commands[n_commands].prog,
2789 X_OK, false);
2790 if (string)
2791 commands[n_commands].argv[0] = string;
2792 n_commands++;
2795 /* If -v, print what we are about to do, and maybe query. */
2797 if (verbose_flag)
2799 /* For help listings, put a blank line between sub-processes. */
2800 if (print_help_list)
2801 fputc ('\n', stderr);
2803 /* Print each piped command as a separate line. */
2804 for (i = 0; i < n_commands; i++)
2806 const char *const *j;
2808 if (verbose_only_flag)
2810 for (j = commands[i].argv; *j; j++)
2812 const char *p;
2813 for (p = *j; *p; ++p)
2814 if (!ISALNUM ((unsigned char) *p)
2815 && *p != '_' && *p != '/' && *p != '-' && *p != '.')
2816 break;
2817 if (*p || !*j)
2819 fprintf (stderr, " \"");
2820 for (p = *j; *p; ++p)
2822 if (*p == '"' || *p == '\\' || *p == '$')
2823 fputc ('\\', stderr);
2824 fputc (*p, stderr);
2826 fputc ('"', stderr);
2828 /* If it's empty, print "". */
2829 else if (!**j)
2830 fprintf (stderr, " \"\"");
2831 else
2832 fprintf (stderr, " %s", *j);
2835 else
2836 for (j = commands[i].argv; *j; j++)
2837 /* If it's empty, print "". */
2838 if (!**j)
2839 fprintf (stderr, " \"\"");
2840 else
2841 fprintf (stderr, " %s", *j);
2843 /* Print a pipe symbol after all but the last command. */
2844 if (i + 1 != n_commands)
2845 fprintf (stderr, " |");
2846 fprintf (stderr, "\n");
2848 fflush (stderr);
2849 if (verbose_only_flag != 0)
2851 /* verbose_only_flag should act as if the spec was
2852 executed, so increment execution_count before
2853 returning. This prevents spurious warnings about
2854 unused linker input files, etc. */
2855 execution_count++;
2856 return 0;
2858 #ifdef DEBUG
2859 fnotice (stderr, "\nGo ahead? (y or n) ");
2860 fflush (stderr);
2861 i = getchar ();
2862 if (i != '\n')
2863 while (getchar () != '\n')
2866 if (i != 'y' && i != 'Y')
2867 return 0;
2868 #endif /* DEBUG */
2871 #ifdef ENABLE_VALGRIND_CHECKING
2872 /* Run the each command through valgrind. To simplify prepending the
2873 path to valgrind and the option "-q" (for quiet operation unless
2874 something triggers), we allocate a separate argv array. */
2876 for (i = 0; i < n_commands; i++)
2878 const char **argv;
2879 int argc;
2880 int j;
2882 for (argc = 0; commands[i].argv[argc] != NULL; argc++)
2885 argv = XALLOCAVEC (const char *, argc + 3);
2887 argv[0] = VALGRIND_PATH;
2888 argv[1] = "-q";
2889 for (j = 2; j < argc + 2; j++)
2890 argv[j] = commands[i].argv[j - 2];
2891 argv[j] = NULL;
2893 commands[i].argv = argv;
2894 commands[i].prog = argv[0];
2896 #endif
2898 /* Run each piped subprocess. */
2900 pex = pex_init (PEX_USE_PIPES | ((report_times || report_times_to_file)
2901 ? PEX_RECORD_TIMES : 0),
2902 progname, temp_filename);
2903 if (pex == NULL)
2904 fatal_error (input_location, "pex_init failed: %m");
2906 for (i = 0; i < n_commands; i++)
2908 const char *errmsg;
2909 int err;
2910 const char *string = commands[i].argv[0];
2912 errmsg = pex_run (pex,
2913 ((i + 1 == n_commands ? PEX_LAST : 0)
2914 | (string == commands[i].prog ? PEX_SEARCH : 0)),
2915 string, CONST_CAST (char **, commands[i].argv),
2916 NULL, NULL, &err);
2917 if (errmsg != NULL)
2919 if (err == 0)
2920 fatal_error (input_location, errmsg);
2921 else
2923 errno = err;
2924 pfatal_with_name (errmsg);
2928 if (i && string != commands[i].prog)
2929 free (CONST_CAST (char *, string));
2932 execution_count++;
2934 /* Wait for all the subprocesses to finish. */
2937 int *statuses;
2938 struct pex_time *times = NULL;
2939 int ret_code = 0;
2941 statuses = (int *) alloca (n_commands * sizeof (int));
2942 if (!pex_get_status (pex, n_commands, statuses))
2943 fatal_error (input_location, "failed to get exit status: %m");
2945 if (report_times || report_times_to_file)
2947 times = (struct pex_time *) alloca (n_commands * sizeof (struct pex_time));
2948 if (!pex_get_times (pex, n_commands, times))
2949 fatal_error (input_location, "failed to get process times: %m");
2952 pex_free (pex);
2954 for (i = 0; i < n_commands; ++i)
2956 int status = statuses[i];
2958 if (WIFSIGNALED (status))
2960 #ifdef SIGPIPE
2961 /* SIGPIPE is a special case. It happens in -pipe mode
2962 when the compiler dies before the preprocessor is done,
2963 or the assembler dies before the compiler is done.
2964 There's generally been an error already, and this is
2965 just fallout. So don't generate another error unless
2966 we would otherwise have succeeded. */
2967 if (WTERMSIG (status) == SIGPIPE
2968 && (signal_count || greatest_status >= MIN_FATAL_STATUS))
2970 signal_count++;
2971 ret_code = -1;
2973 else
2974 #endif
2975 internal_error_no_backtrace ("%s (program %s)",
2976 strsignal (WTERMSIG (status)),
2977 commands[i].prog);
2979 else if (WIFEXITED (status)
2980 && WEXITSTATUS (status) >= MIN_FATAL_STATUS)
2982 /* For ICEs in cc1, cc1obj, cc1plus see if it is
2983 reproducible or not. */
2984 const char *p;
2985 if (flag_report_bug
2986 && WEXITSTATUS (status) == ICE_EXIT_CODE
2987 && i == 0
2988 && (p = strrchr (commands[0].argv[0], DIR_SEPARATOR))
2989 && ! strncmp (p + 1, "cc1", 3))
2990 try_generate_repro (commands[0].argv);
2991 if (WEXITSTATUS (status) > greatest_status)
2992 greatest_status = WEXITSTATUS (status);
2993 ret_code = -1;
2996 if (report_times || report_times_to_file)
2998 struct pex_time *pt = &times[i];
2999 double ut, st;
3001 ut = ((double) pt->user_seconds
3002 + (double) pt->user_microseconds / 1.0e6);
3003 st = ((double) pt->system_seconds
3004 + (double) pt->system_microseconds / 1.0e6);
3006 if (ut + st != 0)
3008 if (report_times)
3009 fnotice (stderr, "# %s %.2f %.2f\n",
3010 commands[i].prog, ut, st);
3012 if (report_times_to_file)
3014 int c = 0;
3015 const char *const *j;
3017 fprintf (report_times_to_file, "%g %g", ut, st);
3019 for (j = &commands[i].prog; *j; j = &commands[i].argv[++c])
3021 const char *p;
3022 for (p = *j; *p; ++p)
3023 if (*p == '"' || *p == '\\' || *p == '$'
3024 || ISSPACE (*p))
3025 break;
3027 if (*p)
3029 fprintf (report_times_to_file, " \"");
3030 for (p = *j; *p; ++p)
3032 if (*p == '"' || *p == '\\' || *p == '$')
3033 fputc ('\\', report_times_to_file);
3034 fputc (*p, report_times_to_file);
3036 fputc ('"', report_times_to_file);
3038 else
3039 fprintf (report_times_to_file, " %s", *j);
3042 fputc ('\n', report_times_to_file);
3048 if (commands[0].argv[0] != commands[0].prog)
3049 free (CONST_CAST (char *, commands[0].argv[0]));
3051 return ret_code;
3055 /* Find all the switches given to us
3056 and make a vector describing them.
3057 The elements of the vector are strings, one per switch given.
3058 If a switch uses following arguments, then the `part1' field
3059 is the switch itself and the `args' field
3060 is a null-terminated vector containing the following arguments.
3061 Bits in the `live_cond' field are:
3062 SWITCH_LIVE to indicate this switch is true in a conditional spec.
3063 SWITCH_FALSE to indicate this switch is overridden by a later switch.
3064 SWITCH_IGNORE to indicate this switch should be ignored (used in %<S).
3065 SWITCH_IGNORE_PERMANENTLY to indicate this switch should be ignored
3066 in all do_spec calls afterwards. Used for %<S from self specs.
3067 The `validated' field is nonzero if any spec has looked at this switch;
3068 if it remains zero at the end of the run, it must be meaningless. */
3070 #define SWITCH_LIVE (1 << 0)
3071 #define SWITCH_FALSE (1 << 1)
3072 #define SWITCH_IGNORE (1 << 2)
3073 #define SWITCH_IGNORE_PERMANENTLY (1 << 3)
3074 #define SWITCH_KEEP_FOR_GCC (1 << 4)
3076 struct switchstr
3078 const char *part1;
3079 const char **args;
3080 unsigned int live_cond;
3081 bool known;
3082 bool validated;
3083 bool ordering;
3086 static struct switchstr *switches;
3088 static int n_switches;
3090 static int n_switches_alloc;
3092 /* Set to zero if -fcompare-debug is disabled, positive if it's
3093 enabled and we're running the first compilation, negative if it's
3094 enabled and we're running the second compilation. For most of the
3095 time, it's in the range -1..1, but it can be temporarily set to 2
3096 or 3 to indicate that the -fcompare-debug flags didn't come from
3097 the command-line, but rather from the GCC_COMPARE_DEBUG environment
3098 variable, until a synthesized -fcompare-debug flag is added to the
3099 command line. */
3100 int compare_debug;
3102 /* Set to nonzero if we've seen the -fcompare-debug-second flag. */
3103 int compare_debug_second;
3105 /* Set to the flags that should be passed to the second compilation in
3106 a -fcompare-debug compilation. */
3107 const char *compare_debug_opt;
3109 static struct switchstr *switches_debug_check[2];
3111 static int n_switches_debug_check[2];
3113 static int n_switches_alloc_debug_check[2];
3115 static char *debug_check_temp_file[2];
3117 /* Language is one of three things:
3119 1) The name of a real programming language.
3120 2) NULL, indicating that no one has figured out
3121 what it is yet.
3122 3) '*', indicating that the file should be passed
3123 to the linker. */
3124 struct infile
3126 const char *name;
3127 const char *language;
3128 struct compiler *incompiler;
3129 bool compiled;
3130 bool preprocessed;
3133 /* Also a vector of input files specified. */
3135 static struct infile *infiles;
3137 int n_infiles;
3139 static int n_infiles_alloc;
3141 /* True if multiple input files are being compiled to a single
3142 assembly file. */
3144 static bool combine_inputs;
3146 /* This counts the number of libraries added by lang_specific_driver, so that
3147 we can tell if there were any user supplied any files or libraries. */
3149 static int added_libraries;
3151 /* And a vector of corresponding output files is made up later. */
3153 const char **outfiles;
3155 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3157 /* Convert NAME to a new name if it is the standard suffix. DO_EXE
3158 is true if we should look for an executable suffix. DO_OBJ
3159 is true if we should look for an object suffix. */
3161 static const char *
3162 convert_filename (const char *name, int do_exe ATTRIBUTE_UNUSED,
3163 int do_obj ATTRIBUTE_UNUSED)
3165 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3166 int i;
3167 #endif
3168 int len;
3170 if (name == NULL)
3171 return NULL;
3173 len = strlen (name);
3175 #ifdef HAVE_TARGET_OBJECT_SUFFIX
3176 /* Convert x.o to x.obj if TARGET_OBJECT_SUFFIX is ".obj". */
3177 if (do_obj && len > 2
3178 && name[len - 2] == '.'
3179 && name[len - 1] == 'o')
3181 obstack_grow (&obstack, name, len - 2);
3182 obstack_grow0 (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
3183 name = XOBFINISH (&obstack, const char *);
3185 #endif
3187 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3188 /* If there is no filetype, make it the executable suffix (which includes
3189 the "."). But don't get confused if we have just "-o". */
3190 if (! do_exe || TARGET_EXECUTABLE_SUFFIX[0] == 0 || (len == 2 && name[0] == '-'))
3191 return name;
3193 for (i = len - 1; i >= 0; i--)
3194 if (IS_DIR_SEPARATOR (name[i]))
3195 break;
3197 for (i++; i < len; i++)
3198 if (name[i] == '.')
3199 return name;
3201 obstack_grow (&obstack, name, len);
3202 obstack_grow0 (&obstack, TARGET_EXECUTABLE_SUFFIX,
3203 strlen (TARGET_EXECUTABLE_SUFFIX));
3204 name = XOBFINISH (&obstack, const char *);
3205 #endif
3207 return name;
3209 #endif
3211 /* Display the command line switches accepted by gcc. */
3212 static void
3213 display_help (void)
3215 printf (_("Usage: %s [options] file...\n"), progname);
3216 fputs (_("Options:\n"), stdout);
3218 fputs (_(" -pass-exit-codes Exit with highest error code from a phase\n"), stdout);
3219 fputs (_(" --help Display this information\n"), stdout);
3220 fputs (_(" --target-help Display target specific command line options\n"), stdout);
3221 fputs (_(" --help={common|optimizers|params|target|warnings|[^]{joined|separate|undocumented}}[,...]\n"), stdout);
3222 fputs (_(" Display specific types of command line options\n"), stdout);
3223 if (! verbose_flag)
3224 fputs (_(" (Use '-v --help' to display command line options of sub-processes)\n"), stdout);
3225 fputs (_(" --version Display compiler version information\n"), stdout);
3226 fputs (_(" -dumpspecs Display all of the built in spec strings\n"), stdout);
3227 fputs (_(" -dumpversion Display the version of the compiler\n"), stdout);
3228 fputs (_(" -dumpmachine Display the compiler's target processor\n"), stdout);
3229 fputs (_(" -print-search-dirs Display the directories in the compiler's search path\n"), stdout);
3230 fputs (_(" -print-libgcc-file-name Display the name of the compiler's companion library\n"), stdout);
3231 fputs (_(" -print-file-name=<lib> Display the full path to library <lib>\n"), stdout);
3232 fputs (_(" -print-prog-name=<prog> Display the full path to compiler component <prog>\n"), stdout);
3233 fputs (_("\
3234 -print-multiarch Display the target's normalized GNU triplet, used as\n\
3235 a component in the library path\n"), stdout);
3236 fputs (_(" -print-multi-directory Display the root directory for versions of libgcc\n"), stdout);
3237 fputs (_("\
3238 -print-multi-lib Display the mapping between command line options and\n\
3239 multiple library search directories\n"), stdout);
3240 fputs (_(" -print-multi-os-directory Display the relative path to OS libraries\n"), stdout);
3241 fputs (_(" -print-sysroot Display the target libraries directory\n"), stdout);
3242 fputs (_(" -print-sysroot-headers-suffix Display the sysroot suffix used to find headers\n"), stdout);
3243 fputs (_(" -Wa,<options> Pass comma-separated <options> on to the assembler\n"), stdout);
3244 fputs (_(" -Wp,<options> Pass comma-separated <options> on to the preprocessor\n"), stdout);
3245 fputs (_(" -Wl,<options> Pass comma-separated <options> on to the linker\n"), stdout);
3246 fputs (_(" -Xassembler <arg> Pass <arg> on to the assembler\n"), stdout);
3247 fputs (_(" -Xpreprocessor <arg> Pass <arg> on to the preprocessor\n"), stdout);
3248 fputs (_(" -Xlinker <arg> Pass <arg> on to the linker\n"), stdout);
3249 fputs (_(" -save-temps Do not delete intermediate files\n"), stdout);
3250 fputs (_(" -save-temps=<arg> Do not delete intermediate files\n"), stdout);
3251 fputs (_("\
3252 -no-canonical-prefixes Do not canonicalize paths when building relative\n\
3253 prefixes to other gcc components\n"), stdout);
3254 fputs (_(" -pipe Use pipes rather than intermediate files\n"), stdout);
3255 fputs (_(" -time Time the execution of each subprocess\n"), stdout);
3256 fputs (_(" -specs=<file> Override built-in specs with the contents of <file>\n"), stdout);
3257 fputs (_(" -std=<standard> Assume that the input sources are for <standard>\n"), stdout);
3258 fputs (_("\
3259 --sysroot=<directory> Use <directory> as the root directory for headers\n\
3260 and libraries\n"), stdout);
3261 fputs (_(" -B <directory> Add <directory> to the compiler's search paths\n"), stdout);
3262 fputs (_(" -v Display the programs invoked by the compiler\n"), stdout);
3263 fputs (_(" -### Like -v but options quoted and commands not executed\n"), stdout);
3264 fputs (_(" -E Preprocess only; do not compile, assemble or link\n"), stdout);
3265 fputs (_(" -S Compile only; do not assemble or link\n"), stdout);
3266 fputs (_(" -c Compile and assemble, but do not link\n"), stdout);
3267 fputs (_(" -o <file> Place the output into <file>\n"), stdout);
3268 fputs (_(" -pie Create a position independent executable\n"), stdout);
3269 fputs (_(" -shared Create a shared library\n"), stdout);
3270 fputs (_("\
3271 -x <language> Specify the language of the following input files\n\
3272 Permissible languages include: c c++ assembler none\n\
3273 'none' means revert to the default behavior of\n\
3274 guessing the language based on the file's extension\n\
3275 "), stdout);
3277 printf (_("\
3278 \nOptions starting with -g, -f, -m, -O, -W, or --param are automatically\n\
3279 passed on to the various sub-processes invoked by %s. In order to pass\n\
3280 other options on to these processes the -W<letter> options must be used.\n\
3281 "), progname);
3283 /* The rest of the options are displayed by invocations of the various
3284 sub-processes. */
3287 static void
3288 add_preprocessor_option (const char *option, int len)
3290 preprocessor_options.safe_push (save_string (option, len));
3293 static void
3294 add_assembler_option (const char *option, int len)
3296 assembler_options.safe_push (save_string (option, len));
3299 static void
3300 add_linker_option (const char *option, int len)
3302 linker_options.safe_push (save_string (option, len));
3305 /* Allocate space for an input file in infiles. */
3307 static void
3308 alloc_infile (void)
3310 if (n_infiles_alloc == 0)
3312 n_infiles_alloc = 16;
3313 infiles = XNEWVEC (struct infile, n_infiles_alloc);
3315 else if (n_infiles_alloc == n_infiles)
3317 n_infiles_alloc *= 2;
3318 infiles = XRESIZEVEC (struct infile, infiles, n_infiles_alloc);
3322 /* Store an input file with the given NAME and LANGUAGE in
3323 infiles. */
3325 static void
3326 add_infile (const char *name, const char *language)
3328 alloc_infile ();
3329 infiles[n_infiles].name = name;
3330 infiles[n_infiles++].language = language;
3333 /* Allocate space for a switch in switches. */
3335 static void
3336 alloc_switch (void)
3338 if (n_switches_alloc == 0)
3340 n_switches_alloc = 16;
3341 switches = XNEWVEC (struct switchstr, n_switches_alloc);
3343 else if (n_switches_alloc == n_switches)
3345 n_switches_alloc *= 2;
3346 switches = XRESIZEVEC (struct switchstr, switches, n_switches_alloc);
3350 /* Save an option OPT with N_ARGS arguments in array ARGS, marking it
3351 as validated if VALIDATED and KNOWN if it is an internal switch. */
3353 static void
3354 save_switch (const char *opt, size_t n_args, const char *const *args,
3355 bool validated, bool known)
3357 alloc_switch ();
3358 switches[n_switches].part1 = opt + 1;
3359 if (n_args == 0)
3360 switches[n_switches].args = 0;
3361 else
3363 switches[n_switches].args = XNEWVEC (const char *, n_args + 1);
3364 memcpy (switches[n_switches].args, args, n_args * sizeof (const char *));
3365 switches[n_switches].args[n_args] = NULL;
3368 switches[n_switches].live_cond = 0;
3369 switches[n_switches].validated = validated;
3370 switches[n_switches].known = known;
3371 switches[n_switches].ordering = 0;
3372 n_switches++;
3375 /* Handle an option DECODED that is unknown to the option-processing
3376 machinery. */
3378 static bool
3379 driver_unknown_option_callback (const struct cl_decoded_option *decoded)
3381 const char *opt = decoded->arg;
3382 if (opt[1] == 'W' && opt[2] == 'n' && opt[3] == 'o' && opt[4] == '-'
3383 && !(decoded->errors & CL_ERR_NEGATIVE))
3385 /* Leave unknown -Wno-* options for the compiler proper, to be
3386 diagnosed only if there are warnings. */
3387 save_switch (decoded->canonical_option[0],
3388 decoded->canonical_option_num_elements - 1,
3389 &decoded->canonical_option[1], false, true);
3390 return false;
3392 if (decoded->opt_index == OPT_SPECIAL_unknown)
3394 /* Give it a chance to define it a a spec file. */
3395 save_switch (decoded->canonical_option[0],
3396 decoded->canonical_option_num_elements - 1,
3397 &decoded->canonical_option[1], false, false);
3398 return false;
3400 else
3401 return true;
3404 /* Handle an option DECODED that is not marked as CL_DRIVER.
3405 LANG_MASK will always be CL_DRIVER. */
3407 static void
3408 driver_wrong_lang_callback (const struct cl_decoded_option *decoded,
3409 unsigned int lang_mask ATTRIBUTE_UNUSED)
3411 /* At this point, non-driver options are accepted (and expected to
3412 be passed down by specs) unless marked to be rejected by the
3413 driver. Options to be rejected by the driver but accepted by the
3414 compilers proper are treated just like completely unknown
3415 options. */
3416 const struct cl_option *option = &cl_options[decoded->opt_index];
3418 if (option->cl_reject_driver)
3419 error ("unrecognized command line option %qs",
3420 decoded->orig_option_with_args_text);
3421 else
3422 save_switch (decoded->canonical_option[0],
3423 decoded->canonical_option_num_elements - 1,
3424 &decoded->canonical_option[1], false, true);
3427 static const char *spec_lang = 0;
3428 static int last_language_n_infiles;
3430 /* Parse -foffload option argument. */
3432 static void
3433 handle_foffload_option (const char *arg)
3435 const char *c, *cur, *n, *next, *end;
3436 char *target;
3438 /* If option argument starts with '-' then no target is specified and we
3439 do not need to parse it. */
3440 if (arg[0] == '-')
3441 return;
3443 end = strchr (arg, '=');
3444 if (end == NULL)
3445 end = strchr (arg, '\0');
3446 cur = arg;
3448 while (cur < end)
3450 next = strchr (cur, ',');
3451 if (next == NULL)
3452 next = end;
3453 next = (next > end) ? end : next;
3455 target = XNEWVEC (char, next - cur + 1);
3456 memcpy (target, cur, next - cur);
3457 target[next - cur] = '\0';
3459 /* If 'disable' is passed to the option, stop parsing the option and clean
3460 the list of offload targets. */
3461 if (strcmp (target, "disable") == 0)
3463 free (offload_targets);
3464 offload_targets = xstrdup ("");
3465 break;
3468 /* Check that GCC is configured to support the offload target. */
3469 c = OFFLOAD_TARGETS;
3470 while (c)
3472 n = strchr (c, ',');
3473 if (n == NULL)
3474 n = strchr (c, '\0');
3476 if (next - cur == n - c && strncmp (target, c, n - c) == 0)
3477 break;
3479 c = *n ? n + 1 : NULL;
3482 if (!c)
3483 fatal_error (input_location,
3484 "GCC is not configured to support %s as offload target",
3485 target);
3487 if (!offload_targets)
3489 offload_targets = target;
3490 target = NULL;
3492 else
3494 /* Check that the target hasn't already presented in the list. */
3495 c = offload_targets;
3498 n = strchr (c, ':');
3499 if (n == NULL)
3500 n = strchr (c, '\0');
3502 if (next - cur == n - c && strncmp (c, target, n - c) == 0)
3503 break;
3505 c = n + 1;
3507 while (*n);
3509 /* If duplicate is not found, append the target to the list. */
3510 if (c > n)
3512 size_t offload_targets_len = strlen (offload_targets);
3513 offload_targets
3514 = XRESIZEVEC (char, offload_targets,
3515 offload_targets_len + next - cur + 2);
3516 if (offload_targets_len)
3517 offload_targets[offload_targets_len++] = ':';
3518 memcpy (offload_targets + offload_targets_len, target, next - cur);
3522 cur = next + 1;
3523 XDELETEVEC (target);
3527 /* Handle a driver option; arguments and return value as for
3528 handle_option. */
3530 static bool
3531 driver_handle_option (struct gcc_options *opts,
3532 struct gcc_options *opts_set,
3533 const struct cl_decoded_option *decoded,
3534 unsigned int lang_mask ATTRIBUTE_UNUSED, int kind,
3535 location_t loc,
3536 const struct cl_option_handlers *handlers ATTRIBUTE_UNUSED,
3537 diagnostic_context *dc)
3539 size_t opt_index = decoded->opt_index;
3540 const char *arg = decoded->arg;
3541 const char *compare_debug_replacement_opt;
3542 int value = decoded->value;
3543 bool validated = false;
3544 bool do_save = true;
3546 gcc_assert (opts == &global_options);
3547 gcc_assert (opts_set == &global_options_set);
3548 gcc_assert (kind == DK_UNSPECIFIED);
3549 gcc_assert (loc == UNKNOWN_LOCATION);
3550 gcc_assert (dc == global_dc);
3552 switch (opt_index)
3554 case OPT_dumpspecs:
3556 struct spec_list *sl;
3557 init_spec ();
3558 for (sl = specs; sl; sl = sl->next)
3559 printf ("*%s:\n%s\n\n", sl->name, *(sl->ptr_spec));
3560 if (link_command_spec)
3561 printf ("*link_command:\n%s\n\n", link_command_spec);
3562 exit (0);
3565 case OPT_dumpversion:
3566 printf ("%s\n", spec_version);
3567 exit (0);
3569 case OPT_dumpmachine:
3570 printf ("%s\n", spec_machine);
3571 exit (0);
3573 case OPT__version:
3574 print_version = 1;
3576 /* CPP driver cannot obtain switch from cc1_options. */
3577 if (is_cpp_driver)
3578 add_preprocessor_option ("--version", strlen ("--version"));
3579 add_assembler_option ("--version", strlen ("--version"));
3580 add_linker_option ("--version", strlen ("--version"));
3581 break;
3583 case OPT__help:
3584 print_help_list = 1;
3586 /* CPP driver cannot obtain switch from cc1_options. */
3587 if (is_cpp_driver)
3588 add_preprocessor_option ("--help", 6);
3589 add_assembler_option ("--help", 6);
3590 add_linker_option ("--help", 6);
3591 break;
3593 case OPT__help_:
3594 print_subprocess_help = 2;
3595 break;
3597 case OPT__target_help:
3598 print_subprocess_help = 1;
3600 /* CPP driver cannot obtain switch from cc1_options. */
3601 if (is_cpp_driver)
3602 add_preprocessor_option ("--target-help", 13);
3603 add_assembler_option ("--target-help", 13);
3604 add_linker_option ("--target-help", 13);
3605 break;
3607 case OPT__no_sysroot_suffix:
3608 case OPT_pass_exit_codes:
3609 case OPT_print_search_dirs:
3610 case OPT_print_file_name_:
3611 case OPT_print_prog_name_:
3612 case OPT_print_multi_lib:
3613 case OPT_print_multi_directory:
3614 case OPT_print_sysroot:
3615 case OPT_print_multi_os_directory:
3616 case OPT_print_multiarch:
3617 case OPT_print_sysroot_headers_suffix:
3618 case OPT_time:
3619 case OPT_wrapper:
3620 /* These options set the variables specified in common.opt
3621 automatically, and do not need to be saved for spec
3622 processing. */
3623 do_save = false;
3624 break;
3626 case OPT_print_libgcc_file_name:
3627 print_file_name = "libgcc.a";
3628 do_save = false;
3629 break;
3631 case OPT_fuse_ld_bfd:
3632 use_ld = ".bfd";
3633 break;
3635 case OPT_fuse_ld_gold:
3636 use_ld = ".gold";
3637 break;
3639 case OPT_fcompare_debug_second:
3640 compare_debug_second = 1;
3641 break;
3643 case OPT_fcompare_debug:
3644 switch (value)
3646 case 0:
3647 compare_debug_replacement_opt = "-fcompare-debug=";
3648 arg = "";
3649 goto compare_debug_with_arg;
3651 case 1:
3652 compare_debug_replacement_opt = "-fcompare-debug=-gtoggle";
3653 arg = "-gtoggle";
3654 goto compare_debug_with_arg;
3656 default:
3657 gcc_unreachable ();
3659 break;
3661 case OPT_fcompare_debug_:
3662 compare_debug_replacement_opt = decoded->canonical_option[0];
3663 compare_debug_with_arg:
3664 gcc_assert (decoded->canonical_option_num_elements == 1);
3665 gcc_assert (arg != NULL);
3666 if (*arg)
3667 compare_debug = 1;
3668 else
3669 compare_debug = -1;
3670 if (compare_debug < 0)
3671 compare_debug_opt = NULL;
3672 else
3673 compare_debug_opt = arg;
3674 save_switch (compare_debug_replacement_opt, 0, NULL, validated, true);
3675 return true;
3677 case OPT_fdiagnostics_color_:
3678 diagnostic_color_init (dc, value);
3679 break;
3681 case OPT_Wa_:
3683 int prev, j;
3684 /* Pass the rest of this option to the assembler. */
3686 /* Split the argument at commas. */
3687 prev = 0;
3688 for (j = 0; arg[j]; j++)
3689 if (arg[j] == ',')
3691 add_assembler_option (arg + prev, j - prev);
3692 prev = j + 1;
3695 /* Record the part after the last comma. */
3696 add_assembler_option (arg + prev, j - prev);
3698 do_save = false;
3699 break;
3701 case OPT_Wp_:
3703 int prev, j;
3704 /* Pass the rest of this option to the preprocessor. */
3706 /* Split the argument at commas. */
3707 prev = 0;
3708 for (j = 0; arg[j]; j++)
3709 if (arg[j] == ',')
3711 add_preprocessor_option (arg + prev, j - prev);
3712 prev = j + 1;
3715 /* Record the part after the last comma. */
3716 add_preprocessor_option (arg + prev, j - prev);
3718 do_save = false;
3719 break;
3721 case OPT_Wl_:
3723 int prev, j;
3724 /* Split the argument at commas. */
3725 prev = 0;
3726 for (j = 0; arg[j]; j++)
3727 if (arg[j] == ',')
3729 add_infile (save_string (arg + prev, j - prev), "*");
3730 prev = j + 1;
3732 /* Record the part after the last comma. */
3733 add_infile (arg + prev, "*");
3735 do_save = false;
3736 break;
3738 case OPT_Xlinker:
3739 add_infile (arg, "*");
3740 do_save = false;
3741 break;
3743 case OPT_Xpreprocessor:
3744 add_preprocessor_option (arg, strlen (arg));
3745 do_save = false;
3746 break;
3748 case OPT_Xassembler:
3749 add_assembler_option (arg, strlen (arg));
3750 do_save = false;
3751 break;
3753 case OPT_l:
3754 /* POSIX allows separation of -l and the lib arg; canonicalize
3755 by concatenating -l with its arg */
3756 add_infile (concat ("-l", arg, NULL), "*");
3757 do_save = false;
3758 break;
3760 case OPT_L:
3761 /* Similarly, canonicalize -L for linkers that may not accept
3762 separate arguments. */
3763 save_switch (concat ("-L", arg, NULL), 0, NULL, validated, true);
3764 return true;
3766 case OPT_F:
3767 /* Likewise -F. */
3768 save_switch (concat ("-F", arg, NULL), 0, NULL, validated, true);
3769 return true;
3771 case OPT_save_temps:
3772 save_temps_flag = SAVE_TEMPS_CWD;
3773 validated = true;
3774 break;
3776 case OPT_save_temps_:
3777 if (strcmp (arg, "cwd") == 0)
3778 save_temps_flag = SAVE_TEMPS_CWD;
3779 else if (strcmp (arg, "obj") == 0
3780 || strcmp (arg, "object") == 0)
3781 save_temps_flag = SAVE_TEMPS_OBJ;
3782 else
3783 fatal_error (input_location, "%qs is an unknown -save-temps option",
3784 decoded->orig_option_with_args_text);
3785 break;
3787 case OPT_no_canonical_prefixes:
3788 /* Already handled as a special case, so ignored here. */
3789 do_save = false;
3790 break;
3792 case OPT_pipe:
3793 validated = true;
3794 /* These options set the variables specified in common.opt
3795 automatically, but do need to be saved for spec
3796 processing. */
3797 break;
3799 case OPT_specs_:
3801 struct user_specs *user = XNEW (struct user_specs);
3803 user->next = (struct user_specs *) 0;
3804 user->filename = arg;
3805 if (user_specs_tail)
3806 user_specs_tail->next = user;
3807 else
3808 user_specs_head = user;
3809 user_specs_tail = user;
3811 validated = true;
3812 break;
3814 case OPT__sysroot_:
3815 target_system_root = arg;
3816 target_system_root_changed = 1;
3817 do_save = false;
3818 break;
3820 case OPT_time_:
3821 if (report_times_to_file)
3822 fclose (report_times_to_file);
3823 report_times_to_file = fopen (arg, "a");
3824 do_save = false;
3825 break;
3827 case OPT____:
3828 /* "-###"
3829 This is similar to -v except that there is no execution
3830 of the commands and the echoed arguments are quoted. It
3831 is intended for use in shell scripts to capture the
3832 driver-generated command line. */
3833 verbose_only_flag++;
3834 verbose_flag = 1;
3835 do_save = false;
3836 break;
3838 case OPT_B:
3840 size_t len = strlen (arg);
3842 /* Catch the case where the user has forgotten to append a
3843 directory separator to the path. Note, they may be using
3844 -B to add an executable name prefix, eg "i386-elf-", in
3845 order to distinguish between multiple installations of
3846 GCC in the same directory. Hence we must check to see
3847 if appending a directory separator actually makes a
3848 valid directory name. */
3849 if (!IS_DIR_SEPARATOR (arg[len - 1])
3850 && is_directory (arg, false))
3852 char *tmp = XNEWVEC (char, len + 2);
3853 strcpy (tmp, arg);
3854 tmp[len] = DIR_SEPARATOR;
3855 tmp[++len] = 0;
3856 arg = tmp;
3859 add_prefix (&exec_prefixes, arg, NULL,
3860 PREFIX_PRIORITY_B_OPT, 0, 0);
3861 add_prefix (&startfile_prefixes, arg, NULL,
3862 PREFIX_PRIORITY_B_OPT, 0, 0);
3863 add_prefix (&include_prefixes, arg, NULL,
3864 PREFIX_PRIORITY_B_OPT, 0, 0);
3866 validated = true;
3867 break;
3869 case OPT_x:
3870 spec_lang = arg;
3871 if (!strcmp (spec_lang, "none"))
3872 /* Suppress the warning if -xnone comes after the last input
3873 file, because alternate command interfaces like g++ might
3874 find it useful to place -xnone after each input file. */
3875 spec_lang = 0;
3876 else
3877 last_language_n_infiles = n_infiles;
3878 do_save = false;
3879 break;
3881 case OPT_o:
3882 have_o = 1;
3883 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX) || defined(HAVE_TARGET_OBJECT_SUFFIX)
3884 arg = convert_filename (arg, ! have_c, 0);
3885 #endif
3886 output_file = arg;
3887 /* Save the output name in case -save-temps=obj was used. */
3888 save_temps_prefix = xstrdup (arg);
3889 /* On some systems, ld cannot handle "-o" without a space. So
3890 split the option from its argument. */
3891 save_switch ("-o", 1, &arg, validated, true);
3892 return true;
3894 case OPT_static_libgcc:
3895 case OPT_shared_libgcc:
3896 case OPT_static_libgfortran:
3897 case OPT_static_libstdc__:
3898 /* These are always valid, since gcc.c itself understands the
3899 first two, gfortranspec.c understands -static-libgfortran and
3900 g++spec.c understands -static-libstdc++ */
3901 validated = true;
3902 break;
3904 case OPT_fwpa:
3905 flag_wpa = "";
3906 break;
3908 case OPT_foffload_:
3909 handle_foffload_option (arg);
3910 break;
3912 default:
3913 /* Various driver options need no special processing at this
3914 point, having been handled in a prescan above or being
3915 handled by specs. */
3916 break;
3919 if (do_save)
3920 save_switch (decoded->canonical_option[0],
3921 decoded->canonical_option_num_elements - 1,
3922 &decoded->canonical_option[1], validated, true);
3923 return true;
3926 /* Put the driver's standard set of option handlers in *HANDLERS. */
3928 static void
3929 set_option_handlers (struct cl_option_handlers *handlers)
3931 handlers->unknown_option_callback = driver_unknown_option_callback;
3932 handlers->wrong_lang_callback = driver_wrong_lang_callback;
3933 handlers->num_handlers = 3;
3934 handlers->handlers[0].handler = driver_handle_option;
3935 handlers->handlers[0].mask = CL_DRIVER;
3936 handlers->handlers[1].handler = common_handle_option;
3937 handlers->handlers[1].mask = CL_COMMON;
3938 handlers->handlers[2].handler = target_handle_option;
3939 handlers->handlers[2].mask = CL_TARGET;
3942 /* Create the vector `switches' and its contents.
3943 Store its length in `n_switches'. */
3945 static void
3946 process_command (unsigned int decoded_options_count,
3947 struct cl_decoded_option *decoded_options)
3949 const char *temp;
3950 char *temp1;
3951 char *tooldir_prefix, *tooldir_prefix2;
3952 char *(*get_relative_prefix) (const char *, const char *,
3953 const char *) = NULL;
3954 struct cl_option_handlers handlers;
3955 unsigned int j;
3957 gcc_exec_prefix = getenv ("GCC_EXEC_PREFIX");
3959 n_switches = 0;
3960 n_infiles = 0;
3961 added_libraries = 0;
3963 /* Figure compiler version from version string. */
3965 compiler_version = temp1 = xstrdup (version_string);
3967 for (; *temp1; ++temp1)
3969 if (*temp1 == ' ')
3971 *temp1 = '\0';
3972 break;
3976 /* Handle any -no-canonical-prefixes flag early, to assign the function
3977 that builds relative prefixes. This function creates default search
3978 paths that are needed later in normal option handling. */
3980 for (j = 1; j < decoded_options_count; j++)
3982 if (decoded_options[j].opt_index == OPT_no_canonical_prefixes)
3984 get_relative_prefix = make_relative_prefix_ignore_links;
3985 break;
3988 if (! get_relative_prefix)
3989 get_relative_prefix = make_relative_prefix;
3991 /* Set up the default search paths. If there is no GCC_EXEC_PREFIX,
3992 see if we can create it from the pathname specified in
3993 decoded_options[0].arg. */
3995 gcc_libexec_prefix = standard_libexec_prefix;
3996 #ifndef VMS
3997 /* FIXME: make_relative_prefix doesn't yet work for VMS. */
3998 if (!gcc_exec_prefix)
4000 gcc_exec_prefix = get_relative_prefix (decoded_options[0].arg,
4001 standard_bindir_prefix,
4002 standard_exec_prefix);
4003 gcc_libexec_prefix = get_relative_prefix (decoded_options[0].arg,
4004 standard_bindir_prefix,
4005 standard_libexec_prefix);
4006 if (gcc_exec_prefix)
4007 xputenv (concat ("GCC_EXEC_PREFIX=", gcc_exec_prefix, NULL));
4009 else
4011 /* make_relative_prefix requires a program name, but
4012 GCC_EXEC_PREFIX is typically a directory name with a trailing
4013 / (which is ignored by make_relative_prefix), so append a
4014 program name. */
4015 char *tmp_prefix = concat (gcc_exec_prefix, "gcc", NULL);
4016 gcc_libexec_prefix = get_relative_prefix (tmp_prefix,
4017 standard_exec_prefix,
4018 standard_libexec_prefix);
4020 /* The path is unrelocated, so fallback to the original setting. */
4021 if (!gcc_libexec_prefix)
4022 gcc_libexec_prefix = standard_libexec_prefix;
4024 free (tmp_prefix);
4026 #else
4027 #endif
4028 /* From this point onward, gcc_exec_prefix is non-null if the toolchain
4029 is relocated. The toolchain was either relocated using GCC_EXEC_PREFIX
4030 or an automatically created GCC_EXEC_PREFIX from
4031 decoded_options[0].arg. */
4033 /* Do language-specific adjustment/addition of flags. */
4034 lang_specific_driver (&decoded_options, &decoded_options_count,
4035 &added_libraries);
4037 if (gcc_exec_prefix)
4039 int len = strlen (gcc_exec_prefix);
4041 if (len > (int) sizeof ("/lib/gcc/") - 1
4042 && (IS_DIR_SEPARATOR (gcc_exec_prefix[len-1])))
4044 temp = gcc_exec_prefix + len - sizeof ("/lib/gcc/") + 1;
4045 if (IS_DIR_SEPARATOR (*temp)
4046 && filename_ncmp (temp + 1, "lib", 3) == 0
4047 && IS_DIR_SEPARATOR (temp[4])
4048 && filename_ncmp (temp + 5, "gcc", 3) == 0)
4049 len -= sizeof ("/lib/gcc/") - 1;
4052 set_std_prefix (gcc_exec_prefix, len);
4053 add_prefix (&exec_prefixes, gcc_libexec_prefix, "GCC",
4054 PREFIX_PRIORITY_LAST, 0, 0);
4055 add_prefix (&startfile_prefixes, gcc_exec_prefix, "GCC",
4056 PREFIX_PRIORITY_LAST, 0, 0);
4059 /* COMPILER_PATH and LIBRARY_PATH have values
4060 that are lists of directory names with colons. */
4062 temp = getenv ("COMPILER_PATH");
4063 if (temp)
4065 const char *startp, *endp;
4066 char *nstore = (char *) alloca (strlen (temp) + 3);
4068 startp = endp = temp;
4069 while (1)
4071 if (*endp == PATH_SEPARATOR || *endp == 0)
4073 strncpy (nstore, startp, endp - startp);
4074 if (endp == startp)
4075 strcpy (nstore, concat (".", dir_separator_str, NULL));
4076 else if (!IS_DIR_SEPARATOR (endp[-1]))
4078 nstore[endp - startp] = DIR_SEPARATOR;
4079 nstore[endp - startp + 1] = 0;
4081 else
4082 nstore[endp - startp] = 0;
4083 add_prefix (&exec_prefixes, nstore, 0,
4084 PREFIX_PRIORITY_LAST, 0, 0);
4085 add_prefix (&include_prefixes, nstore, 0,
4086 PREFIX_PRIORITY_LAST, 0, 0);
4087 if (*endp == 0)
4088 break;
4089 endp = startp = endp + 1;
4091 else
4092 endp++;
4096 temp = getenv (LIBRARY_PATH_ENV);
4097 if (temp && *cross_compile == '0')
4099 const char *startp, *endp;
4100 char *nstore = (char *) alloca (strlen (temp) + 3);
4102 startp = endp = temp;
4103 while (1)
4105 if (*endp == PATH_SEPARATOR || *endp == 0)
4107 strncpy (nstore, startp, endp - startp);
4108 if (endp == startp)
4109 strcpy (nstore, concat (".", dir_separator_str, NULL));
4110 else if (!IS_DIR_SEPARATOR (endp[-1]))
4112 nstore[endp - startp] = DIR_SEPARATOR;
4113 nstore[endp - startp + 1] = 0;
4115 else
4116 nstore[endp - startp] = 0;
4117 add_prefix (&startfile_prefixes, nstore, NULL,
4118 PREFIX_PRIORITY_LAST, 0, 1);
4119 if (*endp == 0)
4120 break;
4121 endp = startp = endp + 1;
4123 else
4124 endp++;
4128 /* Use LPATH like LIBRARY_PATH (for the CMU build program). */
4129 temp = getenv ("LPATH");
4130 if (temp && *cross_compile == '0')
4132 const char *startp, *endp;
4133 char *nstore = (char *) alloca (strlen (temp) + 3);
4135 startp = endp = temp;
4136 while (1)
4138 if (*endp == PATH_SEPARATOR || *endp == 0)
4140 strncpy (nstore, startp, endp - startp);
4141 if (endp == startp)
4142 strcpy (nstore, concat (".", dir_separator_str, NULL));
4143 else if (!IS_DIR_SEPARATOR (endp[-1]))
4145 nstore[endp - startp] = DIR_SEPARATOR;
4146 nstore[endp - startp + 1] = 0;
4148 else
4149 nstore[endp - startp] = 0;
4150 add_prefix (&startfile_prefixes, nstore, NULL,
4151 PREFIX_PRIORITY_LAST, 0, 1);
4152 if (*endp == 0)
4153 break;
4154 endp = startp = endp + 1;
4156 else
4157 endp++;
4161 /* Process the options and store input files and switches in their
4162 vectors. */
4164 last_language_n_infiles = -1;
4166 set_option_handlers (&handlers);
4168 for (j = 1; j < decoded_options_count; j++)
4170 switch (decoded_options[j].opt_index)
4172 case OPT_S:
4173 case OPT_c:
4174 case OPT_E:
4175 have_c = 1;
4176 break;
4178 if (have_c)
4179 break;
4182 for (j = 1; j < decoded_options_count; j++)
4184 if (decoded_options[j].opt_index == OPT_SPECIAL_input_file)
4186 const char *arg = decoded_options[j].arg;
4187 const char *p = strrchr (arg, '@');
4188 char *fname;
4189 long offset;
4190 int consumed;
4191 #ifdef HAVE_TARGET_OBJECT_SUFFIX
4192 arg = convert_filename (arg, 0, access (arg, F_OK));
4193 #endif
4194 /* For LTO static archive support we handle input file
4195 specifications that are composed of a filename and
4196 an offset like FNAME@OFFSET. */
4197 if (p
4198 && p != arg
4199 && sscanf (p, "@%li%n", &offset, &consumed) >= 1
4200 && strlen (p) == (unsigned int)consumed)
4202 fname = (char *)xmalloc (p - arg + 1);
4203 memcpy (fname, arg, p - arg);
4204 fname[p - arg] = '\0';
4205 /* Only accept non-stdin and existing FNAME parts, otherwise
4206 try with the full name. */
4207 if (strcmp (fname, "-") == 0 || access (fname, F_OK) < 0)
4209 free (fname);
4210 fname = xstrdup (arg);
4213 else
4214 fname = xstrdup (arg);
4216 if (strcmp (fname, "-") != 0 && access (fname, F_OK) < 0)
4217 perror_with_name (fname);
4218 else
4219 add_infile (arg, spec_lang);
4221 free (fname);
4222 continue;
4225 read_cmdline_option (&global_options, &global_options_set,
4226 decoded_options + j, UNKNOWN_LOCATION,
4227 CL_DRIVER, &handlers, global_dc);
4230 if (output_file
4231 && strcmp (output_file, "-") != 0
4232 && strcmp (output_file, HOST_BIT_BUCKET) != 0)
4234 int i;
4235 for (i = 0; i < n_infiles; i++)
4236 if ((!infiles[i].language || infiles[i].language[0] != '*')
4237 && canonical_filename_eq (infiles[i].name, output_file))
4238 fatal_error (input_location,
4239 "input file %qs is the same as output file",
4240 output_file);
4243 /* If -save-temps=obj and -o name, create the prefix to use for %b.
4244 Otherwise just make -save-temps=obj the same as -save-temps=cwd. */
4245 if (save_temps_flag == SAVE_TEMPS_OBJ && save_temps_prefix != NULL)
4247 save_temps_length = strlen (save_temps_prefix);
4248 temp = strrchr (lbasename (save_temps_prefix), '.');
4249 if (temp)
4251 save_temps_length -= strlen (temp);
4252 save_temps_prefix[save_temps_length] = '\0';
4256 else if (save_temps_prefix != NULL)
4258 free (save_temps_prefix);
4259 save_temps_prefix = NULL;
4262 if (save_temps_flag && use_pipes)
4264 /* -save-temps overrides -pipe, so that temp files are produced */
4265 if (save_temps_flag)
4266 warning (0, "-pipe ignored because -save-temps specified");
4267 use_pipes = 0;
4270 if (!compare_debug)
4272 const char *gcd = getenv ("GCC_COMPARE_DEBUG");
4274 if (gcd && gcd[0] == '-')
4276 compare_debug = 2;
4277 compare_debug_opt = gcd;
4279 else if (gcd && *gcd && strcmp (gcd, "0"))
4281 compare_debug = 3;
4282 compare_debug_opt = "-gtoggle";
4285 else if (compare_debug < 0)
4287 compare_debug = 0;
4288 gcc_assert (!compare_debug_opt);
4291 /* Set up the search paths. We add directories that we expect to
4292 contain GNU Toolchain components before directories specified by
4293 the machine description so that we will find GNU components (like
4294 the GNU assembler) before those of the host system. */
4296 /* If we don't know where the toolchain has been installed, use the
4297 configured-in locations. */
4298 if (!gcc_exec_prefix)
4300 #ifndef OS2
4301 add_prefix (&exec_prefixes, standard_libexec_prefix, "GCC",
4302 PREFIX_PRIORITY_LAST, 1, 0);
4303 add_prefix (&exec_prefixes, standard_libexec_prefix, "BINUTILS",
4304 PREFIX_PRIORITY_LAST, 2, 0);
4305 add_prefix (&exec_prefixes, standard_exec_prefix, "BINUTILS",
4306 PREFIX_PRIORITY_LAST, 2, 0);
4307 #endif
4308 add_prefix (&startfile_prefixes, standard_exec_prefix, "BINUTILS",
4309 PREFIX_PRIORITY_LAST, 1, 0);
4312 gcc_assert (!IS_ABSOLUTE_PATH (tooldir_base_prefix));
4313 tooldir_prefix2 = concat (tooldir_base_prefix, spec_host_machine,
4314 dir_separator_str, NULL);
4316 /* Look for tools relative to the location from which the driver is
4317 running, or, if that is not available, the configured prefix. */
4318 tooldir_prefix
4319 = concat (gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
4320 spec_host_machine, dir_separator_str, spec_version,
4321 accel_dir_suffix, dir_separator_str, tooldir_prefix2, NULL);
4322 free (tooldir_prefix2);
4324 add_prefix (&exec_prefixes,
4325 concat (tooldir_prefix, "bin", dir_separator_str, NULL),
4326 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 0);
4327 add_prefix (&startfile_prefixes,
4328 concat (tooldir_prefix, "lib", dir_separator_str, NULL),
4329 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 1);
4330 free (tooldir_prefix);
4332 #if defined(TARGET_SYSTEM_ROOT_RELOCATABLE) && !defined(VMS)
4333 /* If the normal TARGET_SYSTEM_ROOT is inside of $exec_prefix,
4334 then consider it to relocate with the rest of the GCC installation
4335 if GCC_EXEC_PREFIX is set.
4336 ``make_relative_prefix'' is not compiled for VMS, so don't call it. */
4337 if (target_system_root && !target_system_root_changed && gcc_exec_prefix)
4339 char *tmp_prefix = get_relative_prefix (decoded_options[0].arg,
4340 standard_bindir_prefix,
4341 target_system_root);
4342 if (tmp_prefix && access_check (tmp_prefix, F_OK) == 0)
4344 target_system_root = tmp_prefix;
4345 target_system_root_changed = 1;
4348 #endif
4350 /* More prefixes are enabled in main, after we read the specs file
4351 and determine whether this is cross-compilation or not. */
4353 if (n_infiles == last_language_n_infiles && spec_lang != 0)
4354 warning (0, "%<-x %s%> after last input file has no effect", spec_lang);
4356 /* Synthesize -fcompare-debug flag from the GCC_COMPARE_DEBUG
4357 environment variable. */
4358 if (compare_debug == 2 || compare_debug == 3)
4360 const char *opt = concat ("-fcompare-debug=", compare_debug_opt, NULL);
4361 save_switch (opt, 0, NULL, false, true);
4362 compare_debug = 1;
4365 /* Ensure we only invoke each subprocess once. */
4366 if (print_subprocess_help || print_help_list || print_version)
4368 n_infiles = 0;
4370 /* Create a dummy input file, so that we can pass
4371 the help option on to the various sub-processes. */
4372 add_infile ("help-dummy", "c");
4375 alloc_switch ();
4376 switches[n_switches].part1 = 0;
4377 alloc_infile ();
4378 infiles[n_infiles].name = 0;
4381 /* Store switches not filtered out by %<S in spec in COLLECT_GCC_OPTIONS
4382 and place that in the environment. */
4384 static void
4385 set_collect_gcc_options (void)
4387 int i;
4388 int first_time;
4390 /* Build COLLECT_GCC_OPTIONS to have all of the options specified to
4391 the compiler. */
4392 obstack_grow (&collect_obstack, "COLLECT_GCC_OPTIONS=",
4393 sizeof ("COLLECT_GCC_OPTIONS=") - 1);
4395 first_time = TRUE;
4396 for (i = 0; (int) i < n_switches; i++)
4398 const char *const *args;
4399 const char *p, *q;
4400 if (!first_time)
4401 obstack_grow (&collect_obstack, " ", 1);
4403 first_time = FALSE;
4405 /* Ignore elided switches. */
4406 if ((switches[i].live_cond
4407 & (SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC))
4408 == SWITCH_IGNORE)
4409 continue;
4411 obstack_grow (&collect_obstack, "'-", 2);
4412 q = switches[i].part1;
4413 while ((p = strchr (q, '\'')))
4415 obstack_grow (&collect_obstack, q, p - q);
4416 obstack_grow (&collect_obstack, "'\\''", 4);
4417 q = ++p;
4419 obstack_grow (&collect_obstack, q, strlen (q));
4420 obstack_grow (&collect_obstack, "'", 1);
4422 for (args = switches[i].args; args && *args; args++)
4424 obstack_grow (&collect_obstack, " '", 2);
4425 q = *args;
4426 while ((p = strchr (q, '\'')))
4428 obstack_grow (&collect_obstack, q, p - q);
4429 obstack_grow (&collect_obstack, "'\\''", 4);
4430 q = ++p;
4432 obstack_grow (&collect_obstack, q, strlen (q));
4433 obstack_grow (&collect_obstack, "'", 1);
4436 obstack_grow (&collect_obstack, "\0", 1);
4437 xputenv (XOBFINISH (&collect_obstack, char *));
4440 /* Process a spec string, accumulating and running commands. */
4442 /* These variables describe the input file name.
4443 input_file_number is the index on outfiles of this file,
4444 so that the output file name can be stored for later use by %o.
4445 input_basename is the start of the part of the input file
4446 sans all directory names, and basename_length is the number
4447 of characters starting there excluding the suffix .c or whatever. */
4449 static const char *gcc_input_filename;
4450 static int input_file_number;
4451 size_t input_filename_length;
4452 static int basename_length;
4453 static int suffixed_basename_length;
4454 static const char *input_basename;
4455 static const char *input_suffix;
4456 #ifndef HOST_LACKS_INODE_NUMBERS
4457 static struct stat input_stat;
4458 #endif
4459 static int input_stat_set;
4461 /* The compiler used to process the current input file. */
4462 static struct compiler *input_file_compiler;
4464 /* These are variables used within do_spec and do_spec_1. */
4466 /* Nonzero if an arg has been started and not yet terminated
4467 (with space, tab or newline). */
4468 static int arg_going;
4470 /* Nonzero means %d or %g has been seen; the next arg to be terminated
4471 is a temporary file name. */
4472 static int delete_this_arg;
4474 /* Nonzero means %w has been seen; the next arg to be terminated
4475 is the output file name of this compilation. */
4476 static int this_is_output_file;
4478 /* Nonzero means %s has been seen; the next arg to be terminated
4479 is the name of a library file and we should try the standard
4480 search dirs for it. */
4481 static int this_is_library_file;
4483 /* Nonzero means %T has been seen; the next arg to be terminated
4484 is the name of a linker script and we should try all of the
4485 standard search dirs for it. If it is found insert a --script
4486 command line switch and then substitute the full path in place,
4487 otherwise generate an error message. */
4488 static int this_is_linker_script;
4490 /* Nonzero means that the input of this command is coming from a pipe. */
4491 static int input_from_pipe;
4493 /* Nonnull means substitute this for any suffix when outputting a switches
4494 arguments. */
4495 static const char *suffix_subst;
4497 /* If there is an argument being accumulated, terminate it and store it. */
4499 static void
4500 end_going_arg (void)
4502 if (arg_going)
4504 const char *string;
4506 obstack_1grow (&obstack, 0);
4507 string = XOBFINISH (&obstack, const char *);
4508 if (this_is_library_file)
4509 string = find_file (string);
4510 if (this_is_linker_script)
4512 char * full_script_path = find_a_file (&startfile_prefixes, string, R_OK, true);
4514 if (full_script_path == NULL)
4516 error ("unable to locate default linker script %qs in the library search paths", string);
4517 /* Script was not found on search path. */
4518 return;
4520 store_arg ("--script", false, false);
4521 string = full_script_path;
4523 store_arg (string, delete_this_arg, this_is_output_file);
4524 if (this_is_output_file)
4525 outfiles[input_file_number] = string;
4526 arg_going = 0;
4531 /* Parse the WRAPPER string which is a comma separated list of the command line
4532 and insert them into the beginning of argbuf. */
4534 static void
4535 insert_wrapper (const char *wrapper)
4537 int n = 0;
4538 int i;
4539 char *buf = xstrdup (wrapper);
4540 char *p = buf;
4541 unsigned int old_length = argbuf.length ();
4545 n++;
4546 while (*p == ',')
4547 p++;
4549 while ((p = strchr (p, ',')) != NULL);
4551 argbuf.safe_grow (old_length + n);
4552 memmove (argbuf.address () + n,
4553 argbuf.address (),
4554 old_length * sizeof (const_char_p));
4556 i = 0;
4557 p = buf;
4560 while (*p == ',')
4562 *p = 0;
4563 p++;
4565 argbuf[i] = p;
4566 i++;
4568 while ((p = strchr (p, ',')) != NULL);
4569 gcc_assert (i == n);
4572 /* Process the spec SPEC and run the commands specified therein.
4573 Returns 0 if the spec is successfully processed; -1 if failed. */
4576 do_spec (const char *spec)
4578 int value;
4580 value = do_spec_2 (spec);
4582 /* Force out any unfinished command.
4583 If -pipe, this forces out the last command if it ended in `|'. */
4584 if (value == 0)
4586 if (argbuf.length () > 0
4587 && !strcmp (argbuf.last (), "|"))
4588 argbuf.pop ();
4590 set_collect_gcc_options ();
4592 if (argbuf.length () > 0)
4593 value = execute ();
4596 return value;
4599 static int
4600 do_spec_2 (const char *spec)
4602 int result;
4604 clear_args ();
4605 arg_going = 0;
4606 delete_this_arg = 0;
4607 this_is_output_file = 0;
4608 this_is_library_file = 0;
4609 this_is_linker_script = 0;
4610 input_from_pipe = 0;
4611 suffix_subst = NULL;
4613 result = do_spec_1 (spec, 0, NULL);
4615 end_going_arg ();
4617 return result;
4621 /* Process the given spec string and add any new options to the end
4622 of the switches/n_switches array. */
4624 static void
4625 do_option_spec (const char *name, const char *spec)
4627 unsigned int i, value_count, value_len;
4628 const char *p, *q, *value;
4629 char *tmp_spec, *tmp_spec_p;
4631 if (configure_default_options[0].name == NULL)
4632 return;
4634 for (i = 0; i < ARRAY_SIZE (configure_default_options); i++)
4635 if (strcmp (configure_default_options[i].name, name) == 0)
4636 break;
4637 if (i == ARRAY_SIZE (configure_default_options))
4638 return;
4640 value = configure_default_options[i].value;
4641 value_len = strlen (value);
4643 /* Compute the size of the final spec. */
4644 value_count = 0;
4645 p = spec;
4646 while ((p = strstr (p, "%(VALUE)")) != NULL)
4648 p ++;
4649 value_count ++;
4652 /* Replace each %(VALUE) by the specified value. */
4653 tmp_spec = (char *) alloca (strlen (spec) + 1
4654 + value_count * (value_len - strlen ("%(VALUE)")));
4655 tmp_spec_p = tmp_spec;
4656 q = spec;
4657 while ((p = strstr (q, "%(VALUE)")) != NULL)
4659 memcpy (tmp_spec_p, q, p - q);
4660 tmp_spec_p = tmp_spec_p + (p - q);
4661 memcpy (tmp_spec_p, value, value_len);
4662 tmp_spec_p += value_len;
4663 q = p + strlen ("%(VALUE)");
4665 strcpy (tmp_spec_p, q);
4667 do_self_spec (tmp_spec);
4670 /* Process the given spec string and add any new options to the end
4671 of the switches/n_switches array. */
4673 static void
4674 do_self_spec (const char *spec)
4676 int i;
4678 do_spec_2 (spec);
4679 do_spec_1 (" ", 0, NULL);
4681 /* Mark %<S switches processed by do_self_spec to be ignored permanently.
4682 do_self_specs adds the replacements to switches array, so it shouldn't
4683 be processed afterwards. */
4684 for (i = 0; i < n_switches; i++)
4685 if ((switches[i].live_cond & SWITCH_IGNORE))
4686 switches[i].live_cond |= SWITCH_IGNORE_PERMANENTLY;
4688 if (argbuf.length () > 0)
4690 const char **argbuf_copy;
4691 struct cl_decoded_option *decoded_options;
4692 struct cl_option_handlers handlers;
4693 unsigned int decoded_options_count;
4694 unsigned int j;
4696 /* Create a copy of argbuf with a dummy argv[0] entry for
4697 decode_cmdline_options_to_array. */
4698 argbuf_copy = XNEWVEC (const char *,
4699 argbuf.length () + 1);
4700 argbuf_copy[0] = "";
4701 memcpy (argbuf_copy + 1, argbuf.address (),
4702 argbuf.length () * sizeof (const char *));
4704 decode_cmdline_options_to_array (argbuf.length () + 1,
4705 argbuf_copy,
4706 CL_DRIVER, &decoded_options,
4707 &decoded_options_count);
4708 free (argbuf_copy);
4710 set_option_handlers (&handlers);
4712 for (j = 1; j < decoded_options_count; j++)
4714 switch (decoded_options[j].opt_index)
4716 case OPT_SPECIAL_input_file:
4717 /* Specs should only generate options, not input
4718 files. */
4719 if (strcmp (decoded_options[j].arg, "-") != 0)
4720 fatal_error (input_location,
4721 "switch %qs does not start with %<-%>",
4722 decoded_options[j].arg);
4723 else
4724 fatal_error (input_location,
4725 "spec-generated switch is just %<-%>");
4726 break;
4728 case OPT_fcompare_debug_second:
4729 case OPT_fcompare_debug:
4730 case OPT_fcompare_debug_:
4731 case OPT_o:
4732 /* Avoid duplicate processing of some options from
4733 compare-debug specs; just save them here. */
4734 save_switch (decoded_options[j].canonical_option[0],
4735 (decoded_options[j].canonical_option_num_elements
4736 - 1),
4737 &decoded_options[j].canonical_option[1], false, true);
4738 break;
4740 default:
4741 read_cmdline_option (&global_options, &global_options_set,
4742 decoded_options + j, UNKNOWN_LOCATION,
4743 CL_DRIVER, &handlers, global_dc);
4744 break;
4748 free (decoded_options);
4750 alloc_switch ();
4751 switches[n_switches].part1 = 0;
4755 /* Callback for processing %D and %I specs. */
4757 struct spec_path_info {
4758 const char *option;
4759 const char *append;
4760 size_t append_len;
4761 bool omit_relative;
4762 bool separate_options;
4765 static void *
4766 spec_path (char *path, void *data)
4768 struct spec_path_info *info = (struct spec_path_info *) data;
4769 size_t len = 0;
4770 char save = 0;
4772 if (info->omit_relative && !IS_ABSOLUTE_PATH (path))
4773 return NULL;
4775 if (info->append_len != 0)
4777 len = strlen (path);
4778 memcpy (path + len, info->append, info->append_len + 1);
4781 if (!is_directory (path, true))
4782 return NULL;
4784 do_spec_1 (info->option, 1, NULL);
4785 if (info->separate_options)
4786 do_spec_1 (" ", 0, NULL);
4788 if (info->append_len == 0)
4790 len = strlen (path);
4791 save = path[len - 1];
4792 if (IS_DIR_SEPARATOR (path[len - 1]))
4793 path[len - 1] = '\0';
4796 do_spec_1 (path, 1, NULL);
4797 do_spec_1 (" ", 0, NULL);
4799 /* Must not damage the original path. */
4800 if (info->append_len == 0)
4801 path[len - 1] = save;
4803 return NULL;
4806 /* Create a temporary FILE with the contents of ARGV. Add @FILE to the
4807 argument list. */
4809 static void
4810 create_at_file (char **argv)
4812 char *temp_file = make_temp_file ("");
4813 char *at_argument = concat ("@", temp_file, NULL);
4814 FILE *f = fopen (temp_file, "w");
4815 int status;
4817 if (f == NULL)
4818 fatal_error (input_location, "could not open temporary response file %s",
4819 temp_file);
4821 status = writeargv (argv, f);
4823 if (status)
4824 fatal_error (input_location,
4825 "could not write to temporary response file %s",
4826 temp_file);
4828 status = fclose (f);
4830 if (EOF == status)
4831 fatal_error (input_location, "could not close temporary response file %s",
4832 temp_file);
4834 store_arg (at_argument, 0, 0);
4836 record_temp_file (temp_file, !save_temps_flag, !save_temps_flag);
4839 /* True if we should compile INFILE. */
4841 static bool
4842 compile_input_file_p (struct infile *infile)
4844 if ((!infile->language) || (infile->language[0] != '*'))
4845 if (infile->incompiler == input_file_compiler)
4846 return true;
4847 return false;
4850 /* Process each member of VEC as a spec. */
4852 static void
4853 do_specs_vec (vec<char_p> vec)
4855 unsigned ix;
4856 char *opt;
4858 FOR_EACH_VEC_ELT (vec, ix, opt)
4860 do_spec_1 (opt, 1, NULL);
4861 /* Make each accumulated option a separate argument. */
4862 do_spec_1 (" ", 0, NULL);
4866 /* Process the sub-spec SPEC as a portion of a larger spec.
4867 This is like processing a whole spec except that we do
4868 not initialize at the beginning and we do not supply a
4869 newline by default at the end.
4870 INSWITCH nonzero means don't process %-sequences in SPEC;
4871 in this case, % is treated as an ordinary character.
4872 This is used while substituting switches.
4873 INSWITCH nonzero also causes SPC not to terminate an argument.
4875 Value is zero unless a line was finished
4876 and the command on that line reported an error. */
4878 static int
4879 do_spec_1 (const char *spec, int inswitch, const char *soft_matched_part)
4881 const char *p = spec;
4882 int c;
4883 int i;
4884 int value;
4886 /* If it's an empty string argument to a switch, keep it as is. */
4887 if (inswitch && !*p)
4888 arg_going = 1;
4890 while ((c = *p++))
4891 /* If substituting a switch, treat all chars like letters.
4892 Otherwise, NL, SPC, TAB and % are special. */
4893 switch (inswitch ? 'a' : c)
4895 case '\n':
4896 end_going_arg ();
4898 if (argbuf.length () > 0
4899 && !strcmp (argbuf.last (), "|"))
4901 /* A `|' before the newline means use a pipe here,
4902 but only if -pipe was specified.
4903 Otherwise, execute now and don't pass the `|' as an arg. */
4904 if (use_pipes)
4906 input_from_pipe = 1;
4907 break;
4909 else
4910 argbuf.pop ();
4913 set_collect_gcc_options ();
4915 if (argbuf.length () > 0)
4917 value = execute ();
4918 if (value)
4919 return value;
4921 /* Reinitialize for a new command, and for a new argument. */
4922 clear_args ();
4923 arg_going = 0;
4924 delete_this_arg = 0;
4925 this_is_output_file = 0;
4926 this_is_library_file = 0;
4927 this_is_linker_script = 0;
4928 input_from_pipe = 0;
4929 break;
4931 case '|':
4932 end_going_arg ();
4934 /* Use pipe */
4935 obstack_1grow (&obstack, c);
4936 arg_going = 1;
4937 break;
4939 case '\t':
4940 case ' ':
4941 end_going_arg ();
4943 /* Reinitialize for a new argument. */
4944 delete_this_arg = 0;
4945 this_is_output_file = 0;
4946 this_is_library_file = 0;
4947 this_is_linker_script = 0;
4948 break;
4950 case '%':
4951 switch (c = *p++)
4953 case 0:
4954 fatal_error (input_location, "spec %qs invalid", spec);
4956 case 'b':
4957 if (save_temps_length)
4958 obstack_grow (&obstack, save_temps_prefix, save_temps_length);
4959 else
4960 obstack_grow (&obstack, input_basename, basename_length);
4961 if (compare_debug < 0)
4962 obstack_grow (&obstack, ".gk", 3);
4963 arg_going = 1;
4964 break;
4966 case 'B':
4967 if (save_temps_length)
4968 obstack_grow (&obstack, save_temps_prefix, save_temps_length);
4969 else
4970 obstack_grow (&obstack, input_basename, suffixed_basename_length);
4971 if (compare_debug < 0)
4972 obstack_grow (&obstack, ".gk", 3);
4973 arg_going = 1;
4974 break;
4976 case 'd':
4977 delete_this_arg = 2;
4978 break;
4980 /* Dump out the directories specified with LIBRARY_PATH,
4981 followed by the absolute directories
4982 that we search for startfiles. */
4983 case 'D':
4985 struct spec_path_info info;
4987 info.option = "-L";
4988 info.append_len = 0;
4989 #ifdef RELATIVE_PREFIX_NOT_LINKDIR
4990 /* Used on systems which record the specified -L dirs
4991 and use them to search for dynamic linking.
4992 Relative directories always come from -B,
4993 and it is better not to use them for searching
4994 at run time. In particular, stage1 loses. */
4995 info.omit_relative = true;
4996 #else
4997 info.omit_relative = false;
4998 #endif
4999 info.separate_options = false;
5001 for_each_path (&startfile_prefixes, true, 0, spec_path, &info);
5003 break;
5005 case 'e':
5006 /* %efoo means report an error with `foo' as error message
5007 and don't execute any more commands for this file. */
5009 const char *q = p;
5010 char *buf;
5011 while (*p != 0 && *p != '\n')
5012 p++;
5013 buf = (char *) alloca (p - q + 1);
5014 strncpy (buf, q, p - q);
5015 buf[p - q] = 0;
5016 error ("%s", _(buf));
5017 return -1;
5019 break;
5020 case 'n':
5021 /* %nfoo means report a notice with `foo' on stderr. */
5023 const char *q = p;
5024 char *buf;
5025 while (*p != 0 && *p != '\n')
5026 p++;
5027 buf = (char *) alloca (p - q + 1);
5028 strncpy (buf, q, p - q);
5029 buf[p - q] = 0;
5030 inform (0, "%s", _(buf));
5031 if (*p)
5032 p++;
5034 break;
5036 case 'j':
5038 struct stat st;
5040 /* If save_temps_flag is off, and the HOST_BIT_BUCKET is
5041 defined, and it is not a directory, and it is
5042 writable, use it. Otherwise, treat this like any
5043 other temporary file. */
5045 if ((!save_temps_flag)
5046 && (stat (HOST_BIT_BUCKET, &st) == 0) && (!S_ISDIR (st.st_mode))
5047 && (access (HOST_BIT_BUCKET, W_OK) == 0))
5049 obstack_grow (&obstack, HOST_BIT_BUCKET,
5050 strlen (HOST_BIT_BUCKET));
5051 delete_this_arg = 0;
5052 arg_going = 1;
5053 break;
5056 goto create_temp_file;
5057 case '|':
5058 if (use_pipes)
5060 obstack_1grow (&obstack, '-');
5061 delete_this_arg = 0;
5062 arg_going = 1;
5064 /* consume suffix */
5065 while (*p == '.' || ISALNUM ((unsigned char) *p))
5066 p++;
5067 if (p[0] == '%' && p[1] == 'O')
5068 p += 2;
5070 break;
5072 goto create_temp_file;
5073 case 'm':
5074 if (use_pipes)
5076 /* consume suffix */
5077 while (*p == '.' || ISALNUM ((unsigned char) *p))
5078 p++;
5079 if (p[0] == '%' && p[1] == 'O')
5080 p += 2;
5082 break;
5084 goto create_temp_file;
5085 case 'g':
5086 case 'u':
5087 case 'U':
5088 create_temp_file:
5090 struct temp_name *t;
5091 int suffix_length;
5092 const char *suffix = p;
5093 char *saved_suffix = NULL;
5095 while (*p == '.' || ISALNUM ((unsigned char) *p))
5096 p++;
5097 suffix_length = p - suffix;
5098 if (p[0] == '%' && p[1] == 'O')
5100 p += 2;
5101 /* We don't support extra suffix characters after %O. */
5102 if (*p == '.' || ISALNUM ((unsigned char) *p))
5103 fatal_error (input_location,
5104 "spec %qs has invalid %<%%0%c%>", spec, *p);
5105 if (suffix_length == 0)
5106 suffix = TARGET_OBJECT_SUFFIX;
5107 else
5109 saved_suffix
5110 = XNEWVEC (char, suffix_length
5111 + strlen (TARGET_OBJECT_SUFFIX) + 1);
5112 strncpy (saved_suffix, suffix, suffix_length);
5113 strcpy (saved_suffix + suffix_length,
5114 TARGET_OBJECT_SUFFIX);
5116 suffix_length += strlen (TARGET_OBJECT_SUFFIX);
5119 if (compare_debug < 0)
5121 suffix = concat (".gk", suffix, NULL);
5122 suffix_length += 3;
5125 /* If -save-temps=obj and -o were specified, use that for the
5126 temp file. */
5127 if (save_temps_length)
5129 char *tmp;
5130 temp_filename_length
5131 = save_temps_length + suffix_length + 1;
5132 tmp = (char *) alloca (temp_filename_length);
5133 memcpy (tmp, save_temps_prefix, save_temps_length);
5134 memcpy (tmp + save_temps_length, suffix, suffix_length);
5135 tmp[save_temps_length + suffix_length] = '\0';
5136 temp_filename = save_string (tmp, save_temps_length
5137 + suffix_length);
5138 obstack_grow (&obstack, temp_filename,
5139 temp_filename_length);
5140 arg_going = 1;
5141 delete_this_arg = 0;
5142 break;
5145 /* If the gcc_input_filename has the same suffix specified
5146 for the %g, %u, or %U, and -save-temps is specified,
5147 we could end up using that file as an intermediate
5148 thus clobbering the user's source file (.e.g.,
5149 gcc -save-temps foo.s would clobber foo.s with the
5150 output of cpp0). So check for this condition and
5151 generate a temp file as the intermediate. */
5153 if (save_temps_flag)
5155 char *tmp;
5156 temp_filename_length = basename_length + suffix_length + 1;
5157 tmp = (char *) alloca (temp_filename_length);
5158 memcpy (tmp, input_basename, basename_length);
5159 memcpy (tmp + basename_length, suffix, suffix_length);
5160 tmp[basename_length + suffix_length] = '\0';
5161 temp_filename = tmp;
5163 if (filename_cmp (temp_filename, gcc_input_filename) != 0)
5165 #ifndef HOST_LACKS_INODE_NUMBERS
5166 struct stat st_temp;
5168 /* Note, set_input() resets input_stat_set to 0. */
5169 if (input_stat_set == 0)
5171 input_stat_set = stat (gcc_input_filename,
5172 &input_stat);
5173 if (input_stat_set >= 0)
5174 input_stat_set = 1;
5177 /* If we have the stat for the gcc_input_filename
5178 and we can do the stat for the temp_filename
5179 then the they could still refer to the same
5180 file if st_dev/st_ino's are the same. */
5181 if (input_stat_set != 1
5182 || stat (temp_filename, &st_temp) < 0
5183 || input_stat.st_dev != st_temp.st_dev
5184 || input_stat.st_ino != st_temp.st_ino)
5185 #else
5186 /* Just compare canonical pathnames. */
5187 char* input_realname = lrealpath (gcc_input_filename);
5188 char* temp_realname = lrealpath (temp_filename);
5189 bool files_differ = filename_cmp (input_realname, temp_realname);
5190 free (input_realname);
5191 free (temp_realname);
5192 if (files_differ)
5193 #endif
5195 temp_filename = save_string (temp_filename,
5196 temp_filename_length + 1);
5197 obstack_grow (&obstack, temp_filename,
5198 temp_filename_length);
5199 arg_going = 1;
5200 delete_this_arg = 0;
5201 break;
5206 /* See if we already have an association of %g/%u/%U and
5207 suffix. */
5208 for (t = temp_names; t; t = t->next)
5209 if (t->length == suffix_length
5210 && strncmp (t->suffix, suffix, suffix_length) == 0
5211 && t->unique == (c == 'u' || c == 'U' || c == 'j'))
5212 break;
5214 /* Make a new association if needed. %u and %j
5215 require one. */
5216 if (t == 0 || c == 'u' || c == 'j')
5218 if (t == 0)
5220 t = XNEW (struct temp_name);
5221 t->next = temp_names;
5222 temp_names = t;
5224 t->length = suffix_length;
5225 if (saved_suffix)
5227 t->suffix = saved_suffix;
5228 saved_suffix = NULL;
5230 else
5231 t->suffix = save_string (suffix, suffix_length);
5232 t->unique = (c == 'u' || c == 'U' || c == 'j');
5233 temp_filename = make_temp_file (t->suffix);
5234 temp_filename_length = strlen (temp_filename);
5235 t->filename = temp_filename;
5236 t->filename_length = temp_filename_length;
5239 free (saved_suffix);
5241 obstack_grow (&obstack, t->filename, t->filename_length);
5242 delete_this_arg = 1;
5244 arg_going = 1;
5245 break;
5247 case 'i':
5248 if (combine_inputs)
5250 if (at_file_supplied)
5252 /* We are going to expand `%i' to `@FILE', where FILE
5253 is a newly-created temporary filename. The filenames
5254 that would usually be expanded in place of %o will be
5255 written to the temporary file. */
5256 char **argv;
5257 int n_files = 0;
5258 int j;
5260 for (i = 0; i < n_infiles; i++)
5261 if (compile_input_file_p (&infiles[i]))
5262 n_files++;
5264 argv = (char **) alloca (sizeof (char *) * (n_files + 1));
5266 /* Copy the strings over. */
5267 for (i = 0, j = 0; i < n_infiles; i++)
5268 if (compile_input_file_p (&infiles[i]))
5270 argv[j] = CONST_CAST (char *, infiles[i].name);
5271 infiles[i].compiled = true;
5272 j++;
5274 argv[j] = NULL;
5276 create_at_file (argv);
5278 else
5279 for (i = 0; (int) i < n_infiles; i++)
5280 if (compile_input_file_p (&infiles[i]))
5282 store_arg (infiles[i].name, 0, 0);
5283 infiles[i].compiled = true;
5286 else
5288 obstack_grow (&obstack, gcc_input_filename,
5289 input_filename_length);
5290 arg_going = 1;
5292 break;
5294 case 'I':
5296 struct spec_path_info info;
5298 if (multilib_dir)
5300 do_spec_1 ("-imultilib", 1, NULL);
5301 /* Make this a separate argument. */
5302 do_spec_1 (" ", 0, NULL);
5303 do_spec_1 (multilib_dir, 1, NULL);
5304 do_spec_1 (" ", 0, NULL);
5307 if (multiarch_dir)
5309 do_spec_1 ("-imultiarch", 1, NULL);
5310 /* Make this a separate argument. */
5311 do_spec_1 (" ", 0, NULL);
5312 do_spec_1 (multiarch_dir, 1, NULL);
5313 do_spec_1 (" ", 0, NULL);
5316 if (gcc_exec_prefix)
5318 do_spec_1 ("-iprefix", 1, NULL);
5319 /* Make this a separate argument. */
5320 do_spec_1 (" ", 0, NULL);
5321 do_spec_1 (gcc_exec_prefix, 1, NULL);
5322 do_spec_1 (" ", 0, NULL);
5325 if (target_system_root_changed ||
5326 (target_system_root && target_sysroot_hdrs_suffix))
5328 do_spec_1 ("-isysroot", 1, NULL);
5329 /* Make this a separate argument. */
5330 do_spec_1 (" ", 0, NULL);
5331 do_spec_1 (target_system_root, 1, NULL);
5332 if (target_sysroot_hdrs_suffix)
5333 do_spec_1 (target_sysroot_hdrs_suffix, 1, NULL);
5334 do_spec_1 (" ", 0, NULL);
5337 info.option = "-isystem";
5338 info.append = "include";
5339 info.append_len = strlen (info.append);
5340 info.omit_relative = false;
5341 info.separate_options = true;
5343 for_each_path (&include_prefixes, false, info.append_len,
5344 spec_path, &info);
5346 info.append = "include-fixed";
5347 if (*sysroot_hdrs_suffix_spec)
5348 info.append = concat (info.append, dir_separator_str,
5349 multilib_dir, NULL);
5350 info.append_len = strlen (info.append);
5351 for_each_path (&include_prefixes, false, info.append_len,
5352 spec_path, &info);
5354 break;
5356 case 'o':
5358 int max = n_infiles;
5359 max += lang_specific_extra_outfiles;
5361 if (HAVE_GNU_LD && at_file_supplied)
5363 /* We are going to expand `%o' to `@FILE', where FILE
5364 is a newly-created temporary filename. The filenames
5365 that would usually be expanded in place of %o will be
5366 written to the temporary file. */
5368 char **argv;
5369 int n_files, j;
5371 /* Convert OUTFILES into a form suitable for writeargv. */
5373 /* Determine how many are non-NULL. */
5374 for (n_files = 0, i = 0; i < max; i++)
5375 n_files += outfiles[i] != NULL;
5377 argv = (char **) alloca (sizeof (char *) * (n_files + 1));
5379 /* Copy the strings over. */
5380 for (i = 0, j = 0; i < max; i++)
5381 if (outfiles[i])
5383 argv[j] = CONST_CAST (char *, outfiles[i]);
5384 j++;
5386 argv[j] = NULL;
5388 create_at_file (argv);
5390 else
5391 for (i = 0; i < max; i++)
5392 if (outfiles[i])
5393 store_arg (outfiles[i], 0, 0);
5394 break;
5397 case 'O':
5398 obstack_grow (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
5399 arg_going = 1;
5400 break;
5402 case 's':
5403 this_is_library_file = 1;
5404 break;
5406 case 'T':
5407 this_is_linker_script = 1;
5408 break;
5410 case 'V':
5411 outfiles[input_file_number] = NULL;
5412 break;
5414 case 'w':
5415 this_is_output_file = 1;
5416 break;
5418 case 'W':
5420 unsigned int cur_index = argbuf.length ();
5421 /* Handle the {...} following the %W. */
5422 if (*p != '{')
5423 fatal_error (input_location,
5424 "spec %qs has invalid %<%%W%c%>", spec, *p);
5425 p = handle_braces (p + 1);
5426 if (p == 0)
5427 return -1;
5428 end_going_arg ();
5429 /* If any args were output, mark the last one for deletion
5430 on failure. */
5431 if (argbuf.length () != cur_index)
5432 record_temp_file (argbuf.last (), 0, 1);
5433 break;
5436 /* %x{OPTION} records OPTION for %X to output. */
5437 case 'x':
5439 const char *p1 = p;
5440 char *string;
5441 char *opt;
5442 unsigned ix;
5444 /* Skip past the option value and make a copy. */
5445 if (*p != '{')
5446 fatal_error (input_location,
5447 "spec %qs has invalid %<%%x%c%>", spec, *p);
5448 while (*p++ != '}')
5450 string = save_string (p1 + 1, p - p1 - 2);
5452 /* See if we already recorded this option. */
5453 FOR_EACH_VEC_ELT (linker_options, ix, opt)
5454 if (! strcmp (string, opt))
5456 free (string);
5457 return 0;
5460 /* This option is new; add it. */
5461 add_linker_option (string, strlen (string));
5462 free (string);
5464 break;
5466 /* Dump out the options accumulated previously using %x. */
5467 case 'X':
5468 do_specs_vec (linker_options);
5469 break;
5471 /* Dump out the options accumulated previously using -Wa,. */
5472 case 'Y':
5473 do_specs_vec (assembler_options);
5474 break;
5476 /* Dump out the options accumulated previously using -Wp,. */
5477 case 'Z':
5478 do_specs_vec (preprocessor_options);
5479 break;
5481 /* Here are digits and numbers that just process
5482 a certain constant string as a spec. */
5484 case '1':
5485 value = do_spec_1 (cc1_spec, 0, NULL);
5486 if (value != 0)
5487 return value;
5488 break;
5490 case '2':
5491 value = do_spec_1 (cc1plus_spec, 0, NULL);
5492 if (value != 0)
5493 return value;
5494 break;
5496 case 'a':
5497 value = do_spec_1 (asm_spec, 0, NULL);
5498 if (value != 0)
5499 return value;
5500 break;
5502 case 'A':
5503 value = do_spec_1 (asm_final_spec, 0, NULL);
5504 if (value != 0)
5505 return value;
5506 break;
5508 case 'C':
5510 const char *const spec
5511 = (input_file_compiler->cpp_spec
5512 ? input_file_compiler->cpp_spec
5513 : cpp_spec);
5514 value = do_spec_1 (spec, 0, NULL);
5515 if (value != 0)
5516 return value;
5518 break;
5520 case 'E':
5521 value = do_spec_1 (endfile_spec, 0, NULL);
5522 if (value != 0)
5523 return value;
5524 break;
5526 case 'l':
5527 value = do_spec_1 (link_spec, 0, NULL);
5528 if (value != 0)
5529 return value;
5530 break;
5532 case 'L':
5533 value = do_spec_1 (lib_spec, 0, NULL);
5534 if (value != 0)
5535 return value;
5536 break;
5538 case 'M':
5539 if (multilib_os_dir == NULL)
5540 obstack_1grow (&obstack, '.');
5541 else
5542 obstack_grow (&obstack, multilib_os_dir,
5543 strlen (multilib_os_dir));
5544 break;
5546 case 'G':
5547 value = do_spec_1 (libgcc_spec, 0, NULL);
5548 if (value != 0)
5549 return value;
5550 break;
5552 case 'R':
5553 /* We assume there is a directory
5554 separator at the end of this string. */
5555 if (target_system_root)
5557 obstack_grow (&obstack, target_system_root,
5558 strlen (target_system_root));
5559 if (target_sysroot_suffix)
5560 obstack_grow (&obstack, target_sysroot_suffix,
5561 strlen (target_sysroot_suffix));
5563 break;
5565 case 'S':
5566 value = do_spec_1 (startfile_spec, 0, NULL);
5567 if (value != 0)
5568 return value;
5569 break;
5571 /* Here we define characters other than letters and digits. */
5573 case '{':
5574 p = handle_braces (p);
5575 if (p == 0)
5576 return -1;
5577 break;
5579 case ':':
5580 p = handle_spec_function (p, NULL);
5581 if (p == 0)
5582 return -1;
5583 break;
5585 case '%':
5586 obstack_1grow (&obstack, '%');
5587 break;
5589 case '.':
5591 unsigned len = 0;
5593 while (p[len] && p[len] != ' ' && p[len] != '%')
5594 len++;
5595 suffix_subst = save_string (p - 1, len + 1);
5596 p += len;
5598 break;
5600 /* Henceforth ignore the option(s) matching the pattern
5601 after the %<. */
5602 case '<':
5603 case '>':
5605 unsigned len = 0;
5606 int have_wildcard = 0;
5607 int i;
5608 int switch_option;
5610 if (c == '>')
5611 switch_option = SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC;
5612 else
5613 switch_option = SWITCH_IGNORE;
5615 while (p[len] && p[len] != ' ' && p[len] != '\t')
5616 len++;
5618 if (p[len-1] == '*')
5619 have_wildcard = 1;
5621 for (i = 0; i < n_switches; i++)
5622 if (!strncmp (switches[i].part1, p, len - have_wildcard)
5623 && (have_wildcard || switches[i].part1[len] == '\0'))
5625 switches[i].live_cond |= switch_option;
5626 /* User switch be validated from validate_all_switches.
5627 when the definition is seen from the spec file.
5628 If not defined anywhere, will be rejected. */
5629 if (switches[i].known)
5630 switches[i].validated = true;
5633 p += len;
5635 break;
5637 case '*':
5638 if (soft_matched_part)
5640 if (soft_matched_part[0])
5641 do_spec_1 (soft_matched_part, 1, NULL);
5642 /* Only insert a space after the substitution if it is at the
5643 end of the current sequence. So if:
5645 "%{foo=*:bar%*}%{foo=*:one%*two}"
5647 matches -foo=hello then it will produce:
5649 barhello onehellotwo
5651 if (*p == 0 || *p == '}')
5652 do_spec_1 (" ", 0, NULL);
5654 else
5655 /* Catch the case where a spec string contains something like
5656 '%{foo:%*}'. i.e. there is no * in the pattern on the left
5657 hand side of the :. */
5658 error ("spec failure: %<%%*%> has not been initialized by pattern match");
5659 break;
5661 /* Process a string found as the value of a spec given by name.
5662 This feature allows individual machine descriptions
5663 to add and use their own specs. */
5664 case '(':
5666 const char *name = p;
5667 struct spec_list *sl;
5668 int len;
5670 /* The string after the S/P is the name of a spec that is to be
5671 processed. */
5672 while (*p && *p != ')')
5673 p++;
5675 /* See if it's in the list. */
5676 for (len = p - name, sl = specs; sl; sl = sl->next)
5677 if (sl->name_len == len && !strncmp (sl->name, name, len))
5679 name = *(sl->ptr_spec);
5680 #ifdef DEBUG_SPECS
5681 fnotice (stderr, "Processing spec (%s), which is '%s'\n",
5682 sl->name, name);
5683 #endif
5684 break;
5687 if (sl)
5689 value = do_spec_1 (name, 0, NULL);
5690 if (value != 0)
5691 return value;
5694 /* Discard the closing paren. */
5695 if (*p)
5696 p++;
5698 break;
5700 default:
5701 error ("spec failure: unrecognized spec option %qc", c);
5702 break;
5704 break;
5706 case '\\':
5707 /* Backslash: treat next character as ordinary. */
5708 c = *p++;
5710 /* Fall through. */
5711 default:
5712 /* Ordinary character: put it into the current argument. */
5713 obstack_1grow (&obstack, c);
5714 arg_going = 1;
5717 /* End of string. If we are processing a spec function, we need to
5718 end any pending argument. */
5719 if (processing_spec_function)
5720 end_going_arg ();
5722 return 0;
5725 /* Look up a spec function. */
5727 static const struct spec_function *
5728 lookup_spec_function (const char *name)
5730 const struct spec_function *sf;
5732 for (sf = static_spec_functions; sf->name != NULL; sf++)
5733 if (strcmp (sf->name, name) == 0)
5734 return sf;
5736 return NULL;
5739 /* Evaluate a spec function. */
5741 static const char *
5742 eval_spec_function (const char *func, const char *args)
5744 const struct spec_function *sf;
5745 const char *funcval;
5747 /* Saved spec processing context. */
5748 vec<const_char_p> save_argbuf;
5750 int save_arg_going;
5751 int save_delete_this_arg;
5752 int save_this_is_output_file;
5753 int save_this_is_library_file;
5754 int save_input_from_pipe;
5755 int save_this_is_linker_script;
5756 const char *save_suffix_subst;
5758 int save_growing_size;
5759 void *save_growing_value = NULL;
5761 sf = lookup_spec_function (func);
5762 if (sf == NULL)
5763 fatal_error (input_location, "unknown spec function %qs", func);
5765 /* Push the spec processing context. */
5766 save_argbuf = argbuf;
5768 save_arg_going = arg_going;
5769 save_delete_this_arg = delete_this_arg;
5770 save_this_is_output_file = this_is_output_file;
5771 save_this_is_library_file = this_is_library_file;
5772 save_this_is_linker_script = this_is_linker_script;
5773 save_input_from_pipe = input_from_pipe;
5774 save_suffix_subst = suffix_subst;
5776 /* If we have some object growing now, finalize it so the args and function
5777 eval proceed from a cleared context. This is needed to prevent the first
5778 constructed arg from mistakenly including the growing value. We'll push
5779 this value back on the obstack once the function evaluation is done, to
5780 restore a consistent processing context for our caller. This is fine as
5781 the address of growing objects isn't guaranteed to remain stable until
5782 they are finalized, and we expect this situation to be rare enough for
5783 the extra copy not to be an issue. */
5784 save_growing_size = obstack_object_size (&obstack);
5785 if (save_growing_size > 0)
5786 save_growing_value = obstack_finish (&obstack);
5788 /* Create a new spec processing context, and build the function
5789 arguments. */
5791 alloc_args ();
5792 if (do_spec_2 (args) < 0)
5793 fatal_error (input_location, "error in args to spec function %qs", func);
5795 /* argbuf_index is an index for the next argument to be inserted, and
5796 so contains the count of the args already inserted. */
5798 funcval = (*sf->func) (argbuf.length (),
5799 argbuf.address ());
5801 /* Pop the spec processing context. */
5802 argbuf.release ();
5803 argbuf = save_argbuf;
5805 arg_going = save_arg_going;
5806 delete_this_arg = save_delete_this_arg;
5807 this_is_output_file = save_this_is_output_file;
5808 this_is_library_file = save_this_is_library_file;
5809 this_is_linker_script = save_this_is_linker_script;
5810 input_from_pipe = save_input_from_pipe;
5811 suffix_subst = save_suffix_subst;
5813 if (save_growing_size > 0)
5814 obstack_grow (&obstack, save_growing_value, save_growing_size);
5816 return funcval;
5819 /* Handle a spec function call of the form:
5821 %:function(args)
5823 ARGS is processed as a spec in a separate context and split into an
5824 argument vector in the normal fashion. The function returns a string
5825 containing a spec which we then process in the caller's context, or
5826 NULL if no processing is required.
5828 If RETVAL_NONNULL is not NULL, then store a bool whether function
5829 returned non-NULL. */
5831 static const char *
5832 handle_spec_function (const char *p, bool *retval_nonnull)
5834 char *func, *args;
5835 const char *endp, *funcval;
5836 int count;
5838 processing_spec_function++;
5840 /* Get the function name. */
5841 for (endp = p; *endp != '\0'; endp++)
5843 if (*endp == '(') /* ) */
5844 break;
5845 /* Only allow [A-Za-z0-9], -, and _ in function names. */
5846 if (!ISALNUM (*endp) && !(*endp == '-' || *endp == '_'))
5847 fatal_error (input_location, "malformed spec function name");
5849 if (*endp != '(') /* ) */
5850 fatal_error (input_location, "no arguments for spec function");
5851 func = save_string (p, endp - p);
5852 p = ++endp;
5854 /* Get the arguments. */
5855 for (count = 0; *endp != '\0'; endp++)
5857 /* ( */
5858 if (*endp == ')')
5860 if (count == 0)
5861 break;
5862 count--;
5864 else if (*endp == '(') /* ) */
5865 count++;
5867 /* ( */
5868 if (*endp != ')')
5869 fatal_error (input_location, "malformed spec function arguments");
5870 args = save_string (p, endp - p);
5871 p = ++endp;
5873 /* p now points to just past the end of the spec function expression. */
5875 funcval = eval_spec_function (func, args);
5876 if (funcval != NULL && do_spec_1 (funcval, 0, NULL) < 0)
5877 p = NULL;
5878 if (retval_nonnull)
5879 *retval_nonnull = funcval != NULL;
5881 free (func);
5882 free (args);
5884 processing_spec_function--;
5886 return p;
5889 /* Inline subroutine of handle_braces. Returns true if the current
5890 input suffix matches the atom bracketed by ATOM and END_ATOM. */
5891 static inline bool
5892 input_suffix_matches (const char *atom, const char *end_atom)
5894 return (input_suffix
5895 && !strncmp (input_suffix, atom, end_atom - atom)
5896 && input_suffix[end_atom - atom] == '\0');
5899 /* Subroutine of handle_braces. Returns true if the current
5900 input file's spec name matches the atom bracketed by ATOM and END_ATOM. */
5901 static bool
5902 input_spec_matches (const char *atom, const char *end_atom)
5904 return (input_file_compiler
5905 && input_file_compiler->suffix
5906 && input_file_compiler->suffix[0] != '\0'
5907 && !strncmp (input_file_compiler->suffix + 1, atom,
5908 end_atom - atom)
5909 && input_file_compiler->suffix[end_atom - atom + 1] == '\0');
5912 /* Subroutine of handle_braces. Returns true if a switch
5913 matching the atom bracketed by ATOM and END_ATOM appeared on the
5914 command line. */
5915 static bool
5916 switch_matches (const char *atom, const char *end_atom, int starred)
5918 int i;
5919 int len = end_atom - atom;
5920 int plen = starred ? len : -1;
5922 for (i = 0; i < n_switches; i++)
5923 if (!strncmp (switches[i].part1, atom, len)
5924 && (starred || switches[i].part1[len] == '\0')
5925 && check_live_switch (i, plen))
5926 return true;
5928 /* Check if a switch with separated form matching the atom.
5929 We check -D and -U switches. */
5930 else if (switches[i].args != 0)
5932 if ((*switches[i].part1 == 'D' || *switches[i].part1 == 'U')
5933 && *switches[i].part1 == atom[0])
5935 if (!strncmp (switches[i].args[0], &atom[1], len - 1)
5936 && (starred || (switches[i].part1[1] == '\0'
5937 && switches[i].args[0][len - 1] == '\0'))
5938 && check_live_switch (i, (starred ? 1 : -1)))
5939 return true;
5943 return false;
5946 /* Inline subroutine of handle_braces. Mark all of the switches which
5947 match ATOM (extends to END_ATOM; STARRED indicates whether there
5948 was a star after the atom) for later processing. */
5949 static inline void
5950 mark_matching_switches (const char *atom, const char *end_atom, int starred)
5952 int i;
5953 int len = end_atom - atom;
5954 int plen = starred ? len : -1;
5956 for (i = 0; i < n_switches; i++)
5957 if (!strncmp (switches[i].part1, atom, len)
5958 && (starred || switches[i].part1[len] == '\0')
5959 && check_live_switch (i, plen))
5960 switches[i].ordering = 1;
5963 /* Inline subroutine of handle_braces. Process all the currently
5964 marked switches through give_switch, and clear the marks. */
5965 static inline void
5966 process_marked_switches (void)
5968 int i;
5970 for (i = 0; i < n_switches; i++)
5971 if (switches[i].ordering == 1)
5973 switches[i].ordering = 0;
5974 give_switch (i, 0);
5978 /* Handle a %{ ... } construct. P points just inside the leading {.
5979 Returns a pointer one past the end of the brace block, or 0
5980 if we call do_spec_1 and that returns -1. */
5982 static const char *
5983 handle_braces (const char *p)
5985 const char *atom, *end_atom;
5986 const char *d_atom = NULL, *d_end_atom = NULL;
5987 const char *orig = p;
5989 bool a_is_suffix;
5990 bool a_is_spectype;
5991 bool a_is_starred;
5992 bool a_is_negated;
5993 bool a_matched;
5995 bool a_must_be_last = false;
5996 bool ordered_set = false;
5997 bool disjunct_set = false;
5998 bool disj_matched = false;
5999 bool disj_starred = true;
6000 bool n_way_choice = false;
6001 bool n_way_matched = false;
6003 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
6007 if (a_must_be_last)
6008 goto invalid;
6010 /* Scan one "atom" (S in the description above of %{}, possibly
6011 with '!', '.', '@', ',', or '*' modifiers). */
6012 a_matched = false;
6013 a_is_suffix = false;
6014 a_is_starred = false;
6015 a_is_negated = false;
6016 a_is_spectype = false;
6018 SKIP_WHITE ();
6019 if (*p == '!')
6020 p++, a_is_negated = true;
6022 SKIP_WHITE ();
6023 if (*p == '%' && p[1] == ':')
6025 atom = NULL;
6026 end_atom = NULL;
6027 p = handle_spec_function (p + 2, &a_matched);
6029 else
6031 if (*p == '.')
6032 p++, a_is_suffix = true;
6033 else if (*p == ',')
6034 p++, a_is_spectype = true;
6036 atom = p;
6037 while (ISIDNUM (*p) || *p == '-' || *p == '+' || *p == '='
6038 || *p == ',' || *p == '.' || *p == '@')
6039 p++;
6040 end_atom = p;
6042 if (*p == '*')
6043 p++, a_is_starred = 1;
6046 SKIP_WHITE ();
6047 switch (*p)
6049 case '&': case '}':
6050 /* Substitute the switch(es) indicated by the current atom. */
6051 ordered_set = true;
6052 if (disjunct_set || n_way_choice || a_is_negated || a_is_suffix
6053 || a_is_spectype || atom == end_atom)
6054 goto invalid;
6056 mark_matching_switches (atom, end_atom, a_is_starred);
6058 if (*p == '}')
6059 process_marked_switches ();
6060 break;
6062 case '|': case ':':
6063 /* Substitute some text if the current atom appears as a switch
6064 or suffix. */
6065 disjunct_set = true;
6066 if (ordered_set)
6067 goto invalid;
6069 if (atom && atom == end_atom)
6071 if (!n_way_choice || disj_matched || *p == '|'
6072 || a_is_negated || a_is_suffix || a_is_spectype
6073 || a_is_starred)
6074 goto invalid;
6076 /* An empty term may appear as the last choice of an
6077 N-way choice set; it means "otherwise". */
6078 a_must_be_last = true;
6079 disj_matched = !n_way_matched;
6080 disj_starred = false;
6082 else
6084 if ((a_is_suffix || a_is_spectype) && a_is_starred)
6085 goto invalid;
6087 if (!a_is_starred)
6088 disj_starred = false;
6090 /* Don't bother testing this atom if we already have a
6091 match. */
6092 if (!disj_matched && !n_way_matched)
6094 if (atom == NULL)
6095 /* a_matched is already set by handle_spec_function. */;
6096 else if (a_is_suffix)
6097 a_matched = input_suffix_matches (atom, end_atom);
6098 else if (a_is_spectype)
6099 a_matched = input_spec_matches (atom, end_atom);
6100 else
6101 a_matched = switch_matches (atom, end_atom, a_is_starred);
6103 if (a_matched != a_is_negated)
6105 disj_matched = true;
6106 d_atom = atom;
6107 d_end_atom = end_atom;
6112 if (*p == ':')
6114 /* Found the body, that is, the text to substitute if the
6115 current disjunction matches. */
6116 p = process_brace_body (p + 1, d_atom, d_end_atom, disj_starred,
6117 disj_matched && !n_way_matched);
6118 if (p == 0)
6119 return 0;
6121 /* If we have an N-way choice, reset state for the next
6122 disjunction. */
6123 if (*p == ';')
6125 n_way_choice = true;
6126 n_way_matched |= disj_matched;
6127 disj_matched = false;
6128 disj_starred = true;
6129 d_atom = d_end_atom = NULL;
6132 break;
6134 default:
6135 goto invalid;
6138 while (*p++ != '}');
6140 return p;
6142 invalid:
6143 fatal_error (input_location, "braced spec %qs is invalid at %qc", orig, *p);
6145 #undef SKIP_WHITE
6148 /* Subroutine of handle_braces. Scan and process a brace substitution body
6149 (X in the description of %{} syntax). P points one past the colon;
6150 ATOM and END_ATOM bracket the first atom which was found to be true
6151 (present) in the current disjunction; STARRED indicates whether all
6152 the atoms in the current disjunction were starred (for syntax validation);
6153 MATCHED indicates whether the disjunction matched or not, and therefore
6154 whether or not the body is to be processed through do_spec_1 or just
6155 skipped. Returns a pointer to the closing } or ;, or 0 if do_spec_1
6156 returns -1. */
6158 static const char *
6159 process_brace_body (const char *p, const char *atom, const char *end_atom,
6160 int starred, int matched)
6162 const char *body, *end_body;
6163 unsigned int nesting_level;
6164 bool have_subst = false;
6166 /* Locate the closing } or ;, honoring nested braces.
6167 Trim trailing whitespace. */
6168 body = p;
6169 nesting_level = 1;
6170 for (;;)
6172 if (*p == '{')
6173 nesting_level++;
6174 else if (*p == '}')
6176 if (!--nesting_level)
6177 break;
6179 else if (*p == ';' && nesting_level == 1)
6180 break;
6181 else if (*p == '%' && p[1] == '*' && nesting_level == 1)
6182 have_subst = true;
6183 else if (*p == '\0')
6184 goto invalid;
6185 p++;
6188 end_body = p;
6189 while (end_body[-1] == ' ' || end_body[-1] == '\t')
6190 end_body--;
6192 if (have_subst && !starred)
6193 goto invalid;
6195 if (matched)
6197 /* Copy the substitution body to permanent storage and execute it.
6198 If have_subst is false, this is a simple matter of running the
6199 body through do_spec_1... */
6200 char *string = save_string (body, end_body - body);
6201 if (!have_subst)
6203 if (do_spec_1 (string, 0, NULL) < 0)
6204 return 0;
6206 else
6208 /* ... but if have_subst is true, we have to process the
6209 body once for each matching switch, with %* set to the
6210 variant part of the switch. */
6211 unsigned int hard_match_len = end_atom - atom;
6212 int i;
6214 for (i = 0; i < n_switches; i++)
6215 if (!strncmp (switches[i].part1, atom, hard_match_len)
6216 && check_live_switch (i, hard_match_len))
6218 if (do_spec_1 (string, 0,
6219 &switches[i].part1[hard_match_len]) < 0)
6220 return 0;
6221 /* Pass any arguments this switch has. */
6222 give_switch (i, 1);
6223 suffix_subst = NULL;
6228 return p;
6230 invalid:
6231 fatal_error (input_location, "braced spec body %qs is invalid", body);
6234 /* Return 0 iff switch number SWITCHNUM is obsoleted by a later switch
6235 on the command line. PREFIX_LENGTH is the length of XXX in an {XXX*}
6236 spec, or -1 if either exact match or %* is used.
6238 A -O switch is obsoleted by a later -O switch. A -f, -g, -m, or -W switch
6239 whose value does not begin with "no-" is obsoleted by the same value
6240 with the "no-", similarly for a switch with the "no-" prefix. */
6242 static int
6243 check_live_switch (int switchnum, int prefix_length)
6245 const char *name = switches[switchnum].part1;
6246 int i;
6248 /* If we already processed this switch and determined if it was
6249 live or not, return our past determination. */
6250 if (switches[switchnum].live_cond != 0)
6251 return ((switches[switchnum].live_cond & SWITCH_LIVE) != 0
6252 && (switches[switchnum].live_cond & SWITCH_FALSE) == 0
6253 && (switches[switchnum].live_cond & SWITCH_IGNORE_PERMANENTLY)
6254 == 0);
6256 /* In the common case of {<at-most-one-letter>*}, a negating
6257 switch would always match, so ignore that case. We will just
6258 send the conflicting switches to the compiler phase. */
6259 if (prefix_length >= 0 && prefix_length <= 1)
6260 return 1;
6262 /* Now search for duplicate in a manner that depends on the name. */
6263 switch (*name)
6265 case 'O':
6266 for (i = switchnum + 1; i < n_switches; i++)
6267 if (switches[i].part1[0] == 'O')
6269 switches[switchnum].validated = true;
6270 switches[switchnum].live_cond = SWITCH_FALSE;
6271 return 0;
6273 break;
6275 case 'W': case 'f': case 'm': case 'g':
6276 if (! strncmp (name + 1, "no-", 3))
6278 /* We have Xno-YYY, search for XYYY. */
6279 for (i = switchnum + 1; i < n_switches; i++)
6280 if (switches[i].part1[0] == name[0]
6281 && ! strcmp (&switches[i].part1[1], &name[4]))
6283 /* --specs are validated with the validate_switches mechanism. */
6284 if (switches[switchnum].known)
6285 switches[switchnum].validated = true;
6286 switches[switchnum].live_cond = SWITCH_FALSE;
6287 return 0;
6290 else
6292 /* We have XYYY, search for Xno-YYY. */
6293 for (i = switchnum + 1; i < n_switches; i++)
6294 if (switches[i].part1[0] == name[0]
6295 && switches[i].part1[1] == 'n'
6296 && switches[i].part1[2] == 'o'
6297 && switches[i].part1[3] == '-'
6298 && !strcmp (&switches[i].part1[4], &name[1]))
6300 /* --specs are validated with the validate_switches mechanism. */
6301 if (switches[switchnum].known)
6302 switches[switchnum].validated = true;
6303 switches[switchnum].live_cond = SWITCH_FALSE;
6304 return 0;
6307 break;
6310 /* Otherwise the switch is live. */
6311 switches[switchnum].live_cond |= SWITCH_LIVE;
6312 return 1;
6315 /* Pass a switch to the current accumulating command
6316 in the same form that we received it.
6317 SWITCHNUM identifies the switch; it is an index into
6318 the vector of switches gcc received, which is `switches'.
6319 This cannot fail since it never finishes a command line.
6321 If OMIT_FIRST_WORD is nonzero, then we omit .part1 of the argument. */
6323 static void
6324 give_switch (int switchnum, int omit_first_word)
6326 if ((switches[switchnum].live_cond & SWITCH_IGNORE) != 0)
6327 return;
6329 if (!omit_first_word)
6331 do_spec_1 ("-", 0, NULL);
6332 do_spec_1 (switches[switchnum].part1, 1, NULL);
6335 if (switches[switchnum].args != 0)
6337 const char **p;
6338 for (p = switches[switchnum].args; *p; p++)
6340 const char *arg = *p;
6342 do_spec_1 (" ", 0, NULL);
6343 if (suffix_subst)
6345 unsigned length = strlen (arg);
6346 int dot = 0;
6348 while (length-- && !IS_DIR_SEPARATOR (arg[length]))
6349 if (arg[length] == '.')
6351 (CONST_CAST (char *, arg))[length] = 0;
6352 dot = 1;
6353 break;
6355 do_spec_1 (arg, 1, NULL);
6356 if (dot)
6357 (CONST_CAST (char *, arg))[length] = '.';
6358 do_spec_1 (suffix_subst, 1, NULL);
6360 else
6361 do_spec_1 (arg, 1, NULL);
6365 do_spec_1 (" ", 0, NULL);
6366 switches[switchnum].validated = true;
6369 /* Print GCC configuration (e.g. version, thread model, target,
6370 configuration_arguments) to a given FILE. */
6372 static void
6373 print_configuration (FILE *file)
6375 int n;
6376 const char *thrmod;
6378 fnotice (file, "Target: %s\n", spec_machine);
6379 fnotice (file, "Configured with: %s\n", configuration_arguments);
6381 #ifdef THREAD_MODEL_SPEC
6382 /* We could have defined THREAD_MODEL_SPEC to "%*" by default,
6383 but there's no point in doing all this processing just to get
6384 thread_model back. */
6385 obstack_init (&obstack);
6386 do_spec_1 (THREAD_MODEL_SPEC, 0, thread_model);
6387 obstack_1grow (&obstack, '\0');
6388 thrmod = XOBFINISH (&obstack, const char *);
6389 #else
6390 thrmod = thread_model;
6391 #endif
6393 fnotice (file, "Thread model: %s\n", thrmod);
6395 /* compiler_version is truncated at the first space when initialized
6396 from version string, so truncate version_string at the first space
6397 before comparing. */
6398 for (n = 0; version_string[n]; n++)
6399 if (version_string[n] == ' ')
6400 break;
6402 if (! strncmp (version_string, compiler_version, n)
6403 && compiler_version[n] == 0)
6404 fnotice (file, "gcc version %s %s\n", version_string,
6405 pkgversion_string);
6406 else
6407 fnotice (file, "gcc driver version %s %sexecuting gcc version %s\n",
6408 version_string, pkgversion_string, compiler_version);
6412 #define RETRY_ICE_ATTEMPTS 3
6414 /* Returns true if FILE1 and FILE2 contain equivalent data, 0 otherwise. */
6416 static bool
6417 files_equal_p (char *file1, char *file2)
6419 struct stat st1, st2;
6420 off_t n, len;
6421 int fd1, fd2;
6422 const int bufsize = 8192;
6423 char *buf = XNEWVEC (char, bufsize);
6425 fd1 = open (file1, O_RDONLY);
6426 fd2 = open (file2, O_RDONLY);
6428 if (fd1 < 0 || fd2 < 0)
6429 goto error;
6431 if (fstat (fd1, &st1) < 0 || fstat (fd2, &st2) < 0)
6432 goto error;
6434 if (st1.st_size != st2.st_size)
6435 goto error;
6437 for (n = st1.st_size; n; n -= len)
6439 len = n;
6440 if ((int) len > bufsize / 2)
6441 len = bufsize / 2;
6443 if (read (fd1, buf, len) != (int) len
6444 || read (fd2, buf + bufsize / 2, len) != (int) len)
6446 goto error;
6449 if (memcmp (buf, buf + bufsize / 2, len) != 0)
6450 goto error;
6453 free (buf);
6454 close (fd1);
6455 close (fd2);
6457 return 1;
6459 error:
6460 free (buf);
6461 close (fd1);
6462 close (fd2);
6463 return 0;
6466 /* Check that compiler's output doesn't differ across runs.
6467 TEMP_STDOUT_FILES and TEMP_STDERR_FILES are arrays of files, containing
6468 stdout and stderr for each compiler run. Return true if all of
6469 TEMP_STDOUT_FILES and TEMP_STDERR_FILES are equivalent. */
6471 static bool
6472 check_repro (char **temp_stdout_files, char **temp_stderr_files)
6474 int i;
6475 for (i = 0; i < RETRY_ICE_ATTEMPTS - 2; ++i)
6477 if (!files_equal_p (temp_stdout_files[i], temp_stdout_files[i + 1])
6478 || !files_equal_p (temp_stderr_files[i], temp_stderr_files[i + 1]))
6480 fnotice (stderr, "The bug is not reproducible, so it is"
6481 " likely a hardware or OS problem.\n");
6482 break;
6485 return i == RETRY_ICE_ATTEMPTS - 2;
6488 enum attempt_status {
6489 ATTEMPT_STATUS_FAIL_TO_RUN,
6490 ATTEMPT_STATUS_SUCCESS,
6491 ATTEMPT_STATUS_ICE
6495 /* Run compiler with arguments NEW_ARGV to reproduce the ICE, storing stdout
6496 to OUT_TEMP and stderr to ERR_TEMP. If APPEND is TRUE, append to OUT_TEMP
6497 and ERR_TEMP instead of truncating. If EMIT_SYSTEM_INFO is TRUE, also write
6498 GCC configuration into to ERR_TEMP. Return ATTEMPT_STATUS_FAIL_TO_RUN if
6499 compiler failed to run, ATTEMPT_STATUS_ICE if compiled ICE-ed and
6500 ATTEMPT_STATUS_SUCCESS otherwise. */
6502 static enum attempt_status
6503 run_attempt (const char **new_argv, const char *out_temp,
6504 const char *err_temp, int emit_system_info, int append)
6507 if (emit_system_info)
6509 FILE *file_out = fopen (err_temp, "a");
6510 print_configuration (file_out);
6511 fputs ("\n", file_out);
6512 fclose (file_out);
6515 int exit_status;
6516 const char *errmsg;
6517 struct pex_obj *pex;
6518 int err;
6519 int pex_flags = PEX_USE_PIPES | PEX_LAST;
6520 enum attempt_status status = ATTEMPT_STATUS_FAIL_TO_RUN;
6522 if (append)
6523 pex_flags |= PEX_STDOUT_APPEND | PEX_STDERR_APPEND;
6525 pex = pex_init (PEX_USE_PIPES, new_argv[0], NULL);
6526 if (!pex)
6527 fatal_error (input_location, "pex_init failed: %m");
6529 errmsg = pex_run (pex, pex_flags, new_argv[0],
6530 CONST_CAST2 (char *const *, const char **, &new_argv[1]), out_temp,
6531 err_temp, &err);
6532 if (errmsg != NULL)
6534 if (err == 0)
6535 fatal_error (input_location, errmsg);
6536 else
6538 errno = err;
6539 pfatal_with_name (errmsg);
6543 if (!pex_get_status (pex, 1, &exit_status))
6544 goto out;
6546 switch (WEXITSTATUS (exit_status))
6548 case ICE_EXIT_CODE:
6549 status = ATTEMPT_STATUS_ICE;
6550 break;
6552 case SUCCESS_EXIT_CODE:
6553 status = ATTEMPT_STATUS_SUCCESS;
6554 break;
6556 default:
6560 out:
6561 pex_free (pex);
6562 return status;
6565 /* This routine reads lines from IN file, adds C++ style comments
6566 at the begining of each line and writes result into OUT. */
6568 static void
6569 insert_comments (const char *file_in, const char *file_out)
6571 FILE *in = fopen (file_in, "rb");
6572 FILE *out = fopen (file_out, "wb");
6573 char line[256];
6575 bool add_comment = true;
6576 while (fgets (line, sizeof (line), in))
6578 if (add_comment)
6579 fputs ("// ", out);
6580 fputs (line, out);
6581 add_comment = strchr (line, '\n') != NULL;
6584 fclose (in);
6585 fclose (out);
6588 /* This routine adds preprocessed source code into the given ERR_FILE.
6589 To do this, it adds "-E" to NEW_ARGV and execute RUN_ATTEMPT routine to
6590 add information in report file. RUN_ATTEMPT should return
6591 ATTEMPT_STATUS_SUCCESS, in other case we cannot generate the report. */
6593 static void
6594 do_report_bug (const char **new_argv, const int nargs,
6595 char **out_file, char **err_file)
6597 int i, status;
6598 int fd = open (*out_file, O_RDWR | O_APPEND);
6599 if (fd < 0)
6600 return;
6601 write (fd, "\n//", 3);
6602 for (i = 0; i < nargs; i++)
6604 write (fd, " ", 1);
6605 write (fd, new_argv[i], strlen (new_argv[i]));
6607 write (fd, "\n\n", 2);
6608 close (fd);
6609 new_argv[nargs] = "-E";
6610 new_argv[nargs + 1] = NULL;
6612 status = run_attempt (new_argv, *out_file, *err_file, 0, 1);
6614 if (status == ATTEMPT_STATUS_SUCCESS)
6616 fnotice (stderr, "Preprocessed source stored into %s file,"
6617 " please attach this to your bugreport.\n", *out_file);
6618 /* Make sure it is not deleted. */
6619 free (*out_file);
6620 *out_file = NULL;
6624 /* Try to reproduce ICE. If bug is reproducible, generate report .err file
6625 containing GCC configuration, backtrace, compiler's command line options
6626 and preprocessed source code. */
6628 static void
6629 try_generate_repro (const char **argv)
6631 int i, nargs, out_arg = -1, quiet = 0, attempt;
6632 const char **new_argv;
6633 char *temp_files[RETRY_ICE_ATTEMPTS * 2];
6634 char **temp_stdout_files = &temp_files[0];
6635 char **temp_stderr_files = &temp_files[RETRY_ICE_ATTEMPTS];
6637 if (gcc_input_filename == NULL || ! strcmp (gcc_input_filename, "-"))
6638 return;
6640 for (nargs = 0; argv[nargs] != NULL; ++nargs)
6641 /* Only retry compiler ICEs, not preprocessor ones. */
6642 if (! strcmp (argv[nargs], "-E"))
6643 return;
6644 else if (argv[nargs][0] == '-' && argv[nargs][1] == 'o')
6646 if (out_arg == -1)
6647 out_arg = nargs;
6648 else
6649 return;
6651 /* If the compiler is going to output any time information,
6652 it might varry between invocations. */
6653 else if (! strcmp (argv[nargs], "-quiet"))
6654 quiet = 1;
6655 else if (! strcmp (argv[nargs], "-ftime-report"))
6656 return;
6658 if (out_arg == -1 || !quiet)
6659 return;
6661 memset (temp_files, '\0', sizeof (temp_files));
6662 new_argv = XALLOCAVEC (const char *, nargs + 4);
6663 memcpy (new_argv, argv, (nargs + 1) * sizeof (const char *));
6664 new_argv[nargs++] = "-frandom-seed=0";
6665 new_argv[nargs++] = "-fdump-noaddr";
6666 new_argv[nargs] = NULL;
6667 if (new_argv[out_arg][2] == '\0')
6668 new_argv[out_arg + 1] = "-";
6669 else
6670 new_argv[out_arg] = "-o-";
6672 int status;
6673 for (attempt = 0; attempt < RETRY_ICE_ATTEMPTS; ++attempt)
6675 int emit_system_info = 0;
6676 int append = 0;
6677 temp_stdout_files[attempt] = make_temp_file (".out");
6678 temp_stderr_files[attempt] = make_temp_file (".err");
6680 if (attempt == RETRY_ICE_ATTEMPTS - 1)
6682 append = 1;
6683 emit_system_info = 1;
6686 status = run_attempt (new_argv, temp_stdout_files[attempt],
6687 temp_stderr_files[attempt], emit_system_info,
6688 append);
6690 if (status != ATTEMPT_STATUS_ICE)
6692 fnotice (stderr, "The bug is not reproducible, so it is"
6693 " likely a hardware or OS problem.\n");
6694 goto out;
6698 if (!check_repro (temp_stdout_files, temp_stderr_files))
6699 goto out;
6702 /* Insert commented out backtrace into report file. */
6703 char **stderr_commented = &temp_stdout_files[RETRY_ICE_ATTEMPTS - 1];
6704 insert_comments (temp_stderr_files[RETRY_ICE_ATTEMPTS - 1],
6705 *stderr_commented);
6707 /* In final attempt we append compiler options and preprocesssed code to last
6708 generated .out file with configuration and backtrace. */
6709 char **output = &temp_stdout_files[RETRY_ICE_ATTEMPTS - 1];
6710 do_report_bug (new_argv, nargs, stderr_commented, output);
6713 out:
6714 for (i = 0; i < RETRY_ICE_ATTEMPTS * 2; i++)
6715 if (temp_files[i])
6717 unlink (temp_stdout_files[i]);
6718 free (temp_stdout_files[i]);
6722 /* Search for a file named NAME trying various prefixes including the
6723 user's -B prefix and some standard ones.
6724 Return the absolute file name found. If nothing is found, return NAME. */
6726 static const char *
6727 find_file (const char *name)
6729 char *newname = find_a_file (&startfile_prefixes, name, R_OK, true);
6730 return newname ? newname : name;
6733 /* Determine whether a directory exists. If LINKER, return 0 for
6734 certain fixed names not needed by the linker. */
6736 static int
6737 is_directory (const char *path1, bool linker)
6739 int len1;
6740 char *path;
6741 char *cp;
6742 struct stat st;
6744 /* Ensure the string ends with "/.". The resulting path will be a
6745 directory even if the given path is a symbolic link. */
6746 len1 = strlen (path1);
6747 path = (char *) alloca (3 + len1);
6748 memcpy (path, path1, len1);
6749 cp = path + len1;
6750 if (!IS_DIR_SEPARATOR (cp[-1]))
6751 *cp++ = DIR_SEPARATOR;
6752 *cp++ = '.';
6753 *cp = '\0';
6755 /* Exclude directories that the linker is known to search. */
6756 if (linker
6757 && IS_DIR_SEPARATOR (path[0])
6758 && ((cp - path == 6
6759 && filename_ncmp (path + 1, "lib", 3) == 0)
6760 || (cp - path == 10
6761 && filename_ncmp (path + 1, "usr", 3) == 0
6762 && IS_DIR_SEPARATOR (path[4])
6763 && filename_ncmp (path + 5, "lib", 3) == 0)))
6764 return 0;
6766 return (stat (path, &st) >= 0 && S_ISDIR (st.st_mode));
6769 /* Set up the various global variables to indicate that we're processing
6770 the input file named FILENAME. */
6772 void
6773 set_input (const char *filename)
6775 const char *p;
6777 gcc_input_filename = filename;
6778 input_filename_length = strlen (gcc_input_filename);
6779 input_basename = lbasename (gcc_input_filename);
6781 /* Find a suffix starting with the last period,
6782 and set basename_length to exclude that suffix. */
6783 basename_length = strlen (input_basename);
6784 suffixed_basename_length = basename_length;
6785 p = input_basename + basename_length;
6786 while (p != input_basename && *p != '.')
6787 --p;
6788 if (*p == '.' && p != input_basename)
6790 basename_length = p - input_basename;
6791 input_suffix = p + 1;
6793 else
6794 input_suffix = "";
6796 /* If a spec for 'g', 'u', or 'U' is seen with -save-temps then
6797 we will need to do a stat on the gcc_input_filename. The
6798 INPUT_STAT_SET signals that the stat is needed. */
6799 input_stat_set = 0;
6802 /* On fatal signals, delete all the temporary files. */
6804 static void
6805 fatal_signal (int signum)
6807 signal (signum, SIG_DFL);
6808 delete_failure_queue ();
6809 delete_temp_files ();
6810 /* Get the same signal again, this time not handled,
6811 so its normal effect occurs. */
6812 kill (getpid (), signum);
6815 /* Compare the contents of the two files named CMPFILE[0] and
6816 CMPFILE[1]. Return zero if they're identical, nonzero
6817 otherwise. */
6819 static int
6820 compare_files (char *cmpfile[])
6822 int ret = 0;
6823 FILE *temp[2] = { NULL, NULL };
6824 int i;
6826 #if HAVE_MMAP_FILE
6828 size_t length[2];
6829 void *map[2] = { NULL, NULL };
6831 for (i = 0; i < 2; i++)
6833 struct stat st;
6835 if (stat (cmpfile[i], &st) < 0 || !S_ISREG (st.st_mode))
6837 error ("%s: could not determine length of compare-debug file %s",
6838 gcc_input_filename, cmpfile[i]);
6839 ret = 1;
6840 break;
6843 length[i] = st.st_size;
6846 if (!ret && length[0] != length[1])
6848 error ("%s: -fcompare-debug failure (length)", gcc_input_filename);
6849 ret = 1;
6852 if (!ret)
6853 for (i = 0; i < 2; i++)
6855 int fd = open (cmpfile[i], O_RDONLY);
6856 if (fd < 0)
6858 error ("%s: could not open compare-debug file %s",
6859 gcc_input_filename, cmpfile[i]);
6860 ret = 1;
6861 break;
6864 map[i] = mmap (NULL, length[i], PROT_READ, MAP_PRIVATE, fd, 0);
6865 close (fd);
6867 if (map[i] == (void *) MAP_FAILED)
6869 ret = -1;
6870 break;
6874 if (!ret)
6876 if (memcmp (map[0], map[1], length[0]) != 0)
6878 error ("%s: -fcompare-debug failure", gcc_input_filename);
6879 ret = 1;
6883 for (i = 0; i < 2; i++)
6884 if (map[i])
6885 munmap ((caddr_t) map[i], length[i]);
6887 if (ret >= 0)
6888 return ret;
6890 ret = 0;
6892 #endif
6894 for (i = 0; i < 2; i++)
6896 temp[i] = fopen (cmpfile[i], "r");
6897 if (!temp[i])
6899 error ("%s: could not open compare-debug file %s",
6900 gcc_input_filename, cmpfile[i]);
6901 ret = 1;
6902 break;
6906 if (!ret && temp[0] && temp[1])
6907 for (;;)
6909 int c0, c1;
6910 c0 = fgetc (temp[0]);
6911 c1 = fgetc (temp[1]);
6913 if (c0 != c1)
6915 error ("%s: -fcompare-debug failure",
6916 gcc_input_filename);
6917 ret = 1;
6918 break;
6921 if (c0 == EOF)
6922 break;
6925 for (i = 1; i >= 0; i--)
6927 if (temp[i])
6928 fclose (temp[i]);
6931 return ret;
6934 /* driver::main is implemented as a series of driver:: method calls. */
6937 driver::main (int argc, char **argv)
6939 bool early_exit;
6941 set_progname (argv[0]);
6942 expand_at_files (&argc, &argv);
6943 decode_argv (argc, const_cast <const char **> (argv));
6944 global_initializations ();
6945 build_multilib_strings ();
6946 set_up_specs ();
6947 putenv_COLLECT_GCC (argv[0]);
6948 maybe_putenv_COLLECT_LTO_WRAPPER ();
6949 maybe_putenv_OFFLOAD_TARGETS ();
6950 handle_unrecognized_options ();
6952 if (!maybe_print_and_exit ())
6953 return 0;
6955 early_exit = prepare_infiles ();
6956 if (early_exit)
6957 return get_exit_code ();
6959 do_spec_on_infiles ();
6960 maybe_run_linker (argv[0]);
6961 final_actions ();
6962 return get_exit_code ();
6965 /* Locate the final component of argv[0] after any leading path, and set
6966 the program name accordingly. */
6968 void
6969 driver::set_progname (const char *argv0) const
6971 const char *p = argv0 + strlen (argv0);
6972 while (p != argv0 && !IS_DIR_SEPARATOR (p[-1]))
6973 --p;
6974 progname = p;
6976 xmalloc_set_program_name (progname);
6979 /* Expand any @ files within the command-line args,
6980 setting at_file_supplied if any were expanded. */
6982 void
6983 driver::expand_at_files (int *argc, char ***argv) const
6985 char **old_argv = *argv;
6987 expandargv (argc, argv);
6989 /* Determine if any expansions were made. */
6990 if (*argv != old_argv)
6991 at_file_supplied = true;
6994 /* Decode the command-line arguments from argc/argv into the
6995 decoded_options array. */
6997 void
6998 driver::decode_argv (int argc, const char **argv)
7000 /* Register the language-independent parameters. */
7001 global_init_params ();
7002 finish_params ();
7004 init_options_struct (&global_options, &global_options_set);
7006 decode_cmdline_options_to_array (argc, argv,
7007 CL_DRIVER,
7008 &decoded_options, &decoded_options_count);
7011 /* Perform various initializations and setup. */
7013 void
7014 driver::global_initializations ()
7016 /* Unlock the stdio streams. */
7017 unlock_std_streams ();
7019 gcc_init_libintl ();
7021 diagnostic_initialize (global_dc, 0);
7022 diagnostic_color_init (global_dc);
7024 #ifdef GCC_DRIVER_HOST_INITIALIZATION
7025 /* Perform host dependent initialization when needed. */
7026 GCC_DRIVER_HOST_INITIALIZATION;
7027 #endif
7029 if (atexit (delete_temp_files) != 0)
7030 fatal_error (input_location, "atexit failed");
7032 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
7033 signal (SIGINT, fatal_signal);
7034 #ifdef SIGHUP
7035 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
7036 signal (SIGHUP, fatal_signal);
7037 #endif
7038 if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
7039 signal (SIGTERM, fatal_signal);
7040 #ifdef SIGPIPE
7041 if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
7042 signal (SIGPIPE, fatal_signal);
7043 #endif
7044 #ifdef SIGCHLD
7045 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
7046 receive the signal. A different setting is inheritable */
7047 signal (SIGCHLD, SIG_DFL);
7048 #endif
7050 /* Parsing and gimplification sometimes need quite large stack.
7051 Increase stack size limits if possible. */
7052 stack_limit_increase (64 * 1024 * 1024);
7054 /* Allocate the argument vector. */
7055 alloc_args ();
7057 obstack_init (&obstack);
7060 /* Build multilib_select, et. al from the separate lines that make up each
7061 multilib selection. */
7063 void
7064 driver::build_multilib_strings () const
7067 const char *p;
7068 const char *const *q = multilib_raw;
7069 int need_space;
7071 obstack_init (&multilib_obstack);
7072 while ((p = *q++) != (char *) 0)
7073 obstack_grow (&multilib_obstack, p, strlen (p));
7075 obstack_1grow (&multilib_obstack, 0);
7076 multilib_select = XOBFINISH (&multilib_obstack, const char *);
7078 q = multilib_matches_raw;
7079 while ((p = *q++) != (char *) 0)
7080 obstack_grow (&multilib_obstack, p, strlen (p));
7082 obstack_1grow (&multilib_obstack, 0);
7083 multilib_matches = XOBFINISH (&multilib_obstack, const char *);
7085 q = multilib_exclusions_raw;
7086 while ((p = *q++) != (char *) 0)
7087 obstack_grow (&multilib_obstack, p, strlen (p));
7089 obstack_1grow (&multilib_obstack, 0);
7090 multilib_exclusions = XOBFINISH (&multilib_obstack, const char *);
7092 q = multilib_reuse_raw;
7093 while ((p = *q++) != (char *) 0)
7094 obstack_grow (&multilib_obstack, p, strlen (p));
7096 obstack_1grow (&multilib_obstack, 0);
7097 multilib_reuse = XOBFINISH (&multilib_obstack, const char *);
7099 need_space = FALSE;
7100 for (size_t i = 0; i < ARRAY_SIZE (multilib_defaults_raw); i++)
7102 if (need_space)
7103 obstack_1grow (&multilib_obstack, ' ');
7104 obstack_grow (&multilib_obstack,
7105 multilib_defaults_raw[i],
7106 strlen (multilib_defaults_raw[i]));
7107 need_space = TRUE;
7110 obstack_1grow (&multilib_obstack, 0);
7111 multilib_defaults = XOBFINISH (&multilib_obstack, const char *);
7115 /* Set up the spec-handling machinery. */
7117 void
7118 driver::set_up_specs () const
7120 const char *spec_machine_suffix;
7121 char *specs_file;
7122 size_t i;
7124 #ifdef INIT_ENVIRONMENT
7125 /* Set up any other necessary machine specific environment variables. */
7126 xputenv (INIT_ENVIRONMENT);
7127 #endif
7129 /* Make a table of what switches there are (switches, n_switches).
7130 Make a table of specified input files (infiles, n_infiles).
7131 Decode switches that are handled locally. */
7133 process_command (decoded_options_count, decoded_options);
7135 /* Initialize the vector of specs to just the default.
7136 This means one element containing 0s, as a terminator. */
7138 compilers = XNEWVAR (struct compiler, sizeof default_compilers);
7139 memcpy (compilers, default_compilers, sizeof default_compilers);
7140 n_compilers = n_default_compilers;
7142 /* Read specs from a file if there is one. */
7144 machine_suffix = concat (spec_host_machine, dir_separator_str, spec_version,
7145 accel_dir_suffix, dir_separator_str, NULL);
7146 just_machine_suffix = concat (spec_machine, dir_separator_str, NULL);
7148 specs_file = find_a_file (&startfile_prefixes, "specs", R_OK, true);
7149 /* Read the specs file unless it is a default one. */
7150 if (specs_file != 0 && strcmp (specs_file, "specs"))
7151 read_specs (specs_file, true, false);
7152 else
7153 init_spec ();
7155 #ifdef ACCEL_COMPILER
7156 spec_machine_suffix = machine_suffix;
7157 #else
7158 spec_machine_suffix = just_machine_suffix;
7159 #endif
7161 /* We need to check standard_exec_prefix/spec_machine_suffix/specs
7162 for any override of as, ld and libraries. */
7163 specs_file = (char *) alloca (strlen (standard_exec_prefix)
7164 + strlen (spec_machine_suffix) + sizeof ("specs"));
7165 strcpy (specs_file, standard_exec_prefix);
7166 strcat (specs_file, spec_machine_suffix);
7167 strcat (specs_file, "specs");
7168 if (access (specs_file, R_OK) == 0)
7169 read_specs (specs_file, true, false);
7171 /* Process any configure-time defaults specified for the command line
7172 options, via OPTION_DEFAULT_SPECS. */
7173 for (i = 0; i < ARRAY_SIZE (option_default_specs); i++)
7174 do_option_spec (option_default_specs[i].name,
7175 option_default_specs[i].spec);
7177 /* Process DRIVER_SELF_SPECS, adding any new options to the end
7178 of the command line. */
7180 for (i = 0; i < ARRAY_SIZE (driver_self_specs); i++)
7181 do_self_spec (driver_self_specs[i]);
7183 /* If not cross-compiling, look for executables in the standard
7184 places. */
7185 if (*cross_compile == '0')
7187 if (*md_exec_prefix)
7189 add_prefix (&exec_prefixes, md_exec_prefix, "GCC",
7190 PREFIX_PRIORITY_LAST, 0, 0);
7194 /* Process sysroot_suffix_spec. */
7195 if (*sysroot_suffix_spec != 0
7196 && !no_sysroot_suffix
7197 && do_spec_2 (sysroot_suffix_spec) == 0)
7199 if (argbuf.length () > 1)
7200 error ("spec failure: more than one arg to SYSROOT_SUFFIX_SPEC");
7201 else if (argbuf.length () == 1)
7202 target_sysroot_suffix = xstrdup (argbuf.last ());
7205 #ifdef HAVE_LD_SYSROOT
7206 /* Pass the --sysroot option to the linker, if it supports that. If
7207 there is a sysroot_suffix_spec, it has already been processed by
7208 this point, so target_system_root really is the system root we
7209 should be using. */
7210 if (target_system_root)
7212 obstack_grow (&obstack, "%(sysroot_spec) ", strlen ("%(sysroot_spec) "));
7213 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
7214 set_spec ("link", XOBFINISH (&obstack, const char *), false);
7216 #endif
7218 /* Process sysroot_hdrs_suffix_spec. */
7219 if (*sysroot_hdrs_suffix_spec != 0
7220 && !no_sysroot_suffix
7221 && do_spec_2 (sysroot_hdrs_suffix_spec) == 0)
7223 if (argbuf.length () > 1)
7224 error ("spec failure: more than one arg to SYSROOT_HEADERS_SUFFIX_SPEC");
7225 else if (argbuf.length () == 1)
7226 target_sysroot_hdrs_suffix = xstrdup (argbuf.last ());
7229 /* Look for startfiles in the standard places. */
7230 if (*startfile_prefix_spec != 0
7231 && do_spec_2 (startfile_prefix_spec) == 0
7232 && do_spec_1 (" ", 0, NULL) == 0)
7234 const char *arg;
7235 int ndx;
7236 FOR_EACH_VEC_ELT (argbuf, ndx, arg)
7237 add_sysrooted_prefix (&startfile_prefixes, arg, "BINUTILS",
7238 PREFIX_PRIORITY_LAST, 0, 1);
7240 /* We should eventually get rid of all these and stick to
7241 startfile_prefix_spec exclusively. */
7242 else if (*cross_compile == '0' || target_system_root)
7244 if (*md_startfile_prefix)
7245 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix,
7246 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
7248 if (*md_startfile_prefix_1)
7249 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix_1,
7250 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
7252 /* If standard_startfile_prefix is relative, base it on
7253 standard_exec_prefix. This lets us move the installed tree
7254 as a unit. If GCC_EXEC_PREFIX is defined, base
7255 standard_startfile_prefix on that as well.
7257 If the prefix is relative, only search it for native compilers;
7258 otherwise we will search a directory containing host libraries. */
7259 if (IS_ABSOLUTE_PATH (standard_startfile_prefix))
7260 add_sysrooted_prefix (&startfile_prefixes,
7261 standard_startfile_prefix, "BINUTILS",
7262 PREFIX_PRIORITY_LAST, 0, 1);
7263 else if (*cross_compile == '0')
7265 add_prefix (&startfile_prefixes,
7266 concat (gcc_exec_prefix
7267 ? gcc_exec_prefix : standard_exec_prefix,
7268 machine_suffix,
7269 standard_startfile_prefix, NULL),
7270 NULL, PREFIX_PRIORITY_LAST, 0, 1);
7273 /* Sysrooted prefixes are relocated because target_system_root is
7274 also relocated by gcc_exec_prefix. */
7275 if (*standard_startfile_prefix_1)
7276 add_sysrooted_prefix (&startfile_prefixes,
7277 standard_startfile_prefix_1, "BINUTILS",
7278 PREFIX_PRIORITY_LAST, 0, 1);
7279 if (*standard_startfile_prefix_2)
7280 add_sysrooted_prefix (&startfile_prefixes,
7281 standard_startfile_prefix_2, "BINUTILS",
7282 PREFIX_PRIORITY_LAST, 0, 1);
7285 /* Process any user specified specs in the order given on the command
7286 line. */
7287 for (struct user_specs *uptr = user_specs_head; uptr; uptr = uptr->next)
7289 char *filename = find_a_file (&startfile_prefixes, uptr->filename,
7290 R_OK, true);
7291 read_specs (filename ? filename : uptr->filename, false, true);
7294 /* Process any user self specs. */
7296 struct spec_list *sl;
7297 for (sl = specs; sl; sl = sl->next)
7298 if (sl->name_len == sizeof "self_spec" - 1
7299 && !strcmp (sl->name, "self_spec"))
7300 do_self_spec (*sl->ptr_spec);
7303 if (compare_debug)
7305 enum save_temps save;
7307 if (!compare_debug_second)
7309 n_switches_debug_check[1] = n_switches;
7310 n_switches_alloc_debug_check[1] = n_switches_alloc;
7311 switches_debug_check[1] = XDUPVEC (struct switchstr, switches,
7312 n_switches_alloc);
7314 do_self_spec ("%:compare-debug-self-opt()");
7315 n_switches_debug_check[0] = n_switches;
7316 n_switches_alloc_debug_check[0] = n_switches_alloc;
7317 switches_debug_check[0] = switches;
7319 n_switches = n_switches_debug_check[1];
7320 n_switches_alloc = n_switches_alloc_debug_check[1];
7321 switches = switches_debug_check[1];
7324 /* Avoid crash when computing %j in this early. */
7325 save = save_temps_flag;
7326 save_temps_flag = SAVE_TEMPS_NONE;
7328 compare_debug = -compare_debug;
7329 do_self_spec ("%:compare-debug-self-opt()");
7331 save_temps_flag = save;
7333 if (!compare_debug_second)
7335 n_switches_debug_check[1] = n_switches;
7336 n_switches_alloc_debug_check[1] = n_switches_alloc;
7337 switches_debug_check[1] = switches;
7338 compare_debug = -compare_debug;
7339 n_switches = n_switches_debug_check[0];
7340 n_switches_alloc = n_switches_debug_check[0];
7341 switches = switches_debug_check[0];
7346 /* If we have a GCC_EXEC_PREFIX envvar, modify it for cpp's sake. */
7347 if (gcc_exec_prefix)
7348 gcc_exec_prefix = concat (gcc_exec_prefix, spec_host_machine,
7349 dir_separator_str, spec_version,
7350 accel_dir_suffix, dir_separator_str, NULL);
7352 /* Now we have the specs.
7353 Set the `valid' bits for switches that match anything in any spec. */
7355 validate_all_switches ();
7357 /* Now that we have the switches and the specs, set
7358 the subdirectory based on the options. */
7359 set_multilib_dir ();
7362 /* Set up to remember the pathname of gcc and any options
7363 needed for collect. We use argv[0] instead of progname because
7364 we need the complete pathname. */
7366 void
7367 driver::putenv_COLLECT_GCC (const char *argv0) const
7369 obstack_init (&collect_obstack);
7370 obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);
7371 obstack_grow (&collect_obstack, argv0, strlen (argv0) + 1);
7372 xputenv (XOBFINISH (&collect_obstack, char *));
7375 /* Set up to remember the pathname of the lto wrapper. */
7377 void
7378 driver::maybe_putenv_COLLECT_LTO_WRAPPER () const
7380 char *lto_wrapper_file;
7382 if (have_c)
7383 lto_wrapper_file = NULL;
7384 else
7385 lto_wrapper_file = find_a_file (&exec_prefixes, "lto-wrapper",
7386 X_OK, false);
7387 if (lto_wrapper_file)
7389 lto_wrapper_file = convert_white_space (lto_wrapper_file);
7390 lto_wrapper_spec = lto_wrapper_file;
7391 obstack_init (&collect_obstack);
7392 obstack_grow (&collect_obstack, "COLLECT_LTO_WRAPPER=",
7393 sizeof ("COLLECT_LTO_WRAPPER=") - 1);
7394 obstack_grow (&collect_obstack, lto_wrapper_spec,
7395 strlen (lto_wrapper_spec) + 1);
7396 xputenv (XOBFINISH (&collect_obstack, char *));
7401 /* Set up to remember the names of offload targets. */
7403 void
7404 driver::maybe_putenv_OFFLOAD_TARGETS () const
7406 const char *targets = offload_targets;
7408 /* If no targets specified by -foffload, use all available targets. */
7409 if (!targets)
7410 targets = OFFLOAD_TARGETS;
7412 if (strlen (targets) > 0)
7414 obstack_grow (&collect_obstack, "OFFLOAD_TARGET_NAMES=",
7415 sizeof ("OFFLOAD_TARGET_NAMES=") - 1);
7416 obstack_grow (&collect_obstack, targets,
7417 strlen (targets) + 1);
7418 xputenv (XOBFINISH (&collect_obstack, char *));
7421 free (offload_targets);
7424 /* Reject switches that no pass was interested in. */
7426 void
7427 driver::handle_unrecognized_options () const
7429 for (size_t i = 0; (int) i < n_switches; i++)
7430 if (! switches[i].validated)
7431 error ("unrecognized command line option %<-%s%>", switches[i].part1);
7434 /* Handle the various -print-* options, returning 0 if the driver
7435 should exit, or nonzero if the driver should continue. */
7438 driver::maybe_print_and_exit () const
7440 if (print_search_dirs)
7442 printf (_("install: %s%s\n"),
7443 gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
7444 gcc_exec_prefix ? "" : machine_suffix);
7445 printf (_("programs: %s\n"),
7446 build_search_list (&exec_prefixes, "", false, false));
7447 printf (_("libraries: %s\n"),
7448 build_search_list (&startfile_prefixes, "", false, true));
7449 return (0);
7452 if (print_file_name)
7454 printf ("%s\n", find_file (print_file_name));
7455 return (0);
7458 if (print_prog_name)
7460 if (use_ld != NULL && ! strcmp (print_prog_name, "ld"))
7462 /* Append USE_LD to to the default linker. */
7463 #ifdef DEFAULT_LINKER
7464 char *ld;
7465 # ifdef HAVE_HOST_EXECUTABLE_SUFFIX
7466 int len = (sizeof (DEFAULT_LINKER)
7467 - sizeof (HOST_EXECUTABLE_SUFFIX));
7468 ld = NULL;
7469 if (len > 0)
7471 char *default_linker = xstrdup (DEFAULT_LINKER);
7472 /* Strip HOST_EXECUTABLE_SUFFIX if DEFAULT_LINKER contains
7473 HOST_EXECUTABLE_SUFFIX. */
7474 if (! strcmp (&default_linker[len], HOST_EXECUTABLE_SUFFIX))
7476 default_linker[len] = '\0';
7477 ld = concat (default_linker, use_ld,
7478 HOST_EXECUTABLE_SUFFIX, NULL);
7481 if (ld == NULL)
7482 # endif
7483 ld = concat (DEFAULT_LINKER, use_ld, NULL);
7484 if (access (ld, X_OK) == 0)
7486 printf ("%s\n", ld);
7487 return (0);
7489 #endif
7490 print_prog_name = concat (print_prog_name, use_ld, NULL);
7492 char *newname = find_a_file (&exec_prefixes, print_prog_name, X_OK, 0);
7493 printf ("%s\n", (newname ? newname : print_prog_name));
7494 return (0);
7497 if (print_multi_lib)
7499 print_multilib_info ();
7500 return (0);
7503 if (print_multi_directory)
7505 if (multilib_dir == NULL)
7506 printf (".\n");
7507 else
7508 printf ("%s\n", multilib_dir);
7509 return (0);
7512 if (print_multiarch)
7514 if (multiarch_dir == NULL)
7515 printf ("\n");
7516 else
7517 printf ("%s\n", multiarch_dir);
7518 return (0);
7521 if (print_sysroot)
7523 if (target_system_root)
7525 if (target_sysroot_suffix)
7526 printf ("%s%s\n", target_system_root, target_sysroot_suffix);
7527 else
7528 printf ("%s\n", target_system_root);
7530 return (0);
7533 if (print_multi_os_directory)
7535 if (multilib_os_dir == NULL)
7536 printf (".\n");
7537 else
7538 printf ("%s\n", multilib_os_dir);
7539 return (0);
7542 if (print_sysroot_headers_suffix)
7544 if (*sysroot_hdrs_suffix_spec)
7546 printf("%s\n", (target_sysroot_hdrs_suffix
7547 ? target_sysroot_hdrs_suffix
7548 : ""));
7549 return (0);
7551 else
7552 /* The error status indicates that only one set of fixed
7553 headers should be built. */
7554 fatal_error (input_location,
7555 "not configured with sysroot headers suffix");
7558 if (print_help_list)
7560 display_help ();
7562 if (! verbose_flag)
7564 printf (_("\nFor bug reporting instructions, please see:\n"));
7565 printf ("%s.\n", bug_report_url);
7567 return (0);
7570 /* We do not exit here. Instead we have created a fake input file
7571 called 'help-dummy' which needs to be compiled, and we pass this
7572 on the various sub-processes, along with the --help switch.
7573 Ensure their output appears after ours. */
7574 fputc ('\n', stdout);
7575 fflush (stdout);
7578 if (print_version)
7580 printf (_("%s %s%s\n"), progname, pkgversion_string,
7581 version_string);
7582 printf ("Copyright %s 2015 Free Software Foundation, Inc.\n",
7583 _("(C)"));
7584 fputs (_("This is free software; see the source for copying conditions. There is NO\n\
7585 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"),
7586 stdout);
7587 if (! verbose_flag)
7588 return 0;
7590 /* We do not exit here. We use the same mechanism of --help to print
7591 the version of the sub-processes. */
7592 fputc ('\n', stdout);
7593 fflush (stdout);
7596 if (verbose_flag)
7598 print_configuration (stderr);
7599 if (n_infiles == 0)
7600 return (0);
7603 return 1;
7606 /* Figure out what to do with each input file.
7607 Return true if we need to exit early from "main", false otherwise. */
7609 bool
7610 driver::prepare_infiles ()
7612 size_t i;
7613 int lang_n_infiles = 0;
7615 if (n_infiles == added_libraries)
7616 fatal_error (input_location, "no input files");
7618 if (seen_error ())
7619 /* Early exit needed from main. */
7620 return true;
7622 /* Make a place to record the compiler output file names
7623 that correspond to the input files. */
7625 i = n_infiles;
7626 i += lang_specific_extra_outfiles;
7627 outfiles = XCNEWVEC (const char *, i);
7629 /* Record which files were specified explicitly as link input. */
7631 explicit_link_files = XCNEWVEC (char, n_infiles);
7633 combine_inputs = have_o || flag_wpa;
7635 for (i = 0; (int) i < n_infiles; i++)
7637 const char *name = infiles[i].name;
7638 struct compiler *compiler = lookup_compiler (name,
7639 strlen (name),
7640 infiles[i].language);
7642 if (compiler && !(compiler->combinable))
7643 combine_inputs = false;
7645 if (lang_n_infiles > 0 && compiler != input_file_compiler
7646 && infiles[i].language && infiles[i].language[0] != '*')
7647 infiles[i].incompiler = compiler;
7648 else if (compiler)
7650 lang_n_infiles++;
7651 input_file_compiler = compiler;
7652 infiles[i].incompiler = compiler;
7654 else
7656 /* Since there is no compiler for this input file, assume it is a
7657 linker file. */
7658 explicit_link_files[i] = 1;
7659 infiles[i].incompiler = NULL;
7661 infiles[i].compiled = false;
7662 infiles[i].preprocessed = false;
7665 if (!combine_inputs && have_c && have_o && lang_n_infiles > 1)
7666 fatal_error (input_location,
7667 "cannot specify -o with -c, -S or -E with multiple files");
7669 /* No early exit needed from main; we can continue. */
7670 return false;
7673 /* Run the spec machinery on each input file. */
7675 void
7676 driver::do_spec_on_infiles () const
7678 size_t i;
7680 for (i = 0; (int) i < n_infiles; i++)
7682 int this_file_error = 0;
7684 /* Tell do_spec what to substitute for %i. */
7686 input_file_number = i;
7687 set_input (infiles[i].name);
7689 if (infiles[i].compiled)
7690 continue;
7692 /* Use the same thing in %o, unless cp->spec says otherwise. */
7694 outfiles[i] = gcc_input_filename;
7696 /* Figure out which compiler from the file's suffix. */
7698 input_file_compiler
7699 = lookup_compiler (infiles[i].name, input_filename_length,
7700 infiles[i].language);
7702 if (input_file_compiler)
7704 /* Ok, we found an applicable compiler. Run its spec. */
7706 if (input_file_compiler->spec[0] == '#')
7708 error ("%s: %s compiler not installed on this system",
7709 gcc_input_filename, &input_file_compiler->spec[1]);
7710 this_file_error = 1;
7712 else
7714 int value;
7716 if (compare_debug)
7718 free (debug_check_temp_file[0]);
7719 debug_check_temp_file[0] = NULL;
7721 free (debug_check_temp_file[1]);
7722 debug_check_temp_file[1] = NULL;
7725 value = do_spec (input_file_compiler->spec);
7726 infiles[i].compiled = true;
7727 if (value < 0)
7728 this_file_error = 1;
7729 else if (compare_debug && debug_check_temp_file[0])
7731 if (verbose_flag)
7732 inform (0, "recompiling with -fcompare-debug");
7734 compare_debug = -compare_debug;
7735 n_switches = n_switches_debug_check[1];
7736 n_switches_alloc = n_switches_alloc_debug_check[1];
7737 switches = switches_debug_check[1];
7739 value = do_spec (input_file_compiler->spec);
7741 compare_debug = -compare_debug;
7742 n_switches = n_switches_debug_check[0];
7743 n_switches_alloc = n_switches_alloc_debug_check[0];
7744 switches = switches_debug_check[0];
7746 if (value < 0)
7748 error ("during -fcompare-debug recompilation");
7749 this_file_error = 1;
7752 gcc_assert (debug_check_temp_file[1]
7753 && filename_cmp (debug_check_temp_file[0],
7754 debug_check_temp_file[1]));
7756 if (verbose_flag)
7757 inform (0, "comparing final insns dumps");
7759 if (compare_files (debug_check_temp_file))
7760 this_file_error = 1;
7763 if (compare_debug)
7765 free (debug_check_temp_file[0]);
7766 debug_check_temp_file[0] = NULL;
7768 free (debug_check_temp_file[1]);
7769 debug_check_temp_file[1] = NULL;
7774 /* If this file's name does not contain a recognized suffix,
7775 record it as explicit linker input. */
7777 else
7778 explicit_link_files[i] = 1;
7780 /* Clear the delete-on-failure queue, deleting the files in it
7781 if this compilation failed. */
7783 if (this_file_error)
7785 delete_failure_queue ();
7786 errorcount++;
7788 /* If this compilation succeeded, don't delete those files later. */
7789 clear_failure_queue ();
7792 /* Reset the input file name to the first compile/object file name, for use
7793 with %b in LINK_SPEC. We use the first input file that we can find
7794 a compiler to compile it instead of using infiles.language since for
7795 languages other than C we use aliases that we then lookup later. */
7796 if (n_infiles > 0)
7798 int i;
7800 for (i = 0; i < n_infiles ; i++)
7801 if (infiles[i].incompiler
7802 || (infiles[i].language && infiles[i].language[0] != '*'))
7804 set_input (infiles[i].name);
7805 break;
7809 if (!seen_error ())
7811 /* Make sure INPUT_FILE_NUMBER points to first available open
7812 slot. */
7813 input_file_number = n_infiles;
7814 if (lang_specific_pre_link ())
7815 errorcount++;
7819 /* If we have to run the linker, do it now. */
7821 void
7822 driver::maybe_run_linker (const char *argv0) const
7824 size_t i;
7825 int linker_was_run = 0;
7826 int num_linker_inputs;
7828 /* Determine if there are any linker input files. */
7829 num_linker_inputs = 0;
7830 for (i = 0; (int) i < n_infiles; i++)
7831 if (explicit_link_files[i] || outfiles[i] != NULL)
7832 num_linker_inputs++;
7834 /* Run ld to link all the compiler output files. */
7836 if (num_linker_inputs > 0 && !seen_error () && print_subprocess_help < 2)
7838 int tmp = execution_count;
7840 if (! have_c)
7842 #if HAVE_LTO_PLUGIN > 0
7843 #if HAVE_LTO_PLUGIN == 2
7844 const char *fno_use_linker_plugin = "fno-use-linker-plugin";
7845 #else
7846 const char *fuse_linker_plugin = "fuse-linker-plugin";
7847 #endif
7848 #endif
7850 /* We'll use ld if we can't find collect2. */
7851 if (! strcmp (linker_name_spec, "collect2"))
7853 char *s = find_a_file (&exec_prefixes, "collect2", X_OK, false);
7854 if (s == NULL)
7855 linker_name_spec = "ld";
7858 #if HAVE_LTO_PLUGIN > 0
7859 #if HAVE_LTO_PLUGIN == 2
7860 if (!switch_matches (fno_use_linker_plugin,
7861 fno_use_linker_plugin
7862 + strlen (fno_use_linker_plugin), 0))
7863 #else
7864 if (switch_matches (fuse_linker_plugin,
7865 fuse_linker_plugin
7866 + strlen (fuse_linker_plugin), 0))
7867 #endif
7869 char *temp_spec = find_a_file (&exec_prefixes,
7870 LTOPLUGINSONAME, R_OK,
7871 false);
7872 if (!temp_spec)
7873 fatal_error (input_location,
7874 "-fuse-linker-plugin, but %s not found",
7875 LTOPLUGINSONAME);
7876 linker_plugin_file_spec = convert_white_space (temp_spec);
7878 #endif
7879 lto_gcc_spec = argv0;
7882 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
7883 for collect. */
7884 putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH", false);
7885 putenv_from_prefixes (&startfile_prefixes, LIBRARY_PATH_ENV, true);
7887 if (print_subprocess_help == 1)
7889 printf (_("\nLinker options\n==============\n\n"));
7890 printf (_("Use \"-Wl,OPTION\" to pass \"OPTION\""
7891 " to the linker.\n\n"));
7892 fflush (stdout);
7894 int value = do_spec (link_command_spec);
7895 if (value < 0)
7896 errorcount = 1;
7897 linker_was_run = (tmp != execution_count);
7900 /* If options said don't run linker,
7901 complain about input files to be given to the linker. */
7903 if (! linker_was_run && !seen_error ())
7904 for (i = 0; (int) i < n_infiles; i++)
7905 if (explicit_link_files[i]
7906 && !(infiles[i].language && infiles[i].language[0] == '*'))
7907 warning (0, "%s: linker input file unused because linking not done",
7908 outfiles[i]);
7911 /* The end of "main". */
7913 void
7914 driver::final_actions () const
7916 /* Delete some or all of the temporary files we made. */
7918 if (seen_error ())
7919 delete_failure_queue ();
7920 delete_temp_files ();
7922 if (print_help_list)
7924 printf (("\nFor bug reporting instructions, please see:\n"));
7925 printf ("%s\n", bug_report_url);
7929 /* Determine what the exit code of the driver should be. */
7932 driver::get_exit_code () const
7934 return (signal_count != 0 ? 2
7935 : seen_error () ? (pass_exit_codes ? greatest_status : 1)
7936 : 0);
7939 /* Find the proper compilation spec for the file name NAME,
7940 whose length is LENGTH. LANGUAGE is the specified language,
7941 or 0 if this file is to be passed to the linker. */
7943 static struct compiler *
7944 lookup_compiler (const char *name, size_t length, const char *language)
7946 struct compiler *cp;
7948 /* If this was specified by the user to be a linker input, indicate that. */
7949 if (language != 0 && language[0] == '*')
7950 return 0;
7952 /* Otherwise, look for the language, if one is spec'd. */
7953 if (language != 0)
7955 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7956 if (cp->suffix[0] == '@' && !strcmp (cp->suffix + 1, language))
7957 return cp;
7959 error ("language %s not recognized", language);
7960 return 0;
7963 /* Look for a suffix. */
7964 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7966 if (/* The suffix `-' matches only the file name `-'. */
7967 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
7968 || (strlen (cp->suffix) < length
7969 /* See if the suffix matches the end of NAME. */
7970 && !strcmp (cp->suffix,
7971 name + length - strlen (cp->suffix))
7973 break;
7976 #if defined (OS2) ||defined (HAVE_DOS_BASED_FILE_SYSTEM)
7977 /* Look again, but case-insensitively this time. */
7978 if (cp < compilers)
7979 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7981 if (/* The suffix `-' matches only the file name `-'. */
7982 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
7983 || (strlen (cp->suffix) < length
7984 /* See if the suffix matches the end of NAME. */
7985 && ((!strcmp (cp->suffix,
7986 name + length - strlen (cp->suffix))
7987 || !strpbrk (cp->suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
7988 && !strcasecmp (cp->suffix,
7989 name + length - strlen (cp->suffix)))
7991 break;
7993 #endif
7995 if (cp >= compilers)
7997 if (cp->spec[0] != '@')
7998 /* A non-alias entry: return it. */
7999 return cp;
8001 /* An alias entry maps a suffix to a language.
8002 Search for the language; pass 0 for NAME and LENGTH
8003 to avoid infinite recursion if language not found. */
8004 return lookup_compiler (NULL, 0, cp->spec + 1);
8006 return 0;
8009 static char *
8010 save_string (const char *s, int len)
8012 char *result = XNEWVEC (char, len + 1);
8014 memcpy (result, s, len);
8015 result[len] = 0;
8016 return result;
8019 void
8020 pfatal_with_name (const char *name)
8022 perror_with_name (name);
8023 delete_temp_files ();
8024 exit (1);
8027 static void
8028 perror_with_name (const char *name)
8030 error ("%s: %m", name);
8033 static inline void
8034 validate_switches_from_spec (const char *spec, bool user)
8036 const char *p = spec;
8037 char c;
8038 while ((c = *p++))
8039 if (c == '%' && (*p == '{' || *p == '<' || (*p == 'W' && *++p == '{')))
8040 /* We have a switch spec. */
8041 p = validate_switches (p + 1, user);
8044 static void
8045 validate_all_switches (void)
8047 struct compiler *comp;
8048 struct spec_list *spec;
8050 for (comp = compilers; comp->spec; comp++)
8051 validate_switches_from_spec (comp->spec, false);
8053 /* Look through the linked list of specs read from the specs file. */
8054 for (spec = specs; spec; spec = spec->next)
8055 validate_switches_from_spec (*spec->ptr_spec, spec->user_p);
8057 validate_switches_from_spec (link_command_spec, false);
8060 /* Look at the switch-name that comes after START
8061 and mark as valid all supplied switches that match it. */
8063 static const char *
8064 validate_switches (const char *start, bool user_spec)
8066 const char *p = start;
8067 const char *atom;
8068 size_t len;
8069 int i;
8070 bool suffix = false;
8071 bool starred = false;
8073 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
8075 next_member:
8076 SKIP_WHITE ();
8078 if (*p == '!')
8079 p++;
8081 SKIP_WHITE ();
8082 if (*p == '.' || *p == ',')
8083 suffix = true, p++;
8085 atom = p;
8086 while (ISIDNUM (*p) || *p == '-' || *p == '+' || *p == '='
8087 || *p == ',' || *p == '.' || *p == '@')
8088 p++;
8089 len = p - atom;
8091 if (*p == '*')
8092 starred = true, p++;
8094 SKIP_WHITE ();
8096 if (!suffix)
8098 /* Mark all matching switches as valid. */
8099 for (i = 0; i < n_switches; i++)
8100 if (!strncmp (switches[i].part1, atom, len)
8101 && (starred || switches[i].part1[len] == '\0')
8102 && (switches[i].known || user_spec))
8103 switches[i].validated = true;
8106 if (*p) p++;
8107 if (*p && (p[-1] == '|' || p[-1] == '&'))
8108 goto next_member;
8110 if (*p && p[-1] == ':')
8112 while (*p && *p != ';' && *p != '}')
8114 if (*p == '%')
8116 p++;
8117 if (*p == '{' || *p == '<')
8118 p = validate_switches (p+1, user_spec);
8119 else if (p[0] == 'W' && p[1] == '{')
8120 p = validate_switches (p+2, user_spec);
8122 else
8123 p++;
8126 if (*p) p++;
8127 if (*p && p[-1] == ';')
8128 goto next_member;
8131 return p;
8132 #undef SKIP_WHITE
8135 struct mdswitchstr
8137 const char *str;
8138 int len;
8141 static struct mdswitchstr *mdswitches;
8142 static int n_mdswitches;
8144 /* Check whether a particular argument was used. The first time we
8145 canonicalize the switches to keep only the ones we care about. */
8147 static int
8148 used_arg (const char *p, int len)
8150 struct mswitchstr
8152 const char *str;
8153 const char *replace;
8154 int len;
8155 int rep_len;
8158 static struct mswitchstr *mswitches;
8159 static int n_mswitches;
8160 int i, j;
8162 if (!mswitches)
8164 struct mswitchstr *matches;
8165 const char *q;
8166 int cnt = 0;
8168 /* Break multilib_matches into the component strings of string
8169 and replacement string. */
8170 for (q = multilib_matches; *q != '\0'; q++)
8171 if (*q == ';')
8172 cnt++;
8174 matches
8175 = (struct mswitchstr *) alloca ((sizeof (struct mswitchstr)) * cnt);
8176 i = 0;
8177 q = multilib_matches;
8178 while (*q != '\0')
8180 matches[i].str = q;
8181 while (*q != ' ')
8183 if (*q == '\0')
8185 invalid_matches:
8186 fatal_error (input_location, "multilib spec %qs is invalid",
8187 multilib_matches);
8189 q++;
8191 matches[i].len = q - matches[i].str;
8193 matches[i].replace = ++q;
8194 while (*q != ';' && *q != '\0')
8196 if (*q == ' ')
8197 goto invalid_matches;
8198 q++;
8200 matches[i].rep_len = q - matches[i].replace;
8201 i++;
8202 if (*q == ';')
8203 q++;
8206 /* Now build a list of the replacement string for switches that we care
8207 about. Make sure we allocate at least one entry. This prevents
8208 xmalloc from calling fatal, and prevents us from re-executing this
8209 block of code. */
8210 mswitches
8211 = XNEWVEC (struct mswitchstr, n_mdswitches + (n_switches ? n_switches : 1));
8212 for (i = 0; i < n_switches; i++)
8213 if ((switches[i].live_cond & SWITCH_IGNORE) == 0)
8215 int xlen = strlen (switches[i].part1);
8216 for (j = 0; j < cnt; j++)
8217 if (xlen == matches[j].len
8218 && ! strncmp (switches[i].part1, matches[j].str, xlen))
8220 mswitches[n_mswitches].str = matches[j].replace;
8221 mswitches[n_mswitches].len = matches[j].rep_len;
8222 mswitches[n_mswitches].replace = (char *) 0;
8223 mswitches[n_mswitches].rep_len = 0;
8224 n_mswitches++;
8225 break;
8229 /* Add MULTILIB_DEFAULTS switches too, as long as they were not present
8230 on the command line nor any options mutually incompatible with
8231 them. */
8232 for (i = 0; i < n_mdswitches; i++)
8234 const char *r;
8236 for (q = multilib_options; *q != '\0'; *q && q++)
8238 while (*q == ' ')
8239 q++;
8241 r = q;
8242 while (strncmp (q, mdswitches[i].str, mdswitches[i].len) != 0
8243 || strchr (" /", q[mdswitches[i].len]) == NULL)
8245 while (*q != ' ' && *q != '/' && *q != '\0')
8246 q++;
8247 if (*q != '/')
8248 break;
8249 q++;
8252 if (*q != ' ' && *q != '\0')
8254 while (*r != ' ' && *r != '\0')
8256 q = r;
8257 while (*q != ' ' && *q != '/' && *q != '\0')
8258 q++;
8260 if (used_arg (r, q - r))
8261 break;
8263 if (*q != '/')
8265 mswitches[n_mswitches].str = mdswitches[i].str;
8266 mswitches[n_mswitches].len = mdswitches[i].len;
8267 mswitches[n_mswitches].replace = (char *) 0;
8268 mswitches[n_mswitches].rep_len = 0;
8269 n_mswitches++;
8270 break;
8273 r = q + 1;
8275 break;
8281 for (i = 0; i < n_mswitches; i++)
8282 if (len == mswitches[i].len && ! strncmp (p, mswitches[i].str, len))
8283 return 1;
8285 return 0;
8288 static int
8289 default_arg (const char *p, int len)
8291 int i;
8293 for (i = 0; i < n_mdswitches; i++)
8294 if (len == mdswitches[i].len && ! strncmp (p, mdswitches[i].str, len))
8295 return 1;
8297 return 0;
8300 /* Work out the subdirectory to use based on the options. The format of
8301 multilib_select is a list of elements. Each element is a subdirectory
8302 name followed by a list of options followed by a semicolon. The format
8303 of multilib_exclusions is the same, but without the preceding
8304 directory. First gcc will check the exclusions, if none of the options
8305 beginning with an exclamation point are present, and all of the other
8306 options are present, then we will ignore this completely. Passing
8307 that, gcc will consider each multilib_select in turn using the same
8308 rules for matching the options. If a match is found, that subdirectory
8309 will be used.
8310 A subdirectory name is optionally followed by a colon and the corresponding
8311 multiarch name. */
8313 static void
8314 set_multilib_dir (void)
8316 const char *p;
8317 unsigned int this_path_len;
8318 const char *this_path, *this_arg;
8319 const char *start, *end;
8320 int not_arg;
8321 int ok, ndfltok, first;
8323 n_mdswitches = 0;
8324 start = multilib_defaults;
8325 while (*start == ' ' || *start == '\t')
8326 start++;
8327 while (*start != '\0')
8329 n_mdswitches++;
8330 while (*start != ' ' && *start != '\t' && *start != '\0')
8331 start++;
8332 while (*start == ' ' || *start == '\t')
8333 start++;
8336 if (n_mdswitches)
8338 int i = 0;
8340 mdswitches = XNEWVEC (struct mdswitchstr, n_mdswitches);
8341 for (start = multilib_defaults; *start != '\0'; start = end + 1)
8343 while (*start == ' ' || *start == '\t')
8344 start++;
8346 if (*start == '\0')
8347 break;
8349 for (end = start + 1;
8350 *end != ' ' && *end != '\t' && *end != '\0'; end++)
8353 obstack_grow (&multilib_obstack, start, end - start);
8354 obstack_1grow (&multilib_obstack, 0);
8355 mdswitches[i].str = XOBFINISH (&multilib_obstack, const char *);
8356 mdswitches[i++].len = end - start;
8358 if (*end == '\0')
8359 break;
8363 p = multilib_exclusions;
8364 while (*p != '\0')
8366 /* Ignore newlines. */
8367 if (*p == '\n')
8369 ++p;
8370 continue;
8373 /* Check the arguments. */
8374 ok = 1;
8375 while (*p != ';')
8377 if (*p == '\0')
8379 invalid_exclusions:
8380 fatal_error (input_location, "multilib exclusions %qs is invalid",
8381 multilib_exclusions);
8384 if (! ok)
8386 ++p;
8387 continue;
8390 this_arg = p;
8391 while (*p != ' ' && *p != ';')
8393 if (*p == '\0')
8394 goto invalid_exclusions;
8395 ++p;
8398 if (*this_arg != '!')
8399 not_arg = 0;
8400 else
8402 not_arg = 1;
8403 ++this_arg;
8406 ok = used_arg (this_arg, p - this_arg);
8407 if (not_arg)
8408 ok = ! ok;
8410 if (*p == ' ')
8411 ++p;
8414 if (ok)
8415 return;
8417 ++p;
8420 first = 1;
8421 p = multilib_select;
8423 /* Append multilib reuse rules if any. With those rules, we can reuse
8424 one multilib for certain different options sets. */
8425 if (strlen (multilib_reuse) > 0)
8426 p = concat (p, multilib_reuse, NULL);
8428 while (*p != '\0')
8430 /* Ignore newlines. */
8431 if (*p == '\n')
8433 ++p;
8434 continue;
8437 /* Get the initial path. */
8438 this_path = p;
8439 while (*p != ' ')
8441 if (*p == '\0')
8443 invalid_select:
8444 fatal_error (input_location, "multilib select %qs %qs is invalid",
8445 multilib_select, multilib_reuse);
8447 ++p;
8449 this_path_len = p - this_path;
8451 /* Check the arguments. */
8452 ok = 1;
8453 ndfltok = 1;
8454 ++p;
8455 while (*p != ';')
8457 if (*p == '\0')
8458 goto invalid_select;
8460 if (! ok)
8462 ++p;
8463 continue;
8466 this_arg = p;
8467 while (*p != ' ' && *p != ';')
8469 if (*p == '\0')
8470 goto invalid_select;
8471 ++p;
8474 if (*this_arg != '!')
8475 not_arg = 0;
8476 else
8478 not_arg = 1;
8479 ++this_arg;
8482 /* If this is a default argument, we can just ignore it.
8483 This is true even if this_arg begins with '!'. Beginning
8484 with '!' does not mean that this argument is necessarily
8485 inappropriate for this library: it merely means that
8486 there is a more specific library which uses this
8487 argument. If this argument is a default, we need not
8488 consider that more specific library. */
8489 ok = used_arg (this_arg, p - this_arg);
8490 if (not_arg)
8491 ok = ! ok;
8493 if (! ok)
8494 ndfltok = 0;
8496 if (default_arg (this_arg, p - this_arg))
8497 ok = 1;
8499 if (*p == ' ')
8500 ++p;
8503 if (ok && first)
8505 if (this_path_len != 1
8506 || this_path[0] != '.')
8508 char *new_multilib_dir = XNEWVEC (char, this_path_len + 1);
8509 char *q;
8511 strncpy (new_multilib_dir, this_path, this_path_len);
8512 new_multilib_dir[this_path_len] = '\0';
8513 q = strchr (new_multilib_dir, ':');
8514 if (q != NULL)
8515 *q = '\0';
8516 multilib_dir = new_multilib_dir;
8518 first = 0;
8521 if (ndfltok)
8523 const char *q = this_path, *end = this_path + this_path_len;
8525 while (q < end && *q != ':')
8526 q++;
8527 if (q < end)
8529 const char *q2 = q + 1, *ml_end = end;
8530 char *new_multilib_os_dir;
8532 while (q2 < end && *q2 != ':')
8533 q2++;
8534 if (*q2 == ':')
8535 ml_end = q2;
8536 if (ml_end - q == 1)
8537 multilib_os_dir = xstrdup (".");
8538 else
8540 new_multilib_os_dir = XNEWVEC (char, ml_end - q);
8541 memcpy (new_multilib_os_dir, q + 1, ml_end - q - 1);
8542 new_multilib_os_dir[ml_end - q - 1] = '\0';
8543 multilib_os_dir = new_multilib_os_dir;
8546 if (q2 < end && *q2 == ':')
8548 char *new_multiarch_dir = XNEWVEC (char, end - q2);
8549 memcpy (new_multiarch_dir, q2 + 1, end - q2 - 1);
8550 new_multiarch_dir[end - q2 - 1] = '\0';
8551 multiarch_dir = new_multiarch_dir;
8553 break;
8557 ++p;
8560 if (multilib_dir == NULL && multilib_os_dir != NULL
8561 && strcmp (multilib_os_dir, ".") == 0)
8563 free (CONST_CAST (char *, multilib_os_dir));
8564 multilib_os_dir = NULL;
8566 else if (multilib_dir != NULL && multilib_os_dir == NULL)
8567 multilib_os_dir = multilib_dir;
8570 /* Print out the multiple library subdirectory selection
8571 information. This prints out a series of lines. Each line looks
8572 like SUBDIRECTORY;@OPTION@OPTION, with as many options as is
8573 required. Only the desired options are printed out, the negative
8574 matches. The options are print without a leading dash. There are
8575 no spaces to make it easy to use the information in the shell.
8576 Each subdirectory is printed only once. This assumes the ordering
8577 generated by the genmultilib script. Also, we leave out ones that match
8578 the exclusions. */
8580 static void
8581 print_multilib_info (void)
8583 const char *p = multilib_select;
8584 const char *last_path = 0, *this_path;
8585 int skip;
8586 unsigned int last_path_len = 0;
8588 while (*p != '\0')
8590 skip = 0;
8591 /* Ignore newlines. */
8592 if (*p == '\n')
8594 ++p;
8595 continue;
8598 /* Get the initial path. */
8599 this_path = p;
8600 while (*p != ' ')
8602 if (*p == '\0')
8604 invalid_select:
8605 fatal_error (input_location,
8606 "multilib select %qs is invalid", multilib_select);
8609 ++p;
8612 /* When --disable-multilib was used but target defines
8613 MULTILIB_OSDIRNAMES, entries starting with .: (and not starting
8614 with .:: for multiarch configurations) are there just to find
8615 multilib_os_dir, so skip them from output. */
8616 if (this_path[0] == '.' && this_path[1] == ':' && this_path[2] != ':')
8617 skip = 1;
8619 /* Check for matches with the multilib_exclusions. We don't bother
8620 with the '!' in either list. If any of the exclusion rules match
8621 all of its options with the select rule, we skip it. */
8623 const char *e = multilib_exclusions;
8624 const char *this_arg;
8626 while (*e != '\0')
8628 int m = 1;
8629 /* Ignore newlines. */
8630 if (*e == '\n')
8632 ++e;
8633 continue;
8636 /* Check the arguments. */
8637 while (*e != ';')
8639 const char *q;
8640 int mp = 0;
8642 if (*e == '\0')
8644 invalid_exclusion:
8645 fatal_error (input_location,
8646 "multilib exclusion %qs is invalid",
8647 multilib_exclusions);
8650 if (! m)
8652 ++e;
8653 continue;
8656 this_arg = e;
8658 while (*e != ' ' && *e != ';')
8660 if (*e == '\0')
8661 goto invalid_exclusion;
8662 ++e;
8665 q = p + 1;
8666 while (*q != ';')
8668 const char *arg;
8669 int len = e - this_arg;
8671 if (*q == '\0')
8672 goto invalid_select;
8674 arg = q;
8676 while (*q != ' ' && *q != ';')
8678 if (*q == '\0')
8679 goto invalid_select;
8680 ++q;
8683 if (! strncmp (arg, this_arg,
8684 (len < q - arg) ? q - arg : len)
8685 || default_arg (this_arg, e - this_arg))
8687 mp = 1;
8688 break;
8691 if (*q == ' ')
8692 ++q;
8695 if (! mp)
8696 m = 0;
8698 if (*e == ' ')
8699 ++e;
8702 if (m)
8704 skip = 1;
8705 break;
8708 if (*e != '\0')
8709 ++e;
8713 if (! skip)
8715 /* If this is a duplicate, skip it. */
8716 skip = (last_path != 0
8717 && (unsigned int) (p - this_path) == last_path_len
8718 && ! filename_ncmp (last_path, this_path, last_path_len));
8720 last_path = this_path;
8721 last_path_len = p - this_path;
8724 /* If this directory requires any default arguments, we can skip
8725 it. We will already have printed a directory identical to
8726 this one which does not require that default argument. */
8727 if (! skip)
8729 const char *q;
8731 q = p + 1;
8732 while (*q != ';')
8734 const char *arg;
8736 if (*q == '\0')
8737 goto invalid_select;
8739 if (*q == '!')
8740 arg = NULL;
8741 else
8742 arg = q;
8744 while (*q != ' ' && *q != ';')
8746 if (*q == '\0')
8747 goto invalid_select;
8748 ++q;
8751 if (arg != NULL
8752 && default_arg (arg, q - arg))
8754 skip = 1;
8755 break;
8758 if (*q == ' ')
8759 ++q;
8763 if (! skip)
8765 const char *p1;
8767 for (p1 = last_path; p1 < p && *p1 != ':'; p1++)
8768 putchar (*p1);
8769 putchar (';');
8772 ++p;
8773 while (*p != ';')
8775 int use_arg;
8777 if (*p == '\0')
8778 goto invalid_select;
8780 if (skip)
8782 ++p;
8783 continue;
8786 use_arg = *p != '!';
8788 if (use_arg)
8789 putchar ('@');
8791 while (*p != ' ' && *p != ';')
8793 if (*p == '\0')
8794 goto invalid_select;
8795 if (use_arg)
8796 putchar (*p);
8797 ++p;
8800 if (*p == ' ')
8801 ++p;
8804 if (! skip)
8806 /* If there are extra options, print them now. */
8807 if (multilib_extra && *multilib_extra)
8809 int print_at = TRUE;
8810 const char *q;
8812 for (q = multilib_extra; *q != '\0'; q++)
8814 if (*q == ' ')
8815 print_at = TRUE;
8816 else
8818 if (print_at)
8819 putchar ('@');
8820 putchar (*q);
8821 print_at = FALSE;
8826 putchar ('\n');
8829 ++p;
8833 /* getenv built-in spec function.
8835 Returns the value of the environment variable given by its first
8836 argument, concatenated with the second argument. If the
8837 environment variable is not defined, a fatal error is issued. */
8839 static const char *
8840 getenv_spec_function (int argc, const char **argv)
8842 char *value;
8843 char *result;
8844 char *ptr;
8845 size_t len;
8847 if (argc != 2)
8848 return NULL;
8850 value = getenv (argv[0]);
8851 if (!value)
8852 fatal_error (input_location,
8853 "environment variable %qs not defined", argv[0]);
8855 /* We have to escape every character of the environment variable so
8856 they are not interpreted as active spec characters. A
8857 particularly painful case is when we are reading a variable
8858 holding a windows path complete with \ separators. */
8859 len = strlen (value) * 2 + strlen (argv[1]) + 1;
8860 result = XNEWVAR (char, len);
8861 for (ptr = result; *value; ptr += 2)
8863 ptr[0] = '\\';
8864 ptr[1] = *value++;
8867 strcpy (ptr, argv[1]);
8869 return result;
8872 /* if-exists built-in spec function.
8874 Checks to see if the file specified by the absolute pathname in
8875 ARGS exists. Returns that pathname if found.
8877 The usual use for this function is to check for a library file
8878 (whose name has been expanded with %s). */
8880 static const char *
8881 if_exists_spec_function (int argc, const char **argv)
8883 /* Must have only one argument. */
8884 if (argc == 1 && IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
8885 return argv[0];
8887 return NULL;
8890 /* if-exists-else built-in spec function.
8892 This is like if-exists, but takes an additional argument which
8893 is returned if the first argument does not exist. */
8895 static const char *
8896 if_exists_else_spec_function (int argc, const char **argv)
8898 /* Must have exactly two arguments. */
8899 if (argc != 2)
8900 return NULL;
8902 if (IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
8903 return argv[0];
8905 return argv[1];
8908 /* sanitize built-in spec function.
8910 This returns non-NULL, if sanitizing address, thread or
8911 any of the undefined behavior sanitizers. */
8913 static const char *
8914 sanitize_spec_function (int argc, const char **argv)
8916 if (argc != 1)
8917 return NULL;
8919 if (strcmp (argv[0], "address") == 0)
8920 return (flag_sanitize & SANITIZE_USER_ADDRESS) ? "" : NULL;
8921 if (strcmp (argv[0], "kernel-address") == 0)
8922 return (flag_sanitize & SANITIZE_KERNEL_ADDRESS) ? "" : NULL;
8923 if (strcmp (argv[0], "thread") == 0)
8924 return (flag_sanitize & SANITIZE_THREAD) ? "" : NULL;
8925 if (strcmp (argv[0], "undefined") == 0)
8926 return ((flag_sanitize & (SANITIZE_UNDEFINED | SANITIZE_NONDEFAULT))
8927 && !flag_sanitize_undefined_trap_on_error) ? "" : NULL;
8928 if (strcmp (argv[0], "leak") == 0)
8929 return ((flag_sanitize
8930 & (SANITIZE_ADDRESS | SANITIZE_LEAK | SANITIZE_THREAD))
8931 == SANITIZE_LEAK) ? "" : NULL;
8932 return NULL;
8935 /* replace-outfile built-in spec function.
8937 This looks for the first argument in the outfiles array's name and
8938 replaces it with the second argument. */
8940 static const char *
8941 replace_outfile_spec_function (int argc, const char **argv)
8943 int i;
8944 /* Must have exactly two arguments. */
8945 if (argc != 2)
8946 abort ();
8948 for (i = 0; i < n_infiles; i++)
8950 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
8951 outfiles[i] = xstrdup (argv[1]);
8953 return NULL;
8956 /* remove-outfile built-in spec function.
8958 * This looks for the first argument in the outfiles array's name and
8959 * removes it. */
8961 static const char *
8962 remove_outfile_spec_function (int argc, const char **argv)
8964 int i;
8965 /* Must have exactly one argument. */
8966 if (argc != 1)
8967 abort ();
8969 for (i = 0; i < n_infiles; i++)
8971 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
8972 outfiles[i] = NULL;
8974 return NULL;
8977 /* Given two version numbers, compares the two numbers.
8978 A version number must match the regular expression
8979 ([1-9][0-9]*|0)(\.([1-9][0-9]*|0))*
8981 static int
8982 compare_version_strings (const char *v1, const char *v2)
8984 int rresult;
8985 regex_t r;
8987 if (regcomp (&r, "^([1-9][0-9]*|0)(\\.([1-9][0-9]*|0))*$",
8988 REG_EXTENDED | REG_NOSUB) != 0)
8989 abort ();
8990 rresult = regexec (&r, v1, 0, NULL, 0);
8991 if (rresult == REG_NOMATCH)
8992 fatal_error (input_location, "invalid version number %qs", v1);
8993 else if (rresult != 0)
8994 abort ();
8995 rresult = regexec (&r, v2, 0, NULL, 0);
8996 if (rresult == REG_NOMATCH)
8997 fatal_error (input_location, "invalid version number %qs", v2);
8998 else if (rresult != 0)
8999 abort ();
9001 return strverscmp (v1, v2);
9005 /* version_compare built-in spec function.
9007 This takes an argument of the following form:
9009 <comparison-op> <arg1> [<arg2>] <switch> <result>
9011 and produces "result" if the comparison evaluates to true,
9012 and nothing if it doesn't.
9014 The supported <comparison-op> values are:
9016 >= true if switch is a later (or same) version than arg1
9017 !> opposite of >=
9018 < true if switch is an earlier version than arg1
9019 !< opposite of <
9020 >< true if switch is arg1 or later, and earlier than arg2
9021 <> true if switch is earlier than arg1 or is arg2 or later
9023 If the switch is not present, the condition is false unless
9024 the first character of the <comparison-op> is '!'.
9026 For example,
9027 %:version-compare(>= 10.3 mmacosx-version-min= -lmx)
9028 adds -lmx if -mmacosx-version-min=10.3.9 was passed. */
9030 static const char *
9031 version_compare_spec_function (int argc, const char **argv)
9033 int comp1, comp2;
9034 size_t switch_len;
9035 const char *switch_value = NULL;
9036 int nargs = 1, i;
9037 bool result;
9039 if (argc < 3)
9040 fatal_error (input_location, "too few arguments to %%:version-compare");
9041 if (argv[0][0] == '\0')
9042 abort ();
9043 if ((argv[0][1] == '<' || argv[0][1] == '>') && argv[0][0] != '!')
9044 nargs = 2;
9045 if (argc != nargs + 3)
9046 fatal_error (input_location, "too many arguments to %%:version-compare");
9048 switch_len = strlen (argv[nargs + 1]);
9049 for (i = 0; i < n_switches; i++)
9050 if (!strncmp (switches[i].part1, argv[nargs + 1], switch_len)
9051 && check_live_switch (i, switch_len))
9052 switch_value = switches[i].part1 + switch_len;
9054 if (switch_value == NULL)
9055 comp1 = comp2 = -1;
9056 else
9058 comp1 = compare_version_strings (switch_value, argv[1]);
9059 if (nargs == 2)
9060 comp2 = compare_version_strings (switch_value, argv[2]);
9061 else
9062 comp2 = -1; /* This value unused. */
9065 switch (argv[0][0] << 8 | argv[0][1])
9067 case '>' << 8 | '=':
9068 result = comp1 >= 0;
9069 break;
9070 case '!' << 8 | '<':
9071 result = comp1 >= 0 || switch_value == NULL;
9072 break;
9073 case '<' << 8:
9074 result = comp1 < 0;
9075 break;
9076 case '!' << 8 | '>':
9077 result = comp1 < 0 || switch_value == NULL;
9078 break;
9079 case '>' << 8 | '<':
9080 result = comp1 >= 0 && comp2 < 0;
9081 break;
9082 case '<' << 8 | '>':
9083 result = comp1 < 0 || comp2 >= 0;
9084 break;
9086 default:
9087 fatal_error (input_location,
9088 "unknown operator %qs in %%:version-compare", argv[0]);
9090 if (! result)
9091 return NULL;
9093 return argv[nargs + 2];
9096 /* %:include builtin spec function. This differs from %include in that it
9097 can be nested inside a spec, and thus be conditionalized. It takes
9098 one argument, the filename, and looks for it in the startfile path.
9099 The result is always NULL, i.e. an empty expansion. */
9101 static const char *
9102 include_spec_function (int argc, const char **argv)
9104 char *file;
9106 if (argc != 1)
9107 abort ();
9109 file = find_a_file (&startfile_prefixes, argv[0], R_OK, true);
9110 read_specs (file ? file : argv[0], false, false);
9112 return NULL;
9115 /* %:find-file spec function. This function replaces its argument by
9116 the file found through find_file, that is the -print-file-name gcc
9117 program option. */
9118 static const char *
9119 find_file_spec_function (int argc, const char **argv)
9121 const char *file;
9123 if (argc != 1)
9124 abort ();
9126 file = find_file (argv[0]);
9127 return file;
9131 /* %:find-plugindir spec function. This function replaces its argument
9132 by the -iplugindir=<dir> option. `dir' is found through find_file, that
9133 is the -print-file-name gcc program option. */
9134 static const char *
9135 find_plugindir_spec_function (int argc, const char **argv ATTRIBUTE_UNUSED)
9137 const char *option;
9139 if (argc != 0)
9140 abort ();
9142 option = concat ("-iplugindir=", find_file ("plugin"), NULL);
9143 return option;
9147 /* %:print-asm-header spec function. Print a banner to say that the
9148 following output is from the assembler. */
9150 static const char *
9151 print_asm_header_spec_function (int arg ATTRIBUTE_UNUSED,
9152 const char **argv ATTRIBUTE_UNUSED)
9154 printf (_("Assembler options\n=================\n\n"));
9155 printf (_("Use \"-Wa,OPTION\" to pass \"OPTION\" to the assembler.\n\n"));
9156 fflush (stdout);
9157 return NULL;
9160 /* Get a random number for -frandom-seed */
9162 static unsigned HOST_WIDE_INT
9163 get_random_number (void)
9165 unsigned HOST_WIDE_INT ret = 0;
9166 int fd;
9168 fd = open ("/dev/urandom", O_RDONLY);
9169 if (fd >= 0)
9171 read (fd, &ret, sizeof (HOST_WIDE_INT));
9172 close (fd);
9173 if (ret)
9174 return ret;
9177 /* Get some more or less random data. */
9178 #ifdef HAVE_GETTIMEOFDAY
9180 struct timeval tv;
9182 gettimeofday (&tv, NULL);
9183 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
9185 #else
9187 time_t now = time (NULL);
9189 if (now != (time_t)-1)
9190 ret = (unsigned) now;
9192 #endif
9194 return ret ^ getpid ();
9197 /* %:compare-debug-dump-opt spec function. Save the last argument,
9198 expected to be the last -fdump-final-insns option, or generate a
9199 temporary. */
9201 static const char *
9202 compare_debug_dump_opt_spec_function (int arg,
9203 const char **argv ATTRIBUTE_UNUSED)
9205 char *ret;
9206 char *name;
9207 int which;
9208 static char random_seed[HOST_BITS_PER_WIDE_INT / 4 + 3];
9210 if (arg != 0)
9211 fatal_error (input_location,
9212 "too many arguments to %%:compare-debug-dump-opt");
9214 do_spec_2 ("%{fdump-final-insns=*:%*}");
9215 do_spec_1 (" ", 0, NULL);
9217 if (argbuf.length () > 0
9218 && strcmp (argv[argbuf.length () - 1], "."))
9220 if (!compare_debug)
9221 return NULL;
9223 name = xstrdup (argv[argbuf.length () - 1]);
9224 ret = NULL;
9226 else
9228 const char *ext = NULL;
9230 if (argbuf.length () > 0)
9232 do_spec_2 ("%{o*:%*}%{!o:%{!S:%b%O}%{S:%b.s}}");
9233 ext = ".gkd";
9235 else if (!compare_debug)
9236 return NULL;
9237 else
9238 do_spec_2 ("%g.gkd");
9240 do_spec_1 (" ", 0, NULL);
9242 gcc_assert (argbuf.length () > 0);
9244 name = concat (argbuf.last (), ext, NULL);
9246 ret = concat ("-fdump-final-insns=", name, NULL);
9249 which = compare_debug < 0;
9250 debug_check_temp_file[which] = name;
9252 if (!which)
9254 unsigned HOST_WIDE_INT value = get_random_number ();
9256 sprintf (random_seed, HOST_WIDE_INT_PRINT_HEX, value);
9259 if (*random_seed)
9261 char *tmp = ret;
9262 ret = concat ("%{!frandom-seed=*:-frandom-seed=", random_seed, "} ",
9263 ret, NULL);
9264 free (tmp);
9267 if (which)
9268 *random_seed = 0;
9270 return ret;
9273 static const char *debug_auxbase_opt;
9275 /* %:compare-debug-self-opt spec function. Expands to the options
9276 that are to be passed in the second compilation of
9277 compare-debug. */
9279 static const char *
9280 compare_debug_self_opt_spec_function (int arg,
9281 const char **argv ATTRIBUTE_UNUSED)
9283 if (arg != 0)
9284 fatal_error (input_location,
9285 "too many arguments to %%:compare-debug-self-opt");
9287 if (compare_debug >= 0)
9288 return NULL;
9290 do_spec_2 ("%{c|S:%{o*:%*}}");
9291 do_spec_1 (" ", 0, NULL);
9293 if (argbuf.length () > 0)
9294 debug_auxbase_opt = concat ("-auxbase-strip ",
9295 argbuf.last (),
9296 NULL);
9297 else
9298 debug_auxbase_opt = NULL;
9300 return concat ("\
9301 %<o %<MD %<MMD %<MF* %<MG %<MP %<MQ* %<MT* \
9302 %<fdump-final-insns=* -w -S -o %j \
9303 %{!fcompare-debug-second:-fcompare-debug-second} \
9304 ", compare_debug_opt, NULL);
9307 /* %:compare-debug-auxbase-opt spec function. Expands to the auxbase
9308 options that are to be passed in the second compilation of
9309 compare-debug. It expects, as an argument, the basename of the
9310 current input file name, with the .gk suffix appended to it. */
9312 static const char *
9313 compare_debug_auxbase_opt_spec_function (int arg,
9314 const char **argv)
9316 char *name;
9317 int len;
9319 if (arg == 0)
9320 fatal_error (input_location,
9321 "too few arguments to %%:compare-debug-auxbase-opt");
9323 if (arg != 1)
9324 fatal_error (input_location,
9325 "too many arguments to %%:compare-debug-auxbase-opt");
9327 if (compare_debug >= 0)
9328 return NULL;
9330 len = strlen (argv[0]);
9331 if (len < 3 || strcmp (argv[0] + len - 3, ".gk") != 0)
9332 fatal_error (input_location, "argument to %%:compare-debug-auxbase-opt "
9333 "does not end in .gk");
9335 if (debug_auxbase_opt)
9336 return debug_auxbase_opt;
9338 #define OPT "-auxbase "
9340 len -= 3;
9341 name = (char*) xmalloc (sizeof (OPT) + len);
9342 memcpy (name, OPT, sizeof (OPT) - 1);
9343 memcpy (name + sizeof (OPT) - 1, argv[0], len);
9344 name[sizeof (OPT) - 1 + len] = '\0';
9346 #undef OPT
9348 return name;
9351 /* %:pass-through-libs spec function. Finds all -l options and input
9352 file names in the lib spec passed to it, and makes a list of them
9353 prepended with the plugin option to cause them to be passed through
9354 to the final link after all the new object files have been added. */
9356 const char *
9357 pass_through_libs_spec_func (int argc, const char **argv)
9359 char *prepended = xstrdup (" ");
9360 int n;
9361 /* Shlemiel the painter's algorithm. Innately horrible, but at least
9362 we know that there will never be more than a handful of strings to
9363 concat, and it's only once per run, so it's not worth optimising. */
9364 for (n = 0; n < argc; n++)
9366 char *old = prepended;
9367 /* Anything that isn't an option is a full path to an output
9368 file; pass it through if it ends in '.a'. Among options,
9369 pass only -l. */
9370 if (argv[n][0] == '-' && argv[n][1] == 'l')
9372 const char *lopt = argv[n] + 2;
9373 /* Handle both joined and non-joined -l options. If for any
9374 reason there's a trailing -l with no joined or following
9375 arg just discard it. */
9376 if (!*lopt && ++n >= argc)
9377 break;
9378 else if (!*lopt)
9379 lopt = argv[n];
9380 prepended = concat (prepended, "-plugin-opt=-pass-through=-l",
9381 lopt, " ", NULL);
9383 else if (!strcmp (".a", argv[n] + strlen (argv[n]) - 2))
9385 prepended = concat (prepended, "-plugin-opt=-pass-through=",
9386 argv[n], " ", NULL);
9388 if (prepended != old)
9389 free (old);
9391 return prepended;
9394 /* %:replace-extension spec function. Replaces the extension of the
9395 first argument with the second argument. */
9397 const char *
9398 replace_extension_spec_func (int argc, const char **argv)
9400 char *name;
9401 char *p;
9402 char *result;
9403 int i;
9405 if (argc != 2)
9406 fatal_error (input_location, "too few arguments to %%:replace-extension");
9408 name = xstrdup (argv[0]);
9410 for (i = strlen (name) - 1; i >= 0; i--)
9411 if (IS_DIR_SEPARATOR (name[i]))
9412 break;
9414 p = strrchr (name + i + 1, '.');
9415 if (p != NULL)
9416 *p = '\0';
9418 result = concat (name, argv[1], NULL);
9420 free (name);
9421 return result;
9424 /* Insert backslash before spaces in ORIG (usually a file path), to
9425 avoid being broken by spec parser.
9427 This function is needed as do_spec_1 treats white space (' ' and '\t')
9428 as the end of an argument. But in case of -plugin /usr/gcc install/xxx.so,
9429 the file name should be treated as a single argument rather than being
9430 broken into multiple. Solution is to insert '\\' before the space in a
9431 file name.
9433 This function converts and only converts all occurrence of ' '
9434 to '\\' + ' ' and '\t' to '\\' + '\t'. For example:
9435 "a b" -> "a\\ b"
9436 "a b" -> "a\\ \\ b"
9437 "a\tb" -> "a\\\tb"
9438 "a\\ b" -> "a\\\\ b"
9440 orig: input null-terminating string that was allocated by xalloc. The
9441 memory it points to might be freed in this function. Behavior undefined
9442 if ORIG wasn't xalloced or was freed already at entry.
9444 Return: ORIG if no conversion needed. Otherwise a newly allocated string
9445 that was converted from ORIG. */
9447 static char *
9448 convert_white_space (char *orig)
9450 int len, number_of_space = 0;
9452 for (len = 0; orig[len]; len++)
9453 if (orig[len] == ' ' || orig[len] == '\t') number_of_space++;
9455 if (number_of_space)
9457 char *new_spec = (char *) xmalloc (len + number_of_space + 1);
9458 int j, k;
9459 for (j = 0, k = 0; j <= len; j++, k++)
9461 if (orig[j] == ' ' || orig[j] == '\t')
9462 new_spec[k++] = '\\';
9463 new_spec[k] = orig[j];
9465 free (orig);
9466 return new_spec;
9468 else
9469 return orig;
9472 /* PR jit/64810.
9473 Targets can provide configure-time default options in
9474 OPTION_DEFAULT_SPECS. The jit needs to access these, but
9475 they are expressed in the spec language.
9477 Run just enough of the driver to be able to expand these
9478 specs, and then call the callback CB on each
9479 such option. The options strings are *without* a leading
9480 '-' character e.g. ("march=x86-64"). Finally, clean up. */
9482 void
9483 driver_get_configure_time_options (void (*cb) (const char *option,
9484 void *user_data),
9485 void *user_data)
9487 size_t i;
9489 obstack_init (&obstack);
9490 gcc_obstack_init (&opts_obstack);
9491 n_switches = 0;
9493 for (i = 0; i < ARRAY_SIZE (option_default_specs); i++)
9494 do_option_spec (option_default_specs[i].name,
9495 option_default_specs[i].spec);
9497 for (i = 0; (int) i < n_switches; i++)
9499 gcc_assert (switches[i].part1);
9500 (*cb) (switches[i].part1, user_data);
9503 obstack_free (&opts_obstack, NULL);
9504 obstack_free (&obstack, NULL);
9505 n_switches = 0;