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