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