Debian Codegraph @

gcc/gcc.cc

raw
1 /* Compiler driver program that can handle many languages.
2 Copyright (C) 1987-2025 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
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.
10
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.
15
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/>. */
19
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.
25
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". */
29
30 #define INCLUDE_STRING
31 #include "config.h"
32 #include "system.h"
33 #ifdef HOST_HAS_PERSONALITY_ADDR_NO_RANDOMIZE
34 #include <sys/personality.h>
35 #endif
36 #include "coretypes.h"
37 #include "multilib.h" /* before tm.h */
38 #include "tm.h"
39 #include "xregex.h"
40 #include "obstack.h"
41 #include "intl.h"
42 #include "prefix.h"
43 #include "opt-suggestions.h"
44 #include "gcc.h"
45 #include "diagnostic.h"
46 #include "diagnostic-format.h"
47 #include "pretty-print-urlifier.h"
48 #include "flags.h"
49 #include "opts.h"
50 #include "filenames.h"
51 #include "spellcheck.h"
52 #include "opts-jobserver.h"
53 #include "common/common-target.h"
54 #include "gcc-urlifier.h"
55 #include "opts-diagnostic.h"
56
57 #ifndef MATH_LIBRARY
58 #define MATH_LIBRARY "m"
59 #endif
60
61
62 /* Manage the manipulation of env vars.
63
64 We poison "getenv" and "putenv", so that all enviroment-handling is
65 done through this class. Note that poisoning happens in the
66 preprocessor at the identifier level, and doesn't distinguish between
67 env.getenv ();
68 and
69 getenv ();
70 Hence we need to use "get" for the accessor method, not "getenv". */
71
72 struct env_manager
73 {
74 public:
75 void init (bool can_restore, bool debug);
76 const char *get (const char *name);
77 void xput (const char *string);
78 void restore ();
79
80 private:
81 bool m_can_restore;
82 bool m_debug;
83 struct kv
84 {
85 char *m_key;
86 char *m_value;
87 };
88 vec<kv> m_keys;
89
90 };
91
92 /* The singleton instance of class env_manager. */
93
94 static env_manager env;
95
96 /* Initializer for class env_manager.
97
98 We can't do this as a constructor since we have a statically
99 allocated instance ("env" above). */
100
101 void
102 env_manager::init (bool can_restore, bool debug)
103 {
104 m_can_restore = can_restore;
105 m_debug = debug;
106 }
107
108 /* Get the value of NAME within the environment. Essentially
109 a wrapper for ::getenv, but adding logging, and the possibility
110 of caching results. */
111
112 const char *
113 env_manager::get (const char *name)
114 {
115 const char *result = ::getenv (name);
116 if (m_debug)
117 fprintf (stderr, "env_manager::getenv (%s) -> %s\n", name, result);
118 return result;
119 }
120
121 /* Put the given KEY=VALUE entry STRING into the environment.
122 If the env_manager was initialized with CAN_RESTORE set, then
123 also record the old value of KEY within the environment, so that it
124 can be later restored. */
125
126 void
127 env_manager::xput (const char *string)
128 {
129 if (m_debug)
130 fprintf (stderr, "env_manager::xput (%s)\n", string);
131 if (verbose_flag)
132 fnotice (stderr, "%s\n", string);
133
134 if (m_can_restore)
135 {
136 char *equals = strchr (const_cast <char *> (string), '=');
137 gcc_assert (equals);
138
139 struct kv kv;
140 kv.m_key = xstrndup (string, equals - string);
141 const char *cur_value = ::getenv (kv.m_key);
142 if (m_debug)
143 fprintf (stderr, "saving old value: %s\n",cur_value);
144 kv.m_value = cur_value ? xstrdup (cur_value) : NULL;
145 m_keys.safe_push (kv);
146 }
147
148 ::putenv (CONST_CAST (char *, string));
149 }
150
151 /* Undo any xputenv changes made since last restore.
152 Can only be called if the env_manager was initialized with
153 CAN_RESTORE enabled. */
154
155 void
156 env_manager::restore ()
157 {
158 unsigned int i;
159 struct kv *item;
160
161 gcc_assert (m_can_restore);
162
163 FOR_EACH_VEC_ELT_REVERSE (m_keys, i, item)
164 {
165 if (m_debug)
166 printf ("restoring saved key: %s value: %s\n", item->m_key, item->m_value);
167 if (item->m_value)
168 ::setenv (item->m_key, item->m_value, 1);
169 else
170 ::unsetenv (item->m_key);
171 free (item->m_key);
172 free (item->m_value);
173 }
174
175 m_keys.truncate (0);
176 }
177
178 /* Forbid other uses of getenv and putenv. */
179 #if (GCC_VERSION >= 3000)
180 #pragma GCC poison getenv putenv
181 #endif
182
183
184
185 /* By default there is no special suffix for target executables. */
186 #ifdef TARGET_EXECUTABLE_SUFFIX
187 #define HAVE_TARGET_EXECUTABLE_SUFFIX
188 #else
189 #define TARGET_EXECUTABLE_SUFFIX ""
190 #endif
191
192 /* By default there is no special suffix for host executables. */
193 #ifdef HOST_EXECUTABLE_SUFFIX
194 #define HAVE_HOST_EXECUTABLE_SUFFIX
195 #else
196 #define HOST_EXECUTABLE_SUFFIX ""
197 #endif
198
199 /* By default, the suffix for target object files is ".o". */
200 #ifdef TARGET_OBJECT_SUFFIX
201 #define HAVE_TARGET_OBJECT_SUFFIX
202 #else
203 #define TARGET_OBJECT_SUFFIX ".o"
204 #endif
205
206 static const char dir_separator_str[] = { DIR_SEPARATOR, 0 };
207
208 /* Most every one is fine with LIBRARY_PATH. For some, it conflicts. */
209 #ifndef LIBRARY_PATH_ENV
210 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
211 #endif
212
213 /* If a stage of compilation returns an exit status >= 1,
214 compilation of that file ceases. */
215
216 #define MIN_FATAL_STATUS 1
217
218 /* Flag set by cppspec.cc to 1. */
219 int is_cpp_driver;
220
221 /* Flag set to nonzero if an @file argument has been supplied to gcc. */
222 static bool at_file_supplied;
223
224 /* Definition of string containing the arguments given to configure. */
225 #include "configargs.h"
226
227 /* Flag saying to print the command line options understood by gcc and its
228 sub-processes. */
229
230 static int print_help_list;
231
232 /* Flag saying to print the version of gcc and its sub-processes. */
233
234 static int print_version;
235
236 /* Flag that stores string prefix for which we provide bash completion. */
237
238 static const char *completion = NULL;
239
240 /* Flag indicating whether we should ONLY print the command and
241 arguments (like verbose_flag) without executing the command.
242 Displayed arguments are quoted so that the generated command
243 line is suitable for execution. This is intended for use in
244 shell scripts to capture the driver-generated command line. */
245 static int verbose_only_flag;
246
247 /* Flag indicating how to print command line options of sub-processes. */
248
249 static int print_subprocess_help;
250
251 /* Linker suffix passed to -fuse-ld=... */
252 static const char *use_ld;
253
254 /* Whether we should report subprocess execution times to a file. */
255
256 FILE *report_times_to_file = NULL;
257
258 /* Nonzero means place this string before uses of /, so that include
259 and library files can be found in an alternate location. */
260
261 #ifdef TARGET_SYSTEM_ROOT
262 #define DEFAULT_TARGET_SYSTEM_ROOT (TARGET_SYSTEM_ROOT)
263 #else
264 #define DEFAULT_TARGET_SYSTEM_ROOT (0)
265 #endif
266 static const char *target_system_root = DEFAULT_TARGET_SYSTEM_ROOT;
267
268 /* Nonzero means pass the updated target_system_root to the compiler. */
269
270 static int target_system_root_changed;
271
272 /* Nonzero means append this string to target_system_root. */
273
274 static const char *target_sysroot_suffix = 0;
275
276 /* Nonzero means append this string to target_system_root for headers. */
277
278 static const char *target_sysroot_hdrs_suffix = 0;
279
280 /* Nonzero means write "temp" files in source directory
281 and use the source file's name in them, and don't delete them. */
282
283 static enum save_temps {
284 SAVE_TEMPS_NONE, /* no -save-temps */
285 SAVE_TEMPS_CWD, /* -save-temps in current directory */
286 SAVE_TEMPS_DUMP, /* -save-temps in dumpdir */
287 SAVE_TEMPS_OBJ /* -save-temps in object directory */
288 } save_temps_flag;
289
290 /* Set this iff the dumppfx implied by a -save-temps=* option is to
291 override a -dumpdir option, if any. */
292 static bool save_temps_overrides_dumpdir = false;
293
294 /* -dumpdir, -dumpbase and -dumpbase-ext flags passed in, possibly
295 rearranged as they are to be passed down, e.g., dumpbase and
296 dumpbase_ext may be cleared if integrated with dumpdir or
297 dropped. */
298 static char *dumpdir, *dumpbase, *dumpbase_ext;
299
300 /* Usually the length of the string in dumpdir. However, during
301 linking, it may be shortened to omit a driver-added trailing dash,
302 by then replaced with a trailing period, that is still to be passed
303 to sub-processes in -dumpdir, but not to be generally used in spec
304 filename expansions. See maybe_run_linker. */
305 static size_t dumpdir_length = 0;
306
307 /* Set if the last character in dumpdir is (or was) a dash that the
308 driver added to dumpdir after dumpbase or linker output name. */
309 static bool dumpdir_trailing_dash_added = false;
310
311 /* True if -r, -shared, -pie, -no-pie, -z lazy, or -z norelro were
312 specified on the command line, and therefore -fhardened should not
313 add -z now/relro. */
314 static bool avoid_linker_hardening_p;
315
316 /* True if -static was specified on the command line. */
317 static bool static_p;
318
319 /* Basename of dump and aux outputs, computed from dumpbase (given or
320 derived from output name), to override input_basename in non-%w %b
321 et al. */
322 static char *outbase;
323 static size_t outbase_length = 0;
324
325 /* The compiler version. */
326
327 static const char *compiler_version;
328
329 /* The target version. */
330
331 static const char *const spec_version = DEFAULT_TARGET_VERSION;
332
333 /* The target machine. */
334
335 static const char *spec_machine = DEFAULT_TARGET_MACHINE;
336 static const char *spec_host_machine = DEFAULT_REAL_TARGET_MACHINE;
337
338 /* List of offload targets. Separated by colon. Empty string for
339 -foffload=disable. */
340
341 static char *offload_targets = NULL;
342
343 #if OFFLOAD_DEFAULTED
344 /* Set to true if -foffload has not been used and offload_targets
345 is set to the configured in default. */
346 static bool offload_targets_default;
347 #endif
348
349 /* Nonzero if cross-compiling.
350 When -b is used, the value comes from the `specs' file. */
351
352 #ifdef CROSS_DIRECTORY_STRUCTURE
353 static const char *cross_compile = "1";
354 #else
355 static const char *cross_compile = "0";
356 #endif
357
358 /* Greatest exit code of sub-processes that has been encountered up to
359 now. */
360 static int greatest_status = 1;
361
362 /* This is the obstack which we use to allocate many strings. */
363
364 static struct obstack obstack;
365
366 /* This is the obstack to build an environment variable to pass to
367 collect2 that describes all of the relevant switches of what to
368 pass the compiler in building the list of pointers to constructors
369 and destructors. */
370
371 static struct obstack collect_obstack;
372
373 /* Forward declaration for prototypes. */
374 struct path_prefix;
375 struct prefix_list;
376
377 static void init_spec (void);
378 static void store_arg (const char *, int, int);
379 static void insert_wrapper (const char *);
380 static char *load_specs (const char *);
381 static void read_specs (const char *, bool, bool);
382 static void set_spec (const char *, const char *, bool);
383 static struct compiler *lookup_compiler (const char *, size_t, const char *);
384 static char *build_search_list (const struct path_prefix *, const char *,
385 bool, bool);
386 static void xputenv (const char *);
387 static void putenv_from_prefixes (const struct path_prefix *, const char *,
388 bool);
389 static int access_check (const char *, int);
390 static char *find_a_file (const struct path_prefix *, const char *, int, bool);
391 static char *find_a_program (const char *);
392 static void add_prefix (struct path_prefix *, const char *, const char *,
393 int, int, int);
394 static void add_sysrooted_prefix (struct path_prefix *, const char *,
395 const char *, int, int, int);
396 static char *skip_whitespace (char *);
397 static void delete_if_ordinary (const char *);
398 static void delete_temp_files (void);
399 static void delete_failure_queue (void);
400 static void clear_failure_queue (void);
401 static int check_live_switch (int, int);
402 static const char *handle_braces (const char *);
403 static inline bool input_suffix_matches (const char *, const char *);
404 static inline bool switch_matches (const char *, const char *, int);
405 static inline void mark_matching_switches (const char *, const char *, int);
406 static inline void process_marked_switches (void);
407 static const char *process_brace_body (const char *, const char *, const char *, int, int);
408 static const struct spec_function *lookup_spec_function (const char *);
409 static const char *eval_spec_function (const char *, const char *, const char *);
410 static const char *handle_spec_function (const char *, bool *, const char *);
411 static char *save_string (const char *, int);
412 static void set_collect_gcc_options (void);
413 static int do_spec_1 (const char *, int, const char *);
414 static int do_spec_2 (const char *, const char *);
415 static void do_option_spec (const char *, const char *);
416 static void do_self_spec (const char *);
417 static const char *find_file (const char *);
418 static int is_directory (const char *);
419 static const char *validate_switches (const char *, bool, bool);
420 static void validate_all_switches (void);
421 static inline void validate_switches_from_spec (const char *, bool);
422 static void give_switch (int, int);
423 static int default_arg (const char *, int);
424 static void set_multilib_dir (void);
425 static void print_multilib_info (void);
426 static void display_help (void);
427 static void add_preprocessor_option (const char *, int);
428 static void add_assembler_option (const char *, int);
429 static void add_linker_option (const char *, int);
430 static void process_command (unsigned int, struct cl_decoded_option *);
431 static int execute (void);
432 static void alloc_args (void);
433 static void clear_args (void);
434 static void fatal_signal (int);
435 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
436 static void init_gcc_specs (struct obstack *, const char *, const char *,
437 const char *);
438 #endif
439 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
440 static const char *convert_filename (const char *, int, int);
441 #endif
442
443 static void try_generate_repro (const char **argv);
444 static const char *getenv_spec_function (int, const char **);
445 static const char *if_exists_spec_function (int, const char **);
446 static const char *if_exists_else_spec_function (int, const char **);
447 static const char *if_exists_then_else_spec_function (int, const char **);
448 static const char *sanitize_spec_function (int, const char **);
449 static const char *replace_outfile_spec_function (int, const char **);
450 static const char *remove_outfile_spec_function (int, const char **);
451 static const char *version_compare_spec_function (int, const char **);
452 static const char *include_spec_function (int, const char **);
453 static const char *find_file_spec_function (int, const char **);
454 static const char *find_plugindir_spec_function (int, const char **);
455 static const char *print_asm_header_spec_function (int, const char **);
456 static const char *compare_debug_dump_opt_spec_function (int, const char **);
457 static const char *compare_debug_self_opt_spec_function (int, const char **);
458 static const char *pass_through_libs_spec_func (int, const char **);
459 static const char *dumps_spec_func (int, const char **);
460 static const char *greater_than_spec_func (int, const char **);
461 static const char *debug_level_greater_than_spec_func (int, const char **);
462 static const char *dwarf_version_greater_than_spec_func (int, const char **);
463 static const char *find_fortran_preinclude_file (int, const char **);
464 static const char *join_spec_func (int, const char **);
465 static const char *if_driverlang_spec_function (int, const char **);
466 static char *convert_white_space (char *);
467 static char *quote_spec (char *);
468 static char *quote_spec_arg (char *);
469 static bool not_actual_file_p (const char *);
470
471
472 /* The Specs Language
473
474 Specs are strings containing lines, each of which (if not blank)
475 is made up of a program name, and arguments separated by spaces.
476 The program name must be exact and start from root, since no path
477 is searched and it is unreliable to depend on the current working directory.
478 Redirection of input or output is not supported; the subprograms must
479 accept filenames saying what files to read and write.
480
481 In addition, the specs can contain %-sequences to substitute variable text
482 or for conditional text. Here is a table of all defined %-sequences.
483 Note that spaces are not generated automatically around the results of
484 expanding these sequences; therefore, you can concatenate them together
485 or with constant text in a single argument.
486
487 %% substitute one % into the program name or argument.
488 %" substitute an empty argument.
489 %i substitute the name of the input file being processed.
490 %b substitute the basename for outputs related with the input file
491 being processed. This is often a substring of the input file name,
492 up to (and not including) the last period but, unless %w is active,
493 it is affected by the directory selected by -save-temps=*, by
494 -dumpdir, and, in case of multiple compilations, even by -dumpbase
495 and -dumpbase-ext and, in case of linking, by the linker output
496 name. When %w is active, it derives the main output name only from
497 the input file base name; when it is not, it names aux/dump output
498 file.
499 %B same as %b, but include the input file suffix (text after the last
500 period).
501 %gSUFFIX
502 substitute a file name that has suffix SUFFIX and is chosen
503 once per compilation, and mark the argument a la %d. To reduce
504 exposure to denial-of-service attacks, the file name is now
505 chosen in a way that is hard to predict even when previously
506 chosen file names are known. For example, `%g.s ... %g.o ... %g.s'
507 might turn into `ccUVUUAU.s ccXYAXZ12.o ccUVUUAU.s'. SUFFIX matches
508 the regexp "[.0-9A-Za-z]*%O"; "%O" is treated exactly as if it
509 had been pre-processed. Previously, %g was simply substituted
510 with a file name chosen once per compilation, without regard
511 to any appended suffix (which was therefore treated just like
512 ordinary text), making such attacks more likely to succeed.
513 %|SUFFIX
514 like %g, but if -pipe is in effect, expands simply to "-".
515 %mSUFFIX
516 like %g, but if -pipe is in effect, expands to nothing. (We have both
517 %| and %m to accommodate differences between system assemblers; see
518 the AS_NEEDS_DASH_FOR_PIPED_INPUT target macro.)
519 %uSUFFIX
520 like %g, but generates a new temporary file name even if %uSUFFIX
521 was already seen.
522 %USUFFIX
523 substitutes the last file name generated with %uSUFFIX, generating a
524 new one if there is no such last file name. In the absence of any
525 %uSUFFIX, this is just like %gSUFFIX, except they don't share
526 the same suffix "space", so `%g.s ... %U.s ... %g.s ... %U.s'
527 would involve the generation of two distinct file names, one
528 for each `%g.s' and another for each `%U.s'. Previously, %U was
529 simply substituted with a file name chosen for the previous %u,
530 without regard to any appended suffix.
531 %jSUFFIX
532 substitutes the name of the HOST_BIT_BUCKET, if any, and if it is
533 writable, and if save-temps is off; otherwise, substitute the name
534 of a temporary file, just like %u. This temporary file is not
535 meant for communication between processes, but rather as a junk
536 disposal mechanism.
537 %.SUFFIX
538 substitutes .SUFFIX for the suffixes of a matched switch's args when
539 it is subsequently output with %*. SUFFIX is terminated by the next
540 space or %.
541 %d marks the argument containing or following the %d as a
542 temporary file name, so that file will be deleted if GCC exits
543 successfully. Unlike %g, this contributes no text to the argument.
544 %w marks the argument containing or following the %w as the
545 "output file" of this compilation. This puts the argument
546 into the sequence of arguments that %o will substitute later.
547 %V indicates that this compilation produces no "output file".
548 %W{...}
549 like %{...} but marks the last argument supplied within as a file
550 to be deleted on failure.
551 %@{...}
552 like %{...} but puts the result into a FILE and substitutes @FILE
553 if an @file argument has been supplied.
554 %o substitutes the names of all the output files, with spaces
555 automatically placed around them. You should write spaces
556 around the %o as well or the results are undefined.
557 %o is for use in the specs for running the linker.
558 Input files whose names have no recognized suffix are not compiled
559 at all, but they are included among the output files, so they will
560 be linked.
561 %O substitutes the suffix for object files. Note that this is
562 handled specially when it immediately follows %g, %u, or %U
563 (with or without a suffix argument) because of the need for
564 those to form complete file names. The handling is such that
565 %O is treated exactly as if it had already been substituted,
566 except that %g, %u, and %U do not currently support additional
567 SUFFIX characters following %O as they would following, for
568 example, `.o'.
569 %I Substitute any of -iprefix (made from GCC_EXEC_PREFIX), -isysroot
570 (made from TARGET_SYSTEM_ROOT), -isystem (made from COMPILER_PATH
571 and -B options) and -imultilib as necessary.
572 %s current argument is the name of a library or startup file of some sort.
573 Search for that file in a standard list of directories
574 and substitute the full name found.
575 %T current argument is the name of a linker script.
576 Search for that file in the current list of directories to scan for
577 libraries. If the file is located, insert a --script option into the
578 command line followed by the full path name found. If the file is
579 not found then generate an error message.
580 Note: the current working directory is not searched.
581 %eSTR Print STR as an error message. STR is terminated by a newline.
582 Use this when inconsistent options are detected.
583 %nSTR Print STR as a notice. STR is terminated by a newline.
584 %x{OPTION} Accumulate an option for %X.
585 %X Output the accumulated linker options specified by compilations.
586 %Y Output the accumulated assembler options specified by compilations.
587 %Z Output the accumulated preprocessor options specified by compilations.
588 %a process ASM_SPEC as a spec.
589 This allows config.h to specify part of the spec for running as.
590 %A process ASM_FINAL_SPEC as a spec. A capital A is actually
591 used here. This can be used to run a post-processor after the
592 assembler has done its job.
593 %D Dump out a -L option for each directory in startfile_prefixes.
594 If multilib_dir is set, extra entries are generated with it affixed.
595 %l process LINK_SPEC as a spec.
596 %L process LIB_SPEC as a spec.
597 %M Output multilib_os_dir.
598 %P Output a RUNPATH_OPTION for each directory in startfile_prefixes.
599 %G process LIBGCC_SPEC as a spec.
600 %R Output the concatenation of target_system_root and
601 target_sysroot_suffix.
602 %S process STARTFILE_SPEC as a spec. A capital S is actually used here.
603 %E process ENDFILE_SPEC as a spec. A capital E is actually used here.
604 %C process CPP_SPEC as a spec.
605 %1 process CC1_SPEC as a spec.
606 %2 process CC1PLUS_SPEC as a spec.
607 %* substitute the variable part of a matched option. (See below.)
608 Note that each comma in the substituted string is replaced by
609 a single space. A space is appended after the last substition
610 unless there is more text in current sequence.
611 %<S remove all occurrences of -S from the command line.
612 Note - this command is position dependent. % commands in the
613 spec string before this one will see -S, % commands in the
614 spec string after this one will not.
615 %>S Similar to "%<S", but keep it in the GCC command line.
616 %<S* remove all occurrences of all switches beginning with -S from the
617 command line.
618 %:function(args)
619 Call the named function FUNCTION, passing it ARGS. ARGS is
620 first processed as a nested spec string, then split into an
621 argument vector in the usual fashion. The function returns
622 a string which is processed as if it had appeared literally
623 as part of the current spec.
624 %{S} substitutes the -S switch, if that switch was given to GCC.
625 If that switch was not specified, this substitutes nothing.
626 Here S is a metasyntactic variable.
627 %{S*} substitutes all the switches specified to GCC whose names start
628 with -S. This is used for -o, -I, etc; switches that take
629 arguments. GCC considers `-o foo' as being one switch whose
630 name starts with `o'. %{o*} would substitute this text,
631 including the space; thus, two arguments would be generated.
632 %{S*&T*} likewise, but preserve order of S and T options (the order
633 of S and T in the spec is not significant). Can be any number
634 of ampersand-separated variables; for each the wild card is
635 optional. Useful for CPP as %{D*&U*&A*}.
636
637 %{S:X} substitutes X, if the -S switch was given to GCC.
638 %{!S:X} substitutes X, if the -S switch was NOT given to GCC.
639 %{S*:X} substitutes X if one or more switches whose names start
640 with -S was given to GCC. Normally X is substituted only
641 once, no matter how many such switches appeared. However,
642 if %* appears somewhere in X, then X will be substituted
643 once for each matching switch, with the %* replaced by the
644 part of that switch that matched the '*'. A space will be
645 appended after the last substition unless there is more
646 text in current sequence.
647 %{.S:X} substitutes X, if processing a file with suffix S.
648 %{!.S:X} substitutes X, if NOT processing a file with suffix S.
649 %{,S:X} substitutes X, if processing a file which will use spec S.
650 %{!,S:X} substitutes X, if NOT processing a file which will use spec S.
651
652 %{S|T:X} substitutes X if either -S or -T was given to GCC. This may be
653 combined with '!', '.', ',', and '*' as above binding stronger
654 than the OR.
655 If %* appears in X, all of the alternatives must be starred, and
656 only the first matching alternative is substituted.
657 %{%:function(args):X}
658 Call function named FUNCTION with args ARGS. If the function
659 returns non-NULL, then X is substituted, if it returns
660 NULL, it isn't substituted.
661 %{S:X; if S was given to GCC, substitutes X;
662 T:Y; else if T was given to GCC, substitutes Y;
663 :D} else substitutes D. There can be as many clauses as you need.
664 This may be combined with '.', '!', ',', '|', and '*' as above.
665
666 %(Spec) processes a specification defined in a specs file as *Spec:
667
668 The switch matching text S in a %{S}, %{S:X}, or similar construct can use
669 a backslash to ignore the special meaning of the character following it,
670 thus allowing literal matching of a character that is otherwise specially
671 treated. For example, %{std=iso9899\:1999:X} substitutes X if the
672 -std=iso9899:1999 option is given.
673
674 The conditional text X in a %{S:X} or similar construct may contain
675 other nested % constructs or spaces, or even newlines. They are
676 processed as usual, as described above. Trailing white space in X is
677 ignored. White space may also appear anywhere on the left side of the
678 colon in these constructs, except between . or * and the corresponding
679 word.
680
681 The -O, -f, -g, -m, and -W switches are handled specifically in these
682 constructs. If another value of -O or the negated form of a -f, -m, or
683 -W switch is found later in the command line, the earlier switch
684 value is ignored, except with {S*} where S is just one letter; this
685 passes all matching options.
686
687 The character | at the beginning of the predicate text is used to indicate
688 that a command should be piped to the following command, but only if -pipe
689 is specified.
690
691 Note that it is built into GCC which switches take arguments and which
692 do not. You might think it would be useful to generalize this to
693 allow each compiler's spec to say which switches take arguments. But
694 this cannot be done in a consistent fashion. GCC cannot even decide
695 which input files have been specified without knowing which switches
696 take arguments, and it must know which input files to compile in order
697 to tell which compilers to run.
698
699 GCC also knows implicitly that arguments starting in `-l' are to be
700 treated as compiler output files, and passed to the linker in their
701 proper position among the other output files. */
702
703 /* Define the macros used for specs %a, %l, %L, %S, %C, %1. */
704
705 /* config.h can define ASM_SPEC to provide extra args to the assembler
706 or extra switch-translations. */
707 #ifndef ASM_SPEC
708 #define ASM_SPEC ""
709 #endif
710
711 /* config.h can define ASM_FINAL_SPEC to run a post processor after
712 the assembler has run. */
713 #ifndef ASM_FINAL_SPEC
714 #define ASM_FINAL_SPEC \
715 "%{gsplit-dwarf: \n\
716 objcopy --extract-dwo \
717 %{c:%{o*:%*}%{!o*:%w%b%O}}%{!c:%U%O} \
718 %b.dwo \n\
719 objcopy --strip-dwo \
720 %{c:%{o*:%*}%{!o*:%w%b%O}}%{!c:%U%O} \
721 }"
722 #endif
723
724 /* config.h can define CPP_SPEC to provide extra args to the C preprocessor
725 or extra switch-translations. */
726 #ifndef CPP_SPEC
727 #define CPP_SPEC ""
728 #endif
729
730 /* libc can define LIBC_CPP_SPEC to provide extra args to the C preprocessor
731 or extra switch-translations. */
732
733 #ifndef LIBC_CPP_SPEC
734 #define LIBC_CPP_SPEC ""
735 #endif
736
737 /* Operating systems can define OS_CC1_SPEC to provide extra args to cc1 and
738 cc1plus or extra switch-translations. The OS_CC1_SPEC is appended
739 to CC1_SPEC in the initialization of cc1_spec. */
740 #ifndef OS_CC1_SPEC
741 #define OS_CC1_SPEC ""
742 #endif
743
744 /* config.h can define CC1_SPEC to provide extra args to cc1 and cc1plus
745 or extra switch-translations. */
746 #ifndef CC1_SPEC
747 #define CC1_SPEC ""
748 #endif
749
750 /* config.h can define CC1PLUS_SPEC to provide extra args to cc1plus
751 or extra switch-translations. */
752 #ifndef CC1PLUS_SPEC
753 #define CC1PLUS_SPEC ""
754 #endif
755
756 /* config.h can define LINK_SPEC to provide extra args to the linker
757 or extra switch-translations. */
758 #ifndef LINK_SPEC
759 #define LINK_SPEC ""
760 #endif
761
762 /* libc can define LIBC_LINK_SPEC to provide extra args to the linker
763 or extra switch-translations. */
764 #ifndef LIBC_LINK_SPEC
765 #define LIBC_LINK_SPEC ""
766 #endif
767
768 /* config.h can define LIB_SPEC to override the default libraries. */
769 #ifndef LIB_SPEC
770 #define LIB_SPEC "%{!shared:%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}}"
771 #endif
772
773 /* When using -fsplit-stack we need to wrap pthread_create, in order
774 to initialize the stack guard. We always use wrapping, rather than
775 shared library ordering, and we keep the wrapper function in
776 libgcc. This is not yet a real spec, though it could become one;
777 it is currently just stuffed into LINK_SPEC. FIXME: This wrapping
778 only works with GNU ld and gold. */
779 #ifdef HAVE_GOLD_NON_DEFAULT_SPLIT_STACK
780 #define STACK_SPLIT_SPEC " %{fsplit-stack: -fuse-ld=gold --wrap=pthread_create}"
781 #else
782 #define STACK_SPLIT_SPEC " %{fsplit-stack: --wrap=pthread_create}"
783 #endif
784
785 #ifndef LIBASAN_SPEC
786 #define STATIC_LIBASAN_LIBS \
787 " %{static-libasan|static:%:include(libsanitizer.spec)%(link_libasan)}"
788 #ifdef LIBASAN_EARLY_SPEC
789 #define LIBASAN_SPEC STATIC_LIBASAN_LIBS
790 #elif defined(HAVE_LD_STATIC_DYNAMIC)
791 #define LIBASAN_SPEC "%{static-libasan:" LD_STATIC_OPTION \
792 "} -lasan %{static-libasan:" LD_DYNAMIC_OPTION "}" \
793 STATIC_LIBASAN_LIBS
794 #else
795 #define LIBASAN_SPEC "-lasan" STATIC_LIBASAN_LIBS
796 #endif
797 #endif
798
799 #ifndef LIBASAN_EARLY_SPEC
800 #define LIBASAN_EARLY_SPEC ""
801 #endif
802
803 #ifndef LIBHWASAN_SPEC
804 #define STATIC_LIBHWASAN_LIBS \
805 " %{static-libhwasan|static:%:include(libsanitizer.spec)%(link_libhwasan)}"
806 #ifdef LIBHWASAN_EARLY_SPEC
807 #define LIBHWASAN_SPEC STATIC_LIBHWASAN_LIBS
808 #elif defined(HAVE_LD_STATIC_DYNAMIC)
809 #define LIBHWASAN_SPEC "%{static-libhwasan:" LD_STATIC_OPTION \
810 "} -lhwasan %{static-libhwasan:" LD_DYNAMIC_OPTION "}" \
811 STATIC_LIBHWASAN_LIBS
812 #else
813 #define LIBHWASAN_SPEC "-lhwasan" STATIC_LIBHWASAN_LIBS
814 #endif
815 #endif
816
817 #ifndef LIBHWASAN_EARLY_SPEC
818 #define LIBHWASAN_EARLY_SPEC ""
819 #endif
820
821 #ifndef LIBTSAN_SPEC
822 #define STATIC_LIBTSAN_LIBS \
823 " %{static-libtsan|static:%:include(libsanitizer.spec)%(link_libtsan)}"
824 #ifdef LIBTSAN_EARLY_SPEC
825 #define LIBTSAN_SPEC STATIC_LIBTSAN_LIBS
826 #elif defined(HAVE_LD_STATIC_DYNAMIC)
827 #define LIBTSAN_SPEC "%{static-libtsan:" LD_STATIC_OPTION \
828 "} -ltsan %{static-libtsan:" LD_DYNAMIC_OPTION "}" \
829 STATIC_LIBTSAN_LIBS
830 #else
831 #define LIBTSAN_SPEC "-ltsan" STATIC_LIBTSAN_LIBS
832 #endif
833 #endif
834
835 #ifndef LIBTSAN_EARLY_SPEC
836 #define LIBTSAN_EARLY_SPEC ""
837 #endif
838
839 #ifndef LIBLSAN_SPEC
840 #define STATIC_LIBLSAN_LIBS \
841 " %{static-liblsan|static:%:include(libsanitizer.spec)%(link_liblsan)}"
842 #ifdef LIBLSAN_EARLY_SPEC
843 #define LIBLSAN_SPEC STATIC_LIBLSAN_LIBS
844 #elif defined(HAVE_LD_STATIC_DYNAMIC)
845 #define LIBLSAN_SPEC "%{static-liblsan:" LD_STATIC_OPTION \
846 "} -llsan %{static-liblsan:" LD_DYNAMIC_OPTION "}" \
847 STATIC_LIBLSAN_LIBS
848 #else
849 #define LIBLSAN_SPEC "-llsan" STATIC_LIBLSAN_LIBS
850 #endif
851 #endif
852
853 #ifndef LIBLSAN_EARLY_SPEC
854 #define LIBLSAN_EARLY_SPEC ""
855 #endif
856
857 #ifndef LIBUBSAN_SPEC
858 #define STATIC_LIBUBSAN_LIBS \
859 " %{static-libubsan|static:%:include(libsanitizer.spec)%(link_libubsan)}"
860 #ifdef HAVE_LD_STATIC_DYNAMIC
861 #define LIBUBSAN_SPEC "%{static-libubsan:" LD_STATIC_OPTION \
862 "} -lubsan %{static-libubsan:" LD_DYNAMIC_OPTION "}" \
863 STATIC_LIBUBSAN_LIBS
864 #else
865 #define LIBUBSAN_SPEC "-lubsan" STATIC_LIBUBSAN_LIBS
866 #endif
867 #endif
868
869 /* Linker options for compressed debug sections. */
870 #if HAVE_LD_COMPRESS_DEBUG == 0
871 /* No linker support. */
872 #define LINK_COMPRESS_DEBUG_SPEC \
873 " %{gz*:%e-gz is not supported in this configuration} "
874 #elif HAVE_LD_COMPRESS_DEBUG == 1
875 /* ELF gABI style. */
876 #define LINK_COMPRESS_DEBUG_SPEC \
877 " %{gz|gz=zlib:" LD_COMPRESS_DEBUG_OPTION "=zlib}" \
878 " %{gz=none:" LD_COMPRESS_DEBUG_OPTION "=none}" \
879 " %{gz=zstd:%e-gz=zstd is not supported in this configuration} " \
880 " %{gz=zlib-gnu:}" /* Ignore silently zlib-gnu option value. */
881 #elif HAVE_LD_COMPRESS_DEBUG == 2
882 /* ELF gABI style and ZSTD. */
883 #define LINK_COMPRESS_DEBUG_SPEC \
884 " %{gz|gz=zlib:" LD_COMPRESS_DEBUG_OPTION "=zlib}" \
885 " %{gz=none:" LD_COMPRESS_DEBUG_OPTION "=none}" \
886 " %{gz=zstd:" LD_COMPRESS_DEBUG_OPTION "=zstd}" \
887 " %{gz=zlib-gnu:}" /* Ignore silently zlib-gnu option value. */
888 #else
889 #error Unknown value for HAVE_LD_COMPRESS_DEBUG.
890 #endif
891
892 /* config.h can define LIBGCC_SPEC to override how and when libgcc.a is
893 included. */
894 #ifndef LIBGCC_SPEC
895 #if defined(REAL_LIBGCC_SPEC)
896 #define LIBGCC_SPEC REAL_LIBGCC_SPEC
897 #elif defined(LINK_LIBGCC_SPECIAL_1)
898 /* Have gcc do the search for libgcc.a. */
899 #define LIBGCC_SPEC "libgcc.a%s"
900 #else
901 #define LIBGCC_SPEC "-lgcc"
902 #endif
903 #endif
904
905 /* config.h can define STARTFILE_SPEC to override the default crt0 files. */
906 #ifndef STARTFILE_SPEC
907 #define STARTFILE_SPEC \
908 "%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
909 #endif
910
911 /* config.h can define ENDFILE_SPEC to override the default crtn files. */
912 #ifndef ENDFILE_SPEC
913 #define ENDFILE_SPEC ""
914 #endif
915
916 #ifndef LINKER_NAME
917 #define LINKER_NAME "collect2"
918 #endif
919
920 #ifdef HAVE_AS_DEBUG_PREFIX_MAP
921 #define ASM_MAP " %{ffile-prefix-map=*:--debug-prefix-map %*} %{fdebug-prefix-map=*:--debug-prefix-map %*}"
922 #else
923 #define ASM_MAP ""
924 #endif
925
926 /* Assembler options for compressed debug sections. */
927 #if HAVE_LD_COMPRESS_DEBUG == 0
928 /* Reject if the linker cannot write compressed debug sections. */
929 #define ASM_COMPRESS_DEBUG_SPEC \
930 " %{gz*:%e-gz is not supported in this configuration} "
931 #else /* HAVE_LD_COMPRESS_DEBUG >= 1 */
932 #if HAVE_AS_COMPRESS_DEBUG == 0
933 /* No assembler support. Ignore silently. */
934 #define ASM_COMPRESS_DEBUG_SPEC \
935 " %{gz*:} "
936 #elif HAVE_AS_COMPRESS_DEBUG == 1
937 /* ELF gABI style. */
938 #define ASM_COMPRESS_DEBUG_SPEC \
939 " %{gz|gz=zlib:" AS_COMPRESS_DEBUG_OPTION "=zlib}" \
940 " %{gz=none:" AS_COMPRESS_DEBUG_OPTION "=none}" \
941 " %{gz=zlib-gnu:}" /* Ignore silently zlib-gnu option value. */
942 #elif HAVE_AS_COMPRESS_DEBUG == 2
943 /* ELF gABI style and ZSTD. */
944 #define ASM_COMPRESS_DEBUG_SPEC \
945 " %{gz|gz=zlib:" AS_COMPRESS_DEBUG_OPTION "=zlib}" \
946 " %{gz=none:" AS_COMPRESS_DEBUG_OPTION "=none}" \
947 " %{gz=zstd:" AS_COMPRESS_DEBUG_OPTION "=zstd}" \
948 " %{gz=zlib-gnu:}" /* Ignore silently zlib-gnu option value. */
949 #else
950 #error Unknown value for HAVE_AS_COMPRESS_DEBUG.
951 #endif
952 #endif /* HAVE_LD_COMPRESS_DEBUG >= 1 */
953
954 /* Define ASM_DEBUG_SPEC to be a spec suitable for translating '-g'
955 to the assembler, when compiling assembly sources only. */
956 #ifndef ASM_DEBUG_SPEC
957 # if defined(HAVE_AS_GDWARF_5_DEBUG_FLAG) && defined(HAVE_AS_WORKING_DWARF_N_FLAG)
958 /* If --gdwarf-N is supported and as can handle even compiler generated
959 .debug_line with it, supply --gdwarf-N in ASM_DEBUG_OPTION_SPEC rather
960 than in ASM_DEBUG_SPEC, so that it applies to both .s and .c etc.
961 compilations. */
962 # define ASM_DEBUG_DWARF_OPTION ""
963 # elif defined(HAVE_AS_GDWARF_5_DEBUG_FLAG) && !defined(HAVE_LD_BROKEN_PE_DWARF5)
964 # define ASM_DEBUG_DWARF_OPTION "%{%:dwarf-version-gt(4):--gdwarf-5;" \
965 "%:dwarf-version-gt(3):--gdwarf-4;" \
966 "%:dwarf-version-gt(2):--gdwarf-3;" \
967 ":--gdwarf2}"
968 # else
969 # define ASM_DEBUG_DWARF_OPTION "--gdwarf2"
970 # endif
971 # if defined(DWARF2_DEBUGGING_INFO) && defined(HAVE_AS_GDWARF2_DEBUG_FLAG)
972 # define ASM_DEBUG_SPEC "%{g*:%{%:debug-level-gt(0):" \
973 ASM_DEBUG_DWARF_OPTION "}}" ASM_MAP
974 # endif
975 # endif
976 #ifndef ASM_DEBUG_SPEC
977 # define ASM_DEBUG_SPEC ""
978 #endif
979
980 /* Define ASM_DEBUG_OPTION_SPEC to be a spec suitable for translating '-g'
981 to the assembler when compiling all sources. */
982 #ifndef ASM_DEBUG_OPTION_SPEC
983 # if defined(HAVE_AS_GDWARF_5_DEBUG_FLAG) && defined(HAVE_AS_WORKING_DWARF_N_FLAG)
984 # define ASM_DEBUG_OPTION_DWARF_OPT \
985 "%{%:dwarf-version-gt(4):--gdwarf-5 ;" \
986 "%:dwarf-version-gt(3):--gdwarf-4 ;" \
987 "%:dwarf-version-gt(2):--gdwarf-3 ;" \
988 ":--gdwarf2 }"
989 # if defined(DWARF2_DEBUGGING_INFO)
990 # define ASM_DEBUG_OPTION_SPEC "%{g*:%{%:debug-level-gt(0):" \
991 ASM_DEBUG_OPTION_DWARF_OPT "}}"
992 # endif
993 # endif
994 #endif
995 #ifndef ASM_DEBUG_OPTION_SPEC
996 # define ASM_DEBUG_OPTION_SPEC ""
997 #endif
998
999 /* Here is the spec for running the linker, after compiling all files. */
1000
1001 /* This is overridable by the target in case they need to specify the
1002 -lgcc and -lc order specially, yet not require them to override all
1003 of LINK_COMMAND_SPEC. */
1004 #ifndef LINK_GCC_C_SEQUENCE_SPEC
1005 #define LINK_GCC_C_SEQUENCE_SPEC "%G %{!nolibc:%L %G}"
1006 #endif
1007
1008 #ifndef LINK_SSP_SPEC
1009 #ifdef TARGET_LIBC_PROVIDES_SSP
1010 #define LINK_SSP_SPEC "%{fstack-protector|fstack-protector-all" \
1011 "|fstack-protector-strong|fstack-protector-explicit:}"
1012 #else
1013 #define LINK_SSP_SPEC "%{fstack-protector|fstack-protector-all" \
1014 "|fstack-protector-strong|fstack-protector-explicit" \
1015 ":-lssp_nonshared -lssp}"
1016 #endif
1017 #endif
1018
1019 #ifdef ENABLE_DEFAULT_PIE
1020 #define PIE_SPEC "!no-pie"
1021 #define NO_FPIE1_SPEC "fno-pie"
1022 #define FPIE1_SPEC NO_FPIE1_SPEC ":;"
1023 #define NO_FPIE2_SPEC "fno-PIE"
1024 #define FPIE2_SPEC NO_FPIE2_SPEC ":;"
1025 #define NO_FPIE_SPEC NO_FPIE1_SPEC "|" NO_FPIE2_SPEC
1026 #define FPIE_SPEC NO_FPIE_SPEC ":;"
1027 #define NO_FPIC1_SPEC "fno-pic"
1028 #define FPIC1_SPEC NO_FPIC1_SPEC ":;"
1029 #define NO_FPIC2_SPEC "fno-PIC"
1030 #define FPIC2_SPEC NO_FPIC2_SPEC ":;"
1031 #define NO_FPIC_SPEC NO_FPIC1_SPEC "|" NO_FPIC2_SPEC
1032 #define FPIC_SPEC NO_FPIC_SPEC ":;"
1033 #define NO_FPIE1_AND_FPIC1_SPEC NO_FPIE1_SPEC "|" NO_FPIC1_SPEC
1034 #define FPIE1_OR_FPIC1_SPEC NO_FPIE1_AND_FPIC1_SPEC ":;"
1035 #define NO_FPIE2_AND_FPIC2_SPEC NO_FPIE2_SPEC "|" NO_FPIC2_SPEC
1036 #define FPIE2_OR_FPIC2_SPEC NO_FPIE2_AND_FPIC2_SPEC ":;"
1037 #define NO_FPIE_AND_FPIC_SPEC NO_FPIE_SPEC "|" NO_FPIC_SPEC
1038 #define FPIE_OR_FPIC_SPEC NO_FPIE_AND_FPIC_SPEC ":;"
1039 #else
1040 #define PIE_SPEC "pie"
1041 #define FPIE1_SPEC "fpie"
1042 #define NO_FPIE1_SPEC FPIE1_SPEC ":;"
1043 #define FPIE2_SPEC "fPIE"
1044 #define NO_FPIE2_SPEC FPIE2_SPEC ":;"
1045 #define FPIE_SPEC FPIE1_SPEC "|" FPIE2_SPEC
1046 #define NO_FPIE_SPEC FPIE_SPEC ":;"
1047 #define FPIC1_SPEC "fpic"
1048 #define NO_FPIC1_SPEC FPIC1_SPEC ":;"
1049 #define FPIC2_SPEC "fPIC"
1050 #define NO_FPIC2_SPEC FPIC2_SPEC ":;"
1051 #define FPIC_SPEC FPIC1_SPEC "|" FPIC2_SPEC
1052 #define NO_FPIC_SPEC FPIC_SPEC ":;"
1053 #define FPIE1_OR_FPIC1_SPEC FPIE1_SPEC "|" FPIC1_SPEC
1054 #define NO_FPIE1_AND_FPIC1_SPEC FPIE1_OR_FPIC1_SPEC ":;"
1055 #define FPIE2_OR_FPIC2_SPEC FPIE2_SPEC "|" FPIC2_SPEC
1056 #define NO_FPIE2_AND_FPIC2_SPEC FPIE1_OR_FPIC2_SPEC ":;"
1057 #define FPIE_OR_FPIC_SPEC FPIE_SPEC "|" FPIC_SPEC
1058 #define NO_FPIE_AND_FPIC_SPEC FPIE_OR_FPIC_SPEC ":;"
1059 #endif
1060
1061 #ifndef LINK_PIE_SPEC
1062 #ifdef HAVE_LD_PIE
1063 #ifndef LD_PIE_SPEC
1064 #define LD_PIE_SPEC "-pie"
1065 #endif
1066 #else
1067 #define LD_PIE_SPEC ""
1068 #endif
1069 #define LINK_PIE_SPEC "%{static|shared|r:;" PIE_SPEC ":" LD_PIE_SPEC "} "
1070 #endif
1071
1072 #ifndef LINK_BUILDID_SPEC
1073 # if defined(HAVE_LD_BUILDID) && defined(ENABLE_LD_BUILDID)
1074 # define LINK_BUILDID_SPEC "%{!r:--build-id} "
1075 # endif
1076 #endif
1077
1078 #ifndef LTO_PLUGIN_SPEC
1079 #define LTO_PLUGIN_SPEC ""
1080 #endif
1081
1082 /* Conditional to test whether the LTO plugin is used or not.
1083 FIXME: For slim LTO we will need to enable plugin unconditionally. This
1084 still cause problems with PLUGIN_LD != LD and when plugin is built but
1085 not useable. For GCC 4.6 we don't support slim LTO and thus we can enable
1086 plugin only when LTO is enabled. We still honor explicit
1087 -fuse-linker-plugin if the linker used understands -plugin. */
1088
1089 /* The linker has some plugin support. */
1090 #if HAVE_LTO_PLUGIN > 0
1091 /* The linker used has full plugin support, use LTO plugin by default. */
1092 #if HAVE_LTO_PLUGIN == 2
1093 #define PLUGIN_COND "!fno-use-linker-plugin:%{!fno-lto"
1094 #define PLUGIN_COND_CLOSE "}"
1095 #else
1096 /* The linker used has limited plugin support, use LTO plugin with explicit
1097 -fuse-linker-plugin. */
1098 #define PLUGIN_COND "fuse-linker-plugin"
1099 #define PLUGIN_COND_CLOSE ""
1100 #endif
1101 #define LINK_PLUGIN_SPEC \
1102 "%{" PLUGIN_COND": \
1103 -plugin %(linker_plugin_file) \
1104 -plugin-opt=%(lto_wrapper) \
1105 -plugin-opt=-fresolution=%u.res \
1106 " LTO_PLUGIN_SPEC "\
1107 %{flinker-output=*:-plugin-opt=-linker-output-known} \
1108 %{!nostdlib:%{!nodefaultlibs:%:pass-through-libs(%(link_gcc_c_sequence))}} \
1109 }" PLUGIN_COND_CLOSE
1110 #else
1111 /* The linker used doesn't support -plugin, reject -fuse-linker-plugin. */
1112 #define LINK_PLUGIN_SPEC "%{fuse-linker-plugin:\
1113 %e-fuse-linker-plugin is not supported in this configuration}"
1114 #endif
1115
1116 /* Linker command line options for -fsanitize= early on the command line. */
1117 #ifndef SANITIZER_EARLY_SPEC
1118 #define SANITIZER_EARLY_SPEC "\
1119 %{!nostdlib:%{!r:%{!nodefaultlibs:%{%:sanitize(address):" LIBASAN_EARLY_SPEC "} \
1120 %{%:sanitize(hwaddress):" LIBHWASAN_EARLY_SPEC "} \
1121 %{%:sanitize(thread):" LIBTSAN_EARLY_SPEC "} \
1122 %{%:sanitize(leak):" LIBLSAN_EARLY_SPEC "}}}}"
1123 #endif
1124
1125 /* Linker command line options for -fsanitize= late on the command line. */
1126 #ifndef SANITIZER_SPEC
1127 #define SANITIZER_SPEC "\
1128 %{!nostdlib:%{!r:%{!nodefaultlibs:%{%:sanitize(address):" LIBASAN_SPEC "\
1129 %{static:%ecannot specify -static with -fsanitize=address}}\
1130 %{%:sanitize(hwaddress):" LIBHWASAN_SPEC "\
1131 %{static:%ecannot specify -static with -fsanitize=hwaddress}}\
1132 %{%:sanitize(thread):" LIBTSAN_SPEC "\
1133 %{static:%ecannot specify -static with -fsanitize=thread}}\
1134 %{%:sanitize(undefined):" LIBUBSAN_SPEC "}\
1135 %{%:sanitize(leak):" LIBLSAN_SPEC "}}}}"
1136 #endif
1137
1138 #ifndef POST_LINK_SPEC
1139 #define POST_LINK_SPEC ""
1140 #endif
1141
1142 /* This is the spec to use, once the code for creating the vtable
1143 verification runtime library, libvtv.so, has been created. Currently
1144 the vtable verification runtime functions are in libstdc++, so we use
1145 the spec just below this one. */
1146 #ifndef VTABLE_VERIFICATION_SPEC
1147 #if ENABLE_VTABLE_VERIFY
1148 #define VTABLE_VERIFICATION_SPEC "\
1149 %{!nostdlib:%{!r:%{fvtable-verify=std: -lvtv -u_vtable_map_vars_start -u_vtable_map_vars_end}\
1150 %{fvtable-verify=preinit: -lvtv -u_vtable_map_vars_start -u_vtable_map_vars_end}}}"
1151 #else
1152 #define VTABLE_VERIFICATION_SPEC "\
1153 %{fvtable-verify=none:} \
1154 %{fvtable-verify=std: \
1155 %e-fvtable-verify=std is not supported in this configuration} \
1156 %{fvtable-verify=preinit: \
1157 %e-fvtable-verify=preinit is not supported in this configuration}"
1158 #endif
1159 #endif
1160
1161 /* -u* was put back because both BSD and SysV seem to support it. */
1162 /* %{static|no-pie|static-pie:} simply prevents an error message:
1163 1. If the target machine doesn't handle -static.
1164 2. If PIE isn't enabled by default.
1165 3. If the target machine doesn't handle -static-pie.
1166 */
1167 /* We want %{T*} after %{L*} and %D so that it can be used to specify linker
1168 scripts which exist in user specified directories, or in standard
1169 directories. */
1170 /* We pass any -flto flags on to the linker, which is expected
1171 to understand them. In practice, this means it had better be collect2. */
1172 /* %{e*} includes -export-dynamic; see comment in common.opt. */
1173 #ifndef LINK_COMMAND_SPEC
1174 #define LINK_COMMAND_SPEC "\
1175 %{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
1176 %(linker) " \
1177 LINK_PLUGIN_SPEC \
1178 "%{flto|flto=*:%<fcompare-debug*} \
1179 %{flto} %{fno-lto} %{flto=*} %l " LINK_PIE_SPEC \
1180 "%{fuse-ld=*:-fuse-ld=%*} " LINK_COMPRESS_DEBUG_SPEC \
1181 "%X %{o*} %{e*} %{N} %{n} %{r}\
1182 %{s} %{t} %{u*} %{z} %{Z} %{!nostdlib:%{!r:%{!nostartfiles:%S}}} \
1183 %{static|no-pie|static-pie:} %@{L*} %(link_libgcc) " \
1184 VTABLE_VERIFICATION_SPEC " " SANITIZER_EARLY_SPEC " %o "" \
1185 %{fopenacc|fopenmp|%:gt(%{ftree-parallelize-loops=*:%*} 1):\
1186 %:include(libgomp.spec)%(link_gomp)}\
1187 %{fgnu-tm:%:include(libitm.spec)%(link_itm)}\
1188 " STACK_SPLIT_SPEC "\
1189 %{fprofile-arcs|fcondition-coverage|fpath-coverage|fprofile-generate*|coverage:-lgcov} " SANITIZER_SPEC " \
1190 %{!nostdlib:%{!r:%{!nodefaultlibs:%(link_ssp) %(link_gcc_c_sequence)}}}\
1191 %{!nostdlib:%{!r:%{!nostartfiles:%E}}} %{T*} \n%(post_link) }}}}}}"
1192 #endif
1193
1194 #ifndef LINK_LIBGCC_SPEC
1195 /* Generate -L options for startfile prefix list. */
1196 # define LINK_LIBGCC_SPEC "%D"
1197 #endif
1198
1199 #ifndef STARTFILE_PREFIX_SPEC
1200 # define STARTFILE_PREFIX_SPEC ""
1201 #endif
1202
1203 #ifndef SYSROOT_SPEC
1204 # define SYSROOT_SPEC "--sysroot=%R"
1205 #endif
1206
1207 #ifndef SYSROOT_SUFFIX_SPEC
1208 # define SYSROOT_SUFFIX_SPEC ""
1209 #endif
1210
1211 #ifndef SYSROOT_HEADERS_SUFFIX_SPEC
1212 # define SYSROOT_HEADERS_SUFFIX_SPEC ""
1213 #endif
1214
1215 #ifndef RUNPATH_OPTION
1216 # define RUNPATH_OPTION "-rpath"
1217 #endif
1218
1219 static const char *asm_debug = ASM_DEBUG_SPEC;
1220 static const char *asm_debug_option = ASM_DEBUG_OPTION_SPEC;
1221 static const char *cpp_spec = CPP_SPEC LIBC_CPP_SPEC;
1222 static const char *cc1_spec = CC1_SPEC OS_CC1_SPEC;
1223 static const char *cc1plus_spec = CC1PLUS_SPEC;
1224 static const char *link_gcc_c_sequence_spec = LINK_GCC_C_SEQUENCE_SPEC;
1225 static const char *link_ssp_spec = LINK_SSP_SPEC;
1226 static const char *asm_spec = ASM_SPEC;
1227 static const char *asm_final_spec = ASM_FINAL_SPEC;
1228 static const char *link_spec = LINK_SPEC LIBC_LINK_SPEC;
1229 static const char *lib_spec = LIB_SPEC;
1230 static const char *link_gomp_spec = "";
1231 static const char *libgcc_spec = LIBGCC_SPEC;
1232 static const char *endfile_spec = ENDFILE_SPEC;
1233 static const char *startfile_spec = STARTFILE_SPEC;
1234 static const char *linker_name_spec = LINKER_NAME;
1235 static const char *linker_plugin_file_spec = "";
1236 static const char *lto_wrapper_spec = "";
1237 static const char *lto_gcc_spec = "";
1238 static const char *post_link_spec = POST_LINK_SPEC;
1239 static const char *link_command_spec = LINK_COMMAND_SPEC;
1240 static const char *link_libgcc_spec = LINK_LIBGCC_SPEC;
1241 static const char *startfile_prefix_spec = STARTFILE_PREFIX_SPEC;
1242 static const char *sysroot_spec = SYSROOT_SPEC;
1243 static const char *sysroot_suffix_spec = SYSROOT_SUFFIX_SPEC;
1244 static const char *sysroot_hdrs_suffix_spec = SYSROOT_HEADERS_SUFFIX_SPEC;
1245 static const char *self_spec = "";
1246
1247 /* Standard options to cpp, cc1, and as, to reduce duplication in specs.
1248 There should be no need to override these in target dependent files,
1249 but we need to copy them to the specs file so that newer versions
1250 of the GCC driver can correctly drive older tool chains with the
1251 appropriate -B options. */
1252
1253 /* When cpplib handles traditional preprocessing, get rid of this, and
1254 call cc1 (or cc1obj in objc/lang-specs.h) from the main specs so
1255 that we default the front end language better. */
1256 static const char *trad_capable_cpp =
1257 "cc1 -E %{traditional|traditional-cpp:-traditional-cpp}";
1258
1259 /* We don't wrap .d files in %W{} since a missing .d file, and
1260 therefore no dependency entry, confuses make into thinking a .o
1261 file that happens to exist is up-to-date. */
1262 static const char *cpp_unique_options =
1263 "%{!Q:-quiet} %{nostdinc*} %{C} %{CC} %{v} %@{I*&F*} %{P} %I\
1264 %{MD:-MD %{!o:%b.d}%{o*:%.d%*}}\
1265 %{MMD:-MMD %{!o:%b.d}%{o*:%.d%*}}\
1266 %{M} %{MM} %{MF*} %{MG} %{MP} %{MQ*} %{MT*}\
1267 %{Mmodules} %{Mno-modules}\
1268 %{!E:%{!M:%{!MM:%{!MT:%{!MQ:%{MD|MMD:%{o*:-MQ %*}}}}}}}\
1269 %{remap} %{%:debug-level-gt(2):-dD}\
1270 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
1271 %{H} %C %{D*&U*&A*} %{i*} %Z %i\
1272 %{E|M|MM:%W{o*}} %{-embed*}\
1273 %{fdeps-format=*:%{!fdeps-file=*:-fdeps-file=%:join(%{!o:%b.ddi}%{o*:%.ddi%*})}}\
1274 %{fdeps-format=*:%{!fdeps-target=*:-fdeps-target=%:join(%{!o:%b.o}%{o*:%.o%*})}}";
1275
1276 /* This contains cpp options which are common with cc1_options and are passed
1277 only when preprocessing only to avoid duplication. We pass the cc1 spec
1278 options to the preprocessor so that it the cc1 spec may manipulate
1279 options used to set target flags. Those special target flags settings may
1280 in turn cause preprocessor symbols to be defined specially. */
1281 static const char *cpp_options =
1282 "%(cpp_unique_options) %1 %{m*} %{std*&ansi&trigraphs} %{W*&pedantic*} %{w}\
1283 %{f*} %{g*:%{%:debug-level-gt(0):%{g*}\
1284 %{!fno-working-directory:-fworking-directory}}} %{O*}\
1285 %{undef} %{save-temps*:-fpch-preprocess}";
1286
1287 /* Pass -d* flags, possibly modifying -dumpdir, -dumpbase et al.
1288
1289 Make it easy for a language to override the argument for the
1290 %:dumps specs function call. */
1291 #define DUMPS_OPTIONS(EXTS) \
1292 "%<dumpdir %<dumpbase %<dumpbase-ext %{d*} %:dumps(" EXTS ")"
1293
1294 /* This contains cpp options which are not passed when the preprocessor
1295 output will be used by another program. */
1296 static const char *cpp_debug_options = DUMPS_OPTIONS ("");
1297
1298 /* NB: This is shared amongst all front-ends, except for Ada. */
1299 static const char *cc1_options =
1300 "%{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
1301 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
1302 %1 %{!Q:-quiet} %(cpp_debug_options) %{m*} %{aux-info*}\
1303 %{g*} %{O*} %{W*&pedantic*} %{w} %{std*&ansi&trigraphs}\
1304 %{v:-version} %{pg:-p} %{p} %{f*} %{undef}\
1305 %{Qn:-fno-ident} %{Qy:} %{-help:--help}\
1306 %{-target-help:--target-help}\
1307 %{-version:--version}\
1308 %{-help=*:--help=%*}\
1309 %{!fsyntax-only:%{S:%W{o*}%{!o*:-o %w%b.s}}}\
1310 %{fsyntax-only:-o %j} %{-param*}\
1311 %{coverage:-fprofile-arcs -ftest-coverage}\
1312 %{fprofile-arcs|fcondition-coverage|fpath-coverage|fprofile-generate*|coverage:\
1313 %{!fprofile-update=single:\
1314 %{pthread:-fprofile-update=prefer-atomic}}}";
1315
1316 static const char *asm_options =
1317 "%{-target-help:%:print-asm-header()} "
1318 #if HAVE_GNU_AS
1319 /* If GNU AS is used, then convert -w (no warnings), -I, and -v
1320 to the assembler equivalents. */
1321 "%{v} %{w:-W} %{I*} "
1322 #endif
1323 "%(asm_debug_option)"
1324 ASM_COMPRESS_DEBUG_SPEC
1325 "%a %Y %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}";
1326
1327 static const char *invoke_as =
1328 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
1329 "%{!fwpa*:\
1330 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
1331 %{!S:-o %|.s |\n as %(asm_options) %|.s %A }\
1332 }";
1333 #else
1334 "%{!fwpa*:\
1335 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
1336 %{!S:-o %|.s |\n as %(asm_options) %m.s %A }\
1337 }";
1338 #endif
1339
1340 /* Some compilers have limits on line lengths, and the multilib_select
1341 and/or multilib_matches strings can be very long, so we build them at
1342 run time. */
1343 static struct obstack multilib_obstack;
1344 static const char *multilib_select;
1345 static const char *multilib_matches;
1346 static const char *multilib_defaults;
1347 static const char *multilib_exclusions;
1348 static const char *multilib_reuse;
1349
1350 /* Check whether a particular argument is a default argument. */
1351
1352 #ifndef MULTILIB_DEFAULTS
1353 #define MULTILIB_DEFAULTS { "" }
1354 #endif
1355
1356 static const char *const multilib_defaults_raw[] = MULTILIB_DEFAULTS;
1357
1358 #ifndef DRIVER_SELF_SPECS
1359 #define DRIVER_SELF_SPECS ""
1360 #endif
1361
1362 /* Linking to libgomp implies pthreads. This is particularly important
1363 for targets that use different start files and suchlike. */
1364 #ifndef GOMP_SELF_SPECS
1365 #define GOMP_SELF_SPECS \
1366 "%{fopenacc|fopenmp|%:gt(%{ftree-parallelize-loops=*:%*} 1): " \
1367 "-pthread}"
1368 #endif
1369
1370 /* Likewise for -fgnu-tm. */
1371 #ifndef GTM_SELF_SPECS
1372 #define GTM_SELF_SPECS "%{fgnu-tm: -pthread}"
1373 #endif
1374
1375 static const char *const driver_self_specs[] = {
1376 "%{fdump-final-insns:-fdump-final-insns=.} %<fdump-final-insns",
1377 DRIVER_SELF_SPECS, CONFIGURE_SPECS, GOMP_SELF_SPECS, GTM_SELF_SPECS,
1378 /* This discards -fmultiflags at the end of self specs processing in the
1379 driver, so that it is effectively Ignored, without actually marking it as
1380 Ignored, which would get it discarded before self specs could remap it. */
1381 "%<fmultiflags"
1382 };
1383
1384 #ifndef OPTION_DEFAULT_SPECS
1385 #define OPTION_DEFAULT_SPECS { "", "" }
1386 #endif
1387
1388 struct default_spec
1389 {
1390 const char *name;
1391 const char *spec;
1392 };
1393
1394 static const struct default_spec
1395 option_default_specs[] = { OPTION_DEFAULT_SPECS };
1396
1397 struct user_specs
1398 {
1399 struct user_specs *next;
1400 const char *filename;
1401 };
1402
1403 static struct user_specs *user_specs_head, *user_specs_tail;
1404
1405
1406 /* Record the mapping from file suffixes for compilation specs. */
1407
1408 struct compiler
1409 {
1410 const char *suffix; /* Use this compiler for input files
1411 whose names end in this suffix. */
1412
1413 const char *spec; /* To use this compiler, run this spec. */
1414
1415 const char *cpp_spec; /* If non-NULL, substitute this spec
1416 for `%C', rather than the usual
1417 cpp_spec. */
1418 int combinable; /* If nonzero, compiler can deal with
1419 multiple source files at once (IMA). */
1420 int needs_preprocessing; /* If nonzero, source files need to
1421 be run through a preprocessor. */
1422 };
1423
1424 /* Pointer to a vector of `struct compiler' that gives the spec for
1425 compiling a file, based on its suffix.
1426 A file that does not end in any of these suffixes will be passed
1427 unchanged to the loader and nothing else will be done to it.
1428
1429 An entry containing two 0s is used to terminate the vector.
1430
1431 If multiple entries match a file, the last matching one is used. */
1432
1433 static struct compiler *compilers;
1434
1435 /* Number of entries in `compilers', not counting the null terminator. */
1436
1437 static int n_compilers;
1438
1439 /* The default list of file name suffixes and their compilation specs. */
1440
1441 static const struct compiler default_compilers[] =
1442 {
1443 /* Add lists of suffixes of known languages here. If those languages
1444 were not present when we built the driver, we will hit these copies
1445 and be given a more meaningful error than "file not used since
1446 linking is not done". */
1447 {".m", "#Objective-C", 0, 0, 0}, {".mi", "#Objective-C", 0, 0, 0},
1448 {".mm", "#Objective-C++", 0, 0, 0}, {".M", "#Objective-C++", 0, 0, 0},
1449 {".mii", "#Objective-C++", 0, 0, 0},
1450 {".cc", "#C++", 0, 0, 0}, {".cxx", "#C++", 0, 0, 0},
1451 {".cpp", "#C++", 0, 0, 0}, {".cp", "#C++", 0, 0, 0},
1452 {".c++", "#C++", 0, 0, 0}, {".C", "#C++", 0, 0, 0},
1453 {".CPP", "#C++", 0, 0, 0}, {".ii", "#C++", 0, 0, 0},
1454 {".ads", "#Ada", 0, 0, 0}, {".adb", "#Ada", 0, 0, 0},
1455 {".f", "#Fortran", 0, 0, 0}, {".F", "#Fortran", 0, 0, 0},
1456 {".for", "#Fortran", 0, 0, 0}, {".FOR", "#Fortran", 0, 0, 0},
1457 {".ftn", "#Fortran", 0, 0, 0}, {".FTN", "#Fortran", 0, 0, 0},
1458 {".fpp", "#Fortran", 0, 0, 0}, {".FPP", "#Fortran", 0, 0, 0},
1459 {".f90", "#Fortran", 0, 0, 0}, {".F90", "#Fortran", 0, 0, 0},
1460 {".f95", "#Fortran", 0, 0, 0}, {".F95", "#Fortran", 0, 0, 0},
1461 {".f03", "#Fortran", 0, 0, 0}, {".F03", "#Fortran", 0, 0, 0},
1462 {".f08", "#Fortran", 0, 0, 0}, {".F08", "#Fortran", 0, 0, 0},
1463 {".r", "#Ratfor", 0, 0, 0},
1464 {".go", "#Go", 0, 1, 0},
1465 {".d", "#D", 0, 1, 0}, {".dd", "#D", 0, 1, 0}, {".di", "#D", 0, 1, 0},
1466 {".mod", "#Modula-2", 0, 0, 0}, {".m2i", "#Modula-2", 0, 0, 0},
1467 /* Next come the entries for C. */
1468 {".c", "@c", 0, 0, 1},
1469 {"@c",
1470 /* cc1 has an integrated ISO C preprocessor. We should invoke the
1471 external preprocessor if -save-temps is given. */
1472 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
1473 %{!E:%{!M:%{!MM:\
1474 %{traditional:\
1475 %eGNU C no longer supports -traditional without -E}\
1476 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
1477 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
1478 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
1479 %(cc1_options)}\
1480 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
1481 cc1 %(cpp_unique_options) %(cc1_options)}}}\
1482 %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 1},
1483 {"-",
1484 "%{!E:%e-E or -x required when input is from standard input}\
1485 %(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)", 0, 0, 0},
1486 {".h", "@c-header", 0, 0, 0},
1487 {"@c-header",
1488 /* cc1 has an integrated ISO C preprocessor. We should invoke the
1489 external preprocessor if -save-temps is given. */
1490 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
1491 %{!E:%{!M:%{!MM:\
1492 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
1493 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
1494 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
1495 %(cc1_options)\
1496 %{!fsyntax-only:%{!S:-o %g.s} \
1497 %{!fdump-ada-spec*:%{!o*:--output-pch %w%i.gch}\
1498 %W{o*:--output-pch %w%*}}%{!S:%V}}}\
1499 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
1500 cc1 %(cpp_unique_options) %(cc1_options)\
1501 %{!fsyntax-only:%{!S:-o %g.s} \
1502 %{!fdump-ada-spec*:%{!o*:--output-pch %w%i.gch}\
1503 %W{o*:--output-pch %w%*}}%{!S:%V}}}}}}}}", 0, 0, 0},
1504 {".i", "@cpp-output", 0, 0, 0},
1505 {"@cpp-output",
1506 "%{!M:%{!MM:%{!E:cc1 -fpreprocessed %i %(cc1_options) %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 0},
1507 {".s", "@assembler", 0, 0, 0},
1508 {"@assembler",
1509 "%{!M:%{!MM:%{!E:%{!S:as %(asm_debug) %(asm_options) %i %A }}}}", 0, 0, 0},
1510 {".sx", "@assembler-with-cpp", 0, 0, 0},
1511 {".S", "@assembler-with-cpp", 0, 0, 0},
1512 {"@assembler-with-cpp",
1513 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
1514 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
1515 %{E|M|MM:%(cpp_debug_options)}\
1516 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
1517 as %(asm_debug) %(asm_options) %|.s %A }}}}"
1518 #else
1519 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
1520 %{E|M|MM:%(cpp_debug_options)}\
1521 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
1522 as %(asm_debug) %(asm_options) %m.s %A }}}}"
1523 #endif
1524 , 0, 0, 0},
1525
1526 #include "specs.h"
1527 /* Mark end of table. */
1528 {0, 0, 0, 0, 0}
1529 };
1530
1531 /* Number of elements in default_compilers, not counting the terminator. */
1532
1533 static const int n_default_compilers = ARRAY_SIZE (default_compilers) - 1;
1534
1535 typedef char *char_p; /* For DEF_VEC_P. */
1536
1537 /* A vector of options to give to the linker.
1538 These options are accumulated by %x,
1539 and substituted into the linker command with %X. */
1540 static vec<char_p> linker_options;
1541
1542 /* A vector of options to give to the assembler.
1543 These options are accumulated by -Wa,
1544 and substituted into the assembler command with %Y. */
1545 static vec<char_p> assembler_options;
1546
1547 /* A vector of options to give to the preprocessor.
1548 These options are accumulated by -Wp,
1549 and substituted into the preprocessor command with %Z. */
1550 static vec<char_p> preprocessor_options;
1551
1552 static char *
1553 skip_whitespace (char *p)
1554 {
1555 while (1)
1556 {
1557 /* A fully-blank line is a delimiter in the SPEC file and shouldn't
1558 be considered whitespace. */
1559 if (p[0] == '\n' && p[1] == '\n' && p[2] == '\n')
1560 return p + 1;
1561 else if (*p == '\n' || *p == ' ' || *p == '\t')
1562 p++;
1563 else if (*p == '#')
1564 {
1565 while (*p != '\n')
1566 p++;
1567 p++;
1568 }
1569 else
1570 break;
1571 }
1572
1573 return p;
1574 }
1575 /* Structures to keep track of prefixes to try when looking for files. */
1576
1577 struct prefix_list
1578 {
1579 const char *prefix; /* String to prepend to the path. */
1580 struct prefix_list *next; /* Next in linked list. */
1581 int require_machine_suffix; /* Don't use without machine_suffix. */
1582 /* 2 means try both machine_suffix and just_machine_suffix. */
1583 int priority; /* Sort key - priority within list. */
1584 int os_multilib; /* 1 if OS multilib scheme should be used,
1585 0 for GCC multilib scheme. */
1586 };
1587
1588 struct path_prefix
1589 {
1590 struct prefix_list *plist; /* List of prefixes to try */
1591 int max_len; /* Max length of a prefix in PLIST */
1592 const char *name; /* Name of this list (used in config stuff) */
1593 };
1594
1595 /* List of prefixes to try when looking for executables. */
1596
1597 static struct path_prefix exec_prefixes = { 0, 0, "exec" };
1598
1599 /* List of prefixes to try when looking for startup (crt0) files. */
1600
1601 static struct path_prefix startfile_prefixes = { 0, 0, "startfile" };
1602
1603 /* List of prefixes to try when looking for include files. */
1604
1605 static struct path_prefix include_prefixes = { 0, 0, "include" };
1606
1607 /* Suffix to attach to directories searched for commands.
1608 This looks like `MACHINE/VERSION/'. */
1609
1610 static const char *machine_suffix = 0;
1611
1612 /* Suffix to attach to directories searched for commands.
1613 This is just `MACHINE/'. */
1614
1615 static const char *just_machine_suffix = 0;
1616
1617 /* Adjusted value of GCC_EXEC_PREFIX envvar. */
1618
1619 static const char *gcc_exec_prefix;
1620
1621 /* Adjusted value of standard_libexec_prefix. */
1622
1623 static const char *gcc_libexec_prefix;
1624
1625 /* Default prefixes to attach to command names. */
1626
1627 #ifndef STANDARD_STARTFILE_PREFIX_1
1628 #define STANDARD_STARTFILE_PREFIX_1 "/lib/"
1629 #endif
1630 #ifndef STANDARD_STARTFILE_PREFIX_2
1631 #define STANDARD_STARTFILE_PREFIX_2 "/usr/lib/"
1632 #endif
1633
1634 #ifdef CROSS_DIRECTORY_STRUCTURE /* Don't use these prefixes for a cross compiler. */
1635 #undef MD_EXEC_PREFIX
1636 #undef MD_STARTFILE_PREFIX
1637 #undef MD_STARTFILE_PREFIX_1
1638 #endif
1639
1640 /* If no prefixes defined, use the null string, which will disable them. */
1641 #ifndef MD_EXEC_PREFIX
1642 #define MD_EXEC_PREFIX ""
1643 #endif
1644 #ifndef MD_STARTFILE_PREFIX
1645 #define MD_STARTFILE_PREFIX ""
1646 #endif
1647 #ifndef MD_STARTFILE_PREFIX_1
1648 #define MD_STARTFILE_PREFIX_1 ""
1649 #endif
1650
1651 /* These directories are locations set at configure-time based on the
1652 --prefix option provided to configure. Their initializers are
1653 defined in Makefile.in. These paths are not *directly* used when
1654 gcc_exec_prefix is set because, in that case, we know where the
1655 compiler has been installed, and use paths relative to that
1656 location instead. */
1657 static const char *const standard_exec_prefix = STANDARD_EXEC_PREFIX;
1658 static const char *const standard_libexec_prefix = STANDARD_LIBEXEC_PREFIX;
1659 static const char *const standard_bindir_prefix = STANDARD_BINDIR_PREFIX;
1660 static const char *const standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
1661
1662 /* For native compilers, these are well-known paths containing
1663 components that may be provided by the system. For cross
1664 compilers, these paths are not used. */
1665 static const char *md_exec_prefix = MD_EXEC_PREFIX;
1666 static const char *md_startfile_prefix = MD_STARTFILE_PREFIX;
1667 static const char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
1668 static const char *const standard_startfile_prefix_1
1669 = STANDARD_STARTFILE_PREFIX_1;
1670 static const char *const standard_startfile_prefix_2
1671 = STANDARD_STARTFILE_PREFIX_2;
1672
1673 /* A relative path to be used in finding the location of tools
1674 relative to the driver. */
1675 static const char *const tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
1676
1677 /* A prefix to be used when this is an accelerator compiler. */
1678 static const char *const accel_dir_suffix = ACCEL_DIR_SUFFIX;
1679
1680 /* Subdirectory to use for locating libraries. Set by
1681 set_multilib_dir based on the compilation options. */
1682
1683 static const char *multilib_dir;
1684
1685 /* Subdirectory to use for locating libraries in OS conventions. Set by
1686 set_multilib_dir based on the compilation options. */
1687
1688 static const char *multilib_os_dir;
1689
1690 /* Subdirectory to use for locating libraries in multiarch conventions. Set by
1691 set_multilib_dir based on the compilation options. */
1692
1693 static const char *multiarch_dir;
1694
1695 /* Structure to keep track of the specs that have been defined so far.
1696 These are accessed using %(specname) in a compiler or link
1697 spec. */
1698
1699 struct spec_list
1700 {
1701 /* The following 2 fields must be first */
1702 /* to allow EXTRA_SPECS to be initialized */
1703 const char *name; /* name of the spec. */
1704 const char *ptr; /* available ptr if no static pointer */
1705
1706 /* The following fields are not initialized */
1707 /* by EXTRA_SPECS */
1708 const char **ptr_spec; /* pointer to the spec itself. */
1709 struct spec_list *next; /* Next spec in linked list. */
1710 int name_len; /* length of the name */
1711 bool user_p; /* whether string come from file spec. */
1712 bool alloc_p; /* whether string was allocated */
1713 const char *default_ptr; /* The default value of *ptr_spec. */
1714 };
1715
1716 #define INIT_STATIC_SPEC(NAME,PTR) \
1717 { NAME, NULL, PTR, (struct spec_list *) 0, sizeof (NAME) - 1, false, false, \
1718 *PTR }
1719
1720 /* List of statically defined specs. */
1721 static struct spec_list static_specs[] =
1722 {
1723 INIT_STATIC_SPEC ("asm", &asm_spec),
1724 INIT_STATIC_SPEC ("asm_debug", &asm_debug),
1725 INIT_STATIC_SPEC ("asm_debug_option", &asm_debug_option),
1726 INIT_STATIC_SPEC ("asm_final", &asm_final_spec),
1727 INIT_STATIC_SPEC ("asm_options", &asm_options),
1728 INIT_STATIC_SPEC ("invoke_as", &invoke_as),
1729 INIT_STATIC_SPEC ("cpp", &cpp_spec),
1730 INIT_STATIC_SPEC ("cpp_options", &cpp_options),
1731 INIT_STATIC_SPEC ("cpp_debug_options", &cpp_debug_options),
1732 INIT_STATIC_SPEC ("cpp_unique_options", &cpp_unique_options),
1733 INIT_STATIC_SPEC ("trad_capable_cpp", &trad_capable_cpp),
1734 INIT_STATIC_SPEC ("cc1", &cc1_spec),
1735 INIT_STATIC_SPEC ("cc1_options", &cc1_options),
1736 INIT_STATIC_SPEC ("cc1plus", &cc1plus_spec),
1737 INIT_STATIC_SPEC ("link_gcc_c_sequence", &link_gcc_c_sequence_spec),
1738 INIT_STATIC_SPEC ("link_ssp", &link_ssp_spec),
1739 INIT_STATIC_SPEC ("endfile", &endfile_spec),
1740 INIT_STATIC_SPEC ("link", &link_spec),
1741 INIT_STATIC_SPEC ("lib", &lib_spec),
1742 INIT_STATIC_SPEC ("link_gomp", &link_gomp_spec),
1743 INIT_STATIC_SPEC ("libgcc", &libgcc_spec),
1744 INIT_STATIC_SPEC ("startfile", &startfile_spec),
1745 INIT_STATIC_SPEC ("cross_compile", &cross_compile),
1746 INIT_STATIC_SPEC ("version", &compiler_version),
1747 INIT_STATIC_SPEC ("multilib", &multilib_select),
1748 INIT_STATIC_SPEC ("multilib_defaults", &multilib_defaults),
1749 INIT_STATIC_SPEC ("multilib_extra", &multilib_extra),
1750 INIT_STATIC_SPEC ("multilib_matches", &multilib_matches),
1751 INIT_STATIC_SPEC ("multilib_exclusions", &multilib_exclusions),
1752 INIT_STATIC_SPEC ("multilib_options", &multilib_options),
1753 INIT_STATIC_SPEC ("multilib_reuse", &multilib_reuse),
1754 INIT_STATIC_SPEC ("linker", &linker_name_spec),
1755 INIT_STATIC_SPEC ("linker_plugin_file", &linker_plugin_file_spec),
1756 INIT_STATIC_SPEC ("lto_wrapper", &lto_wrapper_spec),
1757 INIT_STATIC_SPEC ("lto_gcc", &lto_gcc_spec),
1758 INIT_STATIC_SPEC ("post_link", &post_link_spec),
1759 INIT_STATIC_SPEC ("link_libgcc", &link_libgcc_spec),
1760 INIT_STATIC_SPEC ("md_exec_prefix", &md_exec_prefix),
1761 INIT_STATIC_SPEC ("md_startfile_prefix", &md_startfile_prefix),
1762 INIT_STATIC_SPEC ("md_startfile_prefix_1", &md_startfile_prefix_1),
1763 INIT_STATIC_SPEC ("startfile_prefix_spec", &startfile_prefix_spec),
1764 INIT_STATIC_SPEC ("sysroot_spec", &sysroot_spec),
1765 INIT_STATIC_SPEC ("sysroot_suffix_spec", &sysroot_suffix_spec),
1766 INIT_STATIC_SPEC ("sysroot_hdrs_suffix_spec", &sysroot_hdrs_suffix_spec),
1767 INIT_STATIC_SPEC ("self_spec", &self_spec),
1768 };
1769
1770 #ifdef EXTRA_SPECS /* additional specs needed */
1771 /* Structure to keep track of just the first two args of a spec_list.
1772 That is all that the EXTRA_SPECS macro gives us. */
1773 struct spec_list_1
1774 {
1775 const char *const name;
1776 const char *const ptr;
1777 };
1778
1779 static const struct spec_list_1 extra_specs_1[] = { EXTRA_SPECS };
1780 static struct spec_list *extra_specs = (struct spec_list *) 0;
1781 #endif
1782
1783 /* List of dynamically allocates specs that have been defined so far. */
1784
1785 static struct spec_list *specs = (struct spec_list *) 0;
1786
1787 /* List of static spec functions. */
1788
1789 static const struct spec_function static_spec_functions[] =
1790 {
1791 { "getenv", getenv_spec_function },
1792 { "if-exists", if_exists_spec_function },
1793 { "if-exists-else", if_exists_else_spec_function },
1794 { "if-exists-then-else", if_exists_then_else_spec_function },
1795 { "sanitize", sanitize_spec_function },
1796 { "replace-outfile", replace_outfile_spec_function },
1797 { "remove-outfile", remove_outfile_spec_function },
1798 { "version-compare", version_compare_spec_function },
1799 { "include", include_spec_function },
1800 { "find-file", find_file_spec_function },
1801 { "find-plugindir", find_plugindir_spec_function },
1802 { "print-asm-header", print_asm_header_spec_function },
1803 { "compare-debug-dump-opt", compare_debug_dump_opt_spec_function },
1804 { "compare-debug-self-opt", compare_debug_self_opt_spec_function },
1805 { "pass-through-libs", pass_through_libs_spec_func },
1806 { "dumps", dumps_spec_func },
1807 { "gt", greater_than_spec_func },
1808 { "debug-level-gt", debug_level_greater_than_spec_func },
1809 { "dwarf-version-gt", dwarf_version_greater_than_spec_func },
1810 { "fortran-preinclude-file", find_fortran_preinclude_file},
1811 { "join", join_spec_func},
1812 { "if-driverlang", if_driverlang_spec_function },
1813 #ifdef EXTRA_SPEC_FUNCTIONS
1814 EXTRA_SPEC_FUNCTIONS
1815 #endif
1816 { 0, 0 }
1817 };
1818
1819 static int processing_spec_function;
1820
1821 /* Add appropriate libgcc specs to OBSTACK, taking into account
1822 various permutations of -shared-libgcc, -shared, and such. */
1823
1824 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1825
1826 #ifndef USE_LD_AS_NEEDED
1827 #define USE_LD_AS_NEEDED 0
1828 #endif
1829
1830 static void
1831 init_gcc_specs (struct obstack *obstack, const char *shared_name,
1832 const char *static_name, const char *eh_name)
1833 {
1834 char *buf;
1835
1836 #if USE_LD_AS_NEEDED
1837 buf = concat ("%{static|static-libgcc|static-pie:", static_name, " ", eh_name, "}"
1838 "%{!static:%{!static-libgcc:%{!static-pie:"
1839 "%{!shared-libgcc:",
1840 static_name, " " LD_AS_NEEDED_OPTION " ",
1841 shared_name, " " LD_NO_AS_NEEDED_OPTION
1842 "}"
1843 "%{shared-libgcc:",
1844 shared_name, "%{!shared: ", static_name, "}"
1845 "}}"
1846 #else
1847 buf = concat ("%{static|static-libgcc:", static_name, " ", eh_name, "}"
1848 "%{!static:%{!static-libgcc:"
1849 "%{!shared:"
1850 "%{!shared-libgcc:", static_name, " ", eh_name, "}"
1851 "%{shared-libgcc:", shared_name, " ", static_name, "}"
1852 "}"
1853 #ifdef LINK_EH_SPEC
1854 "%{shared:"
1855 "%{shared-libgcc:", shared_name, "}"
1856 "%{!shared-libgcc:", static_name, "}"
1857 "}"
1858 #else
1859 "%{shared:", shared_name, "}"
1860 #endif
1861 #endif
1862 "}}", NULL);
1863
1864 obstack_grow (obstack, buf, strlen (buf));
1865 free (buf);
1866 }
1867 #endif /* ENABLE_SHARED_LIBGCC */
1868
1869 /* Initialize the specs lookup routines. */
1870
1871 static void
1872 init_spec (void)
1873 {
1874 struct spec_list *next = (struct spec_list *) 0;
1875 struct spec_list *sl = (struct spec_list *) 0;
1876 int i;
1877
1878 if (specs)
1879 return; /* Already initialized. */
1880
1881 if (verbose_flag)
1882 fnotice (stderr, "Using built-in specs.\n");
1883
1884 #ifdef EXTRA_SPECS
1885 extra_specs = XCNEWVEC (struct spec_list, ARRAY_SIZE (extra_specs_1));
1886
1887 for (i = ARRAY_SIZE (extra_specs_1) - 1; i >= 0; i--)
1888 {
1889 sl = &extra_specs[i];
1890 sl->name = extra_specs_1[i].name;
1891 sl->ptr = extra_specs_1[i].ptr;
1892 sl->next = next;
1893 sl->name_len = strlen (sl->name);
1894 sl->ptr_spec = &sl->ptr;
1895 gcc_assert (sl->ptr_spec != NULL);
1896 sl->default_ptr = sl->ptr;
1897 next = sl;
1898 }
1899 #endif
1900
1901 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1902 {
1903 sl = &static_specs[i];
1904 sl->next = next;
1905 next = sl;
1906 }
1907
1908 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1909 /* ??? If neither -shared-libgcc nor --static-libgcc was
1910 seen, then we should be making an educated guess. Some proposed
1911 heuristics for ELF include:
1912
1913 (1) If "-Wl,--export-dynamic", then it's a fair bet that the
1914 program will be doing dynamic loading, which will likely
1915 need the shared libgcc.
1916
1917 (2) If "-ldl", then it's also a fair bet that we're doing
1918 dynamic loading.
1919
1920 (3) For each ET_DYN we're linking against (either through -lfoo
1921 or /some/path/foo.so), check to see whether it or one of
1922 its dependencies depends on a shared libgcc.
1923
1924 (4) If "-shared"
1925
1926 If the runtime is fixed to look for program headers instead
1927 of calling __register_frame_info at all, for each object,
1928 use the shared libgcc if any EH symbol referenced.
1929
1930 If crtstuff is fixed to not invoke __register_frame_info
1931 automatically, for each object, use the shared libgcc if
1932 any non-empty unwind section found.
1933
1934 Doing any of this probably requires invoking an external program to
1935 do the actual object file scanning. */
1936 {
1937 const char *p = libgcc_spec;
1938 int in_sep = 1;
1939
1940 /* Transform the extant libgcc_spec into one that uses the shared libgcc
1941 when given the proper command line arguments. */
1942 while (*p)
1943 {
1944 if (in_sep && *p == '-' && startswith (p, "-lgcc"))
1945 {
1946 init_gcc_specs (&obstack,
1947 "-lgcc_s"
1948 #ifdef USE_LIBUNWIND_EXCEPTIONS
1949 " -lunwind"
1950 #endif
1951 ,
1952 "-lgcc",
1953 "-lgcc_eh"
1954 #ifdef USE_LIBUNWIND_EXCEPTIONS
1955 # ifdef HAVE_LD_STATIC_DYNAMIC
1956 " %{!static:%{!static-pie:" LD_STATIC_OPTION "}} -lunwind"
1957 " %{!static:%{!static-pie:" LD_DYNAMIC_OPTION "}}"
1958 # else
1959 " -lunwind"
1960 # endif
1961 #endif
1962 );
1963
1964 p += 5;
1965 in_sep = 0;
1966 }
1967 else if (in_sep && *p == 'l' && startswith (p, "libgcc.a%s"))
1968 {
1969 /* Ug. We don't know shared library extensions. Hope that
1970 systems that use this form don't do shared libraries. */
1971 init_gcc_specs (&obstack,
1972 "-lgcc_s",
1973 "libgcc.a%s",
1974 "libgcc_eh.a%s"
1975 #ifdef USE_LIBUNWIND_EXCEPTIONS
1976 " -lunwind"
1977 #endif
1978 );
1979 p += 10;
1980 in_sep = 0;
1981 }
1982 else
1983 {
1984 obstack_1grow (&obstack, *p);
1985 in_sep = (*p == ' ');
1986 p += 1;
1987 }
1988 }
1989
1990 obstack_1grow (&obstack, '\0');
1991 libgcc_spec = XOBFINISH (&obstack, const char *);
1992 }
1993 #endif
1994 #ifdef USE_AS_TRADITIONAL_FORMAT
1995 /* Prepend "--traditional-format" to whatever asm_spec we had before. */
1996 {
1997 static const char tf[] = "--traditional-format ";
1998 obstack_grow (&obstack, tf, sizeof (tf) - 1);
1999 obstack_grow0 (&obstack, asm_spec, strlen (asm_spec));
2000 asm_spec = XOBFINISH (&obstack, const char *);
2001 }
2002 #endif
2003
2004 #if defined LINK_EH_SPEC || defined LINK_BUILDID_SPEC || \
2005 defined LINKER_HASH_STYLE
2006 # ifdef LINK_BUILDID_SPEC
2007 /* Prepend LINK_BUILDID_SPEC to whatever link_spec we had before. */
2008 obstack_grow (&obstack, LINK_BUILDID_SPEC, sizeof (LINK_BUILDID_SPEC) - 1);
2009 # endif
2010 # ifdef LINK_EH_SPEC
2011 /* Prepend LINK_EH_SPEC to whatever link_spec we had before. */
2012 obstack_grow (&obstack, LINK_EH_SPEC, sizeof (LINK_EH_SPEC) - 1);
2013 # endif
2014 # ifdef LINKER_HASH_STYLE
2015 /* Prepend --hash-style=LINKER_HASH_STYLE to whatever link_spec we had
2016 before. */
2017 {
2018 static const char hash_style[] = "--hash-style=";
2019 obstack_grow (&obstack, hash_style, sizeof (hash_style) - 1);
2020 obstack_grow (&obstack, LINKER_HASH_STYLE, sizeof (LINKER_HASH_STYLE) - 1);
2021 obstack_1grow (&obstack, ' ');
2022 }
2023 # endif
2024 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
2025 link_spec = XOBFINISH (&obstack, const char *);
2026 #endif
2027
2028 specs = sl;
2029 }
2030
2031 /* Update the entry for SPEC in the static_specs table to point to VALUE,
2032 ensuring that we free the previous value if necessary. Set alloc_p for the
2033 entry to ALLOC_P: this determines whether we take ownership of VALUE (i.e.
2034 whether we need to free it later on). */
2035 static void
2036 set_static_spec (const char **spec, const char *value, bool alloc_p)
2037 {
2038 struct spec_list *sl = NULL;
2039
2040 for (unsigned i = 0; i < ARRAY_SIZE (static_specs); i++)
2041 {
2042 if (static_specs[i].ptr_spec == spec)
2043 {
2044 sl = static_specs + i;
2045 break;
2046 }
2047 }
2048
2049 gcc_assert (sl);
2050
2051 if (sl->alloc_p)
2052 {
2053 const char *old = *spec;
2054 free (const_cast <char *> (old));
2055 }
2056
2057 *spec = value;
2058 sl->alloc_p = alloc_p;
2059 }
2060
2061 /* Update a static spec to a new string, taking ownership of that
2062 string's memory. */
2063 static void set_static_spec_owned (const char **spec, const char *val)
2064 {
2065 return set_static_spec (spec, val, true);
2066 }
2067
2068 /* Update a static spec to point to a new value, but don't take
2069 ownership of (i.e. don't free) that string. */
2070 static void set_static_spec_shared (const char **spec, const char *val)
2071 {
2072 return set_static_spec (spec, val, false);
2073 }
2074
2075
2076 /* Change the value of spec NAME to SPEC. If SPEC is empty, then the spec is
2077 removed; If the spec starts with a + then SPEC is added to the end of the
2078 current spec. */
2079
2080 static void
2081 set_spec (const char *name, const char *spec, bool user_p)
2082 {
2083 struct spec_list *sl;
2084 const char *old_spec;
2085 int name_len = strlen (name);
2086 int i;
2087
2088 /* If this is the first call, initialize the statically allocated specs. */
2089 if (!specs)
2090 {
2091 struct spec_list *next = (struct spec_list *) 0;
2092 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
2093 {
2094 sl = &static_specs[i];
2095 sl->next = next;
2096 next = sl;
2097 }
2098 specs = sl;
2099 }
2100
2101 /* See if the spec already exists. */
2102 for (sl = specs; sl; sl = sl->next)
2103 if (name_len == sl->name_len && !strcmp (sl->name, name))
2104 break;
2105
2106 if (!sl)
2107 {
2108 /* Not found - make it. */
2109 sl = XNEW (struct spec_list);
2110 sl->name = xstrdup (name);
2111 sl->name_len = name_len;
2112 sl->ptr_spec = &sl->ptr;
2113 sl->alloc_p = 0;
2114 *(sl->ptr_spec) = "";
2115 sl->next = specs;
2116 sl->default_ptr = NULL;
2117 specs = sl;
2118 }
2119
2120 old_spec = *(sl->ptr_spec);
2121 *(sl->ptr_spec) = ((spec[0] == '+' && ISSPACE ((unsigned char)spec[1]))
2122 ? concat (old_spec, spec + 1, NULL)
2123 : xstrdup (spec));
2124
2125 #ifdef DEBUG_SPECS
2126 if (verbose_flag)
2127 fnotice (stderr, "Setting spec %s to '%s'\n\n", name, *(sl->ptr_spec));
2128 #endif
2129
2130 /* Free the old spec. */
2131 if (old_spec && sl->alloc_p)
2132 free (CONST_CAST (char *, old_spec));
2133
2134 sl->user_p = user_p;
2135 sl->alloc_p = true;
2136 }
2137
2138 /* Accumulate a command (program name and args), and run it. */
2139
2140 typedef const char *const_char_p; /* For DEF_VEC_P. */
2141
2142 /* Vector of pointers to arguments in the current line of specifications. */
2143 static vec<const_char_p> argbuf;
2144
2145 /* Likewise, but for the current @file. */
2146 static vec<const_char_p> at_file_argbuf;
2147
2148 /* Whether an @file is currently open. */
2149 static bool in_at_file = false;
2150
2151 /* Were the options -c, -S or -E passed. */
2152 static int have_c = 0;
2153
2154 /* Was the option -o passed. */
2155 static int have_o = 0;
2156
2157 /* Was the option -E passed. */
2158 static int have_E = 0;
2159
2160 /* Pointer to output file name passed in with -o. */
2161 static const char *output_file = 0;
2162
2163 /* Pointer to input file name passed in with -truncate.
2164 This file should be truncated after linking. */
2165 static const char *totruncate_file = 0;
2166
2167 /* This is the list of suffixes and codes (%g/%u/%U/%j) and the associated
2168 temp file. If the HOST_BIT_BUCKET is used for %j, no entry is made for
2169 it here. */
2170
2171 static struct temp_name {
2172 const char *suffix; /* suffix associated with the code. */
2173 int length; /* strlen (suffix). */
2174 int unique; /* Indicates whether %g or %u/%U was used. */
2175 const char *filename; /* associated filename. */
2176 int filename_length; /* strlen (filename). */
2177 struct temp_name *next;
2178 } *temp_names;
2179
2180 /* Number of commands executed so far. */
2181
2182 static int execution_count;
2183
2184 /* Number of commands that exited with a signal. */
2185
2186 static int signal_count;
2187
2188 /* Allocate the argument vector. */
2189
2190 static void
2191 alloc_args (void)
2192 {
2193 argbuf.create (10);
2194 at_file_argbuf.create (10);
2195 }
2196
2197 /* Clear out the vector of arguments (after a command is executed). */
2198
2199 static void
2200 clear_args (void)
2201 {
2202 argbuf.truncate (0);
2203 at_file_argbuf.truncate (0);
2204 }
2205
2206 /* Add one argument to the vector at the end.
2207 This is done when a space is seen or at the end of the line.
2208 If DELETE_ALWAYS is nonzero, the arg is a filename
2209 and the file should be deleted eventually.
2210 If DELETE_FAILURE is nonzero, the arg is a filename
2211 and the file should be deleted if this compilation fails. */
2212
2213 static void
2214 store_arg (const char *arg, int delete_always, int delete_failure)
2215 {
2216 if (in_at_file)
2217 at_file_argbuf.safe_push (arg);
2218 else
2219 argbuf.safe_push (arg);
2220
2221 if (delete_always || delete_failure)
2222 {
2223 const char *p;
2224 /* If the temporary file we should delete is specified as
2225 part of a joined argument extract the filename. */
2226 if (arg[0] == '-'
2227 && (p = strrchr (arg, '=')))
2228 arg = p + 1;
2229 record_temp_file (arg, delete_always, delete_failure);
2230 }
2231 }
2232
2233 /* Open a temporary @file into which subsequent arguments will be stored. */
2234
2235 static void
2236 open_at_file (void)
2237 {
2238 if (in_at_file)
2239 fatal_error (input_location, "cannot open nested response file");
2240 else
2241 in_at_file = true;
2242 }
2243
2244 /* Create a temporary @file name. */
2245
2246 static char *make_at_file (void)
2247 {
2248 static int fileno = 0;
2249 char filename[20];
2250 const char *base, *ext;
2251
2252 if (!save_temps_flag)
2253 return make_temp_file ("");
2254
2255 base = dumpbase;
2256 if (!(base && *base))
2257 base = dumpdir;
2258 if (!(base && *base))
2259 base = "a";
2260
2261 sprintf (filename, ".args.%d", fileno++);
2262 ext = filename;
2263
2264 if (base == dumpdir && dumpdir_trailing_dash_added)
2265 ext++;
2266
2267 return concat (base, ext, NULL);
2268 }
2269
2270 /* Close the temporary @file and add @file to the argument list. */
2271
2272 static void
2273 close_at_file (void)
2274 {
2275 if (!in_at_file)
2276 fatal_error (input_location, "cannot close nonexistent response file");
2277
2278 in_at_file = false;
2279
2280 const unsigned int n_args = at_file_argbuf.length ();
2281 if (n_args == 0)
2282 return;
2283
2284 char **argv = XALLOCAVEC (char *, n_args + 1);
2285 char *temp_file = make_at_file ();
2286 char *at_argument = concat ("@", temp_file, NULL);
2287 FILE *f = fopen (temp_file, "w");
2288 int status;
2289 unsigned int i;
2290
2291 /* Copy the strings over. */
2292 for (i = 0; i < n_args; i++)
2293 argv[i] = CONST_CAST (char *, at_file_argbuf[i]);
2294 argv[i] = NULL;
2295
2296 at_file_argbuf.truncate (0);
2297
2298 if (f == NULL)
2299 fatal_error (input_location, "could not open temporary response file %s",
2300 temp_file);
2301
2302 status = writeargv (argv, f);
2303
2304 if (status)
2305 fatal_error (input_location,
2306 "could not write to temporary response file %s",
2307 temp_file);
2308
2309 status = fclose (f);
2310
2311 if (status == EOF)
2312 fatal_error (input_location, "could not close temporary response file %s",
2313 temp_file);
2314
2315 store_arg (at_argument, 0, 0);
2316
2317 record_temp_file (temp_file, !save_temps_flag, !save_temps_flag);
2318 }
2319
2320 /* Load specs from a file name named FILENAME, replacing occurrences of
2321 various different types of line-endings, \r\n, \n\r and just \r, with
2322 a single \n. */
2323
2324 static char *
2325 load_specs (const char *filename)
2326 {
2327 int desc;
2328 int readlen;
2329 struct stat statbuf;
2330 char *buffer;
2331 char *buffer_p;
2332 char *specs;
2333 char *specs_p;
2334
2335 if (verbose_flag)
2336 fnotice (stderr, "Reading specs from %s\n", filename);
2337
2338 /* Open and stat the file. */
2339 desc = open (filename, O_RDONLY, 0);
2340 if (desc < 0)
2341 {
2342 failed:
2343 /* This leaves DESC open, but the OS will save us. */
2344 fatal_error (input_location, "cannot read spec file %qs: %m", filename);
2345 }
2346
2347 if (stat (filename, &statbuf) < 0)
2348 goto failed;
2349
2350 /* Read contents of file into BUFFER. */
2351 buffer = XNEWVEC (char, statbuf.st_size + 1);
2352 readlen = read (desc, buffer, (unsigned) statbuf.st_size);
2353 if (readlen < 0)
2354 goto failed;
2355 buffer[readlen] = 0;
2356 close (desc);
2357
2358 specs = XNEWVEC (char, readlen + 1);
2359 specs_p = specs;
2360 for (buffer_p = buffer; buffer_p && *buffer_p; buffer_p++)
2361 {
2362 int skip = 0;
2363 char c = *buffer_p;
2364 if (c == '\r')
2365 {
2366 if (buffer_p > buffer && *(buffer_p - 1) == '\n') /* \n\r */
2367 skip = 1;
2368 else if (*(buffer_p + 1) == '\n') /* \r\n */
2369 skip = 1;
2370 else /* \r */
2371 c = '\n';
2372 }
2373 if (! skip)
2374 *specs_p++ = c;
2375 }
2376 *specs_p = '\0';
2377
2378 free (buffer);
2379 return (specs);
2380 }
2381
2382 /* Read compilation specs from a file named FILENAME,
2383 replacing the default ones.
2384
2385 A suffix which starts with `*' is a definition for
2386 one of the machine-specific sub-specs. The "suffix" should be
2387 *asm, *cc1, *cpp, *link, *startfile, etc.
2388 The corresponding spec is stored in asm_spec, etc.,
2389 rather than in the `compilers' vector.
2390
2391 Anything invalid in the file is a fatal error. */
2392
2393 static void
2394 read_specs (const char *filename, bool main_p, bool user_p)
2395 {
2396 char *buffer;
2397 char *p;
2398
2399 buffer = load_specs (filename);
2400
2401 /* Scan BUFFER for specs, putting them in the vector. */
2402 p = buffer;
2403 while (1)
2404 {
2405 char *suffix;
2406 char *spec;
2407 char *in, *out, *p1, *p2, *p3;
2408
2409 /* Advance P in BUFFER to the next nonblank nocomment line. */
2410 p = skip_whitespace (p);
2411 if (*p == 0)
2412 break;
2413
2414 /* Is this a special command that starts with '%'? */
2415 /* Don't allow this for the main specs file, since it would
2416 encourage people to overwrite it. */
2417 if (*p == '%' && !main_p)
2418 {
2419 p1 = p;
2420 while (*p && *p != '\n')
2421 p++;
2422
2423 /* Skip '\n'. */
2424 p++;
2425
2426 if (startswith (p1, "%include")
2427 && (p1[sizeof "%include" - 1] == ' '
2428 || p1[sizeof "%include" - 1] == '\t'))
2429 {
2430 char *new_filename;
2431
2432 p1 += sizeof ("%include");
2433 while (*p1 == ' ' || *p1 == '\t')
2434 p1++;
2435
2436 if (*p1++ != '<' || p[-2] != '>')
2437 fatal_error (input_location,
2438 "specs %%include syntax malformed after "
2439 "%td characters", p1 - buffer + 1);
2440
2441 p[-2] = '\0';
2442 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
2443 read_specs (new_filename ? new_filename : p1, false, user_p);
2444 continue;
2445 }
2446 else if (startswith (p1, "%include_noerr")
2447 && (p1[sizeof "%include_noerr" - 1] == ' '
2448 || p1[sizeof "%include_noerr" - 1] == '\t'))
2449 {
2450 char *new_filename;
2451
2452 p1 += sizeof "%include_noerr";
2453 while (*p1 == ' ' || *p1 == '\t')
2454 p1++;
2455
2456 if (*p1++ != '<' || p[-2] != '>')
2457 fatal_error (input_location,
2458 "specs %%include syntax malformed after "
2459 "%td characters", p1 - buffer + 1);
2460
2461 p[-2] = '\0';
2462 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
2463 if (new_filename)
2464 read_specs (new_filename, false, user_p);
2465 else if (verbose_flag)
2466 fnotice (stderr, "could not find specs file %s\n", p1);
2467 continue;
2468 }
2469 else if (startswith (p1, "%rename")
2470 && (p1[sizeof "%rename" - 1] == ' '
2471 || p1[sizeof "%rename" - 1] == '\t'))
2472 {
2473 int name_len;
2474 struct spec_list *sl;
2475 struct spec_list *newsl;
2476
2477 /* Get original name. */
2478 p1 += sizeof "%rename";
2479 while (*p1 == ' ' || *p1 == '\t')
2480 p1++;
2481
2482 if (! ISALPHA ((unsigned char) *p1))
2483 fatal_error (input_location,
2484 "specs %%rename syntax malformed after "
2485 "%td characters", p1 - buffer);
2486
2487 p2 = p1;
2488 while (*p2 && !ISSPACE ((unsigned char) *p2))
2489 p2++;
2490
2491 if (*p2 != ' ' && *p2 != '\t')
2492 fatal_error (input_location,
2493 "specs %%rename syntax malformed after "
2494 "%td characters", p2 - buffer);
2495
2496 name_len = p2 - p1;
2497 *p2++ = '\0';
2498 while (*p2 == ' ' || *p2 == '\t')
2499 p2++;
2500
2501 if (! ISALPHA ((unsigned char) *p2))
2502 fatal_error (input_location,
2503 "specs %%rename syntax malformed after "
2504 "%td characters", p2 - buffer);
2505
2506 /* Get new spec name. */
2507 p3 = p2;
2508 while (*p3 && !ISSPACE ((unsigned char) *p3))
2509 p3++;
2510
2511 if (p3 != p - 1)
2512 fatal_error (input_location,
2513 "specs %%rename syntax malformed after "
2514 "%td characters", p3 - buffer);
2515 *p3 = '\0';
2516
2517 for (sl = specs; sl; sl = sl->next)
2518 if (name_len == sl->name_len && !strcmp (sl->name, p1))
2519 break;
2520
2521 if (!sl)
2522 fatal_error (input_location,
2523 "specs %s spec was not found to be renamed", p1);
2524
2525 if (strcmp (p1, p2) == 0)
2526 continue;
2527
2528 for (newsl = specs; newsl; newsl = newsl->next)
2529 if (strcmp (newsl->name, p2) == 0)
2530 fatal_error (input_location,
2531 "%s: attempt to rename spec %qs to "
2532 "already defined spec %qs",
2533 filename, p1, p2);
2534
2535 if (verbose_flag)
2536 {
2537 fnotice (stderr, "rename spec %s to %s\n", p1, p2);
2538 #ifdef DEBUG_SPECS
2539 fnotice (stderr, "spec is '%s'\n\n", *(sl->ptr_spec));
2540 #endif
2541 }
2542
2543 set_spec (p2, *(sl->ptr_spec), user_p);
2544 if (sl->alloc_p)
2545 free (CONST_CAST (char *, *(sl->ptr_spec)));
2546
2547 *(sl->ptr_spec) = "";
2548 sl->alloc_p = 0;
2549 continue;
2550 }
2551 else
2552 fatal_error (input_location,
2553 "specs unknown %% command after %td characters",
2554 p1 - buffer);
2555 }
2556
2557 /* Find the colon that should end the suffix. */
2558 p1 = p;
2559 while (*p1 && *p1 != ':' && *p1 != '\n')
2560 p1++;
2561
2562 /* The colon shouldn't be missing. */
2563 if (*p1 != ':')
2564 fatal_error (input_location,
2565 "specs file malformed after %td characters",
2566 p1 - buffer);
2567
2568 /* Skip back over trailing whitespace. */
2569 p2 = p1;
2570 while (p2 > buffer && (p2[-1] == ' ' || p2[-1] == '\t'))
2571 p2--;
2572
2573 /* Copy the suffix to a string. */
2574 suffix = save_string (p, p2 - p);
2575 /* Find the next line. */
2576 p = skip_whitespace (p1 + 1);
2577 if (p[1] == 0)
2578 fatal_error (input_location,
2579 "specs file malformed after %td characters",
2580 p - buffer);
2581
2582 p1 = p;
2583 /* Find next blank line or end of string. */
2584 while (*p1 && !(*p1 == '\n' && (p1[1] == '\n' || p1[1] == '\0')))
2585 p1++;
2586
2587 /* Specs end at the blank line and do not include the newline. */
2588 spec = save_string (p, p1 - p);
2589 p = p1;
2590
2591 /* Delete backslash-newline sequences from the spec. */
2592 in = spec;
2593 out = spec;
2594 while (*in != 0)
2595 {
2596 if (in[0] == '\\' && in[1] == '\n')
2597 in += 2;
2598 else if (in[0] == '#')
2599 while (*in && *in != '\n')
2600 in++;
2601
2602 else
2603 *out++ = *in++;
2604 }
2605 *out = 0;
2606
2607 if (suffix[0] == '*')
2608 {
2609 if (! strcmp (suffix, "*link_command"))
2610 link_command_spec = spec;
2611 else
2612 {
2613 set_spec (suffix + 1, spec, user_p);
2614 free (spec);
2615 }
2616 }
2617 else
2618 {
2619 /* Add this pair to the vector. */
2620 compilers
2621 = XRESIZEVEC (struct compiler, compilers, n_compilers + 2);
2622
2623 compilers[n_compilers].suffix = suffix;
2624 compilers[n_compilers].spec = spec;
2625 n_compilers++;
2626 memset (&compilers[n_compilers], 0, sizeof compilers[n_compilers]);
2627 }
2628
2629 if (*suffix == 0)
2630 link_command_spec = spec;
2631 }
2632
2633 if (link_command_spec == 0)
2634 fatal_error (input_location, "spec file has no spec for linking");
2635
2636 XDELETEVEC (buffer);
2637 }
2638
2639 /* Record the names of temporary files we tell compilers to write,
2640 and delete them at the end of the run. */
2641
2642 /* This is the common prefix we use to make temp file names.
2643 It is chosen once for each run of this program.
2644 It is substituted into a spec by %g or %j.
2645 Thus, all temp file names contain this prefix.
2646 In practice, all temp file names start with this prefix.
2647
2648 This prefix comes from the envvar TMPDIR if it is defined;
2649 otherwise, from the P_tmpdir macro if that is defined;
2650 otherwise, in /usr/tmp or /tmp;
2651 or finally the current directory if all else fails. */
2652
2653 static const char *temp_filename;
2654
2655 /* Length of the prefix. */
2656
2657 static int temp_filename_length;
2658
2659 /* Define the list of temporary files to delete. */
2660
2661 struct temp_file
2662 {
2663 const char *name;
2664 struct temp_file *next;
2665 };
2666
2667 /* Queue of files to delete on success or failure of compilation. */
2668 static struct temp_file *always_delete_queue;
2669 /* Queue of files to delete on failure of compilation. */
2670 static struct temp_file *failure_delete_queue;
2671
2672 /* Record FILENAME as a file to be deleted automatically.
2673 ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
2674 otherwise delete it in any case.
2675 FAIL_DELETE nonzero means delete it if a compilation step fails;
2676 otherwise delete it in any case. */
2677
2678 void
2679 record_temp_file (const char *filename, int always_delete, int fail_delete)
2680 {
2681 char *const name = xstrdup (filename);
2682
2683 if (always_delete)
2684 {
2685 struct temp_file *temp;
2686 for (temp = always_delete_queue; temp; temp = temp->next)
2687 if (! filename_cmp (name, temp->name))
2688 {
2689 free (name);
2690 goto already1;
2691 }
2692
2693 temp = XNEW (struct temp_file);
2694 temp->next = always_delete_queue;
2695 temp->name = name;
2696 always_delete_queue = temp;
2697
2698 already1:;
2699 }
2700
2701 if (fail_delete)
2702 {
2703 struct temp_file *temp;
2704 for (temp = failure_delete_queue; temp; temp = temp->next)
2705 if (! filename_cmp (name, temp->name))
2706 {
2707 free (name);
2708 goto already2;
2709 }
2710
2711 temp = XNEW (struct temp_file);
2712 temp->next = failure_delete_queue;
2713 temp->name = name;
2714 failure_delete_queue = temp;
2715
2716 already2:;
2717 }
2718 }
2719
2720 /* Delete all the temporary files whose names we previously recorded. */
2721
2722 #ifndef DELETE_IF_ORDINARY
2723 #define DELETE_IF_ORDINARY(NAME,ST,VERBOSE_FLAG) \
2724 do \
2725 { \
2726 if (stat (NAME, &ST) >= 0 && S_ISREG (ST.st_mode)) \
2727 if (unlink (NAME) < 0) \
2728 if (VERBOSE_FLAG) \
2729 error ("%s: %m", (NAME)); \
2730 } while (0)
2731 #endif
2732
2733 static void
2734 delete_if_ordinary (const char *name)
2735 {
2736 struct stat st;
2737 #ifdef DEBUG
2738 int i, c;
2739
2740 printf ("Delete %s? (y or n) ", name);
2741 fflush (stdout);
2742 i = getchar ();
2743 if (i != '\n')
2744 while ((c = getchar ()) != '\n' && c != EOF)
2745 ;
2746
2747 if (i == 'y' || i == 'Y')
2748 #endif /* DEBUG */
2749 DELETE_IF_ORDINARY (name, st, verbose_flag);
2750 }
2751
2752 static void
2753 delete_temp_files (void)
2754 {
2755 struct temp_file *temp;
2756
2757 for (temp = always_delete_queue; temp; temp = temp->next)
2758 delete_if_ordinary (temp->name);
2759 always_delete_queue = 0;
2760 }
2761
2762 /* Delete all the files to be deleted on error. */
2763
2764 static void
2765 delete_failure_queue (void)
2766 {
2767 struct temp_file *temp;
2768
2769 for (temp = failure_delete_queue; temp; temp = temp->next)
2770 delete_if_ordinary (temp->name);
2771 }
2772
2773 static void
2774 clear_failure_queue (void)
2775 {
2776 failure_delete_queue = 0;
2777 }
2778
2779 /* Call CALLBACK for each path in PATHS, breaking out early if CALLBACK
2780 returns non-NULL.
2781 If DO_MULTI is true iterate over the paths twice, first with multilib
2782 suffix then without, otherwise iterate over the paths once without
2783 adding a multilib suffix. When DO_MULTI is true, some attempt is made
2784 to avoid visiting the same path twice, but we could do better. For
2785 instance, /usr/lib/../lib is considered different from /usr/lib.
2786 At least EXTRA_SPACE chars past the end of the path passed to
2787 CALLBACK are available for use by the callback.
2788 CALLBACK_INFO allows extra parameters to be passed to CALLBACK.
2789
2790 Returns the value returned by CALLBACK. */
2791
2792 static void *
2793 for_each_path (const struct path_prefix *paths,
2794 bool do_multi,
2795 size_t extra_space,
2796 void *(*callback) (char *, void *),
2797 void *callback_info)
2798 {
2799 struct prefix_list *pl;
2800 const char *multi_dir = NULL;
2801 const char *multi_os_dir = NULL;
2802 const char *multiarch_suffix = NULL;
2803 const char *multi_suffix;
2804 const char *just_multi_suffix;
2805 char *path = NULL;
2806 void *ret = NULL;
2807 bool skip_multi_dir = false;
2808 bool skip_multi_os_dir = false;
2809
2810 multi_suffix = machine_suffix;
2811 just_multi_suffix = just_machine_suffix;
2812 if (do_multi && multilib_dir && strcmp (multilib_dir, ".") != 0)
2813 {
2814 multi_dir = concat (multilib_dir, dir_separator_str, NULL);
2815 multi_suffix = concat (multi_suffix, multi_dir, NULL);
2816 just_multi_suffix = concat (just_multi_suffix, multi_dir, NULL);
2817 }
2818 if (do_multi && multilib_os_dir && strcmp (multilib_os_dir, ".") != 0)
2819 multi_os_dir = concat (multilib_os_dir, dir_separator_str, NULL);
2820 if (multiarch_dir)
2821 multiarch_suffix = concat (multiarch_dir, dir_separator_str, NULL);
2822
2823 while (1)
2824 {
2825 size_t multi_dir_len = 0;
2826 size_t multi_os_dir_len = 0;
2827 size_t multiarch_len = 0;
2828 size_t suffix_len;
2829 size_t just_suffix_len;
2830 size_t len;
2831
2832 if (multi_dir)
2833 multi_dir_len = strlen (multi_dir);
2834 if (multi_os_dir)
2835 multi_os_dir_len = strlen (multi_os_dir);
2836 if (multiarch_suffix)
2837 multiarch_len = strlen (multiarch_suffix);
2838 suffix_len = strlen (multi_suffix);
2839 just_suffix_len = strlen (just_multi_suffix);
2840
2841 if (path == NULL)
2842 {
2843 len = paths->max_len + extra_space + 1;
2844 len += MAX (MAX (suffix_len, multi_os_dir_len), multiarch_len);
2845 path = XNEWVEC (char, len);
2846 }
2847
2848 for (pl = paths->plist; pl != 0; pl = pl->next)
2849 {
2850 len = strlen (pl->prefix);
2851 memcpy (path, pl->prefix, len);
2852
2853 /* Look first in MACHINE/VERSION subdirectory. */
2854 if (!skip_multi_dir)
2855 {
2856 memcpy (path + len, multi_suffix, suffix_len + 1);
2857 ret = callback (path, callback_info);
2858 if (ret)
2859 break;
2860 }
2861
2862 /* Some paths are tried with just the machine (ie. target)
2863 subdir. This is used for finding as, ld, etc. */
2864 if (!skip_multi_dir
2865 && pl->require_machine_suffix == 2)
2866 {
2867 memcpy (path + len, just_multi_suffix, just_suffix_len + 1);
2868 ret = callback (path, callback_info);
2869 if (ret)
2870 break;
2871 }
2872
2873 /* Now try the multiarch path. */
2874 if (!skip_multi_dir
2875 && !pl->require_machine_suffix && multiarch_dir)
2876 {
2877 memcpy (path + len, multiarch_suffix, multiarch_len + 1);
2878 ret = callback (path, callback_info);
2879 if (ret)
2880 break;
2881 }
2882
2883 /* Now try the base path. */
2884 if (!pl->require_machine_suffix
2885 && !(pl->os_multilib ? skip_multi_os_dir : skip_multi_dir))
2886 {
2887 const char *this_multi;
2888 size_t this_multi_len;
2889
2890 if (pl->os_multilib)
2891 {
2892 this_multi = multi_os_dir;
2893 this_multi_len = multi_os_dir_len;
2894 }
2895 else
2896 {
2897 this_multi = multi_dir;
2898 this_multi_len = multi_dir_len;
2899 }
2900
2901 if (this_multi_len)
2902 memcpy (path + len, this_multi, this_multi_len + 1);
2903 else
2904 path[len] = '\0';
2905
2906 ret = callback (path, callback_info);
2907 if (ret)
2908 break;
2909 }
2910 }
2911 if (pl)
2912 break;
2913
2914 if (multi_dir == NULL && multi_os_dir == NULL)
2915 break;
2916
2917 /* Run through the paths again, this time without multilibs.
2918 Don't repeat any we have already seen. */
2919 if (multi_dir)
2920 {
2921 free (CONST_CAST (char *, multi_dir));
2922 multi_dir = NULL;
2923 free (CONST_CAST (char *, multi_suffix));
2924 multi_suffix = machine_suffix;
2925 free (CONST_CAST (char *, just_multi_suffix));
2926 just_multi_suffix = just_machine_suffix;
2927 }
2928 else
2929 skip_multi_dir = true;
2930 if (multi_os_dir)
2931 {
2932 free (CONST_CAST (char *, multi_os_dir));
2933 multi_os_dir = NULL;
2934 }
2935 else
2936 skip_multi_os_dir = true;
2937 }
2938
2939 if (multi_dir)
2940 {
2941 free (CONST_CAST (char *, multi_dir));
2942 free (CONST_CAST (char *, multi_suffix));
2943 free (CONST_CAST (char *, just_multi_suffix));
2944 }
2945 if (multi_os_dir)
2946 free (CONST_CAST (char *, multi_os_dir));
2947 if (ret != path)
2948 free (path);
2949 return ret;
2950 }
2951
2952 /* Callback for build_search_list. Adds path to obstack being built. */
2953
2954 struct add_to_obstack_info {
2955 struct obstack *ob;
2956 bool check_dir;
2957 bool first_time;
2958 };
2959
2960 static void *
2961 add_to_obstack (char *path, void *data)
2962 {
2963 struct add_to_obstack_info *info = (struct add_to_obstack_info *) data;
2964
2965 if (info->check_dir && !is_directory (path))
2966 return NULL;
2967
2968 if (!info->first_time)
2969 obstack_1grow (info->ob, PATH_SEPARATOR);
2970
2971 obstack_grow (info->ob, path, strlen (path));
2972
2973 info->first_time = false;
2974 return NULL;
2975 }
2976
2977 /* Add or change the value of an environment variable, outputting the
2978 change to standard error if in verbose mode. */
2979 static void
2980 xputenv (const char *string)
2981 {
2982 env.xput (string);
2983 }
2984
2985 /* Build a list of search directories from PATHS.
2986 PREFIX is a string to prepend to the list.
2987 If CHECK_DIR_P is true we ensure the directory exists.
2988 If DO_MULTI is true, multilib paths are output first, then
2989 non-multilib paths.
2990 This is used mostly by putenv_from_prefixes so we use `collect_obstack'.
2991 It is also used by the --print-search-dirs flag. */
2992
2993 static char *
2994 build_search_list (const struct path_prefix *paths, const char *prefix,
2995 bool check_dir, bool do_multi)
2996 {
2997 struct add_to_obstack_info info;
2998
2999 info.ob = &collect_obstack;
3000 info.check_dir = check_dir;
3001 info.first_time = true;
3002
3003 obstack_grow (&collect_obstack, prefix, strlen (prefix));
3004 obstack_1grow (&collect_obstack, '=');
3005
3006 for_each_path (paths, do_multi, 0, add_to_obstack, &info);
3007
3008 obstack_1grow (&collect_obstack, '\0');
3009 return XOBFINISH (&collect_obstack, char *);
3010 }
3011
3012 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
3013 for collect. */
3014
3015 static void
3016 putenv_from_prefixes (const struct path_prefix *paths, const char *env_var,
3017 bool do_multi)
3018 {
3019 xputenv (build_search_list (paths, env_var, true, do_multi));
3020 }
3021
3022 /* Check whether NAME can be accessed in MODE. This is like access,
3023 except that it never considers directories to be executable. */
3024
3025 static int
3026 access_check (const char *name, int mode)
3027 {
3028 if (mode == X_OK)
3029 {
3030 struct stat st;
3031
3032 if (stat (name, &st) < 0
3033 || S_ISDIR (st.st_mode))
3034 return -1;
3035 }
3036
3037 return access (name, mode);
3038 }
3039
3040 /* Callback for find_a_file. Appends the file name to the directory
3041 path. If the resulting file exists in the right mode, return the
3042 full pathname to the file. */
3043
3044 struct file_at_path_info {
3045 const char *name;
3046 const char *suffix;
3047 int name_len;
3048 int suffix_len;
3049 int mode;
3050 };
3051
3052 static void *
3053 file_at_path (char *path, void *data)
3054 {
3055 struct file_at_path_info *info = (struct file_at_path_info *) data;
3056 size_t len = strlen (path);
3057
3058 memcpy (path + len, info->name, info->name_len);
3059 len += info->name_len;
3060
3061 /* Some systems have a suffix for executable files.
3062 So try appending that first. */
3063 if (info->suffix_len)
3064 {
3065 memcpy (path + len, info->suffix, info->suffix_len + 1);
3066 if (access_check (path, info->mode) == 0)
3067 return path;
3068 }
3069
3070 path[len] = '\0';
3071 if (access_check (path, info->mode) == 0)
3072 return path;
3073
3074 return NULL;
3075 }
3076
3077 /* Search for NAME using the prefix list PREFIXES. MODE is passed to
3078 access to check permissions. If DO_MULTI is true, search multilib
3079 paths then non-multilib paths, otherwise do not search multilib paths.
3080 Return 0 if not found, otherwise return its name, allocated with malloc. */
3081
3082 static char *
3083 find_a_file (const struct path_prefix *pprefix, const char *name, int mode,
3084 bool do_multi)
3085 {
3086 struct file_at_path_info info;
3087
3088 /* Find the filename in question (special case for absolute paths). */
3089
3090 if (IS_ABSOLUTE_PATH (name))
3091 {
3092 if (access (name, mode) == 0)
3093 return xstrdup (name);
3094
3095 return NULL;
3096 }
3097
3098 info.name = name;
3099 info.suffix = (mode & X_OK) != 0 ? HOST_EXECUTABLE_SUFFIX : "";
3100 info.name_len = strlen (info.name);
3101 info.suffix_len = strlen (info.suffix);
3102 info.mode = mode;
3103
3104 return (char*) for_each_path (pprefix, do_multi,
3105 info.name_len + info.suffix_len,
3106 file_at_path, &info);
3107 }
3108
3109 /* Specialization of find_a_file for programs that also takes into account
3110 configure-specified default programs. */
3111
3112 static char*
3113 find_a_program (const char *name)
3114 {
3115 /* Do not search if default matches query. */
3116
3117 #ifdef DEFAULT_ASSEMBLER
3118 if (! strcmp (name, "as") && access (DEFAULT_ASSEMBLER, X_OK) == 0)
3119 return xstrdup (DEFAULT_ASSEMBLER);
3120 #endif
3121
3122 #ifdef DEFAULT_LINKER
3123 if (! strcmp (name, "ld") && access (DEFAULT_LINKER, X_OK) == 0)
3124 return xstrdup (DEFAULT_LINKER);
3125 #endif
3126
3127 #ifdef DEFAULT_DSYMUTIL
3128 if (! strcmp (name, "dsymutil") && access (DEFAULT_DSYMUTIL, X_OK) == 0)
3129 return xstrdup (DEFAULT_DSYMUTIL);
3130 #endif
3131
3132 return find_a_file (&exec_prefixes, name, X_OK, false);
3133 }
3134
3135 /* Ranking of prefixes in the sort list. -B prefixes are put before
3136 all others. */
3137
3138 enum path_prefix_priority
3139 {
3140 PREFIX_PRIORITY_B_OPT,
3141 PREFIX_PRIORITY_LAST
3142 };
3143
3144 /* Add an entry for PREFIX in PLIST. The PLIST is kept in ascending
3145 order according to PRIORITY. Within each PRIORITY, new entries are
3146 appended.
3147
3148 If WARN is nonzero, we will warn if no file is found
3149 through this prefix. WARN should point to an int
3150 which will be set to 1 if this entry is used.
3151
3152 COMPONENT is the value to be passed to update_path.
3153
3154 REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
3155 the complete value of machine_suffix.
3156 2 means try both machine_suffix and just_machine_suffix. */
3157
3158 static void
3159 add_prefix (struct path_prefix *pprefix, const char *prefix,
3160 const char *component, /* enum prefix_priority */ int priority,
3161 int require_machine_suffix, int os_multilib)
3162 {
3163 struct prefix_list *pl, **prev;
3164 int len;
3165
3166 for (prev = &pprefix->plist;
3167 (*prev) != NULL && (*prev)->priority <= priority;
3168 prev = &(*prev)->next)
3169 ;
3170
3171 /* Keep track of the longest prefix. */
3172
3173 prefix = update_path (prefix, component);
3174 len = strlen (prefix);
3175 if (len > pprefix->max_len)
3176 pprefix->max_len = len;
3177
3178 pl = XNEW (struct prefix_list);
3179 pl->prefix = prefix;
3180 pl->require_machine_suffix = require_machine_suffix;
3181 pl->priority = priority;
3182 pl->os_multilib = os_multilib;
3183
3184 /* Insert after PREV. */
3185 pl->next = (*prev);
3186 (*prev) = pl;
3187 }
3188
3189 /* Same as add_prefix, but prepending target_system_root to prefix. */
3190 /* The target_system_root prefix has been relocated by gcc_exec_prefix. */
3191 static void
3192 add_sysrooted_prefix (struct path_prefix *pprefix, const char *prefix,
3193 const char *component,
3194 /* enum prefix_priority */ int priority,
3195 int require_machine_suffix, int os_multilib)
3196 {
3197 if (!IS_ABSOLUTE_PATH (prefix))
3198 fatal_error (input_location, "system path %qs is not absolute", prefix);
3199
3200 if (target_system_root)
3201 {
3202 char *sysroot_no_trailing_dir_separator = xstrdup (target_system_root);
3203 size_t sysroot_len = strlen (target_system_root);
3204
3205 if (sysroot_len > 0
3206 && target_system_root[sysroot_len - 1] == DIR_SEPARATOR)
3207 sysroot_no_trailing_dir_separator[sysroot_len - 1] = '\0';
3208
3209 if (target_sysroot_suffix)
3210 prefix = concat (sysroot_no_trailing_dir_separator,
3211 target_sysroot_suffix, prefix, NULL);
3212 else
3213 prefix = concat (sysroot_no_trailing_dir_separator, prefix, NULL);
3214
3215 free (sysroot_no_trailing_dir_separator);
3216
3217 /* We have to override this because GCC's notion of sysroot
3218 moves along with GCC. */
3219 component = "GCC";
3220 }
3221
3222 add_prefix (pprefix, prefix, component, priority,
3223 require_machine_suffix, os_multilib);
3224 }
3225
3226 /* Same as add_prefix, but prepending target_sysroot_hdrs_suffix to prefix. */
3227
3228 static void
3229 add_sysrooted_hdrs_prefix (struct path_prefix *pprefix, const char *prefix,
3230 const char *component,
3231 /* enum prefix_priority */ int priority,
3232 int require_machine_suffix, int os_multilib)
3233 {
3234 if (!IS_ABSOLUTE_PATH (prefix))
3235 fatal_error (input_location, "system path %qs is not absolute", prefix);
3236
3237 if (target_system_root)
3238 {
3239 char *sysroot_no_trailing_dir_separator = xstrdup (target_system_root);
3240 size_t sysroot_len = strlen (target_system_root);
3241
3242 if (sysroot_len > 0
3243 && target_system_root[sysroot_len - 1] == DIR_SEPARATOR)
3244 sysroot_no_trailing_dir_separator[sysroot_len - 1] = '\0';
3245
3246 if (target_sysroot_hdrs_suffix)
3247 prefix = concat (sysroot_no_trailing_dir_separator,
3248 target_sysroot_hdrs_suffix, prefix, NULL);
3249 else
3250 prefix = concat (sysroot_no_trailing_dir_separator, prefix, NULL);
3251
3252 free (sysroot_no_trailing_dir_separator);
3253
3254 /* We have to override this because GCC's notion of sysroot
3255 moves along with GCC. */
3256 component = "GCC";
3257 }
3258
3259 add_prefix (pprefix, prefix, component, priority,
3260 require_machine_suffix, os_multilib);
3261 }
3262
3263
3264 /* Execute the command specified by the arguments on the current line of spec.
3265 When using pipes, this includes several piped-together commands
3266 with `|' between them.
3267
3268 Return 0 if successful, -1 if failed. */
3269
3270 static int
3271 execute (void)
3272 {
3273 int i;
3274 int n_commands; /* # of command. */
3275 char *string;
3276 struct pex_obj *pex;
3277 struct command
3278 {
3279 const char *prog; /* program name. */
3280 const char **argv; /* vector of args. */
3281 };
3282 const char *arg;
3283
3284 struct command *commands; /* each command buffer with above info. */
3285
3286 gcc_assert (!processing_spec_function);
3287
3288 if (wrapper_string)
3289 {
3290 string = find_a_program (argbuf[0]);
3291 if (string)
3292 argbuf[0] = string;
3293 insert_wrapper (wrapper_string);
3294 }
3295
3296 /* Count # of piped commands. */
3297 for (n_commands = 1, i = 0; argbuf.iterate (i, &arg); i++)
3298 if (strcmp (arg, "|") == 0)
3299 n_commands++;
3300
3301 /* Get storage for each command. */
3302 commands = XALLOCAVEC (struct command, n_commands);
3303
3304 /* Split argbuf into its separate piped processes,
3305 and record info about each one.
3306 Also search for the programs that are to be run. */
3307
3308 argbuf.safe_push (0);
3309
3310 commands[0].prog = argbuf[0]; /* first command. */
3311 commands[0].argv = argbuf.address ();
3312
3313 if (!wrapper_string)
3314 {
3315 string = find_a_program(commands[0].prog);
3316 if (string)
3317 commands[0].argv[0] = string;
3318 }
3319
3320 for (n_commands = 1, i = 0; argbuf.iterate (i, &arg); i++)
3321 if (arg && strcmp (arg, "|") == 0)
3322 { /* each command. */
3323 #if defined (__MSDOS__) || defined (OS2) || defined (VMS)
3324 fatal_error (input_location, "%<-pipe%> not supported");
3325 #endif
3326 argbuf[i] = 0; /* Termination of command args. */
3327 commands[n_commands].prog = argbuf[i + 1];
3328 commands[n_commands].argv
3329 = &(argbuf.address ())[i + 1];
3330 string = find_a_program(commands[n_commands].prog);
3331 if (string)
3332 commands[n_commands].argv[0] = string;
3333 n_commands++;
3334 }
3335
3336 /* If -v, print what we are about to do, and maybe query. */
3337
3338 if (verbose_flag)
3339 {
3340 /* For help listings, put a blank line between sub-processes. */
3341 if (print_help_list)
3342 fputc ('\n', stderr);
3343
3344 /* Print each piped command as a separate line. */
3345 for (i = 0; i < n_commands; i++)
3346 {
3347 const char *const *j;
3348
3349 if (verbose_only_flag)
3350 {
3351 for (j = commands[i].argv; *j; j++)
3352 {
3353 const char *p;
3354 for (p = *j; *p; ++p)
3355 if (!ISALNUM ((unsigned char) *p)
3356 && *p != '_' && *p != '/' && *p != '-' && *p != '.')
3357 break;
3358 if (*p || !*j)
3359 {
3360 fprintf (stderr, " \"");
3361 for (p = *j; *p; ++p)
3362 {
3363 if (*p == '"' || *p == '\\' || *p == '$')
3364 fputc ('\\', stderr);
3365 fputc (*p, stderr);
3366 }
3367 fputc ('"', stderr);
3368 }
3369 /* If it's empty, print "". */
3370 else if (!**j)
3371 fprintf (stderr, " \"\"");
3372 else
3373 fprintf (stderr, " %s", *j);
3374 }
3375 }
3376 else
3377 for (j = commands[i].argv; *j; j++)
3378 /* If it's empty, print "". */
3379 if (!**j)
3380 fprintf (stderr, " \"\"");
3381 else
3382 fprintf (stderr, " %s", *j);
3383
3384 /* Print a pipe symbol after all but the last command. */
3385 if (i + 1 != n_commands)
3386 fprintf (stderr, " |");
3387 fprintf (stderr, "\n");
3388 }
3389 fflush (stderr);
3390 if (verbose_only_flag != 0)
3391 {
3392 /* verbose_only_flag should act as if the spec was
3393 executed, so increment execution_count before
3394 returning. This prevents spurious warnings about
3395 unused linker input files, etc. */
3396 execution_count++;
3397 return 0;
3398 }
3399 #ifdef DEBUG
3400 fnotice (stderr, "\nGo ahead? (y or n) ");
3401 fflush (stderr);
3402 i = getchar ();
3403 if (i != '\n')
3404 while (getchar () != '\n')
3405 ;
3406
3407 if (i != 'y' && i != 'Y')
3408 return 0;
3409 #endif /* DEBUG */
3410 }
3411
3412 #ifdef ENABLE_VALGRIND_CHECKING
3413 /* Run the each command through valgrind. To simplify prepending the
3414 path to valgrind and the option "-q" (for quiet operation unless
3415 something triggers), we allocate a separate argv array. */
3416
3417 for (i = 0; i < n_commands; i++)
3418 {
3419 const char **argv;
3420 int argc;
3421 int j;
3422
3423 for (argc = 0; commands[i].argv[argc] != NULL; argc++)
3424 ;
3425
3426 argv = XALLOCAVEC (const char *, argc + 3);
3427
3428 argv[0] = VALGRIND_PATH;
3429 argv[1] = "-q";
3430 for (j = 2; j < argc + 2; j++)
3431 argv[j] = commands[i].argv[j - 2];
3432 argv[j] = NULL;
3433
3434 commands[i].argv = argv;
3435 commands[i].prog = argv[0];
3436 }
3437 #endif
3438
3439 /* Run each piped subprocess. */
3440
3441 pex = pex_init (PEX_USE_PIPES | ((report_times || report_times_to_file)
3442 ? PEX_RECORD_TIMES : 0),
3443 progname, temp_filename);
3444 if (pex == NULL)
3445 fatal_error (input_location, "%<pex_init%> failed: %m");
3446
3447 for (i = 0; i < n_commands; i++)
3448 {
3449 const char *errmsg;
3450 int err;
3451 const char *string = commands[i].argv[0];
3452
3453 errmsg = pex_run (pex,
3454 ((i + 1 == n_commands ? PEX_LAST : 0)
3455 | (string == commands[i].prog ? PEX_SEARCH : 0)),
3456 string, CONST_CAST (char **, commands[i].argv),
3457 NULL, NULL, &err);
3458 if (errmsg != NULL)
3459 {
3460 errno = err;
3461 fatal_error (input_location,
3462 err ? G_("cannot execute %qs: %s: %m")
3463 : G_("cannot execute %qs: %s"),
3464 string, errmsg);
3465 }
3466
3467 if (i && string != commands[i].prog)
3468 free (CONST_CAST (char *, string));
3469 }
3470
3471 execution_count++;
3472
3473 /* Wait for all the subprocesses to finish. */
3474
3475 {
3476 int *statuses;
3477 struct pex_time *times = NULL;
3478 int ret_code = 0;
3479
3480 statuses = XALLOCAVEC (int, n_commands);
3481 if (!pex_get_status (pex, n_commands, statuses))
3482 fatal_error (input_location, "failed to get exit status: %m");
3483
3484 if (report_times || report_times_to_file)
3485 {
3486 times = XALLOCAVEC (struct pex_time, n_commands);
3487 if (!pex_get_times (pex, n_commands, times))
3488 fatal_error (input_location, "failed to get process times: %m");
3489 }
3490
3491 pex_free (pex);
3492
3493 for (i = 0; i < n_commands; ++i)
3494 {
3495 int status = statuses[i];
3496
3497 if (WIFSIGNALED (status))
3498 switch (WTERMSIG (status))
3499 {
3500 case SIGINT:
3501 case SIGTERM:
3502 /* SIGQUIT and SIGKILL are not available on MinGW. */
3503 #ifdef SIGQUIT
3504 case SIGQUIT:
3505 #endif
3506 #ifdef SIGKILL
3507 case SIGKILL:
3508 #endif
3509 /* The user (or environment) did something to the
3510 inferior. Making this an ICE confuses the user into
3511 thinking there's a compiler bug. Much more likely is
3512 the user or OOM killer nuked it. */
3513 fatal_error (input_location,
3514 "%s signal terminated program %s",
3515 strsignal (WTERMSIG (status)),
3516 commands[i].prog);
3517 break;
3518
3519 #ifdef SIGPIPE
3520 case SIGPIPE:
3521 /* SIGPIPE is a special case. It happens in -pipe mode
3522 when the compiler dies before the preprocessor is
3523 done, or the assembler dies before the compiler is
3524 done. There's generally been an error already, and
3525 this is just fallout. So don't generate another
3526 error unless we would otherwise have succeeded. */
3527 if (signal_count || greatest_status >= MIN_FATAL_STATUS)
3528 {
3529 signal_count++;
3530 ret_code = -1;
3531 break;
3532 }
3533 #endif
3534 /* FALLTHROUGH */
3535
3536 default:
3537 /* The inferior failed to catch the signal. */
3538 internal_error_no_backtrace ("%s signal terminated program %s",
3539 strsignal (WTERMSIG (status)),
3540 commands[i].prog);
3541 }
3542 else if (WIFEXITED (status)
3543 && WEXITSTATUS (status) >= MIN_FATAL_STATUS)
3544 {
3545 /* For ICEs in cc1, cc1obj, cc1plus see if it is
3546 reproducible or not. */
3547 const char *p;
3548 if (flag_report_bug
3549 && WEXITSTATUS (status) == ICE_EXIT_CODE
3550 && i == 0
3551 && (p = strrchr (commands[0].argv[0], DIR_SEPARATOR))
3552 && startswith (p + 1, "cc1"))
3553 try_generate_repro (commands[0].argv);
3554 if (WEXITSTATUS (status) > greatest_status)
3555 greatest_status = WEXITSTATUS (status);
3556 ret_code = -1;
3557 }
3558
3559 if (report_times || report_times_to_file)
3560 {
3561 struct pex_time *pt = &times[i];
3562 double ut, st;
3563
3564 ut = ((double) pt->user_seconds
3565 + (double) pt->user_microseconds / 1.0e6);
3566 st = ((double) pt->system_seconds
3567 + (double) pt->system_microseconds / 1.0e6);
3568
3569 if (ut + st != 0)
3570 {
3571 if (report_times)
3572 fnotice (stderr, "# %s %.2f %.2f\n",
3573 commands[i].prog, ut, st);
3574
3575 if (report_times_to_file)
3576 {
3577 int c = 0;
3578 const char *const *j;
3579
3580 fprintf (report_times_to_file, "%g %g", ut, st);
3581
3582 for (j = &commands[i].prog; *j; j = &commands[i].argv[++c])
3583 {
3584 const char *p;
3585 for (p = *j; *p; ++p)
3586 if (*p == '"' || *p == '\\' || *p == '$'
3587 || ISSPACE (*p))
3588 break;
3589
3590 if (*p)
3591 {
3592 fprintf (report_times_to_file, " \"");
3593 for (p = *j; *p; ++p)
3594 {
3595 if (*p == '"' || *p == '\\' || *p == '$')
3596 fputc ('\\', report_times_to_file);
3597 fputc (*p, report_times_to_file);
3598 }
3599 fputc ('"', report_times_to_file);
3600 }
3601 else
3602 fprintf (report_times_to_file, " %s", *j);
3603 }
3604
3605 fputc ('\n', report_times_to_file);
3606 }
3607 }
3608 }
3609 }
3610
3611 if (commands[0].argv[0] != commands[0].prog)
3612 free (CONST_CAST (char *, commands[0].argv[0]));
3613
3614 return ret_code;
3615 }
3616 }
3617
3618 static struct switchstr *switches;
3619
3620 static int n_switches;
3621
3622 static int n_switches_alloc;
3623
3624 /* Set to zero if -fcompare-debug is disabled, positive if it's
3625 enabled and we're running the first compilation, negative if it's
3626 enabled and we're running the second compilation. For most of the
3627 time, it's in the range -1..1, but it can be temporarily set to 2
3628 or 3 to indicate that the -fcompare-debug flags didn't come from
3629 the command-line, but rather from the GCC_COMPARE_DEBUG environment
3630 variable, until a synthesized -fcompare-debug flag is added to the
3631 command line. */
3632 int compare_debug;
3633
3634 /* Set to nonzero if we've seen the -fcompare-debug-second flag. */
3635 int compare_debug_second;
3636
3637 /* Set to the flags that should be passed to the second compilation in
3638 a -fcompare-debug compilation. */
3639 const char *compare_debug_opt;
3640
3641 static struct switchstr *switches_debug_check[2];
3642
3643 static int n_switches_debug_check[2];
3644
3645 static int n_switches_alloc_debug_check[2];
3646
3647 static char *debug_check_temp_file[2];
3648
3649 /* Language is one of three things:
3650
3651 1) The name of a real programming language.
3652 2) NULL, indicating that no one has figured out
3653 what it is yet.
3654 3) '*', indicating that the file should be passed
3655 to the linker. */
3656 struct infile
3657 {
3658 const char *name;
3659 const char *language;
3660 struct compiler *incompiler;
3661 bool compiled;
3662 bool preprocessed;
3663 };
3664
3665 /* Also a vector of input files specified. */
3666
3667 static struct infile *infiles;
3668
3669 int n_infiles;
3670
3671 static int n_infiles_alloc;
3672
3673 /* True if undefined environment variables encountered during spec processing
3674 are ok to ignore, typically when we're running for --help or --version. */
3675
3676 static bool spec_undefvar_allowed;
3677
3678 /* True if multiple input files are being compiled to a single
3679 assembly file. */
3680
3681 static bool combine_inputs;
3682
3683 /* This counts the number of libraries added by lang_specific_driver, so that
3684 we can tell if there were any user supplied any files or libraries. */
3685
3686 static int added_libraries;
3687
3688 /* And a vector of corresponding output files is made up later. */
3689
3690 const char **outfiles;
3691
3692 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3693
3694 /* Convert NAME to a new name if it is the standard suffix. DO_EXE
3695 is true if we should look for an executable suffix. DO_OBJ
3696 is true if we should look for an object suffix. */
3697
3698 static const char *
3699 convert_filename (const char *name, int do_exe ATTRIBUTE_UNUSED,
3700 int do_obj ATTRIBUTE_UNUSED)
3701 {
3702 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3703 int i;
3704 #endif
3705 int len;
3706
3707 if (name == NULL)
3708 return NULL;
3709
3710 len = strlen (name);
3711
3712 #ifdef HAVE_TARGET_OBJECT_SUFFIX
3713 /* Convert x.o to x.obj if TARGET_OBJECT_SUFFIX is ".obj". */
3714 if (do_obj && len > 2
3715 && name[len - 2] == '.'
3716 && name[len - 1] == 'o')
3717 {
3718 obstack_grow (&obstack, name, len - 2);
3719 obstack_grow0 (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
3720 name = XOBFINISH (&obstack, const char *);
3721 }
3722 #endif
3723
3724 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3725 /* If there is no filetype, make it the executable suffix (which includes
3726 the "."). But don't get confused if we have just "-o". */
3727 if (! do_exe || TARGET_EXECUTABLE_SUFFIX[0] == 0 || not_actual_file_p (name))
3728 return name;
3729
3730 for (i = len - 1; i >= 0; i--)
3731 if (IS_DIR_SEPARATOR (name[i]))
3732 break;
3733
3734 for (i++; i < len; i++)
3735 if (name[i] == '.')
3736 return name;
3737
3738 obstack_grow (&obstack, name, len);
3739 obstack_grow0 (&obstack, TARGET_EXECUTABLE_SUFFIX,
3740 strlen (TARGET_EXECUTABLE_SUFFIX));
3741 name = XOBFINISH (&obstack, const char *);
3742 #endif
3743
3744 return name;
3745 }
3746 #endif
3747
3748 /* Display the command line switches accepted by gcc. */
3749 static void
3750 display_help (void)
3751 {
3752 printf (_("Usage: %s [options] file...\n"), progname);
3753 fputs (_("Options:\n"), stdout);
3754
3755 fputs (_(" -pass-exit-codes Exit with highest error code from a phase.\n"), stdout);
3756 fputs (_(" --help Display this information.\n"), stdout);
3757 fputs (_(" --target-help Display target specific command line options "
3758 "(including assembler and linker options).\n"), stdout);
3759 fputs (_(" --help={common|optimizers|params|target|warnings|[^]{joined|separate|undocumented}}[,...].\n"), stdout);
3760 fputs (_(" Display specific types of command line options.\n"), stdout);
3761 if (! verbose_flag)
3762 fputs (_(" (Use '-v --help' to display command line options of sub-processes).\n"), stdout);
3763 fputs (_(" --version Display compiler version information.\n"), stdout);
3764 fputs (_(" -dumpspecs Display all of the built in spec strings.\n"), stdout);
3765 fputs (_(" -dumpversion Display the version of the compiler.\n"), stdout);
3766 fputs (_(" -dumpmachine Display the compiler's target processor.\n"), stdout);
3767 fputs (_(" -foffload=<targets> Specify offloading targets.\n"), stdout);
3768 fputs (_(" -print-search-dirs Display the directories in the compiler's search path.\n"), stdout);
3769 fputs (_(" -print-libgcc-file-name Display the name of the compiler's companion library.\n"), stdout);
3770 fputs (_(" -print-file-name=<lib> Display the full path to library <lib>.\n"), stdout);
3771 fputs (_(" -print-prog-name=<prog> Display the full path to compiler component <prog>.\n"), stdout);
3772 fputs (_("\
3773 -print-multiarch Display the target's normalized GNU triplet, used as\n\
3774 a component in the library path.\n"), stdout);
3775 fputs (_(" -print-multi-directory Display the root directory for versions of libgcc.\n"), stdout);
3776 fputs (_("\
3777 -print-multi-lib Display the mapping between command line options and\n\
3778 multiple library search directories.\n"), stdout);
3779 fputs (_(" -print-multi-os-directory Display the relative path to OS libraries.\n"), stdout);
3780 fputs (_(" -print-sysroot Display the target libraries directory.\n"), stdout);
3781 fputs (_(" -print-sysroot-headers-suffix Display the sysroot suffix used to find headers.\n"), stdout);
3782 fputs (_(" -Wa,<options> Pass comma-separated <options> on to the assembler.\n"), stdout);
3783 fputs (_(" -Wp,<options> Pass comma-separated <options> on to the preprocessor.\n"), stdout);
3784 fputs (_(" -Wl,<options> Pass comma-separated <options> on to the linker.\n"), stdout);
3785 fputs (_(" -Xassembler <arg> Pass <arg> on to the assembler.\n"), stdout);
3786 fputs (_(" -Xpreprocessor <arg> Pass <arg> on to the preprocessor.\n"), stdout);
3787 fputs (_(" -Xlinker <arg> Pass <arg> on to the linker.\n"), stdout);
3788 fputs (_(" -save-temps Do not delete intermediate files.\n"), stdout);
3789 fputs (_(" -save-temps=<arg> Do not delete intermediate files.\n"), stdout);
3790 fputs (_("\
3791 -no-canonical-prefixes Do not canonicalize paths when building relative\n\
3792 prefixes to other gcc components.\n"), stdout);
3793 fputs (_(" -pipe Use pipes rather than intermediate files.\n"), stdout);
3794 fputs (_(" -time Time the execution of each subprocess.\n"), stdout);
3795 fputs (_(" -specs=<file> Override built-in specs with the contents of <file>.\n"), stdout);
3796 fputs (_(" -std=<standard> Assume that the input sources are for <standard>.\n"), stdout);
3797 fputs (_("\
3798 --sysroot=<directory> Use <directory> as the root directory for headers\n\
3799 and libraries.\n"), stdout);
3800 fputs (_(" -B <directory> Add <directory> to the compiler's search paths.\n"), stdout);
3801 fputs (_(" -v Display the programs invoked by the compiler.\n"), stdout);
3802 fputs (_(" -### Like -v but options quoted and commands not executed.\n"), stdout);
3803 fputs (_(" -E Preprocess only; do not compile, assemble or link.\n"), stdout);
3804 fputs (_(" -S Compile only; do not assemble or link.\n"), stdout);
3805 fputs (_(" -c Compile and assemble, but do not link.\n"), stdout);
3806 fputs (_(" -o <file> Place the output into <file>.\n"), stdout);
3807 fputs (_(" -pie Create a dynamically linked position independent\n\
3808 executable.\n"), stdout);
3809 fputs (_(" -shared Create a shared library.\n"), stdout);
3810 fputs (_("\
3811 -x <language> Specify the language of the following input files.\n\
3812 Permissible languages include: c c++ assembler none\n\
3813 'none' means revert to the default behavior of\n\
3814 guessing the language based on the file's extension.\n\
3815 "), stdout);
3816
3817 printf (_("\
3818 \nOptions starting with -g, -f, -m, -O, -W, or --param are automatically\n\
3819 passed on to the various sub-processes invoked by %s. In order to pass\n\
3820 other options on to these processes the -W<letter> options must be used.\n\
3821 "), progname);
3822
3823 /* The rest of the options are displayed by invocations of the various
3824 sub-processes. */
3825 }
3826
3827 static void
3828 add_preprocessor_option (const char *option, int len)
3829 {
3830 preprocessor_options.safe_push (save_string (option, len));
3831 }
3832
3833 static void
3834 add_assembler_option (const char *option, int len)
3835 {
3836 assembler_options.safe_push (save_string (option, len));
3837 }
3838
3839 static void
3840 add_linker_option (const char *option, int len)
3841 {
3842 linker_options.safe_push (save_string (option, len));
3843 }
3844
3845 /* Allocate space for an input file in infiles. */
3846
3847 static void
3848 alloc_infile (void)
3849 {
3850 if (n_infiles_alloc == 0)
3851 {
3852 n_infiles_alloc = 16;
3853 infiles = XNEWVEC (struct infile, n_infiles_alloc);
3854 }
3855 else if (n_infiles_alloc == n_infiles)
3856 {
3857 n_infiles_alloc *= 2;
3858 infiles = XRESIZEVEC (struct infile, infiles, n_infiles_alloc);
3859 }
3860 }
3861
3862 /* Store an input file with the given NAME and LANGUAGE in
3863 infiles. */
3864
3865 static void
3866 add_infile (const char *name, const char *language)
3867 {
3868 alloc_infile ();
3869 infiles[n_infiles].name = name;
3870 infiles[n_infiles++].language = language;
3871 }
3872
3873 /* Allocate space for a switch in switches. */
3874
3875 static void
3876 alloc_switch (void)
3877 {
3878 if (n_switches_alloc == 0)
3879 {
3880 n_switches_alloc = 16;
3881 switches = XNEWVEC (struct switchstr, n_switches_alloc);
3882 }
3883 else if (n_switches_alloc == n_switches)
3884 {
3885 n_switches_alloc *= 2;
3886 switches = XRESIZEVEC (struct switchstr, switches, n_switches_alloc);
3887 }
3888 }
3889
3890 /* Save an option OPT with N_ARGS arguments in array ARGS, marking it
3891 as validated if VALIDATED and KNOWN if it is an internal switch. */
3892
3893 static void
3894 save_switch (const char *opt, size_t n_args, const char *const *args,
3895 bool validated, bool known)
3896 {
3897 alloc_switch ();
3898 switches[n_switches].part1 = opt + 1;
3899 if (n_args == 0)
3900 switches[n_switches].args = 0;
3901 else
3902 {
3903 switches[n_switches].args = XNEWVEC (const char *, n_args + 1);
3904 memcpy (switches[n_switches].args, args, n_args * sizeof (const char *));
3905 switches[n_switches].args[n_args] = NULL;
3906 }
3907
3908 switches[n_switches].live_cond = 0;
3909 switches[n_switches].validated = validated;
3910 switches[n_switches].known = known;
3911 switches[n_switches].ordering = 0;
3912 n_switches++;
3913 }
3914
3915 /* Set the SOURCE_DATE_EPOCH environment variable to the current time if it is
3916 not set already. */
3917
3918 static void
3919 set_source_date_epoch_envvar ()
3920 {
3921 /* Array size is 21 = ceil(log_10(2^64)) + 1 to hold string representations
3922 of 64 bit integers. */
3923 char source_date_epoch[21];
3924 time_t tt;
3925
3926 errno = 0;
3927 tt = time (NULL);
3928 if (tt < (time_t) 0 || errno != 0)
3929 tt = (time_t) 0;
3930
3931 snprintf (source_date_epoch, 21, "%llu", (unsigned long long) tt);
3932 /* Using setenv instead of xputenv because we want the variable to remain
3933 after finalizing so that it's still set in the second run when using
3934 -fcompare-debug. */
3935 setenv ("SOURCE_DATE_EPOCH", source_date_epoch, 0);
3936 }
3937
3938 /* Handle an option DECODED that is unknown to the option-processing
3939 machinery. */
3940
3941 static bool
3942 driver_unknown_option_callback (const struct cl_decoded_option *decoded)
3943 {
3944 const char *opt = decoded->arg;
3945 if (opt[1] == 'W' && opt[2] == 'n' && opt[3] == 'o' && opt[4] == '-'
3946 && !(decoded->errors & CL_ERR_NEGATIVE))
3947 {
3948 /* Leave unknown -Wno-* options for the compiler proper, to be
3949 diagnosed only if there are warnings. */
3950 save_switch (decoded->canonical_option[0],
3951 decoded->canonical_option_num_elements - 1,
3952 &decoded->canonical_option[1], false, true);
3953 return false;
3954 }
3955 if (decoded->opt_index == OPT_SPECIAL_unknown)
3956 {
3957 /* Give it a chance to define it a spec file. */
3958 save_switch (decoded->canonical_option[0],
3959 decoded->canonical_option_num_elements - 1,
3960 &decoded->canonical_option[1], false, false);
3961 return false;
3962 }
3963 else
3964 return true;
3965 }
3966
3967 /* Handle an option DECODED that is not marked as CL_DRIVER.
3968 LANG_MASK will always be CL_DRIVER. */
3969
3970 static void
3971 driver_wrong_lang_callback (const struct cl_decoded_option *decoded,
3972 unsigned int lang_mask ATTRIBUTE_UNUSED)
3973 {
3974 /* At this point, non-driver options are accepted (and expected to
3975 be passed down by specs) unless marked to be rejected by the
3976 driver. Options to be rejected by the driver but accepted by the
3977 compilers proper are treated just like completely unknown
3978 options. */
3979 const struct cl_option *option = &cl_options[decoded->opt_index];
3980
3981 if (option->cl_reject_driver)
3982 error ("unrecognized command-line option %qs",
3983 decoded->orig_option_with_args_text);
3984 else
3985 save_switch (decoded->canonical_option[0],
3986 decoded->canonical_option_num_elements - 1,
3987 &decoded->canonical_option[1], false, true);
3988 }
3989
3990 static const char *spec_lang = 0;
3991 static int last_language_n_infiles;
3992
3993
3994 /* Check that GCC is configured to support the offload target. */
3995
3996 static bool
3997 check_offload_target_name (const char *target, ptrdiff_t len)
3998 {
3999 const char *n, *c = OFFLOAD_TARGETS;
4000 while (c)
4001 {
4002 n = strchr (c, ',');
4003 if (n == NULL)
4004 n = strchr (c, '\0');
4005 if (len == n - c && strncmp (target, c, n - c) == 0)
4006 break;
4007 c = *n ? n + 1 : NULL;
4008 }
4009 if (!c)
4010 {
4011 auto_vec<const char*> candidates;
4012 size_t olen = strlen (OFFLOAD_TARGETS) + 1;
4013 char *cand = XALLOCAVEC (char, olen);
4014 memcpy (cand, OFFLOAD_TARGETS, olen);
4015 for (c = strtok (cand, ","); c; c = strtok (NULL, ","))
4016 candidates.safe_push (c);
4017 candidates.safe_push ("default");
4018 candidates.safe_push ("disable");
4019
4020 char *target2 = XALLOCAVEC (char, len + 1);
4021 memcpy (target2, target, len);
4022 target2[len] = '\0';
4023
4024 error ("GCC is not configured to support %qs as %<-foffload=%> argument",
4025 target2);
4026
4027 char *s;
4028 const char *hint = candidates_list_and_hint (target2, s, candidates);
4029 if (hint)
4030 inform (UNKNOWN_LOCATION,
4031 "valid %<-foffload=%> arguments are: %s; "
4032 "did you mean %qs?", s, hint);
4033 else
4034 inform (UNKNOWN_LOCATION, "valid %<-foffload=%> arguments are: %s", s);
4035 XDELETEVEC (s);
4036 return false;
4037 }
4038 return true;
4039 }
4040
4041 /* Sanity check for -foffload-options. */
4042
4043 static void
4044 check_foffload_target_names (const char *arg)
4045 {
4046 const char *cur, *next, *end;
4047 /* If option argument starts with '-' then no target is specified and we
4048 do not need to parse it. */
4049 if (arg[0] == '-')
4050 return;
4051 end = strchr (arg, '=');
4052 if (end == NULL)
4053 {
4054 error ("%<=%>options missing after %<-foffload-options=%>target");
4055 return;
4056 }
4057
4058 cur = arg;
4059 while (cur < end)
4060 {
4061 next = strchr (cur, ',');
4062 if (next == NULL)
4063 next = end;
4064 next = (next > end) ? end : next;
4065
4066 /* Retain non-supported targets after printing an error as those will not
4067 be processed; each enabled target only processes its triplet. */
4068 check_offload_target_name (cur, next - cur);
4069 cur = next + 1;
4070 }
4071 }
4072
4073 /* Parse -foffload option argument. */
4074
4075 static void
4076 handle_foffload_option (const char *arg)
4077 {
4078 const char *c, *cur, *n, *next, *end;
4079 char *target;
4080
4081 /* If option argument starts with '-' then no target is specified and we
4082 do not need to parse it. */
4083 if (arg[0] == '-')
4084 return;
4085
4086 end = strchr (arg, '=');
4087 if (end == NULL)
4088 end = strchr (arg, '\0');
4089 cur = arg;
4090
4091 while (cur < end)
4092 {
4093 next = strchr (cur, ',');
4094 if (next == NULL)
4095 next = end;
4096 next = (next > end) ? end : next;
4097
4098 target = XNEWVEC (char, next - cur + 1);
4099 memcpy (target, cur, next - cur);
4100 target[next - cur] = '\0';
4101
4102 /* Reset offloading list and continue. */
4103 if (strcmp (target, "default") == 0)
4104 {
4105 free (offload_targets);
4106 offload_targets = NULL;
4107 goto next_item;
4108 }
4109
4110 /* If 'disable' is passed to the option, clean the list of
4111 offload targets and return, even if more targets follow.
4112 Likewise if GCC is not configured to support that offload target. */
4113 if (strcmp (target, "disable") == 0
4114 || !check_offload_target_name (target, next - cur))
4115 {
4116 free (offload_targets);
4117 offload_targets = xstrdup ("");
4118 return;
4119 }
4120
4121 if (!offload_targets)
4122 {
4123 offload_targets = target;
4124 target = NULL;
4125 }
4126 else
4127 {
4128 /* Check that the target hasn't already presented in the list. */
4129 c = offload_targets;
4130 do
4131 {
4132 n = strchr (c, ':');
4133 if (n == NULL)
4134 n = strchr (c, '\0');
4135
4136 if (next - cur == n - c && strncmp (c, target, n - c) == 0)
4137 break;
4138
4139 c = n + 1;
4140 }
4141 while (*n);
4142
4143 /* If duplicate is not found, append the target to the list. */
4144 if (c > n)
4145 {
4146 size_t offload_targets_len = strlen (offload_targets);
4147 offload_targets
4148 = XRESIZEVEC (char, offload_targets,
4149 offload_targets_len + 1 + next - cur + 1);
4150 offload_targets[offload_targets_len++] = ':';
4151 memcpy (offload_targets + offload_targets_len, target, next - cur + 1);
4152 }
4153 }
4154 next_item:
4155 cur = next + 1;
4156 XDELETEVEC (target);
4157 }
4158 }
4159
4160 /* Forward certain options to offloading compilation. */
4161
4162 static void
4163 forward_offload_option (size_t opt_index, const char *arg, bool validated)
4164 {
4165 switch (opt_index)
4166 {
4167 case OPT_l:
4168 /* Use a '_GCC_' prefix and standard name ('-l_GCC_m' irrespective of the
4169 host's 'MATH_LIBRARY', for example), so that the 'mkoffload's can tell
4170 this has been synthesized here, and translate/drop as necessary. */
4171 /* Note that certain libraries ('-lc', '-lgcc', '-lgomp', for example)
4172 are injected by default in offloading compilation, and therefore not
4173 forwarded here. */
4174 /* GCC libraries. */
4175 if (/* '-lgfortran' */ strcmp (arg, "gfortran") == 0
4176 || /* '-lstdc++' */ strcmp (arg, "stdc++") == 0)
4177 save_switch (concat ("-foffload-options=-l_GCC_", arg, NULL),
4178 0, NULL, validated, true);
4179 /* Other libraries. */
4180 else
4181 {
4182 /* The case will need special consideration where on the host
4183 '!need_math', but for offloading compilation still need
4184 '-foffload-options=-l_GCC_m'. The problem is that we don't get
4185 here anything like '-lm', because it's not synthesized in
4186 'gcc/fortran/gfortranspec.cc:lang_specific_driver', for example.
4187 Generally synthesizing '-foffload-options=-l_GCC_m' etc. in the
4188 language specific drivers is non-trivial, needs very careful
4189 review of their options handling. However, this issue is not
4190 actually relevant for the current set of supported host/offloading
4191 configurations. */
4192 int need_math = (MATH_LIBRARY[0] != '\0');
4193 if (/* '-lm' */ (need_math && strcmp (arg, MATH_LIBRARY) == 0))
4194 save_switch ("-foffload-options=-l_GCC_m",
4195 0, NULL, validated, true);
4196 }
4197 break;
4198 default:
4199 gcc_unreachable ();
4200 }
4201 }
4202
4203 /* Handle a driver option; arguments and return value as for
4204 handle_option. */
4205
4206 static bool
4207 driver_handle_option (struct gcc_options *opts,
4208 struct gcc_options *opts_set,
4209 const struct cl_decoded_option *decoded,
4210 unsigned int lang_mask ATTRIBUTE_UNUSED, int kind,
4211 location_t loc,
4212 const struct cl_option_handlers *handlers ATTRIBUTE_UNUSED,
4213 diagnostic_context *dc,
4214 void (*) (void))
4215 {
4216 size_t opt_index = decoded->opt_index;
4217 const char *arg = decoded->arg;
4218 const char *compare_debug_replacement_opt;
4219 int value = decoded->value;
4220 bool validated = false;
4221 bool do_save = true;
4222
4223 gcc_assert (opts == &global_options);
4224 gcc_assert (opts_set == &global_options_set);
4225 gcc_assert (kind == DK_UNSPECIFIED);
4226 gcc_assert (loc == UNKNOWN_LOCATION);
4227 gcc_assert (dc == global_dc);
4228
4229 switch (opt_index)
4230 {
4231 case OPT_dumpspecs:
4232 {
4233 struct spec_list *sl;
4234 init_spec ();
4235 for (sl = specs; sl; sl = sl->next)
4236 printf ("*%s:\n%s\n\n", sl->name, *(sl->ptr_spec));
4237 if (link_command_spec)
4238 printf ("*link_command:\n%s\n\n", link_command_spec);
4239 exit (0);
4240 }
4241
4242 case OPT_dumpversion:
4243 printf ("%s\n", spec_version);
4244 exit (0);
4245
4246 case OPT_dumpmachine:
4247 printf ("%s\n", spec_machine);
4248 exit (0);
4249
4250 case OPT_dumpfullversion:
4251 printf ("%s\n", BASEVER);
4252 exit (0);
4253
4254 case OPT__version:
4255 print_version = 1;
4256
4257 /* CPP driver cannot obtain switch from cc1_options. */
4258 if (is_cpp_driver)
4259 add_preprocessor_option ("--version", strlen ("--version"));
4260 add_assembler_option ("--version", strlen ("--version"));
4261 add_linker_option ("--version", strlen ("--version"));
4262 break;
4263
4264 case OPT__completion_:
4265 validated = true;
4266 completion = decoded->arg;
4267 break;
4268
4269 case OPT__help:
4270 print_help_list = 1;
4271
4272 /* CPP driver cannot obtain switch from cc1_options. */
4273 if (is_cpp_driver)
4274 add_preprocessor_option ("--help", 6);
4275 add_assembler_option ("--help", 6);
4276 add_linker_option ("--help", 6);
4277 break;
4278
4279 case OPT__help_:
4280 print_subprocess_help = 2;
4281 break;
4282
4283 case OPT__target_help:
4284 print_subprocess_help = 1;
4285
4286 /* CPP driver cannot obtain switch from cc1_options. */
4287 if (is_cpp_driver)
4288 add_preprocessor_option ("--target-help", 13);
4289 add_assembler_option ("--target-help", 13);
4290 add_linker_option ("--target-help", 13);
4291 break;
4292
4293 case OPT__no_sysroot_suffix:
4294 case OPT_pass_exit_codes:
4295 case OPT_print_search_dirs:
4296 case OPT_print_file_name_:
4297 case OPT_print_prog_name_:
4298 case OPT_print_multi_lib:
4299 case OPT_print_multi_directory:
4300 case OPT_print_sysroot:
4301 case OPT_print_multi_os_directory:
4302 case OPT_print_multiarch:
4303 case OPT_print_sysroot_headers_suffix:
4304 case OPT_time:
4305 case OPT_wrapper:
4306 /* These options set the variables specified in common.opt
4307 automatically, and do not need to be saved for spec
4308 processing. */
4309 do_save = false;
4310 break;
4311
4312 case OPT_print_libgcc_file_name:
4313 print_file_name = "libgcc.a";
4314 do_save = false;
4315 break;
4316
4317 case OPT_fuse_ld_bfd:
4318 use_ld = ".bfd";
4319 break;
4320
4321 case OPT_fuse_ld_gold:
4322 use_ld = ".gold";
4323 break;
4324
4325 case OPT_fuse_ld_mold:
4326 use_ld = ".mold";
4327 break;
4328
4329 case OPT_fcompare_debug_second:
4330 compare_debug_second = 1;
4331 break;
4332
4333 case OPT_fcompare_debug:
4334 switch (value)
4335 {
4336 case 0:
4337 compare_debug_replacement_opt = "-fcompare-debug=";
4338 arg = "";
4339 goto compare_debug_with_arg;
4340
4341 case 1:
4342 compare_debug_replacement_opt = "-fcompare-debug=-gtoggle";
4343 arg = "-gtoggle";
4344 goto compare_debug_with_arg;
4345
4346 default:
4347 gcc_unreachable ();
4348 }
4349 break;
4350
4351 case OPT_fcompare_debug_:
4352 compare_debug_replacement_opt = decoded->canonical_option[0];
4353 compare_debug_with_arg:
4354 gcc_assert (decoded->canonical_option_num_elements == 1);
4355 gcc_assert (arg != NULL);
4356 if (*arg)
4357 compare_debug = 1;
4358 else
4359 compare_debug = -1;
4360 if (compare_debug < 0)
4361 compare_debug_opt = NULL;
4362 else
4363 compare_debug_opt = arg;
4364 save_switch (compare_debug_replacement_opt, 0, NULL, validated, true);
4365 set_source_date_epoch_envvar ();
4366 return true;
4367
4368 case OPT_fdiagnostics_color_:
4369 diagnostic_color_init (dc, value);
4370 break;
4371
4372 case OPT_fdiagnostics_urls_:
4373 diagnostic_urls_init (dc, value);
4374 break;
4375
4376 case OPT_fdiagnostics_show_highlight_colors:
4377 dc->set_show_highlight_colors (value);
4378 break;
4379
4380 case OPT_fdiagnostics_format_:
4381 {
4382 const char *basename = (opts->x_dump_base_name ? opts->x_dump_base_name
4383 : opts->x_main_input_basename);
4384 gcc_assert (dc);
4385 diagnostic_output_format_init (*dc,
4386 opts->x_main_input_filename, basename,
4387 (enum diagnostics_output_format)value,
4388 opts->x_flag_diagnostics_json_formatting);
4389 break;
4390 }
4391
4392 case OPT_fdiagnostics_add_output_:
4393 handle_OPT_fdiagnostics_add_output_ (*opts, *dc, arg, loc);
4394 break;
4395
4396 case OPT_fdiagnostics_set_output_:
4397 handle_OPT_fdiagnostics_set_output_ (*opts, *dc, arg, loc);
4398 break;
4399
4400 case OPT_fdiagnostics_text_art_charset_:
4401 dc->set_text_art_charset ((enum diagnostic_text_art_charset)value);
4402 break;
4403
4404 case OPT_Wa_:
4405 {
4406 int prev, j;
4407 /* Pass the rest of this option to the assembler. */
4408
4409 /* Split the argument at commas. */
4410 prev = 0;
4411 for (j = 0; arg[j]; j++)
4412 if (arg[j] == ',')
4413 {
4414 add_assembler_option (arg + prev, j - prev);
4415 prev = j + 1;
4416 }
4417
4418 /* Record the part after the last comma. */
4419 add_assembler_option (arg + prev, j - prev);
4420 }
4421 do_save = false;
4422 break;
4423
4424 case OPT_Wp_:
4425 {
4426 int prev, j;
4427 /* Pass the rest of this option to the preprocessor. */
4428
4429 /* Split the argument at commas. */
4430 prev = 0;
4431 for (j = 0; arg[j]; j++)
4432 if (arg[j] == ',')
4433 {
4434 add_preprocessor_option (arg + prev, j - prev);
4435 prev = j + 1;
4436 }
4437
4438 /* Record the part after the last comma. */
4439 add_preprocessor_option (arg + prev, j - prev);
4440 }
4441 do_save = false;
4442 break;
4443
4444 case OPT_Wl_:
4445 {
4446 int prev, j;
4447 /* Split the argument at commas. */
4448 prev = 0;
4449 for (j = 0; arg[j]; j++)
4450 if (arg[j] == ',')
4451 {
4452 add_infile (save_string (arg + prev, j - prev), "*");
4453 prev = j + 1;
4454 }
4455 /* Record the part after the last comma. */
4456 add_infile (arg + prev, "*");
4457 if (strcmp (arg, "-z,lazy") == 0 || strcmp (arg, "-z,norelro") == 0)
4458 avoid_linker_hardening_p = true;
4459 }
4460 do_save = false;
4461 break;
4462
4463 case OPT_z:
4464 if (strcmp (arg, "lazy") == 0 || strcmp (arg, "norelro") == 0)
4465 avoid_linker_hardening_p = true;
4466 break;
4467
4468 case OPT_Xlinker:
4469 add_infile (arg, "*");
4470 do_save = false;
4471 break;
4472
4473 case OPT_Xpreprocessor:
4474 add_preprocessor_option (arg, strlen (arg));
4475 do_save = false;
4476 break;
4477
4478 case OPT_Xassembler:
4479 add_assembler_option (arg, strlen (arg));
4480 do_save = false;
4481 break;
4482
4483 case OPT_l:
4484 /* POSIX allows separation of -l and the lib arg; canonicalize
4485 by concatenating -l with its arg */
4486 add_infile (concat ("-l", arg, NULL), "*");
4487
4488 /* Forward to offloading compilation '-l[...]' flags for standard,
4489 well-known libraries. */
4490 /* Doing this processing here means that we don't get to see libraries
4491 injected via specs, such as '-lquadmath' injected via
4492 '[build]/[target]/libgfortran/libgfortran.spec'. However, this issue
4493 is not actually relevant for the current set of host/offloading
4494 configurations. */
4495 if (ENABLE_OFFLOADING)
4496 forward_offload_option (opt_index, arg, validated);
4497
4498 do_save = false;
4499 break;
4500
4501 case OPT_L:
4502 /* Similarly, canonicalize -L for linkers that may not accept
4503 separate arguments. */
4504 save_switch (concat ("-L", arg, NULL), 0, NULL, validated, true);
4505 return true;
4506
4507 case OPT_F:
4508 /* Likewise -F. */
4509 save_switch (concat ("-F", arg, NULL), 0, NULL, validated, true);
4510 return true;
4511
4512 case OPT_save_temps:
4513 if (!save_temps_flag)
4514 save_temps_flag = SAVE_TEMPS_DUMP;
4515 validated = true;
4516 break;
4517
4518 case OPT_save_temps_:
4519 if (strcmp (arg, "cwd") == 0)
4520 save_temps_flag = SAVE_TEMPS_CWD;
4521 else if (strcmp (arg, "obj") == 0
4522 || strcmp (arg, "object") == 0)
4523 save_temps_flag = SAVE_TEMPS_OBJ;
4524 else
4525 fatal_error (input_location, "%qs is an unknown %<-save-temps%> option",
4526 decoded->orig_option_with_args_text);
4527 save_temps_overrides_dumpdir = true;
4528 break;
4529
4530 case OPT_dumpdir:
4531 free (dumpdir);
4532 dumpdir = xstrdup (arg);
4533 save_temps_overrides_dumpdir = false;
4534 break;
4535
4536 case OPT_dumpbase:
4537 free (dumpbase);
4538 dumpbase = xstrdup (arg);
4539 break;
4540
4541 case OPT_dumpbase_ext:
4542 free (dumpbase_ext);
4543 dumpbase_ext = xstrdup (arg);
4544 break;
4545
4546 case OPT_no_canonical_prefixes:
4547 /* Already handled as a special case, so ignored here. */
4548 do_save = false;
4549 break;
4550
4551 case OPT_pipe:
4552 validated = true;
4553 /* These options set the variables specified in common.opt
4554 automatically, but do need to be saved for spec
4555 processing. */
4556 break;
4557
4558 case OPT_specs_:
4559 {
4560 struct user_specs *user = XNEW (struct user_specs);
4561
4562 user->next = (struct user_specs *) 0;
4563 user->filename = arg;
4564 if (user_specs_tail)
4565 user_specs_tail->next = user;
4566 else
4567 user_specs_head = user;
4568 user_specs_tail = user;
4569 }
4570 validated = true;
4571 break;
4572
4573 case OPT__sysroot_:
4574 target_system_root = arg;
4575 target_system_root_changed = 1;
4576 /* Saving this option is useful to let self-specs decide to
4577 provide a default one. */
4578 do_save = true;
4579 validated = true;
4580 break;
4581
4582 case OPT_time_:
4583 if (report_times_to_file)
4584 fclose (report_times_to_file);
4585 report_times_to_file = fopen (arg, "a");
4586 do_save = false;
4587 break;
4588
4589 case OPT_truncate:
4590 totruncate_file = arg;
4591 do_save = false;
4592 break;
4593
4594 case OPT____:
4595 /* "-###"
4596 This is similar to -v except that there is no execution
4597 of the commands and the echoed arguments are quoted. It
4598 is intended for use in shell scripts to capture the
4599 driver-generated command line. */
4600 verbose_only_flag++;
4601 verbose_flag = 1;
4602 do_save = false;
4603 break;
4604
4605 case OPT_B:
4606 {
4607 size_t len = strlen (arg);
4608
4609 /* Catch the case where the user has forgotten to append a
4610 directory separator to the path. Note, they may be using
4611 -B to add an executable name prefix, eg "i386-elf-", in
4612 order to distinguish between multiple installations of
4613 GCC in the same directory. Hence we must check to see
4614 if appending a directory separator actually makes a
4615 valid directory name. */
4616 if (!IS_DIR_SEPARATOR (arg[len - 1])
4617 && is_directory (arg))
4618 {
4619 char *tmp = XNEWVEC (char, len + 2);
4620 strcpy (tmp, arg);
4621 tmp[len] = DIR_SEPARATOR;
4622 tmp[++len] = 0;
4623 arg = tmp;
4624 }
4625
4626 add_prefix (&exec_prefixes, arg, NULL,
4627 PREFIX_PRIORITY_B_OPT, 0, 0);
4628 add_prefix (&startfile_prefixes, arg, NULL,
4629 PREFIX_PRIORITY_B_OPT, 0, 0);
4630 add_prefix (&include_prefixes, arg, NULL,
4631 PREFIX_PRIORITY_B_OPT, 0, 0);
4632 }
4633 validated = true;
4634 break;
4635
4636 case OPT_E:
4637 have_E = true;
4638 break;
4639
4640 case OPT_x:
4641 spec_lang = arg;
4642 if (!strcmp (spec_lang, "none"))
4643 /* Suppress the warning if -xnone comes after the last input
4644 file, because alternate command interfaces like g++ might
4645 find it useful to place -xnone after each input file. */
4646 spec_lang = 0;
4647 else
4648 last_language_n_infiles = n_infiles;
4649 do_save = false;
4650 break;
4651
4652 case OPT_o:
4653 have_o = 1;
4654 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX) || defined(HAVE_TARGET_OBJECT_SUFFIX)
4655 arg = convert_filename (arg, ! have_c, 0);
4656 #endif
4657 output_file = arg;
4658 /* On some systems, ld cannot handle "-o" without a space. So
4659 split the option from its argument. */
4660 save_switch ("-o", 1, &arg, validated, true);
4661 return true;
4662
4663 case OPT_pie:
4664 #ifdef ENABLE_DEFAULT_PIE
4665 /* -pie is turned on by default. */
4666 validated = true;
4667 #endif
4668 /* FALLTHROUGH */
4669 case OPT_r:
4670 case OPT_shared:
4671 case OPT_no_pie:
4672 avoid_linker_hardening_p = true;
4673 break;
4674
4675 case OPT_static:
4676 static_p = true;
4677 break;
4678
4679 case OPT_static_libgcc:
4680 case OPT_shared_libgcc:
4681 case OPT_static_libgfortran:
4682 case OPT_static_libquadmath:
4683 case OPT_static_libphobos:
4684 case OPT_static_libgm2:
4685 case OPT_static_libstdc__:
4686 /* These are always valid; gcc.cc itself understands the first two
4687 gfortranspec.cc understands -static-libgfortran,
4688 libgfortran.spec handles -static-libquadmath,
4689 d-spec.cc understands -static-libphobos,
4690 gm2spec.cc understands -static-libgm2,
4691 and g++spec.cc understands -static-libstdc++. */
4692 validated = true;
4693 break;
4694
4695 case OPT_fwpa:
4696 flag_wpa = "";
4697 break;
4698
4699 case OPT_foffload_options_:
4700 check_foffload_target_names (arg);
4701 break;
4702
4703 case OPT_foffload_:
4704 handle_foffload_option (arg);
4705 if (arg[0] == '-' || NULL != strchr (arg, '='))
4706 save_switch (concat ("-foffload-options=", arg, NULL),
4707 0, NULL, validated, true);
4708 do_save = false;
4709 break;
4710
4711 case OPT_gcodeview:
4712 add_infile ("--pdb=", "*");
4713 break;
4714
4715 default:
4716 /* Various driver options need no special processing at this
4717 point, having been handled in a prescan above or being
4718 handled by specs. */
4719 break;
4720 }
4721
4722 if (do_save)
4723 save_switch (decoded->canonical_option[0],
4724 decoded->canonical_option_num_elements - 1,
4725 &decoded->canonical_option[1], validated, true);
4726 return true;
4727 }
4728
4729 /* Return true if F2 is F1 followed by a single suffix, i.e., by a
4730 period and additional characters other than a period. */
4731
4732 static inline bool
4733 adds_single_suffix_p (const char *f2, const char *f1)
4734 {
4735 size_t len = strlen (f1);
4736
4737 return (strncmp (f1, f2, len) == 0
4738 && f2[len] == '.'
4739 && strchr (f2 + len + 1, '.') == NULL);
4740 }
4741
4742 /* Put the driver's standard set of option handlers in *HANDLERS. */
4743
4744 static void
4745 set_option_handlers (struct cl_option_handlers *handlers)
4746 {
4747 handlers->unknown_option_callback = driver_unknown_option_callback;
4748 handlers->wrong_lang_callback = driver_wrong_lang_callback;
4749 handlers->num_handlers = 3;
4750 handlers->handlers[0].handler = driver_handle_option;
4751 handlers->handlers[0].mask = CL_DRIVER;
4752 handlers->handlers[1].handler = common_handle_option;
4753 handlers->handlers[1].mask = CL_COMMON;
4754 handlers->handlers[2].handler = target_handle_option;
4755 handlers->handlers[2].mask = CL_TARGET;
4756 }
4757
4758
4759 /* Return the index into infiles for the single non-library
4760 non-lto-wpa input file, -1 if there isn't any, or -2 if there is
4761 more than one. */
4762 static inline int
4763 single_input_file_index ()
4764 {
4765 int ret = -1;
4766
4767 for (int i = 0; i < n_infiles; i++)
4768 {
4769 if (infiles[i].language
4770 && (infiles[i].language[0] == '*'
4771 || (flag_wpa
4772 && strcmp (infiles[i].language, "lto") == 0)))
4773 continue;
4774
4775 if (ret != -1)
4776 return -2;
4777
4778 ret = i;
4779 }
4780
4781 return ret;
4782 }
4783
4784 /* Create the vector `switches' and its contents.
4785 Store its length in `n_switches'. */
4786
4787 static void
4788 process_command (unsigned int decoded_options_count,
4789 struct cl_decoded_option *decoded_options)
4790 {
4791 const char *temp;
4792 char *temp1;
4793 char *tooldir_prefix, *tooldir_prefix2;
4794 char *(*get_relative_prefix) (const char *, const char *,
4795 const char *) = NULL;
4796 struct cl_option_handlers handlers;
4797 unsigned int j;
4798
4799 gcc_exec_prefix = env.get ("GCC_EXEC_PREFIX");
4800
4801 n_switches = 0;
4802 n_infiles = 0;
4803 added_libraries = 0;
4804
4805 /* Figure compiler version from version string. */
4806
4807 compiler_version = temp1 = xstrdup (version_string);
4808
4809 for (; *temp1; ++temp1)
4810 {
4811 if (*temp1 == ' ')
4812 {
4813 *temp1 = '\0';
4814 break;
4815 }
4816 }
4817
4818 /* Handle any -no-canonical-prefixes flag early, to assign the function
4819 that builds relative prefixes. This function creates default search
4820 paths that are needed later in normal option handling. */
4821
4822 for (j = 1; j < decoded_options_count; j++)
4823 {
4824 if (decoded_options[j].opt_index == OPT_no_canonical_prefixes)
4825 {
4826 get_relative_prefix = make_relative_prefix_ignore_links;
4827 break;
4828 }
4829 }
4830 if (! get_relative_prefix)
4831 get_relative_prefix = make_relative_prefix;
4832
4833 /* Set up the default search paths. If there is no GCC_EXEC_PREFIX,
4834 see if we can create it from the pathname specified in
4835 decoded_options[0].arg. */
4836
4837 gcc_libexec_prefix = standard_libexec_prefix;
4838 #ifndef VMS
4839 /* FIXME: make_relative_prefix doesn't yet work for VMS. */
4840 if (!gcc_exec_prefix)
4841 {
4842 gcc_exec_prefix = get_relative_prefix (decoded_options[0].arg,
4843 standard_bindir_prefix,
4844 standard_exec_prefix);
4845 gcc_libexec_prefix = get_relative_prefix (decoded_options[0].arg,
4846 standard_bindir_prefix,
4847 standard_libexec_prefix);
4848 if (gcc_exec_prefix)
4849 xputenv (concat ("GCC_EXEC_PREFIX=", gcc_exec_prefix, NULL));
4850 }
4851 else
4852 {
4853 /* make_relative_prefix requires a program name, but
4854 GCC_EXEC_PREFIX is typically a directory name with a trailing
4855 / (which is ignored by make_relative_prefix), so append a
4856 program name. */
4857 char *tmp_prefix = concat (gcc_exec_prefix, "gcc", NULL);
4858 gcc_libexec_prefix = get_relative_prefix (tmp_prefix,
4859 standard_exec_prefix,
4860 standard_libexec_prefix);
4861
4862 /* The path is unrelocated, so fallback to the original setting. */
4863 if (!gcc_libexec_prefix)
4864 gcc_libexec_prefix = standard_libexec_prefix;
4865
4866 free (tmp_prefix);
4867 }
4868 #else
4869 #endif
4870 /* From this point onward, gcc_exec_prefix is non-null if the toolchain
4871 is relocated. The toolchain was either relocated using GCC_EXEC_PREFIX
4872 or an automatically created GCC_EXEC_PREFIX from
4873 decoded_options[0].arg. */
4874
4875 /* Do language-specific adjustment/addition of flags. */
4876 lang_specific_driver (&decoded_options, &decoded_options_count,
4877 &added_libraries);
4878
4879 if (gcc_exec_prefix)
4880 {
4881 int len = strlen (gcc_exec_prefix);
4882
4883 if (len > (int) sizeof ("/lib/gcc/") - 1
4884 && (IS_DIR_SEPARATOR (gcc_exec_prefix[len-1])))
4885 {
4886 temp = gcc_exec_prefix + len - sizeof ("/lib/gcc/") + 1;
4887 if (IS_DIR_SEPARATOR (*temp)
4888 && filename_ncmp (temp + 1, "lib", 3) == 0
4889 && IS_DIR_SEPARATOR (temp[4])
4890 && filename_ncmp (temp + 5, "gcc", 3) == 0)
4891 len -= sizeof ("/lib/gcc/") - 1;
4892 }
4893
4894 set_std_prefix (gcc_exec_prefix, len);
4895 add_prefix (&exec_prefixes, gcc_libexec_prefix, "GCC",
4896 PREFIX_PRIORITY_LAST, 0, 0);
4897 add_prefix (&startfile_prefixes, gcc_exec_prefix, "GCC",
4898 PREFIX_PRIORITY_LAST, 0, 0);
4899 }
4900
4901 /* COMPILER_PATH and LIBRARY_PATH have values
4902 that are lists of directory names with colons. */
4903
4904 temp = env.get ("COMPILER_PATH");
4905 if (temp)
4906 {
4907 const char *startp, *endp;
4908 char *nstore = (char *) alloca (strlen (temp) + 3);
4909
4910 startp = endp = temp;
4911 while (1)
4912 {
4913 if (*endp == PATH_SEPARATOR || *endp == 0)
4914 {
4915 strncpy (nstore, startp, endp - startp);
4916 if (endp == startp)
4917 strcpy (nstore, concat (".", dir_separator_str, NULL));
4918 else if (!IS_DIR_SEPARATOR (endp[-1]))
4919 {
4920 nstore[endp - startp] = DIR_SEPARATOR;
4921 nstore[endp - startp + 1] = 0;
4922 }
4923 else
4924 nstore[endp - startp] = 0;
4925 add_prefix (&exec_prefixes, nstore, 0,
4926 PREFIX_PRIORITY_LAST, 0, 0);
4927 add_prefix (&include_prefixes, nstore, 0,
4928 PREFIX_PRIORITY_LAST, 0, 0);
4929 if (*endp == 0)
4930 break;
4931 endp = startp = endp + 1;
4932 }
4933 else
4934 endp++;
4935 }
4936 }
4937
4938 temp = env.get (LIBRARY_PATH_ENV);
4939 if (temp && *cross_compile == '0')
4940 {
4941 const char *startp, *endp;
4942 char *nstore = (char *) alloca (strlen (temp) + 3);
4943
4944 startp = endp = temp;
4945 while (1)
4946 {
4947 if (*endp == PATH_SEPARATOR || *endp == 0)
4948 {
4949 strncpy (nstore, startp, endp - startp);
4950 if (endp == startp)
4951 strcpy (nstore, concat (".", dir_separator_str, NULL));
4952 else if (!IS_DIR_SEPARATOR (endp[-1]))
4953 {
4954 nstore[endp - startp] = DIR_SEPARATOR;
4955 nstore[endp - startp + 1] = 0;
4956 }
4957 else
4958 nstore[endp - startp] = 0;
4959 add_prefix (&startfile_prefixes, nstore, NULL,
4960 PREFIX_PRIORITY_LAST, 0, 1);
4961 if (*endp == 0)
4962 break;
4963 endp = startp = endp + 1;
4964 }
4965 else
4966 endp++;
4967 }
4968 }
4969
4970 /* Use LPATH like LIBRARY_PATH (for the CMU build program). */
4971 temp = env.get ("LPATH");
4972 if (temp && *cross_compile == '0')
4973 {
4974 const char *startp, *endp;
4975 char *nstore = (char *) alloca (strlen (temp) + 3);
4976
4977 startp = endp = temp;
4978 while (1)
4979 {
4980 if (*endp == PATH_SEPARATOR || *endp == 0)
4981 {
4982 strncpy (nstore, startp, endp - startp);
4983 if (endp == startp)
4984 strcpy (nstore, concat (".", dir_separator_str, NULL));
4985 else if (!IS_DIR_SEPARATOR (endp[-1]))
4986 {
4987 nstore[endp - startp] = DIR_SEPARATOR;
4988 nstore[endp - startp + 1] = 0;
4989 }
4990 else
4991 nstore[endp - startp] = 0;
4992 add_prefix (&startfile_prefixes, nstore, NULL,
4993 PREFIX_PRIORITY_LAST, 0, 1);
4994 if (*endp == 0)
4995 break;
4996 endp = startp = endp + 1;
4997 }
4998 else
4999 endp++;
5000 }
5001 }
5002
5003 /* Process the options and store input files and switches in their
5004 vectors. */
5005
5006 last_language_n_infiles = -1;
5007
5008 set_option_handlers (&handlers);
5009
5010 for (j = 1; j < decoded_options_count; j++)
5011 {
5012 switch (decoded_options[j].opt_index)
5013 {
5014 case OPT_S:
5015 case OPT_c:
5016 case OPT_E:
5017 have_c = 1;
5018 break;
5019 }
5020 if (have_c)
5021 break;
5022 }
5023
5024 for (j = 1; j < decoded_options_count; j++)
5025 {
5026 if (decoded_options[j].opt_index == OPT_SPECIAL_input_file)
5027 {
5028 const char *arg = decoded_options[j].arg;
5029
5030 #ifdef HAVE_TARGET_OBJECT_SUFFIX
5031 arg = convert_filename (arg, 0, access (arg, F_OK));
5032 #endif
5033 add_infile (arg, spec_lang);
5034
5035 continue;
5036 }
5037
5038 read_cmdline_option (&global_options, &global_options_set,
5039 decoded_options + j, UNKNOWN_LOCATION,
5040 CL_DRIVER, &handlers, global_dc);
5041 }
5042
5043 /* If the user didn't specify any, default to all configured offload
5044 targets. */
5045 if (ENABLE_OFFLOADING && offload_targets == NULL)
5046 {
5047 handle_foffload_option (OFFLOAD_TARGETS);
5048 #if OFFLOAD_DEFAULTED
5049 offload_targets_default = true;
5050 #endif
5051 }
5052
5053 /* TODO: check if -static -pie works and maybe use it. */
5054 if (flag_hardened)
5055 {
5056 if (!avoid_linker_hardening_p && !static_p)
5057 {
5058 #if defined HAVE_LD_PIE && defined LD_PIE_SPEC
5059 save_switch (LD_PIE_SPEC, 0, NULL, /*validated=*/true, /*known=*/false);
5060 #endif
5061 /* These are passed straight down to collect2 so we have to break
5062 it up like this. */
5063 if (HAVE_LD_NOW_SUPPORT)
5064 {
5065 add_infile ("-z", "*");
5066 add_infile ("now", "*");
5067 }
5068 if (HAVE_LD_RELRO_SUPPORT)
5069 {
5070 add_infile ("-z", "*");
5071 add_infile ("relro", "*");
5072 }
5073 }
5074 /* We can't use OPT_Whardened yet. Sigh. */
5075 else
5076 warning_at (UNKNOWN_LOCATION, 0,
5077 "linker hardening options not enabled by %<-fhardened%> "
5078 "because other link options were specified on the command "
5079 "line");
5080 }
5081
5082 /* Handle -gtoggle as it would later in toplev.cc:process_options to
5083 make the debug-level-gt spec function work as expected. */
5084 if (flag_gtoggle)
5085 {
5086 if (debug_info_level == DINFO_LEVEL_NONE)
5087 debug_info_level = DINFO_LEVEL_NORMAL;
5088 else
5089 debug_info_level = DINFO_LEVEL_NONE;
5090 }
5091
5092 if (output_file
5093 && strcmp (output_file, "-") != 0
5094 && strcmp (output_file, HOST_BIT_BUCKET) != 0)
5095 {
5096 int i;
5097 for (i = 0; i < n_infiles; i++)
5098 if ((!infiles[i].language || infiles[i].language[0] != '*')
5099 && canonical_filename_eq (infiles[i].name, output_file))
5100 fatal_error (input_location,
5101 "input file %qs is the same as output file",
5102 output_file);
5103 }
5104
5105 if (output_file != NULL && output_file[0] == '\0')
5106 fatal_error (input_location, "output filename may not be empty");
5107
5108 /* -dumpdir and -save-temps=* both specify the location of aux/dump
5109 outputs; the one that appears last prevails. When compiling
5110 multiple sources, an explicit dumpbase (minus -ext) may be
5111 combined with an explicit or implicit dumpdir, whereas when
5112 linking, a specified or implied link output name (minus
5113 extension) may be combined with a prevailing -save-temps=* or an
5114 otherwise implied dumpdir, but not override a prevailing
5115 -dumpdir. Primary outputs (e.g., linker output when linking
5116 without -o, or .i, .s or .o outputs when processing multiple
5117 inputs with -E, -S or -c, respectively) are NOT affected by these
5118 -save-temps=/-dump* options, always landing in the current
5119 directory and with the same basename as the input when an output
5120 name is not given, but when they're intermediate outputs, they
5121 are named like other aux outputs, so the options affect their
5122 location and name.
5123
5124 Here are some examples. There are several more in the
5125 documentation of -o and -dump*, and some quite exhaustive tests
5126 in gcc.misc-tests/outputs.exp.
5127
5128 When compiling any number of sources, no -dump* nor
5129 -save-temps=*, all outputs in cwd without prefix:
5130
5131 # gcc -c b.c -gsplit-dwarf
5132 -> cc1 [-dumpdir ./] -dumpbase b.c -dumpbase-ext .c # b.o b.dwo
5133
5134 # gcc -c b.c d.c -gsplit-dwarf
5135 -> cc1 [-dumpdir ./] -dumpbase b.c -dumpbase-ext .c # b.o b.dwo
5136 && cc1 [-dumpdir ./] -dumpbase d.c -dumpbase-ext .c # d.o d.dwo
5137
5138 When compiling and linking, no -dump* nor -save-temps=*, .o
5139 outputs are temporary, aux outputs land in the dir of the output,
5140 prefixed with the basename of the linker output:
5141
5142 # gcc b.c d.c -o ab -gsplit-dwarf
5143 -> cc1 -dumpdir ab- -dumpbase b.c -dumpbase-ext .c # ab-b.dwo
5144 && cc1 -dumpdir ab- -dumpbase d.c -dumpbase-ext .c # ab-d.dwo
5145 && link ... -o ab
5146
5147 # gcc b.c d.c [-o a.out] -gsplit-dwarf
5148 -> cc1 -dumpdir a- -dumpbase b.c -dumpbase-ext .c # a-b.dwo
5149 && cc1 -dumpdir a- -dumpbase d.c -dumpbase-ext .c # a-d.dwo
5150 && link ... [-o a.out]
5151
5152 When compiling and linking, a prevailing -dumpdir fully overrides
5153 the prefix of aux outputs given by the output name:
5154
5155 # gcc -dumpdir f b.c d.c -gsplit-dwarf [-o [dir/]whatever]
5156 -> cc1 -dumpdir f -dumpbase b.c -dumpbase-ext .c # fb.dwo
5157 && cc1 -dumpdir f -dumpbase d.c -dumpbase-ext .c # fd.dwo
5158 && link ... [-o whatever]
5159
5160 When compiling multiple inputs, an explicit -dumpbase is combined
5161 with -dumpdir, affecting aux outputs, but not the .o outputs:
5162
5163 # gcc -dumpdir f -dumpbase g- b.c d.c -gsplit-dwarf -c
5164 -> cc1 -dumpdir fg- -dumpbase b.c -dumpbase-ext .c # b.o fg-b.dwo
5165 && cc1 -dumpdir fg- -dumpbase d.c -dumpbase-ext .c # d.o fg-d.dwo
5166
5167 When compiling and linking with -save-temps, the .o outputs that
5168 would have been temporary become aux outputs, so they get
5169 affected by -dump* flags:
5170
5171 # gcc -dumpdir f -dumpbase g- -save-temps b.c d.c
5172 -> cc1 -dumpdir fg- -dumpbase b.c -dumpbase-ext .c # fg-b.o
5173 && cc1 -dumpdir fg- -dumpbase d.c -dumpbase-ext .c # fg-d.o
5174 && link
5175
5176 If -save-temps=* prevails over -dumpdir, however, the explicit
5177 -dumpdir is discarded, as if it wasn't there. The basename of
5178 the implicit linker output, a.out or a.exe, becomes a- as the aux
5179 output prefix for all compilations:
5180
5181 # gcc [-dumpdir f] -save-temps=cwd b.c d.c
5182 -> cc1 -dumpdir a- -dumpbase b.c -dumpbase-ext .c # a-b.o
5183 && cc1 -dumpdir a- -dumpbase d.c -dumpbase-ext .c # a-d.o
5184 && link
5185
5186 A single -dumpbase, applying to multiple inputs, overrides the
5187 linker output name, implied or explicit, as the aux output prefix:
5188
5189 # gcc [-dumpdir f] -dumpbase g- -save-temps=cwd b.c d.c
5190 -> cc1 -dumpdir g- -dumpbase b.c -dumpbase-ext .c # g-b.o
5191 && cc1 -dumpdir g- -dumpbase d.c -dumpbase-ext .c # g-d.o
5192 && link
5193
5194 # gcc [-dumpdir f] -dumpbase g- -save-temps=cwd b.c d.c -o dir/h.out
5195 -> cc1 -dumpdir g- -dumpbase b.c -dumpbase-ext .c # g-b.o
5196 && cc1 -dumpdir g- -dumpbase d.c -dumpbase-ext .c # g-d.o
5197 && link -o dir/h.out
5198
5199 Now, if the linker output is NOT overridden as a prefix, but
5200 -save-temps=* overrides implicit or explicit -dumpdir, the
5201 effective dump dir combines the dir selected by the -save-temps=*
5202 option with the basename of the specified or implied link output:
5203
5204 # gcc [-dumpdir f] -save-temps=cwd b.c d.c -o dir/h.out
5205 -> cc1 -dumpdir h- -dumpbase b.c -dumpbase-ext .c # h-b.o
5206 && cc1 -dumpdir h- -dumpbase d.c -dumpbase-ext .c # h-d.o
5207 && link -o dir/h.out
5208
5209 # gcc [-dumpdir f] -save-temps=obj b.c d.c -o dir/h.out
5210 -> cc1 -dumpdir dir/h- -dumpbase b.c -dumpbase-ext .c # dir/h-b.o
5211 && cc1 -dumpdir dir/h- -dumpbase d.c -dumpbase-ext .c # dir/h-d.o
5212 && link -o dir/h.out
5213
5214 But then again, a single -dumpbase applying to multiple inputs
5215 gets used instead of the linker output basename in the combined
5216 dumpdir:
5217
5218 # gcc [-dumpdir f] -dumpbase g- -save-temps=obj b.c d.c -o dir/h.out
5219 -> cc1 -dumpdir dir/g- -dumpbase b.c -dumpbase-ext .c # dir/g-b.o
5220 && cc1 -dumpdir dir/g- -dumpbase d.c -dumpbase-ext .c # dir/g-d.o
5221 && link -o dir/h.out
5222
5223 With a single input being compiled, the output basename does NOT
5224 affect the dumpdir prefix.
5225
5226 # gcc -save-temps=obj b.c -gsplit-dwarf -c -o dir/b.o
5227 -> cc1 -dumpdir dir/ -dumpbase b.c -dumpbase-ext .c # dir/b.o dir/b.dwo
5228
5229 but when compiling and linking even a single file, it does:
5230
5231 # gcc -save-temps=obj b.c -o dir/h.out
5232 -> cc1 -dumpdir dir/h- -dumpbase b.c -dumpbase-ext .c # dir/h-b.o
5233
5234 unless an explicit -dumpdir prevails:
5235
5236 # gcc -save-temps[=obj] -dumpdir g- b.c -o dir/h.out
5237 -> cc1 -dumpdir g- -dumpbase b.c -dumpbase-ext .c # g-b.o
5238
5239 */
5240
5241 bool explicit_dumpdir = dumpdir;
5242
5243 if ((!save_temps_overrides_dumpdir && explicit_dumpdir)
5244 || (output_file && not_actual_file_p (output_file)))
5245 {
5246 /* Do nothing. */
5247 }
5248
5249 /* If -save-temps=obj and -o name, create the prefix to use for %b.
5250 Otherwise just make -save-temps=obj the same as -save-temps=cwd. */
5251 else if (save_temps_flag != SAVE_TEMPS_CWD && output_file != NULL)
5252 {
5253 free (dumpdir);
5254 dumpdir = NULL;
5255 temp = lbasename (output_file);
5256 if (temp != output_file)
5257 dumpdir = xstrndup (output_file,
5258 strlen (output_file) - strlen (temp));
5259 }
5260 else if (dumpdir)
5261 {
5262 free (dumpdir);
5263 dumpdir = NULL;
5264 }
5265
5266 if (save_temps_flag)
5267 save_temps_flag = SAVE_TEMPS_DUMP;
5268
5269 /* If there is any pathname component in an explicit -dumpbase, it
5270 overrides dumpdir entirely, so discard it right away. Although
5271 the presence of an explicit -dumpdir matters for the driver, it
5272 shouldn't matter for other processes, that get all that's needed
5273 from the -dumpdir and -dumpbase always passed to them. */
5274 if (dumpdir && dumpbase && lbasename (dumpbase) != dumpbase)
5275 {
5276 free (dumpdir);
5277 dumpdir = NULL;
5278 }
5279
5280 /* Check that dumpbase_ext matches the end of dumpbase, drop it
5281 otherwise. */
5282 if (dumpbase_ext && dumpbase && *dumpbase)
5283 {
5284 int lendb = strlen (dumpbase);
5285 int lendbx = strlen (dumpbase_ext);
5286
5287 /* -dumpbase-ext must be a suffix proper; discard it if it
5288 matches all of -dumpbase, as that would make for an empty
5289 basename. */
5290 if (lendbx >= lendb
5291 || strcmp (dumpbase + lendb - lendbx, dumpbase_ext) != 0)
5292 {
5293 free (dumpbase_ext);
5294 dumpbase_ext = NULL;
5295 }
5296 }
5297
5298 /* -dumpbase with multiple sources goes into dumpdir. With a single
5299 source, it does only if linking and if dumpdir was not explicitly
5300 specified. */
5301 if (dumpbase && *dumpbase
5302 && (single_input_file_index () == -2
5303 || (!have_c && !explicit_dumpdir)))
5304 {
5305 char *prefix;
5306
5307 if (dumpbase_ext)
5308 /* We checked that they match above. */
5309 dumpbase[strlen (dumpbase) - strlen (dumpbase_ext)] = '\0';
5310
5311 if (dumpdir)
5312 prefix = concat (dumpdir, dumpbase, "-", NULL);
5313 else
5314 prefix = concat (dumpbase, "-", NULL);
5315
5316 free (dumpdir);
5317 free (dumpbase);
5318 free (dumpbase_ext);
5319 dumpbase = dumpbase_ext = NULL;
5320 dumpdir = prefix;
5321 dumpdir_trailing_dash_added = true;
5322 }
5323
5324 /* If dumpbase was not brought into dumpdir but we're linking, bring
5325 output_file into dumpdir unless dumpdir was explicitly specified.
5326 The test for !explicit_dumpdir is further below, because we want
5327 to use the obase computation for a ghost outbase, passed to
5328 GCC_COLLECT_OPTIONS. */
5329 else if (!have_c && (!explicit_dumpdir || (dumpbase && !*dumpbase)))
5330 {
5331 /* If we get here, we know dumpbase was not specified, or it was
5332 specified as an empty string. If it was anything else, it
5333 would have combined with dumpdir above, because the condition
5334 for dumpbase to be used when present is broader than the
5335 condition that gets us here. */
5336 gcc_assert (!dumpbase || !*dumpbase);
5337
5338 const char *obase;
5339 char *tofree = NULL;
5340 if (!output_file || not_actual_file_p (output_file))
5341 obase = "a";
5342 else
5343 {
5344 obase = lbasename (output_file);
5345 size_t blen = strlen (obase), xlen;
5346 /* Drop the suffix if it's dumpbase_ext, if given,
5347 otherwise .exe or the target executable suffix, or if the
5348 output was explicitly named a.out, but not otherwise. */
5349 if (dumpbase_ext
5350 ? (blen > (xlen = strlen (dumpbase_ext))
5351 && strcmp ((temp = (obase + blen - xlen)),
5352 dumpbase_ext) == 0)
5353 : ((temp = strrchr (obase + 1, '.'))
5354 && (xlen = strlen (temp))
5355 && (strcmp (temp, ".exe") == 0
5356 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
5357 || strcmp (temp, TARGET_EXECUTABLE_SUFFIX) == 0
5358 #endif
5359 || strcmp (obase, "a.out") == 0)))
5360 {
5361 tofree = xstrndup (obase, blen - xlen);
5362 obase = tofree;
5363 }
5364 }
5365
5366 /* We wish to save this basename to the -dumpdir passed through
5367 GCC_COLLECT_OPTIONS within maybe_run_linker, for e.g. LTO,
5368 but we do NOT wish to add it to e.g. %b, so we keep
5369 outbase_length as zero. */
5370 gcc_assert (!outbase);
5371 outbase_length = 0;
5372
5373 /* If we're building [dir1/]foo[.exe] out of a single input
5374 [dir2/]foo.c that shares the same basename, dump to
5375 [dir2/]foo.c.* rather than duplicating the basename into
5376 [dir2/]foo-foo.c.*. */
5377 int idxin;
5378 if (dumpbase
5379 || ((idxin = single_input_file_index ()) >= 0
5380 && adds_single_suffix_p (lbasename (infiles[idxin].name),
5381 obase)))
5382 {
5383 if (obase == tofree)
5384 outbase = tofree;
5385 else
5386 {
5387 outbase = xstrdup (obase);
5388 free (tofree);
5389 }
5390 obase = tofree = NULL;
5391 }
5392 else
5393 {
5394 if (dumpdir)
5395 {
5396 char *p = concat (dumpdir, obase, "-", NULL);
5397 free (dumpdir);
5398 dumpdir = p;
5399 }
5400 else
5401 dumpdir = concat (obase, "-", NULL);
5402
5403 dumpdir_trailing_dash_added = true;
5404
5405 free (tofree);
5406 obase = tofree = NULL;
5407 }
5408
5409 if (!explicit_dumpdir || dumpbase)
5410 {
5411 /* Absent -dumpbase and present -dumpbase-ext have been applied
5412 to the linker output name, so compute fresh defaults for each
5413 compilation. */
5414 free (dumpbase_ext);
5415 dumpbase_ext = NULL;
5416 }
5417 }
5418
5419 /* Now, if we're compiling, or if we haven't used the dumpbase
5420 above, then outbase (%B) is derived from dumpbase, if given, or
5421 from the output name, given or implied. We can't precompute
5422 implied output names, but that's ok, since they're derived from
5423 input names. Just make sure we skip this if dumpbase is the
5424 empty string: we want to use input names then, so don't set
5425 outbase. */
5426 if ((dumpbase || have_c)
5427 && !(dumpbase && !*dumpbase))
5428 {
5429 gcc_assert (!outbase);
5430
5431 if (dumpbase)
5432 {
5433 gcc_assert (single_input_file_index () != -2);
5434 /* We do not want lbasename here; dumpbase with dirnames
5435 overrides dumpdir entirely, even if dumpdir is
5436 specified. */
5437 if (dumpbase_ext)
5438 /* We've already checked above that the suffix matches. */
5439 outbase = xstrndup (dumpbase,
5440 strlen (dumpbase) - strlen (dumpbase_ext));
5441 else
5442 outbase = xstrdup (dumpbase);
5443 }
5444 else if (output_file && !not_actual_file_p (output_file))
5445 {
5446 outbase = xstrdup (lbasename (output_file));
5447 char *p = strrchr (outbase + 1, '.');
5448 if (p)
5449 *p = '\0';
5450 }
5451
5452 if (outbase)
5453 outbase_length = strlen (outbase);
5454 }
5455
5456 /* If there is any pathname component in an explicit -dumpbase, do
5457 not use dumpdir, but retain it to pass it on to the compiler. */
5458 if (dumpdir)
5459 dumpdir_length = strlen (dumpdir);
5460 else
5461 dumpdir_length = 0;
5462
5463 /* Check that dumpbase_ext, if still present, still matches the end
5464 of dumpbase, if present, and drop it otherwise. We only retained
5465 it above when dumpbase was absent to maybe use it to drop the
5466 extension from output_name before combining it with dumpdir. We
5467 won't deal with -dumpbase-ext when -dumpbase is not explicitly
5468 given, even if just to activate backward-compatible dumpbase:
5469 dropping it on the floor is correct, expected and documented
5470 behavior. Attempting to deal with a -dumpbase-ext that might
5471 match the end of some input filename, or of the combination of
5472 the output basename with the suffix of the input filename,
5473 possible with an intermediate .gk extension for -fcompare-debug,
5474 is just calling for trouble. */
5475 if (dumpbase_ext)
5476 {
5477 if (!dumpbase || !*dumpbase)
5478 {
5479 free (dumpbase_ext);
5480 dumpbase_ext = NULL;
5481 }
5482 else
5483 gcc_assert (strcmp (dumpbase + strlen (dumpbase)
5484 - strlen (dumpbase_ext), dumpbase_ext) == 0);
5485 }
5486
5487 if (save_temps_flag && use_pipes)
5488 {
5489 /* -save-temps overrides -pipe, so that temp files are produced */
5490 if (save_temps_flag)
5491 warning (0, "%<-pipe%> ignored because %<-save-temps%> specified");
5492 use_pipes = 0;
5493 }
5494
5495 if (!compare_debug)
5496 {
5497 const char *gcd = env.get ("GCC_COMPARE_DEBUG");
5498
5499 if (gcd && gcd[0] == '-')
5500 {
5501 compare_debug = 2;
5502 compare_debug_opt = gcd;
5503 }
5504 else if (gcd && *gcd && strcmp (gcd, "0"))
5505 {
5506 compare_debug = 3;
5507 compare_debug_opt = "-gtoggle";
5508 }
5509 }
5510 else if (compare_debug < 0)
5511 {
5512 compare_debug = 0;
5513 gcc_assert (!compare_debug_opt);
5514 }
5515
5516 /* Set up the search paths. We add directories that we expect to
5517 contain GNU Toolchain components before directories specified by
5518 the machine description so that we will find GNU components (like
5519 the GNU assembler) before those of the host system. */
5520
5521 /* If we don't know where the toolchain has been installed, use the
5522 configured-in locations. */
5523 if (!gcc_exec_prefix)
5524 {
5525 #ifndef OS2
5526 add_prefix (&exec_prefixes, standard_libexec_prefix, "GCC",
5527 PREFIX_PRIORITY_LAST, 1, 0);
5528 add_prefix (&exec_prefixes, standard_libexec_prefix, "BINUTILS",
5529 PREFIX_PRIORITY_LAST, 2, 0);
5530 add_prefix (&exec_prefixes, standard_exec_prefix, "BINUTILS",
5531 PREFIX_PRIORITY_LAST, 2, 0);
5532 #endif
5533 add_prefix (&startfile_prefixes, standard_exec_prefix, "BINUTILS",
5534 PREFIX_PRIORITY_LAST, 1, 0);
5535 }
5536
5537 gcc_assert (!IS_ABSOLUTE_PATH (tooldir_base_prefix));
5538 tooldir_prefix2 = concat (tooldir_base_prefix, spec_machine,
5539 dir_separator_str, NULL);
5540
5541 /* Look for tools relative to the location from which the driver is
5542 running, or, if that is not available, the configured prefix. */
5543 tooldir_prefix
5544 = concat (gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
5545 spec_host_machine, dir_separator_str, spec_version,
5546 accel_dir_suffix, dir_separator_str, tooldir_prefix2, NULL);
5547 free (tooldir_prefix2);
5548
5549 add_prefix (&exec_prefixes,
5550 concat (tooldir_prefix, "bin", dir_separator_str, NULL),
5551 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 0);
5552 add_prefix (&startfile_prefixes,
5553 concat (tooldir_prefix, "lib", dir_separator_str, NULL),
5554 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 1);
5555 free (tooldir_prefix);
5556
5557 #if defined(TARGET_SYSTEM_ROOT_RELOCATABLE) && !defined(VMS)
5558 /* If the normal TARGET_SYSTEM_ROOT is inside of $exec_prefix,
5559 then consider it to relocate with the rest of the GCC installation
5560 if GCC_EXEC_PREFIX is set.
5561 ``make_relative_prefix'' is not compiled for VMS, so don't call it. */
5562 if (target_system_root && !target_system_root_changed && gcc_exec_prefix)
5563 {
5564 char *tmp_prefix = get_relative_prefix (decoded_options[0].arg,
5565 standard_bindir_prefix,
5566 target_system_root);
5567 if (tmp_prefix && access_check (tmp_prefix, F_OK) == 0)
5568 {
5569 target_system_root = tmp_prefix;
5570 target_system_root_changed = 1;
5571 }
5572 }
5573 #endif
5574
5575 /* More prefixes are enabled in main, after we read the specs file
5576 and determine whether this is cross-compilation or not. */
5577
5578 if (n_infiles != 0 && n_infiles == last_language_n_infiles && spec_lang != 0)
5579 warning (0, "%<-x %s%> after last input file has no effect", spec_lang);
5580
5581 /* Synthesize -fcompare-debug flag from the GCC_COMPARE_DEBUG
5582 environment variable. */
5583 if (compare_debug == 2 || compare_debug == 3)
5584 {
5585 const char *opt = concat ("-fcompare-debug=", compare_debug_opt, NULL);
5586 save_switch (opt, 0, NULL, false, true);
5587 compare_debug = 1;
5588 }
5589
5590 /* Ensure we only invoke each subprocess once. */
5591 if (n_infiles == 0
5592 && (print_subprocess_help || print_help_list || print_version))
5593 {
5594 /* Create a dummy input file, so that we can pass
5595 the help option on to the various sub-processes. */
5596 add_infile ("help-dummy", "c");
5597 }
5598
5599 /* Decide if undefined variable references are allowed in specs. */
5600
5601 /* -v alone is safe. --version and --help alone or together are safe. Note
5602 that -v would make them unsafe, as they'd then be run for subprocesses as
5603 well, the location of which might depend on variables possibly coming
5604 from self-specs. Note also that the command name is counted in
5605 decoded_options_count. */
5606
5607 unsigned help_version_count = 0;
5608
5609 if (print_version)
5610 help_version_count++;
5611
5612 if (print_help_list)
5613 help_version_count++;
5614
5615 spec_undefvar_allowed =
5616 ((verbose_flag && decoded_options_count == 2)
5617 || help_version_count == decoded_options_count - 1);
5618
5619 alloc_switch ();
5620 switches[n_switches].part1 = 0;
5621 alloc_infile ();
5622 infiles[n_infiles].name = 0;
5623 }
5624
5625 /* Store switches not filtered out by %<S in spec in COLLECT_GCC_OPTIONS
5626 and place that in the environment. */
5627
5628 static void
5629 set_collect_gcc_options (void)
5630 {
5631 int i;
5632 int first_time;
5633
5634 /* Build COLLECT_GCC_OPTIONS to have all of the options specified to
5635 the compiler. */
5636 obstack_grow (&collect_obstack, "COLLECT_GCC_OPTIONS=",
5637 sizeof ("COLLECT_GCC_OPTIONS=") - 1);
5638
5639 first_time = true;
5640 for (i = 0; (int) i < n_switches; i++)
5641 {
5642 const char *const *args;
5643 const char *p, *q;
5644 if (!first_time)
5645 obstack_grow (&collect_obstack, " ", 1);
5646
5647 first_time = false;
5648
5649 /* Ignore elided switches. */
5650 if ((switches[i].live_cond
5651 & (SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC))
5652 == SWITCH_IGNORE)
5653 continue;
5654
5655 obstack_grow (&collect_obstack, "'-", 2);
5656 q = switches[i].part1;
5657 while ((p = strchr (q, '\'')))
5658 {
5659 obstack_grow (&collect_obstack, q, p - q);
5660 obstack_grow (&collect_obstack, "'\\''", 4);
5661 q = ++p;
5662 }
5663 obstack_grow (&collect_obstack, q, strlen (q));
5664 obstack_grow (&collect_obstack, "'", 1);
5665
5666 for (args = switches[i].args; args && *args; args++)
5667 {
5668 obstack_grow (&collect_obstack, " '", 2);
5669 q = *args;
5670 while ((p = strchr (q, '\'')))
5671 {
5672 obstack_grow (&collect_obstack, q, p - q);
5673 obstack_grow (&collect_obstack, "'\\''", 4);
5674 q = ++p;
5675 }
5676 obstack_grow (&collect_obstack, q, strlen (q));
5677 obstack_grow (&collect_obstack, "'", 1);
5678 }
5679 }
5680
5681 if (dumpdir)
5682 {
5683 if (!first_time)
5684 obstack_grow (&collect_obstack, " ", 1);
5685 first_time = false;
5686
5687 obstack_grow (&collect_obstack, "'-dumpdir' '", 12);
5688 const char *p, *q;
5689
5690 q = dumpdir;
5691 while ((p = strchr (q, '\'')))
5692 {
5693 obstack_grow (&collect_obstack, q, p - q);
5694 obstack_grow (&collect_obstack, "'\\''", 4);
5695 q = ++p;
5696 }
5697 obstack_grow (&collect_obstack, q, strlen (q));
5698
5699 obstack_grow (&collect_obstack, "'", 1);
5700 }
5701
5702 obstack_grow (&collect_obstack, "\0", 1);
5703 xputenv (XOBFINISH (&collect_obstack, char *));
5704 }
5705
5706 /* Process a spec string, accumulating and running commands. */
5707
5708 /* These variables describe the input file name.
5709 input_file_number is the index on outfiles of this file,
5710 so that the output file name can be stored for later use by %o.
5711 input_basename is the start of the part of the input file
5712 sans all directory names, and basename_length is the number
5713 of characters starting there excluding the suffix .c or whatever. */
5714
5715 static const char *gcc_input_filename;
5716 static int input_file_number;
5717 size_t input_filename_length;
5718 static int basename_length;
5719 static int suffixed_basename_length;
5720 static const char *input_basename;
5721 static const char *input_suffix;
5722 #ifndef HOST_LACKS_INODE_NUMBERS
5723 static struct stat input_stat;
5724 #endif
5725 static int input_stat_set;
5726
5727 /* The compiler used to process the current input file. */
5728 static struct compiler *input_file_compiler;
5729
5730 /* These are variables used within do_spec and do_spec_1. */
5731
5732 /* Nonzero if an arg has been started and not yet terminated
5733 (with space, tab or newline). */
5734 static int arg_going;
5735
5736 /* Nonzero means %d or %g has been seen; the next arg to be terminated
5737 is a temporary file name. */
5738 static int delete_this_arg;
5739
5740 /* Nonzero means %w has been seen; the next arg to be terminated
5741 is the output file name of this compilation. */
5742 static int this_is_output_file;
5743
5744 /* Nonzero means %s has been seen; the next arg to be terminated
5745 is the name of a library file and we should try the standard
5746 search dirs for it. */
5747 static int this_is_library_file;
5748
5749 /* Nonzero means %T has been seen; the next arg to be terminated
5750 is the name of a linker script and we should try all of the
5751 standard search dirs for it. If it is found insert a --script
5752 command line switch and then substitute the full path in place,
5753 otherwise generate an error message. */
5754 static int this_is_linker_script;
5755
5756 /* Nonzero means that the input of this command is coming from a pipe. */
5757 static int input_from_pipe;
5758
5759 /* Nonnull means substitute this for any suffix when outputting a switches
5760 arguments. */
5761 static const char *suffix_subst;
5762
5763 /* If there is an argument being accumulated, terminate it and store it. */
5764
5765 static void
5766 end_going_arg (void)
5767 {
5768 if (arg_going)
5769 {
5770 const char *string;
5771
5772 obstack_1grow (&obstack, 0);
5773 string = XOBFINISH (&obstack, const char *);
5774 if (this_is_library_file)
5775 string = find_file (string);
5776 if (this_is_linker_script)
5777 {
5778 char * full_script_path = find_a_file (&startfile_prefixes, string, R_OK, true);
5779
5780 if (full_script_path == NULL)
5781 {
5782 error ("unable to locate default linker script %qs in the library search paths", string);
5783 /* Script was not found on search path. */
5784 return;
5785 }
5786 store_arg ("--script", false, false);
5787 string = full_script_path;
5788 }
5789 store_arg (string, delete_this_arg, this_is_output_file);
5790 if (this_is_output_file)
5791 outfiles[input_file_number] = string;
5792 arg_going = 0;
5793 }
5794 }
5795
5796
5797 /* Parse the WRAPPER string which is a comma separated list of the command line
5798 and insert them into the beginning of argbuf. */
5799
5800 static void
5801 insert_wrapper (const char *wrapper)
5802 {
5803 int n = 0;
5804 int i;
5805 char *buf = xstrdup (wrapper);
5806 char *p = buf;
5807 unsigned int old_length = argbuf.length ();
5808
5809 do
5810 {
5811 n++;
5812 while (*p == ',')
5813 p++;
5814 }
5815 while ((p = strchr (p, ',')) != NULL);
5816
5817 argbuf.safe_grow (old_length + n, true);
5818 memmove (argbuf.address () + n,
5819 argbuf.address (),
5820 old_length * sizeof (const_char_p));
5821
5822 i = 0;
5823 p = buf;
5824 do
5825 {
5826 while (*p == ',')
5827 {
5828 *p = 0;
5829 p++;
5830 }
5831 argbuf[i] = p;
5832 i++;
5833 }
5834 while ((p = strchr (p, ',')) != NULL);
5835 gcc_assert (i == n);
5836 }
5837
5838 /* Process the spec SPEC and run the commands specified therein.
5839 Returns 0 if the spec is successfully processed; -1 if failed. */
5840
5841 int
5842 do_spec (const char *spec)
5843 {
5844 int value;
5845
5846 value = do_spec_2 (spec, NULL);
5847
5848 /* Force out any unfinished command.
5849 If -pipe, this forces out the last command if it ended in `|'. */
5850 if (value == 0)
5851 {
5852 if (argbuf.length () > 0
5853 && !strcmp (argbuf.last (), "|"))
5854 argbuf.pop ();
5855
5856 set_collect_gcc_options ();
5857
5858 if (argbuf.length () > 0)
5859 value = execute ();
5860 }
5861
5862 return value;
5863 }
5864
5865 /* Process the spec SPEC, with SOFT_MATCHED_PART designating the current value
5866 of a matched * pattern which may be re-injected by way of %*. */
5867
5868 static int
5869 do_spec_2 (const char *spec, const char *soft_matched_part)
5870 {
5871 int result;
5872
5873 clear_args ();
5874 arg_going = 0;
5875 delete_this_arg = 0;
5876 this_is_output_file = 0;
5877 this_is_library_file = 0;
5878 this_is_linker_script = 0;
5879 input_from_pipe = 0;
5880 suffix_subst = NULL;
5881
5882 result = do_spec_1 (spec, 0, soft_matched_part);
5883
5884 end_going_arg ();
5885
5886 return result;
5887 }
5888
5889 /* Process the given spec string and add any new options to the end
5890 of the switches/n_switches array. */
5891
5892 static void
5893 do_option_spec (const char *name, const char *spec)
5894 {
5895 unsigned int i, value_count, value_len;
5896 const char *p, *q, *value;
5897 char *tmp_spec, *tmp_spec_p;
5898
5899 if (configure_default_options[0].name == NULL)
5900 return;
5901
5902 for (i = 0; i < ARRAY_SIZE (configure_default_options); i++)
5903 if (strcmp (configure_default_options[i].name, name) == 0)
5904 break;
5905 if (i == ARRAY_SIZE (configure_default_options))
5906 return;
5907
5908 value = configure_default_options[i].value;
5909 value_len = strlen (value);
5910
5911 /* Compute the size of the final spec. */
5912 value_count = 0;
5913 p = spec;
5914 while ((p = strstr (p, "%(VALUE)")) != NULL)
5915 {
5916 p ++;
5917 value_count ++;
5918 }
5919
5920 /* Replace each %(VALUE) by the specified value. */
5921 tmp_spec = (char *) alloca (strlen (spec) + 1
5922 + value_count * (value_len - strlen ("%(VALUE)")));
5923 tmp_spec_p = tmp_spec;
5924 q = spec;
5925 while ((p = strstr (q, "%(VALUE)")) != NULL)
5926 {
5927 memcpy (tmp_spec_p, q, p - q);
5928 tmp_spec_p = tmp_spec_p + (p - q);
5929 memcpy (tmp_spec_p, value, value_len);
5930 tmp_spec_p += value_len;
5931 q = p + strlen ("%(VALUE)");
5932 }
5933 strcpy (tmp_spec_p, q);
5934
5935 do_self_spec (tmp_spec);
5936 }
5937
5938 /* Process the given spec string and add any new options to the end
5939 of the switches/n_switches array. */
5940
5941 static void
5942 do_self_spec (const char *spec)
5943 {
5944 int i;
5945
5946 do_spec_2 (spec, NULL);
5947 do_spec_1 (" ", 0, NULL);
5948
5949 /* Mark %<S switches processed by do_self_spec to be ignored permanently.
5950 do_self_specs adds the replacements to switches array, so it shouldn't
5951 be processed afterwards. */
5952 for (i = 0; i < n_switches; i++)
5953 if ((switches[i].live_cond & SWITCH_IGNORE))
5954 switches[i].live_cond |= SWITCH_IGNORE_PERMANENTLY;
5955
5956 if (argbuf.length () > 0)
5957 {
5958 const char **argbuf_copy;
5959 struct cl_decoded_option *decoded_options;
5960 struct cl_option_handlers handlers;
5961 unsigned int decoded_options_count;
5962 unsigned int j;
5963
5964 /* Create a copy of argbuf with a dummy argv[0] entry for
5965 decode_cmdline_options_to_array. */
5966 argbuf_copy = XNEWVEC (const char *,
5967 argbuf.length () + 1);
5968 argbuf_copy[0] = "";
5969 memcpy (argbuf_copy + 1, argbuf.address (),
5970 argbuf.length () * sizeof (const char *));
5971
5972 decode_cmdline_options_to_array (argbuf.length () + 1,
5973 argbuf_copy,
5974 CL_DRIVER, &decoded_options,
5975 &decoded_options_count);
5976 free (argbuf_copy);
5977
5978 set_option_handlers (&handlers);
5979
5980 for (j = 1; j < decoded_options_count; j++)
5981 {
5982 switch (decoded_options[j].opt_index)
5983 {
5984 case OPT_SPECIAL_input_file:
5985 /* Specs should only generate options, not input
5986 files. */
5987 if (strcmp (decoded_options[j].arg, "-") != 0)
5988 fatal_error (input_location,
5989 "switch %qs does not start with %<-%>",
5990 decoded_options[j].arg);
5991 else
5992 fatal_error (input_location,
5993 "spec-generated switch is just %<-%>");
5994 break;
5995
5996 case OPT_fcompare_debug_second:
5997 case OPT_fcompare_debug:
5998 case OPT_fcompare_debug_:
5999 case OPT_o:
6000 /* Avoid duplicate processing of some options from
6001 compare-debug specs; just save them here. */
6002 save_switch (decoded_options[j].canonical_option[0],
6003 (decoded_options[j].canonical_option_num_elements
6004 - 1),
6005 &decoded_options[j].canonical_option[1], false, true);
6006 break;
6007
6008 default:
6009 read_cmdline_option (&global_options, &global_options_set,
6010 decoded_options + j, UNKNOWN_LOCATION,
6011 CL_DRIVER, &handlers, global_dc);
6012 break;
6013 }
6014 }
6015
6016 free (decoded_options);
6017
6018 alloc_switch ();
6019 switches[n_switches].part1 = 0;
6020 }
6021 }
6022
6023 /* Callback for processing %D and %I specs. */
6024
6025 struct spec_path_info {
6026 const char *option;
6027 const char *append;
6028 size_t append_len;
6029 bool omit_relative;
6030 bool separate_options;
6031 bool realpaths;
6032 };
6033
6034 static void *
6035 spec_path (char *path, void *data)
6036 {
6037 struct spec_path_info *info = (struct spec_path_info *) data;
6038 size_t len = 0;
6039 char save = 0;
6040
6041 /* The path must exist; we want to resolve it to the realpath so that this
6042 can be embedded as a runpath. */
6043 if (info->realpaths)
6044 path = lrealpath (path);
6045
6046 /* However, if we failed to resolve it - perhaps because there was a bogus
6047 -B option on the command line, then punt on this entry. */
6048 if (!path)
6049 return NULL;
6050
6051 if (info->omit_relative && !IS_ABSOLUTE_PATH (path))
6052 return NULL;
6053
6054 if (info->append_len != 0)
6055 {
6056 len = strlen (path);
6057 memcpy (path + len, info->append, info->append_len + 1);
6058 }
6059
6060 if (!is_directory (path))
6061 return NULL;
6062
6063 do_spec_1 (info->option, 1, NULL);
6064 if (info->separate_options)
6065 do_spec_1 (" ", 0, NULL);
6066
6067 if (info->append_len == 0)
6068 {
6069 len = strlen (path);
6070 save = path[len - 1];
6071 if (IS_DIR_SEPARATOR (path[len - 1]))
6072 path[len - 1] = '\0';
6073 }
6074
6075 do_spec_1 (path, 1, NULL);
6076 do_spec_1 (" ", 0, NULL);
6077
6078 /* Must not damage the original path. */
6079 if (info->append_len == 0)
6080 path[len - 1] = save;
6081
6082 return NULL;
6083 }
6084
6085 /* True if we should compile INFILE. */
6086
6087 static bool
6088 compile_input_file_p (struct infile *infile)
6089 {
6090 if ((!infile->language) || (infile->language[0] != '*'))
6091 if (infile->incompiler == input_file_compiler)
6092 return true;
6093 return false;
6094 }
6095
6096 /* Process each member of VEC as a spec. */
6097
6098 static void
6099 do_specs_vec (vec<char_p> vec)
6100 {
6101 for (char *opt : vec)
6102 {
6103 do_spec_1 (opt, 1, NULL);
6104 /* Make each accumulated option a separate argument. */
6105 do_spec_1 (" ", 0, NULL);
6106 }
6107 }
6108
6109 /* Add options passed via -Xassembler or -Wa to COLLECT_AS_OPTIONS. */
6110
6111 static void
6112 putenv_COLLECT_AS_OPTIONS (vec<char_p> vec)
6113 {
6114 if (vec.is_empty ())
6115 return;
6116
6117 obstack_init (&collect_obstack);
6118 obstack_grow (&collect_obstack, "COLLECT_AS_OPTIONS=",
6119 strlen ("COLLECT_AS_OPTIONS="));
6120
6121 char *opt;
6122 unsigned ix;
6123
6124 FOR_EACH_VEC_ELT (vec, ix, opt)
6125 {
6126 obstack_1grow (&collect_obstack, '\'');
6127 obstack_grow (&collect_obstack, opt, strlen (opt));
6128 obstack_1grow (&collect_obstack, '\'');
6129 if (ix < vec.length () - 1)
6130 obstack_1grow(&collect_obstack, ' ');
6131 }
6132
6133 obstack_1grow (&collect_obstack, '\0');
6134 xputenv (XOBFINISH (&collect_obstack, char *));
6135 }
6136
6137 /* Process the sub-spec SPEC as a portion of a larger spec.
6138 This is like processing a whole spec except that we do
6139 not initialize at the beginning and we do not supply a
6140 newline by default at the end.
6141 INSWITCH nonzero means don't process %-sequences in SPEC;
6142 in this case, % is treated as an ordinary character.
6143 This is used while substituting switches.
6144 INSWITCH nonzero also causes SPC not to terminate an argument.
6145
6146 Value is zero unless a line was finished
6147 and the command on that line reported an error. */
6148
6149 static int
6150 do_spec_1 (const char *spec, int inswitch, const char *soft_matched_part)
6151 {
6152 const char *p = spec;
6153 int c;
6154 int i;
6155 int value;
6156
6157 /* If it's an empty string argument to a switch, keep it as is. */
6158 if (inswitch && !*p)
6159 arg_going = 1;
6160
6161 while ((c = *p++))
6162 /* If substituting a switch, treat all chars like letters.
6163 Otherwise, NL, SPC, TAB and % are special. */
6164 switch (inswitch ? 'a' : c)
6165 {
6166 case '\n':
6167 end_going_arg ();
6168
6169 if (argbuf.length () > 0
6170 && !strcmp (argbuf.last (), "|"))
6171 {
6172 /* A `|' before the newline means use a pipe here,
6173 but only if -pipe was specified.
6174 Otherwise, execute now and don't pass the `|' as an arg. */
6175 if (use_pipes)
6176 {
6177 input_from_pipe = 1;
6178 break;
6179 }
6180 else
6181 argbuf.pop ();
6182 }
6183
6184 set_collect_gcc_options ();
6185
6186 if (argbuf.length () > 0)
6187 {
6188 value = execute ();
6189 if (value)
6190 return value;
6191 }
6192 /* Reinitialize for a new command, and for a new argument. */
6193 clear_args ();
6194 arg_going = 0;
6195 delete_this_arg = 0;
6196 this_is_output_file = 0;
6197 this_is_library_file = 0;
6198 this_is_linker_script = 0;
6199 input_from_pipe = 0;
6200 break;
6201
6202 case '|':
6203 end_going_arg ();
6204
6205 /* Use pipe */
6206 obstack_1grow (&obstack, c);
6207 arg_going = 1;
6208 break;
6209
6210 case '\t':
6211 case ' ':
6212 end_going_arg ();
6213
6214 /* Reinitialize for a new argument. */
6215 delete_this_arg = 0;
6216 this_is_output_file = 0;
6217 this_is_library_file = 0;
6218 this_is_linker_script = 0;
6219 break;
6220
6221 case '%':
6222 switch (c = *p++)
6223 {
6224 case 0:
6225 fatal_error (input_location, "spec %qs invalid", spec);
6226
6227 case 'b':
6228 /* Don't use %b in the linker command. */
6229 gcc_assert (suffixed_basename_length);
6230 if (!this_is_output_file && dumpdir_length)
6231 obstack_grow (&obstack, dumpdir, dumpdir_length);
6232 if (this_is_output_file || !outbase_length)
6233 obstack_grow (&obstack, input_basename, basename_length);
6234 else
6235 obstack_grow (&obstack, outbase, outbase_length);
6236 if (compare_debug < 0)
6237 obstack_grow (&obstack, ".gk", 3);
6238 arg_going = 1;
6239 break;
6240
6241 case 'B':
6242 /* Don't use %B in the linker command. */
6243 gcc_assert (suffixed_basename_length);
6244 if (!this_is_output_file && dumpdir_length)
6245 obstack_grow (&obstack, dumpdir, dumpdir_length);
6246 if (this_is_output_file || !outbase_length)
6247 obstack_grow (&obstack, input_basename, basename_length);
6248 else
6249 obstack_grow (&obstack, outbase, outbase_length);
6250 if (compare_debug < 0)
6251 obstack_grow (&obstack, ".gk", 3);
6252 obstack_grow (&obstack, input_basename + basename_length,
6253 suffixed_basename_length - basename_length);
6254
6255 arg_going = 1;
6256 break;
6257
6258 case 'd':
6259 delete_this_arg = 2;
6260 break;
6261
6262 /* Dump out the directories specified with LIBRARY_PATH,
6263 followed by the absolute directories
6264 that we search for startfiles. */
6265 case 'D':
6266 {
6267 struct spec_path_info info;
6268
6269 info.option = "-L";
6270 info.append_len = 0;
6271 #ifdef RELATIVE_PREFIX_NOT_LINKDIR
6272 /* Used on systems which record the specified -L dirs
6273 and use them to search for dynamic linking.
6274 Relative directories always come from -B,
6275 and it is better not to use them for searching
6276 at run time. In particular, stage1 loses. */
6277 info.omit_relative = true;
6278 #else
6279 info.omit_relative = false;
6280 #endif
6281 info.separate_options = false;
6282 info.realpaths = false;
6283
6284 for_each_path (&startfile_prefixes, true, 0, spec_path, &info);
6285 }
6286 break;
6287
6288 case 'P':
6289 {
6290 struct spec_path_info info;
6291
6292 info.option = RUNPATH_OPTION;
6293 info.append_len = 0;
6294 info.omit_relative = false;
6295 info.separate_options = true;
6296 /* We want to embed the actual paths that have the libraries. */
6297 info.realpaths = true;
6298
6299 for_each_path (&startfile_prefixes, true, 0, spec_path, &info);
6300 }
6301 break;
6302
6303 case 'e':
6304 /* %efoo means report an error with `foo' as error message
6305 and don't execute any more commands for this file. */
6306 {
6307 const char *q = p;
6308 char *buf;
6309 while (*p != 0 && *p != '\n')
6310 p++;
6311 buf = (char *) alloca (p - q + 1);
6312 strncpy (buf, q, p - q);
6313 buf[p - q] = 0;
6314 error ("%s", _(buf));
6315 return -1;
6316 }
6317 break;
6318 case 'n':
6319 /* %nfoo means report a notice with `foo' on stderr. */
6320 {
6321 const char *q = p;
6322 char *buf;
6323 while (*p != 0 && *p != '\n')
6324 p++;
6325 buf = (char *) alloca (p - q + 1);
6326 strncpy (buf, q, p - q);
6327 buf[p - q] = 0;
6328 inform (UNKNOWN_LOCATION, "%s", _(buf));
6329 if (*p)
6330 p++;
6331 }
6332 break;
6333
6334 case 'j':
6335 {
6336 struct stat st;
6337
6338 /* If save_temps_flag is off, and the HOST_BIT_BUCKET is
6339 defined, and it is not a directory, and it is
6340 writable, use it. Otherwise, treat this like any
6341 other temporary file. */
6342
6343 if ((!save_temps_flag)
6344 && (stat (HOST_BIT_BUCKET, &st) == 0) && (!S_ISDIR (st.st_mode))
6345 && (access (HOST_BIT_BUCKET, W_OK) == 0))
6346 {
6347 obstack_grow (&obstack, HOST_BIT_BUCKET,
6348 strlen (HOST_BIT_BUCKET));
6349 delete_this_arg = 0;
6350 arg_going = 1;
6351 break;
6352 }
6353 }
6354 goto create_temp_file;
6355 case '|':
6356 if (use_pipes)
6357 {
6358 obstack_1grow (&obstack, '-');
6359 delete_this_arg = 0;
6360 arg_going = 1;
6361
6362 /* consume suffix */
6363 while (*p == '.' || ISALNUM ((unsigned char) *p))
6364 p++;
6365 if (p[0] == '%' && p[1] == 'O')
6366 p += 2;
6367
6368 break;
6369 }
6370 goto create_temp_file;
6371 case 'm':
6372 if (use_pipes)
6373 {
6374 /* consume suffix */
6375 while (*p == '.' || ISALNUM ((unsigned char) *p))
6376 p++;
6377 if (p[0] == '%' && p[1] == 'O')
6378 p += 2;
6379
6380 break;
6381 }
6382 goto create_temp_file;
6383 case 'g':
6384 case 'u':
6385 case 'U':
6386 create_temp_file:
6387 {
6388 struct temp_name *t;
6389 int suffix_length;
6390 const char *suffix = p;
6391 char *saved_suffix = NULL;
6392
6393 while (*p == '.' || ISALNUM ((unsigned char) *p))
6394 p++;
6395 suffix_length = p - suffix;
6396 if (p[0] == '%' && p[1] == 'O')
6397 {
6398 p += 2;
6399 /* We don't support extra suffix characters after %O. */
6400 if (*p == '.' || ISALNUM ((unsigned char) *p))
6401 fatal_error (input_location,
6402 "spec %qs has invalid %<%%0%c%>", spec, *p);
6403 if (suffix_length == 0)
6404 suffix = TARGET_OBJECT_SUFFIX;
6405 else
6406 {
6407 saved_suffix
6408 = XNEWVEC (char, suffix_length
6409 + strlen (TARGET_OBJECT_SUFFIX) + 1);
6410 strncpy (saved_suffix, suffix, suffix_length);
6411 strcpy (saved_suffix + suffix_length,
6412 TARGET_OBJECT_SUFFIX);
6413 }
6414 suffix_length += strlen (TARGET_OBJECT_SUFFIX);
6415 }
6416
6417 if (compare_debug < 0)
6418 {
6419 suffix = concat (".gk", suffix, NULL);
6420 suffix_length += 3;
6421 }
6422
6423 /* If -save-temps was specified, use that for the
6424 temp file. */
6425 if (save_temps_flag)
6426 {
6427 char *tmp;
6428 bool adjusted_suffix = false;
6429 if (suffix_length
6430 && !outbase_length && !basename_length
6431 && !dumpdir_trailing_dash_added)
6432 {
6433 adjusted_suffix = true;
6434 suffix++;
6435 suffix_length--;
6436 }
6437 temp_filename_length
6438 = dumpdir_length + suffix_length + 1;
6439 if (outbase_length)
6440 temp_filename_length += outbase_length;
6441 else
6442 temp_filename_length += basename_length;
6443 tmp = (char *) alloca (temp_filename_length);
6444 if (dumpdir_length)
6445 memcpy (tmp, dumpdir, dumpdir_length);
6446 if (outbase_length)
6447 memcpy (tmp + dumpdir_length, outbase,
6448 outbase_length);
6449 else if (basename_length)
6450 memcpy (tmp + dumpdir_length, input_basename,
6451 basename_length);
6452 memcpy (tmp + temp_filename_length - suffix_length - 1,
6453 suffix, suffix_length);
6454 if (adjusted_suffix)
6455 {
6456 adjusted_suffix = false;
6457 suffix--;
6458 suffix_length++;
6459 }
6460 tmp[temp_filename_length - 1] = '\0';
6461 temp_filename = tmp;
6462
6463 if (filename_cmp (temp_filename, gcc_input_filename) != 0)
6464 {
6465 #ifndef HOST_LACKS_INODE_NUMBERS
6466 struct stat st_temp;
6467
6468 /* Note, set_input() resets input_stat_set to 0. */
6469 if (input_stat_set == 0)
6470 {
6471 input_stat_set = stat (gcc_input_filename,
6472 &input_stat);
6473 if (input_stat_set >= 0)
6474 input_stat_set = 1;
6475 }
6476
6477 /* If we have the stat for the gcc_input_filename
6478 and we can do the stat for the temp_filename
6479 then the they could still refer to the same
6480 file if st_dev/st_ino's are the same. */
6481 if (input_stat_set != 1
6482 || stat (temp_filename, &st_temp) < 0
6483 || input_stat.st_dev != st_temp.st_dev
6484 || input_stat.st_ino != st_temp.st_ino)
6485 #else
6486 /* Just compare canonical pathnames. */
6487 char* input_realname = lrealpath (gcc_input_filename);
6488 char* temp_realname = lrealpath (temp_filename);
6489 bool files_differ = filename_cmp (input_realname, temp_realname);
6490 free (input_realname);
6491 free (temp_realname);
6492 if (files_differ)
6493 #endif
6494 {
6495 temp_filename
6496 = save_string (temp_filename,
6497 temp_filename_length - 1);
6498 obstack_grow (&obstack, temp_filename,
6499 temp_filename_length);
6500 arg_going = 1;
6501 delete_this_arg = 0;
6502 break;
6503 }
6504 }
6505 }
6506
6507 /* See if we already have an association of %g/%u/%U and
6508 suffix. */
6509 for (t = temp_names; t; t = t->next)
6510 if (t->length == suffix_length
6511 && strncmp (t->suffix, suffix, suffix_length) == 0
6512 && t->unique == (c == 'u' || c == 'U' || c == 'j'))
6513 break;
6514
6515 /* Make a new association if needed. %u and %j
6516 require one. */
6517 if (t == 0 || c == 'u' || c == 'j')
6518 {
6519 if (t == 0)
6520 {
6521 t = XNEW (struct temp_name);
6522 t->next = temp_names;
6523 temp_names = t;
6524 }
6525 t->length = suffix_length;
6526 if (saved_suffix)
6527 {
6528 t->suffix = saved_suffix;
6529 saved_suffix = NULL;
6530 }
6531 else
6532 t->suffix = save_string (suffix, suffix_length);
6533 t->unique = (c == 'u' || c == 'U' || c == 'j');
6534 temp_filename = make_temp_file (t->suffix);
6535 temp_filename_length = strlen (temp_filename);
6536 t->filename = temp_filename;
6537 t->filename_length = temp_filename_length;
6538 }
6539
6540 free (saved_suffix);
6541
6542 obstack_grow (&obstack, t->filename, t->filename_length);
6543 delete_this_arg = 1;
6544 }
6545 arg_going = 1;
6546 break;
6547
6548 case 'i':
6549 if (combine_inputs)
6550 {
6551 /* We are going to expand `%i' into `@FILE', where FILE
6552 is a newly-created temporary filename. The filenames
6553 that would usually be expanded in place of %o will be
6554 written to the temporary file. */
6555 if (at_file_supplied)
6556 open_at_file ();
6557
6558 for (i = 0; (int) i < n_infiles; i++)
6559 if (compile_input_file_p (&infiles[i]))
6560 {
6561 store_arg (infiles[i].name, 0, 0);
6562 infiles[i].compiled = true;
6563 }
6564
6565 if (at_file_supplied)
6566 close_at_file ();
6567 }
6568 else
6569 {
6570 obstack_grow (&obstack, gcc_input_filename,
6571 input_filename_length);
6572 arg_going = 1;
6573 }
6574 break;
6575
6576 case 'I':
6577 {
6578 struct spec_path_info info;
6579
6580 if (multilib_dir)
6581 {
6582 do_spec_1 ("-imultilib", 1, NULL);
6583 /* Make this a separate argument. */
6584 do_spec_1 (" ", 0, NULL);
6585 do_spec_1 (multilib_dir, 1, NULL);
6586 do_spec_1 (" ", 0, NULL);
6587 }
6588
6589 if (multiarch_dir)
6590 {
6591 do_spec_1 ("-imultiarch", 1, NULL);
6592 /* Make this a separate argument. */
6593 do_spec_1 (" ", 0, NULL);
6594 do_spec_1 (multiarch_dir, 1, NULL);
6595 do_spec_1 (" ", 0, NULL);
6596 }
6597
6598 if (gcc_exec_prefix)
6599 {
6600 do_spec_1 ("-iprefix", 1, NULL);
6601 /* Make this a separate argument. */
6602 do_spec_1 (" ", 0, NULL);
6603 do_spec_1 (gcc_exec_prefix, 1, NULL);
6604 do_spec_1 (" ", 0, NULL);
6605 }
6606
6607 if (target_system_root_changed ||
6608 (target_system_root && target_sysroot_hdrs_suffix))
6609 {
6610 do_spec_1 ("-isysroot", 1, NULL);
6611 /* Make this a separate argument. */
6612 do_spec_1 (" ", 0, NULL);
6613 do_spec_1 (target_system_root, 1, NULL);
6614 if (target_sysroot_hdrs_suffix)
6615 do_spec_1 (target_sysroot_hdrs_suffix, 1, NULL);
6616 do_spec_1 (" ", 0, NULL);
6617 }
6618
6619 info.option = "-isystem";
6620 info.append = "include";
6621 info.append_len = strlen (info.append);
6622 info.omit_relative = false;
6623 info.separate_options = true;
6624 info.realpaths = false;
6625
6626 for_each_path (&include_prefixes, false, info.append_len,
6627 spec_path, &info);
6628
6629 info.append = "include-fixed";
6630 if (*sysroot_hdrs_suffix_spec)
6631 info.append = concat (info.append, dir_separator_str,
6632 multilib_dir, NULL);
6633 else if (multiarch_dir)
6634 {
6635 /* For multiarch, search include-fixed/<multiarch-dir>
6636 before include-fixed. */
6637 info.append = concat (info.append, dir_separator_str,
6638 multiarch_dir, NULL);
6639 info.append_len = strlen (info.append);
6640 for_each_path (&include_prefixes, false, info.append_len,
6641 spec_path, &info);
6642
6643 info.append = "include-fixed";
6644 }
6645 info.append_len = strlen (info.append);
6646 for_each_path (&include_prefixes, false, info.append_len,
6647 spec_path, &info);
6648 }
6649 break;
6650
6651 case 'o':
6652 /* We are going to expand `%o' into `@FILE', where FILE
6653 is a newly-created temporary filename. The filenames
6654 that would usually be expanded in place of %o will be
6655 written to the temporary file. */
6656 if (at_file_supplied)
6657 open_at_file ();
6658
6659 for (i = 0; i < n_infiles + lang_specific_extra_outfiles; i++)
6660 if (outfiles[i])
6661 store_arg (outfiles[i], 0, 0);
6662
6663 if (at_file_supplied)
6664 close_at_file ();
6665 break;
6666
6667 case 'O':
6668 obstack_grow (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
6669 arg_going = 1;
6670 break;
6671
6672 case 's':
6673 this_is_library_file = 1;
6674 break;
6675
6676 case 'T':
6677 this_is_linker_script = 1;
6678 break;
6679
6680 case 'V':
6681 outfiles[input_file_number] = NULL;
6682 break;
6683
6684 case 'w':
6685 this_is_output_file = 1;
6686 break;
6687
6688 case 'W':
6689 {
6690 unsigned int cur_index = argbuf.length ();
6691 /* Handle the {...} following the %W. */
6692 if (*p != '{')
6693 fatal_error (input_location,
6694 "spec %qs has invalid %<%%W%c%>", spec, *p);
6695 p = handle_braces (p + 1);
6696 if (p == 0)
6697 return -1;
6698 end_going_arg ();
6699 /* If any args were output, mark the last one for deletion
6700 on failure. */
6701 if (argbuf.length () != cur_index)
6702 record_temp_file (argbuf.last (), 0, 1);
6703 break;
6704 }
6705
6706 case '@':
6707 /* Handle the {...} following the %@. */
6708 if (*p != '{')
6709 fatal_error (input_location,
6710 "spec %qs has invalid %<%%@%c%>", spec, *p);
6711 if (at_file_supplied)
6712 open_at_file ();
6713 p = handle_braces (p + 1);
6714 if (at_file_supplied)
6715 close_at_file ();
6716 if (p == 0)
6717 return -1;
6718 break;
6719
6720 /* %x{OPTION} records OPTION for %X to output. */
6721 case 'x':
6722 {
6723 const char *p1 = p;
6724 char *string;
6725
6726 /* Skip past the option value and make a copy. */
6727 if (*p != '{')
6728 fatal_error (input_location,
6729 "spec %qs has invalid %<%%x%c%>", spec, *p);
6730 while (*p++ != '}')
6731 ;
6732 string = save_string (p1 + 1, p - p1 - 2);
6733
6734 /* See if we already recorded this option. */
6735 for (const char *opt : linker_options)
6736 if (! strcmp (string, opt))
6737 {
6738 free (string);
6739 return 0;
6740 }
6741
6742 /* This option is new; add it. */
6743 add_linker_option (string, strlen (string));
6744 free (string);
6745 }
6746 break;
6747
6748 /* Dump out the options accumulated previously using %x. */
6749 case 'X':
6750 do_specs_vec (linker_options);
6751 break;
6752
6753 /* Dump out the options accumulated previously using -Wa,. */
6754 case 'Y':
6755 do_specs_vec (assembler_options);
6756 break;
6757
6758 /* Dump out the options accumulated previously using -Wp,. */
6759 case 'Z':
6760 do_specs_vec (preprocessor_options);
6761 break;
6762
6763 /* Here are digits and numbers that just process
6764 a certain constant string as a spec. */
6765
6766 case '1':
6767 value = do_spec_1 (cc1_spec, 0, NULL);
6768 if (value != 0)
6769 return value;
6770 break;
6771
6772 case '2':
6773 value = do_spec_1 (cc1plus_spec, 0, NULL);
6774 if (value != 0)
6775 return value;
6776 break;
6777
6778 case 'a':
6779 value = do_spec_1 (asm_spec, 0, NULL);
6780 if (value != 0)
6781 return value;
6782 break;
6783
6784 case 'A':
6785 value = do_spec_1 (asm_final_spec, 0, NULL);
6786 if (value != 0)
6787 return value;
6788 break;
6789
6790 case 'C':
6791 {
6792 const char *const spec
6793 = (input_file_compiler->cpp_spec
6794 ? input_file_compiler->cpp_spec
6795 : cpp_spec);
6796 value = do_spec_1 (spec, 0, NULL);
6797 if (value != 0)
6798 return value;
6799 }
6800 break;
6801
6802 case 'E':
6803 value = do_spec_1 (endfile_spec, 0, NULL);
6804 if (value != 0)
6805 return value;
6806 break;
6807
6808 case 'l':
6809 value = do_spec_1 (link_spec, 0, NULL);
6810 if (value != 0)
6811 return value;
6812 break;
6813
6814 case 'L':
6815 value = do_spec_1 (lib_spec, 0, NULL);
6816 if (value != 0)
6817 return value;
6818 break;
6819
6820 case 'M':
6821 if (multilib_os_dir == NULL)
6822 obstack_1grow (&obstack, '.');
6823 else
6824 obstack_grow (&obstack, multilib_os_dir,
6825 strlen (multilib_os_dir));
6826 break;
6827
6828 case 'G':
6829 value = do_spec_1 (libgcc_spec, 0, NULL);
6830 if (value != 0)
6831 return value;
6832 break;
6833
6834 case 'R':
6835 /* We assume there is a directory
6836 separator at the end of this string. */
6837 if (target_system_root)
6838 {
6839 obstack_grow (&obstack, target_system_root,
6840 strlen (target_system_root));
6841 if (target_sysroot_suffix)
6842 obstack_grow (&obstack, target_sysroot_suffix,
6843 strlen (target_sysroot_suffix));
6844 }
6845 break;
6846
6847 case 'S':
6848 value = do_spec_1 (startfile_spec, 0, NULL);
6849 if (value != 0)
6850 return value;
6851 break;
6852
6853 /* Here we define characters other than letters and digits. */
6854
6855 case '{':
6856 p = handle_braces (p);
6857 if (p == 0)
6858 return -1;
6859 break;
6860
6861 case ':':
6862 p = handle_spec_function (p, NULL, soft_matched_part);
6863 if (p == 0)
6864 return -1;
6865 break;
6866
6867 case '%':
6868 obstack_1grow (&obstack, '%');
6869 break;
6870
6871 case '.':
6872 {
6873 unsigned len = 0;
6874
6875 while (p[len] && p[len] != ' ' && p[len] != '%')
6876 len++;
6877 suffix_subst = save_string (p - 1, len + 1);
6878 p += len;
6879 }
6880 break;
6881
6882 /* Henceforth ignore the option(s) matching the pattern
6883 after the %<. */
6884 case '<':
6885 case '>':
6886 {
6887 unsigned len = 0;
6888 int have_wildcard = 0;
6889 int i;
6890 int switch_option;
6891
6892 if (c == '>')
6893 switch_option = SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC;
6894 else
6895 switch_option = SWITCH_IGNORE;
6896
6897 while (p[len] && p[len] != ' ' && p[len] != '\t')
6898 len++;
6899
6900 if (p[len-1] == '*')
6901 have_wildcard = 1;
6902
6903 for (i = 0; i < n_switches; i++)
6904 if (!strncmp (switches[i].part1, p, len - have_wildcard)
6905 && (have_wildcard || switches[i].part1[len] == '\0'))
6906 {
6907 switches[i].live_cond |= switch_option;
6908 /* User switch be validated from validate_all_switches.
6909 when the definition is seen from the spec file.
6910 If not defined anywhere, will be rejected. */
6911 if (switches[i].known)
6912 switches[i].validated = true;
6913 }
6914
6915 p += len;
6916 }
6917 break;
6918
6919 case '*':
6920 if (soft_matched_part)
6921 {
6922 if (soft_matched_part[0])
6923 do_spec_1 (soft_matched_part, 1, NULL);
6924 /* Only insert a space after the substitution if it is at the
6925 end of the current sequence. So if:
6926
6927 "%{foo=*:bar%*}%{foo=*:one%*two}"
6928
6929 matches -foo=hello then it will produce:
6930
6931 barhello onehellotwo
6932 */
6933 if (*p == 0 || *p == '}')
6934 do_spec_1 (" ", 0, NULL);
6935 }
6936 else
6937 /* Catch the case where a spec string contains something like
6938 '%{foo:%*}'. i.e. there is no * in the pattern on the left
6939 hand side of the :. */
6940 error ("spec failure: %<%%*%> has not been initialized by pattern match");
6941 break;
6942
6943 /* Process a string found as the value of a spec given by name.
6944 This feature allows individual machine descriptions
6945 to add and use their own specs. */
6946 case '(':
6947 {
6948 const char *name = p;
6949 struct spec_list *sl;
6950 int len;
6951
6952 /* The string after the S/P is the name of a spec that is to be
6953 processed. */
6954 while (*p && *p != ')')
6955 p++;
6956
6957 /* See if it's in the list. */
6958 for (len = p - name, sl = specs; sl; sl = sl->next)
6959 if (sl->name_len == len && !strncmp (sl->name, name, len))
6960 {
6961 name = *(sl->ptr_spec);
6962 #ifdef DEBUG_SPECS
6963 fnotice (stderr, "Processing spec (%s), which is '%s'\n",
6964 sl->name, name);
6965 #endif
6966 break;
6967 }
6968
6969 if (sl)
6970 {
6971 value = do_spec_1 (name, 0, NULL);
6972 if (value != 0)
6973 return value;
6974 }
6975
6976 /* Discard the closing paren. */
6977 if (*p)
6978 p++;
6979 }
6980 break;
6981
6982 case '"':
6983 /* End a previous argument, if there is one, then issue an
6984 empty argument. */
6985 end_going_arg ();
6986 arg_going = 1;
6987 end_going_arg ();
6988 break;
6989
6990 default:
6991 error ("spec failure: unrecognized spec option %qc", c);
6992 break;
6993 }
6994 break;
6995
6996 case '\\':
6997 /* Backslash: treat next character as ordinary. */
6998 c = *p++;
6999
7000 /* When adding more cases that previously matched default, make
7001 sure to adjust quote_spec_char_p as well. */
7002
7003 /* Fall through. */
7004 default:
7005 /* Ordinary character: put it into the current argument. */
7006 obstack_1grow (&obstack, c);
7007 arg_going = 1;
7008 }
7009
7010 /* End of string. If we are processing a spec function, we need to
7011 end any pending argument. */
7012 if (processing_spec_function)
7013 end_going_arg ();
7014
7015 return 0;
7016 }
7017
7018 /* Look up a spec function. */
7019
7020 static const struct spec_function *
7021 lookup_spec_function (const char *name)
7022 {
7023 const struct spec_function *sf;
7024
7025 for (sf = static_spec_functions; sf->name != NULL; sf++)
7026 if (strcmp (sf->name, name) == 0)
7027 return sf;
7028
7029 return NULL;
7030 }
7031
7032 /* Evaluate a spec function. */
7033
7034 static const char *
7035 eval_spec_function (const char *func, const char *args,
7036 const char *soft_matched_part)
7037 {
7038 const struct spec_function *sf;
7039 const char *funcval;
7040
7041 /* Saved spec processing context. */
7042 vec<const_char_p> save_argbuf;
7043
7044 int save_arg_going;
7045 int save_delete_this_arg;
7046 int save_this_is_output_file;
7047 int save_this_is_library_file;
7048 int save_input_from_pipe;
7049 int save_this_is_linker_script;
7050 const char *save_suffix_subst;
7051
7052 int save_growing_size;
7053 void *save_growing_value = NULL;
7054
7055 sf = lookup_spec_function (func);
7056 if (sf == NULL)
7057 fatal_error (input_location, "unknown spec function %qs", func);
7058
7059 /* Push the spec processing context. */
7060 save_argbuf = argbuf;
7061
7062 save_arg_going = arg_going;
7063 save_delete_this_arg = delete_this_arg;
7064 save_this_is_output_file = this_is_output_file;
7065 save_this_is_library_file = this_is_library_file;
7066 save_this_is_linker_script = this_is_linker_script;
7067 save_input_from_pipe = input_from_pipe;
7068 save_suffix_subst = suffix_subst;
7069
7070 /* If we have some object growing now, finalize it so the args and function
7071 eval proceed from a cleared context. This is needed to prevent the first
7072 constructed arg from mistakenly including the growing value. We'll push
7073 this value back on the obstack once the function evaluation is done, to
7074 restore a consistent processing context for our caller. This is fine as
7075 the address of growing objects isn't guaranteed to remain stable until
7076 they are finalized, and we expect this situation to be rare enough for
7077 the extra copy not to be an issue. */
7078 save_growing_size = obstack_object_size (&obstack);
7079 if (save_growing_size > 0)
7080 save_growing_value = obstack_finish (&obstack);
7081
7082 /* Create a new spec processing context, and build the function
7083 arguments. */
7084
7085 alloc_args ();
7086 if (do_spec_2 (args, soft_matched_part) < 0)
7087 fatal_error (input_location, "error in arguments to spec function %qs",
7088 func);
7089
7090 /* argbuf_index is an index for the next argument to be inserted, and
7091 so contains the count of the args already inserted. */
7092
7093 funcval = (*sf->func) (argbuf.length (),
7094 argbuf.address ());
7095
7096 /* Pop the spec processing context. */
7097 argbuf.release ();
7098 argbuf = save_argbuf;
7099
7100 arg_going = save_arg_going;
7101 delete_this_arg = save_delete_this_arg;
7102 this_is_output_file = save_this_is_output_file;
7103 this_is_library_file = save_this_is_library_file;
7104 this_is_linker_script = save_this_is_linker_script;
7105 input_from_pipe = save_input_from_pipe;
7106 suffix_subst = save_suffix_subst;
7107
7108 if (save_growing_size > 0)
7109 obstack_grow (&obstack, save_growing_value, save_growing_size);
7110
7111 return funcval;
7112 }
7113
7114 /* Handle a spec function call of the form:
7115
7116 %:function(args)
7117
7118 ARGS is processed as a spec in a separate context and split into an
7119 argument vector in the normal fashion. The function returns a string
7120 containing a spec which we then process in the caller's context, or
7121 NULL if no processing is required.
7122
7123 If RETVAL_NONNULL is not NULL, then store a bool whether function
7124 returned non-NULL.
7125
7126 SOFT_MATCHED_PART holds the current value of a matched * pattern, which
7127 may be re-expanded with a %* as part of the function arguments. */
7128
7129 static const char *
7130 handle_spec_function (const char *p, bool *retval_nonnull,
7131 const char *soft_matched_part)
7132 {
7133 char *func, *args;
7134 const char *endp, *funcval;
7135 int count;
7136
7137 processing_spec_function++;
7138
7139 /* Get the function name. */
7140 for (endp = p; *endp != '\0'; endp++)
7141 {
7142 if (*endp == '(') /* ) */
7143 break;
7144 /* Only allow [A-Za-z0-9], -, and _ in function names. */
7145 if (!ISALNUM (*endp) && !(*endp == '-' || *endp == '_'))
7146 fatal_error (input_location, "malformed spec function name");
7147 }
7148 if (*endp != '(') /* ) */
7149 fatal_error (input_location, "no arguments for spec function");
7150 func = save_string (p, endp - p);
7151 p = ++endp;
7152
7153 /* Get the arguments. */
7154 for (count = 0; *endp != '\0'; endp++)
7155 {
7156 /* ( */
7157 if (*endp == ')')
7158 {
7159 if (count == 0)
7160 break;
7161 count--;
7162 }
7163 else if (*endp == '(') /* ) */
7164 count++;
7165 }
7166 /* ( */
7167 if (*endp != ')')
7168 fatal_error (input_location, "malformed spec function arguments");
7169 args = save_string (p, endp - p);
7170 p = ++endp;
7171
7172 /* p now points to just past the end of the spec function expression. */
7173
7174 funcval = eval_spec_function (func, args, soft_matched_part);
7175 if (funcval != NULL && do_spec_1 (funcval, 0, NULL) < 0)
7176 p = NULL;
7177 if (retval_nonnull)
7178 *retval_nonnull = funcval != NULL;
7179
7180 free (func);
7181 free (args);
7182
7183 processing_spec_function--;
7184
7185 return p;
7186 }
7187
7188 /* Inline subroutine of handle_braces. Returns true if the current
7189 input suffix matches the atom bracketed by ATOM and END_ATOM. */
7190 static inline bool
7191 input_suffix_matches (const char *atom, const char *end_atom)
7192 {
7193 return (input_suffix
7194 && !strncmp (input_suffix, atom, end_atom - atom)
7195 && input_suffix[end_atom - atom] == '\0');
7196 }
7197
7198 /* Subroutine of handle_braces. Returns true if the current
7199 input file's spec name matches the atom bracketed by ATOM and END_ATOM. */
7200 static bool
7201 input_spec_matches (const char *atom, const char *end_atom)
7202 {
7203 return (input_file_compiler
7204 && input_file_compiler->suffix
7205 && input_file_compiler->suffix[0] != '\0'
7206 && !strncmp (input_file_compiler->suffix + 1, atom,
7207 end_atom - atom)
7208 && input_file_compiler->suffix[end_atom - atom + 1] == '\0');
7209 }
7210
7211 /* Subroutine of handle_braces. Returns true if a switch
7212 matching the atom bracketed by ATOM and END_ATOM appeared on the
7213 command line. */
7214 static bool
7215 switch_matches (const char *atom, const char *end_atom, int starred)
7216 {
7217 int i;
7218 int len = end_atom - atom;
7219 int plen = starred ? len : -1;
7220
7221 for (i = 0; i < n_switches; i++)
7222 if (!strncmp (switches[i].part1, atom, len)
7223 && (starred || switches[i].part1[len] == '\0')
7224 && check_live_switch (i, plen))
7225 return true;
7226
7227 /* Check if a switch with separated form matching the atom.
7228 We check -D and -U switches. */
7229 else if (switches[i].args != 0)
7230 {
7231 if ((*switches[i].part1 == 'D' || *switches[i].part1 == 'U')
7232 && *switches[i].part1 == atom[0])
7233 {
7234 if (!strncmp (switches[i].args[0], &atom[1], len - 1)
7235 && (starred || (switches[i].part1[1] == '\0'
7236 && switches[i].args[0][len - 1] == '\0'))
7237 && check_live_switch (i, (starred ? 1 : -1)))
7238 return true;
7239 }
7240 }
7241
7242 return false;
7243 }
7244
7245 /* Inline subroutine of handle_braces. Mark all of the switches which
7246 match ATOM (extends to END_ATOM; STARRED indicates whether there
7247 was a star after the atom) for later processing. */
7248 static inline void
7249 mark_matching_switches (const char *atom, const char *end_atom, int starred)
7250 {
7251 int i;
7252 int len = end_atom - atom;
7253 int plen = starred ? len : -1;
7254
7255 for (i = 0; i < n_switches; i++)
7256 if (!strncmp (switches[i].part1, atom, len)
7257 && (starred || switches[i].part1[len] == '\0')
7258 && check_live_switch (i, plen))
7259 switches[i].ordering = 1;
7260 }
7261
7262 /* Inline subroutine of handle_braces. Process all the currently
7263 marked switches through give_switch, and clear the marks. */
7264 static inline void
7265 process_marked_switches (void)
7266 {
7267 int i;
7268
7269 for (i = 0; i < n_switches; i++)
7270 if (switches[i].ordering == 1)
7271 {
7272 switches[i].ordering = 0;
7273 give_switch (i, 0);
7274 }
7275 }
7276
7277 /* Handle a %{ ... } construct. P points just inside the leading {.
7278 Returns a pointer one past the end of the brace block, or 0
7279 if we call do_spec_1 and that returns -1. */
7280
7281 static const char *
7282 handle_braces (const char *p)
7283 {
7284 const char *atom, *end_atom;
7285 const char *d_atom = NULL, *d_end_atom = NULL;
7286 char *esc_buf = NULL, *d_esc_buf = NULL;
7287 int esc;
7288 const char *orig = p;
7289
7290 bool a_is_suffix;
7291 bool a_is_spectype;
7292 bool a_is_starred;
7293 bool a_is_negated;
7294 bool a_matched;
7295
7296 bool a_must_be_last = false;
7297 bool ordered_set = false;
7298 bool disjunct_set = false;
7299 bool disj_matched = false;
7300 bool disj_starred = true;
7301 bool n_way_choice = false;
7302 bool n_way_matched = false;
7303
7304 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
7305
7306 do
7307 {
7308 if (a_must_be_last)
7309 goto invalid;
7310
7311 /* Scan one "atom" (S in the description above of %{}, possibly
7312 with '!', '.', '@', ',', or '*' modifiers). */
7313 a_matched = false;
7314 a_is_suffix = false;
7315 a_is_starred = false;
7316 a_is_negated = false;
7317 a_is_spectype = false;
7318
7319 SKIP_WHITE ();
7320 if (*p == '!')
7321 p++, a_is_negated = true;
7322
7323 SKIP_WHITE ();
7324 if (*p == '%' && p[1] == ':')
7325 {
7326 atom = NULL;
7327 end_atom = NULL;
7328 p = handle_spec_function (p + 2, &a_matched, NULL);
7329 }
7330 else
7331 {
7332 if (*p == '.')
7333 p++, a_is_suffix = true;
7334 else if (*p == ',')
7335 p++, a_is_spectype = true;
7336
7337 atom = p;
7338 esc = 0;
7339 while (ISIDNUM (*p) || *p == '-' || *p == '+' || *p == '='
7340 || *p == ',' || *p == '.' || *p == '@' || *p == '\\')
7341 {
7342 if (*p == '\\')
7343 {
7344 p++;
7345 if (!*p)
7346 fatal_error (input_location,
7347 "braced spec %qs ends in escape", orig);
7348 esc++;
7349 }
7350 p++;
7351 }
7352 end_atom = p;
7353
7354 if (esc)
7355 {
7356 const char *ap;
7357 char *ep;
7358
7359 if (esc_buf && esc_buf != d_esc_buf)
7360 free (esc_buf);
7361 esc_buf = NULL;
7362 ep = esc_buf = (char *) xmalloc (end_atom - atom - esc + 1);
7363 for (ap = atom; ap != end_atom; ap++, ep++)
7364 {
7365 if (*ap == '\\')
7366 ap++;
7367 *ep = *ap;
7368 }
7369 *ep = '\0';
7370 atom = esc_buf;
7371 end_atom = ep;
7372 }
7373
7374 if (*p == '*')
7375 p++, a_is_starred = 1;
7376 }
7377
7378 SKIP_WHITE ();
7379 switch (*p)
7380 {
7381 case '&': case '}':
7382 /* Substitute the switch(es) indicated by the current atom. */
7383 ordered_set = true;
7384 if (disjunct_set || n_way_choice || a_is_negated || a_is_suffix
7385 || a_is_spectype || atom == end_atom)
7386 goto invalid;
7387
7388 mark_matching_switches (atom, end_atom, a_is_starred);
7389
7390 if (*p == '}')
7391 process_marked_switches ();
7392 break;
7393
7394 case '|': case ':':
7395 /* Substitute some text if the current atom appears as a switch
7396 or suffix. */
7397 disjunct_set = true;
7398 if (ordered_set)
7399 goto invalid;
7400
7401 if (atom && atom == end_atom)
7402 {
7403 if (!n_way_choice || disj_matched || *p == '|'
7404 || a_is_negated || a_is_suffix || a_is_spectype
7405 || a_is_starred)
7406 goto invalid;
7407
7408 /* An empty term may appear as the last choice of an
7409 N-way choice set; it means "otherwise". */
7410 a_must_be_last = true;
7411 disj_matched = !n_way_matched;
7412 disj_starred = false;
7413 }
7414 else
7415 {
7416 if ((a_is_suffix || a_is_spectype) && a_is_starred)
7417 goto invalid;
7418
7419 if (!a_is_starred)
7420 disj_starred = false;
7421
7422 /* Don't bother testing this atom if we already have a
7423 match. */
7424 if (!disj_matched && !n_way_matched)
7425 {
7426 if (atom == NULL)
7427 /* a_matched is already set by handle_spec_function. */;
7428 else if (a_is_suffix)
7429 a_matched = input_suffix_matches (atom, end_atom);
7430 else if (a_is_spectype)
7431 a_matched = input_spec_matches (atom, end_atom);
7432 else
7433 a_matched = switch_matches (atom, end_atom, a_is_starred);
7434
7435 if (a_matched != a_is_negated)
7436 {
7437 disj_matched = true;
7438 d_atom = atom;
7439 d_end_atom = end_atom;
7440 d_esc_buf = esc_buf;
7441 }
7442 }
7443 }
7444
7445 if (*p == ':')
7446 {
7447 /* Found the body, that is, the text to substitute if the
7448 current disjunction matches. */
7449 p = process_brace_body (p + 1, d_atom, d_end_atom, disj_starred,
7450 disj_matched && !n_way_matched);
7451 if (p == 0)
7452 goto done;
7453
7454 /* If we have an N-way choice, reset state for the next
7455 disjunction. */
7456 if (*p == ';')
7457 {
7458 n_way_choice = true;
7459 n_way_matched |= disj_matched;
7460 disj_matched = false;
7461 disj_starred = true;
7462 d_atom = d_end_atom = NULL;
7463 }
7464 }
7465 break;
7466
7467 default:
7468 goto invalid;
7469 }
7470 }
7471 while (*p++ != '}');
7472
7473 done:
7474 if (d_esc_buf && d_esc_buf != esc_buf)
7475 free (d_esc_buf);
7476 if (esc_buf)
7477 free (esc_buf);
7478
7479 return p;
7480
7481 invalid:
7482 fatal_error (input_location, "braced spec %qs is invalid at %qc", orig, *p);
7483
7484 #undef SKIP_WHITE
7485 }
7486
7487 /* Subroutine of handle_braces. Scan and process a brace substitution body
7488 (X in the description of %{} syntax). P points one past the colon;
7489 ATOM and END_ATOM bracket the first atom which was found to be true
7490 (present) in the current disjunction; STARRED indicates whether all
7491 the atoms in the current disjunction were starred (for syntax validation);
7492 MATCHED indicates whether the disjunction matched or not, and therefore
7493 whether or not the body is to be processed through do_spec_1 or just
7494 skipped. Returns a pointer to the closing } or ;, or 0 if do_spec_1
7495 returns -1. */
7496
7497 static const char *
7498 process_brace_body (const char *p, const char *atom, const char *end_atom,
7499 int starred, int matched)
7500 {
7501 const char *body, *end_body;
7502 unsigned int nesting_level;
7503 bool have_subst = false;
7504
7505 /* Locate the closing } or ;, honoring nested braces.
7506 Trim trailing whitespace. */
7507 body = p;
7508 nesting_level = 1;
7509 for (;;)
7510 {
7511 if (*p == '{')
7512 nesting_level++;
7513 else if (*p == '}')
7514 {
7515 if (!--nesting_level)
7516 break;
7517 }
7518 else if (*p == ';' && nesting_level == 1)
7519 break;
7520 else if (*p == '%' && p[1] == '*' && nesting_level == 1)
7521 have_subst = true;
7522 else if (*p == '\0')
7523 goto invalid;
7524 p++;
7525 }
7526
7527 end_body = p;
7528 while (end_body[-1] == ' ' || end_body[-1] == '\t')
7529 end_body--;
7530
7531 if (have_subst && !starred)
7532 goto invalid;
7533
7534 if (matched)
7535 {
7536 /* Copy the substitution body to permanent storage and execute it.
7537 If have_subst is false, this is a simple matter of running the
7538 body through do_spec_1... */
7539 char *string = save_string (body, end_body - body);
7540 if (!have_subst)
7541 {
7542 if (do_spec_1 (string, 0, NULL) < 0)
7543 {
7544 free (string);
7545 return 0;
7546 }
7547 }
7548 else
7549 {
7550 /* ... but if have_subst is true, we have to process the
7551 body once for each matching switch, with %* set to the
7552 variant part of the switch. */
7553 unsigned int hard_match_len = end_atom - atom;
7554 int i;
7555
7556 for (i = 0; i < n_switches; i++)
7557 if (!strncmp (switches[i].part1, atom, hard_match_len)
7558 && check_live_switch (i, hard_match_len))
7559 {
7560 if (do_spec_1 (string, 0,
7561 &switches[i].part1[hard_match_len]) < 0)
7562 {
7563 free (string);
7564 return 0;
7565 }
7566 /* Pass any arguments this switch has. */
7567 give_switch (i, 1);
7568 suffix_subst = NULL;
7569 }
7570 }
7571 free (string);
7572 }
7573
7574 return p;
7575
7576 invalid:
7577 fatal_error (input_location, "braced spec body %qs is invalid", body);
7578 }
7579
7580 /* Return 0 iff switch number SWITCHNUM is obsoleted by a later switch
7581 on the command line. PREFIX_LENGTH is the length of XXX in an {XXX*}
7582 spec, or -1 if either exact match or %* is used.
7583
7584 A -O switch is obsoleted by a later -O switch. A -f, -g, -m, or -W switch
7585 whose value does not begin with "no-" is obsoleted by the same value
7586 with the "no-", similarly for a switch with the "no-" prefix. */
7587
7588 static int
7589 check_live_switch (int switchnum, int prefix_length)
7590 {
7591 const char *name = switches[switchnum].part1;
7592 int i;
7593
7594 /* If we already processed this switch and determined if it was
7595 live or not, return our past determination. */
7596 if (switches[switchnum].live_cond != 0)
7597 return ((switches[switchnum].live_cond & SWITCH_LIVE) != 0
7598 && (switches[switchnum].live_cond & SWITCH_FALSE) == 0
7599 && (switches[switchnum].live_cond & SWITCH_IGNORE_PERMANENTLY)
7600 == 0);
7601
7602 /* In the common case of {<at-most-one-letter>*}, a negating
7603 switch would always match, so ignore that case. We will just
7604 send the conflicting switches to the compiler phase. */
7605 if (prefix_length >= 0 && prefix_length <= 1)
7606 return 1;
7607
7608 /* Now search for duplicate in a manner that depends on the name. */
7609 switch (*name)
7610 {
7611 case 'O':
7612 for (i = switchnum + 1; i < n_switches; i++)
7613 if (switches[i].part1[0] == 'O')
7614 {
7615 switches[switchnum].validated = true;
7616 switches[switchnum].live_cond = SWITCH_FALSE;
7617 return 0;
7618 }
7619 break;
7620
7621 case 'W': case 'f': case 'm': case 'g':
7622 if (startswith (name + 1, "no-"))
7623 {
7624 /* We have Xno-YYY, search for XYYY. */
7625 for (i = switchnum + 1; i < n_switches; i++)
7626 if (switches[i].part1[0] == name[0]
7627 && ! strcmp (&switches[i].part1[1], &name[4]))
7628 {
7629 /* --specs are validated with the validate_switches mechanism. */
7630 if (switches[switchnum].known)
7631 switches[switchnum].validated = true;
7632 switches[switchnum].live_cond = SWITCH_FALSE;
7633 return 0;
7634 }
7635 }
7636 else
7637 {
7638 /* We have XYYY, search for Xno-YYY. */
7639 for (i = switchnum + 1; i < n_switches; i++)
7640 if (switches[i].part1[0] == name[0]
7641 && switches[i].part1[1] == 'n'
7642 && switches[i].part1[2] == 'o'
7643 && switches[i].part1[3] == '-'
7644 && !strcmp (&switches[i].part1[4], &name[1]))
7645 {
7646 /* --specs are validated with the validate_switches mechanism. */
7647 if (switches[switchnum].known)
7648 switches[switchnum].validated = true;
7649 switches[switchnum].live_cond = SWITCH_FALSE;
7650 return 0;
7651 }
7652 }
7653 break;
7654 }
7655
7656 /* Otherwise the switch is live. */
7657 switches[switchnum].live_cond |= SWITCH_LIVE;
7658 return 1;
7659 }
7660
7661 /* Pass a switch to the current accumulating command
7662 in the same form that we received it.
7663 SWITCHNUM identifies the switch; it is an index into
7664 the vector of switches gcc received, which is `switches'.
7665 This cannot fail since it never finishes a command line.
7666
7667 If OMIT_FIRST_WORD is nonzero, then we omit .part1 of the argument. */
7668
7669 static void
7670 give_switch (int switchnum, int omit_first_word)
7671 {
7672 if ((switches[switchnum].live_cond & SWITCH_IGNORE) != 0)
7673 return;
7674
7675 if (!omit_first_word)
7676 {
7677 do_spec_1 ("-", 0, NULL);
7678 do_spec_1 (switches[switchnum].part1, 1, NULL);
7679 }
7680
7681 if (switches[switchnum].args != 0)
7682 {
7683 const char **p;
7684 for (p = switches[switchnum].args; *p; p++)
7685 {
7686 const char *arg = *p;
7687
7688 do_spec_1 (" ", 0, NULL);
7689 if (suffix_subst)
7690 {
7691 unsigned length = strlen (arg);
7692 int dot = 0;
7693
7694 while (length-- && !IS_DIR_SEPARATOR (arg[length]))
7695 if (arg[length] == '.')
7696 {
7697 (CONST_CAST (char *, arg))[length] = 0;
7698 dot = 1;
7699 break;
7700 }
7701 do_spec_1 (arg, 1, NULL);
7702 if (dot)
7703 (CONST_CAST (char *, arg))[length] = '.';
7704 do_spec_1 (suffix_subst, 1, NULL);
7705 }
7706 else
7707 do_spec_1 (arg, 1, NULL);
7708 }
7709 }
7710
7711 do_spec_1 (" ", 0, NULL);
7712 switches[switchnum].validated = true;
7713 }
7714
7715 /* Print GCC configuration (e.g. version, thread model, target,
7716 configuration_arguments) to a given FILE. */
7717
7718 static void
7719 print_configuration (FILE *file)
7720 {
7721 int n;
7722 const char *thrmod;
7723
7724 fnotice (file, "Target: %s\n", spec_machine);
7725 fnotice (file, "Configured with: %s\n", configuration_arguments);
7726
7727 #ifdef THREAD_MODEL_SPEC
7728 /* We could have defined THREAD_MODEL_SPEC to "%*" by default,
7729 but there's no point in doing all this processing just to get
7730 thread_model back. */
7731 obstack_init (&obstack);
7732 do_spec_1 (THREAD_MODEL_SPEC, 0, thread_model);
7733 obstack_1grow (&obstack, '\0');
7734 thrmod = XOBFINISH (&obstack, const char *);
7735 #else
7736 thrmod = thread_model;
7737 #endif
7738
7739 fnotice (file, "Thread model: %s\n", thrmod);
7740 fnotice (file, "Supported LTO compression algorithms: zlib");
7741 #ifdef HAVE_ZSTD_H
7742 fnotice (file, " zstd");
7743 #endif
7744 fnotice (file, "\n");
7745
7746 /* compiler_version is truncated at the first space when initialized
7747 from version string, so truncate version_string at the first space
7748 before comparing. */
7749 for (n = 0; version_string[n]; n++)
7750 if (version_string[n] == ' ')
7751 break;
7752
7753 if (! strncmp (version_string, compiler_version, n)
7754 && compiler_version[n] == 0)
7755 fnotice (file, "gcc version %s %s\n", version_string,
7756 pkgversion_string);
7757 else
7758 fnotice (file, "gcc driver version %s %sexecuting gcc version %s\n",
7759 version_string, pkgversion_string, compiler_version);
7760
7761 }
7762
7763 #define RETRY_ICE_ATTEMPTS 3
7764
7765 /* Returns true if FILE1 and FILE2 contain equivalent data, 0 otherwise.
7766 If lines start with 0x followed by 1-16 lowercase hexadecimal digits
7767 followed by a space, ignore anything before that space. These are
7768 typically function addresses from libbacktrace and those can differ
7769 due to ASLR. */
7770
7771 static bool
7772 files_equal_p (char *file1, char *file2)
7773 {
7774 FILE *f1 = fopen (file1, "rb");
7775 FILE *f2 = fopen (file2, "rb");
7776 char line1[256], line2[256];
7777
7778 bool line_start = true;
7779 while (fgets (line1, sizeof (line1), f1))
7780 {
7781 if (!fgets (line2, sizeof (line2), f2))
7782 goto error;
7783 char *p1 = line1, *p2 = line2;
7784 if (line_start
7785 && line1[0] == '0'
7786 && line1[1] == 'x'
7787 && line2[0] == '0'
7788 && line2[1] == 'x')
7789 {
7790 int i, j;
7791 for (i = 0; i < 16; ++i)
7792 if (!ISXDIGIT (line1[2 + i]) || ISUPPER (line1[2 + i]))
7793 break;
7794 for (j = 0; j < 16; ++j)
7795 if (!ISXDIGIT (line2[2 + j]) || ISUPPER (line2[2 + j]))
7796 break;
7797 if (i && line1[2 + i] == ' ' && j && line2[2 + j] == ' ')
7798 {
7799 p1 = line1 + i + 3;
7800 p2 = line2 + j + 3;
7801 }
7802 }
7803 if (strcmp (p1, p2) != 0)
7804 goto error;
7805 line_start = strchr (line1, '\n') != NULL;
7806 }
7807 if (fgets (line2, sizeof (line2), f2))
7808 goto error;
7809
7810 fclose (f1);
7811 fclose (f2);
7812 return 1;
7813
7814 error:
7815 fclose (f1);
7816 fclose (f2);
7817 return 0;
7818 }
7819
7820 /* Check that compiler's output doesn't differ across runs.
7821 TEMP_STDOUT_FILES and TEMP_STDERR_FILES are arrays of files, containing
7822 stdout and stderr for each compiler run. Return true if all of
7823 TEMP_STDOUT_FILES and TEMP_STDERR_FILES are equivalent. */
7824
7825 static bool
7826 check_repro (char **temp_stdout_files, char **temp_stderr_files)
7827 {
7828 int i;
7829 for (i = 0; i < RETRY_ICE_ATTEMPTS - 2; ++i)
7830 {
7831 if (!files_equal_p (temp_stdout_files[i], temp_stdout_files[i + 1])
7832 || !files_equal_p (temp_stderr_files[i], temp_stderr_files[i + 1]))
7833 {
7834 fnotice (stderr, "The bug is not reproducible, so it is"
7835 " likely a hardware or OS problem.\n");
7836 break;
7837 }
7838 }
7839 return i == RETRY_ICE_ATTEMPTS - 2;
7840 }
7841
7842 enum attempt_status {
7843 ATTEMPT_STATUS_FAIL_TO_RUN,
7844 ATTEMPT_STATUS_SUCCESS,
7845 ATTEMPT_STATUS_ICE
7846 };
7847
7848
7849 /* Run compiler with arguments NEW_ARGV to reproduce the ICE, storing stdout
7850 to OUT_TEMP and stderr to ERR_TEMP. If APPEND is TRUE, append to OUT_TEMP
7851 and ERR_TEMP instead of truncating. If EMIT_SYSTEM_INFO is TRUE, also write
7852 GCC configuration into to ERR_TEMP. Return ATTEMPT_STATUS_FAIL_TO_RUN if
7853 compiler failed to run, ATTEMPT_STATUS_ICE if compiled ICE-ed and
7854 ATTEMPT_STATUS_SUCCESS otherwise. */
7855
7856 static enum attempt_status
7857 run_attempt (const char **new_argv, const char *out_temp,
7858 const char *err_temp, int emit_system_info, int append)
7859 {
7860
7861 if (emit_system_info)
7862 {
7863 FILE *file_out = fopen (err_temp, "a");
7864 print_configuration (file_out);
7865 fputs ("\n", file_out);
7866 fclose (file_out);
7867 }
7868
7869 int exit_status;
7870 const char *errmsg;
7871 struct pex_obj *pex;
7872 int err;
7873 int pex_flags = PEX_USE_PIPES | PEX_LAST;
7874 enum attempt_status status = ATTEMPT_STATUS_FAIL_TO_RUN;
7875
7876 if (append)
7877 pex_flags |= PEX_STDOUT_APPEND | PEX_STDERR_APPEND;
7878
7879 pex = pex_init (PEX_USE_PIPES, new_argv[0], NULL);
7880 if (!pex)
7881 fatal_error (input_location, "%<pex_init%> failed: %m");
7882
7883 errmsg = pex_run (pex, pex_flags, new_argv[0],
7884 CONST_CAST2 (char *const *, const char **, &new_argv[1]),
7885 out_temp, err_temp, &err);
7886 if (errmsg != NULL)
7887 {
7888 errno = err;
7889 fatal_error (input_location,
7890 err ? G_ ("cannot execute %qs: %s: %m")
7891 : G_ ("cannot execute %qs: %s"),
7892 new_argv[0], errmsg);
7893 }
7894
7895 if (!pex_get_status (pex, 1, &exit_status))
7896 goto out;
7897
7898 switch (WEXITSTATUS (exit_status))
7899 {
7900 case ICE_EXIT_CODE:
7901 status = ATTEMPT_STATUS_ICE;
7902 break;
7903
7904 case SUCCESS_EXIT_CODE:
7905 status = ATTEMPT_STATUS_SUCCESS;
7906 break;
7907
7908 default:
7909 ;
7910 }
7911
7912 out:
7913 pex_free (pex);
7914 return status;
7915 }
7916
7917 /* This routine reads lines from IN file, adds C++ style comments
7918 at the begining of each line and writes result into OUT. */
7919
7920 static void
7921 insert_comments (const char *file_in, const char *file_out)
7922 {
7923 FILE *in = fopen (file_in, "rb");
7924 FILE *out = fopen (file_out, "wb");
7925 char line[256];
7926
7927 bool add_comment = true;
7928 while (fgets (line, sizeof (line), in))
7929 {
7930 if (add_comment)
7931 fputs ("// ", out);
7932 fputs (line, out);
7933 add_comment = strchr (line, '\n') != NULL;
7934 }
7935
7936 fclose (in);
7937 fclose (out);
7938 }
7939
7940 /* This routine adds preprocessed source code into the given ERR_FILE.
7941 To do this, it adds "-E" to NEW_ARGV and execute RUN_ATTEMPT routine to
7942 add information in report file. RUN_ATTEMPT should return
7943 ATTEMPT_STATUS_SUCCESS, in other case we cannot generate the report. */
7944
7945 static void
7946 do_report_bug (const char **new_argv, const int nargs,
7947 char **out_file, char **err_file)
7948 {
7949 int i, status;
7950 int fd = open (*out_file, O_RDWR | O_APPEND);
7951 if (fd < 0)
7952 return;
7953 write (fd, "\n//", 3);
7954 for (i = 0; i < nargs; i++)
7955 {
7956 write (fd, " ", 1);
7957 write (fd, new_argv[i], strlen (new_argv[i]));
7958 }
7959 write (fd, "\n\n", 2);
7960 close (fd);
7961 new_argv[nargs] = "-E";
7962 new_argv[nargs + 1] = NULL;
7963
7964 status = run_attempt (new_argv, *out_file, *err_file, 0, 1);
7965
7966 if (status == ATTEMPT_STATUS_SUCCESS)
7967 {
7968 fnotice (stderr, "Preprocessed source stored into %s file,"
7969 " please attach this to your bugreport.\n", *out_file);
7970 /* Make sure it is not deleted. */
7971 free (*out_file);
7972 *out_file = NULL;
7973 }
7974 }
7975
7976 /* Try to reproduce ICE. If bug is reproducible, generate report .err file
7977 containing GCC configuration, backtrace, compiler's command line options
7978 and preprocessed source code. */
7979
7980 static void
7981 try_generate_repro (const char **argv)
7982 {
7983 int i, nargs, out_arg = -1, quiet = 0, attempt;
7984 const char **new_argv;
7985 char *temp_files[RETRY_ICE_ATTEMPTS * 2];
7986 char **temp_stdout_files = &temp_files[0];
7987 char **temp_stderr_files = &temp_files[RETRY_ICE_ATTEMPTS];
7988
7989 if (gcc_input_filename == NULL || ! strcmp (gcc_input_filename, "-"))
7990 return;
7991
7992 for (nargs = 0; argv[nargs] != NULL; ++nargs)
7993 /* Only retry compiler ICEs, not preprocessor ones. */
7994 if (! strcmp (argv[nargs], "-E"))
7995 return;
7996 else if (argv[nargs][0] == '-' && argv[nargs][1] == 'o')
7997 {
7998 if (out_arg == -1)
7999 out_arg = nargs;
8000 else
8001 return;
8002 }
8003 /* If the compiler is going to output any time information,
8004 it might varry between invocations. */
8005 else if (! strcmp (argv[nargs], "-quiet"))
8006 quiet = 1;
8007 else if (! strcmp (argv[nargs], "-ftime-report"))
8008 return;
8009
8010 if (out_arg == -1 || !quiet)
8011 return;
8012
8013 memset (temp_files, '\0', sizeof (temp_files));
8014 new_argv = XALLOCAVEC (const char *, nargs + 4);
8015 memcpy (new_argv, argv, (nargs + 1) * sizeof (const char *));
8016 new_argv[nargs++] = "-frandom-seed=0";
8017 new_argv[nargs++] = "-fdump-noaddr";
8018 new_argv[nargs] = NULL;
8019 if (new_argv[out_arg][2] == '\0')
8020 new_argv[out_arg + 1] = "-";
8021 else
8022 new_argv[out_arg] = "-o-";
8023
8024 #ifdef HOST_HAS_PERSONALITY_ADDR_NO_RANDOMIZE
8025 personality (personality (0xffffffffU) | ADDR_NO_RANDOMIZE);
8026 #endif
8027
8028 int status;
8029 for (attempt = 0; attempt < RETRY_ICE_ATTEMPTS; ++attempt)
8030 {
8031 int emit_system_info = 0;
8032 int append = 0;
8033 temp_stdout_files[attempt] = make_temp_file (".out");
8034 temp_stderr_files[attempt] = make_temp_file (".err");
8035
8036 if (attempt == RETRY_ICE_ATTEMPTS - 1)
8037 {
8038 append = 1;
8039 emit_system_info = 1;
8040 }
8041
8042 status = run_attempt (new_argv, temp_stdout_files[attempt],
8043 temp_stderr_files[attempt], emit_system_info,
8044 append);
8045
8046 if (status != ATTEMPT_STATUS_ICE)
8047 {
8048 fnotice (stderr, "The bug is not reproducible, so it is"
8049 " likely a hardware or OS problem.\n");
8050 goto out;
8051 }
8052 }
8053
8054 if (!check_repro (temp_stdout_files, temp_stderr_files))
8055 goto out;
8056
8057 {
8058 /* Insert commented out backtrace into report file. */
8059 char **stderr_commented = &temp_stdout_files[RETRY_ICE_ATTEMPTS - 1];
8060 insert_comments (temp_stderr_files[RETRY_ICE_ATTEMPTS - 1],
8061 *stderr_commented);
8062
8063 /* In final attempt we append compiler options and preprocesssed code to last
8064 generated .out file with configuration and backtrace. */
8065 char **err = &temp_stderr_files[RETRY_ICE_ATTEMPTS - 1];
8066 do_report_bug (new_argv, nargs, stderr_commented, err);
8067 }
8068
8069 out:
8070 for (i = 0; i < RETRY_ICE_ATTEMPTS * 2; i++)
8071 if (temp_files[i])
8072 {
8073 unlink (temp_stdout_files[i]);
8074 free (temp_stdout_files[i]);
8075 }
8076 }
8077
8078 /* Search for a file named NAME trying various prefixes including the
8079 user's -B prefix and some standard ones.
8080 Return the absolute file name found. If nothing is found, return NAME. */
8081
8082 static const char *
8083 find_file (const char *name)
8084 {
8085 char *newname = find_a_file (&startfile_prefixes, name, R_OK, true);
8086 return newname ? newname : name;
8087 }
8088
8089 /* Determine whether a directory exists. */
8090
8091 static int
8092 is_directory (const char *path1)
8093 {
8094 int len1;
8095 char *path;
8096 char *cp;
8097 struct stat st;
8098
8099 /* Ensure the string ends with "/.". The resulting path will be a
8100 directory even if the given path is a symbolic link. */
8101 len1 = strlen (path1);
8102 path = (char *) alloca (3 + len1);
8103 memcpy (path, path1, len1);
8104 cp = path + len1;
8105 if (!IS_DIR_SEPARATOR (cp[-1]))
8106 *cp++ = DIR_SEPARATOR;
8107 *cp++ = '.';
8108 *cp = '\0';
8109
8110 return (stat (path, &st) >= 0 && S_ISDIR (st.st_mode));
8111 }
8112
8113 /* Set up the various global variables to indicate that we're processing
8114 the input file named FILENAME. */
8115
8116 void
8117 set_input (const char *filename)
8118 {
8119 const char *p;
8120
8121 gcc_input_filename = filename;
8122 input_filename_length = strlen (gcc_input_filename);
8123 input_basename = lbasename (gcc_input_filename);
8124
8125 /* Find a suffix starting with the last period,
8126 and set basename_length to exclude that suffix. */
8127 basename_length = strlen (input_basename);
8128 suffixed_basename_length = basename_length;
8129 p = input_basename + basename_length;
8130 while (p != input_basename && *p != '.')
8131 --p;
8132 if (*p == '.' && p != input_basename)
8133 {
8134 basename_length = p - input_basename;
8135 input_suffix = p + 1;
8136 }
8137 else
8138 input_suffix = "";
8139
8140 /* If a spec for 'g', 'u', or 'U' is seen with -save-temps then
8141 we will need to do a stat on the gcc_input_filename. The
8142 INPUT_STAT_SET signals that the stat is needed. */
8143 input_stat_set = 0;
8144 }
8145
8146 /* On fatal signals, delete all the temporary files. */
8147
8148 static void
8149 fatal_signal (int signum)
8150 {
8151 signal (signum, SIG_DFL);
8152 delete_failure_queue ();
8153 delete_temp_files ();
8154 /* Get the same signal again, this time not handled,
8155 so its normal effect occurs. */
8156 kill (getpid (), signum);
8157 }
8158
8159 /* Compare the contents of the two files named CMPFILE[0] and
8160 CMPFILE[1]. Return zero if they're identical, nonzero
8161 otherwise. */
8162
8163 static int
8164 compare_files (char *cmpfile[])
8165 {
8166 int ret = 0;
8167 FILE *temp[2] = { NULL, NULL };
8168 int i;
8169
8170 #if HAVE_MMAP_FILE
8171 {
8172 size_t length[2];
8173 void *map[2] = { NULL, NULL };
8174
8175 for (i = 0; i < 2; i++)
8176 {
8177 struct stat st;
8178
8179 if (stat (cmpfile[i], &st) < 0 || !S_ISREG (st.st_mode))
8180 {
8181 error ("%s: could not determine length of compare-debug file %s",
8182 gcc_input_filename, cmpfile[i]);
8183 ret = 1;
8184 break;
8185 }
8186
8187 length[i] = st.st_size;
8188 }
8189
8190 if (!ret && length[0] != length[1])
8191 {
8192 error ("%s: %<-fcompare-debug%> failure (length)", gcc_input_filename);
8193 ret = 1;
8194 }
8195
8196 if (!ret)
8197 for (i = 0; i < 2; i++)
8198 {
8199 int fd = open (cmpfile[i], O_RDONLY);
8200 if (fd < 0)
8201 {
8202 error ("%s: could not open compare-debug file %s",
8203 gcc_input_filename, cmpfile[i]);
8204 ret = 1;
8205 break;
8206 }
8207
8208 map[i] = mmap (NULL, length[i], PROT_READ, MAP_PRIVATE, fd, 0);
8209 close (fd);
8210
8211 if (map[i] == (void *) MAP_FAILED)
8212 {
8213 ret = -1;
8214 break;
8215 }
8216 }
8217
8218 if (!ret)
8219 {
8220 if (memcmp (map[0], map[1], length[0]) != 0)
8221 {
8222 error ("%s: %<-fcompare-debug%> failure", gcc_input_filename);
8223 ret = 1;
8224 }
8225 }
8226
8227 for (i = 0; i < 2; i++)
8228 if (map[i])
8229 munmap ((caddr_t) map[i], length[i]);
8230
8231 if (ret >= 0)
8232 return ret;
8233
8234 ret = 0;
8235 }
8236 #endif
8237
8238 for (i = 0; i < 2; i++)
8239 {
8240 temp[i] = fopen (cmpfile[i], "r");
8241 if (!temp[i])
8242 {
8243 error ("%s: could not open compare-debug file %s",
8244 gcc_input_filename, cmpfile[i]);
8245 ret = 1;
8246 break;
8247 }
8248 }
8249
8250 if (!ret && temp[0] && temp[1])
8251 for (;;)
8252 {
8253 int c0, c1;
8254 c0 = fgetc (temp[0]);
8255 c1 = fgetc (temp[1]);
8256
8257 if (c0 != c1)
8258 {
8259 error ("%s: %<-fcompare-debug%> failure",
8260 gcc_input_filename);
8261 ret = 1;
8262 break;
8263 }
8264
8265 if (c0 == EOF)
8266 break;
8267 }
8268
8269 for (i = 1; i >= 0; i--)
8270 {
8271 if (temp[i])
8272 fclose (temp[i]);
8273 }
8274
8275 return ret;
8276 }
8277
8278 driver::driver (bool can_finalize, bool debug) :
8279 explicit_link_files (NULL),
8280 decoded_options (NULL)
8281 {
8282 env.init (can_finalize, debug);
8283 }
8284
8285 driver::~driver ()
8286 {
8287 XDELETEVEC (explicit_link_files);
8288 XDELETEVEC (decoded_options);
8289 }
8290
8291 /* driver::main is implemented as a series of driver:: method calls. */
8292
8293 int
8294 driver::main (int argc, char **argv)
8295 {
8296 bool early_exit;
8297
8298 set_progname (argv[0]);
8299 expand_at_files (&argc, &argv);
8300 decode_argv (argc, const_cast <const char **> (argv));
8301 global_initializations ();
8302 build_multilib_strings ();
8303 set_up_specs ();
8304 putenv_COLLECT_AS_OPTIONS (assembler_options);
8305 putenv_COLLECT_GCC (argv[0]);
8306 maybe_putenv_COLLECT_LTO_WRAPPER ();
8307 maybe_putenv_OFFLOAD_TARGETS ();
8308 handle_unrecognized_options ();
8309
8310 if (completion)
8311 {
8312 m_option_proposer.suggest_completion (completion);
8313 return 0;
8314 }
8315
8316 if (!maybe_print_and_exit ())
8317 return 0;
8318
8319 early_exit = prepare_infiles ();
8320 if (early_exit)
8321 return get_exit_code ();
8322
8323 do_spec_on_infiles ();
8324 maybe_run_linker (argv[0]);
8325 final_actions ();
8326 return get_exit_code ();
8327 }
8328
8329 /* Locate the final component of argv[0] after any leading path, and set
8330 the program name accordingly. */
8331
8332 void
8333 driver::set_progname (const char *argv0) const
8334 {
8335 const char *p = argv0 + strlen (argv0);
8336 while (p != argv0 && !IS_DIR_SEPARATOR (p[-1]))
8337 --p;
8338 progname = p;
8339
8340 xmalloc_set_program_name (progname);
8341 }
8342
8343 /* Expand any @ files within the command-line args,
8344 setting at_file_supplied if any were expanded. */
8345
8346 void
8347 driver::expand_at_files (int *argc, char ***argv) const
8348 {
8349 char **old_argv = *argv;
8350
8351 expandargv (argc, argv);
8352
8353 /* Determine if any expansions were made. */
8354 if (*argv != old_argv)
8355 at_file_supplied = true;
8356 }
8357
8358 /* Decode the command-line arguments from argc/argv into the
8359 decoded_options array. */
8360
8361 void
8362 driver::decode_argv (int argc, const char **argv)
8363 {
8364 init_opts_obstack ();
8365 init_options_struct (&global_options, &global_options_set);
8366
8367 decode_cmdline_options_to_array (argc, argv,
8368 CL_DRIVER,
8369 &decoded_options, &decoded_options_count);
8370 }
8371
8372 /* Perform various initializations and setup. */
8373
8374 void
8375 driver::global_initializations ()
8376 {
8377 /* Unlock the stdio streams. */
8378 unlock_std_streams ();
8379
8380 gcc_init_libintl ();
8381
8382 diagnostic_initialize (global_dc, 0);
8383 diagnostic_color_init (global_dc);
8384 diagnostic_urls_init (global_dc);
8385 global_dc->push_owned_urlifier (make_gcc_urlifier (0));
8386
8387 #ifdef GCC_DRIVER_HOST_INITIALIZATION
8388 /* Perform host dependent initialization when needed. */
8389 GCC_DRIVER_HOST_INITIALIZATION;
8390 #endif
8391
8392 if (atexit (delete_temp_files) != 0)
8393 fatal_error (input_location, "atexit failed");
8394
8395 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
8396 signal (SIGINT, fatal_signal);
8397 #ifdef SIGHUP
8398 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
8399 signal (SIGHUP, fatal_signal);
8400 #endif
8401 if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
8402 signal (SIGTERM, fatal_signal);
8403 #ifdef SIGPIPE
8404 if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
8405 signal (SIGPIPE, fatal_signal);
8406 #endif
8407 #ifdef SIGCHLD
8408 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
8409 receive the signal. A different setting is inheritable */
8410 signal (SIGCHLD, SIG_DFL);
8411 #endif
8412
8413 /* Parsing and gimplification sometimes need quite large stack.
8414 Increase stack size limits if possible. */
8415 stack_limit_increase (64 * 1024 * 1024);
8416
8417 /* Allocate the argument vector. */
8418 alloc_args ();
8419
8420 obstack_init (&obstack);
8421 }
8422
8423 /* Build multilib_select, et. al from the separate lines that make up each
8424 multilib selection. */
8425
8426 void
8427 driver::build_multilib_strings () const
8428 {
8429 {
8430 const char *p;
8431 const char *const *q = multilib_raw;
8432 int need_space;
8433
8434 obstack_init (&multilib_obstack);
8435 while ((p = *q++) != (char *) 0)
8436 obstack_grow (&multilib_obstack, p, strlen (p));
8437
8438 obstack_1grow (&multilib_obstack, 0);
8439 multilib_select = XOBFINISH (&multilib_obstack, const char *);
8440
8441 q = multilib_matches_raw;
8442 while ((p = *q++) != (char *) 0)
8443 obstack_grow (&multilib_obstack, p, strlen (p));
8444
8445 obstack_1grow (&multilib_obstack, 0);
8446 multilib_matches = XOBFINISH (&multilib_obstack, const char *);
8447
8448 q = multilib_exclusions_raw;
8449 while ((p = *q++) != (char *) 0)
8450 obstack_grow (&multilib_obstack, p, strlen (p));
8451
8452 obstack_1grow (&multilib_obstack, 0);
8453 multilib_exclusions = XOBFINISH (&multilib_obstack, const char *);
8454
8455 q = multilib_reuse_raw;
8456 while ((p = *q++) != (char *) 0)
8457 obstack_grow (&multilib_obstack, p, strlen (p));
8458
8459 obstack_1grow (&multilib_obstack, 0);
8460 multilib_reuse = XOBFINISH (&multilib_obstack, const char *);
8461
8462 need_space = false;
8463 for (size_t i = 0; i < ARRAY_SIZE (multilib_defaults_raw); i++)
8464 {
8465 if (need_space)
8466 obstack_1grow (&multilib_obstack, ' ');
8467 obstack_grow (&multilib_obstack,
8468 multilib_defaults_raw[i],
8469 strlen (multilib_defaults_raw[i]));
8470 need_space = true;
8471 }
8472
8473 obstack_1grow (&multilib_obstack, 0);
8474 multilib_defaults = XOBFINISH (&multilib_obstack, const char *);
8475 }
8476 }
8477
8478 /* Set up the spec-handling machinery. */
8479
8480 void
8481 driver::set_up_specs () const
8482 {
8483 const char *spec_machine_suffix;
8484 char *specs_file;
8485 size_t i;
8486
8487 #ifdef INIT_ENVIRONMENT
8488 /* Set up any other necessary machine specific environment variables. */
8489 xputenv (INIT_ENVIRONMENT);
8490 #endif
8491
8492 /* Make a table of what switches there are (switches, n_switches).
8493 Make a table of specified input files (infiles, n_infiles).
8494 Decode switches that are handled locally. */
8495
8496 process_command (decoded_options_count, decoded_options);
8497
8498 /* Initialize the vector of specs to just the default.
8499 This means one element containing 0s, as a terminator. */
8500
8501 compilers = XNEWVAR (struct compiler, sizeof default_compilers);
8502 memcpy (compilers, default_compilers, sizeof default_compilers);
8503 n_compilers = n_default_compilers;
8504
8505 /* Read specs from a file if there is one. */
8506
8507 machine_suffix = concat (spec_host_machine, dir_separator_str, spec_version,
8508 accel_dir_suffix, dir_separator_str, NULL);
8509 just_machine_suffix = concat (spec_machine, dir_separator_str, NULL);
8510
8511 specs_file = find_a_file (&startfile_prefixes, "specs", R_OK, true);
8512 /* Read the specs file unless it is a default one. */
8513 if (specs_file != 0 && strcmp (specs_file, "specs"))
8514 read_specs (specs_file, true, false);
8515 else
8516 init_spec ();
8517
8518 #ifdef ACCEL_COMPILER
8519 spec_machine_suffix = machine_suffix;
8520 #else
8521 spec_machine_suffix = just_machine_suffix;
8522 #endif
8523
8524 /* We need to check standard_exec_prefix/spec_machine_suffix/specs
8525 for any override of as, ld and libraries. */
8526 specs_file = (char *) alloca (strlen (standard_exec_prefix)
8527 + strlen (spec_machine_suffix) + sizeof ("specs"));
8528 strcpy (specs_file, standard_exec_prefix);
8529 strcat (specs_file, spec_machine_suffix);
8530 strcat (specs_file, "specs");
8531 if (access (specs_file, R_OK) == 0)
8532 read_specs (specs_file, true, false);
8533
8534 /* Process any configure-time defaults specified for the command line
8535 options, via OPTION_DEFAULT_SPECS. */
8536 for (i = 0; i < ARRAY_SIZE (option_default_specs); i++)
8537 do_option_spec (option_default_specs[i].name,
8538 option_default_specs[i].spec);
8539
8540 /* Process DRIVER_SELF_SPECS, adding any new options to the end
8541 of the command line. */
8542
8543 for (i = 0; i < ARRAY_SIZE (driver_self_specs); i++)
8544 do_self_spec (driver_self_specs[i]);
8545
8546 /* If not cross-compiling, look for executables in the standard
8547 places. */
8548 if (*cross_compile == '0')
8549 {
8550 if (*md_exec_prefix)
8551 {
8552 add_prefix (&exec_prefixes, md_exec_prefix, "GCC",
8553 PREFIX_PRIORITY_LAST, 0, 0);
8554 }
8555 }
8556
8557 /* Process sysroot_suffix_spec. */
8558 if (*sysroot_suffix_spec != 0
8559 && !no_sysroot_suffix
8560 && do_spec_2 (sysroot_suffix_spec, NULL) == 0)
8561 {
8562 if (argbuf.length () > 1)
8563 error ("spec failure: more than one argument to "
8564 "%<SYSROOT_SUFFIX_SPEC%>");
8565 else if (argbuf.length () == 1)
8566 target_sysroot_suffix = xstrdup (argbuf.last ());
8567 }
8568
8569 #ifdef HAVE_LD_SYSROOT
8570 /* Pass the --sysroot option to the linker, if it supports that. If
8571 there is a sysroot_suffix_spec, it has already been processed by
8572 this point, so target_system_root really is the system root we
8573 should be using. */
8574 if (target_system_root)
8575 {
8576 obstack_grow (&obstack, "%(sysroot_spec) ", strlen ("%(sysroot_spec) "));
8577 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
8578 set_spec ("link", XOBFINISH (&obstack, const char *), false);
8579 }
8580 #endif
8581
8582 /* Process sysroot_hdrs_suffix_spec. */
8583 if (*sysroot_hdrs_suffix_spec != 0
8584 && !no_sysroot_suffix
8585 && do_spec_2 (sysroot_hdrs_suffix_spec, NULL) == 0)
8586 {
8587 if (argbuf.length () > 1)
8588 error ("spec failure: more than one argument "
8589 "to %<SYSROOT_HEADERS_SUFFIX_SPEC%>");
8590 else if (argbuf.length () == 1)
8591 target_sysroot_hdrs_suffix = xstrdup (argbuf.last ());
8592 }
8593
8594 /* Look for startfiles in the standard places. */
8595 if (*startfile_prefix_spec != 0
8596 && do_spec_2 (startfile_prefix_spec, NULL) == 0
8597 && do_spec_1 (" ", 0, NULL) == 0)
8598 {
8599 for (const char *arg : argbuf)
8600 add_sysrooted_prefix (&startfile_prefixes, arg, "BINUTILS",
8601 PREFIX_PRIORITY_LAST, 0, 1);
8602 }
8603 /* We should eventually get rid of all these and stick to
8604 startfile_prefix_spec exclusively. */
8605 else if (*cross_compile == '0' || target_system_root)
8606 {
8607 if (*md_startfile_prefix)
8608 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix,
8609 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
8610
8611 if (*md_startfile_prefix_1)
8612 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix_1,
8613 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
8614
8615 /* If standard_startfile_prefix is relative, base it on
8616 standard_exec_prefix. This lets us move the installed tree
8617 as a unit. If GCC_EXEC_PREFIX is defined, base
8618 standard_startfile_prefix on that as well.
8619
8620 If the prefix is relative, only search it for native compilers;
8621 otherwise we will search a directory containing host libraries. */
8622 if (IS_ABSOLUTE_PATH (standard_startfile_prefix))
8623 add_sysrooted_prefix (&startfile_prefixes,
8624 standard_startfile_prefix, "BINUTILS",
8625 PREFIX_PRIORITY_LAST, 0, 1);
8626 else if (*cross_compile == '0')
8627 {
8628 add_prefix (&startfile_prefixes,
8629 concat (gcc_exec_prefix
8630 ? gcc_exec_prefix : standard_exec_prefix,
8631 machine_suffix,
8632 standard_startfile_prefix, NULL),
8633 NULL, PREFIX_PRIORITY_LAST, 0, 1);
8634 }
8635
8636 /* Sysrooted prefixes are relocated because target_system_root is
8637 also relocated by gcc_exec_prefix. */
8638 if (*standard_startfile_prefix_1)
8639 add_sysrooted_prefix (&startfile_prefixes,
8640 standard_startfile_prefix_1, "BINUTILS",
8641 PREFIX_PRIORITY_LAST, 0, 1);
8642 if (*standard_startfile_prefix_2)
8643 add_sysrooted_prefix (&startfile_prefixes,
8644 standard_startfile_prefix_2, "BINUTILS",
8645 PREFIX_PRIORITY_LAST, 0, 1);
8646 }
8647
8648 /* Process any user specified specs in the order given on the command
8649 line. */
8650 for (struct user_specs *uptr = user_specs_head; uptr; uptr = uptr->next)
8651 {
8652 char *filename = find_a_file (&startfile_prefixes, uptr->filename,
8653 R_OK, true);
8654 read_specs (filename ? filename : uptr->filename, false, true);
8655 }
8656
8657 /* Process any user self specs. */
8658 {
8659 struct spec_list *sl;
8660 for (sl = specs; sl; sl = sl->next)
8661 if (sl->name_len == sizeof "self_spec" - 1
8662 && !strcmp (sl->name, "self_spec"))
8663 do_self_spec (*sl->ptr_spec);
8664 }
8665
8666 if (compare_debug)
8667 {
8668 enum save_temps save;
8669
8670 if (!compare_debug_second)
8671 {
8672 n_switches_debug_check[1] = n_switches;
8673 n_switches_alloc_debug_check[1] = n_switches_alloc;
8674 switches_debug_check[1] = XDUPVEC (struct switchstr, switches,
8675 n_switches_alloc);
8676
8677 do_self_spec ("%:compare-debug-self-opt()");
8678 n_switches_debug_check[0] = n_switches;
8679 n_switches_alloc_debug_check[0] = n_switches_alloc;
8680 switches_debug_check[0] = switches;
8681
8682 n_switches = n_switches_debug_check[1];
8683 n_switches_alloc = n_switches_alloc_debug_check[1];
8684 switches = switches_debug_check[1];
8685 }
8686
8687 /* Avoid crash when computing %j in this early. */
8688 save = save_temps_flag;
8689 save_temps_flag = SAVE_TEMPS_NONE;
8690
8691 compare_debug = -compare_debug;
8692 do_self_spec ("%:compare-debug-self-opt()");
8693
8694 save_temps_flag = save;
8695
8696 if (!compare_debug_second)
8697 {
8698 n_switches_debug_check[1] = n_switches;
8699 n_switches_alloc_debug_check[1] = n_switches_alloc;
8700 switches_debug_check[1] = switches;
8701 compare_debug = -compare_debug;
8702 n_switches = n_switches_debug_check[0];
8703 n_switches_alloc = n_switches_debug_check[0];
8704 switches = switches_debug_check[0];
8705 }
8706 }
8707
8708
8709 /* If we have a GCC_EXEC_PREFIX envvar, modify it for cpp's sake. */
8710 if (gcc_exec_prefix)
8711 gcc_exec_prefix = concat (gcc_exec_prefix, spec_host_machine,
8712 dir_separator_str, spec_version,
8713 accel_dir_suffix, dir_separator_str, NULL);
8714
8715 /* Now we have the specs.
8716 Set the `valid' bits for switches that match anything in any spec. */
8717
8718 validate_all_switches ();
8719
8720 /* Now that we have the switches and the specs, set
8721 the subdirectory based on the options. */
8722 set_multilib_dir ();
8723 }
8724
8725 /* Set up to remember the pathname of gcc and any options
8726 needed for collect. We use argv[0] instead of progname because
8727 we need the complete pathname. */
8728
8729 void
8730 driver::putenv_COLLECT_GCC (const char *argv0) const
8731 {
8732 obstack_init (&collect_obstack);
8733 obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);
8734 obstack_grow (&collect_obstack, argv0, strlen (argv0) + 1);
8735 xputenv (XOBFINISH (&collect_obstack, char *));
8736 }
8737
8738 /* Set up to remember the pathname of the lto wrapper. */
8739
8740 void
8741 driver::maybe_putenv_COLLECT_LTO_WRAPPER () const
8742 {
8743 char *lto_wrapper_file;
8744
8745 if (have_c)
8746 lto_wrapper_file = NULL;
8747 else
8748 lto_wrapper_file = find_a_program ("lto-wrapper");
8749 if (lto_wrapper_file)
8750 {
8751 lto_wrapper_file = convert_white_space (lto_wrapper_file);
8752 set_static_spec_owned (&lto_wrapper_spec, lto_wrapper_file);
8753 obstack_init (&collect_obstack);
8754 obstack_grow (&collect_obstack, "COLLECT_LTO_WRAPPER=",
8755 sizeof ("COLLECT_LTO_WRAPPER=") - 1);
8756 obstack_grow (&collect_obstack, lto_wrapper_spec,
8757 strlen (lto_wrapper_spec) + 1);
8758 xputenv (XOBFINISH (&collect_obstack, char *));
8759 }
8760
8761 }
8762
8763 /* Set up to remember the names of offload targets. */
8764
8765 void
8766 driver::maybe_putenv_OFFLOAD_TARGETS () const
8767 {
8768 if (offload_targets && offload_targets[0] != '\0')
8769 {
8770 obstack_grow (&collect_obstack, "OFFLOAD_TARGET_NAMES=",
8771 sizeof ("OFFLOAD_TARGET_NAMES=") - 1);
8772 obstack_grow (&collect_obstack, offload_targets,
8773 strlen (offload_targets) + 1);
8774 xputenv (XOBFINISH (&collect_obstack, char *));
8775 #if OFFLOAD_DEFAULTED
8776 if (offload_targets_default)
8777 xputenv ("OFFLOAD_TARGET_DEFAULT=1");
8778 #endif
8779 }
8780
8781 free (offload_targets);
8782 offload_targets = NULL;
8783 }
8784
8785 /* Reject switches that no pass was interested in. */
8786
8787 void
8788 driver::handle_unrecognized_options ()
8789 {
8790 for (size_t i = 0; (int) i < n_switches; i++)
8791 if (! switches[i].validated)
8792 {
8793 const char *hint = m_option_proposer.suggest_option (switches[i].part1);
8794 if (hint)
8795 error ("unrecognized command-line option %<-%s%>;"
8796 " did you mean %<-%s%>?",
8797 switches[i].part1, hint);
8798 else
8799 error ("unrecognized command-line option %<-%s%>",
8800 switches[i].part1);
8801 }
8802 }
8803
8804 /* Handle the various -print-* options, returning 0 if the driver
8805 should exit, or nonzero if the driver should continue. */
8806
8807 int
8808 driver::maybe_print_and_exit () const
8809 {
8810 if (print_search_dirs)
8811 {
8812 printf (_("install: %s%s\n"),
8813 gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
8814 gcc_exec_prefix ? "" : machine_suffix);
8815 printf (_("programs: %s\n"),
8816 build_search_list (&exec_prefixes, "", false, false));
8817 printf (_("libraries: %s\n"),
8818 build_search_list (&startfile_prefixes, "", false, true));
8819 return (0);
8820 }
8821
8822 if (print_file_name)
8823 {
8824 printf ("%s\n", find_file (print_file_name));
8825 return (0);
8826 }
8827
8828 if (print_prog_name)
8829 {
8830 if (use_ld != NULL && ! strcmp (print_prog_name, "ld"))
8831 {
8832 /* Append USE_LD to the default linker. */
8833 #ifdef DEFAULT_LINKER
8834 char *ld;
8835 # ifdef HAVE_HOST_EXECUTABLE_SUFFIX
8836 int len = (sizeof (DEFAULT_LINKER)
8837 - sizeof (HOST_EXECUTABLE_SUFFIX));
8838 ld = NULL;
8839 if (len > 0)
8840 {
8841 char *default_linker = xstrdup (DEFAULT_LINKER);
8842 /* Strip HOST_EXECUTABLE_SUFFIX if DEFAULT_LINKER contains
8843 HOST_EXECUTABLE_SUFFIX. */
8844 if (! strcmp (&default_linker[len], HOST_EXECUTABLE_SUFFIX))
8845 {
8846 default_linker[len] = '\0';
8847 ld = concat (default_linker, use_ld,
8848 HOST_EXECUTABLE_SUFFIX, NULL);
8849 }
8850 }
8851 if (ld == NULL)
8852 # endif
8853 ld = concat (DEFAULT_LINKER, use_ld, NULL);
8854 if (access (ld, X_OK) == 0)
8855 {
8856 printf ("%s\n", ld);
8857 return (0);
8858 }
8859 #endif
8860 print_prog_name = concat (print_prog_name, use_ld, NULL);
8861 }
8862 char *newname = find_a_program (print_prog_name);
8863 printf ("%s\n", (newname ? newname : print_prog_name));
8864 return (0);
8865 }
8866
8867 if (print_multi_lib)
8868 {
8869 print_multilib_info ();
8870 return (0);
8871 }
8872
8873 if (print_multi_directory)
8874 {
8875 if (multilib_dir == NULL)
8876 printf (".\n");
8877 else
8878 printf ("%s\n", multilib_dir);
8879 return (0);
8880 }
8881
8882 if (print_multiarch)
8883 {
8884 if (multiarch_dir == NULL)
8885 printf ("\n");
8886 else
8887 printf ("%s\n", multiarch_dir);
8888 return (0);
8889 }
8890
8891 if (print_sysroot)
8892 {
8893 if (target_system_root)
8894 {
8895 if (target_sysroot_suffix)
8896 printf ("%s%s\n", target_system_root, target_sysroot_suffix);
8897 else
8898 printf ("%s\n", target_system_root);
8899 }
8900 return (0);
8901 }
8902
8903 if (print_multi_os_directory)
8904 {
8905 if (multilib_os_dir == NULL)
8906 printf (".\n");
8907 else
8908 printf ("%s\n", multilib_os_dir);
8909 return (0);
8910 }
8911
8912 if (print_sysroot_headers_suffix)
8913 {
8914 if (*sysroot_hdrs_suffix_spec)
8915 {
8916 printf("%s\n", (target_sysroot_hdrs_suffix
8917 ? target_sysroot_hdrs_suffix
8918 : ""));
8919 return (0);
8920 }
8921 else
8922 /* The error status indicates that only one set of fixed
8923 headers should be built. */
8924 fatal_error (input_location,
8925 "not configured with sysroot headers suffix");
8926 }
8927
8928 if (print_help_list)
8929 {
8930 display_help ();
8931
8932 if (! verbose_flag)
8933 {
8934 printf (_("\nFor bug reporting instructions, please see:\n"));
8935 printf ("%s.\n", bug_report_url);
8936
8937 return (0);
8938 }
8939
8940 /* We do not exit here. Instead we have created a fake input file
8941 called 'help-dummy' which needs to be compiled, and we pass this
8942 on the various sub-processes, along with the --help switch.
8943 Ensure their output appears after ours. */
8944 fputc ('\n', stdout);
8945 fflush (stdout);
8946 }
8947
8948 if (print_version)
8949 {
8950 printf (_("%s %s%s\n"), progname, pkgversion_string,
8951 version_string);
8952 printf ("Copyright %s 2025 Free Software Foundation, Inc.\n",
8953 _("(C)"));
8954 fputs (_("This is free software; see the source for copying conditions. There is NO\n\
8955 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"),
8956 stdout);
8957 if (! verbose_flag)
8958 return 0;
8959
8960 /* We do not exit here. We use the same mechanism of --help to print
8961 the version of the sub-processes. */
8962 fputc ('\n', stdout);
8963 fflush (stdout);
8964 }
8965
8966 if (verbose_flag)
8967 {
8968 print_configuration (stderr);
8969 if (n_infiles == 0)
8970 return (0);
8971 }
8972
8973 return 1;
8974 }
8975
8976 /* Figure out what to do with each input file.
8977 Return true if we need to exit early from "main", false otherwise. */
8978
8979 bool
8980 driver::prepare_infiles ()
8981 {
8982 size_t i;
8983 int lang_n_infiles = 0;
8984
8985 if (n_infiles == added_libraries)
8986 fatal_error (input_location, "no input files");
8987
8988 if (seen_error ())
8989 /* Early exit needed from main. */
8990 return true;
8991
8992 /* Make a place to record the compiler output file names
8993 that correspond to the input files. */
8994
8995 i = n_infiles;
8996 i += lang_specific_extra_outfiles;
8997 outfiles = XCNEWVEC (const char *, i);
8998
8999 /* Record which files were specified explicitly as link input. */
9000
9001 explicit_link_files = XCNEWVEC (char, n_infiles);
9002
9003 combine_inputs = have_o || flag_wpa;
9004
9005 for (i = 0; (int) i < n_infiles; i++)
9006 {
9007 const char *name = infiles[i].name;
9008 struct compiler *compiler = lookup_compiler (name,
9009 strlen (name),
9010 infiles[i].language);
9011
9012 if (compiler && !(compiler->combinable))
9013 combine_inputs = false;
9014
9015 if (lang_n_infiles > 0 && compiler != input_file_compiler
9016 && infiles[i].language && infiles[i].language[0] != '*')
9017 infiles[i].incompiler = compiler;
9018 else if (compiler)
9019 {
9020 lang_n_infiles++;
9021 input_file_compiler = compiler;
9022 infiles[i].incompiler = compiler;
9023 }
9024 else
9025 {
9026 /* Since there is no compiler for this input file, assume it is a
9027 linker file. */
9028 explicit_link_files[i] = 1;
9029 infiles[i].incompiler = NULL;
9030 }
9031 infiles[i].compiled = false;
9032 infiles[i].preprocessed = false;
9033 }
9034
9035 if (!combine_inputs && have_c && have_o && lang_n_infiles > 1)
9036 fatal_error (input_location,
9037 "cannot specify %<-o%> with %<-c%>, %<-S%> or %<-E%> "
9038 "with multiple files");
9039
9040 /* No early exit needed from main; we can continue. */
9041 return false;
9042 }
9043
9044 /* Run the spec machinery on each input file. */
9045
9046 void
9047 driver::do_spec_on_infiles () const
9048 {
9049 size_t i;
9050
9051 for (i = 0; (int) i < n_infiles; i++)
9052 {
9053 int this_file_error = 0;
9054
9055 /* Tell do_spec what to substitute for %i. */
9056
9057 input_file_number = i;
9058 set_input (infiles[i].name);
9059
9060 if (infiles[i].compiled)
9061 continue;
9062
9063 /* Use the same thing in %o, unless cp->spec says otherwise. */
9064
9065 outfiles[i] = gcc_input_filename;
9066
9067 /* Figure out which compiler from the file's suffix. */
9068
9069 input_file_compiler
9070 = lookup_compiler (infiles[i].name, input_filename_length,
9071 infiles[i].language);
9072
9073 if (input_file_compiler)
9074 {
9075 /* Ok, we found an applicable compiler. Run its spec. */
9076
9077 if (input_file_compiler->spec[0] == '#')
9078 {
9079 error ("%s: %s compiler not installed on this system",
9080 gcc_input_filename, &input_file_compiler->spec[1]);
9081 this_file_error = 1;
9082 }
9083 else
9084 {
9085 int value;
9086
9087 if (compare_debug)
9088 {
9089 free (debug_check_temp_file[0]);
9090 debug_check_temp_file[0] = NULL;
9091
9092 free (debug_check_temp_file[1]);
9093 debug_check_temp_file[1] = NULL;
9094 }
9095
9096 value = do_spec (input_file_compiler->spec);
9097 infiles[i].compiled = true;
9098 if (value < 0)
9099 this_file_error = 1;
9100 else if (compare_debug && debug_check_temp_file[0])
9101 {
9102 if (verbose_flag)
9103 inform (UNKNOWN_LOCATION,
9104 "recompiling with %<-fcompare-debug%>");
9105
9106 compare_debug = -compare_debug;
9107 n_switches = n_switches_debug_check[1];
9108 n_switches_alloc = n_switches_alloc_debug_check[1];
9109 switches = switches_debug_check[1];
9110
9111 value = do_spec (input_file_compiler->spec);
9112
9113 compare_debug = -compare_debug;
9114 n_switches = n_switches_debug_check[0];
9115 n_switches_alloc = n_switches_alloc_debug_check[0];
9116 switches = switches_debug_check[0];
9117
9118 if (value < 0)
9119 {
9120 error ("during %<-fcompare-debug%> recompilation");
9121 this_file_error = 1;
9122 }
9123
9124 gcc_assert (debug_check_temp_file[1]
9125 && filename_cmp (debug_check_temp_file[0],
9126 debug_check_temp_file[1]));
9127
9128 if (verbose_flag)
9129 inform (UNKNOWN_LOCATION, "comparing final insns dumps");
9130
9131 if (compare_files (debug_check_temp_file))
9132 this_file_error = 1;
9133 }
9134
9135 if (compare_debug)
9136 {
9137 free (debug_check_temp_file[0]);
9138 debug_check_temp_file[0] = NULL;
9139
9140 free (debug_check_temp_file[1]);
9141 debug_check_temp_file[1] = NULL;
9142 }
9143 }
9144 }
9145
9146 /* If this file's name does not contain a recognized suffix,
9147 record it as explicit linker input. */
9148
9149 else
9150 explicit_link_files[i] = 1;
9151
9152 /* Clear the delete-on-failure queue, deleting the files in it
9153 if this compilation failed. */
9154
9155 if (this_file_error)
9156 {
9157 delete_failure_queue ();
9158 errorcount++;
9159 }
9160 /* If this compilation succeeded, don't delete those files later. */
9161 clear_failure_queue ();
9162 }
9163
9164 /* Reset the input file name to the first compile/object file name, for use
9165 with %b in LINK_SPEC. We use the first input file that we can find
9166 a compiler to compile it instead of using infiles.language since for
9167 languages other than C we use aliases that we then lookup later. */
9168 if (n_infiles > 0)
9169 {
9170 int i;
9171
9172 for (i = 0; i < n_infiles ; i++)
9173 if (infiles[i].incompiler
9174 || (infiles[i].language && infiles[i].language[0] != '*'))
9175 {
9176 set_input (infiles[i].name);
9177 break;
9178 }
9179 }
9180
9181 if (!seen_error ())
9182 {
9183 /* Make sure INPUT_FILE_NUMBER points to first available open
9184 slot. */
9185 input_file_number = n_infiles;
9186 if (lang_specific_pre_link ())
9187 errorcount++;
9188 }
9189 }
9190
9191 /* If we have to run the linker, do it now. */
9192
9193 void
9194 driver::maybe_run_linker (const char *argv0) const
9195 {
9196 size_t i;
9197 int linker_was_run = 0;
9198 int num_linker_inputs;
9199
9200 /* Determine if there are any linker input files. */
9201 num_linker_inputs = 0;
9202 for (i = 0; (int) i < n_infiles; i++)
9203 if (explicit_link_files[i] || outfiles[i] != NULL)
9204 num_linker_inputs++;
9205
9206 /* Arrange for temporary file names created during linking to take
9207 on names related with the linker output rather than with the
9208 inputs when appropriate. */
9209 if (outbase && *outbase)
9210 {
9211 if (dumpdir)
9212 {
9213 char *tofree = dumpdir;
9214 gcc_checking_assert (strlen (dumpdir) == dumpdir_length);
9215 dumpdir = concat (dumpdir, outbase, ".", NULL);
9216 free (tofree);
9217 }
9218 else
9219 dumpdir = concat (outbase, ".", NULL);
9220 dumpdir_length += strlen (outbase) + 1;
9221 dumpdir_trailing_dash_added = true;
9222 }
9223 else if (dumpdir_trailing_dash_added)
9224 {
9225 gcc_assert (dumpdir[dumpdir_length - 1] == '-');
9226 dumpdir[dumpdir_length - 1] = '.';
9227 }
9228
9229 if (dumpdir_trailing_dash_added)
9230 {
9231 gcc_assert (dumpdir_length > 0);
9232 gcc_assert (dumpdir[dumpdir_length - 1] == '.');
9233 dumpdir_length--;
9234 }
9235
9236 free (outbase);
9237 input_basename = outbase = NULL;
9238 outbase_length = suffixed_basename_length = basename_length = 0;
9239
9240 /* Run ld to link all the compiler output files. */
9241
9242 if (num_linker_inputs > 0 && !seen_error () && print_subprocess_help < 2)
9243 {
9244 int tmp = execution_count;
9245
9246 detect_jobserver ();
9247
9248 if (! have_c)
9249 {
9250 #if HAVE_LTO_PLUGIN > 0
9251 #if HAVE_LTO_PLUGIN == 2
9252 const char *fno_use_linker_plugin = "fno-use-linker-plugin";
9253 #else
9254 const char *fuse_linker_plugin = "fuse-linker-plugin";
9255 #endif
9256 #endif
9257
9258 /* We'll use ld if we can't find collect2. */
9259 if (! strcmp (linker_name_spec, "collect2"))
9260 {
9261 char *s = find_a_program ("collect2");
9262 if (s == NULL)
9263 set_static_spec_shared (&linker_name_spec, "ld");
9264 }
9265
9266 #if HAVE_LTO_PLUGIN > 0
9267 #if HAVE_LTO_PLUGIN == 2
9268 if (!switch_matches (fno_use_linker_plugin,
9269 fno_use_linker_plugin
9270 + strlen (fno_use_linker_plugin), 0))
9271 #else
9272 if (switch_matches (fuse_linker_plugin,
9273 fuse_linker_plugin
9274 + strlen (fuse_linker_plugin), 0))
9275 #endif
9276 {
9277 char *temp_spec = find_a_file (&exec_prefixes,
9278 LTOPLUGINSONAME, R_OK,
9279 false);
9280 if (!temp_spec)
9281 fatal_error (input_location,
9282 "%<-fuse-linker-plugin%>, but %s not found",
9283 LTOPLUGINSONAME);
9284 linker_plugin_file_spec = convert_white_space (temp_spec);
9285 }
9286 #endif
9287 set_static_spec_shared (&lto_gcc_spec, argv0);
9288 }
9289
9290 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
9291 for collect. */
9292 putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH", false);
9293 putenv_from_prefixes (&startfile_prefixes, LIBRARY_PATH_ENV, true);
9294
9295 if (print_subprocess_help == 1)
9296 {
9297 printf (_("\nLinker options\n==============\n\n"));
9298 printf (_("Use \"-Wl,OPTION\" to pass \"OPTION\""
9299 " to the linker.\n\n"));
9300 fflush (stdout);
9301 }
9302 int value = do_spec (link_command_spec);
9303 if (value < 0)
9304 errorcount = 1;
9305 linker_was_run = (tmp != execution_count);
9306 }
9307
9308 /* If options said don't run linker,
9309 complain about input files to be given to the linker. */
9310
9311 if (! linker_was_run && !seen_error ())
9312 for (i = 0; (int) i < n_infiles; i++)
9313 if (explicit_link_files[i]
9314 && !(infiles[i].language && infiles[i].language[0] == '*'))
9315 {
9316 warning (0, "%s: linker input file unused because linking not done",
9317 outfiles[i]);
9318 if (access (outfiles[i], F_OK) < 0)
9319 /* This is can be an indication the user specifed an errorneous
9320 separated option value, (or used the wrong prefix for an
9321 option). */
9322 error ("%s: linker input file not found: %m", outfiles[i]);
9323 }
9324 }
9325
9326 /* The end of "main". */
9327
9328 void
9329 driver::final_actions () const
9330 {
9331 /* Delete some or all of the temporary files we made. */
9332
9333 if (seen_error ())
9334 delete_failure_queue ();
9335 delete_temp_files ();
9336
9337 if (totruncate_file != NULL && !seen_error ())
9338 /* Truncate file specified by -truncate.
9339 Used by lto-wrapper to reduce temporary disk-space usage. */
9340 truncate(totruncate_file, 0);
9341
9342 if (print_help_list)
9343 {
9344 printf (("\nFor bug reporting instructions, please see:\n"));
9345 printf ("%s\n", bug_report_url);
9346 }
9347 }
9348
9349 /* Detect whether jobserver is active and working. If not drop
9350 --jobserver-auth from MAKEFLAGS. */
9351
9352 void
9353 driver::detect_jobserver () const
9354 {
9355 jobserver_info jinfo;
9356 if (!jinfo.is_active && !jinfo.skipped_makeflags.empty ())
9357 xputenv (xstrdup (jinfo.skipped_makeflags.c_str ()));
9358 }
9359
9360 /* Determine what the exit code of the driver should be. */
9361
9362 int
9363 driver::get_exit_code () const
9364 {
9365 return (signal_count != 0 ? 2
9366 : seen_error () ? (pass_exit_codes ? greatest_status : 1)
9367 : 0);
9368 }
9369
9370 /* Find the proper compilation spec for the file name NAME,
9371 whose length is LENGTH. LANGUAGE is the specified language,
9372 or 0 if this file is to be passed to the linker. */
9373
9374 static struct compiler *
9375 lookup_compiler (const char *name, size_t length, const char *language)
9376 {
9377 struct compiler *cp;
9378
9379 /* If this was specified by the user to be a linker input, indicate that. */
9380 if (language != 0 && language[0] == '*')
9381 return 0;
9382
9383 /* Otherwise, look for the language, if one is spec'd. */
9384 if (language != 0)
9385 {
9386 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
9387 if (cp->suffix[0] == '@' && !strcmp (cp->suffix + 1, language))
9388 {
9389 if (name != NULL && strcmp (name, "-") == 0
9390 && (strcmp (cp->suffix, "@c-header") == 0
9391 || strcmp (cp->suffix, "@c++-header") == 0)
9392 && !have_E)
9393 fatal_error (input_location,
9394 "cannot use %<-%> as input filename for a "
9395 "precompiled header");
9396
9397 return cp;
9398 }
9399
9400 error ("language %s not recognized", language);
9401 return 0;
9402 }
9403
9404 /* Look for a suffix. */
9405 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
9406 {
9407 if (/* The suffix `-' matches only the file name `-'. */
9408 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
9409 || (strlen (cp->suffix) < length
9410 /* See if the suffix matches the end of NAME. */
9411 && !strcmp (cp->suffix,
9412 name + length - strlen (cp->suffix))
9413 ))
9414 break;
9415 }
9416
9417 #if defined (OS2) ||defined (HAVE_DOS_BASED_FILE_SYSTEM)
9418 /* Look again, but case-insensitively this time. */
9419 if (cp < compilers)
9420 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
9421 {
9422 if (/* The suffix `-' matches only the file name `-'. */
9423 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
9424 || (strlen (cp->suffix) < length
9425 /* See if the suffix matches the end of NAME. */
9426 && ((!strcmp (cp->suffix,
9427 name + length - strlen (cp->suffix))
9428 || !strpbrk (cp->suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
9429 && !strcasecmp (cp->suffix,
9430 name + length - strlen (cp->suffix)))
9431 ))
9432 break;
9433 }
9434 #endif
9435
9436 if (cp >= compilers)
9437 {
9438 if (cp->spec[0] != '@')
9439 /* A non-alias entry: return it. */
9440 return cp;
9441
9442 /* An alias entry maps a suffix to a language.
9443 Search for the language; pass 0 for NAME and LENGTH
9444 to avoid infinite recursion if language not found. */
9445 return lookup_compiler (NULL, 0, cp->spec + 1);
9446 }
9447 return 0;
9448 }
9449
9450 static char *
9451 save_string (const char *s, int len)
9452 {
9453 char *result = XNEWVEC (char, len + 1);
9454
9455 gcc_checking_assert (strlen (s) >= (unsigned int) len);
9456 memcpy (result, s, len);
9457 result[len] = 0;
9458 return result;
9459 }
9460
9461
9462 static inline void
9463 validate_switches_from_spec (const char *spec, bool user)
9464 {
9465 const char *p = spec;
9466 char c;
9467 while ((c = *p++))
9468 if (c == '%'
9469 && (*p == '{'
9470 || *p == '<'
9471 || (*p == 'W' && *++p == '{')
9472 || (*p == '@' && *++p == '{')))
9473 /* We have a switch spec. */
9474 p = validate_switches (p + 1, user, *p == '{');
9475 }
9476
9477 static void
9478 validate_all_switches (void)
9479 {
9480 struct compiler *comp;
9481 struct spec_list *spec;
9482
9483 for (comp = compilers; comp->spec; comp++)
9484 validate_switches_from_spec (comp->spec, false);
9485
9486 /* Look through the linked list of specs read from the specs file. */
9487 for (spec = specs; spec; spec = spec->next)
9488 validate_switches_from_spec (*spec->ptr_spec, spec->user_p);
9489
9490 validate_switches_from_spec (link_command_spec, false);
9491 }
9492
9493 /* Look at the switch-name that comes after START and mark as valid
9494 all supplied switches that match it. If BRACED, handle other
9495 switches after '|' and '&', and specs after ':' until ';' or '}',
9496 going back for more switches after ';'. Without BRACED, handle
9497 only one atom. Return a pointer to whatever follows the handled
9498 items, after the closing brace if BRACED. */
9499
9500 static const char *
9501 validate_switches (const char *start, bool user_spec, bool braced)
9502 {
9503 const char *p = start;
9504 const char *atom;
9505 size_t len;
9506 int i;
9507 bool suffix;
9508 bool starred;
9509
9510 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
9511
9512 next_member:
9513 suffix = false;
9514 starred = false;
9515
9516 SKIP_WHITE ();
9517
9518 if (*p == '!')
9519 p++;
9520
9521 SKIP_WHITE ();
9522 if (*p == '.' || *p == ',')
9523 suffix = true, p++;
9524
9525 atom = p;
9526 while (ISIDNUM (*p) || *p == '-' || *p == '+' || *p == '='
9527 || *p == ',' || *p == '.' || *p == '@')
9528 p++;
9529 len = p - atom;
9530
9531 if (*p == '*')
9532 starred = true, p++;
9533
9534 SKIP_WHITE ();
9535
9536 if (!suffix)
9537 {
9538 /* Mark all matching switches as valid. */
9539 for (i = 0; i < n_switches; i++)
9540 if (!strncmp (switches[i].part1, atom, len)
9541 && (starred || switches[i].part1[len] == '\0')
9542 && (switches[i].known || user_spec))
9543 switches[i].validated = true;
9544 }
9545
9546 if (!braced)
9547 return p;
9548
9549 if (*p) p++;
9550 if (*p && (p[-1] == '|' || p[-1] == '&'))
9551 goto next_member;
9552
9553 if (*p && p[-1] == ':')
9554 {
9555 while (*p && *p != ';' && *p != '}')
9556 {
9557 if (*p == '%')
9558 {
9559 p++;
9560 if (*p == '{' || *p == '<')
9561 p = validate_switches (p+1, user_spec, *p == '{');
9562 else if (p[0] == 'W' && p[1] == '{')
9563 p = validate_switches (p+2, user_spec, true);
9564 else if (p[0] == '@' && p[1] == '{')
9565 p = validate_switches (p+2, user_spec, true);
9566 }
9567 else
9568 p++;
9569 }
9570
9571 if (*p) p++;
9572 if (*p && p[-1] == ';')
9573 goto next_member;
9574 }
9575
9576 return p;
9577 #undef SKIP_WHITE
9578 }
9579
9580 struct mdswitchstr
9581 {
9582 const char *str;
9583 int len;
9584 };
9585
9586 static struct mdswitchstr *mdswitches;
9587 static int n_mdswitches;
9588
9589 /* Check whether a particular argument was used. The first time we
9590 canonicalize the switches to keep only the ones we care about. */
9591
9592 struct used_arg_t
9593 {
9594 public:
9595 int operator () (const char *p, int len);
9596 void finalize ();
9597
9598 private:
9599 struct mswitchstr
9600 {
9601 const char *str;
9602 const char *replace;
9603 int len;
9604 int rep_len;
9605 };
9606
9607 mswitchstr *mswitches;
9608 int n_mswitches;
9609
9610 };
9611
9612 used_arg_t used_arg;
9613
9614 int
9615 used_arg_t::operator () (const char *p, int len)
9616 {
9617 int i, j;
9618
9619 if (!mswitches)
9620 {
9621 struct mswitchstr *matches;
9622 const char *q;
9623 int cnt = 0;
9624
9625 /* Break multilib_matches into the component strings of string
9626 and replacement string. */
9627 for (q = multilib_matches; *q != '\0'; q++)
9628 if (*q == ';')
9629 cnt++;
9630
9631 matches
9632 = (struct mswitchstr *) alloca ((sizeof (struct mswitchstr)) * cnt);
9633 i = 0;
9634 q = multilib_matches;
9635 while (*q != '\0')
9636 {
9637 matches[i].str = q;
9638 while (*q != ' ')
9639 {
9640 if (*q == '\0')
9641 {
9642 invalid_matches:
9643 fatal_error (input_location, "multilib spec %qs is invalid",
9644 multilib_matches);
9645 }
9646 q++;
9647 }
9648 matches[i].len = q - matches[i].str;
9649
9650 matches[i].replace = ++q;
9651 while (*q != ';' && *q != '\0')
9652 {
9653 if (*q == ' ')
9654 goto invalid_matches;
9655 q++;
9656 }
9657 matches[i].rep_len = q - matches[i].replace;
9658 i++;
9659 if (*q == ';')
9660 q++;
9661 }
9662
9663 /* Now build a list of the replacement string for switches that we care
9664 about. Make sure we allocate at least one entry. This prevents
9665 xmalloc from calling fatal, and prevents us from re-executing this
9666 block of code. */
9667 mswitches
9668 = XNEWVEC (struct mswitchstr, n_mdswitches + (n_switches ? n_switches : 1));
9669 for (i = 0; i < n_switches; i++)
9670 if ((switches[i].live_cond & SWITCH_IGNORE) == 0)
9671 {
9672 int xlen = strlen (switches[i].part1);
9673 for (j = 0; j < cnt; j++)
9674 if (xlen == matches[j].len
9675 && ! strncmp (switches[i].part1, matches[j].str, xlen))
9676 {
9677 mswitches[n_mswitches].str = matches[j].replace;
9678 mswitches[n_mswitches].len = matches[j].rep_len;
9679 mswitches[n_mswitches].replace = (char *) 0;
9680 mswitches[n_mswitches].rep_len = 0;
9681 n_mswitches++;
9682 break;
9683 }
9684 }
9685
9686 /* Add MULTILIB_DEFAULTS switches too, as long as they were not present
9687 on the command line nor any options mutually incompatible with
9688 them. */
9689 for (i = 0; i < n_mdswitches; i++)
9690 {
9691 const char *r;
9692
9693 for (q = multilib_options; *q != '\0'; *q && q++)
9694 {
9695 while (*q == ' ')
9696 q++;
9697
9698 r = q;
9699 while (strncmp (q, mdswitches[i].str, mdswitches[i].len) != 0
9700 || strchr (" /", q[mdswitches[i].len]) == NULL)
9701 {
9702 while (*q != ' ' && *q != '/' && *q != '\0')
9703 q++;
9704 if (*q != '/')
9705 break;
9706 q++;
9707 }
9708
9709 if (*q != ' ' && *q != '\0')
9710 {
9711 while (*r != ' ' && *r != '\0')
9712 {
9713 q = r;
9714 while (*q != ' ' && *q != '/' && *q != '\0')
9715 q++;
9716
9717 if (used_arg (r, q - r))
9718 break;
9719
9720 if (*q != '/')
9721 {
9722 mswitches[n_mswitches].str = mdswitches[i].str;
9723 mswitches[n_mswitches].len = mdswitches[i].len;
9724 mswitches[n_mswitches].replace = (char *) 0;
9725 mswitches[n_mswitches].rep_len = 0;
9726 n_mswitches++;
9727 break;
9728 }
9729
9730 r = q + 1;
9731 }
9732 break;
9733 }
9734 }
9735 }
9736 }
9737
9738 for (i = 0; i < n_mswitches; i++)
9739 if (len == mswitches[i].len && ! strncmp (p, mswitches[i].str, len))
9740 return 1;
9741
9742 return 0;
9743 }
9744
9745 void used_arg_t::finalize ()
9746 {
9747 XDELETEVEC (mswitches);
9748 mswitches = NULL;
9749 n_mswitches = 0;
9750 }
9751
9752
9753 static int
9754 default_arg (const char *p, int len)
9755 {
9756 int i;
9757
9758 for (i = 0; i < n_mdswitches; i++)
9759 if (len == mdswitches[i].len && ! strncmp (p, mdswitches[i].str, len))
9760 return 1;
9761
9762 return 0;
9763 }
9764
9765 /* Work out the subdirectory to use based on the options. The format of
9766 multilib_select is a list of elements. Each element is a subdirectory
9767 name followed by a list of options followed by a semicolon. The format
9768 of multilib_exclusions is the same, but without the preceding
9769 directory. First gcc will check the exclusions, if none of the options
9770 beginning with an exclamation point are present, and all of the other
9771 options are present, then we will ignore this completely. Passing
9772 that, gcc will consider each multilib_select in turn using the same
9773 rules for matching the options. If a match is found, that subdirectory
9774 will be used.
9775 A subdirectory name is optionally followed by a colon and the corresponding
9776 multiarch name. */
9777
9778 static void
9779 set_multilib_dir (void)
9780 {
9781 const char *p;
9782 unsigned int this_path_len;
9783 const char *this_path, *this_arg;
9784 const char *start, *end;
9785 int not_arg;
9786 int ok, ndfltok, first;
9787
9788 n_mdswitches = 0;
9789 start = multilib_defaults;
9790 while (*start == ' ' || *start == '\t')
9791 start++;
9792 while (*start != '\0')
9793 {
9794 n_mdswitches++;
9795 while (*start != ' ' && *start != '\t' && *start != '\0')
9796 start++;
9797 while (*start == ' ' || *start == '\t')
9798 start++;
9799 }
9800
9801 if (n_mdswitches)
9802 {
9803 int i = 0;
9804
9805 mdswitches = XNEWVEC (struct mdswitchstr, n_mdswitches);
9806 for (start = multilib_defaults; *start != '\0'; start = end + 1)
9807 {
9808 while (*start == ' ' || *start == '\t')
9809 start++;
9810
9811 if (*start == '\0')
9812 break;
9813
9814 for (end = start + 1;
9815 *end != ' ' && *end != '\t' && *end != '\0'; end++)
9816 ;
9817
9818 obstack_grow (&multilib_obstack, start, end - start);
9819 obstack_1grow (&multilib_obstack, 0);
9820 mdswitches[i].str = XOBFINISH (&multilib_obstack, const char *);
9821 mdswitches[i++].len = end - start;
9822
9823 if (*end == '\0')
9824 break;
9825 }
9826 }
9827
9828 p = multilib_exclusions;
9829 while (*p != '\0')
9830 {
9831 /* Ignore newlines. */
9832 if (*p == '\n')
9833 {
9834 ++p;
9835 continue;
9836 }
9837
9838 /* Check the arguments. */
9839 ok = 1;
9840 while (*p != ';')
9841 {
9842 if (*p == '\0')
9843 {
9844 invalid_exclusions:
9845 fatal_error (input_location, "multilib exclusions %qs is invalid",
9846 multilib_exclusions);
9847 }
9848
9849 if (! ok)
9850 {
9851 ++p;
9852 continue;
9853 }
9854
9855 this_arg = p;
9856 while (*p != ' ' && *p != ';')
9857 {
9858 if (*p == '\0')
9859 goto invalid_exclusions;
9860 ++p;
9861 }
9862
9863 if (*this_arg != '!')
9864 not_arg = 0;
9865 else
9866 {
9867 not_arg = 1;
9868 ++this_arg;
9869 }
9870
9871 ok = used_arg (this_arg, p - this_arg);
9872 if (not_arg)
9873 ok = ! ok;
9874
9875 if (*p == ' ')
9876 ++p;
9877 }
9878
9879 if (ok)
9880 return;
9881
9882 ++p;
9883 }
9884
9885 first = 1;
9886 p = multilib_select;
9887
9888 /* Append multilib reuse rules if any. With those rules, we can reuse
9889 one multilib for certain different options sets. */
9890 if (strlen (multilib_reuse) > 0)
9891 p = concat (p, multilib_reuse, NULL);
9892
9893 while (*p != '\0')
9894 {
9895 /* Ignore newlines. */
9896 if (*p == '\n')
9897 {
9898 ++p;
9899 continue;
9900 }
9901
9902 /* Get the initial path. */
9903 this_path = p;
9904 while (*p != ' ')
9905 {
9906 if (*p == '\0')
9907 {
9908 invalid_select:
9909 fatal_error (input_location, "multilib select %qs %qs is invalid",
9910 multilib_select, multilib_reuse);
9911 }
9912 ++p;
9913 }
9914 this_path_len = p - this_path;
9915
9916 /* Check the arguments. */
9917 ok = 1;
9918 ndfltok = 1;
9919 ++p;
9920 while (*p != ';')
9921 {
9922 if (*p == '\0')
9923 goto invalid_select;
9924
9925 if (! ok)
9926 {
9927 ++p;
9928 continue;
9929 }
9930
9931 this_arg = p;
9932 while (*p != ' ' && *p != ';')
9933 {
9934 if (*p == '\0')
9935 goto invalid_select;
9936 ++p;
9937 }
9938
9939 if (*this_arg != '!')
9940 not_arg = 0;
9941 else
9942 {
9943 not_arg = 1;
9944 ++this_arg;
9945 }
9946
9947 /* If this is a default argument, we can just ignore it.
9948 This is true even if this_arg begins with '!'. Beginning
9949 with '!' does not mean that this argument is necessarily
9950 inappropriate for this library: it merely means that
9951 there is a more specific library which uses this
9952 argument. If this argument is a default, we need not
9953 consider that more specific library. */
9954 ok = used_arg (this_arg, p - this_arg);
9955 if (not_arg)
9956 ok = ! ok;
9957
9958 if (! ok)
9959 ndfltok = 0;
9960
9961 if (default_arg (this_arg, p - this_arg))
9962 ok = 1;
9963
9964 if (*p == ' ')
9965 ++p;
9966 }
9967
9968 if (ok && first)
9969 {
9970 if (this_path_len != 1
9971 || this_path[0] != '.')
9972 {
9973 char *new_multilib_dir = XNEWVEC (char, this_path_len + 1);
9974 char *q;
9975
9976 strncpy (new_multilib_dir, this_path, this_path_len);
9977 new_multilib_dir[this_path_len] = '\0';
9978 q = strchr (new_multilib_dir, ':');
9979 if (q != NULL)
9980 *q = '\0';
9981 multilib_dir = new_multilib_dir;
9982 }
9983 first = 0;
9984 }
9985
9986 if (ndfltok)
9987 {
9988 const char *q = this_path, *end = this_path + this_path_len;
9989
9990 while (q < end && *q != ':')
9991 q++;
9992 if (q < end)
9993 {
9994 const char *q2 = q + 1, *ml_end = end;
9995 char *new_multilib_os_dir;
9996
9997 while (q2 < end && *q2 != ':')
9998 q2++;
9999 if (*q2 == ':')
10000 ml_end = q2;
10001 if (ml_end - q == 1)
10002 multilib_os_dir = xstrdup (".");
10003 else
10004 {
10005 new_multilib_os_dir = XNEWVEC (char, ml_end - q);
10006 memcpy (new_multilib_os_dir, q + 1, ml_end - q - 1);
10007 new_multilib_os_dir[ml_end - q - 1] = '\0';
10008 multilib_os_dir = new_multilib_os_dir;
10009 }
10010
10011 if (q2 < end && *q2 == ':')
10012 {
10013 char *new_multiarch_dir = XNEWVEC (char, end - q2);
10014 memcpy (new_multiarch_dir, q2 + 1, end - q2 - 1);
10015 new_multiarch_dir[end - q2 - 1] = '\0';
10016 multiarch_dir = new_multiarch_dir;
10017 }
10018 break;
10019 }
10020 }
10021
10022 ++p;
10023 }
10024
10025 multilib_dir =
10026 targetm_common.compute_multilib (
10027 switches,
10028 n_switches,
10029 multilib_dir,
10030 multilib_defaults,
10031 multilib_select,
10032 multilib_matches,
10033 multilib_exclusions,
10034 multilib_reuse);
10035
10036 if (multilib_dir == NULL && multilib_os_dir != NULL
10037 && strcmp (multilib_os_dir, ".") == 0)
10038 {
10039 free (CONST_CAST (char *, multilib_os_dir));
10040 multilib_os_dir = NULL;
10041 }
10042 else if (multilib_dir != NULL && multilib_os_dir == NULL)
10043 multilib_os_dir = multilib_dir;
10044 }
10045
10046 /* Print out the multiple library subdirectory selection
10047 information. This prints out a series of lines. Each line looks
10048 like SUBDIRECTORY;@OPTION@OPTION, with as many options as is
10049 required. Only the desired options are printed out, the negative
10050 matches. The options are print without a leading dash. There are
10051 no spaces to make it easy to use the information in the shell.
10052 Each subdirectory is printed only once. This assumes the ordering
10053 generated by the genmultilib script. Also, we leave out ones that match
10054 the exclusions. */
10055
10056 static void
10057 print_multilib_info (void)
10058 {
10059 const char *p = multilib_select;
10060 const char *last_path = 0, *this_path;
10061 int skip;
10062 int not_arg;
10063 unsigned int last_path_len = 0;
10064
10065 while (*p != '\0')
10066 {
10067 skip = 0;
10068 /* Ignore newlines. */
10069 if (*p == '\n')
10070 {
10071 ++p;
10072 continue;
10073 }
10074
10075 /* Get the initial path. */
10076 this_path = p;
10077 while (*p != ' ')
10078 {
10079 if (*p == '\0')
10080 {
10081 invalid_select:
10082 fatal_error (input_location,
10083 "multilib select %qs is invalid", multilib_select);
10084 }
10085
10086 ++p;
10087 }
10088
10089 /* When --disable-multilib was used but target defines
10090 MULTILIB_OSDIRNAMES, entries starting with .: (and not starting
10091 with .:: for multiarch configurations) are there just to find
10092 multilib_os_dir, so skip them from output. */
10093 if (this_path[0] == '.' && this_path[1] == ':' && this_path[2] != ':')
10094 skip = 1;
10095
10096 /* Check for matches with the multilib_exclusions. We don't bother
10097 with the '!' in either list. If any of the exclusion rules match
10098 all of its options with the select rule, we skip it. */
10099 {
10100 const char *e = multilib_exclusions;
10101 const char *this_arg;
10102
10103 while (*e != '\0')
10104 {
10105 int m = 1;
10106 /* Ignore newlines. */
10107 if (*e == '\n')
10108 {
10109 ++e;
10110 continue;
10111 }
10112
10113 /* Check the arguments. */
10114 while (*e != ';')
10115 {
10116 const char *q;
10117 int mp = 0;
10118
10119 if (*e == '\0')
10120 {
10121 invalid_exclusion:
10122 fatal_error (input_location,
10123 "multilib exclusion %qs is invalid",
10124 multilib_exclusions);
10125 }
10126
10127 if (! m)
10128 {
10129 ++e;
10130 continue;
10131 }
10132
10133 this_arg = e;
10134
10135 while (*e != ' ' && *e != ';')
10136 {
10137 if (*e == '\0')
10138 goto invalid_exclusion;
10139 ++e;
10140 }
10141
10142 q = p + 1;
10143 while (*q != ';')
10144 {
10145 const char *arg;
10146 int len = e - this_arg;
10147
10148 if (*q == '\0')
10149 goto invalid_select;
10150
10151 arg = q;
10152
10153 while (*q != ' ' && *q != ';')
10154 {
10155 if (*q == '\0')
10156 goto invalid_select;
10157 ++q;
10158 }
10159
10160 if (! strncmp (arg, this_arg,
10161 (len < q - arg) ? q - arg : len)
10162 || default_arg (this_arg, e - this_arg))
10163 {
10164 mp = 1;
10165 break;
10166 }
10167
10168 if (*q == ' ')
10169 ++q;
10170 }
10171
10172 if (! mp)
10173 m = 0;
10174
10175 if (*e == ' ')
10176 ++e;
10177 }
10178
10179 if (m)
10180 {
10181 skip = 1;
10182 break;
10183 }
10184
10185 if (*e != '\0')
10186 ++e;
10187 }
10188 }
10189
10190 if (! skip)
10191 {
10192 /* If this is a duplicate, skip it. */
10193 skip = (last_path != 0
10194 && (unsigned int) (p - this_path) == last_path_len
10195 && ! filename_ncmp (last_path, this_path, last_path_len));
10196
10197 last_path = this_path;
10198 last_path_len = p - this_path;
10199 }
10200
10201 /* If all required arguments are default arguments, and no default
10202 arguments appear in the ! argument list, then we can skip it.
10203 We will already have printed a directory identical to this one
10204 which does not require that default argument. */
10205 if (! skip)
10206 {
10207 const char *q;
10208 bool default_arg_ok = false;
10209
10210 q = p + 1;
10211 while (*q != ';')
10212 {
10213 const char *arg;
10214
10215 if (*q == '\0')
10216 goto invalid_select;
10217
10218 if (*q == '!')
10219 {
10220 not_arg = 1;
10221 q++;
10222 }
10223 else
10224 not_arg = 0;
10225 arg = q;
10226
10227 while (*q != ' ' && *q != ';')
10228 {
10229 if (*q == '\0')
10230 goto invalid_select;
10231 ++q;
10232 }
10233
10234 if (default_arg (arg, q - arg))
10235 {
10236 /* Stop checking if any default arguments appeared in not
10237 list. */
10238 if (not_arg)
10239 {
10240 default_arg_ok = false;
10241 break;
10242 }
10243
10244 default_arg_ok = true;
10245 }
10246 else if (!not_arg)
10247 {
10248 /* Stop checking if any required argument is not provided by
10249 default arguments. */
10250 default_arg_ok = false;
10251 break;
10252 }
10253
10254 if (*q == ' ')
10255 ++q;
10256 }
10257
10258 /* Make sure all default argument is OK for this multi-lib set. */
10259 if (default_arg_ok)
10260 skip = 1;
10261 else
10262 skip = 0;
10263 }
10264
10265 if (! skip)
10266 {
10267 const char *p1;
10268
10269 for (p1 = last_path; p1 < p && *p1 != ':'; p1++)
10270 putchar (*p1);
10271 putchar (';');
10272 }
10273
10274 ++p;
10275 while (*p != ';')
10276 {
10277 int use_arg;
10278
10279 if (*p == '\0')
10280 goto invalid_select;
10281
10282 if (skip)
10283 {
10284 ++p;
10285 continue;
10286 }
10287
10288 use_arg = *p != '!';
10289
10290 if (use_arg)
10291 putchar ('@');
10292
10293 while (*p != ' ' && *p != ';')
10294 {
10295 if (*p == '\0')
10296 goto invalid_select;
10297 if (use_arg)
10298 putchar (*p);
10299 ++p;
10300 }
10301
10302 if (*p == ' ')
10303 ++p;
10304 }
10305
10306 if (! skip)
10307 {
10308 /* If there are extra options, print them now. */
10309 if (multilib_extra && *multilib_extra)
10310 {
10311 int print_at = true;
10312 const char *q;
10313
10314 for (q = multilib_extra; *q != '\0'; q++)
10315 {
10316 if (*q == ' ')
10317 print_at = true;
10318 else
10319 {
10320 if (print_at)
10321 putchar ('@');
10322 putchar (*q);
10323 print_at = false;
10324 }
10325 }
10326 }
10327
10328 putchar ('\n');
10329 }
10330
10331 ++p;
10332 }
10333 }
10334
10335 /* getenv built-in spec function.
10336
10337 Returns the value of the environment variable given by its first argument,
10338 concatenated with the second argument. If the variable is not defined, a
10339 fatal error is issued unless such undefs are internally allowed, in which
10340 case the variable name prefixed by a '/' is used as the variable value.
10341
10342 The leading '/' allows using the result at a spot where a full path would
10343 normally be expected and when the actual value doesn't really matter since
10344 undef vars are allowed. */
10345
10346 static const char *
10347 getenv_spec_function (int argc, const char **argv)
10348 {
10349 const char *value;
10350 const char *varname;
10351
10352 char *result;
10353 char *ptr;
10354 size_t len;
10355
10356 if (argc != 2)
10357 return NULL;
10358
10359 varname = argv[0];
10360 value = env.get (varname);
10361
10362 /* If the variable isn't defined and this is allowed, craft our expected
10363 return value. Assume variable names used in specs strings don't contain
10364 any active spec character so don't need escaping. */
10365 if (!value && spec_undefvar_allowed)
10366 {
10367 result = XNEWVAR (char, strlen(varname) + 2);
10368 sprintf (result, "/%s", varname);
10369 return result;
10370 }
10371
10372 if (!value)
10373 fatal_error (input_location,
10374 "environment variable %qs not defined", varname);
10375
10376 /* We have to escape every character of the environment variable so
10377 they are not interpreted as active spec characters. A
10378 particularly painful case is when we are reading a variable
10379 holding a windows path complete with \ separators. */
10380 len = strlen (value) * 2 + strlen (argv[1]) + 1;
10381 result = XNEWVAR (char, len);
10382 for (ptr = result; *value; ptr += 2)
10383 {
10384 ptr[0] = '\\';
10385 ptr[1] = *value++;
10386 }
10387
10388 strcpy (ptr, argv[1]);
10389
10390 return result;
10391 }
10392
10393 /* if-exists built-in spec function.
10394
10395 Checks to see if the file specified by the absolute pathname in
10396 ARGS exists. Returns that pathname if found.
10397
10398 The usual use for this function is to check for a library file
10399 (whose name has been expanded with %s). */
10400
10401 static const char *
10402 if_exists_spec_function (int argc, const char **argv)
10403 {
10404 /* Must have only one argument. */
10405 if (argc == 1 && IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
10406 return argv[0];
10407
10408 return NULL;
10409 }
10410
10411 /* if-exists-else built-in spec function.
10412
10413 This is like if-exists, but takes an additional argument which
10414 is returned if the first argument does not exist. */
10415
10416 static const char *
10417 if_exists_else_spec_function (int argc, const char **argv)
10418 {
10419 /* Must have exactly two arguments. */
10420 if (argc != 2)
10421 return NULL;
10422
10423 if (IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
10424 return argv[0];
10425
10426 return argv[1];
10427 }
10428
10429 /* if-exists-then-else built-in spec function.
10430
10431 Checks to see if the file specified by the absolute pathname in
10432 the first arg exists. Returns the second arg if so, otherwise returns
10433 the third arg if it is present. */
10434
10435 static const char *
10436 if_exists_then_else_spec_function (int argc, const char **argv)
10437 {
10438
10439 /* Must have two or three arguments. */
10440 if (argc != 2 && argc != 3)
10441 return NULL;
10442
10443 if (IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
10444 return argv[1];
10445
10446 if (argc == 3)
10447 return argv[2];
10448
10449 return NULL;
10450 }
10451
10452 /* sanitize built-in spec function.
10453
10454 This returns non-NULL, if sanitizing address, thread or
10455 any of the undefined behavior sanitizers. */
10456
10457 static const char *
10458 sanitize_spec_function (int argc, const char **argv)
10459 {
10460 if (argc != 1)
10461 return NULL;
10462
10463 if (strcmp (argv[0], "address") == 0)
10464 return (flag_sanitize & SANITIZE_USER_ADDRESS) ? "" : NULL;
10465 if (strcmp (argv[0], "hwaddress") == 0)
10466 return (flag_sanitize & SANITIZE_USER_HWADDRESS) ? "" : NULL;
10467 if (strcmp (argv[0], "kernel-address") == 0)
10468 return (flag_sanitize & SANITIZE_KERNEL_ADDRESS) ? "" : NULL;
10469 if (strcmp (argv[0], "kernel-hwaddress") == 0)
10470 return (flag_sanitize & SANITIZE_KERNEL_HWADDRESS) ? "" : NULL;
10471 if (strcmp (argv[0], "thread") == 0)
10472 return (flag_sanitize & SANITIZE_THREAD) ? "" : NULL;
10473 if (strcmp (argv[0], "undefined") == 0)
10474 return ((flag_sanitize
10475 & ~flag_sanitize_trap
10476 & (SANITIZE_UNDEFINED | SANITIZE_UNDEFINED_NONDEFAULT)))
10477 ? "" : NULL;
10478 if (strcmp (argv[0], "leak") == 0)
10479 return ((flag_sanitize
10480 & (SANITIZE_ADDRESS | SANITIZE_LEAK | SANITIZE_THREAD))
10481 == SANITIZE_LEAK) ? "" : NULL;
10482 return NULL;
10483 }
10484
10485 /* replace-outfile built-in spec function.
10486
10487 This looks for the first argument in the outfiles array's name and
10488 replaces it with the second argument. */
10489
10490 static const char *
10491 replace_outfile_spec_function (int argc, const char **argv)
10492 {
10493 int i;
10494 /* Must have exactly two arguments. */
10495 if (argc != 2)
10496 abort ();
10497
10498 for (i = 0; i < n_infiles; i++)
10499 {
10500 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
10501 outfiles[i] = xstrdup (argv[1]);
10502 }
10503 return NULL;
10504 }
10505
10506 /* remove-outfile built-in spec function.
10507 *
10508 * This looks for the first argument in the outfiles array's name and
10509 * removes it. */
10510
10511 static const char *
10512 remove_outfile_spec_function (int argc, const char **argv)
10513 {
10514 int i;
10515 /* Must have exactly one argument. */
10516 if (argc != 1)
10517 abort ();
10518
10519 for (i = 0; i < n_infiles; i++)
10520 {
10521 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
10522 outfiles[i] = NULL;
10523 }
10524 return NULL;
10525 }
10526
10527 /* Given two version numbers, compares the two numbers.
10528 A version number must match the regular expression
10529 ([1-9][0-9]*|0)(\.([1-9][0-9]*|0))*
10530 */
10531 static int
10532 compare_version_strings (const char *v1, const char *v2)
10533 {
10534 int rresult;
10535 regex_t r;
10536
10537 if (regcomp (&r, "^([1-9][0-9]*|0)(\\.([1-9][0-9]*|0))*$",
10538 REG_EXTENDED | REG_NOSUB) != 0)
10539 abort ();
10540 rresult = regexec (&r, v1, 0, NULL, 0);
10541 if (rresult == REG_NOMATCH)
10542 fatal_error (input_location, "invalid version number %qs", v1);
10543 else if (rresult != 0)
10544 abort ();
10545 rresult = regexec (&r, v2, 0, NULL, 0);
10546 if (rresult == REG_NOMATCH)
10547 fatal_error (input_location, "invalid version number %qs", v2);
10548 else if (rresult != 0)
10549 abort ();
10550
10551 return strverscmp (v1, v2);
10552 }
10553
10554
10555 /* version_compare built-in spec function.
10556
10557 This takes an argument of the following form:
10558
10559 <comparison-op> <arg1> [<arg2>] <switch> <result>
10560
10561 and produces "result" if the comparison evaluates to true,
10562 and nothing if it doesn't.
10563
10564 The supported <comparison-op> values are:
10565
10566 >= true if switch is a later (or same) version than arg1
10567 !> opposite of >=
10568 < true if switch is an earlier version than arg1
10569 !< opposite of <
10570 >< true if switch is arg1 or later, and earlier than arg2
10571 <> true if switch is earlier than arg1 or is arg2 or later
10572
10573 If the switch is not present, the condition is false unless
10574 the first character of the <comparison-op> is '!'.
10575
10576 For example,
10577 %:version-compare(>= 10.3 mmacosx-version-min= -lmx)
10578 adds -lmx if -mmacosx-version-min=10.3.9 was passed. */
10579
10580 static const char *
10581 version_compare_spec_function (int argc, const char **argv)
10582 {
10583 int comp1, comp2;
10584 size_t switch_len;
10585 const char *switch_value = NULL;
10586 int nargs = 1, i;
10587 bool result;
10588
10589 if (argc < 3)
10590 fatal_error (input_location, "too few arguments to %%:version-compare");
10591 if (argv[0][0] == '\0')
10592 abort ();
10593 if ((argv[0][1] == '<' || argv[0][1] == '>') && argv[0][0] != '!')
10594 nargs = 2;
10595 if (argc != nargs + 3)
10596 fatal_error (input_location, "too many arguments to %%:version-compare");
10597
10598 switch_len = strlen (argv[nargs + 1]);
10599 for (i = 0; i < n_switches; i++)
10600 if (!strncmp (switches[i].part1, argv[nargs + 1], switch_len)
10601 && check_live_switch (i, switch_len))
10602 switch_value = switches[i].part1 + switch_len;
10603
10604 if (switch_value == NULL)
10605 comp1 = comp2 = -1;
10606 else
10607 {
10608 comp1 = compare_version_strings (switch_value, argv[1]);
10609 if (nargs == 2)
10610 comp2 = compare_version_strings (switch_value, argv[2]);
10611 else
10612 comp2 = -1; /* This value unused. */
10613 }
10614
10615 switch (argv[0][0] << 8 | argv[0][1])
10616 {
10617 case '>' << 8 | '=':
10618 result = comp1 >= 0;
10619 break;
10620 case '!' << 8 | '<':
10621 result = comp1 >= 0 || switch_value == NULL;
10622 break;
10623 case '<' << 8:
10624 result = comp1 < 0;
10625 break;
10626 case '!' << 8 | '>':
10627 result = comp1 < 0 || switch_value == NULL;
10628 break;
10629 case '>' << 8 | '<':
10630 result = comp1 >= 0 && comp2 < 0;
10631 break;
10632 case '<' << 8 | '>':
10633 result = comp1 < 0 || comp2 >= 0;
10634 break;
10635
10636 default:
10637 fatal_error (input_location,
10638 "unknown operator %qs in %%:version-compare", argv[0]);
10639 }
10640 if (! result)
10641 return NULL;
10642
10643 return argv[nargs + 2];
10644 }
10645
10646 /* %:include builtin spec function. This differs from %include in that it
10647 can be nested inside a spec, and thus be conditionalized. It takes
10648 one argument, the filename, and looks for it in the startfile path.
10649 The result is always NULL, i.e. an empty expansion. */
10650
10651 static const char *
10652 include_spec_function (int argc, const char **argv)
10653 {
10654 char *file;
10655
10656 if (argc != 1)
10657 abort ();
10658
10659 file = find_a_file (&startfile_prefixes, argv[0], R_OK, true);
10660 read_specs (file ? file : argv[0], false, false);
10661
10662 return NULL;
10663 }
10664
10665 /* %:find-file spec function. This function replaces its argument by
10666 the file found through find_file, that is the -print-file-name gcc
10667 program option. */
10668 static const char *
10669 find_file_spec_function (int argc, const char **argv)
10670 {
10671 const char *file;
10672
10673 if (argc != 1)
10674 abort ();
10675
10676 file = find_file (argv[0]);
10677 return file;
10678 }
10679
10680
10681 /* %:find-plugindir spec function. This function replaces its argument
10682 by the -iplugindir=<dir> option. `dir' is found through find_file, that
10683 is the -print-file-name gcc program option. */
10684 static const char *
10685 find_plugindir_spec_function (int argc, const char **argv ATTRIBUTE_UNUSED)
10686 {
10687 const char *option;
10688
10689 if (argc != 0)
10690 abort ();
10691
10692 option = concat ("-iplugindir=", find_file ("plugin"), NULL);
10693 return option;
10694 }
10695
10696
10697 /* %:print-asm-header spec function. Print a banner to say that the
10698 following output is from the assembler. */
10699
10700 static const char *
10701 print_asm_header_spec_function (int arg ATTRIBUTE_UNUSED,
10702 const char **argv ATTRIBUTE_UNUSED)
10703 {
10704 printf (_("Assembler options\n=================\n\n"));
10705 printf (_("Use \"-Wa,OPTION\" to pass \"OPTION\" to the assembler.\n\n"));
10706 fflush (stdout);
10707 return NULL;
10708 }
10709
10710 /* Get a random number for -frandom-seed */
10711
10712 static unsigned HOST_WIDE_INT
10713 get_random_number (void)
10714 {
10715 unsigned HOST_WIDE_INT ret = 0;
10716 int fd;
10717
10718 fd = open ("/dev/urandom", O_RDONLY);
10719 if (fd >= 0)
10720 {
10721 read (fd, &ret, sizeof (HOST_WIDE_INT));
10722 close (fd);
10723 if (ret)
10724 return ret;
10725 }
10726
10727 /* Get some more or less random data. */
10728 #ifdef HAVE_GETTIMEOFDAY
10729 {
10730 struct timeval tv;
10731
10732 gettimeofday (&tv, NULL);
10733 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
10734 }
10735 #else
10736 {
10737 time_t now = time (NULL);
10738
10739 if (now != (time_t)-1)
10740 ret = (unsigned) now;
10741 }
10742 #endif
10743
10744 return ret ^ getpid ();
10745 }
10746
10747 /* %:compare-debug-dump-opt spec function. Save the last argument,
10748 expected to be the last -fdump-final-insns option, or generate a
10749 temporary. */
10750
10751 static const char *
10752 compare_debug_dump_opt_spec_function (int arg,
10753 const char **argv ATTRIBUTE_UNUSED)
10754 {
10755 char *ret;
10756 char *name;
10757 int which;
10758 static char random_seed[HOST_BITS_PER_WIDE_INT / 4 + 3];
10759
10760 if (arg != 0)
10761 fatal_error (input_location,
10762 "too many arguments to %%:compare-debug-dump-opt");
10763
10764 do_spec_2 ("%{fdump-final-insns=*:%*}", NULL);
10765 do_spec_1 (" ", 0, NULL);
10766
10767 if (argbuf.length () > 0
10768 && strcmp (argv[argbuf.length () - 1], ".") != 0)
10769 {
10770 if (!compare_debug)
10771 return NULL;
10772
10773 name = xstrdup (argv[argbuf.length () - 1]);
10774 ret = NULL;
10775 }
10776 else
10777 {
10778 if (argbuf.length () > 0)
10779 do_spec_2 ("%B.gkd", NULL);
10780 else if (!compare_debug)
10781 return NULL;
10782 else
10783 do_spec_2 ("%{!save-temps*:%g.gkd}%{save-temps*:%B.gkd}", NULL);
10784
10785 do_spec_1 (" ", 0, NULL);
10786
10787 gcc_assert (argbuf.length () > 0);
10788
10789 name = xstrdup (argbuf.last ());
10790
10791 char *arg = quote_spec (xstrdup (name));
10792 ret = concat ("-fdump-final-insns=", arg, NULL);
10793 free (arg);
10794 }
10795
10796 which = compare_debug < 0;
10797 debug_check_temp_file[which] = name;
10798
10799 if (!which)
10800 {
10801 unsigned HOST_WIDE_INT value = get_random_number ();
10802
10803 sprintf (random_seed, HOST_WIDE_INT_PRINT_HEX, value);
10804 }
10805
10806 if (*random_seed)
10807 {
10808 char *tmp = ret;
10809 ret = concat ("%{!frandom-seed=*:-frandom-seed=", random_seed, "} ",
10810 ret, NULL);
10811 free (tmp);
10812 }
10813
10814 if (which)
10815 *random_seed = 0;
10816
10817 return ret;
10818 }
10819
10820 /* %:compare-debug-self-opt spec function. Expands to the options
10821 that are to be passed in the second compilation of
10822 compare-debug. */
10823
10824 static const char *
10825 compare_debug_self_opt_spec_function (int arg,
10826 const char **argv ATTRIBUTE_UNUSED)
10827 {
10828 if (arg != 0)
10829 fatal_error (input_location,
10830 "too many arguments to %%:compare-debug-self-opt");
10831
10832 if (compare_debug >= 0)
10833 return NULL;
10834
10835 return concat ("\
10836 %<o %<MD %<MMD %<MF* %<MG %<MP %<MQ* %<MT* \
10837 %<fdump-final-insns=* -w -S -o %j \
10838 %{!fcompare-debug-second:-fcompare-debug-second} \
10839 ", compare_debug_opt, NULL);
10840 }
10841
10842 /* %:pass-through-libs spec function. Finds all -l options and input
10843 file names in the lib spec passed to it, and makes a list of them
10844 prepended with the plugin option to cause them to be passed through
10845 to the final link after all the new object files have been added. */
10846
10847 const char *
10848 pass_through_libs_spec_func (int argc, const char **argv)
10849 {
10850 char *prepended = xstrdup (" ");
10851 int n;
10852 /* Shlemiel the painter's algorithm. Innately horrible, but at least
10853 we know that there will never be more than a handful of strings to
10854 concat, and it's only once per run, so it's not worth optimising. */
10855 for (n = 0; n < argc; n++)
10856 {
10857 char *old = prepended;
10858 /* Anything that isn't an option is a full path to an output
10859 file; pass it through if it ends in '.a'. Among options,
10860 pass only -l. */
10861 if (argv[n][0] == '-' && argv[n][1] == 'l')
10862 {
10863 const char *lopt = argv[n] + 2;
10864 /* Handle both joined and non-joined -l options. If for any
10865 reason there's a trailing -l with no joined or following
10866 arg just discard it. */
10867 if (!*lopt && ++n >= argc)
10868 break;
10869 else if (!*lopt)
10870 lopt = argv[n];
10871 prepended = concat (prepended, "-plugin-opt=-pass-through=-l",
10872 lopt, " ", NULL);
10873 }
10874 else if (!strcmp (".a", argv[n] + strlen (argv[n]) - 2))
10875 {
10876 prepended = concat (prepended, "-plugin-opt=-pass-through=",
10877 argv[n], " ", NULL);
10878 }
10879 if (prepended != old)
10880 free (old);
10881 }
10882 return prepended;
10883 }
10884
10885 static bool
10886 not_actual_file_p (const char *name)
10887 {
10888 return (strcmp (name, "-") == 0
10889 || strcmp (name, HOST_BIT_BUCKET) == 0);
10890 }
10891
10892 /* %:dumps spec function. Take an optional argument that overrides
10893 the default extension for -dumpbase and -dumpbase-ext.
10894 Return -dumpdir, -dumpbase and -dumpbase-ext, if needed. */
10895 const char *
10896 dumps_spec_func (int argc, const char **argv ATTRIBUTE_UNUSED)
10897 {
10898 const char *ext = dumpbase_ext;
10899 char *p;
10900
10901 char *args[3] = { NULL, NULL, NULL };
10902 int nargs = 0;
10903
10904 /* Do not compute a default for -dumpbase-ext when -dumpbase was
10905 given explicitly. */
10906 if (dumpbase && *dumpbase && !ext)
10907 ext = "";
10908
10909 if (argc == 1)
10910 {
10911 /* Do not override the explicitly-specified -dumpbase-ext with
10912 the specs-provided overrider. */
10913 if (!ext)
10914 ext = argv[0];
10915 }
10916 else if (argc != 0)
10917 fatal_error (input_location, "too many arguments for %%:dumps");
10918
10919 if (dumpdir)
10920 {
10921 p = quote_spec_arg (xstrdup (dumpdir));
10922 args[nargs++] = concat (" -dumpdir ", p, NULL);
10923 free (p);
10924 }
10925
10926 if (!ext)
10927 ext = input_basename + basename_length;
10928
10929 /* Use the precomputed outbase, or compute dumpbase from
10930 input_basename, just like %b would. */
10931 char *base;
10932
10933 if (dumpbase && *dumpbase)
10934 {
10935 base = xstrdup (dumpbase);
10936 p = base + outbase_length;
10937 gcc_checking_assert (strncmp (base, outbase, outbase_length) == 0);
10938 gcc_checking_assert (strcmp (p, ext) == 0);
10939 }
10940 else if (outbase_length)
10941 {
10942 base = xstrndup (outbase, outbase_length);
10943 p = NULL;
10944 }
10945 else
10946 {
10947 base = xstrndup (input_basename, suffixed_basename_length);
10948 p = base + basename_length;
10949 }
10950
10951 if (compare_debug < 0 || !p || strcmp (p, ext) != 0)
10952 {
10953 if (p)
10954 *p = '\0';
10955
10956 const char *gk;
10957 if (compare_debug < 0)
10958 gk = ".gk";
10959 else
10960 gk = "";
10961
10962 p = concat (base, gk, ext, NULL);
10963
10964 free (base);
10965 base = p;
10966 }
10967
10968 base = quote_spec_arg (base);
10969 args[nargs++] = concat (" -dumpbase ", base, NULL);
10970 free (base);
10971
10972 if (*ext)
10973 {
10974 p = quote_spec_arg (xstrdup (ext));
10975 args[nargs++] = concat (" -dumpbase-ext ", p, NULL);
10976 free (p);
10977 }
10978
10979 const char *ret = concat (args[0], args[1], args[2], NULL);
10980 while (nargs > 0)
10981 free (args[--nargs]);
10982
10983 return ret;
10984 }
10985
10986 /* Returns "" if ARGV[ARGC - 2] is greater than ARGV[ARGC-1].
10987 Otherwise, return NULL. */
10988
10989 static const char *
10990 greater_than_spec_func (int argc, const char **argv)
10991 {
10992 char *converted;
10993
10994 if (argc == 1)
10995 return NULL;
10996
10997 gcc_assert (argc >= 2);
10998
10999 long arg = strtol (argv[argc - 2], &converted, 10);
11000 gcc_assert (converted != argv[argc - 2]);
11001
11002 long lim = strtol (argv[argc - 1], &converted, 10);
11003 gcc_assert (converted != argv[argc - 1]);
11004
11005 if (arg > lim)
11006 return "";
11007
11008 return NULL;
11009 }
11010
11011 /* Returns "" if debug_info_level is greater than ARGV[ARGC-1].
11012 Otherwise, return NULL. */
11013
11014 static const char *
11015 debug_level_greater_than_spec_func (int argc, const char **argv)
11016 {
11017 char *converted;
11018
11019 if (argc != 1)
11020 fatal_error (input_location,
11021 "wrong number of arguments to %%:debug-level-gt");
11022
11023 long arg = strtol (argv[0], &converted, 10);
11024 gcc_assert (converted != argv[0]);
11025
11026 if (debug_info_level > arg)
11027 return "";
11028
11029 return NULL;
11030 }
11031
11032 /* Returns "" if dwarf_version is greater than ARGV[ARGC-1].
11033 Otherwise, return NULL. */
11034
11035 static const char *
11036 dwarf_version_greater_than_spec_func (int argc, const char **argv)
11037 {
11038 char *converted;
11039
11040 if (argc != 1)
11041 fatal_error (input_location,
11042 "wrong number of arguments to %%:dwarf-version-gt");
11043
11044 long arg = strtol (argv[0], &converted, 10);
11045 gcc_assert (converted != argv[0]);
11046
11047 if (dwarf_version > arg)
11048 return "";
11049
11050 return NULL;
11051 }
11052
11053 static void
11054 path_prefix_reset (path_prefix *prefix)
11055 {
11056 struct prefix_list *iter, *next;
11057 iter = prefix->plist;
11058 while (iter)
11059 {
11060 next = iter->next;
11061 free (const_cast <char *> (iter->prefix));
11062 XDELETE (iter);
11063 iter = next;
11064 }
11065 prefix->plist = 0;
11066 prefix->max_len = 0;
11067 }
11068
11069 /* The function takes 3 arguments: OPTION name, file name and location
11070 where we search for Fortran modules.
11071 When the FILE is found by find_file, return OPTION=path_to_file. */
11072
11073 static const char *
11074 find_fortran_preinclude_file (int argc, const char **argv)
11075 {
11076 char *result = NULL;
11077 if (argc != 3)
11078 return NULL;
11079
11080 struct path_prefix prefixes = { 0, 0, "preinclude" };
11081
11082 /* Search first for 'finclude' folder location for a header file
11083 installed by the compiler (similar to omp_lib.h). */
11084 add_prefix (&prefixes, argv[2], NULL, 0, 0, 0);
11085 #ifdef TOOL_INCLUDE_DIR
11086 /* Then search: <prefix>/<target>/<include>/finclude */
11087 add_prefix (&prefixes, TOOL_INCLUDE_DIR "/finclude/",
11088 NULL, 0, 0, 0);
11089 #endif
11090 #ifdef NATIVE_SYSTEM_HEADER_DIR
11091 /* Then search: <sysroot>/usr/include/finclude/<multilib> */
11092 add_sysrooted_hdrs_prefix (&prefixes, NATIVE_SYSTEM_HEADER_DIR "/finclude/",
11093 NULL, 0, 0, 0);
11094 #endif
11095
11096 const char *path = find_a_file (&include_prefixes, argv[1], R_OK, false);
11097 if (path != NULL)
11098 result = concat (argv[0], path, NULL);
11099 else
11100 {
11101 path = find_a_file (&prefixes, argv[1], R_OK, false);
11102 if (path != NULL)
11103 result = concat (argv[0], path, NULL);
11104 }
11105
11106 path_prefix_reset (&prefixes);
11107 return result;
11108 }
11109
11110 /* The function takes any number of arguments and joins them together,
11111 escaping any special characters.
11112
11113 This seems to be necessary to build "-fjoined=foo.b" from "-fseparate foo.a"
11114 with a %{fseparate*:-fjoined=%.b$*} rule without adding undesired spaces:
11115 when doing $* replacement we first replace $* with the rest of the switch
11116 (in this case ""), and then add any arguments as arguments after the result,
11117 resulting in "-fjoined= foo.b". Using this function with e.g.
11118 %{fseparate*:-fjoined=%:join(%.b$*)} gets multiple words as separate argv
11119 elements instead of separated by spaces, and we paste them together. */
11120
11121 static const char *
11122 join_spec_func (int argc, const char **argv)
11123 {
11124 const char *result = argv[0];
11125 if (argc != 1)
11126 {
11127 for (int i = 0; i < argc; ++i)
11128 obstack_grow (&obstack, argv[i], strlen (argv[i]));
11129 obstack_1grow (&obstack, '\0');
11130 result = XOBFINISH (&obstack, const char *);
11131 }
11132 return quote_spec (xstrdup (result));
11133 }
11134
11135 /* if-driverlang built-in spec function.
11136
11137 Checks to see if the language-specific driver has specified a
11138 language name that matches the first arg. Returns the second arg if
11139 so, otherwise returns the third arg if it is present. */
11140
11141 static const char *
11142 if_driverlang_spec_function (int argc, const char **argv)
11143 {
11144 const char *language = NULL;
11145
11146 /* Must have two or three arguments. */
11147 if (argc != 2 && argc != 3)
11148 return NULL;
11149
11150 /* The lang_specific_language function is declared with
11151 __attribute__((weak)) making it optional */
11152 if (lang_specific_language != NULL)
11153 language = lang_specific_language();
11154
11155 if (language && !strcmp (argv[0], language))
11156 return argv[1];
11157
11158 if (argc == 3)
11159 return argv[2];
11160
11161 return NULL;
11162 }
11163
11164 /* If any character in ORIG fits QUOTE_P (_, P), reallocate the string
11165 so as to precede every one of them with a backslash. Return the
11166 original string or the reallocated one. */
11167
11168 static inline char *
11169 quote_string (char *orig, bool (*quote_p)(char, void *), void *p)
11170 {
11171 int len, number_of_space = 0;
11172
11173 for (len = 0; orig[len]; len++)
11174 if (quote_p (orig[len], p))
11175 number_of_space++;
11176
11177 if (number_of_space)
11178 {
11179 char *new_spec = (char *) xmalloc (len + number_of_space + 1);
11180 int j, k;
11181 for (j = 0, k = 0; j <= len; j++, k++)
11182 {
11183 if (quote_p (orig[j], p))
11184 new_spec[k++] = '\\';
11185 new_spec[k] = orig[j];
11186 }
11187 free (orig);
11188 return new_spec;
11189 }
11190 else
11191 return orig;
11192 }
11193
11194 /* Return true iff C is any of the characters convert_white_space
11195 should quote. */
11196
11197 static inline bool
11198 whitespace_to_convert_p (char c, void *)
11199 {
11200 return (c == ' ' || c == '\t');
11201 }
11202
11203 /* Insert backslash before spaces in ORIG (usually a file path), to
11204 avoid being broken by spec parser.
11205
11206 This function is needed as do_spec_1 treats white space (' ' and '\t')
11207 as the end of an argument. But in case of -plugin /usr/gcc install/xxx.so,
11208 the file name should be treated as a single argument rather than being
11209 broken into multiple. Solution is to insert '\\' before the space in a
11210 file name.
11211
11212 This function converts and only converts all occurrence of ' '
11213 to '\\' + ' ' and '\t' to '\\' + '\t'. For example:
11214 "a b" -> "a\\ b"
11215 "a b" -> "a\\ \\ b"
11216 "a\tb" -> "a\\\tb"
11217 "a\\ b" -> "a\\\\ b"
11218
11219 orig: input null-terminating string that was allocated by xalloc. The
11220 memory it points to might be freed in this function. Behavior undefined
11221 if ORIG wasn't xalloced or was freed already at entry.
11222
11223 Return: ORIG if no conversion needed. Otherwise a newly allocated string
11224 that was converted from ORIG. */
11225
11226 static char *
11227 convert_white_space (char *orig)
11228 {
11229 return quote_string (orig, whitespace_to_convert_p, NULL);
11230 }
11231
11232 /* Return true iff C matches any of the spec active characters. */
11233 static inline bool
11234 quote_spec_char_p (char c, void *)
11235 {
11236 switch (c)
11237 {
11238 case ' ':
11239 case '\t':
11240 case '\n':
11241 case '|':
11242 case '%':
11243 case '\\':
11244 return true;
11245
11246 default:
11247 return false;
11248 }
11249 }
11250
11251 /* Like convert_white_space, but deactivate all active spec chars by
11252 quoting them. */
11253
11254 static inline char *
11255 quote_spec (char *orig)
11256 {
11257 return quote_string (orig, quote_spec_char_p, NULL);
11258 }
11259
11260 /* Like quote_spec, but also turn an empty string into the spec for an
11261 empty argument. */
11262
11263 static inline char *
11264 quote_spec_arg (char *orig)
11265 {
11266 if (!*orig)
11267 {
11268 free (orig);
11269 return xstrdup ("%\"");
11270 }
11271
11272 return quote_spec (orig);
11273 }
11274
11275 /* Restore all state within gcc.cc to the initial state, so that the driver
11276 code can be safely re-run in-process.
11277
11278 Many const char * variables are referenced by static specs (see
11279 INIT_STATIC_SPEC above). These variables are restored to their default
11280 values by a simple loop over the static specs.
11281
11282 For other variables, we directly restore them all to their initial
11283 values (often implicitly 0).
11284
11285 Free the various obstacks in this file, along with "opts_obstack"
11286 from opts.cc.
11287
11288 This function also restores any environment variables that were changed. */
11289
11290 void
11291 driver::finalize ()
11292 {
11293 env.restore ();
11294 diagnostic_finish (global_dc);
11295
11296 is_cpp_driver = 0;
11297 at_file_supplied = 0;
11298 print_help_list = 0;
11299 print_version = 0;
11300 verbose_only_flag = 0;
11301 print_subprocess_help = 0;
11302 use_ld = NULL;
11303 report_times_to_file = NULL;
11304 target_system_root = DEFAULT_TARGET_SYSTEM_ROOT;
11305 target_system_root_changed = 0;
11306 target_sysroot_suffix = 0;
11307 target_sysroot_hdrs_suffix = 0;
11308 save_temps_flag = SAVE_TEMPS_NONE;
11309 save_temps_overrides_dumpdir = false;
11310 dumpdir_trailing_dash_added = false;
11311 free (dumpdir);
11312 free (dumpbase);
11313 free (dumpbase_ext);
11314 free (outbase);
11315 dumpdir = dumpbase = dumpbase_ext = outbase = NULL;
11316 dumpdir_length = outbase_length = 0;
11317 spec_machine = DEFAULT_TARGET_MACHINE;
11318 greatest_status = 1;
11319
11320 obstack_free (&obstack, NULL);
11321 obstack_free (&opts_obstack, NULL); /* in opts.cc */
11322 obstack_free (&collect_obstack, NULL);
11323
11324 link_command_spec = LINK_COMMAND_SPEC;
11325
11326 obstack_free (&multilib_obstack, NULL);
11327
11328 user_specs_head = NULL;
11329 user_specs_tail = NULL;
11330
11331 /* Within the "compilers" vec, the fields "suffix" and "spec" were
11332 statically allocated for the default compilers, but dynamically
11333 allocated for additional compilers. Delete them for the latter. */
11334 for (int i = n_default_compilers; i < n_compilers; i++)
11335 {
11336 free (const_cast <char *> (compilers[i].suffix));
11337 free (const_cast <char *> (compilers[i].spec));
11338 }
11339 XDELETEVEC (compilers);
11340 compilers = NULL;
11341 n_compilers = 0;
11342
11343 linker_options.truncate (0);
11344 assembler_options.truncate (0);
11345 preprocessor_options.truncate (0);
11346
11347 path_prefix_reset (&exec_prefixes);
11348 path_prefix_reset (&startfile_prefixes);
11349 path_prefix_reset (&include_prefixes);
11350
11351 machine_suffix = 0;
11352 just_machine_suffix = 0;
11353 gcc_exec_prefix = 0;
11354 gcc_libexec_prefix = 0;
11355 set_static_spec_shared (&md_exec_prefix, MD_EXEC_PREFIX);
11356 set_static_spec_shared (&md_startfile_prefix, MD_STARTFILE_PREFIX);
11357 set_static_spec_shared (&md_startfile_prefix_1, MD_STARTFILE_PREFIX_1);
11358 multilib_dir = 0;
11359 multilib_os_dir = 0;
11360 multiarch_dir = 0;
11361
11362 /* Free any specs dynamically-allocated by set_spec.
11363 These will be at the head of the list, before the
11364 statically-allocated ones. */
11365 if (specs)
11366 {
11367 while (specs != static_specs)
11368 {
11369 spec_list *next = specs->next;
11370 free (const_cast <char *> (specs->name));
11371 XDELETE (specs);
11372 specs = next;
11373 }
11374 specs = 0;
11375 }
11376 for (unsigned i = 0; i < ARRAY_SIZE (static_specs); i++)
11377 {
11378 spec_list *sl = &static_specs[i];
11379 if (sl->alloc_p)
11380 {
11381 free (const_cast <char *> (*(sl->ptr_spec)));
11382 sl->alloc_p = false;
11383 }
11384 *(sl->ptr_spec) = sl->default_ptr;
11385 }
11386 #ifdef EXTRA_SPECS
11387 extra_specs = NULL;
11388 #endif
11389
11390 processing_spec_function = 0;
11391
11392 clear_args ();
11393
11394 have_c = 0;
11395 have_o = 0;
11396
11397 temp_names = NULL;
11398 execution_count = 0;
11399 signal_count = 0;
11400
11401 temp_filename = NULL;
11402 temp_filename_length = 0;
11403 always_delete_queue = NULL;
11404 failure_delete_queue = NULL;
11405
11406 XDELETEVEC (switches);
11407 switches = NULL;
11408 n_switches = 0;
11409 n_switches_alloc = 0;
11410
11411 compare_debug = 0;
11412 compare_debug_second = 0;
11413 compare_debug_opt = NULL;
11414 for (int i = 0; i < 2; i++)
11415 {
11416 switches_debug_check[i] = NULL;
11417 n_switches_debug_check[i] = 0;
11418 n_switches_alloc_debug_check[i] = 0;
11419 debug_check_temp_file[i] = NULL;
11420 }
11421
11422 XDELETEVEC (infiles);
11423 infiles = NULL;
11424 n_infiles = 0;
11425 n_infiles_alloc = 0;
11426
11427 combine_inputs = false;
11428 added_libraries = 0;
11429 XDELETEVEC (outfiles);
11430 outfiles = NULL;
11431 spec_lang = 0;
11432 last_language_n_infiles = 0;
11433 gcc_input_filename = NULL;
11434 input_file_number = 0;
11435 input_filename_length = 0;
11436 basename_length = 0;
11437 suffixed_basename_length = 0;
11438 input_basename = NULL;
11439 input_suffix = NULL;
11440 /* We don't need to purge "input_stat", just to unset "input_stat_set". */
11441 input_stat_set = 0;
11442 input_file_compiler = NULL;
11443 arg_going = 0;
11444 delete_this_arg = 0;
11445 this_is_output_file = 0;
11446 this_is_library_file = 0;
11447 this_is_linker_script = 0;
11448 input_from_pipe = 0;
11449 suffix_subst = NULL;
11450
11451 XDELETEVEC (mdswitches);
11452 mdswitches = NULL;
11453 n_mdswitches = 0;
11454
11455 used_arg.finalize ();
11456 }
11457
11458 /* PR jit/64810.
11459 Targets can provide configure-time default options in
11460 OPTION_DEFAULT_SPECS. The jit needs to access these, but
11461 they are expressed in the spec language.
11462
11463 Run just enough of the driver to be able to expand these
11464 specs, and then call the callback CB on each
11465 such option. The options strings are *without* a leading
11466 '-' character e.g. ("march=x86-64"). Finally, clean up. */
11467
11468 void
11469 driver_get_configure_time_options (void (*cb) (const char *option,
11470 void *user_data),
11471 void *user_data)
11472 {
11473 size_t i;
11474
11475 obstack_init (&obstack);
11476 init_opts_obstack ();
11477 n_switches = 0;
11478
11479 for (i = 0; i < ARRAY_SIZE (option_default_specs); i++)
11480 do_option_spec (option_default_specs[i].name,
11481 option_default_specs[i].spec);
11482
11483 for (i = 0; (int) i < n_switches; i++)
11484 {
11485 gcc_assert (switches[i].part1);
11486 (*cb) (switches[i].part1, user_data);
11487 }
11488
11489 obstack_free (&opts_obstack, NULL);
11490 obstack_free (&obstack, NULL);
11491 n_switches = 0;
11492 }