RISC-V: Make stack_save_restore tests more robust
[official-gcc.git] / gcc / gcc.cc
bloba9dd0eb655c5394b692d5376368c2739d1b42ef6
1 /* Compiler driver program that can handle many languages.
2 Copyright (C) 1987-2023 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 #define INCLUDE_STRING
31 #include "config.h"
32 #include "system.h"
33 #include "coretypes.h"
34 #include "multilib.h" /* before tm.h */
35 #include "tm.h"
36 #include "xregex.h"
37 #include "obstack.h"
38 #include "intl.h"
39 #include "prefix.h"
40 #include "opt-suggestions.h"
41 #include "gcc.h"
42 #include "diagnostic.h"
43 #include "flags.h"
44 #include "opts.h"
45 #include "filenames.h"
46 #include "spellcheck.h"
47 #include "opts-jobserver.h"
48 #include "common/common-target.h"
49 #include "diagnostic-text-art.h"
51 #ifndef MATH_LIBRARY
52 #define MATH_LIBRARY "m"
53 #endif
56 /* Manage the manipulation of env vars.
58 We poison "getenv" and "putenv", so that all enviroment-handling is
59 done through this class. Note that poisoning happens in the
60 preprocessor at the identifier level, and doesn't distinguish between
61 env.getenv ();
62 and
63 getenv ();
64 Hence we need to use "get" for the accessor method, not "getenv". */
66 struct env_manager
68 public:
69 void init (bool can_restore, bool debug);
70 const char *get (const char *name);
71 void xput (const char *string);
72 void restore ();
74 private:
75 bool m_can_restore;
76 bool m_debug;
77 struct kv
79 char *m_key;
80 char *m_value;
82 vec<kv> m_keys;
86 /* The singleton instance of class env_manager. */
88 static env_manager env;
90 /* Initializer for class env_manager.
92 We can't do this as a constructor since we have a statically
93 allocated instance ("env" above). */
95 void
96 env_manager::init (bool can_restore, bool debug)
98 m_can_restore = can_restore;
99 m_debug = debug;
102 /* Get the value of NAME within the environment. Essentially
103 a wrapper for ::getenv, but adding logging, and the possibility
104 of caching results. */
106 const char *
107 env_manager::get (const char *name)
109 const char *result = ::getenv (name);
110 if (m_debug)
111 fprintf (stderr, "env_manager::getenv (%s) -> %s\n", name, result);
112 return result;
115 /* Put the given KEY=VALUE entry STRING into the environment.
116 If the env_manager was initialized with CAN_RESTORE set, then
117 also record the old value of KEY within the environment, so that it
118 can be later restored. */
120 void
121 env_manager::xput (const char *string)
123 if (m_debug)
124 fprintf (stderr, "env_manager::xput (%s)\n", string);
125 if (verbose_flag)
126 fnotice (stderr, "%s\n", string);
128 if (m_can_restore)
130 char *equals = strchr (const_cast <char *> (string), '=');
131 gcc_assert (equals);
133 struct kv kv;
134 kv.m_key = xstrndup (string, equals - string);
135 const char *cur_value = ::getenv (kv.m_key);
136 if (m_debug)
137 fprintf (stderr, "saving old value: %s\n",cur_value);
138 kv.m_value = cur_value ? xstrdup (cur_value) : NULL;
139 m_keys.safe_push (kv);
142 ::putenv (CONST_CAST (char *, string));
145 /* Undo any xputenv changes made since last restore.
146 Can only be called if the env_manager was initialized with
147 CAN_RESTORE enabled. */
149 void
150 env_manager::restore ()
152 unsigned int i;
153 struct kv *item;
155 gcc_assert (m_can_restore);
157 FOR_EACH_VEC_ELT_REVERSE (m_keys, i, item)
159 if (m_debug)
160 printf ("restoring saved key: %s value: %s\n", item->m_key, item->m_value);
161 if (item->m_value)
162 ::setenv (item->m_key, item->m_value, 1);
163 else
164 ::unsetenv (item->m_key);
165 free (item->m_key);
166 free (item->m_value);
169 m_keys.truncate (0);
172 /* Forbid other uses of getenv and putenv. */
173 #if (GCC_VERSION >= 3000)
174 #pragma GCC poison getenv putenv
175 #endif
179 /* By default there is no special suffix for target executables. */
180 #ifdef TARGET_EXECUTABLE_SUFFIX
181 #define HAVE_TARGET_EXECUTABLE_SUFFIX
182 #else
183 #define TARGET_EXECUTABLE_SUFFIX ""
184 #endif
186 /* By default there is no special suffix for host executables. */
187 #ifdef HOST_EXECUTABLE_SUFFIX
188 #define HAVE_HOST_EXECUTABLE_SUFFIX
189 #else
190 #define HOST_EXECUTABLE_SUFFIX ""
191 #endif
193 /* By default, the suffix for target object files is ".o". */
194 #ifdef TARGET_OBJECT_SUFFIX
195 #define HAVE_TARGET_OBJECT_SUFFIX
196 #else
197 #define TARGET_OBJECT_SUFFIX ".o"
198 #endif
200 static const char dir_separator_str[] = { DIR_SEPARATOR, 0 };
202 /* Most every one is fine with LIBRARY_PATH. For some, it conflicts. */
203 #ifndef LIBRARY_PATH_ENV
204 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
205 #endif
207 /* If a stage of compilation returns an exit status >= 1,
208 compilation of that file ceases. */
210 #define MIN_FATAL_STATUS 1
212 /* Flag set by cppspec.cc to 1. */
213 int is_cpp_driver;
215 /* Flag set to nonzero if an @file argument has been supplied to gcc. */
216 static bool at_file_supplied;
218 /* Definition of string containing the arguments given to configure. */
219 #include "configargs.h"
221 /* Flag saying to print the command line options understood by gcc and its
222 sub-processes. */
224 static int print_help_list;
226 /* Flag saying to print the version of gcc and its sub-processes. */
228 static int print_version;
230 /* Flag that stores string prefix for which we provide bash completion. */
232 static const char *completion = NULL;
234 /* Flag indicating whether we should ONLY print the command and
235 arguments (like verbose_flag) without executing the command.
236 Displayed arguments are quoted so that the generated command
237 line is suitable for execution. This is intended for use in
238 shell scripts to capture the driver-generated command line. */
239 static int verbose_only_flag;
241 /* Flag indicating how to print command line options of sub-processes. */
243 static int print_subprocess_help;
245 /* Linker suffix passed to -fuse-ld=... */
246 static const char *use_ld;
248 /* Whether we should report subprocess execution times to a file. */
250 FILE *report_times_to_file = NULL;
252 /* Nonzero means place this string before uses of /, so that include
253 and library files can be found in an alternate location. */
255 #ifdef TARGET_SYSTEM_ROOT
256 #define DEFAULT_TARGET_SYSTEM_ROOT (TARGET_SYSTEM_ROOT)
257 #else
258 #define DEFAULT_TARGET_SYSTEM_ROOT (0)
259 #endif
260 static const char *target_system_root = DEFAULT_TARGET_SYSTEM_ROOT;
262 /* Nonzero means pass the updated target_system_root to the compiler. */
264 static int target_system_root_changed;
266 /* Nonzero means append this string to target_system_root. */
268 static const char *target_sysroot_suffix = 0;
270 /* Nonzero means append this string to target_system_root for headers. */
272 static const char *target_sysroot_hdrs_suffix = 0;
274 /* Nonzero means write "temp" files in source directory
275 and use the source file's name in them, and don't delete them. */
277 static enum save_temps {
278 SAVE_TEMPS_NONE, /* no -save-temps */
279 SAVE_TEMPS_CWD, /* -save-temps in current directory */
280 SAVE_TEMPS_DUMP, /* -save-temps in dumpdir */
281 SAVE_TEMPS_OBJ /* -save-temps in object directory */
282 } save_temps_flag;
284 /* Set this iff the dumppfx implied by a -save-temps=* option is to
285 override a -dumpdir option, if any. */
286 static bool save_temps_overrides_dumpdir = false;
288 /* -dumpdir, -dumpbase and -dumpbase-ext flags passed in, possibly
289 rearranged as they are to be passed down, e.g., dumpbase and
290 dumpbase_ext may be cleared if integrated with dumpdir or
291 dropped. */
292 static char *dumpdir, *dumpbase, *dumpbase_ext;
294 /* Usually the length of the string in dumpdir. However, during
295 linking, it may be shortened to omit a driver-added trailing dash,
296 by then replaced with a trailing period, that is still to be passed
297 to sub-processes in -dumpdir, but not to be generally used in spec
298 filename expansions. See maybe_run_linker. */
299 static size_t dumpdir_length = 0;
301 /* Set if the last character in dumpdir is (or was) a dash that the
302 driver added to dumpdir after dumpbase or linker output name. */
303 static bool dumpdir_trailing_dash_added = false;
305 /* Basename of dump and aux outputs, computed from dumpbase (given or
306 derived from output name), to override input_basename in non-%w %b
307 et al. */
308 static char *outbase;
309 static size_t outbase_length = 0;
311 /* The compiler version. */
313 static const char *compiler_version;
315 /* The target version. */
317 static const char *const spec_version = DEFAULT_TARGET_VERSION;
319 /* The target machine. */
321 static const char *spec_machine = DEFAULT_TARGET_MACHINE;
322 static const char *spec_host_machine = DEFAULT_REAL_TARGET_MACHINE;
324 /* List of offload targets. Separated by colon. Empty string for
325 -foffload=disable. */
327 static char *offload_targets = NULL;
329 #if OFFLOAD_DEFAULTED
330 /* Set to true if -foffload has not been used and offload_targets
331 is set to the configured in default. */
332 static bool offload_targets_default;
333 #endif
335 /* Nonzero if cross-compiling.
336 When -b is used, the value comes from the `specs' file. */
338 #ifdef CROSS_DIRECTORY_STRUCTURE
339 static const char *cross_compile = "1";
340 #else
341 static const char *cross_compile = "0";
342 #endif
344 /* Greatest exit code of sub-processes that has been encountered up to
345 now. */
346 static int greatest_status = 1;
348 /* This is the obstack which we use to allocate many strings. */
350 static struct obstack obstack;
352 /* This is the obstack to build an environment variable to pass to
353 collect2 that describes all of the relevant switches of what to
354 pass the compiler in building the list of pointers to constructors
355 and destructors. */
357 static struct obstack collect_obstack;
359 /* Forward declaration for prototypes. */
360 struct path_prefix;
361 struct prefix_list;
363 static void init_spec (void);
364 static void store_arg (const char *, int, int);
365 static void insert_wrapper (const char *);
366 static char *load_specs (const char *);
367 static void read_specs (const char *, bool, bool);
368 static void set_spec (const char *, const char *, bool);
369 static struct compiler *lookup_compiler (const char *, size_t, const char *);
370 static char *build_search_list (const struct path_prefix *, const char *,
371 bool, bool);
372 static void xputenv (const char *);
373 static void putenv_from_prefixes (const struct path_prefix *, const char *,
374 bool);
375 static int access_check (const char *, int);
376 static char *find_a_file (const struct path_prefix *, const char *, int, bool);
377 static char *find_a_program (const char *);
378 static void add_prefix (struct path_prefix *, const char *, const char *,
379 int, int, int);
380 static void add_sysrooted_prefix (struct path_prefix *, const char *,
381 const char *, int, int, int);
382 static char *skip_whitespace (char *);
383 static void delete_if_ordinary (const char *);
384 static void delete_temp_files (void);
385 static void delete_failure_queue (void);
386 static void clear_failure_queue (void);
387 static int check_live_switch (int, int);
388 static const char *handle_braces (const char *);
389 static inline bool input_suffix_matches (const char *, const char *);
390 static inline bool switch_matches (const char *, const char *, int);
391 static inline void mark_matching_switches (const char *, const char *, int);
392 static inline void process_marked_switches (void);
393 static const char *process_brace_body (const char *, const char *, const char *, int, int);
394 static const struct spec_function *lookup_spec_function (const char *);
395 static const char *eval_spec_function (const char *, const char *, const char *);
396 static const char *handle_spec_function (const char *, bool *, const char *);
397 static char *save_string (const char *, int);
398 static void set_collect_gcc_options (void);
399 static int do_spec_1 (const char *, int, const char *);
400 static int do_spec_2 (const char *, const char *);
401 static void do_option_spec (const char *, const char *);
402 static void do_self_spec (const char *);
403 static const char *find_file (const char *);
404 static int is_directory (const char *, bool);
405 static const char *validate_switches (const char *, bool, bool);
406 static void validate_all_switches (void);
407 static inline void validate_switches_from_spec (const char *, bool);
408 static void give_switch (int, int);
409 static int default_arg (const char *, int);
410 static void set_multilib_dir (void);
411 static void print_multilib_info (void);
412 static void display_help (void);
413 static void add_preprocessor_option (const char *, int);
414 static void add_assembler_option (const char *, int);
415 static void add_linker_option (const char *, int);
416 static void process_command (unsigned int, struct cl_decoded_option *);
417 static int execute (void);
418 static void alloc_args (void);
419 static void clear_args (void);
420 static void fatal_signal (int);
421 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
422 static void init_gcc_specs (struct obstack *, const char *, const char *,
423 const char *);
424 #endif
425 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
426 static const char *convert_filename (const char *, int, int);
427 #endif
429 static void try_generate_repro (const char **argv);
430 static const char *getenv_spec_function (int, const char **);
431 static const char *if_exists_spec_function (int, const char **);
432 static const char *if_exists_else_spec_function (int, const char **);
433 static const char *if_exists_then_else_spec_function (int, const char **);
434 static const char *sanitize_spec_function (int, const char **);
435 static const char *replace_outfile_spec_function (int, const char **);
436 static const char *remove_outfile_spec_function (int, const char **);
437 static const char *version_compare_spec_function (int, const char **);
438 static const char *include_spec_function (int, const char **);
439 static const char *find_file_spec_function (int, const char **);
440 static const char *find_plugindir_spec_function (int, const char **);
441 static const char *print_asm_header_spec_function (int, const char **);
442 static const char *compare_debug_dump_opt_spec_function (int, const char **);
443 static const char *compare_debug_self_opt_spec_function (int, const char **);
444 static const char *pass_through_libs_spec_func (int, const char **);
445 static const char *dumps_spec_func (int, const char **);
446 static const char *greater_than_spec_func (int, const char **);
447 static const char *debug_level_greater_than_spec_func (int, const char **);
448 static const char *dwarf_version_greater_than_spec_func (int, const char **);
449 static const char *find_fortran_preinclude_file (int, const char **);
450 static char *convert_white_space (char *);
451 static char *quote_spec (char *);
452 static char *quote_spec_arg (char *);
453 static bool not_actual_file_p (const char *);
456 /* The Specs Language
458 Specs are strings containing lines, each of which (if not blank)
459 is made up of a program name, and arguments separated by spaces.
460 The program name must be exact and start from root, since no path
461 is searched and it is unreliable to depend on the current working directory.
462 Redirection of input or output is not supported; the subprograms must
463 accept filenames saying what files to read and write.
465 In addition, the specs can contain %-sequences to substitute variable text
466 or for conditional text. Here is a table of all defined %-sequences.
467 Note that spaces are not generated automatically around the results of
468 expanding these sequences; therefore, you can concatenate them together
469 or with constant text in a single argument.
471 %% substitute one % into the program name or argument.
472 %" substitute an empty argument.
473 %i substitute the name of the input file being processed.
474 %b substitute the basename for outputs related with the input file
475 being processed. This is often a substring of the input file name,
476 up to (and not including) the last period but, unless %w is active,
477 it is affected by the directory selected by -save-temps=*, by
478 -dumpdir, and, in case of multiple compilations, even by -dumpbase
479 and -dumpbase-ext and, in case of linking, by the linker output
480 name. When %w is active, it derives the main output name only from
481 the input file base name; when it is not, it names aux/dump output
482 file.
483 %B same as %b, but include the input file suffix (text after the last
484 period).
485 %gSUFFIX
486 substitute a file name that has suffix SUFFIX and is chosen
487 once per compilation, and mark the argument a la %d. To reduce
488 exposure to denial-of-service attacks, the file name is now
489 chosen in a way that is hard to predict even when previously
490 chosen file names are known. For example, `%g.s ... %g.o ... %g.s'
491 might turn into `ccUVUUAU.s ccXYAXZ12.o ccUVUUAU.s'. SUFFIX matches
492 the regexp "[.0-9A-Za-z]*%O"; "%O" is treated exactly as if it
493 had been pre-processed. Previously, %g was simply substituted
494 with a file name chosen once per compilation, without regard
495 to any appended suffix (which was therefore treated just like
496 ordinary text), making such attacks more likely to succeed.
497 %|SUFFIX
498 like %g, but if -pipe is in effect, expands simply to "-".
499 %mSUFFIX
500 like %g, but if -pipe is in effect, expands to nothing. (We have both
501 %| and %m to accommodate differences between system assemblers; see
502 the AS_NEEDS_DASH_FOR_PIPED_INPUT target macro.)
503 %uSUFFIX
504 like %g, but generates a new temporary file name even if %uSUFFIX
505 was already seen.
506 %USUFFIX
507 substitutes the last file name generated with %uSUFFIX, generating a
508 new one if there is no such last file name. In the absence of any
509 %uSUFFIX, this is just like %gSUFFIX, except they don't share
510 the same suffix "space", so `%g.s ... %U.s ... %g.s ... %U.s'
511 would involve the generation of two distinct file names, one
512 for each `%g.s' and another for each `%U.s'. Previously, %U was
513 simply substituted with a file name chosen for the previous %u,
514 without regard to any appended suffix.
515 %jSUFFIX
516 substitutes the name of the HOST_BIT_BUCKET, if any, and if it is
517 writable, and if save-temps is off; otherwise, substitute the name
518 of a temporary file, just like %u. This temporary file is not
519 meant for communication between processes, but rather as a junk
520 disposal mechanism.
521 %.SUFFIX
522 substitutes .SUFFIX for the suffixes of a matched switch's args when
523 it is subsequently output with %*. SUFFIX is terminated by the next
524 space or %.
525 %d marks the argument containing or following the %d as a
526 temporary file name, so that file will be deleted if GCC exits
527 successfully. Unlike %g, this contributes no text to the argument.
528 %w marks the argument containing or following the %w as the
529 "output file" of this compilation. This puts the argument
530 into the sequence of arguments that %o will substitute later.
531 %V indicates that this compilation produces no "output file".
532 %W{...}
533 like %{...} but marks the last argument supplied within as a file
534 to be deleted on failure.
535 %@{...}
536 like %{...} but puts the result into a FILE and substitutes @FILE
537 if an @file argument has been supplied.
538 %o substitutes the names of all the output files, with spaces
539 automatically placed around them. You should write spaces
540 around the %o as well or the results are undefined.
541 %o is for use in the specs for running the linker.
542 Input files whose names have no recognized suffix are not compiled
543 at all, but they are included among the output files, so they will
544 be linked.
545 %O substitutes the suffix for object files. Note that this is
546 handled specially when it immediately follows %g, %u, or %U
547 (with or without a suffix argument) because of the need for
548 those to form complete file names. The handling is such that
549 %O is treated exactly as if it had already been substituted,
550 except that %g, %u, and %U do not currently support additional
551 SUFFIX characters following %O as they would following, for
552 example, `.o'.
553 %I Substitute any of -iprefix (made from GCC_EXEC_PREFIX), -isysroot
554 (made from TARGET_SYSTEM_ROOT), -isystem (made from COMPILER_PATH
555 and -B options) and -imultilib as necessary.
556 %s current argument is the name of a library or startup file of some sort.
557 Search for that file in a standard list of directories
558 and substitute the full name found.
559 %T current argument is the name of a linker script.
560 Search for that file in the current list of directories to scan for
561 libraries. If the file is located, insert a --script option into the
562 command line followed by the full path name found. If the file is
563 not found then generate an error message.
564 Note: the current working directory is not searched.
565 %eSTR Print STR as an error message. STR is terminated by a newline.
566 Use this when inconsistent options are detected.
567 %nSTR Print STR as a notice. STR is terminated by a newline.
568 %x{OPTION} Accumulate an option for %X.
569 %X Output the accumulated linker options specified by compilations.
570 %Y Output the accumulated assembler options specified by compilations.
571 %Z Output the accumulated preprocessor options specified by compilations.
572 %a process ASM_SPEC as a spec.
573 This allows config.h to specify part of the spec for running as.
574 %A process ASM_FINAL_SPEC as a spec. A capital A is actually
575 used here. This can be used to run a post-processor after the
576 assembler has done its job.
577 %D Dump out a -L option for each directory in startfile_prefixes.
578 If multilib_dir is set, extra entries are generated with it affixed.
579 %l process LINK_SPEC as a spec.
580 %L process LIB_SPEC as a spec.
581 %M Output multilib_os_dir.
582 %G process LIBGCC_SPEC as a spec.
583 %R Output the concatenation of target_system_root and
584 target_sysroot_suffix.
585 %S process STARTFILE_SPEC as a spec. A capital S is actually used here.
586 %E process ENDFILE_SPEC as a spec. A capital E is actually used here.
587 %C process CPP_SPEC as a spec.
588 %1 process CC1_SPEC as a spec.
589 %2 process CC1PLUS_SPEC as a spec.
590 %* substitute the variable part of a matched option. (See below.)
591 Note that each comma in the substituted string is replaced by
592 a single space. A space is appended after the last substition
593 unless there is more text in current sequence.
594 %<S remove all occurrences of -S from the command line.
595 Note - this command is position dependent. % commands in the
596 spec string before this one will see -S, % commands in the
597 spec string after this one will not.
598 %>S Similar to "%<S", but keep it in the GCC command line.
599 %<S* remove all occurrences of all switches beginning with -S from the
600 command line.
601 %:function(args)
602 Call the named function FUNCTION, passing it ARGS. ARGS is
603 first processed as a nested spec string, then split into an
604 argument vector in the usual fashion. The function returns
605 a string which is processed as if it had appeared literally
606 as part of the current spec.
607 %{S} substitutes the -S switch, if that switch was given to GCC.
608 If that switch was not specified, this substitutes nothing.
609 Here S is a metasyntactic variable.
610 %{S*} substitutes all the switches specified to GCC whose names start
611 with -S. This is used for -o, -I, etc; switches that take
612 arguments. GCC considers `-o foo' as being one switch whose
613 name starts with `o'. %{o*} would substitute this text,
614 including the space; thus, two arguments would be generated.
615 %{S*&T*} likewise, but preserve order of S and T options (the order
616 of S and T in the spec is not significant). Can be any number
617 of ampersand-separated variables; for each the wild card is
618 optional. Useful for CPP as %{D*&U*&A*}.
620 %{S:X} substitutes X, if the -S switch was given to GCC.
621 %{!S:X} substitutes X, if the -S switch was NOT given to GCC.
622 %{S*:X} substitutes X if one or more switches whose names start
623 with -S was given to GCC. Normally X is substituted only
624 once, no matter how many such switches appeared. However,
625 if %* appears somewhere in X, then X will be substituted
626 once for each matching switch, with the %* replaced by the
627 part of that switch that matched the '*'. A space will be
628 appended after the last substition unless there is more
629 text in current sequence.
630 %{.S:X} substitutes X, if processing a file with suffix S.
631 %{!.S:X} substitutes X, if NOT processing a file with suffix S.
632 %{,S:X} substitutes X, if processing a file which will use spec S.
633 %{!,S:X} substitutes X, if NOT processing a file which will use spec S.
635 %{S|T:X} substitutes X if either -S or -T was given to GCC. This may be
636 combined with '!', '.', ',', and '*' as above binding stronger
637 than the OR.
638 If %* appears in X, all of the alternatives must be starred, and
639 only the first matching alternative is substituted.
640 %{%:function(args):X}
641 Call function named FUNCTION with args ARGS. If the function
642 returns non-NULL, then X is substituted, if it returns
643 NULL, it isn't substituted.
644 %{S:X; if S was given to GCC, substitutes X;
645 T:Y; else if T was given to GCC, substitutes Y;
646 :D} else substitutes D. There can be as many clauses as you need.
647 This may be combined with '.', '!', ',', '|', and '*' as above.
649 %(Spec) processes a specification defined in a specs file as *Spec:
651 The switch matching text S in a %{S}, %{S:X}, or similar construct can use
652 a backslash to ignore the special meaning of the character following it,
653 thus allowing literal matching of a character that is otherwise specially
654 treated. For example, %{std=iso9899\:1999:X} substitutes X if the
655 -std=iso9899:1999 option is given.
657 The conditional text X in a %{S:X} or similar construct may contain
658 other nested % constructs or spaces, or even newlines. They are
659 processed as usual, as described above. Trailing white space in X is
660 ignored. White space may also appear anywhere on the left side of the
661 colon in these constructs, except between . or * and the corresponding
662 word.
664 The -O, -f, -g, -m, and -W switches are handled specifically in these
665 constructs. If another value of -O or the negated form of a -f, -m, or
666 -W switch is found later in the command line, the earlier switch
667 value is ignored, except with {S*} where S is just one letter; this
668 passes all matching options.
670 The character | at the beginning of the predicate text is used to indicate
671 that a command should be piped to the following command, but only if -pipe
672 is specified.
674 Note that it is built into GCC which switches take arguments and which
675 do not. You might think it would be useful to generalize this to
676 allow each compiler's spec to say which switches take arguments. But
677 this cannot be done in a consistent fashion. GCC cannot even decide
678 which input files have been specified without knowing which switches
679 take arguments, and it must know which input files to compile in order
680 to tell which compilers to run.
682 GCC also knows implicitly that arguments starting in `-l' are to be
683 treated as compiler output files, and passed to the linker in their
684 proper position among the other output files. */
686 /* Define the macros used for specs %a, %l, %L, %S, %C, %1. */
688 /* config.h can define ASM_SPEC to provide extra args to the assembler
689 or extra switch-translations. */
690 #ifndef ASM_SPEC
691 #define ASM_SPEC ""
692 #endif
694 /* config.h can define ASM_FINAL_SPEC to run a post processor after
695 the assembler has run. */
696 #ifndef ASM_FINAL_SPEC
697 #define ASM_FINAL_SPEC \
698 "%{gsplit-dwarf: \n\
699 objcopy --extract-dwo \
700 %{c:%{o*:%*}%{!o*:%w%b%O}}%{!c:%U%O} \
701 %b.dwo \n\
702 objcopy --strip-dwo \
703 %{c:%{o*:%*}%{!o*:%w%b%O}}%{!c:%U%O} \
705 #endif
707 /* config.h can define CPP_SPEC to provide extra args to the C preprocessor
708 or extra switch-translations. */
709 #ifndef CPP_SPEC
710 #define CPP_SPEC ""
711 #endif
713 /* Operating systems can define OS_CC1_SPEC to provide extra args to cc1 and
714 cc1plus or extra switch-translations. The OS_CC1_SPEC is appended
715 to CC1_SPEC in the initialization of cc1_spec. */
716 #ifndef OS_CC1_SPEC
717 #define OS_CC1_SPEC ""
718 #endif
720 /* config.h can define CC1_SPEC to provide extra args to cc1 and cc1plus
721 or extra switch-translations. */
722 #ifndef CC1_SPEC
723 #define CC1_SPEC ""
724 #endif
726 /* config.h can define CC1PLUS_SPEC to provide extra args to cc1plus
727 or extra switch-translations. */
728 #ifndef CC1PLUS_SPEC
729 #define CC1PLUS_SPEC ""
730 #endif
732 /* config.h can define LINK_SPEC to provide extra args to the linker
733 or extra switch-translations. */
734 #ifndef LINK_SPEC
735 #define LINK_SPEC ""
736 #endif
738 /* config.h can define LIB_SPEC to override the default libraries. */
739 #ifndef LIB_SPEC
740 #define LIB_SPEC "%{!shared:%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}}"
741 #endif
743 /* When using -fsplit-stack we need to wrap pthread_create, in order
744 to initialize the stack guard. We always use wrapping, rather than
745 shared library ordering, and we keep the wrapper function in
746 libgcc. This is not yet a real spec, though it could become one;
747 it is currently just stuffed into LINK_SPEC. FIXME: This wrapping
748 only works with GNU ld and gold. */
749 #ifdef HAVE_GOLD_NON_DEFAULT_SPLIT_STACK
750 #define STACK_SPLIT_SPEC " %{fsplit-stack: -fuse-ld=gold --wrap=pthread_create}"
751 #else
752 #define STACK_SPLIT_SPEC " %{fsplit-stack: --wrap=pthread_create}"
753 #endif
755 #ifndef LIBASAN_SPEC
756 #define STATIC_LIBASAN_LIBS \
757 " %{static-libasan|static:%:include(libsanitizer.spec)%(link_libasan)}"
758 #ifdef LIBASAN_EARLY_SPEC
759 #define LIBASAN_SPEC STATIC_LIBASAN_LIBS
760 #elif defined(HAVE_LD_STATIC_DYNAMIC)
761 #define LIBASAN_SPEC "%{static-libasan:" LD_STATIC_OPTION \
762 "} -lasan %{static-libasan:" LD_DYNAMIC_OPTION "}" \
763 STATIC_LIBASAN_LIBS
764 #else
765 #define LIBASAN_SPEC "-lasan" STATIC_LIBASAN_LIBS
766 #endif
767 #endif
769 #ifndef LIBASAN_EARLY_SPEC
770 #define LIBASAN_EARLY_SPEC ""
771 #endif
773 #ifndef LIBHWASAN_SPEC
774 #define STATIC_LIBHWASAN_LIBS \
775 " %{static-libhwasan|static:%:include(libsanitizer.spec)%(link_libhwasan)}"
776 #ifdef LIBHWASAN_EARLY_SPEC
777 #define LIBHWASAN_SPEC STATIC_LIBHWASAN_LIBS
778 #elif defined(HAVE_LD_STATIC_DYNAMIC)
779 #define LIBHWASAN_SPEC "%{static-libhwasan:" LD_STATIC_OPTION \
780 "} -lhwasan %{static-libhwasan:" LD_DYNAMIC_OPTION "}" \
781 STATIC_LIBHWASAN_LIBS
782 #else
783 #define LIBHWASAN_SPEC "-lhwasan" STATIC_LIBHWASAN_LIBS
784 #endif
785 #endif
787 #ifndef LIBHWASAN_EARLY_SPEC
788 #define LIBHWASAN_EARLY_SPEC ""
789 #endif
791 #ifndef LIBTSAN_SPEC
792 #define STATIC_LIBTSAN_LIBS \
793 " %{static-libtsan|static:%:include(libsanitizer.spec)%(link_libtsan)}"
794 #ifdef LIBTSAN_EARLY_SPEC
795 #define LIBTSAN_SPEC STATIC_LIBTSAN_LIBS
796 #elif defined(HAVE_LD_STATIC_DYNAMIC)
797 #define LIBTSAN_SPEC "%{static-libtsan:" LD_STATIC_OPTION \
798 "} -ltsan %{static-libtsan:" LD_DYNAMIC_OPTION "}" \
799 STATIC_LIBTSAN_LIBS
800 #else
801 #define LIBTSAN_SPEC "-ltsan" STATIC_LIBTSAN_LIBS
802 #endif
803 #endif
805 #ifndef LIBTSAN_EARLY_SPEC
806 #define LIBTSAN_EARLY_SPEC ""
807 #endif
809 #ifndef LIBLSAN_SPEC
810 #define STATIC_LIBLSAN_LIBS \
811 " %{static-liblsan|static:%:include(libsanitizer.spec)%(link_liblsan)}"
812 #ifdef LIBLSAN_EARLY_SPEC
813 #define LIBLSAN_SPEC STATIC_LIBLSAN_LIBS
814 #elif defined(HAVE_LD_STATIC_DYNAMIC)
815 #define LIBLSAN_SPEC "%{static-liblsan:" LD_STATIC_OPTION \
816 "} -llsan %{static-liblsan:" LD_DYNAMIC_OPTION "}" \
817 STATIC_LIBLSAN_LIBS
818 #else
819 #define LIBLSAN_SPEC "-llsan" STATIC_LIBLSAN_LIBS
820 #endif
821 #endif
823 #ifndef LIBLSAN_EARLY_SPEC
824 #define LIBLSAN_EARLY_SPEC ""
825 #endif
827 #ifndef LIBUBSAN_SPEC
828 #define STATIC_LIBUBSAN_LIBS \
829 " %{static-libubsan|static:%:include(libsanitizer.spec)%(link_libubsan)}"
830 #ifdef HAVE_LD_STATIC_DYNAMIC
831 #define LIBUBSAN_SPEC "%{static-libubsan:" LD_STATIC_OPTION \
832 "} -lubsan %{static-libubsan:" LD_DYNAMIC_OPTION "}" \
833 STATIC_LIBUBSAN_LIBS
834 #else
835 #define LIBUBSAN_SPEC "-lubsan" STATIC_LIBUBSAN_LIBS
836 #endif
837 #endif
839 /* Linker options for compressed debug sections. */
840 #if HAVE_LD_COMPRESS_DEBUG == 0
841 /* No linker support. */
842 #define LINK_COMPRESS_DEBUG_SPEC \
843 " %{gz*:%e-gz is not supported in this configuration} "
844 #elif HAVE_LD_COMPRESS_DEBUG == 1
845 /* ELF gABI style. */
846 #define LINK_COMPRESS_DEBUG_SPEC \
847 " %{gz|gz=zlib:" LD_COMPRESS_DEBUG_OPTION "=zlib}" \
848 " %{gz=none:" LD_COMPRESS_DEBUG_OPTION "=none}" \
849 " %{gz=zstd:%e-gz=zstd is not supported in this configuration} " \
850 " %{gz=zlib-gnu:}" /* Ignore silently zlib-gnu option value. */
851 #elif HAVE_LD_COMPRESS_DEBUG == 2
852 /* ELF gABI style and ZSTD. */
853 #define LINK_COMPRESS_DEBUG_SPEC \
854 " %{gz|gz=zlib:" LD_COMPRESS_DEBUG_OPTION "=zlib}" \
855 " %{gz=none:" LD_COMPRESS_DEBUG_OPTION "=none}" \
856 " %{gz=zstd:" LD_COMPRESS_DEBUG_OPTION "=zstd}" \
857 " %{gz=zlib-gnu:}" /* Ignore silently zlib-gnu option value. */
858 #else
859 #error Unknown value for HAVE_LD_COMPRESS_DEBUG.
860 #endif
862 /* config.h can define LIBGCC_SPEC to override how and when libgcc.a is
863 included. */
864 #ifndef LIBGCC_SPEC
865 #if defined(REAL_LIBGCC_SPEC)
866 #define LIBGCC_SPEC REAL_LIBGCC_SPEC
867 #elif defined(LINK_LIBGCC_SPECIAL_1)
868 /* Have gcc do the search for libgcc.a. */
869 #define LIBGCC_SPEC "libgcc.a%s"
870 #else
871 #define LIBGCC_SPEC "-lgcc"
872 #endif
873 #endif
875 /* config.h can define STARTFILE_SPEC to override the default crt0 files. */
876 #ifndef STARTFILE_SPEC
877 #define STARTFILE_SPEC \
878 "%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
879 #endif
881 /* config.h can define ENDFILE_SPEC to override the default crtn files. */
882 #ifndef ENDFILE_SPEC
883 #define ENDFILE_SPEC ""
884 #endif
886 #ifndef LINKER_NAME
887 #define LINKER_NAME "collect2"
888 #endif
890 #ifdef HAVE_AS_DEBUG_PREFIX_MAP
891 #define ASM_MAP " %{ffile-prefix-map=*:--debug-prefix-map %*} %{fdebug-prefix-map=*:--debug-prefix-map %*}"
892 #else
893 #define ASM_MAP ""
894 #endif
896 /* Assembler options for compressed debug sections. */
897 #if HAVE_LD_COMPRESS_DEBUG == 0
898 /* Reject if the linker cannot write compressed debug sections. */
899 #define ASM_COMPRESS_DEBUG_SPEC \
900 " %{gz*:%e-gz is not supported in this configuration} "
901 #else /* HAVE_LD_COMPRESS_DEBUG >= 1 */
902 #if HAVE_AS_COMPRESS_DEBUG == 0
903 /* No assembler support. Ignore silently. */
904 #define ASM_COMPRESS_DEBUG_SPEC \
905 " %{gz*:} "
906 #elif HAVE_AS_COMPRESS_DEBUG == 1
907 /* ELF gABI style. */
908 #define ASM_COMPRESS_DEBUG_SPEC \
909 " %{gz|gz=zlib:" AS_COMPRESS_DEBUG_OPTION "=zlib}" \
910 " %{gz=none:" AS_COMPRESS_DEBUG_OPTION "=none}" \
911 " %{gz=zlib-gnu:}" /* Ignore silently zlib-gnu option value. */
912 #elif HAVE_AS_COMPRESS_DEBUG == 2
913 /* ELF gABI style and ZSTD. */
914 #define ASM_COMPRESS_DEBUG_SPEC \
915 " %{gz|gz=zlib:" AS_COMPRESS_DEBUG_OPTION "=zlib}" \
916 " %{gz=none:" AS_COMPRESS_DEBUG_OPTION "=none}" \
917 " %{gz=zstd:" AS_COMPRESS_DEBUG_OPTION "=zstd}" \
918 " %{gz=zlib-gnu:}" /* Ignore silently zlib-gnu option value. */
919 #else
920 #error Unknown value for HAVE_AS_COMPRESS_DEBUG.
921 #endif
922 #endif /* HAVE_LD_COMPRESS_DEBUG >= 1 */
924 /* Define ASM_DEBUG_SPEC to be a spec suitable for translating '-g'
925 to the assembler, when compiling assembly sources only. */
926 #ifndef ASM_DEBUG_SPEC
927 # if defined(HAVE_AS_GDWARF_5_DEBUG_FLAG) && defined(HAVE_AS_WORKING_DWARF_N_FLAG)
928 /* If --gdwarf-N is supported and as can handle even compiler generated
929 .debug_line with it, supply --gdwarf-N in ASM_DEBUG_OPTION_SPEC rather
930 than in ASM_DEBUG_SPEC, so that it applies to both .s and .c etc.
931 compilations. */
932 # define ASM_DEBUG_DWARF_OPTION ""
933 # elif defined(HAVE_AS_GDWARF_5_DEBUG_FLAG) && !defined(HAVE_LD_BROKEN_PE_DWARF5)
934 # define ASM_DEBUG_DWARF_OPTION "%{%:dwarf-version-gt(4):--gdwarf-5;" \
935 "%:dwarf-version-gt(3):--gdwarf-4;" \
936 "%:dwarf-version-gt(2):--gdwarf-3;" \
937 ":--gdwarf2}"
938 # else
939 # define ASM_DEBUG_DWARF_OPTION "--gdwarf2"
940 # endif
941 # if defined(DWARF2_DEBUGGING_INFO) && defined(HAVE_AS_GDWARF2_DEBUG_FLAG)
942 # define ASM_DEBUG_SPEC "%{g*:%{%:debug-level-gt(0):" \
943 ASM_DEBUG_DWARF_OPTION "}}" ASM_MAP
944 # endif
945 # endif
946 #ifndef ASM_DEBUG_SPEC
947 # define ASM_DEBUG_SPEC ""
948 #endif
950 /* Define ASM_DEBUG_OPTION_SPEC to be a spec suitable for translating '-g'
951 to the assembler when compiling all sources. */
952 #ifndef ASM_DEBUG_OPTION_SPEC
953 # if defined(HAVE_AS_GDWARF_5_DEBUG_FLAG) && defined(HAVE_AS_WORKING_DWARF_N_FLAG)
954 # define ASM_DEBUG_OPTION_DWARF_OPT \
955 "%{%:dwarf-version-gt(4):--gdwarf-5 ;" \
956 "%:dwarf-version-gt(3):--gdwarf-4 ;" \
957 "%:dwarf-version-gt(2):--gdwarf-3 ;" \
958 ":--gdwarf2 }"
959 # if defined(DWARF2_DEBUGGING_INFO)
960 # define ASM_DEBUG_OPTION_SPEC "%{g*:%{%:debug-level-gt(0):" \
961 ASM_DEBUG_OPTION_DWARF_OPT "}}"
962 # endif
963 # endif
964 #endif
965 #ifndef ASM_DEBUG_OPTION_SPEC
966 # define ASM_DEBUG_OPTION_SPEC ""
967 #endif
969 /* Here is the spec for running the linker, after compiling all files. */
971 /* This is overridable by the target in case they need to specify the
972 -lgcc and -lc order specially, yet not require them to override all
973 of LINK_COMMAND_SPEC. */
974 #ifndef LINK_GCC_C_SEQUENCE_SPEC
975 #define LINK_GCC_C_SEQUENCE_SPEC "%G %{!nolibc:%L %G}"
976 #endif
978 #ifndef LINK_SSP_SPEC
979 #ifdef TARGET_LIBC_PROVIDES_SSP
980 #define LINK_SSP_SPEC "%{fstack-protector|fstack-protector-all" \
981 "|fstack-protector-strong|fstack-protector-explicit:}"
982 #else
983 #define LINK_SSP_SPEC "%{fstack-protector|fstack-protector-all" \
984 "|fstack-protector-strong|fstack-protector-explicit" \
985 ":-lssp_nonshared -lssp}"
986 #endif
987 #endif
989 #ifdef ENABLE_DEFAULT_PIE
990 #define PIE_SPEC "!no-pie"
991 #define NO_FPIE1_SPEC "fno-pie"
992 #define FPIE1_SPEC NO_FPIE1_SPEC ":;"
993 #define NO_FPIE2_SPEC "fno-PIE"
994 #define FPIE2_SPEC NO_FPIE2_SPEC ":;"
995 #define NO_FPIE_SPEC NO_FPIE1_SPEC "|" NO_FPIE2_SPEC
996 #define FPIE_SPEC NO_FPIE_SPEC ":;"
997 #define NO_FPIC1_SPEC "fno-pic"
998 #define FPIC1_SPEC NO_FPIC1_SPEC ":;"
999 #define NO_FPIC2_SPEC "fno-PIC"
1000 #define FPIC2_SPEC NO_FPIC2_SPEC ":;"
1001 #define NO_FPIC_SPEC NO_FPIC1_SPEC "|" NO_FPIC2_SPEC
1002 #define FPIC_SPEC NO_FPIC_SPEC ":;"
1003 #define NO_FPIE1_AND_FPIC1_SPEC NO_FPIE1_SPEC "|" NO_FPIC1_SPEC
1004 #define FPIE1_OR_FPIC1_SPEC NO_FPIE1_AND_FPIC1_SPEC ":;"
1005 #define NO_FPIE2_AND_FPIC2_SPEC NO_FPIE2_SPEC "|" NO_FPIC2_SPEC
1006 #define FPIE2_OR_FPIC2_SPEC NO_FPIE2_AND_FPIC2_SPEC ":;"
1007 #define NO_FPIE_AND_FPIC_SPEC NO_FPIE_SPEC "|" NO_FPIC_SPEC
1008 #define FPIE_OR_FPIC_SPEC NO_FPIE_AND_FPIC_SPEC ":;"
1009 #else
1010 #define PIE_SPEC "pie"
1011 #define FPIE1_SPEC "fpie"
1012 #define NO_FPIE1_SPEC FPIE1_SPEC ":;"
1013 #define FPIE2_SPEC "fPIE"
1014 #define NO_FPIE2_SPEC FPIE2_SPEC ":;"
1015 #define FPIE_SPEC FPIE1_SPEC "|" FPIE2_SPEC
1016 #define NO_FPIE_SPEC FPIE_SPEC ":;"
1017 #define FPIC1_SPEC "fpic"
1018 #define NO_FPIC1_SPEC FPIC1_SPEC ":;"
1019 #define FPIC2_SPEC "fPIC"
1020 #define NO_FPIC2_SPEC FPIC2_SPEC ":;"
1021 #define FPIC_SPEC FPIC1_SPEC "|" FPIC2_SPEC
1022 #define NO_FPIC_SPEC FPIC_SPEC ":;"
1023 #define FPIE1_OR_FPIC1_SPEC FPIE1_SPEC "|" FPIC1_SPEC
1024 #define NO_FPIE1_AND_FPIC1_SPEC FPIE1_OR_FPIC1_SPEC ":;"
1025 #define FPIE2_OR_FPIC2_SPEC FPIE2_SPEC "|" FPIC2_SPEC
1026 #define NO_FPIE2_AND_FPIC2_SPEC FPIE1_OR_FPIC2_SPEC ":;"
1027 #define FPIE_OR_FPIC_SPEC FPIE_SPEC "|" FPIC_SPEC
1028 #define NO_FPIE_AND_FPIC_SPEC FPIE_OR_FPIC_SPEC ":;"
1029 #endif
1031 #ifndef LINK_PIE_SPEC
1032 #ifdef HAVE_LD_PIE
1033 #ifndef LD_PIE_SPEC
1034 #define LD_PIE_SPEC "-pie"
1035 #endif
1036 #else
1037 #define LD_PIE_SPEC ""
1038 #endif
1039 #define LINK_PIE_SPEC "%{static|shared|r:;" PIE_SPEC ":" LD_PIE_SPEC "} "
1040 #endif
1042 #ifndef LINK_BUILDID_SPEC
1043 # if defined(HAVE_LD_BUILDID) && defined(ENABLE_LD_BUILDID)
1044 # define LINK_BUILDID_SPEC "%{!r:--build-id} "
1045 # endif
1046 #endif
1048 #ifndef LTO_PLUGIN_SPEC
1049 #define LTO_PLUGIN_SPEC ""
1050 #endif
1052 /* Conditional to test whether the LTO plugin is used or not.
1053 FIXME: For slim LTO we will need to enable plugin unconditionally. This
1054 still cause problems with PLUGIN_LD != LD and when plugin is built but
1055 not useable. For GCC 4.6 we don't support slim LTO and thus we can enable
1056 plugin only when LTO is enabled. We still honor explicit
1057 -fuse-linker-plugin if the linker used understands -plugin. */
1059 /* The linker has some plugin support. */
1060 #if HAVE_LTO_PLUGIN > 0
1061 /* The linker used has full plugin support, use LTO plugin by default. */
1062 #if HAVE_LTO_PLUGIN == 2
1063 #define PLUGIN_COND "!fno-use-linker-plugin:%{!fno-lto"
1064 #define PLUGIN_COND_CLOSE "}"
1065 #else
1066 /* The linker used has limited plugin support, use LTO plugin with explicit
1067 -fuse-linker-plugin. */
1068 #define PLUGIN_COND "fuse-linker-plugin"
1069 #define PLUGIN_COND_CLOSE ""
1070 #endif
1071 #define LINK_PLUGIN_SPEC \
1072 "%{" PLUGIN_COND": \
1073 -plugin %(linker_plugin_file) \
1074 -plugin-opt=%(lto_wrapper) \
1075 -plugin-opt=-fresolution=%u.res \
1076 " LTO_PLUGIN_SPEC "\
1077 %{flinker-output=*:-plugin-opt=-linker-output-known} \
1078 %{!nostdlib:%{!nodefaultlibs:%:pass-through-libs(%(link_gcc_c_sequence))}} \
1079 }" PLUGIN_COND_CLOSE
1080 #else
1081 /* The linker used doesn't support -plugin, reject -fuse-linker-plugin. */
1082 #define LINK_PLUGIN_SPEC "%{fuse-linker-plugin:\
1083 %e-fuse-linker-plugin is not supported in this configuration}"
1084 #endif
1086 /* Linker command line options for -fsanitize= early on the command line. */
1087 #ifndef SANITIZER_EARLY_SPEC
1088 #define SANITIZER_EARLY_SPEC "\
1089 %{!nostdlib:%{!r:%{!nodefaultlibs:%{%:sanitize(address):" LIBASAN_EARLY_SPEC "} \
1090 %{%:sanitize(hwaddress):" LIBHWASAN_EARLY_SPEC "} \
1091 %{%:sanitize(thread):" LIBTSAN_EARLY_SPEC "} \
1092 %{%:sanitize(leak):" LIBLSAN_EARLY_SPEC "}}}}"
1093 #endif
1095 /* Linker command line options for -fsanitize= late on the command line. */
1096 #ifndef SANITIZER_SPEC
1097 #define SANITIZER_SPEC "\
1098 %{!nostdlib:%{!r:%{!nodefaultlibs:%{%:sanitize(address):" LIBASAN_SPEC "\
1099 %{static:%ecannot specify -static with -fsanitize=address}}\
1100 %{%:sanitize(hwaddress):" LIBHWASAN_SPEC "\
1101 %{static:%ecannot specify -static with -fsanitize=hwaddress}}\
1102 %{%:sanitize(thread):" LIBTSAN_SPEC "\
1103 %{static:%ecannot specify -static with -fsanitize=thread}}\
1104 %{%:sanitize(undefined):" LIBUBSAN_SPEC "}\
1105 %{%:sanitize(leak):" LIBLSAN_SPEC "}}}}"
1106 #endif
1108 #ifndef POST_LINK_SPEC
1109 #define POST_LINK_SPEC ""
1110 #endif
1112 /* This is the spec to use, once the code for creating the vtable
1113 verification runtime library, libvtv.so, has been created. Currently
1114 the vtable verification runtime functions are in libstdc++, so we use
1115 the spec just below this one. */
1116 #ifndef VTABLE_VERIFICATION_SPEC
1117 #if ENABLE_VTABLE_VERIFY
1118 #define VTABLE_VERIFICATION_SPEC "\
1119 %{!nostdlib:%{!r:%{fvtable-verify=std: -lvtv -u_vtable_map_vars_start -u_vtable_map_vars_end}\
1120 %{fvtable-verify=preinit: -lvtv -u_vtable_map_vars_start -u_vtable_map_vars_end}}}"
1121 #else
1122 #define VTABLE_VERIFICATION_SPEC "\
1123 %{fvtable-verify=none:} \
1124 %{fvtable-verify=std: \
1125 %e-fvtable-verify=std is not supported in this configuration} \
1126 %{fvtable-verify=preinit: \
1127 %e-fvtable-verify=preinit is not supported in this configuration}"
1128 #endif
1129 #endif
1131 /* -u* was put back because both BSD and SysV seem to support it. */
1132 /* %{static|no-pie|static-pie:} simply prevents an error message:
1133 1. If the target machine doesn't handle -static.
1134 2. If PIE isn't enabled by default.
1135 3. If the target machine doesn't handle -static-pie.
1137 /* We want %{T*} after %{L*} and %D so that it can be used to specify linker
1138 scripts which exist in user specified directories, or in standard
1139 directories. */
1140 /* We pass any -flto flags on to the linker, which is expected
1141 to understand them. In practice, this means it had better be collect2. */
1142 /* %{e*} includes -export-dynamic; see comment in common.opt. */
1143 #ifndef LINK_COMMAND_SPEC
1144 #define LINK_COMMAND_SPEC "\
1145 %{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
1146 %(linker) " \
1147 LINK_PLUGIN_SPEC \
1148 "%{flto|flto=*:%<fcompare-debug*} \
1149 %{flto} %{fno-lto} %{flto=*} %l " LINK_PIE_SPEC \
1150 "%{fuse-ld=*:-fuse-ld=%*} " LINK_COMPRESS_DEBUG_SPEC \
1151 "%X %{o*} %{e*} %{N} %{n} %{r}\
1152 %{s} %{t} %{u*} %{z} %{Z} %{!nostdlib:%{!r:%{!nostartfiles:%S}}} \
1153 %{static|no-pie|static-pie:} %@{L*} %(link_libgcc) " \
1154 VTABLE_VERIFICATION_SPEC " " SANITIZER_EARLY_SPEC " %o "" \
1155 %{fopenacc|fopenmp|%:gt(%{ftree-parallelize-loops=*:%*} 1):\
1156 %:include(libgomp.spec)%(link_gomp)}\
1157 %{fgnu-tm:%:include(libitm.spec)%(link_itm)}\
1158 " STACK_SPLIT_SPEC "\
1159 %{fprofile-arcs|fprofile-generate*|coverage:-lgcov} " SANITIZER_SPEC " \
1160 %{!nostdlib:%{!r:%{!nodefaultlibs:%(link_ssp) %(link_gcc_c_sequence)}}}\
1161 %{!nostdlib:%{!r:%{!nostartfiles:%E}}} %{T*} \n%(post_link) }}}}}}"
1162 #endif
1164 #ifndef LINK_LIBGCC_SPEC
1165 /* Generate -L options for startfile prefix list. */
1166 # define LINK_LIBGCC_SPEC "%D"
1167 #endif
1169 #ifndef STARTFILE_PREFIX_SPEC
1170 # define STARTFILE_PREFIX_SPEC ""
1171 #endif
1173 #ifndef SYSROOT_SPEC
1174 # define SYSROOT_SPEC "--sysroot=%R"
1175 #endif
1177 #ifndef SYSROOT_SUFFIX_SPEC
1178 # define SYSROOT_SUFFIX_SPEC ""
1179 #endif
1181 #ifndef SYSROOT_HEADERS_SUFFIX_SPEC
1182 # define SYSROOT_HEADERS_SUFFIX_SPEC ""
1183 #endif
1185 static const char *asm_debug = ASM_DEBUG_SPEC;
1186 static const char *asm_debug_option = ASM_DEBUG_OPTION_SPEC;
1187 static const char *cpp_spec = CPP_SPEC;
1188 static const char *cc1_spec = CC1_SPEC OS_CC1_SPEC;
1189 static const char *cc1plus_spec = CC1PLUS_SPEC;
1190 static const char *link_gcc_c_sequence_spec = LINK_GCC_C_SEQUENCE_SPEC;
1191 static const char *link_ssp_spec = LINK_SSP_SPEC;
1192 static const char *asm_spec = ASM_SPEC;
1193 static const char *asm_final_spec = ASM_FINAL_SPEC;
1194 static const char *link_spec = LINK_SPEC;
1195 static const char *lib_spec = LIB_SPEC;
1196 static const char *link_gomp_spec = "";
1197 static const char *libgcc_spec = LIBGCC_SPEC;
1198 static const char *endfile_spec = ENDFILE_SPEC;
1199 static const char *startfile_spec = STARTFILE_SPEC;
1200 static const char *linker_name_spec = LINKER_NAME;
1201 static const char *linker_plugin_file_spec = "";
1202 static const char *lto_wrapper_spec = "";
1203 static const char *lto_gcc_spec = "";
1204 static const char *post_link_spec = POST_LINK_SPEC;
1205 static const char *link_command_spec = LINK_COMMAND_SPEC;
1206 static const char *link_libgcc_spec = LINK_LIBGCC_SPEC;
1207 static const char *startfile_prefix_spec = STARTFILE_PREFIX_SPEC;
1208 static const char *sysroot_spec = SYSROOT_SPEC;
1209 static const char *sysroot_suffix_spec = SYSROOT_SUFFIX_SPEC;
1210 static const char *sysroot_hdrs_suffix_spec = SYSROOT_HEADERS_SUFFIX_SPEC;
1211 static const char *self_spec = "";
1213 /* Standard options to cpp, cc1, and as, to reduce duplication in specs.
1214 There should be no need to override these in target dependent files,
1215 but we need to copy them to the specs file so that newer versions
1216 of the GCC driver can correctly drive older tool chains with the
1217 appropriate -B options. */
1219 /* When cpplib handles traditional preprocessing, get rid of this, and
1220 call cc1 (or cc1obj in objc/lang-specs.h) from the main specs so
1221 that we default the front end language better. */
1222 static const char *trad_capable_cpp =
1223 "cc1 -E %{traditional|traditional-cpp:-traditional-cpp}";
1225 /* We don't wrap .d files in %W{} since a missing .d file, and
1226 therefore no dependency entry, confuses make into thinking a .o
1227 file that happens to exist is up-to-date. */
1228 static const char *cpp_unique_options =
1229 "%{!Q:-quiet} %{nostdinc*} %{C} %{CC} %{v} %@{I*&F*} %{P} %I\
1230 %{MD:-MD %{!o:%b.d}%{o*:%.d%*}}\
1231 %{MMD:-MMD %{!o:%b.d}%{o*:%.d%*}}\
1232 %{M} %{MM} %{MF*} %{MG} %{MP} %{MQ*} %{MT*}\
1233 %{Mmodules} %{Mno-modules}\
1234 %{!E:%{!M:%{!MM:%{!MT:%{!MQ:%{MD|MMD:%{o*:-MQ %*}}}}}}}\
1235 %{remap} %{%:debug-level-gt(2):-dD}\
1236 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
1237 %{H} %C %{D*&U*&A*} %{i*} %Z %i\
1238 %{E|M|MM:%W{o*}}";
1240 /* This contains cpp options which are common with cc1_options and are passed
1241 only when preprocessing only to avoid duplication. We pass the cc1 spec
1242 options to the preprocessor so that it the cc1 spec may manipulate
1243 options used to set target flags. Those special target flags settings may
1244 in turn cause preprocessor symbols to be defined specially. */
1245 static const char *cpp_options =
1246 "%(cpp_unique_options) %1 %{m*} %{std*&ansi&trigraphs} %{W*&pedantic*} %{w}\
1247 %{f*} %{g*:%{%:debug-level-gt(0):%{g*}\
1248 %{!fno-working-directory:-fworking-directory}}} %{O*}\
1249 %{undef} %{save-temps*:-fpch-preprocess}";
1251 /* Pass -d* flags, possibly modifying -dumpdir, -dumpbase et al.
1253 Make it easy for a language to override the argument for the
1254 %:dumps specs function call. */
1255 #define DUMPS_OPTIONS(EXTS) \
1256 "%<dumpdir %<dumpbase %<dumpbase-ext %{d*} %:dumps(" EXTS ")"
1258 /* This contains cpp options which are not passed when the preprocessor
1259 output will be used by another program. */
1260 static const char *cpp_debug_options = DUMPS_OPTIONS ("");
1262 /* NB: This is shared amongst all front-ends, except for Ada. */
1263 static const char *cc1_options =
1264 "%{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
1265 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
1266 %1 %{!Q:-quiet} %(cpp_debug_options) %{m*} %{aux-info*}\
1267 %{g*} %{O*} %{W*&pedantic*} %{w} %{std*&ansi&trigraphs}\
1268 %{v:-version} %{pg:-p} %{p} %{f*} %{undef}\
1269 %{Qn:-fno-ident} %{Qy:} %{-help:--help}\
1270 %{-target-help:--target-help}\
1271 %{-version:--version}\
1272 %{-help=*:--help=%*}\
1273 %{!fsyntax-only:%{S:%W{o*}%{!o*:-o %w%b.s}}}\
1274 %{fsyntax-only:-o %j} %{-param*}\
1275 %{coverage:-fprofile-arcs -ftest-coverage}\
1276 %{fprofile-arcs|fprofile-generate*|coverage:\
1277 %{!fprofile-update=single:\
1278 %{pthread:-fprofile-update=prefer-atomic}}}";
1280 static const char *asm_options =
1281 "%{-target-help:%:print-asm-header()} "
1282 #if HAVE_GNU_AS
1283 /* If GNU AS is used, then convert -w (no warnings), -I, and -v
1284 to the assembler equivalents. */
1285 "%{v} %{w:-W} %{I*} "
1286 #endif
1287 "%(asm_debug_option)"
1288 ASM_COMPRESS_DEBUG_SPEC
1289 "%a %Y %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}";
1291 static const char *invoke_as =
1292 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
1293 "%{!fwpa*:\
1294 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
1295 %{!S:-o %|.s |\n as %(asm_options) %|.s %A }\
1297 #else
1298 "%{!fwpa*:\
1299 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
1300 %{!S:-o %|.s |\n as %(asm_options) %m.s %A }\
1302 #endif
1304 /* Some compilers have limits on line lengths, and the multilib_select
1305 and/or multilib_matches strings can be very long, so we build them at
1306 run time. */
1307 static struct obstack multilib_obstack;
1308 static const char *multilib_select;
1309 static const char *multilib_matches;
1310 static const char *multilib_defaults;
1311 static const char *multilib_exclusions;
1312 static const char *multilib_reuse;
1314 /* Check whether a particular argument is a default argument. */
1316 #ifndef MULTILIB_DEFAULTS
1317 #define MULTILIB_DEFAULTS { "" }
1318 #endif
1320 static const char *const multilib_defaults_raw[] = MULTILIB_DEFAULTS;
1322 #ifndef DRIVER_SELF_SPECS
1323 #define DRIVER_SELF_SPECS ""
1324 #endif
1326 /* Linking to libgomp implies pthreads. This is particularly important
1327 for targets that use different start files and suchlike. */
1328 #ifndef GOMP_SELF_SPECS
1329 #define GOMP_SELF_SPECS \
1330 "%{fopenacc|fopenmp|%:gt(%{ftree-parallelize-loops=*:%*} 1): " \
1331 "-pthread}"
1332 #endif
1334 /* Likewise for -fgnu-tm. */
1335 #ifndef GTM_SELF_SPECS
1336 #define GTM_SELF_SPECS "%{fgnu-tm: -pthread}"
1337 #endif
1339 static const char *const driver_self_specs[] = {
1340 "%{fdump-final-insns:-fdump-final-insns=.} %<fdump-final-insns",
1341 DRIVER_SELF_SPECS, CONFIGURE_SPECS, GOMP_SELF_SPECS, GTM_SELF_SPECS,
1342 /* This discards -fmultiflags at the end of self specs processing in the
1343 driver, so that it is effectively Ignored, without actually marking it as
1344 Ignored, which would get it discarded before self specs could remap it. */
1345 "%<fmultiflags"
1348 #ifndef OPTION_DEFAULT_SPECS
1349 #define OPTION_DEFAULT_SPECS { "", "" }
1350 #endif
1352 struct default_spec
1354 const char *name;
1355 const char *spec;
1358 static const struct default_spec
1359 option_default_specs[] = { OPTION_DEFAULT_SPECS };
1361 struct user_specs
1363 struct user_specs *next;
1364 const char *filename;
1367 static struct user_specs *user_specs_head, *user_specs_tail;
1370 /* Record the mapping from file suffixes for compilation specs. */
1372 struct compiler
1374 const char *suffix; /* Use this compiler for input files
1375 whose names end in this suffix. */
1377 const char *spec; /* To use this compiler, run this spec. */
1379 const char *cpp_spec; /* If non-NULL, substitute this spec
1380 for `%C', rather than the usual
1381 cpp_spec. */
1382 int combinable; /* If nonzero, compiler can deal with
1383 multiple source files at once (IMA). */
1384 int needs_preprocessing; /* If nonzero, source files need to
1385 be run through a preprocessor. */
1388 /* Pointer to a vector of `struct compiler' that gives the spec for
1389 compiling a file, based on its suffix.
1390 A file that does not end in any of these suffixes will be passed
1391 unchanged to the loader and nothing else will be done to it.
1393 An entry containing two 0s is used to terminate the vector.
1395 If multiple entries match a file, the last matching one is used. */
1397 static struct compiler *compilers;
1399 /* Number of entries in `compilers', not counting the null terminator. */
1401 static int n_compilers;
1403 /* The default list of file name suffixes and their compilation specs. */
1405 static const struct compiler default_compilers[] =
1407 /* Add lists of suffixes of known languages here. If those languages
1408 were not present when we built the driver, we will hit these copies
1409 and be given a more meaningful error than "file not used since
1410 linking is not done". */
1411 {".m", "#Objective-C", 0, 0, 0}, {".mi", "#Objective-C", 0, 0, 0},
1412 {".mm", "#Objective-C++", 0, 0, 0}, {".M", "#Objective-C++", 0, 0, 0},
1413 {".mii", "#Objective-C++", 0, 0, 0},
1414 {".cc", "#C++", 0, 0, 0}, {".cxx", "#C++", 0, 0, 0},
1415 {".cpp", "#C++", 0, 0, 0}, {".cp", "#C++", 0, 0, 0},
1416 {".c++", "#C++", 0, 0, 0}, {".C", "#C++", 0, 0, 0},
1417 {".CPP", "#C++", 0, 0, 0}, {".ii", "#C++", 0, 0, 0},
1418 {".ads", "#Ada", 0, 0, 0}, {".adb", "#Ada", 0, 0, 0},
1419 {".f", "#Fortran", 0, 0, 0}, {".F", "#Fortran", 0, 0, 0},
1420 {".for", "#Fortran", 0, 0, 0}, {".FOR", "#Fortran", 0, 0, 0},
1421 {".ftn", "#Fortran", 0, 0, 0}, {".FTN", "#Fortran", 0, 0, 0},
1422 {".fpp", "#Fortran", 0, 0, 0}, {".FPP", "#Fortran", 0, 0, 0},
1423 {".f90", "#Fortran", 0, 0, 0}, {".F90", "#Fortran", 0, 0, 0},
1424 {".f95", "#Fortran", 0, 0, 0}, {".F95", "#Fortran", 0, 0, 0},
1425 {".f03", "#Fortran", 0, 0, 0}, {".F03", "#Fortran", 0, 0, 0},
1426 {".f08", "#Fortran", 0, 0, 0}, {".F08", "#Fortran", 0, 0, 0},
1427 {".r", "#Ratfor", 0, 0, 0},
1428 {".go", "#Go", 0, 1, 0},
1429 {".d", "#D", 0, 1, 0}, {".dd", "#D", 0, 1, 0}, {".di", "#D", 0, 1, 0},
1430 {".mod", "#Modula-2", 0, 0, 0}, {".m2i", "#Modula-2", 0, 0, 0},
1431 /* Next come the entries for C. */
1432 {".c", "@c", 0, 0, 1},
1433 {"@c",
1434 /* cc1 has an integrated ISO C preprocessor. We should invoke the
1435 external preprocessor if -save-temps is given. */
1436 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
1437 %{!E:%{!M:%{!MM:\
1438 %{traditional:\
1439 %eGNU C no longer supports -traditional without -E}\
1440 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
1441 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
1442 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
1443 %(cc1_options)}\
1444 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
1445 cc1 %(cpp_unique_options) %(cc1_options)}}}\
1446 %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 1},
1447 {"-",
1448 "%{!E:%e-E or -x required when input is from standard input}\
1449 %(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)", 0, 0, 0},
1450 {".h", "@c-header", 0, 0, 0},
1451 {"@c-header",
1452 /* cc1 has an integrated ISO C preprocessor. We should invoke the
1453 external preprocessor if -save-temps is given. */
1454 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
1455 %{!E:%{!M:%{!MM:\
1456 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
1457 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
1458 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
1459 %(cc1_options)\
1460 %{!fsyntax-only:%{!S:-o %g.s} \
1461 %{!fdump-ada-spec*:%{!o*:--output-pch %w%i.gch}\
1462 %W{o*:--output-pch %w%*}}%{!S:%V}}}\
1463 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
1464 cc1 %(cpp_unique_options) %(cc1_options)\
1465 %{!fsyntax-only:%{!S:-o %g.s} \
1466 %{!fdump-ada-spec*:%{!o*:--output-pch %w%i.gch}\
1467 %W{o*:--output-pch %w%*}}%{!S:%V}}}}}}}}", 0, 0, 0},
1468 {".i", "@cpp-output", 0, 0, 0},
1469 {"@cpp-output",
1470 "%{!M:%{!MM:%{!E:cc1 -fpreprocessed %i %(cc1_options) %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 0},
1471 {".s", "@assembler", 0, 0, 0},
1472 {"@assembler",
1473 "%{!M:%{!MM:%{!E:%{!S:as %(asm_debug) %(asm_options) %i %A }}}}", 0, 0, 0},
1474 {".sx", "@assembler-with-cpp", 0, 0, 0},
1475 {".S", "@assembler-with-cpp", 0, 0, 0},
1476 {"@assembler-with-cpp",
1477 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
1478 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
1479 %{E|M|MM:%(cpp_debug_options)}\
1480 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
1481 as %(asm_debug) %(asm_options) %|.s %A }}}}"
1482 #else
1483 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
1484 %{E|M|MM:%(cpp_debug_options)}\
1485 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
1486 as %(asm_debug) %(asm_options) %m.s %A }}}}"
1487 #endif
1488 , 0, 0, 0},
1490 #include "specs.h"
1491 /* Mark end of table. */
1492 {0, 0, 0, 0, 0}
1495 /* Number of elements in default_compilers, not counting the terminator. */
1497 static const int n_default_compilers = ARRAY_SIZE (default_compilers) - 1;
1499 typedef char *char_p; /* For DEF_VEC_P. */
1501 /* A vector of options to give to the linker.
1502 These options are accumulated by %x,
1503 and substituted into the linker command with %X. */
1504 static vec<char_p> linker_options;
1506 /* A vector of options to give to the assembler.
1507 These options are accumulated by -Wa,
1508 and substituted into the assembler command with %Y. */
1509 static vec<char_p> assembler_options;
1511 /* A vector of options to give to the preprocessor.
1512 These options are accumulated by -Wp,
1513 and substituted into the preprocessor command with %Z. */
1514 static vec<char_p> preprocessor_options;
1516 static char *
1517 skip_whitespace (char *p)
1519 while (1)
1521 /* A fully-blank line is a delimiter in the SPEC file and shouldn't
1522 be considered whitespace. */
1523 if (p[0] == '\n' && p[1] == '\n' && p[2] == '\n')
1524 return p + 1;
1525 else if (*p == '\n' || *p == ' ' || *p == '\t')
1526 p++;
1527 else if (*p == '#')
1529 while (*p != '\n')
1530 p++;
1531 p++;
1533 else
1534 break;
1537 return p;
1539 /* Structures to keep track of prefixes to try when looking for files. */
1541 struct prefix_list
1543 const char *prefix; /* String to prepend to the path. */
1544 struct prefix_list *next; /* Next in linked list. */
1545 int require_machine_suffix; /* Don't use without machine_suffix. */
1546 /* 2 means try both machine_suffix and just_machine_suffix. */
1547 int priority; /* Sort key - priority within list. */
1548 int os_multilib; /* 1 if OS multilib scheme should be used,
1549 0 for GCC multilib scheme. */
1552 struct path_prefix
1554 struct prefix_list *plist; /* List of prefixes to try */
1555 int max_len; /* Max length of a prefix in PLIST */
1556 const char *name; /* Name of this list (used in config stuff) */
1559 /* List of prefixes to try when looking for executables. */
1561 static struct path_prefix exec_prefixes = { 0, 0, "exec" };
1563 /* List of prefixes to try when looking for startup (crt0) files. */
1565 static struct path_prefix startfile_prefixes = { 0, 0, "startfile" };
1567 /* List of prefixes to try when looking for include files. */
1569 static struct path_prefix include_prefixes = { 0, 0, "include" };
1571 /* Suffix to attach to directories searched for commands.
1572 This looks like `MACHINE/VERSION/'. */
1574 static const char *machine_suffix = 0;
1576 /* Suffix to attach to directories searched for commands.
1577 This is just `MACHINE/'. */
1579 static const char *just_machine_suffix = 0;
1581 /* Adjusted value of GCC_EXEC_PREFIX envvar. */
1583 static const char *gcc_exec_prefix;
1585 /* Adjusted value of standard_libexec_prefix. */
1587 static const char *gcc_libexec_prefix;
1589 /* Default prefixes to attach to command names. */
1591 #ifndef STANDARD_STARTFILE_PREFIX_1
1592 #define STANDARD_STARTFILE_PREFIX_1 "/lib/"
1593 #endif
1594 #ifndef STANDARD_STARTFILE_PREFIX_2
1595 #define STANDARD_STARTFILE_PREFIX_2 "/usr/lib/"
1596 #endif
1598 #ifdef CROSS_DIRECTORY_STRUCTURE /* Don't use these prefixes for a cross compiler. */
1599 #undef MD_EXEC_PREFIX
1600 #undef MD_STARTFILE_PREFIX
1601 #undef MD_STARTFILE_PREFIX_1
1602 #endif
1604 /* If no prefixes defined, use the null string, which will disable them. */
1605 #ifndef MD_EXEC_PREFIX
1606 #define MD_EXEC_PREFIX ""
1607 #endif
1608 #ifndef MD_STARTFILE_PREFIX
1609 #define MD_STARTFILE_PREFIX ""
1610 #endif
1611 #ifndef MD_STARTFILE_PREFIX_1
1612 #define MD_STARTFILE_PREFIX_1 ""
1613 #endif
1615 /* These directories are locations set at configure-time based on the
1616 --prefix option provided to configure. Their initializers are
1617 defined in Makefile.in. These paths are not *directly* used when
1618 gcc_exec_prefix is set because, in that case, we know where the
1619 compiler has been installed, and use paths relative to that
1620 location instead. */
1621 static const char *const standard_exec_prefix = STANDARD_EXEC_PREFIX;
1622 static const char *const standard_libexec_prefix = STANDARD_LIBEXEC_PREFIX;
1623 static const char *const standard_bindir_prefix = STANDARD_BINDIR_PREFIX;
1624 static const char *const standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
1626 /* For native compilers, these are well-known paths containing
1627 components that may be provided by the system. For cross
1628 compilers, these paths are not used. */
1629 static const char *md_exec_prefix = MD_EXEC_PREFIX;
1630 static const char *md_startfile_prefix = MD_STARTFILE_PREFIX;
1631 static const char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
1632 static const char *const standard_startfile_prefix_1
1633 = STANDARD_STARTFILE_PREFIX_1;
1634 static const char *const standard_startfile_prefix_2
1635 = STANDARD_STARTFILE_PREFIX_2;
1637 /* A relative path to be used in finding the location of tools
1638 relative to the driver. */
1639 static const char *const tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
1641 /* A prefix to be used when this is an accelerator compiler. */
1642 static const char *const accel_dir_suffix = ACCEL_DIR_SUFFIX;
1644 /* Subdirectory to use for locating libraries. Set by
1645 set_multilib_dir based on the compilation options. */
1647 static const char *multilib_dir;
1649 /* Subdirectory to use for locating libraries in OS conventions. Set by
1650 set_multilib_dir based on the compilation options. */
1652 static const char *multilib_os_dir;
1654 /* Subdirectory to use for locating libraries in multiarch conventions. Set by
1655 set_multilib_dir based on the compilation options. */
1657 static const char *multiarch_dir;
1659 /* Structure to keep track of the specs that have been defined so far.
1660 These are accessed using %(specname) in a compiler or link
1661 spec. */
1663 struct spec_list
1665 /* The following 2 fields must be first */
1666 /* to allow EXTRA_SPECS to be initialized */
1667 const char *name; /* name of the spec. */
1668 const char *ptr; /* available ptr if no static pointer */
1670 /* The following fields are not initialized */
1671 /* by EXTRA_SPECS */
1672 const char **ptr_spec; /* pointer to the spec itself. */
1673 struct spec_list *next; /* Next spec in linked list. */
1674 int name_len; /* length of the name */
1675 bool user_p; /* whether string come from file spec. */
1676 bool alloc_p; /* whether string was allocated */
1677 const char *default_ptr; /* The default value of *ptr_spec. */
1680 #define INIT_STATIC_SPEC(NAME,PTR) \
1681 { NAME, NULL, PTR, (struct spec_list *) 0, sizeof (NAME) - 1, false, false, \
1682 *PTR }
1684 /* List of statically defined specs. */
1685 static struct spec_list static_specs[] =
1687 INIT_STATIC_SPEC ("asm", &asm_spec),
1688 INIT_STATIC_SPEC ("asm_debug", &asm_debug),
1689 INIT_STATIC_SPEC ("asm_debug_option", &asm_debug_option),
1690 INIT_STATIC_SPEC ("asm_final", &asm_final_spec),
1691 INIT_STATIC_SPEC ("asm_options", &asm_options),
1692 INIT_STATIC_SPEC ("invoke_as", &invoke_as),
1693 INIT_STATIC_SPEC ("cpp", &cpp_spec),
1694 INIT_STATIC_SPEC ("cpp_options", &cpp_options),
1695 INIT_STATIC_SPEC ("cpp_debug_options", &cpp_debug_options),
1696 INIT_STATIC_SPEC ("cpp_unique_options", &cpp_unique_options),
1697 INIT_STATIC_SPEC ("trad_capable_cpp", &trad_capable_cpp),
1698 INIT_STATIC_SPEC ("cc1", &cc1_spec),
1699 INIT_STATIC_SPEC ("cc1_options", &cc1_options),
1700 INIT_STATIC_SPEC ("cc1plus", &cc1plus_spec),
1701 INIT_STATIC_SPEC ("link_gcc_c_sequence", &link_gcc_c_sequence_spec),
1702 INIT_STATIC_SPEC ("link_ssp", &link_ssp_spec),
1703 INIT_STATIC_SPEC ("endfile", &endfile_spec),
1704 INIT_STATIC_SPEC ("link", &link_spec),
1705 INIT_STATIC_SPEC ("lib", &lib_spec),
1706 INIT_STATIC_SPEC ("link_gomp", &link_gomp_spec),
1707 INIT_STATIC_SPEC ("libgcc", &libgcc_spec),
1708 INIT_STATIC_SPEC ("startfile", &startfile_spec),
1709 INIT_STATIC_SPEC ("cross_compile", &cross_compile),
1710 INIT_STATIC_SPEC ("version", &compiler_version),
1711 INIT_STATIC_SPEC ("multilib", &multilib_select),
1712 INIT_STATIC_SPEC ("multilib_defaults", &multilib_defaults),
1713 INIT_STATIC_SPEC ("multilib_extra", &multilib_extra),
1714 INIT_STATIC_SPEC ("multilib_matches", &multilib_matches),
1715 INIT_STATIC_SPEC ("multilib_exclusions", &multilib_exclusions),
1716 INIT_STATIC_SPEC ("multilib_options", &multilib_options),
1717 INIT_STATIC_SPEC ("multilib_reuse", &multilib_reuse),
1718 INIT_STATIC_SPEC ("linker", &linker_name_spec),
1719 INIT_STATIC_SPEC ("linker_plugin_file", &linker_plugin_file_spec),
1720 INIT_STATIC_SPEC ("lto_wrapper", &lto_wrapper_spec),
1721 INIT_STATIC_SPEC ("lto_gcc", &lto_gcc_spec),
1722 INIT_STATIC_SPEC ("post_link", &post_link_spec),
1723 INIT_STATIC_SPEC ("link_libgcc", &link_libgcc_spec),
1724 INIT_STATIC_SPEC ("md_exec_prefix", &md_exec_prefix),
1725 INIT_STATIC_SPEC ("md_startfile_prefix", &md_startfile_prefix),
1726 INIT_STATIC_SPEC ("md_startfile_prefix_1", &md_startfile_prefix_1),
1727 INIT_STATIC_SPEC ("startfile_prefix_spec", &startfile_prefix_spec),
1728 INIT_STATIC_SPEC ("sysroot_spec", &sysroot_spec),
1729 INIT_STATIC_SPEC ("sysroot_suffix_spec", &sysroot_suffix_spec),
1730 INIT_STATIC_SPEC ("sysroot_hdrs_suffix_spec", &sysroot_hdrs_suffix_spec),
1731 INIT_STATIC_SPEC ("self_spec", &self_spec),
1734 #ifdef EXTRA_SPECS /* additional specs needed */
1735 /* Structure to keep track of just the first two args of a spec_list.
1736 That is all that the EXTRA_SPECS macro gives us. */
1737 struct spec_list_1
1739 const char *const name;
1740 const char *const ptr;
1743 static const struct spec_list_1 extra_specs_1[] = { EXTRA_SPECS };
1744 static struct spec_list *extra_specs = (struct spec_list *) 0;
1745 #endif
1747 /* List of dynamically allocates specs that have been defined so far. */
1749 static struct spec_list *specs = (struct spec_list *) 0;
1751 /* List of static spec functions. */
1753 static const struct spec_function static_spec_functions[] =
1755 { "getenv", getenv_spec_function },
1756 { "if-exists", if_exists_spec_function },
1757 { "if-exists-else", if_exists_else_spec_function },
1758 { "if-exists-then-else", if_exists_then_else_spec_function },
1759 { "sanitize", sanitize_spec_function },
1760 { "replace-outfile", replace_outfile_spec_function },
1761 { "remove-outfile", remove_outfile_spec_function },
1762 { "version-compare", version_compare_spec_function },
1763 { "include", include_spec_function },
1764 { "find-file", find_file_spec_function },
1765 { "find-plugindir", find_plugindir_spec_function },
1766 { "print-asm-header", print_asm_header_spec_function },
1767 { "compare-debug-dump-opt", compare_debug_dump_opt_spec_function },
1768 { "compare-debug-self-opt", compare_debug_self_opt_spec_function },
1769 { "pass-through-libs", pass_through_libs_spec_func },
1770 { "dumps", dumps_spec_func },
1771 { "gt", greater_than_spec_func },
1772 { "debug-level-gt", debug_level_greater_than_spec_func },
1773 { "dwarf-version-gt", dwarf_version_greater_than_spec_func },
1774 { "fortran-preinclude-file", find_fortran_preinclude_file},
1775 #ifdef EXTRA_SPEC_FUNCTIONS
1776 EXTRA_SPEC_FUNCTIONS
1777 #endif
1778 { 0, 0 }
1781 static int processing_spec_function;
1783 /* Add appropriate libgcc specs to OBSTACK, taking into account
1784 various permutations of -shared-libgcc, -shared, and such. */
1786 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1788 #ifndef USE_LD_AS_NEEDED
1789 #define USE_LD_AS_NEEDED 0
1790 #endif
1792 static void
1793 init_gcc_specs (struct obstack *obstack, const char *shared_name,
1794 const char *static_name, const char *eh_name)
1796 char *buf;
1798 #if USE_LD_AS_NEEDED
1799 buf = concat ("%{static|static-libgcc|static-pie:", static_name, " ", eh_name, "}"
1800 "%{!static:%{!static-libgcc:%{!static-pie:"
1801 "%{!shared-libgcc:",
1802 static_name, " " LD_AS_NEEDED_OPTION " ",
1803 shared_name, " " LD_NO_AS_NEEDED_OPTION
1805 "%{shared-libgcc:",
1806 shared_name, "%{!shared: ", static_name, "}"
1807 "}}"
1808 #else
1809 buf = concat ("%{static|static-libgcc:", static_name, " ", eh_name, "}"
1810 "%{!static:%{!static-libgcc:"
1811 "%{!shared:"
1812 "%{!shared-libgcc:", static_name, " ", eh_name, "}"
1813 "%{shared-libgcc:", shared_name, " ", static_name, "}"
1815 #ifdef LINK_EH_SPEC
1816 "%{shared:"
1817 "%{shared-libgcc:", shared_name, "}"
1818 "%{!shared-libgcc:", static_name, "}"
1820 #else
1821 "%{shared:", shared_name, "}"
1822 #endif
1823 #endif
1824 "}}", NULL);
1826 obstack_grow (obstack, buf, strlen (buf));
1827 free (buf);
1829 #endif /* ENABLE_SHARED_LIBGCC */
1831 /* Initialize the specs lookup routines. */
1833 static void
1834 init_spec (void)
1836 struct spec_list *next = (struct spec_list *) 0;
1837 struct spec_list *sl = (struct spec_list *) 0;
1838 int i;
1840 if (specs)
1841 return; /* Already initialized. */
1843 if (verbose_flag)
1844 fnotice (stderr, "Using built-in specs.\n");
1846 #ifdef EXTRA_SPECS
1847 extra_specs = XCNEWVEC (struct spec_list, ARRAY_SIZE (extra_specs_1));
1849 for (i = ARRAY_SIZE (extra_specs_1) - 1; i >= 0; i--)
1851 sl = &extra_specs[i];
1852 sl->name = extra_specs_1[i].name;
1853 sl->ptr = extra_specs_1[i].ptr;
1854 sl->next = next;
1855 sl->name_len = strlen (sl->name);
1856 sl->ptr_spec = &sl->ptr;
1857 gcc_assert (sl->ptr_spec != NULL);
1858 sl->default_ptr = sl->ptr;
1859 next = sl;
1861 #endif
1863 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1865 sl = &static_specs[i];
1866 sl->next = next;
1867 next = sl;
1870 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1871 /* ??? If neither -shared-libgcc nor --static-libgcc was
1872 seen, then we should be making an educated guess. Some proposed
1873 heuristics for ELF include:
1875 (1) If "-Wl,--export-dynamic", then it's a fair bet that the
1876 program will be doing dynamic loading, which will likely
1877 need the shared libgcc.
1879 (2) If "-ldl", then it's also a fair bet that we're doing
1880 dynamic loading.
1882 (3) For each ET_DYN we're linking against (either through -lfoo
1883 or /some/path/foo.so), check to see whether it or one of
1884 its dependencies depends on a shared libgcc.
1886 (4) If "-shared"
1888 If the runtime is fixed to look for program headers instead
1889 of calling __register_frame_info at all, for each object,
1890 use the shared libgcc if any EH symbol referenced.
1892 If crtstuff is fixed to not invoke __register_frame_info
1893 automatically, for each object, use the shared libgcc if
1894 any non-empty unwind section found.
1896 Doing any of this probably requires invoking an external program to
1897 do the actual object file scanning. */
1899 const char *p = libgcc_spec;
1900 int in_sep = 1;
1902 /* Transform the extant libgcc_spec into one that uses the shared libgcc
1903 when given the proper command line arguments. */
1904 while (*p)
1906 if (in_sep && *p == '-' && startswith (p, "-lgcc"))
1908 init_gcc_specs (&obstack,
1909 "-lgcc_s"
1910 #ifdef USE_LIBUNWIND_EXCEPTIONS
1911 " -lunwind"
1912 #endif
1914 "-lgcc",
1915 "-lgcc_eh"
1916 #ifdef USE_LIBUNWIND_EXCEPTIONS
1917 # ifdef HAVE_LD_STATIC_DYNAMIC
1918 " %{!static:%{!static-pie:" LD_STATIC_OPTION "}} -lunwind"
1919 " %{!static:%{!static-pie:" LD_DYNAMIC_OPTION "}}"
1920 # else
1921 " -lunwind"
1922 # endif
1923 #endif
1926 p += 5;
1927 in_sep = 0;
1929 else if (in_sep && *p == 'l' && startswith (p, "libgcc.a%s"))
1931 /* Ug. We don't know shared library extensions. Hope that
1932 systems that use this form don't do shared libraries. */
1933 init_gcc_specs (&obstack,
1934 "-lgcc_s",
1935 "libgcc.a%s",
1936 "libgcc_eh.a%s"
1937 #ifdef USE_LIBUNWIND_EXCEPTIONS
1938 " -lunwind"
1939 #endif
1941 p += 10;
1942 in_sep = 0;
1944 else
1946 obstack_1grow (&obstack, *p);
1947 in_sep = (*p == ' ');
1948 p += 1;
1952 obstack_1grow (&obstack, '\0');
1953 libgcc_spec = XOBFINISH (&obstack, const char *);
1955 #endif
1956 #ifdef USE_AS_TRADITIONAL_FORMAT
1957 /* Prepend "--traditional-format" to whatever asm_spec we had before. */
1959 static const char tf[] = "--traditional-format ";
1960 obstack_grow (&obstack, tf, sizeof (tf) - 1);
1961 obstack_grow0 (&obstack, asm_spec, strlen (asm_spec));
1962 asm_spec = XOBFINISH (&obstack, const char *);
1964 #endif
1966 #if defined LINK_EH_SPEC || defined LINK_BUILDID_SPEC || \
1967 defined LINKER_HASH_STYLE
1968 # ifdef LINK_BUILDID_SPEC
1969 /* Prepend LINK_BUILDID_SPEC to whatever link_spec we had before. */
1970 obstack_grow (&obstack, LINK_BUILDID_SPEC, sizeof (LINK_BUILDID_SPEC) - 1);
1971 # endif
1972 # ifdef LINK_EH_SPEC
1973 /* Prepend LINK_EH_SPEC to whatever link_spec we had before. */
1974 obstack_grow (&obstack, LINK_EH_SPEC, sizeof (LINK_EH_SPEC) - 1);
1975 # endif
1976 # ifdef LINKER_HASH_STYLE
1977 /* Prepend --hash-style=LINKER_HASH_STYLE to whatever link_spec we had
1978 before. */
1980 static const char hash_style[] = "--hash-style=";
1981 obstack_grow (&obstack, hash_style, sizeof (hash_style) - 1);
1982 obstack_grow (&obstack, LINKER_HASH_STYLE, sizeof (LINKER_HASH_STYLE) - 1);
1983 obstack_1grow (&obstack, ' ');
1985 # endif
1986 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
1987 link_spec = XOBFINISH (&obstack, const char *);
1988 #endif
1990 specs = sl;
1993 /* Update the entry for SPEC in the static_specs table to point to VALUE,
1994 ensuring that we free the previous value if necessary. Set alloc_p for the
1995 entry to ALLOC_P: this determines whether we take ownership of VALUE (i.e.
1996 whether we need to free it later on). */
1997 static void
1998 set_static_spec (const char **spec, const char *value, bool alloc_p)
2000 struct spec_list *sl = NULL;
2002 for (unsigned i = 0; i < ARRAY_SIZE (static_specs); i++)
2004 if (static_specs[i].ptr_spec == spec)
2006 sl = static_specs + i;
2007 break;
2011 gcc_assert (sl);
2013 if (sl->alloc_p)
2015 const char *old = *spec;
2016 free (const_cast <char *> (old));
2019 *spec = value;
2020 sl->alloc_p = alloc_p;
2023 /* Update a static spec to a new string, taking ownership of that
2024 string's memory. */
2025 static void set_static_spec_owned (const char **spec, const char *val)
2027 return set_static_spec (spec, val, true);
2030 /* Update a static spec to point to a new value, but don't take
2031 ownership of (i.e. don't free) that string. */
2032 static void set_static_spec_shared (const char **spec, const char *val)
2034 return set_static_spec (spec, val, false);
2038 /* Change the value of spec NAME to SPEC. If SPEC is empty, then the spec is
2039 removed; If the spec starts with a + then SPEC is added to the end of the
2040 current spec. */
2042 static void
2043 set_spec (const char *name, const char *spec, bool user_p)
2045 struct spec_list *sl;
2046 const char *old_spec;
2047 int name_len = strlen (name);
2048 int i;
2050 /* If this is the first call, initialize the statically allocated specs. */
2051 if (!specs)
2053 struct spec_list *next = (struct spec_list *) 0;
2054 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
2056 sl = &static_specs[i];
2057 sl->next = next;
2058 next = sl;
2060 specs = sl;
2063 /* See if the spec already exists. */
2064 for (sl = specs; sl; sl = sl->next)
2065 if (name_len == sl->name_len && !strcmp (sl->name, name))
2066 break;
2068 if (!sl)
2070 /* Not found - make it. */
2071 sl = XNEW (struct spec_list);
2072 sl->name = xstrdup (name);
2073 sl->name_len = name_len;
2074 sl->ptr_spec = &sl->ptr;
2075 sl->alloc_p = 0;
2076 *(sl->ptr_spec) = "";
2077 sl->next = specs;
2078 sl->default_ptr = NULL;
2079 specs = sl;
2082 old_spec = *(sl->ptr_spec);
2083 *(sl->ptr_spec) = ((spec[0] == '+' && ISSPACE ((unsigned char)spec[1]))
2084 ? concat (old_spec, spec + 1, NULL)
2085 : xstrdup (spec));
2087 #ifdef DEBUG_SPECS
2088 if (verbose_flag)
2089 fnotice (stderr, "Setting spec %s to '%s'\n\n", name, *(sl->ptr_spec));
2090 #endif
2092 /* Free the old spec. */
2093 if (old_spec && sl->alloc_p)
2094 free (CONST_CAST (char *, old_spec));
2096 sl->user_p = user_p;
2097 sl->alloc_p = true;
2100 /* Accumulate a command (program name and args), and run it. */
2102 typedef const char *const_char_p; /* For DEF_VEC_P. */
2104 /* Vector of pointers to arguments in the current line of specifications. */
2105 static vec<const_char_p> argbuf;
2107 /* Likewise, but for the current @file. */
2108 static vec<const_char_p> at_file_argbuf;
2110 /* Whether an @file is currently open. */
2111 static bool in_at_file = false;
2113 /* Were the options -c, -S or -E passed. */
2114 static int have_c = 0;
2116 /* Was the option -o passed. */
2117 static int have_o = 0;
2119 /* Was the option -E passed. */
2120 static int have_E = 0;
2122 /* Pointer to output file name passed in with -o. */
2123 static const char *output_file = 0;
2125 /* This is the list of suffixes and codes (%g/%u/%U/%j) and the associated
2126 temp file. If the HOST_BIT_BUCKET is used for %j, no entry is made for
2127 it here. */
2129 static struct temp_name {
2130 const char *suffix; /* suffix associated with the code. */
2131 int length; /* strlen (suffix). */
2132 int unique; /* Indicates whether %g or %u/%U was used. */
2133 const char *filename; /* associated filename. */
2134 int filename_length; /* strlen (filename). */
2135 struct temp_name *next;
2136 } *temp_names;
2138 /* Number of commands executed so far. */
2140 static int execution_count;
2142 /* Number of commands that exited with a signal. */
2144 static int signal_count;
2146 /* Allocate the argument vector. */
2148 static void
2149 alloc_args (void)
2151 argbuf.create (10);
2152 at_file_argbuf.create (10);
2155 /* Clear out the vector of arguments (after a command is executed). */
2157 static void
2158 clear_args (void)
2160 argbuf.truncate (0);
2161 at_file_argbuf.truncate (0);
2164 /* Add one argument to the vector at the end.
2165 This is done when a space is seen or at the end of the line.
2166 If DELETE_ALWAYS is nonzero, the arg is a filename
2167 and the file should be deleted eventually.
2168 If DELETE_FAILURE is nonzero, the arg is a filename
2169 and the file should be deleted if this compilation fails. */
2171 static void
2172 store_arg (const char *arg, int delete_always, int delete_failure)
2174 if (in_at_file)
2175 at_file_argbuf.safe_push (arg);
2176 else
2177 argbuf.safe_push (arg);
2179 if (delete_always || delete_failure)
2181 const char *p;
2182 /* If the temporary file we should delete is specified as
2183 part of a joined argument extract the filename. */
2184 if (arg[0] == '-'
2185 && (p = strrchr (arg, '=')))
2186 arg = p + 1;
2187 record_temp_file (arg, delete_always, delete_failure);
2191 /* Open a temporary @file into which subsequent arguments will be stored. */
2193 static void
2194 open_at_file (void)
2196 if (in_at_file)
2197 fatal_error (input_location, "cannot open nested response file");
2198 else
2199 in_at_file = true;
2202 /* Create a temporary @file name. */
2204 static char *make_at_file (void)
2206 static int fileno = 0;
2207 char filename[20];
2208 const char *base, *ext;
2210 if (!save_temps_flag)
2211 return make_temp_file ("");
2213 base = dumpbase;
2214 if (!(base && *base))
2215 base = dumpdir;
2216 if (!(base && *base))
2217 base = "a";
2219 sprintf (filename, ".args.%d", fileno++);
2220 ext = filename;
2222 if (base == dumpdir && dumpdir_trailing_dash_added)
2223 ext++;
2225 return concat (base, ext, NULL);
2228 /* Close the temporary @file and add @file to the argument list. */
2230 static void
2231 close_at_file (void)
2233 if (!in_at_file)
2234 fatal_error (input_location, "cannot close nonexistent response file");
2236 in_at_file = false;
2238 const unsigned int n_args = at_file_argbuf.length ();
2239 if (n_args == 0)
2240 return;
2242 char **argv = XALLOCAVEC (char *, n_args + 1);
2243 char *temp_file = make_at_file ();
2244 char *at_argument = concat ("@", temp_file, NULL);
2245 FILE *f = fopen (temp_file, "w");
2246 int status;
2247 unsigned int i;
2249 /* Copy the strings over. */
2250 for (i = 0; i < n_args; i++)
2251 argv[i] = CONST_CAST (char *, at_file_argbuf[i]);
2252 argv[i] = NULL;
2254 at_file_argbuf.truncate (0);
2256 if (f == NULL)
2257 fatal_error (input_location, "could not open temporary response file %s",
2258 temp_file);
2260 status = writeargv (argv, f);
2262 if (status)
2263 fatal_error (input_location,
2264 "could not write to temporary response file %s",
2265 temp_file);
2267 status = fclose (f);
2269 if (status == EOF)
2270 fatal_error (input_location, "could not close temporary response file %s",
2271 temp_file);
2273 store_arg (at_argument, 0, 0);
2275 record_temp_file (temp_file, !save_temps_flag, !save_temps_flag);
2278 /* Load specs from a file name named FILENAME, replacing occurrences of
2279 various different types of line-endings, \r\n, \n\r and just \r, with
2280 a single \n. */
2282 static char *
2283 load_specs (const char *filename)
2285 int desc;
2286 int readlen;
2287 struct stat statbuf;
2288 char *buffer;
2289 char *buffer_p;
2290 char *specs;
2291 char *specs_p;
2293 if (verbose_flag)
2294 fnotice (stderr, "Reading specs from %s\n", filename);
2296 /* Open and stat the file. */
2297 desc = open (filename, O_RDONLY, 0);
2298 if (desc < 0)
2300 failed:
2301 /* This leaves DESC open, but the OS will save us. */
2302 fatal_error (input_location, "cannot read spec file %qs: %m", filename);
2305 if (stat (filename, &statbuf) < 0)
2306 goto failed;
2308 /* Read contents of file into BUFFER. */
2309 buffer = XNEWVEC (char, statbuf.st_size + 1);
2310 readlen = read (desc, buffer, (unsigned) statbuf.st_size);
2311 if (readlen < 0)
2312 goto failed;
2313 buffer[readlen] = 0;
2314 close (desc);
2316 specs = XNEWVEC (char, readlen + 1);
2317 specs_p = specs;
2318 for (buffer_p = buffer; buffer_p && *buffer_p; buffer_p++)
2320 int skip = 0;
2321 char c = *buffer_p;
2322 if (c == '\r')
2324 if (buffer_p > buffer && *(buffer_p - 1) == '\n') /* \n\r */
2325 skip = 1;
2326 else if (*(buffer_p + 1) == '\n') /* \r\n */
2327 skip = 1;
2328 else /* \r */
2329 c = '\n';
2331 if (! skip)
2332 *specs_p++ = c;
2334 *specs_p = '\0';
2336 free (buffer);
2337 return (specs);
2340 /* Read compilation specs from a file named FILENAME,
2341 replacing the default ones.
2343 A suffix which starts with `*' is a definition for
2344 one of the machine-specific sub-specs. The "suffix" should be
2345 *asm, *cc1, *cpp, *link, *startfile, etc.
2346 The corresponding spec is stored in asm_spec, etc.,
2347 rather than in the `compilers' vector.
2349 Anything invalid in the file is a fatal error. */
2351 static void
2352 read_specs (const char *filename, bool main_p, bool user_p)
2354 char *buffer;
2355 char *p;
2357 buffer = load_specs (filename);
2359 /* Scan BUFFER for specs, putting them in the vector. */
2360 p = buffer;
2361 while (1)
2363 char *suffix;
2364 char *spec;
2365 char *in, *out, *p1, *p2, *p3;
2367 /* Advance P in BUFFER to the next nonblank nocomment line. */
2368 p = skip_whitespace (p);
2369 if (*p == 0)
2370 break;
2372 /* Is this a special command that starts with '%'? */
2373 /* Don't allow this for the main specs file, since it would
2374 encourage people to overwrite it. */
2375 if (*p == '%' && !main_p)
2377 p1 = p;
2378 while (*p && *p != '\n')
2379 p++;
2381 /* Skip '\n'. */
2382 p++;
2384 if (startswith (p1, "%include")
2385 && (p1[sizeof "%include" - 1] == ' '
2386 || p1[sizeof "%include" - 1] == '\t'))
2388 char *new_filename;
2390 p1 += sizeof ("%include");
2391 while (*p1 == ' ' || *p1 == '\t')
2392 p1++;
2394 if (*p1++ != '<' || p[-2] != '>')
2395 fatal_error (input_location,
2396 "specs %%include syntax malformed after "
2397 "%ld characters",
2398 (long) (p1 - buffer + 1));
2400 p[-2] = '\0';
2401 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
2402 read_specs (new_filename ? new_filename : p1, false, user_p);
2403 continue;
2405 else if (startswith (p1, "%include_noerr")
2406 && (p1[sizeof "%include_noerr" - 1] == ' '
2407 || p1[sizeof "%include_noerr" - 1] == '\t'))
2409 char *new_filename;
2411 p1 += sizeof "%include_noerr";
2412 while (*p1 == ' ' || *p1 == '\t')
2413 p1++;
2415 if (*p1++ != '<' || p[-2] != '>')
2416 fatal_error (input_location,
2417 "specs %%include syntax malformed after "
2418 "%ld characters",
2419 (long) (p1 - buffer + 1));
2421 p[-2] = '\0';
2422 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
2423 if (new_filename)
2424 read_specs (new_filename, false, user_p);
2425 else if (verbose_flag)
2426 fnotice (stderr, "could not find specs file %s\n", p1);
2427 continue;
2429 else if (startswith (p1, "%rename")
2430 && (p1[sizeof "%rename" - 1] == ' '
2431 || p1[sizeof "%rename" - 1] == '\t'))
2433 int name_len;
2434 struct spec_list *sl;
2435 struct spec_list *newsl;
2437 /* Get original name. */
2438 p1 += sizeof "%rename";
2439 while (*p1 == ' ' || *p1 == '\t')
2440 p1++;
2442 if (! ISALPHA ((unsigned char) *p1))
2443 fatal_error (input_location,
2444 "specs %%rename syntax malformed after "
2445 "%ld characters",
2446 (long) (p1 - buffer));
2448 p2 = p1;
2449 while (*p2 && !ISSPACE ((unsigned char) *p2))
2450 p2++;
2452 if (*p2 != ' ' && *p2 != '\t')
2453 fatal_error (input_location,
2454 "specs %%rename syntax malformed after "
2455 "%ld characters",
2456 (long) (p2 - buffer));
2458 name_len = p2 - p1;
2459 *p2++ = '\0';
2460 while (*p2 == ' ' || *p2 == '\t')
2461 p2++;
2463 if (! ISALPHA ((unsigned char) *p2))
2464 fatal_error (input_location,
2465 "specs %%rename syntax malformed after "
2466 "%ld characters",
2467 (long) (p2 - buffer));
2469 /* Get new spec name. */
2470 p3 = p2;
2471 while (*p3 && !ISSPACE ((unsigned char) *p3))
2472 p3++;
2474 if (p3 != p - 1)
2475 fatal_error (input_location,
2476 "specs %%rename syntax malformed after "
2477 "%ld characters",
2478 (long) (p3 - buffer));
2479 *p3 = '\0';
2481 for (sl = specs; sl; sl = sl->next)
2482 if (name_len == sl->name_len && !strcmp (sl->name, p1))
2483 break;
2485 if (!sl)
2486 fatal_error (input_location,
2487 "specs %s spec was not found to be renamed", p1);
2489 if (strcmp (p1, p2) == 0)
2490 continue;
2492 for (newsl = specs; newsl; newsl = newsl->next)
2493 if (strcmp (newsl->name, p2) == 0)
2494 fatal_error (input_location,
2495 "%s: attempt to rename spec %qs to "
2496 "already defined spec %qs",
2497 filename, p1, p2);
2499 if (verbose_flag)
2501 fnotice (stderr, "rename spec %s to %s\n", p1, p2);
2502 #ifdef DEBUG_SPECS
2503 fnotice (stderr, "spec is '%s'\n\n", *(sl->ptr_spec));
2504 #endif
2507 set_spec (p2, *(sl->ptr_spec), user_p);
2508 if (sl->alloc_p)
2509 free (CONST_CAST (char *, *(sl->ptr_spec)));
2511 *(sl->ptr_spec) = "";
2512 sl->alloc_p = 0;
2513 continue;
2515 else
2516 fatal_error (input_location,
2517 "specs unknown %% command after %ld characters",
2518 (long) (p1 - buffer));
2521 /* Find the colon that should end the suffix. */
2522 p1 = p;
2523 while (*p1 && *p1 != ':' && *p1 != '\n')
2524 p1++;
2526 /* The colon shouldn't be missing. */
2527 if (*p1 != ':')
2528 fatal_error (input_location,
2529 "specs file malformed after %ld characters",
2530 (long) (p1 - buffer));
2532 /* Skip back over trailing whitespace. */
2533 p2 = p1;
2534 while (p2 > buffer && (p2[-1] == ' ' || p2[-1] == '\t'))
2535 p2--;
2537 /* Copy the suffix to a string. */
2538 suffix = save_string (p, p2 - p);
2539 /* Find the next line. */
2540 p = skip_whitespace (p1 + 1);
2541 if (p[1] == 0)
2542 fatal_error (input_location,
2543 "specs file malformed after %ld characters",
2544 (long) (p - buffer));
2546 p1 = p;
2547 /* Find next blank line or end of string. */
2548 while (*p1 && !(*p1 == '\n' && (p1[1] == '\n' || p1[1] == '\0')))
2549 p1++;
2551 /* Specs end at the blank line and do not include the newline. */
2552 spec = save_string (p, p1 - p);
2553 p = p1;
2555 /* Delete backslash-newline sequences from the spec. */
2556 in = spec;
2557 out = spec;
2558 while (*in != 0)
2560 if (in[0] == '\\' && in[1] == '\n')
2561 in += 2;
2562 else if (in[0] == '#')
2563 while (*in && *in != '\n')
2564 in++;
2566 else
2567 *out++ = *in++;
2569 *out = 0;
2571 if (suffix[0] == '*')
2573 if (! strcmp (suffix, "*link_command"))
2574 link_command_spec = spec;
2575 else
2577 set_spec (suffix + 1, spec, user_p);
2578 free (spec);
2581 else
2583 /* Add this pair to the vector. */
2584 compilers
2585 = XRESIZEVEC (struct compiler, compilers, n_compilers + 2);
2587 compilers[n_compilers].suffix = suffix;
2588 compilers[n_compilers].spec = spec;
2589 n_compilers++;
2590 memset (&compilers[n_compilers], 0, sizeof compilers[n_compilers]);
2593 if (*suffix == 0)
2594 link_command_spec = spec;
2597 if (link_command_spec == 0)
2598 fatal_error (input_location, "spec file has no spec for linking");
2600 XDELETEVEC (buffer);
2603 /* Record the names of temporary files we tell compilers to write,
2604 and delete them at the end of the run. */
2606 /* This is the common prefix we use to make temp file names.
2607 It is chosen once for each run of this program.
2608 It is substituted into a spec by %g or %j.
2609 Thus, all temp file names contain this prefix.
2610 In practice, all temp file names start with this prefix.
2612 This prefix comes from the envvar TMPDIR if it is defined;
2613 otherwise, from the P_tmpdir macro if that is defined;
2614 otherwise, in /usr/tmp or /tmp;
2615 or finally the current directory if all else fails. */
2617 static const char *temp_filename;
2619 /* Length of the prefix. */
2621 static int temp_filename_length;
2623 /* Define the list of temporary files to delete. */
2625 struct temp_file
2627 const char *name;
2628 struct temp_file *next;
2631 /* Queue of files to delete on success or failure of compilation. */
2632 static struct temp_file *always_delete_queue;
2633 /* Queue of files to delete on failure of compilation. */
2634 static struct temp_file *failure_delete_queue;
2636 /* Record FILENAME as a file to be deleted automatically.
2637 ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
2638 otherwise delete it in any case.
2639 FAIL_DELETE nonzero means delete it if a compilation step fails;
2640 otherwise delete it in any case. */
2642 void
2643 record_temp_file (const char *filename, int always_delete, int fail_delete)
2645 char *const name = xstrdup (filename);
2647 if (always_delete)
2649 struct temp_file *temp;
2650 for (temp = always_delete_queue; temp; temp = temp->next)
2651 if (! filename_cmp (name, temp->name))
2653 free (name);
2654 goto already1;
2657 temp = XNEW (struct temp_file);
2658 temp->next = always_delete_queue;
2659 temp->name = name;
2660 always_delete_queue = temp;
2662 already1:;
2665 if (fail_delete)
2667 struct temp_file *temp;
2668 for (temp = failure_delete_queue; temp; temp = temp->next)
2669 if (! filename_cmp (name, temp->name))
2671 free (name);
2672 goto already2;
2675 temp = XNEW (struct temp_file);
2676 temp->next = failure_delete_queue;
2677 temp->name = name;
2678 failure_delete_queue = temp;
2680 already2:;
2684 /* Delete all the temporary files whose names we previously recorded. */
2686 #ifndef DELETE_IF_ORDINARY
2687 #define DELETE_IF_ORDINARY(NAME,ST,VERBOSE_FLAG) \
2688 do \
2690 if (stat (NAME, &ST) >= 0 && S_ISREG (ST.st_mode)) \
2691 if (unlink (NAME) < 0) \
2692 if (VERBOSE_FLAG) \
2693 error ("%s: %m", (NAME)); \
2694 } while (0)
2695 #endif
2697 static void
2698 delete_if_ordinary (const char *name)
2700 struct stat st;
2701 #ifdef DEBUG
2702 int i, c;
2704 printf ("Delete %s? (y or n) ", name);
2705 fflush (stdout);
2706 i = getchar ();
2707 if (i != '\n')
2708 while ((c = getchar ()) != '\n' && c != EOF)
2711 if (i == 'y' || i == 'Y')
2712 #endif /* DEBUG */
2713 DELETE_IF_ORDINARY (name, st, verbose_flag);
2716 static void
2717 delete_temp_files (void)
2719 struct temp_file *temp;
2721 for (temp = always_delete_queue; temp; temp = temp->next)
2722 delete_if_ordinary (temp->name);
2723 always_delete_queue = 0;
2726 /* Delete all the files to be deleted on error. */
2728 static void
2729 delete_failure_queue (void)
2731 struct temp_file *temp;
2733 for (temp = failure_delete_queue; temp; temp = temp->next)
2734 delete_if_ordinary (temp->name);
2737 static void
2738 clear_failure_queue (void)
2740 failure_delete_queue = 0;
2743 /* Call CALLBACK for each path in PATHS, breaking out early if CALLBACK
2744 returns non-NULL.
2745 If DO_MULTI is true iterate over the paths twice, first with multilib
2746 suffix then without, otherwise iterate over the paths once without
2747 adding a multilib suffix. When DO_MULTI is true, some attempt is made
2748 to avoid visiting the same path twice, but we could do better. For
2749 instance, /usr/lib/../lib is considered different from /usr/lib.
2750 At least EXTRA_SPACE chars past the end of the path passed to
2751 CALLBACK are available for use by the callback.
2752 CALLBACK_INFO allows extra parameters to be passed to CALLBACK.
2754 Returns the value returned by CALLBACK. */
2756 static void *
2757 for_each_path (const struct path_prefix *paths,
2758 bool do_multi,
2759 size_t extra_space,
2760 void *(*callback) (char *, void *),
2761 void *callback_info)
2763 struct prefix_list *pl;
2764 const char *multi_dir = NULL;
2765 const char *multi_os_dir = NULL;
2766 const char *multiarch_suffix = NULL;
2767 const char *multi_suffix;
2768 const char *just_multi_suffix;
2769 char *path = NULL;
2770 void *ret = NULL;
2771 bool skip_multi_dir = false;
2772 bool skip_multi_os_dir = false;
2774 multi_suffix = machine_suffix;
2775 just_multi_suffix = just_machine_suffix;
2776 if (do_multi && multilib_dir && strcmp (multilib_dir, ".") != 0)
2778 multi_dir = concat (multilib_dir, dir_separator_str, NULL);
2779 multi_suffix = concat (multi_suffix, multi_dir, NULL);
2780 just_multi_suffix = concat (just_multi_suffix, multi_dir, NULL);
2782 if (do_multi && multilib_os_dir && strcmp (multilib_os_dir, ".") != 0)
2783 multi_os_dir = concat (multilib_os_dir, dir_separator_str, NULL);
2784 if (multiarch_dir)
2785 multiarch_suffix = concat (multiarch_dir, dir_separator_str, NULL);
2787 while (1)
2789 size_t multi_dir_len = 0;
2790 size_t multi_os_dir_len = 0;
2791 size_t multiarch_len = 0;
2792 size_t suffix_len;
2793 size_t just_suffix_len;
2794 size_t len;
2796 if (multi_dir)
2797 multi_dir_len = strlen (multi_dir);
2798 if (multi_os_dir)
2799 multi_os_dir_len = strlen (multi_os_dir);
2800 if (multiarch_suffix)
2801 multiarch_len = strlen (multiarch_suffix);
2802 suffix_len = strlen (multi_suffix);
2803 just_suffix_len = strlen (just_multi_suffix);
2805 if (path == NULL)
2807 len = paths->max_len + extra_space + 1;
2808 len += MAX (MAX (suffix_len, multi_os_dir_len), multiarch_len);
2809 path = XNEWVEC (char, len);
2812 for (pl = paths->plist; pl != 0; pl = pl->next)
2814 len = strlen (pl->prefix);
2815 memcpy (path, pl->prefix, len);
2817 /* Look first in MACHINE/VERSION subdirectory. */
2818 if (!skip_multi_dir)
2820 memcpy (path + len, multi_suffix, suffix_len + 1);
2821 ret = callback (path, callback_info);
2822 if (ret)
2823 break;
2826 /* Some paths are tried with just the machine (ie. target)
2827 subdir. This is used for finding as, ld, etc. */
2828 if (!skip_multi_dir
2829 && pl->require_machine_suffix == 2)
2831 memcpy (path + len, just_multi_suffix, just_suffix_len + 1);
2832 ret = callback (path, callback_info);
2833 if (ret)
2834 break;
2837 /* Now try the multiarch path. */
2838 if (!skip_multi_dir
2839 && !pl->require_machine_suffix && multiarch_dir)
2841 memcpy (path + len, multiarch_suffix, multiarch_len + 1);
2842 ret = callback (path, callback_info);
2843 if (ret)
2844 break;
2847 /* Now try the base path. */
2848 if (!pl->require_machine_suffix
2849 && !(pl->os_multilib ? skip_multi_os_dir : skip_multi_dir))
2851 const char *this_multi;
2852 size_t this_multi_len;
2854 if (pl->os_multilib)
2856 this_multi = multi_os_dir;
2857 this_multi_len = multi_os_dir_len;
2859 else
2861 this_multi = multi_dir;
2862 this_multi_len = multi_dir_len;
2865 if (this_multi_len)
2866 memcpy (path + len, this_multi, this_multi_len + 1);
2867 else
2868 path[len] = '\0';
2870 ret = callback (path, callback_info);
2871 if (ret)
2872 break;
2875 if (pl)
2876 break;
2878 if (multi_dir == NULL && multi_os_dir == NULL)
2879 break;
2881 /* Run through the paths again, this time without multilibs.
2882 Don't repeat any we have already seen. */
2883 if (multi_dir)
2885 free (CONST_CAST (char *, multi_dir));
2886 multi_dir = NULL;
2887 free (CONST_CAST (char *, multi_suffix));
2888 multi_suffix = machine_suffix;
2889 free (CONST_CAST (char *, just_multi_suffix));
2890 just_multi_suffix = just_machine_suffix;
2892 else
2893 skip_multi_dir = true;
2894 if (multi_os_dir)
2896 free (CONST_CAST (char *, multi_os_dir));
2897 multi_os_dir = NULL;
2899 else
2900 skip_multi_os_dir = true;
2903 if (multi_dir)
2905 free (CONST_CAST (char *, multi_dir));
2906 free (CONST_CAST (char *, multi_suffix));
2907 free (CONST_CAST (char *, just_multi_suffix));
2909 if (multi_os_dir)
2910 free (CONST_CAST (char *, multi_os_dir));
2911 if (ret != path)
2912 free (path);
2913 return ret;
2916 /* Callback for build_search_list. Adds path to obstack being built. */
2918 struct add_to_obstack_info {
2919 struct obstack *ob;
2920 bool check_dir;
2921 bool first_time;
2924 static void *
2925 add_to_obstack (char *path, void *data)
2927 struct add_to_obstack_info *info = (struct add_to_obstack_info *) data;
2929 if (info->check_dir && !is_directory (path, false))
2930 return NULL;
2932 if (!info->first_time)
2933 obstack_1grow (info->ob, PATH_SEPARATOR);
2935 obstack_grow (info->ob, path, strlen (path));
2937 info->first_time = false;
2938 return NULL;
2941 /* Add or change the value of an environment variable, outputting the
2942 change to standard error if in verbose mode. */
2943 static void
2944 xputenv (const char *string)
2946 env.xput (string);
2949 /* Build a list of search directories from PATHS.
2950 PREFIX is a string to prepend to the list.
2951 If CHECK_DIR_P is true we ensure the directory exists.
2952 If DO_MULTI is true, multilib paths are output first, then
2953 non-multilib paths.
2954 This is used mostly by putenv_from_prefixes so we use `collect_obstack'.
2955 It is also used by the --print-search-dirs flag. */
2957 static char *
2958 build_search_list (const struct path_prefix *paths, const char *prefix,
2959 bool check_dir, bool do_multi)
2961 struct add_to_obstack_info info;
2963 info.ob = &collect_obstack;
2964 info.check_dir = check_dir;
2965 info.first_time = true;
2967 obstack_grow (&collect_obstack, prefix, strlen (prefix));
2968 obstack_1grow (&collect_obstack, '=');
2970 for_each_path (paths, do_multi, 0, add_to_obstack, &info);
2972 obstack_1grow (&collect_obstack, '\0');
2973 return XOBFINISH (&collect_obstack, char *);
2976 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
2977 for collect. */
2979 static void
2980 putenv_from_prefixes (const struct path_prefix *paths, const char *env_var,
2981 bool do_multi)
2983 xputenv (build_search_list (paths, env_var, true, do_multi));
2986 /* Check whether NAME can be accessed in MODE. This is like access,
2987 except that it never considers directories to be executable. */
2989 static int
2990 access_check (const char *name, int mode)
2992 if (mode == X_OK)
2994 struct stat st;
2996 if (stat (name, &st) < 0
2997 || S_ISDIR (st.st_mode))
2998 return -1;
3001 return access (name, mode);
3004 /* Callback for find_a_file. Appends the file name to the directory
3005 path. If the resulting file exists in the right mode, return the
3006 full pathname to the file. */
3008 struct file_at_path_info {
3009 const char *name;
3010 const char *suffix;
3011 int name_len;
3012 int suffix_len;
3013 int mode;
3016 static void *
3017 file_at_path (char *path, void *data)
3019 struct file_at_path_info *info = (struct file_at_path_info *) data;
3020 size_t len = strlen (path);
3022 memcpy (path + len, info->name, info->name_len);
3023 len += info->name_len;
3025 /* Some systems have a suffix for executable files.
3026 So try appending that first. */
3027 if (info->suffix_len)
3029 memcpy (path + len, info->suffix, info->suffix_len + 1);
3030 if (access_check (path, info->mode) == 0)
3031 return path;
3034 path[len] = '\0';
3035 if (access_check (path, info->mode) == 0)
3036 return path;
3038 return NULL;
3041 /* Search for NAME using the prefix list PREFIXES. MODE is passed to
3042 access to check permissions. If DO_MULTI is true, search multilib
3043 paths then non-multilib paths, otherwise do not search multilib paths.
3044 Return 0 if not found, otherwise return its name, allocated with malloc. */
3046 static char *
3047 find_a_file (const struct path_prefix *pprefix, const char *name, int mode,
3048 bool do_multi)
3050 struct file_at_path_info info;
3052 /* Find the filename in question (special case for absolute paths). */
3054 if (IS_ABSOLUTE_PATH (name))
3056 if (access (name, mode) == 0)
3057 return xstrdup (name);
3059 return NULL;
3062 info.name = name;
3063 info.suffix = (mode & X_OK) != 0 ? HOST_EXECUTABLE_SUFFIX : "";
3064 info.name_len = strlen (info.name);
3065 info.suffix_len = strlen (info.suffix);
3066 info.mode = mode;
3068 return (char*) for_each_path (pprefix, do_multi,
3069 info.name_len + info.suffix_len,
3070 file_at_path, &info);
3073 /* Specialization of find_a_file for programs that also takes into account
3074 configure-specified default programs. */
3076 static char*
3077 find_a_program (const char *name)
3079 /* Do not search if default matches query. */
3081 #ifdef DEFAULT_ASSEMBLER
3082 if (! strcmp (name, "as") && access (DEFAULT_ASSEMBLER, X_OK) == 0)
3083 return xstrdup (DEFAULT_ASSEMBLER);
3084 #endif
3086 #ifdef DEFAULT_LINKER
3087 if (! strcmp (name, "ld") && access (DEFAULT_LINKER, X_OK) == 0)
3088 return xstrdup (DEFAULT_LINKER);
3089 #endif
3091 #ifdef DEFAULT_DSYMUTIL
3092 if (! strcmp (name, "dsymutil") && access (DEFAULT_DSYMUTIL, X_OK) == 0)
3093 return xstrdup (DEFAULT_DSYMUTIL);
3094 #endif
3096 return find_a_file (&exec_prefixes, name, X_OK, false);
3099 /* Ranking of prefixes in the sort list. -B prefixes are put before
3100 all others. */
3102 enum path_prefix_priority
3104 PREFIX_PRIORITY_B_OPT,
3105 PREFIX_PRIORITY_LAST
3108 /* Add an entry for PREFIX in PLIST. The PLIST is kept in ascending
3109 order according to PRIORITY. Within each PRIORITY, new entries are
3110 appended.
3112 If WARN is nonzero, we will warn if no file is found
3113 through this prefix. WARN should point to an int
3114 which will be set to 1 if this entry is used.
3116 COMPONENT is the value to be passed to update_path.
3118 REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
3119 the complete value of machine_suffix.
3120 2 means try both machine_suffix and just_machine_suffix. */
3122 static void
3123 add_prefix (struct path_prefix *pprefix, const char *prefix,
3124 const char *component, /* enum prefix_priority */ int priority,
3125 int require_machine_suffix, int os_multilib)
3127 struct prefix_list *pl, **prev;
3128 int len;
3130 for (prev = &pprefix->plist;
3131 (*prev) != NULL && (*prev)->priority <= priority;
3132 prev = &(*prev)->next)
3135 /* Keep track of the longest prefix. */
3137 prefix = update_path (prefix, component);
3138 len = strlen (prefix);
3139 if (len > pprefix->max_len)
3140 pprefix->max_len = len;
3142 pl = XNEW (struct prefix_list);
3143 pl->prefix = prefix;
3144 pl->require_machine_suffix = require_machine_suffix;
3145 pl->priority = priority;
3146 pl->os_multilib = os_multilib;
3148 /* Insert after PREV. */
3149 pl->next = (*prev);
3150 (*prev) = pl;
3153 /* Same as add_prefix, but prepending target_system_root to prefix. */
3154 /* The target_system_root prefix has been relocated by gcc_exec_prefix. */
3155 static void
3156 add_sysrooted_prefix (struct path_prefix *pprefix, const char *prefix,
3157 const char *component,
3158 /* enum prefix_priority */ int priority,
3159 int require_machine_suffix, int os_multilib)
3161 if (!IS_ABSOLUTE_PATH (prefix))
3162 fatal_error (input_location, "system path %qs is not absolute", prefix);
3164 if (target_system_root)
3166 char *sysroot_no_trailing_dir_separator = xstrdup (target_system_root);
3167 size_t sysroot_len = strlen (target_system_root);
3169 if (sysroot_len > 0
3170 && target_system_root[sysroot_len - 1] == DIR_SEPARATOR)
3171 sysroot_no_trailing_dir_separator[sysroot_len - 1] = '\0';
3173 if (target_sysroot_suffix)
3174 prefix = concat (sysroot_no_trailing_dir_separator,
3175 target_sysroot_suffix, prefix, NULL);
3176 else
3177 prefix = concat (sysroot_no_trailing_dir_separator, prefix, NULL);
3179 free (sysroot_no_trailing_dir_separator);
3181 /* We have to override this because GCC's notion of sysroot
3182 moves along with GCC. */
3183 component = "GCC";
3186 add_prefix (pprefix, prefix, component, priority,
3187 require_machine_suffix, os_multilib);
3190 /* Same as add_prefix, but prepending target_sysroot_hdrs_suffix to prefix. */
3192 static void
3193 add_sysrooted_hdrs_prefix (struct path_prefix *pprefix, const char *prefix,
3194 const char *component,
3195 /* enum prefix_priority */ int priority,
3196 int require_machine_suffix, int os_multilib)
3198 if (!IS_ABSOLUTE_PATH (prefix))
3199 fatal_error (input_location, "system path %qs is not absolute", prefix);
3201 if (target_system_root)
3203 char *sysroot_no_trailing_dir_separator = xstrdup (target_system_root);
3204 size_t sysroot_len = strlen (target_system_root);
3206 if (sysroot_len > 0
3207 && target_system_root[sysroot_len - 1] == DIR_SEPARATOR)
3208 sysroot_no_trailing_dir_separator[sysroot_len - 1] = '\0';
3210 if (target_sysroot_hdrs_suffix)
3211 prefix = concat (sysroot_no_trailing_dir_separator,
3212 target_sysroot_hdrs_suffix, prefix, NULL);
3213 else
3214 prefix = concat (sysroot_no_trailing_dir_separator, prefix, NULL);
3216 free (sysroot_no_trailing_dir_separator);
3218 /* We have to override this because GCC's notion of sysroot
3219 moves along with GCC. */
3220 component = "GCC";
3223 add_prefix (pprefix, prefix, component, priority,
3224 require_machine_suffix, os_multilib);
3228 /* Execute the command specified by the arguments on the current line of spec.
3229 When using pipes, this includes several piped-together commands
3230 with `|' between them.
3232 Return 0 if successful, -1 if failed. */
3234 static int
3235 execute (void)
3237 int i;
3238 int n_commands; /* # of command. */
3239 char *string;
3240 struct pex_obj *pex;
3241 struct command
3243 const char *prog; /* program name. */
3244 const char **argv; /* vector of args. */
3246 const char *arg;
3248 struct command *commands; /* each command buffer with above info. */
3250 gcc_assert (!processing_spec_function);
3252 if (wrapper_string)
3254 string = find_a_program (argbuf[0]);
3255 if (string)
3256 argbuf[0] = string;
3257 insert_wrapper (wrapper_string);
3260 /* Count # of piped commands. */
3261 for (n_commands = 1, i = 0; argbuf.iterate (i, &arg); i++)
3262 if (strcmp (arg, "|") == 0)
3263 n_commands++;
3265 /* Get storage for each command. */
3266 commands = XALLOCAVEC (struct command, n_commands);
3268 /* Split argbuf into its separate piped processes,
3269 and record info about each one.
3270 Also search for the programs that are to be run. */
3272 argbuf.safe_push (0);
3274 commands[0].prog = argbuf[0]; /* first command. */
3275 commands[0].argv = argbuf.address ();
3277 if (!wrapper_string)
3279 string = find_a_program(commands[0].prog);
3280 if (string)
3281 commands[0].argv[0] = string;
3284 for (n_commands = 1, i = 0; argbuf.iterate (i, &arg); i++)
3285 if (arg && strcmp (arg, "|") == 0)
3286 { /* each command. */
3287 #if defined (__MSDOS__) || defined (OS2) || defined (VMS)
3288 fatal_error (input_location, "%<-pipe%> not supported");
3289 #endif
3290 argbuf[i] = 0; /* Termination of command args. */
3291 commands[n_commands].prog = argbuf[i + 1];
3292 commands[n_commands].argv
3293 = &(argbuf.address ())[i + 1];
3294 string = find_a_program(commands[n_commands].prog);
3295 if (string)
3296 commands[n_commands].argv[0] = string;
3297 n_commands++;
3300 /* If -v, print what we are about to do, and maybe query. */
3302 if (verbose_flag)
3304 /* For help listings, put a blank line between sub-processes. */
3305 if (print_help_list)
3306 fputc ('\n', stderr);
3308 /* Print each piped command as a separate line. */
3309 for (i = 0; i < n_commands; i++)
3311 const char *const *j;
3313 if (verbose_only_flag)
3315 for (j = commands[i].argv; *j; j++)
3317 const char *p;
3318 for (p = *j; *p; ++p)
3319 if (!ISALNUM ((unsigned char) *p)
3320 && *p != '_' && *p != '/' && *p != '-' && *p != '.')
3321 break;
3322 if (*p || !*j)
3324 fprintf (stderr, " \"");
3325 for (p = *j; *p; ++p)
3327 if (*p == '"' || *p == '\\' || *p == '$')
3328 fputc ('\\', stderr);
3329 fputc (*p, stderr);
3331 fputc ('"', stderr);
3333 /* If it's empty, print "". */
3334 else if (!**j)
3335 fprintf (stderr, " \"\"");
3336 else
3337 fprintf (stderr, " %s", *j);
3340 else
3341 for (j = commands[i].argv; *j; j++)
3342 /* If it's empty, print "". */
3343 if (!**j)
3344 fprintf (stderr, " \"\"");
3345 else
3346 fprintf (stderr, " %s", *j);
3348 /* Print a pipe symbol after all but the last command. */
3349 if (i + 1 != n_commands)
3350 fprintf (stderr, " |");
3351 fprintf (stderr, "\n");
3353 fflush (stderr);
3354 if (verbose_only_flag != 0)
3356 /* verbose_only_flag should act as if the spec was
3357 executed, so increment execution_count before
3358 returning. This prevents spurious warnings about
3359 unused linker input files, etc. */
3360 execution_count++;
3361 return 0;
3363 #ifdef DEBUG
3364 fnotice (stderr, "\nGo ahead? (y or n) ");
3365 fflush (stderr);
3366 i = getchar ();
3367 if (i != '\n')
3368 while (getchar () != '\n')
3371 if (i != 'y' && i != 'Y')
3372 return 0;
3373 #endif /* DEBUG */
3376 #ifdef ENABLE_VALGRIND_CHECKING
3377 /* Run the each command through valgrind. To simplify prepending the
3378 path to valgrind and the option "-q" (for quiet operation unless
3379 something triggers), we allocate a separate argv array. */
3381 for (i = 0; i < n_commands; i++)
3383 const char **argv;
3384 int argc;
3385 int j;
3387 for (argc = 0; commands[i].argv[argc] != NULL; argc++)
3390 argv = XALLOCAVEC (const char *, argc + 3);
3392 argv[0] = VALGRIND_PATH;
3393 argv[1] = "-q";
3394 for (j = 2; j < argc + 2; j++)
3395 argv[j] = commands[i].argv[j - 2];
3396 argv[j] = NULL;
3398 commands[i].argv = argv;
3399 commands[i].prog = argv[0];
3401 #endif
3403 /* Run each piped subprocess. */
3405 pex = pex_init (PEX_USE_PIPES | ((report_times || report_times_to_file)
3406 ? PEX_RECORD_TIMES : 0),
3407 progname, temp_filename);
3408 if (pex == NULL)
3409 fatal_error (input_location, "%<pex_init%> failed: %m");
3411 for (i = 0; i < n_commands; i++)
3413 const char *errmsg;
3414 int err;
3415 const char *string = commands[i].argv[0];
3417 errmsg = pex_run (pex,
3418 ((i + 1 == n_commands ? PEX_LAST : 0)
3419 | (string == commands[i].prog ? PEX_SEARCH : 0)),
3420 string, CONST_CAST (char **, commands[i].argv),
3421 NULL, NULL, &err);
3422 if (errmsg != NULL)
3424 errno = err;
3425 fatal_error (input_location,
3426 err ? G_("cannot execute %qs: %s: %m")
3427 : G_("cannot execute %qs: %s"),
3428 string, errmsg);
3431 if (i && string != commands[i].prog)
3432 free (CONST_CAST (char *, string));
3435 execution_count++;
3437 /* Wait for all the subprocesses to finish. */
3440 int *statuses;
3441 struct pex_time *times = NULL;
3442 int ret_code = 0;
3444 statuses = XALLOCAVEC (int, n_commands);
3445 if (!pex_get_status (pex, n_commands, statuses))
3446 fatal_error (input_location, "failed to get exit status: %m");
3448 if (report_times || report_times_to_file)
3450 times = XALLOCAVEC (struct pex_time, n_commands);
3451 if (!pex_get_times (pex, n_commands, times))
3452 fatal_error (input_location, "failed to get process times: %m");
3455 pex_free (pex);
3457 for (i = 0; i < n_commands; ++i)
3459 int status = statuses[i];
3461 if (WIFSIGNALED (status))
3462 switch (WTERMSIG (status))
3464 case SIGINT:
3465 case SIGTERM:
3466 /* SIGQUIT and SIGKILL are not available on MinGW. */
3467 #ifdef SIGQUIT
3468 case SIGQUIT:
3469 #endif
3470 #ifdef SIGKILL
3471 case SIGKILL:
3472 #endif
3473 /* The user (or environment) did something to the
3474 inferior. Making this an ICE confuses the user into
3475 thinking there's a compiler bug. Much more likely is
3476 the user or OOM killer nuked it. */
3477 fatal_error (input_location,
3478 "%s signal terminated program %s",
3479 strsignal (WTERMSIG (status)),
3480 commands[i].prog);
3481 break;
3483 #ifdef SIGPIPE
3484 case SIGPIPE:
3485 /* SIGPIPE is a special case. It happens in -pipe mode
3486 when the compiler dies before the preprocessor is
3487 done, or the assembler dies before the compiler is
3488 done. There's generally been an error already, and
3489 this is just fallout. So don't generate another
3490 error unless we would otherwise have succeeded. */
3491 if (signal_count || greatest_status >= MIN_FATAL_STATUS)
3493 signal_count++;
3494 ret_code = -1;
3495 break;
3497 #endif
3498 /* FALLTHROUGH */
3500 default:
3501 /* The inferior failed to catch the signal. */
3502 internal_error_no_backtrace ("%s signal terminated program %s",
3503 strsignal (WTERMSIG (status)),
3504 commands[i].prog);
3506 else if (WIFEXITED (status)
3507 && WEXITSTATUS (status) >= MIN_FATAL_STATUS)
3509 /* For ICEs in cc1, cc1obj, cc1plus see if it is
3510 reproducible or not. */
3511 const char *p;
3512 if (flag_report_bug
3513 && WEXITSTATUS (status) == ICE_EXIT_CODE
3514 && i == 0
3515 && (p = strrchr (commands[0].argv[0], DIR_SEPARATOR))
3516 && startswith (p + 1, "cc1"))
3517 try_generate_repro (commands[0].argv);
3518 if (WEXITSTATUS (status) > greatest_status)
3519 greatest_status = WEXITSTATUS (status);
3520 ret_code = -1;
3523 if (report_times || report_times_to_file)
3525 struct pex_time *pt = &times[i];
3526 double ut, st;
3528 ut = ((double) pt->user_seconds
3529 + (double) pt->user_microseconds / 1.0e6);
3530 st = ((double) pt->system_seconds
3531 + (double) pt->system_microseconds / 1.0e6);
3533 if (ut + st != 0)
3535 if (report_times)
3536 fnotice (stderr, "# %s %.2f %.2f\n",
3537 commands[i].prog, ut, st);
3539 if (report_times_to_file)
3541 int c = 0;
3542 const char *const *j;
3544 fprintf (report_times_to_file, "%g %g", ut, st);
3546 for (j = &commands[i].prog; *j; j = &commands[i].argv[++c])
3548 const char *p;
3549 for (p = *j; *p; ++p)
3550 if (*p == '"' || *p == '\\' || *p == '$'
3551 || ISSPACE (*p))
3552 break;
3554 if (*p)
3556 fprintf (report_times_to_file, " \"");
3557 for (p = *j; *p; ++p)
3559 if (*p == '"' || *p == '\\' || *p == '$')
3560 fputc ('\\', report_times_to_file);
3561 fputc (*p, report_times_to_file);
3563 fputc ('"', report_times_to_file);
3565 else
3566 fprintf (report_times_to_file, " %s", *j);
3569 fputc ('\n', report_times_to_file);
3575 if (commands[0].argv[0] != commands[0].prog)
3576 free (CONST_CAST (char *, commands[0].argv[0]));
3578 return ret_code;
3582 static struct switchstr *switches;
3584 static int n_switches;
3586 static int n_switches_alloc;
3588 /* Set to zero if -fcompare-debug is disabled, positive if it's
3589 enabled and we're running the first compilation, negative if it's
3590 enabled and we're running the second compilation. For most of the
3591 time, it's in the range -1..1, but it can be temporarily set to 2
3592 or 3 to indicate that the -fcompare-debug flags didn't come from
3593 the command-line, but rather from the GCC_COMPARE_DEBUG environment
3594 variable, until a synthesized -fcompare-debug flag is added to the
3595 command line. */
3596 int compare_debug;
3598 /* Set to nonzero if we've seen the -fcompare-debug-second flag. */
3599 int compare_debug_second;
3601 /* Set to the flags that should be passed to the second compilation in
3602 a -fcompare-debug compilation. */
3603 const char *compare_debug_opt;
3605 static struct switchstr *switches_debug_check[2];
3607 static int n_switches_debug_check[2];
3609 static int n_switches_alloc_debug_check[2];
3611 static char *debug_check_temp_file[2];
3613 /* Language is one of three things:
3615 1) The name of a real programming language.
3616 2) NULL, indicating that no one has figured out
3617 what it is yet.
3618 3) '*', indicating that the file should be passed
3619 to the linker. */
3620 struct infile
3622 const char *name;
3623 const char *language;
3624 struct compiler *incompiler;
3625 bool compiled;
3626 bool preprocessed;
3629 /* Also a vector of input files specified. */
3631 static struct infile *infiles;
3633 int n_infiles;
3635 static int n_infiles_alloc;
3637 /* True if undefined environment variables encountered during spec processing
3638 are ok to ignore, typically when we're running for --help or --version. */
3640 static bool spec_undefvar_allowed;
3642 /* True if multiple input files are being compiled to a single
3643 assembly file. */
3645 static bool combine_inputs;
3647 /* This counts the number of libraries added by lang_specific_driver, so that
3648 we can tell if there were any user supplied any files or libraries. */
3650 static int added_libraries;
3652 /* And a vector of corresponding output files is made up later. */
3654 const char **outfiles;
3656 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3658 /* Convert NAME to a new name if it is the standard suffix. DO_EXE
3659 is true if we should look for an executable suffix. DO_OBJ
3660 is true if we should look for an object suffix. */
3662 static const char *
3663 convert_filename (const char *name, int do_exe ATTRIBUTE_UNUSED,
3664 int do_obj ATTRIBUTE_UNUSED)
3666 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3667 int i;
3668 #endif
3669 int len;
3671 if (name == NULL)
3672 return NULL;
3674 len = strlen (name);
3676 #ifdef HAVE_TARGET_OBJECT_SUFFIX
3677 /* Convert x.o to x.obj if TARGET_OBJECT_SUFFIX is ".obj". */
3678 if (do_obj && len > 2
3679 && name[len - 2] == '.'
3680 && name[len - 1] == 'o')
3682 obstack_grow (&obstack, name, len - 2);
3683 obstack_grow0 (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
3684 name = XOBFINISH (&obstack, const char *);
3686 #endif
3688 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3689 /* If there is no filetype, make it the executable suffix (which includes
3690 the "."). But don't get confused if we have just "-o". */
3691 if (! do_exe || TARGET_EXECUTABLE_SUFFIX[0] == 0 || not_actual_file_p (name))
3692 return name;
3694 for (i = len - 1; i >= 0; i--)
3695 if (IS_DIR_SEPARATOR (name[i]))
3696 break;
3698 for (i++; i < len; i++)
3699 if (name[i] == '.')
3700 return name;
3702 obstack_grow (&obstack, name, len);
3703 obstack_grow0 (&obstack, TARGET_EXECUTABLE_SUFFIX,
3704 strlen (TARGET_EXECUTABLE_SUFFIX));
3705 name = XOBFINISH (&obstack, const char *);
3706 #endif
3708 return name;
3710 #endif
3712 /* Display the command line switches accepted by gcc. */
3713 static void
3714 display_help (void)
3716 printf (_("Usage: %s [options] file...\n"), progname);
3717 fputs (_("Options:\n"), stdout);
3719 fputs (_(" -pass-exit-codes Exit with highest error code from a phase.\n"), stdout);
3720 fputs (_(" --help Display this information.\n"), stdout);
3721 fputs (_(" --target-help Display target specific command line options "
3722 "(including assembler and linker options).\n"), stdout);
3723 fputs (_(" --help={common|optimizers|params|target|warnings|[^]{joined|separate|undocumented}}[,...].\n"), stdout);
3724 fputs (_(" Display specific types of command line options.\n"), stdout);
3725 if (! verbose_flag)
3726 fputs (_(" (Use '-v --help' to display command line options of sub-processes).\n"), stdout);
3727 fputs (_(" --version Display compiler version information.\n"), stdout);
3728 fputs (_(" -dumpspecs Display all of the built in spec strings.\n"), stdout);
3729 fputs (_(" -dumpversion Display the version of the compiler.\n"), stdout);
3730 fputs (_(" -dumpmachine Display the compiler's target processor.\n"), stdout);
3731 fputs (_(" -foffload=<targets> Specify offloading targets.\n"), stdout);
3732 fputs (_(" -print-search-dirs Display the directories in the compiler's search path.\n"), stdout);
3733 fputs (_(" -print-libgcc-file-name Display the name of the compiler's companion library.\n"), stdout);
3734 fputs (_(" -print-file-name=<lib> Display the full path to library <lib>.\n"), stdout);
3735 fputs (_(" -print-prog-name=<prog> Display the full path to compiler component <prog>.\n"), stdout);
3736 fputs (_("\
3737 -print-multiarch Display the target's normalized GNU triplet, used as\n\
3738 a component in the library path.\n"), stdout);
3739 fputs (_(" -print-multi-directory Display the root directory for versions of libgcc.\n"), stdout);
3740 fputs (_("\
3741 -print-multi-lib Display the mapping between command line options and\n\
3742 multiple library search directories.\n"), stdout);
3743 fputs (_(" -print-multi-os-directory Display the relative path to OS libraries.\n"), stdout);
3744 fputs (_(" -print-sysroot Display the target libraries directory.\n"), stdout);
3745 fputs (_(" -print-sysroot-headers-suffix Display the sysroot suffix used to find headers.\n"), stdout);
3746 fputs (_(" -Wa,<options> Pass comma-separated <options> on to the assembler.\n"), stdout);
3747 fputs (_(" -Wp,<options> Pass comma-separated <options> on to the preprocessor.\n"), stdout);
3748 fputs (_(" -Wl,<options> Pass comma-separated <options> on to the linker.\n"), stdout);
3749 fputs (_(" -Xassembler <arg> Pass <arg> on to the assembler.\n"), stdout);
3750 fputs (_(" -Xpreprocessor <arg> Pass <arg> on to the preprocessor.\n"), stdout);
3751 fputs (_(" -Xlinker <arg> Pass <arg> on to the linker.\n"), stdout);
3752 fputs (_(" -save-temps Do not delete intermediate files.\n"), stdout);
3753 fputs (_(" -save-temps=<arg> Do not delete intermediate files.\n"), stdout);
3754 fputs (_("\
3755 -no-canonical-prefixes Do not canonicalize paths when building relative\n\
3756 prefixes to other gcc components.\n"), stdout);
3757 fputs (_(" -pipe Use pipes rather than intermediate files.\n"), stdout);
3758 fputs (_(" -time Time the execution of each subprocess.\n"), stdout);
3759 fputs (_(" -specs=<file> Override built-in specs with the contents of <file>.\n"), stdout);
3760 fputs (_(" -std=<standard> Assume that the input sources are for <standard>.\n"), stdout);
3761 fputs (_("\
3762 --sysroot=<directory> Use <directory> as the root directory for headers\n\
3763 and libraries.\n"), stdout);
3764 fputs (_(" -B <directory> Add <directory> to the compiler's search paths.\n"), stdout);
3765 fputs (_(" -v Display the programs invoked by the compiler.\n"), stdout);
3766 fputs (_(" -### Like -v but options quoted and commands not executed.\n"), stdout);
3767 fputs (_(" -E Preprocess only; do not compile, assemble or link.\n"), stdout);
3768 fputs (_(" -S Compile only; do not assemble or link.\n"), stdout);
3769 fputs (_(" -c Compile and assemble, but do not link.\n"), stdout);
3770 fputs (_(" -o <file> Place the output into <file>.\n"), stdout);
3771 fputs (_(" -pie Create a dynamically linked position independent\n\
3772 executable.\n"), stdout);
3773 fputs (_(" -shared Create a shared library.\n"), stdout);
3774 fputs (_("\
3775 -x <language> Specify the language of the following input files.\n\
3776 Permissible languages include: c c++ assembler none\n\
3777 'none' means revert to the default behavior of\n\
3778 guessing the language based on the file's extension.\n\
3779 "), stdout);
3781 printf (_("\
3782 \nOptions starting with -g, -f, -m, -O, -W, or --param are automatically\n\
3783 passed on to the various sub-processes invoked by %s. In order to pass\n\
3784 other options on to these processes the -W<letter> options must be used.\n\
3785 "), progname);
3787 /* The rest of the options are displayed by invocations of the various
3788 sub-processes. */
3791 static void
3792 add_preprocessor_option (const char *option, int len)
3794 preprocessor_options.safe_push (save_string (option, len));
3797 static void
3798 add_assembler_option (const char *option, int len)
3800 assembler_options.safe_push (save_string (option, len));
3803 static void
3804 add_linker_option (const char *option, int len)
3806 linker_options.safe_push (save_string (option, len));
3809 /* Allocate space for an input file in infiles. */
3811 static void
3812 alloc_infile (void)
3814 if (n_infiles_alloc == 0)
3816 n_infiles_alloc = 16;
3817 infiles = XNEWVEC (struct infile, n_infiles_alloc);
3819 else if (n_infiles_alloc == n_infiles)
3821 n_infiles_alloc *= 2;
3822 infiles = XRESIZEVEC (struct infile, infiles, n_infiles_alloc);
3826 /* Store an input file with the given NAME and LANGUAGE in
3827 infiles. */
3829 static void
3830 add_infile (const char *name, const char *language)
3832 alloc_infile ();
3833 infiles[n_infiles].name = name;
3834 infiles[n_infiles++].language = language;
3837 /* Allocate space for a switch in switches. */
3839 static void
3840 alloc_switch (void)
3842 if (n_switches_alloc == 0)
3844 n_switches_alloc = 16;
3845 switches = XNEWVEC (struct switchstr, n_switches_alloc);
3847 else if (n_switches_alloc == n_switches)
3849 n_switches_alloc *= 2;
3850 switches = XRESIZEVEC (struct switchstr, switches, n_switches_alloc);
3854 /* Save an option OPT with N_ARGS arguments in array ARGS, marking it
3855 as validated if VALIDATED and KNOWN if it is an internal switch. */
3857 static void
3858 save_switch (const char *opt, size_t n_args, const char *const *args,
3859 bool validated, bool known)
3861 alloc_switch ();
3862 switches[n_switches].part1 = opt + 1;
3863 if (n_args == 0)
3864 switches[n_switches].args = 0;
3865 else
3867 switches[n_switches].args = XNEWVEC (const char *, n_args + 1);
3868 memcpy (switches[n_switches].args, args, n_args * sizeof (const char *));
3869 switches[n_switches].args[n_args] = NULL;
3872 switches[n_switches].live_cond = 0;
3873 switches[n_switches].validated = validated;
3874 switches[n_switches].known = known;
3875 switches[n_switches].ordering = 0;
3876 n_switches++;
3879 /* Set the SOURCE_DATE_EPOCH environment variable to the current time if it is
3880 not set already. */
3882 static void
3883 set_source_date_epoch_envvar ()
3885 /* Array size is 21 = ceil(log_10(2^64)) + 1 to hold string representations
3886 of 64 bit integers. */
3887 char source_date_epoch[21];
3888 time_t tt;
3890 errno = 0;
3891 tt = time (NULL);
3892 if (tt < (time_t) 0 || errno != 0)
3893 tt = (time_t) 0;
3895 snprintf (source_date_epoch, 21, "%llu", (unsigned long long) tt);
3896 /* Using setenv instead of xputenv because we want the variable to remain
3897 after finalizing so that it's still set in the second run when using
3898 -fcompare-debug. */
3899 setenv ("SOURCE_DATE_EPOCH", source_date_epoch, 0);
3902 /* Handle an option DECODED that is unknown to the option-processing
3903 machinery. */
3905 static bool
3906 driver_unknown_option_callback (const struct cl_decoded_option *decoded)
3908 const char *opt = decoded->arg;
3909 if (opt[1] == 'W' && opt[2] == 'n' && opt[3] == 'o' && opt[4] == '-'
3910 && !(decoded->errors & CL_ERR_NEGATIVE))
3912 /* Leave unknown -Wno-* options for the compiler proper, to be
3913 diagnosed only if there are warnings. */
3914 save_switch (decoded->canonical_option[0],
3915 decoded->canonical_option_num_elements - 1,
3916 &decoded->canonical_option[1], false, true);
3917 return false;
3919 if (decoded->opt_index == OPT_SPECIAL_unknown)
3921 /* Give it a chance to define it a spec file. */
3922 save_switch (decoded->canonical_option[0],
3923 decoded->canonical_option_num_elements - 1,
3924 &decoded->canonical_option[1], false, false);
3925 return false;
3927 else
3928 return true;
3931 /* Handle an option DECODED that is not marked as CL_DRIVER.
3932 LANG_MASK will always be CL_DRIVER. */
3934 static void
3935 driver_wrong_lang_callback (const struct cl_decoded_option *decoded,
3936 unsigned int lang_mask ATTRIBUTE_UNUSED)
3938 /* At this point, non-driver options are accepted (and expected to
3939 be passed down by specs) unless marked to be rejected by the
3940 driver. Options to be rejected by the driver but accepted by the
3941 compilers proper are treated just like completely unknown
3942 options. */
3943 const struct cl_option *option = &cl_options[decoded->opt_index];
3945 if (option->cl_reject_driver)
3946 error ("unrecognized command-line option %qs",
3947 decoded->orig_option_with_args_text);
3948 else
3949 save_switch (decoded->canonical_option[0],
3950 decoded->canonical_option_num_elements - 1,
3951 &decoded->canonical_option[1], false, true);
3954 static const char *spec_lang = 0;
3955 static int last_language_n_infiles;
3958 /* Check that GCC is configured to support the offload target. */
3960 static bool
3961 check_offload_target_name (const char *target, ptrdiff_t len)
3963 const char *n, *c = OFFLOAD_TARGETS;
3964 while (c)
3966 n = strchr (c, ',');
3967 if (n == NULL)
3968 n = strchr (c, '\0');
3969 if (len == n - c && strncmp (target, c, n - c) == 0)
3970 break;
3971 c = *n ? n + 1 : NULL;
3973 if (!c)
3975 auto_vec<const char*> candidates;
3976 size_t olen = strlen (OFFLOAD_TARGETS) + 1;
3977 char *cand = XALLOCAVEC (char, olen);
3978 memcpy (cand, OFFLOAD_TARGETS, olen);
3979 for (c = strtok (cand, ","); c; c = strtok (NULL, ","))
3980 candidates.safe_push (c);
3981 candidates.safe_push ("default");
3982 candidates.safe_push ("disable");
3984 char *target2 = XALLOCAVEC (char, len + 1);
3985 memcpy (target2, target, len);
3986 target2[len] = '\0';
3988 error ("GCC is not configured to support %qs as %<-foffload=%> argument",
3989 target2);
3991 char *s;
3992 const char *hint = candidates_list_and_hint (target2, s, candidates);
3993 if (hint)
3994 inform (UNKNOWN_LOCATION,
3995 "valid %<-foffload=%> arguments are: %s; "
3996 "did you mean %qs?", s, hint);
3997 else
3998 inform (UNKNOWN_LOCATION, "valid %<-foffload=%> arguments are: %s", s);
3999 XDELETEVEC (s);
4000 return false;
4002 return true;
4005 /* Sanity check for -foffload-options. */
4007 static void
4008 check_foffload_target_names (const char *arg)
4010 const char *cur, *next, *end;
4011 /* If option argument starts with '-' then no target is specified and we
4012 do not need to parse it. */
4013 if (arg[0] == '-')
4014 return;
4015 end = strchr (arg, '=');
4016 if (end == NULL)
4018 error ("%<=%>options missing after %<-foffload-options=%>target");
4019 return;
4022 cur = arg;
4023 while (cur < end)
4025 next = strchr (cur, ',');
4026 if (next == NULL)
4027 next = end;
4028 next = (next > end) ? end : next;
4030 /* Retain non-supported targets after printing an error as those will not
4031 be processed; each enabled target only processes its triplet. */
4032 check_offload_target_name (cur, next - cur);
4033 cur = next + 1;
4037 /* Parse -foffload option argument. */
4039 static void
4040 handle_foffload_option (const char *arg)
4042 const char *c, *cur, *n, *next, *end;
4043 char *target;
4045 /* If option argument starts with '-' then no target is specified and we
4046 do not need to parse it. */
4047 if (arg[0] == '-')
4048 return;
4050 end = strchr (arg, '=');
4051 if (end == NULL)
4052 end = strchr (arg, '\0');
4053 cur = arg;
4055 while (cur < end)
4057 next = strchr (cur, ',');
4058 if (next == NULL)
4059 next = end;
4060 next = (next > end) ? end : next;
4062 target = XNEWVEC (char, next - cur + 1);
4063 memcpy (target, cur, next - cur);
4064 target[next - cur] = '\0';
4066 /* Reset offloading list and continue. */
4067 if (strcmp (target, "default") == 0)
4069 free (offload_targets);
4070 offload_targets = NULL;
4071 goto next_item;
4074 /* If 'disable' is passed to the option, clean the list of
4075 offload targets and return, even if more targets follow.
4076 Likewise if GCC is not configured to support that offload target. */
4077 if (strcmp (target, "disable") == 0
4078 || !check_offload_target_name (target, next - cur))
4080 free (offload_targets);
4081 offload_targets = xstrdup ("");
4082 return;
4085 if (!offload_targets)
4087 offload_targets = target;
4088 target = NULL;
4090 else
4092 /* Check that the target hasn't already presented in the list. */
4093 c = offload_targets;
4096 n = strchr (c, ':');
4097 if (n == NULL)
4098 n = strchr (c, '\0');
4100 if (next - cur == n - c && strncmp (c, target, n - c) == 0)
4101 break;
4103 c = n + 1;
4105 while (*n);
4107 /* If duplicate is not found, append the target to the list. */
4108 if (c > n)
4110 size_t offload_targets_len = strlen (offload_targets);
4111 offload_targets
4112 = XRESIZEVEC (char, offload_targets,
4113 offload_targets_len + 1 + next - cur + 1);
4114 offload_targets[offload_targets_len++] = ':';
4115 memcpy (offload_targets + offload_targets_len, target, next - cur + 1);
4118 next_item:
4119 cur = next + 1;
4120 XDELETEVEC (target);
4124 /* Forward certain options to offloading compilation. */
4126 static void
4127 forward_offload_option (size_t opt_index, const char *arg, bool validated)
4129 switch (opt_index)
4131 case OPT_l:
4132 /* Use a '_GCC_' prefix and standard name ('-l_GCC_m' irrespective of the
4133 host's 'MATH_LIBRARY', for example), so that the 'mkoffload's can tell
4134 this has been synthesized here, and translate/drop as necessary. */
4135 /* Note that certain libraries ('-lc', '-lgcc', '-lgomp', for example)
4136 are injected by default in offloading compilation, and therefore not
4137 forwarded here. */
4138 /* GCC libraries. */
4139 if (/* '-lgfortran' */ strcmp (arg, "gfortran") == 0 )
4140 save_switch (concat ("-foffload-options=-l_GCC_", arg, NULL),
4141 0, NULL, validated, true);
4142 /* Other libraries. */
4143 else
4145 /* The case will need special consideration where on the host
4146 '!need_math', but for offloading compilation still need
4147 '-foffload-options=-l_GCC_m'. The problem is that we don't get
4148 here anything like '-lm', because it's not synthesized in
4149 'gcc/fortran/gfortranspec.cc:lang_specific_driver', for example.
4150 Generally synthesizing '-foffload-options=-l_GCC_m' etc. in the
4151 language specific drivers is non-trivial, needs very careful
4152 review of their options handling. However, this issue is not
4153 actually relevant for the current set of supported host/offloading
4154 configurations. */
4155 int need_math = (MATH_LIBRARY[0] != '\0');
4156 if (/* '-lm' */ (need_math && strcmp (arg, MATH_LIBRARY) == 0))
4157 save_switch ("-foffload-options=-l_GCC_m",
4158 0, NULL, validated, true);
4160 break;
4161 default:
4162 gcc_unreachable ();
4166 /* Handle a driver option; arguments and return value as for
4167 handle_option. */
4169 static bool
4170 driver_handle_option (struct gcc_options *opts,
4171 struct gcc_options *opts_set,
4172 const struct cl_decoded_option *decoded,
4173 unsigned int lang_mask ATTRIBUTE_UNUSED, int kind,
4174 location_t loc,
4175 const struct cl_option_handlers *handlers ATTRIBUTE_UNUSED,
4176 diagnostic_context *dc,
4177 void (*) (void))
4179 size_t opt_index = decoded->opt_index;
4180 const char *arg = decoded->arg;
4181 const char *compare_debug_replacement_opt;
4182 int value = decoded->value;
4183 bool validated = false;
4184 bool do_save = true;
4186 gcc_assert (opts == &global_options);
4187 gcc_assert (opts_set == &global_options_set);
4188 gcc_assert (kind == DK_UNSPECIFIED);
4189 gcc_assert (loc == UNKNOWN_LOCATION);
4190 gcc_assert (dc == global_dc);
4192 switch (opt_index)
4194 case OPT_dumpspecs:
4196 struct spec_list *sl;
4197 init_spec ();
4198 for (sl = specs; sl; sl = sl->next)
4199 printf ("*%s:\n%s\n\n", sl->name, *(sl->ptr_spec));
4200 if (link_command_spec)
4201 printf ("*link_command:\n%s\n\n", link_command_spec);
4202 exit (0);
4205 case OPT_dumpversion:
4206 printf ("%s\n", spec_version);
4207 exit (0);
4209 case OPT_dumpmachine:
4210 printf ("%s\n", spec_machine);
4211 exit (0);
4213 case OPT_dumpfullversion:
4214 printf ("%s\n", BASEVER);
4215 exit (0);
4217 case OPT__version:
4218 print_version = 1;
4220 /* CPP driver cannot obtain switch from cc1_options. */
4221 if (is_cpp_driver)
4222 add_preprocessor_option ("--version", strlen ("--version"));
4223 add_assembler_option ("--version", strlen ("--version"));
4224 add_linker_option ("--version", strlen ("--version"));
4225 break;
4227 case OPT__completion_:
4228 validated = true;
4229 completion = decoded->arg;
4230 break;
4232 case OPT__help:
4233 print_help_list = 1;
4235 /* CPP driver cannot obtain switch from cc1_options. */
4236 if (is_cpp_driver)
4237 add_preprocessor_option ("--help", 6);
4238 add_assembler_option ("--help", 6);
4239 add_linker_option ("--help", 6);
4240 break;
4242 case OPT__help_:
4243 print_subprocess_help = 2;
4244 break;
4246 case OPT__target_help:
4247 print_subprocess_help = 1;
4249 /* CPP driver cannot obtain switch from cc1_options. */
4250 if (is_cpp_driver)
4251 add_preprocessor_option ("--target-help", 13);
4252 add_assembler_option ("--target-help", 13);
4253 add_linker_option ("--target-help", 13);
4254 break;
4256 case OPT__no_sysroot_suffix:
4257 case OPT_pass_exit_codes:
4258 case OPT_print_search_dirs:
4259 case OPT_print_file_name_:
4260 case OPT_print_prog_name_:
4261 case OPT_print_multi_lib:
4262 case OPT_print_multi_directory:
4263 case OPT_print_sysroot:
4264 case OPT_print_multi_os_directory:
4265 case OPT_print_multiarch:
4266 case OPT_print_sysroot_headers_suffix:
4267 case OPT_time:
4268 case OPT_wrapper:
4269 /* These options set the variables specified in common.opt
4270 automatically, and do not need to be saved for spec
4271 processing. */
4272 do_save = false;
4273 break;
4275 case OPT_print_libgcc_file_name:
4276 print_file_name = "libgcc.a";
4277 do_save = false;
4278 break;
4280 case OPT_fuse_ld_bfd:
4281 use_ld = ".bfd";
4282 break;
4284 case OPT_fuse_ld_gold:
4285 use_ld = ".gold";
4286 break;
4288 case OPT_fuse_ld_mold:
4289 use_ld = ".mold";
4290 break;
4292 case OPT_fcompare_debug_second:
4293 compare_debug_second = 1;
4294 break;
4296 case OPT_fcompare_debug:
4297 switch (value)
4299 case 0:
4300 compare_debug_replacement_opt = "-fcompare-debug=";
4301 arg = "";
4302 goto compare_debug_with_arg;
4304 case 1:
4305 compare_debug_replacement_opt = "-fcompare-debug=-gtoggle";
4306 arg = "-gtoggle";
4307 goto compare_debug_with_arg;
4309 default:
4310 gcc_unreachable ();
4312 break;
4314 case OPT_fcompare_debug_:
4315 compare_debug_replacement_opt = decoded->canonical_option[0];
4316 compare_debug_with_arg:
4317 gcc_assert (decoded->canonical_option_num_elements == 1);
4318 gcc_assert (arg != NULL);
4319 if (*arg)
4320 compare_debug = 1;
4321 else
4322 compare_debug = -1;
4323 if (compare_debug < 0)
4324 compare_debug_opt = NULL;
4325 else
4326 compare_debug_opt = arg;
4327 save_switch (compare_debug_replacement_opt, 0, NULL, validated, true);
4328 set_source_date_epoch_envvar ();
4329 return true;
4331 case OPT_fdiagnostics_color_:
4332 diagnostic_color_init (dc, value);
4333 break;
4335 case OPT_fdiagnostics_urls_:
4336 diagnostic_urls_init (dc, value);
4337 break;
4339 case OPT_fdiagnostics_format_:
4341 const char *basename = (opts->x_dump_base_name ? opts->x_dump_base_name
4342 : opts->x_main_input_basename);
4343 diagnostic_output_format_init (dc, basename,
4344 (enum diagnostics_output_format)value);
4345 break;
4348 case OPT_fdiagnostics_text_art_charset_:
4349 diagnostics_text_art_charset_init (dc,
4350 (enum diagnostic_text_art_charset)value);
4351 break;
4353 case OPT_Wa_:
4355 int prev, j;
4356 /* Pass the rest of this option to the assembler. */
4358 /* Split the argument at commas. */
4359 prev = 0;
4360 for (j = 0; arg[j]; j++)
4361 if (arg[j] == ',')
4363 add_assembler_option (arg + prev, j - prev);
4364 prev = j + 1;
4367 /* Record the part after the last comma. */
4368 add_assembler_option (arg + prev, j - prev);
4370 do_save = false;
4371 break;
4373 case OPT_Wp_:
4375 int prev, j;
4376 /* Pass the rest of this option to the preprocessor. */
4378 /* Split the argument at commas. */
4379 prev = 0;
4380 for (j = 0; arg[j]; j++)
4381 if (arg[j] == ',')
4383 add_preprocessor_option (arg + prev, j - prev);
4384 prev = j + 1;
4387 /* Record the part after the last comma. */
4388 add_preprocessor_option (arg + prev, j - prev);
4390 do_save = false;
4391 break;
4393 case OPT_Wl_:
4395 int prev, j;
4396 /* Split the argument at commas. */
4397 prev = 0;
4398 for (j = 0; arg[j]; j++)
4399 if (arg[j] == ',')
4401 add_infile (save_string (arg + prev, j - prev), "*");
4402 prev = j + 1;
4404 /* Record the part after the last comma. */
4405 add_infile (arg + prev, "*");
4407 do_save = false;
4408 break;
4410 case OPT_Xlinker:
4411 add_infile (arg, "*");
4412 do_save = false;
4413 break;
4415 case OPT_Xpreprocessor:
4416 add_preprocessor_option (arg, strlen (arg));
4417 do_save = false;
4418 break;
4420 case OPT_Xassembler:
4421 add_assembler_option (arg, strlen (arg));
4422 do_save = false;
4423 break;
4425 case OPT_l:
4426 /* POSIX allows separation of -l and the lib arg; canonicalize
4427 by concatenating -l with its arg */
4428 add_infile (concat ("-l", arg, NULL), "*");
4430 /* Forward to offloading compilation '-l[...]' flags for standard,
4431 well-known libraries. */
4432 /* Doing this processing here means that we don't get to see libraries
4433 injected via specs, such as '-lquadmath' injected via
4434 '[build]/[target]/libgfortran/libgfortran.spec'. However, this issue
4435 is not actually relevant for the current set of host/offloading
4436 configurations. */
4437 if (ENABLE_OFFLOADING)
4438 forward_offload_option (opt_index, arg, validated);
4440 do_save = false;
4441 break;
4443 case OPT_L:
4444 /* Similarly, canonicalize -L for linkers that may not accept
4445 separate arguments. */
4446 save_switch (concat ("-L", arg, NULL), 0, NULL, validated, true);
4447 return true;
4449 case OPT_F:
4450 /* Likewise -F. */
4451 save_switch (concat ("-F", arg, NULL), 0, NULL, validated, true);
4452 return true;
4454 case OPT_save_temps:
4455 if (!save_temps_flag)
4456 save_temps_flag = SAVE_TEMPS_DUMP;
4457 validated = true;
4458 break;
4460 case OPT_save_temps_:
4461 if (strcmp (arg, "cwd") == 0)
4462 save_temps_flag = SAVE_TEMPS_CWD;
4463 else if (strcmp (arg, "obj") == 0
4464 || strcmp (arg, "object") == 0)
4465 save_temps_flag = SAVE_TEMPS_OBJ;
4466 else
4467 fatal_error (input_location, "%qs is an unknown %<-save-temps%> option",
4468 decoded->orig_option_with_args_text);
4469 save_temps_overrides_dumpdir = true;
4470 break;
4472 case OPT_dumpdir:
4473 free (dumpdir);
4474 dumpdir = xstrdup (arg);
4475 save_temps_overrides_dumpdir = false;
4476 break;
4478 case OPT_dumpbase:
4479 free (dumpbase);
4480 dumpbase = xstrdup (arg);
4481 break;
4483 case OPT_dumpbase_ext:
4484 free (dumpbase_ext);
4485 dumpbase_ext = xstrdup (arg);
4486 break;
4488 case OPT_no_canonical_prefixes:
4489 /* Already handled as a special case, so ignored here. */
4490 do_save = false;
4491 break;
4493 case OPT_pipe:
4494 validated = true;
4495 /* These options set the variables specified in common.opt
4496 automatically, but do need to be saved for spec
4497 processing. */
4498 break;
4500 case OPT_specs_:
4502 struct user_specs *user = XNEW (struct user_specs);
4504 user->next = (struct user_specs *) 0;
4505 user->filename = arg;
4506 if (user_specs_tail)
4507 user_specs_tail->next = user;
4508 else
4509 user_specs_head = user;
4510 user_specs_tail = user;
4512 validated = true;
4513 break;
4515 case OPT__sysroot_:
4516 target_system_root = arg;
4517 target_system_root_changed = 1;
4518 /* Saving this option is useful to let self-specs decide to
4519 provide a default one. */
4520 do_save = true;
4521 validated = true;
4522 break;
4524 case OPT_time_:
4525 if (report_times_to_file)
4526 fclose (report_times_to_file);
4527 report_times_to_file = fopen (arg, "a");
4528 do_save = false;
4529 break;
4531 case OPT____:
4532 /* "-###"
4533 This is similar to -v except that there is no execution
4534 of the commands and the echoed arguments are quoted. It
4535 is intended for use in shell scripts to capture the
4536 driver-generated command line. */
4537 verbose_only_flag++;
4538 verbose_flag = 1;
4539 do_save = false;
4540 break;
4542 case OPT_B:
4544 size_t len = strlen (arg);
4546 /* Catch the case where the user has forgotten to append a
4547 directory separator to the path. Note, they may be using
4548 -B to add an executable name prefix, eg "i386-elf-", in
4549 order to distinguish between multiple installations of
4550 GCC in the same directory. Hence we must check to see
4551 if appending a directory separator actually makes a
4552 valid directory name. */
4553 if (!IS_DIR_SEPARATOR (arg[len - 1])
4554 && is_directory (arg, false))
4556 char *tmp = XNEWVEC (char, len + 2);
4557 strcpy (tmp, arg);
4558 tmp[len] = DIR_SEPARATOR;
4559 tmp[++len] = 0;
4560 arg = tmp;
4563 add_prefix (&exec_prefixes, arg, NULL,
4564 PREFIX_PRIORITY_B_OPT, 0, 0);
4565 add_prefix (&startfile_prefixes, arg, NULL,
4566 PREFIX_PRIORITY_B_OPT, 0, 0);
4567 add_prefix (&include_prefixes, arg, NULL,
4568 PREFIX_PRIORITY_B_OPT, 0, 0);
4570 validated = true;
4571 break;
4573 case OPT_E:
4574 have_E = true;
4575 break;
4577 case OPT_x:
4578 spec_lang = arg;
4579 if (!strcmp (spec_lang, "none"))
4580 /* Suppress the warning if -xnone comes after the last input
4581 file, because alternate command interfaces like g++ might
4582 find it useful to place -xnone after each input file. */
4583 spec_lang = 0;
4584 else
4585 last_language_n_infiles = n_infiles;
4586 do_save = false;
4587 break;
4589 case OPT_o:
4590 have_o = 1;
4591 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX) || defined(HAVE_TARGET_OBJECT_SUFFIX)
4592 arg = convert_filename (arg, ! have_c, 0);
4593 #endif
4594 output_file = arg;
4595 /* On some systems, ld cannot handle "-o" without a space. So
4596 split the option from its argument. */
4597 save_switch ("-o", 1, &arg, validated, true);
4598 return true;
4600 #ifdef ENABLE_DEFAULT_PIE
4601 case OPT_pie:
4602 /* -pie is turned on by default. */
4603 #endif
4605 case OPT_static_libgcc:
4606 case OPT_shared_libgcc:
4607 case OPT_static_libgfortran:
4608 case OPT_static_libquadmath:
4609 case OPT_static_libphobos:
4610 case OPT_static_libgm2:
4611 case OPT_static_libstdc__:
4612 /* These are always valid; gcc.cc itself understands the first two
4613 gfortranspec.cc understands -static-libgfortran,
4614 libgfortran.spec handles -static-libquadmath,
4615 d-spec.cc understands -static-libphobos,
4616 gm2spec.cc understands -static-libgm2,
4617 and g++spec.cc understands -static-libstdc++. */
4618 validated = true;
4619 break;
4621 case OPT_fwpa:
4622 flag_wpa = "";
4623 break;
4625 case OPT_foffload_options_:
4626 check_foffload_target_names (arg);
4627 break;
4629 case OPT_foffload_:
4630 handle_foffload_option (arg);
4631 if (arg[0] == '-' || NULL != strchr (arg, '='))
4632 save_switch (concat ("-foffload-options=", arg, NULL),
4633 0, NULL, validated, true);
4634 do_save = false;
4635 break;
4637 case OPT_gcodeview:
4638 add_infile ("--pdb=", "*");
4639 break;
4641 default:
4642 /* Various driver options need no special processing at this
4643 point, having been handled in a prescan above or being
4644 handled by specs. */
4645 break;
4648 if (do_save)
4649 save_switch (decoded->canonical_option[0],
4650 decoded->canonical_option_num_elements - 1,
4651 &decoded->canonical_option[1], validated, true);
4652 return true;
4655 /* Return true if F2 is F1 followed by a single suffix, i.e., by a
4656 period and additional characters other than a period. */
4658 static inline bool
4659 adds_single_suffix_p (const char *f2, const char *f1)
4661 size_t len = strlen (f1);
4663 return (strncmp (f1, f2, len) == 0
4664 && f2[len] == '.'
4665 && strchr (f2 + len + 1, '.') == NULL);
4668 /* Put the driver's standard set of option handlers in *HANDLERS. */
4670 static void
4671 set_option_handlers (struct cl_option_handlers *handlers)
4673 handlers->unknown_option_callback = driver_unknown_option_callback;
4674 handlers->wrong_lang_callback = driver_wrong_lang_callback;
4675 handlers->num_handlers = 3;
4676 handlers->handlers[0].handler = driver_handle_option;
4677 handlers->handlers[0].mask = CL_DRIVER;
4678 handlers->handlers[1].handler = common_handle_option;
4679 handlers->handlers[1].mask = CL_COMMON;
4680 handlers->handlers[2].handler = target_handle_option;
4681 handlers->handlers[2].mask = CL_TARGET;
4685 /* Return the index into infiles for the single non-library
4686 non-lto-wpa input file, -1 if there isn't any, or -2 if there is
4687 more than one. */
4688 static inline int
4689 single_input_file_index ()
4691 int ret = -1;
4693 for (int i = 0; i < n_infiles; i++)
4695 if (infiles[i].language
4696 && (infiles[i].language[0] == '*'
4697 || (flag_wpa
4698 && strcmp (infiles[i].language, "lto") == 0)))
4699 continue;
4701 if (ret != -1)
4702 return -2;
4704 ret = i;
4707 return ret;
4710 /* Create the vector `switches' and its contents.
4711 Store its length in `n_switches'. */
4713 static void
4714 process_command (unsigned int decoded_options_count,
4715 struct cl_decoded_option *decoded_options)
4717 const char *temp;
4718 char *temp1;
4719 char *tooldir_prefix, *tooldir_prefix2;
4720 char *(*get_relative_prefix) (const char *, const char *,
4721 const char *) = NULL;
4722 struct cl_option_handlers handlers;
4723 unsigned int j;
4725 gcc_exec_prefix = env.get ("GCC_EXEC_PREFIX");
4727 n_switches = 0;
4728 n_infiles = 0;
4729 added_libraries = 0;
4731 /* Figure compiler version from version string. */
4733 compiler_version = temp1 = xstrdup (version_string);
4735 for (; *temp1; ++temp1)
4737 if (*temp1 == ' ')
4739 *temp1 = '\0';
4740 break;
4744 /* Handle any -no-canonical-prefixes flag early, to assign the function
4745 that builds relative prefixes. This function creates default search
4746 paths that are needed later in normal option handling. */
4748 for (j = 1; j < decoded_options_count; j++)
4750 if (decoded_options[j].opt_index == OPT_no_canonical_prefixes)
4752 get_relative_prefix = make_relative_prefix_ignore_links;
4753 break;
4756 if (! get_relative_prefix)
4757 get_relative_prefix = make_relative_prefix;
4759 /* Set up the default search paths. If there is no GCC_EXEC_PREFIX,
4760 see if we can create it from the pathname specified in
4761 decoded_options[0].arg. */
4763 gcc_libexec_prefix = standard_libexec_prefix;
4764 #ifndef VMS
4765 /* FIXME: make_relative_prefix doesn't yet work for VMS. */
4766 if (!gcc_exec_prefix)
4768 gcc_exec_prefix = get_relative_prefix (decoded_options[0].arg,
4769 standard_bindir_prefix,
4770 standard_exec_prefix);
4771 gcc_libexec_prefix = get_relative_prefix (decoded_options[0].arg,
4772 standard_bindir_prefix,
4773 standard_libexec_prefix);
4774 if (gcc_exec_prefix)
4775 xputenv (concat ("GCC_EXEC_PREFIX=", gcc_exec_prefix, NULL));
4777 else
4779 /* make_relative_prefix requires a program name, but
4780 GCC_EXEC_PREFIX is typically a directory name with a trailing
4781 / (which is ignored by make_relative_prefix), so append a
4782 program name. */
4783 char *tmp_prefix = concat (gcc_exec_prefix, "gcc", NULL);
4784 gcc_libexec_prefix = get_relative_prefix (tmp_prefix,
4785 standard_exec_prefix,
4786 standard_libexec_prefix);
4788 /* The path is unrelocated, so fallback to the original setting. */
4789 if (!gcc_libexec_prefix)
4790 gcc_libexec_prefix = standard_libexec_prefix;
4792 free (tmp_prefix);
4794 #else
4795 #endif
4796 /* From this point onward, gcc_exec_prefix is non-null if the toolchain
4797 is relocated. The toolchain was either relocated using GCC_EXEC_PREFIX
4798 or an automatically created GCC_EXEC_PREFIX from
4799 decoded_options[0].arg. */
4801 /* Do language-specific adjustment/addition of flags. */
4802 lang_specific_driver (&decoded_options, &decoded_options_count,
4803 &added_libraries);
4805 if (gcc_exec_prefix)
4807 int len = strlen (gcc_exec_prefix);
4809 if (len > (int) sizeof ("/lib/gcc/") - 1
4810 && (IS_DIR_SEPARATOR (gcc_exec_prefix[len-1])))
4812 temp = gcc_exec_prefix + len - sizeof ("/lib/gcc/") + 1;
4813 if (IS_DIR_SEPARATOR (*temp)
4814 && filename_ncmp (temp + 1, "lib", 3) == 0
4815 && IS_DIR_SEPARATOR (temp[4])
4816 && filename_ncmp (temp + 5, "gcc", 3) == 0)
4817 len -= sizeof ("/lib/gcc/") - 1;
4820 set_std_prefix (gcc_exec_prefix, len);
4821 add_prefix (&exec_prefixes, gcc_libexec_prefix, "GCC",
4822 PREFIX_PRIORITY_LAST, 0, 0);
4823 add_prefix (&startfile_prefixes, gcc_exec_prefix, "GCC",
4824 PREFIX_PRIORITY_LAST, 0, 0);
4827 /* COMPILER_PATH and LIBRARY_PATH have values
4828 that are lists of directory names with colons. */
4830 temp = env.get ("COMPILER_PATH");
4831 if (temp)
4833 const char *startp, *endp;
4834 char *nstore = (char *) alloca (strlen (temp) + 3);
4836 startp = endp = temp;
4837 while (1)
4839 if (*endp == PATH_SEPARATOR || *endp == 0)
4841 strncpy (nstore, startp, endp - startp);
4842 if (endp == startp)
4843 strcpy (nstore, concat (".", dir_separator_str, NULL));
4844 else if (!IS_DIR_SEPARATOR (endp[-1]))
4846 nstore[endp - startp] = DIR_SEPARATOR;
4847 nstore[endp - startp + 1] = 0;
4849 else
4850 nstore[endp - startp] = 0;
4851 add_prefix (&exec_prefixes, nstore, 0,
4852 PREFIX_PRIORITY_LAST, 0, 0);
4853 add_prefix (&include_prefixes, nstore, 0,
4854 PREFIX_PRIORITY_LAST, 0, 0);
4855 if (*endp == 0)
4856 break;
4857 endp = startp = endp + 1;
4859 else
4860 endp++;
4864 temp = env.get (LIBRARY_PATH_ENV);
4865 if (temp && *cross_compile == '0')
4867 const char *startp, *endp;
4868 char *nstore = (char *) alloca (strlen (temp) + 3);
4870 startp = endp = temp;
4871 while (1)
4873 if (*endp == PATH_SEPARATOR || *endp == 0)
4875 strncpy (nstore, startp, endp - startp);
4876 if (endp == startp)
4877 strcpy (nstore, concat (".", dir_separator_str, NULL));
4878 else if (!IS_DIR_SEPARATOR (endp[-1]))
4880 nstore[endp - startp] = DIR_SEPARATOR;
4881 nstore[endp - startp + 1] = 0;
4883 else
4884 nstore[endp - startp] = 0;
4885 add_prefix (&startfile_prefixes, nstore, NULL,
4886 PREFIX_PRIORITY_LAST, 0, 1);
4887 if (*endp == 0)
4888 break;
4889 endp = startp = endp + 1;
4891 else
4892 endp++;
4896 /* Use LPATH like LIBRARY_PATH (for the CMU build program). */
4897 temp = env.get ("LPATH");
4898 if (temp && *cross_compile == '0')
4900 const char *startp, *endp;
4901 char *nstore = (char *) alloca (strlen (temp) + 3);
4903 startp = endp = temp;
4904 while (1)
4906 if (*endp == PATH_SEPARATOR || *endp == 0)
4908 strncpy (nstore, startp, endp - startp);
4909 if (endp == startp)
4910 strcpy (nstore, concat (".", dir_separator_str, NULL));
4911 else if (!IS_DIR_SEPARATOR (endp[-1]))
4913 nstore[endp - startp] = DIR_SEPARATOR;
4914 nstore[endp - startp + 1] = 0;
4916 else
4917 nstore[endp - startp] = 0;
4918 add_prefix (&startfile_prefixes, nstore, NULL,
4919 PREFIX_PRIORITY_LAST, 0, 1);
4920 if (*endp == 0)
4921 break;
4922 endp = startp = endp + 1;
4924 else
4925 endp++;
4929 /* Process the options and store input files and switches in their
4930 vectors. */
4932 last_language_n_infiles = -1;
4934 set_option_handlers (&handlers);
4936 for (j = 1; j < decoded_options_count; j++)
4938 switch (decoded_options[j].opt_index)
4940 case OPT_S:
4941 case OPT_c:
4942 case OPT_E:
4943 have_c = 1;
4944 break;
4946 if (have_c)
4947 break;
4950 for (j = 1; j < decoded_options_count; j++)
4952 if (decoded_options[j].opt_index == OPT_SPECIAL_input_file)
4954 const char *arg = decoded_options[j].arg;
4956 #ifdef HAVE_TARGET_OBJECT_SUFFIX
4957 arg = convert_filename (arg, 0, access (arg, F_OK));
4958 #endif
4959 add_infile (arg, spec_lang);
4961 continue;
4964 read_cmdline_option (&global_options, &global_options_set,
4965 decoded_options + j, UNKNOWN_LOCATION,
4966 CL_DRIVER, &handlers, global_dc);
4969 /* If the user didn't specify any, default to all configured offload
4970 targets. */
4971 if (ENABLE_OFFLOADING && offload_targets == NULL)
4973 handle_foffload_option (OFFLOAD_TARGETS);
4974 #if OFFLOAD_DEFAULTED
4975 offload_targets_default = true;
4976 #endif
4979 /* Handle -gtoggle as it would later in toplev.cc:process_options to
4980 make the debug-level-gt spec function work as expected. */
4981 if (flag_gtoggle)
4983 if (debug_info_level == DINFO_LEVEL_NONE)
4984 debug_info_level = DINFO_LEVEL_NORMAL;
4985 else
4986 debug_info_level = DINFO_LEVEL_NONE;
4989 if (output_file
4990 && strcmp (output_file, "-") != 0
4991 && strcmp (output_file, HOST_BIT_BUCKET) != 0)
4993 int i;
4994 for (i = 0; i < n_infiles; i++)
4995 if ((!infiles[i].language || infiles[i].language[0] != '*')
4996 && canonical_filename_eq (infiles[i].name, output_file))
4997 fatal_error (input_location,
4998 "input file %qs is the same as output file",
4999 output_file);
5002 if (output_file != NULL && output_file[0] == '\0')
5003 fatal_error (input_location, "output filename may not be empty");
5005 /* -dumpdir and -save-temps=* both specify the location of aux/dump
5006 outputs; the one that appears last prevails. When compiling
5007 multiple sources, an explicit dumpbase (minus -ext) may be
5008 combined with an explicit or implicit dumpdir, whereas when
5009 linking, a specified or implied link output name (minus
5010 extension) may be combined with a prevailing -save-temps=* or an
5011 otherwise implied dumpdir, but not override a prevailing
5012 -dumpdir. Primary outputs (e.g., linker output when linking
5013 without -o, or .i, .s or .o outputs when processing multiple
5014 inputs with -E, -S or -c, respectively) are NOT affected by these
5015 -save-temps=/-dump* options, always landing in the current
5016 directory and with the same basename as the input when an output
5017 name is not given, but when they're intermediate outputs, they
5018 are named like other aux outputs, so the options affect their
5019 location and name.
5021 Here are some examples. There are several more in the
5022 documentation of -o and -dump*, and some quite exhaustive tests
5023 in gcc.misc-tests/outputs.exp.
5025 When compiling any number of sources, no -dump* nor
5026 -save-temps=*, all outputs in cwd without prefix:
5028 # gcc -c b.c -gsplit-dwarf
5029 -> cc1 [-dumpdir ./] -dumpbase b.c -dumpbase-ext .c # b.o b.dwo
5031 # gcc -c b.c d.c -gsplit-dwarf
5032 -> cc1 [-dumpdir ./] -dumpbase b.c -dumpbase-ext .c # b.o b.dwo
5033 && cc1 [-dumpdir ./] -dumpbase d.c -dumpbase-ext .c # d.o d.dwo
5035 When compiling and linking, no -dump* nor -save-temps=*, .o
5036 outputs are temporary, aux outputs land in the dir of the output,
5037 prefixed with the basename of the linker output:
5039 # gcc b.c d.c -o ab -gsplit-dwarf
5040 -> cc1 -dumpdir ab- -dumpbase b.c -dumpbase-ext .c # ab-b.dwo
5041 && cc1 -dumpdir ab- -dumpbase d.c -dumpbase-ext .c # ab-d.dwo
5042 && link ... -o ab
5044 # gcc b.c d.c [-o a.out] -gsplit-dwarf
5045 -> cc1 -dumpdir a- -dumpbase b.c -dumpbase-ext .c # a-b.dwo
5046 && cc1 -dumpdir a- -dumpbase d.c -dumpbase-ext .c # a-d.dwo
5047 && link ... [-o a.out]
5049 When compiling and linking, a prevailing -dumpdir fully overrides
5050 the prefix of aux outputs given by the output name:
5052 # gcc -dumpdir f b.c d.c -gsplit-dwarf [-o [dir/]whatever]
5053 -> cc1 -dumpdir f -dumpbase b.c -dumpbase-ext .c # fb.dwo
5054 && cc1 -dumpdir f -dumpbase d.c -dumpbase-ext .c # fd.dwo
5055 && link ... [-o whatever]
5057 When compiling multiple inputs, an explicit -dumpbase is combined
5058 with -dumpdir, affecting aux outputs, but not the .o outputs:
5060 # gcc -dumpdir f -dumpbase g- b.c d.c -gsplit-dwarf -c
5061 -> cc1 -dumpdir fg- -dumpbase b.c -dumpbase-ext .c # b.o fg-b.dwo
5062 && cc1 -dumpdir fg- -dumpbase d.c -dumpbase-ext .c # d.o fg-d.dwo
5064 When compiling and linking with -save-temps, the .o outputs that
5065 would have been temporary become aux outputs, so they get
5066 affected by -dump* flags:
5068 # gcc -dumpdir f -dumpbase g- -save-temps b.c d.c
5069 -> cc1 -dumpdir fg- -dumpbase b.c -dumpbase-ext .c # fg-b.o
5070 && cc1 -dumpdir fg- -dumpbase d.c -dumpbase-ext .c # fg-d.o
5071 && link
5073 If -save-temps=* prevails over -dumpdir, however, the explicit
5074 -dumpdir is discarded, as if it wasn't there. The basename of
5075 the implicit linker output, a.out or a.exe, becomes a- as the aux
5076 output prefix for all compilations:
5078 # gcc [-dumpdir f] -save-temps=cwd b.c d.c
5079 -> cc1 -dumpdir a- -dumpbase b.c -dumpbase-ext .c # a-b.o
5080 && cc1 -dumpdir a- -dumpbase d.c -dumpbase-ext .c # a-d.o
5081 && link
5083 A single -dumpbase, applying to multiple inputs, overrides the
5084 linker output name, implied or explicit, as the aux output prefix:
5086 # gcc [-dumpdir f] -dumpbase g- -save-temps=cwd b.c d.c
5087 -> cc1 -dumpdir g- -dumpbase b.c -dumpbase-ext .c # g-b.o
5088 && cc1 -dumpdir g- -dumpbase d.c -dumpbase-ext .c # g-d.o
5089 && link
5091 # gcc [-dumpdir f] -dumpbase g- -save-temps=cwd b.c d.c -o dir/h.out
5092 -> cc1 -dumpdir g- -dumpbase b.c -dumpbase-ext .c # g-b.o
5093 && cc1 -dumpdir g- -dumpbase d.c -dumpbase-ext .c # g-d.o
5094 && link -o dir/h.out
5096 Now, if the linker output is NOT overridden as a prefix, but
5097 -save-temps=* overrides implicit or explicit -dumpdir, the
5098 effective dump dir combines the dir selected by the -save-temps=*
5099 option with the basename of the specified or implied link output:
5101 # gcc [-dumpdir f] -save-temps=cwd b.c d.c -o dir/h.out
5102 -> cc1 -dumpdir h- -dumpbase b.c -dumpbase-ext .c # h-b.o
5103 && cc1 -dumpdir h- -dumpbase d.c -dumpbase-ext .c # h-d.o
5104 && link -o dir/h.out
5106 # gcc [-dumpdir f] -save-temps=obj b.c d.c -o dir/h.out
5107 -> cc1 -dumpdir dir/h- -dumpbase b.c -dumpbase-ext .c # dir/h-b.o
5108 && cc1 -dumpdir dir/h- -dumpbase d.c -dumpbase-ext .c # dir/h-d.o
5109 && link -o dir/h.out
5111 But then again, a single -dumpbase applying to multiple inputs
5112 gets used instead of the linker output basename in the combined
5113 dumpdir:
5115 # gcc [-dumpdir f] -dumpbase g- -save-temps=obj b.c d.c -o dir/h.out
5116 -> cc1 -dumpdir dir/g- -dumpbase b.c -dumpbase-ext .c # dir/g-b.o
5117 && cc1 -dumpdir dir/g- -dumpbase d.c -dumpbase-ext .c # dir/g-d.o
5118 && link -o dir/h.out
5120 With a single input being compiled, the output basename does NOT
5121 affect the dumpdir prefix.
5123 # gcc -save-temps=obj b.c -gsplit-dwarf -c -o dir/b.o
5124 -> cc1 -dumpdir dir/ -dumpbase b.c -dumpbase-ext .c # dir/b.o dir/b.dwo
5126 but when compiling and linking even a single file, it does:
5128 # gcc -save-temps=obj b.c -o dir/h.out
5129 -> cc1 -dumpdir dir/h- -dumpbase b.c -dumpbase-ext .c # dir/h-b.o
5131 unless an explicit -dumpdir prevails:
5133 # gcc -save-temps[=obj] -dumpdir g- b.c -o dir/h.out
5134 -> cc1 -dumpdir g- -dumpbase b.c -dumpbase-ext .c # g-b.o
5138 bool explicit_dumpdir = dumpdir;
5140 if ((!save_temps_overrides_dumpdir && explicit_dumpdir)
5141 || (output_file && not_actual_file_p (output_file)))
5143 /* Do nothing. */
5146 /* If -save-temps=obj and -o name, create the prefix to use for %b.
5147 Otherwise just make -save-temps=obj the same as -save-temps=cwd. */
5148 else if (save_temps_flag != SAVE_TEMPS_CWD && output_file != NULL)
5150 free (dumpdir);
5151 dumpdir = NULL;
5152 temp = lbasename (output_file);
5153 if (temp != output_file)
5154 dumpdir = xstrndup (output_file,
5155 strlen (output_file) - strlen (temp));
5157 else if (dumpdir)
5159 free (dumpdir);
5160 dumpdir = NULL;
5163 if (save_temps_flag)
5164 save_temps_flag = SAVE_TEMPS_DUMP;
5166 /* If there is any pathname component in an explicit -dumpbase, it
5167 overrides dumpdir entirely, so discard it right away. Although
5168 the presence of an explicit -dumpdir matters for the driver, it
5169 shouldn't matter for other processes, that get all that's needed
5170 from the -dumpdir and -dumpbase always passed to them. */
5171 if (dumpdir && dumpbase && lbasename (dumpbase) != dumpbase)
5173 free (dumpdir);
5174 dumpdir = NULL;
5177 /* Check that dumpbase_ext matches the end of dumpbase, drop it
5178 otherwise. */
5179 if (dumpbase_ext && dumpbase && *dumpbase)
5181 int lendb = strlen (dumpbase);
5182 int lendbx = strlen (dumpbase_ext);
5184 /* -dumpbase-ext must be a suffix proper; discard it if it
5185 matches all of -dumpbase, as that would make for an empty
5186 basename. */
5187 if (lendbx >= lendb
5188 || strcmp (dumpbase + lendb - lendbx, dumpbase_ext) != 0)
5190 free (dumpbase_ext);
5191 dumpbase_ext = NULL;
5195 /* -dumpbase with multiple sources goes into dumpdir. With a single
5196 source, it does only if linking and if dumpdir was not explicitly
5197 specified. */
5198 if (dumpbase && *dumpbase
5199 && (single_input_file_index () == -2
5200 || (!have_c && !explicit_dumpdir)))
5202 char *prefix;
5204 if (dumpbase_ext)
5205 /* We checked that they match above. */
5206 dumpbase[strlen (dumpbase) - strlen (dumpbase_ext)] = '\0';
5208 if (dumpdir)
5209 prefix = concat (dumpdir, dumpbase, "-", NULL);
5210 else
5211 prefix = concat (dumpbase, "-", NULL);
5213 free (dumpdir);
5214 free (dumpbase);
5215 free (dumpbase_ext);
5216 dumpbase = dumpbase_ext = NULL;
5217 dumpdir = prefix;
5218 dumpdir_trailing_dash_added = true;
5221 /* If dumpbase was not brought into dumpdir but we're linking, bring
5222 output_file into dumpdir unless dumpdir was explicitly specified.
5223 The test for !explicit_dumpdir is further below, because we want
5224 to use the obase computation for a ghost outbase, passed to
5225 GCC_COLLECT_OPTIONS. */
5226 else if (!have_c && (!explicit_dumpdir || (dumpbase && !*dumpbase)))
5228 /* If we get here, we know dumpbase was not specified, or it was
5229 specified as an empty string. If it was anything else, it
5230 would have combined with dumpdir above, because the condition
5231 for dumpbase to be used when present is broader than the
5232 condition that gets us here. */
5233 gcc_assert (!dumpbase || !*dumpbase);
5235 const char *obase;
5236 char *tofree = NULL;
5237 if (!output_file || not_actual_file_p (output_file))
5238 obase = "a";
5239 else
5241 obase = lbasename (output_file);
5242 size_t blen = strlen (obase), xlen;
5243 /* Drop the suffix if it's dumpbase_ext, if given,
5244 otherwise .exe or the target executable suffix, or if the
5245 output was explicitly named a.out, but not otherwise. */
5246 if (dumpbase_ext
5247 ? (blen > (xlen = strlen (dumpbase_ext))
5248 && strcmp ((temp = (obase + blen - xlen)),
5249 dumpbase_ext) == 0)
5250 : ((temp = strrchr (obase + 1, '.'))
5251 && (xlen = strlen (temp))
5252 && (strcmp (temp, ".exe") == 0
5253 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
5254 || strcmp (temp, TARGET_EXECUTABLE_SUFFIX) == 0
5255 #endif
5256 || strcmp (obase, "a.out") == 0)))
5258 tofree = xstrndup (obase, blen - xlen);
5259 obase = tofree;
5263 /* We wish to save this basename to the -dumpdir passed through
5264 GCC_COLLECT_OPTIONS within maybe_run_linker, for e.g. LTO,
5265 but we do NOT wish to add it to e.g. %b, so we keep
5266 outbase_length as zero. */
5267 gcc_assert (!outbase);
5268 outbase_length = 0;
5270 /* If we're building [dir1/]foo[.exe] out of a single input
5271 [dir2/]foo.c that shares the same basename, dump to
5272 [dir2/]foo.c.* rather than duplicating the basename into
5273 [dir2/]foo-foo.c.*. */
5274 int idxin;
5275 if (dumpbase
5276 || ((idxin = single_input_file_index ()) >= 0
5277 && adds_single_suffix_p (lbasename (infiles[idxin].name),
5278 obase)))
5280 if (obase == tofree)
5281 outbase = tofree;
5282 else
5284 outbase = xstrdup (obase);
5285 free (tofree);
5287 obase = tofree = NULL;
5289 else
5291 if (dumpdir)
5293 char *p = concat (dumpdir, obase, "-", NULL);
5294 free (dumpdir);
5295 dumpdir = p;
5297 else
5298 dumpdir = concat (obase, "-", NULL);
5300 dumpdir_trailing_dash_added = true;
5302 free (tofree);
5303 obase = tofree = NULL;
5306 if (!explicit_dumpdir || dumpbase)
5308 /* Absent -dumpbase and present -dumpbase-ext have been applied
5309 to the linker output name, so compute fresh defaults for each
5310 compilation. */
5311 free (dumpbase_ext);
5312 dumpbase_ext = NULL;
5316 /* Now, if we're compiling, or if we haven't used the dumpbase
5317 above, then outbase (%B) is derived from dumpbase, if given, or
5318 from the output name, given or implied. We can't precompute
5319 implied output names, but that's ok, since they're derived from
5320 input names. Just make sure we skip this if dumpbase is the
5321 empty string: we want to use input names then, so don't set
5322 outbase. */
5323 if ((dumpbase || have_c)
5324 && !(dumpbase && !*dumpbase))
5326 gcc_assert (!outbase);
5328 if (dumpbase)
5330 gcc_assert (single_input_file_index () != -2);
5331 /* We do not want lbasename here; dumpbase with dirnames
5332 overrides dumpdir entirely, even if dumpdir is
5333 specified. */
5334 if (dumpbase_ext)
5335 /* We've already checked above that the suffix matches. */
5336 outbase = xstrndup (dumpbase,
5337 strlen (dumpbase) - strlen (dumpbase_ext));
5338 else
5339 outbase = xstrdup (dumpbase);
5341 else if (output_file && !not_actual_file_p (output_file))
5343 outbase = xstrdup (lbasename (output_file));
5344 char *p = strrchr (outbase + 1, '.');
5345 if (p)
5346 *p = '\0';
5349 if (outbase)
5350 outbase_length = strlen (outbase);
5353 /* If there is any pathname component in an explicit -dumpbase, do
5354 not use dumpdir, but retain it to pass it on to the compiler. */
5355 if (dumpdir)
5356 dumpdir_length = strlen (dumpdir);
5357 else
5358 dumpdir_length = 0;
5360 /* Check that dumpbase_ext, if still present, still matches the end
5361 of dumpbase, if present, and drop it otherwise. We only retained
5362 it above when dumpbase was absent to maybe use it to drop the
5363 extension from output_name before combining it with dumpdir. We
5364 won't deal with -dumpbase-ext when -dumpbase is not explicitly
5365 given, even if just to activate backward-compatible dumpbase:
5366 dropping it on the floor is correct, expected and documented
5367 behavior. Attempting to deal with a -dumpbase-ext that might
5368 match the end of some input filename, or of the combination of
5369 the output basename with the suffix of the input filename,
5370 possible with an intermediate .gk extension for -fcompare-debug,
5371 is just calling for trouble. */
5372 if (dumpbase_ext)
5374 if (!dumpbase || !*dumpbase)
5376 free (dumpbase_ext);
5377 dumpbase_ext = NULL;
5379 else
5380 gcc_assert (strcmp (dumpbase + strlen (dumpbase)
5381 - strlen (dumpbase_ext), dumpbase_ext) == 0);
5384 if (save_temps_flag && use_pipes)
5386 /* -save-temps overrides -pipe, so that temp files are produced */
5387 if (save_temps_flag)
5388 warning (0, "%<-pipe%> ignored because %<-save-temps%> specified");
5389 use_pipes = 0;
5392 if (!compare_debug)
5394 const char *gcd = env.get ("GCC_COMPARE_DEBUG");
5396 if (gcd && gcd[0] == '-')
5398 compare_debug = 2;
5399 compare_debug_opt = gcd;
5401 else if (gcd && *gcd && strcmp (gcd, "0"))
5403 compare_debug = 3;
5404 compare_debug_opt = "-gtoggle";
5407 else if (compare_debug < 0)
5409 compare_debug = 0;
5410 gcc_assert (!compare_debug_opt);
5413 /* Set up the search paths. We add directories that we expect to
5414 contain GNU Toolchain components before directories specified by
5415 the machine description so that we will find GNU components (like
5416 the GNU assembler) before those of the host system. */
5418 /* If we don't know where the toolchain has been installed, use the
5419 configured-in locations. */
5420 if (!gcc_exec_prefix)
5422 #ifndef OS2
5423 add_prefix (&exec_prefixes, standard_libexec_prefix, "GCC",
5424 PREFIX_PRIORITY_LAST, 1, 0);
5425 add_prefix (&exec_prefixes, standard_libexec_prefix, "BINUTILS",
5426 PREFIX_PRIORITY_LAST, 2, 0);
5427 add_prefix (&exec_prefixes, standard_exec_prefix, "BINUTILS",
5428 PREFIX_PRIORITY_LAST, 2, 0);
5429 #endif
5430 add_prefix (&startfile_prefixes, standard_exec_prefix, "BINUTILS",
5431 PREFIX_PRIORITY_LAST, 1, 0);
5434 gcc_assert (!IS_ABSOLUTE_PATH (tooldir_base_prefix));
5435 tooldir_prefix2 = concat (tooldir_base_prefix, spec_machine,
5436 dir_separator_str, NULL);
5438 /* Look for tools relative to the location from which the driver is
5439 running, or, if that is not available, the configured prefix. */
5440 tooldir_prefix
5441 = concat (gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
5442 spec_host_machine, dir_separator_str, spec_version,
5443 accel_dir_suffix, dir_separator_str, tooldir_prefix2, NULL);
5444 free (tooldir_prefix2);
5446 add_prefix (&exec_prefixes,
5447 concat (tooldir_prefix, "bin", dir_separator_str, NULL),
5448 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 0);
5449 add_prefix (&startfile_prefixes,
5450 concat (tooldir_prefix, "lib", dir_separator_str, NULL),
5451 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 1);
5452 free (tooldir_prefix);
5454 #if defined(TARGET_SYSTEM_ROOT_RELOCATABLE) && !defined(VMS)
5455 /* If the normal TARGET_SYSTEM_ROOT is inside of $exec_prefix,
5456 then consider it to relocate with the rest of the GCC installation
5457 if GCC_EXEC_PREFIX is set.
5458 ``make_relative_prefix'' is not compiled for VMS, so don't call it. */
5459 if (target_system_root && !target_system_root_changed && gcc_exec_prefix)
5461 char *tmp_prefix = get_relative_prefix (decoded_options[0].arg,
5462 standard_bindir_prefix,
5463 target_system_root);
5464 if (tmp_prefix && access_check (tmp_prefix, F_OK) == 0)
5466 target_system_root = tmp_prefix;
5467 target_system_root_changed = 1;
5470 #endif
5472 /* More prefixes are enabled in main, after we read the specs file
5473 and determine whether this is cross-compilation or not. */
5475 if (n_infiles != 0 && n_infiles == last_language_n_infiles && spec_lang != 0)
5476 warning (0, "%<-x %s%> after last input file has no effect", spec_lang);
5478 /* Synthesize -fcompare-debug flag from the GCC_COMPARE_DEBUG
5479 environment variable. */
5480 if (compare_debug == 2 || compare_debug == 3)
5482 const char *opt = concat ("-fcompare-debug=", compare_debug_opt, NULL);
5483 save_switch (opt, 0, NULL, false, true);
5484 compare_debug = 1;
5487 /* Ensure we only invoke each subprocess once. */
5488 if (n_infiles == 0
5489 && (print_subprocess_help || print_help_list || print_version))
5491 /* Create a dummy input file, so that we can pass
5492 the help option on to the various sub-processes. */
5493 add_infile ("help-dummy", "c");
5496 /* Decide if undefined variable references are allowed in specs. */
5498 /* -v alone is safe. --version and --help alone or together are safe. Note
5499 that -v would make them unsafe, as they'd then be run for subprocesses as
5500 well, the location of which might depend on variables possibly coming
5501 from self-specs. Note also that the command name is counted in
5502 decoded_options_count. */
5504 unsigned help_version_count = 0;
5506 if (print_version)
5507 help_version_count++;
5509 if (print_help_list)
5510 help_version_count++;
5512 spec_undefvar_allowed =
5513 ((verbose_flag && decoded_options_count == 2)
5514 || help_version_count == decoded_options_count - 1);
5516 alloc_switch ();
5517 switches[n_switches].part1 = 0;
5518 alloc_infile ();
5519 infiles[n_infiles].name = 0;
5522 /* Store switches not filtered out by %<S in spec in COLLECT_GCC_OPTIONS
5523 and place that in the environment. */
5525 static void
5526 set_collect_gcc_options (void)
5528 int i;
5529 int first_time;
5531 /* Build COLLECT_GCC_OPTIONS to have all of the options specified to
5532 the compiler. */
5533 obstack_grow (&collect_obstack, "COLLECT_GCC_OPTIONS=",
5534 sizeof ("COLLECT_GCC_OPTIONS=") - 1);
5536 first_time = true;
5537 for (i = 0; (int) i < n_switches; i++)
5539 const char *const *args;
5540 const char *p, *q;
5541 if (!first_time)
5542 obstack_grow (&collect_obstack, " ", 1);
5544 first_time = false;
5546 /* Ignore elided switches. */
5547 if ((switches[i].live_cond
5548 & (SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC))
5549 == SWITCH_IGNORE)
5550 continue;
5552 obstack_grow (&collect_obstack, "'-", 2);
5553 q = switches[i].part1;
5554 while ((p = strchr (q, '\'')))
5556 obstack_grow (&collect_obstack, q, p - q);
5557 obstack_grow (&collect_obstack, "'\\''", 4);
5558 q = ++p;
5560 obstack_grow (&collect_obstack, q, strlen (q));
5561 obstack_grow (&collect_obstack, "'", 1);
5563 for (args = switches[i].args; args && *args; args++)
5565 obstack_grow (&collect_obstack, " '", 2);
5566 q = *args;
5567 while ((p = strchr (q, '\'')))
5569 obstack_grow (&collect_obstack, q, p - q);
5570 obstack_grow (&collect_obstack, "'\\''", 4);
5571 q = ++p;
5573 obstack_grow (&collect_obstack, q, strlen (q));
5574 obstack_grow (&collect_obstack, "'", 1);
5578 if (dumpdir)
5580 if (!first_time)
5581 obstack_grow (&collect_obstack, " ", 1);
5582 first_time = false;
5584 obstack_grow (&collect_obstack, "'-dumpdir' '", 12);
5585 const char *p, *q;
5587 q = dumpdir;
5588 while ((p = strchr (q, '\'')))
5590 obstack_grow (&collect_obstack, q, p - q);
5591 obstack_grow (&collect_obstack, "'\\''", 4);
5592 q = ++p;
5594 obstack_grow (&collect_obstack, q, strlen (q));
5596 obstack_grow (&collect_obstack, "'", 1);
5599 obstack_grow (&collect_obstack, "\0", 1);
5600 xputenv (XOBFINISH (&collect_obstack, char *));
5603 /* Process a spec string, accumulating and running commands. */
5605 /* These variables describe the input file name.
5606 input_file_number is the index on outfiles of this file,
5607 so that the output file name can be stored for later use by %o.
5608 input_basename is the start of the part of the input file
5609 sans all directory names, and basename_length is the number
5610 of characters starting there excluding the suffix .c or whatever. */
5612 static const char *gcc_input_filename;
5613 static int input_file_number;
5614 size_t input_filename_length;
5615 static int basename_length;
5616 static int suffixed_basename_length;
5617 static const char *input_basename;
5618 static const char *input_suffix;
5619 #ifndef HOST_LACKS_INODE_NUMBERS
5620 static struct stat input_stat;
5621 #endif
5622 static int input_stat_set;
5624 /* The compiler used to process the current input file. */
5625 static struct compiler *input_file_compiler;
5627 /* These are variables used within do_spec and do_spec_1. */
5629 /* Nonzero if an arg has been started and not yet terminated
5630 (with space, tab or newline). */
5631 static int arg_going;
5633 /* Nonzero means %d or %g has been seen; the next arg to be terminated
5634 is a temporary file name. */
5635 static int delete_this_arg;
5637 /* Nonzero means %w has been seen; the next arg to be terminated
5638 is the output file name of this compilation. */
5639 static int this_is_output_file;
5641 /* Nonzero means %s has been seen; the next arg to be terminated
5642 is the name of a library file and we should try the standard
5643 search dirs for it. */
5644 static int this_is_library_file;
5646 /* Nonzero means %T has been seen; the next arg to be terminated
5647 is the name of a linker script and we should try all of the
5648 standard search dirs for it. If it is found insert a --script
5649 command line switch and then substitute the full path in place,
5650 otherwise generate an error message. */
5651 static int this_is_linker_script;
5653 /* Nonzero means that the input of this command is coming from a pipe. */
5654 static int input_from_pipe;
5656 /* Nonnull means substitute this for any suffix when outputting a switches
5657 arguments. */
5658 static const char *suffix_subst;
5660 /* If there is an argument being accumulated, terminate it and store it. */
5662 static void
5663 end_going_arg (void)
5665 if (arg_going)
5667 const char *string;
5669 obstack_1grow (&obstack, 0);
5670 string = XOBFINISH (&obstack, const char *);
5671 if (this_is_library_file)
5672 string = find_file (string);
5673 if (this_is_linker_script)
5675 char * full_script_path = find_a_file (&startfile_prefixes, string, R_OK, true);
5677 if (full_script_path == NULL)
5679 error ("unable to locate default linker script %qs in the library search paths", string);
5680 /* Script was not found on search path. */
5681 return;
5683 store_arg ("--script", false, false);
5684 string = full_script_path;
5686 store_arg (string, delete_this_arg, this_is_output_file);
5687 if (this_is_output_file)
5688 outfiles[input_file_number] = string;
5689 arg_going = 0;
5694 /* Parse the WRAPPER string which is a comma separated list of the command line
5695 and insert them into the beginning of argbuf. */
5697 static void
5698 insert_wrapper (const char *wrapper)
5700 int n = 0;
5701 int i;
5702 char *buf = xstrdup (wrapper);
5703 char *p = buf;
5704 unsigned int old_length = argbuf.length ();
5708 n++;
5709 while (*p == ',')
5710 p++;
5712 while ((p = strchr (p, ',')) != NULL);
5714 argbuf.safe_grow (old_length + n, true);
5715 memmove (argbuf.address () + n,
5716 argbuf.address (),
5717 old_length * sizeof (const_char_p));
5719 i = 0;
5720 p = buf;
5723 while (*p == ',')
5725 *p = 0;
5726 p++;
5728 argbuf[i] = p;
5729 i++;
5731 while ((p = strchr (p, ',')) != NULL);
5732 gcc_assert (i == n);
5735 /* Process the spec SPEC and run the commands specified therein.
5736 Returns 0 if the spec is successfully processed; -1 if failed. */
5739 do_spec (const char *spec)
5741 int value;
5743 value = do_spec_2 (spec, NULL);
5745 /* Force out any unfinished command.
5746 If -pipe, this forces out the last command if it ended in `|'. */
5747 if (value == 0)
5749 if (argbuf.length () > 0
5750 && !strcmp (argbuf.last (), "|"))
5751 argbuf.pop ();
5753 set_collect_gcc_options ();
5755 if (argbuf.length () > 0)
5756 value = execute ();
5759 return value;
5762 /* Process the spec SPEC, with SOFT_MATCHED_PART designating the current value
5763 of a matched * pattern which may be re-injected by way of %*. */
5765 static int
5766 do_spec_2 (const char *spec, const char *soft_matched_part)
5768 int result;
5770 clear_args ();
5771 arg_going = 0;
5772 delete_this_arg = 0;
5773 this_is_output_file = 0;
5774 this_is_library_file = 0;
5775 this_is_linker_script = 0;
5776 input_from_pipe = 0;
5777 suffix_subst = NULL;
5779 result = do_spec_1 (spec, 0, soft_matched_part);
5781 end_going_arg ();
5783 return result;
5786 /* Process the given spec string and add any new options to the end
5787 of the switches/n_switches array. */
5789 static void
5790 do_option_spec (const char *name, const char *spec)
5792 unsigned int i, value_count, value_len;
5793 const char *p, *q, *value;
5794 char *tmp_spec, *tmp_spec_p;
5796 if (configure_default_options[0].name == NULL)
5797 return;
5799 for (i = 0; i < ARRAY_SIZE (configure_default_options); i++)
5800 if (strcmp (configure_default_options[i].name, name) == 0)
5801 break;
5802 if (i == ARRAY_SIZE (configure_default_options))
5803 return;
5805 value = configure_default_options[i].value;
5806 value_len = strlen (value);
5808 /* Compute the size of the final spec. */
5809 value_count = 0;
5810 p = spec;
5811 while ((p = strstr (p, "%(VALUE)")) != NULL)
5813 p ++;
5814 value_count ++;
5817 /* Replace each %(VALUE) by the specified value. */
5818 tmp_spec = (char *) alloca (strlen (spec) + 1
5819 + value_count * (value_len - strlen ("%(VALUE)")));
5820 tmp_spec_p = tmp_spec;
5821 q = spec;
5822 while ((p = strstr (q, "%(VALUE)")) != NULL)
5824 memcpy (tmp_spec_p, q, p - q);
5825 tmp_spec_p = tmp_spec_p + (p - q);
5826 memcpy (tmp_spec_p, value, value_len);
5827 tmp_spec_p += value_len;
5828 q = p + strlen ("%(VALUE)");
5830 strcpy (tmp_spec_p, q);
5832 do_self_spec (tmp_spec);
5835 /* Process the given spec string and add any new options to the end
5836 of the switches/n_switches array. */
5838 static void
5839 do_self_spec (const char *spec)
5841 int i;
5843 do_spec_2 (spec, NULL);
5844 do_spec_1 (" ", 0, NULL);
5846 /* Mark %<S switches processed by do_self_spec to be ignored permanently.
5847 do_self_specs adds the replacements to switches array, so it shouldn't
5848 be processed afterwards. */
5849 for (i = 0; i < n_switches; i++)
5850 if ((switches[i].live_cond & SWITCH_IGNORE))
5851 switches[i].live_cond |= SWITCH_IGNORE_PERMANENTLY;
5853 if (argbuf.length () > 0)
5855 const char **argbuf_copy;
5856 struct cl_decoded_option *decoded_options;
5857 struct cl_option_handlers handlers;
5858 unsigned int decoded_options_count;
5859 unsigned int j;
5861 /* Create a copy of argbuf with a dummy argv[0] entry for
5862 decode_cmdline_options_to_array. */
5863 argbuf_copy = XNEWVEC (const char *,
5864 argbuf.length () + 1);
5865 argbuf_copy[0] = "";
5866 memcpy (argbuf_copy + 1, argbuf.address (),
5867 argbuf.length () * sizeof (const char *));
5869 decode_cmdline_options_to_array (argbuf.length () + 1,
5870 argbuf_copy,
5871 CL_DRIVER, &decoded_options,
5872 &decoded_options_count);
5873 free (argbuf_copy);
5875 set_option_handlers (&handlers);
5877 for (j = 1; j < decoded_options_count; j++)
5879 switch (decoded_options[j].opt_index)
5881 case OPT_SPECIAL_input_file:
5882 /* Specs should only generate options, not input
5883 files. */
5884 if (strcmp (decoded_options[j].arg, "-") != 0)
5885 fatal_error (input_location,
5886 "switch %qs does not start with %<-%>",
5887 decoded_options[j].arg);
5888 else
5889 fatal_error (input_location,
5890 "spec-generated switch is just %<-%>");
5891 break;
5893 case OPT_fcompare_debug_second:
5894 case OPT_fcompare_debug:
5895 case OPT_fcompare_debug_:
5896 case OPT_o:
5897 /* Avoid duplicate processing of some options from
5898 compare-debug specs; just save them here. */
5899 save_switch (decoded_options[j].canonical_option[0],
5900 (decoded_options[j].canonical_option_num_elements
5901 - 1),
5902 &decoded_options[j].canonical_option[1], false, true);
5903 break;
5905 default:
5906 read_cmdline_option (&global_options, &global_options_set,
5907 decoded_options + j, UNKNOWN_LOCATION,
5908 CL_DRIVER, &handlers, global_dc);
5909 break;
5913 free (decoded_options);
5915 alloc_switch ();
5916 switches[n_switches].part1 = 0;
5920 /* Callback for processing %D and %I specs. */
5922 struct spec_path_info {
5923 const char *option;
5924 const char *append;
5925 size_t append_len;
5926 bool omit_relative;
5927 bool separate_options;
5930 static void *
5931 spec_path (char *path, void *data)
5933 struct spec_path_info *info = (struct spec_path_info *) data;
5934 size_t len = 0;
5935 char save = 0;
5937 if (info->omit_relative && !IS_ABSOLUTE_PATH (path))
5938 return NULL;
5940 if (info->append_len != 0)
5942 len = strlen (path);
5943 memcpy (path + len, info->append, info->append_len + 1);
5946 if (!is_directory (path, true))
5947 return NULL;
5949 do_spec_1 (info->option, 1, NULL);
5950 if (info->separate_options)
5951 do_spec_1 (" ", 0, NULL);
5953 if (info->append_len == 0)
5955 len = strlen (path);
5956 save = path[len - 1];
5957 if (IS_DIR_SEPARATOR (path[len - 1]))
5958 path[len - 1] = '\0';
5961 do_spec_1 (path, 1, NULL);
5962 do_spec_1 (" ", 0, NULL);
5964 /* Must not damage the original path. */
5965 if (info->append_len == 0)
5966 path[len - 1] = save;
5968 return NULL;
5971 /* True if we should compile INFILE. */
5973 static bool
5974 compile_input_file_p (struct infile *infile)
5976 if ((!infile->language) || (infile->language[0] != '*'))
5977 if (infile->incompiler == input_file_compiler)
5978 return true;
5979 return false;
5982 /* Process each member of VEC as a spec. */
5984 static void
5985 do_specs_vec (vec<char_p> vec)
5987 for (char *opt : vec)
5989 do_spec_1 (opt, 1, NULL);
5990 /* Make each accumulated option a separate argument. */
5991 do_spec_1 (" ", 0, NULL);
5995 /* Add options passed via -Xassembler or -Wa to COLLECT_AS_OPTIONS. */
5997 static void
5998 putenv_COLLECT_AS_OPTIONS (vec<char_p> vec)
6000 if (vec.is_empty ())
6001 return;
6003 obstack_init (&collect_obstack);
6004 obstack_grow (&collect_obstack, "COLLECT_AS_OPTIONS=",
6005 strlen ("COLLECT_AS_OPTIONS="));
6007 char *opt;
6008 unsigned ix;
6010 FOR_EACH_VEC_ELT (vec, ix, opt)
6012 obstack_1grow (&collect_obstack, '\'');
6013 obstack_grow (&collect_obstack, opt, strlen (opt));
6014 obstack_1grow (&collect_obstack, '\'');
6015 if (ix < vec.length () - 1)
6016 obstack_1grow(&collect_obstack, ' ');
6019 obstack_1grow (&collect_obstack, '\0');
6020 xputenv (XOBFINISH (&collect_obstack, char *));
6023 /* Process the sub-spec SPEC as a portion of a larger spec.
6024 This is like processing a whole spec except that we do
6025 not initialize at the beginning and we do not supply a
6026 newline by default at the end.
6027 INSWITCH nonzero means don't process %-sequences in SPEC;
6028 in this case, % is treated as an ordinary character.
6029 This is used while substituting switches.
6030 INSWITCH nonzero also causes SPC not to terminate an argument.
6032 Value is zero unless a line was finished
6033 and the command on that line reported an error. */
6035 static int
6036 do_spec_1 (const char *spec, int inswitch, const char *soft_matched_part)
6038 const char *p = spec;
6039 int c;
6040 int i;
6041 int value;
6043 /* If it's an empty string argument to a switch, keep it as is. */
6044 if (inswitch && !*p)
6045 arg_going = 1;
6047 while ((c = *p++))
6048 /* If substituting a switch, treat all chars like letters.
6049 Otherwise, NL, SPC, TAB and % are special. */
6050 switch (inswitch ? 'a' : c)
6052 case '\n':
6053 end_going_arg ();
6055 if (argbuf.length () > 0
6056 && !strcmp (argbuf.last (), "|"))
6058 /* A `|' before the newline means use a pipe here,
6059 but only if -pipe was specified.
6060 Otherwise, execute now and don't pass the `|' as an arg. */
6061 if (use_pipes)
6063 input_from_pipe = 1;
6064 break;
6066 else
6067 argbuf.pop ();
6070 set_collect_gcc_options ();
6072 if (argbuf.length () > 0)
6074 value = execute ();
6075 if (value)
6076 return value;
6078 /* Reinitialize for a new command, and for a new argument. */
6079 clear_args ();
6080 arg_going = 0;
6081 delete_this_arg = 0;
6082 this_is_output_file = 0;
6083 this_is_library_file = 0;
6084 this_is_linker_script = 0;
6085 input_from_pipe = 0;
6086 break;
6088 case '|':
6089 end_going_arg ();
6091 /* Use pipe */
6092 obstack_1grow (&obstack, c);
6093 arg_going = 1;
6094 break;
6096 case '\t':
6097 case ' ':
6098 end_going_arg ();
6100 /* Reinitialize for a new argument. */
6101 delete_this_arg = 0;
6102 this_is_output_file = 0;
6103 this_is_library_file = 0;
6104 this_is_linker_script = 0;
6105 break;
6107 case '%':
6108 switch (c = *p++)
6110 case 0:
6111 fatal_error (input_location, "spec %qs invalid", spec);
6113 case 'b':
6114 /* Don't use %b in the linker command. */
6115 gcc_assert (suffixed_basename_length);
6116 if (!this_is_output_file && dumpdir_length)
6117 obstack_grow (&obstack, dumpdir, dumpdir_length);
6118 if (this_is_output_file || !outbase_length)
6119 obstack_grow (&obstack, input_basename, basename_length);
6120 else
6121 obstack_grow (&obstack, outbase, outbase_length);
6122 if (compare_debug < 0)
6123 obstack_grow (&obstack, ".gk", 3);
6124 arg_going = 1;
6125 break;
6127 case 'B':
6128 /* Don't use %B in the linker command. */
6129 gcc_assert (suffixed_basename_length);
6130 if (!this_is_output_file && dumpdir_length)
6131 obstack_grow (&obstack, dumpdir, dumpdir_length);
6132 if (this_is_output_file || !outbase_length)
6133 obstack_grow (&obstack, input_basename, basename_length);
6134 else
6135 obstack_grow (&obstack, outbase, outbase_length);
6136 if (compare_debug < 0)
6137 obstack_grow (&obstack, ".gk", 3);
6138 obstack_grow (&obstack, input_basename + basename_length,
6139 suffixed_basename_length - basename_length);
6141 arg_going = 1;
6142 break;
6144 case 'd':
6145 delete_this_arg = 2;
6146 break;
6148 /* Dump out the directories specified with LIBRARY_PATH,
6149 followed by the absolute directories
6150 that we search for startfiles. */
6151 case 'D':
6153 struct spec_path_info info;
6155 info.option = "-L";
6156 info.append_len = 0;
6157 #ifdef RELATIVE_PREFIX_NOT_LINKDIR
6158 /* Used on systems which record the specified -L dirs
6159 and use them to search for dynamic linking.
6160 Relative directories always come from -B,
6161 and it is better not to use them for searching
6162 at run time. In particular, stage1 loses. */
6163 info.omit_relative = true;
6164 #else
6165 info.omit_relative = false;
6166 #endif
6167 info.separate_options = false;
6169 for_each_path (&startfile_prefixes, true, 0, spec_path, &info);
6171 break;
6173 case 'e':
6174 /* %efoo means report an error with `foo' as error message
6175 and don't execute any more commands for this file. */
6177 const char *q = p;
6178 char *buf;
6179 while (*p != 0 && *p != '\n')
6180 p++;
6181 buf = (char *) alloca (p - q + 1);
6182 strncpy (buf, q, p - q);
6183 buf[p - q] = 0;
6184 error ("%s", _(buf));
6185 return -1;
6187 break;
6188 case 'n':
6189 /* %nfoo means report a notice with `foo' on stderr. */
6191 const char *q = p;
6192 char *buf;
6193 while (*p != 0 && *p != '\n')
6194 p++;
6195 buf = (char *) alloca (p - q + 1);
6196 strncpy (buf, q, p - q);
6197 buf[p - q] = 0;
6198 inform (UNKNOWN_LOCATION, "%s", _(buf));
6199 if (*p)
6200 p++;
6202 break;
6204 case 'j':
6206 struct stat st;
6208 /* If save_temps_flag is off, and the HOST_BIT_BUCKET is
6209 defined, and it is not a directory, and it is
6210 writable, use it. Otherwise, treat this like any
6211 other temporary file. */
6213 if ((!save_temps_flag)
6214 && (stat (HOST_BIT_BUCKET, &st) == 0) && (!S_ISDIR (st.st_mode))
6215 && (access (HOST_BIT_BUCKET, W_OK) == 0))
6217 obstack_grow (&obstack, HOST_BIT_BUCKET,
6218 strlen (HOST_BIT_BUCKET));
6219 delete_this_arg = 0;
6220 arg_going = 1;
6221 break;
6224 goto create_temp_file;
6225 case '|':
6226 if (use_pipes)
6228 obstack_1grow (&obstack, '-');
6229 delete_this_arg = 0;
6230 arg_going = 1;
6232 /* consume suffix */
6233 while (*p == '.' || ISALNUM ((unsigned char) *p))
6234 p++;
6235 if (p[0] == '%' && p[1] == 'O')
6236 p += 2;
6238 break;
6240 goto create_temp_file;
6241 case 'm':
6242 if (use_pipes)
6244 /* consume suffix */
6245 while (*p == '.' || ISALNUM ((unsigned char) *p))
6246 p++;
6247 if (p[0] == '%' && p[1] == 'O')
6248 p += 2;
6250 break;
6252 goto create_temp_file;
6253 case 'g':
6254 case 'u':
6255 case 'U':
6256 create_temp_file:
6258 struct temp_name *t;
6259 int suffix_length;
6260 const char *suffix = p;
6261 char *saved_suffix = NULL;
6263 while (*p == '.' || ISALNUM ((unsigned char) *p))
6264 p++;
6265 suffix_length = p - suffix;
6266 if (p[0] == '%' && p[1] == 'O')
6268 p += 2;
6269 /* We don't support extra suffix characters after %O. */
6270 if (*p == '.' || ISALNUM ((unsigned char) *p))
6271 fatal_error (input_location,
6272 "spec %qs has invalid %<%%0%c%>", spec, *p);
6273 if (suffix_length == 0)
6274 suffix = TARGET_OBJECT_SUFFIX;
6275 else
6277 saved_suffix
6278 = XNEWVEC (char, suffix_length
6279 + strlen (TARGET_OBJECT_SUFFIX) + 1);
6280 strncpy (saved_suffix, suffix, suffix_length);
6281 strcpy (saved_suffix + suffix_length,
6282 TARGET_OBJECT_SUFFIX);
6284 suffix_length += strlen (TARGET_OBJECT_SUFFIX);
6287 if (compare_debug < 0)
6289 suffix = concat (".gk", suffix, NULL);
6290 suffix_length += 3;
6293 /* If -save-temps was specified, use that for the
6294 temp file. */
6295 if (save_temps_flag)
6297 char *tmp;
6298 bool adjusted_suffix = false;
6299 if (suffix_length
6300 && !outbase_length && !basename_length
6301 && !dumpdir_trailing_dash_added)
6303 adjusted_suffix = true;
6304 suffix++;
6305 suffix_length--;
6307 temp_filename_length
6308 = dumpdir_length + suffix_length + 1;
6309 if (outbase_length)
6310 temp_filename_length += outbase_length;
6311 else
6312 temp_filename_length += basename_length;
6313 tmp = (char *) alloca (temp_filename_length);
6314 if (dumpdir_length)
6315 memcpy (tmp, dumpdir, dumpdir_length);
6316 if (outbase_length)
6317 memcpy (tmp + dumpdir_length, outbase,
6318 outbase_length);
6319 else if (basename_length)
6320 memcpy (tmp + dumpdir_length, input_basename,
6321 basename_length);
6322 memcpy (tmp + temp_filename_length - suffix_length - 1,
6323 suffix, suffix_length);
6324 if (adjusted_suffix)
6326 adjusted_suffix = false;
6327 suffix--;
6328 suffix_length++;
6330 tmp[temp_filename_length - 1] = '\0';
6331 temp_filename = tmp;
6333 if (filename_cmp (temp_filename, gcc_input_filename) != 0)
6335 #ifndef HOST_LACKS_INODE_NUMBERS
6336 struct stat st_temp;
6338 /* Note, set_input() resets input_stat_set to 0. */
6339 if (input_stat_set == 0)
6341 input_stat_set = stat (gcc_input_filename,
6342 &input_stat);
6343 if (input_stat_set >= 0)
6344 input_stat_set = 1;
6347 /* If we have the stat for the gcc_input_filename
6348 and we can do the stat for the temp_filename
6349 then the they could still refer to the same
6350 file if st_dev/st_ino's are the same. */
6351 if (input_stat_set != 1
6352 || stat (temp_filename, &st_temp) < 0
6353 || input_stat.st_dev != st_temp.st_dev
6354 || input_stat.st_ino != st_temp.st_ino)
6355 #else
6356 /* Just compare canonical pathnames. */
6357 char* input_realname = lrealpath (gcc_input_filename);
6358 char* temp_realname = lrealpath (temp_filename);
6359 bool files_differ = filename_cmp (input_realname, temp_realname);
6360 free (input_realname);
6361 free (temp_realname);
6362 if (files_differ)
6363 #endif
6365 temp_filename
6366 = save_string (temp_filename,
6367 temp_filename_length - 1);
6368 obstack_grow (&obstack, temp_filename,
6369 temp_filename_length);
6370 arg_going = 1;
6371 delete_this_arg = 0;
6372 break;
6377 /* See if we already have an association of %g/%u/%U and
6378 suffix. */
6379 for (t = temp_names; t; t = t->next)
6380 if (t->length == suffix_length
6381 && strncmp (t->suffix, suffix, suffix_length) == 0
6382 && t->unique == (c == 'u' || c == 'U' || c == 'j'))
6383 break;
6385 /* Make a new association if needed. %u and %j
6386 require one. */
6387 if (t == 0 || c == 'u' || c == 'j')
6389 if (t == 0)
6391 t = XNEW (struct temp_name);
6392 t->next = temp_names;
6393 temp_names = t;
6395 t->length = suffix_length;
6396 if (saved_suffix)
6398 t->suffix = saved_suffix;
6399 saved_suffix = NULL;
6401 else
6402 t->suffix = save_string (suffix, suffix_length);
6403 t->unique = (c == 'u' || c == 'U' || c == 'j');
6404 temp_filename = make_temp_file (t->suffix);
6405 temp_filename_length = strlen (temp_filename);
6406 t->filename = temp_filename;
6407 t->filename_length = temp_filename_length;
6410 free (saved_suffix);
6412 obstack_grow (&obstack, t->filename, t->filename_length);
6413 delete_this_arg = 1;
6415 arg_going = 1;
6416 break;
6418 case 'i':
6419 if (combine_inputs)
6421 /* We are going to expand `%i' into `@FILE', where FILE
6422 is a newly-created temporary filename. The filenames
6423 that would usually be expanded in place of %o will be
6424 written to the temporary file. */
6425 if (at_file_supplied)
6426 open_at_file ();
6428 for (i = 0; (int) i < n_infiles; i++)
6429 if (compile_input_file_p (&infiles[i]))
6431 store_arg (infiles[i].name, 0, 0);
6432 infiles[i].compiled = true;
6435 if (at_file_supplied)
6436 close_at_file ();
6438 else
6440 obstack_grow (&obstack, gcc_input_filename,
6441 input_filename_length);
6442 arg_going = 1;
6444 break;
6446 case 'I':
6448 struct spec_path_info info;
6450 if (multilib_dir)
6452 do_spec_1 ("-imultilib", 1, NULL);
6453 /* Make this a separate argument. */
6454 do_spec_1 (" ", 0, NULL);
6455 do_spec_1 (multilib_dir, 1, NULL);
6456 do_spec_1 (" ", 0, NULL);
6459 if (multiarch_dir)
6461 do_spec_1 ("-imultiarch", 1, NULL);
6462 /* Make this a separate argument. */
6463 do_spec_1 (" ", 0, NULL);
6464 do_spec_1 (multiarch_dir, 1, NULL);
6465 do_spec_1 (" ", 0, NULL);
6468 if (gcc_exec_prefix)
6470 do_spec_1 ("-iprefix", 1, NULL);
6471 /* Make this a separate argument. */
6472 do_spec_1 (" ", 0, NULL);
6473 do_spec_1 (gcc_exec_prefix, 1, NULL);
6474 do_spec_1 (" ", 0, NULL);
6477 if (target_system_root_changed ||
6478 (target_system_root && target_sysroot_hdrs_suffix))
6480 do_spec_1 ("-isysroot", 1, NULL);
6481 /* Make this a separate argument. */
6482 do_spec_1 (" ", 0, NULL);
6483 do_spec_1 (target_system_root, 1, NULL);
6484 if (target_sysroot_hdrs_suffix)
6485 do_spec_1 (target_sysroot_hdrs_suffix, 1, NULL);
6486 do_spec_1 (" ", 0, NULL);
6489 info.option = "-isystem";
6490 info.append = "include";
6491 info.append_len = strlen (info.append);
6492 info.omit_relative = false;
6493 info.separate_options = true;
6495 for_each_path (&include_prefixes, false, info.append_len,
6496 spec_path, &info);
6498 info.append = "include-fixed";
6499 if (*sysroot_hdrs_suffix_spec)
6500 info.append = concat (info.append, dir_separator_str,
6501 multilib_dir, NULL);
6502 else if (multiarch_dir)
6504 /* For multiarch, search include-fixed/<multiarch-dir>
6505 before include-fixed. */
6506 info.append = concat (info.append, dir_separator_str,
6507 multiarch_dir, NULL);
6508 info.append_len = strlen (info.append);
6509 for_each_path (&include_prefixes, false, info.append_len,
6510 spec_path, &info);
6512 info.append = "include-fixed";
6514 info.append_len = strlen (info.append);
6515 for_each_path (&include_prefixes, false, info.append_len,
6516 spec_path, &info);
6518 break;
6520 case 'o':
6521 /* We are going to expand `%o' into `@FILE', where FILE
6522 is a newly-created temporary filename. The filenames
6523 that would usually be expanded in place of %o will be
6524 written to the temporary file. */
6525 if (at_file_supplied)
6526 open_at_file ();
6528 for (i = 0; i < n_infiles + lang_specific_extra_outfiles; i++)
6529 if (outfiles[i])
6530 store_arg (outfiles[i], 0, 0);
6532 if (at_file_supplied)
6533 close_at_file ();
6534 break;
6536 case 'O':
6537 obstack_grow (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
6538 arg_going = 1;
6539 break;
6541 case 's':
6542 this_is_library_file = 1;
6543 break;
6545 case 'T':
6546 this_is_linker_script = 1;
6547 break;
6549 case 'V':
6550 outfiles[input_file_number] = NULL;
6551 break;
6553 case 'w':
6554 this_is_output_file = 1;
6555 break;
6557 case 'W':
6559 unsigned int cur_index = argbuf.length ();
6560 /* Handle the {...} following the %W. */
6561 if (*p != '{')
6562 fatal_error (input_location,
6563 "spec %qs has invalid %<%%W%c%>", spec, *p);
6564 p = handle_braces (p + 1);
6565 if (p == 0)
6566 return -1;
6567 end_going_arg ();
6568 /* If any args were output, mark the last one for deletion
6569 on failure. */
6570 if (argbuf.length () != cur_index)
6571 record_temp_file (argbuf.last (), 0, 1);
6572 break;
6575 case '@':
6576 /* Handle the {...} following the %@. */
6577 if (*p != '{')
6578 fatal_error (input_location,
6579 "spec %qs has invalid %<%%@%c%>", spec, *p);
6580 if (at_file_supplied)
6581 open_at_file ();
6582 p = handle_braces (p + 1);
6583 if (at_file_supplied)
6584 close_at_file ();
6585 if (p == 0)
6586 return -1;
6587 break;
6589 /* %x{OPTION} records OPTION for %X to output. */
6590 case 'x':
6592 const char *p1 = p;
6593 char *string;
6595 /* Skip past the option value and make a copy. */
6596 if (*p != '{')
6597 fatal_error (input_location,
6598 "spec %qs has invalid %<%%x%c%>", spec, *p);
6599 while (*p++ != '}')
6601 string = save_string (p1 + 1, p - p1 - 2);
6603 /* See if we already recorded this option. */
6604 for (const char *opt : linker_options)
6605 if (! strcmp (string, opt))
6607 free (string);
6608 return 0;
6611 /* This option is new; add it. */
6612 add_linker_option (string, strlen (string));
6613 free (string);
6615 break;
6617 /* Dump out the options accumulated previously using %x. */
6618 case 'X':
6619 do_specs_vec (linker_options);
6620 break;
6622 /* Dump out the options accumulated previously using -Wa,. */
6623 case 'Y':
6624 do_specs_vec (assembler_options);
6625 break;
6627 /* Dump out the options accumulated previously using -Wp,. */
6628 case 'Z':
6629 do_specs_vec (preprocessor_options);
6630 break;
6632 /* Here are digits and numbers that just process
6633 a certain constant string as a spec. */
6635 case '1':
6636 value = do_spec_1 (cc1_spec, 0, NULL);
6637 if (value != 0)
6638 return value;
6639 break;
6641 case '2':
6642 value = do_spec_1 (cc1plus_spec, 0, NULL);
6643 if (value != 0)
6644 return value;
6645 break;
6647 case 'a':
6648 value = do_spec_1 (asm_spec, 0, NULL);
6649 if (value != 0)
6650 return value;
6651 break;
6653 case 'A':
6654 value = do_spec_1 (asm_final_spec, 0, NULL);
6655 if (value != 0)
6656 return value;
6657 break;
6659 case 'C':
6661 const char *const spec
6662 = (input_file_compiler->cpp_spec
6663 ? input_file_compiler->cpp_spec
6664 : cpp_spec);
6665 value = do_spec_1 (spec, 0, NULL);
6666 if (value != 0)
6667 return value;
6669 break;
6671 case 'E':
6672 value = do_spec_1 (endfile_spec, 0, NULL);
6673 if (value != 0)
6674 return value;
6675 break;
6677 case 'l':
6678 value = do_spec_1 (link_spec, 0, NULL);
6679 if (value != 0)
6680 return value;
6681 break;
6683 case 'L':
6684 value = do_spec_1 (lib_spec, 0, NULL);
6685 if (value != 0)
6686 return value;
6687 break;
6689 case 'M':
6690 if (multilib_os_dir == NULL)
6691 obstack_1grow (&obstack, '.');
6692 else
6693 obstack_grow (&obstack, multilib_os_dir,
6694 strlen (multilib_os_dir));
6695 break;
6697 case 'G':
6698 value = do_spec_1 (libgcc_spec, 0, NULL);
6699 if (value != 0)
6700 return value;
6701 break;
6703 case 'R':
6704 /* We assume there is a directory
6705 separator at the end of this string. */
6706 if (target_system_root)
6708 obstack_grow (&obstack, target_system_root,
6709 strlen (target_system_root));
6710 if (target_sysroot_suffix)
6711 obstack_grow (&obstack, target_sysroot_suffix,
6712 strlen (target_sysroot_suffix));
6714 break;
6716 case 'S':
6717 value = do_spec_1 (startfile_spec, 0, NULL);
6718 if (value != 0)
6719 return value;
6720 break;
6722 /* Here we define characters other than letters and digits. */
6724 case '{':
6725 p = handle_braces (p);
6726 if (p == 0)
6727 return -1;
6728 break;
6730 case ':':
6731 p = handle_spec_function (p, NULL, soft_matched_part);
6732 if (p == 0)
6733 return -1;
6734 break;
6736 case '%':
6737 obstack_1grow (&obstack, '%');
6738 break;
6740 case '.':
6742 unsigned len = 0;
6744 while (p[len] && p[len] != ' ' && p[len] != '%')
6745 len++;
6746 suffix_subst = save_string (p - 1, len + 1);
6747 p += len;
6749 break;
6751 /* Henceforth ignore the option(s) matching the pattern
6752 after the %<. */
6753 case '<':
6754 case '>':
6756 unsigned len = 0;
6757 int have_wildcard = 0;
6758 int i;
6759 int switch_option;
6761 if (c == '>')
6762 switch_option = SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC;
6763 else
6764 switch_option = SWITCH_IGNORE;
6766 while (p[len] && p[len] != ' ' && p[len] != '\t')
6767 len++;
6769 if (p[len-1] == '*')
6770 have_wildcard = 1;
6772 for (i = 0; i < n_switches; i++)
6773 if (!strncmp (switches[i].part1, p, len - have_wildcard)
6774 && (have_wildcard || switches[i].part1[len] == '\0'))
6776 switches[i].live_cond |= switch_option;
6777 /* User switch be validated from validate_all_switches.
6778 when the definition is seen from the spec file.
6779 If not defined anywhere, will be rejected. */
6780 if (switches[i].known)
6781 switches[i].validated = true;
6784 p += len;
6786 break;
6788 case '*':
6789 if (soft_matched_part)
6791 if (soft_matched_part[0])
6792 do_spec_1 (soft_matched_part, 1, NULL);
6793 /* Only insert a space after the substitution if it is at the
6794 end of the current sequence. So if:
6796 "%{foo=*:bar%*}%{foo=*:one%*two}"
6798 matches -foo=hello then it will produce:
6800 barhello onehellotwo
6802 if (*p == 0 || *p == '}')
6803 do_spec_1 (" ", 0, NULL);
6805 else
6806 /* Catch the case where a spec string contains something like
6807 '%{foo:%*}'. i.e. there is no * in the pattern on the left
6808 hand side of the :. */
6809 error ("spec failure: %<%%*%> has not been initialized by pattern match");
6810 break;
6812 /* Process a string found as the value of a spec given by name.
6813 This feature allows individual machine descriptions
6814 to add and use their own specs. */
6815 case '(':
6817 const char *name = p;
6818 struct spec_list *sl;
6819 int len;
6821 /* The string after the S/P is the name of a spec that is to be
6822 processed. */
6823 while (*p && *p != ')')
6824 p++;
6826 /* See if it's in the list. */
6827 for (len = p - name, sl = specs; sl; sl = sl->next)
6828 if (sl->name_len == len && !strncmp (sl->name, name, len))
6830 name = *(sl->ptr_spec);
6831 #ifdef DEBUG_SPECS
6832 fnotice (stderr, "Processing spec (%s), which is '%s'\n",
6833 sl->name, name);
6834 #endif
6835 break;
6838 if (sl)
6840 value = do_spec_1 (name, 0, NULL);
6841 if (value != 0)
6842 return value;
6845 /* Discard the closing paren. */
6846 if (*p)
6847 p++;
6849 break;
6851 case '"':
6852 /* End a previous argument, if there is one, then issue an
6853 empty argument. */
6854 end_going_arg ();
6855 arg_going = 1;
6856 end_going_arg ();
6857 break;
6859 default:
6860 error ("spec failure: unrecognized spec option %qc", c);
6861 break;
6863 break;
6865 case '\\':
6866 /* Backslash: treat next character as ordinary. */
6867 c = *p++;
6869 /* When adding more cases that previously matched default, make
6870 sure to adjust quote_spec_char_p as well. */
6872 /* Fall through. */
6873 default:
6874 /* Ordinary character: put it into the current argument. */
6875 obstack_1grow (&obstack, c);
6876 arg_going = 1;
6879 /* End of string. If we are processing a spec function, we need to
6880 end any pending argument. */
6881 if (processing_spec_function)
6882 end_going_arg ();
6884 return 0;
6887 /* Look up a spec function. */
6889 static const struct spec_function *
6890 lookup_spec_function (const char *name)
6892 const struct spec_function *sf;
6894 for (sf = static_spec_functions; sf->name != NULL; sf++)
6895 if (strcmp (sf->name, name) == 0)
6896 return sf;
6898 return NULL;
6901 /* Evaluate a spec function. */
6903 static const char *
6904 eval_spec_function (const char *func, const char *args,
6905 const char *soft_matched_part)
6907 const struct spec_function *sf;
6908 const char *funcval;
6910 /* Saved spec processing context. */
6911 vec<const_char_p> save_argbuf;
6913 int save_arg_going;
6914 int save_delete_this_arg;
6915 int save_this_is_output_file;
6916 int save_this_is_library_file;
6917 int save_input_from_pipe;
6918 int save_this_is_linker_script;
6919 const char *save_suffix_subst;
6921 int save_growing_size;
6922 void *save_growing_value = NULL;
6924 sf = lookup_spec_function (func);
6925 if (sf == NULL)
6926 fatal_error (input_location, "unknown spec function %qs", func);
6928 /* Push the spec processing context. */
6929 save_argbuf = argbuf;
6931 save_arg_going = arg_going;
6932 save_delete_this_arg = delete_this_arg;
6933 save_this_is_output_file = this_is_output_file;
6934 save_this_is_library_file = this_is_library_file;
6935 save_this_is_linker_script = this_is_linker_script;
6936 save_input_from_pipe = input_from_pipe;
6937 save_suffix_subst = suffix_subst;
6939 /* If we have some object growing now, finalize it so the args and function
6940 eval proceed from a cleared context. This is needed to prevent the first
6941 constructed arg from mistakenly including the growing value. We'll push
6942 this value back on the obstack once the function evaluation is done, to
6943 restore a consistent processing context for our caller. This is fine as
6944 the address of growing objects isn't guaranteed to remain stable until
6945 they are finalized, and we expect this situation to be rare enough for
6946 the extra copy not to be an issue. */
6947 save_growing_size = obstack_object_size (&obstack);
6948 if (save_growing_size > 0)
6949 save_growing_value = obstack_finish (&obstack);
6951 /* Create a new spec processing context, and build the function
6952 arguments. */
6954 alloc_args ();
6955 if (do_spec_2 (args, soft_matched_part) < 0)
6956 fatal_error (input_location, "error in arguments to spec function %qs",
6957 func);
6959 /* argbuf_index is an index for the next argument to be inserted, and
6960 so contains the count of the args already inserted. */
6962 funcval = (*sf->func) (argbuf.length (),
6963 argbuf.address ());
6965 /* Pop the spec processing context. */
6966 argbuf.release ();
6967 argbuf = save_argbuf;
6969 arg_going = save_arg_going;
6970 delete_this_arg = save_delete_this_arg;
6971 this_is_output_file = save_this_is_output_file;
6972 this_is_library_file = save_this_is_library_file;
6973 this_is_linker_script = save_this_is_linker_script;
6974 input_from_pipe = save_input_from_pipe;
6975 suffix_subst = save_suffix_subst;
6977 if (save_growing_size > 0)
6978 obstack_grow (&obstack, save_growing_value, save_growing_size);
6980 return funcval;
6983 /* Handle a spec function call of the form:
6985 %:function(args)
6987 ARGS is processed as a spec in a separate context and split into an
6988 argument vector in the normal fashion. The function returns a string
6989 containing a spec which we then process in the caller's context, or
6990 NULL if no processing is required.
6992 If RETVAL_NONNULL is not NULL, then store a bool whether function
6993 returned non-NULL.
6995 SOFT_MATCHED_PART holds the current value of a matched * pattern, which
6996 may be re-expanded with a %* as part of the function arguments. */
6998 static const char *
6999 handle_spec_function (const char *p, bool *retval_nonnull,
7000 const char *soft_matched_part)
7002 char *func, *args;
7003 const char *endp, *funcval;
7004 int count;
7006 processing_spec_function++;
7008 /* Get the function name. */
7009 for (endp = p; *endp != '\0'; endp++)
7011 if (*endp == '(') /* ) */
7012 break;
7013 /* Only allow [A-Za-z0-9], -, and _ in function names. */
7014 if (!ISALNUM (*endp) && !(*endp == '-' || *endp == '_'))
7015 fatal_error (input_location, "malformed spec function name");
7017 if (*endp != '(') /* ) */
7018 fatal_error (input_location, "no arguments for spec function");
7019 func = save_string (p, endp - p);
7020 p = ++endp;
7022 /* Get the arguments. */
7023 for (count = 0; *endp != '\0'; endp++)
7025 /* ( */
7026 if (*endp == ')')
7028 if (count == 0)
7029 break;
7030 count--;
7032 else if (*endp == '(') /* ) */
7033 count++;
7035 /* ( */
7036 if (*endp != ')')
7037 fatal_error (input_location, "malformed spec function arguments");
7038 args = save_string (p, endp - p);
7039 p = ++endp;
7041 /* p now points to just past the end of the spec function expression. */
7043 funcval = eval_spec_function (func, args, soft_matched_part);
7044 if (funcval != NULL && do_spec_1 (funcval, 0, NULL) < 0)
7045 p = NULL;
7046 if (retval_nonnull)
7047 *retval_nonnull = funcval != NULL;
7049 free (func);
7050 free (args);
7052 processing_spec_function--;
7054 return p;
7057 /* Inline subroutine of handle_braces. Returns true if the current
7058 input suffix matches the atom bracketed by ATOM and END_ATOM. */
7059 static inline bool
7060 input_suffix_matches (const char *atom, const char *end_atom)
7062 return (input_suffix
7063 && !strncmp (input_suffix, atom, end_atom - atom)
7064 && input_suffix[end_atom - atom] == '\0');
7067 /* Subroutine of handle_braces. Returns true if the current
7068 input file's spec name matches the atom bracketed by ATOM and END_ATOM. */
7069 static bool
7070 input_spec_matches (const char *atom, const char *end_atom)
7072 return (input_file_compiler
7073 && input_file_compiler->suffix
7074 && input_file_compiler->suffix[0] != '\0'
7075 && !strncmp (input_file_compiler->suffix + 1, atom,
7076 end_atom - atom)
7077 && input_file_compiler->suffix[end_atom - atom + 1] == '\0');
7080 /* Subroutine of handle_braces. Returns true if a switch
7081 matching the atom bracketed by ATOM and END_ATOM appeared on the
7082 command line. */
7083 static bool
7084 switch_matches (const char *atom, const char *end_atom, int starred)
7086 int i;
7087 int len = end_atom - atom;
7088 int plen = starred ? len : -1;
7090 for (i = 0; i < n_switches; i++)
7091 if (!strncmp (switches[i].part1, atom, len)
7092 && (starred || switches[i].part1[len] == '\0')
7093 && check_live_switch (i, plen))
7094 return true;
7096 /* Check if a switch with separated form matching the atom.
7097 We check -D and -U switches. */
7098 else if (switches[i].args != 0)
7100 if ((*switches[i].part1 == 'D' || *switches[i].part1 == 'U')
7101 && *switches[i].part1 == atom[0])
7103 if (!strncmp (switches[i].args[0], &atom[1], len - 1)
7104 && (starred || (switches[i].part1[1] == '\0'
7105 && switches[i].args[0][len - 1] == '\0'))
7106 && check_live_switch (i, (starred ? 1 : -1)))
7107 return true;
7111 return false;
7114 /* Inline subroutine of handle_braces. Mark all of the switches which
7115 match ATOM (extends to END_ATOM; STARRED indicates whether there
7116 was a star after the atom) for later processing. */
7117 static inline void
7118 mark_matching_switches (const char *atom, const char *end_atom, int starred)
7120 int i;
7121 int len = end_atom - atom;
7122 int plen = starred ? len : -1;
7124 for (i = 0; i < n_switches; i++)
7125 if (!strncmp (switches[i].part1, atom, len)
7126 && (starred || switches[i].part1[len] == '\0')
7127 && check_live_switch (i, plen))
7128 switches[i].ordering = 1;
7131 /* Inline subroutine of handle_braces. Process all the currently
7132 marked switches through give_switch, and clear the marks. */
7133 static inline void
7134 process_marked_switches (void)
7136 int i;
7138 for (i = 0; i < n_switches; i++)
7139 if (switches[i].ordering == 1)
7141 switches[i].ordering = 0;
7142 give_switch (i, 0);
7146 /* Handle a %{ ... } construct. P points just inside the leading {.
7147 Returns a pointer one past the end of the brace block, or 0
7148 if we call do_spec_1 and that returns -1. */
7150 static const char *
7151 handle_braces (const char *p)
7153 const char *atom, *end_atom;
7154 const char *d_atom = NULL, *d_end_atom = NULL;
7155 char *esc_buf = NULL, *d_esc_buf = NULL;
7156 int esc;
7157 const char *orig = p;
7159 bool a_is_suffix;
7160 bool a_is_spectype;
7161 bool a_is_starred;
7162 bool a_is_negated;
7163 bool a_matched;
7165 bool a_must_be_last = false;
7166 bool ordered_set = false;
7167 bool disjunct_set = false;
7168 bool disj_matched = false;
7169 bool disj_starred = true;
7170 bool n_way_choice = false;
7171 bool n_way_matched = false;
7173 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
7177 if (a_must_be_last)
7178 goto invalid;
7180 /* Scan one "atom" (S in the description above of %{}, possibly
7181 with '!', '.', '@', ',', or '*' modifiers). */
7182 a_matched = false;
7183 a_is_suffix = false;
7184 a_is_starred = false;
7185 a_is_negated = false;
7186 a_is_spectype = false;
7188 SKIP_WHITE ();
7189 if (*p == '!')
7190 p++, a_is_negated = true;
7192 SKIP_WHITE ();
7193 if (*p == '%' && p[1] == ':')
7195 atom = NULL;
7196 end_atom = NULL;
7197 p = handle_spec_function (p + 2, &a_matched, NULL);
7199 else
7201 if (*p == '.')
7202 p++, a_is_suffix = true;
7203 else if (*p == ',')
7204 p++, a_is_spectype = true;
7206 atom = p;
7207 esc = 0;
7208 while (ISIDNUM (*p) || *p == '-' || *p == '+' || *p == '='
7209 || *p == ',' || *p == '.' || *p == '@' || *p == '\\')
7211 if (*p == '\\')
7213 p++;
7214 if (!*p)
7215 fatal_error (input_location,
7216 "braced spec %qs ends in escape", orig);
7217 esc++;
7219 p++;
7221 end_atom = p;
7223 if (esc)
7225 const char *ap;
7226 char *ep;
7228 if (esc_buf && esc_buf != d_esc_buf)
7229 free (esc_buf);
7230 esc_buf = NULL;
7231 ep = esc_buf = (char *) xmalloc (end_atom - atom - esc + 1);
7232 for (ap = atom; ap != end_atom; ap++, ep++)
7234 if (*ap == '\\')
7235 ap++;
7236 *ep = *ap;
7238 *ep = '\0';
7239 atom = esc_buf;
7240 end_atom = ep;
7243 if (*p == '*')
7244 p++, a_is_starred = 1;
7247 SKIP_WHITE ();
7248 switch (*p)
7250 case '&': case '}':
7251 /* Substitute the switch(es) indicated by the current atom. */
7252 ordered_set = true;
7253 if (disjunct_set || n_way_choice || a_is_negated || a_is_suffix
7254 || a_is_spectype || atom == end_atom)
7255 goto invalid;
7257 mark_matching_switches (atom, end_atom, a_is_starred);
7259 if (*p == '}')
7260 process_marked_switches ();
7261 break;
7263 case '|': case ':':
7264 /* Substitute some text if the current atom appears as a switch
7265 or suffix. */
7266 disjunct_set = true;
7267 if (ordered_set)
7268 goto invalid;
7270 if (atom && atom == end_atom)
7272 if (!n_way_choice || disj_matched || *p == '|'
7273 || a_is_negated || a_is_suffix || a_is_spectype
7274 || a_is_starred)
7275 goto invalid;
7277 /* An empty term may appear as the last choice of an
7278 N-way choice set; it means "otherwise". */
7279 a_must_be_last = true;
7280 disj_matched = !n_way_matched;
7281 disj_starred = false;
7283 else
7285 if ((a_is_suffix || a_is_spectype) && a_is_starred)
7286 goto invalid;
7288 if (!a_is_starred)
7289 disj_starred = false;
7291 /* Don't bother testing this atom if we already have a
7292 match. */
7293 if (!disj_matched && !n_way_matched)
7295 if (atom == NULL)
7296 /* a_matched is already set by handle_spec_function. */;
7297 else if (a_is_suffix)
7298 a_matched = input_suffix_matches (atom, end_atom);
7299 else if (a_is_spectype)
7300 a_matched = input_spec_matches (atom, end_atom);
7301 else
7302 a_matched = switch_matches (atom, end_atom, a_is_starred);
7304 if (a_matched != a_is_negated)
7306 disj_matched = true;
7307 d_atom = atom;
7308 d_end_atom = end_atom;
7309 d_esc_buf = esc_buf;
7314 if (*p == ':')
7316 /* Found the body, that is, the text to substitute if the
7317 current disjunction matches. */
7318 p = process_brace_body (p + 1, d_atom, d_end_atom, disj_starred,
7319 disj_matched && !n_way_matched);
7320 if (p == 0)
7321 goto done;
7323 /* If we have an N-way choice, reset state for the next
7324 disjunction. */
7325 if (*p == ';')
7327 n_way_choice = true;
7328 n_way_matched |= disj_matched;
7329 disj_matched = false;
7330 disj_starred = true;
7331 d_atom = d_end_atom = NULL;
7334 break;
7336 default:
7337 goto invalid;
7340 while (*p++ != '}');
7342 done:
7343 if (d_esc_buf && d_esc_buf != esc_buf)
7344 free (d_esc_buf);
7345 if (esc_buf)
7346 free (esc_buf);
7348 return p;
7350 invalid:
7351 fatal_error (input_location, "braced spec %qs is invalid at %qc", orig, *p);
7353 #undef SKIP_WHITE
7356 /* Subroutine of handle_braces. Scan and process a brace substitution body
7357 (X in the description of %{} syntax). P points one past the colon;
7358 ATOM and END_ATOM bracket the first atom which was found to be true
7359 (present) in the current disjunction; STARRED indicates whether all
7360 the atoms in the current disjunction were starred (for syntax validation);
7361 MATCHED indicates whether the disjunction matched or not, and therefore
7362 whether or not the body is to be processed through do_spec_1 or just
7363 skipped. Returns a pointer to the closing } or ;, or 0 if do_spec_1
7364 returns -1. */
7366 static const char *
7367 process_brace_body (const char *p, const char *atom, const char *end_atom,
7368 int starred, int matched)
7370 const char *body, *end_body;
7371 unsigned int nesting_level;
7372 bool have_subst = false;
7374 /* Locate the closing } or ;, honoring nested braces.
7375 Trim trailing whitespace. */
7376 body = p;
7377 nesting_level = 1;
7378 for (;;)
7380 if (*p == '{')
7381 nesting_level++;
7382 else if (*p == '}')
7384 if (!--nesting_level)
7385 break;
7387 else if (*p == ';' && nesting_level == 1)
7388 break;
7389 else if (*p == '%' && p[1] == '*' && nesting_level == 1)
7390 have_subst = true;
7391 else if (*p == '\0')
7392 goto invalid;
7393 p++;
7396 end_body = p;
7397 while (end_body[-1] == ' ' || end_body[-1] == '\t')
7398 end_body--;
7400 if (have_subst && !starred)
7401 goto invalid;
7403 if (matched)
7405 /* Copy the substitution body to permanent storage and execute it.
7406 If have_subst is false, this is a simple matter of running the
7407 body through do_spec_1... */
7408 char *string = save_string (body, end_body - body);
7409 if (!have_subst)
7411 if (do_spec_1 (string, 0, NULL) < 0)
7413 free (string);
7414 return 0;
7417 else
7419 /* ... but if have_subst is true, we have to process the
7420 body once for each matching switch, with %* set to the
7421 variant part of the switch. */
7422 unsigned int hard_match_len = end_atom - atom;
7423 int i;
7425 for (i = 0; i < n_switches; i++)
7426 if (!strncmp (switches[i].part1, atom, hard_match_len)
7427 && check_live_switch (i, hard_match_len))
7429 if (do_spec_1 (string, 0,
7430 &switches[i].part1[hard_match_len]) < 0)
7432 free (string);
7433 return 0;
7435 /* Pass any arguments this switch has. */
7436 give_switch (i, 1);
7437 suffix_subst = NULL;
7440 free (string);
7443 return p;
7445 invalid:
7446 fatal_error (input_location, "braced spec body %qs is invalid", body);
7449 /* Return 0 iff switch number SWITCHNUM is obsoleted by a later switch
7450 on the command line. PREFIX_LENGTH is the length of XXX in an {XXX*}
7451 spec, or -1 if either exact match or %* is used.
7453 A -O switch is obsoleted by a later -O switch. A -f, -g, -m, or -W switch
7454 whose value does not begin with "no-" is obsoleted by the same value
7455 with the "no-", similarly for a switch with the "no-" prefix. */
7457 static int
7458 check_live_switch (int switchnum, int prefix_length)
7460 const char *name = switches[switchnum].part1;
7461 int i;
7463 /* If we already processed this switch and determined if it was
7464 live or not, return our past determination. */
7465 if (switches[switchnum].live_cond != 0)
7466 return ((switches[switchnum].live_cond & SWITCH_LIVE) != 0
7467 && (switches[switchnum].live_cond & SWITCH_FALSE) == 0
7468 && (switches[switchnum].live_cond & SWITCH_IGNORE_PERMANENTLY)
7469 == 0);
7471 /* In the common case of {<at-most-one-letter>*}, a negating
7472 switch would always match, so ignore that case. We will just
7473 send the conflicting switches to the compiler phase. */
7474 if (prefix_length >= 0 && prefix_length <= 1)
7475 return 1;
7477 /* Now search for duplicate in a manner that depends on the name. */
7478 switch (*name)
7480 case 'O':
7481 for (i = switchnum + 1; i < n_switches; i++)
7482 if (switches[i].part1[0] == 'O')
7484 switches[switchnum].validated = true;
7485 switches[switchnum].live_cond = SWITCH_FALSE;
7486 return 0;
7488 break;
7490 case 'W': case 'f': case 'm': case 'g':
7491 if (startswith (name + 1, "no-"))
7493 /* We have Xno-YYY, search for XYYY. */
7494 for (i = switchnum + 1; i < n_switches; i++)
7495 if (switches[i].part1[0] == name[0]
7496 && ! strcmp (&switches[i].part1[1], &name[4]))
7498 /* --specs are validated with the validate_switches mechanism. */
7499 if (switches[switchnum].known)
7500 switches[switchnum].validated = true;
7501 switches[switchnum].live_cond = SWITCH_FALSE;
7502 return 0;
7505 else
7507 /* We have XYYY, search for Xno-YYY. */
7508 for (i = switchnum + 1; i < n_switches; i++)
7509 if (switches[i].part1[0] == name[0]
7510 && switches[i].part1[1] == 'n'
7511 && switches[i].part1[2] == 'o'
7512 && switches[i].part1[3] == '-'
7513 && !strcmp (&switches[i].part1[4], &name[1]))
7515 /* --specs are validated with the validate_switches mechanism. */
7516 if (switches[switchnum].known)
7517 switches[switchnum].validated = true;
7518 switches[switchnum].live_cond = SWITCH_FALSE;
7519 return 0;
7522 break;
7525 /* Otherwise the switch is live. */
7526 switches[switchnum].live_cond |= SWITCH_LIVE;
7527 return 1;
7530 /* Pass a switch to the current accumulating command
7531 in the same form that we received it.
7532 SWITCHNUM identifies the switch; it is an index into
7533 the vector of switches gcc received, which is `switches'.
7534 This cannot fail since it never finishes a command line.
7536 If OMIT_FIRST_WORD is nonzero, then we omit .part1 of the argument. */
7538 static void
7539 give_switch (int switchnum, int omit_first_word)
7541 if ((switches[switchnum].live_cond & SWITCH_IGNORE) != 0)
7542 return;
7544 if (!omit_first_word)
7546 do_spec_1 ("-", 0, NULL);
7547 do_spec_1 (switches[switchnum].part1, 1, NULL);
7550 if (switches[switchnum].args != 0)
7552 const char **p;
7553 for (p = switches[switchnum].args; *p; p++)
7555 const char *arg = *p;
7557 do_spec_1 (" ", 0, NULL);
7558 if (suffix_subst)
7560 unsigned length = strlen (arg);
7561 int dot = 0;
7563 while (length-- && !IS_DIR_SEPARATOR (arg[length]))
7564 if (arg[length] == '.')
7566 (CONST_CAST (char *, arg))[length] = 0;
7567 dot = 1;
7568 break;
7570 do_spec_1 (arg, 1, NULL);
7571 if (dot)
7572 (CONST_CAST (char *, arg))[length] = '.';
7573 do_spec_1 (suffix_subst, 1, NULL);
7575 else
7576 do_spec_1 (arg, 1, NULL);
7580 do_spec_1 (" ", 0, NULL);
7581 switches[switchnum].validated = true;
7584 /* Print GCC configuration (e.g. version, thread model, target,
7585 configuration_arguments) to a given FILE. */
7587 static void
7588 print_configuration (FILE *file)
7590 int n;
7591 const char *thrmod;
7593 fnotice (file, "Target: %s\n", spec_machine);
7594 fnotice (file, "Configured with: %s\n", configuration_arguments);
7596 #ifdef THREAD_MODEL_SPEC
7597 /* We could have defined THREAD_MODEL_SPEC to "%*" by default,
7598 but there's no point in doing all this processing just to get
7599 thread_model back. */
7600 obstack_init (&obstack);
7601 do_spec_1 (THREAD_MODEL_SPEC, 0, thread_model);
7602 obstack_1grow (&obstack, '\0');
7603 thrmod = XOBFINISH (&obstack, const char *);
7604 #else
7605 thrmod = thread_model;
7606 #endif
7608 fnotice (file, "Thread model: %s\n", thrmod);
7609 fnotice (file, "Supported LTO compression algorithms: zlib");
7610 #ifdef HAVE_ZSTD_H
7611 fnotice (file, " zstd");
7612 #endif
7613 fnotice (file, "\n");
7615 /* compiler_version is truncated at the first space when initialized
7616 from version string, so truncate version_string at the first space
7617 before comparing. */
7618 for (n = 0; version_string[n]; n++)
7619 if (version_string[n] == ' ')
7620 break;
7622 if (! strncmp (version_string, compiler_version, n)
7623 && compiler_version[n] == 0)
7624 fnotice (file, "gcc version %s %s\n", version_string,
7625 pkgversion_string);
7626 else
7627 fnotice (file, "gcc driver version %s %sexecuting gcc version %s\n",
7628 version_string, pkgversion_string, compiler_version);
7632 #define RETRY_ICE_ATTEMPTS 3
7634 /* Returns true if FILE1 and FILE2 contain equivalent data, 0 otherwise. */
7636 static bool
7637 files_equal_p (char *file1, char *file2)
7639 struct stat st1, st2;
7640 off_t n, len;
7641 int fd1, fd2;
7642 const int bufsize = 8192;
7643 char *buf = XNEWVEC (char, bufsize);
7645 fd1 = open (file1, O_RDONLY);
7646 fd2 = open (file2, O_RDONLY);
7648 if (fd1 < 0 || fd2 < 0)
7649 goto error;
7651 if (fstat (fd1, &st1) < 0 || fstat (fd2, &st2) < 0)
7652 goto error;
7654 if (st1.st_size != st2.st_size)
7655 goto error;
7657 for (n = st1.st_size; n; n -= len)
7659 len = n;
7660 if ((int) len > bufsize / 2)
7661 len = bufsize / 2;
7663 if (read (fd1, buf, len) != (int) len
7664 || read (fd2, buf + bufsize / 2, len) != (int) len)
7666 goto error;
7669 if (memcmp (buf, buf + bufsize / 2, len) != 0)
7670 goto error;
7673 free (buf);
7674 close (fd1);
7675 close (fd2);
7677 return 1;
7679 error:
7680 free (buf);
7681 close (fd1);
7682 close (fd2);
7683 return 0;
7686 /* Check that compiler's output doesn't differ across runs.
7687 TEMP_STDOUT_FILES and TEMP_STDERR_FILES are arrays of files, containing
7688 stdout and stderr for each compiler run. Return true if all of
7689 TEMP_STDOUT_FILES and TEMP_STDERR_FILES are equivalent. */
7691 static bool
7692 check_repro (char **temp_stdout_files, char **temp_stderr_files)
7694 int i;
7695 for (i = 0; i < RETRY_ICE_ATTEMPTS - 2; ++i)
7697 if (!files_equal_p (temp_stdout_files[i], temp_stdout_files[i + 1])
7698 || !files_equal_p (temp_stderr_files[i], temp_stderr_files[i + 1]))
7700 fnotice (stderr, "The bug is not reproducible, so it is"
7701 " likely a hardware or OS problem.\n");
7702 break;
7705 return i == RETRY_ICE_ATTEMPTS - 2;
7708 enum attempt_status {
7709 ATTEMPT_STATUS_FAIL_TO_RUN,
7710 ATTEMPT_STATUS_SUCCESS,
7711 ATTEMPT_STATUS_ICE
7715 /* Run compiler with arguments NEW_ARGV to reproduce the ICE, storing stdout
7716 to OUT_TEMP and stderr to ERR_TEMP. If APPEND is TRUE, append to OUT_TEMP
7717 and ERR_TEMP instead of truncating. If EMIT_SYSTEM_INFO is TRUE, also write
7718 GCC configuration into to ERR_TEMP. Return ATTEMPT_STATUS_FAIL_TO_RUN if
7719 compiler failed to run, ATTEMPT_STATUS_ICE if compiled ICE-ed and
7720 ATTEMPT_STATUS_SUCCESS otherwise. */
7722 static enum attempt_status
7723 run_attempt (const char **new_argv, const char *out_temp,
7724 const char *err_temp, int emit_system_info, int append)
7727 if (emit_system_info)
7729 FILE *file_out = fopen (err_temp, "a");
7730 print_configuration (file_out);
7731 fputs ("\n", file_out);
7732 fclose (file_out);
7735 int exit_status;
7736 const char *errmsg;
7737 struct pex_obj *pex;
7738 int err;
7739 int pex_flags = PEX_USE_PIPES | PEX_LAST;
7740 enum attempt_status status = ATTEMPT_STATUS_FAIL_TO_RUN;
7742 if (append)
7743 pex_flags |= PEX_STDOUT_APPEND | PEX_STDERR_APPEND;
7745 pex = pex_init (PEX_USE_PIPES, new_argv[0], NULL);
7746 if (!pex)
7747 fatal_error (input_location, "%<pex_init%> failed: %m");
7749 errmsg = pex_run (pex, pex_flags, new_argv[0],
7750 CONST_CAST2 (char *const *, const char **, &new_argv[1]),
7751 out_temp, err_temp, &err);
7752 if (errmsg != NULL)
7754 errno = err;
7755 fatal_error (input_location,
7756 err ? G_ ("cannot execute %qs: %s: %m")
7757 : G_ ("cannot execute %qs: %s"),
7758 new_argv[0], errmsg);
7761 if (!pex_get_status (pex, 1, &exit_status))
7762 goto out;
7764 switch (WEXITSTATUS (exit_status))
7766 case ICE_EXIT_CODE:
7767 status = ATTEMPT_STATUS_ICE;
7768 break;
7770 case SUCCESS_EXIT_CODE:
7771 status = ATTEMPT_STATUS_SUCCESS;
7772 break;
7774 default:
7778 out:
7779 pex_free (pex);
7780 return status;
7783 /* This routine reads lines from IN file, adds C++ style comments
7784 at the begining of each line and writes result into OUT. */
7786 static void
7787 insert_comments (const char *file_in, const char *file_out)
7789 FILE *in = fopen (file_in, "rb");
7790 FILE *out = fopen (file_out, "wb");
7791 char line[256];
7793 bool add_comment = true;
7794 while (fgets (line, sizeof (line), in))
7796 if (add_comment)
7797 fputs ("// ", out);
7798 fputs (line, out);
7799 add_comment = strchr (line, '\n') != NULL;
7802 fclose (in);
7803 fclose (out);
7806 /* This routine adds preprocessed source code into the given ERR_FILE.
7807 To do this, it adds "-E" to NEW_ARGV and execute RUN_ATTEMPT routine to
7808 add information in report file. RUN_ATTEMPT should return
7809 ATTEMPT_STATUS_SUCCESS, in other case we cannot generate the report. */
7811 static void
7812 do_report_bug (const char **new_argv, const int nargs,
7813 char **out_file, char **err_file)
7815 int i, status;
7816 int fd = open (*out_file, O_RDWR | O_APPEND);
7817 if (fd < 0)
7818 return;
7819 write (fd, "\n//", 3);
7820 for (i = 0; i < nargs; i++)
7822 write (fd, " ", 1);
7823 write (fd, new_argv[i], strlen (new_argv[i]));
7825 write (fd, "\n\n", 2);
7826 close (fd);
7827 new_argv[nargs] = "-E";
7828 new_argv[nargs + 1] = NULL;
7830 status = run_attempt (new_argv, *out_file, *err_file, 0, 1);
7832 if (status == ATTEMPT_STATUS_SUCCESS)
7834 fnotice (stderr, "Preprocessed source stored into %s file,"
7835 " please attach this to your bugreport.\n", *out_file);
7836 /* Make sure it is not deleted. */
7837 free (*out_file);
7838 *out_file = NULL;
7842 /* Try to reproduce ICE. If bug is reproducible, generate report .err file
7843 containing GCC configuration, backtrace, compiler's command line options
7844 and preprocessed source code. */
7846 static void
7847 try_generate_repro (const char **argv)
7849 int i, nargs, out_arg = -1, quiet = 0, attempt;
7850 const char **new_argv;
7851 char *temp_files[RETRY_ICE_ATTEMPTS * 2];
7852 char **temp_stdout_files = &temp_files[0];
7853 char **temp_stderr_files = &temp_files[RETRY_ICE_ATTEMPTS];
7855 if (gcc_input_filename == NULL || ! strcmp (gcc_input_filename, "-"))
7856 return;
7858 for (nargs = 0; argv[nargs] != NULL; ++nargs)
7859 /* Only retry compiler ICEs, not preprocessor ones. */
7860 if (! strcmp (argv[nargs], "-E"))
7861 return;
7862 else if (argv[nargs][0] == '-' && argv[nargs][1] == 'o')
7864 if (out_arg == -1)
7865 out_arg = nargs;
7866 else
7867 return;
7869 /* If the compiler is going to output any time information,
7870 it might varry between invocations. */
7871 else if (! strcmp (argv[nargs], "-quiet"))
7872 quiet = 1;
7873 else if (! strcmp (argv[nargs], "-ftime-report"))
7874 return;
7876 if (out_arg == -1 || !quiet)
7877 return;
7879 memset (temp_files, '\0', sizeof (temp_files));
7880 new_argv = XALLOCAVEC (const char *, nargs + 4);
7881 memcpy (new_argv, argv, (nargs + 1) * sizeof (const char *));
7882 new_argv[nargs++] = "-frandom-seed=0";
7883 new_argv[nargs++] = "-fdump-noaddr";
7884 new_argv[nargs] = NULL;
7885 if (new_argv[out_arg][2] == '\0')
7886 new_argv[out_arg + 1] = "-";
7887 else
7888 new_argv[out_arg] = "-o-";
7890 int status;
7891 for (attempt = 0; attempt < RETRY_ICE_ATTEMPTS; ++attempt)
7893 int emit_system_info = 0;
7894 int append = 0;
7895 temp_stdout_files[attempt] = make_temp_file (".out");
7896 temp_stderr_files[attempt] = make_temp_file (".err");
7898 if (attempt == RETRY_ICE_ATTEMPTS - 1)
7900 append = 1;
7901 emit_system_info = 1;
7904 status = run_attempt (new_argv, temp_stdout_files[attempt],
7905 temp_stderr_files[attempt], emit_system_info,
7906 append);
7908 if (status != ATTEMPT_STATUS_ICE)
7910 fnotice (stderr, "The bug is not reproducible, so it is"
7911 " likely a hardware or OS problem.\n");
7912 goto out;
7916 if (!check_repro (temp_stdout_files, temp_stderr_files))
7917 goto out;
7920 /* Insert commented out backtrace into report file. */
7921 char **stderr_commented = &temp_stdout_files[RETRY_ICE_ATTEMPTS - 1];
7922 insert_comments (temp_stderr_files[RETRY_ICE_ATTEMPTS - 1],
7923 *stderr_commented);
7925 /* In final attempt we append compiler options and preprocesssed code to last
7926 generated .out file with configuration and backtrace. */
7927 char **err = &temp_stderr_files[RETRY_ICE_ATTEMPTS - 1];
7928 do_report_bug (new_argv, nargs, stderr_commented, err);
7931 out:
7932 for (i = 0; i < RETRY_ICE_ATTEMPTS * 2; i++)
7933 if (temp_files[i])
7935 unlink (temp_stdout_files[i]);
7936 free (temp_stdout_files[i]);
7940 /* Search for a file named NAME trying various prefixes including the
7941 user's -B prefix and some standard ones.
7942 Return the absolute file name found. If nothing is found, return NAME. */
7944 static const char *
7945 find_file (const char *name)
7947 char *newname = find_a_file (&startfile_prefixes, name, R_OK, true);
7948 return newname ? newname : name;
7951 /* Determine whether a directory exists. If LINKER, return 0 for
7952 certain fixed names not needed by the linker. */
7954 static int
7955 is_directory (const char *path1, bool linker)
7957 int len1;
7958 char *path;
7959 char *cp;
7960 struct stat st;
7962 /* Ensure the string ends with "/.". The resulting path will be a
7963 directory even if the given path is a symbolic link. */
7964 len1 = strlen (path1);
7965 path = (char *) alloca (3 + len1);
7966 memcpy (path, path1, len1);
7967 cp = path + len1;
7968 if (!IS_DIR_SEPARATOR (cp[-1]))
7969 *cp++ = DIR_SEPARATOR;
7970 *cp++ = '.';
7971 *cp = '\0';
7973 /* Exclude directories that the linker is known to search. */
7974 if (linker
7975 && IS_DIR_SEPARATOR (path[0])
7976 && ((cp - path == 6
7977 && filename_ncmp (path + 1, "lib", 3) == 0)
7978 || (cp - path == 10
7979 && filename_ncmp (path + 1, "usr", 3) == 0
7980 && IS_DIR_SEPARATOR (path[4])
7981 && filename_ncmp (path + 5, "lib", 3) == 0)))
7982 return 0;
7984 return (stat (path, &st) >= 0 && S_ISDIR (st.st_mode));
7987 /* Set up the various global variables to indicate that we're processing
7988 the input file named FILENAME. */
7990 void
7991 set_input (const char *filename)
7993 const char *p;
7995 gcc_input_filename = filename;
7996 input_filename_length = strlen (gcc_input_filename);
7997 input_basename = lbasename (gcc_input_filename);
7999 /* Find a suffix starting with the last period,
8000 and set basename_length to exclude that suffix. */
8001 basename_length = strlen (input_basename);
8002 suffixed_basename_length = basename_length;
8003 p = input_basename + basename_length;
8004 while (p != input_basename && *p != '.')
8005 --p;
8006 if (*p == '.' && p != input_basename)
8008 basename_length = p - input_basename;
8009 input_suffix = p + 1;
8011 else
8012 input_suffix = "";
8014 /* If a spec for 'g', 'u', or 'U' is seen with -save-temps then
8015 we will need to do a stat on the gcc_input_filename. The
8016 INPUT_STAT_SET signals that the stat is needed. */
8017 input_stat_set = 0;
8020 /* On fatal signals, delete all the temporary files. */
8022 static void
8023 fatal_signal (int signum)
8025 signal (signum, SIG_DFL);
8026 delete_failure_queue ();
8027 delete_temp_files ();
8028 /* Get the same signal again, this time not handled,
8029 so its normal effect occurs. */
8030 kill (getpid (), signum);
8033 /* Compare the contents of the two files named CMPFILE[0] and
8034 CMPFILE[1]. Return zero if they're identical, nonzero
8035 otherwise. */
8037 static int
8038 compare_files (char *cmpfile[])
8040 int ret = 0;
8041 FILE *temp[2] = { NULL, NULL };
8042 int i;
8044 #if HAVE_MMAP_FILE
8046 size_t length[2];
8047 void *map[2] = { NULL, NULL };
8049 for (i = 0; i < 2; i++)
8051 struct stat st;
8053 if (stat (cmpfile[i], &st) < 0 || !S_ISREG (st.st_mode))
8055 error ("%s: could not determine length of compare-debug file %s",
8056 gcc_input_filename, cmpfile[i]);
8057 ret = 1;
8058 break;
8061 length[i] = st.st_size;
8064 if (!ret && length[0] != length[1])
8066 error ("%s: %<-fcompare-debug%> failure (length)", gcc_input_filename);
8067 ret = 1;
8070 if (!ret)
8071 for (i = 0; i < 2; i++)
8073 int fd = open (cmpfile[i], O_RDONLY);
8074 if (fd < 0)
8076 error ("%s: could not open compare-debug file %s",
8077 gcc_input_filename, cmpfile[i]);
8078 ret = 1;
8079 break;
8082 map[i] = mmap (NULL, length[i], PROT_READ, MAP_PRIVATE, fd, 0);
8083 close (fd);
8085 if (map[i] == (void *) MAP_FAILED)
8087 ret = -1;
8088 break;
8092 if (!ret)
8094 if (memcmp (map[0], map[1], length[0]) != 0)
8096 error ("%s: %<-fcompare-debug%> failure", gcc_input_filename);
8097 ret = 1;
8101 for (i = 0; i < 2; i++)
8102 if (map[i])
8103 munmap ((caddr_t) map[i], length[i]);
8105 if (ret >= 0)
8106 return ret;
8108 ret = 0;
8110 #endif
8112 for (i = 0; i < 2; i++)
8114 temp[i] = fopen (cmpfile[i], "r");
8115 if (!temp[i])
8117 error ("%s: could not open compare-debug file %s",
8118 gcc_input_filename, cmpfile[i]);
8119 ret = 1;
8120 break;
8124 if (!ret && temp[0] && temp[1])
8125 for (;;)
8127 int c0, c1;
8128 c0 = fgetc (temp[0]);
8129 c1 = fgetc (temp[1]);
8131 if (c0 != c1)
8133 error ("%s: %<-fcompare-debug%> failure",
8134 gcc_input_filename);
8135 ret = 1;
8136 break;
8139 if (c0 == EOF)
8140 break;
8143 for (i = 1; i >= 0; i--)
8145 if (temp[i])
8146 fclose (temp[i]);
8149 return ret;
8152 driver::driver (bool can_finalize, bool debug) :
8153 explicit_link_files (NULL),
8154 decoded_options (NULL)
8156 env.init (can_finalize, debug);
8159 driver::~driver ()
8161 XDELETEVEC (explicit_link_files);
8162 XDELETEVEC (decoded_options);
8165 /* driver::main is implemented as a series of driver:: method calls. */
8168 driver::main (int argc, char **argv)
8170 bool early_exit;
8172 set_progname (argv[0]);
8173 expand_at_files (&argc, &argv);
8174 decode_argv (argc, const_cast <const char **> (argv));
8175 global_initializations ();
8176 build_multilib_strings ();
8177 set_up_specs ();
8178 putenv_COLLECT_AS_OPTIONS (assembler_options);
8179 putenv_COLLECT_GCC (argv[0]);
8180 maybe_putenv_COLLECT_LTO_WRAPPER ();
8181 maybe_putenv_OFFLOAD_TARGETS ();
8182 handle_unrecognized_options ();
8184 if (completion)
8186 m_option_proposer.suggest_completion (completion);
8187 return 0;
8190 if (!maybe_print_and_exit ())
8191 return 0;
8193 early_exit = prepare_infiles ();
8194 if (early_exit)
8195 return get_exit_code ();
8197 do_spec_on_infiles ();
8198 maybe_run_linker (argv[0]);
8199 final_actions ();
8200 return get_exit_code ();
8203 /* Locate the final component of argv[0] after any leading path, and set
8204 the program name accordingly. */
8206 void
8207 driver::set_progname (const char *argv0) const
8209 const char *p = argv0 + strlen (argv0);
8210 while (p != argv0 && !IS_DIR_SEPARATOR (p[-1]))
8211 --p;
8212 progname = p;
8214 xmalloc_set_program_name (progname);
8217 /* Expand any @ files within the command-line args,
8218 setting at_file_supplied if any were expanded. */
8220 void
8221 driver::expand_at_files (int *argc, char ***argv) const
8223 char **old_argv = *argv;
8225 expandargv (argc, argv);
8227 /* Determine if any expansions were made. */
8228 if (*argv != old_argv)
8229 at_file_supplied = true;
8232 /* Decode the command-line arguments from argc/argv into the
8233 decoded_options array. */
8235 void
8236 driver::decode_argv (int argc, const char **argv)
8238 init_opts_obstack ();
8239 init_options_struct (&global_options, &global_options_set);
8241 decode_cmdline_options_to_array (argc, argv,
8242 CL_DRIVER,
8243 &decoded_options, &decoded_options_count);
8246 /* Perform various initializations and setup. */
8248 void
8249 driver::global_initializations ()
8251 /* Unlock the stdio streams. */
8252 unlock_std_streams ();
8254 gcc_init_libintl ();
8256 diagnostic_initialize (global_dc, 0);
8257 diagnostic_color_init (global_dc);
8258 diagnostic_urls_init (global_dc);
8260 #ifdef GCC_DRIVER_HOST_INITIALIZATION
8261 /* Perform host dependent initialization when needed. */
8262 GCC_DRIVER_HOST_INITIALIZATION;
8263 #endif
8265 if (atexit (delete_temp_files) != 0)
8266 fatal_error (input_location, "atexit failed");
8268 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
8269 signal (SIGINT, fatal_signal);
8270 #ifdef SIGHUP
8271 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
8272 signal (SIGHUP, fatal_signal);
8273 #endif
8274 if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
8275 signal (SIGTERM, fatal_signal);
8276 #ifdef SIGPIPE
8277 if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
8278 signal (SIGPIPE, fatal_signal);
8279 #endif
8280 #ifdef SIGCHLD
8281 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
8282 receive the signal. A different setting is inheritable */
8283 signal (SIGCHLD, SIG_DFL);
8284 #endif
8286 /* Parsing and gimplification sometimes need quite large stack.
8287 Increase stack size limits if possible. */
8288 stack_limit_increase (64 * 1024 * 1024);
8290 /* Allocate the argument vector. */
8291 alloc_args ();
8293 obstack_init (&obstack);
8296 /* Build multilib_select, et. al from the separate lines that make up each
8297 multilib selection. */
8299 void
8300 driver::build_multilib_strings () const
8303 const char *p;
8304 const char *const *q = multilib_raw;
8305 int need_space;
8307 obstack_init (&multilib_obstack);
8308 while ((p = *q++) != (char *) 0)
8309 obstack_grow (&multilib_obstack, p, strlen (p));
8311 obstack_1grow (&multilib_obstack, 0);
8312 multilib_select = XOBFINISH (&multilib_obstack, const char *);
8314 q = multilib_matches_raw;
8315 while ((p = *q++) != (char *) 0)
8316 obstack_grow (&multilib_obstack, p, strlen (p));
8318 obstack_1grow (&multilib_obstack, 0);
8319 multilib_matches = XOBFINISH (&multilib_obstack, const char *);
8321 q = multilib_exclusions_raw;
8322 while ((p = *q++) != (char *) 0)
8323 obstack_grow (&multilib_obstack, p, strlen (p));
8325 obstack_1grow (&multilib_obstack, 0);
8326 multilib_exclusions = XOBFINISH (&multilib_obstack, const char *);
8328 q = multilib_reuse_raw;
8329 while ((p = *q++) != (char *) 0)
8330 obstack_grow (&multilib_obstack, p, strlen (p));
8332 obstack_1grow (&multilib_obstack, 0);
8333 multilib_reuse = XOBFINISH (&multilib_obstack, const char *);
8335 need_space = false;
8336 for (size_t i = 0; i < ARRAY_SIZE (multilib_defaults_raw); i++)
8338 if (need_space)
8339 obstack_1grow (&multilib_obstack, ' ');
8340 obstack_grow (&multilib_obstack,
8341 multilib_defaults_raw[i],
8342 strlen (multilib_defaults_raw[i]));
8343 need_space = true;
8346 obstack_1grow (&multilib_obstack, 0);
8347 multilib_defaults = XOBFINISH (&multilib_obstack, const char *);
8351 /* Set up the spec-handling machinery. */
8353 void
8354 driver::set_up_specs () const
8356 const char *spec_machine_suffix;
8357 char *specs_file;
8358 size_t i;
8360 #ifdef INIT_ENVIRONMENT
8361 /* Set up any other necessary machine specific environment variables. */
8362 xputenv (INIT_ENVIRONMENT);
8363 #endif
8365 /* Make a table of what switches there are (switches, n_switches).
8366 Make a table of specified input files (infiles, n_infiles).
8367 Decode switches that are handled locally. */
8369 process_command (decoded_options_count, decoded_options);
8371 /* Initialize the vector of specs to just the default.
8372 This means one element containing 0s, as a terminator. */
8374 compilers = XNEWVAR (struct compiler, sizeof default_compilers);
8375 memcpy (compilers, default_compilers, sizeof default_compilers);
8376 n_compilers = n_default_compilers;
8378 /* Read specs from a file if there is one. */
8380 machine_suffix = concat (spec_host_machine, dir_separator_str, spec_version,
8381 accel_dir_suffix, dir_separator_str, NULL);
8382 just_machine_suffix = concat (spec_machine, dir_separator_str, NULL);
8384 specs_file = find_a_file (&startfile_prefixes, "specs", R_OK, true);
8385 /* Read the specs file unless it is a default one. */
8386 if (specs_file != 0 && strcmp (specs_file, "specs"))
8387 read_specs (specs_file, true, false);
8388 else
8389 init_spec ();
8391 #ifdef ACCEL_COMPILER
8392 spec_machine_suffix = machine_suffix;
8393 #else
8394 spec_machine_suffix = just_machine_suffix;
8395 #endif
8397 /* We need to check standard_exec_prefix/spec_machine_suffix/specs
8398 for any override of as, ld and libraries. */
8399 specs_file = (char *) alloca (strlen (standard_exec_prefix)
8400 + strlen (spec_machine_suffix) + sizeof ("specs"));
8401 strcpy (specs_file, standard_exec_prefix);
8402 strcat (specs_file, spec_machine_suffix);
8403 strcat (specs_file, "specs");
8404 if (access (specs_file, R_OK) == 0)
8405 read_specs (specs_file, true, false);
8407 /* Process any configure-time defaults specified for the command line
8408 options, via OPTION_DEFAULT_SPECS. */
8409 for (i = 0; i < ARRAY_SIZE (option_default_specs); i++)
8410 do_option_spec (option_default_specs[i].name,
8411 option_default_specs[i].spec);
8413 /* Process DRIVER_SELF_SPECS, adding any new options to the end
8414 of the command line. */
8416 for (i = 0; i < ARRAY_SIZE (driver_self_specs); i++)
8417 do_self_spec (driver_self_specs[i]);
8419 /* If not cross-compiling, look for executables in the standard
8420 places. */
8421 if (*cross_compile == '0')
8423 if (*md_exec_prefix)
8425 add_prefix (&exec_prefixes, md_exec_prefix, "GCC",
8426 PREFIX_PRIORITY_LAST, 0, 0);
8430 /* Process sysroot_suffix_spec. */
8431 if (*sysroot_suffix_spec != 0
8432 && !no_sysroot_suffix
8433 && do_spec_2 (sysroot_suffix_spec, NULL) == 0)
8435 if (argbuf.length () > 1)
8436 error ("spec failure: more than one argument to "
8437 "%<SYSROOT_SUFFIX_SPEC%>");
8438 else if (argbuf.length () == 1)
8439 target_sysroot_suffix = xstrdup (argbuf.last ());
8442 #ifdef HAVE_LD_SYSROOT
8443 /* Pass the --sysroot option to the linker, if it supports that. If
8444 there is a sysroot_suffix_spec, it has already been processed by
8445 this point, so target_system_root really is the system root we
8446 should be using. */
8447 if (target_system_root)
8449 obstack_grow (&obstack, "%(sysroot_spec) ", strlen ("%(sysroot_spec) "));
8450 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
8451 set_spec ("link", XOBFINISH (&obstack, const char *), false);
8453 #endif
8455 /* Process sysroot_hdrs_suffix_spec. */
8456 if (*sysroot_hdrs_suffix_spec != 0
8457 && !no_sysroot_suffix
8458 && do_spec_2 (sysroot_hdrs_suffix_spec, NULL) == 0)
8460 if (argbuf.length () > 1)
8461 error ("spec failure: more than one argument "
8462 "to %<SYSROOT_HEADERS_SUFFIX_SPEC%>");
8463 else if (argbuf.length () == 1)
8464 target_sysroot_hdrs_suffix = xstrdup (argbuf.last ());
8467 /* Look for startfiles in the standard places. */
8468 if (*startfile_prefix_spec != 0
8469 && do_spec_2 (startfile_prefix_spec, NULL) == 0
8470 && do_spec_1 (" ", 0, NULL) == 0)
8472 for (const char *arg : argbuf)
8473 add_sysrooted_prefix (&startfile_prefixes, arg, "BINUTILS",
8474 PREFIX_PRIORITY_LAST, 0, 1);
8476 /* We should eventually get rid of all these and stick to
8477 startfile_prefix_spec exclusively. */
8478 else if (*cross_compile == '0' || target_system_root)
8480 if (*md_startfile_prefix)
8481 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix,
8482 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
8484 if (*md_startfile_prefix_1)
8485 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix_1,
8486 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
8488 /* If standard_startfile_prefix is relative, base it on
8489 standard_exec_prefix. This lets us move the installed tree
8490 as a unit. If GCC_EXEC_PREFIX is defined, base
8491 standard_startfile_prefix on that as well.
8493 If the prefix is relative, only search it for native compilers;
8494 otherwise we will search a directory containing host libraries. */
8495 if (IS_ABSOLUTE_PATH (standard_startfile_prefix))
8496 add_sysrooted_prefix (&startfile_prefixes,
8497 standard_startfile_prefix, "BINUTILS",
8498 PREFIX_PRIORITY_LAST, 0, 1);
8499 else if (*cross_compile == '0')
8501 add_prefix (&startfile_prefixes,
8502 concat (gcc_exec_prefix
8503 ? gcc_exec_prefix : standard_exec_prefix,
8504 machine_suffix,
8505 standard_startfile_prefix, NULL),
8506 NULL, PREFIX_PRIORITY_LAST, 0, 1);
8509 /* Sysrooted prefixes are relocated because target_system_root is
8510 also relocated by gcc_exec_prefix. */
8511 if (*standard_startfile_prefix_1)
8512 add_sysrooted_prefix (&startfile_prefixes,
8513 standard_startfile_prefix_1, "BINUTILS",
8514 PREFIX_PRIORITY_LAST, 0, 1);
8515 if (*standard_startfile_prefix_2)
8516 add_sysrooted_prefix (&startfile_prefixes,
8517 standard_startfile_prefix_2, "BINUTILS",
8518 PREFIX_PRIORITY_LAST, 0, 1);
8521 /* Process any user specified specs in the order given on the command
8522 line. */
8523 for (struct user_specs *uptr = user_specs_head; uptr; uptr = uptr->next)
8525 char *filename = find_a_file (&startfile_prefixes, uptr->filename,
8526 R_OK, true);
8527 read_specs (filename ? filename : uptr->filename, false, true);
8530 /* Process any user self specs. */
8532 struct spec_list *sl;
8533 for (sl = specs; sl; sl = sl->next)
8534 if (sl->name_len == sizeof "self_spec" - 1
8535 && !strcmp (sl->name, "self_spec"))
8536 do_self_spec (*sl->ptr_spec);
8539 if (compare_debug)
8541 enum save_temps save;
8543 if (!compare_debug_second)
8545 n_switches_debug_check[1] = n_switches;
8546 n_switches_alloc_debug_check[1] = n_switches_alloc;
8547 switches_debug_check[1] = XDUPVEC (struct switchstr, switches,
8548 n_switches_alloc);
8550 do_self_spec ("%:compare-debug-self-opt()");
8551 n_switches_debug_check[0] = n_switches;
8552 n_switches_alloc_debug_check[0] = n_switches_alloc;
8553 switches_debug_check[0] = switches;
8555 n_switches = n_switches_debug_check[1];
8556 n_switches_alloc = n_switches_alloc_debug_check[1];
8557 switches = switches_debug_check[1];
8560 /* Avoid crash when computing %j in this early. */
8561 save = save_temps_flag;
8562 save_temps_flag = SAVE_TEMPS_NONE;
8564 compare_debug = -compare_debug;
8565 do_self_spec ("%:compare-debug-self-opt()");
8567 save_temps_flag = save;
8569 if (!compare_debug_second)
8571 n_switches_debug_check[1] = n_switches;
8572 n_switches_alloc_debug_check[1] = n_switches_alloc;
8573 switches_debug_check[1] = switches;
8574 compare_debug = -compare_debug;
8575 n_switches = n_switches_debug_check[0];
8576 n_switches_alloc = n_switches_debug_check[0];
8577 switches = switches_debug_check[0];
8582 /* If we have a GCC_EXEC_PREFIX envvar, modify it for cpp's sake. */
8583 if (gcc_exec_prefix)
8584 gcc_exec_prefix = concat (gcc_exec_prefix, spec_host_machine,
8585 dir_separator_str, spec_version,
8586 accel_dir_suffix, dir_separator_str, NULL);
8588 /* Now we have the specs.
8589 Set the `valid' bits for switches that match anything in any spec. */
8591 validate_all_switches ();
8593 /* Now that we have the switches and the specs, set
8594 the subdirectory based on the options. */
8595 set_multilib_dir ();
8598 /* Set up to remember the pathname of gcc and any options
8599 needed for collect. We use argv[0] instead of progname because
8600 we need the complete pathname. */
8602 void
8603 driver::putenv_COLLECT_GCC (const char *argv0) const
8605 obstack_init (&collect_obstack);
8606 obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);
8607 obstack_grow (&collect_obstack, argv0, strlen (argv0) + 1);
8608 xputenv (XOBFINISH (&collect_obstack, char *));
8611 /* Set up to remember the pathname of the lto wrapper. */
8613 void
8614 driver::maybe_putenv_COLLECT_LTO_WRAPPER () const
8616 char *lto_wrapper_file;
8618 if (have_c)
8619 lto_wrapper_file = NULL;
8620 else
8621 lto_wrapper_file = find_a_program ("lto-wrapper");
8622 if (lto_wrapper_file)
8624 lto_wrapper_file = convert_white_space (lto_wrapper_file);
8625 set_static_spec_owned (&lto_wrapper_spec, lto_wrapper_file);
8626 obstack_init (&collect_obstack);
8627 obstack_grow (&collect_obstack, "COLLECT_LTO_WRAPPER=",
8628 sizeof ("COLLECT_LTO_WRAPPER=") - 1);
8629 obstack_grow (&collect_obstack, lto_wrapper_spec,
8630 strlen (lto_wrapper_spec) + 1);
8631 xputenv (XOBFINISH (&collect_obstack, char *));
8636 /* Set up to remember the names of offload targets. */
8638 void
8639 driver::maybe_putenv_OFFLOAD_TARGETS () const
8641 if (offload_targets && offload_targets[0] != '\0')
8643 obstack_grow (&collect_obstack, "OFFLOAD_TARGET_NAMES=",
8644 sizeof ("OFFLOAD_TARGET_NAMES=") - 1);
8645 obstack_grow (&collect_obstack, offload_targets,
8646 strlen (offload_targets) + 1);
8647 xputenv (XOBFINISH (&collect_obstack, char *));
8648 #if OFFLOAD_DEFAULTED
8649 if (offload_targets_default)
8650 xputenv ("OFFLOAD_TARGET_DEFAULT=1");
8651 #endif
8654 free (offload_targets);
8655 offload_targets = NULL;
8658 /* Reject switches that no pass was interested in. */
8660 void
8661 driver::handle_unrecognized_options ()
8663 for (size_t i = 0; (int) i < n_switches; i++)
8664 if (! switches[i].validated)
8666 const char *hint = m_option_proposer.suggest_option (switches[i].part1);
8667 if (hint)
8668 error ("unrecognized command-line option %<-%s%>;"
8669 " did you mean %<-%s%>?",
8670 switches[i].part1, hint);
8671 else
8672 error ("unrecognized command-line option %<-%s%>",
8673 switches[i].part1);
8677 /* Handle the various -print-* options, returning 0 if the driver
8678 should exit, or nonzero if the driver should continue. */
8681 driver::maybe_print_and_exit () const
8683 if (print_search_dirs)
8685 printf (_("install: %s%s\n"),
8686 gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
8687 gcc_exec_prefix ? "" : machine_suffix);
8688 printf (_("programs: %s\n"),
8689 build_search_list (&exec_prefixes, "", false, false));
8690 printf (_("libraries: %s\n"),
8691 build_search_list (&startfile_prefixes, "", false, true));
8692 return (0);
8695 if (print_file_name)
8697 printf ("%s\n", find_file (print_file_name));
8698 return (0);
8701 if (print_prog_name)
8703 if (use_ld != NULL && ! strcmp (print_prog_name, "ld"))
8705 /* Append USE_LD to the default linker. */
8706 #ifdef DEFAULT_LINKER
8707 char *ld;
8708 # ifdef HAVE_HOST_EXECUTABLE_SUFFIX
8709 int len = (sizeof (DEFAULT_LINKER)
8710 - sizeof (HOST_EXECUTABLE_SUFFIX));
8711 ld = NULL;
8712 if (len > 0)
8714 char *default_linker = xstrdup (DEFAULT_LINKER);
8715 /* Strip HOST_EXECUTABLE_SUFFIX if DEFAULT_LINKER contains
8716 HOST_EXECUTABLE_SUFFIX. */
8717 if (! strcmp (&default_linker[len], HOST_EXECUTABLE_SUFFIX))
8719 default_linker[len] = '\0';
8720 ld = concat (default_linker, use_ld,
8721 HOST_EXECUTABLE_SUFFIX, NULL);
8724 if (ld == NULL)
8725 # endif
8726 ld = concat (DEFAULT_LINKER, use_ld, NULL);
8727 if (access (ld, X_OK) == 0)
8729 printf ("%s\n", ld);
8730 return (0);
8732 #endif
8733 print_prog_name = concat (print_prog_name, use_ld, NULL);
8735 char *newname = find_a_program (print_prog_name);
8736 printf ("%s\n", (newname ? newname : print_prog_name));
8737 return (0);
8740 if (print_multi_lib)
8742 print_multilib_info ();
8743 return (0);
8746 if (print_multi_directory)
8748 if (multilib_dir == NULL)
8749 printf (".\n");
8750 else
8751 printf ("%s\n", multilib_dir);
8752 return (0);
8755 if (print_multiarch)
8757 if (multiarch_dir == NULL)
8758 printf ("\n");
8759 else
8760 printf ("%s\n", multiarch_dir);
8761 return (0);
8764 if (print_sysroot)
8766 if (target_system_root)
8768 if (target_sysroot_suffix)
8769 printf ("%s%s\n", target_system_root, target_sysroot_suffix);
8770 else
8771 printf ("%s\n", target_system_root);
8773 return (0);
8776 if (print_multi_os_directory)
8778 if (multilib_os_dir == NULL)
8779 printf (".\n");
8780 else
8781 printf ("%s\n", multilib_os_dir);
8782 return (0);
8785 if (print_sysroot_headers_suffix)
8787 if (*sysroot_hdrs_suffix_spec)
8789 printf("%s\n", (target_sysroot_hdrs_suffix
8790 ? target_sysroot_hdrs_suffix
8791 : ""));
8792 return (0);
8794 else
8795 /* The error status indicates that only one set of fixed
8796 headers should be built. */
8797 fatal_error (input_location,
8798 "not configured with sysroot headers suffix");
8801 if (print_help_list)
8803 display_help ();
8805 if (! verbose_flag)
8807 printf (_("\nFor bug reporting instructions, please see:\n"));
8808 printf ("%s.\n", bug_report_url);
8810 return (0);
8813 /* We do not exit here. Instead we have created a fake input file
8814 called 'help-dummy' which needs to be compiled, and we pass this
8815 on the various sub-processes, along with the --help switch.
8816 Ensure their output appears after ours. */
8817 fputc ('\n', stdout);
8818 fflush (stdout);
8821 if (print_version)
8823 printf (_("%s %s%s\n"), progname, pkgversion_string,
8824 version_string);
8825 printf ("Copyright %s 2023 Free Software Foundation, Inc.\n",
8826 _("(C)"));
8827 fputs (_("This is free software; see the source for copying conditions. There is NO\n\
8828 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"),
8829 stdout);
8830 if (! verbose_flag)
8831 return 0;
8833 /* We do not exit here. We use the same mechanism of --help to print
8834 the version of the sub-processes. */
8835 fputc ('\n', stdout);
8836 fflush (stdout);
8839 if (verbose_flag)
8841 print_configuration (stderr);
8842 if (n_infiles == 0)
8843 return (0);
8846 return 1;
8849 /* Figure out what to do with each input file.
8850 Return true if we need to exit early from "main", false otherwise. */
8852 bool
8853 driver::prepare_infiles ()
8855 size_t i;
8856 int lang_n_infiles = 0;
8858 if (n_infiles == added_libraries)
8859 fatal_error (input_location, "no input files");
8861 if (seen_error ())
8862 /* Early exit needed from main. */
8863 return true;
8865 /* Make a place to record the compiler output file names
8866 that correspond to the input files. */
8868 i = n_infiles;
8869 i += lang_specific_extra_outfiles;
8870 outfiles = XCNEWVEC (const char *, i);
8872 /* Record which files were specified explicitly as link input. */
8874 explicit_link_files = XCNEWVEC (char, n_infiles);
8876 combine_inputs = have_o || flag_wpa;
8878 for (i = 0; (int) i < n_infiles; i++)
8880 const char *name = infiles[i].name;
8881 struct compiler *compiler = lookup_compiler (name,
8882 strlen (name),
8883 infiles[i].language);
8885 if (compiler && !(compiler->combinable))
8886 combine_inputs = false;
8888 if (lang_n_infiles > 0 && compiler != input_file_compiler
8889 && infiles[i].language && infiles[i].language[0] != '*')
8890 infiles[i].incompiler = compiler;
8891 else if (compiler)
8893 lang_n_infiles++;
8894 input_file_compiler = compiler;
8895 infiles[i].incompiler = compiler;
8897 else
8899 /* Since there is no compiler for this input file, assume it is a
8900 linker file. */
8901 explicit_link_files[i] = 1;
8902 infiles[i].incompiler = NULL;
8904 infiles[i].compiled = false;
8905 infiles[i].preprocessed = false;
8908 if (!combine_inputs && have_c && have_o && lang_n_infiles > 1)
8909 fatal_error (input_location,
8910 "cannot specify %<-o%> with %<-c%>, %<-S%> or %<-E%> "
8911 "with multiple files");
8913 /* No early exit needed from main; we can continue. */
8914 return false;
8917 /* Run the spec machinery on each input file. */
8919 void
8920 driver::do_spec_on_infiles () const
8922 size_t i;
8924 for (i = 0; (int) i < n_infiles; i++)
8926 int this_file_error = 0;
8928 /* Tell do_spec what to substitute for %i. */
8930 input_file_number = i;
8931 set_input (infiles[i].name);
8933 if (infiles[i].compiled)
8934 continue;
8936 /* Use the same thing in %o, unless cp->spec says otherwise. */
8938 outfiles[i] = gcc_input_filename;
8940 /* Figure out which compiler from the file's suffix. */
8942 input_file_compiler
8943 = lookup_compiler (infiles[i].name, input_filename_length,
8944 infiles[i].language);
8946 if (input_file_compiler)
8948 /* Ok, we found an applicable compiler. Run its spec. */
8950 if (input_file_compiler->spec[0] == '#')
8952 error ("%s: %s compiler not installed on this system",
8953 gcc_input_filename, &input_file_compiler->spec[1]);
8954 this_file_error = 1;
8956 else
8958 int value;
8960 if (compare_debug)
8962 free (debug_check_temp_file[0]);
8963 debug_check_temp_file[0] = NULL;
8965 free (debug_check_temp_file[1]);
8966 debug_check_temp_file[1] = NULL;
8969 value = do_spec (input_file_compiler->spec);
8970 infiles[i].compiled = true;
8971 if (value < 0)
8972 this_file_error = 1;
8973 else if (compare_debug && debug_check_temp_file[0])
8975 if (verbose_flag)
8976 inform (UNKNOWN_LOCATION,
8977 "recompiling with %<-fcompare-debug%>");
8979 compare_debug = -compare_debug;
8980 n_switches = n_switches_debug_check[1];
8981 n_switches_alloc = n_switches_alloc_debug_check[1];
8982 switches = switches_debug_check[1];
8984 value = do_spec (input_file_compiler->spec);
8986 compare_debug = -compare_debug;
8987 n_switches = n_switches_debug_check[0];
8988 n_switches_alloc = n_switches_alloc_debug_check[0];
8989 switches = switches_debug_check[0];
8991 if (value < 0)
8993 error ("during %<-fcompare-debug%> recompilation");
8994 this_file_error = 1;
8997 gcc_assert (debug_check_temp_file[1]
8998 && filename_cmp (debug_check_temp_file[0],
8999 debug_check_temp_file[1]));
9001 if (verbose_flag)
9002 inform (UNKNOWN_LOCATION, "comparing final insns dumps");
9004 if (compare_files (debug_check_temp_file))
9005 this_file_error = 1;
9008 if (compare_debug)
9010 free (debug_check_temp_file[0]);
9011 debug_check_temp_file[0] = NULL;
9013 free (debug_check_temp_file[1]);
9014 debug_check_temp_file[1] = NULL;
9019 /* If this file's name does not contain a recognized suffix,
9020 record it as explicit linker input. */
9022 else
9023 explicit_link_files[i] = 1;
9025 /* Clear the delete-on-failure queue, deleting the files in it
9026 if this compilation failed. */
9028 if (this_file_error)
9030 delete_failure_queue ();
9031 errorcount++;
9033 /* If this compilation succeeded, don't delete those files later. */
9034 clear_failure_queue ();
9037 /* Reset the input file name to the first compile/object file name, for use
9038 with %b in LINK_SPEC. We use the first input file that we can find
9039 a compiler to compile it instead of using infiles.language since for
9040 languages other than C we use aliases that we then lookup later. */
9041 if (n_infiles > 0)
9043 int i;
9045 for (i = 0; i < n_infiles ; i++)
9046 if (infiles[i].incompiler
9047 || (infiles[i].language && infiles[i].language[0] != '*'))
9049 set_input (infiles[i].name);
9050 break;
9054 if (!seen_error ())
9056 /* Make sure INPUT_FILE_NUMBER points to first available open
9057 slot. */
9058 input_file_number = n_infiles;
9059 if (lang_specific_pre_link ())
9060 errorcount++;
9064 /* If we have to run the linker, do it now. */
9066 void
9067 driver::maybe_run_linker (const char *argv0) const
9069 size_t i;
9070 int linker_was_run = 0;
9071 int num_linker_inputs;
9073 /* Determine if there are any linker input files. */
9074 num_linker_inputs = 0;
9075 for (i = 0; (int) i < n_infiles; i++)
9076 if (explicit_link_files[i] || outfiles[i] != NULL)
9077 num_linker_inputs++;
9079 /* Arrange for temporary file names created during linking to take
9080 on names related with the linker output rather than with the
9081 inputs when appropriate. */
9082 if (outbase && *outbase)
9084 if (dumpdir)
9086 char *tofree = dumpdir;
9087 gcc_checking_assert (strlen (dumpdir) == dumpdir_length);
9088 dumpdir = concat (dumpdir, outbase, ".", NULL);
9089 free (tofree);
9091 else
9092 dumpdir = concat (outbase, ".", NULL);
9093 dumpdir_length += strlen (outbase) + 1;
9094 dumpdir_trailing_dash_added = true;
9096 else if (dumpdir_trailing_dash_added)
9098 gcc_assert (dumpdir[dumpdir_length - 1] == '-');
9099 dumpdir[dumpdir_length - 1] = '.';
9102 if (dumpdir_trailing_dash_added)
9104 gcc_assert (dumpdir_length > 0);
9105 gcc_assert (dumpdir[dumpdir_length - 1] == '.');
9106 dumpdir_length--;
9109 free (outbase);
9110 input_basename = outbase = NULL;
9111 outbase_length = suffixed_basename_length = basename_length = 0;
9113 /* Run ld to link all the compiler output files. */
9115 if (num_linker_inputs > 0 && !seen_error () && print_subprocess_help < 2)
9117 int tmp = execution_count;
9119 detect_jobserver ();
9121 if (! have_c)
9123 #if HAVE_LTO_PLUGIN > 0
9124 #if HAVE_LTO_PLUGIN == 2
9125 const char *fno_use_linker_plugin = "fno-use-linker-plugin";
9126 #else
9127 const char *fuse_linker_plugin = "fuse-linker-plugin";
9128 #endif
9129 #endif
9131 /* We'll use ld if we can't find collect2. */
9132 if (! strcmp (linker_name_spec, "collect2"))
9134 char *s = find_a_program ("collect2");
9135 if (s == NULL)
9136 set_static_spec_shared (&linker_name_spec, "ld");
9139 #if HAVE_LTO_PLUGIN > 0
9140 #if HAVE_LTO_PLUGIN == 2
9141 if (!switch_matches (fno_use_linker_plugin,
9142 fno_use_linker_plugin
9143 + strlen (fno_use_linker_plugin), 0))
9144 #else
9145 if (switch_matches (fuse_linker_plugin,
9146 fuse_linker_plugin
9147 + strlen (fuse_linker_plugin), 0))
9148 #endif
9150 char *temp_spec = find_a_file (&exec_prefixes,
9151 LTOPLUGINSONAME, R_OK,
9152 false);
9153 if (!temp_spec)
9154 fatal_error (input_location,
9155 "%<-fuse-linker-plugin%>, but %s not found",
9156 LTOPLUGINSONAME);
9157 linker_plugin_file_spec = convert_white_space (temp_spec);
9159 #endif
9160 set_static_spec_shared (&lto_gcc_spec, argv0);
9163 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
9164 for collect. */
9165 putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH", false);
9166 putenv_from_prefixes (&startfile_prefixes, LIBRARY_PATH_ENV, true);
9168 if (print_subprocess_help == 1)
9170 printf (_("\nLinker options\n==============\n\n"));
9171 printf (_("Use \"-Wl,OPTION\" to pass \"OPTION\""
9172 " to the linker.\n\n"));
9173 fflush (stdout);
9175 int value = do_spec (link_command_spec);
9176 if (value < 0)
9177 errorcount = 1;
9178 linker_was_run = (tmp != execution_count);
9181 /* If options said don't run linker,
9182 complain about input files to be given to the linker. */
9184 if (! linker_was_run && !seen_error ())
9185 for (i = 0; (int) i < n_infiles; i++)
9186 if (explicit_link_files[i]
9187 && !(infiles[i].language && infiles[i].language[0] == '*'))
9189 warning (0, "%s: linker input file unused because linking not done",
9190 outfiles[i]);
9191 if (access (outfiles[i], F_OK) < 0)
9192 /* This is can be an indication the user specifed an errorneous
9193 separated option value, (or used the wrong prefix for an
9194 option). */
9195 error ("%s: linker input file not found: %m", outfiles[i]);
9199 /* The end of "main". */
9201 void
9202 driver::final_actions () const
9204 /* Delete some or all of the temporary files we made. */
9206 if (seen_error ())
9207 delete_failure_queue ();
9208 delete_temp_files ();
9210 if (print_help_list)
9212 printf (("\nFor bug reporting instructions, please see:\n"));
9213 printf ("%s\n", bug_report_url);
9217 /* Detect whether jobserver is active and working. If not drop
9218 --jobserver-auth from MAKEFLAGS. */
9220 void
9221 driver::detect_jobserver () const
9223 jobserver_info jinfo;
9224 if (!jinfo.is_active && !jinfo.skipped_makeflags.empty ())
9225 xputenv (xstrdup (jinfo.skipped_makeflags.c_str ()));
9228 /* Determine what the exit code of the driver should be. */
9231 driver::get_exit_code () const
9233 return (signal_count != 0 ? 2
9234 : seen_error () ? (pass_exit_codes ? greatest_status : 1)
9235 : 0);
9238 /* Find the proper compilation spec for the file name NAME,
9239 whose length is LENGTH. LANGUAGE is the specified language,
9240 or 0 if this file is to be passed to the linker. */
9242 static struct compiler *
9243 lookup_compiler (const char *name, size_t length, const char *language)
9245 struct compiler *cp;
9247 /* If this was specified by the user to be a linker input, indicate that. */
9248 if (language != 0 && language[0] == '*')
9249 return 0;
9251 /* Otherwise, look for the language, if one is spec'd. */
9252 if (language != 0)
9254 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
9255 if (cp->suffix[0] == '@' && !strcmp (cp->suffix + 1, language))
9257 if (name != NULL && strcmp (name, "-") == 0
9258 && (strcmp (cp->suffix, "@c-header") == 0
9259 || strcmp (cp->suffix, "@c++-header") == 0)
9260 && !have_E)
9261 fatal_error (input_location,
9262 "cannot use %<-%> as input filename for a "
9263 "precompiled header");
9265 return cp;
9268 error ("language %s not recognized", language);
9269 return 0;
9272 /* Look for a suffix. */
9273 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
9275 if (/* The suffix `-' matches only the file name `-'. */
9276 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
9277 || (strlen (cp->suffix) < length
9278 /* See if the suffix matches the end of NAME. */
9279 && !strcmp (cp->suffix,
9280 name + length - strlen (cp->suffix))
9282 break;
9285 #if defined (OS2) ||defined (HAVE_DOS_BASED_FILE_SYSTEM)
9286 /* Look again, but case-insensitively this time. */
9287 if (cp < compilers)
9288 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
9290 if (/* The suffix `-' matches only the file name `-'. */
9291 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
9292 || (strlen (cp->suffix) < length
9293 /* See if the suffix matches the end of NAME. */
9294 && ((!strcmp (cp->suffix,
9295 name + length - strlen (cp->suffix))
9296 || !strpbrk (cp->suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
9297 && !strcasecmp (cp->suffix,
9298 name + length - strlen (cp->suffix)))
9300 break;
9302 #endif
9304 if (cp >= compilers)
9306 if (cp->spec[0] != '@')
9307 /* A non-alias entry: return it. */
9308 return cp;
9310 /* An alias entry maps a suffix to a language.
9311 Search for the language; pass 0 for NAME and LENGTH
9312 to avoid infinite recursion if language not found. */
9313 return lookup_compiler (NULL, 0, cp->spec + 1);
9315 return 0;
9318 static char *
9319 save_string (const char *s, int len)
9321 char *result = XNEWVEC (char, len + 1);
9323 gcc_checking_assert (strlen (s) >= (unsigned int) len);
9324 memcpy (result, s, len);
9325 result[len] = 0;
9326 return result;
9330 static inline void
9331 validate_switches_from_spec (const char *spec, bool user)
9333 const char *p = spec;
9334 char c;
9335 while ((c = *p++))
9336 if (c == '%'
9337 && (*p == '{'
9338 || *p == '<'
9339 || (*p == 'W' && *++p == '{')
9340 || (*p == '@' && *++p == '{')))
9341 /* We have a switch spec. */
9342 p = validate_switches (p + 1, user, *p == '{');
9345 static void
9346 validate_all_switches (void)
9348 struct compiler *comp;
9349 struct spec_list *spec;
9351 for (comp = compilers; comp->spec; comp++)
9352 validate_switches_from_spec (comp->spec, false);
9354 /* Look through the linked list of specs read from the specs file. */
9355 for (spec = specs; spec; spec = spec->next)
9356 validate_switches_from_spec (*spec->ptr_spec, spec->user_p);
9358 validate_switches_from_spec (link_command_spec, false);
9361 /* Look at the switch-name that comes after START and mark as valid
9362 all supplied switches that match it. If BRACED, handle other
9363 switches after '|' and '&', and specs after ':' until ';' or '}',
9364 going back for more switches after ';'. Without BRACED, handle
9365 only one atom. Return a pointer to whatever follows the handled
9366 items, after the closing brace if BRACED. */
9368 static const char *
9369 validate_switches (const char *start, bool user_spec, bool braced)
9371 const char *p = start;
9372 const char *atom;
9373 size_t len;
9374 int i;
9375 bool suffix;
9376 bool starred;
9378 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
9380 next_member:
9381 suffix = false;
9382 starred = false;
9384 SKIP_WHITE ();
9386 if (*p == '!')
9387 p++;
9389 SKIP_WHITE ();
9390 if (*p == '.' || *p == ',')
9391 suffix = true, p++;
9393 atom = p;
9394 while (ISIDNUM (*p) || *p == '-' || *p == '+' || *p == '='
9395 || *p == ',' || *p == '.' || *p == '@')
9396 p++;
9397 len = p - atom;
9399 if (*p == '*')
9400 starred = true, p++;
9402 SKIP_WHITE ();
9404 if (!suffix)
9406 /* Mark all matching switches as valid. */
9407 for (i = 0; i < n_switches; i++)
9408 if (!strncmp (switches[i].part1, atom, len)
9409 && (starred || switches[i].part1[len] == '\0')
9410 && (switches[i].known || user_spec))
9411 switches[i].validated = true;
9414 if (!braced)
9415 return p;
9417 if (*p) p++;
9418 if (*p && (p[-1] == '|' || p[-1] == '&'))
9419 goto next_member;
9421 if (*p && p[-1] == ':')
9423 while (*p && *p != ';' && *p != '}')
9425 if (*p == '%')
9427 p++;
9428 if (*p == '{' || *p == '<')
9429 p = validate_switches (p+1, user_spec, *p == '{');
9430 else if (p[0] == 'W' && p[1] == '{')
9431 p = validate_switches (p+2, user_spec, true);
9432 else if (p[0] == '@' && p[1] == '{')
9433 p = validate_switches (p+2, user_spec, true);
9435 else
9436 p++;
9439 if (*p) p++;
9440 if (*p && p[-1] == ';')
9441 goto next_member;
9444 return p;
9445 #undef SKIP_WHITE
9448 struct mdswitchstr
9450 const char *str;
9451 int len;
9454 static struct mdswitchstr *mdswitches;
9455 static int n_mdswitches;
9457 /* Check whether a particular argument was used. The first time we
9458 canonicalize the switches to keep only the ones we care about. */
9460 struct used_arg_t
9462 public:
9463 int operator () (const char *p, int len);
9464 void finalize ();
9466 private:
9467 struct mswitchstr
9469 const char *str;
9470 const char *replace;
9471 int len;
9472 int rep_len;
9475 mswitchstr *mswitches;
9476 int n_mswitches;
9480 used_arg_t used_arg;
9483 used_arg_t::operator () (const char *p, int len)
9485 int i, j;
9487 if (!mswitches)
9489 struct mswitchstr *matches;
9490 const char *q;
9491 int cnt = 0;
9493 /* Break multilib_matches into the component strings of string
9494 and replacement string. */
9495 for (q = multilib_matches; *q != '\0'; q++)
9496 if (*q == ';')
9497 cnt++;
9499 matches
9500 = (struct mswitchstr *) alloca ((sizeof (struct mswitchstr)) * cnt);
9501 i = 0;
9502 q = multilib_matches;
9503 while (*q != '\0')
9505 matches[i].str = q;
9506 while (*q != ' ')
9508 if (*q == '\0')
9510 invalid_matches:
9511 fatal_error (input_location, "multilib spec %qs is invalid",
9512 multilib_matches);
9514 q++;
9516 matches[i].len = q - matches[i].str;
9518 matches[i].replace = ++q;
9519 while (*q != ';' && *q != '\0')
9521 if (*q == ' ')
9522 goto invalid_matches;
9523 q++;
9525 matches[i].rep_len = q - matches[i].replace;
9526 i++;
9527 if (*q == ';')
9528 q++;
9531 /* Now build a list of the replacement string for switches that we care
9532 about. Make sure we allocate at least one entry. This prevents
9533 xmalloc from calling fatal, and prevents us from re-executing this
9534 block of code. */
9535 mswitches
9536 = XNEWVEC (struct mswitchstr, n_mdswitches + (n_switches ? n_switches : 1));
9537 for (i = 0; i < n_switches; i++)
9538 if ((switches[i].live_cond & SWITCH_IGNORE) == 0)
9540 int xlen = strlen (switches[i].part1);
9541 for (j = 0; j < cnt; j++)
9542 if (xlen == matches[j].len
9543 && ! strncmp (switches[i].part1, matches[j].str, xlen))
9545 mswitches[n_mswitches].str = matches[j].replace;
9546 mswitches[n_mswitches].len = matches[j].rep_len;
9547 mswitches[n_mswitches].replace = (char *) 0;
9548 mswitches[n_mswitches].rep_len = 0;
9549 n_mswitches++;
9550 break;
9554 /* Add MULTILIB_DEFAULTS switches too, as long as they were not present
9555 on the command line nor any options mutually incompatible with
9556 them. */
9557 for (i = 0; i < n_mdswitches; i++)
9559 const char *r;
9561 for (q = multilib_options; *q != '\0'; *q && q++)
9563 while (*q == ' ')
9564 q++;
9566 r = q;
9567 while (strncmp (q, mdswitches[i].str, mdswitches[i].len) != 0
9568 || strchr (" /", q[mdswitches[i].len]) == NULL)
9570 while (*q != ' ' && *q != '/' && *q != '\0')
9571 q++;
9572 if (*q != '/')
9573 break;
9574 q++;
9577 if (*q != ' ' && *q != '\0')
9579 while (*r != ' ' && *r != '\0')
9581 q = r;
9582 while (*q != ' ' && *q != '/' && *q != '\0')
9583 q++;
9585 if (used_arg (r, q - r))
9586 break;
9588 if (*q != '/')
9590 mswitches[n_mswitches].str = mdswitches[i].str;
9591 mswitches[n_mswitches].len = mdswitches[i].len;
9592 mswitches[n_mswitches].replace = (char *) 0;
9593 mswitches[n_mswitches].rep_len = 0;
9594 n_mswitches++;
9595 break;
9598 r = q + 1;
9600 break;
9606 for (i = 0; i < n_mswitches; i++)
9607 if (len == mswitches[i].len && ! strncmp (p, mswitches[i].str, len))
9608 return 1;
9610 return 0;
9613 void used_arg_t::finalize ()
9615 XDELETEVEC (mswitches);
9616 mswitches = NULL;
9617 n_mswitches = 0;
9621 static int
9622 default_arg (const char *p, int len)
9624 int i;
9626 for (i = 0; i < n_mdswitches; i++)
9627 if (len == mdswitches[i].len && ! strncmp (p, mdswitches[i].str, len))
9628 return 1;
9630 return 0;
9633 /* Work out the subdirectory to use based on the options. The format of
9634 multilib_select is a list of elements. Each element is a subdirectory
9635 name followed by a list of options followed by a semicolon. The format
9636 of multilib_exclusions is the same, but without the preceding
9637 directory. First gcc will check the exclusions, if none of the options
9638 beginning with an exclamation point are present, and all of the other
9639 options are present, then we will ignore this completely. Passing
9640 that, gcc will consider each multilib_select in turn using the same
9641 rules for matching the options. If a match is found, that subdirectory
9642 will be used.
9643 A subdirectory name is optionally followed by a colon and the corresponding
9644 multiarch name. */
9646 static void
9647 set_multilib_dir (void)
9649 const char *p;
9650 unsigned int this_path_len;
9651 const char *this_path, *this_arg;
9652 const char *start, *end;
9653 int not_arg;
9654 int ok, ndfltok, first;
9656 n_mdswitches = 0;
9657 start = multilib_defaults;
9658 while (*start == ' ' || *start == '\t')
9659 start++;
9660 while (*start != '\0')
9662 n_mdswitches++;
9663 while (*start != ' ' && *start != '\t' && *start != '\0')
9664 start++;
9665 while (*start == ' ' || *start == '\t')
9666 start++;
9669 if (n_mdswitches)
9671 int i = 0;
9673 mdswitches = XNEWVEC (struct mdswitchstr, n_mdswitches);
9674 for (start = multilib_defaults; *start != '\0'; start = end + 1)
9676 while (*start == ' ' || *start == '\t')
9677 start++;
9679 if (*start == '\0')
9680 break;
9682 for (end = start + 1;
9683 *end != ' ' && *end != '\t' && *end != '\0'; end++)
9686 obstack_grow (&multilib_obstack, start, end - start);
9687 obstack_1grow (&multilib_obstack, 0);
9688 mdswitches[i].str = XOBFINISH (&multilib_obstack, const char *);
9689 mdswitches[i++].len = end - start;
9691 if (*end == '\0')
9692 break;
9696 p = multilib_exclusions;
9697 while (*p != '\0')
9699 /* Ignore newlines. */
9700 if (*p == '\n')
9702 ++p;
9703 continue;
9706 /* Check the arguments. */
9707 ok = 1;
9708 while (*p != ';')
9710 if (*p == '\0')
9712 invalid_exclusions:
9713 fatal_error (input_location, "multilib exclusions %qs is invalid",
9714 multilib_exclusions);
9717 if (! ok)
9719 ++p;
9720 continue;
9723 this_arg = p;
9724 while (*p != ' ' && *p != ';')
9726 if (*p == '\0')
9727 goto invalid_exclusions;
9728 ++p;
9731 if (*this_arg != '!')
9732 not_arg = 0;
9733 else
9735 not_arg = 1;
9736 ++this_arg;
9739 ok = used_arg (this_arg, p - this_arg);
9740 if (not_arg)
9741 ok = ! ok;
9743 if (*p == ' ')
9744 ++p;
9747 if (ok)
9748 return;
9750 ++p;
9753 first = 1;
9754 p = multilib_select;
9756 /* Append multilib reuse rules if any. With those rules, we can reuse
9757 one multilib for certain different options sets. */
9758 if (strlen (multilib_reuse) > 0)
9759 p = concat (p, multilib_reuse, NULL);
9761 while (*p != '\0')
9763 /* Ignore newlines. */
9764 if (*p == '\n')
9766 ++p;
9767 continue;
9770 /* Get the initial path. */
9771 this_path = p;
9772 while (*p != ' ')
9774 if (*p == '\0')
9776 invalid_select:
9777 fatal_error (input_location, "multilib select %qs %qs is invalid",
9778 multilib_select, multilib_reuse);
9780 ++p;
9782 this_path_len = p - this_path;
9784 /* Check the arguments. */
9785 ok = 1;
9786 ndfltok = 1;
9787 ++p;
9788 while (*p != ';')
9790 if (*p == '\0')
9791 goto invalid_select;
9793 if (! ok)
9795 ++p;
9796 continue;
9799 this_arg = p;
9800 while (*p != ' ' && *p != ';')
9802 if (*p == '\0')
9803 goto invalid_select;
9804 ++p;
9807 if (*this_arg != '!')
9808 not_arg = 0;
9809 else
9811 not_arg = 1;
9812 ++this_arg;
9815 /* If this is a default argument, we can just ignore it.
9816 This is true even if this_arg begins with '!'. Beginning
9817 with '!' does not mean that this argument is necessarily
9818 inappropriate for this library: it merely means that
9819 there is a more specific library which uses this
9820 argument. If this argument is a default, we need not
9821 consider that more specific library. */
9822 ok = used_arg (this_arg, p - this_arg);
9823 if (not_arg)
9824 ok = ! ok;
9826 if (! ok)
9827 ndfltok = 0;
9829 if (default_arg (this_arg, p - this_arg))
9830 ok = 1;
9832 if (*p == ' ')
9833 ++p;
9836 if (ok && first)
9838 if (this_path_len != 1
9839 || this_path[0] != '.')
9841 char *new_multilib_dir = XNEWVEC (char, this_path_len + 1);
9842 char *q;
9844 strncpy (new_multilib_dir, this_path, this_path_len);
9845 new_multilib_dir[this_path_len] = '\0';
9846 q = strchr (new_multilib_dir, ':');
9847 if (q != NULL)
9848 *q = '\0';
9849 multilib_dir = new_multilib_dir;
9851 first = 0;
9854 if (ndfltok)
9856 const char *q = this_path, *end = this_path + this_path_len;
9858 while (q < end && *q != ':')
9859 q++;
9860 if (q < end)
9862 const char *q2 = q + 1, *ml_end = end;
9863 char *new_multilib_os_dir;
9865 while (q2 < end && *q2 != ':')
9866 q2++;
9867 if (*q2 == ':')
9868 ml_end = q2;
9869 if (ml_end - q == 1)
9870 multilib_os_dir = xstrdup (".");
9871 else
9873 new_multilib_os_dir = XNEWVEC (char, ml_end - q);
9874 memcpy (new_multilib_os_dir, q + 1, ml_end - q - 1);
9875 new_multilib_os_dir[ml_end - q - 1] = '\0';
9876 multilib_os_dir = new_multilib_os_dir;
9879 if (q2 < end && *q2 == ':')
9881 char *new_multiarch_dir = XNEWVEC (char, end - q2);
9882 memcpy (new_multiarch_dir, q2 + 1, end - q2 - 1);
9883 new_multiarch_dir[end - q2 - 1] = '\0';
9884 multiarch_dir = new_multiarch_dir;
9886 break;
9890 ++p;
9893 multilib_dir =
9894 targetm_common.compute_multilib (
9895 switches,
9896 n_switches,
9897 multilib_dir,
9898 multilib_defaults,
9899 multilib_select,
9900 multilib_matches,
9901 multilib_exclusions,
9902 multilib_reuse);
9904 if (multilib_dir == NULL && multilib_os_dir != NULL
9905 && strcmp (multilib_os_dir, ".") == 0)
9907 free (CONST_CAST (char *, multilib_os_dir));
9908 multilib_os_dir = NULL;
9910 else if (multilib_dir != NULL && multilib_os_dir == NULL)
9911 multilib_os_dir = multilib_dir;
9914 /* Print out the multiple library subdirectory selection
9915 information. This prints out a series of lines. Each line looks
9916 like SUBDIRECTORY;@OPTION@OPTION, with as many options as is
9917 required. Only the desired options are printed out, the negative
9918 matches. The options are print without a leading dash. There are
9919 no spaces to make it easy to use the information in the shell.
9920 Each subdirectory is printed only once. This assumes the ordering
9921 generated by the genmultilib script. Also, we leave out ones that match
9922 the exclusions. */
9924 static void
9925 print_multilib_info (void)
9927 const char *p = multilib_select;
9928 const char *last_path = 0, *this_path;
9929 int skip;
9930 int not_arg;
9931 unsigned int last_path_len = 0;
9933 while (*p != '\0')
9935 skip = 0;
9936 /* Ignore newlines. */
9937 if (*p == '\n')
9939 ++p;
9940 continue;
9943 /* Get the initial path. */
9944 this_path = p;
9945 while (*p != ' ')
9947 if (*p == '\0')
9949 invalid_select:
9950 fatal_error (input_location,
9951 "multilib select %qs is invalid", multilib_select);
9954 ++p;
9957 /* When --disable-multilib was used but target defines
9958 MULTILIB_OSDIRNAMES, entries starting with .: (and not starting
9959 with .:: for multiarch configurations) are there just to find
9960 multilib_os_dir, so skip them from output. */
9961 if (this_path[0] == '.' && this_path[1] == ':' && this_path[2] != ':')
9962 skip = 1;
9964 /* Check for matches with the multilib_exclusions. We don't bother
9965 with the '!' in either list. If any of the exclusion rules match
9966 all of its options with the select rule, we skip it. */
9968 const char *e = multilib_exclusions;
9969 const char *this_arg;
9971 while (*e != '\0')
9973 int m = 1;
9974 /* Ignore newlines. */
9975 if (*e == '\n')
9977 ++e;
9978 continue;
9981 /* Check the arguments. */
9982 while (*e != ';')
9984 const char *q;
9985 int mp = 0;
9987 if (*e == '\0')
9989 invalid_exclusion:
9990 fatal_error (input_location,
9991 "multilib exclusion %qs is invalid",
9992 multilib_exclusions);
9995 if (! m)
9997 ++e;
9998 continue;
10001 this_arg = e;
10003 while (*e != ' ' && *e != ';')
10005 if (*e == '\0')
10006 goto invalid_exclusion;
10007 ++e;
10010 q = p + 1;
10011 while (*q != ';')
10013 const char *arg;
10014 int len = e - this_arg;
10016 if (*q == '\0')
10017 goto invalid_select;
10019 arg = q;
10021 while (*q != ' ' && *q != ';')
10023 if (*q == '\0')
10024 goto invalid_select;
10025 ++q;
10028 if (! strncmp (arg, this_arg,
10029 (len < q - arg) ? q - arg : len)
10030 || default_arg (this_arg, e - this_arg))
10032 mp = 1;
10033 break;
10036 if (*q == ' ')
10037 ++q;
10040 if (! mp)
10041 m = 0;
10043 if (*e == ' ')
10044 ++e;
10047 if (m)
10049 skip = 1;
10050 break;
10053 if (*e != '\0')
10054 ++e;
10058 if (! skip)
10060 /* If this is a duplicate, skip it. */
10061 skip = (last_path != 0
10062 && (unsigned int) (p - this_path) == last_path_len
10063 && ! filename_ncmp (last_path, this_path, last_path_len));
10065 last_path = this_path;
10066 last_path_len = p - this_path;
10069 /* If all required arguments are default arguments, and no default
10070 arguments appear in the ! argument list, then we can skip it.
10071 We will already have printed a directory identical to this one
10072 which does not require that default argument. */
10073 if (! skip)
10075 const char *q;
10076 bool default_arg_ok = false;
10078 q = p + 1;
10079 while (*q != ';')
10081 const char *arg;
10083 if (*q == '\0')
10084 goto invalid_select;
10086 if (*q == '!')
10088 not_arg = 1;
10089 q++;
10091 else
10092 not_arg = 0;
10093 arg = q;
10095 while (*q != ' ' && *q != ';')
10097 if (*q == '\0')
10098 goto invalid_select;
10099 ++q;
10102 if (default_arg (arg, q - arg))
10104 /* Stop checking if any default arguments appeared in not
10105 list. */
10106 if (not_arg)
10108 default_arg_ok = false;
10109 break;
10112 default_arg_ok = true;
10114 else if (!not_arg)
10116 /* Stop checking if any required argument is not provided by
10117 default arguments. */
10118 default_arg_ok = false;
10119 break;
10122 if (*q == ' ')
10123 ++q;
10126 /* Make sure all default argument is OK for this multi-lib set. */
10127 if (default_arg_ok)
10128 skip = 1;
10129 else
10130 skip = 0;
10133 if (! skip)
10135 const char *p1;
10137 for (p1 = last_path; p1 < p && *p1 != ':'; p1++)
10138 putchar (*p1);
10139 putchar (';');
10142 ++p;
10143 while (*p != ';')
10145 int use_arg;
10147 if (*p == '\0')
10148 goto invalid_select;
10150 if (skip)
10152 ++p;
10153 continue;
10156 use_arg = *p != '!';
10158 if (use_arg)
10159 putchar ('@');
10161 while (*p != ' ' && *p != ';')
10163 if (*p == '\0')
10164 goto invalid_select;
10165 if (use_arg)
10166 putchar (*p);
10167 ++p;
10170 if (*p == ' ')
10171 ++p;
10174 if (! skip)
10176 /* If there are extra options, print them now. */
10177 if (multilib_extra && *multilib_extra)
10179 int print_at = true;
10180 const char *q;
10182 for (q = multilib_extra; *q != '\0'; q++)
10184 if (*q == ' ')
10185 print_at = true;
10186 else
10188 if (print_at)
10189 putchar ('@');
10190 putchar (*q);
10191 print_at = false;
10196 putchar ('\n');
10199 ++p;
10203 /* getenv built-in spec function.
10205 Returns the value of the environment variable given by its first argument,
10206 concatenated with the second argument. If the variable is not defined, a
10207 fatal error is issued unless such undefs are internally allowed, in which
10208 case the variable name prefixed by a '/' is used as the variable value.
10210 The leading '/' allows using the result at a spot where a full path would
10211 normally be expected and when the actual value doesn't really matter since
10212 undef vars are allowed. */
10214 static const char *
10215 getenv_spec_function (int argc, const char **argv)
10217 const char *value;
10218 const char *varname;
10220 char *result;
10221 char *ptr;
10222 size_t len;
10224 if (argc != 2)
10225 return NULL;
10227 varname = argv[0];
10228 value = env.get (varname);
10230 /* If the variable isn't defined and this is allowed, craft our expected
10231 return value. Assume variable names used in specs strings don't contain
10232 any active spec character so don't need escaping. */
10233 if (!value && spec_undefvar_allowed)
10235 result = XNEWVAR (char, strlen(varname) + 2);
10236 sprintf (result, "/%s", varname);
10237 return result;
10240 if (!value)
10241 fatal_error (input_location,
10242 "environment variable %qs not defined", varname);
10244 /* We have to escape every character of the environment variable so
10245 they are not interpreted as active spec characters. A
10246 particularly painful case is when we are reading a variable
10247 holding a windows path complete with \ separators. */
10248 len = strlen (value) * 2 + strlen (argv[1]) + 1;
10249 result = XNEWVAR (char, len);
10250 for (ptr = result; *value; ptr += 2)
10252 ptr[0] = '\\';
10253 ptr[1] = *value++;
10256 strcpy (ptr, argv[1]);
10258 return result;
10261 /* if-exists built-in spec function.
10263 Checks to see if the file specified by the absolute pathname in
10264 ARGS exists. Returns that pathname if found.
10266 The usual use for this function is to check for a library file
10267 (whose name has been expanded with %s). */
10269 static const char *
10270 if_exists_spec_function (int argc, const char **argv)
10272 /* Must have only one argument. */
10273 if (argc == 1 && IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
10274 return argv[0];
10276 return NULL;
10279 /* if-exists-else built-in spec function.
10281 This is like if-exists, but takes an additional argument which
10282 is returned if the first argument does not exist. */
10284 static const char *
10285 if_exists_else_spec_function (int argc, const char **argv)
10287 /* Must have exactly two arguments. */
10288 if (argc != 2)
10289 return NULL;
10291 if (IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
10292 return argv[0];
10294 return argv[1];
10297 /* if-exists-then-else built-in spec function.
10299 Checks to see if the file specified by the absolute pathname in
10300 the first arg exists. Returns the second arg if so, otherwise returns
10301 the third arg if it is present. */
10303 static const char *
10304 if_exists_then_else_spec_function (int argc, const char **argv)
10307 /* Must have two or three arguments. */
10308 if (argc != 2 && argc != 3)
10309 return NULL;
10311 if (IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
10312 return argv[1];
10314 if (argc == 3)
10315 return argv[2];
10317 return NULL;
10320 /* sanitize built-in spec function.
10322 This returns non-NULL, if sanitizing address, thread or
10323 any of the undefined behavior sanitizers. */
10325 static const char *
10326 sanitize_spec_function (int argc, const char **argv)
10328 if (argc != 1)
10329 return NULL;
10331 if (strcmp (argv[0], "address") == 0)
10332 return (flag_sanitize & SANITIZE_USER_ADDRESS) ? "" : NULL;
10333 if (strcmp (argv[0], "hwaddress") == 0)
10334 return (flag_sanitize & SANITIZE_USER_HWADDRESS) ? "" : NULL;
10335 if (strcmp (argv[0], "kernel-address") == 0)
10336 return (flag_sanitize & SANITIZE_KERNEL_ADDRESS) ? "" : NULL;
10337 if (strcmp (argv[0], "kernel-hwaddress") == 0)
10338 return (flag_sanitize & SANITIZE_KERNEL_HWADDRESS) ? "" : NULL;
10339 if (strcmp (argv[0], "thread") == 0)
10340 return (flag_sanitize & SANITIZE_THREAD) ? "" : NULL;
10341 if (strcmp (argv[0], "undefined") == 0)
10342 return ((flag_sanitize
10343 & ~flag_sanitize_trap
10344 & (SANITIZE_UNDEFINED | SANITIZE_UNDEFINED_NONDEFAULT)))
10345 ? "" : NULL;
10346 if (strcmp (argv[0], "leak") == 0)
10347 return ((flag_sanitize
10348 & (SANITIZE_ADDRESS | SANITIZE_LEAK | SANITIZE_THREAD))
10349 == SANITIZE_LEAK) ? "" : NULL;
10350 return NULL;
10353 /* replace-outfile built-in spec function.
10355 This looks for the first argument in the outfiles array's name and
10356 replaces it with the second argument. */
10358 static const char *
10359 replace_outfile_spec_function (int argc, const char **argv)
10361 int i;
10362 /* Must have exactly two arguments. */
10363 if (argc != 2)
10364 abort ();
10366 for (i = 0; i < n_infiles; i++)
10368 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
10369 outfiles[i] = xstrdup (argv[1]);
10371 return NULL;
10374 /* remove-outfile built-in spec function.
10376 * This looks for the first argument in the outfiles array's name and
10377 * removes it. */
10379 static const char *
10380 remove_outfile_spec_function (int argc, const char **argv)
10382 int i;
10383 /* Must have exactly one argument. */
10384 if (argc != 1)
10385 abort ();
10387 for (i = 0; i < n_infiles; i++)
10389 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
10390 outfiles[i] = NULL;
10392 return NULL;
10395 /* Given two version numbers, compares the two numbers.
10396 A version number must match the regular expression
10397 ([1-9][0-9]*|0)(\.([1-9][0-9]*|0))*
10399 static int
10400 compare_version_strings (const char *v1, const char *v2)
10402 int rresult;
10403 regex_t r;
10405 if (regcomp (&r, "^([1-9][0-9]*|0)(\\.([1-9][0-9]*|0))*$",
10406 REG_EXTENDED | REG_NOSUB) != 0)
10407 abort ();
10408 rresult = regexec (&r, v1, 0, NULL, 0);
10409 if (rresult == REG_NOMATCH)
10410 fatal_error (input_location, "invalid version number %qs", v1);
10411 else if (rresult != 0)
10412 abort ();
10413 rresult = regexec (&r, v2, 0, NULL, 0);
10414 if (rresult == REG_NOMATCH)
10415 fatal_error (input_location, "invalid version number %qs", v2);
10416 else if (rresult != 0)
10417 abort ();
10419 return strverscmp (v1, v2);
10423 /* version_compare built-in spec function.
10425 This takes an argument of the following form:
10427 <comparison-op> <arg1> [<arg2>] <switch> <result>
10429 and produces "result" if the comparison evaluates to true,
10430 and nothing if it doesn't.
10432 The supported <comparison-op> values are:
10434 >= true if switch is a later (or same) version than arg1
10435 !> opposite of >=
10436 < true if switch is an earlier version than arg1
10437 !< opposite of <
10438 >< true if switch is arg1 or later, and earlier than arg2
10439 <> true if switch is earlier than arg1 or is arg2 or later
10441 If the switch is not present, the condition is false unless
10442 the first character of the <comparison-op> is '!'.
10444 For example,
10445 %:version-compare(>= 10.3 mmacosx-version-min= -lmx)
10446 adds -lmx if -mmacosx-version-min=10.3.9 was passed. */
10448 static const char *
10449 version_compare_spec_function (int argc, const char **argv)
10451 int comp1, comp2;
10452 size_t switch_len;
10453 const char *switch_value = NULL;
10454 int nargs = 1, i;
10455 bool result;
10457 if (argc < 3)
10458 fatal_error (input_location, "too few arguments to %%:version-compare");
10459 if (argv[0][0] == '\0')
10460 abort ();
10461 if ((argv[0][1] == '<' || argv[0][1] == '>') && argv[0][0] != '!')
10462 nargs = 2;
10463 if (argc != nargs + 3)
10464 fatal_error (input_location, "too many arguments to %%:version-compare");
10466 switch_len = strlen (argv[nargs + 1]);
10467 for (i = 0; i < n_switches; i++)
10468 if (!strncmp (switches[i].part1, argv[nargs + 1], switch_len)
10469 && check_live_switch (i, switch_len))
10470 switch_value = switches[i].part1 + switch_len;
10472 if (switch_value == NULL)
10473 comp1 = comp2 = -1;
10474 else
10476 comp1 = compare_version_strings (switch_value, argv[1]);
10477 if (nargs == 2)
10478 comp2 = compare_version_strings (switch_value, argv[2]);
10479 else
10480 comp2 = -1; /* This value unused. */
10483 switch (argv[0][0] << 8 | argv[0][1])
10485 case '>' << 8 | '=':
10486 result = comp1 >= 0;
10487 break;
10488 case '!' << 8 | '<':
10489 result = comp1 >= 0 || switch_value == NULL;
10490 break;
10491 case '<' << 8:
10492 result = comp1 < 0;
10493 break;
10494 case '!' << 8 | '>':
10495 result = comp1 < 0 || switch_value == NULL;
10496 break;
10497 case '>' << 8 | '<':
10498 result = comp1 >= 0 && comp2 < 0;
10499 break;
10500 case '<' << 8 | '>':
10501 result = comp1 < 0 || comp2 >= 0;
10502 break;
10504 default:
10505 fatal_error (input_location,
10506 "unknown operator %qs in %%:version-compare", argv[0]);
10508 if (! result)
10509 return NULL;
10511 return argv[nargs + 2];
10514 /* %:include builtin spec function. This differs from %include in that it
10515 can be nested inside a spec, and thus be conditionalized. It takes
10516 one argument, the filename, and looks for it in the startfile path.
10517 The result is always NULL, i.e. an empty expansion. */
10519 static const char *
10520 include_spec_function (int argc, const char **argv)
10522 char *file;
10524 if (argc != 1)
10525 abort ();
10527 file = find_a_file (&startfile_prefixes, argv[0], R_OK, true);
10528 read_specs (file ? file : argv[0], false, false);
10530 return NULL;
10533 /* %:find-file spec function. This function replaces its argument by
10534 the file found through find_file, that is the -print-file-name gcc
10535 program option. */
10536 static const char *
10537 find_file_spec_function (int argc, const char **argv)
10539 const char *file;
10541 if (argc != 1)
10542 abort ();
10544 file = find_file (argv[0]);
10545 return file;
10549 /* %:find-plugindir spec function. This function replaces its argument
10550 by the -iplugindir=<dir> option. `dir' is found through find_file, that
10551 is the -print-file-name gcc program option. */
10552 static const char *
10553 find_plugindir_spec_function (int argc, const char **argv ATTRIBUTE_UNUSED)
10555 const char *option;
10557 if (argc != 0)
10558 abort ();
10560 option = concat ("-iplugindir=", find_file ("plugin"), NULL);
10561 return option;
10565 /* %:print-asm-header spec function. Print a banner to say that the
10566 following output is from the assembler. */
10568 static const char *
10569 print_asm_header_spec_function (int arg ATTRIBUTE_UNUSED,
10570 const char **argv ATTRIBUTE_UNUSED)
10572 printf (_("Assembler options\n=================\n\n"));
10573 printf (_("Use \"-Wa,OPTION\" to pass \"OPTION\" to the assembler.\n\n"));
10574 fflush (stdout);
10575 return NULL;
10578 /* Get a random number for -frandom-seed */
10580 static unsigned HOST_WIDE_INT
10581 get_random_number (void)
10583 unsigned HOST_WIDE_INT ret = 0;
10584 int fd;
10586 fd = open ("/dev/urandom", O_RDONLY);
10587 if (fd >= 0)
10589 read (fd, &ret, sizeof (HOST_WIDE_INT));
10590 close (fd);
10591 if (ret)
10592 return ret;
10595 /* Get some more or less random data. */
10596 #ifdef HAVE_GETTIMEOFDAY
10598 struct timeval tv;
10600 gettimeofday (&tv, NULL);
10601 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
10603 #else
10605 time_t now = time (NULL);
10607 if (now != (time_t)-1)
10608 ret = (unsigned) now;
10610 #endif
10612 return ret ^ getpid ();
10615 /* %:compare-debug-dump-opt spec function. Save the last argument,
10616 expected to be the last -fdump-final-insns option, or generate a
10617 temporary. */
10619 static const char *
10620 compare_debug_dump_opt_spec_function (int arg,
10621 const char **argv ATTRIBUTE_UNUSED)
10623 char *ret;
10624 char *name;
10625 int which;
10626 static char random_seed[HOST_BITS_PER_WIDE_INT / 4 + 3];
10628 if (arg != 0)
10629 fatal_error (input_location,
10630 "too many arguments to %%:compare-debug-dump-opt");
10632 do_spec_2 ("%{fdump-final-insns=*:%*}", NULL);
10633 do_spec_1 (" ", 0, NULL);
10635 if (argbuf.length () > 0
10636 && strcmp (argv[argbuf.length () - 1], ".") != 0)
10638 if (!compare_debug)
10639 return NULL;
10641 name = xstrdup (argv[argbuf.length () - 1]);
10642 ret = NULL;
10644 else
10646 if (argbuf.length () > 0)
10647 do_spec_2 ("%B.gkd", NULL);
10648 else if (!compare_debug)
10649 return NULL;
10650 else
10651 do_spec_2 ("%{!save-temps*:%g.gkd}%{save-temps*:%B.gkd}", NULL);
10653 do_spec_1 (" ", 0, NULL);
10655 gcc_assert (argbuf.length () > 0);
10657 name = xstrdup (argbuf.last ());
10659 char *arg = quote_spec (xstrdup (name));
10660 ret = concat ("-fdump-final-insns=", arg, NULL);
10661 free (arg);
10664 which = compare_debug < 0;
10665 debug_check_temp_file[which] = name;
10667 if (!which)
10669 unsigned HOST_WIDE_INT value = get_random_number ();
10671 sprintf (random_seed, HOST_WIDE_INT_PRINT_HEX, value);
10674 if (*random_seed)
10676 char *tmp = ret;
10677 ret = concat ("%{!frandom-seed=*:-frandom-seed=", random_seed, "} ",
10678 ret, NULL);
10679 free (tmp);
10682 if (which)
10683 *random_seed = 0;
10685 return ret;
10688 /* %:compare-debug-self-opt spec function. Expands to the options
10689 that are to be passed in the second compilation of
10690 compare-debug. */
10692 static const char *
10693 compare_debug_self_opt_spec_function (int arg,
10694 const char **argv ATTRIBUTE_UNUSED)
10696 if (arg != 0)
10697 fatal_error (input_location,
10698 "too many arguments to %%:compare-debug-self-opt");
10700 if (compare_debug >= 0)
10701 return NULL;
10703 return concat ("\
10704 %<o %<MD %<MMD %<MF* %<MG %<MP %<MQ* %<MT* \
10705 %<fdump-final-insns=* -w -S -o %j \
10706 %{!fcompare-debug-second:-fcompare-debug-second} \
10707 ", compare_debug_opt, NULL);
10710 /* %:pass-through-libs spec function. Finds all -l options and input
10711 file names in the lib spec passed to it, and makes a list of them
10712 prepended with the plugin option to cause them to be passed through
10713 to the final link after all the new object files have been added. */
10715 const char *
10716 pass_through_libs_spec_func (int argc, const char **argv)
10718 char *prepended = xstrdup (" ");
10719 int n;
10720 /* Shlemiel the painter's algorithm. Innately horrible, but at least
10721 we know that there will never be more than a handful of strings to
10722 concat, and it's only once per run, so it's not worth optimising. */
10723 for (n = 0; n < argc; n++)
10725 char *old = prepended;
10726 /* Anything that isn't an option is a full path to an output
10727 file; pass it through if it ends in '.a'. Among options,
10728 pass only -l. */
10729 if (argv[n][0] == '-' && argv[n][1] == 'l')
10731 const char *lopt = argv[n] + 2;
10732 /* Handle both joined and non-joined -l options. If for any
10733 reason there's a trailing -l with no joined or following
10734 arg just discard it. */
10735 if (!*lopt && ++n >= argc)
10736 break;
10737 else if (!*lopt)
10738 lopt = argv[n];
10739 prepended = concat (prepended, "-plugin-opt=-pass-through=-l",
10740 lopt, " ", NULL);
10742 else if (!strcmp (".a", argv[n] + strlen (argv[n]) - 2))
10744 prepended = concat (prepended, "-plugin-opt=-pass-through=",
10745 argv[n], " ", NULL);
10747 if (prepended != old)
10748 free (old);
10750 return prepended;
10753 static bool
10754 not_actual_file_p (const char *name)
10756 return (strcmp (name, "-") == 0
10757 || strcmp (name, HOST_BIT_BUCKET) == 0);
10760 /* %:dumps spec function. Take an optional argument that overrides
10761 the default extension for -dumpbase and -dumpbase-ext.
10762 Return -dumpdir, -dumpbase and -dumpbase-ext, if needed. */
10763 const char *
10764 dumps_spec_func (int argc, const char **argv ATTRIBUTE_UNUSED)
10766 const char *ext = dumpbase_ext;
10767 char *p;
10769 char *args[3] = { NULL, NULL, NULL };
10770 int nargs = 0;
10772 /* Do not compute a default for -dumpbase-ext when -dumpbase was
10773 given explicitly. */
10774 if (dumpbase && *dumpbase && !ext)
10775 ext = "";
10777 if (argc == 1)
10779 /* Do not override the explicitly-specified -dumpbase-ext with
10780 the specs-provided overrider. */
10781 if (!ext)
10782 ext = argv[0];
10784 else if (argc != 0)
10785 fatal_error (input_location, "too many arguments for %%:dumps");
10787 if (dumpdir)
10789 p = quote_spec_arg (xstrdup (dumpdir));
10790 args[nargs++] = concat (" -dumpdir ", p, NULL);
10791 free (p);
10794 if (!ext)
10795 ext = input_basename + basename_length;
10797 /* Use the precomputed outbase, or compute dumpbase from
10798 input_basename, just like %b would. */
10799 char *base;
10801 if (dumpbase && *dumpbase)
10803 base = xstrdup (dumpbase);
10804 p = base + outbase_length;
10805 gcc_checking_assert (strncmp (base, outbase, outbase_length) == 0);
10806 gcc_checking_assert (strcmp (p, ext) == 0);
10808 else if (outbase_length)
10810 base = xstrndup (outbase, outbase_length);
10811 p = NULL;
10813 else
10815 base = xstrndup (input_basename, suffixed_basename_length);
10816 p = base + basename_length;
10819 if (compare_debug < 0 || !p || strcmp (p, ext) != 0)
10821 if (p)
10822 *p = '\0';
10824 const char *gk;
10825 if (compare_debug < 0)
10826 gk = ".gk";
10827 else
10828 gk = "";
10830 p = concat (base, gk, ext, NULL);
10832 free (base);
10833 base = p;
10836 base = quote_spec_arg (base);
10837 args[nargs++] = concat (" -dumpbase ", base, NULL);
10838 free (base);
10840 if (*ext)
10842 p = quote_spec_arg (xstrdup (ext));
10843 args[nargs++] = concat (" -dumpbase-ext ", p, NULL);
10844 free (p);
10847 const char *ret = concat (args[0], args[1], args[2], NULL);
10848 while (nargs > 0)
10849 free (args[--nargs]);
10851 return ret;
10854 /* Returns "" if ARGV[ARGC - 2] is greater than ARGV[ARGC-1].
10855 Otherwise, return NULL. */
10857 static const char *
10858 greater_than_spec_func (int argc, const char **argv)
10860 char *converted;
10862 if (argc == 1)
10863 return NULL;
10865 gcc_assert (argc >= 2);
10867 long arg = strtol (argv[argc - 2], &converted, 10);
10868 gcc_assert (converted != argv[argc - 2]);
10870 long lim = strtol (argv[argc - 1], &converted, 10);
10871 gcc_assert (converted != argv[argc - 1]);
10873 if (arg > lim)
10874 return "";
10876 return NULL;
10879 /* Returns "" if debug_info_level is greater than ARGV[ARGC-1].
10880 Otherwise, return NULL. */
10882 static const char *
10883 debug_level_greater_than_spec_func (int argc, const char **argv)
10885 char *converted;
10887 if (argc != 1)
10888 fatal_error (input_location,
10889 "wrong number of arguments to %%:debug-level-gt");
10891 long arg = strtol (argv[0], &converted, 10);
10892 gcc_assert (converted != argv[0]);
10894 if (debug_info_level > arg)
10895 return "";
10897 return NULL;
10900 /* Returns "" if dwarf_version is greater than ARGV[ARGC-1].
10901 Otherwise, return NULL. */
10903 static const char *
10904 dwarf_version_greater_than_spec_func (int argc, const char **argv)
10906 char *converted;
10908 if (argc != 1)
10909 fatal_error (input_location,
10910 "wrong number of arguments to %%:dwarf-version-gt");
10912 long arg = strtol (argv[0], &converted, 10);
10913 gcc_assert (converted != argv[0]);
10915 if (dwarf_version > arg)
10916 return "";
10918 return NULL;
10921 static void
10922 path_prefix_reset (path_prefix *prefix)
10924 struct prefix_list *iter, *next;
10925 iter = prefix->plist;
10926 while (iter)
10928 next = iter->next;
10929 free (const_cast <char *> (iter->prefix));
10930 XDELETE (iter);
10931 iter = next;
10933 prefix->plist = 0;
10934 prefix->max_len = 0;
10937 /* The function takes 3 arguments: OPTION name, file name and location
10938 where we search for Fortran modules.
10939 When the FILE is found by find_file, return OPTION=path_to_file. */
10941 static const char *
10942 find_fortran_preinclude_file (int argc, const char **argv)
10944 char *result = NULL;
10945 if (argc != 3)
10946 return NULL;
10948 struct path_prefix prefixes = { 0, 0, "preinclude" };
10950 /* Search first for 'finclude' folder location for a header file
10951 installed by the compiler (similar to omp_lib.h). */
10952 add_prefix (&prefixes, argv[2], NULL, 0, 0, 0);
10953 #ifdef TOOL_INCLUDE_DIR
10954 /* Then search: <prefix>/<target>/<include>/finclude */
10955 add_prefix (&prefixes, TOOL_INCLUDE_DIR "/finclude/",
10956 NULL, 0, 0, 0);
10957 #endif
10958 #ifdef NATIVE_SYSTEM_HEADER_DIR
10959 /* Then search: <sysroot>/usr/include/finclude/<multilib> */
10960 add_sysrooted_hdrs_prefix (&prefixes, NATIVE_SYSTEM_HEADER_DIR "/finclude/",
10961 NULL, 0, 0, 0);
10962 #endif
10964 const char *path = find_a_file (&include_prefixes, argv[1], R_OK, false);
10965 if (path != NULL)
10966 result = concat (argv[0], path, NULL);
10967 else
10969 path = find_a_file (&prefixes, argv[1], R_OK, false);
10970 if (path != NULL)
10971 result = concat (argv[0], path, NULL);
10974 path_prefix_reset (&prefixes);
10975 return result;
10978 /* If any character in ORIG fits QUOTE_P (_, P), reallocate the string
10979 so as to precede every one of them with a backslash. Return the
10980 original string or the reallocated one. */
10982 static inline char *
10983 quote_string (char *orig, bool (*quote_p)(char, void *), void *p)
10985 int len, number_of_space = 0;
10987 for (len = 0; orig[len]; len++)
10988 if (quote_p (orig[len], p))
10989 number_of_space++;
10991 if (number_of_space)
10993 char *new_spec = (char *) xmalloc (len + number_of_space + 1);
10994 int j, k;
10995 for (j = 0, k = 0; j <= len; j++, k++)
10997 if (quote_p (orig[j], p))
10998 new_spec[k++] = '\\';
10999 new_spec[k] = orig[j];
11001 free (orig);
11002 return new_spec;
11004 else
11005 return orig;
11008 /* Return true iff C is any of the characters convert_white_space
11009 should quote. */
11011 static inline bool
11012 whitespace_to_convert_p (char c, void *)
11014 return (c == ' ' || c == '\t');
11017 /* Insert backslash before spaces in ORIG (usually a file path), to
11018 avoid being broken by spec parser.
11020 This function is needed as do_spec_1 treats white space (' ' and '\t')
11021 as the end of an argument. But in case of -plugin /usr/gcc install/xxx.so,
11022 the file name should be treated as a single argument rather than being
11023 broken into multiple. Solution is to insert '\\' before the space in a
11024 file name.
11026 This function converts and only converts all occurrence of ' '
11027 to '\\' + ' ' and '\t' to '\\' + '\t'. For example:
11028 "a b" -> "a\\ b"
11029 "a b" -> "a\\ \\ b"
11030 "a\tb" -> "a\\\tb"
11031 "a\\ b" -> "a\\\\ b"
11033 orig: input null-terminating string that was allocated by xalloc. The
11034 memory it points to might be freed in this function. Behavior undefined
11035 if ORIG wasn't xalloced or was freed already at entry.
11037 Return: ORIG if no conversion needed. Otherwise a newly allocated string
11038 that was converted from ORIG. */
11040 static char *
11041 convert_white_space (char *orig)
11043 return quote_string (orig, whitespace_to_convert_p, NULL);
11046 /* Return true iff C matches any of the spec active characters. */
11047 static inline bool
11048 quote_spec_char_p (char c, void *)
11050 switch (c)
11052 case ' ':
11053 case '\t':
11054 case '\n':
11055 case '|':
11056 case '%':
11057 case '\\':
11058 return true;
11060 default:
11061 return false;
11065 /* Like convert_white_space, but deactivate all active spec chars by
11066 quoting them. */
11068 static inline char *
11069 quote_spec (char *orig)
11071 return quote_string (orig, quote_spec_char_p, NULL);
11074 /* Like quote_spec, but also turn an empty string into the spec for an
11075 empty argument. */
11077 static inline char *
11078 quote_spec_arg (char *orig)
11080 if (!*orig)
11082 free (orig);
11083 return xstrdup ("%\"");
11086 return quote_spec (orig);
11089 /* Restore all state within gcc.cc to the initial state, so that the driver
11090 code can be safely re-run in-process.
11092 Many const char * variables are referenced by static specs (see
11093 INIT_STATIC_SPEC above). These variables are restored to their default
11094 values by a simple loop over the static specs.
11096 For other variables, we directly restore them all to their initial
11097 values (often implicitly 0).
11099 Free the various obstacks in this file, along with "opts_obstack"
11100 from opts.cc.
11102 This function also restores any environment variables that were changed. */
11104 void
11105 driver::finalize ()
11107 env.restore ();
11108 diagnostic_finish (global_dc);
11110 is_cpp_driver = 0;
11111 at_file_supplied = 0;
11112 print_help_list = 0;
11113 print_version = 0;
11114 verbose_only_flag = 0;
11115 print_subprocess_help = 0;
11116 use_ld = NULL;
11117 report_times_to_file = NULL;
11118 target_system_root = DEFAULT_TARGET_SYSTEM_ROOT;
11119 target_system_root_changed = 0;
11120 target_sysroot_suffix = 0;
11121 target_sysroot_hdrs_suffix = 0;
11122 save_temps_flag = SAVE_TEMPS_NONE;
11123 save_temps_overrides_dumpdir = false;
11124 dumpdir_trailing_dash_added = false;
11125 free (dumpdir);
11126 free (dumpbase);
11127 free (dumpbase_ext);
11128 free (outbase);
11129 dumpdir = dumpbase = dumpbase_ext = outbase = NULL;
11130 dumpdir_length = outbase_length = 0;
11131 spec_machine = DEFAULT_TARGET_MACHINE;
11132 greatest_status = 1;
11134 obstack_free (&obstack, NULL);
11135 obstack_free (&opts_obstack, NULL); /* in opts.cc */
11136 obstack_free (&collect_obstack, NULL);
11138 link_command_spec = LINK_COMMAND_SPEC;
11140 obstack_free (&multilib_obstack, NULL);
11142 user_specs_head = NULL;
11143 user_specs_tail = NULL;
11145 /* Within the "compilers" vec, the fields "suffix" and "spec" were
11146 statically allocated for the default compilers, but dynamically
11147 allocated for additional compilers. Delete them for the latter. */
11148 for (int i = n_default_compilers; i < n_compilers; i++)
11150 free (const_cast <char *> (compilers[i].suffix));
11151 free (const_cast <char *> (compilers[i].spec));
11153 XDELETEVEC (compilers);
11154 compilers = NULL;
11155 n_compilers = 0;
11157 linker_options.truncate (0);
11158 assembler_options.truncate (0);
11159 preprocessor_options.truncate (0);
11161 path_prefix_reset (&exec_prefixes);
11162 path_prefix_reset (&startfile_prefixes);
11163 path_prefix_reset (&include_prefixes);
11165 machine_suffix = 0;
11166 just_machine_suffix = 0;
11167 gcc_exec_prefix = 0;
11168 gcc_libexec_prefix = 0;
11169 set_static_spec_shared (&md_exec_prefix, MD_EXEC_PREFIX);
11170 set_static_spec_shared (&md_startfile_prefix, MD_STARTFILE_PREFIX);
11171 set_static_spec_shared (&md_startfile_prefix_1, MD_STARTFILE_PREFIX_1);
11172 multilib_dir = 0;
11173 multilib_os_dir = 0;
11174 multiarch_dir = 0;
11176 /* Free any specs dynamically-allocated by set_spec.
11177 These will be at the head of the list, before the
11178 statically-allocated ones. */
11179 if (specs)
11181 while (specs != static_specs)
11183 spec_list *next = specs->next;
11184 free (const_cast <char *> (specs->name));
11185 XDELETE (specs);
11186 specs = next;
11188 specs = 0;
11190 for (unsigned i = 0; i < ARRAY_SIZE (static_specs); i++)
11192 spec_list *sl = &static_specs[i];
11193 if (sl->alloc_p)
11195 free (const_cast <char *> (*(sl->ptr_spec)));
11196 sl->alloc_p = false;
11198 *(sl->ptr_spec) = sl->default_ptr;
11200 #ifdef EXTRA_SPECS
11201 extra_specs = NULL;
11202 #endif
11204 processing_spec_function = 0;
11206 clear_args ();
11208 have_c = 0;
11209 have_o = 0;
11211 temp_names = NULL;
11212 execution_count = 0;
11213 signal_count = 0;
11215 temp_filename = NULL;
11216 temp_filename_length = 0;
11217 always_delete_queue = NULL;
11218 failure_delete_queue = NULL;
11220 XDELETEVEC (switches);
11221 switches = NULL;
11222 n_switches = 0;
11223 n_switches_alloc = 0;
11225 compare_debug = 0;
11226 compare_debug_second = 0;
11227 compare_debug_opt = NULL;
11228 for (int i = 0; i < 2; i++)
11230 switches_debug_check[i] = NULL;
11231 n_switches_debug_check[i] = 0;
11232 n_switches_alloc_debug_check[i] = 0;
11233 debug_check_temp_file[i] = NULL;
11236 XDELETEVEC (infiles);
11237 infiles = NULL;
11238 n_infiles = 0;
11239 n_infiles_alloc = 0;
11241 combine_inputs = false;
11242 added_libraries = 0;
11243 XDELETEVEC (outfiles);
11244 outfiles = NULL;
11245 spec_lang = 0;
11246 last_language_n_infiles = 0;
11247 gcc_input_filename = NULL;
11248 input_file_number = 0;
11249 input_filename_length = 0;
11250 basename_length = 0;
11251 suffixed_basename_length = 0;
11252 input_basename = NULL;
11253 input_suffix = NULL;
11254 /* We don't need to purge "input_stat", just to unset "input_stat_set". */
11255 input_stat_set = 0;
11256 input_file_compiler = NULL;
11257 arg_going = 0;
11258 delete_this_arg = 0;
11259 this_is_output_file = 0;
11260 this_is_library_file = 0;
11261 this_is_linker_script = 0;
11262 input_from_pipe = 0;
11263 suffix_subst = NULL;
11265 mdswitches = NULL;
11266 n_mdswitches = 0;
11268 used_arg.finalize ();
11271 /* PR jit/64810.
11272 Targets can provide configure-time default options in
11273 OPTION_DEFAULT_SPECS. The jit needs to access these, but
11274 they are expressed in the spec language.
11276 Run just enough of the driver to be able to expand these
11277 specs, and then call the callback CB on each
11278 such option. The options strings are *without* a leading
11279 '-' character e.g. ("march=x86-64"). Finally, clean up. */
11281 void
11282 driver_get_configure_time_options (void (*cb) (const char *option,
11283 void *user_data),
11284 void *user_data)
11286 size_t i;
11288 obstack_init (&obstack);
11289 init_opts_obstack ();
11290 n_switches = 0;
11292 for (i = 0; i < ARRAY_SIZE (option_default_specs); i++)
11293 do_option_spec (option_default_specs[i].name,
11294 option_default_specs[i].spec);
11296 for (i = 0; (int) i < n_switches; i++)
11298 gcc_assert (switches[i].part1);
11299 (*cb) (switches[i].part1, user_data);
11302 obstack_free (&opts_obstack, NULL);
11303 obstack_free (&obstack, NULL);
11304 n_switches = 0;