xref: /netbsd-src/external/gpl3/gcc.old/dist/gcc/opts-common.c (revision 23f5f46327e37e7811da3520f4bb933f9489322f)
1 /* Command line option handling.
2    Copyright (C) 2006-2020 Free Software Foundation, Inc.
3 
4 This file is part of GCC.
5 
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10 
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15 
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19 
20 #define INCLUDE_STRING
21 #include "config.h"
22 #include "system.h"
23 #include "intl.h"
24 #include "coretypes.h"
25 #include "opts.h"
26 #include "options.h"
27 #include "diagnostic.h"
28 #include "spellcheck.h"
29 #include "opts-jobserver.h"
30 
31 static void prune_options (struct cl_decoded_option **, unsigned int *);
32 
33 /* An option that is undocumented, that takes a joined argument, and
34    that doesn't fit any of the classes of uses (language/common,
35    driver, target) is assumed to be a prefix used to catch
36    e.g. negated options, and stop them from being further shortened to
37    a prefix that could use the negated option as an argument.  For
38    example, we want -gno-statement-frontiers to be taken as a negation
39    of -gstatement-frontiers, but without catching the gno- prefix and
40    signaling it's to be used for option remapping, it would end up
41    backtracked to g with no-statemnet-frontiers as the debug level.  */
42 
43 static bool
remapping_prefix_p(const struct cl_option * opt)44 remapping_prefix_p (const struct cl_option *opt)
45 {
46   return opt->flags & CL_UNDOCUMENTED
47     && opt->flags & CL_JOINED
48     && !(opt->flags & (CL_DRIVER | CL_TARGET | CL_COMMON | CL_LANG_ALL));
49 }
50 
51 /* Perform a binary search to find which option the command-line INPUT
52    matches.  Returns its index in the option array, and
53    OPT_SPECIAL_unknown on failure.
54 
55    This routine is quite subtle.  A normal binary search is not good
56    enough because some options can be suffixed with an argument, and
57    multiple sub-matches can occur, e.g. input of "-pedantic" matching
58    the initial substring of "-pedantic-errors".
59 
60    A more complicated example is -gstabs.  It should match "-g" with
61    an argument of "stabs".  Suppose, however, that the number and list
62    of switches are such that the binary search tests "-gen-decls"
63    before having tested "-g".  This doesn't match, and as "-gen-decls"
64    is less than "-gstabs", it will become the lower bound of the
65    binary search range, and "-g" will never be seen.  To resolve this
66    issue, 'optc-gen.awk' makes "-gen-decls" point, via the back_chain member,
67    to "-g" so that failed searches that end between "-gen-decls" and
68    the lexicographically subsequent switch know to go back and see if
69    "-g" causes a match (which it does in this example).
70 
71    This search is done in such a way that the longest match for the
72    front end in question wins.  If there is no match for the current
73    front end, the longest match for a different front end is returned
74    (or N_OPTS if none) and the caller emits an error message.  */
75 size_t
find_opt(const char * input,unsigned int lang_mask)76 find_opt (const char *input, unsigned int lang_mask)
77 {
78   size_t mn, mn_orig, mx, md, opt_len;
79   size_t match_wrong_lang;
80   int comp;
81 
82   mn = 0;
83   mx = cl_options_count;
84 
85   /* Find mn such this lexicographical inequality holds:
86      cl_options[mn] <= input < cl_options[mn + 1].  */
87   while (mx - mn > 1)
88     {
89       md = (mn + mx) / 2;
90       opt_len = cl_options[md].opt_len;
91       comp = strncmp (input, cl_options[md].opt_text + 1, opt_len);
92 
93       if (comp < 0)
94 	mx = md;
95       else
96 	mn = md;
97     }
98 
99   mn_orig = mn;
100 
101   /* This is the switch that is the best match but for a different
102      front end, or OPT_SPECIAL_unknown if there is no match at all.  */
103   match_wrong_lang = OPT_SPECIAL_unknown;
104 
105   /* Backtrace the chain of possible matches, returning the longest
106      one, if any, that fits best.  With current GCC switches, this
107      loop executes at most twice.  */
108   do
109     {
110       const struct cl_option *opt = &cl_options[mn];
111 
112       /* Is the input either an exact match or a prefix that takes a
113 	 joined argument?  */
114       if (!strncmp (input, opt->opt_text + 1, opt->opt_len)
115 	  && (input[opt->opt_len] == '\0' || (opt->flags & CL_JOINED)))
116 	{
117 	  /* If language is OK, return it.  */
118 	  if (opt->flags & lang_mask)
119 	    return mn;
120 
121 	  if (remapping_prefix_p (opt))
122 	    return OPT_SPECIAL_unknown;
123 
124 	  /* If we haven't remembered a prior match, remember this
125 	     one.  Any prior match is necessarily better.  */
126 	  if (match_wrong_lang == OPT_SPECIAL_unknown)
127 	    match_wrong_lang = mn;
128 	}
129 
130       /* Try the next possibility.  This is cl_options_count if there
131 	 are no more.  */
132       mn = opt->back_chain;
133     }
134   while (mn != cl_options_count);
135 
136   if (match_wrong_lang == OPT_SPECIAL_unknown && input[0] == '-')
137     {
138       /* Long options, starting "--", may be abbreviated if the
139 	 abbreviation is unambiguous.  This only applies to options
140 	 not taking a joined argument, and abbreviations of "--option"
141 	 are permitted even if there is a variant "--option=".  */
142       size_t mnc = mn_orig + 1;
143       size_t cmp_len = strlen (input);
144       while (mnc < cl_options_count
145 	     && strncmp (input, cl_options[mnc].opt_text + 1, cmp_len) == 0)
146 	{
147 	  /* Option matching this abbreviation.  OK if it is the first
148 	     match and that does not take a joined argument, or the
149 	     second match, taking a joined argument and with only '='
150 	     added to the first match; otherwise considered
151 	     ambiguous.  */
152 	  if (mnc == mn_orig + 1
153 	      && !(cl_options[mnc].flags & CL_JOINED))
154 	    match_wrong_lang = mnc;
155 	  else if (mnc == mn_orig + 2
156 		   && match_wrong_lang == mn_orig + 1
157 		   && (cl_options[mnc].flags & CL_JOINED)
158 		   && (cl_options[mnc].opt_len
159 		       == cl_options[mn_orig + 1].opt_len + 1)
160 		   && strncmp (cl_options[mnc].opt_text + 1,
161 			       cl_options[mn_orig + 1].opt_text + 1,
162 			       cl_options[mn_orig + 1].opt_len) == 0)
163 	    ; /* OK, as long as there are no more matches.  */
164 	  else
165 	    return OPT_SPECIAL_unknown;
166 	  mnc++;
167 	}
168     }
169 
170   /* Return the best wrong match, or OPT_SPECIAL_unknown if none.  */
171   return match_wrong_lang;
172 }
173 
174 /* If ARG is a non-negative decimal or hexadecimal integer representable
175    in HOST_WIDE_INT return its value, otherwise return -1.  If ERR is not
176    null set *ERR to zero on success or to EINVAL or to the value of errno
177    otherwise.  */
178 
179 HOST_WIDE_INT
integral_argument(const char * arg,int * err,bool byte_size_suffix)180 integral_argument (const char *arg, int *err, bool byte_size_suffix)
181 {
182   if (!err)
183     err = &errno;
184 
185   if (!ISDIGIT (*arg))
186     {
187       *err = EINVAL;
188       return -1;
189     }
190 
191   *err = 0;
192   errno = 0;
193 
194   char *end = NULL;
195   unsigned HOST_WIDE_INT unit = 1;
196   unsigned HOST_WIDE_INT value = strtoull (arg, &end, 10);
197 
198   /* If the value is too large to be represented use the maximum
199      representable value that strtoull sets VALUE to (setting
200      errno to ERANGE).  */
201 
202   if (end && *end)
203     {
204       if (!byte_size_suffix)
205 	{
206 	  errno = 0;
207 	  value = strtoull (arg, &end, 0);
208 	  if (*end)
209 	    {
210 	      if (errno)
211 		*err = errno;
212 	      else
213 		*err = EINVAL;
214 	      return -1;
215 	    }
216 
217 	  return value;
218 	}
219 
220       /* Numeric option arguments are at most INT_MAX.  Make it
221 	 possible to specify a larger value by accepting common
222 	 suffixes.  */
223       if (!strcmp (end, "kB"))
224 	unit = 1000;
225       else if (!strcasecmp (end, "KiB") || !strcmp (end, "KB"))
226 	unit = 1024;
227       else if (!strcmp (end, "MB"))
228 	unit = HOST_WIDE_INT_UC (1000) * 1000;
229       else if (!strcasecmp (end, "MiB"))
230 	unit = HOST_WIDE_INT_UC (1024) * 1024;
231       else if (!strcasecmp (end, "GB"))
232 	unit = HOST_WIDE_INT_UC (1000) * 1000 * 1000;
233       else if (!strcasecmp (end, "GiB"))
234 	unit = HOST_WIDE_INT_UC (1024) * 1024 * 1024;
235       else if (!strcasecmp (end, "TB"))
236 	unit = HOST_WIDE_INT_UC (1000) * 1000 * 1000 * 1000;
237       else if (!strcasecmp (end, "TiB"))
238 	unit = HOST_WIDE_INT_UC (1024) * 1024 * 1024 * 1024;
239       else if (!strcasecmp (end, "PB"))
240 	unit = HOST_WIDE_INT_UC (1000) * 1000 * 1000 * 1000 * 1000;
241       else if (!strcasecmp (end, "PiB"))
242 	unit = HOST_WIDE_INT_UC (1024) * 1024 * 1024 * 1024 * 1024;
243       else if (!strcasecmp (end, "EB"))
244 	unit = HOST_WIDE_INT_UC (1000) * 1000 * 1000 * 1000 * 1000
245 	  * 1000;
246       else if (!strcasecmp (end, "EiB"))
247 	unit = HOST_WIDE_INT_UC (1024) * 1024 * 1024 * 1024 * 1024
248 	  * 1024;
249       else
250 	{
251 	  /* This could mean an unknown suffix or a bad prefix, like
252 	     "+-1".  */
253 	  *err = EINVAL;
254 	  return -1;
255 	}
256     }
257 
258   if (unit)
259     {
260       unsigned HOST_WIDE_INT prod = value * unit;
261       value = prod < value ? HOST_WIDE_INT_M1U : prod;
262     }
263 
264   return value;
265 }
266 
267 /* Return whether OPTION is OK for the language given by
268    LANG_MASK.  */
269 static bool
option_ok_for_language(const struct cl_option * option,unsigned int lang_mask)270 option_ok_for_language (const struct cl_option *option,
271 			unsigned int lang_mask)
272 {
273   if (!(option->flags & lang_mask))
274     return false;
275   else if ((option->flags & CL_TARGET)
276 	   && (option->flags & (CL_LANG_ALL | CL_DRIVER))
277 	   && !(option->flags & (lang_mask & ~CL_COMMON & ~CL_TARGET)))
278     /* Complain for target flag language mismatches if any languages
279        are specified.  */
280     return false;
281   return true;
282 }
283 
284 /* Return whether ENUM_ARG is OK for the language given by
285    LANG_MASK.  */
286 
287 static bool
enum_arg_ok_for_language(const struct cl_enum_arg * enum_arg,unsigned int lang_mask)288 enum_arg_ok_for_language (const struct cl_enum_arg *enum_arg,
289 			  unsigned int lang_mask)
290 {
291   return (lang_mask & CL_DRIVER) || !(enum_arg->flags & CL_ENUM_DRIVER_ONLY);
292 }
293 
294 /* Look up ARG in ENUM_ARGS for language LANG_MASK, returning true and
295    storing the value in *VALUE if found, and returning false without
296    modifying *VALUE if not found.  */
297 
298 static bool
enum_arg_to_value(const struct cl_enum_arg * enum_args,const char * arg,HOST_WIDE_INT * value,unsigned int lang_mask)299 enum_arg_to_value (const struct cl_enum_arg *enum_args,
300 		   const char *arg, HOST_WIDE_INT *value,
301 		   unsigned int lang_mask)
302 {
303   unsigned int i;
304 
305   for (i = 0; enum_args[i].arg != NULL; i++)
306     if (strcmp (arg, enum_args[i].arg) == 0
307 	&& enum_arg_ok_for_language (&enum_args[i], lang_mask))
308       {
309 	*value = enum_args[i].value;
310 	return true;
311       }
312 
313   return false;
314 }
315 
316 /* Look up ARG in the enum used by option OPT_INDEX for language
317    LANG_MASK, returning true and storing the value in *VALUE if found,
318    and returning false without modifying *VALUE if not found.  */
319 
320 bool
opt_enum_arg_to_value(size_t opt_index,const char * arg,int * value,unsigned int lang_mask)321 opt_enum_arg_to_value (size_t opt_index, const char *arg,
322 		       int *value, unsigned int lang_mask)
323 {
324   const struct cl_option *option = &cl_options[opt_index];
325 
326   gcc_assert (option->var_type == CLVC_ENUM);
327 
328   HOST_WIDE_INT wideval;
329   if (enum_arg_to_value (cl_enums[option->var_enum].values, arg,
330 			 &wideval, lang_mask))
331     {
332       *value = wideval;
333       return true;
334     }
335 
336   return false;
337 }
338 
339 /* Look of VALUE in ENUM_ARGS for language LANG_MASK and store the
340    corresponding string in *ARGP, returning true if the found string
341    was marked as canonical, false otherwise.  If VALUE is not found
342    (which may be the case for uninitialized values if the relevant
343    option has not been passed), set *ARGP to NULL and return
344    false.  */
345 
346 bool
enum_value_to_arg(const struct cl_enum_arg * enum_args,const char ** argp,int value,unsigned int lang_mask)347 enum_value_to_arg (const struct cl_enum_arg *enum_args,
348 		   const char **argp, int value, unsigned int lang_mask)
349 {
350   unsigned int i;
351 
352   for (i = 0; enum_args[i].arg != NULL; i++)
353     if (enum_args[i].value == value
354 	&& (enum_args[i].flags & CL_ENUM_CANONICAL)
355 	&& enum_arg_ok_for_language (&enum_args[i], lang_mask))
356       {
357 	*argp = enum_args[i].arg;
358 	return true;
359       }
360 
361   for (i = 0; enum_args[i].arg != NULL; i++)
362     if (enum_args[i].value == value
363 	&& enum_arg_ok_for_language (&enum_args[i], lang_mask))
364       {
365 	*argp = enum_args[i].arg;
366 	return false;
367       }
368 
369   *argp = NULL;
370   return false;
371 }
372 
373 /* Fill in the canonical option part of *DECODED with an option
374    described by OPT_INDEX, ARG and VALUE.  */
375 
376 static void
generate_canonical_option(size_t opt_index,const char * arg,HOST_WIDE_INT value,struct cl_decoded_option * decoded)377 generate_canonical_option (size_t opt_index, const char *arg,
378 			   HOST_WIDE_INT value,
379 			   struct cl_decoded_option *decoded)
380 {
381   const struct cl_option *option = &cl_options[opt_index];
382   const char *opt_text = option->opt_text;
383 
384   if (value == 0
385       && !option->cl_reject_negative
386       && (opt_text[1] == 'W' || opt_text[1] == 'f'
387 	  || opt_text[1] == 'g' || opt_text[1] == 'm'))
388     {
389       char *t = XOBNEWVEC (&opts_obstack, char, option->opt_len + 5);
390       t[0] = '-';
391       t[1] = opt_text[1];
392       t[2] = 'n';
393       t[3] = 'o';
394       t[4] = '-';
395       memcpy (t + 5, opt_text + 2, option->opt_len);
396       opt_text = t;
397     }
398 
399   decoded->canonical_option[2] = NULL;
400   decoded->canonical_option[3] = NULL;
401 
402   if (arg)
403     {
404       if ((option->flags & CL_SEPARATE)
405 	  && !option->cl_separate_alias)
406 	{
407 	  decoded->canonical_option[0] = opt_text;
408 	  decoded->canonical_option[1] = arg;
409 	  decoded->canonical_option_num_elements = 2;
410 	}
411       else
412 	{
413 	  gcc_assert (option->flags & CL_JOINED);
414 	  decoded->canonical_option[0] = opts_concat (opt_text, arg, NULL);
415 	  decoded->canonical_option[1] = NULL;
416 	  decoded->canonical_option_num_elements = 1;
417 	}
418     }
419   else
420     {
421       decoded->canonical_option[0] = opt_text;
422       decoded->canonical_option[1] = NULL;
423       decoded->canonical_option_num_elements = 1;
424     }
425 }
426 
427 /* Structure describing mappings from options on the command line to
428    options to look up with find_opt.  */
429 struct option_map
430 {
431   /* Prefix of the option on the command line.  */
432   const char *opt0;
433   /* If two argv elements are considered to be merged into one option,
434      prefix for the second element, otherwise NULL.  */
435   const char *opt1;
436   /* The new prefix to map to.  */
437   const char *new_prefix;
438   /* Whether at least one character is needed following opt1 or opt0
439      for this mapping to be used.  (--optimize= is valid for -O, but
440      --warn- is not valid for -W.)  */
441   bool another_char_needed;
442   /* Whether the original option is a negated form of the option
443      resulting from this map.  */
444   bool negated;
445 };
446 static const struct option_map option_map[] =
447   {
448     { "-Wno-", NULL, "-W", false, true },
449     { "-fno-", NULL, "-f", false, true },
450     { "-gno-", NULL, "-g", false, true },
451     { "-mno-", NULL, "-m", false, true },
452     { "--debug=", NULL, "-g", false, false },
453     { "--machine-", NULL, "-m", true, false },
454     { "--machine-no-", NULL, "-m", false, true },
455     { "--machine=", NULL, "-m", false, false },
456     { "--machine=no-", NULL, "-m", false, true },
457     { "--machine", "", "-m", false, false },
458     { "--machine", "no-", "-m", false, true },
459     { "--optimize=", NULL, "-O", false, false },
460     { "--std=", NULL, "-std=", false, false },
461     { "--std", "", "-std=", false, false },
462     { "--warn-", NULL, "-W", true, false },
463     { "--warn-no-", NULL, "-W", false, true },
464     { "--", NULL, "-f", true, false },
465     { "--no-", NULL, "-f", false, true }
466   };
467 
468 /* Helper function for gcc.c's driver::suggest_option, for populating the
469    vec of suggestions for misspelled options.
470 
471    option_map above provides various prefixes for spelling command-line
472    options, which decode_cmdline_option uses to map spellings of options
473    to specific options.  We want to do the reverse: to find all the ways
474    that a user could validly spell an option.
475 
476    Given valid OPT_TEXT (with a leading dash) for OPTION, add it and all
477    of its valid variant spellings to CANDIDATES, each without a leading
478    dash.
479 
480    For example, given "-Wabi-tag", the following are added to CANDIDATES:
481      "Wabi-tag"
482      "Wno-abi-tag"
483      "-warn-abi-tag"
484      "-warn-no-abi-tag".
485 
486    The added strings must be freed using free.  */
487 
488 void
add_misspelling_candidates(auto_vec<char * > * candidates,const struct cl_option * option,const char * opt_text)489 add_misspelling_candidates (auto_vec<char *> *candidates,
490 			    const struct cl_option *option,
491 			    const char *opt_text)
492 {
493   gcc_assert (candidates);
494   gcc_assert (option);
495   gcc_assert (opt_text);
496   if (remapping_prefix_p (option))
497     return;
498   candidates->safe_push (xstrdup (opt_text + 1));
499   for (unsigned i = 0; i < ARRAY_SIZE (option_map); i++)
500     {
501       const char *opt0 = option_map[i].opt0;
502       const char *new_prefix = option_map[i].new_prefix;
503       size_t new_prefix_len = strlen (new_prefix);
504 
505       if (option->cl_reject_negative && option_map[i].negated)
506 	continue;
507 
508       if (strncmp (opt_text, new_prefix, new_prefix_len) == 0)
509 	{
510 	  char *alternative = concat (opt0 + 1, opt_text + new_prefix_len,
511 				      NULL);
512 	  candidates->safe_push (alternative);
513 	}
514     }
515 
516   /* For all params (e.g. --param=key=value),
517      include also '--param key=value'.  */
518   const char *prefix = "--param=";
519   if (strstr (opt_text, prefix) == opt_text)
520     {
521       char *param = xstrdup (opt_text + 1);
522       gcc_assert (param[6] == '=');
523       param[6] = ' ';
524       candidates->safe_push (param);
525     }
526 }
527 
528 /* Decode the switch beginning at ARGV for the language indicated by
529    LANG_MASK (including CL_COMMON and CL_TARGET if applicable), into
530    the structure *DECODED.  Returns the number of switches
531    consumed.  */
532 
533 static unsigned int
decode_cmdline_option(const char ** argv,unsigned int lang_mask,struct cl_decoded_option * decoded)534 decode_cmdline_option (const char **argv, unsigned int lang_mask,
535 		       struct cl_decoded_option *decoded)
536 {
537   size_t opt_index;
538   const char *arg = 0;
539   HOST_WIDE_INT value = 1;
540   unsigned int result = 1, i, extra_args, separate_args = 0;
541   int adjust_len = 0;
542   size_t total_len;
543   char *p;
544   const struct cl_option *option;
545   int errors = 0;
546   const char *warn_message = NULL;
547   bool separate_arg_flag;
548   bool joined_arg_flag;
549   bool have_separate_arg = false;
550 
551   extra_args = 0;
552 
553   const char *opt_value = argv[0] + 1;
554   opt_index = find_opt (opt_value, lang_mask);
555   i = 0;
556   while (opt_index == OPT_SPECIAL_unknown
557 	 && i < ARRAY_SIZE (option_map))
558     {
559       const char *opt0 = option_map[i].opt0;
560       const char *opt1 = option_map[i].opt1;
561       const char *new_prefix = option_map[i].new_prefix;
562       bool another_char_needed = option_map[i].another_char_needed;
563       size_t opt0_len = strlen (opt0);
564       size_t opt1_len = (opt1 == NULL ? 0 : strlen (opt1));
565       size_t optn_len = (opt1 == NULL ? opt0_len : opt1_len);
566       size_t new_prefix_len = strlen (new_prefix);
567 
568       extra_args = (opt1 == NULL ? 0 : 1);
569       value = !option_map[i].negated;
570 
571       if (strncmp (argv[0], opt0, opt0_len) == 0
572 	  && (opt1 == NULL
573 	      || (argv[1] != NULL && strncmp (argv[1], opt1, opt1_len) == 0))
574 	  && (!another_char_needed
575 	      || argv[extra_args][optn_len] != 0))
576 	{
577 	  size_t arglen = strlen (argv[extra_args]);
578 	  char *dup;
579 
580 	  adjust_len = (int) optn_len - (int) new_prefix_len;
581 	  dup = XNEWVEC (char, arglen + 1 - adjust_len);
582 	  memcpy (dup, new_prefix, new_prefix_len);
583 	  memcpy (dup + new_prefix_len, argv[extra_args] + optn_len,
584 		  arglen - optn_len + 1);
585 	  opt_index = find_opt (dup + 1, lang_mask);
586 	  free (dup);
587 	}
588       i++;
589     }
590 
591   if (opt_index == OPT_SPECIAL_unknown)
592     {
593       arg = argv[0];
594       extra_args = 0;
595       value = 1;
596       goto done;
597     }
598 
599   option = &cl_options[opt_index];
600 
601   /* Reject negative form of switches that don't take negatives as
602      unrecognized.  */
603   if (!value && option->cl_reject_negative)
604     {
605       opt_index = OPT_SPECIAL_unknown;
606       errors |= CL_ERR_NEGATIVE;
607       arg = argv[0];
608       goto done;
609     }
610 
611   /* Clear the initial value for size options (it will be overwritten
612      later based on the Init(value) specification in the opt file.  */
613   if (option->var_type == CLVC_SIZE)
614     value = 0;
615 
616   result = extra_args + 1;
617   warn_message = option->warn_message;
618 
619   /* Check to see if the option is disabled for this configuration.  */
620   if (option->cl_disabled)
621     errors |= CL_ERR_DISABLED;
622 
623   /* Determine whether there may be a separate argument based on
624      whether this option is being processed for the driver, and, if
625      so, how many such arguments.  */
626   separate_arg_flag = ((option->flags & CL_SEPARATE)
627 		       && !(option->cl_no_driver_arg
628 			    && (lang_mask & CL_DRIVER)));
629   separate_args = (separate_arg_flag
630 		   ? option->cl_separate_nargs + 1
631 		   : 0);
632   joined_arg_flag = (option->flags & CL_JOINED) != 0;
633 
634   /* Sort out any argument the switch takes.  */
635   if (joined_arg_flag)
636     {
637       /* Have arg point to the original switch.  This is because
638 	 some code, such as disable_builtin_function, expects its
639 	 argument to be persistent until the program exits.  */
640       arg = argv[extra_args] + cl_options[opt_index].opt_len + 1 + adjust_len;
641 
642       if (*arg == '\0' && !option->cl_missing_ok)
643 	{
644 	  if (separate_arg_flag)
645 	    {
646 	      arg = argv[extra_args + 1];
647 	      result = extra_args + 2;
648 	      if (arg == NULL)
649 		result = extra_args + 1;
650 	      else
651 		have_separate_arg = true;
652 	    }
653 	  else
654 	    /* Missing argument.  */
655 	    arg = NULL;
656 	}
657     }
658   else if (separate_arg_flag)
659     {
660       arg = argv[extra_args + 1];
661       for (i = 0; i < separate_args; i++)
662 	if (argv[extra_args + 1 + i] == NULL)
663 	  {
664 	    errors |= CL_ERR_MISSING_ARG;
665 	    break;
666 	  }
667       result = extra_args + 1 + i;
668       if (arg != NULL)
669 	have_separate_arg = true;
670     }
671 
672   if (arg == NULL && (separate_arg_flag || joined_arg_flag))
673     errors |= CL_ERR_MISSING_ARG;
674 
675   /* Is this option an alias (or an ignored option, marked as an alias
676      of OPT_SPECIAL_ignore)?  */
677   if (option->alias_target != N_OPTS
678       && (!option->cl_separate_alias || have_separate_arg))
679     {
680       size_t new_opt_index = option->alias_target;
681 
682       if (new_opt_index == OPT_SPECIAL_ignore
683 	  || new_opt_index == OPT_SPECIAL_warn_removed)
684 	{
685 	  gcc_assert (option->alias_arg == NULL);
686 	  gcc_assert (option->neg_alias_arg == NULL);
687 	  opt_index = new_opt_index;
688 	  arg = NULL;
689 	}
690       else
691 	{
692 	  const struct cl_option *new_option = &cl_options[new_opt_index];
693 
694 	  /* The new option must not be an alias itself.  */
695 	  gcc_assert (new_option->alias_target == N_OPTS
696 		      || new_option->cl_separate_alias);
697 
698 	  if (option->neg_alias_arg)
699 	    {
700 	      gcc_assert (option->alias_arg != NULL);
701 	      gcc_assert (arg == NULL);
702 	      gcc_assert (!option->cl_negative_alias);
703 	      if (value)
704 		arg = option->alias_arg;
705 	      else
706 		arg = option->neg_alias_arg;
707 	      value = 1;
708 	    }
709 	  else if (option->alias_arg)
710 	    {
711 	      gcc_assert (value == 1);
712 	      gcc_assert (arg == NULL);
713 	      gcc_assert (!option->cl_negative_alias);
714 	      arg = option->alias_arg;
715 	    }
716 
717 	  if (option->cl_negative_alias)
718 	    value = !value;
719 
720 	  opt_index = new_opt_index;
721 	  option = new_option;
722 
723 	  if (value == 0)
724 	    gcc_assert (!option->cl_reject_negative);
725 
726 	  /* Recompute what arguments are allowed.  */
727 	  separate_arg_flag = ((option->flags & CL_SEPARATE)
728 			       && !(option->cl_no_driver_arg
729 				    && (lang_mask & CL_DRIVER)));
730 	  joined_arg_flag = (option->flags & CL_JOINED) != 0;
731 
732 	  if (separate_args > 1 || option->cl_separate_nargs)
733 	    gcc_assert (separate_args
734 			== (unsigned int) option->cl_separate_nargs + 1);
735 
736 	  if (!(errors & CL_ERR_MISSING_ARG))
737 	    {
738 	      if (separate_arg_flag || joined_arg_flag)
739 		{
740 		  if (option->cl_missing_ok && arg == NULL)
741 		    arg = "";
742 		  gcc_assert (arg != NULL);
743 		}
744 	      else
745 		gcc_assert (arg == NULL);
746 	    }
747 
748 	  /* Recheck for warnings and disabled options.  */
749 	  if (option->warn_message)
750 	    {
751 	      gcc_assert (warn_message == NULL);
752 	      warn_message = option->warn_message;
753 	    }
754 	  if (option->cl_disabled)
755 	    errors |= CL_ERR_DISABLED;
756 	}
757     }
758 
759   /* Check if this is a switch for a different front end.  */
760   if (!option_ok_for_language (option, lang_mask))
761     errors |= CL_ERR_WRONG_LANG;
762   else if (strcmp (option->opt_text, "-Werror=") == 0
763 	   && strchr (opt_value, ',') == NULL)
764     {
765       /* Verify that -Werror argument is a valid warning
766 	 for a language.  */
767       char *werror_arg = xstrdup (opt_value + 6);
768       werror_arg[0] = 'W';
769 
770       size_t warning_index = find_opt (werror_arg, lang_mask);
771       if (warning_index != OPT_SPECIAL_unknown)
772 	{
773 	  const struct cl_option *warning_option
774 	    = &cl_options[warning_index];
775 	  if (!option_ok_for_language (warning_option, lang_mask))
776 	    errors |= CL_ERR_WRONG_LANG;
777 	}
778     }
779 
780   /* Convert the argument to lowercase if appropriate.  */
781   if (arg && option->cl_tolower)
782     {
783       size_t j;
784       size_t len = strlen (arg);
785       char *arg_lower = XOBNEWVEC (&opts_obstack, char, len + 1);
786 
787       for (j = 0; j < len; j++)
788 	arg_lower[j] = TOLOWER ((unsigned char) arg[j]);
789       arg_lower[len] = 0;
790       arg = arg_lower;
791     }
792 
793   /* If the switch takes an integer argument, convert it.  */
794   if (arg && (option->cl_uinteger || option->cl_host_wide_int))
795     {
796       int error = 0;
797       value = *arg ? integral_argument (arg, &error, option->cl_byte_size) : 0;
798       if (error)
799 	errors |= CL_ERR_UINT_ARG;
800 
801       /* Reject value out of a range.  */
802       if (option->range_max != -1
803 	  && (value < option->range_min || value > option->range_max))
804 	errors |= CL_ERR_INT_RANGE_ARG;
805     }
806 
807   /* If the switch takes an enumerated argument, convert it.  */
808   if (arg && (option->var_type == CLVC_ENUM))
809     {
810       const struct cl_enum *e = &cl_enums[option->var_enum];
811 
812       gcc_assert (value == 1);
813       if (enum_arg_to_value (e->values, arg, &value, lang_mask))
814 	{
815 	  const char *carg = NULL;
816 
817 	  if (enum_value_to_arg (e->values, &carg, value, lang_mask))
818 	    arg = carg;
819 	  gcc_assert (carg != NULL);
820 	}
821       else
822 	errors |= CL_ERR_ENUM_ARG;
823     }
824 
825  done:
826   decoded->opt_index = opt_index;
827   decoded->arg = arg;
828   decoded->value = value;
829   decoded->errors = errors;
830   decoded->warn_message = warn_message;
831 
832   if (opt_index == OPT_SPECIAL_unknown)
833     gcc_assert (result == 1);
834 
835   gcc_assert (result >= 1 && result <= ARRAY_SIZE (decoded->canonical_option));
836   decoded->canonical_option_num_elements = result;
837   total_len = 0;
838   for (i = 0; i < ARRAY_SIZE (decoded->canonical_option); i++)
839     {
840       if (i < result)
841 	{
842 	  size_t len;
843 	  if (opt_index == OPT_SPECIAL_unknown)
844 	    decoded->canonical_option[i] = argv[i];
845 	  else
846 	    decoded->canonical_option[i] = NULL;
847 	  len = strlen (argv[i]);
848 	  /* If the argument is an empty string, we will print it as "" in
849 	     orig_option_with_args_text.  */
850 	  total_len += (len != 0 ? len : 2) + 1;
851 	}
852       else
853 	decoded->canonical_option[i] = NULL;
854     }
855   if (opt_index != OPT_SPECIAL_unknown && opt_index != OPT_SPECIAL_ignore
856       && opt_index != OPT_SPECIAL_warn_removed)
857     {
858       generate_canonical_option (opt_index, arg, value, decoded);
859       if (separate_args > 1)
860 	{
861 	  for (i = 0; i < separate_args; i++)
862 	    {
863 	      if (argv[extra_args + 1 + i] == NULL)
864 		  break;
865 	      else
866 		decoded->canonical_option[1 + i] = argv[extra_args + 1 + i];
867 	    }
868 	  gcc_assert (result == 1 + i);
869 	  decoded->canonical_option_num_elements = result;
870 	}
871     }
872   decoded->orig_option_with_args_text
873     = p = XOBNEWVEC (&opts_obstack, char, total_len);
874   for (i = 0; i < result; i++)
875     {
876       size_t len = strlen (argv[i]);
877 
878       /* Print the empty string verbally.  */
879       if (len == 0)
880 	{
881 	  *p++ = '"';
882 	  *p++ = '"';
883 	}
884       else
885 	memcpy (p, argv[i], len);
886       p += len;
887       if (i == result - 1)
888 	*p++ = 0;
889       else
890 	*p++ = ' ';
891     }
892 
893   return result;
894 }
895 
896 /* Obstack for option strings.  */
897 
898 struct obstack opts_obstack;
899 
900 /* Like libiberty concat, but allocate using opts_obstack.  */
901 
902 char *
opts_concat(const char * first,...)903 opts_concat (const char *first, ...)
904 {
905   char *newstr, *end;
906   size_t length = 0;
907   const char *arg;
908   va_list ap;
909 
910   /* First compute the size of the result and get sufficient memory.  */
911   va_start (ap, first);
912   for (arg = first; arg; arg = va_arg (ap, const char *))
913     length += strlen (arg);
914   newstr = XOBNEWVEC (&opts_obstack, char, length + 1);
915   va_end (ap);
916 
917   /* Now copy the individual pieces to the result string. */
918   va_start (ap, first);
919   for (arg = first, end = newstr; arg; arg = va_arg (ap, const char *))
920     {
921       length = strlen (arg);
922       memcpy (end, arg, length);
923       end += length;
924     }
925   *end = '\0';
926   va_end (ap);
927   return newstr;
928 }
929 
930 /* Decode command-line options (ARGC and ARGV being the arguments of
931    main) into an array, setting *DECODED_OPTIONS to a pointer to that
932    array and *DECODED_OPTIONS_COUNT to the number of entries in the
933    array.  The first entry in the array is always one for the program
934    name (OPT_SPECIAL_program_name).  LANG_MASK indicates the language
935    flags applicable for decoding (including CL_COMMON and CL_TARGET if
936    those options should be considered applicable).  Do not produce any
937    diagnostics or set state outside of these variables.  */
938 
939 void
decode_cmdline_options_to_array(unsigned int argc,const char ** argv,unsigned int lang_mask,struct cl_decoded_option ** decoded_options,unsigned int * decoded_options_count)940 decode_cmdline_options_to_array (unsigned int argc, const char **argv,
941 				 unsigned int lang_mask,
942 				 struct cl_decoded_option **decoded_options,
943 				 unsigned int *decoded_options_count)
944 {
945   unsigned int n, i;
946   struct cl_decoded_option *opt_array;
947   unsigned int num_decoded_options;
948 
949   opt_array = XNEWVEC (struct cl_decoded_option, argc);
950 
951   opt_array[0].opt_index = OPT_SPECIAL_program_name;
952   opt_array[0].warn_message = NULL;
953   opt_array[0].arg = argv[0];
954   opt_array[0].orig_option_with_args_text = argv[0];
955   opt_array[0].canonical_option_num_elements = 1;
956   opt_array[0].canonical_option[0] = argv[0];
957   opt_array[0].canonical_option[1] = NULL;
958   opt_array[0].canonical_option[2] = NULL;
959   opt_array[0].canonical_option[3] = NULL;
960   opt_array[0].value = 1;
961   opt_array[0].errors = 0;
962   num_decoded_options = 1;
963 
964   for (i = 1; i < argc; i += n)
965     {
966       const char *opt = argv[i];
967 
968       /* Interpret "-" or a non-switch as a file name.  */
969       if (opt[0] != '-' || opt[1] == '\0')
970 	{
971 	  generate_option_input_file (opt, &opt_array[num_decoded_options]);
972 	  num_decoded_options++;
973 	  n = 1;
974 	  continue;
975 	}
976 
977       /* Interpret "--param" "key=name" as "--param=key=name".  */
978       const char *needle = "--param";
979       if (i + 1 < argc && strcmp (opt, needle) == 0)
980 	{
981 	  const char *replacement
982 	    = opts_concat (needle, "=", argv[i + 1], NULL);
983 	  argv[++i] = replacement;
984 	}
985 
986       n = decode_cmdline_option (argv + i, lang_mask,
987 				 &opt_array[num_decoded_options]);
988       num_decoded_options++;
989     }
990 
991   *decoded_options = opt_array;
992   *decoded_options_count = num_decoded_options;
993   prune_options (decoded_options, decoded_options_count);
994 }
995 
996 /* Return true if NEXT_OPT_IDX cancels OPT_IDX.  Return false if the
997    next one is the same as ORIG_NEXT_OPT_IDX.  */
998 
999 static bool
cancel_option(int opt_idx,int next_opt_idx,int orig_next_opt_idx)1000 cancel_option (int opt_idx, int next_opt_idx, int orig_next_opt_idx)
1001 {
1002   /* An option can be canceled by the same option or an option with
1003      Negative.  */
1004   if (cl_options [next_opt_idx].neg_index == opt_idx)
1005     return true;
1006 
1007   if (cl_options [next_opt_idx].neg_index != orig_next_opt_idx)
1008     return cancel_option (opt_idx, cl_options [next_opt_idx].neg_index,
1009 			  orig_next_opt_idx);
1010 
1011   return false;
1012 }
1013 
1014 /* Filter out options canceled by the ones after them.  */
1015 
1016 static void
prune_options(struct cl_decoded_option ** decoded_options,unsigned int * decoded_options_count)1017 prune_options (struct cl_decoded_option **decoded_options,
1018 	       unsigned int *decoded_options_count)
1019 {
1020   unsigned int old_decoded_options_count = *decoded_options_count;
1021   struct cl_decoded_option *old_decoded_options = *decoded_options;
1022   unsigned int new_decoded_options_count;
1023   struct cl_decoded_option *new_decoded_options
1024     = XNEWVEC (struct cl_decoded_option, old_decoded_options_count);
1025   unsigned int i;
1026   const struct cl_option *option;
1027   unsigned int fdiagnostics_color_idx = 0;
1028 
1029   /* Remove arguments which are negated by others after them.  */
1030   new_decoded_options_count = 0;
1031   for (i = 0; i < old_decoded_options_count; i++)
1032     {
1033       unsigned int j, opt_idx, next_opt_idx;
1034 
1035       if (old_decoded_options[i].errors & ~CL_ERR_WRONG_LANG)
1036 	goto keep;
1037 
1038       opt_idx = old_decoded_options[i].opt_index;
1039       switch (opt_idx)
1040 	{
1041 	case OPT_SPECIAL_unknown:
1042 	case OPT_SPECIAL_ignore:
1043 	case OPT_SPECIAL_warn_removed:
1044 	case OPT_SPECIAL_program_name:
1045 	case OPT_SPECIAL_input_file:
1046 	  goto keep;
1047 
1048 	/* Do not save OPT_fdiagnostics_color_, just remember the last one.  */
1049 	case OPT_fdiagnostics_color_:
1050 	  fdiagnostics_color_idx = i;
1051 	  continue;
1052 
1053 	default:
1054 	  gcc_assert (opt_idx < cl_options_count);
1055 	  option = &cl_options[opt_idx];
1056 	  if (option->neg_index < 0)
1057 	    goto keep;
1058 
1059 	  /* Skip joined switches.  */
1060 	  if ((option->flags & CL_JOINED)
1061 	      && (!option->cl_reject_negative
1062 		  || (unsigned int) option->neg_index != opt_idx))
1063 	    goto keep;
1064 
1065 	  for (j = i + 1; j < old_decoded_options_count; j++)
1066 	    {
1067 	      if (old_decoded_options[j].errors & ~CL_ERR_WRONG_LANG)
1068 		continue;
1069 	      next_opt_idx = old_decoded_options[j].opt_index;
1070 	      if (next_opt_idx >= cl_options_count)
1071 		continue;
1072 	      if (cl_options[next_opt_idx].neg_index < 0)
1073 		continue;
1074 	      if ((cl_options[next_opt_idx].flags & CL_JOINED)
1075 		  && (!cl_options[next_opt_idx].cl_reject_negative
1076 		      || ((unsigned int) cl_options[next_opt_idx].neg_index
1077 			  != next_opt_idx)))
1078 		continue;
1079 	      if (cancel_option (opt_idx, next_opt_idx, next_opt_idx))
1080 		break;
1081 	    }
1082 	  if (j == old_decoded_options_count)
1083 	    {
1084 keep:
1085 	      new_decoded_options[new_decoded_options_count]
1086 		= old_decoded_options[i];
1087 	      new_decoded_options_count++;
1088 	    }
1089 	  break;
1090 	}
1091     }
1092 
1093   if (fdiagnostics_color_idx >= 1)
1094     {
1095       /* We put the last -fdiagnostics-color= at the first position
1096 	 after argv[0] so it can take effect immediately.  */
1097       memmove (new_decoded_options + 2, new_decoded_options + 1,
1098 	       sizeof (struct cl_decoded_option)
1099 	       * (new_decoded_options_count - 1));
1100       new_decoded_options[1] = old_decoded_options[fdiagnostics_color_idx];
1101       new_decoded_options_count++;
1102     }
1103 
1104   free (old_decoded_options);
1105   new_decoded_options = XRESIZEVEC (struct cl_decoded_option,
1106 				    new_decoded_options,
1107 				    new_decoded_options_count);
1108   *decoded_options = new_decoded_options;
1109   *decoded_options_count = new_decoded_options_count;
1110 }
1111 
1112 /* Handle option DECODED for the language indicated by LANG_MASK,
1113    using the handlers in HANDLERS and setting fields in OPTS and
1114    OPTS_SET.  KIND is the diagnostic_t if this is a diagnostics
1115    option, DK_UNSPECIFIED otherwise, and LOC is the location of the
1116    option for options from the source file, UNKNOWN_LOCATION
1117    otherwise.  GENERATED_P is true for an option generated as part of
1118    processing another option or otherwise generated internally, false
1119    for one explicitly passed by the user.  control_warning_option
1120    generated options are considered explicitly passed by the user.
1121    Returns false if the switch was invalid.  DC is the diagnostic
1122    context for options affecting diagnostics state, or NULL.  */
1123 
1124 static bool
handle_option(struct gcc_options * opts,struct gcc_options * opts_set,const struct cl_decoded_option * decoded,unsigned int lang_mask,int kind,location_t loc,const struct cl_option_handlers * handlers,bool generated_p,diagnostic_context * dc)1125 handle_option (struct gcc_options *opts,
1126 	       struct gcc_options *opts_set,
1127 	       const struct cl_decoded_option *decoded,
1128 	       unsigned int lang_mask, int kind, location_t loc,
1129 	       const struct cl_option_handlers *handlers,
1130 	       bool generated_p, diagnostic_context *dc)
1131 {
1132   size_t opt_index = decoded->opt_index;
1133   const char *arg = decoded->arg;
1134   HOST_WIDE_INT value = decoded->value;
1135   const struct cl_option *option = &cl_options[opt_index];
1136   void *flag_var = option_flag_var (opt_index, opts);
1137   size_t i;
1138 
1139   if (flag_var)
1140     set_option (opts, (generated_p ? NULL : opts_set),
1141 		opt_index, value, arg, kind, loc, dc);
1142 
1143   for (i = 0; i < handlers->num_handlers; i++)
1144     if (option->flags & handlers->handlers[i].mask)
1145       {
1146 	if (!handlers->handlers[i].handler (opts, opts_set, decoded,
1147 					    lang_mask, kind, loc,
1148 					    handlers, dc,
1149 					    handlers->target_option_override_hook))
1150 	  return false;
1151       }
1152 
1153   return true;
1154 }
1155 
1156 /* Like handle_option, but OPT_INDEX, ARG and VALUE describe the
1157    option instead of DECODED.  This is used for callbacks when one
1158    option implies another instead of an option being decoded from the
1159    command line.  */
1160 
1161 bool
handle_generated_option(struct gcc_options * opts,struct gcc_options * opts_set,size_t opt_index,const char * arg,HOST_WIDE_INT value,unsigned int lang_mask,int kind,location_t loc,const struct cl_option_handlers * handlers,bool generated_p,diagnostic_context * dc)1162 handle_generated_option (struct gcc_options *opts,
1163 			 struct gcc_options *opts_set,
1164 			 size_t opt_index, const char *arg, HOST_WIDE_INT value,
1165 			 unsigned int lang_mask, int kind, location_t loc,
1166 			 const struct cl_option_handlers *handlers,
1167 			 bool generated_p, diagnostic_context *dc)
1168 {
1169   struct cl_decoded_option decoded;
1170 
1171   generate_option (opt_index, arg, value, lang_mask, &decoded);
1172   return handle_option (opts, opts_set, &decoded, lang_mask, kind, loc,
1173 			handlers, generated_p, dc);
1174 }
1175 
1176 /* Fill in *DECODED with an option described by OPT_INDEX, ARG and
1177    VALUE for a front end using LANG_MASK.  This is used when the
1178    compiler generates options internally.  */
1179 
1180 void
generate_option(size_t opt_index,const char * arg,HOST_WIDE_INT value,unsigned int lang_mask,struct cl_decoded_option * decoded)1181 generate_option (size_t opt_index, const char *arg, HOST_WIDE_INT value,
1182 		 unsigned int lang_mask, struct cl_decoded_option *decoded)
1183 {
1184   const struct cl_option *option = &cl_options[opt_index];
1185 
1186   decoded->opt_index = opt_index;
1187   decoded->warn_message = NULL;
1188   decoded->arg = arg;
1189   decoded->value = value;
1190   decoded->errors = (option_ok_for_language (option, lang_mask)
1191 		     ? 0
1192 		     : CL_ERR_WRONG_LANG);
1193 
1194   generate_canonical_option (opt_index, arg, value, decoded);
1195   switch (decoded->canonical_option_num_elements)
1196     {
1197     case 1:
1198       decoded->orig_option_with_args_text = decoded->canonical_option[0];
1199       break;
1200 
1201     case 2:
1202       decoded->orig_option_with_args_text
1203 	= opts_concat (decoded->canonical_option[0], " ",
1204 		       decoded->canonical_option[1], NULL);
1205       break;
1206 
1207     default:
1208       gcc_unreachable ();
1209     }
1210 }
1211 
1212 /* Fill in *DECODED with an option for input file FILE.  */
1213 
1214 void
generate_option_input_file(const char * file,struct cl_decoded_option * decoded)1215 generate_option_input_file (const char *file,
1216 			    struct cl_decoded_option *decoded)
1217 {
1218   decoded->opt_index = OPT_SPECIAL_input_file;
1219   decoded->warn_message = NULL;
1220   decoded->arg = file;
1221   decoded->orig_option_with_args_text = file;
1222   decoded->canonical_option_num_elements = 1;
1223   decoded->canonical_option[0] = file;
1224   decoded->canonical_option[1] = NULL;
1225   decoded->canonical_option[2] = NULL;
1226   decoded->canonical_option[3] = NULL;
1227   decoded->value = 1;
1228   decoded->errors = 0;
1229 }
1230 
1231 /* Helper function for listing valid choices and hint for misspelled
1232    value.  CANDIDATES is a vector containing all valid strings,
1233    STR is set to a heap allocated string that contains all those
1234    strings concatenated, separated by spaces, and the return value
1235    is the closest string from those to ARG, or NULL if nothing is
1236    close enough.  Callers should XDELETEVEC (STR) after using it
1237    to avoid memory leaks.  */
1238 
1239 const char *
candidates_list_and_hint(const char * arg,char * & str,const auto_vec<const char * > & candidates)1240 candidates_list_and_hint (const char *arg, char *&str,
1241 			  const auto_vec <const char *> &candidates)
1242 {
1243   size_t len = 0;
1244   int i;
1245   const char *candidate;
1246   char *p;
1247 
1248   FOR_EACH_VEC_ELT (candidates, i, candidate)
1249     len += strlen (candidate) + 1;
1250 
1251   str = p = XNEWVEC (char, len);
1252   FOR_EACH_VEC_ELT (candidates, i, candidate)
1253     {
1254       len = strlen (candidate);
1255       memcpy (p, candidate, len);
1256       p[len] = ' ';
1257       p += len + 1;
1258     }
1259   p[-1] = '\0';
1260   return find_closest_string (arg, &candidates);
1261 }
1262 
1263 /* Perform diagnostics for read_cmdline_option and control_warning_option
1264    functions.  Returns true if an error has been diagnosed.
1265    LOC and LANG_MASK arguments like in read_cmdline_option.
1266    OPTION is the option to report diagnostics for, OPT the name
1267    of the option as text, ARG the argument of the option (for joined
1268    options), ERRORS is bitmask of CL_ERR_* values.  */
1269 
1270 static bool
cmdline_handle_error(location_t loc,const struct cl_option * option,const char * opt,const char * arg,int errors,unsigned int lang_mask)1271 cmdline_handle_error (location_t loc, const struct cl_option *option,
1272 		      const char *opt, const char *arg, int errors,
1273 		      unsigned int lang_mask)
1274 {
1275   if (errors & CL_ERR_DISABLED)
1276     {
1277       error_at (loc, "command-line option %qs"
1278 		     " is not supported by this configuration", opt);
1279       return true;
1280     }
1281 
1282   if (errors & CL_ERR_MISSING_ARG)
1283     {
1284       if (option->missing_argument_error)
1285 	error_at (loc, option->missing_argument_error, opt);
1286       else
1287 	error_at (loc, "missing argument to %qs", opt);
1288       return true;
1289     }
1290 
1291   if (errors & CL_ERR_UINT_ARG)
1292     {
1293       if (option->cl_byte_size)
1294 	error_at (loc, "argument to %qs should be a non-negative integer "
1295 		  "optionally followed by a size unit",
1296 		  option->opt_text);
1297       else
1298 	error_at (loc, "argument to %qs should be a non-negative integer",
1299 		  option->opt_text);
1300       return true;
1301     }
1302 
1303   if (errors & CL_ERR_INT_RANGE_ARG)
1304     {
1305       error_at (loc, "argument to %qs is not between %d and %d",
1306 		option->opt_text, option->range_min, option->range_max);
1307       return true;
1308     }
1309 
1310   if (errors & CL_ERR_ENUM_ARG)
1311     {
1312       const struct cl_enum *e = &cl_enums[option->var_enum];
1313       unsigned int i;
1314       char *s;
1315 
1316       auto_diagnostic_group d;
1317       if (e->unknown_error)
1318 	error_at (loc, e->unknown_error, arg);
1319       else
1320 	error_at (loc, "unrecognized argument in option %qs", opt);
1321 
1322       auto_vec <const char *> candidates;
1323       for (i = 0; e->values[i].arg != NULL; i++)
1324 	{
1325 	  if (!enum_arg_ok_for_language (&e->values[i], lang_mask))
1326 	    continue;
1327 	  candidates.safe_push (e->values[i].arg);
1328 	}
1329       const char *hint = candidates_list_and_hint (arg, s, candidates);
1330       if (hint)
1331 	inform (loc, "valid arguments to %qs are: %s; did you mean %qs?",
1332 		option->opt_text, s, hint);
1333       else
1334 	inform (loc, "valid arguments to %qs are: %s", option->opt_text, s);
1335       XDELETEVEC (s);
1336 
1337       return true;
1338     }
1339 
1340   return false;
1341 }
1342 
1343 /* Handle the switch DECODED (location LOC) for the language indicated
1344    by LANG_MASK, using the handlers in *HANDLERS and setting fields in
1345    OPTS and OPTS_SET and using diagnostic context DC (if not NULL) for
1346    diagnostic options.  */
1347 
1348 void
read_cmdline_option(struct gcc_options * opts,struct gcc_options * opts_set,struct cl_decoded_option * decoded,location_t loc,unsigned int lang_mask,const struct cl_option_handlers * handlers,diagnostic_context * dc)1349 read_cmdline_option (struct gcc_options *opts,
1350 		     struct gcc_options *opts_set,
1351 		     struct cl_decoded_option *decoded,
1352 		     location_t loc,
1353 		     unsigned int lang_mask,
1354 		     const struct cl_option_handlers *handlers,
1355 		     diagnostic_context *dc)
1356 {
1357   const struct cl_option *option;
1358   const char *opt = decoded->orig_option_with_args_text;
1359 
1360   if (decoded->warn_message)
1361     warning_at (loc, 0, decoded->warn_message, opt);
1362 
1363   if (decoded->opt_index == OPT_SPECIAL_unknown)
1364     {
1365       if (handlers->unknown_option_callback (decoded))
1366 	error_at (loc, "unrecognized command-line option %qs", decoded->arg);
1367       return;
1368     }
1369 
1370   if (decoded->opt_index == OPT_SPECIAL_ignore)
1371     return;
1372 
1373   if (decoded->opt_index == OPT_SPECIAL_warn_removed)
1374     {
1375       /* Warn only about positive ignored options.  */
1376       if (decoded->value)
1377 	warning_at (loc, 0, "switch %qs is no longer supported", opt);
1378       return;
1379     }
1380 
1381   option = &cl_options[decoded->opt_index];
1382 
1383   if (decoded->errors
1384       && cmdline_handle_error (loc, option, opt, decoded->arg,
1385 			       decoded->errors, lang_mask))
1386     return;
1387 
1388   if (decoded->errors & CL_ERR_WRONG_LANG)
1389     {
1390       handlers->wrong_lang_callback (decoded, lang_mask);
1391       return;
1392     }
1393 
1394   gcc_assert (!decoded->errors);
1395 
1396   if (!handle_option (opts, opts_set, decoded, lang_mask, DK_UNSPECIFIED,
1397 		      loc, handlers, false, dc))
1398     error_at (loc, "unrecognized command-line option %qs", opt);
1399 }
1400 
1401 /* Set any field in OPTS, and OPTS_SET if not NULL, for option
1402    OPT_INDEX according to VALUE and ARG, diagnostic kind KIND,
1403    location LOC, using diagnostic context DC if not NULL for
1404    diagnostic classification.  */
1405 
1406 void
set_option(struct gcc_options * opts,struct gcc_options * opts_set,int opt_index,HOST_WIDE_INT value,const char * arg,int kind,location_t loc,diagnostic_context * dc)1407 set_option (struct gcc_options *opts, struct gcc_options *opts_set,
1408 	    int opt_index, HOST_WIDE_INT value, const char *arg, int kind,
1409 	    location_t loc, diagnostic_context *dc)
1410 {
1411   const struct cl_option *option = &cl_options[opt_index];
1412   void *flag_var = option_flag_var (opt_index, opts);
1413   void *set_flag_var = NULL;
1414 
1415   if (!flag_var)
1416     return;
1417 
1418   if ((diagnostic_t) kind != DK_UNSPECIFIED && dc != NULL)
1419     diagnostic_classify_diagnostic (dc, opt_index, (diagnostic_t) kind, loc);
1420 
1421   if (opts_set != NULL)
1422     set_flag_var = option_flag_var (opt_index, opts_set);
1423 
1424   switch (option->var_type)
1425     {
1426     case CLVC_BOOLEAN:
1427 	if (option->cl_host_wide_int)
1428 	  {
1429 	    *(HOST_WIDE_INT *) flag_var = value;
1430 	    if (set_flag_var)
1431 	      *(HOST_WIDE_INT *) set_flag_var = 1;
1432 	  }
1433 	else
1434 	  {
1435 	    *(int *) flag_var = value;
1436 	    if (set_flag_var)
1437 	      *(int *) set_flag_var = 1;
1438 	  }
1439 
1440 	break;
1441 
1442     case CLVC_SIZE:
1443 	if (option->cl_host_wide_int)
1444 	  {
1445 	    *(HOST_WIDE_INT *) flag_var = value;
1446 	    if (set_flag_var)
1447 	      *(HOST_WIDE_INT *) set_flag_var = value;
1448 	  }
1449 	else
1450 	  {
1451 	    *(int *) flag_var = value;
1452 	    if (set_flag_var)
1453 	      *(int *) set_flag_var = value;
1454 	  }
1455 
1456 	break;
1457 
1458     case CLVC_EQUAL:
1459 	if (option->cl_host_wide_int)
1460 	  {
1461 	    *(HOST_WIDE_INT *) flag_var = (value
1462 					   ? option->var_value
1463 					   : !option->var_value);
1464 	    if (set_flag_var)
1465 	      *(HOST_WIDE_INT *) set_flag_var = 1;
1466 	  }
1467 	else
1468 	  {
1469 	    *(int *) flag_var = (value
1470 				 ? option->var_value
1471 				 : !option->var_value);
1472 	    if (set_flag_var)
1473 	      *(int *) set_flag_var = 1;
1474 	  }
1475 	break;
1476 
1477     case CLVC_BIT_CLEAR:
1478     case CLVC_BIT_SET:
1479 	if ((value != 0) == (option->var_type == CLVC_BIT_SET))
1480 	  {
1481 	    if (option->cl_host_wide_int)
1482 	      *(HOST_WIDE_INT *) flag_var |= option->var_value;
1483 	    else
1484 	      *(int *) flag_var |= option->var_value;
1485 	  }
1486 	else
1487 	  {
1488 	    if (option->cl_host_wide_int)
1489 	      *(HOST_WIDE_INT *) flag_var &= ~option->var_value;
1490 	    else
1491 	      *(int *) flag_var &= ~option->var_value;
1492 	  }
1493 	if (set_flag_var)
1494 	  {
1495 	    if (option->cl_host_wide_int)
1496 	      *(HOST_WIDE_INT *) set_flag_var |= option->var_value;
1497 	    else
1498 	      *(int *) set_flag_var |= option->var_value;
1499 	  }
1500 	break;
1501 
1502     case CLVC_STRING:
1503 	*(const char **) flag_var = arg;
1504 	if (set_flag_var)
1505 	  *(const char **) set_flag_var = "";
1506 	break;
1507 
1508     case CLVC_ENUM:
1509       {
1510 	const struct cl_enum *e = &cl_enums[option->var_enum];
1511 
1512 	e->set (flag_var, value);
1513 	if (set_flag_var)
1514 	  e->set (set_flag_var, 1);
1515       }
1516       break;
1517 
1518     case CLVC_DEFER:
1519 	{
1520 	  vec<cl_deferred_option> *v
1521 	    = (vec<cl_deferred_option> *) *(void **) flag_var;
1522 	  cl_deferred_option p = {opt_index, arg, value};
1523 	  if (!v)
1524 	    v = XCNEW (vec<cl_deferred_option>);
1525 	  v->safe_push (p);
1526 	  *(void **) flag_var = v;
1527 	  if (set_flag_var)
1528 	    *(void **) set_flag_var = v;
1529 	}
1530 	break;
1531     }
1532 }
1533 
1534 /* Return the address of the flag variable for option OPT_INDEX in
1535    options structure OPTS, or NULL if there is no flag variable.  */
1536 
1537 void *
option_flag_var(int opt_index,struct gcc_options * opts)1538 option_flag_var (int opt_index, struct gcc_options *opts)
1539 {
1540   const struct cl_option *option = &cl_options[opt_index];
1541 
1542   if (option->flag_var_offset == (unsigned short) -1)
1543     return NULL;
1544   return (void *)(((char *) opts) + option->flag_var_offset);
1545 }
1546 
1547 /* Return 1 if option OPT_IDX is enabled in OPTS, 0 if it is disabled,
1548    or -1 if it isn't a simple on-off switch.  */
1549 
1550 int
option_enabled(int opt_idx,unsigned lang_mask,void * opts)1551 option_enabled (int opt_idx, unsigned lang_mask, void *opts)
1552 {
1553   const struct cl_option *option = &(cl_options[opt_idx]);
1554 
1555   /* A language-specific option can only be considered enabled when it's
1556      valid for the current language.  */
1557   if (!(option->flags & CL_COMMON)
1558       && (option->flags & CL_LANG_ALL)
1559       && !(option->flags & lang_mask))
1560     return 0;
1561 
1562   struct gcc_options *optsg = (struct gcc_options *) opts;
1563   void *flag_var = option_flag_var (opt_idx, optsg);
1564 
1565   if (flag_var)
1566     switch (option->var_type)
1567       {
1568       case CLVC_BOOLEAN:
1569 	if (option->cl_host_wide_int)
1570 	  return *(HOST_WIDE_INT *) flag_var != 0;
1571 	else
1572 	  return *(int *) flag_var != 0;
1573 
1574       case CLVC_EQUAL:
1575 	if (option->cl_host_wide_int)
1576 	  return *(HOST_WIDE_INT *) flag_var == option->var_value;
1577 	else
1578 	  return *(int *) flag_var == option->var_value;
1579 
1580       case CLVC_BIT_CLEAR:
1581 	if (option->cl_host_wide_int)
1582 	  return (*(HOST_WIDE_INT *) flag_var & option->var_value) == 0;
1583 	else
1584 	  return (*(int *) flag_var & option->var_value) == 0;
1585 
1586       case CLVC_BIT_SET:
1587 	if (option->cl_host_wide_int)
1588 	  return (*(HOST_WIDE_INT *) flag_var & option->var_value) != 0;
1589 	else
1590 	  return (*(int *) flag_var & option->var_value) != 0;
1591 
1592       case CLVC_SIZE:
1593 	if (option->cl_host_wide_int)
1594 	  return *(HOST_WIDE_INT *) flag_var != -1;
1595 	else
1596 	  return *(int *) flag_var != -1;
1597 
1598       case CLVC_STRING:
1599       case CLVC_ENUM:
1600       case CLVC_DEFER:
1601 	break;
1602       }
1603   return -1;
1604 }
1605 
1606 /* Fill STATE with the current state of option OPTION in OPTS.  Return
1607    true if there is some state to store.  */
1608 
1609 bool
get_option_state(struct gcc_options * opts,int option,struct cl_option_state * state)1610 get_option_state (struct gcc_options *opts, int option,
1611 		  struct cl_option_state *state)
1612 {
1613   void *flag_var = option_flag_var (option, opts);
1614 
1615   if (flag_var == 0)
1616     return false;
1617 
1618   switch (cl_options[option].var_type)
1619     {
1620     case CLVC_BOOLEAN:
1621     case CLVC_EQUAL:
1622     case CLVC_SIZE:
1623       state->data = flag_var;
1624       state->size = (cl_options[option].cl_host_wide_int
1625 		     ? sizeof (HOST_WIDE_INT)
1626 		     : sizeof (int));
1627       break;
1628 
1629     case CLVC_BIT_CLEAR:
1630     case CLVC_BIT_SET:
1631       state->ch = option_enabled (option, -1, opts);
1632       state->data = &state->ch;
1633       state->size = 1;
1634       break;
1635 
1636     case CLVC_STRING:
1637       state->data = *(const char **) flag_var;
1638       if (state->data == 0)
1639 	state->data = "";
1640       state->size = strlen ((const char *) state->data) + 1;
1641       break;
1642 
1643     case CLVC_ENUM:
1644       state->data = flag_var;
1645       state->size = cl_enums[cl_options[option].var_enum].var_size;
1646       break;
1647 
1648     case CLVC_DEFER:
1649       return false;
1650     }
1651   return true;
1652 }
1653 
1654 /* Set a warning option OPT_INDEX (language mask LANG_MASK, option
1655    handlers HANDLERS) to have diagnostic kind KIND for option
1656    structures OPTS and OPTS_SET and diagnostic context DC (possibly
1657    NULL), at location LOC (UNKNOWN_LOCATION for -Werror=).  ARG is the
1658    argument of the option for joined options, or NULL otherwise.  If IMPLY,
1659    the warning option in question is implied at this point.  This is
1660    used by -Werror= and #pragma GCC diagnostic.  */
1661 
1662 void
control_warning_option(unsigned int opt_index,int kind,const char * arg,bool imply,location_t loc,unsigned int lang_mask,const struct cl_option_handlers * handlers,struct gcc_options * opts,struct gcc_options * opts_set,diagnostic_context * dc)1663 control_warning_option (unsigned int opt_index, int kind, const char *arg,
1664 			bool imply, location_t loc, unsigned int lang_mask,
1665 			const struct cl_option_handlers *handlers,
1666 			struct gcc_options *opts,
1667 			struct gcc_options *opts_set,
1668 			diagnostic_context *dc)
1669 {
1670   if (cl_options[opt_index].alias_target != N_OPTS)
1671     {
1672       gcc_assert (!cl_options[opt_index].cl_separate_alias
1673 		  && !cl_options[opt_index].cl_negative_alias);
1674       if (cl_options[opt_index].alias_arg)
1675 	arg = cl_options[opt_index].alias_arg;
1676       opt_index = cl_options[opt_index].alias_target;
1677     }
1678   if (opt_index == OPT_SPECIAL_ignore || opt_index == OPT_SPECIAL_warn_removed)
1679     return;
1680   if (dc)
1681     diagnostic_classify_diagnostic (dc, opt_index, (diagnostic_t) kind, loc);
1682   if (imply)
1683     {
1684       const struct cl_option *option = &cl_options[opt_index];
1685 
1686       /* -Werror=foo implies -Wfoo.  */
1687       if (option->var_type == CLVC_BOOLEAN
1688 	  || option->var_type == CLVC_ENUM
1689 	  || option->var_type == CLVC_SIZE)
1690 	{
1691 	  HOST_WIDE_INT value = 1;
1692 
1693 	  if (arg && *arg == '\0' && !option->cl_missing_ok)
1694 	    arg = NULL;
1695 
1696 	  if ((option->flags & CL_JOINED) && arg == NULL)
1697 	    {
1698 	      cmdline_handle_error (loc, option, option->opt_text, arg,
1699 				    CL_ERR_MISSING_ARG, lang_mask);
1700 	      return;
1701 	    }
1702 
1703 	  /* If the switch takes an integer argument, convert it.  */
1704 	  if (arg && (option->cl_uinteger || option->cl_host_wide_int))
1705 	    {
1706 	      int error = 0;
1707 	      value = *arg ? integral_argument (arg, &error,
1708 						option->cl_byte_size) : 0;
1709 	      if (error)
1710 		{
1711 		  cmdline_handle_error (loc, option, option->opt_text, arg,
1712 					CL_ERR_UINT_ARG, lang_mask);
1713 		  return;
1714 		}
1715 	    }
1716 
1717 	  /* If the switch takes an enumerated argument, convert it.  */
1718 	  if (arg && option->var_type == CLVC_ENUM)
1719 	    {
1720 	      const struct cl_enum *e = &cl_enums[option->var_enum];
1721 
1722 	      if (enum_arg_to_value (e->values, arg, &value, lang_mask))
1723 		{
1724 		  const char *carg = NULL;
1725 
1726 		  if (enum_value_to_arg (e->values, &carg, value, lang_mask))
1727 		    arg = carg;
1728 		  gcc_assert (carg != NULL);
1729 		}
1730 	      else
1731 		{
1732 		  cmdline_handle_error (loc, option, option->opt_text, arg,
1733 					CL_ERR_ENUM_ARG, lang_mask);
1734 		  return;
1735 		}
1736 	    }
1737 
1738 	  handle_generated_option (opts, opts_set,
1739 				   opt_index, arg, value, lang_mask,
1740 				   kind, loc, handlers, false, dc);
1741 	}
1742     }
1743 }
1744 
1745 /* Parse options in COLLECT_GCC_OPTIONS and push them on ARGV_OBSTACK.
1746    Store number of arguments into ARGC_P.  */
1747 
1748 void
parse_options_from_collect_gcc_options(const char * collect_gcc_options,obstack * argv_obstack,int * argc_p)1749 parse_options_from_collect_gcc_options (const char *collect_gcc_options,
1750 					obstack *argv_obstack,
1751 					int *argc_p)
1752 {
1753   char *argv_storage = xstrdup (collect_gcc_options);
1754   int j, k;
1755 
1756   for (j = 0, k = 0; argv_storage[j] != '\0'; ++j)
1757     {
1758       if (argv_storage[j] == '\'')
1759 	{
1760 	  obstack_ptr_grow (argv_obstack, &argv_storage[k]);
1761 	  ++j;
1762 	  do
1763 	    {
1764 	      if (argv_storage[j] == '\0')
1765 		fatal_error (input_location,
1766 			     "malformed %<COLLECT_GCC_OPTIONS%>");
1767 	      else if (strncmp (&argv_storage[j], "'\\''", 4) == 0)
1768 		{
1769 		  argv_storage[k++] = '\'';
1770 		  j += 4;
1771 		}
1772 	      else if (argv_storage[j] == '\'')
1773 		break;
1774 	      else
1775 		argv_storage[k++] = argv_storage[j++];
1776 	    }
1777 	  while (1);
1778 	  argv_storage[k++] = '\0';
1779 	}
1780     }
1781 
1782   obstack_ptr_grow (argv_obstack, NULL);
1783   *argc_p = obstack_object_size (argv_obstack) / sizeof (void *) - 1;
1784 }
1785 
1786 /* Prepend -Xassembler for each option in COLLECT_AS_OPTIONS,
1787    and push on O.  */
1788 
prepend_xassembler_to_collect_as_options(const char * collect_as_options,obstack * o)1789 void prepend_xassembler_to_collect_as_options (const char *collect_as_options,
1790 					       obstack *o)
1791 {
1792   obstack opts_obstack;
1793   int opts_count;
1794 
1795   obstack_init (&opts_obstack);
1796   parse_options_from_collect_gcc_options (collect_as_options,
1797 					  &opts_obstack, &opts_count);
1798   const char **assembler_opts = XOBFINISH (&opts_obstack, const char **);
1799 
1800   for (int i = 0; i < opts_count; i++)
1801     {
1802       obstack_grow (o, " '-Xassembler' ",
1803 		    strlen (" '-Xassembler' "));
1804       const char *opt = assembler_opts[i];
1805       obstack_1grow (o, '\'');
1806       obstack_grow (o, opt, strlen (opt));
1807       obstack_1grow (o, '\'');
1808     }
1809 }
1810 
jobserver_info()1811 jobserver_info::jobserver_info ()
1812 {
1813   /* Traditionally, GNU make uses opened pipes for jobserver-auth,
1814     e.g. --jobserver-auth=3,4.
1815     Starting with GNU make 4.4, one can use --jobserver-style=fifo
1816     and then named pipe is used: --jobserver-auth=fifo:/tmp/hcsparta.  */
1817 
1818   /* Detect jobserver and drop it if it's not working.  */
1819   string js_needle = "--jobserver-auth=";
1820   string fifo_prefix = "fifo:";
1821 
1822   const char *envval = getenv ("MAKEFLAGS");
1823   if (envval != NULL)
1824     {
1825       string makeflags = envval;
1826       size_t n = makeflags.rfind (js_needle);
1827       if (n != string::npos)
1828 	{
1829 	  string ending = makeflags.substr (n + js_needle.size ());
1830 	  if (ending.find (fifo_prefix) == 0)
1831 	    {
1832 	      ending = ending.substr (fifo_prefix.size ());
1833 	      pipe_path = ending.substr (0, ending.find (' '));
1834 	      is_active = true;
1835 	    }
1836 	  else if (sscanf (makeflags.c_str () + n + js_needle.size (),
1837 			   "%d,%d", &rfd, &wfd) == 2
1838 	      && rfd > 0
1839 	      && wfd > 0
1840 	      && is_valid_fd (rfd)
1841 	      && is_valid_fd (wfd))
1842 	    is_active = true;
1843 	  else
1844 	    {
1845 	      string dup = makeflags.substr (0, n);
1846 	      size_t pos = makeflags.find (' ', n);
1847 	      if (pos != string::npos)
1848 		dup += makeflags.substr (pos);
1849 	      skipped_makeflags = "MAKEFLAGS=" + dup;
1850 	      error_msg
1851 		= "cannot access %<" + js_needle + "%> file descriptors";
1852 	    }
1853 	}
1854       error_msg = "%<" + js_needle + "%> is not present in %<MAKEFLAGS%>";
1855     }
1856   else
1857     error_msg = "%<MAKEFLAGS%> environment variable is unset";
1858 
1859   if (!error_msg.empty ())
1860     error_msg = "jobserver is not available: " + error_msg;
1861 }
1862