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