Bug Summary

File:tools/lldb/source/Interpreter/Options.cpp
Warning:line 1105, column 10
Access to field 'option_has_arg' results in a dereference of a null pointer (loaded from field 'definition')

Annotated Source Code

Press '?' to see keyboard shortcuts

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