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