invoke.texi: Document -print-multiarch.
[official-gcc.git] / gcc / gcc.c
blobe584319369e9597e5b30949be1815221ca2d5bde
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
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 /* config.h can define LIBGCC_SPEC to override how and when libgcc.a is
548 included. */
549 #ifndef LIBGCC_SPEC
550 #if defined(REAL_LIBGCC_SPEC)
551 #define LIBGCC_SPEC REAL_LIBGCC_SPEC
552 #elif defined(LINK_LIBGCC_SPECIAL_1)
553 /* Have gcc do the search for libgcc.a. */
554 #define LIBGCC_SPEC "libgcc.a%s"
555 #else
556 #define LIBGCC_SPEC "-lgcc"
557 #endif
558 #endif
560 /* config.h can define STARTFILE_SPEC to override the default crt0 files. */
561 #ifndef STARTFILE_SPEC
562 #define STARTFILE_SPEC \
563 "%{!shared:%{pg:gcrt0%O%s}%{!pg:%{p:mcrt0%O%s}%{!p:crt0%O%s}}}"
564 #endif
566 /* config.h can define ENDFILE_SPEC to override the default crtn files. */
567 #ifndef ENDFILE_SPEC
568 #define ENDFILE_SPEC ""
569 #endif
571 #ifndef LINKER_NAME
572 #define LINKER_NAME "collect2"
573 #endif
575 #ifdef HAVE_AS_DEBUG_PREFIX_MAP
576 #define ASM_MAP " %{fdebug-prefix-map=*:--debug-prefix-map %*}"
577 #else
578 #define ASM_MAP ""
579 #endif
581 /* Define ASM_DEBUG_SPEC to be a spec suitable for translating '-g'
582 to the assembler. */
583 #ifndef ASM_DEBUG_SPEC
584 # if defined(DBX_DEBUGGING_INFO) && defined(DWARF2_DEBUGGING_INFO) \
585 && defined(HAVE_AS_GDWARF2_DEBUG_FLAG) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
586 # define ASM_DEBUG_SPEC \
587 (PREFERRED_DEBUGGING_TYPE == DBX_DEBUG \
588 ? "%{!g0:%{gdwarf-2*:--gdwarf2}%{!gdwarf-2*:%{g*:--gstabs}}}" ASM_MAP \
589 : "%{!g0:%{gstabs*:--gstabs}%{!gstabs*:%{g*:--gdwarf2}}}" ASM_MAP)
590 # else
591 # if defined(DBX_DEBUGGING_INFO) && defined(HAVE_AS_GSTABS_DEBUG_FLAG)
592 # define ASM_DEBUG_SPEC "%{g*:%{!g0:--gstabs}}" ASM_MAP
593 # endif
594 # if defined(DWARF2_DEBUGGING_INFO) && defined(HAVE_AS_GDWARF2_DEBUG_FLAG)
595 # define ASM_DEBUG_SPEC "%{g*:%{!g0:--gdwarf2}}" ASM_MAP
596 # endif
597 # endif
598 #endif
599 #ifndef ASM_DEBUG_SPEC
600 # define ASM_DEBUG_SPEC ""
601 #endif
603 /* Here is the spec for running the linker, after compiling all files. */
605 /* This is overridable by the target in case they need to specify the
606 -lgcc and -lc order specially, yet not require them to override all
607 of LINK_COMMAND_SPEC. */
608 #ifndef LINK_GCC_C_SEQUENCE_SPEC
609 #define LINK_GCC_C_SEQUENCE_SPEC "%G %L %G"
610 #endif
612 #ifndef LINK_SSP_SPEC
613 #ifdef TARGET_LIBC_PROVIDES_SSP
614 #define LINK_SSP_SPEC "%{fstack-protector:}"
615 #else
616 #define LINK_SSP_SPEC "%{fstack-protector|fstack-protector-all:-lssp_nonshared -lssp}"
617 #endif
618 #endif
620 #ifndef LINK_PIE_SPEC
621 #ifdef HAVE_LD_PIE
622 #define LINK_PIE_SPEC "%{pie:-pie} "
623 #else
624 #define LINK_PIE_SPEC "%{pie:} "
625 #endif
626 #endif
628 #ifndef LINK_BUILDID_SPEC
629 # if defined(HAVE_LD_BUILDID) && defined(ENABLE_LD_BUILDID)
630 # define LINK_BUILDID_SPEC "%{!r:--build-id} "
631 # endif
632 #endif
634 /* Conditional to test whether the LTO plugin is used or not.
635 FIXME: For slim LTO we will need to enable plugin unconditionally. This
636 still cause problems with PLUGIN_LD != LD and when plugin is built but
637 not useable. For GCC 4.6 we don't support slim LTO and thus we can enable
638 plugin only when LTO is enabled. We still honor explicit
639 -fuse-linker-plugin if the linker used understands -plugin. */
641 /* The linker has some plugin support. */
642 #if HAVE_LTO_PLUGIN > 0
643 /* The linker used has full plugin support, use LTO plugin by default. */
644 #if HAVE_LTO_PLUGIN == 2
645 #define PLUGIN_COND "!fno-use-linker-plugin:%{flto|flto=*|fuse-linker-plugin"
646 #define PLUGIN_COND_CLOSE "}"
647 #else
648 /* The linker used has limited plugin support, use LTO plugin with explicit
649 -fuse-linker-plugin. */
650 #define PLUGIN_COND "fuse-linker-plugin"
651 #define PLUGIN_COND_CLOSE ""
652 #endif
653 #define LINK_PLUGIN_SPEC \
654 "%{"PLUGIN_COND": \
655 -plugin %(linker_plugin_file) \
656 -plugin-opt=%(lto_wrapper) \
657 -plugin-opt=-fresolution=%u.res \
658 %{!nostdlib:%{!nodefaultlibs:%:pass-through-libs(%(link_gcc_c_sequence))}} \
659 }"PLUGIN_COND_CLOSE
660 #else
661 /* The linker used doesn't support -plugin, reject -fuse-linker-plugin. */
662 #define LINK_PLUGIN_SPEC "%{fuse-linker-plugin:\
663 %e-fuse-linker-plugin is not supported in this configuration}"
664 #endif
667 /* -u* was put back because both BSD and SysV seem to support it. */
668 /* %{static:} simply prevents an error message if the target machine
669 doesn't handle -static. */
670 /* We want %{T*} after %{L*} and %D so that it can be used to specify linker
671 scripts which exist in user specified directories, or in standard
672 directories. */
673 /* We pass any -flto flags on to the linker, which is expected
674 to understand them. In practice, this means it had better be collect2. */
675 /* %{e*} includes -export-dynamic; see comment in common.opt. */
676 #ifndef LINK_COMMAND_SPEC
677 #define LINK_COMMAND_SPEC "\
678 %{!fsyntax-only:%{!c:%{!M:%{!MM:%{!E:%{!S:\
679 %(linker) " \
680 LINK_PLUGIN_SPEC \
681 "%{flto|flto=*:%<fcompare-debug*} \
682 %{flto} %{flto=*} %l " LINK_PIE_SPEC \
683 "%X %{o*} %{e*} %{N} %{n} %{r}\
684 %{s} %{t} %{u*} %{z} %{Z} %{!nostdlib:%{!nostartfiles:%S}}\
685 %{static:} %{L*} %(mfwrap) %(link_libgcc) %o\
686 %{fopenmp|ftree-parallelize-loops=*:%:include(libgomp.spec)%(link_gomp)}\
687 %{fgnu-tm:%:include(libitm.spec)%(link_itm)}\
688 %(mflib) " STACK_SPLIT_SPEC "\
689 %{fprofile-arcs|fprofile-generate*|coverage:-lgcov}\
690 %{faddress-sanitizer:-lasan}\
691 %{!nostdlib:%{!nodefaultlibs:%(link_ssp) %(link_gcc_c_sequence)}}\
692 %{!nostdlib:%{!nostartfiles:%E}} %{T*} }}}}}}"
693 #endif
695 #ifndef LINK_LIBGCC_SPEC
696 /* Generate -L options for startfile prefix list. */
697 # define LINK_LIBGCC_SPEC "%D"
698 #endif
700 #ifndef STARTFILE_PREFIX_SPEC
701 # define STARTFILE_PREFIX_SPEC ""
702 #endif
704 #ifndef SYSROOT_SPEC
705 # define SYSROOT_SPEC "--sysroot=%R"
706 #endif
708 #ifndef SYSROOT_SUFFIX_SPEC
709 # define SYSROOT_SUFFIX_SPEC ""
710 #endif
712 #ifndef SYSROOT_HEADERS_SUFFIX_SPEC
713 # define SYSROOT_HEADERS_SUFFIX_SPEC ""
714 #endif
716 static const char *asm_debug = ASM_DEBUG_SPEC;
717 static const char *cpp_spec = CPP_SPEC;
718 static const char *cc1_spec = CC1_SPEC;
719 static const char *cc1plus_spec = CC1PLUS_SPEC;
720 static const char *link_gcc_c_sequence_spec = LINK_GCC_C_SEQUENCE_SPEC;
721 static const char *link_ssp_spec = LINK_SSP_SPEC;
722 static const char *asm_spec = ASM_SPEC;
723 static const char *asm_final_spec = ASM_FINAL_SPEC;
724 static const char *link_spec = LINK_SPEC;
725 static const char *lib_spec = LIB_SPEC;
726 static const char *mfwrap_spec = MFWRAP_SPEC;
727 static const char *mflib_spec = MFLIB_SPEC;
728 static const char *link_gomp_spec = "";
729 static const char *libgcc_spec = LIBGCC_SPEC;
730 static const char *endfile_spec = ENDFILE_SPEC;
731 static const char *startfile_spec = STARTFILE_SPEC;
732 static const char *linker_name_spec = LINKER_NAME;
733 static const char *linker_plugin_file_spec = "";
734 static const char *lto_wrapper_spec = "";
735 static const char *lto_gcc_spec = "";
736 static const char *link_command_spec = LINK_COMMAND_SPEC;
737 static const char *link_libgcc_spec = LINK_LIBGCC_SPEC;
738 static const char *startfile_prefix_spec = STARTFILE_PREFIX_SPEC;
739 static const char *sysroot_spec = SYSROOT_SPEC;
740 static const char *sysroot_suffix_spec = SYSROOT_SUFFIX_SPEC;
741 static const char *sysroot_hdrs_suffix_spec = SYSROOT_HEADERS_SUFFIX_SPEC;
742 static const char *self_spec = "";
744 /* Standard options to cpp, cc1, and as, to reduce duplication in specs.
745 There should be no need to override these in target dependent files,
746 but we need to copy them to the specs file so that newer versions
747 of the GCC driver can correctly drive older tool chains with the
748 appropriate -B options. */
750 /* When cpplib handles traditional preprocessing, get rid of this, and
751 call cc1 (or cc1obj in objc/lang-specs.h) from the main specs so
752 that we default the front end language better. */
753 static const char *trad_capable_cpp =
754 "cc1 -E %{traditional|traditional-cpp:-traditional-cpp}";
756 /* We don't wrap .d files in %W{} since a missing .d file, and
757 therefore no dependency entry, confuses make into thinking a .o
758 file that happens to exist is up-to-date. */
759 static const char *cpp_unique_options =
760 "%{!Q:-quiet} %{nostdinc*} %{C} %{CC} %{v} %{I*&F*} %{P} %I\
761 %{MD:-MD %{!o:%b.d}%{o*:%.d%*}}\
762 %{MMD:-MMD %{!o:%b.d}%{o*:%.d%*}}\
763 %{M} %{MM} %{MF*} %{MG} %{MP} %{MQ*} %{MT*}\
764 %{!E:%{!M:%{!MM:%{!MT:%{!MQ:%{MD|MMD:%{o*:-MQ %*}}}}}}}\
765 %{remap} %{g3|ggdb3|gstabs3|gcoff3|gxcoff3|gvms3:-dD}\
766 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
767 %{H} %C %{D*&U*&A*} %{i*} %Z %i\
768 %{fmudflap:-D_MUDFLAP -include mf-runtime.h}\
769 %{fmudflapth:-D_MUDFLAP -D_MUDFLAPTH -include mf-runtime.h}\
770 %{E|M|MM:%W{o*}}";
772 /* This contains cpp options which are common with cc1_options and are passed
773 only when preprocessing only to avoid duplication. We pass the cc1 spec
774 options to the preprocessor so that it the cc1 spec may manipulate
775 options used to set target flags. Those special target flags settings may
776 in turn cause preprocessor symbols to be defined specially. */
777 static const char *cpp_options =
778 "%(cpp_unique_options) %1 %{m*} %{std*&ansi&trigraphs} %{W*&pedantic*} %{w}\
779 %{f*} %{g*:%{!g0:%{g*} %{!fno-working-directory:-fworking-directory}}} %{O*}\
780 %{undef} %{save-temps*:-fpch-preprocess}";
782 /* This contains cpp options which are not passed when the preprocessor
783 output will be used by another program. */
784 static const char *cpp_debug_options = "%{d*}";
786 /* NB: This is shared amongst all front-ends, except for Ada. */
787 static const char *cc1_options =
788 "%{pg:%{fomit-frame-pointer:%e-pg and -fomit-frame-pointer are incompatible}}\
789 %{!iplugindir*:%{fplugin*:%:find-plugindir()}}\
790 %1 %{!Q:-quiet} %{!dumpbase:-dumpbase %B} %{d*} %{m*} %{aux-info*}\
791 %{fcompare-debug-second:%:compare-debug-auxbase-opt(%b)} \
792 %{!fcompare-debug-second:%{c|S:%{o*:-auxbase-strip %*}%{!o*:-auxbase %b}}}%{!c:%{!S:-auxbase %b}} \
793 %{g*} %{O*} %{W*&pedantic*} %{w} %{std*&ansi&trigraphs}\
794 %{v:-version} %{pg:-p} %{p} %{f*} %{undef}\
795 %{Qn:-fno-ident} %{Qy:} %{-help:--help}\
796 %{-target-help:--target-help}\
797 %{-version:--version}\
798 %{-help=*:--help=%*}\
799 %{!fsyntax-only:%{S:%W{o*}%{!o*:-o %b.s}}}\
800 %{fsyntax-only:-o %j} %{-param*}\
801 %{fmudflap|fmudflapth:-fno-builtin -fno-merge-constants}\
802 %{coverage:-fprofile-arcs -ftest-coverage}";
804 static const char *asm_options =
805 "%{-target-help:%:print-asm-header()} "
806 #if HAVE_GNU_AS
807 /* If GNU AS is used, then convert -w (no warnings), -I, and -v
808 to the assembler equivalents. */
809 "%{v} %{w:-W} %{I*} "
810 #endif
811 "%a %Y %{c:%W{o*}%{!o*:-o %w%b%O}}%{!c:-o %d%w%u%O}";
813 static const char *invoke_as =
814 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
815 "%{!fwpa:\
816 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
817 %{!S:-o %|.s |\n as %(asm_options) %|.s %A }\
819 #else
820 "%{!fwpa:\
821 %{fcompare-debug=*|fdump-final-insns=*:%:compare-debug-dump-opt()}\
822 %{!S:-o %|.s |\n as %(asm_options) %m.s %A }\
824 #endif
826 /* Some compilers have limits on line lengths, and the multilib_select
827 and/or multilib_matches strings can be very long, so we build them at
828 run time. */
829 static struct obstack multilib_obstack;
830 static const char *multilib_select;
831 static const char *multilib_matches;
832 static const char *multilib_defaults;
833 static const char *multilib_exclusions;
835 /* Check whether a particular argument is a default argument. */
837 #ifndef MULTILIB_DEFAULTS
838 #define MULTILIB_DEFAULTS { "" }
839 #endif
841 static const char *const multilib_defaults_raw[] = MULTILIB_DEFAULTS;
843 #ifndef DRIVER_SELF_SPECS
844 #define DRIVER_SELF_SPECS ""
845 #endif
847 /* Adding -fopenmp should imply pthreads. This is particularly important
848 for targets that use different start files and suchlike. */
849 #ifndef GOMP_SELF_SPECS
850 #define GOMP_SELF_SPECS "%{fopenmp|ftree-parallelize-loops=*: -pthread}"
851 #endif
853 /* Likewise for -fgnu-tm. */
854 #ifndef GTM_SELF_SPECS
855 #define GTM_SELF_SPECS "%{fgnu-tm: -pthread}"
856 #endif
858 static const char *const driver_self_specs[] = {
859 "%{fdump-final-insns:-fdump-final-insns=.} %<fdump-final-insns",
860 DRIVER_SELF_SPECS, CONFIGURE_SPECS, GOMP_SELF_SPECS, GTM_SELF_SPECS
863 #ifndef OPTION_DEFAULT_SPECS
864 #define OPTION_DEFAULT_SPECS { "", "" }
865 #endif
867 struct default_spec
869 const char *name;
870 const char *spec;
873 static const struct default_spec
874 option_default_specs[] = { OPTION_DEFAULT_SPECS };
876 struct user_specs
878 struct user_specs *next;
879 const char *filename;
882 static struct user_specs *user_specs_head, *user_specs_tail;
885 /* Record the mapping from file suffixes for compilation specs. */
887 struct compiler
889 const char *suffix; /* Use this compiler for input files
890 whose names end in this suffix. */
892 const char *spec; /* To use this compiler, run this spec. */
894 const char *cpp_spec; /* If non-NULL, substitute this spec
895 for `%C', rather than the usual
896 cpp_spec. */
897 const int combinable; /* If nonzero, compiler can deal with
898 multiple source files at once (IMA). */
899 const int needs_preprocessing; /* If nonzero, source files need to
900 be run through a preprocessor. */
903 /* Pointer to a vector of `struct compiler' that gives the spec for
904 compiling a file, based on its suffix.
905 A file that does not end in any of these suffixes will be passed
906 unchanged to the loader and nothing else will be done to it.
908 An entry containing two 0s is used to terminate the vector.
910 If multiple entries match a file, the last matching one is used. */
912 static struct compiler *compilers;
914 /* Number of entries in `compilers', not counting the null terminator. */
916 static int n_compilers;
918 /* The default list of file name suffixes and their compilation specs. */
920 static const struct compiler default_compilers[] =
922 /* Add lists of suffixes of known languages here. If those languages
923 were not present when we built the driver, we will hit these copies
924 and be given a more meaningful error than "file not used since
925 linking is not done". */
926 {".m", "#Objective-C", 0, 0, 0}, {".mi", "#Objective-C", 0, 0, 0},
927 {".mm", "#Objective-C++", 0, 0, 0}, {".M", "#Objective-C++", 0, 0, 0},
928 {".mii", "#Objective-C++", 0, 0, 0},
929 {".cc", "#C++", 0, 0, 0}, {".cxx", "#C++", 0, 0, 0},
930 {".cpp", "#C++", 0, 0, 0}, {".cp", "#C++", 0, 0, 0},
931 {".c++", "#C++", 0, 0, 0}, {".C", "#C++", 0, 0, 0},
932 {".CPP", "#C++", 0, 0, 0}, {".ii", "#C++", 0, 0, 0},
933 {".ads", "#Ada", 0, 0, 0}, {".adb", "#Ada", 0, 0, 0},
934 {".f", "#Fortran", 0, 0, 0}, {".F", "#Fortran", 0, 0, 0},
935 {".for", "#Fortran", 0, 0, 0}, {".FOR", "#Fortran", 0, 0, 0},
936 {".ftn", "#Fortran", 0, 0, 0}, {".FTN", "#Fortran", 0, 0, 0},
937 {".fpp", "#Fortran", 0, 0, 0}, {".FPP", "#Fortran", 0, 0, 0},
938 {".f90", "#Fortran", 0, 0, 0}, {".F90", "#Fortran", 0, 0, 0},
939 {".f95", "#Fortran", 0, 0, 0}, {".F95", "#Fortran", 0, 0, 0},
940 {".f03", "#Fortran", 0, 0, 0}, {".F03", "#Fortran", 0, 0, 0},
941 {".f08", "#Fortran", 0, 0, 0}, {".F08", "#Fortran", 0, 0, 0},
942 {".r", "#Ratfor", 0, 0, 0},
943 {".p", "#Pascal", 0, 0, 0}, {".pas", "#Pascal", 0, 0, 0},
944 {".java", "#Java", 0, 0, 0}, {".class", "#Java", 0, 0, 0},
945 {".zip", "#Java", 0, 0, 0}, {".jar", "#Java", 0, 0, 0},
946 {".go", "#Go", 0, 1, 0},
947 /* Next come the entries for C. */
948 {".c", "@c", 0, 0, 1},
949 {"@c",
950 /* cc1 has an integrated ISO C preprocessor. We should invoke the
951 external preprocessor if -save-temps is given. */
952 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
953 %{!E:%{!M:%{!MM:\
954 %{traditional:\
955 %eGNU C no longer supports -traditional without -E}\
956 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
957 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
958 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
959 %(cc1_options)}\
960 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
961 cc1 %(cpp_unique_options) %(cc1_options)}}}\
962 %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 1},
963 {"-",
964 "%{!E:%e-E or -x required when input is from standard input}\
965 %(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)", 0, 0, 0},
966 {".h", "@c-header", 0, 0, 0},
967 {"@c-header",
968 /* cc1 has an integrated ISO C preprocessor. We should invoke the
969 external preprocessor if -save-temps is given. */
970 "%{E|M|MM:%(trad_capable_cpp) %(cpp_options) %(cpp_debug_options)}\
971 %{!E:%{!M:%{!MM:\
972 %{save-temps*|traditional-cpp|no-integrated-cpp:%(trad_capable_cpp) \
973 %(cpp_options) -o %{save-temps*:%b.i} %{!save-temps*:%g.i} \n\
974 cc1 -fpreprocessed %{save-temps*:%b.i} %{!save-temps*:%g.i} \
975 %(cc1_options)\
976 %{!fdump-ada-spec*:-o %g.s %{!o*:--output-pch=%i.gch}\
977 %W{o*:--output-pch=%*}}%V}\
978 %{!save-temps*:%{!traditional-cpp:%{!no-integrated-cpp:\
979 cc1 %(cpp_unique_options) %(cc1_options)\
980 %{!fdump-ada-spec*:-o %g.s %{!o*:--output-pch=%i.gch}\
981 %W{o*:--output-pch=%*}}%V}}}}}}", 0, 0, 0},
982 {".i", "@cpp-output", 0, 0, 0},
983 {"@cpp-output",
984 "%{!M:%{!MM:%{!E:cc1 -fpreprocessed %i %(cc1_options) %{!fsyntax-only:%(invoke_as)}}}}", 0, 0, 0},
985 {".s", "@assembler", 0, 0, 0},
986 {"@assembler",
987 "%{!M:%{!MM:%{!E:%{!S:as %(asm_debug) %(asm_options) %i %A }}}}", 0, 0, 0},
988 {".sx", "@assembler-with-cpp", 0, 0, 0},
989 {".S", "@assembler-with-cpp", 0, 0, 0},
990 {"@assembler-with-cpp",
991 #ifdef AS_NEEDS_DASH_FOR_PIPED_INPUT
992 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
993 %{E|M|MM:%(cpp_debug_options)}\
994 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
995 as %(asm_debug) %(asm_options) %|.s %A }}}}"
996 #else
997 "%(trad_capable_cpp) -lang-asm %(cpp_options) -fno-directives-only\
998 %{E|M|MM:%(cpp_debug_options)}\
999 %{!M:%{!MM:%{!E:%{!S:-o %|.s |\n\
1000 as %(asm_debug) %(asm_options) %m.s %A }}}}"
1001 #endif
1002 , 0, 0, 0},
1004 #include "specs.h"
1005 /* Mark end of table. */
1006 {0, 0, 0, 0, 0}
1009 /* Number of elements in default_compilers, not counting the terminator. */
1011 static const int n_default_compilers = ARRAY_SIZE (default_compilers) - 1;
1013 typedef char *char_p; /* For DEF_VEC_P. */
1014 DEF_VEC_P(char_p);
1015 DEF_VEC_ALLOC_P(char_p,heap);
1017 /* A vector of options to give to the linker.
1018 These options are accumulated by %x,
1019 and substituted into the linker command with %X. */
1020 static VEC(char_p,heap) *linker_options;
1022 /* A vector of options to give to the assembler.
1023 These options are accumulated by -Wa,
1024 and substituted into the assembler command with %Y. */
1025 static VEC(char_p,heap) *assembler_options;
1027 /* A vector of options to give to the preprocessor.
1028 These options are accumulated by -Wp,
1029 and substituted into the preprocessor command with %Z. */
1030 static VEC(char_p,heap) *preprocessor_options;
1032 static char *
1033 skip_whitespace (char *p)
1035 while (1)
1037 /* A fully-blank line is a delimiter in the SPEC file and shouldn't
1038 be considered whitespace. */
1039 if (p[0] == '\n' && p[1] == '\n' && p[2] == '\n')
1040 return p + 1;
1041 else if (*p == '\n' || *p == ' ' || *p == '\t')
1042 p++;
1043 else if (*p == '#')
1045 while (*p != '\n')
1046 p++;
1047 p++;
1049 else
1050 break;
1053 return p;
1055 /* Structures to keep track of prefixes to try when looking for files. */
1057 struct prefix_list
1059 const char *prefix; /* String to prepend to the path. */
1060 struct prefix_list *next; /* Next in linked list. */
1061 int require_machine_suffix; /* Don't use without machine_suffix. */
1062 /* 2 means try both machine_suffix and just_machine_suffix. */
1063 int priority; /* Sort key - priority within list. */
1064 int os_multilib; /* 1 if OS multilib scheme should be used,
1065 0 for GCC multilib scheme. */
1068 struct path_prefix
1070 struct prefix_list *plist; /* List of prefixes to try */
1071 int max_len; /* Max length of a prefix in PLIST */
1072 const char *name; /* Name of this list (used in config stuff) */
1075 /* List of prefixes to try when looking for executables. */
1077 static struct path_prefix exec_prefixes = { 0, 0, "exec" };
1079 /* List of prefixes to try when looking for startup (crt0) files. */
1081 static struct path_prefix startfile_prefixes = { 0, 0, "startfile" };
1083 /* List of prefixes to try when looking for include files. */
1085 static struct path_prefix include_prefixes = { 0, 0, "include" };
1087 /* Suffix to attach to directories searched for commands.
1088 This looks like `MACHINE/VERSION/'. */
1090 static const char *machine_suffix = 0;
1092 /* Suffix to attach to directories searched for commands.
1093 This is just `MACHINE/'. */
1095 static const char *just_machine_suffix = 0;
1097 /* Adjusted value of GCC_EXEC_PREFIX envvar. */
1099 static const char *gcc_exec_prefix;
1101 /* Adjusted value of standard_libexec_prefix. */
1103 static const char *gcc_libexec_prefix;
1105 /* Default prefixes to attach to command names. */
1107 #ifndef STANDARD_STARTFILE_PREFIX_1
1108 #define STANDARD_STARTFILE_PREFIX_1 "/lib/"
1109 #endif
1110 #ifndef STANDARD_STARTFILE_PREFIX_2
1111 #define STANDARD_STARTFILE_PREFIX_2 "/usr/lib/"
1112 #endif
1114 #ifdef CROSS_DIRECTORY_STRUCTURE /* Don't use these prefixes for a cross compiler. */
1115 #undef MD_EXEC_PREFIX
1116 #undef MD_STARTFILE_PREFIX
1117 #undef MD_STARTFILE_PREFIX_1
1118 #endif
1120 /* If no prefixes defined, use the null string, which will disable them. */
1121 #ifndef MD_EXEC_PREFIX
1122 #define MD_EXEC_PREFIX ""
1123 #endif
1124 #ifndef MD_STARTFILE_PREFIX
1125 #define MD_STARTFILE_PREFIX ""
1126 #endif
1127 #ifndef MD_STARTFILE_PREFIX_1
1128 #define MD_STARTFILE_PREFIX_1 ""
1129 #endif
1131 /* These directories are locations set at configure-time based on the
1132 --prefix option provided to configure. Their initializers are
1133 defined in Makefile.in. These paths are not *directly* used when
1134 gcc_exec_prefix is set because, in that case, we know where the
1135 compiler has been installed, and use paths relative to that
1136 location instead. */
1137 static const char *const standard_exec_prefix = STANDARD_EXEC_PREFIX;
1138 static const char *const standard_libexec_prefix = STANDARD_LIBEXEC_PREFIX;
1139 static const char *const standard_bindir_prefix = STANDARD_BINDIR_PREFIX;
1140 static const char *const standard_startfile_prefix = STANDARD_STARTFILE_PREFIX;
1142 /* For native compilers, these are well-known paths containing
1143 components that may be provided by the system. For cross
1144 compilers, these paths are not used. */
1145 static const char *md_exec_prefix = MD_EXEC_PREFIX;
1146 static const char *md_startfile_prefix = MD_STARTFILE_PREFIX;
1147 static const char *md_startfile_prefix_1 = MD_STARTFILE_PREFIX_1;
1148 static const char *const standard_startfile_prefix_1
1149 = STANDARD_STARTFILE_PREFIX_1;
1150 static const char *const standard_startfile_prefix_2
1151 = STANDARD_STARTFILE_PREFIX_2;
1153 /* A relative path to be used in finding the location of tools
1154 relative to the driver. */
1155 static const char *const tooldir_base_prefix = TOOLDIR_BASE_PREFIX;
1157 /* Subdirectory to use for locating libraries. Set by
1158 set_multilib_dir based on the compilation options. */
1160 static const char *multilib_dir;
1162 /* Subdirectory to use for locating libraries in OS conventions. Set by
1163 set_multilib_dir based on the compilation options. */
1165 static const char *multilib_os_dir;
1167 /* Subdirectory to use for locating libraries in multiarch conventions. Set by
1168 set_multilib_dir based on the compilation options. */
1170 static const char *multiarch_dir;
1172 /* Structure to keep track of the specs that have been defined so far.
1173 These are accessed using %(specname) in a compiler or link
1174 spec. */
1176 struct spec_list
1178 /* The following 2 fields must be first */
1179 /* to allow EXTRA_SPECS to be initialized */
1180 const char *name; /* name of the spec. */
1181 const char *ptr; /* available ptr if no static pointer */
1183 /* The following fields are not initialized */
1184 /* by EXTRA_SPECS */
1185 const char **ptr_spec; /* pointer to the spec itself. */
1186 struct spec_list *next; /* Next spec in linked list. */
1187 int name_len; /* length of the name */
1188 bool user_p; /* whether string come from file spec. */
1189 bool alloc_p; /* whether string was allocated */
1192 #define INIT_STATIC_SPEC(NAME,PTR) \
1193 { NAME, NULL, PTR, (struct spec_list *) 0, sizeof (NAME) - 1, false, false }
1195 /* List of statically defined specs. */
1196 static struct spec_list static_specs[] =
1198 INIT_STATIC_SPEC ("asm", &asm_spec),
1199 INIT_STATIC_SPEC ("asm_debug", &asm_debug),
1200 INIT_STATIC_SPEC ("asm_final", &asm_final_spec),
1201 INIT_STATIC_SPEC ("asm_options", &asm_options),
1202 INIT_STATIC_SPEC ("invoke_as", &invoke_as),
1203 INIT_STATIC_SPEC ("cpp", &cpp_spec),
1204 INIT_STATIC_SPEC ("cpp_options", &cpp_options),
1205 INIT_STATIC_SPEC ("cpp_debug_options", &cpp_debug_options),
1206 INIT_STATIC_SPEC ("cpp_unique_options", &cpp_unique_options),
1207 INIT_STATIC_SPEC ("trad_capable_cpp", &trad_capable_cpp),
1208 INIT_STATIC_SPEC ("cc1", &cc1_spec),
1209 INIT_STATIC_SPEC ("cc1_options", &cc1_options),
1210 INIT_STATIC_SPEC ("cc1plus", &cc1plus_spec),
1211 INIT_STATIC_SPEC ("link_gcc_c_sequence", &link_gcc_c_sequence_spec),
1212 INIT_STATIC_SPEC ("link_ssp", &link_ssp_spec),
1213 INIT_STATIC_SPEC ("endfile", &endfile_spec),
1214 INIT_STATIC_SPEC ("link", &link_spec),
1215 INIT_STATIC_SPEC ("lib", &lib_spec),
1216 INIT_STATIC_SPEC ("mfwrap", &mfwrap_spec),
1217 INIT_STATIC_SPEC ("mflib", &mflib_spec),
1218 INIT_STATIC_SPEC ("link_gomp", &link_gomp_spec),
1219 INIT_STATIC_SPEC ("libgcc", &libgcc_spec),
1220 INIT_STATIC_SPEC ("startfile", &startfile_spec),
1221 INIT_STATIC_SPEC ("cross_compile", &cross_compile),
1222 INIT_STATIC_SPEC ("version", &compiler_version),
1223 INIT_STATIC_SPEC ("multilib", &multilib_select),
1224 INIT_STATIC_SPEC ("multilib_defaults", &multilib_defaults),
1225 INIT_STATIC_SPEC ("multilib_extra", &multilib_extra),
1226 INIT_STATIC_SPEC ("multilib_matches", &multilib_matches),
1227 INIT_STATIC_SPEC ("multilib_exclusions", &multilib_exclusions),
1228 INIT_STATIC_SPEC ("multilib_options", &multilib_options),
1229 INIT_STATIC_SPEC ("linker", &linker_name_spec),
1230 INIT_STATIC_SPEC ("linker_plugin_file", &linker_plugin_file_spec),
1231 INIT_STATIC_SPEC ("lto_wrapper", &lto_wrapper_spec),
1232 INIT_STATIC_SPEC ("lto_gcc", &lto_gcc_spec),
1233 INIT_STATIC_SPEC ("link_libgcc", &link_libgcc_spec),
1234 INIT_STATIC_SPEC ("md_exec_prefix", &md_exec_prefix),
1235 INIT_STATIC_SPEC ("md_startfile_prefix", &md_startfile_prefix),
1236 INIT_STATIC_SPEC ("md_startfile_prefix_1", &md_startfile_prefix_1),
1237 INIT_STATIC_SPEC ("startfile_prefix_spec", &startfile_prefix_spec),
1238 INIT_STATIC_SPEC ("sysroot_spec", &sysroot_spec),
1239 INIT_STATIC_SPEC ("sysroot_suffix_spec", &sysroot_suffix_spec),
1240 INIT_STATIC_SPEC ("sysroot_hdrs_suffix_spec", &sysroot_hdrs_suffix_spec),
1241 INIT_STATIC_SPEC ("self_spec", &self_spec),
1244 #ifdef EXTRA_SPECS /* additional specs needed */
1245 /* Structure to keep track of just the first two args of a spec_list.
1246 That is all that the EXTRA_SPECS macro gives us. */
1247 struct spec_list_1
1249 const char *const name;
1250 const char *const ptr;
1253 static const struct spec_list_1 extra_specs_1[] = { EXTRA_SPECS };
1254 static struct spec_list *extra_specs = (struct spec_list *) 0;
1255 #endif
1257 /* List of dynamically allocates specs that have been defined so far. */
1259 static struct spec_list *specs = (struct spec_list *) 0;
1261 /* List of static spec functions. */
1263 static const struct spec_function static_spec_functions[] =
1265 { "getenv", getenv_spec_function },
1266 { "if-exists", if_exists_spec_function },
1267 { "if-exists-else", if_exists_else_spec_function },
1268 { "replace-outfile", replace_outfile_spec_function },
1269 { "remove-outfile", remove_outfile_spec_function },
1270 { "version-compare", version_compare_spec_function },
1271 { "include", include_spec_function },
1272 { "find-file", find_file_spec_function },
1273 { "find-plugindir", find_plugindir_spec_function },
1274 { "print-asm-header", print_asm_header_spec_function },
1275 { "compare-debug-dump-opt", compare_debug_dump_opt_spec_function },
1276 { "compare-debug-self-opt", compare_debug_self_opt_spec_function },
1277 { "compare-debug-auxbase-opt", compare_debug_auxbase_opt_spec_function },
1278 { "pass-through-libs", pass_through_libs_spec_func },
1279 { "replace-extension", replace_extension_spec_func },
1280 #ifdef EXTRA_SPEC_FUNCTIONS
1281 EXTRA_SPEC_FUNCTIONS
1282 #endif
1283 { 0, 0 }
1286 static int processing_spec_function;
1288 /* Add appropriate libgcc specs to OBSTACK, taking into account
1289 various permutations of -shared-libgcc, -shared, and such. */
1291 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1293 #ifndef USE_LD_AS_NEEDED
1294 #define USE_LD_AS_NEEDED 0
1295 #endif
1297 static void
1298 init_gcc_specs (struct obstack *obstack, const char *shared_name,
1299 const char *static_name, const char *eh_name)
1301 char *buf;
1303 buf = concat ("%{static|static-libgcc:", static_name, " ", eh_name, "}"
1304 "%{!static:%{!static-libgcc:"
1305 #if USE_LD_AS_NEEDED
1306 "%{!shared-libgcc:",
1307 static_name, " --as-needed ", shared_name, " --no-as-needed"
1309 "%{shared-libgcc:",
1310 shared_name, "%{!shared: ", static_name, "}"
1312 #else
1313 "%{!shared:"
1314 "%{!shared-libgcc:", static_name, " ", eh_name, "}"
1315 "%{shared-libgcc:", shared_name, " ", static_name, "}"
1317 #ifdef LINK_EH_SPEC
1318 "%{shared:"
1319 "%{shared-libgcc:", shared_name, "}"
1320 "%{!shared-libgcc:", static_name, "}"
1322 #else
1323 "%{shared:", shared_name, "}"
1324 #endif
1325 #endif
1326 "}}", NULL);
1328 obstack_grow (obstack, buf, strlen (buf));
1329 free (buf);
1331 #endif /* ENABLE_SHARED_LIBGCC */
1333 /* Initialize the specs lookup routines. */
1335 static void
1336 init_spec (void)
1338 struct spec_list *next = (struct spec_list *) 0;
1339 struct spec_list *sl = (struct spec_list *) 0;
1340 int i;
1342 if (specs)
1343 return; /* Already initialized. */
1345 if (verbose_flag)
1346 fnotice (stderr, "Using built-in specs.\n");
1348 #ifdef EXTRA_SPECS
1349 extra_specs = XCNEWVEC (struct spec_list, ARRAY_SIZE (extra_specs_1));
1351 for (i = ARRAY_SIZE (extra_specs_1) - 1; i >= 0; i--)
1353 sl = &extra_specs[i];
1354 sl->name = extra_specs_1[i].name;
1355 sl->ptr = extra_specs_1[i].ptr;
1356 sl->next = next;
1357 sl->name_len = strlen (sl->name);
1358 sl->ptr_spec = &sl->ptr;
1359 next = sl;
1361 #endif
1363 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1365 sl = &static_specs[i];
1366 sl->next = next;
1367 next = sl;
1370 #if defined(ENABLE_SHARED_LIBGCC) && !defined(REAL_LIBGCC_SPEC)
1371 /* ??? If neither -shared-libgcc nor --static-libgcc was
1372 seen, then we should be making an educated guess. Some proposed
1373 heuristics for ELF include:
1375 (1) If "-Wl,--export-dynamic", then it's a fair bet that the
1376 program will be doing dynamic loading, which will likely
1377 need the shared libgcc.
1379 (2) If "-ldl", then it's also a fair bet that we're doing
1380 dynamic loading.
1382 (3) For each ET_DYN we're linking against (either through -lfoo
1383 or /some/path/foo.so), check to see whether it or one of
1384 its dependencies depends on a shared libgcc.
1386 (4) If "-shared"
1388 If the runtime is fixed to look for program headers instead
1389 of calling __register_frame_info at all, for each object,
1390 use the shared libgcc if any EH symbol referenced.
1392 If crtstuff is fixed to not invoke __register_frame_info
1393 automatically, for each object, use the shared libgcc if
1394 any non-empty unwind section found.
1396 Doing any of this probably requires invoking an external program to
1397 do the actual object file scanning. */
1399 const char *p = libgcc_spec;
1400 int in_sep = 1;
1402 /* Transform the extant libgcc_spec into one that uses the shared libgcc
1403 when given the proper command line arguments. */
1404 while (*p)
1406 if (in_sep && *p == '-' && strncmp (p, "-lgcc", 5) == 0)
1408 init_gcc_specs (&obstack,
1409 "-lgcc_s"
1410 #ifdef USE_LIBUNWIND_EXCEPTIONS
1411 " -lunwind"
1412 #endif
1414 "-lgcc",
1415 "-lgcc_eh"
1416 #ifdef USE_LIBUNWIND_EXCEPTIONS
1417 # ifdef HAVE_LD_STATIC_DYNAMIC
1418 " %{!static:" LD_STATIC_OPTION "} -lunwind"
1419 " %{!static:" LD_DYNAMIC_OPTION "}"
1420 # else
1421 " -lunwind"
1422 # endif
1423 #endif
1426 p += 5;
1427 in_sep = 0;
1429 else if (in_sep && *p == 'l' && strncmp (p, "libgcc.a%s", 10) == 0)
1431 /* Ug. We don't know shared library extensions. Hope that
1432 systems that use this form don't do shared libraries. */
1433 init_gcc_specs (&obstack,
1434 "-lgcc_s",
1435 "libgcc.a%s",
1436 "libgcc_eh.a%s"
1437 #ifdef USE_LIBUNWIND_EXCEPTIONS
1438 " -lunwind"
1439 #endif
1441 p += 10;
1442 in_sep = 0;
1444 else
1446 obstack_1grow (&obstack, *p);
1447 in_sep = (*p == ' ');
1448 p += 1;
1452 obstack_1grow (&obstack, '\0');
1453 libgcc_spec = XOBFINISH (&obstack, const char *);
1455 #endif
1456 #ifdef USE_AS_TRADITIONAL_FORMAT
1457 /* Prepend "--traditional-format" to whatever asm_spec we had before. */
1459 static const char tf[] = "--traditional-format ";
1460 obstack_grow (&obstack, tf, sizeof(tf) - 1);
1461 obstack_grow0 (&obstack, asm_spec, strlen (asm_spec));
1462 asm_spec = XOBFINISH (&obstack, const char *);
1464 #endif
1466 #if defined LINK_EH_SPEC || defined LINK_BUILDID_SPEC || \
1467 defined LINKER_HASH_STYLE
1468 # ifdef LINK_BUILDID_SPEC
1469 /* Prepend LINK_BUILDID_SPEC to whatever link_spec we had before. */
1470 obstack_grow (&obstack, LINK_BUILDID_SPEC, sizeof(LINK_BUILDID_SPEC) - 1);
1471 # endif
1472 # ifdef LINK_EH_SPEC
1473 /* Prepend LINK_EH_SPEC to whatever link_spec we had before. */
1474 obstack_grow (&obstack, LINK_EH_SPEC, sizeof(LINK_EH_SPEC) - 1);
1475 # endif
1476 # ifdef LINKER_HASH_STYLE
1477 /* Prepend --hash-style=LINKER_HASH_STYLE to whatever link_spec we had
1478 before. */
1480 static const char hash_style[] = "--hash-style=";
1481 obstack_grow (&obstack, hash_style, sizeof(hash_style) - 1);
1482 obstack_grow (&obstack, LINKER_HASH_STYLE, sizeof(LINKER_HASH_STYLE) - 1);
1483 obstack_1grow (&obstack, ' ');
1485 # endif
1486 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
1487 link_spec = XOBFINISH (&obstack, const char *);
1488 #endif
1490 specs = sl;
1493 /* Change the value of spec NAME to SPEC. If SPEC is empty, then the spec is
1494 removed; If the spec starts with a + then SPEC is added to the end of the
1495 current spec. */
1497 static void
1498 set_spec (const char *name, const char *spec, bool user_p)
1500 struct spec_list *sl;
1501 const char *old_spec;
1502 int name_len = strlen (name);
1503 int i;
1505 /* If this is the first call, initialize the statically allocated specs. */
1506 if (!specs)
1508 struct spec_list *next = (struct spec_list *) 0;
1509 for (i = ARRAY_SIZE (static_specs) - 1; i >= 0; i--)
1511 sl = &static_specs[i];
1512 sl->next = next;
1513 next = sl;
1515 specs = sl;
1518 /* See if the spec already exists. */
1519 for (sl = specs; sl; sl = sl->next)
1520 if (name_len == sl->name_len && !strcmp (sl->name, name))
1521 break;
1523 if (!sl)
1525 /* Not found - make it. */
1526 sl = XNEW (struct spec_list);
1527 sl->name = xstrdup (name);
1528 sl->name_len = name_len;
1529 sl->ptr_spec = &sl->ptr;
1530 sl->alloc_p = 0;
1531 *(sl->ptr_spec) = "";
1532 sl->next = specs;
1533 specs = sl;
1536 old_spec = *(sl->ptr_spec);
1537 *(sl->ptr_spec) = ((spec[0] == '+' && ISSPACE ((unsigned char)spec[1]))
1538 ? concat (old_spec, spec + 1, NULL)
1539 : xstrdup (spec));
1541 #ifdef DEBUG_SPECS
1542 if (verbose_flag)
1543 fnotice (stderr, "Setting spec %s to '%s'\n\n", name, *(sl->ptr_spec));
1544 #endif
1546 /* Free the old spec. */
1547 if (old_spec && sl->alloc_p)
1548 free (CONST_CAST(char *, old_spec));
1550 sl->user_p = user_p;
1551 sl->alloc_p = true;
1554 /* Accumulate a command (program name and args), and run it. */
1556 typedef const char *const_char_p; /* For DEF_VEC_P. */
1557 DEF_VEC_P(const_char_p);
1558 DEF_VEC_ALLOC_P(const_char_p,heap);
1560 /* Vector of pointers to arguments in the current line of specifications. */
1562 static VEC(const_char_p,heap) *argbuf;
1564 /* Position in the argbuf vector containing the name of the output file
1565 (the value associated with the "-o" flag). */
1567 static int have_o_argbuf_index = 0;
1569 /* Were the options -c, -S or -E passed. */
1570 static int have_c = 0;
1572 /* Was the option -o passed. */
1573 static int have_o = 0;
1575 /* This is the list of suffixes and codes (%g/%u/%U/%j) and the associated
1576 temp file. If the HOST_BIT_BUCKET is used for %j, no entry is made for
1577 it here. */
1579 static struct temp_name {
1580 const char *suffix; /* suffix associated with the code. */
1581 int length; /* strlen (suffix). */
1582 int unique; /* Indicates whether %g or %u/%U was used. */
1583 const char *filename; /* associated filename. */
1584 int filename_length; /* strlen (filename). */
1585 struct temp_name *next;
1586 } *temp_names;
1588 /* Number of commands executed so far. */
1590 static int execution_count;
1592 /* Number of commands that exited with a signal. */
1594 static int signal_count;
1596 /* Allocate the argument vector. */
1598 static void
1599 alloc_args (void)
1601 argbuf = VEC_alloc (const_char_p, heap, 10);
1604 /* Clear out the vector of arguments (after a command is executed). */
1606 static void
1607 clear_args (void)
1609 VEC_truncate (const_char_p, argbuf, 0);
1612 /* Add one argument to the vector at the end.
1613 This is done when a space is seen or at the end of the line.
1614 If DELETE_ALWAYS is nonzero, the arg is a filename
1615 and the file should be deleted eventually.
1616 If DELETE_FAILURE is nonzero, the arg is a filename
1617 and the file should be deleted if this compilation fails. */
1619 static void
1620 store_arg (const char *arg, int delete_always, int delete_failure)
1622 VEC_safe_push (const_char_p, heap, argbuf, arg);
1624 if (strcmp (arg, "-o") == 0)
1625 have_o_argbuf_index = VEC_length (const_char_p, argbuf);
1626 if (delete_always || delete_failure)
1628 const char *p;
1629 /* If the temporary file we should delete is specified as
1630 part of a joined argument extract the filename. */
1631 if (arg[0] == '-'
1632 && (p = strrchr (arg, '=')))
1633 arg = p + 1;
1634 record_temp_file (arg, delete_always, delete_failure);
1638 /* Load specs from a file name named FILENAME, replacing occurrences of
1639 various different types of line-endings, \r\n, \n\r and just \r, with
1640 a single \n. */
1642 static char *
1643 load_specs (const char *filename)
1645 int desc;
1646 int readlen;
1647 struct stat statbuf;
1648 char *buffer;
1649 char *buffer_p;
1650 char *specs;
1651 char *specs_p;
1653 if (verbose_flag)
1654 fnotice (stderr, "Reading specs from %s\n", filename);
1656 /* Open and stat the file. */
1657 desc = open (filename, O_RDONLY, 0);
1658 if (desc < 0)
1659 pfatal_with_name (filename);
1660 if (stat (filename, &statbuf) < 0)
1661 pfatal_with_name (filename);
1663 /* Read contents of file into BUFFER. */
1664 buffer = XNEWVEC (char, statbuf.st_size + 1);
1665 readlen = read (desc, buffer, (unsigned) statbuf.st_size);
1666 if (readlen < 0)
1667 pfatal_with_name (filename);
1668 buffer[readlen] = 0;
1669 close (desc);
1671 specs = XNEWVEC (char, readlen + 1);
1672 specs_p = specs;
1673 for (buffer_p = buffer; buffer_p && *buffer_p; buffer_p++)
1675 int skip = 0;
1676 char c = *buffer_p;
1677 if (c == '\r')
1679 if (buffer_p > buffer && *(buffer_p - 1) == '\n') /* \n\r */
1680 skip = 1;
1681 else if (*(buffer_p + 1) == '\n') /* \r\n */
1682 skip = 1;
1683 else /* \r */
1684 c = '\n';
1686 if (! skip)
1687 *specs_p++ = c;
1689 *specs_p = '\0';
1691 free (buffer);
1692 return (specs);
1695 /* Read compilation specs from a file named FILENAME,
1696 replacing the default ones.
1698 A suffix which starts with `*' is a definition for
1699 one of the machine-specific sub-specs. The "suffix" should be
1700 *asm, *cc1, *cpp, *link, *startfile, etc.
1701 The corresponding spec is stored in asm_spec, etc.,
1702 rather than in the `compilers' vector.
1704 Anything invalid in the file is a fatal error. */
1706 static void
1707 read_specs (const char *filename, bool main_p, bool user_p)
1709 char *buffer;
1710 char *p;
1712 buffer = load_specs (filename);
1714 /* Scan BUFFER for specs, putting them in the vector. */
1715 p = buffer;
1716 while (1)
1718 char *suffix;
1719 char *spec;
1720 char *in, *out, *p1, *p2, *p3;
1722 /* Advance P in BUFFER to the next nonblank nocomment line. */
1723 p = skip_whitespace (p);
1724 if (*p == 0)
1725 break;
1727 /* Is this a special command that starts with '%'? */
1728 /* Don't allow this for the main specs file, since it would
1729 encourage people to overwrite it. */
1730 if (*p == '%' && !main_p)
1732 p1 = p;
1733 while (*p && *p != '\n')
1734 p++;
1736 /* Skip '\n'. */
1737 p++;
1739 if (!strncmp (p1, "%include", sizeof ("%include") - 1)
1740 && (p1[sizeof "%include" - 1] == ' '
1741 || p1[sizeof "%include" - 1] == '\t'))
1743 char *new_filename;
1745 p1 += sizeof ("%include");
1746 while (*p1 == ' ' || *p1 == '\t')
1747 p1++;
1749 if (*p1++ != '<' || p[-2] != '>')
1750 fatal_error ("specs %%include syntax malformed after "
1751 "%ld characters",
1752 (long) (p1 - buffer + 1));
1754 p[-2] = '\0';
1755 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
1756 read_specs (new_filename ? new_filename : p1, false, user_p);
1757 continue;
1759 else if (!strncmp (p1, "%include_noerr", sizeof "%include_noerr" - 1)
1760 && (p1[sizeof "%include_noerr" - 1] == ' '
1761 || p1[sizeof "%include_noerr" - 1] == '\t'))
1763 char *new_filename;
1765 p1 += sizeof "%include_noerr";
1766 while (*p1 == ' ' || *p1 == '\t')
1767 p1++;
1769 if (*p1++ != '<' || p[-2] != '>')
1770 fatal_error ("specs %%include syntax malformed after "
1771 "%ld characters",
1772 (long) (p1 - buffer + 1));
1774 p[-2] = '\0';
1775 new_filename = find_a_file (&startfile_prefixes, p1, R_OK, true);
1776 if (new_filename)
1777 read_specs (new_filename, false, user_p);
1778 else if (verbose_flag)
1779 fnotice (stderr, "could not find specs file %s\n", p1);
1780 continue;
1782 else if (!strncmp (p1, "%rename", sizeof "%rename" - 1)
1783 && (p1[sizeof "%rename" - 1] == ' '
1784 || p1[sizeof "%rename" - 1] == '\t'))
1786 int name_len;
1787 struct spec_list *sl;
1788 struct spec_list *newsl;
1790 /* Get original name. */
1791 p1 += sizeof "%rename";
1792 while (*p1 == ' ' || *p1 == '\t')
1793 p1++;
1795 if (! ISALPHA ((unsigned char) *p1))
1796 fatal_error ("specs %%rename syntax malformed after "
1797 "%ld characters",
1798 (long) (p1 - buffer));
1800 p2 = p1;
1801 while (*p2 && !ISSPACE ((unsigned char) *p2))
1802 p2++;
1804 if (*p2 != ' ' && *p2 != '\t')
1805 fatal_error ("specs %%rename syntax malformed after "
1806 "%ld characters",
1807 (long) (p2 - buffer));
1809 name_len = p2 - p1;
1810 *p2++ = '\0';
1811 while (*p2 == ' ' || *p2 == '\t')
1812 p2++;
1814 if (! ISALPHA ((unsigned char) *p2))
1815 fatal_error ("specs %%rename syntax malformed after "
1816 "%ld characters",
1817 (long) (p2 - buffer));
1819 /* Get new spec name. */
1820 p3 = p2;
1821 while (*p3 && !ISSPACE ((unsigned char) *p3))
1822 p3++;
1824 if (p3 != p - 1)
1825 fatal_error ("specs %%rename syntax malformed after "
1826 "%ld characters",
1827 (long) (p3 - buffer));
1828 *p3 = '\0';
1830 for (sl = specs; sl; sl = sl->next)
1831 if (name_len == sl->name_len && !strcmp (sl->name, p1))
1832 break;
1834 if (!sl)
1835 fatal_error ("specs %s spec was not found to be renamed", p1);
1837 if (strcmp (p1, p2) == 0)
1838 continue;
1840 for (newsl = specs; newsl; newsl = newsl->next)
1841 if (strcmp (newsl->name, p2) == 0)
1842 fatal_error ("%s: attempt to rename spec %qs to "
1843 "already defined spec %qs",
1844 filename, p1, p2);
1846 if (verbose_flag)
1848 fnotice (stderr, "rename spec %s to %s\n", p1, p2);
1849 #ifdef DEBUG_SPECS
1850 fnotice (stderr, "spec is '%s'\n\n", *(sl->ptr_spec));
1851 #endif
1854 set_spec (p2, *(sl->ptr_spec), user_p);
1855 if (sl->alloc_p)
1856 free (CONST_CAST (char *, *(sl->ptr_spec)));
1858 *(sl->ptr_spec) = "";
1859 sl->alloc_p = 0;
1860 continue;
1862 else
1863 fatal_error ("specs unknown %% command after %ld characters",
1864 (long) (p1 - buffer));
1867 /* Find the colon that should end the suffix. */
1868 p1 = p;
1869 while (*p1 && *p1 != ':' && *p1 != '\n')
1870 p1++;
1872 /* The colon shouldn't be missing. */
1873 if (*p1 != ':')
1874 fatal_error ("specs file malformed after %ld characters",
1875 (long) (p1 - buffer));
1877 /* Skip back over trailing whitespace. */
1878 p2 = p1;
1879 while (p2 > buffer && (p2[-1] == ' ' || p2[-1] == '\t'))
1880 p2--;
1882 /* Copy the suffix to a string. */
1883 suffix = save_string (p, p2 - p);
1884 /* Find the next line. */
1885 p = skip_whitespace (p1 + 1);
1886 if (p[1] == 0)
1887 fatal_error ("specs file malformed after %ld characters",
1888 (long) (p - buffer));
1890 p1 = p;
1891 /* Find next blank line or end of string. */
1892 while (*p1 && !(*p1 == '\n' && (p1[1] == '\n' || p1[1] == '\0')))
1893 p1++;
1895 /* Specs end at the blank line and do not include the newline. */
1896 spec = save_string (p, p1 - p);
1897 p = p1;
1899 /* Delete backslash-newline sequences from the spec. */
1900 in = spec;
1901 out = spec;
1902 while (*in != 0)
1904 if (in[0] == '\\' && in[1] == '\n')
1905 in += 2;
1906 else if (in[0] == '#')
1907 while (*in && *in != '\n')
1908 in++;
1910 else
1911 *out++ = *in++;
1913 *out = 0;
1915 if (suffix[0] == '*')
1917 if (! strcmp (suffix, "*link_command"))
1918 link_command_spec = spec;
1919 else
1920 set_spec (suffix + 1, spec, user_p);
1922 else
1924 /* Add this pair to the vector. */
1925 compilers
1926 = XRESIZEVEC (struct compiler, compilers, n_compilers + 2);
1928 compilers[n_compilers].suffix = suffix;
1929 compilers[n_compilers].spec = spec;
1930 n_compilers++;
1931 memset (&compilers[n_compilers], 0, sizeof compilers[n_compilers]);
1934 if (*suffix == 0)
1935 link_command_spec = spec;
1938 if (link_command_spec == 0)
1939 fatal_error ("spec file has no spec for linking");
1942 /* Record the names of temporary files we tell compilers to write,
1943 and delete them at the end of the run. */
1945 /* This is the common prefix we use to make temp file names.
1946 It is chosen once for each run of this program.
1947 It is substituted into a spec by %g or %j.
1948 Thus, all temp file names contain this prefix.
1949 In practice, all temp file names start with this prefix.
1951 This prefix comes from the envvar TMPDIR if it is defined;
1952 otherwise, from the P_tmpdir macro if that is defined;
1953 otherwise, in /usr/tmp or /tmp;
1954 or finally the current directory if all else fails. */
1956 static const char *temp_filename;
1958 /* Length of the prefix. */
1960 static int temp_filename_length;
1962 /* Define the list of temporary files to delete. */
1964 struct temp_file
1966 const char *name;
1967 struct temp_file *next;
1970 /* Queue of files to delete on success or failure of compilation. */
1971 static struct temp_file *always_delete_queue;
1972 /* Queue of files to delete on failure of compilation. */
1973 static struct temp_file *failure_delete_queue;
1975 /* Record FILENAME as a file to be deleted automatically.
1976 ALWAYS_DELETE nonzero means delete it if all compilation succeeds;
1977 otherwise delete it in any case.
1978 FAIL_DELETE nonzero means delete it if a compilation step fails;
1979 otherwise delete it in any case. */
1981 void
1982 record_temp_file (const char *filename, int always_delete, int fail_delete)
1984 char *const name = xstrdup (filename);
1986 if (always_delete)
1988 struct temp_file *temp;
1989 for (temp = always_delete_queue; temp; temp = temp->next)
1990 if (! filename_cmp (name, temp->name))
1991 goto already1;
1993 temp = XNEW (struct temp_file);
1994 temp->next = always_delete_queue;
1995 temp->name = name;
1996 always_delete_queue = temp;
1998 already1:;
2001 if (fail_delete)
2003 struct temp_file *temp;
2004 for (temp = failure_delete_queue; temp; temp = temp->next)
2005 if (! filename_cmp (name, temp->name))
2007 free (name);
2008 goto already2;
2011 temp = XNEW (struct temp_file);
2012 temp->next = failure_delete_queue;
2013 temp->name = name;
2014 failure_delete_queue = temp;
2016 already2:;
2020 /* Delete all the temporary files whose names we previously recorded. */
2022 #ifndef DELETE_IF_ORDINARY
2023 #define DELETE_IF_ORDINARY(NAME,ST,VERBOSE_FLAG) \
2024 do \
2026 if (stat (NAME, &ST) >= 0 && S_ISREG (ST.st_mode)) \
2027 if (unlink (NAME) < 0) \
2028 if (VERBOSE_FLAG) \
2029 perror_with_name (NAME); \
2030 } while (0)
2031 #endif
2033 static void
2034 delete_if_ordinary (const char *name)
2036 struct stat st;
2037 #ifdef DEBUG
2038 int i, c;
2040 printf ("Delete %s? (y or n) ", name);
2041 fflush (stdout);
2042 i = getchar ();
2043 if (i != '\n')
2044 while ((c = getchar ()) != '\n' && c != EOF)
2047 if (i == 'y' || i == 'Y')
2048 #endif /* DEBUG */
2049 DELETE_IF_ORDINARY (name, st, verbose_flag);
2052 static void
2053 delete_temp_files (void)
2055 struct temp_file *temp;
2057 for (temp = always_delete_queue; temp; temp = temp->next)
2058 delete_if_ordinary (temp->name);
2059 always_delete_queue = 0;
2062 /* Delete all the files to be deleted on error. */
2064 static void
2065 delete_failure_queue (void)
2067 struct temp_file *temp;
2069 for (temp = failure_delete_queue; temp; temp = temp->next)
2070 delete_if_ordinary (temp->name);
2073 static void
2074 clear_failure_queue (void)
2076 failure_delete_queue = 0;
2079 /* Call CALLBACK for each path in PATHS, breaking out early if CALLBACK
2080 returns non-NULL.
2081 If DO_MULTI is true iterate over the paths twice, first with multilib
2082 suffix then without, otherwise iterate over the paths once without
2083 adding a multilib suffix. When DO_MULTI is true, some attempt is made
2084 to avoid visiting the same path twice, but we could do better. For
2085 instance, /usr/lib/../lib is considered different from /usr/lib.
2086 At least EXTRA_SPACE chars past the end of the path passed to
2087 CALLBACK are available for use by the callback.
2088 CALLBACK_INFO allows extra parameters to be passed to CALLBACK.
2090 Returns the value returned by CALLBACK. */
2092 static void *
2093 for_each_path (const struct path_prefix *paths,
2094 bool do_multi,
2095 size_t extra_space,
2096 void *(*callback) (char *, void *),
2097 void *callback_info)
2099 struct prefix_list *pl;
2100 const char *multi_dir = NULL;
2101 const char *multi_os_dir = NULL;
2102 const char *multiarch_suffix = NULL;
2103 const char *multi_suffix;
2104 const char *just_multi_suffix;
2105 char *path = NULL;
2106 void *ret = NULL;
2107 bool skip_multi_dir = false;
2108 bool skip_multi_os_dir = false;
2110 multi_suffix = machine_suffix;
2111 just_multi_suffix = just_machine_suffix;
2112 if (do_multi && multilib_dir && strcmp (multilib_dir, ".") != 0)
2114 multi_dir = concat (multilib_dir, dir_separator_str, NULL);
2115 multi_suffix = concat (multi_suffix, multi_dir, NULL);
2116 just_multi_suffix = concat (just_multi_suffix, multi_dir, NULL);
2118 if (do_multi && multilib_os_dir && strcmp (multilib_os_dir, ".") != 0)
2119 multi_os_dir = concat (multilib_os_dir, dir_separator_str, NULL);
2120 if (multiarch_dir)
2121 multiarch_suffix = concat (multiarch_dir, dir_separator_str, NULL);
2123 while (1)
2125 size_t multi_dir_len = 0;
2126 size_t multi_os_dir_len = 0;
2127 size_t multiarch_len = 0;
2128 size_t suffix_len;
2129 size_t just_suffix_len;
2130 size_t len;
2132 if (multi_dir)
2133 multi_dir_len = strlen (multi_dir);
2134 if (multi_os_dir)
2135 multi_os_dir_len = strlen (multi_os_dir);
2136 if (multiarch_suffix)
2137 multiarch_len = strlen (multiarch_suffix);
2138 suffix_len = strlen (multi_suffix);
2139 just_suffix_len = strlen (just_multi_suffix);
2141 if (path == NULL)
2143 len = paths->max_len + extra_space + 1;
2144 len += MAX (MAX (suffix_len, multi_os_dir_len), multiarch_len);
2145 path = XNEWVEC (char, len);
2148 for (pl = paths->plist; pl != 0; pl = pl->next)
2150 len = strlen (pl->prefix);
2151 memcpy (path, pl->prefix, len);
2153 /* Look first in MACHINE/VERSION subdirectory. */
2154 if (!skip_multi_dir)
2156 memcpy (path + len, multi_suffix, suffix_len + 1);
2157 ret = callback (path, callback_info);
2158 if (ret)
2159 break;
2162 /* Some paths are tried with just the machine (ie. target)
2163 subdir. This is used for finding as, ld, etc. */
2164 if (!skip_multi_dir
2165 && pl->require_machine_suffix == 2)
2167 memcpy (path + len, just_multi_suffix, just_suffix_len + 1);
2168 ret = callback (path, callback_info);
2169 if (ret)
2170 break;
2173 /* Now try the multiarch path. */
2174 if (!skip_multi_dir
2175 && !pl->require_machine_suffix && multiarch_dir)
2177 memcpy (path + len, multiarch_suffix, multiarch_len + 1);
2178 ret = callback (path, callback_info);
2179 if (ret)
2180 break;
2183 /* Now try the base path. */
2184 if (!pl->require_machine_suffix
2185 && !(pl->os_multilib ? skip_multi_os_dir : skip_multi_dir))
2187 const char *this_multi;
2188 size_t this_multi_len;
2190 if (pl->os_multilib)
2192 this_multi = multi_os_dir;
2193 this_multi_len = multi_os_dir_len;
2195 else
2197 this_multi = multi_dir;
2198 this_multi_len = multi_dir_len;
2201 if (this_multi_len)
2202 memcpy (path + len, this_multi, this_multi_len + 1);
2203 else
2204 path[len] = '\0';
2206 ret = callback (path, callback_info);
2207 if (ret)
2208 break;
2211 if (pl)
2212 break;
2214 if (multi_dir == NULL && multi_os_dir == NULL)
2215 break;
2217 /* Run through the paths again, this time without multilibs.
2218 Don't repeat any we have already seen. */
2219 if (multi_dir)
2221 free (CONST_CAST (char *, multi_dir));
2222 multi_dir = NULL;
2223 free (CONST_CAST (char *, multi_suffix));
2224 multi_suffix = machine_suffix;
2225 free (CONST_CAST (char *, just_multi_suffix));
2226 just_multi_suffix = just_machine_suffix;
2228 else
2229 skip_multi_dir = true;
2230 if (multi_os_dir)
2232 free (CONST_CAST (char *, multi_os_dir));
2233 multi_os_dir = NULL;
2235 else
2236 skip_multi_os_dir = true;
2239 if (multi_dir)
2241 free (CONST_CAST (char *, multi_dir));
2242 free (CONST_CAST (char *, multi_suffix));
2243 free (CONST_CAST (char *, just_multi_suffix));
2245 if (multi_os_dir)
2246 free (CONST_CAST (char *, multi_os_dir));
2247 if (ret != path)
2248 free (path);
2249 return ret;
2252 /* Callback for build_search_list. Adds path to obstack being built. */
2254 struct add_to_obstack_info {
2255 struct obstack *ob;
2256 bool check_dir;
2257 bool first_time;
2260 static void *
2261 add_to_obstack (char *path, void *data)
2263 struct add_to_obstack_info *info = (struct add_to_obstack_info *) data;
2265 if (info->check_dir && !is_directory (path, false))
2266 return NULL;
2268 if (!info->first_time)
2269 obstack_1grow (info->ob, PATH_SEPARATOR);
2271 obstack_grow (info->ob, path, strlen (path));
2273 info->first_time = false;
2274 return NULL;
2277 /* Add or change the value of an environment variable, outputting the
2278 change to standard error if in verbose mode. */
2279 static void
2280 xputenv (const char *string)
2282 if (verbose_flag)
2283 fnotice (stderr, "%s\n", string);
2284 putenv (CONST_CAST (char *, string));
2287 /* Build a list of search directories from PATHS.
2288 PREFIX is a string to prepend to the list.
2289 If CHECK_DIR_P is true we ensure the directory exists.
2290 If DO_MULTI is true, multilib paths are output first, then
2291 non-multilib paths.
2292 This is used mostly by putenv_from_prefixes so we use `collect_obstack'.
2293 It is also used by the --print-search-dirs flag. */
2295 static char *
2296 build_search_list (const struct path_prefix *paths, const char *prefix,
2297 bool check_dir, bool do_multi)
2299 struct add_to_obstack_info info;
2301 info.ob = &collect_obstack;
2302 info.check_dir = check_dir;
2303 info.first_time = true;
2305 obstack_grow (&collect_obstack, prefix, strlen (prefix));
2306 obstack_1grow (&collect_obstack, '=');
2308 for_each_path (paths, do_multi, 0, add_to_obstack, &info);
2310 obstack_1grow (&collect_obstack, '\0');
2311 return XOBFINISH (&collect_obstack, char *);
2314 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
2315 for collect. */
2317 static void
2318 putenv_from_prefixes (const struct path_prefix *paths, const char *env_var,
2319 bool do_multi)
2321 xputenv (build_search_list (paths, env_var, true, do_multi));
2324 /* Check whether NAME can be accessed in MODE. This is like access,
2325 except that it never considers directories to be executable. */
2327 static int
2328 access_check (const char *name, int mode)
2330 if (mode == X_OK)
2332 struct stat st;
2334 if (stat (name, &st) < 0
2335 || S_ISDIR (st.st_mode))
2336 return -1;
2339 return access (name, mode);
2342 /* Callback for find_a_file. Appends the file name to the directory
2343 path. If the resulting file exists in the right mode, return the
2344 full pathname to the file. */
2346 struct file_at_path_info {
2347 const char *name;
2348 const char *suffix;
2349 int name_len;
2350 int suffix_len;
2351 int mode;
2354 static void *
2355 file_at_path (char *path, void *data)
2357 struct file_at_path_info *info = (struct file_at_path_info *) data;
2358 size_t len = strlen (path);
2360 memcpy (path + len, info->name, info->name_len);
2361 len += info->name_len;
2363 /* Some systems have a suffix for executable files.
2364 So try appending that first. */
2365 if (info->suffix_len)
2367 memcpy (path + len, info->suffix, info->suffix_len + 1);
2368 if (access_check (path, info->mode) == 0)
2369 return path;
2372 path[len] = '\0';
2373 if (access_check (path, info->mode) == 0)
2374 return path;
2376 return NULL;
2379 /* Search for NAME using the prefix list PREFIXES. MODE is passed to
2380 access to check permissions. If DO_MULTI is true, search multilib
2381 paths then non-multilib paths, otherwise do not search multilib paths.
2382 Return 0 if not found, otherwise return its name, allocated with malloc. */
2384 static char *
2385 find_a_file (const struct path_prefix *pprefix, const char *name, int mode,
2386 bool do_multi)
2388 struct file_at_path_info info;
2390 #ifdef DEFAULT_ASSEMBLER
2391 if (! strcmp (name, "as") && access (DEFAULT_ASSEMBLER, mode) == 0)
2392 return xstrdup (DEFAULT_ASSEMBLER);
2393 #endif
2395 #ifdef DEFAULT_LINKER
2396 if (! strcmp(name, "ld") && access (DEFAULT_LINKER, mode) == 0)
2397 return xstrdup (DEFAULT_LINKER);
2398 #endif
2400 /* Determine the filename to execute (special case for absolute paths). */
2402 if (IS_ABSOLUTE_PATH (name))
2404 if (access (name, mode) == 0)
2405 return xstrdup (name);
2407 return NULL;
2410 info.name = name;
2411 info.suffix = (mode & X_OK) != 0 ? HOST_EXECUTABLE_SUFFIX : "";
2412 info.name_len = strlen (info.name);
2413 info.suffix_len = strlen (info.suffix);
2414 info.mode = mode;
2416 return (char*) for_each_path (pprefix, do_multi,
2417 info.name_len + info.suffix_len,
2418 file_at_path, &info);
2421 /* Ranking of prefixes in the sort list. -B prefixes are put before
2422 all others. */
2424 enum path_prefix_priority
2426 PREFIX_PRIORITY_B_OPT,
2427 PREFIX_PRIORITY_LAST
2430 /* Add an entry for PREFIX in PLIST. The PLIST is kept in ascending
2431 order according to PRIORITY. Within each PRIORITY, new entries are
2432 appended.
2434 If WARN is nonzero, we will warn if no file is found
2435 through this prefix. WARN should point to an int
2436 which will be set to 1 if this entry is used.
2438 COMPONENT is the value to be passed to update_path.
2440 REQUIRE_MACHINE_SUFFIX is 1 if this prefix can't be used without
2441 the complete value of machine_suffix.
2442 2 means try both machine_suffix and just_machine_suffix. */
2444 static void
2445 add_prefix (struct path_prefix *pprefix, const char *prefix,
2446 const char *component, /* enum prefix_priority */ int priority,
2447 int require_machine_suffix, int os_multilib)
2449 struct prefix_list *pl, **prev;
2450 int len;
2452 for (prev = &pprefix->plist;
2453 (*prev) != NULL && (*prev)->priority <= priority;
2454 prev = &(*prev)->next)
2457 /* Keep track of the longest prefix. */
2459 prefix = update_path (prefix, component);
2460 len = strlen (prefix);
2461 if (len > pprefix->max_len)
2462 pprefix->max_len = len;
2464 pl = XNEW (struct prefix_list);
2465 pl->prefix = prefix;
2466 pl->require_machine_suffix = require_machine_suffix;
2467 pl->priority = priority;
2468 pl->os_multilib = os_multilib;
2470 /* Insert after PREV. */
2471 pl->next = (*prev);
2472 (*prev) = pl;
2475 /* Same as add_prefix, but prepending target_system_root to prefix. */
2476 /* The target_system_root prefix has been relocated by gcc_exec_prefix. */
2477 static void
2478 add_sysrooted_prefix (struct path_prefix *pprefix, const char *prefix,
2479 const char *component,
2480 /* enum prefix_priority */ int priority,
2481 int require_machine_suffix, int os_multilib)
2483 if (!IS_ABSOLUTE_PATH (prefix))
2484 fatal_error ("system path %qs is not absolute", prefix);
2486 if (target_system_root)
2488 char *sysroot_no_trailing_dir_separator = xstrdup (target_system_root);
2489 size_t sysroot_len = strlen (target_system_root);
2491 if (sysroot_len > 0
2492 && target_system_root[sysroot_len - 1] == DIR_SEPARATOR)
2493 sysroot_no_trailing_dir_separator[sysroot_len - 1] = '\0';
2495 if (target_sysroot_suffix)
2496 prefix = concat (sysroot_no_trailing_dir_separator,
2497 target_sysroot_suffix, prefix, NULL);
2498 else
2499 prefix = concat (sysroot_no_trailing_dir_separator, prefix, NULL);
2501 free (sysroot_no_trailing_dir_separator);
2503 /* We have to override this because GCC's notion of sysroot
2504 moves along with GCC. */
2505 component = "GCC";
2508 add_prefix (pprefix, prefix, component, priority,
2509 require_machine_suffix, os_multilib);
2512 /* Execute the command specified by the arguments on the current line of spec.
2513 When using pipes, this includes several piped-together commands
2514 with `|' between them.
2516 Return 0 if successful, -1 if failed. */
2518 static int
2519 execute (void)
2521 int i;
2522 int n_commands; /* # of command. */
2523 char *string;
2524 struct pex_obj *pex;
2525 struct command
2527 const char *prog; /* program name. */
2528 const char **argv; /* vector of args. */
2530 const char *arg;
2532 struct command *commands; /* each command buffer with above info. */
2534 gcc_assert (!processing_spec_function);
2536 if (wrapper_string)
2538 string = find_a_file (&exec_prefixes,
2539 VEC_index (const_char_p, argbuf, 0), X_OK, false);
2540 if (string)
2541 VEC_replace (const_char_p, argbuf, 0, string);
2542 insert_wrapper (wrapper_string);
2545 /* Count # of piped commands. */
2546 for (n_commands = 1, i = 0; VEC_iterate (const_char_p, argbuf, i, arg); i++)
2547 if (strcmp (arg, "|") == 0)
2548 n_commands++;
2550 /* Get storage for each command. */
2551 commands = (struct command *) alloca (n_commands * sizeof (struct command));
2553 /* Split argbuf into its separate piped processes,
2554 and record info about each one.
2555 Also search for the programs that are to be run. */
2557 VEC_safe_push (const_char_p, heap, argbuf, 0);
2559 commands[0].prog = VEC_index (const_char_p, argbuf, 0); /* first command. */
2560 commands[0].argv = VEC_address (const_char_p, argbuf);
2562 if (!wrapper_string)
2564 string = find_a_file (&exec_prefixes, commands[0].prog, X_OK, false);
2565 commands[0].argv[0] = (string) ? string : commands[0].argv[0];
2568 for (n_commands = 1, i = 0; VEC_iterate (const_char_p, argbuf, i, arg); i++)
2569 if (arg && strcmp (arg, "|") == 0)
2570 { /* each command. */
2571 #if defined (__MSDOS__) || defined (OS2) || defined (VMS)
2572 fatal_error ("-pipe not supported");
2573 #endif
2574 VEC_replace (const_char_p, argbuf, i, 0); /* Termination of
2575 command args. */
2576 commands[n_commands].prog = VEC_index (const_char_p, argbuf, i + 1);
2577 commands[n_commands].argv
2578 = &(VEC_address (const_char_p, argbuf))[i + 1];
2579 string = find_a_file (&exec_prefixes, commands[n_commands].prog,
2580 X_OK, false);
2581 if (string)
2582 commands[n_commands].argv[0] = string;
2583 n_commands++;
2586 /* If -v, print what we are about to do, and maybe query. */
2588 if (verbose_flag)
2590 /* For help listings, put a blank line between sub-processes. */
2591 if (print_help_list)
2592 fputc ('\n', stderr);
2594 /* Print each piped command as a separate line. */
2595 for (i = 0; i < n_commands; i++)
2597 const char *const *j;
2599 if (verbose_only_flag)
2601 for (j = commands[i].argv; *j; j++)
2603 const char *p;
2604 for (p = *j; *p; ++p)
2605 if (!ISALNUM ((unsigned char) *p)
2606 && *p != '_' && *p != '/' && *p != '-' && *p != '.')
2607 break;
2608 if (*p || !*j)
2610 fprintf (stderr, " \"");
2611 for (p = *j; *p; ++p)
2613 if (*p == '"' || *p == '\\' || *p == '$')
2614 fputc ('\\', stderr);
2615 fputc (*p, stderr);
2617 fputc ('"', stderr);
2619 /* If it's empty, print "". */
2620 else if (!**j)
2621 fprintf (stderr, " \"\"");
2622 else
2623 fprintf (stderr, " %s", *j);
2626 else
2627 for (j = commands[i].argv; *j; j++)
2628 /* If it's empty, print "". */
2629 if (!**j)
2630 fprintf (stderr, " \"\"");
2631 else
2632 fprintf (stderr, " %s", *j);
2634 /* Print a pipe symbol after all but the last command. */
2635 if (i + 1 != n_commands)
2636 fprintf (stderr, " |");
2637 fprintf (stderr, "\n");
2639 fflush (stderr);
2640 if (verbose_only_flag != 0)
2642 /* verbose_only_flag should act as if the spec was
2643 executed, so increment execution_count before
2644 returning. This prevents spurious warnings about
2645 unused linker input files, etc. */
2646 execution_count++;
2647 return 0;
2649 #ifdef DEBUG
2650 fnotice (stderr, "\nGo ahead? (y or n) ");
2651 fflush (stderr);
2652 i = getchar ();
2653 if (i != '\n')
2654 while (getchar () != '\n')
2657 if (i != 'y' && i != 'Y')
2658 return 0;
2659 #endif /* DEBUG */
2662 #ifdef ENABLE_VALGRIND_CHECKING
2663 /* Run the each command through valgrind. To simplify prepending the
2664 path to valgrind and the option "-q" (for quiet operation unless
2665 something triggers), we allocate a separate argv array. */
2667 for (i = 0; i < n_commands; i++)
2669 const char **argv;
2670 int argc;
2671 int j;
2673 for (argc = 0; commands[i].argv[argc] != NULL; argc++)
2676 argv = XALLOCAVEC (const char *, argc + 3);
2678 argv[0] = VALGRIND_PATH;
2679 argv[1] = "-q";
2680 for (j = 2; j < argc + 2; j++)
2681 argv[j] = commands[i].argv[j - 2];
2682 argv[j] = NULL;
2684 commands[i].argv = argv;
2685 commands[i].prog = argv[0];
2687 #endif
2689 /* Run each piped subprocess. */
2691 pex = pex_init (PEX_USE_PIPES | ((report_times || report_times_to_file)
2692 ? PEX_RECORD_TIMES : 0),
2693 progname, temp_filename);
2694 if (pex == NULL)
2695 fatal_error ("pex_init failed: %m");
2697 for (i = 0; i < n_commands; i++)
2699 const char *errmsg;
2700 int err;
2701 const char *string = commands[i].argv[0];
2703 errmsg = pex_run (pex,
2704 ((i + 1 == n_commands ? PEX_LAST : 0)
2705 | (string == commands[i].prog ? PEX_SEARCH : 0)),
2706 string, CONST_CAST (char **, commands[i].argv),
2707 NULL, NULL, &err);
2708 if (errmsg != NULL)
2710 if (err == 0)
2711 fatal_error (errmsg);
2712 else
2714 errno = err;
2715 pfatal_with_name (errmsg);
2719 if (string != commands[i].prog)
2720 free (CONST_CAST (char *, string));
2723 execution_count++;
2725 /* Wait for all the subprocesses to finish. */
2728 int *statuses;
2729 struct pex_time *times = NULL;
2730 int ret_code = 0;
2732 statuses = (int *) alloca (n_commands * sizeof (int));
2733 if (!pex_get_status (pex, n_commands, statuses))
2734 fatal_error ("failed to get exit status: %m");
2736 if (report_times || report_times_to_file)
2738 times = (struct pex_time *) alloca (n_commands * sizeof (struct pex_time));
2739 if (!pex_get_times (pex, n_commands, times))
2740 fatal_error ("failed to get process times: %m");
2743 pex_free (pex);
2745 for (i = 0; i < n_commands; ++i)
2747 int status = statuses[i];
2749 if (WIFSIGNALED (status))
2751 #ifdef SIGPIPE
2752 /* SIGPIPE is a special case. It happens in -pipe mode
2753 when the compiler dies before the preprocessor is done,
2754 or the assembler dies before the compiler is done.
2755 There's generally been an error already, and this is
2756 just fallout. So don't generate another error unless
2757 we would otherwise have succeeded. */
2758 if (WTERMSIG (status) == SIGPIPE
2759 && (signal_count || greatest_status >= MIN_FATAL_STATUS))
2761 signal_count++;
2762 ret_code = -1;
2764 else
2765 #endif
2766 internal_error ("%s (program %s)",
2767 strsignal (WTERMSIG (status)), commands[i].prog);
2769 else if (WIFEXITED (status)
2770 && WEXITSTATUS (status) >= MIN_FATAL_STATUS)
2772 if (WEXITSTATUS (status) > greatest_status)
2773 greatest_status = WEXITSTATUS (status);
2774 ret_code = -1;
2777 if (report_times || report_times_to_file)
2779 struct pex_time *pt = &times[i];
2780 double ut, st;
2782 ut = ((double) pt->user_seconds
2783 + (double) pt->user_microseconds / 1.0e6);
2784 st = ((double) pt->system_seconds
2785 + (double) pt->system_microseconds / 1.0e6);
2787 if (ut + st != 0)
2789 if (report_times)
2790 fnotice (stderr, "# %s %.2f %.2f\n",
2791 commands[i].prog, ut, st);
2793 if (report_times_to_file)
2795 int c = 0;
2796 const char *const *j;
2798 fprintf (report_times_to_file, "%g %g", ut, st);
2800 for (j = &commands[i].prog; *j; j = &commands[i].argv[++c])
2802 const char *p;
2803 for (p = *j; *p; ++p)
2804 if (*p == '"' || *p == '\\' || *p == '$'
2805 || ISSPACE (*p))
2806 break;
2808 if (*p)
2810 fprintf (report_times_to_file, " \"");
2811 for (p = *j; *p; ++p)
2813 if (*p == '"' || *p == '\\' || *p == '$')
2814 fputc ('\\', report_times_to_file);
2815 fputc (*p, report_times_to_file);
2817 fputc ('"', report_times_to_file);
2819 else
2820 fprintf (report_times_to_file, " %s", *j);
2823 fputc ('\n', report_times_to_file);
2829 return ret_code;
2833 /* Find all the switches given to us
2834 and make a vector describing them.
2835 The elements of the vector are strings, one per switch given.
2836 If a switch uses following arguments, then the `part1' field
2837 is the switch itself and the `args' field
2838 is a null-terminated vector containing the following arguments.
2839 Bits in the `live_cond' field are:
2840 SWITCH_LIVE to indicate this switch is true in a conditional spec.
2841 SWITCH_FALSE to indicate this switch is overridden by a later switch.
2842 SWITCH_IGNORE to indicate this switch should be ignored (used in %<S).
2843 SWITCH_IGNORE_PERMANENTLY to indicate this switch should be ignored
2844 in all do_spec calls afterwards. Used for %<S from self specs.
2845 The `validated' field is nonzero if any spec has looked at this switch;
2846 if it remains zero at the end of the run, it must be meaningless. */
2848 #define SWITCH_LIVE (1 << 0)
2849 #define SWITCH_FALSE (1 << 1)
2850 #define SWITCH_IGNORE (1 << 2)
2851 #define SWITCH_IGNORE_PERMANENTLY (1 << 3)
2852 #define SWITCH_KEEP_FOR_GCC (1 << 4)
2854 struct switchstr
2856 const char *part1;
2857 const char **args;
2858 unsigned int live_cond;
2859 bool known;
2860 bool validated;
2861 bool ordering;
2864 static struct switchstr *switches;
2866 static int n_switches;
2868 static int n_switches_alloc;
2870 /* Set to zero if -fcompare-debug is disabled, positive if it's
2871 enabled and we're running the first compilation, negative if it's
2872 enabled and we're running the second compilation. For most of the
2873 time, it's in the range -1..1, but it can be temporarily set to 2
2874 or 3 to indicate that the -fcompare-debug flags didn't come from
2875 the command-line, but rather from the GCC_COMPARE_DEBUG environment
2876 variable, until a synthesized -fcompare-debug flag is added to the
2877 command line. */
2878 int compare_debug;
2880 /* Set to nonzero if we've seen the -fcompare-debug-second flag. */
2881 int compare_debug_second;
2883 /* Set to the flags that should be passed to the second compilation in
2884 a -fcompare-debug compilation. */
2885 const char *compare_debug_opt;
2887 static struct switchstr *switches_debug_check[2];
2889 static int n_switches_debug_check[2];
2891 static int n_switches_alloc_debug_check[2];
2893 static char *debug_check_temp_file[2];
2895 /* Language is one of three things:
2897 1) The name of a real programming language.
2898 2) NULL, indicating that no one has figured out
2899 what it is yet.
2900 3) '*', indicating that the file should be passed
2901 to the linker. */
2902 struct infile
2904 const char *name;
2905 const char *language;
2906 struct compiler *incompiler;
2907 bool compiled;
2908 bool preprocessed;
2911 /* Also a vector of input files specified. */
2913 static struct infile *infiles;
2915 int n_infiles;
2917 static int n_infiles_alloc;
2919 /* True if multiple input files are being compiled to a single
2920 assembly file. */
2922 static bool combine_inputs;
2924 /* This counts the number of libraries added by lang_specific_driver, so that
2925 we can tell if there were any user supplied any files or libraries. */
2927 static int added_libraries;
2929 /* And a vector of corresponding output files is made up later. */
2931 const char **outfiles;
2933 #if defined(HAVE_TARGET_OBJECT_SUFFIX) || defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
2935 /* Convert NAME to a new name if it is the standard suffix. DO_EXE
2936 is true if we should look for an executable suffix. DO_OBJ
2937 is true if we should look for an object suffix. */
2939 static const char *
2940 convert_filename (const char *name, int do_exe ATTRIBUTE_UNUSED,
2941 int do_obj ATTRIBUTE_UNUSED)
2943 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
2944 int i;
2945 #endif
2946 int len;
2948 if (name == NULL)
2949 return NULL;
2951 len = strlen (name);
2953 #ifdef HAVE_TARGET_OBJECT_SUFFIX
2954 /* Convert x.o to x.obj if TARGET_OBJECT_SUFFIX is ".obj". */
2955 if (do_obj && len > 2
2956 && name[len - 2] == '.'
2957 && name[len - 1] == 'o')
2959 obstack_grow (&obstack, name, len - 2);
2960 obstack_grow0 (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
2961 name = XOBFINISH (&obstack, const char *);
2963 #endif
2965 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX)
2966 /* If there is no filetype, make it the executable suffix (which includes
2967 the "."). But don't get confused if we have just "-o". */
2968 if (! do_exe || TARGET_EXECUTABLE_SUFFIX[0] == 0 || (len == 2 && name[0] == '-'))
2969 return name;
2971 for (i = len - 1; i >= 0; i--)
2972 if (IS_DIR_SEPARATOR (name[i]))
2973 break;
2975 for (i++; i < len; i++)
2976 if (name[i] == '.')
2977 return name;
2979 obstack_grow (&obstack, name, len);
2980 obstack_grow0 (&obstack, TARGET_EXECUTABLE_SUFFIX,
2981 strlen (TARGET_EXECUTABLE_SUFFIX));
2982 name = XOBFINISH (&obstack, const char *);
2983 #endif
2985 return name;
2987 #endif
2989 /* Display the command line switches accepted by gcc. */
2990 static void
2991 display_help (void)
2993 printf (_("Usage: %s [options] file...\n"), progname);
2994 fputs (_("Options:\n"), stdout);
2996 fputs (_(" -pass-exit-codes Exit with highest error code from a phase\n"), stdout);
2997 fputs (_(" --help Display this information\n"), stdout);
2998 fputs (_(" --target-help Display target specific command line options\n"), stdout);
2999 fputs (_(" --help={common|optimizers|params|target|warnings|[^]{joined|separate|undocumented}}[,...]\n"), stdout);
3000 fputs (_(" Display specific types of command line options\n"), stdout);
3001 if (! verbose_flag)
3002 fputs (_(" (Use '-v --help' to display command line options of sub-processes)\n"), stdout);
3003 fputs (_(" --version Display compiler version information\n"), stdout);
3004 fputs (_(" -dumpspecs Display all of the built in spec strings\n"), stdout);
3005 fputs (_(" -dumpversion Display the version of the compiler\n"), stdout);
3006 fputs (_(" -dumpmachine Display the compiler's target processor\n"), stdout);
3007 fputs (_(" -print-search-dirs Display the directories in the compiler's search path\n"), stdout);
3008 fputs (_(" -print-libgcc-file-name Display the name of the compiler's companion library\n"), stdout);
3009 fputs (_(" -print-file-name=<lib> Display the full path to library <lib>\n"), stdout);
3010 fputs (_(" -print-prog-name=<prog> Display the full path to compiler component <prog>\n"), stdout);
3011 fputs (_("\
3012 -print-multiarch Display the target's normalized GNU triplet, used as\n\
3013 a component in the library path\n"), stdout);
3014 fputs (_(" -print-multi-directory Display the root directory for versions of libgcc\n"), stdout);
3015 fputs (_("\
3016 -print-multi-lib Display the mapping between command line options and\n\
3017 multiple library search directories\n"), stdout);
3018 fputs (_(" -print-multi-os-directory Display the relative path to OS libraries\n"), stdout);
3019 fputs (_(" -print-sysroot Display the target libraries directory\n"), stdout);
3020 fputs (_(" -print-sysroot-headers-suffix Display the sysroot suffix used to find headers\n"), stdout);
3021 fputs (_(" -Wa,<options> Pass comma-separated <options> on to the assembler\n"), stdout);
3022 fputs (_(" -Wp,<options> Pass comma-separated <options> on to the preprocessor\n"), stdout);
3023 fputs (_(" -Wl,<options> Pass comma-separated <options> on to the linker\n"), stdout);
3024 fputs (_(" -Xassembler <arg> Pass <arg> on to the assembler\n"), stdout);
3025 fputs (_(" -Xpreprocessor <arg> Pass <arg> on to the preprocessor\n"), stdout);
3026 fputs (_(" -Xlinker <arg> Pass <arg> on to the linker\n"), stdout);
3027 fputs (_(" -save-temps Do not delete intermediate files\n"), stdout);
3028 fputs (_(" -save-temps=<arg> Do not delete intermediate files\n"), stdout);
3029 fputs (_("\
3030 -no-canonical-prefixes Do not canonicalize paths when building relative\n\
3031 prefixes to other gcc components\n"), stdout);
3032 fputs (_(" -pipe Use pipes rather than intermediate files\n"), stdout);
3033 fputs (_(" -time Time the execution of each subprocess\n"), stdout);
3034 fputs (_(" -specs=<file> Override built-in specs with the contents of <file>\n"), stdout);
3035 fputs (_(" -std=<standard> Assume that the input sources are for <standard>\n"), stdout);
3036 fputs (_("\
3037 --sysroot=<directory> Use <directory> as the root directory for headers\n\
3038 and libraries\n"), stdout);
3039 fputs (_(" -B <directory> Add <directory> to the compiler's search paths\n"), stdout);
3040 fputs (_(" -v Display the programs invoked by the compiler\n"), stdout);
3041 fputs (_(" -### Like -v but options quoted and commands not executed\n"), stdout);
3042 fputs (_(" -E Preprocess only; do not compile, assemble or link\n"), stdout);
3043 fputs (_(" -S Compile only; do not assemble or link\n"), stdout);
3044 fputs (_(" -c Compile and assemble, but do not link\n"), stdout);
3045 fputs (_(" -o <file> Place the output into <file>\n"), stdout);
3046 fputs (_(" -pie Create a position independent executable\n"), stdout);
3047 fputs (_(" -shared Create a shared library\n"), stdout);
3048 fputs (_("\
3049 -x <language> Specify the language of the following input files\n\
3050 Permissible languages include: c c++ assembler none\n\
3051 'none' means revert to the default behavior of\n\
3052 guessing the language based on the file's extension\n\
3053 "), stdout);
3055 printf (_("\
3056 \nOptions starting with -g, -f, -m, -O, -W, or --param are automatically\n\
3057 passed on to the various sub-processes invoked by %s. In order to pass\n\
3058 other options on to these processes the -W<letter> options must be used.\n\
3059 "), progname);
3061 /* The rest of the options are displayed by invocations of the various
3062 sub-processes. */
3065 static void
3066 add_preprocessor_option (const char *option, int len)
3068 VEC_safe_push (char_p, heap, preprocessor_options,
3069 save_string (option, len));
3072 static void
3073 add_assembler_option (const char *option, int len)
3075 VEC_safe_push (char_p, heap, assembler_options, save_string (option, len));
3078 static void
3079 add_linker_option (const char *option, int len)
3081 VEC_safe_push (char_p, heap, linker_options, save_string (option, len));
3084 /* Allocate space for an input file in infiles. */
3086 static void
3087 alloc_infile (void)
3089 if (n_infiles_alloc == 0)
3091 n_infiles_alloc = 16;
3092 infiles = XNEWVEC (struct infile, n_infiles_alloc);
3094 else if (n_infiles_alloc == n_infiles)
3096 n_infiles_alloc *= 2;
3097 infiles = XRESIZEVEC (struct infile, infiles, n_infiles_alloc);
3101 /* Store an input file with the given NAME and LANGUAGE in
3102 infiles. */
3104 static void
3105 add_infile (const char *name, const char *language)
3107 alloc_infile ();
3108 infiles[n_infiles].name = name;
3109 infiles[n_infiles++].language = language;
3112 /* Allocate space for a switch in switches. */
3114 static void
3115 alloc_switch (void)
3117 if (n_switches_alloc == 0)
3119 n_switches_alloc = 16;
3120 switches = XNEWVEC (struct switchstr, n_switches_alloc);
3122 else if (n_switches_alloc == n_switches)
3124 n_switches_alloc *= 2;
3125 switches = XRESIZEVEC (struct switchstr, switches, n_switches_alloc);
3129 /* Save an option OPT with N_ARGS arguments in array ARGS, marking it
3130 as validated if VALIDATED and KNOWN if it is an internal switch. */
3132 static void
3133 save_switch (const char *opt, size_t n_args, const char *const *args,
3134 bool validated, bool known)
3136 alloc_switch ();
3137 switches[n_switches].part1 = opt + 1;
3138 if (n_args == 0)
3139 switches[n_switches].args = 0;
3140 else
3142 switches[n_switches].args = XNEWVEC (const char *, n_args + 1);
3143 memcpy (switches[n_switches].args, args, n_args * sizeof (const char *));
3144 switches[n_switches].args[n_args] = NULL;
3147 switches[n_switches].live_cond = 0;
3148 switches[n_switches].validated = validated;
3149 switches[n_switches].known = known;
3150 switches[n_switches].ordering = 0;
3151 n_switches++;
3154 /* Handle an option DECODED that is unknown to the option-processing
3155 machinery. */
3157 static bool
3158 driver_unknown_option_callback (const struct cl_decoded_option *decoded)
3160 const char *opt = decoded->arg;
3161 if (opt[1] == 'W' && opt[2] == 'n' && opt[3] == 'o' && opt[4] == '-'
3162 && !(decoded->errors & CL_ERR_NEGATIVE))
3164 /* Leave unknown -Wno-* options for the compiler proper, to be
3165 diagnosed only if there are warnings. */
3166 save_switch (decoded->canonical_option[0],
3167 decoded->canonical_option_num_elements - 1,
3168 &decoded->canonical_option[1], false, true);
3169 return false;
3171 if (decoded->opt_index == OPT_SPECIAL_unknown)
3173 /* Give it a chance to define it a a spec file. */
3174 save_switch (decoded->canonical_option[0],
3175 decoded->canonical_option_num_elements - 1,
3176 &decoded->canonical_option[1], false, false);
3177 return false;
3179 else
3180 return true;
3183 /* Handle an option DECODED that is not marked as CL_DRIVER.
3184 LANG_MASK will always be CL_DRIVER. */
3186 static void
3187 driver_wrong_lang_callback (const struct cl_decoded_option *decoded,
3188 unsigned int lang_mask ATTRIBUTE_UNUSED)
3190 /* At this point, non-driver options are accepted (and expected to
3191 be passed down by specs) unless marked to be rejected by the
3192 driver. Options to be rejected by the driver but accepted by the
3193 compilers proper are treated just like completely unknown
3194 options. */
3195 const struct cl_option *option = &cl_options[decoded->opt_index];
3197 if (option->cl_reject_driver)
3198 error ("unrecognized command line option %qs",
3199 decoded->orig_option_with_args_text);
3200 else
3201 save_switch (decoded->canonical_option[0],
3202 decoded->canonical_option_num_elements - 1,
3203 &decoded->canonical_option[1], false, true);
3206 static const char *spec_lang = 0;
3207 static int last_language_n_infiles;
3209 /* Handle a driver option; arguments and return value as for
3210 handle_option. */
3212 static bool
3213 driver_handle_option (struct gcc_options *opts,
3214 struct gcc_options *opts_set,
3215 const struct cl_decoded_option *decoded,
3216 unsigned int lang_mask ATTRIBUTE_UNUSED, int kind,
3217 location_t loc,
3218 const struct cl_option_handlers *handlers ATTRIBUTE_UNUSED,
3219 diagnostic_context *dc)
3221 size_t opt_index = decoded->opt_index;
3222 const char *arg = decoded->arg;
3223 const char *compare_debug_replacement_opt;
3224 int value = decoded->value;
3225 bool validated = false;
3226 bool do_save = true;
3228 gcc_assert (opts == &global_options);
3229 gcc_assert (opts_set == &global_options_set);
3230 gcc_assert (kind == DK_UNSPECIFIED);
3231 gcc_assert (loc == UNKNOWN_LOCATION);
3232 gcc_assert (dc == global_dc);
3234 switch (opt_index)
3236 case OPT_dumpspecs:
3238 struct spec_list *sl;
3239 init_spec ();
3240 for (sl = specs; sl; sl = sl->next)
3241 printf ("*%s:\n%s\n\n", sl->name, *(sl->ptr_spec));
3242 if (link_command_spec)
3243 printf ("*link_command:\n%s\n\n", link_command_spec);
3244 exit (0);
3247 case OPT_dumpversion:
3248 printf ("%s\n", spec_version);
3249 exit (0);
3251 case OPT_dumpmachine:
3252 printf ("%s\n", spec_machine);
3253 exit (0);
3255 case OPT__version:
3256 print_version = 1;
3258 /* CPP driver cannot obtain switch from cc1_options. */
3259 if (is_cpp_driver)
3260 add_preprocessor_option ("--version", strlen ("--version"));
3261 add_assembler_option ("--version", strlen ("--version"));
3262 add_linker_option ("--version", strlen ("--version"));
3263 break;
3265 case OPT__help:
3266 print_help_list = 1;
3268 /* CPP driver cannot obtain switch from cc1_options. */
3269 if (is_cpp_driver)
3270 add_preprocessor_option ("--help", 6);
3271 add_assembler_option ("--help", 6);
3272 add_linker_option ("--help", 6);
3273 break;
3275 case OPT__help_:
3276 print_subprocess_help = 2;
3277 break;
3279 case OPT__target_help:
3280 print_subprocess_help = 1;
3282 /* CPP driver cannot obtain switch from cc1_options. */
3283 if (is_cpp_driver)
3284 add_preprocessor_option ("--target-help", 13);
3285 add_assembler_option ("--target-help", 13);
3286 add_linker_option ("--target-help", 13);
3287 break;
3289 case OPT__no_sysroot_suffix:
3290 case OPT_pass_exit_codes:
3291 case OPT_print_search_dirs:
3292 case OPT_print_file_name_:
3293 case OPT_print_prog_name_:
3294 case OPT_print_multi_lib:
3295 case OPT_print_multi_directory:
3296 case OPT_print_sysroot:
3297 case OPT_print_multi_os_directory:
3298 case OPT_print_multiarch:
3299 case OPT_print_sysroot_headers_suffix:
3300 case OPT_time:
3301 case OPT_wrapper:
3302 /* These options set the variables specified in common.opt
3303 automatically, and do not need to be saved for spec
3304 processing. */
3305 do_save = false;
3306 break;
3308 case OPT_print_libgcc_file_name:
3309 print_file_name = "libgcc.a";
3310 do_save = false;
3311 break;
3313 case OPT_fcompare_debug_second:
3314 compare_debug_second = 1;
3315 break;
3317 case OPT_fcompare_debug:
3318 switch (value)
3320 case 0:
3321 compare_debug_replacement_opt = "-fcompare-debug=";
3322 arg = "";
3323 goto compare_debug_with_arg;
3325 case 1:
3326 compare_debug_replacement_opt = "-fcompare-debug=-gtoggle";
3327 arg = "-gtoggle";
3328 goto compare_debug_with_arg;
3330 default:
3331 gcc_unreachable ();
3333 break;
3335 case OPT_fcompare_debug_:
3336 compare_debug_replacement_opt = decoded->canonical_option[0];
3337 compare_debug_with_arg:
3338 gcc_assert (decoded->canonical_option_num_elements == 1);
3339 gcc_assert (arg != NULL);
3340 if (*arg)
3341 compare_debug = 1;
3342 else
3343 compare_debug = -1;
3344 if (compare_debug < 0)
3345 compare_debug_opt = NULL;
3346 else
3347 compare_debug_opt = arg;
3348 save_switch (compare_debug_replacement_opt, 0, NULL, validated, true);
3349 return true;
3351 case OPT_Wa_:
3353 int prev, j;
3354 /* Pass the rest of this option to the assembler. */
3356 /* Split the argument at commas. */
3357 prev = 0;
3358 for (j = 0; arg[j]; j++)
3359 if (arg[j] == ',')
3361 add_assembler_option (arg + prev, j - prev);
3362 prev = j + 1;
3365 /* Record the part after the last comma. */
3366 add_assembler_option (arg + prev, j - prev);
3368 do_save = false;
3369 break;
3371 case OPT_Wp_:
3373 int prev, j;
3374 /* Pass the rest of this option to the preprocessor. */
3376 /* Split the argument at commas. */
3377 prev = 0;
3378 for (j = 0; arg[j]; j++)
3379 if (arg[j] == ',')
3381 add_preprocessor_option (arg + prev, j - prev);
3382 prev = j + 1;
3385 /* Record the part after the last comma. */
3386 add_preprocessor_option (arg + prev, j - prev);
3388 do_save = false;
3389 break;
3391 case OPT_Wl_:
3393 int prev, j;
3394 /* Split the argument at commas. */
3395 prev = 0;
3396 for (j = 0; arg[j]; j++)
3397 if (arg[j] == ',')
3399 add_infile (save_string (arg + prev, j - prev), "*");
3400 prev = j + 1;
3402 /* Record the part after the last comma. */
3403 add_infile (arg + prev, "*");
3405 do_save = false;
3406 break;
3408 case OPT_Xlinker:
3409 add_infile (arg, "*");
3410 do_save = false;
3411 break;
3413 case OPT_Xpreprocessor:
3414 add_preprocessor_option (arg, strlen (arg));
3415 do_save = false;
3416 break;
3418 case OPT_Xassembler:
3419 add_assembler_option (arg, strlen (arg));
3420 do_save = false;
3421 break;
3423 case OPT_l:
3424 /* POSIX allows separation of -l and the lib arg; canonicalize
3425 by concatenating -l with its arg */
3426 add_infile (concat ("-l", arg, NULL), "*");
3427 do_save = false;
3428 break;
3430 case OPT_L:
3431 /* Similarly, canonicalize -L for linkers that may not accept
3432 separate arguments. */
3433 save_switch (concat ("-L", arg, NULL), 0, NULL, validated, true);
3434 return true;
3436 case OPT_F:
3437 /* Likewise -F. */
3438 save_switch (concat ("-F", arg, NULL), 0, NULL, validated, true);
3439 return true;
3441 case OPT_save_temps:
3442 save_temps_flag = SAVE_TEMPS_CWD;
3443 validated = true;
3444 break;
3446 case OPT_save_temps_:
3447 if (strcmp (arg, "cwd") == 0)
3448 save_temps_flag = SAVE_TEMPS_CWD;
3449 else if (strcmp (arg, "obj") == 0
3450 || strcmp (arg, "object") == 0)
3451 save_temps_flag = SAVE_TEMPS_OBJ;
3452 else
3453 fatal_error ("%qs is an unknown -save-temps option",
3454 decoded->orig_option_with_args_text);
3455 break;
3457 case OPT_no_canonical_prefixes:
3458 /* Already handled as a special case, so ignored here. */
3459 do_save = false;
3460 break;
3462 case OPT_pipe:
3463 validated = true;
3464 /* These options set the variables specified in common.opt
3465 automatically, but do need to be saved for spec
3466 processing. */
3467 break;
3469 case OPT_specs_:
3471 struct user_specs *user = XNEW (struct user_specs);
3473 user->next = (struct user_specs *) 0;
3474 user->filename = arg;
3475 if (user_specs_tail)
3476 user_specs_tail->next = user;
3477 else
3478 user_specs_head = user;
3479 user_specs_tail = user;
3481 validated = true;
3482 break;
3484 case OPT__sysroot_:
3485 target_system_root = arg;
3486 target_system_root_changed = 1;
3487 do_save = false;
3488 break;
3490 case OPT_time_:
3491 if (report_times_to_file)
3492 fclose (report_times_to_file);
3493 report_times_to_file = fopen (arg, "a");
3494 do_save = false;
3495 break;
3497 case OPT____:
3498 /* "-###"
3499 This is similar to -v except that there is no execution
3500 of the commands and the echoed arguments are quoted. It
3501 is intended for use in shell scripts to capture the
3502 driver-generated command line. */
3503 verbose_only_flag++;
3504 verbose_flag = 1;
3505 do_save = false;
3506 break;
3508 case OPT_B:
3510 size_t len = strlen (arg);
3512 /* Catch the case where the user has forgotten to append a
3513 directory separator to the path. Note, they may be using
3514 -B to add an executable name prefix, eg "i386-elf-", in
3515 order to distinguish between multiple installations of
3516 GCC in the same directory. Hence we must check to see
3517 if appending a directory separator actually makes a
3518 valid directory name. */
3519 if (!IS_DIR_SEPARATOR (arg[len - 1])
3520 && is_directory (arg, false))
3522 char *tmp = XNEWVEC (char, len + 2);
3523 strcpy (tmp, arg);
3524 tmp[len] = DIR_SEPARATOR;
3525 tmp[++len] = 0;
3526 arg = tmp;
3529 add_prefix (&exec_prefixes, arg, NULL,
3530 PREFIX_PRIORITY_B_OPT, 0, 0);
3531 add_prefix (&startfile_prefixes, arg, NULL,
3532 PREFIX_PRIORITY_B_OPT, 0, 0);
3533 add_prefix (&include_prefixes, arg, NULL,
3534 PREFIX_PRIORITY_B_OPT, 0, 0);
3536 validated = true;
3537 break;
3539 case OPT_x:
3540 spec_lang = arg;
3541 if (!strcmp (spec_lang, "none"))
3542 /* Suppress the warning if -xnone comes after the last input
3543 file, because alternate command interfaces like g++ might
3544 find it useful to place -xnone after each input file. */
3545 spec_lang = 0;
3546 else
3547 last_language_n_infiles = n_infiles;
3548 do_save = false;
3549 break;
3551 case OPT_o:
3552 have_o = 1;
3553 #if defined(HAVE_TARGET_EXECUTABLE_SUFFIX) || defined(HAVE_TARGET_OBJECT_SUFFIX)
3554 arg = convert_filename (arg, ! have_c, 0);
3555 #endif
3556 /* Save the output name in case -save-temps=obj was used. */
3557 save_temps_prefix = xstrdup (arg);
3558 /* On some systems, ld cannot handle "-o" without a space. So
3559 split the option from its argument. */
3560 save_switch ("-o", 1, &arg, validated, true);
3561 return true;
3563 case OPT_static_libgcc:
3564 case OPT_shared_libgcc:
3565 case OPT_static_libgfortran:
3566 case OPT_static_libstdc__:
3567 /* These are always valid, since gcc.c itself understands the
3568 first two, gfortranspec.c understands -static-libgfortran and
3569 g++spec.c understands -static-libstdc++ */
3570 validated = true;
3571 break;
3573 default:
3574 /* Various driver options need no special processing at this
3575 point, having been handled in a prescan above or being
3576 handled by specs. */
3577 break;
3580 if (do_save)
3581 save_switch (decoded->canonical_option[0],
3582 decoded->canonical_option_num_elements - 1,
3583 &decoded->canonical_option[1], validated, true);
3584 return true;
3587 /* Put the driver's standard set of option handlers in *HANDLERS. */
3589 static void
3590 set_option_handlers (struct cl_option_handlers *handlers)
3592 handlers->unknown_option_callback = driver_unknown_option_callback;
3593 handlers->wrong_lang_callback = driver_wrong_lang_callback;
3594 handlers->num_handlers = 3;
3595 handlers->handlers[0].handler = driver_handle_option;
3596 handlers->handlers[0].mask = CL_DRIVER;
3597 handlers->handlers[1].handler = common_handle_option;
3598 handlers->handlers[1].mask = CL_COMMON;
3599 handlers->handlers[2].handler = target_handle_option;
3600 handlers->handlers[2].mask = CL_TARGET;
3603 /* Create the vector `switches' and its contents.
3604 Store its length in `n_switches'. */
3606 static void
3607 process_command (unsigned int decoded_options_count,
3608 struct cl_decoded_option *decoded_options)
3610 const char *temp;
3611 char *temp1;
3612 char *tooldir_prefix, *tooldir_prefix2;
3613 char *(*get_relative_prefix) (const char *, const char *,
3614 const char *) = NULL;
3615 struct cl_option_handlers handlers;
3616 unsigned int j;
3618 gcc_exec_prefix = getenv ("GCC_EXEC_PREFIX");
3620 n_switches = 0;
3621 n_infiles = 0;
3622 added_libraries = 0;
3624 /* Figure compiler version from version string. */
3626 compiler_version = temp1 = xstrdup (version_string);
3628 for (; *temp1; ++temp1)
3630 if (*temp1 == ' ')
3632 *temp1 = '\0';
3633 break;
3637 /* Handle any -no-canonical-prefixes flag early, to assign the function
3638 that builds relative prefixes. This function creates default search
3639 paths that are needed later in normal option handling. */
3641 for (j = 1; j < decoded_options_count; j++)
3643 if (decoded_options[j].opt_index == OPT_no_canonical_prefixes)
3645 get_relative_prefix = make_relative_prefix_ignore_links;
3646 break;
3649 if (! get_relative_prefix)
3650 get_relative_prefix = make_relative_prefix;
3652 /* Set up the default search paths. If there is no GCC_EXEC_PREFIX,
3653 see if we can create it from the pathname specified in
3654 decoded_options[0].arg. */
3656 gcc_libexec_prefix = standard_libexec_prefix;
3657 #ifndef VMS
3658 /* FIXME: make_relative_prefix doesn't yet work for VMS. */
3659 if (!gcc_exec_prefix)
3661 gcc_exec_prefix = get_relative_prefix (decoded_options[0].arg,
3662 standard_bindir_prefix,
3663 standard_exec_prefix);
3664 gcc_libexec_prefix = get_relative_prefix (decoded_options[0].arg,
3665 standard_bindir_prefix,
3666 standard_libexec_prefix);
3667 if (gcc_exec_prefix)
3668 xputenv (concat ("GCC_EXEC_PREFIX=", gcc_exec_prefix, NULL));
3670 else
3672 /* make_relative_prefix requires a program name, but
3673 GCC_EXEC_PREFIX is typically a directory name with a trailing
3674 / (which is ignored by make_relative_prefix), so append a
3675 program name. */
3676 char *tmp_prefix = concat (gcc_exec_prefix, "gcc", NULL);
3677 gcc_libexec_prefix = get_relative_prefix (tmp_prefix,
3678 standard_exec_prefix,
3679 standard_libexec_prefix);
3681 /* The path is unrelocated, so fallback to the original setting. */
3682 if (!gcc_libexec_prefix)
3683 gcc_libexec_prefix = standard_libexec_prefix;
3685 free (tmp_prefix);
3687 #else
3688 #endif
3689 /* From this point onward, gcc_exec_prefix is non-null if the toolchain
3690 is relocated. The toolchain was either relocated using GCC_EXEC_PREFIX
3691 or an automatically created GCC_EXEC_PREFIX from
3692 decoded_options[0].arg. */
3694 /* Do language-specific adjustment/addition of flags. */
3695 lang_specific_driver (&decoded_options, &decoded_options_count,
3696 &added_libraries);
3698 if (gcc_exec_prefix)
3700 int len = strlen (gcc_exec_prefix);
3702 if (len > (int) sizeof ("/lib/gcc/") - 1
3703 && (IS_DIR_SEPARATOR (gcc_exec_prefix[len-1])))
3705 temp = gcc_exec_prefix + len - sizeof ("/lib/gcc/") + 1;
3706 if (IS_DIR_SEPARATOR (*temp)
3707 && filename_ncmp (temp + 1, "lib", 3) == 0
3708 && IS_DIR_SEPARATOR (temp[4])
3709 && filename_ncmp (temp + 5, "gcc", 3) == 0)
3710 len -= sizeof ("/lib/gcc/") - 1;
3713 set_std_prefix (gcc_exec_prefix, len);
3714 add_prefix (&exec_prefixes, gcc_libexec_prefix, "GCC",
3715 PREFIX_PRIORITY_LAST, 0, 0);
3716 add_prefix (&startfile_prefixes, gcc_exec_prefix, "GCC",
3717 PREFIX_PRIORITY_LAST, 0, 0);
3720 /* COMPILER_PATH and LIBRARY_PATH have values
3721 that are lists of directory names with colons. */
3723 temp = getenv ("COMPILER_PATH");
3724 if (temp)
3726 const char *startp, *endp;
3727 char *nstore = (char *) alloca (strlen (temp) + 3);
3729 startp = endp = temp;
3730 while (1)
3732 if (*endp == PATH_SEPARATOR || *endp == 0)
3734 strncpy (nstore, startp, endp - startp);
3735 if (endp == startp)
3736 strcpy (nstore, concat (".", dir_separator_str, NULL));
3737 else if (!IS_DIR_SEPARATOR (endp[-1]))
3739 nstore[endp - startp] = DIR_SEPARATOR;
3740 nstore[endp - startp + 1] = 0;
3742 else
3743 nstore[endp - startp] = 0;
3744 add_prefix (&exec_prefixes, nstore, 0,
3745 PREFIX_PRIORITY_LAST, 0, 0);
3746 add_prefix (&include_prefixes, nstore, 0,
3747 PREFIX_PRIORITY_LAST, 0, 0);
3748 if (*endp == 0)
3749 break;
3750 endp = startp = endp + 1;
3752 else
3753 endp++;
3757 temp = getenv (LIBRARY_PATH_ENV);
3758 if (temp && *cross_compile == '0')
3760 const char *startp, *endp;
3761 char *nstore = (char *) alloca (strlen (temp) + 3);
3763 startp = endp = temp;
3764 while (1)
3766 if (*endp == PATH_SEPARATOR || *endp == 0)
3768 strncpy (nstore, startp, endp - startp);
3769 if (endp == startp)
3770 strcpy (nstore, concat (".", dir_separator_str, NULL));
3771 else if (!IS_DIR_SEPARATOR (endp[-1]))
3773 nstore[endp - startp] = DIR_SEPARATOR;
3774 nstore[endp - startp + 1] = 0;
3776 else
3777 nstore[endp - startp] = 0;
3778 add_prefix (&startfile_prefixes, nstore, NULL,
3779 PREFIX_PRIORITY_LAST, 0, 1);
3780 if (*endp == 0)
3781 break;
3782 endp = startp = endp + 1;
3784 else
3785 endp++;
3789 /* Use LPATH like LIBRARY_PATH (for the CMU build program). */
3790 temp = getenv ("LPATH");
3791 if (temp && *cross_compile == '0')
3793 const char *startp, *endp;
3794 char *nstore = (char *) alloca (strlen (temp) + 3);
3796 startp = endp = temp;
3797 while (1)
3799 if (*endp == PATH_SEPARATOR || *endp == 0)
3801 strncpy (nstore, startp, endp - startp);
3802 if (endp == startp)
3803 strcpy (nstore, concat (".", dir_separator_str, NULL));
3804 else if (!IS_DIR_SEPARATOR (endp[-1]))
3806 nstore[endp - startp] = DIR_SEPARATOR;
3807 nstore[endp - startp + 1] = 0;
3809 else
3810 nstore[endp - startp] = 0;
3811 add_prefix (&startfile_prefixes, nstore, NULL,
3812 PREFIX_PRIORITY_LAST, 0, 1);
3813 if (*endp == 0)
3814 break;
3815 endp = startp = endp + 1;
3817 else
3818 endp++;
3822 /* Process the options and store input files and switches in their
3823 vectors. */
3825 last_language_n_infiles = -1;
3827 set_option_handlers (&handlers);
3829 for (j = 1; j < decoded_options_count; j++)
3831 switch (decoded_options[j].opt_index)
3833 case OPT_S:
3834 case OPT_c:
3835 case OPT_E:
3836 have_c = 1;
3837 break;
3839 if (have_c)
3840 break;
3843 for (j = 1; j < decoded_options_count; j++)
3845 if (decoded_options[j].opt_index == OPT_SPECIAL_input_file)
3847 const char *arg = decoded_options[j].arg;
3848 const char *p = strrchr (arg, '@');
3849 char *fname;
3850 long offset;
3851 int consumed;
3852 #ifdef HAVE_TARGET_OBJECT_SUFFIX
3853 arg = convert_filename (arg, 0, access (arg, F_OK));
3854 #endif
3855 /* For LTO static archive support we handle input file
3856 specifications that are composed of a filename and
3857 an offset like FNAME@OFFSET. */
3858 if (p
3859 && p != arg
3860 && sscanf (p, "@%li%n", &offset, &consumed) >= 1
3861 && strlen (p) == (unsigned int)consumed)
3863 fname = (char *)xmalloc (p - arg + 1);
3864 memcpy (fname, arg, p - arg);
3865 fname[p - arg] = '\0';
3866 /* Only accept non-stdin and existing FNAME parts, otherwise
3867 try with the full name. */
3868 if (strcmp (fname, "-") == 0 || access (fname, F_OK) < 0)
3870 free (fname);
3871 fname = xstrdup (arg);
3874 else
3875 fname = xstrdup (arg);
3877 if (strcmp (fname, "-") != 0 && access (fname, F_OK) < 0)
3878 perror_with_name (fname);
3879 else
3880 add_infile (arg, spec_lang);
3882 free (fname);
3883 continue;
3886 read_cmdline_option (&global_options, &global_options_set,
3887 decoded_options + j, UNKNOWN_LOCATION,
3888 CL_DRIVER, &handlers, global_dc);
3891 /* If -save-temps=obj and -o name, create the prefix to use for %b.
3892 Otherwise just make -save-temps=obj the same as -save-temps=cwd. */
3893 if (save_temps_flag == SAVE_TEMPS_OBJ && save_temps_prefix != NULL)
3895 save_temps_length = strlen (save_temps_prefix);
3896 temp = strrchr (lbasename (save_temps_prefix), '.');
3897 if (temp)
3899 save_temps_length -= strlen (temp);
3900 save_temps_prefix[save_temps_length] = '\0';
3904 else if (save_temps_prefix != NULL)
3906 free (save_temps_prefix);
3907 save_temps_prefix = NULL;
3910 if (save_temps_flag && use_pipes)
3912 /* -save-temps overrides -pipe, so that temp files are produced */
3913 if (save_temps_flag)
3914 warning (0, "-pipe ignored because -save-temps specified");
3915 use_pipes = 0;
3918 if (!compare_debug)
3920 const char *gcd = getenv ("GCC_COMPARE_DEBUG");
3922 if (gcd && gcd[0] == '-')
3924 compare_debug = 2;
3925 compare_debug_opt = gcd;
3927 else if (gcd && *gcd && strcmp (gcd, "0"))
3929 compare_debug = 3;
3930 compare_debug_opt = "-gtoggle";
3933 else if (compare_debug < 0)
3935 compare_debug = 0;
3936 gcc_assert (!compare_debug_opt);
3939 /* Set up the search paths. We add directories that we expect to
3940 contain GNU Toolchain components before directories specified by
3941 the machine description so that we will find GNU components (like
3942 the GNU assembler) before those of the host system. */
3944 /* If we don't know where the toolchain has been installed, use the
3945 configured-in locations. */
3946 if (!gcc_exec_prefix)
3948 #ifndef OS2
3949 add_prefix (&exec_prefixes, standard_libexec_prefix, "GCC",
3950 PREFIX_PRIORITY_LAST, 1, 0);
3951 add_prefix (&exec_prefixes, standard_libexec_prefix, "BINUTILS",
3952 PREFIX_PRIORITY_LAST, 2, 0);
3953 add_prefix (&exec_prefixes, standard_exec_prefix, "BINUTILS",
3954 PREFIX_PRIORITY_LAST, 2, 0);
3955 #endif
3956 add_prefix (&startfile_prefixes, standard_exec_prefix, "BINUTILS",
3957 PREFIX_PRIORITY_LAST, 1, 0);
3960 gcc_assert (!IS_ABSOLUTE_PATH (tooldir_base_prefix));
3961 tooldir_prefix2 = concat (tooldir_base_prefix, spec_machine,
3962 dir_separator_str, NULL);
3964 /* Look for tools relative to the location from which the driver is
3965 running, or, if that is not available, the configured prefix. */
3966 tooldir_prefix
3967 = concat (gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
3968 spec_machine, dir_separator_str,
3969 spec_version, dir_separator_str, tooldir_prefix2, NULL);
3970 free (tooldir_prefix2);
3972 add_prefix (&exec_prefixes,
3973 concat (tooldir_prefix, "bin", dir_separator_str, NULL),
3974 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 0);
3975 add_prefix (&startfile_prefixes,
3976 concat (tooldir_prefix, "lib", dir_separator_str, NULL),
3977 "BINUTILS", PREFIX_PRIORITY_LAST, 0, 1);
3978 free (tooldir_prefix);
3980 #if defined(TARGET_SYSTEM_ROOT_RELOCATABLE) && !defined(VMS)
3981 /* If the normal TARGET_SYSTEM_ROOT is inside of $exec_prefix,
3982 then consider it to relocate with the rest of the GCC installation
3983 if GCC_EXEC_PREFIX is set.
3984 ``make_relative_prefix'' is not compiled for VMS, so don't call it. */
3985 if (target_system_root && !target_system_root_changed && gcc_exec_prefix)
3987 char *tmp_prefix = get_relative_prefix (decoded_options[0].arg,
3988 standard_bindir_prefix,
3989 target_system_root);
3990 if (tmp_prefix && access_check (tmp_prefix, F_OK) == 0)
3992 target_system_root = tmp_prefix;
3993 target_system_root_changed = 1;
3996 #endif
3998 /* More prefixes are enabled in main, after we read the specs file
3999 and determine whether this is cross-compilation or not. */
4001 if (n_infiles == last_language_n_infiles && spec_lang != 0)
4002 warning (0, "%<-x %s%> after last input file has no effect", spec_lang);
4004 /* Synthesize -fcompare-debug flag from the GCC_COMPARE_DEBUG
4005 environment variable. */
4006 if (compare_debug == 2 || compare_debug == 3)
4008 const char *opt = concat ("-fcompare-debug=", compare_debug_opt, NULL);
4009 save_switch (opt, 0, NULL, false, true);
4010 compare_debug = 1;
4013 /* Ensure we only invoke each subprocess once. */
4014 if (print_subprocess_help || print_help_list || print_version)
4016 n_infiles = 0;
4018 /* Create a dummy input file, so that we can pass
4019 the help option on to the various sub-processes. */
4020 add_infile ("help-dummy", "c");
4023 alloc_switch ();
4024 switches[n_switches].part1 = 0;
4025 alloc_infile ();
4026 infiles[n_infiles].name = 0;
4029 /* Store switches not filtered out by %<S in spec in COLLECT_GCC_OPTIONS
4030 and place that in the environment. */
4032 static void
4033 set_collect_gcc_options (void)
4035 int i;
4036 int first_time;
4038 /* Build COLLECT_GCC_OPTIONS to have all of the options specified to
4039 the compiler. */
4040 obstack_grow (&collect_obstack, "COLLECT_GCC_OPTIONS=",
4041 sizeof ("COLLECT_GCC_OPTIONS=") - 1);
4043 first_time = TRUE;
4044 for (i = 0; (int) i < n_switches; i++)
4046 const char *const *args;
4047 const char *p, *q;
4048 if (!first_time)
4049 obstack_grow (&collect_obstack, " ", 1);
4051 first_time = FALSE;
4053 /* Ignore elided switches. */
4054 if ((switches[i].live_cond
4055 & (SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC))
4056 == SWITCH_IGNORE)
4057 continue;
4059 obstack_grow (&collect_obstack, "'-", 2);
4060 q = switches[i].part1;
4061 while ((p = strchr (q, '\'')))
4063 obstack_grow (&collect_obstack, q, p - q);
4064 obstack_grow (&collect_obstack, "'\\''", 4);
4065 q = ++p;
4067 obstack_grow (&collect_obstack, q, strlen (q));
4068 obstack_grow (&collect_obstack, "'", 1);
4070 for (args = switches[i].args; args && *args; args++)
4072 obstack_grow (&collect_obstack, " '", 2);
4073 q = *args;
4074 while ((p = strchr (q, '\'')))
4076 obstack_grow (&collect_obstack, q, p - q);
4077 obstack_grow (&collect_obstack, "'\\''", 4);
4078 q = ++p;
4080 obstack_grow (&collect_obstack, q, strlen (q));
4081 obstack_grow (&collect_obstack, "'", 1);
4084 obstack_grow (&collect_obstack, "\0", 1);
4085 xputenv (XOBFINISH (&collect_obstack, char *));
4088 /* Process a spec string, accumulating and running commands. */
4090 /* These variables describe the input file name.
4091 input_file_number is the index on outfiles of this file,
4092 so that the output file name can be stored for later use by %o.
4093 input_basename is the start of the part of the input file
4094 sans all directory names, and basename_length is the number
4095 of characters starting there excluding the suffix .c or whatever. */
4097 static const char *gcc_input_filename;
4098 static int input_file_number;
4099 size_t input_filename_length;
4100 static int basename_length;
4101 static int suffixed_basename_length;
4102 static const char *input_basename;
4103 static const char *input_suffix;
4104 #ifndef HOST_LACKS_INODE_NUMBERS
4105 static struct stat input_stat;
4106 #endif
4107 static int input_stat_set;
4109 /* The compiler used to process the current input file. */
4110 static struct compiler *input_file_compiler;
4112 /* These are variables used within do_spec and do_spec_1. */
4114 /* Nonzero if an arg has been started and not yet terminated
4115 (with space, tab or newline). */
4116 static int arg_going;
4118 /* Nonzero means %d or %g has been seen; the next arg to be terminated
4119 is a temporary file name. */
4120 static int delete_this_arg;
4122 /* Nonzero means %w has been seen; the next arg to be terminated
4123 is the output file name of this compilation. */
4124 static int this_is_output_file;
4126 /* Nonzero means %s has been seen; the next arg to be terminated
4127 is the name of a library file and we should try the standard
4128 search dirs for it. */
4129 static int this_is_library_file;
4131 /* Nonzero means %T has been seen; the next arg to be terminated
4132 is the name of a linker script and we should try all of the
4133 standard search dirs for it. If it is found insert a --script
4134 command line switch and then substitute the full path in place,
4135 otherwise generate an error message. */
4136 static int this_is_linker_script;
4138 /* Nonzero means that the input of this command is coming from a pipe. */
4139 static int input_from_pipe;
4141 /* Nonnull means substitute this for any suffix when outputting a switches
4142 arguments. */
4143 static const char *suffix_subst;
4145 /* If there is an argument being accumulated, terminate it and store it. */
4147 static void
4148 end_going_arg (void)
4150 if (arg_going)
4152 const char *string;
4154 obstack_1grow (&obstack, 0);
4155 string = XOBFINISH (&obstack, const char *);
4156 if (this_is_library_file)
4157 string = find_file (string);
4158 if (this_is_linker_script)
4160 char * full_script_path = find_a_file (&startfile_prefixes, string, R_OK, true);
4162 if (full_script_path == NULL)
4164 error ("unable to locate default linker script %qs in the library search paths", string);
4165 /* Script was not found on search path. */
4166 return;
4168 store_arg ("--script", false, false);
4169 string = full_script_path;
4171 store_arg (string, delete_this_arg, this_is_output_file);
4172 if (this_is_output_file)
4173 outfiles[input_file_number] = string;
4174 arg_going = 0;
4179 /* Parse the WRAPPER string which is a comma separated list of the command line
4180 and insert them into the beginning of argbuf. */
4182 static void
4183 insert_wrapper (const char *wrapper)
4185 int n = 0;
4186 int i;
4187 char *buf = xstrdup (wrapper);
4188 char *p = buf;
4189 unsigned int old_length = VEC_length (const_char_p, argbuf);
4193 n++;
4194 while (*p == ',')
4195 p++;
4197 while ((p = strchr (p, ',')) != NULL);
4199 VEC_safe_grow (const_char_p, heap, argbuf, old_length + n);
4200 memmove (VEC_address (const_char_p, argbuf) + n,
4201 VEC_address (const_char_p, argbuf),
4202 old_length * sizeof (const_char_p));
4204 i = 0;
4205 p = buf;
4208 while (*p == ',')
4210 *p = 0;
4211 p++;
4213 VEC_replace (const_char_p, argbuf, i, p);
4214 i++;
4216 while ((p = strchr (p, ',')) != NULL);
4217 gcc_assert (i == n);
4220 /* Process the spec SPEC and run the commands specified therein.
4221 Returns 0 if the spec is successfully processed; -1 if failed. */
4224 do_spec (const char *spec)
4226 int value;
4228 value = do_spec_2 (spec);
4230 /* Force out any unfinished command.
4231 If -pipe, this forces out the last command if it ended in `|'. */
4232 if (value == 0)
4234 if (VEC_length (const_char_p, argbuf) > 0
4235 && !strcmp (VEC_last (const_char_p, argbuf), "|"))
4236 VEC_pop (const_char_p, argbuf);
4238 set_collect_gcc_options ();
4240 if (VEC_length (const_char_p, argbuf) > 0)
4241 value = execute ();
4244 return value;
4247 static int
4248 do_spec_2 (const char *spec)
4250 int result;
4252 clear_args ();
4253 arg_going = 0;
4254 delete_this_arg = 0;
4255 this_is_output_file = 0;
4256 this_is_library_file = 0;
4257 this_is_linker_script = 0;
4258 input_from_pipe = 0;
4259 suffix_subst = NULL;
4261 result = do_spec_1 (spec, 0, NULL);
4263 end_going_arg ();
4265 return result;
4269 /* Process the given spec string and add any new options to the end
4270 of the switches/n_switches array. */
4272 static void
4273 do_option_spec (const char *name, const char *spec)
4275 unsigned int i, value_count, value_len;
4276 const char *p, *q, *value;
4277 char *tmp_spec, *tmp_spec_p;
4279 if (configure_default_options[0].name == NULL)
4280 return;
4282 for (i = 0; i < ARRAY_SIZE (configure_default_options); i++)
4283 if (strcmp (configure_default_options[i].name, name) == 0)
4284 break;
4285 if (i == ARRAY_SIZE (configure_default_options))
4286 return;
4288 value = configure_default_options[i].value;
4289 value_len = strlen (value);
4291 /* Compute the size of the final spec. */
4292 value_count = 0;
4293 p = spec;
4294 while ((p = strstr (p, "%(VALUE)")) != NULL)
4296 p ++;
4297 value_count ++;
4300 /* Replace each %(VALUE) by the specified value. */
4301 tmp_spec = (char *) alloca (strlen (spec) + 1
4302 + value_count * (value_len - strlen ("%(VALUE)")));
4303 tmp_spec_p = tmp_spec;
4304 q = spec;
4305 while ((p = strstr (q, "%(VALUE)")) != NULL)
4307 memcpy (tmp_spec_p, q, p - q);
4308 tmp_spec_p = tmp_spec_p + (p - q);
4309 memcpy (tmp_spec_p, value, value_len);
4310 tmp_spec_p += value_len;
4311 q = p + strlen ("%(VALUE)");
4313 strcpy (tmp_spec_p, q);
4315 do_self_spec (tmp_spec);
4318 /* Process the given spec string and add any new options to the end
4319 of the switches/n_switches array. */
4321 static void
4322 do_self_spec (const char *spec)
4324 int i;
4326 do_spec_2 (spec);
4327 do_spec_1 (" ", 0, NULL);
4329 /* Mark %<S switches processed by do_self_spec to be ignored permanently.
4330 do_self_specs adds the replacements to switches array, so it shouldn't
4331 be processed afterwards. */
4332 for (i = 0; i < n_switches; i++)
4333 if ((switches[i].live_cond & SWITCH_IGNORE))
4334 switches[i].live_cond |= SWITCH_IGNORE_PERMANENTLY;
4336 if (VEC_length (const_char_p, argbuf) > 0)
4338 const char **argbuf_copy;
4339 struct cl_decoded_option *decoded_options;
4340 struct cl_option_handlers handlers;
4341 unsigned int decoded_options_count;
4342 unsigned int j;
4344 /* Create a copy of argbuf with a dummy argv[0] entry for
4345 decode_cmdline_options_to_array. */
4346 argbuf_copy = XNEWVEC (const char *,
4347 VEC_length (const_char_p, argbuf) + 1);
4348 argbuf_copy[0] = "";
4349 memcpy (argbuf_copy + 1, VEC_address (const_char_p, argbuf),
4350 VEC_length (const_char_p, argbuf) * sizeof (const char *));
4352 decode_cmdline_options_to_array (VEC_length (const_char_p, argbuf) + 1,
4353 argbuf_copy,
4354 CL_DRIVER, &decoded_options,
4355 &decoded_options_count);
4356 free (argbuf_copy);
4358 set_option_handlers (&handlers);
4360 for (j = 1; j < decoded_options_count; j++)
4362 switch (decoded_options[j].opt_index)
4364 case OPT_SPECIAL_input_file:
4365 /* Specs should only generate options, not input
4366 files. */
4367 if (strcmp (decoded_options[j].arg, "-") != 0)
4368 fatal_error ("switch %qs does not start with %<-%>",
4369 decoded_options[j].arg);
4370 else
4371 fatal_error ("spec-generated switch is just %<-%>");
4372 break;
4374 case OPT_fcompare_debug_second:
4375 case OPT_fcompare_debug:
4376 case OPT_fcompare_debug_:
4377 case OPT_o:
4378 /* Avoid duplicate processing of some options from
4379 compare-debug specs; just save them here. */
4380 save_switch (decoded_options[j].canonical_option[0],
4381 (decoded_options[j].canonical_option_num_elements
4382 - 1),
4383 &decoded_options[j].canonical_option[1], false, true);
4384 break;
4386 default:
4387 read_cmdline_option (&global_options, &global_options_set,
4388 decoded_options + j, UNKNOWN_LOCATION,
4389 CL_DRIVER, &handlers, global_dc);
4390 break;
4394 alloc_switch ();
4395 switches[n_switches].part1 = 0;
4399 /* Callback for processing %D and %I specs. */
4401 struct spec_path_info {
4402 const char *option;
4403 const char *append;
4404 size_t append_len;
4405 bool omit_relative;
4406 bool separate_options;
4409 static void *
4410 spec_path (char *path, void *data)
4412 struct spec_path_info *info = (struct spec_path_info *) data;
4413 size_t len = 0;
4414 char save = 0;
4416 if (info->omit_relative && !IS_ABSOLUTE_PATH (path))
4417 return NULL;
4419 if (info->append_len != 0)
4421 len = strlen (path);
4422 memcpy (path + len, info->append, info->append_len + 1);
4425 if (!is_directory (path, true))
4426 return NULL;
4428 do_spec_1 (info->option, 1, NULL);
4429 if (info->separate_options)
4430 do_spec_1 (" ", 0, NULL);
4432 if (info->append_len == 0)
4434 len = strlen (path);
4435 save = path[len - 1];
4436 if (IS_DIR_SEPARATOR (path[len - 1]))
4437 path[len - 1] = '\0';
4440 do_spec_1 (path, 1, NULL);
4441 do_spec_1 (" ", 0, NULL);
4443 /* Must not damage the original path. */
4444 if (info->append_len == 0)
4445 path[len - 1] = save;
4447 return NULL;
4450 /* Create a temporary FILE with the contents of ARGV. Add @FILE to the
4451 argument list. */
4453 static void
4454 create_at_file (char **argv)
4456 char *temp_file = make_temp_file ("");
4457 char *at_argument = concat ("@", temp_file, NULL);
4458 FILE *f = fopen (temp_file, "w");
4459 int status;
4461 if (f == NULL)
4462 fatal_error ("could not open temporary response file %s",
4463 temp_file);
4465 status = writeargv (argv, f);
4467 if (status)
4468 fatal_error ("could not write to temporary response file %s",
4469 temp_file);
4471 status = fclose (f);
4473 if (EOF == status)
4474 fatal_error ("could not close temporary response file %s",
4475 temp_file);
4477 store_arg (at_argument, 0, 0);
4479 record_temp_file (temp_file, !save_temps_flag, !save_temps_flag);
4482 /* True if we should compile INFILE. */
4484 static bool
4485 compile_input_file_p (struct infile *infile)
4487 if ((!infile->language) || (infile->language[0] != '*'))
4488 if (infile->incompiler == input_file_compiler)
4489 return true;
4490 return false;
4493 /* Process each member of VEC as a spec. */
4495 static void
4496 do_specs_vec (VEC(char_p,heap) *vec)
4498 unsigned ix;
4499 char *opt;
4501 FOR_EACH_VEC_ELT (char_p, vec, ix, opt)
4503 do_spec_1 (opt, 1, NULL);
4504 /* Make each accumulated option a separate argument. */
4505 do_spec_1 (" ", 0, NULL);
4509 /* Process the sub-spec SPEC as a portion of a larger spec.
4510 This is like processing a whole spec except that we do
4511 not initialize at the beginning and we do not supply a
4512 newline by default at the end.
4513 INSWITCH nonzero means don't process %-sequences in SPEC;
4514 in this case, % is treated as an ordinary character.
4515 This is used while substituting switches.
4516 INSWITCH nonzero also causes SPC not to terminate an argument.
4518 Value is zero unless a line was finished
4519 and the command on that line reported an error. */
4521 static int
4522 do_spec_1 (const char *spec, int inswitch, const char *soft_matched_part)
4524 const char *p = spec;
4525 int c;
4526 int i;
4527 int value;
4529 /* If it's an empty string argument to a switch, keep it as is. */
4530 if (inswitch && !*p)
4531 arg_going = 1;
4533 while ((c = *p++))
4534 /* If substituting a switch, treat all chars like letters.
4535 Otherwise, NL, SPC, TAB and % are special. */
4536 switch (inswitch ? 'a' : c)
4538 case '\n':
4539 end_going_arg ();
4541 if (VEC_length (const_char_p, argbuf) > 0
4542 && !strcmp (VEC_last (const_char_p, argbuf), "|"))
4544 /* A `|' before the newline means use a pipe here,
4545 but only if -pipe was specified.
4546 Otherwise, execute now and don't pass the `|' as an arg. */
4547 if (use_pipes)
4549 input_from_pipe = 1;
4550 break;
4552 else
4553 VEC_pop (const_char_p, argbuf);
4556 set_collect_gcc_options ();
4558 if (VEC_length (const_char_p, argbuf) > 0)
4560 value = execute ();
4561 if (value)
4562 return value;
4564 /* Reinitialize for a new command, and for a new argument. */
4565 clear_args ();
4566 arg_going = 0;
4567 delete_this_arg = 0;
4568 this_is_output_file = 0;
4569 this_is_library_file = 0;
4570 this_is_linker_script = 0;
4571 input_from_pipe = 0;
4572 break;
4574 case '|':
4575 end_going_arg ();
4577 /* Use pipe */
4578 obstack_1grow (&obstack, c);
4579 arg_going = 1;
4580 break;
4582 case '\t':
4583 case ' ':
4584 end_going_arg ();
4586 /* Reinitialize for a new argument. */
4587 delete_this_arg = 0;
4588 this_is_output_file = 0;
4589 this_is_library_file = 0;
4590 this_is_linker_script = 0;
4591 break;
4593 case '%':
4594 switch (c = *p++)
4596 case 0:
4597 fatal_error ("spec %qs invalid", spec);
4599 case 'b':
4600 if (save_temps_length)
4601 obstack_grow (&obstack, save_temps_prefix, save_temps_length);
4602 else
4603 obstack_grow (&obstack, input_basename, basename_length);
4604 if (compare_debug < 0)
4605 obstack_grow (&obstack, ".gk", 3);
4606 arg_going = 1;
4607 break;
4609 case 'B':
4610 if (save_temps_length)
4611 obstack_grow (&obstack, save_temps_prefix, save_temps_length);
4612 else
4613 obstack_grow (&obstack, input_basename, suffixed_basename_length);
4614 if (compare_debug < 0)
4615 obstack_grow (&obstack, ".gk", 3);
4616 arg_going = 1;
4617 break;
4619 case 'd':
4620 delete_this_arg = 2;
4621 break;
4623 /* Dump out the directories specified with LIBRARY_PATH,
4624 followed by the absolute directories
4625 that we search for startfiles. */
4626 case 'D':
4628 struct spec_path_info info;
4630 info.option = "-L";
4631 info.append_len = 0;
4632 #ifdef RELATIVE_PREFIX_NOT_LINKDIR
4633 /* Used on systems which record the specified -L dirs
4634 and use them to search for dynamic linking.
4635 Relative directories always come from -B,
4636 and it is better not to use them for searching
4637 at run time. In particular, stage1 loses. */
4638 info.omit_relative = true;
4639 #else
4640 info.omit_relative = false;
4641 #endif
4642 info.separate_options = false;
4644 for_each_path (&startfile_prefixes, true, 0, spec_path, &info);
4646 break;
4648 case 'e':
4649 /* %efoo means report an error with `foo' as error message
4650 and don't execute any more commands for this file. */
4652 const char *q = p;
4653 char *buf;
4654 while (*p != 0 && *p != '\n')
4655 p++;
4656 buf = (char *) alloca (p - q + 1);
4657 strncpy (buf, q, p - q);
4658 buf[p - q] = 0;
4659 error ("%s", _(buf));
4660 return -1;
4662 break;
4663 case 'n':
4664 /* %nfoo means report a notice with `foo' on stderr. */
4666 const char *q = p;
4667 char *buf;
4668 while (*p != 0 && *p != '\n')
4669 p++;
4670 buf = (char *) alloca (p - q + 1);
4671 strncpy (buf, q, p - q);
4672 buf[p - q] = 0;
4673 inform (0, "%s", _(buf));
4674 if (*p)
4675 p++;
4677 break;
4679 case 'j':
4681 struct stat st;
4683 /* If save_temps_flag is off, and the HOST_BIT_BUCKET is
4684 defined, and it is not a directory, and it is
4685 writable, use it. Otherwise, treat this like any
4686 other temporary file. */
4688 if ((!save_temps_flag)
4689 && (stat (HOST_BIT_BUCKET, &st) == 0) && (!S_ISDIR (st.st_mode))
4690 && (access (HOST_BIT_BUCKET, W_OK) == 0))
4692 obstack_grow (&obstack, HOST_BIT_BUCKET,
4693 strlen (HOST_BIT_BUCKET));
4694 delete_this_arg = 0;
4695 arg_going = 1;
4696 break;
4699 goto create_temp_file;
4700 case '|':
4701 if (use_pipes)
4703 obstack_1grow (&obstack, '-');
4704 delete_this_arg = 0;
4705 arg_going = 1;
4707 /* consume suffix */
4708 while (*p == '.' || ISALNUM ((unsigned char) *p))
4709 p++;
4710 if (p[0] == '%' && p[1] == 'O')
4711 p += 2;
4713 break;
4715 goto create_temp_file;
4716 case 'm':
4717 if (use_pipes)
4719 /* consume suffix */
4720 while (*p == '.' || ISALNUM ((unsigned char) *p))
4721 p++;
4722 if (p[0] == '%' && p[1] == 'O')
4723 p += 2;
4725 break;
4727 goto create_temp_file;
4728 case 'g':
4729 case 'u':
4730 case 'U':
4731 create_temp_file:
4733 struct temp_name *t;
4734 int suffix_length;
4735 const char *suffix = p;
4736 char *saved_suffix = NULL;
4738 while (*p == '.' || ISALNUM ((unsigned char) *p))
4739 p++;
4740 suffix_length = p - suffix;
4741 if (p[0] == '%' && p[1] == 'O')
4743 p += 2;
4744 /* We don't support extra suffix characters after %O. */
4745 if (*p == '.' || ISALNUM ((unsigned char) *p))
4746 fatal_error ("spec %qs has invalid %<%%0%c%>", spec, *p);
4747 if (suffix_length == 0)
4748 suffix = TARGET_OBJECT_SUFFIX;
4749 else
4751 saved_suffix
4752 = XNEWVEC (char, suffix_length
4753 + strlen (TARGET_OBJECT_SUFFIX));
4754 strncpy (saved_suffix, suffix, suffix_length);
4755 strcpy (saved_suffix + suffix_length,
4756 TARGET_OBJECT_SUFFIX);
4758 suffix_length += strlen (TARGET_OBJECT_SUFFIX);
4761 if (compare_debug < 0)
4763 suffix = concat (".gk", suffix, NULL);
4764 suffix_length += 3;
4767 /* If -save-temps=obj and -o were specified, use that for the
4768 temp file. */
4769 if (save_temps_length)
4771 char *tmp;
4772 temp_filename_length
4773 = save_temps_length + suffix_length + 1;
4774 tmp = (char *) alloca (temp_filename_length);
4775 memcpy (tmp, save_temps_prefix, save_temps_length);
4776 memcpy (tmp + save_temps_length, suffix, suffix_length);
4777 tmp[save_temps_length + suffix_length] = '\0';
4778 temp_filename = save_string (tmp, save_temps_length
4779 + suffix_length);
4780 obstack_grow (&obstack, temp_filename,
4781 temp_filename_length);
4782 arg_going = 1;
4783 delete_this_arg = 0;
4784 break;
4787 /* If the gcc_input_filename has the same suffix specified
4788 for the %g, %u, or %U, and -save-temps is specified,
4789 we could end up using that file as an intermediate
4790 thus clobbering the user's source file (.e.g.,
4791 gcc -save-temps foo.s would clobber foo.s with the
4792 output of cpp0). So check for this condition and
4793 generate a temp file as the intermediate. */
4795 if (save_temps_flag)
4797 char *tmp;
4798 temp_filename_length = basename_length + suffix_length + 1;
4799 tmp = (char *) alloca (temp_filename_length);
4800 memcpy (tmp, input_basename, basename_length);
4801 memcpy (tmp + basename_length, suffix, suffix_length);
4802 tmp[basename_length + suffix_length] = '\0';
4803 temp_filename = tmp;
4805 if (filename_cmp (temp_filename, gcc_input_filename) != 0)
4807 #ifndef HOST_LACKS_INODE_NUMBERS
4808 struct stat st_temp;
4810 /* Note, set_input() resets input_stat_set to 0. */
4811 if (input_stat_set == 0)
4813 input_stat_set = stat (gcc_input_filename,
4814 &input_stat);
4815 if (input_stat_set >= 0)
4816 input_stat_set = 1;
4819 /* If we have the stat for the gcc_input_filename
4820 and we can do the stat for the temp_filename
4821 then the they could still refer to the same
4822 file if st_dev/st_ino's are the same. */
4823 if (input_stat_set != 1
4824 || stat (temp_filename, &st_temp) < 0
4825 || input_stat.st_dev != st_temp.st_dev
4826 || input_stat.st_ino != st_temp.st_ino)
4827 #else
4828 /* Just compare canonical pathnames. */
4829 char* input_realname = lrealpath (gcc_input_filename);
4830 char* temp_realname = lrealpath (temp_filename);
4831 bool files_differ = filename_cmp (input_realname, temp_realname);
4832 free (input_realname);
4833 free (temp_realname);
4834 if (files_differ)
4835 #endif
4837 temp_filename = save_string (temp_filename,
4838 temp_filename_length + 1);
4839 obstack_grow (&obstack, temp_filename,
4840 temp_filename_length);
4841 arg_going = 1;
4842 delete_this_arg = 0;
4843 break;
4848 /* See if we already have an association of %g/%u/%U and
4849 suffix. */
4850 for (t = temp_names; t; t = t->next)
4851 if (t->length == suffix_length
4852 && strncmp (t->suffix, suffix, suffix_length) == 0
4853 && t->unique == (c == 'u' || c == 'U' || c == 'j'))
4854 break;
4856 /* Make a new association if needed. %u and %j
4857 require one. */
4858 if (t == 0 || c == 'u' || c == 'j')
4860 if (t == 0)
4862 t = XNEW (struct temp_name);
4863 t->next = temp_names;
4864 temp_names = t;
4866 t->length = suffix_length;
4867 if (saved_suffix)
4869 t->suffix = saved_suffix;
4870 saved_suffix = NULL;
4872 else
4873 t->suffix = save_string (suffix, suffix_length);
4874 t->unique = (c == 'u' || c == 'U' || c == 'j');
4875 temp_filename = make_temp_file (t->suffix);
4876 temp_filename_length = strlen (temp_filename);
4877 t->filename = temp_filename;
4878 t->filename_length = temp_filename_length;
4881 free (saved_suffix);
4883 obstack_grow (&obstack, t->filename, t->filename_length);
4884 delete_this_arg = 1;
4886 arg_going = 1;
4887 break;
4889 case 'i':
4890 if (combine_inputs)
4892 if (at_file_supplied)
4894 /* We are going to expand `%i' to `@FILE', where FILE
4895 is a newly-created temporary filename. The filenames
4896 that would usually be expanded in place of %o will be
4897 written to the temporary file. */
4898 char **argv;
4899 int n_files = 0;
4900 int j;
4902 for (i = 0; i < n_infiles; i++)
4903 if (compile_input_file_p (&infiles[i]))
4904 n_files++;
4906 argv = (char **) alloca (sizeof (char *) * (n_files + 1));
4908 /* Copy the strings over. */
4909 for (i = 0, j = 0; i < n_infiles; i++)
4910 if (compile_input_file_p (&infiles[i]))
4912 argv[j] = CONST_CAST (char *, infiles[i].name);
4913 infiles[i].compiled = true;
4914 j++;
4916 argv[j] = NULL;
4918 create_at_file (argv);
4920 else
4921 for (i = 0; (int) i < n_infiles; i++)
4922 if (compile_input_file_p (&infiles[i]))
4924 store_arg (infiles[i].name, 0, 0);
4925 infiles[i].compiled = true;
4928 else
4930 obstack_grow (&obstack, gcc_input_filename,
4931 input_filename_length);
4932 arg_going = 1;
4934 break;
4936 case 'I':
4938 struct spec_path_info info;
4940 if (multilib_dir)
4942 do_spec_1 ("-imultilib", 1, NULL);
4943 /* Make this a separate argument. */
4944 do_spec_1 (" ", 0, NULL);
4945 do_spec_1 (multilib_dir, 1, NULL);
4946 do_spec_1 (" ", 0, NULL);
4949 if (multiarch_dir)
4951 do_spec_1 ("-imultiarch", 1, NULL);
4952 /* Make this a separate argument. */
4953 do_spec_1 (" ", 0, NULL);
4954 do_spec_1 (multiarch_dir, 1, NULL);
4955 do_spec_1 (" ", 0, NULL);
4958 if (gcc_exec_prefix)
4960 do_spec_1 ("-iprefix", 1, NULL);
4961 /* Make this a separate argument. */
4962 do_spec_1 (" ", 0, NULL);
4963 do_spec_1 (gcc_exec_prefix, 1, NULL);
4964 do_spec_1 (" ", 0, NULL);
4967 if (target_system_root_changed ||
4968 (target_system_root && target_sysroot_hdrs_suffix))
4970 do_spec_1 ("-isysroot", 1, NULL);
4971 /* Make this a separate argument. */
4972 do_spec_1 (" ", 0, NULL);
4973 do_spec_1 (target_system_root, 1, NULL);
4974 if (target_sysroot_hdrs_suffix)
4975 do_spec_1 (target_sysroot_hdrs_suffix, 1, NULL);
4976 do_spec_1 (" ", 0, NULL);
4979 info.option = "-isystem";
4980 info.append = "include";
4981 info.append_len = strlen (info.append);
4982 info.omit_relative = false;
4983 info.separate_options = true;
4985 for_each_path (&include_prefixes, false, info.append_len,
4986 spec_path, &info);
4988 info.append = "include-fixed";
4989 if (*sysroot_hdrs_suffix_spec)
4990 info.append = concat (info.append, dir_separator_str,
4991 multilib_dir, NULL);
4992 info.append_len = strlen (info.append);
4993 for_each_path (&include_prefixes, false, info.append_len,
4994 spec_path, &info);
4996 break;
4998 case 'o':
5000 int max = n_infiles;
5001 max += lang_specific_extra_outfiles;
5003 if (HAVE_GNU_LD && at_file_supplied)
5005 /* We are going to expand `%o' to `@FILE', where FILE
5006 is a newly-created temporary filename. The filenames
5007 that would usually be expanded in place of %o will be
5008 written to the temporary file. */
5010 char **argv;
5011 int n_files, j;
5013 /* Convert OUTFILES into a form suitable for writeargv. */
5015 /* Determine how many are non-NULL. */
5016 for (n_files = 0, i = 0; i < max; i++)
5017 n_files += outfiles[i] != NULL;
5019 argv = (char **) alloca (sizeof (char *) * (n_files + 1));
5021 /* Copy the strings over. */
5022 for (i = 0, j = 0; i < max; i++)
5023 if (outfiles[i])
5025 argv[j] = CONST_CAST (char *, outfiles[i]);
5026 j++;
5028 argv[j] = NULL;
5030 create_at_file (argv);
5032 else
5033 for (i = 0; i < max; i++)
5034 if (outfiles[i])
5035 store_arg (outfiles[i], 0, 0);
5036 break;
5039 case 'O':
5040 obstack_grow (&obstack, TARGET_OBJECT_SUFFIX, strlen (TARGET_OBJECT_SUFFIX));
5041 arg_going = 1;
5042 break;
5044 case 's':
5045 this_is_library_file = 1;
5046 break;
5048 case 'T':
5049 this_is_linker_script = 1;
5050 break;
5052 case 'V':
5053 outfiles[input_file_number] = NULL;
5054 break;
5056 case 'w':
5057 this_is_output_file = 1;
5058 break;
5060 case 'W':
5062 unsigned int cur_index = VEC_length (const_char_p, argbuf);
5063 /* Handle the {...} following the %W. */
5064 if (*p != '{')
5065 fatal_error ("spec %qs has invalid %<%%W%c%>", spec, *p);
5066 p = handle_braces (p + 1);
5067 if (p == 0)
5068 return -1;
5069 end_going_arg ();
5070 /* If any args were output, mark the last one for deletion
5071 on failure. */
5072 if (VEC_length (const_char_p, argbuf) != cur_index)
5073 record_temp_file (VEC_last (const_char_p, argbuf), 0, 1);
5074 break;
5077 /* %x{OPTION} records OPTION for %X to output. */
5078 case 'x':
5080 const char *p1 = p;
5081 char *string;
5082 char *opt;
5083 unsigned ix;
5085 /* Skip past the option value and make a copy. */
5086 if (*p != '{')
5087 fatal_error ("spec %qs has invalid %<%%x%c%>", spec, *p);
5088 while (*p++ != '}')
5090 string = save_string (p1 + 1, p - p1 - 2);
5092 /* See if we already recorded this option. */
5093 FOR_EACH_VEC_ELT (char_p, linker_options, ix, opt)
5094 if (! strcmp (string, opt))
5096 free (string);
5097 return 0;
5100 /* This option is new; add it. */
5101 add_linker_option (string, strlen (string));
5102 free (string);
5104 break;
5106 /* Dump out the options accumulated previously using %x. */
5107 case 'X':
5108 do_specs_vec (linker_options);
5109 break;
5111 /* Dump out the options accumulated previously using -Wa,. */
5112 case 'Y':
5113 do_specs_vec (assembler_options);
5114 break;
5116 /* Dump out the options accumulated previously using -Wp,. */
5117 case 'Z':
5118 do_specs_vec (preprocessor_options);
5119 break;
5121 /* Here are digits and numbers that just process
5122 a certain constant string as a spec. */
5124 case '1':
5125 value = do_spec_1 (cc1_spec, 0, NULL);
5126 if (value != 0)
5127 return value;
5128 break;
5130 case '2':
5131 value = do_spec_1 (cc1plus_spec, 0, NULL);
5132 if (value != 0)
5133 return value;
5134 break;
5136 case 'a':
5137 value = do_spec_1 (asm_spec, 0, NULL);
5138 if (value != 0)
5139 return value;
5140 break;
5142 case 'A':
5143 value = do_spec_1 (asm_final_spec, 0, NULL);
5144 if (value != 0)
5145 return value;
5146 break;
5148 case 'C':
5150 const char *const spec
5151 = (input_file_compiler->cpp_spec
5152 ? input_file_compiler->cpp_spec
5153 : cpp_spec);
5154 value = do_spec_1 (spec, 0, NULL);
5155 if (value != 0)
5156 return value;
5158 break;
5160 case 'E':
5161 value = do_spec_1 (endfile_spec, 0, NULL);
5162 if (value != 0)
5163 return value;
5164 break;
5166 case 'l':
5167 value = do_spec_1 (link_spec, 0, NULL);
5168 if (value != 0)
5169 return value;
5170 break;
5172 case 'L':
5173 value = do_spec_1 (lib_spec, 0, NULL);
5174 if (value != 0)
5175 return value;
5176 break;
5178 case 'M':
5179 if (multilib_os_dir == NULL)
5180 obstack_1grow (&obstack, '.');
5181 else
5182 obstack_grow (&obstack, multilib_os_dir,
5183 strlen (multilib_os_dir));
5184 break;
5186 case 'G':
5187 value = do_spec_1 (libgcc_spec, 0, NULL);
5188 if (value != 0)
5189 return value;
5190 break;
5192 case 'R':
5193 /* We assume there is a directory
5194 separator at the end of this string. */
5195 if (target_system_root)
5197 obstack_grow (&obstack, target_system_root,
5198 strlen (target_system_root));
5199 if (target_sysroot_suffix)
5200 obstack_grow (&obstack, target_sysroot_suffix,
5201 strlen (target_sysroot_suffix));
5203 break;
5205 case 'S':
5206 value = do_spec_1 (startfile_spec, 0, NULL);
5207 if (value != 0)
5208 return value;
5209 break;
5211 /* Here we define characters other than letters and digits. */
5213 case '{':
5214 p = handle_braces (p);
5215 if (p == 0)
5216 return -1;
5217 break;
5219 case ':':
5220 p = handle_spec_function (p);
5221 if (p == 0)
5222 return -1;
5223 break;
5225 case '%':
5226 obstack_1grow (&obstack, '%');
5227 break;
5229 case '.':
5231 unsigned len = 0;
5233 while (p[len] && p[len] != ' ' && p[len] != '%')
5234 len++;
5235 suffix_subst = save_string (p - 1, len + 1);
5236 p += len;
5238 break;
5240 /* Henceforth ignore the option(s) matching the pattern
5241 after the %<. */
5242 case '<':
5243 case '>':
5245 unsigned len = 0;
5246 int have_wildcard = 0;
5247 int i;
5248 int switch_option;
5250 if (c == '>')
5251 switch_option = SWITCH_IGNORE | SWITCH_KEEP_FOR_GCC;
5252 else
5253 switch_option = SWITCH_IGNORE;
5255 while (p[len] && p[len] != ' ' && p[len] != '\t')
5256 len++;
5258 if (p[len-1] == '*')
5259 have_wildcard = 1;
5261 for (i = 0; i < n_switches; i++)
5262 if (!strncmp (switches[i].part1, p, len - have_wildcard)
5263 && (have_wildcard || switches[i].part1[len] == '\0'))
5265 switches[i].live_cond |= switch_option;
5266 /* User switch be validated from validate_all_switches.
5267 when the definition is seen from the spec file.
5268 If not defined anywhere, will be rejected. */
5269 if (switches[i].known)
5270 switches[i].validated = true;
5273 p += len;
5275 break;
5277 case '*':
5278 if (soft_matched_part)
5280 if (soft_matched_part[0])
5281 do_spec_1 (soft_matched_part, 1, NULL);
5282 do_spec_1 (" ", 0, NULL);
5284 else
5285 /* Catch the case where a spec string contains something like
5286 '%{foo:%*}'. i.e. there is no * in the pattern on the left
5287 hand side of the :. */
5288 error ("spec failure: %<%%*%> has not been initialized by pattern match");
5289 break;
5291 /* Process a string found as the value of a spec given by name.
5292 This feature allows individual machine descriptions
5293 to add and use their own specs. */
5294 case '(':
5296 const char *name = p;
5297 struct spec_list *sl;
5298 int len;
5300 /* The string after the S/P is the name of a spec that is to be
5301 processed. */
5302 while (*p && *p != ')')
5303 p++;
5305 /* See if it's in the list. */
5306 for (len = p - name, sl = specs; sl; sl = sl->next)
5307 if (sl->name_len == len && !strncmp (sl->name, name, len))
5309 name = *(sl->ptr_spec);
5310 #ifdef DEBUG_SPECS
5311 fnotice (stderr, "Processing spec (%s), which is '%s'\n",
5312 sl->name, name);
5313 #endif
5314 break;
5317 if (sl)
5319 value = do_spec_1 (name, 0, NULL);
5320 if (value != 0)
5321 return value;
5324 /* Discard the closing paren. */
5325 if (*p)
5326 p++;
5328 break;
5330 default:
5331 error ("spec failure: unrecognized spec option %qc", c);
5332 break;
5334 break;
5336 case '\\':
5337 /* Backslash: treat next character as ordinary. */
5338 c = *p++;
5340 /* Fall through. */
5341 default:
5342 /* Ordinary character: put it into the current argument. */
5343 obstack_1grow (&obstack, c);
5344 arg_going = 1;
5347 /* End of string. If we are processing a spec function, we need to
5348 end any pending argument. */
5349 if (processing_spec_function)
5350 end_going_arg ();
5352 return 0;
5355 /* Look up a spec function. */
5357 static const struct spec_function *
5358 lookup_spec_function (const char *name)
5360 const struct spec_function *sf;
5362 for (sf = static_spec_functions; sf->name != NULL; sf++)
5363 if (strcmp (sf->name, name) == 0)
5364 return sf;
5366 return NULL;
5369 /* Evaluate a spec function. */
5371 static const char *
5372 eval_spec_function (const char *func, const char *args)
5374 const struct spec_function *sf;
5375 const char *funcval;
5377 /* Saved spec processing context. */
5378 VEC(const_char_p,heap) *save_argbuf;
5380 int save_arg_going;
5381 int save_delete_this_arg;
5382 int save_this_is_output_file;
5383 int save_this_is_library_file;
5384 int save_input_from_pipe;
5385 int save_this_is_linker_script;
5386 const char *save_suffix_subst;
5388 int save_growing_size;
5389 void *save_growing_value;
5391 sf = lookup_spec_function (func);
5392 if (sf == NULL)
5393 fatal_error ("unknown spec function %qs", func);
5395 /* Push the spec processing context. */
5396 save_argbuf = argbuf;
5398 save_arg_going = arg_going;
5399 save_delete_this_arg = delete_this_arg;
5400 save_this_is_output_file = this_is_output_file;
5401 save_this_is_library_file = this_is_library_file;
5402 save_this_is_linker_script = this_is_linker_script;
5403 save_input_from_pipe = input_from_pipe;
5404 save_suffix_subst = suffix_subst;
5406 /* If we have some object growing now, finalize it so the args and function
5407 eval proceed from a cleared context. This is needed to prevent the first
5408 constructed arg from mistakenly including the growing value. We'll push
5409 this value back on the obstack once the function evaluation is done, to
5410 restore a consistent processing context for our caller. This is fine as
5411 the address of growing objects isn't guaranteed to remain stable until
5412 they are finalized, and we expect this situation to be rare enough for
5413 the extra copy not to be an issue. */
5414 save_growing_size = obstack_object_size (&obstack);
5415 if (save_growing_size > 0)
5416 save_growing_value = obstack_finish (&obstack);
5418 /* Create a new spec processing context, and build the function
5419 arguments. */
5421 alloc_args ();
5422 if (do_spec_2 (args) < 0)
5423 fatal_error ("error in args to spec function %qs", func);
5425 /* argbuf_index is an index for the next argument to be inserted, and
5426 so contains the count of the args already inserted. */
5428 funcval = (*sf->func) (VEC_length (const_char_p, argbuf),
5429 VEC_address (const_char_p, argbuf));
5431 /* Pop the spec processing context. */
5432 VEC_free (const_char_p, heap, argbuf);
5433 argbuf = save_argbuf;
5435 arg_going = save_arg_going;
5436 delete_this_arg = save_delete_this_arg;
5437 this_is_output_file = save_this_is_output_file;
5438 this_is_library_file = save_this_is_library_file;
5439 this_is_linker_script = save_this_is_linker_script;
5440 input_from_pipe = save_input_from_pipe;
5441 suffix_subst = save_suffix_subst;
5443 if (save_growing_size > 0)
5444 obstack_grow (&obstack, save_growing_value, save_growing_size);
5446 return funcval;
5449 /* Handle a spec function call of the form:
5451 %:function(args)
5453 ARGS is processed as a spec in a separate context and split into an
5454 argument vector in the normal fashion. The function returns a string
5455 containing a spec which we then process in the caller's context, or
5456 NULL if no processing is required. */
5458 static const char *
5459 handle_spec_function (const char *p)
5461 char *func, *args;
5462 const char *endp, *funcval;
5463 int count;
5465 processing_spec_function++;
5467 /* Get the function name. */
5468 for (endp = p; *endp != '\0'; endp++)
5470 if (*endp == '(') /* ) */
5471 break;
5472 /* Only allow [A-Za-z0-9], -, and _ in function names. */
5473 if (!ISALNUM (*endp) && !(*endp == '-' || *endp == '_'))
5474 fatal_error ("malformed spec function name");
5476 if (*endp != '(') /* ) */
5477 fatal_error ("no arguments for spec function");
5478 func = save_string (p, endp - p);
5479 p = ++endp;
5481 /* Get the arguments. */
5482 for (count = 0; *endp != '\0'; endp++)
5484 /* ( */
5485 if (*endp == ')')
5487 if (count == 0)
5488 break;
5489 count--;
5491 else if (*endp == '(') /* ) */
5492 count++;
5494 /* ( */
5495 if (*endp != ')')
5496 fatal_error ("malformed spec function arguments");
5497 args = save_string (p, endp - p);
5498 p = ++endp;
5500 /* p now points to just past the end of the spec function expression. */
5502 funcval = eval_spec_function (func, args);
5503 if (funcval != NULL && do_spec_1 (funcval, 0, NULL) < 0)
5504 p = NULL;
5506 free (func);
5507 free (args);
5509 processing_spec_function--;
5511 return p;
5514 /* Inline subroutine of handle_braces. Returns true if the current
5515 input suffix matches the atom bracketed by ATOM and END_ATOM. */
5516 static inline bool
5517 input_suffix_matches (const char *atom, const char *end_atom)
5519 return (input_suffix
5520 && !strncmp (input_suffix, atom, end_atom - atom)
5521 && input_suffix[end_atom - atom] == '\0');
5524 /* Subroutine of handle_braces. Returns true if the current
5525 input file's spec name matches the atom bracketed by ATOM and END_ATOM. */
5526 static bool
5527 input_spec_matches (const char *atom, const char *end_atom)
5529 return (input_file_compiler
5530 && input_file_compiler->suffix
5531 && input_file_compiler->suffix[0] != '\0'
5532 && !strncmp (input_file_compiler->suffix + 1, atom,
5533 end_atom - atom)
5534 && input_file_compiler->suffix[end_atom - atom + 1] == '\0');
5537 /* Subroutine of handle_braces. Returns true if a switch
5538 matching the atom bracketed by ATOM and END_ATOM appeared on the
5539 command line. */
5540 static bool
5541 switch_matches (const char *atom, const char *end_atom, int starred)
5543 int i;
5544 int len = end_atom - atom;
5545 int plen = starred ? len : -1;
5547 for (i = 0; i < n_switches; i++)
5548 if (!strncmp (switches[i].part1, atom, len)
5549 && (starred || switches[i].part1[len] == '\0')
5550 && check_live_switch (i, plen))
5551 return true;
5553 /* Check if a switch with separated form matching the atom.
5554 We check -D and -U switches. */
5555 else if (switches[i].args != 0)
5557 if ((*switches[i].part1 == 'D' || *switches[i].part1 == 'U')
5558 && *switches[i].part1 == atom[0])
5560 if (!strncmp (switches[i].args[0], &atom[1], len - 1)
5561 && (starred || (switches[i].part1[1] == '\0'
5562 && switches[i].args[0][len - 1] == '\0'))
5563 && check_live_switch (i, (starred ? 1 : -1)))
5564 return true;
5568 return false;
5571 /* Inline subroutine of handle_braces. Mark all of the switches which
5572 match ATOM (extends to END_ATOM; STARRED indicates whether there
5573 was a star after the atom) for later processing. */
5574 static inline void
5575 mark_matching_switches (const char *atom, const char *end_atom, int starred)
5577 int i;
5578 int len = end_atom - atom;
5579 int plen = starred ? len : -1;
5581 for (i = 0; i < n_switches; i++)
5582 if (!strncmp (switches[i].part1, atom, len)
5583 && (starred || switches[i].part1[len] == '\0')
5584 && check_live_switch (i, plen))
5585 switches[i].ordering = 1;
5588 /* Inline subroutine of handle_braces. Process all the currently
5589 marked switches through give_switch, and clear the marks. */
5590 static inline void
5591 process_marked_switches (void)
5593 int i;
5595 for (i = 0; i < n_switches; i++)
5596 if (switches[i].ordering == 1)
5598 switches[i].ordering = 0;
5599 give_switch (i, 0);
5603 /* Handle a %{ ... } construct. P points just inside the leading {.
5604 Returns a pointer one past the end of the brace block, or 0
5605 if we call do_spec_1 and that returns -1. */
5607 static const char *
5608 handle_braces (const char *p)
5610 const char *atom, *end_atom;
5611 const char *d_atom = NULL, *d_end_atom = NULL;
5612 const char *orig = p;
5614 bool a_is_suffix;
5615 bool a_is_spectype;
5616 bool a_is_starred;
5617 bool a_is_negated;
5618 bool a_matched;
5620 bool a_must_be_last = false;
5621 bool ordered_set = false;
5622 bool disjunct_set = false;
5623 bool disj_matched = false;
5624 bool disj_starred = true;
5625 bool n_way_choice = false;
5626 bool n_way_matched = false;
5628 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
5632 if (a_must_be_last)
5633 goto invalid;
5635 /* Scan one "atom" (S in the description above of %{}, possibly
5636 with '!', '.', '@', ',', or '*' modifiers). */
5637 a_matched = false;
5638 a_is_suffix = false;
5639 a_is_starred = false;
5640 a_is_negated = false;
5641 a_is_spectype = false;
5643 SKIP_WHITE();
5644 if (*p == '!')
5645 p++, a_is_negated = true;
5647 SKIP_WHITE();
5648 if (*p == '.')
5649 p++, a_is_suffix = true;
5650 else if (*p == ',')
5651 p++, a_is_spectype = true;
5653 atom = p;
5654 while (ISIDNUM(*p) || *p == '-' || *p == '+' || *p == '='
5655 || *p == ',' || *p == '.' || *p == '@')
5656 p++;
5657 end_atom = p;
5659 if (*p == '*')
5660 p++, a_is_starred = 1;
5662 SKIP_WHITE();
5663 switch (*p)
5665 case '&': case '}':
5666 /* Substitute the switch(es) indicated by the current atom. */
5667 ordered_set = true;
5668 if (disjunct_set || n_way_choice || a_is_negated || a_is_suffix
5669 || a_is_spectype || atom == end_atom)
5670 goto invalid;
5672 mark_matching_switches (atom, end_atom, a_is_starred);
5674 if (*p == '}')
5675 process_marked_switches ();
5676 break;
5678 case '|': case ':':
5679 /* Substitute some text if the current atom appears as a switch
5680 or suffix. */
5681 disjunct_set = true;
5682 if (ordered_set)
5683 goto invalid;
5685 if (atom == end_atom)
5687 if (!n_way_choice || disj_matched || *p == '|'
5688 || a_is_negated || a_is_suffix || a_is_spectype
5689 || a_is_starred)
5690 goto invalid;
5692 /* An empty term may appear as the last choice of an
5693 N-way choice set; it means "otherwise". */
5694 a_must_be_last = true;
5695 disj_matched = !n_way_matched;
5696 disj_starred = false;
5698 else
5700 if ((a_is_suffix || a_is_spectype) && a_is_starred)
5701 goto invalid;
5703 if (!a_is_starred)
5704 disj_starred = false;
5706 /* Don't bother testing this atom if we already have a
5707 match. */
5708 if (!disj_matched && !n_way_matched)
5710 if (a_is_suffix)
5711 a_matched = input_suffix_matches (atom, end_atom);
5712 else if (a_is_spectype)
5713 a_matched = input_spec_matches (atom, end_atom);
5714 else
5715 a_matched = switch_matches (atom, end_atom, a_is_starred);
5717 if (a_matched != a_is_negated)
5719 disj_matched = true;
5720 d_atom = atom;
5721 d_end_atom = end_atom;
5726 if (*p == ':')
5728 /* Found the body, that is, the text to substitute if the
5729 current disjunction matches. */
5730 p = process_brace_body (p + 1, d_atom, d_end_atom, disj_starred,
5731 disj_matched && !n_way_matched);
5732 if (p == 0)
5733 return 0;
5735 /* If we have an N-way choice, reset state for the next
5736 disjunction. */
5737 if (*p == ';')
5739 n_way_choice = true;
5740 n_way_matched |= disj_matched;
5741 disj_matched = false;
5742 disj_starred = true;
5743 d_atom = d_end_atom = NULL;
5746 break;
5748 default:
5749 goto invalid;
5752 while (*p++ != '}');
5754 return p;
5756 invalid:
5757 fatal_error ("braced spec %qs is invalid at %qc", orig, *p);
5759 #undef SKIP_WHITE
5762 /* Subroutine of handle_braces. Scan and process a brace substitution body
5763 (X in the description of %{} syntax). P points one past the colon;
5764 ATOM and END_ATOM bracket the first atom which was found to be true
5765 (present) in the current disjunction; STARRED indicates whether all
5766 the atoms in the current disjunction were starred (for syntax validation);
5767 MATCHED indicates whether the disjunction matched or not, and therefore
5768 whether or not the body is to be processed through do_spec_1 or just
5769 skipped. Returns a pointer to the closing } or ;, or 0 if do_spec_1
5770 returns -1. */
5772 static const char *
5773 process_brace_body (const char *p, const char *atom, const char *end_atom,
5774 int starred, int matched)
5776 const char *body, *end_body;
5777 unsigned int nesting_level;
5778 bool have_subst = false;
5780 /* Locate the closing } or ;, honoring nested braces.
5781 Trim trailing whitespace. */
5782 body = p;
5783 nesting_level = 1;
5784 for (;;)
5786 if (*p == '{')
5787 nesting_level++;
5788 else if (*p == '}')
5790 if (!--nesting_level)
5791 break;
5793 else if (*p == ';' && nesting_level == 1)
5794 break;
5795 else if (*p == '%' && p[1] == '*' && nesting_level == 1)
5796 have_subst = true;
5797 else if (*p == '\0')
5798 goto invalid;
5799 p++;
5802 end_body = p;
5803 while (end_body[-1] == ' ' || end_body[-1] == '\t')
5804 end_body--;
5806 if (have_subst && !starred)
5807 goto invalid;
5809 if (matched)
5811 /* Copy the substitution body to permanent storage and execute it.
5812 If have_subst is false, this is a simple matter of running the
5813 body through do_spec_1... */
5814 char *string = save_string (body, end_body - body);
5815 if (!have_subst)
5817 if (do_spec_1 (string, 0, NULL) < 0)
5818 return 0;
5820 else
5822 /* ... but if have_subst is true, we have to process the
5823 body once for each matching switch, with %* set to the
5824 variant part of the switch. */
5825 unsigned int hard_match_len = end_atom - atom;
5826 int i;
5828 for (i = 0; i < n_switches; i++)
5829 if (!strncmp (switches[i].part1, atom, hard_match_len)
5830 && check_live_switch (i, hard_match_len))
5832 if (do_spec_1 (string, 0,
5833 &switches[i].part1[hard_match_len]) < 0)
5834 return 0;
5835 /* Pass any arguments this switch has. */
5836 give_switch (i, 1);
5837 suffix_subst = NULL;
5842 return p;
5844 invalid:
5845 fatal_error ("braced spec body %qs is invalid", body);
5848 /* Return 0 iff switch number SWITCHNUM is obsoleted by a later switch
5849 on the command line. PREFIX_LENGTH is the length of XXX in an {XXX*}
5850 spec, or -1 if either exact match or %* is used.
5852 A -O switch is obsoleted by a later -O switch. A -f, -g, -m, or -W switch
5853 whose value does not begin with "no-" is obsoleted by the same value
5854 with the "no-", similarly for a switch with the "no-" prefix. */
5856 static int
5857 check_live_switch (int switchnum, int prefix_length)
5859 const char *name = switches[switchnum].part1;
5860 int i;
5862 /* If we already processed this switch and determined if it was
5863 live or not, return our past determination. */
5864 if (switches[switchnum].live_cond != 0)
5865 return ((switches[switchnum].live_cond & SWITCH_LIVE) != 0
5866 && (switches[switchnum].live_cond & SWITCH_FALSE) == 0
5867 && (switches[switchnum].live_cond & SWITCH_IGNORE_PERMANENTLY)
5868 == 0);
5870 /* In the common case of {<at-most-one-letter>*}, a negating
5871 switch would always match, so ignore that case. We will just
5872 send the conflicting switches to the compiler phase. */
5873 if (prefix_length >= 0 && prefix_length <= 1)
5874 return 1;
5876 /* Now search for duplicate in a manner that depends on the name. */
5877 switch (*name)
5879 case 'O':
5880 for (i = switchnum + 1; i < n_switches; i++)
5881 if (switches[i].part1[0] == 'O')
5883 switches[switchnum].validated = true;
5884 switches[switchnum].live_cond = SWITCH_FALSE;
5885 return 0;
5887 break;
5889 case 'W': case 'f': case 'm': case 'g':
5890 if (! strncmp (name + 1, "no-", 3))
5892 /* We have Xno-YYY, search for XYYY. */
5893 for (i = switchnum + 1; i < n_switches; i++)
5894 if (switches[i].part1[0] == name[0]
5895 && ! strcmp (&switches[i].part1[1], &name[4]))
5897 /* --specs are validated with the validate_switches mechanism. */
5898 if (switches[switchnum].known)
5899 switches[switchnum].validated = true;
5900 switches[switchnum].live_cond = SWITCH_FALSE;
5901 return 0;
5904 else
5906 /* We have XYYY, search for Xno-YYY. */
5907 for (i = switchnum + 1; i < n_switches; i++)
5908 if (switches[i].part1[0] == name[0]
5909 && switches[i].part1[1] == 'n'
5910 && switches[i].part1[2] == 'o'
5911 && switches[i].part1[3] == '-'
5912 && !strcmp (&switches[i].part1[4], &name[1]))
5914 /* --specs are validated with the validate_switches mechanism. */
5915 if (switches[switchnum].known)
5916 switches[switchnum].validated = true;
5917 switches[switchnum].live_cond = SWITCH_FALSE;
5918 return 0;
5921 break;
5924 /* Otherwise the switch is live. */
5925 switches[switchnum].live_cond |= SWITCH_LIVE;
5926 return 1;
5929 /* Pass a switch to the current accumulating command
5930 in the same form that we received it.
5931 SWITCHNUM identifies the switch; it is an index into
5932 the vector of switches gcc received, which is `switches'.
5933 This cannot fail since it never finishes a command line.
5935 If OMIT_FIRST_WORD is nonzero, then we omit .part1 of the argument. */
5937 static void
5938 give_switch (int switchnum, int omit_first_word)
5940 if ((switches[switchnum].live_cond & SWITCH_IGNORE) != 0)
5941 return;
5943 if (!omit_first_word)
5945 do_spec_1 ("-", 0, NULL);
5946 do_spec_1 (switches[switchnum].part1, 1, NULL);
5949 if (switches[switchnum].args != 0)
5951 const char **p;
5952 for (p = switches[switchnum].args; *p; p++)
5954 const char *arg = *p;
5956 do_spec_1 (" ", 0, NULL);
5957 if (suffix_subst)
5959 unsigned length = strlen (arg);
5960 int dot = 0;
5962 while (length-- && !IS_DIR_SEPARATOR (arg[length]))
5963 if (arg[length] == '.')
5965 (CONST_CAST(char *, arg))[length] = 0;
5966 dot = 1;
5967 break;
5969 do_spec_1 (arg, 1, NULL);
5970 if (dot)
5971 (CONST_CAST(char *, arg))[length] = '.';
5972 do_spec_1 (suffix_subst, 1, NULL);
5974 else
5975 do_spec_1 (arg, 1, NULL);
5979 do_spec_1 (" ", 0, NULL);
5980 switches[switchnum].validated = true;
5983 /* Search for a file named NAME trying various prefixes including the
5984 user's -B prefix and some standard ones.
5985 Return the absolute file name found. If nothing is found, return NAME. */
5987 static const char *
5988 find_file (const char *name)
5990 char *newname = find_a_file (&startfile_prefixes, name, R_OK, true);
5991 return newname ? newname : name;
5994 /* Determine whether a directory exists. If LINKER, return 0 for
5995 certain fixed names not needed by the linker. */
5997 static int
5998 is_directory (const char *path1, bool linker)
6000 int len1;
6001 char *path;
6002 char *cp;
6003 struct stat st;
6005 /* Ensure the string ends with "/.". The resulting path will be a
6006 directory even if the given path is a symbolic link. */
6007 len1 = strlen (path1);
6008 path = (char *) alloca (3 + len1);
6009 memcpy (path, path1, len1);
6010 cp = path + len1;
6011 if (!IS_DIR_SEPARATOR (cp[-1]))
6012 *cp++ = DIR_SEPARATOR;
6013 *cp++ = '.';
6014 *cp = '\0';
6016 /* Exclude directories that the linker is known to search. */
6017 if (linker
6018 && IS_DIR_SEPARATOR (path[0])
6019 && ((cp - path == 6
6020 && filename_ncmp (path + 1, "lib", 3) == 0)
6021 || (cp - path == 10
6022 && filename_ncmp (path + 1, "usr", 3) == 0
6023 && IS_DIR_SEPARATOR (path[4])
6024 && filename_ncmp (path + 5, "lib", 3) == 0)))
6025 return 0;
6027 return (stat (path, &st) >= 0 && S_ISDIR (st.st_mode));
6030 /* Set up the various global variables to indicate that we're processing
6031 the input file named FILENAME. */
6033 void
6034 set_input (const char *filename)
6036 const char *p;
6038 gcc_input_filename = filename;
6039 input_filename_length = strlen (gcc_input_filename);
6040 input_basename = lbasename (gcc_input_filename);
6042 /* Find a suffix starting with the last period,
6043 and set basename_length to exclude that suffix. */
6044 basename_length = strlen (input_basename);
6045 suffixed_basename_length = basename_length;
6046 p = input_basename + basename_length;
6047 while (p != input_basename && *p != '.')
6048 --p;
6049 if (*p == '.' && p != input_basename)
6051 basename_length = p - input_basename;
6052 input_suffix = p + 1;
6054 else
6055 input_suffix = "";
6057 /* If a spec for 'g', 'u', or 'U' is seen with -save-temps then
6058 we will need to do a stat on the gcc_input_filename. The
6059 INPUT_STAT_SET signals that the stat is needed. */
6060 input_stat_set = 0;
6063 /* On fatal signals, delete all the temporary files. */
6065 static void
6066 fatal_signal (int signum)
6068 signal (signum, SIG_DFL);
6069 delete_failure_queue ();
6070 delete_temp_files ();
6071 /* Get the same signal again, this time not handled,
6072 so its normal effect occurs. */
6073 kill (getpid (), signum);
6076 /* Compare the contents of the two files named CMPFILE[0] and
6077 CMPFILE[1]. Return zero if they're identical, nonzero
6078 otherwise. */
6080 static int
6081 compare_files (char *cmpfile[])
6083 int ret = 0;
6084 FILE *temp[2] = { NULL, NULL };
6085 int i;
6087 #if HAVE_MMAP_FILE
6089 size_t length[2];
6090 void *map[2] = { NULL, NULL };
6092 for (i = 0; i < 2; i++)
6094 struct stat st;
6096 if (stat (cmpfile[i], &st) < 0 || !S_ISREG (st.st_mode))
6098 error ("%s: could not determine length of compare-debug file %s",
6099 gcc_input_filename, cmpfile[i]);
6100 ret = 1;
6101 break;
6104 length[i] = st.st_size;
6107 if (!ret && length[0] != length[1])
6109 error ("%s: -fcompare-debug failure (length)", gcc_input_filename);
6110 ret = 1;
6113 if (!ret)
6114 for (i = 0; i < 2; i++)
6116 int fd = open (cmpfile[i], O_RDONLY);
6117 if (fd < 0)
6119 error ("%s: could not open compare-debug file %s",
6120 gcc_input_filename, cmpfile[i]);
6121 ret = 1;
6122 break;
6125 map[i] = mmap (NULL, length[i], PROT_READ, MAP_PRIVATE, fd, 0);
6126 close (fd);
6128 if (map[i] == (void *) MAP_FAILED)
6130 ret = -1;
6131 break;
6135 if (!ret)
6137 if (memcmp (map[0], map[1], length[0]) != 0)
6139 error ("%s: -fcompare-debug failure", gcc_input_filename);
6140 ret = 1;
6144 for (i = 0; i < 2; i++)
6145 if (map[i])
6146 munmap ((caddr_t) map[i], length[i]);
6148 if (ret >= 0)
6149 return ret;
6151 ret = 0;
6153 #endif
6155 for (i = 0; i < 2; i++)
6157 temp[i] = fopen (cmpfile[i], "r");
6158 if (!temp[i])
6160 error ("%s: could not open compare-debug file %s",
6161 gcc_input_filename, cmpfile[i]);
6162 ret = 1;
6163 break;
6167 if (!ret && temp[0] && temp[1])
6168 for (;;)
6170 int c0, c1;
6171 c0 = fgetc (temp[0]);
6172 c1 = fgetc (temp[1]);
6174 if (c0 != c1)
6176 error ("%s: -fcompare-debug failure",
6177 gcc_input_filename);
6178 ret = 1;
6179 break;
6182 if (c0 == EOF)
6183 break;
6186 for (i = 1; i >= 0; i--)
6188 if (temp[i])
6189 fclose (temp[i]);
6192 return ret;
6195 extern int main (int, char **);
6198 main (int argc, char **argv)
6200 size_t i;
6201 int value;
6202 int linker_was_run = 0;
6203 int lang_n_infiles = 0;
6204 int num_linker_inputs = 0;
6205 char *explicit_link_files;
6206 char *specs_file;
6207 char *lto_wrapper_file;
6208 const char *p;
6209 struct user_specs *uptr;
6210 char **old_argv = argv;
6211 struct cl_decoded_option *decoded_options;
6212 unsigned int decoded_options_count;
6214 p = argv[0] + strlen (argv[0]);
6215 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
6216 --p;
6217 progname = p;
6219 xmalloc_set_program_name (progname);
6221 expandargv (&argc, &argv);
6223 /* Determine if any expansions were made. */
6224 if (argv != old_argv)
6225 at_file_supplied = true;
6227 /* Register the language-independent parameters. */
6228 global_init_params ();
6229 finish_params ();
6231 init_options_struct (&global_options, &global_options_set);
6233 decode_cmdline_options_to_array (argc, CONST_CAST2 (const char **, char **,
6234 argv),
6235 CL_DRIVER,
6236 &decoded_options, &decoded_options_count);
6238 /* Unlock the stdio streams. */
6239 unlock_std_streams ();
6241 gcc_init_libintl ();
6243 diagnostic_initialize (global_dc, 0);
6245 #ifdef GCC_DRIVER_HOST_INITIALIZATION
6246 /* Perform host dependent initialization when needed. */
6247 GCC_DRIVER_HOST_INITIALIZATION;
6248 #endif
6250 if (atexit (delete_temp_files) != 0)
6251 fatal_error ("atexit failed");
6253 if (signal (SIGINT, SIG_IGN) != SIG_IGN)
6254 signal (SIGINT, fatal_signal);
6255 #ifdef SIGHUP
6256 if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
6257 signal (SIGHUP, fatal_signal);
6258 #endif
6259 if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
6260 signal (SIGTERM, fatal_signal);
6261 #ifdef SIGPIPE
6262 if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
6263 signal (SIGPIPE, fatal_signal);
6264 #endif
6265 #ifdef SIGCHLD
6266 /* We *MUST* set SIGCHLD to SIG_DFL so that the wait4() call will
6267 receive the signal. A different setting is inheritable */
6268 signal (SIGCHLD, SIG_DFL);
6269 #endif
6271 /* Parsing and gimplification sometimes need quite large stack.
6272 Increase stack size limits if possible. */
6273 stack_limit_increase (64 * 1024 * 1024);
6275 /* Allocate the argument vector. */
6276 alloc_args ();
6278 obstack_init (&obstack);
6280 /* Build multilib_select, et. al from the separate lines that make up each
6281 multilib selection. */
6283 const char *const *q = multilib_raw;
6284 int need_space;
6286 obstack_init (&multilib_obstack);
6287 while ((p = *q++) != (char *) 0)
6288 obstack_grow (&multilib_obstack, p, strlen (p));
6290 obstack_1grow (&multilib_obstack, 0);
6291 multilib_select = XOBFINISH (&multilib_obstack, const char *);
6293 q = multilib_matches_raw;
6294 while ((p = *q++) != (char *) 0)
6295 obstack_grow (&multilib_obstack, p, strlen (p));
6297 obstack_1grow (&multilib_obstack, 0);
6298 multilib_matches = XOBFINISH (&multilib_obstack, const char *);
6300 q = multilib_exclusions_raw;
6301 while ((p = *q++) != (char *) 0)
6302 obstack_grow (&multilib_obstack, p, strlen (p));
6304 obstack_1grow (&multilib_obstack, 0);
6305 multilib_exclusions = XOBFINISH (&multilib_obstack, const char *);
6307 need_space = FALSE;
6308 for (i = 0; i < ARRAY_SIZE (multilib_defaults_raw); i++)
6310 if (need_space)
6311 obstack_1grow (&multilib_obstack, ' ');
6312 obstack_grow (&multilib_obstack,
6313 multilib_defaults_raw[i],
6314 strlen (multilib_defaults_raw[i]));
6315 need_space = TRUE;
6318 obstack_1grow (&multilib_obstack, 0);
6319 multilib_defaults = XOBFINISH (&multilib_obstack, const char *);
6322 #ifdef INIT_ENVIRONMENT
6323 /* Set up any other necessary machine specific environment variables. */
6324 xputenv (INIT_ENVIRONMENT);
6325 #endif
6327 /* Make a table of what switches there are (switches, n_switches).
6328 Make a table of specified input files (infiles, n_infiles).
6329 Decode switches that are handled locally. */
6331 process_command (decoded_options_count, decoded_options);
6333 /* Initialize the vector of specs to just the default.
6334 This means one element containing 0s, as a terminator. */
6336 compilers = XNEWVAR (struct compiler, sizeof default_compilers);
6337 memcpy (compilers, default_compilers, sizeof default_compilers);
6338 n_compilers = n_default_compilers;
6340 /* Read specs from a file if there is one. */
6342 machine_suffix = concat (spec_machine, dir_separator_str,
6343 spec_version, dir_separator_str, NULL);
6344 just_machine_suffix = concat (spec_machine, dir_separator_str, NULL);
6346 specs_file = find_a_file (&startfile_prefixes, "specs", R_OK, true);
6347 /* Read the specs file unless it is a default one. */
6348 if (specs_file != 0 && strcmp (specs_file, "specs"))
6349 read_specs (specs_file, true, false);
6350 else
6351 init_spec ();
6353 /* We need to check standard_exec_prefix/just_machine_suffix/specs
6354 for any override of as, ld and libraries. */
6355 specs_file = (char *) alloca (strlen (standard_exec_prefix)
6356 + strlen (just_machine_suffix) + sizeof ("specs"));
6358 strcpy (specs_file, standard_exec_prefix);
6359 strcat (specs_file, just_machine_suffix);
6360 strcat (specs_file, "specs");
6361 if (access (specs_file, R_OK) == 0)
6362 read_specs (specs_file, true, false);
6364 /* Process any configure-time defaults specified for the command line
6365 options, via OPTION_DEFAULT_SPECS. */
6366 for (i = 0; i < ARRAY_SIZE (option_default_specs); i++)
6367 do_option_spec (option_default_specs[i].name,
6368 option_default_specs[i].spec);
6370 /* Process DRIVER_SELF_SPECS, adding any new options to the end
6371 of the command line. */
6373 for (i = 0; i < ARRAY_SIZE (driver_self_specs); i++)
6374 do_self_spec (driver_self_specs[i]);
6376 /* If not cross-compiling, look for executables in the standard
6377 places. */
6378 if (*cross_compile == '0')
6380 if (*md_exec_prefix)
6382 add_prefix (&exec_prefixes, md_exec_prefix, "GCC",
6383 PREFIX_PRIORITY_LAST, 0, 0);
6387 /* Process sysroot_suffix_spec. */
6388 if (*sysroot_suffix_spec != 0
6389 && !no_sysroot_suffix
6390 && do_spec_2 (sysroot_suffix_spec) == 0)
6392 if (VEC_length (const_char_p, argbuf) > 1)
6393 error ("spec failure: more than one arg to SYSROOT_SUFFIX_SPEC");
6394 else if (VEC_length (const_char_p, argbuf) == 1)
6395 target_sysroot_suffix = xstrdup (VEC_last (const_char_p, argbuf));
6398 #ifdef HAVE_LD_SYSROOT
6399 /* Pass the --sysroot option to the linker, if it supports that. If
6400 there is a sysroot_suffix_spec, it has already been processed by
6401 this point, so target_system_root really is the system root we
6402 should be using. */
6403 if (target_system_root)
6405 obstack_grow (&obstack, "%(sysroot_spec) ", strlen ("%(sysroot_spec) "));
6406 obstack_grow0 (&obstack, link_spec, strlen (link_spec));
6407 set_spec ("link", XOBFINISH (&obstack, const char *), false);
6409 #endif
6411 /* Process sysroot_hdrs_suffix_spec. */
6412 if (*sysroot_hdrs_suffix_spec != 0
6413 && !no_sysroot_suffix
6414 && do_spec_2 (sysroot_hdrs_suffix_spec) == 0)
6416 if (VEC_length (const_char_p, argbuf) > 1)
6417 error ("spec failure: more than one arg to SYSROOT_HEADERS_SUFFIX_SPEC");
6418 else if (VEC_length (const_char_p, argbuf) == 1)
6419 target_sysroot_hdrs_suffix = xstrdup (VEC_last (const_char_p, argbuf));
6422 /* Look for startfiles in the standard places. */
6423 if (*startfile_prefix_spec != 0
6424 && do_spec_2 (startfile_prefix_spec) == 0
6425 && do_spec_1 (" ", 0, NULL) == 0)
6427 const char *arg;
6428 int ndx;
6429 FOR_EACH_VEC_ELT (const_char_p, argbuf, ndx, arg)
6430 add_sysrooted_prefix (&startfile_prefixes, arg, "BINUTILS",
6431 PREFIX_PRIORITY_LAST, 0, 1);
6433 /* We should eventually get rid of all these and stick to
6434 startfile_prefix_spec exclusively. */
6435 else if (*cross_compile == '0' || target_system_root)
6437 if (*md_startfile_prefix)
6438 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix,
6439 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
6441 if (*md_startfile_prefix_1)
6442 add_sysrooted_prefix (&startfile_prefixes, md_startfile_prefix_1,
6443 "GCC", PREFIX_PRIORITY_LAST, 0, 1);
6445 /* If standard_startfile_prefix is relative, base it on
6446 standard_exec_prefix. This lets us move the installed tree
6447 as a unit. If GCC_EXEC_PREFIX is defined, base
6448 standard_startfile_prefix on that as well.
6450 If the prefix is relative, only search it for native compilers;
6451 otherwise we will search a directory containing host libraries. */
6452 if (IS_ABSOLUTE_PATH (standard_startfile_prefix))
6453 add_sysrooted_prefix (&startfile_prefixes,
6454 standard_startfile_prefix, "BINUTILS",
6455 PREFIX_PRIORITY_LAST, 0, 1);
6456 else if (*cross_compile == '0')
6458 add_prefix (&startfile_prefixes,
6459 concat (gcc_exec_prefix
6460 ? gcc_exec_prefix : standard_exec_prefix,
6461 machine_suffix,
6462 standard_startfile_prefix, NULL),
6463 NULL, PREFIX_PRIORITY_LAST, 0, 1);
6466 /* Sysrooted prefixes are relocated because target_system_root is
6467 also relocated by gcc_exec_prefix. */
6468 if (*standard_startfile_prefix_1)
6469 add_sysrooted_prefix (&startfile_prefixes,
6470 standard_startfile_prefix_1, "BINUTILS",
6471 PREFIX_PRIORITY_LAST, 0, 1);
6472 if (*standard_startfile_prefix_2)
6473 add_sysrooted_prefix (&startfile_prefixes,
6474 standard_startfile_prefix_2, "BINUTILS",
6475 PREFIX_PRIORITY_LAST, 0, 1);
6478 /* Process any user specified specs in the order given on the command
6479 line. */
6480 for (uptr = user_specs_head; uptr; uptr = uptr->next)
6482 char *filename = find_a_file (&startfile_prefixes, uptr->filename,
6483 R_OK, true);
6484 read_specs (filename ? filename : uptr->filename, false, true);
6487 /* Process any user self specs. */
6489 struct spec_list *sl;
6490 for (sl = specs; sl; sl = sl->next)
6491 if (sl->name_len == sizeof "self_spec" - 1
6492 && !strcmp (sl->name, "self_spec"))
6493 do_self_spec (*sl->ptr_spec);
6496 if (compare_debug)
6498 enum save_temps save;
6500 if (!compare_debug_second)
6502 n_switches_debug_check[1] = n_switches;
6503 n_switches_alloc_debug_check[1] = n_switches_alloc;
6504 switches_debug_check[1] = XDUPVEC (struct switchstr, switches,
6505 n_switches_alloc);
6507 do_self_spec ("%:compare-debug-self-opt()");
6508 n_switches_debug_check[0] = n_switches;
6509 n_switches_alloc_debug_check[0] = n_switches_alloc;
6510 switches_debug_check[0] = switches;
6512 n_switches = n_switches_debug_check[1];
6513 n_switches_alloc = n_switches_alloc_debug_check[1];
6514 switches = switches_debug_check[1];
6517 /* Avoid crash when computing %j in this early. */
6518 save = save_temps_flag;
6519 save_temps_flag = SAVE_TEMPS_NONE;
6521 compare_debug = -compare_debug;
6522 do_self_spec ("%:compare-debug-self-opt()");
6524 save_temps_flag = save;
6526 if (!compare_debug_second)
6528 n_switches_debug_check[1] = n_switches;
6529 n_switches_alloc_debug_check[1] = n_switches_alloc;
6530 switches_debug_check[1] = switches;
6531 compare_debug = -compare_debug;
6532 n_switches = n_switches_debug_check[0];
6533 n_switches_alloc = n_switches_debug_check[0];
6534 switches = switches_debug_check[0];
6539 /* If we have a GCC_EXEC_PREFIX envvar, modify it for cpp's sake. */
6540 if (gcc_exec_prefix)
6541 gcc_exec_prefix = concat (gcc_exec_prefix, spec_machine, dir_separator_str,
6542 spec_version, dir_separator_str, NULL);
6544 /* Now we have the specs.
6545 Set the `valid' bits for switches that match anything in any spec. */
6547 validate_all_switches ();
6549 /* Now that we have the switches and the specs, set
6550 the subdirectory based on the options. */
6551 set_multilib_dir ();
6553 /* Set up to remember the pathname of gcc and any options
6554 needed for collect. We use argv[0] instead of progname because
6555 we need the complete pathname. */
6556 obstack_init (&collect_obstack);
6557 obstack_grow (&collect_obstack, "COLLECT_GCC=", sizeof ("COLLECT_GCC=") - 1);
6558 obstack_grow (&collect_obstack, argv[0], strlen (argv[0]) + 1);
6559 xputenv (XOBFINISH (&collect_obstack, char *));
6561 /* Set up to remember the pathname of the lto wrapper. */
6563 if (have_c)
6564 lto_wrapper_file = NULL;
6565 else
6566 lto_wrapper_file = find_a_file (&exec_prefixes, "lto-wrapper",
6567 X_OK, false);
6568 if (lto_wrapper_file)
6570 lto_wrapper_spec = lto_wrapper_file;
6571 obstack_init (&collect_obstack);
6572 obstack_grow (&collect_obstack, "COLLECT_LTO_WRAPPER=",
6573 sizeof ("COLLECT_LTO_WRAPPER=") - 1);
6574 obstack_grow (&collect_obstack, lto_wrapper_spec,
6575 strlen (lto_wrapper_spec) + 1);
6576 xputenv (XOBFINISH (&collect_obstack, char *));
6579 /* Reject switches that no pass was interested in. */
6581 for (i = 0; (int) i < n_switches; i++)
6582 if (! switches[i].validated)
6583 error ("unrecognized command line option %<-%s%>", switches[i].part1);
6585 /* Obey some of the options. */
6587 if (print_search_dirs)
6589 printf (_("install: %s%s\n"),
6590 gcc_exec_prefix ? gcc_exec_prefix : standard_exec_prefix,
6591 gcc_exec_prefix ? "" : machine_suffix);
6592 printf (_("programs: %s\n"),
6593 build_search_list (&exec_prefixes, "", false, false));
6594 printf (_("libraries: %s\n"),
6595 build_search_list (&startfile_prefixes, "", false, true));
6596 return (0);
6599 if (print_file_name)
6601 printf ("%s\n", find_file (print_file_name));
6602 return (0);
6605 if (print_prog_name)
6607 char *newname = find_a_file (&exec_prefixes, print_prog_name, X_OK, 0);
6608 printf ("%s\n", (newname ? newname : print_prog_name));
6609 return (0);
6612 if (print_multi_lib)
6614 print_multilib_info ();
6615 return (0);
6618 if (print_multi_directory)
6620 if (multilib_dir == NULL)
6621 printf (".\n");
6622 else
6623 printf ("%s\n", multilib_dir);
6624 return (0);
6627 if (print_multiarch)
6629 if (multiarch_dir == NULL)
6630 printf ("\n");
6631 else
6632 printf ("%s\n", multiarch_dir);
6633 return (0);
6636 if (print_sysroot)
6638 if (target_system_root)
6640 if (target_sysroot_suffix)
6641 printf ("%s%s\n", target_system_root, target_sysroot_suffix);
6642 else
6643 printf ("%s\n", target_system_root);
6645 return (0);
6648 if (print_multi_os_directory)
6650 if (multilib_os_dir == NULL)
6651 printf (".\n");
6652 else
6653 printf ("%s\n", multilib_os_dir);
6654 return (0);
6657 if (print_sysroot_headers_suffix)
6659 if (*sysroot_hdrs_suffix_spec)
6661 printf("%s\n", (target_sysroot_hdrs_suffix
6662 ? target_sysroot_hdrs_suffix
6663 : ""));
6664 return (0);
6666 else
6667 /* The error status indicates that only one set of fixed
6668 headers should be built. */
6669 fatal_error ("not configured with sysroot headers suffix");
6672 if (print_help_list)
6674 display_help ();
6676 if (! verbose_flag)
6678 printf (_("\nFor bug reporting instructions, please see:\n"));
6679 printf ("%s.\n", bug_report_url);
6681 return (0);
6684 /* We do not exit here. Instead we have created a fake input file
6685 called 'help-dummy' which needs to be compiled, and we pass this
6686 on the various sub-processes, along with the --help switch.
6687 Ensure their output appears after ours. */
6688 fputc ('\n', stdout);
6689 fflush (stdout);
6692 if (print_version)
6694 printf (_("%s %s%s\n"), progname, pkgversion_string,
6695 version_string);
6696 printf ("Copyright %s 2012 Free Software Foundation, Inc.\n",
6697 _("(C)"));
6698 fputs (_("This is free software; see the source for copying conditions. There is NO\n\
6699 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"),
6700 stdout);
6701 if (! verbose_flag)
6702 return 0;
6704 /* We do not exit here. We use the same mechanism of --help to print
6705 the version of the sub-processes. */
6706 fputc ('\n', stdout);
6707 fflush (stdout);
6710 if (verbose_flag)
6712 int n;
6713 const char *thrmod;
6715 fnotice (stderr, "Target: %s\n", spec_machine);
6716 fnotice (stderr, "Configured with: %s\n", configuration_arguments);
6718 #ifdef THREAD_MODEL_SPEC
6719 /* We could have defined THREAD_MODEL_SPEC to "%*" by default,
6720 but there's no point in doing all this processing just to get
6721 thread_model back. */
6722 obstack_init (&obstack);
6723 do_spec_1 (THREAD_MODEL_SPEC, 0, thread_model);
6724 obstack_1grow (&obstack, '\0');
6725 thrmod = XOBFINISH (&obstack, const char *);
6726 #else
6727 thrmod = thread_model;
6728 #endif
6730 fnotice (stderr, "Thread model: %s\n", thrmod);
6732 /* compiler_version is truncated at the first space when initialized
6733 from version string, so truncate version_string at the first space
6734 before comparing. */
6735 for (n = 0; version_string[n]; n++)
6736 if (version_string[n] == ' ')
6737 break;
6739 if (! strncmp (version_string, compiler_version, n)
6740 && compiler_version[n] == 0)
6741 fnotice (stderr, "gcc version %s %s\n", version_string,
6742 pkgversion_string);
6743 else
6744 fnotice (stderr, "gcc driver version %s %sexecuting gcc version %s\n",
6745 version_string, pkgversion_string, compiler_version);
6747 if (n_infiles == 0)
6748 return (0);
6751 if (n_infiles == added_libraries)
6752 fatal_error ("no input files");
6754 if (seen_error ())
6755 goto out;
6757 /* Make a place to record the compiler output file names
6758 that correspond to the input files. */
6760 i = n_infiles;
6761 i += lang_specific_extra_outfiles;
6762 outfiles = XCNEWVEC (const char *, i);
6764 /* Record which files were specified explicitly as link input. */
6766 explicit_link_files = XCNEWVEC (char, n_infiles);
6768 combine_inputs = have_o || flag_wpa;
6770 for (i = 0; (int) i < n_infiles; i++)
6772 const char *name = infiles[i].name;
6773 struct compiler *compiler = lookup_compiler (name,
6774 strlen (name),
6775 infiles[i].language);
6777 if (compiler && !(compiler->combinable))
6778 combine_inputs = false;
6780 if (lang_n_infiles > 0 && compiler != input_file_compiler
6781 && infiles[i].language && infiles[i].language[0] != '*')
6782 infiles[i].incompiler = compiler;
6783 else if (compiler)
6785 lang_n_infiles++;
6786 input_file_compiler = compiler;
6787 infiles[i].incompiler = compiler;
6789 else
6791 /* Since there is no compiler for this input file, assume it is a
6792 linker file. */
6793 explicit_link_files[i] = 1;
6794 infiles[i].incompiler = NULL;
6796 infiles[i].compiled = false;
6797 infiles[i].preprocessed = false;
6800 if (!combine_inputs && have_c && have_o && lang_n_infiles > 1)
6801 fatal_error ("cannot specify -o with -c, -S or -E with multiple files");
6803 for (i = 0; (int) i < n_infiles; i++)
6805 int this_file_error = 0;
6807 /* Tell do_spec what to substitute for %i. */
6809 input_file_number = i;
6810 set_input (infiles[i].name);
6812 if (infiles[i].compiled)
6813 continue;
6815 /* Use the same thing in %o, unless cp->spec says otherwise. */
6817 outfiles[i] = gcc_input_filename;
6819 /* Figure out which compiler from the file's suffix. */
6821 input_file_compiler
6822 = lookup_compiler (infiles[i].name, input_filename_length,
6823 infiles[i].language);
6825 if (input_file_compiler)
6827 /* Ok, we found an applicable compiler. Run its spec. */
6829 if (input_file_compiler->spec[0] == '#')
6831 error ("%s: %s compiler not installed on this system",
6832 gcc_input_filename, &input_file_compiler->spec[1]);
6833 this_file_error = 1;
6835 else
6837 if (compare_debug)
6839 free (debug_check_temp_file[0]);
6840 debug_check_temp_file[0] = NULL;
6842 free (debug_check_temp_file[1]);
6843 debug_check_temp_file[1] = NULL;
6846 value = do_spec (input_file_compiler->spec);
6847 infiles[i].compiled = true;
6848 if (value < 0)
6849 this_file_error = 1;
6850 else if (compare_debug && debug_check_temp_file[0])
6852 if (verbose_flag)
6853 inform (0, "recompiling with -fcompare-debug");
6855 compare_debug = -compare_debug;
6856 n_switches = n_switches_debug_check[1];
6857 n_switches_alloc = n_switches_alloc_debug_check[1];
6858 switches = switches_debug_check[1];
6860 value = do_spec (input_file_compiler->spec);
6862 compare_debug = -compare_debug;
6863 n_switches = n_switches_debug_check[0];
6864 n_switches_alloc = n_switches_alloc_debug_check[0];
6865 switches = switches_debug_check[0];
6867 if (value < 0)
6869 error ("during -fcompare-debug recompilation");
6870 this_file_error = 1;
6873 gcc_assert (debug_check_temp_file[1]
6874 && filename_cmp (debug_check_temp_file[0],
6875 debug_check_temp_file[1]));
6877 if (verbose_flag)
6878 inform (0, "comparing final insns dumps");
6880 if (compare_files (debug_check_temp_file))
6881 this_file_error = 1;
6884 if (compare_debug)
6886 free (debug_check_temp_file[0]);
6887 debug_check_temp_file[0] = NULL;
6889 free (debug_check_temp_file[1]);
6890 debug_check_temp_file[1] = NULL;
6895 /* If this file's name does not contain a recognized suffix,
6896 record it as explicit linker input. */
6898 else
6899 explicit_link_files[i] = 1;
6901 /* Clear the delete-on-failure queue, deleting the files in it
6902 if this compilation failed. */
6904 if (this_file_error)
6906 delete_failure_queue ();
6907 errorcount++;
6909 /* If this compilation succeeded, don't delete those files later. */
6910 clear_failure_queue ();
6913 /* Reset the input file name to the first compile/object file name, for use
6914 with %b in LINK_SPEC. We use the first input file that we can find
6915 a compiler to compile it instead of using infiles.language since for
6916 languages other than C we use aliases that we then lookup later. */
6917 if (n_infiles > 0)
6919 int i;
6921 for (i = 0; i < n_infiles ; i++)
6922 if (infiles[i].incompiler
6923 || (infiles[i].language && infiles[i].language[0] != '*'))
6925 set_input (infiles[i].name);
6926 break;
6930 if (!seen_error ())
6932 /* Make sure INPUT_FILE_NUMBER points to first available open
6933 slot. */
6934 input_file_number = n_infiles;
6935 if (lang_specific_pre_link ())
6936 errorcount++;
6939 /* Determine if there are any linker input files. */
6940 num_linker_inputs = 0;
6941 for (i = 0; (int) i < n_infiles; i++)
6942 if (explicit_link_files[i] || outfiles[i] != NULL)
6943 num_linker_inputs++;
6945 /* Run ld to link all the compiler output files. */
6947 if (num_linker_inputs > 0 && !seen_error () && print_subprocess_help < 2)
6949 int tmp = execution_count;
6951 if (! have_c)
6953 #if HAVE_LTO_PLUGIN > 0
6954 #if HAVE_LTO_PLUGIN == 2
6955 const char *fno_use_linker_plugin = "fno-use-linker-plugin";
6956 #else
6957 const char *fuse_linker_plugin = "fuse-linker-plugin";
6958 #endif
6959 #endif
6961 /* We'll use ld if we can't find collect2. */
6962 if (! strcmp (linker_name_spec, "collect2"))
6964 char *s = find_a_file (&exec_prefixes, "collect2", X_OK, false);
6965 if (s == NULL)
6966 linker_name_spec = "ld";
6969 #if HAVE_LTO_PLUGIN > 0
6970 #if HAVE_LTO_PLUGIN == 2
6971 if (!switch_matches (fno_use_linker_plugin,
6972 fno_use_linker_plugin
6973 + strlen (fno_use_linker_plugin), 0))
6974 #else
6975 if (switch_matches (fuse_linker_plugin,
6976 fuse_linker_plugin
6977 + strlen (fuse_linker_plugin), 0))
6978 #endif
6980 linker_plugin_file_spec = find_a_file (&exec_prefixes,
6981 LTOPLUGINSONAME, R_OK,
6982 false);
6983 if (!linker_plugin_file_spec)
6984 fatal_error ("-fuse-linker-plugin, but %s not found",
6985 LTOPLUGINSONAME);
6987 #endif
6988 lto_gcc_spec = argv[0];
6991 /* Rebuild the COMPILER_PATH and LIBRARY_PATH environment variables
6992 for collect. */
6993 putenv_from_prefixes (&exec_prefixes, "COMPILER_PATH", false);
6994 putenv_from_prefixes (&startfile_prefixes, LIBRARY_PATH_ENV, true);
6996 if (print_subprocess_help == 1)
6998 printf (_("\nLinker options\n==============\n\n"));
6999 printf (_("Use \"-Wl,OPTION\" to pass \"OPTION\""
7000 " to the linker.\n\n"));
7001 fflush (stdout);
7003 value = do_spec (link_command_spec);
7004 if (value < 0)
7005 errorcount = 1;
7006 linker_was_run = (tmp != execution_count);
7009 /* If options said don't run linker,
7010 complain about input files to be given to the linker. */
7012 if (! linker_was_run && !seen_error ())
7013 for (i = 0; (int) i < n_infiles; i++)
7014 if (explicit_link_files[i]
7015 && !(infiles[i].language && infiles[i].language[0] == '*'))
7016 warning (0, "%s: linker input file unused because linking not done",
7017 outfiles[i]);
7019 /* Delete some or all of the temporary files we made. */
7021 if (seen_error ())
7022 delete_failure_queue ();
7023 delete_temp_files ();
7025 if (print_help_list)
7027 printf (("\nFor bug reporting instructions, please see:\n"));
7028 printf ("%s\n", bug_report_url);
7031 out:
7032 return (signal_count != 0 ? 2
7033 : seen_error () ? (pass_exit_codes ? greatest_status : 1)
7034 : 0);
7037 /* Find the proper compilation spec for the file name NAME,
7038 whose length is LENGTH. LANGUAGE is the specified language,
7039 or 0 if this file is to be passed to the linker. */
7041 static struct compiler *
7042 lookup_compiler (const char *name, size_t length, const char *language)
7044 struct compiler *cp;
7046 /* If this was specified by the user to be a linker input, indicate that. */
7047 if (language != 0 && language[0] == '*')
7048 return 0;
7050 /* Otherwise, look for the language, if one is spec'd. */
7051 if (language != 0)
7053 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7054 if (cp->suffix[0] == '@' && !strcmp (cp->suffix + 1, language))
7055 return cp;
7057 error ("language %s not recognized", language);
7058 return 0;
7061 /* Look for a suffix. */
7062 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7064 if (/* The suffix `-' matches only the file name `-'. */
7065 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
7066 || (strlen (cp->suffix) < length
7067 /* See if the suffix matches the end of NAME. */
7068 && !strcmp (cp->suffix,
7069 name + length - strlen (cp->suffix))
7071 break;
7074 #if defined (OS2) ||defined (HAVE_DOS_BASED_FILE_SYSTEM)
7075 /* Look again, but case-insensitively this time. */
7076 if (cp < compilers)
7077 for (cp = compilers + n_compilers - 1; cp >= compilers; cp--)
7079 if (/* The suffix `-' matches only the file name `-'. */
7080 (!strcmp (cp->suffix, "-") && !strcmp (name, "-"))
7081 || (strlen (cp->suffix) < length
7082 /* See if the suffix matches the end of NAME. */
7083 && ((!strcmp (cp->suffix,
7084 name + length - strlen (cp->suffix))
7085 || !strpbrk (cp->suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
7086 && !strcasecmp (cp->suffix,
7087 name + length - strlen (cp->suffix)))
7089 break;
7091 #endif
7093 if (cp >= compilers)
7095 if (cp->spec[0] != '@')
7096 /* A non-alias entry: return it. */
7097 return cp;
7099 /* An alias entry maps a suffix to a language.
7100 Search for the language; pass 0 for NAME and LENGTH
7101 to avoid infinite recursion if language not found. */
7102 return lookup_compiler (NULL, 0, cp->spec + 1);
7104 return 0;
7107 static char *
7108 save_string (const char *s, int len)
7110 char *result = XNEWVEC (char, len + 1);
7112 memcpy (result, s, len);
7113 result[len] = 0;
7114 return result;
7117 void
7118 pfatal_with_name (const char *name)
7120 perror_with_name (name);
7121 delete_temp_files ();
7122 exit (1);
7125 static void
7126 perror_with_name (const char *name)
7128 error ("%s: %m", name);
7131 static inline void
7132 validate_switches_from_spec (const char *spec, bool user)
7134 const char *p = spec;
7135 char c;
7136 while ((c = *p++))
7137 if (c == '%' && (*p == '{' || *p == '<' || (*p == 'W' && *++p == '{')))
7138 /* We have a switch spec. */
7139 p = validate_switches (p + 1, user);
7142 static void
7143 validate_all_switches (void)
7145 struct compiler *comp;
7146 struct spec_list *spec;
7148 for (comp = compilers; comp->spec; comp++)
7149 validate_switches_from_spec (comp->spec, false);
7151 /* Look through the linked list of specs read from the specs file. */
7152 for (spec = specs; spec; spec = spec->next)
7153 validate_switches_from_spec (*spec->ptr_spec, spec->user_p);
7155 validate_switches_from_spec (link_command_spec, false);
7158 /* Look at the switch-name that comes after START
7159 and mark as valid all supplied switches that match it. */
7161 static const char *
7162 validate_switches (const char *start, bool user_spec)
7164 const char *p = start;
7165 const char *atom;
7166 size_t len;
7167 int i;
7168 bool suffix = false;
7169 bool starred = false;
7171 #define SKIP_WHITE() do { while (*p == ' ' || *p == '\t') p++; } while (0)
7173 next_member:
7174 SKIP_WHITE ();
7176 if (*p == '!')
7177 p++;
7179 SKIP_WHITE ();
7180 if (*p == '.' || *p == ',')
7181 suffix = true, p++;
7183 atom = p;
7184 while (ISIDNUM (*p) || *p == '-' || *p == '+' || *p == '='
7185 || *p == ',' || *p == '.' || *p == '@')
7186 p++;
7187 len = p - atom;
7189 if (*p == '*')
7190 starred = true, p++;
7192 SKIP_WHITE ();
7194 if (!suffix)
7196 /* Mark all matching switches as valid. */
7197 for (i = 0; i < n_switches; i++)
7198 if (!strncmp (switches[i].part1, atom, len)
7199 && (starred || switches[i].part1[len] == '\0')
7200 && (switches[i].known || user_spec))
7201 switches[i].validated = true;
7204 if (*p) p++;
7205 if (*p && (p[-1] == '|' || p[-1] == '&'))
7206 goto next_member;
7208 if (*p && p[-1] == ':')
7210 while (*p && *p != ';' && *p != '}')
7212 if (*p == '%')
7214 p++;
7215 if (*p == '{' || *p == '<')
7216 p = validate_switches (p+1, user_spec);
7217 else if (p[0] == 'W' && p[1] == '{')
7218 p = validate_switches (p+2, user_spec);
7220 else
7221 p++;
7224 if (*p) p++;
7225 if (*p && p[-1] == ';')
7226 goto next_member;
7229 return p;
7230 #undef SKIP_WHITE
7233 struct mdswitchstr
7235 const char *str;
7236 int len;
7239 static struct mdswitchstr *mdswitches;
7240 static int n_mdswitches;
7242 /* Check whether a particular argument was used. The first time we
7243 canonicalize the switches to keep only the ones we care about. */
7245 static int
7246 used_arg (const char *p, int len)
7248 struct mswitchstr
7250 const char *str;
7251 const char *replace;
7252 int len;
7253 int rep_len;
7256 static struct mswitchstr *mswitches;
7257 static int n_mswitches;
7258 int i, j;
7260 if (!mswitches)
7262 struct mswitchstr *matches;
7263 const char *q;
7264 int cnt = 0;
7266 /* Break multilib_matches into the component strings of string
7267 and replacement string. */
7268 for (q = multilib_matches; *q != '\0'; q++)
7269 if (*q == ';')
7270 cnt++;
7272 matches
7273 = (struct mswitchstr *) alloca ((sizeof (struct mswitchstr)) * cnt);
7274 i = 0;
7275 q = multilib_matches;
7276 while (*q != '\0')
7278 matches[i].str = q;
7279 while (*q != ' ')
7281 if (*q == '\0')
7283 invalid_matches:
7284 fatal_error ("multilib spec %qs is invalid",
7285 multilib_matches);
7287 q++;
7289 matches[i].len = q - matches[i].str;
7291 matches[i].replace = ++q;
7292 while (*q != ';' && *q != '\0')
7294 if (*q == ' ')
7295 goto invalid_matches;
7296 q++;
7298 matches[i].rep_len = q - matches[i].replace;
7299 i++;
7300 if (*q == ';')
7301 q++;
7304 /* Now build a list of the replacement string for switches that we care
7305 about. Make sure we allocate at least one entry. This prevents
7306 xmalloc from calling fatal, and prevents us from re-executing this
7307 block of code. */
7308 mswitches
7309 = XNEWVEC (struct mswitchstr, n_mdswitches + (n_switches ? n_switches : 1));
7310 for (i = 0; i < n_switches; i++)
7311 if ((switches[i].live_cond & SWITCH_IGNORE) == 0)
7313 int xlen = strlen (switches[i].part1);
7314 for (j = 0; j < cnt; j++)
7315 if (xlen == matches[j].len
7316 && ! strncmp (switches[i].part1, matches[j].str, xlen))
7318 mswitches[n_mswitches].str = matches[j].replace;
7319 mswitches[n_mswitches].len = matches[j].rep_len;
7320 mswitches[n_mswitches].replace = (char *) 0;
7321 mswitches[n_mswitches].rep_len = 0;
7322 n_mswitches++;
7323 break;
7327 /* Add MULTILIB_DEFAULTS switches too, as long as they were not present
7328 on the command line nor any options mutually incompatible with
7329 them. */
7330 for (i = 0; i < n_mdswitches; i++)
7332 const char *r;
7334 for (q = multilib_options; *q != '\0'; q++)
7336 while (*q == ' ')
7337 q++;
7339 r = q;
7340 while (strncmp (q, mdswitches[i].str, mdswitches[i].len) != 0
7341 || strchr (" /", q[mdswitches[i].len]) == NULL)
7343 while (*q != ' ' && *q != '/' && *q != '\0')
7344 q++;
7345 if (*q != '/')
7346 break;
7347 q++;
7350 if (*q != ' ' && *q != '\0')
7352 while (*r != ' ' && *r != '\0')
7354 q = r;
7355 while (*q != ' ' && *q != '/' && *q != '\0')
7356 q++;
7358 if (used_arg (r, q - r))
7359 break;
7361 if (*q != '/')
7363 mswitches[n_mswitches].str = mdswitches[i].str;
7364 mswitches[n_mswitches].len = mdswitches[i].len;
7365 mswitches[n_mswitches].replace = (char *) 0;
7366 mswitches[n_mswitches].rep_len = 0;
7367 n_mswitches++;
7368 break;
7371 r = q + 1;
7373 break;
7379 for (i = 0; i < n_mswitches; i++)
7380 if (len == mswitches[i].len && ! strncmp (p, mswitches[i].str, len))
7381 return 1;
7383 return 0;
7386 static int
7387 default_arg (const char *p, int len)
7389 int i;
7391 for (i = 0; i < n_mdswitches; i++)
7392 if (len == mdswitches[i].len && ! strncmp (p, mdswitches[i].str, len))
7393 return 1;
7395 return 0;
7398 /* Work out the subdirectory to use based on the options. The format of
7399 multilib_select is a list of elements. Each element is a subdirectory
7400 name followed by a list of options followed by a semicolon. The format
7401 of multilib_exclusions is the same, but without the preceding
7402 directory. First gcc will check the exclusions, if none of the options
7403 beginning with an exclamation point are present, and all of the other
7404 options are present, then we will ignore this completely. Passing
7405 that, gcc will consider each multilib_select in turn using the same
7406 rules for matching the options. If a match is found, that subdirectory
7407 will be used.
7408 A subdirectory name is optionally followed by a colon and the corresponding
7409 multiarch name. */
7411 static void
7412 set_multilib_dir (void)
7414 const char *p;
7415 unsigned int this_path_len;
7416 const char *this_path, *this_arg;
7417 const char *start, *end;
7418 int not_arg;
7419 int ok, ndfltok, first;
7421 n_mdswitches = 0;
7422 start = multilib_defaults;
7423 while (*start == ' ' || *start == '\t')
7424 start++;
7425 while (*start != '\0')
7427 n_mdswitches++;
7428 while (*start != ' ' && *start != '\t' && *start != '\0')
7429 start++;
7430 while (*start == ' ' || *start == '\t')
7431 start++;
7434 if (n_mdswitches)
7436 int i = 0;
7438 mdswitches = XNEWVEC (struct mdswitchstr, n_mdswitches);
7439 for (start = multilib_defaults; *start != '\0'; start = end + 1)
7441 while (*start == ' ' || *start == '\t')
7442 start++;
7444 if (*start == '\0')
7445 break;
7447 for (end = start + 1;
7448 *end != ' ' && *end != '\t' && *end != '\0'; end++)
7451 obstack_grow (&multilib_obstack, start, end - start);
7452 obstack_1grow (&multilib_obstack, 0);
7453 mdswitches[i].str = XOBFINISH (&multilib_obstack, const char *);
7454 mdswitches[i++].len = end - start;
7456 if (*end == '\0')
7457 break;
7461 p = multilib_exclusions;
7462 while (*p != '\0')
7464 /* Ignore newlines. */
7465 if (*p == '\n')
7467 ++p;
7468 continue;
7471 /* Check the arguments. */
7472 ok = 1;
7473 while (*p != ';')
7475 if (*p == '\0')
7477 invalid_exclusions:
7478 fatal_error ("multilib exclusions %qs is invalid",
7479 multilib_exclusions);
7482 if (! ok)
7484 ++p;
7485 continue;
7488 this_arg = p;
7489 while (*p != ' ' && *p != ';')
7491 if (*p == '\0')
7492 goto invalid_exclusions;
7493 ++p;
7496 if (*this_arg != '!')
7497 not_arg = 0;
7498 else
7500 not_arg = 1;
7501 ++this_arg;
7504 ok = used_arg (this_arg, p - this_arg);
7505 if (not_arg)
7506 ok = ! ok;
7508 if (*p == ' ')
7509 ++p;
7512 if (ok)
7513 return;
7515 ++p;
7518 first = 1;
7519 p = multilib_select;
7520 while (*p != '\0')
7522 /* Ignore newlines. */
7523 if (*p == '\n')
7525 ++p;
7526 continue;
7529 /* Get the initial path. */
7530 this_path = p;
7531 while (*p != ' ')
7533 if (*p == '\0')
7535 invalid_select:
7536 fatal_error ("multilib select %qs is invalid",
7537 multilib_select);
7539 ++p;
7541 this_path_len = p - this_path;
7543 /* Check the arguments. */
7544 ok = 1;
7545 ndfltok = 1;
7546 ++p;
7547 while (*p != ';')
7549 if (*p == '\0')
7550 goto invalid_select;
7552 if (! ok)
7554 ++p;
7555 continue;
7558 this_arg = p;
7559 while (*p != ' ' && *p != ';')
7561 if (*p == '\0')
7562 goto invalid_select;
7563 ++p;
7566 if (*this_arg != '!')
7567 not_arg = 0;
7568 else
7570 not_arg = 1;
7571 ++this_arg;
7574 /* If this is a default argument, we can just ignore it.
7575 This is true even if this_arg begins with '!'. Beginning
7576 with '!' does not mean that this argument is necessarily
7577 inappropriate for this library: it merely means that
7578 there is a more specific library which uses this
7579 argument. If this argument is a default, we need not
7580 consider that more specific library. */
7581 ok = used_arg (this_arg, p - this_arg);
7582 if (not_arg)
7583 ok = ! ok;
7585 if (! ok)
7586 ndfltok = 0;
7588 if (default_arg (this_arg, p - this_arg))
7589 ok = 1;
7591 if (*p == ' ')
7592 ++p;
7595 if (ok && first)
7597 if (this_path_len != 1
7598 || this_path[0] != '.')
7600 char *new_multilib_dir = XNEWVEC (char, this_path_len + 1);
7601 char *q;
7603 strncpy (new_multilib_dir, this_path, this_path_len);
7604 new_multilib_dir[this_path_len] = '\0';
7605 q = strchr (new_multilib_dir, ':');
7606 if (q != NULL)
7607 *q = '\0';
7608 multilib_dir = new_multilib_dir;
7610 first = 0;
7613 if (ndfltok)
7615 const char *q = this_path, *end = this_path + this_path_len;
7617 while (q < end && *q != ':')
7618 q++;
7619 if (q < end)
7621 const char *q2 = q + 1, *ml_end = end;
7622 char *new_multilib_os_dir;
7624 while (q2 < end && *q2 != ':')
7625 q2++;
7626 if (*q2 == ':')
7627 ml_end = q2;
7628 new_multilib_os_dir = XNEWVEC (char, ml_end - q);
7629 memcpy (new_multilib_os_dir, q + 1, ml_end - q - 1);
7630 new_multilib_os_dir[ml_end - q - 1] = '\0';
7631 multilib_os_dir = *new_multilib_os_dir ? new_multilib_os_dir : ".";
7633 if (q2 < end && *q2 == ':')
7635 char *new_multiarch_dir = XNEWVEC (char, end - q2);
7636 memcpy (new_multiarch_dir, q2 + 1, end - q2 - 1);
7637 new_multiarch_dir[end - q2 - 1] = '\0';
7638 multiarch_dir = new_multiarch_dir;
7640 break;
7644 ++p;
7647 if (multilib_dir == NULL && multilib_os_dir != NULL
7648 && strcmp (multilib_os_dir, ".") == 0)
7650 free (CONST_CAST (char *, multilib_os_dir));
7651 multilib_os_dir = NULL;
7653 else if (multilib_dir != NULL && multilib_os_dir == NULL)
7654 multilib_os_dir = multilib_dir;
7657 /* Print out the multiple library subdirectory selection
7658 information. This prints out a series of lines. Each line looks
7659 like SUBDIRECTORY;@OPTION@OPTION, with as many options as is
7660 required. Only the desired options are printed out, the negative
7661 matches. The options are print without a leading dash. There are
7662 no spaces to make it easy to use the information in the shell.
7663 Each subdirectory is printed only once. This assumes the ordering
7664 generated by the genmultilib script. Also, we leave out ones that match
7665 the exclusions. */
7667 static void
7668 print_multilib_info (void)
7670 const char *p = multilib_select;
7671 const char *last_path = 0, *this_path;
7672 int skip;
7673 unsigned int last_path_len = 0;
7675 while (*p != '\0')
7677 skip = 0;
7678 /* Ignore newlines. */
7679 if (*p == '\n')
7681 ++p;
7682 continue;
7685 /* Get the initial path. */
7686 this_path = p;
7687 while (*p != ' ')
7689 if (*p == '\0')
7691 invalid_select:
7692 fatal_error ("multilib select %qs is invalid", multilib_select);
7695 ++p;
7698 /* When --disable-multilib was used but target defines
7699 MULTILIB_OSDIRNAMES, entries starting with .: (and not starting
7700 with .:: for multiarch configurations) are there just to find
7701 multilib_os_dir, so skip them from output. */
7702 if (this_path[0] == '.' && this_path[1] == ':' && this_path[2] != ':')
7703 skip = 1;
7705 /* Check for matches with the multilib_exclusions. We don't bother
7706 with the '!' in either list. If any of the exclusion rules match
7707 all of its options with the select rule, we skip it. */
7709 const char *e = multilib_exclusions;
7710 const char *this_arg;
7712 while (*e != '\0')
7714 int m = 1;
7715 /* Ignore newlines. */
7716 if (*e == '\n')
7718 ++e;
7719 continue;
7722 /* Check the arguments. */
7723 while (*e != ';')
7725 const char *q;
7726 int mp = 0;
7728 if (*e == '\0')
7730 invalid_exclusion:
7731 fatal_error ("multilib exclusion %qs is invalid",
7732 multilib_exclusions);
7735 if (! m)
7737 ++e;
7738 continue;
7741 this_arg = e;
7743 while (*e != ' ' && *e != ';')
7745 if (*e == '\0')
7746 goto invalid_exclusion;
7747 ++e;
7750 q = p + 1;
7751 while (*q != ';')
7753 const char *arg;
7754 int len = e - this_arg;
7756 if (*q == '\0')
7757 goto invalid_select;
7759 arg = q;
7761 while (*q != ' ' && *q != ';')
7763 if (*q == '\0')
7764 goto invalid_select;
7765 ++q;
7768 if (! strncmp (arg, this_arg,
7769 (len < q - arg) ? q - arg : len)
7770 || default_arg (this_arg, e - this_arg))
7772 mp = 1;
7773 break;
7776 if (*q == ' ')
7777 ++q;
7780 if (! mp)
7781 m = 0;
7783 if (*e == ' ')
7784 ++e;
7787 if (m)
7789 skip = 1;
7790 break;
7793 if (*e != '\0')
7794 ++e;
7798 if (! skip)
7800 /* If this is a duplicate, skip it. */
7801 skip = (last_path != 0
7802 && (unsigned int) (p - this_path) == last_path_len
7803 && ! filename_ncmp (last_path, this_path, last_path_len));
7805 last_path = this_path;
7806 last_path_len = p - this_path;
7809 /* If this directory requires any default arguments, we can skip
7810 it. We will already have printed a directory identical to
7811 this one which does not require that default argument. */
7812 if (! skip)
7814 const char *q;
7816 q = p + 1;
7817 while (*q != ';')
7819 const char *arg;
7821 if (*q == '\0')
7822 goto invalid_select;
7824 if (*q == '!')
7825 arg = NULL;
7826 else
7827 arg = q;
7829 while (*q != ' ' && *q != ';')
7831 if (*q == '\0')
7832 goto invalid_select;
7833 ++q;
7836 if (arg != NULL
7837 && default_arg (arg, q - arg))
7839 skip = 1;
7840 break;
7843 if (*q == ' ')
7844 ++q;
7848 if (! skip)
7850 const char *p1;
7852 for (p1 = last_path; p1 < p && *p1 != ':'; p1++)
7853 putchar (*p1);
7854 putchar (';');
7857 ++p;
7858 while (*p != ';')
7860 int use_arg;
7862 if (*p == '\0')
7863 goto invalid_select;
7865 if (skip)
7867 ++p;
7868 continue;
7871 use_arg = *p != '!';
7873 if (use_arg)
7874 putchar ('@');
7876 while (*p != ' ' && *p != ';')
7878 if (*p == '\0')
7879 goto invalid_select;
7880 if (use_arg)
7881 putchar (*p);
7882 ++p;
7885 if (*p == ' ')
7886 ++p;
7889 if (! skip)
7891 /* If there are extra options, print them now. */
7892 if (multilib_extra && *multilib_extra)
7894 int print_at = TRUE;
7895 const char *q;
7897 for (q = multilib_extra; *q != '\0'; q++)
7899 if (*q == ' ')
7900 print_at = TRUE;
7901 else
7903 if (print_at)
7904 putchar ('@');
7905 putchar (*q);
7906 print_at = FALSE;
7911 putchar ('\n');
7914 ++p;
7918 /* getenv built-in spec function.
7920 Returns the value of the environment variable given by its first
7921 argument, concatenated with the second argument. If the
7922 environment variable is not defined, a fatal error is issued. */
7924 static const char *
7925 getenv_spec_function (int argc, const char **argv)
7927 char *value;
7928 char *result;
7929 char *ptr;
7930 size_t len;
7932 if (argc != 2)
7933 return NULL;
7935 value = getenv (argv[0]);
7936 if (!value)
7937 fatal_error ("environment variable %qs not defined", argv[0]);
7939 /* We have to escape every character of the environment variable so
7940 they are not interpreted as active spec characters. A
7941 particularly painful case is when we are reading a variable
7942 holding a windows path complete with \ separators. */
7943 len = strlen (value) * 2 + strlen (argv[1]) + 1;
7944 result = XNEWVAR (char, len);
7945 for (ptr = result; *value; ptr += 2)
7947 ptr[0] = '\\';
7948 ptr[1] = *value++;
7951 strcpy (ptr, argv[1]);
7953 return result;
7956 /* if-exists built-in spec function.
7958 Checks to see if the file specified by the absolute pathname in
7959 ARGS exists. Returns that pathname if found.
7961 The usual use for this function is to check for a library file
7962 (whose name has been expanded with %s). */
7964 static const char *
7965 if_exists_spec_function (int argc, const char **argv)
7967 /* Must have only one argument. */
7968 if (argc == 1 && IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
7969 return argv[0];
7971 return NULL;
7974 /* if-exists-else built-in spec function.
7976 This is like if-exists, but takes an additional argument which
7977 is returned if the first argument does not exist. */
7979 static const char *
7980 if_exists_else_spec_function (int argc, const char **argv)
7982 /* Must have exactly two arguments. */
7983 if (argc != 2)
7984 return NULL;
7986 if (IS_ABSOLUTE_PATH (argv[0]) && ! access (argv[0], R_OK))
7987 return argv[0];
7989 return argv[1];
7992 /* replace-outfile built-in spec function.
7994 This looks for the first argument in the outfiles array's name and
7995 replaces it with the second argument. */
7997 static const char *
7998 replace_outfile_spec_function (int argc, const char **argv)
8000 int i;
8001 /* Must have exactly two arguments. */
8002 if (argc != 2)
8003 abort ();
8005 for (i = 0; i < n_infiles; i++)
8007 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
8008 outfiles[i] = xstrdup (argv[1]);
8010 return NULL;
8013 /* remove-outfile built-in spec function.
8015 * This looks for the first argument in the outfiles array's name and
8016 * removes it. */
8018 static const char *
8019 remove_outfile_spec_function (int argc, const char **argv)
8021 int i;
8022 /* Must have exactly one argument. */
8023 if (argc != 1)
8024 abort ();
8026 for (i = 0; i < n_infiles; i++)
8028 if (outfiles[i] && !filename_cmp (outfiles[i], argv[0]))
8029 outfiles[i] = NULL;
8031 return NULL;
8034 /* Given two version numbers, compares the two numbers.
8035 A version number must match the regular expression
8036 ([1-9][0-9]*|0)(\.([1-9][0-9]*|0))*
8038 static int
8039 compare_version_strings (const char *v1, const char *v2)
8041 int rresult;
8042 regex_t r;
8044 if (regcomp (&r, "^([1-9][0-9]*|0)(\\.([1-9][0-9]*|0))*$",
8045 REG_EXTENDED | REG_NOSUB) != 0)
8046 abort ();
8047 rresult = regexec (&r, v1, 0, NULL, 0);
8048 if (rresult == REG_NOMATCH)
8049 fatal_error ("invalid version number %qs", v1);
8050 else if (rresult != 0)
8051 abort ();
8052 rresult = regexec (&r, v2, 0, NULL, 0);
8053 if (rresult == REG_NOMATCH)
8054 fatal_error ("invalid version number %qs", v2);
8055 else if (rresult != 0)
8056 abort ();
8058 return strverscmp (v1, v2);
8062 /* version_compare built-in spec function.
8064 This takes an argument of the following form:
8066 <comparison-op> <arg1> [<arg2>] <switch> <result>
8068 and produces "result" if the comparison evaluates to true,
8069 and nothing if it doesn't.
8071 The supported <comparison-op> values are:
8073 >= true if switch is a later (or same) version than arg1
8074 !> opposite of >=
8075 < true if switch is an earlier version than arg1
8076 !< opposite of <
8077 >< true if switch is arg1 or later, and earlier than arg2
8078 <> true if switch is earlier than arg1 or is arg2 or later
8080 If the switch is not present, the condition is false unless
8081 the first character of the <comparison-op> is '!'.
8083 For example,
8084 %:version-compare(>= 10.3 mmacosx-version-min= -lmx)
8085 adds -lmx if -mmacosx-version-min=10.3.9 was passed. */
8087 static const char *
8088 version_compare_spec_function (int argc, const char **argv)
8090 int comp1, comp2;
8091 size_t switch_len;
8092 const char *switch_value = NULL;
8093 int nargs = 1, i;
8094 bool result;
8096 if (argc < 3)
8097 fatal_error ("too few arguments to %%:version-compare");
8098 if (argv[0][0] == '\0')
8099 abort ();
8100 if ((argv[0][1] == '<' || argv[0][1] == '>') && argv[0][0] != '!')
8101 nargs = 2;
8102 if (argc != nargs + 3)
8103 fatal_error ("too many arguments to %%:version-compare");
8105 switch_len = strlen (argv[nargs + 1]);
8106 for (i = 0; i < n_switches; i++)
8107 if (!strncmp (switches[i].part1, argv[nargs + 1], switch_len)
8108 && check_live_switch (i, switch_len))
8109 switch_value = switches[i].part1 + switch_len;
8111 if (switch_value == NULL)
8112 comp1 = comp2 = -1;
8113 else
8115 comp1 = compare_version_strings (switch_value, argv[1]);
8116 if (nargs == 2)
8117 comp2 = compare_version_strings (switch_value, argv[2]);
8118 else
8119 comp2 = -1; /* This value unused. */
8122 switch (argv[0][0] << 8 | argv[0][1])
8124 case '>' << 8 | '=':
8125 result = comp1 >= 0;
8126 break;
8127 case '!' << 8 | '<':
8128 result = comp1 >= 0 || switch_value == NULL;
8129 break;
8130 case '<' << 8:
8131 result = comp1 < 0;
8132 break;
8133 case '!' << 8 | '>':
8134 result = comp1 < 0 || switch_value == NULL;
8135 break;
8136 case '>' << 8 | '<':
8137 result = comp1 >= 0 && comp2 < 0;
8138 break;
8139 case '<' << 8 | '>':
8140 result = comp1 < 0 || comp2 >= 0;
8141 break;
8143 default:
8144 fatal_error ("unknown operator %qs in %%:version-compare", argv[0]);
8146 if (! result)
8147 return NULL;
8149 return argv[nargs + 2];
8152 /* %:include builtin spec function. This differs from %include in that it
8153 can be nested inside a spec, and thus be conditionalized. It takes
8154 one argument, the filename, and looks for it in the startfile path.
8155 The result is always NULL, i.e. an empty expansion. */
8157 static const char *
8158 include_spec_function (int argc, const char **argv)
8160 char *file;
8162 if (argc != 1)
8163 abort ();
8165 file = find_a_file (&startfile_prefixes, argv[0], R_OK, true);
8166 read_specs (file ? file : argv[0], false, false);
8168 return NULL;
8171 /* %:find-file spec function. This function replaces its argument by
8172 the file found through find_file, that is the -print-file-name gcc
8173 program option. */
8174 static const char *
8175 find_file_spec_function (int argc, const char **argv)
8177 const char *file;
8179 if (argc != 1)
8180 abort ();
8182 file = find_file (argv[0]);
8183 return file;
8187 /* %:find-plugindir spec function. This function replaces its argument
8188 by the -iplugindir=<dir> option. `dir' is found through find_file, that
8189 is the -print-file-name gcc program option. */
8190 static const char *
8191 find_plugindir_spec_function (int argc, const char **argv ATTRIBUTE_UNUSED)
8193 const char *option;
8195 if (argc != 0)
8196 abort ();
8198 option = concat ("-iplugindir=", find_file ("plugin"), NULL);
8199 return option;
8203 /* %:print-asm-header spec function. Print a banner to say that the
8204 following output is from the assembler. */
8206 static const char *
8207 print_asm_header_spec_function (int arg ATTRIBUTE_UNUSED,
8208 const char **argv ATTRIBUTE_UNUSED)
8210 printf (_("Assembler options\n=================\n\n"));
8211 printf (_("Use \"-Wa,OPTION\" to pass \"OPTION\" to the assembler.\n\n"));
8212 fflush (stdout);
8213 return NULL;
8216 /* Get a random number for -frandom-seed */
8218 static unsigned HOST_WIDE_INT
8219 get_random_number (void)
8221 unsigned HOST_WIDE_INT ret = 0;
8222 int fd;
8224 fd = open ("/dev/urandom", O_RDONLY);
8225 if (fd >= 0)
8227 read (fd, &ret, sizeof (HOST_WIDE_INT));
8228 close (fd);
8229 if (ret)
8230 return ret;
8233 /* Get some more or less random data. */
8234 #ifdef HAVE_GETTIMEOFDAY
8236 struct timeval tv;
8238 gettimeofday (&tv, NULL);
8239 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
8241 #else
8243 time_t now = time (NULL);
8245 if (now != (time_t)-1)
8246 ret = (unsigned) now;
8248 #endif
8250 return ret ^ getpid();
8253 /* %:compare-debug-dump-opt spec function. Save the last argument,
8254 expected to be the last -fdump-final-insns option, or generate a
8255 temporary. */
8257 static const char *
8258 compare_debug_dump_opt_spec_function (int arg,
8259 const char **argv ATTRIBUTE_UNUSED)
8261 char *ret;
8262 char *name;
8263 int which;
8264 static char random_seed[HOST_BITS_PER_WIDE_INT / 4 + 3];
8266 if (arg != 0)
8267 fatal_error ("too many arguments to %%:compare-debug-dump-opt");
8269 do_spec_2 ("%{fdump-final-insns=*:%*}");
8270 do_spec_1 (" ", 0, NULL);
8272 if (VEC_length (const_char_p, argbuf) > 0
8273 && strcmp (argv[VEC_length (const_char_p, argbuf) - 1], "."))
8275 if (!compare_debug)
8276 return NULL;
8278 name = xstrdup (argv[VEC_length (const_char_p, argbuf) - 1]);
8279 ret = NULL;
8281 else
8283 const char *ext = NULL;
8285 if (VEC_length (const_char_p, argbuf) > 0)
8287 do_spec_2 ("%{o*:%*}%{!o:%{!S:%b%O}%{S:%b.s}}");
8288 ext = ".gkd";
8290 else if (!compare_debug)
8291 return NULL;
8292 else
8293 do_spec_2 ("%g.gkd");
8295 do_spec_1 (" ", 0, NULL);
8297 gcc_assert (VEC_length (const_char_p, argbuf) > 0);
8299 name = concat (VEC_last (const_char_p, argbuf), ext, NULL);
8301 ret = concat ("-fdump-final-insns=", name, NULL);
8304 which = compare_debug < 0;
8305 debug_check_temp_file[which] = name;
8307 if (!which)
8309 unsigned HOST_WIDE_INT value = get_random_number ();
8311 sprintf (random_seed, HOST_WIDE_INT_PRINT_HEX, value);
8314 if (*random_seed)
8316 char *tmp = ret;
8317 ret = concat ("%{!frandom-seed=*:-frandom-seed=", random_seed, "} ",
8318 ret, NULL);
8319 free (tmp);
8322 if (which)
8323 *random_seed = 0;
8325 return ret;
8328 static const char *debug_auxbase_opt;
8330 /* %:compare-debug-self-opt spec function. Expands to the options
8331 that are to be passed in the second compilation of
8332 compare-debug. */
8334 static const char *
8335 compare_debug_self_opt_spec_function (int arg,
8336 const char **argv ATTRIBUTE_UNUSED)
8338 if (arg != 0)
8339 fatal_error ("too many arguments to %%:compare-debug-self-opt");
8341 if (compare_debug >= 0)
8342 return NULL;
8344 do_spec_2 ("%{c|S:%{o*:%*}}");
8345 do_spec_1 (" ", 0, NULL);
8347 if (VEC_length (const_char_p, argbuf) > 0)
8348 debug_auxbase_opt = concat ("-auxbase-strip ",
8349 VEC_last (const_char_p, argbuf),
8350 NULL);
8351 else
8352 debug_auxbase_opt = NULL;
8354 return concat ("\
8355 %<o %<MD %<MMD %<MF* %<MG %<MP %<MQ* %<MT* \
8356 %<fdump-final-insns=* -w -S -o %j \
8357 %{!fcompare-debug-second:-fcompare-debug-second} \
8358 ", compare_debug_opt, NULL);
8361 /* %:compare-debug-auxbase-opt spec function. Expands to the auxbase
8362 options that are to be passed in the second compilation of
8363 compare-debug. It expects, as an argument, the basename of the
8364 current input file name, with the .gk suffix appended to it. */
8366 static const char *
8367 compare_debug_auxbase_opt_spec_function (int arg,
8368 const char **argv)
8370 char *name;
8371 int len;
8373 if (arg == 0)
8374 fatal_error ("too few arguments to %%:compare-debug-auxbase-opt");
8376 if (arg != 1)
8377 fatal_error ("too many arguments to %%:compare-debug-auxbase-opt");
8379 if (compare_debug >= 0)
8380 return NULL;
8382 len = strlen (argv[0]);
8383 if (len < 3 || strcmp (argv[0] + len - 3, ".gk") != 0)
8384 fatal_error ("argument to %%:compare-debug-auxbase-opt "
8385 "does not end in .gk");
8387 if (debug_auxbase_opt)
8388 return debug_auxbase_opt;
8390 #define OPT "-auxbase "
8392 len -= 3;
8393 name = (char*) xmalloc (sizeof (OPT) + len);
8394 memcpy (name, OPT, sizeof (OPT) - 1);
8395 memcpy (name + sizeof (OPT) - 1, argv[0], len);
8396 name[sizeof (OPT) - 1 + len] = '\0';
8398 #undef OPT
8400 return name;
8403 /* %:pass-through-libs spec function. Finds all -l options and input
8404 file names in the lib spec passed to it, and makes a list of them
8405 prepended with the plugin option to cause them to be passed through
8406 to the final link after all the new object files have been added. */
8408 const char *
8409 pass_through_libs_spec_func (int argc, const char **argv)
8411 char *prepended = xstrdup (" ");
8412 int n;
8413 /* Shlemiel the painter's algorithm. Innately horrible, but at least
8414 we know that there will never be more than a handful of strings to
8415 concat, and it's only once per run, so it's not worth optimising. */
8416 for (n = 0; n < argc; n++)
8418 char *old = prepended;
8419 /* Anything that isn't an option is a full path to an output
8420 file; pass it through if it ends in '.a'. Among options,
8421 pass only -l. */
8422 if (argv[n][0] == '-' && argv[n][1] == 'l')
8424 const char *lopt = argv[n] + 2;
8425 /* Handle both joined and non-joined -l options. If for any
8426 reason there's a trailing -l with no joined or following
8427 arg just discard it. */
8428 if (!*lopt && ++n >= argc)
8429 break;
8430 else if (!*lopt)
8431 lopt = argv[n];
8432 prepended = concat (prepended, "-plugin-opt=-pass-through=-l",
8433 lopt, " ", NULL);
8435 else if (!strcmp (".a", argv[n] + strlen (argv[n]) - 2))
8437 prepended = concat (prepended, "-plugin-opt=-pass-through=",
8438 argv[n], " ", NULL);
8440 if (prepended != old)
8441 free (old);
8443 return prepended;
8446 /* %:replace-extension spec function. Replaces the extension of the
8447 first argument with the second argument. */
8449 const char *
8450 replace_extension_spec_func (int argc, const char **argv)
8452 char *name;
8453 char *p;
8454 char *result;
8455 int i;
8457 if (argc != 2)
8458 fatal_error ("too few arguments to %%:replace-extension");
8460 name = xstrdup (argv[0]);
8462 for (i = strlen(name) - 1; i >= 0; i--)
8463 if (IS_DIR_SEPARATOR (name[i]))
8464 break;
8466 p = strrchr (name + i + 1, '.');
8467 if (p != NULL)
8468 *p = '\0';
8470 result = concat (name, argv[1], NULL);
8472 free (name);
8473 return result;