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