1 //===-- Options.cpp ---------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Interpreter/Options.h"
10 
11 #include <algorithm>
12 #include <bitset>
13 #include <map>
14 #include <set>
15 
16 #include "lldb/Host/OptionParser.h"
17 #include "lldb/Interpreter/CommandCompletions.h"
18 #include "lldb/Interpreter/CommandInterpreter.h"
19 #include "lldb/Interpreter/CommandObject.h"
20 #include "lldb/Interpreter/CommandReturnObject.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Utility/StreamString.h"
23 
24 using namespace lldb;
25 using namespace lldb_private;
26 
27 //-------------------------------------------------------------------------
28 // Options
29 //-------------------------------------------------------------------------
30 Options::Options() : m_getopt_table() { BuildValidOptionSets(); }
31 
32 Options::~Options() {}
33 
34 void Options::NotifyOptionParsingStarting(ExecutionContext *execution_context) {
35   m_seen_options.clear();
36   // Let the subclass reset its option values
37   OptionParsingStarting(execution_context);
38 }
39 
40 Status
41 Options::NotifyOptionParsingFinished(ExecutionContext *execution_context) {
42   return OptionParsingFinished(execution_context);
43 }
44 
45 void Options::OptionSeen(int option_idx) { m_seen_options.insert(option_idx); }
46 
47 // Returns true is set_a is a subset of set_b;  Otherwise returns false.
48 
49 bool Options::IsASubset(const OptionSet &set_a, const OptionSet &set_b) {
50   bool is_a_subset = true;
51   OptionSet::const_iterator pos_a;
52   OptionSet::const_iterator pos_b;
53 
54   // set_a is a subset of set_b if every member of set_a is also a member of
55   // set_b
56 
57   for (pos_a = set_a.begin(); pos_a != set_a.end() && is_a_subset; ++pos_a) {
58     pos_b = set_b.find(*pos_a);
59     if (pos_b == set_b.end())
60       is_a_subset = false;
61   }
62 
63   return is_a_subset;
64 }
65 
66 // Returns the set difference set_a - set_b, i.e. { x | ElementOf (x, set_a) &&
67 // !ElementOf (x, set_b) }
68 
69 size_t Options::OptionsSetDiff(const OptionSet &set_a, const OptionSet &set_b,
70                                OptionSet &diffs) {
71   size_t num_diffs = 0;
72   OptionSet::const_iterator pos_a;
73   OptionSet::const_iterator pos_b;
74 
75   for (pos_a = set_a.begin(); pos_a != set_a.end(); ++pos_a) {
76     pos_b = set_b.find(*pos_a);
77     if (pos_b == set_b.end()) {
78       ++num_diffs;
79       diffs.insert(*pos_a);
80     }
81   }
82 
83   return num_diffs;
84 }
85 
86 // Returns the union of set_a and set_b.  Does not put duplicate members into
87 // the union.
88 
89 void Options::OptionsSetUnion(const OptionSet &set_a, const OptionSet &set_b,
90                               OptionSet &union_set) {
91   OptionSet::const_iterator pos;
92   OptionSet::iterator pos_union;
93 
94   // Put all the elements of set_a into the union.
95 
96   for (pos = set_a.begin(); pos != set_a.end(); ++pos)
97     union_set.insert(*pos);
98 
99   // Put all the elements of set_b that are not already there into the union.
100   for (pos = set_b.begin(); pos != set_b.end(); ++pos) {
101     pos_union = union_set.find(*pos);
102     if (pos_union == union_set.end())
103       union_set.insert(*pos);
104   }
105 }
106 
107 bool Options::VerifyOptions(CommandReturnObject &result) {
108   bool options_are_valid = false;
109 
110   int num_levels = GetRequiredOptions().size();
111   if (num_levels) {
112     for (int i = 0; i < num_levels && !options_are_valid; ++i) {
113       // This is the correct set of options if:  1). m_seen_options contains
114       // all of m_required_options[i] (i.e. all the required options at this
115       // level are a subset of m_seen_options); AND 2). { m_seen_options -
116       // m_required_options[i] is a subset of m_options_options[i] (i.e. all
117       // the rest of m_seen_options are in the set of optional options at this
118       // level.
119 
120       // Check to see if all of m_required_options[i] are a subset of
121       // m_seen_options
122       if (IsASubset(GetRequiredOptions()[i], m_seen_options)) {
123         // Construct the set difference: remaining_options = {m_seen_options} -
124         // {m_required_options[i]}
125         OptionSet remaining_options;
126         OptionsSetDiff(m_seen_options, GetRequiredOptions()[i],
127                        remaining_options);
128         // Check to see if remaining_options is a subset of
129         // m_optional_options[i]
130         if (IsASubset(remaining_options, GetOptionalOptions()[i]))
131           options_are_valid = true;
132       }
133     }
134   } else {
135     options_are_valid = true;
136   }
137 
138   if (options_are_valid) {
139     result.SetStatus(eReturnStatusSuccessFinishNoResult);
140   } else {
141     result.AppendError("invalid combination of options for the given command");
142     result.SetStatus(eReturnStatusFailed);
143   }
144 
145   return options_are_valid;
146 }
147 
148 // This is called in the Options constructor, though we could call it lazily if
149 // that ends up being a performance problem.
150 
151 void Options::BuildValidOptionSets() {
152   // Check to see if we already did this.
153   if (m_required_options.size() != 0)
154     return;
155 
156   // Check to see if there are any options.
157   int num_options = NumCommandOptions();
158   if (num_options == 0)
159     return;
160 
161   auto opt_defs = GetDefinitions();
162   m_required_options.resize(1);
163   m_optional_options.resize(1);
164 
165   // First count the number of option sets we've got.  Ignore
166   // LLDB_ALL_OPTION_SETS...
167 
168   uint32_t num_option_sets = 0;
169 
170   for (const auto &def : opt_defs) {
171     uint32_t this_usage_mask = def.usage_mask;
172     if (this_usage_mask == LLDB_OPT_SET_ALL) {
173       if (num_option_sets == 0)
174         num_option_sets = 1;
175     } else {
176       for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++) {
177         if (this_usage_mask & (1 << j)) {
178           if (num_option_sets <= j)
179             num_option_sets = j + 1;
180         }
181       }
182     }
183   }
184 
185   if (num_option_sets > 0) {
186     m_required_options.resize(num_option_sets);
187     m_optional_options.resize(num_option_sets);
188 
189     for (const auto &def : opt_defs) {
190       for (uint32_t j = 0; j < num_option_sets; j++) {
191         if (def.usage_mask & 1 << j) {
192           if (def.required)
193             m_required_options[j].insert(def.short_option);
194           else
195             m_optional_options[j].insert(def.short_option);
196         }
197       }
198     }
199   }
200 }
201 
202 uint32_t Options::NumCommandOptions() { return GetDefinitions().size(); }
203 
204 Option *Options::GetLongOptions() {
205   // Check to see if this has already been done.
206   if (m_getopt_table.empty()) {
207     auto defs = GetDefinitions();
208     if (defs.empty())
209       return nullptr;
210 
211     std::map<int, uint32_t> option_seen;
212 
213     m_getopt_table.resize(defs.size() + 1);
214     for (size_t i = 0; i < defs.size(); ++i) {
215       const int short_opt = defs[i].short_option;
216 
217       m_getopt_table[i].definition = &defs[i];
218       m_getopt_table[i].flag = nullptr;
219       m_getopt_table[i].val = short_opt;
220 
221       if (option_seen.find(short_opt) == option_seen.end()) {
222         option_seen[short_opt] = i;
223       } else if (short_opt) {
224         m_getopt_table[i].val = 0;
225         std::map<int, uint32_t>::const_iterator pos =
226             option_seen.find(short_opt);
227         StreamString strm;
228         if (isprint8(short_opt))
229           Host::SystemLog(Host::eSystemLogError,
230                           "option[%u] --%s has a short option -%c that "
231                           "conflicts with option[%u] --%s, short option won't "
232                           "be used for --%s\n",
233                           (int)i, defs[i].long_option, short_opt, pos->second,
234                           m_getopt_table[pos->second].definition->long_option,
235                           defs[i].long_option);
236         else
237           Host::SystemLog(Host::eSystemLogError,
238                           "option[%u] --%s has a short option 0x%x that "
239                           "conflicts with option[%u] --%s, short option won't "
240                           "be used for --%s\n",
241                           (int)i, defs[i].long_option, short_opt, pos->second,
242                           m_getopt_table[pos->second].definition->long_option,
243                           defs[i].long_option);
244       }
245     }
246 
247     // getopt_long_only requires a NULL final entry in the table:
248 
249     m_getopt_table.back().definition = nullptr;
250     m_getopt_table.back().flag = nullptr;
251     m_getopt_table.back().val = 0;
252   }
253 
254   if (m_getopt_table.empty())
255     return nullptr;
256 
257   return &m_getopt_table.front();
258 }
259 
260 // This function takes INDENT, which tells how many spaces to output at the
261 // front of each line; SPACES, which is a string containing 80 spaces; and
262 // TEXT, which is the text that is to be output.   It outputs the text, on
263 // multiple lines if necessary, to RESULT, with INDENT spaces at the front of
264 // each line.  It breaks lines on spaces, tabs or newlines, shortening the line
265 // if necessary to not break in the middle of a word.  It assumes that each
266 // output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
267 
268 void Options::OutputFormattedUsageText(Stream &strm,
269                                        const OptionDefinition &option_def,
270                                        uint32_t output_max_columns) {
271   std::string actual_text;
272   if (option_def.validator) {
273     const char *condition = option_def.validator->ShortConditionString();
274     if (condition) {
275       actual_text = "[";
276       actual_text.append(condition);
277       actual_text.append("] ");
278     }
279   }
280   actual_text.append(option_def.usage_text);
281 
282   // Will it all fit on one line?
283 
284   if (static_cast<uint32_t>(actual_text.length() + strm.GetIndentLevel()) <
285       output_max_columns) {
286     // Output it as a single line.
287     strm.Indent(actual_text.c_str());
288     strm.EOL();
289   } else {
290     // We need to break it up into multiple lines.
291 
292     int text_width = output_max_columns - strm.GetIndentLevel() - 1;
293     int start = 0;
294     int end = start;
295     int final_end = actual_text.length();
296     int sub_len;
297 
298     while (end < final_end) {
299       // Don't start the 'text' on a space, since we're already outputting the
300       // indentation.
301       while ((start < final_end) && (actual_text[start] == ' '))
302         start++;
303 
304       end = start + text_width;
305       if (end > final_end)
306         end = final_end;
307       else {
308         // If we're not at the end of the text, make sure we break the line on
309         // white space.
310         while (end > start && actual_text[end] != ' ' &&
311                actual_text[end] != '\t' && actual_text[end] != '\n')
312           end--;
313       }
314 
315       sub_len = end - start;
316       if (start != 0)
317         strm.EOL();
318       strm.Indent();
319       assert(start < final_end);
320       assert(start + sub_len <= final_end);
321       strm.Write(actual_text.c_str() + start, sub_len);
322       start = end + 1;
323     }
324     strm.EOL();
325   }
326 }
327 
328 bool Options::SupportsLongOption(const char *long_option) {
329   if (!long_option || !long_option[0])
330     return false;
331 
332   auto opt_defs = GetDefinitions();
333   if (opt_defs.empty())
334     return false;
335 
336   const char *long_option_name = long_option;
337   if (long_option[0] == '-' && long_option[1] == '-')
338     long_option_name += 2;
339 
340   for (auto &def : opt_defs) {
341     if (!def.long_option)
342       continue;
343 
344     if (strcmp(def.long_option, long_option_name) == 0)
345       return true;
346   }
347 
348   return false;
349 }
350 
351 enum OptionDisplayType {
352   eDisplayBestOption,
353   eDisplayShortOption,
354   eDisplayLongOption
355 };
356 
357 static bool PrintOption(const OptionDefinition &opt_def,
358                         OptionDisplayType display_type, const char *header,
359                         const char *footer, bool show_optional, Stream &strm) {
360   const bool has_short_option = isprint8(opt_def.short_option) != 0;
361 
362   if (display_type == eDisplayShortOption && !has_short_option)
363     return false;
364 
365   if (header && header[0])
366     strm.PutCString(header);
367 
368   if (show_optional && !opt_def.required)
369     strm.PutChar('[');
370   const bool show_short_option =
371       has_short_option && display_type != eDisplayLongOption;
372   if (show_short_option)
373     strm.Printf("-%c", opt_def.short_option);
374   else
375     strm.Printf("--%s", opt_def.long_option);
376   switch (opt_def.option_has_arg) {
377   case OptionParser::eNoArgument:
378     break;
379   case OptionParser::eRequiredArgument:
380     strm.Printf(" <%s>", CommandObject::GetArgumentName(opt_def.argument_type));
381     break;
382 
383   case OptionParser::eOptionalArgument:
384     strm.Printf("%s[<%s>]", show_short_option ? "" : "=",
385                 CommandObject::GetArgumentName(opt_def.argument_type));
386     break;
387   }
388   if (show_optional && !opt_def.required)
389     strm.PutChar(']');
390   if (footer && footer[0])
391     strm.PutCString(footer);
392   return true;
393 }
394 
395 void Options::GenerateOptionUsage(Stream &strm, CommandObject *cmd,
396                                   uint32_t screen_width) {
397   const bool only_print_args = cmd->IsDashDashCommand();
398 
399   auto opt_defs = GetDefinitions();
400   const uint32_t save_indent_level = strm.GetIndentLevel();
401   llvm::StringRef name;
402 
403   StreamString arguments_str;
404 
405   if (cmd) {
406     name = cmd->GetCommandName();
407     cmd->GetFormattedCommandArguments(arguments_str);
408   } else
409     name = "";
410 
411   strm.PutCString("\nCommand Options Usage:\n");
412 
413   strm.IndentMore(2);
414 
415   // First, show each usage level set of options, e.g. <cmd> [options-for-
416   // level-0]
417   //                                                   <cmd>
418   //                                                   [options-for-level-1]
419   //                                                   etc.
420 
421   const uint32_t num_options = NumCommandOptions();
422   if (num_options == 0)
423     return;
424 
425   uint32_t num_option_sets = GetRequiredOptions().size();
426 
427   uint32_t i;
428 
429   if (!only_print_args) {
430     for (uint32_t opt_set = 0; opt_set < num_option_sets; ++opt_set) {
431       uint32_t opt_set_mask;
432 
433       opt_set_mask = 1 << opt_set;
434       if (opt_set > 0)
435         strm.Printf("\n");
436       strm.Indent(name);
437 
438       // Different option sets may require different args.
439       StreamString args_str;
440       if (cmd)
441         cmd->GetFormattedCommandArguments(args_str, opt_set_mask);
442 
443       // First go through and print all options that take no arguments as a
444       // single string. If a command has "-a" "-b" and "-c", this will show up
445       // as [-abc]
446 
447       std::set<int> options;
448       std::set<int>::const_iterator options_pos, options_end;
449       for (auto &def : opt_defs) {
450         if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
451           // Add current option to the end of out_stream.
452 
453           if (def.required && def.option_has_arg == OptionParser::eNoArgument) {
454             options.insert(def.short_option);
455           }
456         }
457       }
458 
459       if (!options.empty()) {
460         // We have some required options with no arguments
461         strm.PutCString(" -");
462         for (i = 0; i < 2; ++i)
463           for (options_pos = options.begin(), options_end = options.end();
464                options_pos != options_end; ++options_pos) {
465             if (i == 0 && ::islower(*options_pos))
466               continue;
467             if (i == 1 && ::isupper(*options_pos))
468               continue;
469             strm << (char)*options_pos;
470           }
471       }
472 
473       options.clear();
474       for (auto &def : opt_defs) {
475         if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
476           // Add current option to the end of out_stream.
477 
478           if (!def.required &&
479               def.option_has_arg == OptionParser::eNoArgument) {
480             options.insert(def.short_option);
481           }
482         }
483       }
484 
485       if (!options.empty()) {
486         // We have some required options with no arguments
487         strm.PutCString(" [-");
488         for (i = 0; i < 2; ++i)
489           for (options_pos = options.begin(), options_end = options.end();
490                options_pos != options_end; ++options_pos) {
491             if (i == 0 && ::islower(*options_pos))
492               continue;
493             if (i == 1 && ::isupper(*options_pos))
494               continue;
495             strm << (char)*options_pos;
496           }
497         strm.PutChar(']');
498       }
499 
500       // First go through and print the required options (list them up front).
501 
502       for (auto &def : opt_defs) {
503         if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
504           if (def.required && def.option_has_arg != OptionParser::eNoArgument)
505             PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
506         }
507       }
508 
509       // Now go through again, and this time only print the optional options.
510 
511       for (auto &def : opt_defs) {
512         if (def.usage_mask & opt_set_mask) {
513           // Add current option to the end of out_stream.
514 
515           if (!def.required && def.option_has_arg != OptionParser::eNoArgument)
516             PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
517         }
518       }
519 
520       if (args_str.GetSize() > 0) {
521         if (cmd->WantsRawCommandString() && !only_print_args)
522           strm.Printf(" --");
523 
524         strm << " " << args_str.GetString();
525         if (only_print_args)
526           break;
527       }
528     }
529   }
530 
531   if (cmd && (only_print_args || cmd->WantsRawCommandString()) &&
532       arguments_str.GetSize() > 0) {
533     if (!only_print_args)
534       strm.PutChar('\n');
535     strm.Indent(name);
536     strm << " " << arguments_str.GetString();
537   }
538 
539   strm.Printf("\n\n");
540 
541   if (!only_print_args) {
542     // Now print out all the detailed information about the various options:
543     // long form, short form and help text:
544     //   -short <argument> ( --long_name <argument> )
545     //   help text
546 
547     // This variable is used to keep track of which options' info we've printed
548     // out, because some options can be in more than one usage level, but we
549     // only want to print the long form of its information once.
550 
551     std::multimap<int, uint32_t> options_seen;
552     strm.IndentMore(5);
553 
554     // Put the unique command options in a vector & sort it, so we can output
555     // them alphabetically (by short_option) when writing out detailed help for
556     // each option.
557 
558     i = 0;
559     for (auto &def : opt_defs)
560       options_seen.insert(std::make_pair(def.short_option, i++));
561 
562     // Go through the unique'd and alphabetically sorted vector of options,
563     // find the table entry for each option and write out the detailed help
564     // information for that option.
565 
566     bool first_option_printed = false;
567 
568     for (auto pos : options_seen) {
569       i = pos.second;
570       // Print out the help information for this option.
571 
572       // Put a newline separation between arguments
573       if (first_option_printed)
574         strm.EOL();
575       else
576         first_option_printed = true;
577 
578       CommandArgumentType arg_type = opt_defs[i].argument_type;
579 
580       StreamString arg_name_str;
581       arg_name_str.Printf("<%s>", CommandObject::GetArgumentName(arg_type));
582 
583       strm.Indent();
584       if (opt_defs[i].short_option && isprint8(opt_defs[i].short_option)) {
585         PrintOption(opt_defs[i], eDisplayShortOption, nullptr, nullptr, false,
586                     strm);
587         PrintOption(opt_defs[i], eDisplayLongOption, " ( ", " )", false, strm);
588       } else {
589         // Short option is not printable, just print long option
590         PrintOption(opt_defs[i], eDisplayLongOption, nullptr, nullptr, false,
591                     strm);
592       }
593       strm.EOL();
594 
595       strm.IndentMore(5);
596 
597       if (opt_defs[i].usage_text)
598         OutputFormattedUsageText(strm, opt_defs[i], screen_width);
599       if (!opt_defs[i].enum_values.empty()) {
600         strm.Indent();
601         strm.Printf("Values: ");
602         bool is_first = true;
603         for (const auto &enum_value : opt_defs[i].enum_values) {
604           if (is_first) {
605             strm.Printf("%s", enum_value.string_value);
606             is_first = false;
607           }
608           else
609             strm.Printf(" | %s", enum_value.string_value);
610         }
611         strm.EOL();
612       }
613       strm.IndentLess(5);
614     }
615   }
616 
617   // Restore the indent level
618   strm.SetIndentLevel(save_indent_level);
619 }
620 
621 // This function is called when we have been given a potentially incomplete set
622 // of options, such as when an alias has been defined (more options might be
623 // added at at the time the alias is invoked).  We need to verify that the
624 // options in the set m_seen_options are all part of a set that may be used
625 // together, but m_seen_options may be missing some of the "required" options.
626 
627 bool Options::VerifyPartialOptions(CommandReturnObject &result) {
628   bool options_are_valid = false;
629 
630   int num_levels = GetRequiredOptions().size();
631   if (num_levels) {
632     for (int i = 0; i < num_levels && !options_are_valid; ++i) {
633       // In this case we are treating all options as optional rather than
634       // required. Therefore a set of options is correct if m_seen_options is a
635       // subset of the union of m_required_options and m_optional_options.
636       OptionSet union_set;
637       OptionsSetUnion(GetRequiredOptions()[i], GetOptionalOptions()[i],
638                       union_set);
639       if (IsASubset(m_seen_options, union_set))
640         options_are_valid = true;
641     }
642   }
643 
644   return options_are_valid;
645 }
646 
647 bool Options::HandleOptionCompletion(CompletionRequest &request,
648                                      OptionElementVector &opt_element_vector,
649                                      CommandInterpreter &interpreter) {
650   request.SetWordComplete(true);
651 
652   // For now we just scan the completions to see if the cursor position is in
653   // an option or its argument.  Otherwise we'll call HandleArgumentCompletion.
654   // In the future we can use completion to validate options as well if we
655   // want.
656 
657   auto opt_defs = GetDefinitions();
658 
659   std::string cur_opt_std_str = request.GetCursorArgumentPrefix().str();
660   const char *cur_opt_str = cur_opt_std_str.c_str();
661 
662   for (size_t i = 0; i < opt_element_vector.size(); i++) {
663     int opt_pos = opt_element_vector[i].opt_pos;
664     int opt_arg_pos = opt_element_vector[i].opt_arg_pos;
665     int opt_defs_index = opt_element_vector[i].opt_defs_index;
666     if (opt_pos == request.GetCursorIndex()) {
667       // We're completing the option itself.
668 
669       if (opt_defs_index == OptionArgElement::eBareDash) {
670         // We're completing a bare dash.  That means all options are open.
671         // FIXME: We should scan the other options provided and only complete
672         // options
673         // within the option group they belong to.
674         char opt_str[3] = {'-', 'a', '\0'};
675 
676         for (auto &def : opt_defs) {
677           if (!def.short_option)
678             continue;
679           opt_str[1] = def.short_option;
680           request.AddCompletion(opt_str);
681         }
682 
683         return true;
684       } else if (opt_defs_index == OptionArgElement::eBareDoubleDash) {
685         std::string full_name("--");
686         for (auto &def : opt_defs) {
687           if (!def.short_option)
688             continue;
689 
690           full_name.erase(full_name.begin() + 2, full_name.end());
691           full_name.append(def.long_option);
692           request.AddCompletion(full_name.c_str());
693         }
694         return true;
695       } else if (opt_defs_index != OptionArgElement::eUnrecognizedArg) {
696         // We recognized it, if it an incomplete long option, complete it
697         // anyway (getopt_long_only is happy with shortest unique string, but
698         // it's still a nice thing to do.)  Otherwise return The string so the
699         // upper level code will know this is a full match and add the " ".
700         if (cur_opt_str && strlen(cur_opt_str) > 2 && cur_opt_str[0] == '-' &&
701             cur_opt_str[1] == '-' &&
702             strcmp(opt_defs[opt_defs_index].long_option, cur_opt_str) != 0) {
703           std::string full_name("--");
704           full_name.append(opt_defs[opt_defs_index].long_option);
705           request.AddCompletion(full_name.c_str());
706           return true;
707         } else {
708           request.AddCompletion(request.GetCursorArgument());
709           return true;
710         }
711       } else {
712         // FIXME - not handling wrong options yet:
713         // Check to see if they are writing a long option & complete it.
714         // I think we will only get in here if the long option table has two
715         // elements
716         // that are not unique up to this point.  getopt_long_only does
717         // shortest unique match for long options already.
718 
719         if (cur_opt_str && strlen(cur_opt_str) > 2 && cur_opt_str[0] == '-' &&
720             cur_opt_str[1] == '-') {
721           for (auto &def : opt_defs) {
722             if (!def.long_option)
723               continue;
724 
725             if (strstr(def.long_option, cur_opt_str + 2) == def.long_option) {
726               std::string full_name("--");
727               full_name.append(def.long_option);
728               request.AddCompletion(full_name.c_str());
729             }
730           }
731         }
732         return true;
733       }
734 
735     } else if (opt_arg_pos == request.GetCursorIndex()) {
736       // Okay the cursor is on the completion of an argument. See if it has a
737       // completion, otherwise return no matches.
738 
739       CompletionRequest subrequest = request;
740       subrequest.SetCursorCharPosition(subrequest.GetCursorArgument().size());
741       if (opt_defs_index != -1) {
742         HandleOptionArgumentCompletion(subrequest, opt_element_vector, i,
743                                        interpreter);
744         request.SetWordComplete(subrequest.GetWordComplete());
745         return true;
746       } else {
747         // No completion callback means no completions...
748         return true;
749       }
750 
751     } else {
752       // Not the last element, keep going.
753       continue;
754     }
755   }
756   return false;
757 }
758 
759 bool Options::HandleOptionArgumentCompletion(
760     CompletionRequest &request, OptionElementVector &opt_element_vector,
761     int opt_element_index, CommandInterpreter &interpreter) {
762   auto opt_defs = GetDefinitions();
763   std::unique_ptr<SearchFilter> filter_up;
764 
765   int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos;
766   int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
767 
768   // See if this is an enumeration type option, and if so complete it here:
769 
770   const auto &enum_values = opt_defs[opt_defs_index].enum_values;
771   if (!enum_values.empty()) {
772     bool return_value = false;
773     std::string match_string(
774         request.GetParsedLine().GetArgumentAtIndex(opt_arg_pos),
775         request.GetParsedLine().GetArgumentAtIndex(opt_arg_pos) +
776             request.GetCursorCharPosition());
777 
778     for (const auto &enum_value : enum_values) {
779       if (strstr(enum_value.string_value, match_string.c_str()) ==
780           enum_value.string_value) {
781         request.AddCompletion(enum_value.string_value);
782         return_value = true;
783       }
784     }
785     return return_value;
786   }
787 
788   // If this is a source file or symbol type completion, and  there is a -shlib
789   // option somewhere in the supplied arguments, then make a search filter for
790   // that shared library.
791   // FIXME: Do we want to also have an "OptionType" so we don't have to match
792   // string names?
793 
794   uint32_t completion_mask = opt_defs[opt_defs_index].completion_type;
795 
796   if (completion_mask == 0) {
797     lldb::CommandArgumentType option_arg_type =
798         opt_defs[opt_defs_index].argument_type;
799     if (option_arg_type != eArgTypeNone) {
800       const CommandObject::ArgumentTableEntry *arg_entry =
801           CommandObject::FindArgumentDataByType(
802               opt_defs[opt_defs_index].argument_type);
803       if (arg_entry)
804         completion_mask = arg_entry->completion_type;
805     }
806   }
807 
808   if (completion_mask & CommandCompletions::eSourceFileCompletion ||
809       completion_mask & CommandCompletions::eSymbolCompletion) {
810     for (size_t i = 0; i < opt_element_vector.size(); i++) {
811       int cur_defs_index = opt_element_vector[i].opt_defs_index;
812 
813       // trying to use <0 indices will definitely cause problems
814       if (cur_defs_index == OptionArgElement::eUnrecognizedArg ||
815           cur_defs_index == OptionArgElement::eBareDash ||
816           cur_defs_index == OptionArgElement::eBareDoubleDash)
817         continue;
818 
819       int cur_arg_pos = opt_element_vector[i].opt_arg_pos;
820       const char *cur_opt_name = opt_defs[cur_defs_index].long_option;
821 
822       // If this is the "shlib" option and there was an argument provided,
823       // restrict it to that shared library.
824       if (cur_opt_name && strcmp(cur_opt_name, "shlib") == 0 &&
825           cur_arg_pos != -1) {
826         const char *module_name =
827             request.GetParsedLine().GetArgumentAtIndex(cur_arg_pos);
828         if (module_name) {
829           FileSpec module_spec(module_name);
830           lldb::TargetSP target_sp =
831               interpreter.GetDebugger().GetSelectedTarget();
832           // Search filters require a target...
833           if (target_sp)
834             filter_up.reset(new SearchFilterByModule(target_sp, module_spec));
835         }
836         break;
837       }
838     }
839   }
840 
841   return CommandCompletions::InvokeCommonCompletionCallbacks(
842       interpreter, completion_mask, request, filter_up.get());
843 }
844 
845 void OptionGroupOptions::Append(OptionGroup *group) {
846   auto group_option_defs = group->GetDefinitions();
847   for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
848     m_option_infos.push_back(OptionInfo(group, i));
849     m_option_defs.push_back(group_option_defs[i]);
850   }
851 }
852 
853 const OptionGroup *OptionGroupOptions::GetGroupWithOption(char short_opt) {
854   for (uint32_t i = 0; i < m_option_defs.size(); i++) {
855     OptionDefinition opt_def = m_option_defs[i];
856     if (opt_def.short_option == short_opt)
857       return m_option_infos[i].option_group;
858   }
859   return nullptr;
860 }
861 
862 void OptionGroupOptions::Append(OptionGroup *group, uint32_t src_mask,
863                                 uint32_t dst_mask) {
864   auto group_option_defs = group->GetDefinitions();
865   for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
866     if (group_option_defs[i].usage_mask & src_mask) {
867       m_option_infos.push_back(OptionInfo(group, i));
868       m_option_defs.push_back(group_option_defs[i]);
869       m_option_defs.back().usage_mask = dst_mask;
870     }
871   }
872 }
873 
874 void OptionGroupOptions::Finalize() {
875   m_did_finalize = true;
876 }
877 
878 Status OptionGroupOptions::SetOptionValue(uint32_t option_idx,
879                                           llvm::StringRef option_value,
880                                           ExecutionContext *execution_context) {
881   // After calling OptionGroupOptions::Append(...), you must finalize the
882   // groups by calling OptionGroupOptions::Finlize()
883   assert(m_did_finalize);
884   Status error;
885   if (option_idx < m_option_infos.size()) {
886     error = m_option_infos[option_idx].option_group->SetOptionValue(
887         m_option_infos[option_idx].option_index, option_value,
888         execution_context);
889 
890   } else {
891     error.SetErrorString("invalid option index"); // Shouldn't happen...
892   }
893   return error;
894 }
895 
896 void OptionGroupOptions::OptionParsingStarting(
897     ExecutionContext *execution_context) {
898   std::set<OptionGroup *> group_set;
899   OptionInfos::iterator pos, end = m_option_infos.end();
900   for (pos = m_option_infos.begin(); pos != end; ++pos) {
901     OptionGroup *group = pos->option_group;
902     if (group_set.find(group) == group_set.end()) {
903       group->OptionParsingStarting(execution_context);
904       group_set.insert(group);
905     }
906   }
907 }
908 Status
909 OptionGroupOptions::OptionParsingFinished(ExecutionContext *execution_context) {
910   std::set<OptionGroup *> group_set;
911   Status error;
912   OptionInfos::iterator pos, end = m_option_infos.end();
913   for (pos = m_option_infos.begin(); pos != end; ++pos) {
914     OptionGroup *group = pos->option_group;
915     if (group_set.find(group) == group_set.end()) {
916       error = group->OptionParsingFinished(execution_context);
917       group_set.insert(group);
918       if (error.Fail())
919         return error;
920     }
921   }
922   return error;
923 }
924 
925 // OptionParser permutes the arguments while processing them, so we create a
926 // temporary array holding to avoid modification of the input arguments. The
927 // options themselves are never modified, but the API expects a char * anyway,
928 // hence the const_cast.
929 static std::vector<char *> GetArgvForParsing(const Args &args) {
930   std::vector<char *> result;
931   // OptionParser always skips the first argument as it is based on getopt().
932   result.push_back(const_cast<char *>("<FAKE-ARG0>"));
933   for (const Args::ArgEntry &entry : args)
934     result.push_back(const_cast<char *>(entry.c_str()));
935   return result;
936 }
937 
938 // Given a permuted argument, find it's position in the original Args vector.
939 static Args::const_iterator FindOriginalIter(const char *arg,
940                                              const Args &original) {
941   return llvm::find_if(
942       original, [arg](const Args::ArgEntry &D) { return D.c_str() == arg; });
943 }
944 
945 // Given a permuted argument, find it's index in the original Args vector.
946 static size_t FindOriginalIndex(const char *arg, const Args &original) {
947   return std::distance(original.begin(), FindOriginalIter(arg, original));
948 }
949 
950 // Construct a new Args object, consisting of the entries from the original
951 // arguments, but in the permuted order.
952 static Args ReconstituteArgsAfterParsing(llvm::ArrayRef<char *> parsed,
953                                          const Args &original) {
954   Args result;
955   for (const char *arg : parsed) {
956     auto pos = FindOriginalIter(arg, original);
957     assert(pos != original.end());
958     result.AppendArgument(pos->ref, pos->quote);
959   }
960   return result;
961 }
962 
963 static size_t FindArgumentIndexForOption(const Args &args,
964                                          const Option &long_option) {
965   std::string short_opt = llvm::formatv("-{0}", char(long_option.val)).str();
966   std::string long_opt =
967       llvm::formatv("--{0}", long_option.definition->long_option);
968   for (const auto &entry : llvm::enumerate(args)) {
969     if (entry.value().ref.startswith(short_opt) ||
970         entry.value().ref.startswith(long_opt))
971       return entry.index();
972   }
973 
974   return size_t(-1);
975 }
976 
977 llvm::Expected<Args> Options::ParseAlias(const Args &args,
978                                          OptionArgVector *option_arg_vector,
979                                          std::string &input_line) {
980   StreamString sstr;
981   int i;
982   Option *long_options = GetLongOptions();
983 
984   if (long_options == nullptr) {
985     return llvm::make_error<llvm::StringError>("Invalid long options",
986                                                llvm::inconvertibleErrorCode());
987   }
988 
989   for (i = 0; long_options[i].definition != nullptr; ++i) {
990     if (long_options[i].flag == nullptr) {
991       sstr << (char)long_options[i].val;
992       switch (long_options[i].definition->option_has_arg) {
993       default:
994       case OptionParser::eNoArgument:
995         break;
996       case OptionParser::eRequiredArgument:
997         sstr << ":";
998         break;
999       case OptionParser::eOptionalArgument:
1000         sstr << "::";
1001         break;
1002       }
1003     }
1004   }
1005 
1006   Args args_copy = args;
1007   std::vector<char *> argv = GetArgvForParsing(args);
1008 
1009   std::unique_lock<std::mutex> lock;
1010   OptionParser::Prepare(lock);
1011   int val;
1012   while (1) {
1013     int long_options_index = -1;
1014     val = OptionParser::Parse(argv.size(), &*argv.begin(), sstr.GetString(),
1015                               long_options, &long_options_index);
1016 
1017     if (val == -1)
1018       break;
1019 
1020     if (val == '?') {
1021       return llvm::make_error<llvm::StringError>(
1022           "Unknown or ambiguous option", llvm::inconvertibleErrorCode());
1023     }
1024 
1025     if (val == 0)
1026       continue;
1027 
1028     OptionSeen(val);
1029 
1030     // Look up the long option index
1031     if (long_options_index == -1) {
1032       for (int j = 0; long_options[j].definition || long_options[j].flag ||
1033                       long_options[j].val;
1034            ++j) {
1035         if (long_options[j].val == val) {
1036           long_options_index = j;
1037           break;
1038         }
1039       }
1040     }
1041 
1042     // See if the option takes an argument, and see if one was supplied.
1043     if (long_options_index == -1) {
1044       return llvm::make_error<llvm::StringError>(
1045           llvm::formatv("Invalid option with value '{0}'.", char(val)).str(),
1046           llvm::inconvertibleErrorCode());
1047     }
1048 
1049     StreamString option_str;
1050     option_str.Printf("-%c", val);
1051     const OptionDefinition *def = long_options[long_options_index].definition;
1052     int has_arg =
1053         (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1054 
1055     const char *option_arg = nullptr;
1056     switch (has_arg) {
1057     case OptionParser::eRequiredArgument:
1058       if (OptionParser::GetOptionArgument() == nullptr) {
1059         return llvm::make_error<llvm::StringError>(
1060             llvm::formatv("Option '{0}' is missing argument specifier.",
1061                           option_str.GetString())
1062                 .str(),
1063             llvm::inconvertibleErrorCode());
1064       }
1065       LLVM_FALLTHROUGH;
1066     case OptionParser::eOptionalArgument:
1067       option_arg = OptionParser::GetOptionArgument();
1068       LLVM_FALLTHROUGH;
1069     case OptionParser::eNoArgument:
1070       break;
1071     default:
1072       return llvm::make_error<llvm::StringError>(
1073           llvm::formatv("error with options table; invalid value in has_arg "
1074                         "field for option '{0}'.",
1075                         char(val))
1076               .str(),
1077           llvm::inconvertibleErrorCode());
1078     }
1079     if (!option_arg)
1080       option_arg = "<no-argument>";
1081     option_arg_vector->emplace_back(option_str.GetString(), has_arg,
1082                                     option_arg);
1083 
1084     // Find option in the argument list; also see if it was supposed to take an
1085     // argument and if one was supplied.  Remove option (and argument, if
1086     // given) from the argument list.  Also remove them from the
1087     // raw_input_string, if one was passed in.
1088     size_t idx =
1089         FindArgumentIndexForOption(args_copy, long_options[long_options_index]);
1090     if (idx == size_t(-1))
1091       continue;
1092 
1093     if (!input_line.empty()) {
1094       auto tmp_arg = args_copy[idx].ref;
1095       size_t pos = input_line.find(tmp_arg);
1096       if (pos != std::string::npos)
1097         input_line.erase(pos, tmp_arg.size());
1098     }
1099     args_copy.DeleteArgumentAtIndex(idx);
1100     if ((long_options[long_options_index].definition->option_has_arg !=
1101          OptionParser::eNoArgument) &&
1102         (OptionParser::GetOptionArgument() != nullptr) &&
1103         (idx < args_copy.GetArgumentCount()) &&
1104         (args_copy[idx].ref == OptionParser::GetOptionArgument())) {
1105       if (input_line.size() > 0) {
1106         auto tmp_arg = args_copy[idx].ref;
1107         size_t pos = input_line.find(tmp_arg);
1108         if (pos != std::string::npos)
1109           input_line.erase(pos, tmp_arg.size());
1110       }
1111       args_copy.DeleteArgumentAtIndex(idx);
1112     }
1113   }
1114 
1115   return std::move(args_copy);
1116 }
1117 
1118 OptionElementVector Options::ParseForCompletion(const Args &args,
1119                                                 uint32_t cursor_index) {
1120   OptionElementVector option_element_vector;
1121   StreamString sstr;
1122   Option *long_options = GetLongOptions();
1123   option_element_vector.clear();
1124 
1125   if (long_options == nullptr)
1126     return option_element_vector;
1127 
1128   // Leading : tells getopt to return a : for a missing option argument AND to
1129   // suppress error messages.
1130 
1131   sstr << ":";
1132   for (int i = 0; long_options[i].definition != nullptr; ++i) {
1133     if (long_options[i].flag == nullptr) {
1134       sstr << (char)long_options[i].val;
1135       switch (long_options[i].definition->option_has_arg) {
1136       default:
1137       case OptionParser::eNoArgument:
1138         break;
1139       case OptionParser::eRequiredArgument:
1140         sstr << ":";
1141         break;
1142       case OptionParser::eOptionalArgument:
1143         sstr << "::";
1144         break;
1145       }
1146     }
1147   }
1148 
1149   std::unique_lock<std::mutex> lock;
1150   OptionParser::Prepare(lock);
1151   OptionParser::EnableError(false);
1152 
1153   int val;
1154   auto opt_defs = GetDefinitions();
1155 
1156   std::vector<char *> dummy_vec = GetArgvForParsing(args);
1157 
1158   // I stick an element on the end of the input, because if the last element
1159   // is option that requires an argument, getopt_long_only will freak out.
1160   dummy_vec.push_back(const_cast<char *>("<FAKE-VALUE>"));
1161 
1162   bool failed_once = false;
1163   uint32_t dash_dash_pos = -1;
1164 
1165   while (1) {
1166     bool missing_argument = false;
1167     int long_options_index = -1;
1168 
1169     val = OptionParser::Parse(dummy_vec.size(), &dummy_vec[0], sstr.GetString(),
1170                               long_options, &long_options_index);
1171 
1172     if (val == -1) {
1173       // When we're completing a "--" which is the last option on line,
1174       if (failed_once)
1175         break;
1176 
1177       failed_once = true;
1178 
1179       // If this is a bare  "--" we mark it as such so we can complete it
1180       // successfully later.  Handling the "--" is a little tricky, since that
1181       // may mean end of options or arguments, or the user might want to
1182       // complete options by long name.  I make this work by checking whether
1183       // the cursor is in the "--" argument, and if so I assume we're
1184       // completing the long option, otherwise I let it pass to
1185       // OptionParser::Parse which will terminate the option parsing.  Note, in
1186       // either case we continue parsing the line so we can figure out what
1187       // other options were passed.  This will be useful when we come to
1188       // restricting completions based on what other options we've seen on the
1189       // line.
1190 
1191       if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1192               dummy_vec.size() &&
1193           (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1194         dash_dash_pos = FindOriginalIndex(
1195             dummy_vec[OptionParser::GetOptionIndex() - 1], args);
1196         if (dash_dash_pos == cursor_index) {
1197           option_element_vector.push_back(
1198               OptionArgElement(OptionArgElement::eBareDoubleDash, dash_dash_pos,
1199                                OptionArgElement::eBareDoubleDash));
1200           continue;
1201         } else
1202           break;
1203       } else
1204         break;
1205     } else if (val == '?') {
1206       option_element_vector.push_back(OptionArgElement(
1207           OptionArgElement::eUnrecognizedArg,
1208           FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1209                             args),
1210           OptionArgElement::eUnrecognizedArg));
1211       continue;
1212     } else if (val == 0) {
1213       continue;
1214     } else if (val == ':') {
1215       // This is a missing argument.
1216       val = OptionParser::GetOptionErrorCause();
1217       missing_argument = true;
1218     }
1219 
1220     OptionSeen(val);
1221 
1222     // Look up the long option index
1223     if (long_options_index == -1) {
1224       for (int j = 0; long_options[j].definition || long_options[j].flag ||
1225                       long_options[j].val;
1226            ++j) {
1227         if (long_options[j].val == val) {
1228           long_options_index = j;
1229           break;
1230         }
1231       }
1232     }
1233 
1234     // See if the option takes an argument, and see if one was supplied.
1235     if (long_options_index >= 0) {
1236       int opt_defs_index = -1;
1237       for (size_t i = 0; i < opt_defs.size(); i++) {
1238         if (opt_defs[i].short_option != val)
1239           continue;
1240         opt_defs_index = i;
1241         break;
1242       }
1243 
1244       const OptionDefinition *def = long_options[long_options_index].definition;
1245       int has_arg =
1246           (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1247       switch (has_arg) {
1248       case OptionParser::eNoArgument:
1249         option_element_vector.push_back(OptionArgElement(
1250             opt_defs_index,
1251             FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1252                               args),
1253             0));
1254         break;
1255       case OptionParser::eRequiredArgument:
1256         if (OptionParser::GetOptionArgument() != nullptr) {
1257           int arg_index;
1258           if (missing_argument)
1259             arg_index = -1;
1260           else
1261             arg_index = OptionParser::GetOptionIndex() - 2;
1262 
1263           option_element_vector.push_back(OptionArgElement(
1264               opt_defs_index,
1265               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1266                                 args),
1267               arg_index));
1268         } else {
1269           option_element_vector.push_back(OptionArgElement(
1270               opt_defs_index,
1271               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1272                                 args),
1273               -1));
1274         }
1275         break;
1276       case OptionParser::eOptionalArgument:
1277         if (OptionParser::GetOptionArgument() != nullptr) {
1278           option_element_vector.push_back(OptionArgElement(
1279               opt_defs_index,
1280               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1281                                 args),
1282               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1283                                 args)));
1284         } else {
1285           option_element_vector.push_back(OptionArgElement(
1286               opt_defs_index,
1287               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1288                                 args),
1289               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1290                                 args)));
1291         }
1292         break;
1293       default:
1294         // The options table is messed up.  Here we'll just continue
1295         option_element_vector.push_back(OptionArgElement(
1296             OptionArgElement::eUnrecognizedArg,
1297             FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1298                               args),
1299             OptionArgElement::eUnrecognizedArg));
1300         break;
1301       }
1302     } else {
1303       option_element_vector.push_back(OptionArgElement(
1304           OptionArgElement::eUnrecognizedArg,
1305           FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1306                             args),
1307           OptionArgElement::eUnrecognizedArg));
1308     }
1309   }
1310 
1311   // Finally we have to handle the case where the cursor index points at a
1312   // single "-".  We want to mark that in the option_element_vector, but only
1313   // if it is not after the "--".  But it turns out that OptionParser::Parse
1314   // just ignores an isolated "-".  So we have to look it up by hand here.  We
1315   // only care if it is AT the cursor position. Note, a single quoted dash is
1316   // not the same as a single dash...
1317 
1318   const Args::ArgEntry &cursor = args[cursor_index];
1319   if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1320        cursor_index < dash_dash_pos) &&
1321       !cursor.IsQuoted() && cursor.ref == "-") {
1322     option_element_vector.push_back(
1323         OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1324                          OptionArgElement::eBareDash));
1325   }
1326   return option_element_vector;
1327 }
1328 
1329 llvm::Expected<Args> Options::Parse(const Args &args,
1330                                     ExecutionContext *execution_context,
1331                                     lldb::PlatformSP platform_sp,
1332                                     bool require_validation) {
1333   StreamString sstr;
1334   Status error;
1335   Option *long_options = GetLongOptions();
1336   if (long_options == nullptr) {
1337     return llvm::make_error<llvm::StringError>("Invalid long options.",
1338                                                llvm::inconvertibleErrorCode());
1339   }
1340 
1341   for (int i = 0; long_options[i].definition != nullptr; ++i) {
1342     if (long_options[i].flag == nullptr) {
1343       if (isprint8(long_options[i].val)) {
1344         sstr << (char)long_options[i].val;
1345         switch (long_options[i].definition->option_has_arg) {
1346         default:
1347         case OptionParser::eNoArgument:
1348           break;
1349         case OptionParser::eRequiredArgument:
1350           sstr << ':';
1351           break;
1352         case OptionParser::eOptionalArgument:
1353           sstr << "::";
1354           break;
1355         }
1356       }
1357     }
1358   }
1359   std::vector<char *> argv = GetArgvForParsing(args);
1360   std::unique_lock<std::mutex> lock;
1361   OptionParser::Prepare(lock);
1362   int val;
1363   while (1) {
1364     int long_options_index = -1;
1365     val = OptionParser::Parse(argv.size(), &*argv.begin(), sstr.GetString(),
1366                               long_options, &long_options_index);
1367     if (val == -1)
1368       break;
1369 
1370     // Did we get an error?
1371     if (val == '?') {
1372       error.SetErrorStringWithFormat("unknown or ambiguous option");
1373       break;
1374     }
1375     // The option auto-set itself
1376     if (val == 0)
1377       continue;
1378 
1379     OptionSeen(val);
1380 
1381     // Lookup the long option index
1382     if (long_options_index == -1) {
1383       for (int i = 0; long_options[i].definition || long_options[i].flag ||
1384                       long_options[i].val;
1385            ++i) {
1386         if (long_options[i].val == val) {
1387           long_options_index = i;
1388           break;
1389         }
1390       }
1391     }
1392     // Call the callback with the option
1393     if (long_options_index >= 0 &&
1394         long_options[long_options_index].definition) {
1395       const OptionDefinition *def = long_options[long_options_index].definition;
1396 
1397       if (!platform_sp) {
1398         // User did not pass in an explicit platform.  Try to grab from the
1399         // execution context.
1400         TargetSP target_sp =
1401             execution_context ? execution_context->GetTargetSP() : TargetSP();
1402         platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
1403       }
1404       OptionValidator *validator = def->validator;
1405 
1406       if (!platform_sp && require_validation) {
1407         // Caller requires validation but we cannot validate as we don't have
1408         // the mandatory platform against which to validate.
1409         return llvm::make_error<llvm::StringError>(
1410             "cannot validate options: no platform available",
1411             llvm::inconvertibleErrorCode());
1412       }
1413 
1414       bool validation_failed = false;
1415       if (platform_sp) {
1416         // Ensure we have an execution context, empty or not.
1417         ExecutionContext dummy_context;
1418         ExecutionContext *exe_ctx_p =
1419             execution_context ? execution_context : &dummy_context;
1420         if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
1421           validation_failed = true;
1422           error.SetErrorStringWithFormat("Option \"%s\" invalid.  %s",
1423                                          def->long_option,
1424                                          def->validator->LongConditionString());
1425         }
1426       }
1427 
1428       // As long as validation didn't fail, we set the option value.
1429       if (!validation_failed)
1430         error =
1431             SetOptionValue(long_options_index,
1432                            (def->option_has_arg == OptionParser::eNoArgument)
1433                                ? nullptr
1434                                : OptionParser::GetOptionArgument(),
1435                            execution_context);
1436     } else {
1437       error.SetErrorStringWithFormat("invalid option with value '%i'", val);
1438     }
1439   }
1440 
1441   if (error.Fail())
1442     return error.ToError();
1443 
1444   argv.erase(argv.begin(), argv.begin() + OptionParser::GetOptionIndex());
1445   return ReconstituteArgsAfterParsing(argv, args);
1446 }
1447