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