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