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