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   const bool only_print_args = cmd->IsDashDashCommand();
394 
395   auto opt_defs = GetDefinitions();
396   const uint32_t save_indent_level = strm.GetIndentLevel();
397   llvm::StringRef name;
398 
399   StreamString arguments_str;
400 
401   if (cmd) {
402     name = cmd->GetCommandName();
403     cmd->GetFormattedCommandArguments(arguments_str);
404   } else
405     name = "";
406 
407   const uint32_t num_options = NumCommandOptions();
408   if (num_options == 0)
409     return;
410 
411   if (!only_print_args)
412     strm.PutCString("\nCommand Options Usage:\n");
413 
414   strm.IndentMore(2);
415 
416   // First, show each usage level set of options, e.g. <cmd> [options-for-
417   // level-0]
418   //                                                   <cmd>
419   //                                                   [options-for-level-1]
420   //                                                   etc.
421 
422   uint32_t num_option_sets = GetRequiredOptions().size();
423 
424   if (!only_print_args) {
425     for (uint32_t opt_set = 0; opt_set < num_option_sets; ++opt_set) {
426       uint32_t opt_set_mask;
427 
428       opt_set_mask = 1 << opt_set;
429       if (opt_set > 0)
430         strm.Printf("\n");
431       strm.Indent(name);
432 
433       // Different option sets may require different args.
434       StreamString args_str;
435       if (cmd)
436         cmd->GetFormattedCommandArguments(args_str, opt_set_mask);
437 
438       // First go through and print all options that take no arguments as a
439       // single string. If a command has "-a" "-b" and "-c", this will show up
440       // as [-abc]
441 
442       // We use a set here so that they will be sorted.
443       std::set<int> required_options;
444       std::set<int> optional_options;
445 
446       for (auto &def : opt_defs) {
447         if (def.usage_mask & opt_set_mask && def.HasShortOption() &&
448             def.option_has_arg == OptionParser::eNoArgument) {
449           if (def.required) {
450             required_options.insert(def.short_option);
451           } else {
452             optional_options.insert(def.short_option);
453           }
454         }
455       }
456 
457       if (!required_options.empty()) {
458         strm.PutCString(" -");
459         for (int short_option : required_options)
460           strm.PutChar(short_option);
461       }
462 
463       if (!optional_options.empty()) {
464         strm.PutCString(" [-");
465         for (int short_option : optional_options)
466           strm.PutChar(short_option);
467         strm.PutChar(']');
468       }
469 
470       // First go through and print the required options (list them up front).
471       for (auto &def : opt_defs) {
472         if (def.usage_mask & opt_set_mask && def.HasShortOption() &&
473             def.required && def.option_has_arg != OptionParser::eNoArgument)
474           PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
475       }
476 
477       // Now go through again, and this time only print the optional options.
478       for (auto &def : opt_defs) {
479         if (def.usage_mask & opt_set_mask && !def.required &&
480             def.option_has_arg != OptionParser::eNoArgument)
481           PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
482       }
483 
484       if (args_str.GetSize() > 0) {
485         if (cmd->WantsRawCommandString() && !only_print_args)
486           strm.Printf(" --");
487 
488         strm << " " << args_str.GetString();
489         if (only_print_args)
490           break;
491       }
492     }
493   }
494 
495   if (cmd && (only_print_args || cmd->WantsRawCommandString()) &&
496       arguments_str.GetSize() > 0) {
497     if (!only_print_args)
498       strm.PutChar('\n');
499     strm.Indent(name);
500     strm << " " << arguments_str.GetString();
501   }
502 
503   if (!only_print_args) {
504     strm.Printf("\n\n");
505 
506     // Now print out all the detailed information about the various options:
507     // long form, short form and help text:
508     //   -short <argument> ( --long_name <argument> )
509     //   help text
510 
511     strm.IndentMore(5);
512 
513     // Put the command options in a sorted container, so we can output
514     // them alphabetically by short_option.
515     std::multimap<int, uint32_t> options_ordered;
516     for (auto def : llvm::enumerate(opt_defs))
517       options_ordered.insert(
518           std::make_pair(def.value().short_option, def.index()));
519 
520     // Go through each option, find the table entry and write out the detailed
521     // help information for that option.
522 
523     bool first_option_printed = false;
524 
525     for (auto pos : options_ordered) {
526       // Put a newline separation between arguments
527       if (first_option_printed)
528         strm.EOL();
529       else
530         first_option_printed = true;
531 
532       OptionDefinition opt_def = opt_defs[pos.second];
533 
534       strm.Indent();
535       if (opt_def.short_option && opt_def.HasShortOption()) {
536         PrintOption(opt_def, eDisplayShortOption, nullptr, nullptr, false,
537                     strm);
538         PrintOption(opt_def, eDisplayLongOption, " ( ", " )", false, strm);
539       } else {
540         // Short option is not printable, just print long option
541         PrintOption(opt_def, eDisplayLongOption, nullptr, nullptr, false, strm);
542       }
543       strm.EOL();
544 
545       strm.IndentMore(5);
546 
547       if (opt_def.usage_text)
548         OutputFormattedUsageText(strm, opt_def, screen_width);
549       if (!opt_def.enum_values.empty()) {
550         strm.Indent();
551         strm.Printf("Values: ");
552         bool is_first = true;
553         for (const auto &enum_value : opt_def.enum_values) {
554           if (is_first) {
555             strm.Printf("%s", enum_value.string_value);
556             is_first = false;
557           }
558           else
559             strm.Printf(" | %s", enum_value.string_value);
560         }
561         strm.EOL();
562       }
563       strm.IndentLess(5);
564     }
565   }
566 
567   // Restore the indent level
568   strm.SetIndentLevel(save_indent_level);
569 }
570 
571 // This function is called when we have been given a potentially incomplete set
572 // of options, such as when an alias has been defined (more options might be
573 // added at at the time the alias is invoked).  We need to verify that the
574 // options in the set m_seen_options are all part of a set that may be used
575 // together, but m_seen_options may be missing some of the "required" options.
576 
577 bool Options::VerifyPartialOptions(CommandReturnObject &result) {
578   bool options_are_valid = false;
579 
580   int num_levels = GetRequiredOptions().size();
581   if (num_levels) {
582     for (int i = 0; i < num_levels && !options_are_valid; ++i) {
583       // In this case we are treating all options as optional rather than
584       // required. Therefore a set of options is correct if m_seen_options is a
585       // subset of the union of m_required_options and m_optional_options.
586       OptionSet union_set;
587       OptionsSetUnion(GetRequiredOptions()[i], GetOptionalOptions()[i],
588                       union_set);
589       if (IsASubset(m_seen_options, union_set))
590         options_are_valid = true;
591     }
592   }
593 
594   return options_are_valid;
595 }
596 
597 bool Options::HandleOptionCompletion(CompletionRequest &request,
598                                      OptionElementVector &opt_element_vector,
599                                      CommandInterpreter &interpreter) {
600   // For now we just scan the completions to see if the cursor position is in
601   // an option or its argument.  Otherwise we'll call HandleArgumentCompletion.
602   // In the future we can use completion to validate options as well if we
603   // want.
604 
605   auto opt_defs = GetDefinitions();
606 
607   llvm::StringRef cur_opt_str = request.GetCursorArgumentPrefix();
608 
609   for (size_t i = 0; i < opt_element_vector.size(); i++) {
610     size_t opt_pos = static_cast<size_t>(opt_element_vector[i].opt_pos);
611     size_t opt_arg_pos = static_cast<size_t>(opt_element_vector[i].opt_arg_pos);
612     int opt_defs_index = opt_element_vector[i].opt_defs_index;
613     if (opt_pos == request.GetCursorIndex()) {
614       // We're completing the option itself.
615 
616       if (opt_defs_index == OptionArgElement::eBareDash) {
617         // We're completing a bare dash.  That means all options are open.
618         // FIXME: We should scan the other options provided and only complete
619         // options
620         // within the option group they belong to.
621         std::string opt_str = "-a";
622 
623         for (auto &def : opt_defs) {
624           if (!def.short_option)
625             continue;
626           opt_str[1] = def.short_option;
627           request.AddCompletion(opt_str, def.usage_text);
628         }
629 
630         return true;
631       } else if (opt_defs_index == OptionArgElement::eBareDoubleDash) {
632         std::string full_name("--");
633         for (auto &def : opt_defs) {
634           if (!def.short_option)
635             continue;
636 
637           full_name.erase(full_name.begin() + 2, full_name.end());
638           full_name.append(def.long_option);
639           request.AddCompletion(full_name, def.usage_text);
640         }
641         return true;
642       } else if (opt_defs_index != OptionArgElement::eUnrecognizedArg) {
643         // We recognized it, if it an incomplete long option, complete it
644         // anyway (getopt_long_only is happy with shortest unique string, but
645         // it's still a nice thing to do.)  Otherwise return The string so the
646         // upper level code will know this is a full match and add the " ".
647         const OptionDefinition &opt = opt_defs[opt_defs_index];
648         llvm::StringRef long_option = opt.long_option;
649         if (cur_opt_str.startswith("--") && cur_opt_str != long_option) {
650           request.AddCompletion("--" + long_option.str(), opt.usage_text);
651           return true;
652         } else
653           request.AddCompletion(request.GetCursorArgumentPrefix());
654         return true;
655       } else {
656         // FIXME - not handling wrong options yet:
657         // Check to see if they are writing a long option & complete it.
658         // I think we will only get in here if the long option table has two
659         // elements
660         // that are not unique up to this point.  getopt_long_only does
661         // shortest unique match for long options already.
662         if (cur_opt_str.consume_front("--")) {
663           for (auto &def : opt_defs) {
664             llvm::StringRef long_option(def.long_option);
665             if (long_option.startswith(cur_opt_str))
666               request.AddCompletion("--" + long_option.str(), def.usage_text);
667           }
668         }
669         return true;
670       }
671 
672     } else if (opt_arg_pos == request.GetCursorIndex()) {
673       // Okay the cursor is on the completion of an argument. See if it has a
674       // completion, otherwise return no matches.
675       if (opt_defs_index != -1) {
676         HandleOptionArgumentCompletion(request, opt_element_vector, i,
677                                        interpreter);
678         return true;
679       } else {
680         // No completion callback means no completions...
681         return true;
682       }
683 
684     } else {
685       // Not the last element, keep going.
686       continue;
687     }
688   }
689   return false;
690 }
691 
692 void Options::HandleOptionArgumentCompletion(
693     CompletionRequest &request, OptionElementVector &opt_element_vector,
694     int opt_element_index, CommandInterpreter &interpreter) {
695   auto opt_defs = GetDefinitions();
696   std::unique_ptr<SearchFilter> filter_up;
697 
698   int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
699 
700   // See if this is an enumeration type option, and if so complete it here:
701 
702   const auto &enum_values = opt_defs[opt_defs_index].enum_values;
703   if (!enum_values.empty())
704     for (const auto &enum_value : enum_values)
705       request.TryCompleteCurrentArg(enum_value.string_value);
706 
707   // If this is a source file or symbol type completion, and  there is a -shlib
708   // option somewhere in the supplied arguments, then make a search filter for
709   // that shared library.
710   // FIXME: Do we want to also have an "OptionType" so we don't have to match
711   // string names?
712 
713   uint32_t completion_mask = opt_defs[opt_defs_index].completion_type;
714 
715   if (completion_mask == 0) {
716     lldb::CommandArgumentType option_arg_type =
717         opt_defs[opt_defs_index].argument_type;
718     if (option_arg_type != eArgTypeNone) {
719       const CommandObject::ArgumentTableEntry *arg_entry =
720           CommandObject::FindArgumentDataByType(
721               opt_defs[opt_defs_index].argument_type);
722       if (arg_entry)
723         completion_mask = arg_entry->completion_type;
724     }
725   }
726 
727   if (completion_mask & CommandCompletions::eSourceFileCompletion ||
728       completion_mask & CommandCompletions::eSymbolCompletion) {
729     for (size_t i = 0; i < opt_element_vector.size(); i++) {
730       int cur_defs_index = opt_element_vector[i].opt_defs_index;
731 
732       // trying to use <0 indices will definitely cause problems
733       if (cur_defs_index == OptionArgElement::eUnrecognizedArg ||
734           cur_defs_index == OptionArgElement::eBareDash ||
735           cur_defs_index == OptionArgElement::eBareDoubleDash)
736         continue;
737 
738       int cur_arg_pos = opt_element_vector[i].opt_arg_pos;
739       const char *cur_opt_name = opt_defs[cur_defs_index].long_option;
740 
741       // If this is the "shlib" option and there was an argument provided,
742       // restrict it to that shared library.
743       if (cur_opt_name && strcmp(cur_opt_name, "shlib") == 0 &&
744           cur_arg_pos != -1) {
745         const char *module_name =
746             request.GetParsedLine().GetArgumentAtIndex(cur_arg_pos);
747         if (module_name) {
748           FileSpec module_spec(module_name);
749           lldb::TargetSP target_sp =
750               interpreter.GetDebugger().GetSelectedTarget();
751           // Search filters require a target...
752           if (target_sp)
753             filter_up =
754                 std::make_unique<SearchFilterByModule>(target_sp, module_spec);
755         }
756         break;
757       }
758     }
759   }
760 
761   CommandCompletions::InvokeCommonCompletionCallbacks(
762       interpreter, completion_mask, request, filter_up.get());
763 }
764 
765 void OptionGroupOptions::Append(OptionGroup *group) {
766   auto group_option_defs = group->GetDefinitions();
767   for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
768     m_option_infos.push_back(OptionInfo(group, i));
769     m_option_defs.push_back(group_option_defs[i]);
770   }
771 }
772 
773 const OptionGroup *OptionGroupOptions::GetGroupWithOption(char short_opt) {
774   for (uint32_t i = 0; i < m_option_defs.size(); i++) {
775     OptionDefinition opt_def = m_option_defs[i];
776     if (opt_def.short_option == short_opt)
777       return m_option_infos[i].option_group;
778   }
779   return nullptr;
780 }
781 
782 void OptionGroupOptions::Append(OptionGroup *group, uint32_t src_mask,
783                                 uint32_t dst_mask) {
784   auto group_option_defs = group->GetDefinitions();
785   for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
786     if (group_option_defs[i].usage_mask & src_mask) {
787       m_option_infos.push_back(OptionInfo(group, i));
788       m_option_defs.push_back(group_option_defs[i]);
789       m_option_defs.back().usage_mask = dst_mask;
790     }
791   }
792 }
793 
794 void OptionGroupOptions::Finalize() {
795   m_did_finalize = true;
796 }
797 
798 Status OptionGroupOptions::SetOptionValue(uint32_t option_idx,
799                                           llvm::StringRef option_value,
800                                           ExecutionContext *execution_context) {
801   // After calling OptionGroupOptions::Append(...), you must finalize the
802   // groups by calling OptionGroupOptions::Finlize()
803   assert(m_did_finalize);
804   Status error;
805   if (option_idx < m_option_infos.size()) {
806     error = m_option_infos[option_idx].option_group->SetOptionValue(
807         m_option_infos[option_idx].option_index, option_value,
808         execution_context);
809 
810   } else {
811     error.SetErrorString("invalid option index"); // Shouldn't happen...
812   }
813   return error;
814 }
815 
816 void OptionGroupOptions::OptionParsingStarting(
817     ExecutionContext *execution_context) {
818   std::set<OptionGroup *> group_set;
819   OptionInfos::iterator pos, end = m_option_infos.end();
820   for (pos = m_option_infos.begin(); pos != end; ++pos) {
821     OptionGroup *group = pos->option_group;
822     if (group_set.find(group) == group_set.end()) {
823       group->OptionParsingStarting(execution_context);
824       group_set.insert(group);
825     }
826   }
827 }
828 Status
829 OptionGroupOptions::OptionParsingFinished(ExecutionContext *execution_context) {
830   std::set<OptionGroup *> group_set;
831   Status error;
832   OptionInfos::iterator pos, end = m_option_infos.end();
833   for (pos = m_option_infos.begin(); pos != end; ++pos) {
834     OptionGroup *group = pos->option_group;
835     if (group_set.find(group) == group_set.end()) {
836       error = group->OptionParsingFinished(execution_context);
837       group_set.insert(group);
838       if (error.Fail())
839         return error;
840     }
841   }
842   return error;
843 }
844 
845 // OptionParser permutes the arguments while processing them, so we create a
846 // temporary array holding to avoid modification of the input arguments. The
847 // options themselves are never modified, but the API expects a char * anyway,
848 // hence the const_cast.
849 static std::vector<char *> GetArgvForParsing(const Args &args) {
850   std::vector<char *> result;
851   // OptionParser always skips the first argument as it is based on getopt().
852   result.push_back(const_cast<char *>("<FAKE-ARG0>"));
853   for (const Args::ArgEntry &entry : args)
854     result.push_back(const_cast<char *>(entry.c_str()));
855   result.push_back(nullptr);
856   return result;
857 }
858 
859 // Given a permuted argument, find it's position in the original Args vector.
860 static Args::const_iterator FindOriginalIter(const char *arg,
861                                              const Args &original) {
862   return llvm::find_if(
863       original, [arg](const Args::ArgEntry &D) { return D.c_str() == arg; });
864 }
865 
866 // Given a permuted argument, find it's index in the original Args vector.
867 static size_t FindOriginalIndex(const char *arg, const Args &original) {
868   return std::distance(original.begin(), FindOriginalIter(arg, original));
869 }
870 
871 // Construct a new Args object, consisting of the entries from the original
872 // arguments, but in the permuted order.
873 static Args ReconstituteArgsAfterParsing(llvm::ArrayRef<char *> parsed,
874                                          const Args &original) {
875   Args result;
876   for (const char *arg : parsed) {
877     auto pos = FindOriginalIter(arg, original);
878     assert(pos != original.end());
879     result.AppendArgument(pos->ref(), pos->GetQuoteChar());
880   }
881   return result;
882 }
883 
884 static size_t FindArgumentIndexForOption(const Args &args,
885                                          const Option &long_option) {
886   std::string short_opt = llvm::formatv("-{0}", char(long_option.val)).str();
887   std::string long_opt =
888       std::string(llvm::formatv("--{0}", long_option.definition->long_option));
889   for (const auto &entry : llvm::enumerate(args)) {
890     if (entry.value().ref().startswith(short_opt) ||
891         entry.value().ref().startswith(long_opt))
892       return entry.index();
893   }
894 
895   return size_t(-1);
896 }
897 
898 static std::string BuildShortOptions(const Option *long_options) {
899   std::string storage;
900   llvm::raw_string_ostream sstr(storage);
901 
902   // Leading : tells getopt to return a : for a missing option argument AND to
903   // suppress error messages.
904   sstr << ":";
905 
906   for (size_t i = 0; long_options[i].definition != nullptr; ++i) {
907     if (long_options[i].flag == nullptr) {
908       sstr << (char)long_options[i].val;
909       switch (long_options[i].definition->option_has_arg) {
910       default:
911       case OptionParser::eNoArgument:
912         break;
913       case OptionParser::eRequiredArgument:
914         sstr << ":";
915         break;
916       case OptionParser::eOptionalArgument:
917         sstr << "::";
918         break;
919       }
920     }
921   }
922   return std::move(sstr.str());
923 }
924 
925 llvm::Expected<Args> Options::ParseAlias(const Args &args,
926                                          OptionArgVector *option_arg_vector,
927                                          std::string &input_line) {
928   Option *long_options = GetLongOptions();
929 
930   if (long_options == nullptr) {
931     return llvm::make_error<llvm::StringError>("Invalid long options",
932                                                llvm::inconvertibleErrorCode());
933   }
934 
935   std::string short_options = BuildShortOptions(long_options);
936 
937   Args args_copy = args;
938   std::vector<char *> argv = GetArgvForParsing(args);
939 
940   std::unique_lock<std::mutex> lock;
941   OptionParser::Prepare(lock);
942   int val;
943   while (true) {
944     int long_options_index = -1;
945     val = OptionParser::Parse(argv, short_options, long_options,
946                               &long_options_index);
947 
948     if (val == ':') {
949       return llvm::createStringError(llvm::inconvertibleErrorCode(),
950                                      "last option requires an argument");
951     }
952 
953     if (val == -1)
954       break;
955 
956     if (val == '?') {
957       return llvm::make_error<llvm::StringError>(
958           "Unknown or ambiguous option", llvm::inconvertibleErrorCode());
959     }
960 
961     if (val == 0)
962       continue;
963 
964     OptionSeen(val);
965 
966     // Look up the long option index
967     if (long_options_index == -1) {
968       for (int j = 0; long_options[j].definition || long_options[j].flag ||
969                       long_options[j].val;
970            ++j) {
971         if (long_options[j].val == val) {
972           long_options_index = j;
973           break;
974         }
975       }
976     }
977 
978     // See if the option takes an argument, and see if one was supplied.
979     if (long_options_index == -1) {
980       return llvm::make_error<llvm::StringError>(
981           llvm::formatv("Invalid option with value '{0}'.", char(val)).str(),
982           llvm::inconvertibleErrorCode());
983     }
984 
985     StreamString option_str;
986     option_str.Printf("-%c", val);
987     const OptionDefinition *def = long_options[long_options_index].definition;
988     int has_arg =
989         (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
990 
991     const char *option_arg = nullptr;
992     switch (has_arg) {
993     case OptionParser::eRequiredArgument:
994       if (OptionParser::GetOptionArgument() == nullptr) {
995         return llvm::make_error<llvm::StringError>(
996             llvm::formatv("Option '{0}' is missing argument specifier.",
997                           option_str.GetString())
998                 .str(),
999             llvm::inconvertibleErrorCode());
1000       }
1001       LLVM_FALLTHROUGH;
1002     case OptionParser::eOptionalArgument:
1003       option_arg = OptionParser::GetOptionArgument();
1004       LLVM_FALLTHROUGH;
1005     case OptionParser::eNoArgument:
1006       break;
1007     default:
1008       return llvm::make_error<llvm::StringError>(
1009           llvm::formatv("error with options table; invalid value in has_arg "
1010                         "field for option '{0}'.",
1011                         char(val))
1012               .str(),
1013           llvm::inconvertibleErrorCode());
1014     }
1015     if (!option_arg)
1016       option_arg = "<no-argument>";
1017     option_arg_vector->emplace_back(std::string(option_str.GetString()),
1018                                     has_arg, std::string(option_arg));
1019 
1020     // Find option in the argument list; also see if it was supposed to take an
1021     // argument and if one was supplied.  Remove option (and argument, if
1022     // given) from the argument list.  Also remove them from the
1023     // raw_input_string, if one was passed in.
1024     size_t idx =
1025         FindArgumentIndexForOption(args_copy, long_options[long_options_index]);
1026     if (idx == size_t(-1))
1027       continue;
1028 
1029     if (!input_line.empty()) {
1030       auto tmp_arg = args_copy[idx].ref();
1031       size_t pos = input_line.find(std::string(tmp_arg));
1032       if (pos != std::string::npos)
1033         input_line.erase(pos, tmp_arg.size());
1034     }
1035     args_copy.DeleteArgumentAtIndex(idx);
1036     if ((long_options[long_options_index].definition->option_has_arg !=
1037          OptionParser::eNoArgument) &&
1038         (OptionParser::GetOptionArgument() != nullptr) &&
1039         (idx < args_copy.GetArgumentCount()) &&
1040         (args_copy[idx].ref() == OptionParser::GetOptionArgument())) {
1041       if (input_line.size() > 0) {
1042         auto tmp_arg = args_copy[idx].ref();
1043         size_t pos = input_line.find(std::string(tmp_arg));
1044         if (pos != std::string::npos)
1045           input_line.erase(pos, tmp_arg.size());
1046       }
1047       args_copy.DeleteArgumentAtIndex(idx);
1048     }
1049   }
1050 
1051   return std::move(args_copy);
1052 }
1053 
1054 OptionElementVector Options::ParseForCompletion(const Args &args,
1055                                                 uint32_t cursor_index) {
1056   OptionElementVector option_element_vector;
1057   Option *long_options = GetLongOptions();
1058   option_element_vector.clear();
1059 
1060   if (long_options == nullptr)
1061     return option_element_vector;
1062 
1063   std::string short_options = BuildShortOptions(long_options);
1064 
1065   std::unique_lock<std::mutex> lock;
1066   OptionParser::Prepare(lock);
1067   OptionParser::EnableError(false);
1068 
1069   int val;
1070   auto opt_defs = GetDefinitions();
1071 
1072   std::vector<char *> dummy_vec = GetArgvForParsing(args);
1073 
1074   bool failed_once = false;
1075   uint32_t dash_dash_pos = -1;
1076 
1077   while (true) {
1078     bool missing_argument = false;
1079     int long_options_index = -1;
1080 
1081     val = OptionParser::Parse(dummy_vec, short_options, long_options,
1082                               &long_options_index);
1083 
1084     if (val == -1) {
1085       // When we're completing a "--" which is the last option on line,
1086       if (failed_once)
1087         break;
1088 
1089       failed_once = true;
1090 
1091       // If this is a bare  "--" we mark it as such so we can complete it
1092       // successfully later.  Handling the "--" is a little tricky, since that
1093       // may mean end of options or arguments, or the user might want to
1094       // complete options by long name.  I make this work by checking whether
1095       // the cursor is in the "--" argument, and if so I assume we're
1096       // completing the long option, otherwise I let it pass to
1097       // OptionParser::Parse which will terminate the option parsing.  Note, in
1098       // either case we continue parsing the line so we can figure out what
1099       // other options were passed.  This will be useful when we come to
1100       // restricting completions based on what other options we've seen on the
1101       // line.
1102 
1103       if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1104               dummy_vec.size() &&
1105           (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1106         dash_dash_pos = FindOriginalIndex(
1107             dummy_vec[OptionParser::GetOptionIndex() - 1], args);
1108         if (dash_dash_pos == cursor_index) {
1109           option_element_vector.push_back(
1110               OptionArgElement(OptionArgElement::eBareDoubleDash, dash_dash_pos,
1111                                OptionArgElement::eBareDoubleDash));
1112           continue;
1113         } else
1114           break;
1115       } else
1116         break;
1117     } else if (val == '?') {
1118       option_element_vector.push_back(OptionArgElement(
1119           OptionArgElement::eUnrecognizedArg,
1120           FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1121                             args),
1122           OptionArgElement::eUnrecognizedArg));
1123       continue;
1124     } else if (val == 0) {
1125       continue;
1126     } else if (val == ':') {
1127       // This is a missing argument.
1128       val = OptionParser::GetOptionErrorCause();
1129       missing_argument = true;
1130     }
1131 
1132     OptionSeen(val);
1133 
1134     // Look up the long option index
1135     if (long_options_index == -1) {
1136       for (int j = 0; long_options[j].definition || long_options[j].flag ||
1137                       long_options[j].val;
1138            ++j) {
1139         if (long_options[j].val == val) {
1140           long_options_index = j;
1141           break;
1142         }
1143       }
1144     }
1145 
1146     // See if the option takes an argument, and see if one was supplied.
1147     if (long_options_index >= 0) {
1148       int opt_defs_index = -1;
1149       for (size_t i = 0; i < opt_defs.size(); i++) {
1150         if (opt_defs[i].short_option != val)
1151           continue;
1152         opt_defs_index = i;
1153         break;
1154       }
1155 
1156       const OptionDefinition *def = long_options[long_options_index].definition;
1157       int has_arg =
1158           (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1159       switch (has_arg) {
1160       case OptionParser::eNoArgument:
1161         option_element_vector.push_back(OptionArgElement(
1162             opt_defs_index,
1163             FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1164                               args),
1165             0));
1166         break;
1167       case OptionParser::eRequiredArgument:
1168         if (OptionParser::GetOptionArgument() != nullptr) {
1169           int arg_index;
1170           if (missing_argument)
1171             arg_index = -1;
1172           else
1173             arg_index = OptionParser::GetOptionIndex() - 2;
1174 
1175           option_element_vector.push_back(OptionArgElement(
1176               opt_defs_index,
1177               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1178                                 args),
1179               arg_index));
1180         } else {
1181           option_element_vector.push_back(OptionArgElement(
1182               opt_defs_index,
1183               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1184                                 args),
1185               -1));
1186         }
1187         break;
1188       case OptionParser::eOptionalArgument:
1189         if (OptionParser::GetOptionArgument() != nullptr) {
1190           option_element_vector.push_back(OptionArgElement(
1191               opt_defs_index,
1192               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1193                                 args),
1194               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1195                                 args)));
1196         } else {
1197           option_element_vector.push_back(OptionArgElement(
1198               opt_defs_index,
1199               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1200                                 args),
1201               FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1202                                 args)));
1203         }
1204         break;
1205       default:
1206         // The options table is messed up.  Here we'll just continue
1207         option_element_vector.push_back(OptionArgElement(
1208             OptionArgElement::eUnrecognizedArg,
1209             FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1210                               args),
1211             OptionArgElement::eUnrecognizedArg));
1212         break;
1213       }
1214     } else {
1215       option_element_vector.push_back(OptionArgElement(
1216           OptionArgElement::eUnrecognizedArg,
1217           FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1218                             args),
1219           OptionArgElement::eUnrecognizedArg));
1220     }
1221   }
1222 
1223   // Finally we have to handle the case where the cursor index points at a
1224   // single "-".  We want to mark that in the option_element_vector, but only
1225   // if it is not after the "--".  But it turns out that OptionParser::Parse
1226   // just ignores an isolated "-".  So we have to look it up by hand here.  We
1227   // only care if it is AT the cursor position. Note, a single quoted dash is
1228   // not the same as a single dash...
1229 
1230   const Args::ArgEntry &cursor = args[cursor_index];
1231   if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1232        cursor_index < dash_dash_pos) &&
1233       !cursor.IsQuoted() && cursor.ref() == "-") {
1234     option_element_vector.push_back(
1235         OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1236                          OptionArgElement::eBareDash));
1237   }
1238   return option_element_vector;
1239 }
1240 
1241 llvm::Expected<Args> Options::Parse(const Args &args,
1242                                     ExecutionContext *execution_context,
1243                                     lldb::PlatformSP platform_sp,
1244                                     bool require_validation) {
1245   Status error;
1246   Option *long_options = GetLongOptions();
1247   if (long_options == nullptr) {
1248     return llvm::make_error<llvm::StringError>("Invalid long options.",
1249                                                llvm::inconvertibleErrorCode());
1250   }
1251 
1252   std::string short_options = BuildShortOptions(long_options);
1253   std::vector<char *> argv = GetArgvForParsing(args);
1254   std::unique_lock<std::mutex> lock;
1255   OptionParser::Prepare(lock);
1256   int val;
1257   while (true) {
1258     int long_options_index = -1;
1259     val = OptionParser::Parse(argv, short_options, long_options,
1260                               &long_options_index);
1261 
1262     if (val == ':') {
1263       error.SetErrorString("last option requires an argument");
1264       break;
1265     }
1266 
1267     if (val == -1)
1268       break;
1269 
1270     // Did we get an error?
1271     if (val == '?') {
1272       error.SetErrorString("unknown or ambiguous option");
1273       break;
1274     }
1275     // The option auto-set itself
1276     if (val == 0)
1277       continue;
1278 
1279     OptionSeen(val);
1280 
1281     // Lookup the long option index
1282     if (long_options_index == -1) {
1283       for (int i = 0; long_options[i].definition || long_options[i].flag ||
1284                       long_options[i].val;
1285            ++i) {
1286         if (long_options[i].val == val) {
1287           long_options_index = i;
1288           break;
1289         }
1290       }
1291     }
1292     // Call the callback with the option
1293     if (long_options_index >= 0 &&
1294         long_options[long_options_index].definition) {
1295       const OptionDefinition *def = long_options[long_options_index].definition;
1296 
1297       if (!platform_sp) {
1298         // User did not pass in an explicit platform.  Try to grab from the
1299         // execution context.
1300         TargetSP target_sp =
1301             execution_context ? execution_context->GetTargetSP() : TargetSP();
1302         platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
1303       }
1304       OptionValidator *validator = def->validator;
1305 
1306       if (!platform_sp && require_validation) {
1307         // Caller requires validation but we cannot validate as we don't have
1308         // the mandatory platform against which to validate.
1309         return llvm::make_error<llvm::StringError>(
1310             "cannot validate options: no platform available",
1311             llvm::inconvertibleErrorCode());
1312       }
1313 
1314       bool validation_failed = false;
1315       if (platform_sp) {
1316         // Ensure we have an execution context, empty or not.
1317         ExecutionContext dummy_context;
1318         ExecutionContext *exe_ctx_p =
1319             execution_context ? execution_context : &dummy_context;
1320         if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
1321           validation_failed = true;
1322           error.SetErrorStringWithFormat("Option \"%s\" invalid.  %s",
1323                                          def->long_option,
1324                                          def->validator->LongConditionString());
1325         }
1326       }
1327 
1328       // As long as validation didn't fail, we set the option value.
1329       if (!validation_failed)
1330         error =
1331             SetOptionValue(long_options_index,
1332                            (def->option_has_arg == OptionParser::eNoArgument)
1333                                ? nullptr
1334                                : OptionParser::GetOptionArgument(),
1335                            execution_context);
1336       // If the Option setting returned an error, we should stop parsing
1337       // and return the error.
1338       if (error.Fail())
1339         break;
1340     } else {
1341       error.SetErrorStringWithFormat("invalid option with value '%i'", val);
1342     }
1343   }
1344 
1345   if (error.Fail())
1346     return error.ToError();
1347 
1348   argv.pop_back();
1349   argv.erase(argv.begin(), argv.begin() + OptionParser::GetOptionIndex());
1350   return ReconstituteArgsAfterParsing(argv, args);
1351 }
1352