Merge trunk version 194962 into gupc branch.
[official-gcc.git] / gcc / gcc.c
blobbe9299a6cc4d60ba2ca1532bde8c38330fb39983
1 /* Compiler driver program that can handle many languages.
2 Copyright (C) 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
4 2010, 2011, 2012, 2013
5 Free Software Foundation, Inc.
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 /* This program is the user interface to the C compiler and possibly to
24 other compilers. It is used because compilation is a complicated procedure
25 which involves running several programs and passing temporary files between
26 them, forwarding the users switches to those programs selectively,
27 and deleting the temporary files at the end.
29 CC recognizes how to compile each input file by suffixes in the file names.
30 Once it knows which kind of compilation to perform, the procedure for
31 compilation is specified by a string called a "spec". */
33 #include "config.h"
34 #include "system.h"
35 #include "coretypes.h"
36 #include "multilib.h" /* before tm.h */
37 #include "tm.h"
38 #include "xregex.h"
39 #include "obstack.h"
40 #include "intl.h"
41 #include "prefix.h"
42 #include "gcc.h"
43 #include "diagnostic.h"
44 #include "flags.h"
45 #include "opts.h"
46 #include "params.h"
47 #include "vec.h"
48 #include "filenames.h"
50 /* By default there is no special suffix for target executables. */
51 /* FIXME: when autoconf is fixed, remove the host check - dj */
52 #if defined(TARGET_EXECUTABLE_SUFFIX) && defined(HOST_EXECUTABLE_SUFFIX)
53 #define HAVE_TARGET_EXECUTABLE_SUFFIX
54 #endif
56 /* By default there is no special suffix for host executables. */
57 #ifdef HOST_EXECUTABLE_SUFFIX
58 #define HAVE_HOST_EXECUTABLE_SUFFIX
59 #else
60 #define HOST_EXECUTABLE_SUFFIX ""
61 #endif
63 /* By default, the suffix for target object files is ".o". */
64 #ifdef TARGET_OBJECT_SUFFIX
65 #define HAVE_TARGET_OBJECT_SUFFIX
66 #else
67 #define TARGET_OBJECT_SUFFIX ".o"
68 #endif
70 static const char dir_separator_str[] = { DIR_SEPARATOR, 0 };
72 /* Most every one is fine with LIBRARY_PATH. For some, it conflicts. */
73 #ifndef LIBRARY_PATH_ENV
74 #define LIBRARY_PATH_ENV "LIBRARY_PATH"
75 #endif
77 /* If a stage of compilation returns an exit status >= 1,
78 compilation of that file ceases. */
80 #define MIN_FATAL_STATUS 1
82 /* Flag set by cppspec.c to 1. */
83 int is_cpp_driver;
85 /* Flag set to nonzero if an @file argument has been supplied to gcc. */
86 static bool at_file_supplied;
88 /* Definition of string containing the arguments given to configure. */
89 #include "configargs.h"
91 /* Flag saying to print the command line options understood by gcc and its
92 sub-processes. */
94 static int print_help_list;
96 /* Flag saying to print the version of gcc and its sub-processes. */
98 static int print_version;
100 /* Flag indicating whether we should ONLY print the command and
101 arguments (like verbose_flag) without executing the command.
102 Displayed arguments are quoted so that the generated command
103 line is suitable for execution. This is intended for use in
104 shell scripts to capture the driver-generated command line. */
105 static int verbose_only_flag;
107 /* Flag indicating how to print command line options of sub-processes. */
109 static int print_subprocess_help;
111 /* Whether we should report subprocess execution times to a file. */
113 FILE *report_times_to_file = NULL;
115 /* Nonzero means place this string before uses of /, so that include
116 and library files can be found in an alternate location. */
118 #ifdef TARGET_SYSTEM_ROOT
119 static const char *target_system_root = TARGET_SYSTEM_ROOT;
120 #else
121 static const char *target_system_root = 0;
122 #endif
124 /* Nonzero means pass the updated target_system_root to the compiler. */
126 static int target_system_root_changed;
128 /* Nonzero means append this string to target_system_root. */
130 static const char *target_sysroot_suffix = 0;
132 /* Nonzero means append this string to target_system_root for headers. */
134 static const char *target_sysroot_hdrs_suffix = 0;
136 /* Nonzero means write "temp" files in source directory
137 and use the source file's name in them, and don't delete them. */
139 static enum save_temps {
140 SAVE_TEMPS_NONE, /* no -save-temps */
141 SAVE_TEMPS_CWD, /* -save-temps in current directory */
142 SAVE_TEMPS_OBJ /* -save-temps in object directory */
143 } save_temps_flag;
145 /* Output file to use to get the object directory for -save-temps=obj */
146 static char *save_temps_prefix = 0;
147 static size_t save_temps_length = 0;
149 /* The compiler version. */
151 static const char *compiler_version;
153 /* The target version. */
155 static const char *const spec_version = DEFAULT_TARGET_VERSION;
157 /* The target machine. */
159 static const char *spec_machine = DEFAULT_TARGET_MACHINE;
161 /* Nonzero if cross-compiling.
162 When -b is used, the value comes from the `specs' file. */
164 #ifdef CROSS_DIRECTORY_STRUCTURE
165 static const char *cross_compile = "1";
166 #else
167 static const char *cross_compile = "0";
168 #endif
170 /* Greatest exit code of sub-processes that has been encountered up to
171 now. */
172 static int greatest_status = 1;
174 /* This is the obstack which we use to allocate many strings. */
176 static struct obstack obstack;
178 /* This is the obstack to build an environment variable to pass to
179 collect2 that describes all of the relevant switches of what to
180 pass the compiler in building the list of pointers to constructors
181 and destructors. */
183 static struct obstack collect_obstack;
185 /* Forward declaration for prototypes. */
186 struct path_prefix;
187 struct prefix_list;
189 static void init_spec (void);
190 static void store_arg (const char *, int, int);
191 static void insert_wrapper (const char *);
192 static char *load_specs (const char *);
193 static void read_specs (const char *, bool, bool);
194 static void set_spec (const char *, const char *, bool);
195 static struct compiler *lookup_compiler (const char *, size_t, const char *);
196 static char *build_search_list (const struct path_prefix *, const char *,
197 bool, bool);
198 static void xputenv (const char *);
199 static void putenv_from_prefixes (const struct path_prefix *, const char *,
200 bool);
201 static int access_check (const char *, int);
202 static char *find_a_file (const struct path_prefix *, const char *, int, bool);
203 static void add_prefix (struct path_prefix *, const char *, const char *,
204 int, int, int);
205 static void add_sysrooted_prefix (struct path_prefix *, const char *,
206 const char *, int, int, int);
207 static char *skip_whitespace (char *);
208 static void delete_if_ordinary (const char *);
209 static void delete_temp_files (void);
210 static void delete_failure_queue (void);
211 static void clear_failure_queue (void);
212 static int check_live_switch (int, int);
213 static const char *handle_braces (const char *);
214 static inline bool input_suffix_matches (const char *, const char *);
215 static inline bool switch_matches (const char *, const char *, int);
216 static inline void mark_matching_switches (const char *, const char *, int);
217 static inline void process_marked_switches (void);
218 static const char *process_brace_body (const char *, const char *, const char *, int, int);
219 static const struct spec_function *lookup_spec_function (const char *);
220 static const char *eval_spec_function (const char *, const char *);
221 static const char *handle_spec_function (const char *);
222 static char *save_string (const char *, int);
223 static void set_collect_gcc_options (void);
224 static int do_spec_1 (const char *, int, const char *);
225 static int do_spec_2 (const char *);
226 static void do_option_spec (const char *, const char *);
227 static void do_self_spec (const char *);
228 static const char *find_file (const char *);
229 static int is_directory (const char *, bool);
230 static const char *validate_switches (const char *, bool);
231 static void validate_all_switches (void);
232 static inline void validate_switches_from_spec (const char *, bool);
233 static void give_switch (int, int);
234 static int used_arg (const char *, int);
235 static int default_arg (const char *, int);
236 static void set_multilib_dir (void);
237 static void print_multilib_info (void);
238 static void perror_with_name (const char *);
239 static void display_help (void);
240 static void add_preprocessor_option (const char *, int);
241 static void add_assembler_option (const char *, int);
242 static void add_linker_option (const char *, int);
243 static void process_command (unsigned int, struct cl_decoded_option *);
244 static int execute (void);
245 static void alloc_args (void);
246 static void clear_args (void);
247 static void fatal_signal (int);
248 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
249 static void init_gcc_specs (struct obstack *, const char *, const char *,
250 const char *);
251 #endif
252 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
253 static const char *convert_filename (const char *, int, int);
254 #endif
256 static const char *getenv_spec_function (int, const char **);
257 static const char *if_exists_spec_function (int, const char **);
258 static const char *if_exists_else_spec_function (int, const char **);
259 static const char *replace_outfile_spec_function (int, const char **);
260 static const char *remove_outfile_spec_function (int, const char **);
261 static const char *version_compare_spec_function (int, const char **);
262 static const char *include_spec_function (int, const char **);
263 static const char *find_file_spec_function (int, const char **);
264 static const char *find_plugindir_spec_function (int, const char **);
265 static const char *print_asm_header_spec_function (int, const char **);
266 static const char *compare_debug_dump_opt_spec_function (int, const char **);
267 static const char *compare_debug_self_opt_spec_function (int, const char **);
268 static const char *compare_debug_auxbase_opt_spec_function (int, const char **);
269 static const char *pass_through_libs_spec_func (int, const char **);
270 static const char *replace_extension_spec_func (int, const char **);
272 /* The Specs Language
274 Specs are strings containing lines, each of which (if not blank)
275 is made up of a program name, and arguments separated by spaces.
276 The program name must be exact and start from root, since no path
277 is searched and it is unreliable to depend on the current working directory.
278 Redirection of input or output is not supported; the subprograms must
279 accept filenames saying what files to read and write.
281 In addition, the specs can contain %-sequences to substitute variable text
282 or for conditional text. Here is a table of all defined %-sequences.
283 Note that spaces are not generated automatically around the results of
284 expanding these sequences; therefore, you can concatenate them together
285 or with constant text in a single argument.
287 %% substitute one % into the program name or argument.
288 %i substitute the name of the input file being processed.
289 %b substitute the basename of the input file being processed.
290 This is the substring up to (and not including) the last period
291 and not including the directory unless -save-temps was specified
292 to put temporaries in a different location.
293 %B same as %b, but include the file suffix (text after the last period).
294 %gSUFFIX
295 substitute a file name that has suffix SUFFIX and is chosen
296 once per compilation, and mark the argument a la %d. To reduce
297 exposure to denial-of-service attacks, the file name is now
298 chosen in a way that is hard to predict even when previously
299 chosen file names are known. For example, `%g.s ... %g.o ... %g.s'
300 might turn into `ccUVUUAU.s ccXYAXZ12.o ccUVUUAU.s'. SUFFIX matches
301 the regexp "[.0-9A-Za-z]*%O"; "%O" is treated exactly as if it
302 had been pre-processed. Previously, %g was simply substituted
303 with a file name chosen once per compilation, without regard
304 to any appended suffix (which was therefore treated just like
305 ordinary text), making such attacks more likely to succeed.
306 %|SUFFIX
307 like %g, but if -pipe is in effect, expands simply to "-".
308 %mSUFFIX
309 like %g, but if -pipe is in effect, expands to nothing. (We have both
310 %| and %m to accommodate differences between system assemblers; see
311 the AS_NEEDS_DASH_FOR_PIPED_INPUT target macro.)
312 %uSUFFIX
313 like %g, but generates a new temporary file name even if %uSUFFIX
314 was already seen.
315 %USUFFIX
316 substitutes the last file name generated with %uSUFFIX, generating a
317 new one if there is no such last file name. In the absence of any
318 %uSUFFIX, this is just like %gSUFFIX, except they don't share
319 the same suffix "space", so `%g.s ... %U.s ... %g.s ... %U.s'
320 would involve the generation of two distinct file names, one
321 for each `%g.s' and another for each `%U.s'. Previously, %U was
322 simply substituted with a file name chosen for the previous %u,
323 without regard to any appended suffix.
324 %jSUFFIX
325 substitutes the name of the HOST_BIT_BUCKET, if any, and if it is
326 writable, and if save-temps is off; otherwise, substitute the name
327 of a temporary file, just like %u. This temporary file is not
328 meant for communication between processes, but rather as a junk
329 disposal mechanism.
330 %.SUFFIX
331 substitutes .SUFFIX for the suffixes of a matched switch's args when
332 it is subsequently output with %*. SUFFIX is terminated by the next
333 space or %.
334 %d marks the argument containing or following the %d as a
335 temporary file name, so that that file will be deleted if GCC exits
336 successfully. Unlike %g, this contributes no text to the argument.
337 %w marks the argument containing or following the %w as the
338 "output file" of this compilation. This puts the argument
339 into the sequence of arguments that %o will substitute later.
340 %V indicates that this compilation produces no "output file".
341 %W{...}
342 like %{...} but mark last argument supplied within
343 as a file to be deleted on failure.
344 %o substitutes the names of all the output files, with spaces
345 automatically placed around them. You should write spaces
346 around the %o as well or the results are undefined.
347 %o is for use in the specs for running the linker.
348 Input files whose names have no recognized suffix are not compiled
349 at all, but they are included among the output files, so they will
350 be linked.
351 %O substitutes the suffix for object files. Note that this is
352 handled specially when it immediately follows %g, %u, or %U
353 (with or without a suffix argument) because of the need for
354 those to form complete file names. The handling is such that
355 %O is treated exactly as if it had already been substituted,
356 except that %g, %u, and %U do not currently support additional
357 SUFFIX characters following %O as they would following, for
358 example, `.o'.
359 %I Substitute any of -iprefix (made from GCC_EXEC_PREFIX), -isysroot
360 (made from TARGET_SYSTEM_ROOT), -isystem (made from COMPILER_PATH
361 and -B options) and -imultilib as necessary.
362 %s current argument is the name of a library or startup file of some sort.
363 Search for that file in a standard list of directories
364 and substitute the full name found.
365 %eSTR Print STR as an error message. STR is terminated by a newline.
366 Use this when inconsistent options are detected.
367 %nSTR Print STR as a notice. STR is terminated by a newline.
368 %x{OPTION} Accumulate an option for %X.
369 %X Output the accumulated linker options specified by compilations.
370 %Y Output the accumulated assembler options specified by compilations.
371 %Z Output the accumulated preprocessor options specified by compilations.
372 %a process ASM_SPEC as a spec.
373 This allows config.h to specify part of the spec for running as.
374 %A process ASM_FINAL_SPEC as a spec. A capital A is actually
375 used here. This can be used to run a post-processor after the
376 assembler has done its job.
377 %D Dump out a -L option for each directory in startfile_prefixes.
378 If multilib_dir is set, extra entries are generated with it affixed.
379 %l process LINK_SPEC as a spec.
380 %L process LIB_SPEC as a spec.
381 %M Output multilib_os_dir.
382 %G process LIBGCC_SPEC as a spec.
383 %R Output the concatenation of target_system_root and
384 target_sysroot_suffix.
385 %S process STARTFILE_SPEC as a spec. A capital S is actually used here.
386 %E process ENDFILE_SPEC as a spec. A capital E is actually used here.
387 %C process CPP_SPEC as a spec.
388 %1 process CC1_SPEC as a spec.
389 %2 process CC1PLUS_SPEC as a spec.
390 %* substitute the variable part of a matched option. (See below.)
391 Note that each comma in the substituted string is replaced by
392 a single space.
393 %<S remove all occurrences of -S from the command line.
394 Note - this command is position dependent. % commands in the
395 spec string before this one will see -S, % commands in the
396 spec string after this one will not.
397 %>S Similar to "%<S", but keep it in the GCC command line.
398 %<S* remove all occurrences of all switches beginning with -S from the
399 command line.
400 %:function(args)
401 Call the named function FUNCTION, passing it ARGS. ARGS is
402 first processed as a nested spec string, then split into an
403 argument vector in the usual fashion. The function returns
404 a string which is processed as if it had appeared literally
405 as part of the current spec.
406 %{S} substitutes the -S switch, if that switch was given to GCC.
407 If that switch was not specified, this substitutes nothing.
408 Here S is a metasyntactic variable.
409 %{S*} substitutes all the switches specified to GCC whose names start
410 with -S. This is used for -o, -I, etc; switches that take
411 arguments. GCC considers `-o foo' as being one switch whose
412 name starts with `o'. %{o*} would substitute this text,
413 including the space; thus, two arguments would be generated.
414 %{S*&T*} likewise, but preserve order of S and T options (the order
415 of S and T in the spec is not significant). Can be any number
416 of ampersand-separated variables; for each the wild card is
417 optional. Useful for CPP as %{D*&U*&A*}.
419 %{S:X} substitutes X, if the -S switch was given to GCC.
420 %{!S:X} substitutes X, if the -S switch was NOT given to GCC.
421 %{S*:X} substitutes X if one or more switches whose names start
422 with -S was given to GCC. Normally X is substituted only
423 once, no matter how many such switches appeared. However,
424 if %* appears somewhere in X, then X will be substituted
425 once for each matching switch, with the %* replaced by the
426 part of that switch that matched the '*'.
427 %{.S:X} substitutes X, if processing a file with suffix S.
428 %{!.S:X} substitutes X, if NOT processing a file with suffix S.
429 %{,S:X} substitutes X, if processing a file which will use spec S.
430 %{!,S:X} substitutes X, if NOT processing a file which will use spec S.
432 %{S|T:X} substitutes X if either -S or -T was given to GCC. This may be
433 combined with '!', '.', ',', and '*' as above binding stronger
434 than the OR.
435 If %* appears in X, all of the alternatives must be starred, and
436 only the first matching alternative is substituted.
437 %{S:X; if S was given to GCC, substitutes X;
438 T:Y; else if T was given to GCC, substitutes Y;
439 :D} else substitutes D. There can be as many clauses as you need.
440 This may be combined with '.', '!', ',', '|', and '*' as above.
442 %(Spec) processes a specification defined in a specs file as *Spec:
444 The conditional text X in a %{S:X} or similar construct may contain
445 other nested % constructs or spaces, or even newlines. They are
446 processed as usual, as described above. Trailing white space in X is
447 ignored. White space may also appear anywhere on the left side of the
448 colon in these constructs, except between . or * and the corresponding
449 word.
451 The -O, -f, -g, -m, and -W switches are handled specifically in these
452 constructs. If another value of -O or the negated form of a -f, -m, or
453 -W switch is found later in the command line, the earlier switch
454 value is ignored, except with {S*} where S is just one letter; this
455 passes all matching options.
457 The character | at the beginning of the predicate text is used to indicate
458 that a command should be piped to the following command, but only if -pipe
459 is specified.
461 Note that it is built into GCC which switches take arguments and which
462 do not. You might think it would be useful to generalize this to
463 allow each compiler's spec to say which switches take arguments. But
464 this cannot be done in a consistent fashion. GCC cannot even decide
465 which input files have been specified without knowing which switches
466 take arguments, and it must know which input files to compile in order
467 to tell which compilers to run.
469 GCC also knows implicitly that arguments starting in `-l' are to be
470 treated as compiler output files, and passed to the linker in their
471 proper position among the other output files. */
473 /* Define the macros used for specs %a, %l, %L, %S, %C, %1. */
475 /* config.h can define ASM_SPEC to provide extra args to the assembler
476 or extra switch-translations. */
477 #ifndef ASM_SPEC
478 #define ASM_SPEC ""
479 #endif
481 /* config.h can define ASM_FINAL_SPEC to run a post processor after
482 the assembler has run. */
483 #ifndef ASM_FINAL_SPEC
484 #define ASM_FINAL_SPEC \
485 "%{gsplit-dwarf: \n\
486 objcopy --extract-dwo \
487 %{c:%{o*:%*}%{!o*:%b%O}}%{!c:%U%O} \
488 %{c:%{o*:%:replace-extension(%{o*:%*} .dwo)}%{!o*:%b.dwo}}%{!c:%b.dwo} \n\
489 objcopy --strip-dwo \
490 %{c:%{o*:%*}%{!o*:%b%O}}%{!c:%U%O} \
492 #endif
494 /* config.h can define CPP_SPEC to provide extra args to the C preprocessor
495 or extra switch-translations. */
496 #ifndef CPP_SPEC
497 #define CPP_SPEC ""
498 #endif
500 /* config.h can define CC1_SPEC to provide extra args to cc1 and cc1plus
501 or extra switch-translations. */
502 #ifndef CC1_SPEC
503 #define CC1_SPEC ""
504 #endif
506 /* config.h can define CC1PLUS_SPEC to provide extra args to cc1plus
507 or extra switch-translations. */
508 #ifndef CC1PLUS_SPEC
509 #define CC1PLUS_SPEC ""
510 #endif
512 /* config.h can define LINK_SPEC to provide extra args to the linker
513 or extra switch-translations. */
514 #ifndef LINK_SPEC
515 #define LINK_SPEC ""
516 #endif
518 /* config.h can define LIB_SPEC to override the default libraries. */
519 #ifndef LIB_SPEC
520 #define LIB_SPEC "%{!shared:%{g*:-lg} %{!p:%{!pg:-lc}}%{p:-lc_p}%{pg:-lc_p}}"
521 #endif
523 /* mudflap specs */
524 #ifndef MFWRAP_SPEC
525 /* XXX: valid only for GNU ld */
526 /* XXX: should exactly match hooks provided by libmudflap.a */
527 #define MFWRAP_SPEC " %{static: %{fmudflap|fmudflapth: \
528 --wrap=malloc --wrap=free --wrap=calloc --wrap=realloc\
529 --wrap=mmap --wrap=mmap64 --wrap=munmap --wrap=alloca\
530 } %{fmudflapth: --wrap=pthread_create\
531 }} %{fmudflap|fmudflapth: --wrap=main}"
532 #endif
533 #ifndef MFLIB_SPEC
534 #define MFLIB_SPEC "%{fmudflap|fmudflapth: -export-dynamic}"
535 #endif
537 /* When using -fsplit-stack we need to wrap pthread_create, in order
538 to initialize the stack guard. We always use wrapping, rather than
539 shared library ordering, and we keep the wrapper function in
540 libgcc. This is not yet a real spec, though it could become one;
541 it is currently just stuffed into LINK_SPEC. FIXME: This wrapping
542 only works with GNU ld and gold. FIXME: This is incompatible with
543 -fmudflap when linking statically, which wants to do its own
544 wrapping. */
545 #define STACK_SPLIT_SPEC " %{fsplit-stack: --wrap=pthread_create}"
547 #ifndef LIBASAN_SPEC
548 #ifdef STATIC_LIBASAN_LIBS
549 #define ADD_STATIC_LIBASAN_LIBS \
550 " %{static-libasan:" STATIC_LIBASAN_LIBS "}"
551 #else
552 #define ADD_STATIC_LIBASAN_LIBS
553 #endif
554 #ifdef HAVE_LD_STATIC_DYNAMIC
555 #define LIBASAN_SPEC "%{static-libasan:" LD_STATIC_OPTION \
556 "} -lasan %{static-libasan:" LD_DYNAMIC_OPTION "}" \
557 ADD_STATIC_LIBASAN_LIBS
558 #else
559 #define LIBASAN_SPEC "-lasan" ADD_STATIC_LIBASAN_LIBS
560 #endif
561 #endif
563 #ifndef LIBTSAN_SPEC
564 #ifdef HAVE_LD_STATIC_DYNAMIC
565 #define LIBTSAN_SPEC "%{static-libtsan:" LD_STATIC_OPTION \
566 "} -ltsan %{static-libtsan:" LD_DYNAMIC_OPTION "}"
567 #else
568 #define LIBTSAN_SPEC "-ltsan"
569 #endif
570 #endif
572 /* config.h can define LIBGCC_SPEC to override how and when libgcc.a is
573 included. */
574 #ifndef LIBGCC_SPEC
575 #if defined(REAL_LIBGCC_SPEC)
576 #define LIBGCC_SPEC REAL_LIBGCC_SPEC
577 #elif defined(LINK_LIBGCC_SPECIAL_1)
578 /* Have gcc do the search for libgcc.a. */
579 #define LIBGCC_SPEC "libgcc.a%s"
580 #else
581 #define LIBGCC_SPEC "-lgcc"
582 #endif
583 #endif
585 /* config.h can define STARTFILE_SPEC to override the default crt0 files. */
586 #ifndef STARTFILE_SPEC
587 #define STARTFILE_SPEC \
588 "%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
589 #endif
591 /* config.h can define ENDFILE_SPEC to override the default crtn files. */
592 #ifndef ENDFILE_SPEC
593 #define ENDFILE_SPEC ""
594 #endif
596 #ifndef LINKER_NAME
597 #define LINKER_NAME "collect2"
598 #endif
600 #ifdef HAVE_AS_DEBUG_PREFIX_MAP
601 #define ASM_MAP " %{fdebug-prefix-map=*:--debug-prefix-map %*}"
602 #else
603 #define ASM_MAP ""
604 #endif
606 /* Define ASM_DEBUG_SPEC to be a spec suitable for translating '-g'
607 to the assembler. */
608 #ifndef ASM_DEBUG_SPEC
609 # if defined(DBX_DEBUGGING_INFO) && defined(DWARF2_DEBUGGING_INFO) \
610 && defined(HAVE_AS_GDWARF2_DEBUG_FLAG) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
611 # define ASM_DEBUG_SPEC \
612 (PREFERRED_DEBUGGING_TYPE == DBX_DEBUG \
613 ? "%{!g0:%{gdwarf-2*:--gdwarf2}%{!gdwarf-2*:%{g*:--gstabs}}}" ASM_MAP \
614 : "%{!g0:%{gstabs*:--gstabs}%{!gstabs*:%{g*:--gdwarf2}}}" ASM_MAP)
615 # else
616 # if defined(DBX_DEBUGGING_INFO) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
617 # define ASM_DEBUG_SPEC "%{g*:%{!g0:--gstabs}}" ASM_MAP
618 # endif
619 # if defined(DWARF2_DEBUGGING_INFO) && defined(HAVE_AS_GDWARF2_DEBUG_FLAG)
620 # define ASM_DEBUG_SPEC "%{g*:%{!g0:--gdwarf2}}" ASM_MAP
621 # endif
622 # endif
623 #endif
624 #ifndef ASM_DEBUG_SPEC
625 # define ASM_DEBUG_SPEC ""
626 #endif
628 /* Here is the spec for running the linker, after compiling all files. */
630 /* This is overridable by the target in case they need to specify the
631 -lgcc and -lc order specially, yet not require them to override all
632 of LINK_COMMAND_SPEC. */
633 #ifndef LINK_GCC_C_SEQUENCE_SPEC
634 #define LINK_GCC_C_SEQUENCE_SPEC "%G %L %G"
635 #endif
637 #ifndef LINK_SSP_SPEC
638 #ifdef TARGET_LIBC_PROVIDES_SSP
639 #define LINK_SSP_SPEC "%{fstack-protector:}"
640 #else
641 #define LINK_SSP_SPEC "%{fstack-protector|fstack-protector-all:-lssp_nonshared -lssp}"
642 #endif
643 #endif
645 #ifndef LINK_PIE_SPEC
646 #ifdef HAVE_LD_PIE
647 #define LINK_PIE_SPEC "%{pie:-pie} "
648 #else
649 #define LINK_PIE_SPEC "%{pie:} "
650 #endif
651 #endif
653 #ifndef LINK_BUILDID_SPEC
654 # if defined(HAVE_LD_BUILDID) && defined(ENABLE_LD_BUILDID)
655 # define LINK_BUILDID_SPEC "%{!r:--build-id} "
656 # endif
657 #endif
659 /* Conditional to test whether the LTO plugin is used or not.
660 FIXME: For slim LTO we will need to enable plugin unconditionally. This
661 still cause problems with PLUGIN_LD != LD and when plugin is built but
662 not useable. For GCC 4.6 we don't support slim LTO and thus we can enable
663 plugin only when LTO is enabled. We still honor explicit
664 -fuse-linker-plugin if the linker used understands -plugin. */
666 /* The linker has some plugin support. */
667 #if HAVE_LTO_PLUGIN > 0
668 /* The linker used has full plugin support, use LTO plugin by default. */
669 #if HAVE_LTO_PLUGIN == 2
670 #define PLUGIN_COND "!fno-use-linker-plugin:%{flto|flto=*|fuse-linker-plugin"
671 #define PLUGIN_COND_CLOSE "}"
672 #else
673 /* The linker used has limited plugin support, use LTO plugin with explicit
674 -fuse-linker-plugin. */
675 #define PLUGIN_COND "fuse-linker-plugin"
676 #define PLUGIN_COND_CLOSE ""
677 #endif
678 #define LINK_PLUGIN_SPEC \
679 "%{"PLUGIN_COND": \
680 -plugin %(linker_plugin_file) \
681 -plugin-opt=%(lto_wrapper) \
682 -plugin-opt=-fresolution=%u.res \
683 %{!nostdlib:%{!nodefaultlibs:%:pass-through-libs(%(link_gcc_c_sequence))}} \
684 }"PLUGIN_COND_CLOSE
685 #else
686 /* The linker used doesn't support -plugin, reject -fuse-linker-plugin. */
687 #define LINK_PLUGIN_SPEC "%{fuse-linker-plugin:\
688 %e-fuse-linker-plugin is not supported in this configuration}"
689 #endif
692 /* -u* was put back because both BSD and SysV seem to support it. */
693 /* %{static:} simply prevents an error message if the target machine
694 doesn't handle -static. */
695 /* We want %{T*} after %{L*} and %D so that it can be used to specify linker
696 scripts which exist in user specified directories, or in standard
697 directories. */
698 /* We pass any -flto flags on to the linker, which is expected
699 to understand them. In practice, this means it had better be collect2. */
700 /* %{e*} includes -export-dynamic; see comment in common.opt. */
701 #ifndef LINK_COMMAND_SPEC
702 #define LINK_COMMAND_SPEC "\
703 %{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
704 %(linker) " \
705 LINK_PLUGIN_SPEC \
706 "%{flto|flto=*:%<fcompare-debug*} \
707 %{flto} %{flto=*} %l " LINK_PIE_SPEC \
708 "%X %{o*} %{e*} %{N} %{n} %{r}\
709 %{s} %{t} %{u*} %{z} %{Z} %{!nostdlib:%{!nostartfiles:%S}}\
710 %{!nostdlib:%{!nostartfiles:%{fupc-link:%:include(upc-crtbegin.spec)%(upc_crtbegin)}}}\
711 %{static:} %{L*} %(mfwrap) %(link_libgcc) %o\
712 %{fopenmp|ftree-parallelize-loops=*:%:include(libgomp.spec)%(link_gomp)}\
713 %{fgnu-tm:%:include(libitm.spec)%(link_itm)}\
714 %{fupc-link:%:include(libgupc.spec)%(link_upc)}\
715 %(mflib) " STACK_SPLIT_SPEC "\
716 %{fprofile-arcs|fprofile-generate*|coverage:-lgcov}\
717 %{fsanitize=address:" LIBASAN_SPEC "%{static:%ecannot specify -static with -fsanitize=address}}\
718 %{fsanitize=thread:" LIBTSAN_SPEC "}\
719 %{!nostdlib:%{!nodefaultlibs:%(link_ssp) %(link_gcc_c_sequence)}}\
720 %{!nostdlib:%{!nostartfiles:%{fupc-link:%:include(upc-crtend.spec)%(upc_crtend)}}}\
721 %{!nostdlib:%{!nostartfiles:%E}} %{T*} }}}}}}"
722 #endif
724 #ifndef LINK_LIBGCC_SPEC
725 /* Generate -L options for startfile prefix list. */
726 # define LINK_LIBGCC_SPEC "%D"
727 #endif
729 #ifndef STARTFILE_PREFIX_SPEC
730 # define STARTFILE_PREFIX_SPEC ""
731 #endif
733 #ifndef SYSROOT_SPEC
734 # define SYSROOT_SPEC "--sysroot=%R"
735 #endif
737 #ifndef SYSROOT_SUFFIX_SPEC
738 # define SYSROOT_SUFFIX_SPEC ""
739 #endif
741 #ifndef SYSROOT_HEADERS_SUFFIX_SPEC
742 # define SYSROOT_HEADERS_SUFFIX_SPEC ""
743 #endif
745 static const char *asm_debug = ASM_DEBUG_SPEC;
746 static const char *cpp_spec = CPP_SPEC;
747 static const char *cc1_spec = CC1_SPEC;
748 static const char *cc1plus_spec = CC1PLUS_SPEC;
749 static const char *link_gcc_c_sequence_spec = LINK_GCC_C_SEQUENCE_SPEC;
750 static const char *link_ssp_spec = LINK_SSP_SPEC;
751 static const char *asm_spec = ASM_SPEC;
752 static const char *asm_final_spec = ASM_FINAL_SPEC;
753 static const char *link_spec = LINK_SPEC;
754 static const char *lib_spec = LIB_SPEC;
755 static const char *mfwrap_spec = MFWRAP_SPEC;
756 static const char *mflib_spec = MFLIB_SPEC;
757 static const char *link_gomp_spec = "";
758 static const char *upc_crtbegin_spec = "";
759 static const char *link_upc_spec = "";
760 static const char *upc_crtend_spec = "";
761 static const char *libgcc_spec = LIBGCC_SPEC;
762 static const char *endfile_spec = ENDFILE_SPEC;
763 static const char *startfile_spec = STARTFILE_SPEC;
764 static const char *linker_name_spec = LINKER_NAME;
765 static const char *linker_plugin_file_spec = "";
766 static const char *lto_wrapper_spec = "";
767 static const char *lto_gcc_spec = "";
768 static const char *link_command_spec = LINK_COMMAND_SPEC;
769 static const char *link_libgcc_spec = LINK_LIBGCC_SPEC;
770 static const char *startfile_prefix_spec = STARTFILE_PREFIX_SPEC;
771 static const char *sysroot_spec = SYSROOT_SPEC;
772 static const char *sysroot_suffix_spec = SYSROOT_SUFFIX_SPEC;
773 static const char *sysroot_hdrs_suffix_spec = SYSROOT_HEADERS_SUFFIX_SPEC;
774 static const char *self_spec = "";
776 /* Standard options to cpp, cc1, and as, to reduce duplication in specs.
777 There should be no need to override these in target dependent files,
778 but we need to copy them to the specs file so that newer versions
779 of the GCC driver can correctly drive older tool chains with the
780 appropriate -B options. */
782 /* When cpplib handles traditional preprocessing, get rid of this, and
783 call cc1 (or cc1obj in objc/lang-specs.h) from the main specs so
784 that we default the front end language better. */
785 static const char *trad_capable_cpp =
786 "cc1 -E %{traditional|traditional-cpp:-traditional-cpp}";
788 /* We don't wrap .d files in %W{} since a missing .d file, and
789 therefore no dependency entry, confuses make into thinking a .o
790 file that happens to exist is up-to-date. */
791 static const char *cpp_unique_options =
792 "%{!Q:-quiet} %{nostdinc*} %{C} %{CC} %{v} %{I*&F*} %{P} %I\
793 %{MD:-MD %{!o:%b.d}%{o*:%.d%*}}\
794 %{MMD:-MMD %{!o:%b.d}%{o*:%.d%*}}\
795 %{M} %{MM} %{MF*} %{MG} %{MP} %{MQ*} %{MT*}\
796 %{!E:%{!M:%{!MM:%{!MT:%{!MQ:%{MD|MMD:%{o*:-MQ %*}}}}}}}\
797 %{remap} %{g3|ggdb3|gstabs3|gcoff3|gxcoff3|gvms3:-dD}\
798 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
799 %{H} %C %{D*&U*&A*} %{i*} %Z %i\
800 %{fmudflap:-D_MUDFLAP -include mf-runtime.h}\
801 %{fmudflapth:-D_MUDFLAP -D_MUDFLAPTH -include mf-runtime.h}\
802 %{E|M|MM:%W{o*}}";
804 /* This contains cpp options which are common with cc1_options and are passed
805 only when preprocessing only to avoid duplication. We pass the cc1 spec
806 options to the preprocessor so that it the cc1 spec may manipulate
807 options used to set target flags. Those special target flags settings may
808 in turn cause preprocessor symbols to be defined specially. */
809 static const char *cpp_options =
810 "%(cpp_unique_options) %1 %{m*} %{std*&ansi&trigraphs} %{W*&pedantic*} %{w}\
811 %{f*} %{g*:%{!g0:%{g*} %{!fno-working-directory:-fworking-directory}}} %{O*}\
812 %{undef} %{save-temps*:-fpch-preprocess}";
814 /* This contains cpp options which are not passed when the preprocessor
815 output will be used by another program. */
816 static const char *cpp_debug_options = "%{d*}";
818 /* NB: This is shared amongst all front-ends, except for Ada. */
819 static const char *cc1_options =
820 "%{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
821 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
822 %1 %{!Q:-quiet} %{!dumpbase:-dumpbase %B} %{d*} %{m*} %{aux-info*}\
823 %{fcompare-debug-second:%:compare-debug-auxbase-opt(%b)} \
824 %{!fcompare-debug-second:%{c|S:%{o*:-auxbase-strip %*}%{!o*:-auxbase %b}}}%{!c:%{!S:-auxbase %b}} \
825 %{g*} %{O*} %{W*&pedantic*} %{w} %{std*&ansi&trigraphs}\
826 %{v:-version} %{pg:-p} %{p} %{f*} %{undef}\
827 %{Qn:-fno-ident} %{Qy:} %{-help:--help}\
828 %{-target-help:--target-help}\
829 %{-version:--version}\
830 %{-help=*:--help=%*}\
831 %{!fsyntax-only:%{S:%W{o*}%{!o*:-o %b.s}}}\
832 %{fsyntax-only:-o %j} %{-param*}\
833 %{fmudflap|fmudflapth:-fno-builtin -fno-merge-constants}\
834 %{coverage:-fprofile-arcs -ftest-coverage}";
836 static const char *upc_options = "-lang-upc \
837 %{!fno-upc-pre-include:-include gcc-upc.h}";
839 static const char *asm_options =
840 "%{-target-help:%:print-asm-header()} "
841 #if HAVE_GNU_AS
842 /* If GNU AS is used, then convert -w (no warnings), -I, and -v
843 to the assembler equivalents. */
844 "%{v} %{w:-W} %{I*} "
845 #endif
846 "%a %Y %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}";
848 static const char *invoke_as =
849 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
850 "%{!fwpa:\
851 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
852 %{!S:-o %|.s |\n as %(asm_options) %|.s %A }\
854 #else
855 "%{!fwpa:\
856 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
857 %{!S:-o %|.s |\n as %(asm_options) %m.s %A }\
859 #endif
861 /* Some compilers have limits on line lengths, and the multilib_select
862 and/or multilib_matches strings can be very long, so we build them at
863 run time. */
864 static struct obstack multilib_obstack;
865 static const char *multilib_select;
866 static const char *multilib_matches;
867 static const char *multilib_defaults;
868 static const char *multilib_exclusions;
870 /* Check whether a particular argument is a default argument. */
872 #ifndef MULTILIB_DEFAULTS
873 #define MULTILIB_DEFAULTS { "" }
874 #endif
876 static const char *const multilib_defaults_raw[] = MULTILIB_DEFAULTS;
878 #ifndef DRIVER_SELF_SPECS
879 #define DRIVER_SELF_SPECS ""
880 #endif
882 /* Adding -fopenmp should imply pthreads. This is particularly important
883 for targets that use different start files and suchlike. */
884 #ifndef GOMP_SELF_SPECS
885 #define GOMP_SELF_SPECS "%{fopenmp|ftree-parallelize-loops=*: -pthread}"
886 #endif
888 /* Likewise for -fgnu-tm. */
889 #ifndef GTM_SELF_SPECS
890 #define GTM_SELF_SPECS "%{fgnu-tm: -pthread}"
891 #endif
893 static const char *const driver_self_specs[] = {
894 "%{fdump-final-insns:-fdump-final-insns=.} %<fdump-final-insns",
895 DRIVER_SELF_SPECS, CONFIGURE_SPECS, GOMP_SELF_SPECS, GTM_SELF_SPECS
898 #ifndef OPTION_DEFAULT_SPECS
899 #define OPTION_DEFAULT_SPECS { "", "" }
900 #endif
902 struct default_spec
904 const char *name;
905 const char *spec;
908 static const struct default_spec
909 option_default_specs[] = { OPTION_DEFAULT_SPECS };
911 struct user_specs
913 struct user_specs *next;
914 const char *filename;
917 static struct user_specs *user_specs_head, *user_specs_tail;
920 /* Record the mapping from file suffixes for compilation specs. */
922 struct compiler
924 const char *suffix; /* Use this compiler for input files
925 whose names end in this suffix. */
927 const char *spec; /* To use this compiler, run this spec. */
929 const char *cpp_spec; /* If non-NULL, substitute this spec
930 for `%C', rather than the usual
931 cpp_spec. */
932 const int combinable; /* If nonzero, compiler can deal with
933 multiple source files at once (IMA). */
934 const int needs_preprocessing; /* If nonzero, source files need to
935 be run through a preprocessor. */
938 /* Pointer to a vector of `struct compiler' that gives the spec for
939 compiling a file, based on its suffix.
940 A file that does not end in any of these suffixes will be passed
941 unchanged to the loader and nothing else will be done to it.
943 An entry containing two 0s is used to terminate the vector.
945 If multiple entries match a file, the last matching one is used. */
947 static struct compiler *compilers;
949 /* Number of entries in `compilers', not counting the null terminator. */
951 static int n_compilers;
953 /* The default list of file name suffixes and their compilation specs. */
955 static const struct compiler default_compilers[] =
957 /* Add lists of suffixes of known languages here. If those languages
958 were not present when we built the driver, we will hit these copies
959 and be given a more meaningful error than "file not used since
960 linking is not done". */
961 {".m", "#Objective-C", 0, 0, 0}, {".mi", "#Objective-C", 0, 0, 0},
962 {".mm", "#Objective-C++", 0, 0, 0}, {".M", "#Objective-C++", 0, 0, 0},
963 {".mii", "#Objective-C++", 0, 0, 0},
964 {".cc", "#C++", 0, 0, 0}, {".cxx", "#C++", 0, 0, 0},
965 {".cpp", "#C++", 0, 0, 0}, {".cp", "#C++", 0, 0, 0},
966 {".c++", "#C++", 0, 0, 0}, {".C", "#C++", 0, 0, 0},
967 {".CPP", "#C++", 0, 0, 0}, {".ii", "#C++", 0, 0, 0},
968 {".ads", "#Ada", 0, 0, 0}, {".adb", "#Ada", 0, 0, 0},
969 {".f", "#Fortran", 0, 0, 0}, {".F", "#Fortran", 0, 0, 0},
970 {".for", "#Fortran", 0, 0, 0}, {".FOR", "#Fortran", 0, 0, 0},
971 {".ftn", "#Fortran", 0, 0, 0}, {".FTN", "#Fortran", 0, 0, 0},
972 {".fpp", "#Fortran", 0, 0, 0}, {".FPP", "#Fortran", 0, 0, 0},
973 {".f90", "#Fortran", 0, 0, 0}, {".F90", "#Fortran", 0, 0, 0},
974 {".f95", "#Fortran", 0, 0, 0}, {".F95", "#Fortran", 0, 0, 0},
975 {".f03", "#Fortran", 0, 0, 0}, {".F03", "#Fortran", 0, 0, 0},
976 {".f08", "#Fortran", 0, 0, 0}, {".F08", "#Fortran", 0, 0, 0},
977 {".r", "#Ratfor", 0, 0, 0},
978 {".p", "#Pascal", 0, 0, 0}, {".pas", "#Pascal", 0, 0, 0},
979 {".java", "#Java", 0, 0, 0}, {".class", "#Java", 0, 0, 0},
980 {".upc", "#UPC", 0, 0, 0},
981 {".zip", "#Java", 0, 0, 0}, {".jar", "#Java", 0, 0, 0},
982 {".go", "#Go", 0, 1, 0},
983 /* Next come the entries for C. */
984 {".c", "@c", 0, 0, 1},
985 {"@c",
986 /* cc1 has an integrated ISO C preprocessor. We should invoke the
987 external preprocessor if -save-temps is given. */
988 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
989 %{!E:%{!M:%{!MM:\
990 %{traditional:\
991 %eGNU C no longer supports -traditional without -E}\
992 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
993 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
994 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
995 %(cc1_options)}\
996 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
997 cc1 %(cpp_unique_options) %(cc1_options)}}}\
998 %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 1},
999 {"-",
1000 "%{!E:%e-E or -x required when input is from standard input}\
1001 %(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)", 0, 0, 0},
1002 {".h", "@c-header", 0, 0, 0},
1003 {"@c-header",
1004 /* cc1 has an integrated ISO C preprocessor. We should invoke the
1005 external preprocessor if -save-temps is given. */
1006 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
1007 %{!E:%{!M:%{!MM:\
1008 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
1009 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
1010 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
1011 %(cc1_options)\
1012 %{!fdump-ada-spec*:-o %g.s %{!o*:--output-pch=%i.gch}\
1013 %W{o*:--output-pch=%*}}%V}\
1014 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
1015 cc1 %(cpp_unique_options) %(cc1_options)\
1016 %{!fdump-ada-spec*:-o %g.s %{!o*:--output-pch=%i.gch}\
1017 %W{o*:--output-pch=%*}}%V}}}}}}", 0, 0, 0},
1018 {".i", "@cpp-output", 0, 0, 0},
1019 {"@cpp-output",
1020 "%{!M:%{!MM:%{!E:cc1 -fpreprocessed %i %(cc1_options) %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 0},
1021 {".s", "@assembler", 0, 0, 0},
1022 {"@assembler",
1023 "%{!M:%{!MM:%{!E:%{!S:as %(asm_debug) %(asm_options) %i %A }}}}", 0, 0, 0},
1024 {".sx", "@assembler-with-cpp", 0, 0, 0},
1025 {".S", "@assembler-with-cpp", 0, 0, 0},
1026 {"@assembler-with-cpp",
1027 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
1028 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
1029 %{E|M|MM:%(cpp_debug_options)}\
1030 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
1031 as %(asm_debug) %(asm_options) %|.s %A }}}}"
1032 #else
1033 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
1034 %{E|M|MM:%(cpp_debug_options)}\
1035 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
1036 as %(asm_debug) %(asm_options) %m.s %A }}}}"
1037 #endif
1038 , 0, 0, 0},
1040 #include "specs.h"
1041 /* Mark end of table. */
1042 {0, 0, 0, 0, 0}
1045 /* Number of elements in default_compilers, not counting the terminator. */
1047 static const int n_default_compilers = ARRAY_SIZE (default_compilers) - 1;
1049 typedef char *char_p; /* For DEF_VEC_P. */
1051 /* A vector of options to give to the linker.
1052 These options are accumulated by %x,
1053 and substituted into the linker command with %X. */
1054 static vec<char_p> linker_options;
1056 /* A vector of options to give to the assembler.
1057 These options are accumulated by -Wa,
1058 and substituted into the assembler command with %Y. */
1059 static vec<char_p> assembler_options;
1061 /* A vector of options to give to the preprocessor.
1062 These options are accumulated by -Wp,
1063 and substituted into the preprocessor command with %Z. */
1064 static vec<char_p> preprocessor_options;
1066 static char *
1067 skip_whitespace (char *p)
1069 while (1)
1071 /* A fully-blank line is a delimiter in the SPEC file and shouldn't
1072 be considered whitespace. */
1073 if (p[0] == '\n' && p[1] == '\n' && p[2] == '\n')
1074 return p + 1;
1075 else if (*p == '\n' || *p == ' ' || *p == '\t')
1076 p++;
1077 else if (*p == '#')
1079 while (*p != '\n')
1080 p++;
1081 p++;
1083 else
1084 break;
1087 return p;
1089 /* Structures to keep track of prefixes to try when looking for files. */
1091 struct prefix_list
1093 const char *prefix; /* String to prepend to the path. */
1094 struct prefix_list *next; /* Next in linked list. */
1095 int require_machine_suffix; /* Don't use without machine_suffix. */
1096 /* 2 means try both machine_suffix and just_machine_suffix. */
1097 int priority; /* Sort key - priority within list. */
1098 int os_multilib; /* 1 if OS multilib scheme should be used,
1099 0 for GCC multilib scheme. */
1102 struct path_prefix
1104 struct prefix_list *plist; /* List of prefixes to try */
1105 int max_len; /* Max length of a prefix in PLIST */
1106 const char *name; /* Name of this list (used in config stuff) */
1109 /* List of prefixes to try when looking for executables. */
1111 static struct path_prefix exec_prefixes = { 0, 0, "exec" };
1113 /* List of prefixes to try when looking for startup (crt0) files. */
1115 static struct path_prefix startfile_prefixes = { 0, 0, "startfile" };
1117 /* List of prefixes to try when looking for include files. */
1119 static struct path_prefix include_prefixes = { 0, 0, "include" };
1121 /* Suffix to attach to directories searched for commands.
1122 This looks like `MACHINE/VERSION/'. */
1124 static const char *machine_suffix = 0;
1126 /* Suffix to attach to directories searched for commands.
1127 This is just `MACHINE/'. */
1129 static const char *just_machine_suffix = 0;
1131 /* Adjusted value of GCC_EXEC_PREFIX envvar. */
1133 static const char *gcc_exec_prefix;
1135 /* Adjusted value of standard_libexec_prefix. */
1137 static const char *gcc_libexec_prefix;
1139 /* Default prefixes to attach to command names. */
1141 #ifndef STANDARD_STARTFILE_PREFIX_1
1142 #define STANDARD_STARTFILE_PREFIX_1 "/lib/"
1143 #endif
1144 #ifndef STANDARD_STARTFILE_PREFIX_2
1145 #define STANDARD_STARTFILE_PREFIX_2 "/usr/lib/"
1146 #endif
1148 #ifdef CROSS_DIRECTORY_STRUCTURE /* Don't use these prefixes for a cross compiler. */
1149 #undef MD_EXEC_PREFIX
1150 #undef MD_STARTFILE_PREFIX
1151 #undef MD_STARTFILE_PREFIX_1
1152 #endif
1154 /* If no prefixes defined, use the null string, which will disable them. */
1155 #ifndef MD_EXEC_PREFIX
1156 #define MD_EXEC_PREFIX ""
1157 #endif
1158 #ifndef MD_STARTFILE_PREFIX
1159 #define MD_STARTFILE_PREFIX ""
1160 #endif
1161 #ifndef MD_STARTFILE_PREFIX_1
1162 #define MD_STARTFILE_PREFIX_1 ""
1163 #endif
1165 /* These directories are locations set at configure-time based on the
1166 --prefix option provided to configure. Their initializers are
1167 defined in Makefile.in. These paths are not *directly* used when
1168 gcc_exec_prefix is set because, in that case, we know where the
1169 compiler has been installed, and use paths relative to that
1170 location instead. */
1171 static const char *const standard_exec_prefix = STANDARD_EXEC_PREFIX;
1172 static const char *const standard_libexec_prefix = STANDARD_LIBEXEC_PREFIX;
1173 static const char *const standard_bindir_prefix = STANDARD_BINDIR_PREFIX;
1174 static const char *const standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
1176 /* For native compilers, these are well-known paths containing
1177 components that may be provided by the system. For cross
1178 compilers, these paths are not used. */
1179 static const char *md_exec_prefix = MD_EXEC_PREFIX;
1180 static const char *md_startfile_prefix = MD_STARTFILE_PREFIX;
1181 static const char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
1182 static const char *const standard_startfile_prefix_1
1183 = STANDARD_STARTFILE_PREFIX_1;
1184 static const char *const standard_startfile_prefix_2
1185 = STANDARD_STARTFILE_PREFIX_2;
1187 /* A relative path to be used in finding the location of tools
1188 relative to the driver. */
1189 static const char *const tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
1191 /* Subdirectory to use for locating libraries. Set by
1192 set_multilib_dir based on the compilation options. */
1194 static const char *multilib_dir;
1196 /* Subdirectory to use for locating libraries in OS conventions. Set by
1197 set_multilib_dir based on the compilation options. */
1199 static const char *multilib_os_dir;
1201 /* Subdirectory to use for locating libraries in multiarch conventions. Set by
1202 set_multilib_dir based on the compilation options. */
1204 static const char *multiarch_dir;
1206 /* Structure to keep track of the specs that have been defined so far.
1207 These are accessed using %(specname) in a compiler or link
1208 spec. */
1210 struct spec_list
1212 /* The following 2 fields must be first */
1213 /* to allow EXTRA_SPECS to be initialized */
1214 const char *name; /* name of the spec. */
1215 const char *ptr; /* available ptr if no static pointer */
1217 /* The following fields are not initialized */
1218 /* by EXTRA_SPECS */
1219 const char **ptr_spec; /* pointer to the spec itself. */
1220 struct spec_list *next; /* Next spec in linked list. */
1221 int name_len; /* length of the name */
1222 bool user_p; /* whether string come from file spec. */
1223 bool alloc_p; /* whether string was allocated */
1226 #define INIT_STATIC_SPEC(NAME,PTR) \
1227 { NAME, NULL, PTR, (struct spec_list *) 0, sizeof (NAME) - 1, false, false }
1229 /* List of statically defined specs. */
1230 static struct spec_list static_specs[] =
1232 INIT_STATIC_SPEC ("asm", &asm_spec),
1233 INIT_STATIC_SPEC ("asm_debug", &asm_debug),
1234 INIT_STATIC_SPEC ("asm_final", &asm_final_spec),
1235 INIT_STATIC_SPEC ("asm_options", &asm_options),
1236 INIT_STATIC_SPEC ("invoke_as", &invoke_as),
1237 INIT_STATIC_SPEC ("cpp", &cpp_spec),
1238 INIT_STATIC_SPEC ("cpp_options", &cpp_options),
1239 INIT_STATIC_SPEC ("cpp_debug_options", &cpp_debug_options),
1240 INIT_STATIC_SPEC ("cpp_unique_options", &cpp_unique_options),
1241 INIT_STATIC_SPEC ("trad_capable_cpp", &trad_capable_cpp),
1242 INIT_STATIC_SPEC ("cc1", &cc1_spec),
1243 INIT_STATIC_SPEC ("cc1_options", &cc1_options),
1244 INIT_STATIC_SPEC ("upc_options", &upc_options),
1245 INIT_STATIC_SPEC ("cc1plus", &cc1plus_spec),
1246 INIT_STATIC_SPEC ("link_gcc_c_sequence", &link_gcc_c_sequence_spec),
1247 INIT_STATIC_SPEC ("link_ssp", &link_ssp_spec),
1248 INIT_STATIC_SPEC ("endfile", &endfile_spec),
1249 INIT_STATIC_SPEC ("link", &link_spec),
1250 INIT_STATIC_SPEC ("lib", &lib_spec),
1251 INIT_STATIC_SPEC ("mfwrap", &mfwrap_spec),
1252 INIT_STATIC_SPEC ("mflib", &mflib_spec),
1253 INIT_STATIC_SPEC ("link_gomp", &link_gomp_spec),
1254 INIT_STATIC_SPEC ("upc_crtbegin", &upc_crtbegin_spec),
1255 INIT_STATIC_SPEC ("link_upc", &link_upc_spec),
1256 INIT_STATIC_SPEC ("upc_crtend", &upc_crtend_spec),
1257 INIT_STATIC_SPEC ("libgcc", &libgcc_spec),
1258 INIT_STATIC_SPEC ("startfile", &startfile_spec),
1259 INIT_STATIC_SPEC ("cross_compile", &cross_compile),
1260 INIT_STATIC_SPEC ("version", &compiler_version),
1261 INIT_STATIC_SPEC ("multilib", &multilib_select),
1262 INIT_STATIC_SPEC ("multilib_defaults", &multilib_defaults),
1263 INIT_STATIC_SPEC ("multilib_extra", &multilib_extra),
1264 INIT_STATIC_SPEC ("multilib_matches", &multilib_matches),
1265 INIT_STATIC_SPEC ("multilib_exclusions", &multilib_exclusions),
1266 INIT_STATIC_SPEC ("multilib_options", &multilib_options),
1267 INIT_STATIC_SPEC ("linker", &linker_name_spec),
1268 INIT_STATIC_SPEC ("linker_plugin_file", &linker_plugin_file_spec),
1269 INIT_STATIC_SPEC ("lto_wrapper", &lto_wrapper_spec),
1270 INIT_STATIC_SPEC ("lto_gcc", &lto_gcc_spec),
1271 INIT_STATIC_SPEC ("link_libgcc", &link_libgcc_spec),
1272 INIT_STATIC_SPEC ("md_exec_prefix", &md_exec_prefix),
1273 INIT_STATIC_SPEC ("md_startfile_prefix", &md_startfile_prefix),
1274 INIT_STATIC_SPEC ("md_startfile_prefix_1", &md_startfile_prefix_1),
1275 INIT_STATIC_SPEC ("startfile_prefix_spec", &startfile_prefix_spec),
1276 INIT_STATIC_SPEC ("sysroot_spec", &sysroot_spec),
1277 INIT_STATIC_SPEC ("sysroot_suffix_spec", &sysroot_suffix_spec),
1278 INIT_STATIC_SPEC ("sysroot_hdrs_suffix_spec", &sysroot_hdrs_suffix_spec),
1279 INIT_STATIC_SPEC ("self_spec", &self_spec),
1282 #ifdef EXTRA_SPECS /* additional specs needed */
1283 /* Structure to keep track of just the first two args of a spec_list.
1284 That is all that the EXTRA_SPECS macro gives us. */
1285 struct spec_list_1
1287 const char *const name;
1288 const char *const ptr;
1291 static const struct spec_list_1 extra_specs_1[] = { EXTRA_SPECS };
1292 static struct spec_list *extra_specs = (struct spec_list *) 0;
1293 #endif
1295 /* List of dynamically allocates specs that have been defined so far. */
1297 static struct spec_list *specs = (struct spec_list *) 0;
1299 /* List of static spec functions. */
1301 static const struct spec_function static_spec_functions[] =
1303 { "getenv", getenv_spec_function },
1304 { "if-exists", if_exists_spec_function },
1305 { "if-exists-else", if_exists_else_spec_function },
1306 { "replace-outfile", replace_outfile_spec_function },
1307 { "remove-outfile", remove_outfile_spec_function },
1308 { "version-compare", version_compare_spec_function },
1309 { "include", include_spec_function },
1310 { "find-file", find_file_spec_function },
1311 { "find-plugindir", find_plugindir_spec_function },
1312 { "print-asm-header", print_asm_header_spec_function },
1313 { "compare-debug-dump-opt", compare_debug_dump_opt_spec_function },
1314 { "compare-debug-self-opt", compare_debug_self_opt_spec_function },
1315 { "compare-debug-auxbase-opt", compare_debug_auxbase_opt_spec_function },
1316 { "pass-through-libs", pass_through_libs_spec_func },
1317 { "replace-extension", replace_extension_spec_func },
1318 #ifdef EXTRA_SPEC_FUNCTIONS
1319 EXTRA_SPEC_FUNCTIONS
1320 #endif
1321 { 0, 0 }
1324 static int processing_spec_function;
1326 /* Add appropriate libgcc specs to OBSTACK, taking into account
1327 various permutations of -shared-libgcc, -shared, and such. */
1329 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1331 #ifndef USE_LD_AS_NEEDED
1332 #define USE_LD_AS_NEEDED 0
1333 #endif
1335 static void
1336 init_gcc_specs (struct obstack *obstack, const char *shared_name,
1337 const char *static_name, const char *eh_name)
1339 char *buf;
1341 buf = concat ("%{static|static-libgcc:", static_name, " ", eh_name, "}"
1342 "%{!static:%{!static-libgcc:"
1343 #if USE_LD_AS_NEEDED
1344 "%{!shared-libgcc:",
1345 static_name, " --as-needed ", shared_name, " --no-as-needed"
1347 "%{shared-libgcc:",
1348 shared_name, "%{!shared: ", static_name, "}"
1350 #else
1351 "%{!shared:"
1352 "%{!shared-libgcc:", static_name, " ", eh_name, "}"
1353 "%{shared-libgcc:", shared_name, " ", static_name, "}"
1355 #ifdef LINK_EH_SPEC
1356 "%{shared:"
1357 "%{shared-libgcc:", shared_name, "}"
1358 "%{!shared-libgcc:", static_name, "}"
1360 #else
1361 "%{shared:", shared_name, "}"
1362 #endif
1363 #endif
1364 "}}", NULL);
1366 obstack_grow (obstack, buf, strlen (buf));
1367 free (buf);
1369 #endif /* ENABLE_SHARED_LIBGCC */
1371 /* Initialize the specs lookup routines. */
1373 static void
1374 init_spec (void)
1376 struct spec_list *next = (struct spec_list *) 0;
1377 struct spec_list *sl = (struct spec_list *) 0;
1378 int i;
1380 if (specs)
1381 return; /* Already initialized. */
1383 if (verbose_flag)
1384 fnotice (stderr, "Using built-in specs.\n");
1386 #ifdef EXTRA_SPECS
1387 extra_specs = XCNEWVEC (struct spec_list, ARRAY_SIZE (extra_specs_1));
1389 for (i = ARRAY_SIZE (extra_specs_1) - 1; i >= 0; i--)
1391 sl = &extra_specs[i];
1392 sl->name = extra_specs_1[i].name;
1393 sl->ptr = extra_specs_1[i].ptr;
1394 sl->next = next;
1395 sl->name_len = strlen (sl->name);
1396 sl->ptr_spec = &sl->ptr;
1397 next = sl;
1399 #endif
1401 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1403 sl = &static_specs[i];
1404 sl->next = next;
1405 next = sl;
1408 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1409 /* ??? If neither -shared-libgcc nor --static-libgcc was
1410 seen, then we should be making an educated guess. Some proposed
1411 heuristics for ELF include:
1413 (1) If "-Wl,--export-dynamic", then it's a fair bet that the
1414 program will be doing dynamic loading, which will likely
1415 need the shared libgcc.
1417 (2) If "-ldl", then it's also a fair bet that we're doing
1418 dynamic loading.
1420 (3) For each ET_DYN we're linking against (either through -lfoo
1421 or /some/path/foo.so), check to see whether it or one of
1422 its dependencies depends on a shared libgcc.
1424 (4) If "-shared"
1426 If the runtime is fixed to look for program headers instead
1427 of calling __register_frame_info at all, for each object,
1428 use the shared libgcc if any EH symbol referenced.
1430 If crtstuff is fixed to not invoke __register_frame_info
1431 automatically, for each object, use the shared libgcc if
1432 any non-empty unwind section found.
1434 Doing any of this probably requires invoking an external program to
1435 do the actual object file scanning. */
1437 const char *p = libgcc_spec;
1438 int in_sep = 1;
1440 /* Transform the extant libgcc_spec into one that uses the shared libgcc
1441 when given the proper command line arguments. */
1442 while (*p)
1444 if (in_sep && *p == '-' && strncmp (p, "-lgcc", 5) == 0)
1446 init_gcc_specs (&obstack,
1447 "-lgcc_s"
1448 #ifdef USE_LIBUNWIND_EXCEPTIONS
1449 " -lunwind"
1450 #endif
1452 "-lgcc",
1453 "-lgcc_eh"
1454 #ifdef USE_LIBUNWIND_EXCEPTIONS
1455 # ifdef HAVE_LD_STATIC_DYNAMIC
1456 " %{!static:" LD_STATIC_OPTION "} -lunwind"
1457 " %{!static:" LD_DYNAMIC_OPTION "}"
1458 # else
1459 " -lunwind"
1460 # endif
1461 #endif
1464 p += 5;
1465 in_sep = 0;
1467 else if (in_sep && *p == 'l' && strncmp (p, "libgcc.a%s", 10) == 0)
1469 /* Ug. We don't know shared library extensions. Hope that
1470 systems that use this form don't do shared libraries. */
1471 init_gcc_specs (&obstack,
1472 "-lgcc_s",
1473 "libgcc.a%s",
1474 "libgcc_eh.a%s"
1475 #ifdef USE_LIBUNWIND_EXCEPTIONS
1476 " -lunwind"
1477 #endif
1479 p += 10;
1480 in_sep = 0;
1482 else
1484 obstack_1grow (&obstack, *p);
1485 in_sep = (*p == ' ');
1486 p += 1;
1490 obstack_1grow (&obstack, '\0');
1491 libgcc_spec = XOBFINISH (&obstack, const char *);
1493 #endif
1494 #ifdef USE_AS_TRADITIONAL_FORMAT
1495 /* Prepend "--traditional-format" to whatever asm_spec we had before. */
1497 static const char tf[] = "--traditional-format ";
1498 obstack_grow (&obstack, tf, sizeof(tf) - 1);
1499 obstack_grow0 (&obstack, asm_spec, strlen (asm_spec));
1500 asm_spec = XOBFINISH (&obstack, const char *);
1502 #endif
1504 #if defined LINK_EH_SPEC || defined LINK_BUILDID_SPEC || \
1505 defined LINKER_HASH_STYLE
1506 # ifdef LINK_BUILDID_SPEC
1507 /* Prepend LINK_BUILDID_SPEC to whatever link_spec we had before. */
1508 obstack_grow (&obstack, LINK_BUILDID_SPEC, sizeof(LINK_BUILDID_SPEC) - 1);
1509 # endif
1510 # ifdef LINK_EH_SPEC
1511 /* Prepend LINK_EH_SPEC to whatever link_spec we had before. */
1512 obstack_grow (&obstack, LINK_EH_SPEC, sizeof(LINK_EH_SPEC) - 1);
1513 # endif
1514 # ifdef LINKER_HASH_STYLE
1515 /* Prepend --hash-style=LINKER_HASH_STYLE to whatever link_spec we had
1516 before. */
1518 static const char hash_style[] = "--hash-style=";
1519 obstack_grow (&obstack, hash_style, sizeof(hash_style) - 1);
1520 obstack_grow (&obstack, LINKER_HASH_STYLE, sizeof(LINKER_HASH_STYLE) - 1);
1521 obstack_1grow (&obstack, ' ');
1523 # endif
1524 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
1525 link_spec = XOBFINISH (&obstack, const char *);
1526 #endif
1528 specs = sl;
1531 /* Change the value of spec NAME to SPEC. If SPEC is empty, then the spec is
1532 removed; If the spec starts with a + then SPEC is added to the end of the
1533 current spec. */
1535 static void
1536 set_spec (const char *name, const char *spec, bool user_p)
1538 struct spec_list *sl;
1539 const char *old_spec;
1540 int name_len = strlen (name);
1541 int i;
1543 /* If this is the first call, initialize the statically allocated specs. */
1544 if (!specs)
1546 struct spec_list *next = (struct spec_list *) 0;
1547 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1549 sl = &static_specs[i];
1550 sl->next = next;
1551 next = sl;
1553 specs = sl;
1556 /* See if the spec already exists. */
1557 for (sl = specs; sl; sl = sl->next)
1558 if (name_len == sl->name_len && !strcmp (sl->name, name))
1559 break;
1561 if (!sl)
1563 /* Not found - make it. */
1564 sl = XNEW (struct spec_list);
1565 sl->name = xstrdup (name);
1566 sl->name_len = name_len;
1567 sl->ptr_spec = &sl->ptr;
1568 sl->alloc_p = 0;
1569 *(sl->ptr_spec) = "";
1570 sl->next = specs;
1571 specs = sl;
1574 old_spec = *(sl->ptr_spec);
1575 *(sl->ptr_spec) = ((spec[0] == '+' && ISSPACE ((unsigned char)spec[1]))
1576 ? concat (old_spec, spec + 1, NULL)
1577 : xstrdup (spec));
1579 #ifdef DEBUG_SPECS
1580 if (verbose_flag)
1581 fnotice (stderr, "Setting spec %s to '%s'\n\n", name, *(sl->ptr_spec));
1582 #endif
1584 /* Free the old spec. */
1585 if (old_spec && sl->alloc_p)
1586 free (CONST_CAST(char *, old_spec));
1588 sl->user_p = user_p;
1589 sl->alloc_p = true;
1592 /* Accumulate a command (program name and args), and run it. */
1594 typedef const char *const_char_p; /* For DEF_VEC_P. */
1596 /* Vector of pointers to arguments in the current line of specifications. */
1598 static vec<const_char_p> argbuf;
1600 /* Position in the argbuf vector containing the name of the output file
1601 (the value associated with the "-o" flag). */
1603 static int have_o_argbuf_index = 0;
1605 /* Were the options -c, -S or -E passed. */
1606 static int have_c = 0;
1608 /* Was the option -o passed. */
1609 static int have_o = 0;
1611 /* This is the list of suffixes and codes (%g/%u/%U/%j) and the associated
1612 temp file. If the HOST_BIT_BUCKET is used for %j, no entry is made for
1613 it here. */
1615 static struct temp_name {
1616 const char *suffix; /* suffix associated with the code. */
1617 int length; /* strlen (suffix). */
1618 int unique; /* Indicates whether %g or %u/%U was used. */
1619 const char *filename; /* associated filename. */
1620 int filename_length; /* strlen (filename). */
1621 struct temp_name *next;
1622 } *temp_names;
1624 /* Number of commands executed so far. */
1626 static int execution_count;
1628 /* Number of commands that exited with a signal. */
1630 static int signal_count;
1632 /* Allocate the argument vector. */
1634 static void
1635 alloc_args (void)
1637 argbuf.create (10);
1640 /* Clear out the vector of arguments (after a command is executed). */
1642 static void
1643 clear_args (void)
1645 argbuf.truncate (0);
1648 /* Add one argument to the vector at the end.
1649 This is done when a space is seen or at the end of the line.
1650 If DELETE_ALWAYS is nonzero, the arg is a filename
1651 and the file should be deleted eventually.
1652 If DELETE_FAILURE is nonzero, the arg is a filename
1653 and the file should be deleted if this compilation fails. */
1655 static void
1656 store_arg (const char *arg, int delete_always, int delete_failure)
1658 argbuf.safe_push (arg);
1660 if (strcmp (arg, "-o") == 0)
1661 have_o_argbuf_index = argbuf.length ();
1662 if (delete_always || delete_failure)
1664 const char *p;
1665 /* If the temporary file we should delete is specified as
1666 part of a joined argument extract the filename. */
1667 if (arg[0] == '-'
1668 && (p = strrchr (arg, '=')))
1669 arg = p + 1;
1670 record_temp_file (arg, delete_always, delete_failure);
1674 /* Load specs from a file name named FILENAME, replacing occurrences of
1675 various different types of line-endings, \r\n, \n\r and just \r, with
1676 a single \n. */
1678 static char *
1679 load_specs (const char *filename)
1681 int desc;
1682 int readlen;
1683 struct stat statbuf;
1684 char *buffer;
1685 char *buffer_p;
1686 char *specs;
1687 char *specs_p;
1689 if (verbose_flag)
1690 fnotice (stderr, "Reading specs from %s\n", filename);
1692 /* Open and stat the file. */
1693 desc = open (filename, O_RDONLY, 0);
1694 if (desc < 0)
1695 pfatal_with_name (filename);
1696 if (stat (filename, &statbuf) < 0)
1697 pfatal_with_name (filename);
1699 /* Read contents of file into BUFFER. */
1700 buffer = XNEWVEC (char, statbuf.st_size + 1);
1701 readlen = read (desc, buffer, (unsigned) statbuf.st_size);
1702 if (readlen < 0)
1703 pfatal_with_name (filename);
1704 buffer[readlen] = 0;
1705 close (desc);
1707 specs = XNEWVEC (char, readlen + 1);
1708 specs_p = specs;
1709 for (buffer_p = buffer; buffer_p && *buffer_p; buffer_p++)
1711 int skip = 0;
1712 char c = *buffer_p;
1713 if (c == '\r')
1715 if (buffer_p > buffer && *(buffer_p - 1) == '\n') /* \n\r */
1716 skip = 1;
1717 else if (*(buffer_p + 1) == '\n') /* \r\n */
1718 skip = 1;
1719 else /* \r */
1720 c = '\n';
1722 if (! skip)
1723 *specs_p++ = c;
1725 *specs_p = '\0';
1727 free (buffer);
1728 return (specs);
1731 /* Read compilation specs from a file named FILENAME,
1732 replacing the default ones.
1734 A suffix which starts with `*' is a definition for
1735 one of the machine-specific sub-specs. The "suffix" should be
1736 *asm, *cc1, *cpp, *link, *startfile, etc.
1737 The corresponding spec is stored in asm_spec, etc.,
1738 rather than in the `compilers' vector.
1740 Anything invalid in the file is a fatal error. */
1742 static void
1743 read_specs (const char *filename, bool main_p, bool user_p)
1745 char *buffer;
1746 char *p;
1748 buffer = load_specs (filename);
1750 /* Scan BUFFER for specs, putting them in the vector. */
1751 p = buffer;
1752 while (1)
1754 char *suffix;
1755 char *spec;
1756 char *in, *out, *p1, *p2, *p3;
1758 /* Advance P in BUFFER to the next nonblank nocomment line. */
1759 p = skip_whitespace (p);
1760 if (*p == 0)
1761 break;
1763 /* Is this a special command that starts with '%'? */
1764 /* Don't allow this for the main specs file, since it would
1765 encourage people to overwrite it. */
1766 if (*p == '%' && !main_p)
1768 p1 = p;
1769 while (*p && *p != '\n')
1770 p++;
1772 /* Skip '\n'. */
1773 p++;
1775 if (!strncmp (p1, "%include", sizeof ("%include") - 1)
1776 && (p1[sizeof "%include" - 1] == ' '
1777 || p1[sizeof "%include" - 1] == '\t'))
1779 char *new_filename;
1781 p1 += sizeof ("%include");
1782 while (*p1 == ' ' || *p1 == '\t')
1783 p1++;
1785 if (*p1++ != '<' || p[-2] != '>')
1786 fatal_error ("specs %%include syntax malformed after "
1787 "%ld characters",
1788 (long) (p1 - buffer + 1));
1790 p[-2] = '\0';
1791 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
1792 read_specs (new_filename ? new_filename : p1, false, user_p);
1793 continue;
1795 else if (!strncmp (p1, "%include_noerr", sizeof "%include_noerr" - 1)
1796 && (p1[sizeof "%include_noerr" - 1] == ' '
1797 || p1[sizeof "%include_noerr" - 1] == '\t'))
1799 char *new_filename;
1801 p1 += sizeof "%include_noerr";
1802 while (*p1 == ' ' || *p1 == '\t')
1803 p1++;
1805 if (*p1++ != '<' || p[-2] != '>')
1806 fatal_error ("specs %%include syntax malformed after "
1807 "%ld characters",
1808 (long) (p1 - buffer + 1));
1810 p[-2] = '\0';
1811 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
1812 if (new_filename)
1813 read_specs (new_filename, false, user_p);
1814 else if (verbose_flag)
1815 fnotice (stderr, "could not find specs file %s\n", p1);
1816 continue;
1818 else if (!strncmp (p1, "%rename", sizeof "%rename" - 1)
1819 && (p1[sizeof "%rename" - 1] == ' '
1820 || p1[sizeof "%rename" - 1] == '\t'))
1822 int name_len;
1823 struct spec_list *sl;
1824 struct spec_list *newsl;
1826 /* Get original name. */
1827 p1 += sizeof "%rename";
1828 while (*p1 == ' ' || *p1 == '\t')
1829 p1++;
1831 if (! ISALPHA ((unsigned char) *p1))
1832 fatal_error ("specs %%rename syntax malformed after "
1833 "%ld characters",
1834 (long) (p1 - buffer));
1836 p2 = p1;
1837 while (*p2 && !ISSPACE ((unsigned char) *p2))
1838 p2++;
1840 if (*p2 != ' ' && *p2 != '\t')
1841 fatal_error ("specs %%rename syntax malformed after "
1842 "%ld characters",
1843 (long) (p2 - buffer));
1845 name_len = p2 - p1;
1846 *p2++ = '\0';
1847 while (*p2 == ' ' || *p2 == '\t')
1848 p2++;
1850 if (! ISALPHA ((unsigned char) *p2))
1851 fatal_error ("specs %%rename syntax malformed after "
1852 "%ld characters",
1853 (long) (p2 - buffer));
1855 /* Get new spec name. */
1856 p3 = p2;
1857 while (*p3 && !ISSPACE ((unsigned char) *p3))
1858 p3++;
1860 if (p3 != p - 1)
1861 fatal_error ("specs %%rename syntax malformed after "
1862 "%ld characters",
1863 (long) (p3 - buffer));
1864 *p3 = '\0';
1866 for (sl = specs; sl; sl = sl->next)
1867 if (name_len == sl->name_len && !strcmp (sl->name, p1))
1868 break;
1870 if (!sl)
1871 fatal_error ("specs %s spec was not found to be renamed", p1);
1873 if (strcmp (p1, p2) == 0)
1874 continue;
1876 for (newsl = specs; newsl; newsl = newsl->next)
1877 if (strcmp (newsl->name, p2) == 0)
1878 fatal_error ("%s: attempt to rename spec %qs to "
1879 "already defined spec %qs",
1880 filename, p1, p2);
1882 if (verbose_flag)
1884 fnotice (stderr, "rename spec %s to %s\n", p1, p2);
1885 #ifdef DEBUG_SPECS
1886 fnotice (stderr, "spec is '%s'\n\n", *(sl->ptr_spec));
1887 #endif
1890 set_spec (p2, *(sl->ptr_spec), user_p);
1891 if (sl->alloc_p)
1892 free (CONST_CAST (char *, *(sl->ptr_spec)));
1894 *(sl->ptr_spec) = "";
1895 sl->alloc_p = 0;
1896 continue;
1898 else
1899 fatal_error ("specs unknown %% command after %ld characters",
1900 (long) (p1 - buffer));
1903 /* Find the colon that should end the suffix. */
1904 p1 = p;
1905 while (*p1 && *p1 != ':' && *p1 != '\n')
1906 p1++;
1908 /* The colon shouldn't be missing. */
1909 if (*p1 != ':')
1910 fatal_error ("specs file malformed after %ld characters",
1911 (long) (p1 - buffer));
1913 /* Skip back over trailing whitespace. */
1914 p2 = p1;
1915 while (p2 > buffer && (p2[-1] == ' ' || p2[-1] == '\t'))
1916 p2--;
1918 /* Copy the suffix to a string. */
1919 suffix = save_string (p, p2 - p);
1920 /* Find the next line. */
1921 p = skip_whitespace (p1 + 1);
1922 if (p[1] == 0)
1923 fatal_error ("specs file malformed after %ld characters",
1924 (long) (p - buffer));
1926 p1 = p;
1927 /* Find next blank line or end of string. */
1928 while (*p1 && !(*p1 == '\n' && (p1[1] == '\n' || p1[1] == '\0')))
1929 p1++;
1931 /* Specs end at the blank line and do not include the newline. */
1932 spec = save_string (p, p1 - p);
1933 p = p1;
1935 /* Delete backslash-newline sequences from the spec. */
1936 in = spec;
1937 out = spec;
1938 while (*in != 0)
1940 if (in[0] == '\\' && in[1] == '\n')
1941 in += 2;
1942 else if (in[0] == '#')
1943 while (*in && *in != '\n')
1944 in++;
1946 else
1947 *out++ = *in++;
1949 *out = 0;
1951 if (suffix[0] == '*')
1953 if (! strcmp (suffix, "*link_command"))
1954 link_command_spec = spec;
1955 else
1956 set_spec (suffix + 1, spec, user_p);
1958 else
1960 /* Add this pair to the vector. */
1961 compilers
1962 = XRESIZEVEC (struct compiler, compilers, n_compilers + 2);
1964 compilers[n_compilers].suffix = suffix;
1965 compilers[n_compilers].spec = spec;
1966 n_compilers++;
1967 memset (&compilers[n_compilers], 0, sizeof compilers[n_compilers]);
1970 if (*suffix == 0)
1971 link_command_spec = spec;
1974 if (link_command_spec == 0)
1975 fatal_error ("spec file has no spec for linking");
1978 /* Record the names of temporary files we tell compilers to write,
1979 and delete them at the end of the run. */
1981 /* This is the common prefix we use to make temp file names.
1982 It is chosen once for each run of this program.
1983 It is substituted into a spec by %g or %j.
1984 Thus, all temp file names contain this prefix.
1985 In practice, all temp file names start with this prefix.
1987 This prefix comes from the envvar TMPDIR if it is defined;
1988 otherwise, from the P_tmpdir macro if that is defined;
1989 otherwise, in /usr/tmp or /tmp;
1990 or finally the current directory if all else fails. */
1992 static const char *temp_filename;
1994 /* Length of the prefix. */
1996 static int temp_filename_length;
1998 /* Define the list of temporary files to delete. */
2000 struct temp_file
2002 const char *name;
2003 struct temp_file *next;
2006 /* Queue of files to delete on success or failure of compilation. */
2007 static struct temp_file *always_delete_queue;
2008 /* Queue of files to delete on failure of compilation. */
2009 static struct temp_file *failure_delete_queue;
2011 /* Record FILENAME as a file to be deleted automatically.
2012 ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
2013 otherwise delete it in any case.
2014 FAIL_DELETE nonzero means delete it if a compilation step fails;
2015 otherwise delete it in any case. */
2017 void
2018 record_temp_file (const char *filename, int always_delete, int fail_delete)
2020 char *const name = xstrdup (filename);
2022 if (always_delete)
2024 struct temp_file *temp;
2025 for (temp = always_delete_queue; temp; temp = temp->next)
2026 if (! filename_cmp (name, temp->name))
2027 goto already1;
2029 temp = XNEW (struct temp_file);
2030 temp->next = always_delete_queue;
2031 temp->name = name;
2032 always_delete_queue = temp;
2034 already1:;
2037 if (fail_delete)
2039 struct temp_file *temp;
2040 for (temp = failure_delete_queue; temp; temp = temp->next)
2041 if (! filename_cmp (name, temp->name))
2043 free (name);
2044 goto already2;
2047 temp = XNEW (struct temp_file);
2048 temp->next = failure_delete_queue;
2049 temp->name = name;
2050 failure_delete_queue = temp;
2052 already2:;
2056 /* Delete all the temporary files whose names we previously recorded. */
2058 #ifndef DELETE_IF_ORDINARY
2059 #define DELETE_IF_ORDINARY(NAME,ST,VERBOSE_FLAG) \
2060 do \
2062 if (stat (NAME, &ST) >= 0 && S_ISREG (ST.st_mode)) \
2063 if (unlink (NAME) < 0) \
2064 if (VERBOSE_FLAG) \
2065 perror_with_name (NAME); \
2066 } while (0)
2067 #endif
2069 static void
2070 delete_if_ordinary (const char *name)
2072 struct stat st;
2073 #ifdef DEBUG
2074 int i, c;
2076 printf ("Delete %s? (y or n) ", name);
2077 fflush (stdout);
2078 i = getchar ();
2079 if (i != '\n')
2080 while ((c = getchar ()) != '\n' && c != EOF)
2083 if (i == 'y' || i == 'Y')
2084 #endif /* DEBUG */
2085 DELETE_IF_ORDINARY (name, st, verbose_flag);
2088 static void
2089 delete_temp_files (void)
2091 struct temp_file *temp;
2093 for (temp = always_delete_queue; temp; temp = temp->next)
2094 delete_if_ordinary (temp->name);
2095 always_delete_queue = 0;
2098 /* Delete all the files to be deleted on error. */
2100 static void
2101 delete_failure_queue (void)
2103 struct temp_file *temp;
2105 for (temp = failure_delete_queue; temp; temp = temp->next)
2106 delete_if_ordinary (temp->name);
2109 static void
2110 clear_failure_queue (void)
2112 failure_delete_queue = 0;
2115 /* Call CALLBACK for each path in PATHS, breaking out early if CALLBACK
2116 returns non-NULL.
2117 If DO_MULTI is true iterate over the paths twice, first with multilib
2118 suffix then without, otherwise iterate over the paths once without
2119 adding a multilib suffix. When DO_MULTI is true, some attempt is made
2120 to avoid visiting the same path twice, but we could do better. For
2121 instance, /usr/lib/../lib is considered different from /usr/lib.
2122 At least EXTRA_SPACE chars past the end of the path passed to
2123 CALLBACK are available for use by the callback.
2124 CALLBACK_INFO allows extra parameters to be passed to CALLBACK.
2126 Returns the value returned by CALLBACK. */
2128 static void *
2129 for_each_path (const struct path_prefix *paths,
2130 bool do_multi,
2131 size_t extra_space,
2132 void *(*callback) (char *, void *),
2133 void *callback_info)
2135 struct prefix_list *pl;
2136 const char *multi_dir = NULL;
2137 const char *multi_os_dir = NULL;
2138 const char *multiarch_suffix = NULL;
2139 const char *multi_suffix;
2140 const char *just_multi_suffix;
2141 char *path = NULL;
2142 void *ret = NULL;
2143 bool skip_multi_dir = false;
2144 bool skip_multi_os_dir = false;
2146 multi_suffix = machine_suffix;
2147 just_multi_suffix = just_machine_suffix;
2148 if (do_multi && multilib_dir && strcmp (multilib_dir, ".") != 0)
2150 multi_dir = concat (multilib_dir, dir_separator_str, NULL);
2151 multi_suffix = concat (multi_suffix, multi_dir, NULL);
2152 just_multi_suffix = concat (just_multi_suffix, multi_dir, NULL);
2154 if (do_multi && multilib_os_dir && strcmp (multilib_os_dir, ".") != 0)
2155 multi_os_dir = concat (multilib_os_dir, dir_separator_str, NULL);
2156 if (multiarch_dir)
2157 multiarch_suffix = concat (multiarch_dir, dir_separator_str, NULL);
2159 while (1)
2161 size_t multi_dir_len = 0;
2162 size_t multi_os_dir_len = 0;
2163 size_t multiarch_len = 0;
2164 size_t suffix_len;
2165 size_t just_suffix_len;
2166 size_t len;
2168 if (multi_dir)
2169 multi_dir_len = strlen (multi_dir);
2170 if (multi_os_dir)
2171 multi_os_dir_len = strlen (multi_os_dir);
2172 if (multiarch_suffix)
2173 multiarch_len = strlen (multiarch_suffix);
2174 suffix_len = strlen (multi_suffix);
2175 just_suffix_len = strlen (just_multi_suffix);
2177 if (path == NULL)
2179 len = paths->max_len + extra_space + 1;
2180 len += MAX (MAX (suffix_len, multi_os_dir_len), multiarch_len);
2181 path = XNEWVEC (char, len);
2184 for (pl = paths->plist; pl != 0; pl = pl->next)
2186 len = strlen (pl->prefix);
2187 memcpy (path, pl->prefix, len);
2189 /* Look first in MACHINE/VERSION subdirectory. */
2190 if (!skip_multi_dir)
2192 memcpy (path + len, multi_suffix, suffix_len + 1);
2193 ret = callback (path, callback_info);
2194 if (ret)
2195 break;
2198 /* Some paths are tried with just the machine (ie. target)
2199 subdir. This is used for finding as, ld, etc. */
2200 if (!skip_multi_dir
2201 && pl->require_machine_suffix == 2)
2203 memcpy (path + len, just_multi_suffix, just_suffix_len + 1);
2204 ret = callback (path, callback_info);
2205 if (ret)
2206 break;
2209 /* Now try the multiarch path. */
2210 if (!skip_multi_dir
2211 && !pl->require_machine_suffix && multiarch_dir)
2213 memcpy (path + len, multiarch_suffix, multiarch_len + 1);
2214 ret = callback (path, callback_info);
2215 if (ret)
2216 break;
2219 /* Now try the base path. */
2220 if (!pl->require_machine_suffix
2221 && !(pl->os_multilib ? skip_multi_os_dir : skip_multi_dir))
2223 const char *this_multi;
2224 size_t this_multi_len;
2226 if (pl->os_multilib)
2228 this_multi = multi_os_dir;
2229 this_multi_len = multi_os_dir_len;
2231 else
2233 this_multi = multi_dir;
2234 this_multi_len = multi_dir_len;
2237 if (this_multi_len)
2238 memcpy (path + len, this_multi, this_multi_len + 1);
2239 else
2240 path[len] = '\0';
2242 ret = callback (path, callback_info);
2243 if (ret)
2244 break;
2247 if (pl)
2248 break;
2250 if (multi_dir == NULL && multi_os_dir == NULL)
2251 break;
2253 /* Run through the paths again, this time without multilibs.
2254 Don't repeat any we have already seen. */
2255 if (multi_dir)
2257 free (CONST_CAST (char *, multi_dir));
2258 multi_dir = NULL;
2259 free (CONST_CAST (char *, multi_suffix));
2260 multi_suffix = machine_suffix;
2261 free (CONST_CAST (char *, just_multi_suffix));
2262 just_multi_suffix = just_machine_suffix;
2264 else
2265 skip_multi_dir = true;
2266 if (multi_os_dir)
2268 free (CONST_CAST (char *, multi_os_dir));
2269 multi_os_dir = NULL;
2271 else
2272 skip_multi_os_dir = true;
2275 if (multi_dir)
2277 free (CONST_CAST (char *, multi_dir));
2278 free (CONST_CAST (char *, multi_suffix));
2279 free (CONST_CAST (char *, just_multi_suffix));
2281 if (multi_os_dir)
2282 free (CONST_CAST (char *, multi_os_dir));
2283 if (ret != path)
2284 free (path);
2285 return ret;
2288 /* Callback for build_search_list. Adds path to obstack being built. */
2290 struct add_to_obstack_info {
2291 struct obstack *ob;
2292 bool check_dir;
2293 bool first_time;
2296 static void *
2297 add_to_obstack (char *path, void *data)
2299 struct add_to_obstack_info *info = (struct add_to_obstack_info *) data;
2301 if (info->check_dir && !is_directory (path, false))
2302 return NULL;
2304 if (!info->first_time)
2305 obstack_1grow (info->ob, PATH_SEPARATOR);
2307 obstack_grow (info->ob, path, strlen (path));
2309 info->first_time = false;
2310 return NULL;
2313 /* Add or change the value of an environment variable, outputting the
2314 change to standard error if in verbose mode. */
2315 static void
2316 xputenv (const char *string)
2318 if (verbose_flag)
2319 fnotice (stderr, "%s\n", string);
2320 putenv (CONST_CAST (char *, string));
2323 /* Build a list of search directories from PATHS.
2324 PREFIX is a string to prepend to the list.
2325 If CHECK_DIR_P is true we ensure the directory exists.
2326 If DO_MULTI is true, multilib paths are output first, then
2327 non-multilib paths.
2328 This is used mostly by putenv_from_prefixes so we use `collect_obstack'.
2329 It is also used by the --print-search-dirs flag. */
2331 static char *
2332 build_search_list (const struct path_prefix *paths, const char *prefix,
2333 bool check_dir, bool do_multi)
2335 struct add_to_obstack_info info;
2337 info.ob = &collect_obstack;
2338 info.check_dir = check_dir;
2339 info.first_time = true;
2341 obstack_grow (&collect_obstack, prefix, strlen (prefix));
2342 obstack_1grow (&collect_obstack, '=');
2344 for_each_path (paths, do_multi, 0, add_to_obstack, &info);
2346 obstack_1grow (&collect_obstack, '\0');
2347 return XOBFINISH (&collect_obstack, char *);
2350 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
2351 for collect. */
2353 static void
2354 putenv_from_prefixes (const struct path_prefix *paths, const char *env_var,
2355 bool do_multi)
2357 xputenv (build_search_list (paths, env_var, true, do_multi));
2360 /* Check whether NAME can be accessed in MODE. This is like access,
2361 except that it never considers directories to be executable. */
2363 static int
2364 access_check (const char *name, int mode)
2366 if (mode == X_OK)
2368 struct stat st;
2370 if (stat (name, &st) < 0
2371 || S_ISDIR (st.st_mode))
2372 return -1;
2375 return access (name, mode);
2378 /* Callback for find_a_file. Appends the file name to the directory
2379 path. If the resulting file exists in the right mode, return the
2380 full pathname to the file. */
2382 struct file_at_path_info {
2383 const char *name;
2384 const char *suffix;
2385 int name_len;
2386 int suffix_len;
2387 int mode;
2390 static void *
2391 file_at_path (char *path, void *data)
2393 struct file_at_path_info *info = (struct file_at_path_info *) data;
2394 size_t len = strlen (path);
2396 memcpy (path + len, info->name, info->name_len);
2397 len += info->name_len;
2399 /* Some systems have a suffix for executable files.
2400 So try appending that first. */
2401 if (info->suffix_len)
2403 memcpy (path + len, info->suffix, info->suffix_len + 1);
2404 if (access_check (path, info->mode) == 0)
2405 return path;
2408 path[len] = '\0';
2409 if (access_check (path, info->mode) == 0)
2410 return path;
2412 return NULL;
2415 /* Search for NAME using the prefix list PREFIXES. MODE is passed to
2416 access to check permissions. If DO_MULTI is true, search multilib
2417 paths then non-multilib paths, otherwise do not search multilib paths.
2418 Return 0 if not found, otherwise return its name, allocated with malloc. */
2420 static char *
2421 find_a_file (const struct path_prefix *pprefix, const char *name, int mode,
2422 bool do_multi)
2424 struct file_at_path_info info;
2426 #ifdef DEFAULT_ASSEMBLER
2427 if (! strcmp (name, "as") && access (DEFAULT_ASSEMBLER, mode) == 0)
2428 return xstrdup (DEFAULT_ASSEMBLER);
2429 #endif
2431 #ifdef DEFAULT_LINKER
2432 if (! strcmp(name, "ld") && access (DEFAULT_LINKER, mode) == 0)
2433 return xstrdup (DEFAULT_LINKER);
2434 #endif
2436 /* Determine the filename to execute (special case for absolute paths). */
2438 if (IS_ABSOLUTE_PATH (name))
2440 if (access (name, mode) == 0)
2441 return xstrdup (name);
2443 return NULL;
2446 info.name = name;
2447 info.suffix = (mode & X_OK) != 0 ? HOST_EXECUTABLE_SUFFIX : "";
2448 info.name_len = strlen (info.name);
2449 info.suffix_len = strlen (info.suffix);
2450 info.mode = mode;
2452 return (char*) for_each_path (pprefix, do_multi,
2453 info.name_len + info.suffix_len,
2454 file_at_path, &info);
2457 /* Ranking of prefixes in the sort list. -B prefixes are put before
2458 all others. */
2460 enum path_prefix_priority
2462 PREFIX_PRIORITY_B_OPT,
2463 PREFIX_PRIORITY_LAST
2466 /* Add an entry for PREFIX in PLIST. The PLIST is kept in ascending
2467 order according to PRIORITY. Within each PRIORITY, new entries are
2468 appended.
2470 If WARN is nonzero, we will warn if no file is found
2471 through this prefix. WARN should point to an int
2472 which will be set to 1 if this entry is used.
2474 COMPONENT is the value to be passed to update_path.
2476 REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
2477 the complete value of machine_suffix.
2478 2 means try both machine_suffix and just_machine_suffix. */
2480 static void
2481 add_prefix (struct path_prefix *pprefix, const char *prefix,
2482 const char *component, /* enum prefix_priority */ int priority,
2483 int require_machine_suffix, int os_multilib)
2485 struct prefix_list *pl, **prev;
2486 int len;
2488 for (prev = &pprefix->plist;
2489 (*prev) != NULL && (*prev)->priority <= priority;
2490 prev = &(*prev)->next)
2493 /* Keep track of the longest prefix. */
2495 prefix = update_path (prefix, component);
2496 len = strlen (prefix);
2497 if (len > pprefix->max_len)
2498 pprefix->max_len = len;
2500 pl = XNEW (struct prefix_list);
2501 pl->prefix = prefix;
2502 pl->require_machine_suffix = require_machine_suffix;
2503 pl->priority = priority;
2504 pl->os_multilib = os_multilib;
2506 /* Insert after PREV. */
2507 pl->next = (*prev);
2508 (*prev) = pl;
2511 /* Same as add_prefix, but prepending target_system_root to prefix. */
2512 /* The target_system_root prefix has been relocated by gcc_exec_prefix. */
2513 static void
2514 add_sysrooted_prefix (struct path_prefix *pprefix, const char *prefix,
2515 const char *component,
2516 /* enum prefix_priority */ int priority,
2517 int require_machine_suffix, int os_multilib)
2519 if (!IS_ABSOLUTE_PATH (prefix))
2520 fatal_error ("system path %qs is not absolute", prefix);
2522 if (target_system_root)
2524 char *sysroot_no_trailing_dir_separator = xstrdup (target_system_root);
2525 size_t sysroot_len = strlen (target_system_root);
2527 if (sysroot_len > 0
2528 && target_system_root[sysroot_len - 1] == DIR_SEPARATOR)
2529 sysroot_no_trailing_dir_separator[sysroot_len - 1] = '\0';
2531 if (target_sysroot_suffix)
2532 prefix = concat (sysroot_no_trailing_dir_separator,
2533 target_sysroot_suffix, prefix, NULL);
2534 else
2535 prefix = concat (sysroot_no_trailing_dir_separator, prefix, NULL);
2537 free (sysroot_no_trailing_dir_separator);
2539 /* We have to override this because GCC's notion of sysroot
2540 moves along with GCC. */
2541 component = "GCC";
2544 add_prefix (pprefix, prefix, component, priority,
2545 require_machine_suffix, os_multilib);
2548 /* Execute the command specified by the arguments on the current line of spec.
2549 When using pipes, this includes several piped-together commands
2550 with `|' between them.
2552 Return 0 if successful, -1 if failed. */
2554 static int
2555 execute (void)
2557 int i;
2558 int n_commands; /* # of command. */
2559 char *string;
2560 struct pex_obj *pex;
2561 struct command
2563 const char *prog; /* program name. */
2564 const char **argv; /* vector of args. */
2566 const char *arg;
2568 struct command *commands; /* each command buffer with above info. */
2570 gcc_assert (!processing_spec_function);
2572 if (wrapper_string)
2574 string = find_a_file (&exec_prefixes,
2575 argbuf[0], X_OK, false);
2576 if (string)
2577 argbuf[0] = string;
2578 insert_wrapper (wrapper_string);
2581 /* Count # of piped commands. */
2582 for (n_commands = 1, i = 0; argbuf.iterate (i, &arg); i++)
2583 if (strcmp (arg, "|") == 0)
2584 n_commands++;
2586 /* Get storage for each command. */
2587 commands = (struct command *) alloca (n_commands * sizeof (struct command));
2589 /* Split argbuf into its separate piped processes,
2590 and record info about each one.
2591 Also search for the programs that are to be run. */
2593 argbuf.safe_push (0);
2595 commands[0].prog = argbuf[0]; /* first command. */
2596 commands[0].argv = argbuf.address ();
2598 if (!wrapper_string)
2600 string = find_a_file (&exec_prefixes, commands[0].prog, X_OK, false);
2601 commands[0].argv[0] = (string) ? string : commands[0].argv[0];
2604 for (n_commands = 1, i = 0; argbuf.iterate (i, &arg); i++)
2605 if (arg && strcmp (arg, "|") == 0)
2606 { /* each command. */
2607 #if defined (__MSDOS__) || defined (OS2) || defined (VMS)
2608 fatal_error ("-pipe not supported");
2609 #endif
2610 argbuf[i] = 0; /* Termination of
2611 command args. */
2612 commands[n_commands].prog = argbuf[i + 1];
2613 commands[n_commands].argv
2614 = &(argbuf.address ())[i + 1];
2615 string = find_a_file (&exec_prefixes, commands[n_commands].prog,
2616 X_OK, false);
2617 if (string)
2618 commands[n_commands].argv[0] = string;
2619 n_commands++;
2622 /* If -v, print what we are about to do, and maybe query. */
2624 if (verbose_flag)
2626 /* For help listings, put a blank line between sub-processes. */
2627 if (print_help_list)
2628 fputc ('\n', stderr);
2630 /* Print each piped command as a separate line. */
2631 for (i = 0; i < n_commands; i++)
2633 const char *const *j;
2635 if (verbose_only_flag)
2637 for (j = commands[i].argv; *j; j++)
2639 const char *p;
2640 for (p = *j; *p; ++p)
2641 if (!ISALNUM ((unsigned char) *p)
2642 && *p != '_' && *p != '/' && *p != '-' && *p != '.')
2643 break;
2644 if (*p || !*j)
2646 fprintf (stderr, " \"");
2647 for (p = *j; *p; ++p)
2649 if (*p == '"' || *p == '\\' || *p == '$')
2650 fputc ('\\', stderr);
2651 fputc (*p, stderr);
2653 fputc ('"', stderr);
2655 /* If it's empty, print "". */
2656 else if (!**j)
2657 fprintf (stderr, " \"\"");
2658 else
2659 fprintf (stderr, " %s", *j);
2662 else
2663 for (j = commands[i].argv; *j; j++)
2664 /* If it's empty, print "". */
2665 if (!**j)
2666 fprintf (stderr, " \"\"");
2667 else
2668 fprintf (stderr, " %s", *j);
2670 /* Print a pipe symbol after all but the last command. */
2671 if (i + 1 != n_commands)
2672 fprintf (stderr, " |");
2673 fprintf (stderr, "\n");
2675 fflush (stderr);
2676 if (verbose_only_flag != 0)
2678 /* verbose_only_flag should act as if the spec was
2679 executed, so increment execution_count before
2680 returning. This prevents spurious warnings about
2681 unused linker input files, etc. */
2682 execution_count++;
2683 return 0;
2685 #ifdef DEBUG
2686 fnotice (stderr, "\nGo ahead? (y or n) ");
2687 fflush (stderr);
2688 i = getchar ();
2689 if (i != '\n')
2690 while (getchar () != '\n')
2693 if (i != 'y' && i != 'Y')
2694 return 0;
2695 #endif /* DEBUG */
2698 #ifdef ENABLE_VALGRIND_CHECKING
2699 /* Run the each command through valgrind. To simplify prepending the
2700 path to valgrind and the option "-q" (for quiet operation unless
2701 something triggers), we allocate a separate argv array. */
2703 for (i = 0; i < n_commands; i++)
2705 const char **argv;
2706 int argc;
2707 int j;
2709 for (argc = 0; commands[i].argv[argc] != NULL; argc++)
2712 argv = XALLOCAVEC (const char *, argc + 3);
2714 argv[0] = VALGRIND_PATH;
2715 argv[1] = "-q";
2716 for (j = 2; j < argc + 2; j++)
2717 argv[j] = commands[i].argv[j - 2];
2718 argv[j] = NULL;
2720 commands[i].argv = argv;
2721 commands[i].prog = argv[0];
2723 #endif
2725 /* Run each piped subprocess. */
2727 pex = pex_init (PEX_USE_PIPES | ((report_times || report_times_to_file)
2728 ? PEX_RECORD_TIMES : 0),
2729 progname, temp_filename);
2730 if (pex == NULL)
2731 fatal_error ("pex_init failed: %m");
2733 for (i = 0; i < n_commands; i++)
2735 const char *errmsg;
2736 int err;
2737 const char *string = commands[i].argv[0];
2739 errmsg = pex_run (pex,
2740 ((i + 1 == n_commands ? PEX_LAST : 0)
2741 | (string == commands[i].prog ? PEX_SEARCH : 0)),
2742 string, CONST_CAST (char **, commands[i].argv),
2743 NULL, NULL, &err);
2744 if (errmsg != NULL)
2746 if (err == 0)
2747 fatal_error (errmsg);
2748 else
2750 errno = err;
2751 pfatal_with_name (errmsg);
2755 if (string != commands[i].prog)
2756 free (CONST_CAST (char *, string));
2759 execution_count++;
2761 /* Wait for all the subprocesses to finish. */
2764 int *statuses;
2765 struct pex_time *times = NULL;
2766 int ret_code = 0;
2768 statuses = (int *) alloca (n_commands * sizeof (int));
2769 if (!pex_get_status (pex, n_commands, statuses))
2770 fatal_error ("failed to get exit status: %m");
2772 if (report_times || report_times_to_file)
2774 times = (struct pex_time *) alloca (n_commands * sizeof (struct pex_time));
2775 if (!pex_get_times (pex, n_commands, times))
2776 fatal_error ("failed to get process times: %m");
2779 pex_free (pex);
2781 for (i = 0; i < n_commands; ++i)
2783 int status = statuses[i];
2785 if (WIFSIGNALED (status))
2787 #ifdef SIGPIPE
2788 /* SIGPIPE is a special case. It happens in -pipe mode
2789 when the compiler dies before the preprocessor is done,
2790 or the assembler dies before the compiler is done.
2791 There's generally been an error already, and this is
2792 just fallout. So don't generate another error unless
2793 we would otherwise have succeeded. */
2794 if (WTERMSIG (status) == SIGPIPE
2795 && (signal_count || greatest_status >= MIN_FATAL_STATUS))
2797 signal_count++;
2798 ret_code = -1;
2800 else
2801 #endif
2802 internal_error ("%s (program %s)",
2803 strsignal (WTERMSIG (status)), commands[i].prog);
2805 else if (WIFEXITED (status)
2806 && WEXITSTATUS (status) >= MIN_FATAL_STATUS)
2808 if (WEXITSTATUS (status) > greatest_status)
2809 greatest_status = WEXITSTATUS (status);
2810 ret_code = -1;
2813 if (report_times || report_times_to_file)
2815 struct pex_time *pt = &times[i];
2816 double ut, st;
2818 ut = ((double) pt->user_seconds
2819 + (double) pt->user_microseconds / 1.0e6);
2820 st = ((double) pt->system_seconds
2821 + (double) pt->system_microseconds / 1.0e6);
2823 if (ut + st != 0)
2825 if (report_times)
2826 fnotice (stderr, "# %s %.2f %.2f\n",
2827 commands[i].prog, ut, st);
2829 if (report_times_to_file)
2831 int c = 0;
2832 const char *const *j;
2834 fprintf (report_times_to_file, "%g %g", ut, st);
2836 for (j = &commands[i].prog; *j; j = &commands[i].argv[++c])
2838 const char *p;
2839 for (p = *j; *p; ++p)
2840 if (*p == '"' || *p == '\\' || *p == '$'
2841 || ISSPACE (*p))
2842 break;
2844 if (*p)
2846 fprintf (report_times_to_file, " \"");
2847 for (p = *j; *p; ++p)
2849 if (*p == '"' || *p == '\\' || *p == '$')
2850 fputc ('\\', report_times_to_file);
2851 fputc (*p, report_times_to_file);
2853 fputc ('"', report_times_to_file);
2855 else
2856 fprintf (report_times_to_file, " %s", *j);
2859 fputc ('\n', report_times_to_file);
2865 return ret_code;
2869 /* Find all the switches given to us
2870 and make a vector describing them.
2871 The elements of the vector are strings, one per switch given.
2872 If a switch uses following arguments, then the `part1' field
2873 is the switch itself and the `args' field
2874 is a null-terminated vector containing the following arguments.
2875 Bits in the `live_cond' field are:
2876 SWITCH_LIVE to indicate this switch is true in a conditional spec.
2877 SWITCH_FALSE to indicate this switch is overridden by a later switch.
2878 SWITCH_IGNORE to indicate this switch should be ignored (used in %<S).
2879 SWITCH_IGNORE_PERMANENTLY to indicate this switch should be ignored
2880 in all do_spec calls afterwards. Used for %<S from self specs.
2881 The `validated' field is nonzero if any spec has looked at this switch;
2882 if it remains zero at the end of the run, it must be meaningless. */
2884 #define SWITCH_LIVE (1 << 0)
2885 #define SWITCH_FALSE (1 << 1)
2886 #define SWITCH_IGNORE (1 << 2)
2887 #define SWITCH_IGNORE_PERMANENTLY (1 << 3)
2888 #define SWITCH_KEEP_FOR_GCC (1 << 4)
2890 struct switchstr
2892 const char *part1;
2893 const char **args;
2894 unsigned int live_cond;
2895 bool known;
2896 bool validated;
2897 bool ordering;
2900 static struct switchstr *switches;
2902 static int n_switches;
2904 static int n_switches_alloc;
2906 /* Set to zero if -fcompare-debug is disabled, positive if it's
2907 enabled and we're running the first compilation, negative if it's
2908 enabled and we're running the second compilation. For most of the
2909 time, it's in the range -1..1, but it can be temporarily set to 2
2910 or 3 to indicate that the -fcompare-debug flags didn't come from
2911 the command-line, but rather from the GCC_COMPARE_DEBUG environment
2912 variable, until a synthesized -fcompare-debug flag is added to the
2913 command line. */
2914 int compare_debug;
2916 /* Set to nonzero if we've seen the -fcompare-debug-second flag. */
2917 int compare_debug_second;
2919 /* Set to the flags that should be passed to the second compilation in
2920 a -fcompare-debug compilation. */
2921 const char *compare_debug_opt;
2923 static struct switchstr *switches_debug_check[2];
2925 static int n_switches_debug_check[2];
2927 static int n_switches_alloc_debug_check[2];
2929 static char *debug_check_temp_file[2];
2931 /* Language is one of three things:
2933 1) The name of a real programming language.
2934 2) NULL, indicating that no one has figured out
2935 what it is yet.
2936 3) '*', indicating that the file should be passed
2937 to the linker. */
2938 struct infile
2940 const char *name;
2941 const char *language;
2942 struct compiler *incompiler;
2943 bool compiled;
2944 bool preprocessed;
2947 /* Also a vector of input files specified. */
2949 static struct infile *infiles;
2951 int n_infiles;
2953 static int n_infiles_alloc;
2955 /* True if multiple input files are being compiled to a single
2956 assembly file. */
2958 static bool combine_inputs;
2960 /* This counts the number of libraries added by lang_specific_driver, so that
2961 we can tell if there were any user supplied any files or libraries. */
2963 static int added_libraries;
2965 /* And a vector of corresponding output files is made up later. */
2967 const char **outfiles;
2969 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
2971 /* Convert NAME to a new name if it is the standard suffix. DO_EXE
2972 is true if we should look for an executable suffix. DO_OBJ
2973 is true if we should look for an object suffix. */
2975 static const char *
2976 convert_filename (const char *name, int do_exe ATTRIBUTE_UNUSED,
2977 int do_obj ATTRIBUTE_UNUSED)
2979 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
2980 int i;
2981 #endif
2982 int len;
2984 if (name == NULL)
2985 return NULL;
2987 len = strlen (name);
2989 #ifdef HAVE_TARGET_OBJECT_SUFFIX
2990 /* Convert x.o to x.obj if TARGET_OBJECT_SUFFIX is ".obj". */
2991 if (do_obj && len > 2
2992 && name[len - 2] == '.'
2993 && name[len - 1] == 'o')
2995 obstack_grow (&obstack, name, len - 2);
2996 obstack_grow0 (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
2997 name = XOBFINISH (&obstack, const char *);
2999 #endif
3001 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
3002 /* If there is no filetype, make it the executable suffix (which includes
3003 the "."). But don't get confused if we have just "-o". */
3004 if (! do_exe || TARGET_EXECUTABLE_SUFFIX[0] == 0 || (len == 2 && name[0] == '-'))
3005 return name;
3007 for (i = len - 1; i >= 0; i--)
3008 if (IS_DIR_SEPARATOR (name[i]))
3009 break;
3011 for (i++; i < len; i++)
3012 if (name[i] == '.')
3013 return name;
3015 obstack_grow (&obstack, name, len);
3016 obstack_grow0 (&obstack, TARGET_EXECUTABLE_SUFFIX,
3017 strlen (TARGET_EXECUTABLE_SUFFIX));
3018 name = XOBFINISH (&obstack, const char *);
3019 #endif
3021 return name;
3023 #endif
3025 /* Display the command line switches accepted by gcc. */
3026 static void
3027 display_help (void)
3029 printf (_("Usage: %s [options] file...\n"), progname);
3030 fputs (_("Options:\n"), stdout);
3032 fputs (_(" -pass-exit-codes Exit with highest error code from a phase\n"), stdout);
3033 fputs (_(" --help Display this information\n"), stdout);
3034 fputs (_(" --target-help Display target specific command line options\n"), stdout);
3035 fputs (_(" --help={common|optimizers|params|target|warnings|[^]{joined|separate|undocumented}}[,...]\n"), stdout);
3036 fputs (_(" Display specific types of command line options\n"), stdout);
3037 if (! verbose_flag)
3038 fputs (_(" (Use '-v --help' to display command line options of sub-processes)\n"), stdout);
3039 fputs (_(" --version Display compiler version information\n"), stdout);
3040 fputs (_(" -dumpspecs Display all of the built in spec strings\n"), stdout);
3041 fputs (_(" -dumpversion Display the version of the compiler\n"), stdout);
3042 fputs (_(" -dumpmachine Display the compiler's target processor\n"), stdout);
3043 fputs (_(" -print-search-dirs Display the directories in the compiler's search path\n"), stdout);
3044 fputs (_(" -print-libgcc-file-name Display the name of the compiler's companion library\n"), stdout);
3045 fputs (_(" -print-file-name=<lib> Display the full path to library <lib>\n"), stdout);
3046 fputs (_(" -print-prog-name=<prog> Display the full path to compiler component <prog>\n"), stdout);
3047 fputs (_("\
3048 -print-multiarch Display the target's normalized GNU triplet, used as\n\
3049 a component in the library path\n"), stdout);
3050 fputs (_(" -print-multi-directory Display the root directory for versions of libgcc\n"), stdout);
3051 fputs (_("\
3052 -print-multi-lib Display the mapping between command line options and\n\
3053 multiple library search directories\n"), stdout);
3054 fputs (_(" -print-multi-os-directory Display the relative path to OS libraries\n"), stdout);
3055 fputs (_(" -print-sysroot Display the target libraries directory\n"), stdout);
3056 fputs (_(" -print-sysroot-headers-suffix Display the sysroot suffix used to find headers\n"), stdout);
3057 fputs (_(" -Wa,<options> Pass comma-separated <options> on to the assembler\n"), stdout);
3058 fputs (_(" -Wp,<options> Pass comma-separated <options> on to the preprocessor\n"), stdout);
3059 fputs (_(" -Wl,<options> Pass comma-separated <options> on to the linker\n"), stdout);
3060 fputs (_(" -Xassembler <arg> Pass <arg> on to the assembler\n"), stdout);
3061 fputs (_(" -Xpreprocessor <arg> Pass <arg> on to the preprocessor\n"), stdout);
3062 fputs (_(" -Xlinker <arg> Pass <arg> on to the linker\n"), stdout);
3063 fputs (_(" -save-temps Do not delete intermediate files\n"), stdout);
3064 fputs (_(" -save-temps=<arg> Do not delete intermediate files\n"), stdout);
3065 fputs (_("\
3066 -no-canonical-prefixes Do not canonicalize paths when building relative\n\
3067 prefixes to other gcc components\n"), stdout);
3068 fputs (_(" -pipe Use pipes rather than intermediate files\n"), stdout);
3069 fputs (_(" -time Time the execution of each subprocess\n"), stdout);
3070 fputs (_(" -specs=<file> Override built-in specs with the contents of <file>\n"), stdout);
3071 fputs (_(" -std=<standard> Assume that the input sources are for <standard>\n"), stdout);
3072 fputs (_("\
3073 --sysroot=<directory> Use <directory> as the root directory for headers\n\
3074 and libraries\n"), stdout);
3075 fputs (_(" -B <directory> Add <directory> to the compiler's search paths\n"), stdout);
3076 fputs (_(" -v Display the programs invoked by the compiler\n"), stdout);
3077 fputs (_(" -### Like -v but options quoted and commands not executed\n"), stdout);
3078 fputs (_(" -E Preprocess only; do not compile, assemble or link\n"), stdout);
3079 fputs (_(" -S Compile only; do not assemble or link\n"), stdout);
3080 fputs (_(" -c Compile and assemble, but do not link\n"), stdout);
3081 fputs (_(" -o <file> Place the output into <file>\n"), stdout);
3082 fputs (_(" -pie Create a position independent executable\n"), stdout);
3083 fputs (_(" -shared Create a shared library\n"), stdout);
3084 fputs (_("\
3085 -x <language> Specify the language of the following input files\n\
3086 Permissible languages include: c c++ assembler none\n\
3087 'none' means revert to the default behavior of\n\
3088 guessing the language based on the file's extension\n\
3089 "), stdout);
3091 printf (_("\
3092 \nOptions starting with -g, -f, -m, -O, -W, or --param are automatically\n\
3093 passed on to the various sub-processes invoked by %s. In order to pass\n\
3094 other options on to these processes the -W<letter> options must be used.\n\
3095 "), progname);
3097 /* The rest of the options are displayed by invocations of the various
3098 sub-processes. */
3101 static void
3102 add_preprocessor_option (const char *option, int len)
3104 preprocessor_options.safe_push (save_string (option, len));
3107 static void
3108 add_assembler_option (const char *option, int len)
3110 assembler_options.safe_push (save_string (option, len));
3113 static void
3114 add_linker_option (const char *option, int len)
3116 linker_options.safe_push (save_string (option, len));
3119 /* Allocate space for an input file in infiles. */
3121 static void
3122 alloc_infile (void)
3124 if (n_infiles_alloc == 0)
3126 n_infiles_alloc = 16;
3127 infiles = XNEWVEC (struct infile, n_infiles_alloc);
3129 else if (n_infiles_alloc == n_infiles)
3131 n_infiles_alloc *= 2;
3132 infiles = XRESIZEVEC (struct infile, infiles, n_infiles_alloc);
3136 /* Store an input file with the given NAME and LANGUAGE in
3137 infiles. */
3139 static void
3140 add_infile (const char *name, const char *language)
3142 alloc_infile ();
3143 infiles[n_infiles].name = name;
3144 infiles[n_infiles++].language = language;
3147 /* Allocate space for a switch in switches. */
3149 static void
3150 alloc_switch (void)
3152 if (n_switches_alloc == 0)
3154 n_switches_alloc = 16;
3155 switches = XNEWVEC (struct switchstr, n_switches_alloc);
3157 else if (n_switches_alloc == n_switches)
3159 n_switches_alloc *= 2;
3160 switches = XRESIZEVEC (struct switchstr, switches, n_switches_alloc);
3164 /* Save an option OPT with N_ARGS arguments in array ARGS, marking it
3165 as validated if VALIDATED and KNOWN if it is an internal switch. */
3167 static void
3168 save_switch (const char *opt, size_t n_args, const char *const *args,
3169 bool validated, bool known)
3171 alloc_switch ();
3172 switches[n_switches].part1 = opt + 1;
3173 if (n_args == 0)
3174 switches[n_switches].args = 0;
3175 else
3177 switches[n_switches].args = XNEWVEC (const char *, n_args + 1);
3178 memcpy (switches[n_switches].args, args, n_args * sizeof (const char *));
3179 switches[n_switches].args[n_args] = NULL;
3182 switches[n_switches].live_cond = 0;
3183 switches[n_switches].validated = validated;
3184 switches[n_switches].known = known;
3185 switches[n_switches].ordering = 0;
3186 n_switches++;
3189 /* Handle an option DECODED that is unknown to the option-processing
3190 machinery. */
3192 static bool
3193 driver_unknown_option_callback (const struct cl_decoded_option *decoded)
3195 const char *opt = decoded->arg;
3196 if (opt[1] == 'W' && opt[2] == 'n' && opt[3] == 'o' && opt[4] == '-'
3197 && !(decoded->errors & CL_ERR_NEGATIVE))
3199 /* Leave unknown -Wno-* options for the compiler proper, to be
3200 diagnosed only if there are warnings. */
3201 save_switch (decoded->canonical_option[0],
3202 decoded->canonical_option_num_elements - 1,
3203 &decoded->canonical_option[1], false, true);
3204 return false;
3206 if (decoded->opt_index == OPT_SPECIAL_unknown)
3208 /* Give it a chance to define it a a spec file. */
3209 save_switch (decoded->canonical_option[0],
3210 decoded->canonical_option_num_elements - 1,
3211 &decoded->canonical_option[1], false, false);
3212 return false;
3214 else
3215 return true;
3218 /* Handle an option DECODED that is not marked as CL_DRIVER.
3219 LANG_MASK will always be CL_DRIVER. */
3221 static void
3222 driver_wrong_lang_callback (const struct cl_decoded_option *decoded,
3223 unsigned int lang_mask ATTRIBUTE_UNUSED)
3225 /* At this point, non-driver options are accepted (and expected to
3226 be passed down by specs) unless marked to be rejected by the
3227 driver. Options to be rejected by the driver but accepted by the
3228 compilers proper are treated just like completely unknown
3229 options. */
3230 const struct cl_option *option = &cl_options[decoded->opt_index];
3232 if (option->cl_reject_driver)
3233 error ("unrecognized command line option %qs",
3234 decoded->orig_option_with_args_text);
3235 else
3236 save_switch (decoded->canonical_option[0],
3237 decoded->canonical_option_num_elements - 1,
3238 &decoded->canonical_option[1], false, true);
3241 static const char *spec_lang = 0;
3242 static int last_language_n_infiles;
3244 /* Handle a driver option; arguments and return value as for
3245 handle_option. */
3247 static bool
3248 driver_handle_option (struct gcc_options *opts,
3249 struct gcc_options *opts_set,
3250 const struct cl_decoded_option *decoded,
3251 unsigned int lang_mask ATTRIBUTE_UNUSED, int kind,
3252 location_t loc,
3253 const struct cl_option_handlers *handlers ATTRIBUTE_UNUSED,
3254 diagnostic_context *dc)
3256 size_t opt_index = decoded->opt_index;
3257 const char *arg = decoded->arg;
3258 const char *compare_debug_replacement_opt;
3259 int value = decoded->value;
3260 bool validated = false;
3261 bool do_save = true;
3263 gcc_assert (opts == &global_options);
3264 gcc_assert (opts_set == &global_options_set);
3265 gcc_assert (kind == DK_UNSPECIFIED);
3266 gcc_assert (loc == UNKNOWN_LOCATION);
3267 gcc_assert (dc == global_dc);
3269 switch (opt_index)
3271 case OPT_dumpspecs:
3273 struct spec_list *sl;
3274 init_spec ();
3275 for (sl = specs; sl; sl = sl->next)
3276 printf ("*%s:\n%s\n\n", sl->name, *(sl->ptr_spec));
3277 if (link_command_spec)
3278 printf ("*link_command:\n%s\n\n", link_command_spec);
3279 exit (0);
3282 case OPT_dumpversion:
3283 printf ("%s\n", spec_version);
3284 exit (0);
3286 case OPT_dumpmachine:
3287 printf ("%s\n", spec_machine);
3288 exit (0);
3290 case OPT__version:
3291 print_version = 1;
3293 /* CPP driver cannot obtain switch from cc1_options. */
3294 if (is_cpp_driver)
3295 add_preprocessor_option ("--version", strlen ("--version"));
3296 add_assembler_option ("--version", strlen ("--version"));
3297 add_linker_option ("--version", strlen ("--version"));
3298 break;
3300 case OPT__help:
3301 print_help_list = 1;
3303 /* CPP driver cannot obtain switch from cc1_options. */
3304 if (is_cpp_driver)
3305 add_preprocessor_option ("--help", 6);
3306 add_assembler_option ("--help", 6);
3307 add_linker_option ("--help", 6);
3308 break;
3310 case OPT__help_:
3311 print_subprocess_help = 2;
3312 break;
3314 case OPT__target_help:
3315 print_subprocess_help = 1;
3317 /* CPP driver cannot obtain switch from cc1_options. */
3318 if (is_cpp_driver)
3319 add_preprocessor_option ("--target-help", 13);
3320 add_assembler_option ("--target-help", 13);
3321 add_linker_option ("--target-help", 13);
3322 break;
3324 case OPT__no_sysroot_suffix:
3325 case OPT_pass_exit_codes:
3326 case OPT_print_search_dirs:
3327 case OPT_print_file_name_:
3328 case OPT_print_prog_name_:
3329 case OPT_print_multi_lib:
3330 case OPT_print_multi_directory:
3331 case OPT_print_sysroot:
3332 case OPT_print_multi_os_directory:
3333 case OPT_print_multiarch:
3334 case OPT_print_sysroot_headers_suffix:
3335 case OPT_time:
3336 case OPT_wrapper:
3337 /* These options set the variables specified in common.opt
3338 automatically, and do not need to be saved for spec
3339 processing. */
3340 do_save = false;
3341 break;
3343 case OPT_print_libgcc_file_name:
3344 print_file_name = "libgcc.a";
3345 do_save = false;
3346 break;
3348 case OPT_fcompare_debug_second:
3349 compare_debug_second = 1;
3350 break;
3352 case OPT_fcompare_debug:
3353 switch (value)
3355 case 0:
3356 compare_debug_replacement_opt = "-fcompare-debug=";
3357 arg = "";
3358 goto compare_debug_with_arg;
3360 case 1:
3361 compare_debug_replacement_opt = "-fcompare-debug=-gtoggle";
3362 arg = "-gtoggle";
3363 goto compare_debug_with_arg;
3365 default:
3366 gcc_unreachable ();
3368 break;
3370 case OPT_fcompare_debug_:
3371 compare_debug_replacement_opt = decoded->canonical_option[0];
3372 compare_debug_with_arg:
3373 gcc_assert (decoded->canonical_option_num_elements == 1);
3374 gcc_assert (arg != NULL);
3375 if (*arg)
3376 compare_debug = 1;
3377 else
3378 compare_debug = -1;
3379 if (compare_debug < 0)
3380 compare_debug_opt = NULL;
3381 else
3382 compare_debug_opt = arg;
3383 save_switch (compare_debug_replacement_opt, 0, NULL, validated, true);
3384 return true;
3386 case OPT_Wa_:
3388 int prev, j;
3389 /* Pass the rest of this option to the assembler. */
3391 /* Split the argument at commas. */
3392 prev = 0;
3393 for (j = 0; arg[j]; j++)
3394 if (arg[j] == ',')
3396 add_assembler_option (arg + prev, j - prev);
3397 prev = j + 1;
3400 /* Record the part after the last comma. */
3401 add_assembler_option (arg + prev, j - prev);
3403 do_save = false;
3404 break;
3406 case OPT_Wp_:
3408 int prev, j;
3409 /* Pass the rest of this option to the preprocessor. */
3411 /* Split the argument at commas. */
3412 prev = 0;
3413 for (j = 0; arg[j]; j++)
3414 if (arg[j] == ',')
3416 add_preprocessor_option (arg + prev, j - prev);
3417 prev = j + 1;
3420 /* Record the part after the last comma. */
3421 add_preprocessor_option (arg + prev, j - prev);
3423 do_save = false;
3424 break;
3426 case OPT_Wl_:
3428 int prev, j;
3429 /* Split the argument at commas. */
3430 prev = 0;
3431 for (j = 0; arg[j]; j++)
3432 if (arg[j] == ',')
3434 add_infile (save_string (arg + prev, j - prev), "*");
3435 prev = j + 1;
3437 /* Record the part after the last comma. */
3438 add_infile (arg + prev, "*");
3440 do_save = false;
3441 break;
3443 case OPT_Xlinker:
3444 add_infile (arg, "*");
3445 do_save = false;
3446 break;
3448 case OPT_Xpreprocessor:
3449 add_preprocessor_option (arg, strlen (arg));
3450 do_save = false;
3451 break;
3453 case OPT_Xassembler:
3454 add_assembler_option (arg, strlen (arg));
3455 do_save = false;
3456 break;
3458 case OPT_l:
3459 /* POSIX allows separation of -l and the lib arg; canonicalize
3460 by concatenating -l with its arg */
3461 add_infile (concat ("-l", arg, NULL), "*");
3462 do_save = false;
3463 break;
3465 case OPT_L:
3466 /* Similarly, canonicalize -L for linkers that may not accept
3467 separate arguments. */
3468 save_switch (concat ("-L", arg, NULL), 0, NULL, validated, true);
3469 return true;
3471 case OPT_F:
3472 /* Likewise -F. */
3473 save_switch (concat ("-F", arg, NULL), 0, NULL, validated, true);
3474 return true;
3476 case OPT_save_temps:
3477 save_temps_flag = SAVE_TEMPS_CWD;
3478 validated = true;
3479 break;
3481 case OPT_save_temps_:
3482 if (strcmp (arg, "cwd") == 0)
3483 save_temps_flag = SAVE_TEMPS_CWD;
3484 else if (strcmp (arg, "obj") == 0
3485 || strcmp (arg, "object") == 0)
3486 save_temps_flag = SAVE_TEMPS_OBJ;
3487 else
3488 fatal_error ("%qs is an unknown -save-temps option",
3489 decoded->orig_option_with_args_text);
3490 break;
3492 case OPT_no_canonical_prefixes:
3493 /* Already handled as a special case, so ignored here. */
3494 do_save = false;
3495 break;
3497 case OPT_pipe:
3498 validated = true;
3499 /* These options set the variables specified in common.opt
3500 automatically, but do need to be saved for spec
3501 processing. */
3502 break;
3504 case OPT_specs_:
3506 struct user_specs *user = XNEW (struct user_specs);
3508 user->next = (struct user_specs *) 0;
3509 user->filename = arg;
3510 if (user_specs_tail)
3511 user_specs_tail->next = user;
3512 else
3513 user_specs_head = user;
3514 user_specs_tail = user;
3516 validated = true;
3517 break;
3519 case OPT__sysroot_:
3520 target_system_root = arg;
3521 target_system_root_changed = 1;
3522 do_save = false;
3523 break;
3525 case OPT_time_:
3526 if (report_times_to_file)
3527 fclose (report_times_to_file);
3528 report_times_to_file = fopen (arg, "a");
3529 do_save = false;
3530 break;
3532 case OPT____:
3533 /* "-###"
3534 This is similar to -v except that there is no execution
3535 of the commands and the echoed arguments are quoted. It
3536 is intended for use in shell scripts to capture the
3537 driver-generated command line. */
3538 verbose_only_flag++;
3539 verbose_flag = 1;
3540 do_save = false;
3541 break;
3543 case OPT_B:
3545 size_t len = strlen (arg);
3547 /* Catch the case where the user has forgotten to append a
3548 directory separator to the path. Note, they may be using
3549 -B to add an executable name prefix, eg "i386-elf-", in
3550 order to distinguish between multiple installations of
3551 GCC in the same directory. Hence we must check to see
3552 if appending a directory separator actually makes a
3553 valid directory name. */
3554 if (!IS_DIR_SEPARATOR (arg[len - 1])
3555 && is_directory (arg, false))
3557 char *tmp = XNEWVEC (char, len + 2);
3558 strcpy (tmp, arg);
3559 tmp[len] = DIR_SEPARATOR;
3560 tmp[++len] = 0;
3561 arg = tmp;
3564 add_prefix (&exec_prefixes, arg, NULL,
3565 PREFIX_PRIORITY_B_OPT, 0, 0);
3566 add_prefix (&startfile_prefixes, arg, NULL,
3567 PREFIX_PRIORITY_B_OPT, 0, 0);
3568 add_prefix (&include_prefixes, arg, NULL,
3569 PREFIX_PRIORITY_B_OPT, 0, 0);
3571 validated = true;
3572 break;
3574 case OPT_x:
3575 spec_lang = arg;
3576 if (!strcmp (spec_lang, "none"))
3577 /* Suppress the warning if -xnone comes after the last input
3578 file, because alternate command interfaces like g++ might
3579 find it useful to place -xnone after each input file. */
3580 spec_lang = 0;
3581 else
3582 last_language_n_infiles = n_infiles;
3583 do_save = false;
3584 break;
3586 case OPT_o:
3587 have_o = 1;
3588 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX) || defined(HAVE_TARGET_OBJECT_SUFFIX)
3589 arg = convert_filename (arg, ! have_c, 0);
3590 #endif
3591 /* Save the output name in case -save-temps=obj was used. */
3592 save_temps_prefix = xstrdup (arg);
3593 /* On some systems, ld cannot handle "-o" without a space. So
3594 split the option from its argument. */
3595 save_switch ("-o", 1, &arg, validated, true);
3596 return true;
3598 case OPT_static_libgcc:
3599 case OPT_shared_libgcc:
3600 case OPT_static_libgfortran:
3601 case OPT_static_libstdc__:
3602 /* These are always valid, since gcc.c itself understands the
3603 first two, gfortranspec.c understands -static-libgfortran and
3604 g++spec.c understands -static-libstdc++ */
3605 validated = true;
3606 break;
3608 default:
3609 /* Various driver options need no special processing at this
3610 point, having been handled in a prescan above or being
3611 handled by specs. */
3612 break;
3615 if (do_save)
3616 save_switch (decoded->canonical_option[0],
3617 decoded->canonical_option_num_elements - 1,
3618 &decoded->canonical_option[1], validated, true);
3619 return true;
3622 /* Put the driver's standard set of option handlers in *HANDLERS. */
3624 static void
3625 set_option_handlers (struct cl_option_handlers *handlers)
3627 handlers->unknown_option_callback = driver_unknown_option_callback;
3628 handlers->wrong_lang_callback = driver_wrong_lang_callback;
3629 handlers->num_handlers = 3;
3630 handlers->handlers[0].handler = driver_handle_option;
3631 handlers->handlers[0].mask = CL_DRIVER;
3632 handlers->handlers[1].handler = common_handle_option;
3633 handlers->handlers[1].mask = CL_COMMON;
3634 handlers->handlers[2].handler = target_handle_option;
3635 handlers->handlers[2].mask = CL_TARGET;
3638 /* Create the vector `switches' and its contents.
3639 Store its length in `n_switches'. */
3641 static void
3642 process_command (unsigned int decoded_options_count,
3643 struct cl_decoded_option *decoded_options)
3645 const char *temp;
3646 char *temp1;
3647 char *tooldir_prefix, *tooldir_prefix2;
3648 char *(*get_relative_prefix) (const char *, const char *,
3649 const char *) = NULL;
3650 struct cl_option_handlers handlers;
3651 unsigned int j;
3653 gcc_exec_prefix = getenv ("GCC_EXEC_PREFIX");
3655 n_switches = 0;
3656 n_infiles = 0;
3657 added_libraries = 0;
3659 /* Figure compiler version from version string. */
3661 compiler_version = temp1 = xstrdup (version_string);
3663 for (; *temp1; ++temp1)
3665 if (*temp1 == ' ')
3667 *temp1 = '\0';
3668 break;
3672 /* Handle any -no-canonical-prefixes flag early, to assign the function
3673 that builds relative prefixes. This function creates default search
3674 paths that are needed later in normal option handling. */
3676 for (j = 1; j < decoded_options_count; j++)
3678 if (decoded_options[j].opt_index == OPT_no_canonical_prefixes)
3680 get_relative_prefix = make_relative_prefix_ignore_links;
3681 break;
3684 if (! get_relative_prefix)
3685 get_relative_prefix = make_relative_prefix;
3687 /* Set up the default search paths. If there is no GCC_EXEC_PREFIX,
3688 see if we can create it from the pathname specified in
3689 decoded_options[0].arg. */
3691 gcc_libexec_prefix = standard_libexec_prefix;
3692 #ifndef VMS
3693 /* FIXME: make_relative_prefix doesn't yet work for VMS. */
3694 if (!gcc_exec_prefix)
3696 gcc_exec_prefix = get_relative_prefix (decoded_options[0].arg,
3697 standard_bindir_prefix,
3698 standard_exec_prefix);
3699 gcc_libexec_prefix = get_relative_prefix (decoded_options[0].arg,
3700 standard_bindir_prefix,
3701 standard_libexec_prefix);
3702 if (gcc_exec_prefix)
3703 xputenv (concat ("GCC_EXEC_PREFIX=", gcc_exec_prefix, NULL));
3705 else
3707 /* make_relative_prefix requires a program name, but
3708 GCC_EXEC_PREFIX is typically a directory name with a trailing
3709 / (which is ignored by make_relative_prefix), so append a
3710 program name. */
3711 char *tmp_prefix = concat (gcc_exec_prefix, "gcc", NULL);
3712 gcc_libexec_prefix = get_relative_prefix (tmp_prefix,
3713 standard_exec_prefix,
3714 standard_libexec_prefix);
3716 /* The path is unrelocated, so fallback to the original setting. */
3717 if (!gcc_libexec_prefix)
3718 gcc_libexec_prefix = standard_libexec_prefix;
3720 free (tmp_prefix);
3722 #else
3723 #endif
3724 /* From this point onward, gcc_exec_prefix is non-null if the toolchain
3725 is relocated. The toolchain was either relocated using GCC_EXEC_PREFIX
3726 or an automatically created GCC_EXEC_PREFIX from
3727 decoded_options[0].arg. */
3729 /* Do language-specific adjustment/addition of flags. */
3730 lang_specific_driver (&decoded_options, &decoded_options_count,
3731 &added_libraries);
3733 if (gcc_exec_prefix)
3735 int len = strlen (gcc_exec_prefix);
3737 if (len > (int) sizeof ("/lib/gcc/") - 1
3738 && (IS_DIR_SEPARATOR (gcc_exec_prefix[len-1])))
3740 temp = gcc_exec_prefix + len - sizeof ("/lib/gcc/") + 1;
3741 if (IS_DIR_SEPARATOR (*temp)
3742 && filename_ncmp (temp + 1, "lib", 3) == 0
3743 && IS_DIR_SEPARATOR (temp[4])
3744 && filename_ncmp (temp + 5, "gcc", 3) == 0)
3745 len -= sizeof ("/lib/gcc/") - 1;
3748 set_std_prefix (gcc_exec_prefix, len);
3749 add_prefix (&exec_prefixes, gcc_libexec_prefix, "GCC",
3750 PREFIX_PRIORITY_LAST, 0, 0);
3751 add_prefix (&startfile_prefixes, gcc_exec_prefix, "GCC",
3752 PREFIX_PRIORITY_LAST, 0, 0);
3755 /* COMPILER_PATH and LIBRARY_PATH have values
3756 that are lists of directory names with colons. */
3758 temp = getenv ("COMPILER_PATH");
3759 if (temp)
3761 const char *startp, *endp;
3762 char *nstore = (char *) alloca (strlen (temp) + 3);
3764 startp = endp = temp;
3765 while (1)
3767 if (*endp == PATH_SEPARATOR || *endp == 0)
3769 strncpy (nstore, startp, endp - startp);
3770 if (endp == startp)
3771 strcpy (nstore, concat (".", dir_separator_str, NULL));
3772 else if (!IS_DIR_SEPARATOR (endp[-1]))
3774 nstore[endp - startp] = DIR_SEPARATOR;
3775 nstore[endp - startp + 1] = 0;
3777 else
3778 nstore[endp - startp] = 0;
3779 add_prefix (&exec_prefixes, nstore, 0,
3780 PREFIX_PRIORITY_LAST, 0, 0);
3781 add_prefix (&include_prefixes, nstore, 0,
3782 PREFIX_PRIORITY_LAST, 0, 0);
3783 if (*endp == 0)
3784 break;
3785 endp = startp = endp + 1;
3787 else
3788 endp++;
3792 temp = getenv (LIBRARY_PATH_ENV);
3793 if (temp && *cross_compile == '0')
3795 const char *startp, *endp;
3796 char *nstore = (char *) alloca (strlen (temp) + 3);
3798 startp = endp = temp;
3799 while (1)
3801 if (*endp == PATH_SEPARATOR || *endp == 0)
3803 strncpy (nstore, startp, endp - startp);
3804 if (endp == startp)
3805 strcpy (nstore, concat (".", dir_separator_str, NULL));
3806 else if (!IS_DIR_SEPARATOR (endp[-1]))
3808 nstore[endp - startp] = DIR_SEPARATOR;
3809 nstore[endp - startp + 1] = 0;
3811 else
3812 nstore[endp - startp] = 0;
3813 add_prefix (&startfile_prefixes, nstore, NULL,
3814 PREFIX_PRIORITY_LAST, 0, 1);
3815 if (*endp == 0)
3816 break;
3817 endp = startp = endp + 1;
3819 else
3820 endp++;
3824 /* Use LPATH like LIBRARY_PATH (for the CMU build program). */
3825 temp = getenv ("LPATH");
3826 if (temp && *cross_compile == '0')
3828 const char *startp, *endp;
3829 char *nstore = (char *) alloca (strlen (temp) + 3);
3831 startp = endp = temp;
3832 while (1)
3834 if (*endp == PATH_SEPARATOR || *endp == 0)
3836 strncpy (nstore, startp, endp - startp);
3837 if (endp == startp)
3838 strcpy (nstore, concat (".", dir_separator_str, NULL));
3839 else if (!IS_DIR_SEPARATOR (endp[-1]))
3841 nstore[endp - startp] = DIR_SEPARATOR;
3842 nstore[endp - startp + 1] = 0;
3844 else
3845 nstore[endp - startp] = 0;
3846 add_prefix (&startfile_prefixes, nstore, NULL,
3847 PREFIX_PRIORITY_LAST, 0, 1);
3848 if (*endp == 0)
3849 break;
3850 endp = startp = endp + 1;
3852 else
3853 endp++;
3857 /* Process the options and store input files and switches in their
3858 vectors. */
3860 last_language_n_infiles = -1;
3862 set_option_handlers (&handlers);
3864 for (j = 1; j < decoded_options_count; j++)
3866 switch (decoded_options[j].opt_index)
3868 case OPT_S:
3869 case OPT_c:
3870 case OPT_E:
3871 have_c = 1;
3872 break;
3874 if (have_c)
3875 break;
3878 for (j = 1; j < decoded_options_count; j++)
3880 if (decoded_options[j].opt_index == OPT_SPECIAL_input_file)
3882 const char *arg = decoded_options[j].arg;
3883 const char *p = strrchr (arg, '@');
3884 char *fname;
3885 long offset;
3886 int consumed;
3887 #ifdef HAVE_TARGET_OBJECT_SUFFIX
3888 arg = convert_filename (arg, 0, access (arg, F_OK));
3889 #endif
3890 /* For LTO static archive support we handle input file
3891 specifications that are composed of a filename and
3892 an offset like FNAME@OFFSET. */
3893 if (p
3894 && p != arg
3895 && sscanf (p, "@%li%n", &offset, &consumed) >= 1
3896 && strlen (p) == (unsigned int)consumed)
3898 fname = (char *)xmalloc (p - arg + 1);
3899 memcpy (fname, arg, p - arg);
3900 fname[p - arg] = '\0';
3901 /* Only accept non-stdin and existing FNAME parts, otherwise
3902 try with the full name. */
3903 if (strcmp (fname, "-") == 0 || access (fname, F_OK) < 0)
3905 free (fname);
3906 fname = xstrdup (arg);
3909 else
3910 fname = xstrdup (arg);
3912 if (strcmp (fname, "-") != 0 && access (fname, F_OK) < 0)
3913 perror_with_name (fname);
3914 else
3915 add_infile (arg, spec_lang);
3917 free (fname);
3918 continue;
3921 read_cmdline_option (&global_options, &global_options_set,
3922 decoded_options + j, UNKNOWN_LOCATION,
3923 CL_DRIVER, &handlers, global_dc);
3926 /* If -save-temps=obj and -o name, create the prefix to use for %b.
3927 Otherwise just make -save-temps=obj the same as -save-temps=cwd. */
3928 if (save_temps_flag == SAVE_TEMPS_OBJ && save_temps_prefix != NULL)
3930 save_temps_length = strlen (save_temps_prefix);
3931 temp = strrchr (lbasename (save_temps_prefix), '.');
3932 if (temp)
3934 save_temps_length -= strlen (temp);
3935 save_temps_prefix[save_temps_length] = '\0';
3939 else if (save_temps_prefix != NULL)
3941 free (save_temps_prefix);
3942 save_temps_prefix = NULL;
3945 if (save_temps_flag && use_pipes)
3947 /* -save-temps overrides -pipe, so that temp files are produced */
3948 if (save_temps_flag)
3949 warning (0, "-pipe ignored because -save-temps specified");
3950 use_pipes = 0;
3953 if (!compare_debug)
3955 const char *gcd = getenv ("GCC_COMPARE_DEBUG");
3957 if (gcd && gcd[0] == '-')
3959 compare_debug = 2;
3960 compare_debug_opt = gcd;
3962 else if (gcd && *gcd && strcmp (gcd, "0"))
3964 compare_debug = 3;
3965 compare_debug_opt = "-gtoggle";
3968 else if (compare_debug < 0)
3970 compare_debug = 0;
3971 gcc_assert (!compare_debug_opt);
3974 /* Set up the search paths. We add directories that we expect to
3975 contain GNU Toolchain components before directories specified by
3976 the machine description so that we will find GNU components (like
3977 the GNU assembler) before those of the host system. */
3979 /* If we don't know where the toolchain has been installed, use the
3980 configured-in locations. */
3981 if (!gcc_exec_prefix)
3983 #ifndef OS2
3984 add_prefix (&exec_prefixes, standard_libexec_prefix, "GCC",
3985 PREFIX_PRIORITY_LAST, 1, 0);
3986 add_prefix (&exec_prefixes, standard_libexec_prefix, "BINUTILS",
3987 PREFIX_PRIORITY_LAST, 2, 0);
3988 add_prefix (&exec_prefixes, standard_exec_prefix, "BINUTILS",
3989 PREFIX_PRIORITY_LAST, 2, 0);
3990 #endif
3991 add_prefix (&startfile_prefixes, standard_exec_prefix, "BINUTILS",
3992 PREFIX_PRIORITY_LAST, 1, 0);
3995 gcc_assert (!IS_ABSOLUTE_PATH (tooldir_base_prefix));
3996 tooldir_prefix2 = concat (tooldir_base_prefix, spec_machine,
3997 dir_separator_str, NULL);
3999 /* Look for tools relative to the location from which the driver is
4000 running, or, if that is not available, the configured prefix. */
4001 tooldir_prefix
4002 = concat (gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
4003 spec_machine, dir_separator_str,
4004 spec_version, dir_separator_str, tooldir_prefix2, NULL);
4005 free (tooldir_prefix2);
4007 add_prefix (&exec_prefixes,
4008 concat (tooldir_prefix, "bin", dir_separator_str, NULL),
4009 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 0);
4010 add_prefix (&startfile_prefixes,
4011 concat (tooldir_prefix, "lib", dir_separator_str, NULL),
4012 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 1);
4013 free (tooldir_prefix);
4015 #if defined(TARGET_SYSTEM_ROOT_RELOCATABLE) && !defined(VMS)
4016 /* If the normal TARGET_SYSTEM_ROOT is inside of $exec_prefix,
4017 then consider it to relocate with the rest of the GCC installation
4018 if GCC_EXEC_PREFIX is set.
4019 ``make_relative_prefix'' is not compiled for VMS, so don't call it. */
4020 if (target_system_root && !target_system_root_changed && gcc_exec_prefix)
4022 char *tmp_prefix = get_relative_prefix (decoded_options[0].arg,
4023 standard_bindir_prefix,
4024 target_system_root);
4025 if (tmp_prefix && access_check (tmp_prefix, F_OK) == 0)
4027 target_system_root = tmp_prefix;
4028 target_system_root_changed = 1;
4031 #endif
4033 /* More prefixes are enabled in main, after we read the specs file
4034 and determine whether this is cross-compilation or not. */
4036 if (n_infiles == last_language_n_infiles && spec_lang != 0)
4037 warning (0, "%<-x %s%> after last input file has no effect", spec_lang);
4039 /* Synthesize -fcompare-debug flag from the GCC_COMPARE_DEBUG
4040 environment variable. */
4041 if (compare_debug == 2 || compare_debug == 3)
4043 const char *opt = concat ("-fcompare-debug=", compare_debug_opt, NULL);
4044 save_switch (opt, 0, NULL, false, true);
4045 compare_debug = 1;
4048 /* Ensure we only invoke each subprocess once. */
4049 if (print_subprocess_help || print_help_list || print_version)
4051 n_infiles = 0;
4053 /* Create a dummy input file, so that we can pass
4054 the help option on to the various sub-processes. */
4055 add_infile ("help-dummy", "c");
4058 alloc_switch ();
4059 switches[n_switches].part1 = 0;
4060 alloc_infile ();
4061 infiles[n_infiles].name = 0;
4064 /* Store switches not filtered out by %<S in spec in COLLECT_GCC_OPTIONS
4065 and place that in the environment. */
4067 static void
4068 set_collect_gcc_options (void)
4070 int i;
4071 int first_time;
4073 /* Build COLLECT_GCC_OPTIONS to have all of the options specified to
4074 the compiler. */
4075 obstack_grow (&collect_obstack, "COLLECT_GCC_OPTIONS=",
4076 sizeof ("COLLECT_GCC_OPTIONS=") - 1);
4078 first_time = TRUE;
4079 for (i = 0; (int) i < n_switches; i++)
4081 const char *const *args;
4082 const char *p, *q;
4083 if (!first_time)
4084 obstack_grow (&collect_obstack, " ", 1);
4086 first_time = FALSE;
4088 /* Ignore elided switches. */
4089 if ((switches[i].live_cond
4090 & (SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC))
4091 == SWITCH_IGNORE)
4092 continue;
4094 obstack_grow (&collect_obstack, "'-", 2);
4095 q = switches[i].part1;
4096 while ((p = strchr (q, '\'')))
4098 obstack_grow (&collect_obstack, q, p - q);
4099 obstack_grow (&collect_obstack, "'\\''", 4);
4100 q = ++p;
4102 obstack_grow (&collect_obstack, q, strlen (q));
4103 obstack_grow (&collect_obstack, "'", 1);
4105 for (args = switches[i].args; args && *args; args++)
4107 obstack_grow (&collect_obstack, " '", 2);
4108 q = *args;
4109 while ((p = strchr (q, '\'')))
4111 obstack_grow (&collect_obstack, q, p - q);
4112 obstack_grow (&collect_obstack, "'\\''", 4);
4113 q = ++p;
4115 obstack_grow (&collect_obstack, q, strlen (q));
4116 obstack_grow (&collect_obstack, "'", 1);
4119 obstack_grow (&collect_obstack, "\0", 1);
4120 xputenv (XOBFINISH (&collect_obstack, char *));
4123 /* Process a spec string, accumulating and running commands. */
4125 /* These variables describe the input file name.
4126 input_file_number is the index on outfiles of this file,
4127 so that the output file name can be stored for later use by %o.
4128 input_basename is the start of the part of the input file
4129 sans all directory names, and basename_length is the number
4130 of characters starting there excluding the suffix .c or whatever. */
4132 static const char *gcc_input_filename;
4133 static int input_file_number;
4134 size_t input_filename_length;
4135 static int basename_length;
4136 static int suffixed_basename_length;
4137 static const char *input_basename;
4138 static const char *input_suffix;
4139 #ifndef HOST_LACKS_INODE_NUMBERS
4140 static struct stat input_stat;
4141 #endif
4142 static int input_stat_set;
4144 /* The compiler used to process the current input file. */
4145 static struct compiler *input_file_compiler;
4147 /* These are variables used within do_spec and do_spec_1. */
4149 /* Nonzero if an arg has been started and not yet terminated
4150 (with space, tab or newline). */
4151 static int arg_going;
4153 /* Nonzero means %d or %g has been seen; the next arg to be terminated
4154 is a temporary file name. */
4155 static int delete_this_arg;
4157 /* Nonzero means %w has been seen; the next arg to be terminated
4158 is the output file name of this compilation. */
4159 static int this_is_output_file;
4161 /* Nonzero means %s has been seen; the next arg to be terminated
4162 is the name of a library file and we should try the standard
4163 search dirs for it. */
4164 static int this_is_library_file;
4166 /* Nonzero means %T has been seen; the next arg to be terminated
4167 is the name of a linker script and we should try all of the
4168 standard search dirs for it. If it is found insert a --script
4169 command line switch and then substitute the full path in place,
4170 otherwise generate an error message. */
4171 static int this_is_linker_script;
4173 /* Nonzero means that the input of this command is coming from a pipe. */
4174 static int input_from_pipe;
4176 /* Nonnull means substitute this for any suffix when outputting a switches
4177 arguments. */
4178 static const char *suffix_subst;
4180 /* If there is an argument being accumulated, terminate it and store it. */
4182 static void
4183 end_going_arg (void)
4185 if (arg_going)
4187 const char *string;
4189 obstack_1grow (&obstack, 0);
4190 string = XOBFINISH (&obstack, const char *);
4191 if (this_is_library_file)
4192 string = find_file (string);
4193 if (this_is_linker_script)
4195 char * full_script_path = find_a_file (&startfile_prefixes, string, R_OK, true);
4197 if (full_script_path == NULL)
4199 error ("unable to locate default linker script %qs in the library search paths", string);
4200 /* Script was not found on search path. */
4201 return;
4203 store_arg ("--script", false, false);
4204 string = full_script_path;
4206 store_arg (string, delete_this_arg, this_is_output_file);
4207 if (this_is_output_file)
4208 outfiles[input_file_number] = string;
4209 arg_going = 0;
4214 /* Parse the WRAPPER string which is a comma separated list of the command line
4215 and insert them into the beginning of argbuf. */
4217 static void
4218 insert_wrapper (const char *wrapper)
4220 int n = 0;
4221 int i;
4222 char *buf = xstrdup (wrapper);
4223 char *p = buf;
4224 unsigned int old_length = argbuf.length ();
4228 n++;
4229 while (*p == ',')
4230 p++;
4232 while ((p = strchr (p, ',')) != NULL);
4234 argbuf.safe_grow (old_length + n);
4235 memmove (argbuf.address () + n,
4236 argbuf.address (),
4237 old_length * sizeof (const_char_p));
4239 i = 0;
4240 p = buf;
4243 while (*p == ',')
4245 *p = 0;
4246 p++;
4248 argbuf[i] = p;
4249 i++;
4251 while ((p = strchr (p, ',')) != NULL);
4252 gcc_assert (i == n);
4255 /* Process the spec SPEC and run the commands specified therein.
4256 Returns 0 if the spec is successfully processed; -1 if failed. */
4259 do_spec (const char *spec)
4261 int value;
4263 value = do_spec_2 (spec);
4265 /* Force out any unfinished command.
4266 If -pipe, this forces out the last command if it ended in `|'. */
4267 if (value == 0)
4269 if (argbuf.length () > 0
4270 && !strcmp (argbuf.last (), "|"))
4271 argbuf.pop ();
4273 set_collect_gcc_options ();
4275 if (argbuf.length () > 0)
4276 value = execute ();
4279 return value;
4282 static int
4283 do_spec_2 (const char *spec)
4285 int result;
4287 clear_args ();
4288 arg_going = 0;
4289 delete_this_arg = 0;
4290 this_is_output_file = 0;
4291 this_is_library_file = 0;
4292 this_is_linker_script = 0;
4293 input_from_pipe = 0;
4294 suffix_subst = NULL;
4296 result = do_spec_1 (spec, 0, NULL);
4298 end_going_arg ();
4300 return result;
4304 /* Process the given spec string and add any new options to the end
4305 of the switches/n_switches array. */
4307 static void
4308 do_option_spec (const char *name, const char *spec)
4310 unsigned int i, value_count, value_len;
4311 const char *p, *q, *value;
4312 char *tmp_spec, *tmp_spec_p;
4314 if (configure_default_options[0].name == NULL)
4315 return;
4317 for (i = 0; i < ARRAY_SIZE (configure_default_options); i++)
4318 if (strcmp (configure_default_options[i].name, name) == 0)
4319 break;
4320 if (i == ARRAY_SIZE (configure_default_options))
4321 return;
4323 value = configure_default_options[i].value;
4324 value_len = strlen (value);
4326 /* Compute the size of the final spec. */
4327 value_count = 0;
4328 p = spec;
4329 while ((p = strstr (p, "%(VALUE)")) != NULL)
4331 p ++;
4332 value_count ++;
4335 /* Replace each %(VALUE) by the specified value. */
4336 tmp_spec = (char *) alloca (strlen (spec) + 1
4337 + value_count * (value_len - strlen ("%(VALUE)")));
4338 tmp_spec_p = tmp_spec;
4339 q = spec;
4340 while ((p = strstr (q, "%(VALUE)")) != NULL)
4342 memcpy (tmp_spec_p, q, p - q);
4343 tmp_spec_p = tmp_spec_p + (p - q);
4344 memcpy (tmp_spec_p, value, value_len);
4345 tmp_spec_p += value_len;
4346 q = p + strlen ("%(VALUE)");
4348 strcpy (tmp_spec_p, q);
4350 do_self_spec (tmp_spec);
4353 /* Process the given spec string and add any new options to the end
4354 of the switches/n_switches array. */
4356 static void
4357 do_self_spec (const char *spec)
4359 int i;
4361 do_spec_2 (spec);
4362 do_spec_1 (" ", 0, NULL);
4364 /* Mark %<S switches processed by do_self_spec to be ignored permanently.
4365 do_self_specs adds the replacements to switches array, so it shouldn't
4366 be processed afterwards. */
4367 for (i = 0; i < n_switches; i++)
4368 if ((switches[i].live_cond & SWITCH_IGNORE))
4369 switches[i].live_cond |= SWITCH_IGNORE_PERMANENTLY;
4371 if (argbuf.length () > 0)
4373 const char **argbuf_copy;
4374 struct cl_decoded_option *decoded_options;
4375 struct cl_option_handlers handlers;
4376 unsigned int decoded_options_count;
4377 unsigned int j;
4379 /* Create a copy of argbuf with a dummy argv[0] entry for
4380 decode_cmdline_options_to_array. */
4381 argbuf_copy = XNEWVEC (const char *,
4382 argbuf.length () + 1);
4383 argbuf_copy[0] = "";
4384 memcpy (argbuf_copy + 1, argbuf.address (),
4385 argbuf.length () * sizeof (const char *));
4387 decode_cmdline_options_to_array (argbuf.length () + 1,
4388 argbuf_copy,
4389 CL_DRIVER, &decoded_options,
4390 &decoded_options_count);
4391 free (argbuf_copy);
4393 set_option_handlers (&handlers);
4395 for (j = 1; j < decoded_options_count; j++)
4397 switch (decoded_options[j].opt_index)
4399 case OPT_SPECIAL_input_file:
4400 /* Specs should only generate options, not input
4401 files. */
4402 if (strcmp (decoded_options[j].arg, "-") != 0)
4403 fatal_error ("switch %qs does not start with %<-%>",
4404 decoded_options[j].arg);
4405 else
4406 fatal_error ("spec-generated switch is just %<-%>");
4407 break;
4409 case OPT_fcompare_debug_second:
4410 case OPT_fcompare_debug:
4411 case OPT_fcompare_debug_:
4412 case OPT_o:
4413 /* Avoid duplicate processing of some options from
4414 compare-debug specs; just save them here. */
4415 save_switch (decoded_options[j].canonical_option[0],
4416 (decoded_options[j].canonical_option_num_elements
4417 - 1),
4418 &decoded_options[j].canonical_option[1], false, true);
4419 break;
4421 default:
4422 read_cmdline_option (&global_options, &global_options_set,
4423 decoded_options + j, UNKNOWN_LOCATION,
4424 CL_DRIVER, &handlers, global_dc);
4425 break;
4429 alloc_switch ();
4430 switches[n_switches].part1 = 0;
4434 /* Callback for processing %D and %I specs. */
4436 struct spec_path_info {
4437 const char *option;
4438 const char *append;
4439 size_t append_len;
4440 bool omit_relative;
4441 bool separate_options;
4444 static void *
4445 spec_path (char *path, void *data)
4447 struct spec_path_info *info = (struct spec_path_info *) data;
4448 size_t len = 0;
4449 char save = 0;
4451 if (info->omit_relative && !IS_ABSOLUTE_PATH (path))
4452 return NULL;
4454 if (info->append_len != 0)
4456 len = strlen (path);
4457 memcpy (path + len, info->append, info->append_len + 1);
4460 if (!is_directory (path, true))
4461 return NULL;
4463 do_spec_1 (info->option, 1, NULL);
4464 if (info->separate_options)
4465 do_spec_1 (" ", 0, NULL);
4467 if (info->append_len == 0)
4469 len = strlen (path);
4470 save = path[len - 1];
4471 if (IS_DIR_SEPARATOR (path[len - 1]))
4472 path[len - 1] = '\0';
4475 do_spec_1 (path, 1, NULL);
4476 do_spec_1 (" ", 0, NULL);
4478 /* Must not damage the original path. */
4479 if (info->append_len == 0)
4480 path[len - 1] = save;
4482 return NULL;
4485 /* Create a temporary FILE with the contents of ARGV. Add @FILE to the
4486 argument list. */
4488 static void
4489 create_at_file (char **argv)
4491 char *temp_file = make_temp_file ("");
4492 char *at_argument = concat ("@", temp_file, NULL);
4493 FILE *f = fopen (temp_file, "w");
4494 int status;
4496 if (f == NULL)
4497 fatal_error ("could not open temporary response file %s",
4498 temp_file);
4500 status = writeargv (argv, f);
4502 if (status)
4503 fatal_error ("could not write to temporary response file %s",
4504 temp_file);
4506 status = fclose (f);
4508 if (EOF == status)
4509 fatal_error ("could not close temporary response file %s",
4510 temp_file);
4512 store_arg (at_argument, 0, 0);
4514 record_temp_file (temp_file, !save_temps_flag, !save_temps_flag);
4517 /* True if we should compile INFILE. */
4519 static bool
4520 compile_input_file_p (struct infile *infile)
4522 if ((!infile->language) || (infile->language[0] != '*'))
4523 if (infile->incompiler == input_file_compiler)
4524 return true;
4525 return false;
4528 /* Process each member of VEC as a spec. */
4530 static void
4531 do_specs_vec (vec<char_p> vec)
4533 unsigned ix;
4534 char *opt;
4536 FOR_EACH_VEC_ELT (vec, ix, opt)
4538 do_spec_1 (opt, 1, NULL);
4539 /* Make each accumulated option a separate argument. */
4540 do_spec_1 (" ", 0, NULL);
4544 /* Process the sub-spec SPEC as a portion of a larger spec.
4545 This is like processing a whole spec except that we do
4546 not initialize at the beginning and we do not supply a
4547 newline by default at the end.
4548 INSWITCH nonzero means don't process %-sequences in SPEC;
4549 in this case, % is treated as an ordinary character.
4550 This is used while substituting switches.
4551 INSWITCH nonzero also causes SPC not to terminate an argument.
4553 Value is zero unless a line was finished
4554 and the command on that line reported an error. */
4556 static int
4557 do_spec_1 (const char *spec, int inswitch, const char *soft_matched_part)
4559 const char *p = spec;
4560 int c;
4561 int i;
4562 int value;
4564 /* If it's an empty string argument to a switch, keep it as is. */
4565 if (inswitch && !*p)
4566 arg_going = 1;
4568 while ((c = *p++))
4569 /* If substituting a switch, treat all chars like letters.
4570 Otherwise, NL, SPC, TAB and % are special. */
4571 switch (inswitch ? 'a' : c)
4573 case '\n':
4574 end_going_arg ();
4576 if (argbuf.length () > 0
4577 && !strcmp (argbuf.last (), "|"))
4579 /* A `|' before the newline means use a pipe here,
4580 but only if -pipe was specified.
4581 Otherwise, execute now and don't pass the `|' as an arg. */
4582 if (use_pipes)
4584 input_from_pipe = 1;
4585 break;
4587 else
4588 argbuf.pop ();
4591 set_collect_gcc_options ();
4593 if (argbuf.length () > 0)
4595 value = execute ();
4596 if (value)
4597 return value;
4599 /* Reinitialize for a new command, and for a new argument. */
4600 clear_args ();
4601 arg_going = 0;
4602 delete_this_arg = 0;
4603 this_is_output_file = 0;
4604 this_is_library_file = 0;
4605 this_is_linker_script = 0;
4606 input_from_pipe = 0;
4607 break;
4609 case '|':
4610 end_going_arg ();
4612 /* Use pipe */
4613 obstack_1grow (&obstack, c);
4614 arg_going = 1;
4615 break;
4617 case '\t':
4618 case ' ':
4619 end_going_arg ();
4621 /* Reinitialize for a new argument. */
4622 delete_this_arg = 0;
4623 this_is_output_file = 0;
4624 this_is_library_file = 0;
4625 this_is_linker_script = 0;
4626 break;
4628 case '%':
4629 switch (c = *p++)
4631 case 0:
4632 fatal_error ("spec %qs invalid", spec);
4634 case 'b':
4635 if (save_temps_length)
4636 obstack_grow (&obstack, save_temps_prefix, save_temps_length);
4637 else
4638 obstack_grow (&obstack, input_basename, basename_length);
4639 if (compare_debug < 0)
4640 obstack_grow (&obstack, ".gk", 3);
4641 arg_going = 1;
4642 break;
4644 case 'B':
4645 if (save_temps_length)
4646 obstack_grow (&obstack, save_temps_prefix, save_temps_length);
4647 else
4648 obstack_grow (&obstack, input_basename, suffixed_basename_length);
4649 if (compare_debug < 0)
4650 obstack_grow (&obstack, ".gk", 3);
4651 arg_going = 1;
4652 break;
4654 case 'd':
4655 delete_this_arg = 2;
4656 break;
4658 /* Dump out the directories specified with LIBRARY_PATH,
4659 followed by the absolute directories
4660 that we search for startfiles. */
4661 case 'D':
4663 struct spec_path_info info;
4665 info.option = "-L";
4666 info.append_len = 0;
4667 #ifdef RELATIVE_PREFIX_NOT_LINKDIR
4668 /* Used on systems which record the specified -L dirs
4669 and use them to search for dynamic linking.
4670 Relative directories always come from -B,
4671 and it is better not to use them for searching
4672 at run time. In particular, stage1 loses. */
4673 info.omit_relative = true;
4674 #else
4675 info.omit_relative = false;
4676 #endif
4677 info.separate_options = false;
4679 for_each_path (&startfile_prefixes, true, 0, spec_path, &info);
4681 break;
4683 case 'e':
4684 /* %efoo means report an error with `foo' as error message
4685 and don't execute any more commands for this file. */
4687 const char *q = p;
4688 char *buf;
4689 while (*p != 0 && *p != '\n')
4690 p++;
4691 buf = (char *) alloca (p - q + 1);
4692 strncpy (buf, q, p - q);
4693 buf[p - q] = 0;
4694 error ("%s", _(buf));
4695 return -1;
4697 break;
4698 case 'n':
4699 /* %nfoo means report a notice with `foo' on stderr. */
4701 const char *q = p;
4702 char *buf;
4703 while (*p != 0 && *p != '\n')
4704 p++;
4705 buf = (char *) alloca (p - q + 1);
4706 strncpy (buf, q, p - q);
4707 buf[p - q] = 0;
4708 inform (0, "%s", _(buf));
4709 if (*p)
4710 p++;
4712 break;
4714 case 'j':
4716 struct stat st;
4718 /* If save_temps_flag is off, and the HOST_BIT_BUCKET is
4719 defined, and it is not a directory, and it is
4720 writable, use it. Otherwise, treat this like any
4721 other temporary file. */
4723 if ((!save_temps_flag)
4724 && (stat (HOST_BIT_BUCKET, &st) == 0) && (!S_ISDIR (st.st_mode))
4725 && (access (HOST_BIT_BUCKET, W_OK) == 0))
4727 obstack_grow (&obstack, HOST_BIT_BUCKET,
4728 strlen (HOST_BIT_BUCKET));
4729 delete_this_arg = 0;
4730 arg_going = 1;
4731 break;
4734 goto create_temp_file;
4735 case '|':
4736 if (use_pipes)
4738 obstack_1grow (&obstack, '-');
4739 delete_this_arg = 0;
4740 arg_going = 1;
4742 /* consume suffix */
4743 while (*p == '.' || ISALNUM ((unsigned char) *p))
4744 p++;
4745 if (p[0] == '%' && p[1] == 'O')
4746 p += 2;
4748 break;
4750 goto create_temp_file;
4751 case 'm':
4752 if (use_pipes)
4754 /* consume suffix */
4755 while (*p == '.' || ISALNUM ((unsigned char) *p))
4756 p++;
4757 if (p[0] == '%' && p[1] == 'O')
4758 p += 2;
4760 break;
4762 goto create_temp_file;
4763 case 'g':
4764 case 'u':
4765 case 'U':
4766 create_temp_file:
4768 struct temp_name *t;
4769 int suffix_length;
4770 const char *suffix = p;
4771 char *saved_suffix = NULL;
4773 while (*p == '.' || ISALNUM ((unsigned char) *p))
4774 p++;
4775 suffix_length = p - suffix;
4776 if (p[0] == '%' && p[1] == 'O')
4778 p += 2;
4779 /* We don't support extra suffix characters after %O. */
4780 if (*p == '.' || ISALNUM ((unsigned char) *p))
4781 fatal_error ("spec %qs has invalid %<%%0%c%>", spec, *p);
4782 if (suffix_length == 0)
4783 suffix = TARGET_OBJECT_SUFFIX;
4784 else
4786 saved_suffix
4787 = XNEWVEC (char, suffix_length
4788 + strlen (TARGET_OBJECT_SUFFIX));
4789 strncpy (saved_suffix, suffix, suffix_length);
4790 strcpy (saved_suffix + suffix_length,
4791 TARGET_OBJECT_SUFFIX);
4793 suffix_length += strlen (TARGET_OBJECT_SUFFIX);
4796 if (compare_debug < 0)
4798 suffix = concat (".gk", suffix, NULL);
4799 suffix_length += 3;
4802 /* If -save-temps=obj and -o were specified, use that for the
4803 temp file. */
4804 if (save_temps_length)
4806 char *tmp;
4807 temp_filename_length
4808 = save_temps_length + suffix_length + 1;
4809 tmp = (char *) alloca (temp_filename_length);
4810 memcpy (tmp, save_temps_prefix, save_temps_length);
4811 memcpy (tmp + save_temps_length, suffix, suffix_length);
4812 tmp[save_temps_length + suffix_length] = '\0';
4813 temp_filename = save_string (tmp, save_temps_length
4814 + suffix_length);
4815 obstack_grow (&obstack, temp_filename,
4816 temp_filename_length);
4817 arg_going = 1;
4818 delete_this_arg = 0;
4819 break;
4822 /* If the gcc_input_filename has the same suffix specified
4823 for the %g, %u, or %U, and -save-temps is specified,
4824 we could end up using that file as an intermediate
4825 thus clobbering the user's source file (.e.g.,
4826 gcc -save-temps foo.s would clobber foo.s with the
4827 output of cpp0). So check for this condition and
4828 generate a temp file as the intermediate. */
4830 if (save_temps_flag)
4832 char *tmp;
4833 temp_filename_length = basename_length + suffix_length + 1;
4834 tmp = (char *) alloca (temp_filename_length);
4835 memcpy (tmp, input_basename, basename_length);
4836 memcpy (tmp + basename_length, suffix, suffix_length);
4837 tmp[basename_length + suffix_length] = '\0';
4838 temp_filename = tmp;
4840 if (filename_cmp (temp_filename, gcc_input_filename) != 0)
4842 #ifndef HOST_LACKS_INODE_NUMBERS
4843 struct stat st_temp;
4845 /* Note, set_input() resets input_stat_set to 0. */
4846 if (input_stat_set == 0)
4848 input_stat_set = stat (gcc_input_filename,
4849 &input_stat);
4850 if (input_stat_set >= 0)
4851 input_stat_set = 1;
4854 /* If we have the stat for the gcc_input_filename
4855 and we can do the stat for the temp_filename
4856 then the they could still refer to the same
4857 file if st_dev/st_ino's are the same. */
4858 if (input_stat_set != 1
4859 || stat (temp_filename, &st_temp) < 0
4860 || input_stat.st_dev != st_temp.st_dev
4861 || input_stat.st_ino != st_temp.st_ino)
4862 #else
4863 /* Just compare canonical pathnames. */
4864 char* input_realname = lrealpath (gcc_input_filename);
4865 char* temp_realname = lrealpath (temp_filename);
4866 bool files_differ = filename_cmp (input_realname, temp_realname);
4867 free (input_realname);
4868 free (temp_realname);
4869 if (files_differ)
4870 #endif
4872 temp_filename = save_string (temp_filename,
4873 temp_filename_length + 1);
4874 obstack_grow (&obstack, temp_filename,
4875 temp_filename_length);
4876 arg_going = 1;
4877 delete_this_arg = 0;
4878 break;
4883 /* See if we already have an association of %g/%u/%U and
4884 suffix. */
4885 for (t = temp_names; t; t = t->next)
4886 if (t->length == suffix_length
4887 && strncmp (t->suffix, suffix, suffix_length) == 0
4888 && t->unique == (c == 'u' || c == 'U' || c == 'j'))
4889 break;
4891 /* Make a new association if needed. %u and %j
4892 require one. */
4893 if (t == 0 || c == 'u' || c == 'j')
4895 if (t == 0)
4897 t = XNEW (struct temp_name);
4898 t->next = temp_names;
4899 temp_names = t;
4901 t->length = suffix_length;
4902 if (saved_suffix)
4904 t->suffix = saved_suffix;
4905 saved_suffix = NULL;
4907 else
4908 t->suffix = save_string (suffix, suffix_length);
4909 t->unique = (c == 'u' || c == 'U' || c == 'j');
4910 temp_filename = make_temp_file (t->suffix);
4911 temp_filename_length = strlen (temp_filename);
4912 t->filename = temp_filename;
4913 t->filename_length = temp_filename_length;
4916 free (saved_suffix);
4918 obstack_grow (&obstack, t->filename, t->filename_length);
4919 delete_this_arg = 1;
4921 arg_going = 1;
4922 break;
4924 case 'i':
4925 if (combine_inputs)
4927 if (at_file_supplied)
4929 /* We are going to expand `%i' to `@FILE', where FILE
4930 is a newly-created temporary filename. The filenames
4931 that would usually be expanded in place of %o will be
4932 written to the temporary file. */
4933 char **argv;
4934 int n_files = 0;
4935 int j;
4937 for (i = 0; i < n_infiles; i++)
4938 if (compile_input_file_p (&infiles[i]))
4939 n_files++;
4941 argv = (char **) alloca (sizeof (char *) * (n_files + 1));
4943 /* Copy the strings over. */
4944 for (i = 0, j = 0; i < n_infiles; i++)
4945 if (compile_input_file_p (&infiles[i]))
4947 argv[j] = CONST_CAST (char *, infiles[i].name);
4948 infiles[i].compiled = true;
4949 j++;
4951 argv[j] = NULL;
4953 create_at_file (argv);
4955 else
4956 for (i = 0; (int) i < n_infiles; i++)
4957 if (compile_input_file_p (&infiles[i]))
4959 store_arg (infiles[i].name, 0, 0);
4960 infiles[i].compiled = true;
4963 else
4965 obstack_grow (&obstack, gcc_input_filename,
4966 input_filename_length);
4967 arg_going = 1;
4969 break;
4971 case 'I':
4973 struct spec_path_info info;
4975 if (multilib_dir)
4977 do_spec_1 ("-imultilib", 1, NULL);
4978 /* Make this a separate argument. */
4979 do_spec_1 (" ", 0, NULL);
4980 do_spec_1 (multilib_dir, 1, NULL);
4981 do_spec_1 (" ", 0, NULL);
4984 if (multiarch_dir)
4986 do_spec_1 ("-imultiarch", 1, NULL);
4987 /* Make this a separate argument. */
4988 do_spec_1 (" ", 0, NULL);
4989 do_spec_1 (multiarch_dir, 1, NULL);
4990 do_spec_1 (" ", 0, NULL);
4993 if (gcc_exec_prefix)
4995 do_spec_1 ("-iprefix", 1, NULL);
4996 /* Make this a separate argument. */
4997 do_spec_1 (" ", 0, NULL);
4998 do_spec_1 (gcc_exec_prefix, 1, NULL);
4999 do_spec_1 (" ", 0, NULL);
5002 if (target_system_root_changed ||
5003 (target_system_root && target_sysroot_hdrs_suffix))
5005 do_spec_1 ("-isysroot", 1, NULL);
5006 /* Make this a separate argument. */
5007 do_spec_1 (" ", 0, NULL);
5008 do_spec_1 (target_system_root, 1, NULL);
5009 if (target_sysroot_hdrs_suffix)
5010 do_spec_1 (target_sysroot_hdrs_suffix, 1, NULL);
5011 do_spec_1 (" ", 0, NULL);
5014 info.option = "-isystem";
5015 info.append = "include";
5016 info.append_len = strlen (info.append);
5017 info.omit_relative = false;
5018 info.separate_options = true;
5020 for_each_path (&include_prefixes, false, info.append_len,
5021 spec_path, &info);
5023 info.append = "include-fixed";
5024 if (*sysroot_hdrs_suffix_spec)
5025 info.append = concat (info.append, dir_separator_str,
5026 multilib_dir, NULL);
5027 info.append_len = strlen (info.append);
5028 for_each_path (&include_prefixes, false, info.append_len,
5029 spec_path, &info);
5031 break;
5033 case 'o':
5035 int max = n_infiles;
5036 max += lang_specific_extra_outfiles;
5038 if (HAVE_GNU_LD && at_file_supplied)
5040 /* We are going to expand `%o' to `@FILE', where FILE
5041 is a newly-created temporary filename. The filenames
5042 that would usually be expanded in place of %o will be
5043 written to the temporary file. */
5045 char **argv;
5046 int n_files, j;
5048 /* Convert OUTFILES into a form suitable for writeargv. */
5050 /* Determine how many are non-NULL. */
5051 for (n_files = 0, i = 0; i < max; i++)
5052 n_files += outfiles[i] != NULL;
5054 argv = (char **) alloca (sizeof (char *) * (n_files + 1));
5056 /* Copy the strings over. */
5057 for (i = 0, j = 0; i < max; i++)
5058 if (outfiles[i])
5060 argv[j] = CONST_CAST (char *, outfiles[i]);
5061 j++;
5063 argv[j] = NULL;
5065 create_at_file (argv);
5067 else
5068 for (i = 0; i < max; i++)
5069 if (outfiles[i])
5070 store_arg (outfiles[i], 0, 0);
5071 break;
5074 case 'O':
5075 obstack_grow (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
5076 arg_going = 1;
5077 break;
5079 case 's':
5080 this_is_library_file = 1;
5081 break;
5083 case 'T':
5084 this_is_linker_script = 1;
5085 break;
5087 case 'V':
5088 outfiles[input_file_number] = NULL;
5089 break;
5091 case 'w':
5092 this_is_output_file = 1;
5093 break;
5095 case 'W':
5097 unsigned int cur_index = argbuf.length ();
5098 /* Handle the {...} following the %W. */
5099 if (*p != '{')
5100 fatal_error ("spec %qs has invalid %<%%W%c%>", spec, *p);
5101 p = handle_braces (p + 1);
5102 if (p == 0)
5103 return -1;
5104 end_going_arg ();
5105 /* If any args were output, mark the last one for deletion
5106 on failure. */
5107 if (argbuf.length () != cur_index)
5108 record_temp_file (argbuf.last (), 0, 1);
5109 break;
5112 /* %x{OPTION} records OPTION for %X to output. */
5113 case 'x':
5115 const char *p1 = p;
5116 char *string;
5117 char *opt;
5118 unsigned ix;
5120 /* Skip past the option value and make a copy. */
5121 if (*p != '{')
5122 fatal_error ("spec %qs has invalid %<%%x%c%>", spec, *p);
5123 while (*p++ != '}')
5125 string = save_string (p1 + 1, p - p1 - 2);
5127 /* See if we already recorded this option. */
5128 FOR_EACH_VEC_ELT (linker_options, ix, opt)
5129 if (! strcmp (string, opt))
5131 free (string);
5132 return 0;
5135 /* This option is new; add it. */
5136 add_linker_option (string, strlen (string));
5137 free (string);
5139 break;
5141 /* Dump out the options accumulated previously using %x. */
5142 case 'X':
5143 do_specs_vec (linker_options);
5144 break;
5146 /* Dump out the options accumulated previously using -Wa,. */
5147 case 'Y':
5148 do_specs_vec (assembler_options);
5149 break;
5151 /* Dump out the options accumulated previously using -Wp,. */
5152 case 'Z':
5153 do_specs_vec (preprocessor_options);
5154 break;
5156 /* Here are digits and numbers that just process
5157 a certain constant string as a spec. */
5159 case '1':
5160 value = do_spec_1 (cc1_spec, 0, NULL);
5161 if (value != 0)
5162 return value;
5163 break;
5165 case '2':
5166 value = do_spec_1 (cc1plus_spec, 0, NULL);
5167 if (value != 0)
5168 return value;
5169 break;
5171 case 'a':
5172 value = do_spec_1 (asm_spec, 0, NULL);
5173 if (value != 0)
5174 return value;
5175 break;
5177 case 'A':
5178 value = do_spec_1 (asm_final_spec, 0, NULL);
5179 if (value != 0)
5180 return value;
5181 break;
5183 case 'C':
5185 const char *const spec
5186 = (input_file_compiler->cpp_spec
5187 ? input_file_compiler->cpp_spec
5188 : cpp_spec);
5189 value = do_spec_1 (spec, 0, NULL);
5190 if (value != 0)
5191 return value;
5193 break;
5195 case 'E':
5196 value = do_spec_1 (endfile_spec, 0, NULL);
5197 if (value != 0)
5198 return value;
5199 break;
5201 case 'l':
5202 value = do_spec_1 (link_spec, 0, NULL);
5203 if (value != 0)
5204 return value;
5205 break;
5207 case 'L':
5208 value = do_spec_1 (lib_spec, 0, NULL);
5209 if (value != 0)
5210 return value;
5211 break;
5213 case 'M':
5214 if (multilib_os_dir == NULL)
5215 obstack_1grow (&obstack, '.');
5216 else
5217 obstack_grow (&obstack, multilib_os_dir,
5218 strlen (multilib_os_dir));
5219 break;
5221 case 'G':
5222 value = do_spec_1 (libgcc_spec, 0, NULL);
5223 if (value != 0)
5224 return value;
5225 break;
5227 case 'R':
5228 /* We assume there is a directory
5229 separator at the end of this string. */
5230 if (target_system_root)
5232 obstack_grow (&obstack, target_system_root,
5233 strlen (target_system_root));
5234 if (target_sysroot_suffix)
5235 obstack_grow (&obstack, target_sysroot_suffix,
5236 strlen (target_sysroot_suffix));
5238 break;
5240 case 'S':
5241 value = do_spec_1 (startfile_spec, 0, NULL);
5242 if (value != 0)
5243 return value;
5244 break;
5246 /* Here we define characters other than letters and digits. */
5248 case '{':
5249 p = handle_braces (p);
5250 if (p == 0)
5251 return -1;
5252 break;
5254 case ':':
5255 p = handle_spec_function (p);
5256 if (p == 0)
5257 return -1;
5258 break;
5260 case '%':
5261 obstack_1grow (&obstack, '%');
5262 break;
5264 case '.':
5266 unsigned len = 0;
5268 while (p[len] && p[len] != ' ' && p[len] != '%')
5269 len++;
5270 suffix_subst = save_string (p - 1, len + 1);
5271 p += len;
5273 break;
5275 /* Henceforth ignore the option(s) matching the pattern
5276 after the %<. */
5277 case '<':
5278 case '>':
5280 unsigned len = 0;
5281 int have_wildcard = 0;
5282 int i;
5283 int switch_option;
5285 if (c == '>')
5286 switch_option = SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC;
5287 else
5288 switch_option = SWITCH_IGNORE;
5290 while (p[len] && p[len] != ' ' && p[len] != '\t')
5291 len++;
5293 if (p[len-1] == '*')
5294 have_wildcard = 1;
5296 for (i = 0; i < n_switches; i++)
5297 if (!strncmp (switches[i].part1, p, len - have_wildcard)
5298 && (have_wildcard || switches[i].part1[len] == '\0'))
5300 switches[i].live_cond |= switch_option;
5301 /* User switch be validated from validate_all_switches.
5302 when the definition is seen from the spec file.
5303 If not defined anywhere, will be rejected. */
5304 if (switches[i].known)
5305 switches[i].validated = true;
5308 p += len;
5310 break;
5312 case '*':
5313 if (soft_matched_part)
5315 if (soft_matched_part[0])
5316 do_spec_1 (soft_matched_part, 1, NULL);
5317 do_spec_1 (" ", 0, NULL);
5319 else
5320 /* Catch the case where a spec string contains something like
5321 '%{foo:%*}'. i.e. there is no * in the pattern on the left
5322 hand side of the :. */
5323 error ("spec failure: %<%%*%> has not been initialized by pattern match");
5324 break;
5326 /* Process a string found as the value of a spec given by name.
5327 This feature allows individual machine descriptions
5328 to add and use their own specs. */
5329 case '(':
5331 const char *name = p;
5332 struct spec_list *sl;
5333 int len;
5335 /* The string after the S/P is the name of a spec that is to be
5336 processed. */
5337 while (*p && *p != ')')
5338 p++;
5340 /* See if it's in the list. */
5341 for (len = p - name, sl = specs; sl; sl = sl->next)
5342 if (sl->name_len == len && !strncmp (sl->name, name, len))
5344 name = *(sl->ptr_spec);
5345 #ifdef DEBUG_SPECS
5346 fnotice (stderr, "Processing spec (%s), which is '%s'\n",
5347 sl->name, name);
5348 #endif
5349 break;
5352 if (sl)
5354 value = do_spec_1 (name, 0, NULL);
5355 if (value != 0)
5356 return value;
5359 /* Discard the closing paren. */
5360 if (*p)
5361 p++;
5363 break;
5365 default:
5366 error ("spec failure: unrecognized spec option %qc", c);
5367 break;
5369 break;
5371 case '\\':
5372 /* Backslash: treat next character as ordinary. */
5373 c = *p++;
5375 /* Fall through. */
5376 default:
5377 /* Ordinary character: put it into the current argument. */
5378 obstack_1grow (&obstack, c);
5379 arg_going = 1;
5382 /* End of string. If we are processing a spec function, we need to
5383 end any pending argument. */
5384 if (processing_spec_function)
5385 end_going_arg ();
5387 return 0;
5390 /* Look up a spec function. */
5392 static const struct spec_function *
5393 lookup_spec_function (const char *name)
5395 const struct spec_function *sf;
5397 for (sf = static_spec_functions; sf->name != NULL; sf++)
5398 if (strcmp (sf->name, name) == 0)
5399 return sf;
5401 return NULL;
5404 /* Evaluate a spec function. */
5406 static const char *
5407 eval_spec_function (const char *func, const char *args)
5409 const struct spec_function *sf;
5410 const char *funcval;
5412 /* Saved spec processing context. */
5413 vec<const_char_p> save_argbuf;
5415 int save_arg_going;
5416 int save_delete_this_arg;
5417 int save_this_is_output_file;
5418 int save_this_is_library_file;
5419 int save_input_from_pipe;
5420 int save_this_is_linker_script;
5421 const char *save_suffix_subst;
5423 int save_growing_size;
5424 void *save_growing_value;
5426 sf = lookup_spec_function (func);
5427 if (sf == NULL)
5428 fatal_error ("unknown spec function %qs", func);
5430 /* Push the spec processing context. */
5431 save_argbuf = argbuf;
5433 save_arg_going = arg_going;
5434 save_delete_this_arg = delete_this_arg;
5435 save_this_is_output_file = this_is_output_file;
5436 save_this_is_library_file = this_is_library_file;
5437 save_this_is_linker_script = this_is_linker_script;
5438 save_input_from_pipe = input_from_pipe;
5439 save_suffix_subst = suffix_subst;
5441 /* If we have some object growing now, finalize it so the args and function
5442 eval proceed from a cleared context. This is needed to prevent the first
5443 constructed arg from mistakenly including the growing value. We'll push
5444 this value back on the obstack once the function evaluation is done, to
5445 restore a consistent processing context for our caller. This is fine as
5446 the address of growing objects isn't guaranteed to remain stable until
5447 they are finalized, and we expect this situation to be rare enough for
5448 the extra copy not to be an issue. */
5449 save_growing_size = obstack_object_size (&obstack);
5450 if (save_growing_size > 0)
5451 save_growing_value = obstack_finish (&obstack);
5453 /* Create a new spec processing context, and build the function
5454 arguments. */
5456 alloc_args ();
5457 if (do_spec_2 (args) < 0)
5458 fatal_error ("error in args to spec function %qs", func);
5460 /* argbuf_index is an index for the next argument to be inserted, and
5461 so contains the count of the args already inserted. */
5463 funcval = (*sf->func) (argbuf.length (),
5464 argbuf.address ());
5466 /* Pop the spec processing context. */
5467 argbuf.release ();
5468 argbuf = save_argbuf;
5470 arg_going = save_arg_going;
5471 delete_this_arg = save_delete_this_arg;
5472 this_is_output_file = save_this_is_output_file;
5473 this_is_library_file = save_this_is_library_file;
5474 this_is_linker_script = save_this_is_linker_script;
5475 input_from_pipe = save_input_from_pipe;
5476 suffix_subst = save_suffix_subst;
5478 if (save_growing_size > 0)
5479 obstack_grow (&obstack, save_growing_value, save_growing_size);
5481 return funcval;
5484 /* Handle a spec function call of the form:
5486 %:function(args)
5488 ARGS is processed as a spec in a separate context and split into an
5489 argument vector in the normal fashion. The function returns a string
5490 containing a spec which we then process in the caller's context, or
5491 NULL if no processing is required. */
5493 static const char *
5494 handle_spec_function (const char *p)
5496 char *func, *args;
5497 const char *endp, *funcval;
5498 int count;
5500 processing_spec_function++;
5502 /* Get the function name. */
5503 for (endp = p; *endp != '\0'; endp++)
5505 if (*endp == '(') /* ) */
5506 break;
5507 /* Only allow [A-Za-z0-9], -, and _ in function names. */
5508 if (!ISALNUM (*endp) && !(*endp == '-' || *endp == '_'))
5509 fatal_error ("malformed spec function name");
5511 if (*endp != '(') /* ) */
5512 fatal_error ("no arguments for spec function");
5513 func = save_string (p, endp - p);
5514 p = ++endp;
5516 /* Get the arguments. */
5517 for (count = 0; *endp != '\0'; endp++)
5519 /* ( */
5520 if (*endp == ')')
5522 if (count == 0)
5523 break;
5524 count--;
5526 else if (*endp == '(') /* ) */
5527 count++;
5529 /* ( */
5530 if (*endp != ')')
5531 fatal_error ("malformed spec function arguments");
5532 args = save_string (p, endp - p);
5533 p = ++endp;
5535 /* p now points to just past the end of the spec function expression. */
5537 funcval = eval_spec_function (func, args);
5538 if (funcval != NULL && do_spec_1 (funcval, 0, NULL) < 0)
5539 p = NULL;
5541 free (func);
5542 free (args);
5544 processing_spec_function--;
5546 return p;
5549 /* Inline subroutine of handle_braces. Returns true if the current
5550 input suffix matches the atom bracketed by ATOM and END_ATOM. */
5551 static inline bool
5552 input_suffix_matches (const char *atom, const char *end_atom)
5554 return (input_suffix
5555 && !strncmp (input_suffix, atom, end_atom - atom)
5556 && input_suffix[end_atom - atom] == '\0');
5559 /* Subroutine of handle_braces. Returns true if the current
5560 input file's spec name matches the atom bracketed by ATOM and END_ATOM. */
5561 static bool
5562 input_spec_matches (const char *atom, const char *end_atom)
5564 return (input_file_compiler
5565 && input_file_compiler->suffix
5566 && input_file_compiler->suffix[0] != '\0'
5567 && !strncmp (input_file_compiler->suffix + 1, atom,
5568 end_atom - atom)
5569 && input_file_compiler->suffix[end_atom - atom + 1] == '\0');
5572 /* Subroutine of handle_braces. Returns true if a switch
5573 matching the atom bracketed by ATOM and END_ATOM appeared on the
5574 command line. */
5575 static bool
5576 switch_matches (const char *atom, const char *end_atom, int starred)
5578 int i;
5579 int len = end_atom - atom;
5580 int plen = starred ? len : -1;
5582 for (i = 0; i < n_switches; i++)
5583 if (!strncmp (switches[i].part1, atom, len)
5584 && (starred || switches[i].part1[len] == '\0')
5585 && check_live_switch (i, plen))
5586 return true;
5588 /* Check if a switch with separated form matching the atom.
5589 We check -D and -U switches. */
5590 else if (switches[i].args != 0)
5592 if ((*switches[i].part1 == 'D' || *switches[i].part1 == 'U')
5593 && *switches[i].part1 == atom[0])
5595 if (!strncmp (switches[i].args[0], &atom[1], len - 1)
5596 && (starred || (switches[i].part1[1] == '\0'
5597 && switches[i].args[0][len - 1] == '\0'))
5598 && check_live_switch (i, (starred ? 1 : -1)))
5599 return true;
5603 return false;
5606 /* Inline subroutine of handle_braces. Mark all of the switches which
5607 match ATOM (extends to END_ATOM; STARRED indicates whether there
5608 was a star after the atom) for later processing. */
5609 static inline void
5610 mark_matching_switches (const char *atom, const char *end_atom, int starred)
5612 int i;
5613 int len = end_atom - atom;
5614 int plen = starred ? len : -1;
5616 for (i = 0; i < n_switches; i++)
5617 if (!strncmp (switches[i].part1, atom, len)
5618 && (starred || switches[i].part1[len] == '\0')
5619 && check_live_switch (i, plen))
5620 switches[i].ordering = 1;
5623 /* Inline subroutine of handle_braces. Process all the currently
5624 marked switches through give_switch, and clear the marks. */
5625 static inline void
5626 process_marked_switches (void)
5628 int i;
5630 for (i = 0; i < n_switches; i++)
5631 if (switches[i].ordering == 1)
5633 switches[i].ordering = 0;
5634 give_switch (i, 0);
5638 /* Handle a %{ ... } construct. P points just inside the leading {.
5639 Returns a pointer one past the end of the brace block, or 0
5640 if we call do_spec_1 and that returns -1. */
5642 static const char *
5643 handle_braces (const char *p)
5645 const char *atom, *end_atom;
5646 const char *d_atom = NULL, *d_end_atom = NULL;
5647 const char *orig = p;
5649 bool a_is_suffix;
5650 bool a_is_spectype;
5651 bool a_is_starred;
5652 bool a_is_negated;
5653 bool a_matched;
5655 bool a_must_be_last = false;
5656 bool ordered_set = false;
5657 bool disjunct_set = false;
5658 bool disj_matched = false;
5659 bool disj_starred = true;
5660 bool n_way_choice = false;
5661 bool n_way_matched = false;
5663 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
5667 if (a_must_be_last)
5668 goto invalid;
5670 /* Scan one "atom" (S in the description above of %{}, possibly
5671 with '!', '.', '@', ',', or '*' modifiers). */
5672 a_matched = false;
5673 a_is_suffix = false;
5674 a_is_starred = false;
5675 a_is_negated = false;
5676 a_is_spectype = false;
5678 SKIP_WHITE();
5679 if (*p == '!')
5680 p++, a_is_negated = true;
5682 SKIP_WHITE();
5683 if (*p == '.')
5684 p++, a_is_suffix = true;
5685 else if (*p == ',')
5686 p++, a_is_spectype = true;
5688 atom = p;
5689 while (ISIDNUM(*p) || *p == '-' || *p == '+' || *p == '='
5690 || *p == ',' || *p == '.' || *p == '@')
5691 p++;
5692 end_atom = p;
5694 if (*p == '*')
5695 p++, a_is_starred = 1;
5697 SKIP_WHITE();
5698 switch (*p)
5700 case '&': case '}':
5701 /* Substitute the switch(es) indicated by the current atom. */
5702 ordered_set = true;
5703 if (disjunct_set || n_way_choice || a_is_negated || a_is_suffix
5704 || a_is_spectype || atom == end_atom)
5705 goto invalid;
5707 mark_matching_switches (atom, end_atom, a_is_starred);
5709 if (*p == '}')
5710 process_marked_switches ();
5711 break;
5713 case '|': case ':':
5714 /* Substitute some text if the current atom appears as a switch
5715 or suffix. */
5716 disjunct_set = true;
5717 if (ordered_set)
5718 goto invalid;
5720 if (atom == end_atom)
5722 if (!n_way_choice || disj_matched || *p == '|'
5723 || a_is_negated || a_is_suffix || a_is_spectype
5724 || a_is_starred)
5725 goto invalid;
5727 /* An empty term may appear as the last choice of an
5728 N-way choice set; it means "otherwise". */
5729 a_must_be_last = true;
5730 disj_matched = !n_way_matched;
5731 disj_starred = false;
5733 else
5735 if ((a_is_suffix || a_is_spectype) && a_is_starred)
5736 goto invalid;
5738 if (!a_is_starred)
5739 disj_starred = false;
5741 /* Don't bother testing this atom if we already have a
5742 match. */
5743 if (!disj_matched && !n_way_matched)
5745 if (a_is_suffix)
5746 a_matched = input_suffix_matches (atom, end_atom);
5747 else if (a_is_spectype)
5748 a_matched = input_spec_matches (atom, end_atom);
5749 else
5750 a_matched = switch_matches (atom, end_atom, a_is_starred);
5752 if (a_matched != a_is_negated)
5754 disj_matched = true;
5755 d_atom = atom;
5756 d_end_atom = end_atom;
5761 if (*p == ':')
5763 /* Found the body, that is, the text to substitute if the
5764 current disjunction matches. */
5765 p = process_brace_body (p + 1, d_atom, d_end_atom, disj_starred,
5766 disj_matched && !n_way_matched);
5767 if (p == 0)
5768 return 0;
5770 /* If we have an N-way choice, reset state for the next
5771 disjunction. */
5772 if (*p == ';')
5774 n_way_choice = true;
5775 n_way_matched |= disj_matched;
5776 disj_matched = false;
5777 disj_starred = true;
5778 d_atom = d_end_atom = NULL;
5781 break;
5783 default:
5784 goto invalid;
5787 while (*p++ != '}');
5789 return p;
5791 invalid:
5792 fatal_error ("braced spec %qs is invalid at %qc", orig, *p);
5794 #undef SKIP_WHITE
5797 /* Subroutine of handle_braces. Scan and process a brace substitution body
5798 (X in the description of %{} syntax). P points one past the colon;
5799 ATOM and END_ATOM bracket the first atom which was found to be true
5800 (present) in the current disjunction; STARRED indicates whether all
5801 the atoms in the current disjunction were starred (for syntax validation);
5802 MATCHED indicates whether the disjunction matched or not, and therefore
5803 whether or not the body is to be processed through do_spec_1 or just
5804 skipped. Returns a pointer to the closing } or ;, or 0 if do_spec_1
5805 returns -1. */
5807 static const char *
5808 process_brace_body (const char *p, const char *atom, const char *end_atom,
5809 int starred, int matched)
5811 const char *body, *end_body;
5812 unsigned int nesting_level;
5813 bool have_subst = false;
5815 /* Locate the closing } or ;, honoring nested braces.
5816 Trim trailing whitespace. */
5817 body = p;
5818 nesting_level = 1;
5819 for (;;)
5821 if (*p == '{')
5822 nesting_level++;
5823 else if (*p == '}')
5825 if (!--nesting_level)
5826 break;
5828 else if (*p == ';' && nesting_level == 1)
5829 break;
5830 else if (*p == '%' && p[1] == '*' && nesting_level == 1)
5831 have_subst = true;
5832 else if (*p == '\0')
5833 goto invalid;
5834 p++;
5837 end_body = p;
5838 while (end_body[-1] == ' ' || end_body[-1] == '\t')
5839 end_body--;
5841 if (have_subst && !starred)
5842 goto invalid;
5844 if (matched)
5846 /* Copy the substitution body to permanent storage and execute it.
5847 If have_subst is false, this is a simple matter of running the
5848 body through do_spec_1... */
5849 char *string = save_string (body, end_body - body);
5850 if (!have_subst)
5852 if (do_spec_1 (string, 0, NULL) < 0)
5853 return 0;
5855 else
5857 /* ... but if have_subst is true, we have to process the
5858 body once for each matching switch, with %* set to the
5859 variant part of the switch. */
5860 unsigned int hard_match_len = end_atom - atom;
5861 int i;
5863 for (i = 0; i < n_switches; i++)
5864 if (!strncmp (switches[i].part1, atom, hard_match_len)
5865 && check_live_switch (i, hard_match_len))
5867 if (do_spec_1 (string, 0,
5868 &switches[i].part1[hard_match_len]) < 0)
5869 return 0;
5870 /* Pass any arguments this switch has. */
5871 give_switch (i, 1);
5872 suffix_subst = NULL;
5877 return p;
5879 invalid:
5880 fatal_error ("braced spec body %qs is invalid", body);
5883 /* Return 0 iff switch number SWITCHNUM is obsoleted by a later switch
5884 on the command line. PREFIX_LENGTH is the length of XXX in an {XXX*}
5885 spec, or -1 if either exact match or %* is used.
5887 A -O switch is obsoleted by a later -O switch. A -f, -g, -m, or -W switch
5888 whose value does not begin with "no-" is obsoleted by the same value
5889 with the "no-", similarly for a switch with the "no-" prefix. */
5891 static int
5892 check_live_switch (int switchnum, int prefix_length)
5894 const char *name = switches[switchnum].part1;
5895 int i;
5897 /* If we already processed this switch and determined if it was
5898 live or not, return our past determination. */
5899 if (switches[switchnum].live_cond != 0)
5900 return ((switches[switchnum].live_cond & SWITCH_LIVE) != 0
5901 && (switches[switchnum].live_cond & SWITCH_FALSE) == 0
5902 && (switches[switchnum].live_cond & SWITCH_IGNORE_PERMANENTLY)
5903 == 0);
5905 /* In the common case of {<at-most-one-letter>*}, a negating
5906 switch would always match, so ignore that case. We will just
5907 send the conflicting switches to the compiler phase. */
5908 if (prefix_length >= 0 && prefix_length <= 1)
5909 return 1;
5911 /* Now search for duplicate in a manner that depends on the name. */
5912 switch (*name)
5914 case 'O':
5915 for (i = switchnum + 1; i < n_switches; i++)
5916 if (switches[i].part1[0] == 'O')
5918 switches[switchnum].validated = true;
5919 switches[switchnum].live_cond = SWITCH_FALSE;
5920 return 0;
5922 break;
5924 case 'W': case 'f': case 'm': case 'g':
5925 if (! strncmp (name + 1, "no-", 3))
5927 /* We have Xno-YYY, search for XYYY. */
5928 for (i = switchnum + 1; i < n_switches; i++)
5929 if (switches[i].part1[0] == name[0]
5930 && ! strcmp (&switches[i].part1[1], &name[4]))
5932 /* --specs are validated with the validate_switches mechanism. */
5933 if (switches[switchnum].known)
5934 switches[switchnum].validated = true;
5935 switches[switchnum].live_cond = SWITCH_FALSE;
5936 return 0;
5939 else
5941 /* We have XYYY, search for Xno-YYY. */
5942 for (i = switchnum + 1; i < n_switches; i++)
5943 if (switches[i].part1[0] == name[0]
5944 && switches[i].part1[1] == 'n'
5945 && switches[i].part1[2] == 'o'
5946 && switches[i].part1[3] == '-'
5947 && !strcmp (&switches[i].part1[4], &name[1]))
5949 /* --specs are validated with the validate_switches mechanism. */
5950 if (switches[switchnum].known)
5951 switches[switchnum].validated = true;
5952 switches[switchnum].live_cond = SWITCH_FALSE;
5953 return 0;
5956 break;
5959 /* Otherwise the switch is live. */
5960 switches[switchnum].live_cond |= SWITCH_LIVE;
5961 return 1;
5964 /* Pass a switch to the current accumulating command
5965 in the same form that we received it.
5966 SWITCHNUM identifies the switch; it is an index into
5967 the vector of switches gcc received, which is `switches'.
5968 This cannot fail since it never finishes a command line.
5970 If OMIT_FIRST_WORD is nonzero, then we omit .part1 of the argument. */
5972 static void
5973 give_switch (int switchnum, int omit_first_word)
5975 if ((switches[switchnum].live_cond & SWITCH_IGNORE) != 0)
5976 return;
5978 if (!omit_first_word)
5980 do_spec_1 ("-", 0, NULL);
5981 do_spec_1 (switches[switchnum].part1, 1, NULL);
5984 if (switches[switchnum].args != 0)
5986 const char **p;
5987 for (p = switches[switchnum].args; *p; p++)
5989 const char *arg = *p;
5991 do_spec_1 (" ", 0, NULL);
5992 if (suffix_subst)
5994 unsigned length = strlen (arg);
5995 int dot = 0;
5997 while (length-- && !IS_DIR_SEPARATOR (arg[length]))
5998 if (arg[length] == '.')
6000 (CONST_CAST(char *, arg))[length] = 0;
6001 dot = 1;
6002 break;
6004 do_spec_1 (arg, 1, NULL);
6005 if (dot)
6006 (CONST_CAST(char *, arg))[length] = '.';
6007 do_spec_1 (suffix_subst, 1, NULL);
6009 else
6010 do_spec_1 (arg, 1, NULL);
6014 do_spec_1 (" ", 0, NULL);
6015 switches[switchnum].validated = true;
6018 /* Search for a file named NAME trying various prefixes including the
6019 user's -B prefix and some standard ones.
6020 Return the absolute file name found. If nothing is found, return NAME. */
6022 static const char *
6023 find_file (const char *name)
6025 char *newname = find_a_file (&startfile_prefixes, name, R_OK, true);
6026 return newname ? newname : name;
6029 /* Determine whether a directory exists. If LINKER, return 0 for
6030 certain fixed names not needed by the linker. */
6032 static int
6033 is_directory (const char *path1, bool linker)
6035 int len1;
6036 char *path;
6037 char *cp;
6038 struct stat st;
6040 /* Ensure the string ends with "/.". The resulting path will be a
6041 directory even if the given path is a symbolic link. */
6042 len1 = strlen (path1);
6043 path = (char *) alloca (3 + len1);
6044 memcpy (path, path1, len1);
6045 cp = path + len1;
6046 if (!IS_DIR_SEPARATOR (cp[-1]))
6047 *cp++ = DIR_SEPARATOR;
6048 *cp++ = '.';
6049 *cp = '\0';
6051 /* Exclude directories that the linker is known to search. */
6052 if (linker
6053 && IS_DIR_SEPARATOR (path[0])
6054 && ((cp - path == 6
6055 && filename_ncmp (path + 1, "lib", 3) == 0)
6056 || (cp - path == 10
6057 && filename_ncmp (path + 1, "usr", 3) == 0
6058 && IS_DIR_SEPARATOR (path[4])
6059 && filename_ncmp (path + 5, "lib", 3) == 0)))
6060 return 0;
6062 return (stat (path, &st) >= 0 && S_ISDIR (st.st_mode));
6065 /* Set up the various global variables to indicate that we're processing
6066 the input file named FILENAME. */
6068 void
6069 set_input (const char *filename)
6071 const char *p;
6073 gcc_input_filename = filename;
6074 input_filename_length = strlen (gcc_input_filename);
6075 input_basename = lbasename (gcc_input_filename);
6077 /* Find a suffix starting with the last period,
6078 and set basename_length to exclude that suffix. */
6079 basename_length = strlen (input_basename);
6080 suffixed_basename_length = basename_length;
6081 p = input_basename + basename_length;
6082 while (p != input_basename && *p != '.')
6083 --p;
6084 if (*p == '.' && p != input_basename)
6086 basename_length = p - input_basename;
6087 input_suffix = p + 1;
6089 else
6090 input_suffix = "";
6092 /* If a spec for 'g', 'u', or 'U' is seen with -save-temps then
6093 we will need to do a stat on the gcc_input_filename. The
6094 INPUT_STAT_SET signals that the stat is needed. */
6095 input_stat_set = 0;
6098 /* On fatal signals, delete all the temporary files. */
6100 static void
6101 fatal_signal (int signum)
6103 signal (signum, SIG_DFL);
6104 delete_failure_queue ();
6105 delete_temp_files ();
6106 /* Get the same signal again, this time not handled,
6107 so its normal effect occurs. */
6108 kill (getpid (), signum);
6111 /* Compare the contents of the two files named CMPFILE[0] and
6112 CMPFILE[1]. Return zero if they're identical, nonzero
6113 otherwise. */
6115 static int
6116 compare_files (char *cmpfile[])
6118 int ret = 0;
6119 FILE *temp[2] = { NULL, NULL };
6120 int i;
6122 #if HAVE_MMAP_FILE
6124 size_t length[2];
6125 void *map[2] = { NULL, NULL };
6127 for (i = 0; i < 2; i++)
6129 struct stat st;
6131 if (stat (cmpfile[i], &st) < 0 || !S_ISREG (st.st_mode))
6133 error ("%s: could not determine length of compare-debug file %s",
6134 gcc_input_filename, cmpfile[i]);
6135 ret = 1;
6136 break;
6139 length[i] = st.st_size;
6142 if (!ret && length[0] != length[1])
6144 error ("%s: -fcompare-debug failure (length)", gcc_input_filename);
6145 ret = 1;
6148 if (!ret)
6149 for (i = 0; i < 2; i++)
6151 int fd = open (cmpfile[i], O_RDONLY);
6152 if (fd < 0)
6154 error ("%s: could not open compare-debug file %s",
6155 gcc_input_filename, cmpfile[i]);
6156 ret = 1;
6157 break;
6160 map[i] = mmap (NULL, length[i], PROT_READ, MAP_PRIVATE, fd, 0);
6161 close (fd);
6163 if (map[i] == (void *) MAP_FAILED)
6165 ret = -1;
6166 break;
6170 if (!ret)
6172 if (memcmp (map[0], map[1], length[0]) != 0)
6174 error ("%s: -fcompare-debug failure", gcc_input_filename);
6175 ret = 1;
6179 for (i = 0; i < 2; i++)
6180 if (map[i])
6181 munmap ((caddr_t) map[i], length[i]);
6183 if (ret >= 0)
6184 return ret;
6186 ret = 0;
6188 #endif
6190 for (i = 0; i < 2; i++)
6192 temp[i] = fopen (cmpfile[i], "r");
6193 if (!temp[i])
6195 error ("%s: could not open compare-debug file %s",
6196 gcc_input_filename, cmpfile[i]);
6197 ret = 1;
6198 break;
6202 if (!ret && temp[0] && temp[1])
6203 for (;;)
6205 int c0, c1;
6206 c0 = fgetc (temp[0]);
6207 c1 = fgetc (temp[1]);
6209 if (c0 != c1)
6211 error ("%s: -fcompare-debug failure",
6212 gcc_input_filename);
6213 ret = 1;
6214 break;
6217 if (c0 == EOF)
6218 break;
6221 for (i = 1; i >= 0; i--)
6223 if (temp[i])
6224 fclose (temp[i]);
6227 return ret;
6230 extern int main (int, char **);
6233 main (int argc, char **argv)
6235 size_t i;
6236 int value;
6237 int linker_was_run = 0;
6238 int lang_n_infiles = 0;
6239 int num_linker_inputs = 0;
6240 char *explicit_link_files;
6241 char *specs_file;
6242 char *lto_wrapper_file;
6243 const char *p;
6244 struct user_specs *uptr;
6245 char **old_argv = argv;
6246 struct cl_decoded_option *decoded_options;
6247 unsigned int decoded_options_count;
6249 p = argv[0] + strlen (argv[0]);
6250 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
6251 --p;
6252 progname = p;
6254 xmalloc_set_program_name (progname);
6256 expandargv (&argc, &argv);
6258 /* Determine if any expansions were made. */
6259 if (argv != old_argv)
6260 at_file_supplied = true;
6262 /* Register the language-independent parameters. */
6263 global_init_params ();
6264 finish_params ();
6266 init_options_struct (&global_options, &global_options_set);
6268 decode_cmdline_options_to_array (argc, CONST_CAST2 (const char **, char **,
6269 argv),
6270 CL_DRIVER,
6271 &decoded_options, &decoded_options_count);
6273 /* Unlock the stdio streams. */
6274 unlock_std_streams ();
6276 gcc_init_libintl ();
6278 diagnostic_initialize (global_dc, 0);
6280 #ifdef GCC_DRIVER_HOST_INITIALIZATION
6281 /* Perform host dependent initialization when needed. */
6282 GCC_DRIVER_HOST_INITIALIZATION;
6283 #endif
6285 if (atexit (delete_temp_files) != 0)
6286 fatal_error ("atexit failed");
6288 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
6289 signal (SIGINT, fatal_signal);
6290 #ifdef SIGHUP
6291 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
6292 signal (SIGHUP, fatal_signal);
6293 #endif
6294 if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
6295 signal (SIGTERM, fatal_signal);
6296 #ifdef SIGPIPE
6297 if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
6298 signal (SIGPIPE, fatal_signal);
6299 #endif
6300 #ifdef SIGCHLD
6301 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
6302 receive the signal. A different setting is inheritable */
6303 signal (SIGCHLD, SIG_DFL);
6304 #endif
6306 /* Parsing and gimplification sometimes need quite large stack.
6307 Increase stack size limits if possible. */
6308 stack_limit_increase (64 * 1024 * 1024);
6310 /* Allocate the argument vector. */
6311 alloc_args ();
6313 obstack_init (&obstack);
6315 /* Build multilib_select, et. al from the separate lines that make up each
6316 multilib selection. */
6318 const char *const *q = multilib_raw;
6319 int need_space;
6321 obstack_init (&multilib_obstack);
6322 while ((p = *q++) != (char *) 0)
6323 obstack_grow (&multilib_obstack, p, strlen (p));
6325 obstack_1grow (&multilib_obstack, 0);
6326 multilib_select = XOBFINISH (&multilib_obstack, const char *);
6328 q = multilib_matches_raw;
6329 while ((p = *q++) != (char *) 0)
6330 obstack_grow (&multilib_obstack, p, strlen (p));
6332 obstack_1grow (&multilib_obstack, 0);
6333 multilib_matches = XOBFINISH (&multilib_obstack, const char *);
6335 q = multilib_exclusions_raw;
6336 while ((p = *q++) != (char *) 0)
6337 obstack_grow (&multilib_obstack, p, strlen (p));
6339 obstack_1grow (&multilib_obstack, 0);
6340 multilib_exclusions = XOBFINISH (&multilib_obstack, const char *);
6342 need_space = FALSE;
6343 for (i = 0; i < ARRAY_SIZE (multilib_defaults_raw); i++)
6345 if (need_space)
6346 obstack_1grow (&multilib_obstack, ' ');
6347 obstack_grow (&multilib_obstack,
6348 multilib_defaults_raw[i],
6349 strlen (multilib_defaults_raw[i]));
6350 need_space = TRUE;
6353 obstack_1grow (&multilib_obstack, 0);
6354 multilib_defaults = XOBFINISH (&multilib_obstack, const char *);
6357 #ifdef INIT_ENVIRONMENT
6358 /* Set up any other necessary machine specific environment variables. */
6359 xputenv (INIT_ENVIRONMENT);
6360 #endif
6362 /* Make a table of what switches there are (switches, n_switches).
6363 Make a table of specified input files (infiles, n_infiles).
6364 Decode switches that are handled locally. */
6366 process_command (decoded_options_count, decoded_options);
6368 /* Initialize the vector of specs to just the default.
6369 This means one element containing 0s, as a terminator. */
6371 compilers = XNEWVAR (struct compiler, sizeof default_compilers);
6372 memcpy (compilers, default_compilers, sizeof default_compilers);
6373 n_compilers = n_default_compilers;
6375 /* Read specs from a file if there is one. */
6377 machine_suffix = concat (spec_machine, dir_separator_str,
6378 spec_version, dir_separator_str, NULL);
6379 just_machine_suffix = concat (spec_machine, dir_separator_str, NULL);
6381 specs_file = find_a_file (&startfile_prefixes, "specs", R_OK, true);
6382 /* Read the specs file unless it is a default one. */
6383 if (specs_file != 0 && strcmp (specs_file, "specs"))
6384 read_specs (specs_file, true, false);
6385 else
6386 init_spec ();
6388 /* We need to check standard_exec_prefix/just_machine_suffix/specs
6389 for any override of as, ld and libraries. */
6390 specs_file = (char *) alloca (strlen (standard_exec_prefix)
6391 + strlen (just_machine_suffix) + sizeof ("specs"));
6393 strcpy (specs_file, standard_exec_prefix);
6394 strcat (specs_file, just_machine_suffix);
6395 strcat (specs_file, "specs");
6396 if (access (specs_file, R_OK) == 0)
6397 read_specs (specs_file, true, false);
6399 /* Process any configure-time defaults specified for the command line
6400 options, via OPTION_DEFAULT_SPECS. */
6401 for (i = 0; i < ARRAY_SIZE (option_default_specs); i++)
6402 do_option_spec (option_default_specs[i].name,
6403 option_default_specs[i].spec);
6405 /* Process DRIVER_SELF_SPECS, adding any new options to the end
6406 of the command line. */
6408 for (i = 0; i < ARRAY_SIZE (driver_self_specs); i++)
6409 do_self_spec (driver_self_specs[i]);
6411 /* If not cross-compiling, look for executables in the standard
6412 places. */
6413 if (*cross_compile == '0')
6415 if (*md_exec_prefix)
6417 add_prefix (&exec_prefixes, md_exec_prefix, "GCC",
6418 PREFIX_PRIORITY_LAST, 0, 0);
6422 /* Process sysroot_suffix_spec. */
6423 if (*sysroot_suffix_spec != 0
6424 && !no_sysroot_suffix
6425 && do_spec_2 (sysroot_suffix_spec) == 0)
6427 if (argbuf.length () > 1)
6428 error ("spec failure: more than one arg to SYSROOT_SUFFIX_SPEC");
6429 else if (argbuf.length () == 1)
6430 target_sysroot_suffix = xstrdup (argbuf.last ());
6433 #ifdef HAVE_LD_SYSROOT
6434 /* Pass the --sysroot option to the linker, if it supports that. If
6435 there is a sysroot_suffix_spec, it has already been processed by
6436 this point, so target_system_root really is the system root we
6437 should be using. */
6438 if (target_system_root)
6440 obstack_grow (&obstack, "%(sysroot_spec) ", strlen ("%(sysroot_spec) "));
6441 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
6442 set_spec ("link", XOBFINISH (&obstack, const char *), false);
6444 #endif
6446 /* Process sysroot_hdrs_suffix_spec. */
6447 if (*sysroot_hdrs_suffix_spec != 0
6448 && !no_sysroot_suffix
6449 && do_spec_2 (sysroot_hdrs_suffix_spec) == 0)
6451 if (argbuf.length () > 1)
6452 error ("spec failure: more than one arg to SYSROOT_HEADERS_SUFFIX_SPEC");
6453 else if (argbuf.length () == 1)
6454 target_sysroot_hdrs_suffix = xstrdup (argbuf.last ());
6457 /* Look for startfiles in the standard places. */
6458 if (*startfile_prefix_spec != 0
6459 && do_spec_2 (startfile_prefix_spec) == 0
6460 && do_spec_1 (" ", 0, NULL) == 0)
6462 const char *arg;
6463 int ndx;
6464 FOR_EACH_VEC_ELT (argbuf, ndx, arg)
6465 add_sysrooted_prefix (&startfile_prefixes, arg, "BINUTILS",
6466 PREFIX_PRIORITY_LAST, 0, 1);
6468 /* We should eventually get rid of all these and stick to
6469 startfile_prefix_spec exclusively. */
6470 else if (*cross_compile == '0' || target_system_root)
6472 if (*md_startfile_prefix)
6473 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix,
6474 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
6476 if (*md_startfile_prefix_1)
6477 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix_1,
6478 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
6480 /* If standard_startfile_prefix is relative, base it on
6481 standard_exec_prefix. This lets us move the installed tree
6482 as a unit. If GCC_EXEC_PREFIX is defined, base
6483 standard_startfile_prefix on that as well.
6485 If the prefix is relative, only search it for native compilers;
6486 otherwise we will search a directory containing host libraries. */
6487 if (IS_ABSOLUTE_PATH (standard_startfile_prefix))
6488 add_sysrooted_prefix (&startfile_prefixes,
6489 standard_startfile_prefix, "BINUTILS",
6490 PREFIX_PRIORITY_LAST, 0, 1);
6491 else if (*cross_compile == '0')
6493 add_prefix (&startfile_prefixes,
6494 concat (gcc_exec_prefix
6495 ? gcc_exec_prefix : standard_exec_prefix,
6496 machine_suffix,
6497 standard_startfile_prefix, NULL),
6498 NULL, PREFIX_PRIORITY_LAST, 0, 1);
6501 /* Sysrooted prefixes are relocated because target_system_root is
6502 also relocated by gcc_exec_prefix. */
6503 if (*standard_startfile_prefix_1)
6504 add_sysrooted_prefix (&startfile_prefixes,
6505 standard_startfile_prefix_1, "BINUTILS",
6506 PREFIX_PRIORITY_LAST, 0, 1);
6507 if (*standard_startfile_prefix_2)
6508 add_sysrooted_prefix (&startfile_prefixes,
6509 standard_startfile_prefix_2, "BINUTILS",
6510 PREFIX_PRIORITY_LAST, 0, 1);
6513 /* Process any user specified specs in the order given on the command
6514 line. */
6515 for (uptr = user_specs_head; uptr; uptr = uptr->next)
6517 char *filename = find_a_file (&startfile_prefixes, uptr->filename,
6518 R_OK, true);
6519 read_specs (filename ? filename : uptr->filename, false, true);
6522 /* Process any user self specs. */
6524 struct spec_list *sl;
6525 for (sl = specs; sl; sl = sl->next)
6526 if (sl->name_len == sizeof "self_spec" - 1
6527 && !strcmp (sl->name, "self_spec"))
6528 do_self_spec (*sl->ptr_spec);
6531 if (compare_debug)
6533 enum save_temps save;
6535 if (!compare_debug_second)
6537 n_switches_debug_check[1] = n_switches;
6538 n_switches_alloc_debug_check[1] = n_switches_alloc;
6539 switches_debug_check[1] = XDUPVEC (struct switchstr, switches,
6540 n_switches_alloc);
6542 do_self_spec ("%:compare-debug-self-opt()");
6543 n_switches_debug_check[0] = n_switches;
6544 n_switches_alloc_debug_check[0] = n_switches_alloc;
6545 switches_debug_check[0] = switches;
6547 n_switches = n_switches_debug_check[1];
6548 n_switches_alloc = n_switches_alloc_debug_check[1];
6549 switches = switches_debug_check[1];
6552 /* Avoid crash when computing %j in this early. */
6553 save = save_temps_flag;
6554 save_temps_flag = SAVE_TEMPS_NONE;
6556 compare_debug = -compare_debug;
6557 do_self_spec ("%:compare-debug-self-opt()");
6559 save_temps_flag = save;
6561 if (!compare_debug_second)
6563 n_switches_debug_check[1] = n_switches;
6564 n_switches_alloc_debug_check[1] = n_switches_alloc;
6565 switches_debug_check[1] = switches;
6566 compare_debug = -compare_debug;
6567 n_switches = n_switches_debug_check[0];
6568 n_switches_alloc = n_switches_debug_check[0];
6569 switches = switches_debug_check[0];
6574 /* If we have a GCC_EXEC_PREFIX envvar, modify it for cpp's sake. */
6575 if (gcc_exec_prefix)
6576 gcc_exec_prefix = concat (gcc_exec_prefix, spec_machine, dir_separator_str,
6577 spec_version, dir_separator_str, NULL);
6579 /* Now we have the specs.
6580 Set the `valid' bits for switches that match anything in any spec. */
6582 validate_all_switches ();
6584 /* Now that we have the switches and the specs, set
6585 the subdirectory based on the options. */
6586 set_multilib_dir ();
6588 /* Set up to remember the pathname of gcc and any options
6589 needed for collect. We use argv[0] instead of progname because
6590 we need the complete pathname. */
6591 obstack_init (&collect_obstack);
6592 obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);
6593 obstack_grow (&collect_obstack, argv[0], strlen (argv[0]) + 1);
6594 xputenv (XOBFINISH (&collect_obstack, char *));
6596 /* Set up to remember the pathname of the lto wrapper. */
6598 if (have_c)
6599 lto_wrapper_file = NULL;
6600 else
6601 lto_wrapper_file = find_a_file (&exec_prefixes, "lto-wrapper",
6602 X_OK, false);
6603 if (lto_wrapper_file)
6605 lto_wrapper_spec = lto_wrapper_file;
6606 obstack_init (&collect_obstack);
6607 obstack_grow (&collect_obstack, "COLLECT_LTO_WRAPPER=",
6608 sizeof ("COLLECT_LTO_WRAPPER=") - 1);
6609 obstack_grow (&collect_obstack, lto_wrapper_spec,
6610 strlen (lto_wrapper_spec) + 1);
6611 xputenv (XOBFINISH (&collect_obstack, char *));
6614 /* Reject switches that no pass was interested in. */
6616 for (i = 0; (int) i < n_switches; i++)
6617 if (! switches[i].validated)
6618 error ("unrecognized command line option %<-%s%>", switches[i].part1);
6620 /* Obey some of the options. */
6622 if (print_search_dirs)
6624 printf (_("install: %s%s\n"),
6625 gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
6626 gcc_exec_prefix ? "" : machine_suffix);
6627 printf (_("programs: %s\n"),
6628 build_search_list (&exec_prefixes, "", false, false));
6629 printf (_("libraries: %s\n"),
6630 build_search_list (&startfile_prefixes, "", false, true));
6631 return (0);
6634 if (print_file_name)
6636 printf ("%s\n", find_file (print_file_name));
6637 return (0);
6640 if (print_prog_name)
6642 char *newname = find_a_file (&exec_prefixes, print_prog_name, X_OK, 0);
6643 printf ("%s\n", (newname ? newname : print_prog_name));
6644 return (0);
6647 if (print_multi_lib)
6649 print_multilib_info ();
6650 return (0);
6653 if (print_multi_directory)
6655 if (multilib_dir == NULL)
6656 printf (".\n");
6657 else
6658 printf ("%s\n", multilib_dir);
6659 return (0);
6662 if (print_multiarch)
6664 if (multiarch_dir == NULL)
6665 printf ("\n");
6666 else
6667 printf ("%s\n", multiarch_dir);
6668 return (0);
6671 if (print_sysroot)
6673 if (target_system_root)
6675 if (target_sysroot_suffix)
6676 printf ("%s%s\n", target_system_root, target_sysroot_suffix);
6677 else
6678 printf ("%s\n", target_system_root);
6680 return (0);
6683 if (print_multi_os_directory)
6685 if (multilib_os_dir == NULL)
6686 printf (".\n");
6687 else
6688 printf ("%s\n", multilib_os_dir);
6689 return (0);
6692 if (print_sysroot_headers_suffix)
6694 if (*sysroot_hdrs_suffix_spec)
6696 printf("%s\n", (target_sysroot_hdrs_suffix
6697 ? target_sysroot_hdrs_suffix
6698 : ""));
6699 return (0);
6701 else
6702 /* The error status indicates that only one set of fixed
6703 headers should be built. */
6704 fatal_error ("not configured with sysroot headers suffix");
6707 if (print_help_list)
6709 display_help ();
6711 if (! verbose_flag)
6713 printf (_("\nFor bug reporting instructions, please see:\n"));
6714 printf ("%s.\n", bug_report_url);
6716 return (0);
6719 /* We do not exit here. Instead we have created a fake input file
6720 called 'help-dummy' which needs to be compiled, and we pass this
6721 on the various sub-processes, along with the --help switch.
6722 Ensure their output appears after ours. */
6723 fputc ('\n', stdout);
6724 fflush (stdout);
6727 if (print_version)
6729 printf (_("%s %s%s\n"), progname, pkgversion_string,
6730 version_string);
6731 printf ("Copyright %s 2013 Free Software Foundation, Inc.\n",
6732 _("(C)"));
6733 fputs (_("This is free software; see the source for copying conditions. There is NO\n\
6734 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"),
6735 stdout);
6736 if (! verbose_flag)
6737 return 0;
6739 /* We do not exit here. We use the same mechanism of --help to print
6740 the version of the sub-processes. */
6741 fputc ('\n', stdout);
6742 fflush (stdout);
6745 if (verbose_flag)
6747 int n;
6748 const char *thrmod;
6750 fnotice (stderr, "Target: %s\n", spec_machine);
6751 fnotice (stderr, "Configured with: %s\n", configuration_arguments);
6753 #ifdef THREAD_MODEL_SPEC
6754 /* We could have defined THREAD_MODEL_SPEC to "%*" by default,
6755 but there's no point in doing all this processing just to get
6756 thread_model back. */
6757 obstack_init (&obstack);
6758 do_spec_1 (THREAD_MODEL_SPEC, 0, thread_model);
6759 obstack_1grow (&obstack, '\0');
6760 thrmod = XOBFINISH (&obstack, const char *);
6761 #else
6762 thrmod = thread_model;
6763 #endif
6765 fnotice (stderr, "Thread model: %s\n", thrmod);
6767 /* compiler_version is truncated at the first space when initialized
6768 from version string, so truncate version_string at the first space
6769 before comparing. */
6770 for (n = 0; version_string[n]; n++)
6771 if (version_string[n] == ' ')
6772 break;
6774 if (! strncmp (version_string, compiler_version, n)
6775 && compiler_version[n] == 0)
6776 fnotice (stderr, "gcc version %s %s\n", version_string,
6777 pkgversion_string);
6778 else
6779 fnotice (stderr, "gcc driver version %s %sexecuting gcc version %s\n",
6780 version_string, pkgversion_string, compiler_version);
6782 if (n_infiles == 0)
6783 return (0);
6786 if (n_infiles == added_libraries)
6787 fatal_error ("no input files");
6789 if (seen_error ())
6790 goto out;
6792 /* Make a place to record the compiler output file names
6793 that correspond to the input files. */
6795 i = n_infiles;
6796 i += lang_specific_extra_outfiles;
6797 outfiles = XCNEWVEC (const char *, i);
6799 /* Record which files were specified explicitly as link input. */
6801 explicit_link_files = XCNEWVEC (char, n_infiles);
6803 combine_inputs = have_o || flag_wpa;
6805 for (i = 0; (int) i < n_infiles; i++)
6807 const char *name = infiles[i].name;
6808 struct compiler *compiler = lookup_compiler (name,
6809 strlen (name),
6810 infiles[i].language);
6812 if (compiler && !(compiler->combinable))
6813 combine_inputs = false;
6815 if (lang_n_infiles > 0 && compiler != input_file_compiler
6816 && infiles[i].language && infiles[i].language[0] != '*')
6817 infiles[i].incompiler = compiler;
6818 else if (compiler)
6820 lang_n_infiles++;
6821 input_file_compiler = compiler;
6822 infiles[i].incompiler = compiler;
6824 else
6826 /* Since there is no compiler for this input file, assume it is a
6827 linker file. */
6828 explicit_link_files[i] = 1;
6829 infiles[i].incompiler = NULL;
6831 infiles[i].compiled = false;
6832 infiles[i].preprocessed = false;
6835 if (!combine_inputs && have_c && have_o && lang_n_infiles > 1)
6836 fatal_error ("cannot specify -o with -c, -S or -E with multiple files");
6838 for (i = 0; (int) i < n_infiles; i++)
6840 int this_file_error = 0;
6842 /* Tell do_spec what to substitute for %i. */
6844 input_file_number = i;
6845 set_input (infiles[i].name);
6847 if (infiles[i].compiled)
6848 continue;
6850 /* Use the same thing in %o, unless cp->spec says otherwise. */
6852 outfiles[i] = gcc_input_filename;
6854 /* Figure out which compiler from the file's suffix. */
6856 input_file_compiler
6857 = lookup_compiler (infiles[i].name, input_filename_length,
6858 infiles[i].language);
6860 if (input_file_compiler)
6862 /* Ok, we found an applicable compiler. Run its spec. */
6864 if (input_file_compiler->spec[0] == '#')
6866 error ("%s: %s compiler not installed on this system",
6867 gcc_input_filename, &input_file_compiler->spec[1]);
6868 this_file_error = 1;
6870 else
6872 if (compare_debug)
6874 free (debug_check_temp_file[0]);
6875 debug_check_temp_file[0] = NULL;
6877 free (debug_check_temp_file[1]);
6878 debug_check_temp_file[1] = NULL;
6881 value = do_spec (input_file_compiler->spec);
6882 infiles[i].compiled = true;
6883 if (value < 0)
6884 this_file_error = 1;
6885 else if (compare_debug && debug_check_temp_file[0])
6887 if (verbose_flag)
6888 inform (0, "recompiling with -fcompare-debug");
6890 compare_debug = -compare_debug;
6891 n_switches = n_switches_debug_check[1];
6892 n_switches_alloc = n_switches_alloc_debug_check[1];
6893 switches = switches_debug_check[1];
6895 value = do_spec (input_file_compiler->spec);
6897 compare_debug = -compare_debug;
6898 n_switches = n_switches_debug_check[0];
6899 n_switches_alloc = n_switches_alloc_debug_check[0];
6900 switches = switches_debug_check[0];
6902 if (value < 0)
6904 error ("during -fcompare-debug recompilation");
6905 this_file_error = 1;
6908 gcc_assert (debug_check_temp_file[1]
6909 && filename_cmp (debug_check_temp_file[0],
6910 debug_check_temp_file[1]));
6912 if (verbose_flag)
6913 inform (0, "comparing final insns dumps");
6915 if (compare_files (debug_check_temp_file))
6916 this_file_error = 1;
6919 if (compare_debug)
6921 free (debug_check_temp_file[0]);
6922 debug_check_temp_file[0] = NULL;
6924 free (debug_check_temp_file[1]);
6925 debug_check_temp_file[1] = NULL;
6930 /* If this file's name does not contain a recognized suffix,
6931 record it as explicit linker input. */
6933 else
6934 explicit_link_files[i] = 1;
6936 /* Clear the delete-on-failure queue, deleting the files in it
6937 if this compilation failed. */
6939 if (this_file_error)
6941 delete_failure_queue ();
6942 errorcount++;
6944 /* If this compilation succeeded, don't delete those files later. */
6945 clear_failure_queue ();
6948 /* Reset the input file name to the first compile/object file name, for use
6949 with %b in LINK_SPEC. We use the first input file that we can find
6950 a compiler to compile it instead of using infiles.language since for
6951 languages other than C we use aliases that we then lookup later. */
6952 if (n_infiles > 0)
6954 int i;
6956 for (i = 0; i < n_infiles ; i++)
6957 if (infiles[i].incompiler
6958 || (infiles[i].language && infiles[i].language[0] != '*'))
6960 set_input (infiles[i].name);
6961 break;
6965 if (!seen_error ())
6967 /* Make sure INPUT_FILE_NUMBER points to first available open
6968 slot. */
6969 input_file_number = n_infiles;
6970 if (lang_specific_pre_link ())
6971 errorcount++;
6974 /* Determine if there are any linker input files. */
6975 num_linker_inputs = 0;
6976 for (i = 0; (int) i < n_infiles; i++)
6977 if (explicit_link_files[i] || outfiles[i] != NULL)
6978 num_linker_inputs++;
6980 /* Run ld to link all the compiler output files. */
6982 if (num_linker_inputs > 0 && !seen_error () && print_subprocess_help < 2)
6984 int tmp = execution_count;
6986 if (! have_c)
6988 #if HAVE_LTO_PLUGIN > 0
6989 #if HAVE_LTO_PLUGIN == 2
6990 const char *fno_use_linker_plugin = "fno-use-linker-plugin";
6991 #else
6992 const char *fuse_linker_plugin = "fuse-linker-plugin";
6993 #endif
6994 #endif
6996 /* We'll use ld if we can't find collect2. */
6997 if (! strcmp (linker_name_spec, "collect2"))
6999 char *s = find_a_file (&exec_prefixes, "collect2", X_OK, false);
7000 if (s == NULL)
7001 linker_name_spec = "ld";
7004 #if HAVE_LTO_PLUGIN > 0
7005 #if HAVE_LTO_PLUGIN == 2
7006 if (!switch_matches (fno_use_linker_plugin,
7007 fno_use_linker_plugin
7008 + strlen (fno_use_linker_plugin), 0))
7009 #else
7010 if (switch_matches (fuse_linker_plugin,
7011 fuse_linker_plugin
7012 + strlen (fuse_linker_plugin), 0))
7013 #endif
7015 linker_plugin_file_spec = find_a_file (&exec_prefixes,
7016 LTOPLUGINSONAME, R_OK,
7017 false);
7018 if (!linker_plugin_file_spec)
7019 fatal_error ("-fuse-linker-plugin, but %s not found",
7020 LTOPLUGINSONAME);
7022 #endif
7023 lto_gcc_spec = argv[0];
7026 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
7027 for collect. */
7028 putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH", false);
7029 putenv_from_prefixes (&startfile_prefixes, LIBRARY_PATH_ENV, true);
7031 if (print_subprocess_help == 1)
7033 printf (_("\nLinker options\n==============\n\n"));
7034 printf (_("Use \"-Wl,OPTION\" to pass \"OPTION\""
7035 " to the linker.\n\n"));
7036 fflush (stdout);
7038 value = do_spec (link_command_spec);
7039 if (value < 0)
7040 errorcount = 1;
7041 linker_was_run = (tmp != execution_count);
7044 /* If options said don't run linker,
7045 complain about input files to be given to the linker. */
7047 if (! linker_was_run && !seen_error ())
7048 for (i = 0; (int) i < n_infiles; i++)
7049 if (explicit_link_files[i]
7050 && !(infiles[i].language && infiles[i].language[0] == '*'))
7051 warning (0, "%s: linker input file unused because linking not done",
7052 outfiles[i]);
7054 /* Delete some or all of the temporary files we made. */
7056 if (seen_error ())
7057 delete_failure_queue ();
7058 delete_temp_files ();
7060 if (print_help_list)
7062 printf (("\nFor bug reporting instructions, please see:\n"));
7063 printf ("%s\n", bug_report_url);
7066 out:
7067 return (signal_count != 0 ? 2
7068 : seen_error () ? (pass_exit_codes ? greatest_status : 1)
7069 : 0);
7072 /* Find the proper compilation spec for the file name NAME,
7073 whose length is LENGTH. LANGUAGE is the specified language,
7074 or 0 if this file is to be passed to the linker. */
7076 static struct compiler *
7077 lookup_compiler (const char *name, size_t length, const char *language)
7079 struct compiler *cp;
7081 /* If this was specified by the user to be a linker input, indicate that. */
7082 if (language != 0 && language[0] == '*')
7083 return 0;
7085 /* Otherwise, look for the language, if one is spec'd. */
7086 if (language != 0)
7088 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7089 if (cp->suffix[0] == '@' && !strcmp (cp->suffix + 1, language))
7090 return cp;
7092 error ("language %s not recognized", language);
7093 return 0;
7096 /* Look for a suffix. */
7097 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7099 if (/* The suffix `-' matches only the file name `-'. */
7100 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
7101 || (strlen (cp->suffix) < length
7102 /* See if the suffix matches the end of NAME. */
7103 && !strcmp (cp->suffix,
7104 name + length - strlen (cp->suffix))
7106 break;
7109 #if defined (OS2) ||defined (HAVE_DOS_BASED_FILE_SYSTEM)
7110 /* Look again, but case-insensitively this time. */
7111 if (cp < compilers)
7112 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7114 if (/* The suffix `-' matches only the file name `-'. */
7115 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
7116 || (strlen (cp->suffix) < length
7117 /* See if the suffix matches the end of NAME. */
7118 && ((!strcmp (cp->suffix,
7119 name + length - strlen (cp->suffix))
7120 || !strpbrk (cp->suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
7121 && !strcasecmp (cp->suffix,
7122 name + length - strlen (cp->suffix)))
7124 break;
7126 #endif
7128 if (cp >= compilers)
7130 if (cp->spec[0] != '@')
7131 /* A non-alias entry: return it. */
7132 return cp;
7134 /* An alias entry maps a suffix to a language.
7135 Search for the language; pass 0 for NAME and LENGTH
7136 to avoid infinite recursion if language not found. */
7137 return lookup_compiler (NULL, 0, cp->spec + 1);
7139 return 0;
7142 static char *
7143 save_string (const char *s, int len)
7145 char *result = XNEWVEC (char, len + 1);
7147 memcpy (result, s, len);
7148 result[len] = 0;
7149 return result;
7152 void
7153 pfatal_with_name (const char *name)
7155 perror_with_name (name);
7156 delete_temp_files ();
7157 exit (1);
7160 static void
7161 perror_with_name (const char *name)
7163 error ("%s: %m", name);
7166 static inline void
7167 validate_switches_from_spec (const char *spec, bool user)
7169 const char *p = spec;
7170 char c;
7171 while ((c = *p++))
7172 if (c == '%' && (*p == '{' || *p == '<' || (*p == 'W' && *++p == '{')))
7173 /* We have a switch spec. */
7174 p = validate_switches (p + 1, user);
7177 static void
7178 validate_all_switches (void)
7180 struct compiler *comp;
7181 struct spec_list *spec;
7183 for (comp = compilers; comp->spec; comp++)
7184 validate_switches_from_spec (comp->spec, false);
7186 /* Look through the linked list of specs read from the specs file. */
7187 for (spec = specs; spec; spec = spec->next)
7188 validate_switches_from_spec (*spec->ptr_spec, spec->user_p);
7190 validate_switches_from_spec (link_command_spec, false);
7193 /* Look at the switch-name that comes after START
7194 and mark as valid all supplied switches that match it. */
7196 static const char *
7197 validate_switches (const char *start, bool user_spec)
7199 const char *p = start;
7200 const char *atom;
7201 size_t len;
7202 int i;
7203 bool suffix = false;
7204 bool starred = false;
7206 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
7208 next_member:
7209 SKIP_WHITE ();
7211 if (*p == '!')
7212 p++;
7214 SKIP_WHITE ();
7215 if (*p == '.' || *p == ',')
7216 suffix = true, p++;
7218 atom = p;
7219 while (ISIDNUM (*p) || *p == '-' || *p == '+' || *p == '='
7220 || *p == ',' || *p == '.' || *p == '@')
7221 p++;
7222 len = p - atom;
7224 if (*p == '*')
7225 starred = true, p++;
7227 SKIP_WHITE ();
7229 if (!suffix)
7231 /* Mark all matching switches as valid. */
7232 for (i = 0; i < n_switches; i++)
7233 if (!strncmp (switches[i].part1, atom, len)
7234 && (starred || switches[i].part1[len] == '\0')
7235 && (switches[i].known || user_spec))
7236 switches[i].validated = true;
7239 if (*p) p++;
7240 if (*p && (p[-1] == '|' || p[-1] == '&'))
7241 goto next_member;
7243 if (*p && p[-1] == ':')
7245 while (*p && *p != ';' && *p != '}')
7247 if (*p == '%')
7249 p++;
7250 if (*p == '{' || *p == '<')
7251 p = validate_switches (p+1, user_spec);
7252 else if (p[0] == 'W' && p[1] == '{')
7253 p = validate_switches (p+2, user_spec);
7255 else
7256 p++;
7259 if (*p) p++;
7260 if (*p && p[-1] == ';')
7261 goto next_member;
7264 return p;
7265 #undef SKIP_WHITE
7268 struct mdswitchstr
7270 const char *str;
7271 int len;
7274 static struct mdswitchstr *mdswitches;
7275 static int n_mdswitches;
7277 /* Check whether a particular argument was used. The first time we
7278 canonicalize the switches to keep only the ones we care about. */
7280 static int
7281 used_arg (const char *p, int len)
7283 struct mswitchstr
7285 const char *str;
7286 const char *replace;
7287 int len;
7288 int rep_len;
7291 static struct mswitchstr *mswitches;
7292 static int n_mswitches;
7293 int i, j;
7295 if (!mswitches)
7297 struct mswitchstr *matches;
7298 const char *q;
7299 int cnt = 0;
7301 /* Break multilib_matches into the component strings of string
7302 and replacement string. */
7303 for (q = multilib_matches; *q != '\0'; q++)
7304 if (*q == ';')
7305 cnt++;
7307 matches
7308 = (struct mswitchstr *) alloca ((sizeof (struct mswitchstr)) * cnt);
7309 i = 0;
7310 q = multilib_matches;
7311 while (*q != '\0')
7313 matches[i].str = q;
7314 while (*q != ' ')
7316 if (*q == '\0')
7318 invalid_matches:
7319 fatal_error ("multilib spec %qs is invalid",
7320 multilib_matches);
7322 q++;
7324 matches[i].len = q - matches[i].str;
7326 matches[i].replace = ++q;
7327 while (*q != ';' && *q != '\0')
7329 if (*q == ' ')
7330 goto invalid_matches;
7331 q++;
7333 matches[i].rep_len = q - matches[i].replace;
7334 i++;
7335 if (*q == ';')
7336 q++;
7339 /* Now build a list of the replacement string for switches that we care
7340 about. Make sure we allocate at least one entry. This prevents
7341 xmalloc from calling fatal, and prevents us from re-executing this
7342 block of code. */
7343 mswitches
7344 = XNEWVEC (struct mswitchstr, n_mdswitches + (n_switches ? n_switches : 1));
7345 for (i = 0; i < n_switches; i++)
7346 if ((switches[i].live_cond & SWITCH_IGNORE) == 0)
7348 int xlen = strlen (switches[i].part1);
7349 for (j = 0; j < cnt; j++)
7350 if (xlen == matches[j].len
7351 && ! strncmp (switches[i].part1, matches[j].str, xlen))
7353 mswitches[n_mswitches].str = matches[j].replace;
7354 mswitches[n_mswitches].len = matches[j].rep_len;
7355 mswitches[n_mswitches].replace = (char *) 0;
7356 mswitches[n_mswitches].rep_len = 0;
7357 n_mswitches++;
7358 break;
7362 /* Add MULTILIB_DEFAULTS switches too, as long as they were not present
7363 on the command line nor any options mutually incompatible with
7364 them. */
7365 for (i = 0; i < n_mdswitches; i++)
7367 const char *r;
7369 for (q = multilib_options; *q != '\0'; q++)
7371 while (*q == ' ')
7372 q++;
7374 r = q;
7375 while (strncmp (q, mdswitches[i].str, mdswitches[i].len) != 0
7376 || strchr (" /", q[mdswitches[i].len]) == NULL)
7378 while (*q != ' ' && *q != '/' && *q != '\0')
7379 q++;
7380 if (*q != '/')
7381 break;
7382 q++;
7385 if (*q != ' ' && *q != '\0')
7387 while (*r != ' ' && *r != '\0')
7389 q = r;
7390 while (*q != ' ' && *q != '/' && *q != '\0')
7391 q++;
7393 if (used_arg (r, q - r))
7394 break;
7396 if (*q != '/')
7398 mswitches[n_mswitches].str = mdswitches[i].str;
7399 mswitches[n_mswitches].len = mdswitches[i].len;
7400 mswitches[n_mswitches].replace = (char *) 0;
7401 mswitches[n_mswitches].rep_len = 0;
7402 n_mswitches++;
7403 break;
7406 r = q + 1;
7408 break;
7414 for (i = 0; i < n_mswitches; i++)
7415 if (len == mswitches[i].len && ! strncmp (p, mswitches[i].str, len))
7416 return 1;
7418 return 0;
7421 static int
7422 default_arg (const char *p, int len)
7424 int i;
7426 for (i = 0; i < n_mdswitches; i++)
7427 if (len == mdswitches[i].len && ! strncmp (p, mdswitches[i].str, len))
7428 return 1;
7430 return 0;
7433 /* Work out the subdirectory to use based on the options. The format of
7434 multilib_select is a list of elements. Each element is a subdirectory
7435 name followed by a list of options followed by a semicolon. The format
7436 of multilib_exclusions is the same, but without the preceding
7437 directory. First gcc will check the exclusions, if none of the options
7438 beginning with an exclamation point are present, and all of the other
7439 options are present, then we will ignore this completely. Passing
7440 that, gcc will consider each multilib_select in turn using the same
7441 rules for matching the options. If a match is found, that subdirectory
7442 will be used.
7443 A subdirectory name is optionally followed by a colon and the corresponding
7444 multiarch name. */
7446 static void
7447 set_multilib_dir (void)
7449 const char *p;
7450 unsigned int this_path_len;
7451 const char *this_path, *this_arg;
7452 const char *start, *end;
7453 int not_arg;
7454 int ok, ndfltok, first;
7456 n_mdswitches = 0;
7457 start = multilib_defaults;
7458 while (*start == ' ' || *start == '\t')
7459 start++;
7460 while (*start != '\0')
7462 n_mdswitches++;
7463 while (*start != ' ' && *start != '\t' && *start != '\0')
7464 start++;
7465 while (*start == ' ' || *start == '\t')
7466 start++;
7469 if (n_mdswitches)
7471 int i = 0;
7473 mdswitches = XNEWVEC (struct mdswitchstr, n_mdswitches);
7474 for (start = multilib_defaults; *start != '\0'; start = end + 1)
7476 while (*start == ' ' || *start == '\t')
7477 start++;
7479 if (*start == '\0')
7480 break;
7482 for (end = start + 1;
7483 *end != ' ' && *end != '\t' && *end != '\0'; end++)
7486 obstack_grow (&multilib_obstack, start, end - start);
7487 obstack_1grow (&multilib_obstack, 0);
7488 mdswitches[i].str = XOBFINISH (&multilib_obstack, const char *);
7489 mdswitches[i++].len = end - start;
7491 if (*end == '\0')
7492 break;
7496 p = multilib_exclusions;
7497 while (*p != '\0')
7499 /* Ignore newlines. */
7500 if (*p == '\n')
7502 ++p;
7503 continue;
7506 /* Check the arguments. */
7507 ok = 1;
7508 while (*p != ';')
7510 if (*p == '\0')
7512 invalid_exclusions:
7513 fatal_error ("multilib exclusions %qs is invalid",
7514 multilib_exclusions);
7517 if (! ok)
7519 ++p;
7520 continue;
7523 this_arg = p;
7524 while (*p != ' ' && *p != ';')
7526 if (*p == '\0')
7527 goto invalid_exclusions;
7528 ++p;
7531 if (*this_arg != '!')
7532 not_arg = 0;
7533 else
7535 not_arg = 1;
7536 ++this_arg;
7539 ok = used_arg (this_arg, p - this_arg);
7540 if (not_arg)
7541 ok = ! ok;
7543 if (*p == ' ')
7544 ++p;
7547 if (ok)
7548 return;
7550 ++p;
7553 first = 1;
7554 p = multilib_select;
7555 while (*p != '\0')
7557 /* Ignore newlines. */
7558 if (*p == '\n')
7560 ++p;
7561 continue;
7564 /* Get the initial path. */
7565 this_path = p;
7566 while (*p != ' ')
7568 if (*p == '\0')
7570 invalid_select:
7571 fatal_error ("multilib select %qs is invalid",
7572 multilib_select);
7574 ++p;
7576 this_path_len = p - this_path;
7578 /* Check the arguments. */
7579 ok = 1;
7580 ndfltok = 1;
7581 ++p;
7582 while (*p != ';')
7584 if (*p == '\0')
7585 goto invalid_select;
7587 if (! ok)
7589 ++p;
7590 continue;
7593 this_arg = p;
7594 while (*p != ' ' && *p != ';')
7596 if (*p == '\0')
7597 goto invalid_select;
7598 ++p;
7601 if (*this_arg != '!')
7602 not_arg = 0;
7603 else
7605 not_arg = 1;
7606 ++this_arg;
7609 /* If this is a default argument, we can just ignore it.
7610 This is true even if this_arg begins with '!'. Beginning
7611 with '!' does not mean that this argument is necessarily
7612 inappropriate for this library: it merely means that
7613 there is a more specific library which uses this
7614 argument. If this argument is a default, we need not
7615 consider that more specific library. */
7616 ok = used_arg (this_arg, p - this_arg);
7617 if (not_arg)
7618 ok = ! ok;
7620 if (! ok)
7621 ndfltok = 0;
7623 if (default_arg (this_arg, p - this_arg))
7624 ok = 1;
7626 if (*p == ' ')
7627 ++p;
7630 if (ok && first)
7632 if (this_path_len != 1
7633 || this_path[0] != '.')
7635 char *new_multilib_dir = XNEWVEC (char, this_path_len + 1);
7636 char *q;
7638 strncpy (new_multilib_dir, this_path, this_path_len);
7639 new_multilib_dir[this_path_len] = '\0';
7640 q = strchr (new_multilib_dir, ':');
7641 if (q != NULL)
7642 *q = '\0';
7643 multilib_dir = new_multilib_dir;
7645 first = 0;
7648 if (ndfltok)
7650 const char *q = this_path, *end = this_path + this_path_len;
7652 while (q < end && *q != ':')
7653 q++;
7654 if (q < end)
7656 const char *q2 = q + 1, *ml_end = end;
7657 char *new_multilib_os_dir;
7659 while (q2 < end && *q2 != ':')
7660 q2++;
7661 if (*q2 == ':')
7662 ml_end = q2;
7663 new_multilib_os_dir = XNEWVEC (char, ml_end - q);
7664 memcpy (new_multilib_os_dir, q + 1, ml_end - q - 1);
7665 new_multilib_os_dir[ml_end - q - 1] = '\0';
7666 multilib_os_dir = *new_multilib_os_dir ? new_multilib_os_dir : ".";
7668 if (q2 < end && *q2 == ':')
7670 char *new_multiarch_dir = XNEWVEC (char, end - q2);
7671 memcpy (new_multiarch_dir, q2 + 1, end - q2 - 1);
7672 new_multiarch_dir[end - q2 - 1] = '\0';
7673 multiarch_dir = new_multiarch_dir;
7675 break;
7679 ++p;
7682 if (multilib_dir == NULL && multilib_os_dir != NULL
7683 && strcmp (multilib_os_dir, ".") == 0)
7685 free (CONST_CAST (char *, multilib_os_dir));
7686 multilib_os_dir = NULL;
7688 else if (multilib_dir != NULL && multilib_os_dir == NULL)
7689 multilib_os_dir = multilib_dir;
7692 /* Print out the multiple library subdirectory selection
7693 information. This prints out a series of lines. Each line looks
7694 like SUBDIRECTORY;@OPTION@OPTION, with as many options as is
7695 required. Only the desired options are printed out, the negative
7696 matches. The options are print without a leading dash. There are
7697 no spaces to make it easy to use the information in the shell.
7698 Each subdirectory is printed only once. This assumes the ordering
7699 generated by the genmultilib script. Also, we leave out ones that match
7700 the exclusions. */
7702 static void
7703 print_multilib_info (void)
7705 const char *p = multilib_select;
7706 const char *last_path = 0, *this_path;
7707 int skip;
7708 unsigned int last_path_len = 0;
7710 while (*p != '\0')
7712 skip = 0;
7713 /* Ignore newlines. */
7714 if (*p == '\n')
7716 ++p;
7717 continue;
7720 /* Get the initial path. */
7721 this_path = p;
7722 while (*p != ' ')
7724 if (*p == '\0')
7726 invalid_select:
7727 fatal_error ("multilib select %qs is invalid", multilib_select);
7730 ++p;
7733 /* When --disable-multilib was used but target defines
7734 MULTILIB_OSDIRNAMES, entries starting with .: (and not starting
7735 with .:: for multiarch configurations) are there just to find
7736 multilib_os_dir, so skip them from output. */
7737 if (this_path[0] == '.' && this_path[1] == ':' && this_path[2] != ':')
7738 skip = 1;
7740 /* Check for matches with the multilib_exclusions. We don't bother
7741 with the '!' in either list. If any of the exclusion rules match
7742 all of its options with the select rule, we skip it. */
7744 const char *e = multilib_exclusions;
7745 const char *this_arg;
7747 while (*e != '\0')
7749 int m = 1;
7750 /* Ignore newlines. */
7751 if (*e == '\n')
7753 ++e;
7754 continue;
7757 /* Check the arguments. */
7758 while (*e != ';')
7760 const char *q;
7761 int mp = 0;
7763 if (*e == '\0')
7765 invalid_exclusion:
7766 fatal_error ("multilib exclusion %qs is invalid",
7767 multilib_exclusions);
7770 if (! m)
7772 ++e;
7773 continue;
7776 this_arg = e;
7778 while (*e != ' ' && *e != ';')
7780 if (*e == '\0')
7781 goto invalid_exclusion;
7782 ++e;
7785 q = p + 1;
7786 while (*q != ';')
7788 const char *arg;
7789 int len = e - this_arg;
7791 if (*q == '\0')
7792 goto invalid_select;
7794 arg = q;
7796 while (*q != ' ' && *q != ';')
7798 if (*q == '\0')
7799 goto invalid_select;
7800 ++q;
7803 if (! strncmp (arg, this_arg,
7804 (len < q - arg) ? q - arg : len)
7805 || default_arg (this_arg, e - this_arg))
7807 mp = 1;
7808 break;
7811 if (*q == ' ')
7812 ++q;
7815 if (! mp)
7816 m = 0;
7818 if (*e == ' ')
7819 ++e;
7822 if (m)
7824 skip = 1;
7825 break;
7828 if (*e != '\0')
7829 ++e;
7833 if (! skip)
7835 /* If this is a duplicate, skip it. */
7836 skip = (last_path != 0
7837 && (unsigned int) (p - this_path) == last_path_len
7838 && ! filename_ncmp (last_path, this_path, last_path_len));
7840 last_path = this_path;
7841 last_path_len = p - this_path;
7844 /* If this directory requires any default arguments, we can skip
7845 it. We will already have printed a directory identical to
7846 this one which does not require that default argument. */
7847 if (! skip)
7849 const char *q;
7851 q = p + 1;
7852 while (*q != ';')
7854 const char *arg;
7856 if (*q == '\0')
7857 goto invalid_select;
7859 if (*q == '!')
7860 arg = NULL;
7861 else
7862 arg = q;
7864 while (*q != ' ' && *q != ';')
7866 if (*q == '\0')
7867 goto invalid_select;
7868 ++q;
7871 if (arg != NULL
7872 && default_arg (arg, q - arg))
7874 skip = 1;
7875 break;
7878 if (*q == ' ')
7879 ++q;
7883 if (! skip)
7885 const char *p1;
7887 for (p1 = last_path; p1 < p && *p1 != ':'; p1++)
7888 putchar (*p1);
7889 putchar (';');
7892 ++p;
7893 while (*p != ';')
7895 int use_arg;
7897 if (*p == '\0')
7898 goto invalid_select;
7900 if (skip)
7902 ++p;
7903 continue;
7906 use_arg = *p != '!';
7908 if (use_arg)
7909 putchar ('@');
7911 while (*p != ' ' && *p != ';')
7913 if (*p == '\0')
7914 goto invalid_select;
7915 if (use_arg)
7916 putchar (*p);
7917 ++p;
7920 if (*p == ' ')
7921 ++p;
7924 if (! skip)
7926 /* If there are extra options, print them now. */
7927 if (multilib_extra && *multilib_extra)
7929 int print_at = TRUE;
7930 const char *q;
7932 for (q = multilib_extra; *q != '\0'; q++)
7934 if (*q == ' ')
7935 print_at = TRUE;
7936 else
7938 if (print_at)
7939 putchar ('@');
7940 putchar (*q);
7941 print_at = FALSE;
7946 putchar ('\n');
7949 ++p;
7953 /* getenv built-in spec function.
7955 Returns the value of the environment variable given by its first
7956 argument, concatenated with the second argument. If the
7957 environment variable is not defined, a fatal error is issued. */
7959 static const char *
7960 getenv_spec_function (int argc, const char **argv)
7962 char *value;
7963 char *result;
7964 char *ptr;
7965 size_t len;
7967 if (argc != 2)
7968 return NULL;
7970 value = getenv (argv[0]);
7971 if (!value)
7972 fatal_error ("environment variable %qs not defined", argv[0]);
7974 /* We have to escape every character of the environment variable so
7975 they are not interpreted as active spec characters. A
7976 particularly painful case is when we are reading a variable
7977 holding a windows path complete with \ separators. */
7978 len = strlen (value) * 2 + strlen (argv[1]) + 1;
7979 result = XNEWVAR (char, len);
7980 for (ptr = result; *value; ptr += 2)
7982 ptr[0] = '\\';
7983 ptr[1] = *value++;
7986 strcpy (ptr, argv[1]);
7988 return result;
7991 /* if-exists built-in spec function.
7993 Checks to see if the file specified by the absolute pathname in
7994 ARGS exists. Returns that pathname if found.
7996 The usual use for this function is to check for a library file
7997 (whose name has been expanded with %s). */
7999 static const char *
8000 if_exists_spec_function (int argc, const char **argv)
8002 /* Must have only one argument. */
8003 if (argc == 1 && IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
8004 return argv[0];
8006 return NULL;
8009 /* if-exists-else built-in spec function.
8011 This is like if-exists, but takes an additional argument which
8012 is returned if the first argument does not exist. */
8014 static const char *
8015 if_exists_else_spec_function (int argc, const char **argv)
8017 /* Must have exactly two arguments. */
8018 if (argc != 2)
8019 return NULL;
8021 if (IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
8022 return argv[0];
8024 return argv[1];
8027 /* replace-outfile built-in spec function.
8029 This looks for the first argument in the outfiles array's name and
8030 replaces it with the second argument. */
8032 static const char *
8033 replace_outfile_spec_function (int argc, const char **argv)
8035 int i;
8036 /* Must have exactly two arguments. */
8037 if (argc != 2)
8038 abort ();
8040 for (i = 0; i < n_infiles; i++)
8042 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
8043 outfiles[i] = xstrdup (argv[1]);
8045 return NULL;
8048 /* remove-outfile built-in spec function.
8050 * This looks for the first argument in the outfiles array's name and
8051 * removes it. */
8053 static const char *
8054 remove_outfile_spec_function (int argc, const char **argv)
8056 int i;
8057 /* Must have exactly one argument. */
8058 if (argc != 1)
8059 abort ();
8061 for (i = 0; i < n_infiles; i++)
8063 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
8064 outfiles[i] = NULL;
8066 return NULL;
8069 /* Given two version numbers, compares the two numbers.
8070 A version number must match the regular expression
8071 ([1-9][0-9]*|0)(\.([1-9][0-9]*|0))*
8073 static int
8074 compare_version_strings (const char *v1, const char *v2)
8076 int rresult;
8077 regex_t r;
8079 if (regcomp (&r, "^([1-9][0-9]*|0)(\\.([1-9][0-9]*|0))*$",
8080 REG_EXTENDED | REG_NOSUB) != 0)
8081 abort ();
8082 rresult = regexec (&r, v1, 0, NULL, 0);
8083 if (rresult == REG_NOMATCH)
8084 fatal_error ("invalid version number %qs", v1);
8085 else if (rresult != 0)
8086 abort ();
8087 rresult = regexec (&r, v2, 0, NULL, 0);
8088 if (rresult == REG_NOMATCH)
8089 fatal_error ("invalid version number %qs", v2);
8090 else if (rresult != 0)
8091 abort ();
8093 return strverscmp (v1, v2);
8097 /* version_compare built-in spec function.
8099 This takes an argument of the following form:
8101 <comparison-op> <arg1> [<arg2>] <switch> <result>
8103 and produces "result" if the comparison evaluates to true,
8104 and nothing if it doesn't.
8106 The supported <comparison-op> values are:
8108 >= true if switch is a later (or same) version than arg1
8109 !> opposite of >=
8110 < true if switch is an earlier version than arg1
8111 !< opposite of <
8112 >< true if switch is arg1 or later, and earlier than arg2
8113 <> true if switch is earlier than arg1 or is arg2 or later
8115 If the switch is not present, the condition is false unless
8116 the first character of the <comparison-op> is '!'.
8118 For example,
8119 %:version-compare(>= 10.3 mmacosx-version-min= -lmx)
8120 adds -lmx if -mmacosx-version-min=10.3.9 was passed. */
8122 static const char *
8123 version_compare_spec_function (int argc, const char **argv)
8125 int comp1, comp2;
8126 size_t switch_len;
8127 const char *switch_value = NULL;
8128 int nargs = 1, i;
8129 bool result;
8131 if (argc < 3)
8132 fatal_error ("too few arguments to %%:version-compare");
8133 if (argv[0][0] == '\0')
8134 abort ();
8135 if ((argv[0][1] == '<' || argv[0][1] == '>') && argv[0][0] != '!')
8136 nargs = 2;
8137 if (argc != nargs + 3)
8138 fatal_error ("too many arguments to %%:version-compare");
8140 switch_len = strlen (argv[nargs + 1]);
8141 for (i = 0; i < n_switches; i++)
8142 if (!strncmp (switches[i].part1, argv[nargs + 1], switch_len)
8143 && check_live_switch (i, switch_len))
8144 switch_value = switches[i].part1 + switch_len;
8146 if (switch_value == NULL)
8147 comp1 = comp2 = -1;
8148 else
8150 comp1 = compare_version_strings (switch_value, argv[1]);
8151 if (nargs == 2)
8152 comp2 = compare_version_strings (switch_value, argv[2]);
8153 else
8154 comp2 = -1; /* This value unused. */
8157 switch (argv[0][0] << 8 | argv[0][1])
8159 case '>' << 8 | '=':
8160 result = comp1 >= 0;
8161 break;
8162 case '!' << 8 | '<':
8163 result = comp1 >= 0 || switch_value == NULL;
8164 break;
8165 case '<' << 8:
8166 result = comp1 < 0;
8167 break;
8168 case '!' << 8 | '>':
8169 result = comp1 < 0 || switch_value == NULL;
8170 break;
8171 case '>' << 8 | '<':
8172 result = comp1 >= 0 && comp2 < 0;
8173 break;
8174 case '<' << 8 | '>':
8175 result = comp1 < 0 || comp2 >= 0;
8176 break;
8178 default:
8179 fatal_error ("unknown operator %qs in %%:version-compare", argv[0]);
8181 if (! result)
8182 return NULL;
8184 return argv[nargs + 2];
8187 /* %:include builtin spec function. This differs from %include in that it
8188 can be nested inside a spec, and thus be conditionalized. It takes
8189 one argument, the filename, and looks for it in the startfile path.
8190 The result is always NULL, i.e. an empty expansion. */
8192 static const char *
8193 include_spec_function (int argc, const char **argv)
8195 char *file;
8197 if (argc != 1)
8198 abort ();
8200 file = find_a_file (&startfile_prefixes, argv[0], R_OK, true);
8201 read_specs (file ? file : argv[0], false, false);
8203 return NULL;
8206 /* %:find-file spec function. This function replaces its argument by
8207 the file found through find_file, that is the -print-file-name gcc
8208 program option. */
8209 static const char *
8210 find_file_spec_function (int argc, const char **argv)
8212 const char *file;
8214 if (argc != 1)
8215 abort ();
8217 file = find_file (argv[0]);
8218 return file;
8222 /* %:find-plugindir spec function. This function replaces its argument
8223 by the -iplugindir=<dir> option. `dir' is found through find_file, that
8224 is the -print-file-name gcc program option. */
8225 static const char *
8226 find_plugindir_spec_function (int argc, const char **argv ATTRIBUTE_UNUSED)
8228 const char *option;
8230 if (argc != 0)
8231 abort ();
8233 option = concat ("-iplugindir=", find_file ("plugin"), NULL);
8234 return option;
8238 /* %:print-asm-header spec function. Print a banner to say that the
8239 following output is from the assembler. */
8241 static const char *
8242 print_asm_header_spec_function (int arg ATTRIBUTE_UNUSED,
8243 const char **argv ATTRIBUTE_UNUSED)
8245 printf (_("Assembler options\n=================\n\n"));
8246 printf (_("Use \"-Wa,OPTION\" to pass \"OPTION\" to the assembler.\n\n"));
8247 fflush (stdout);
8248 return NULL;
8251 /* Get a random number for -frandom-seed */
8253 static unsigned HOST_WIDE_INT
8254 get_random_number (void)
8256 unsigned HOST_WIDE_INT ret = 0;
8257 int fd;
8259 fd = open ("/dev/urandom", O_RDONLY);
8260 if (fd >= 0)
8262 read (fd, &ret, sizeof (HOST_WIDE_INT));
8263 close (fd);
8264 if (ret)
8265 return ret;
8268 /* Get some more or less random data. */
8269 #ifdef HAVE_GETTIMEOFDAY
8271 struct timeval tv;
8273 gettimeofday (&tv, NULL);
8274 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
8276 #else
8278 time_t now = time (NULL);
8280 if (now != (time_t)-1)
8281 ret = (unsigned) now;
8283 #endif
8285 return ret ^ getpid();
8288 /* %:compare-debug-dump-opt spec function. Save the last argument,
8289 expected to be the last -fdump-final-insns option, or generate a
8290 temporary. */
8292 static const char *
8293 compare_debug_dump_opt_spec_function (int arg,
8294 const char **argv ATTRIBUTE_UNUSED)
8296 char *ret;
8297 char *name;
8298 int which;
8299 static char random_seed[HOST_BITS_PER_WIDE_INT / 4 + 3];
8301 if (arg != 0)
8302 fatal_error ("too many arguments to %%:compare-debug-dump-opt");
8304 do_spec_2 ("%{fdump-final-insns=*:%*}");
8305 do_spec_1 (" ", 0, NULL);
8307 if (argbuf.length () > 0
8308 && strcmp (argv[argbuf.length () - 1], "."))
8310 if (!compare_debug)
8311 return NULL;
8313 name = xstrdup (argv[argbuf.length () - 1]);
8314 ret = NULL;
8316 else
8318 const char *ext = NULL;
8320 if (argbuf.length () > 0)
8322 do_spec_2 ("%{o*:%*}%{!o:%{!S:%b%O}%{S:%b.s}}");
8323 ext = ".gkd";
8325 else if (!compare_debug)
8326 return NULL;
8327 else
8328 do_spec_2 ("%g.gkd");
8330 do_spec_1 (" ", 0, NULL);
8332 gcc_assert (argbuf.length () > 0);
8334 name = concat (argbuf.last (), ext, NULL);
8336 ret = concat ("-fdump-final-insns=", name, NULL);
8339 which = compare_debug < 0;
8340 debug_check_temp_file[which] = name;
8342 if (!which)
8344 unsigned HOST_WIDE_INT value = get_random_number ();
8346 sprintf (random_seed, HOST_WIDE_INT_PRINT_HEX, value);
8349 if (*random_seed)
8351 char *tmp = ret;
8352 ret = concat ("%{!frandom-seed=*:-frandom-seed=", random_seed, "} ",
8353 ret, NULL);
8354 free (tmp);
8357 if (which)
8358 *random_seed = 0;
8360 return ret;
8363 static const char *debug_auxbase_opt;
8365 /* %:compare-debug-self-opt spec function. Expands to the options
8366 that are to be passed in the second compilation of
8367 compare-debug. */
8369 static const char *
8370 compare_debug_self_opt_spec_function (int arg,
8371 const char **argv ATTRIBUTE_UNUSED)
8373 if (arg != 0)
8374 fatal_error ("too many arguments to %%:compare-debug-self-opt");
8376 if (compare_debug >= 0)
8377 return NULL;
8379 do_spec_2 ("%{c|S:%{o*:%*}}");
8380 do_spec_1 (" ", 0, NULL);
8382 if (argbuf.length () > 0)
8383 debug_auxbase_opt = concat ("-auxbase-strip ",
8384 argbuf.last (),
8385 NULL);
8386 else
8387 debug_auxbase_opt = NULL;
8389 return concat ("\
8390 %<o %<MD %<MMD %<MF* %<MG %<MP %<MQ* %<MT* \
8391 %<fdump-final-insns=* -w -S -o %j \
8392 %{!fcompare-debug-second:-fcompare-debug-second} \
8393 ", compare_debug_opt, NULL);
8396 /* %:compare-debug-auxbase-opt spec function. Expands to the auxbase
8397 options that are to be passed in the second compilation of
8398 compare-debug. It expects, as an argument, the basename of the
8399 current input file name, with the .gk suffix appended to it. */
8401 static const char *
8402 compare_debug_auxbase_opt_spec_function (int arg,
8403 const char **argv)
8405 char *name;
8406 int len;
8408 if (arg == 0)
8409 fatal_error ("too few arguments to %%:compare-debug-auxbase-opt");
8411 if (arg != 1)
8412 fatal_error ("too many arguments to %%:compare-debug-auxbase-opt");
8414 if (compare_debug >= 0)
8415 return NULL;
8417 len = strlen (argv[0]);
8418 if (len < 3 || strcmp (argv[0] + len - 3, ".gk") != 0)
8419 fatal_error ("argument to %%:compare-debug-auxbase-opt "
8420 "does not end in .gk");
8422 if (debug_auxbase_opt)
8423 return debug_auxbase_opt;
8425 #define OPT "-auxbase "
8427 len -= 3;
8428 name = (char*) xmalloc (sizeof (OPT) + len);
8429 memcpy (name, OPT, sizeof (OPT) - 1);
8430 memcpy (name + sizeof (OPT) - 1, argv[0], len);
8431 name[sizeof (OPT) - 1 + len] = '\0';
8433 #undef OPT
8435 return name;
8438 /* %:pass-through-libs spec function. Finds all -l options and input
8439 file names in the lib spec passed to it, and makes a list of them
8440 prepended with the plugin option to cause them to be passed through
8441 to the final link after all the new object files have been added. */
8443 const char *
8444 pass_through_libs_spec_func (int argc, const char **argv)
8446 char *prepended = xstrdup (" ");
8447 int n;
8448 /* Shlemiel the painter's algorithm. Innately horrible, but at least
8449 we know that there will never be more than a handful of strings to
8450 concat, and it's only once per run, so it's not worth optimising. */
8451 for (n = 0; n < argc; n++)
8453 char *old = prepended;
8454 /* Anything that isn't an option is a full path to an output
8455 file; pass it through if it ends in '.a'. Among options,
8456 pass only -l. */
8457 if (argv[n][0] == '-' && argv[n][1] == 'l')
8459 const char *lopt = argv[n] + 2;
8460 /* Handle both joined and non-joined -l options. If for any
8461 reason there's a trailing -l with no joined or following
8462 arg just discard it. */
8463 if (!*lopt && ++n >= argc)
8464 break;
8465 else if (!*lopt)
8466 lopt = argv[n];
8467 prepended = concat (prepended, "-plugin-opt=-pass-through=-l",
8468 lopt, " ", NULL);
8470 else if (!strcmp (".a", argv[n] + strlen (argv[n]) - 2))
8472 prepended = concat (prepended, "-plugin-opt=-pass-through=",
8473 argv[n], " ", NULL);
8475 if (prepended != old)
8476 free (old);
8478 return prepended;
8481 /* %:replace-extension spec function. Replaces the extension of the
8482 first argument with the second argument. */
8484 const char *
8485 replace_extension_spec_func (int argc, const char **argv)
8487 char *name;
8488 char *p;
8489 char *result;
8490 int i;
8492 if (argc != 2)
8493 fatal_error ("too few arguments to %%:replace-extension");
8495 name = xstrdup (argv[0]);
8497 for (i = strlen(name) - 1; i >= 0; i--)
8498 if (IS_DIR_SEPARATOR (name[i]))
8499 break;
8501 p = strrchr (name + i + 1, '.');
8502 if (p != NULL)
8503 *p = '\0';
8505 result = concat (name, argv[1], NULL);
8507 free (name);
8508 return result;