blob: a6c0b49396d03a088257ff290c722d0b0e56a77b [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Options.cpp ---------------------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Jim Ingham40af72e2010-06-15 19:49:27 +00009#include "lldb/Interpreter/Options.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000010
Caroline Ticef362c452010-09-09 16:44:14 +000011#include <algorithm>
Greg Claytonab65b342011-04-13 22:47:15 +000012#include <bitset>
Greg Clayton3bcdfc02012-12-04 00:32:51 +000013#include <map>
Enrico Granatabef55ac2016-03-14 22:17:04 +000014#include <set>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000015
Zachary Turner3eb2b442017-03-22 23:33:16 +000016#include "lldb/Host/OptionParser.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017#include "lldb/Interpreter/CommandCompletions.h"
18#include "lldb/Interpreter/CommandInterpreter.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000019#include "lldb/Interpreter/CommandObject.h"
20#include "lldb/Interpreter/CommandReturnObject.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include "lldb/Target/Target.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000022#include "lldb/Utility/StreamString.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023
24using namespace lldb;
25using namespace lldb_private;
26
27//-------------------------------------------------------------------------
28// Options
29//-------------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000030Options::Options() : m_getopt_table() { BuildValidOptionSets(); }
31
32Options::~Options() {}
33
34void Options::NotifyOptionParsingStarting(ExecutionContext *execution_context) {
35 m_seen_options.clear();
36 // Let the subclass reset its option values
37 OptionParsingStarting(execution_context);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038}
39
Zachary Turner97206d52017-05-12 04:51:55 +000040Status
41Options::NotifyOptionParsingFinished(ExecutionContext *execution_context) {
Kate Stoneb9c1b512016-09-06 20:57:50 +000042 return OptionParsingFinished(execution_context);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043}
44
Kate Stoneb9c1b512016-09-06 20:57:50 +000045void Options::OptionSeen(int option_idx) { m_seen_options.insert(option_idx); }
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046
47// Returns true is set_a is a subset of set_b; Otherwise returns false.
48
Kate Stoneb9c1b512016-09-06 20:57:50 +000049bool Options::IsASubset(const OptionSet &set_a, const OptionSet &set_b) {
50 bool is_a_subset = true;
51 OptionSet::const_iterator pos_a;
52 OptionSet::const_iterator pos_b;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053
Kate Stoneb9c1b512016-09-06 20:57:50 +000054 // set_a is a subset of set_b if every member of set_a is also a member of
55 // set_b
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056
Kate Stoneb9c1b512016-09-06 20:57:50 +000057 for (pos_a = set_a.begin(); pos_a != set_a.end() && is_a_subset; ++pos_a) {
58 pos_b = set_b.find(*pos_a);
59 if (pos_b == set_b.end())
60 is_a_subset = false;
61 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +000062
Kate Stoneb9c1b512016-09-06 20:57:50 +000063 return is_a_subset;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000064}
65
Kate Stoneb9c1b512016-09-06 20:57:50 +000066// Returns the set difference set_a - set_b, i.e. { x | ElementOf (x, set_a) &&
67// !ElementOf (x, set_b) }
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068
Kate Stoneb9c1b512016-09-06 20:57:50 +000069size_t Options::OptionsSetDiff(const OptionSet &set_a, const OptionSet &set_b,
70 OptionSet &diffs) {
71 size_t num_diffs = 0;
72 OptionSet::const_iterator pos_a;
73 OptionSet::const_iterator pos_b;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074
Kate Stoneb9c1b512016-09-06 20:57:50 +000075 for (pos_a = set_a.begin(); pos_a != set_a.end(); ++pos_a) {
76 pos_b = set_b.find(*pos_a);
77 if (pos_b == set_b.end()) {
78 ++num_diffs;
79 diffs.insert(*pos_a);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000080 }
Kate Stoneb9c1b512016-09-06 20:57:50 +000081 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +000082
Kate Stoneb9c1b512016-09-06 20:57:50 +000083 return num_diffs;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000084}
85
Kate Stoneb9c1b512016-09-06 20:57:50 +000086// Returns the union of set_a and set_b. Does not put duplicate members into
87// the union.
Chris Lattner30fdc8d2010-06-08 16:52:24 +000088
Kate Stoneb9c1b512016-09-06 20:57:50 +000089void Options::OptionsSetUnion(const OptionSet &set_a, const OptionSet &set_b,
90 OptionSet &union_set) {
91 OptionSet::const_iterator pos;
92 OptionSet::iterator pos_union;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000093
Kate Stoneb9c1b512016-09-06 20:57:50 +000094 // Put all the elements of set_a into the union.
Chris Lattner30fdc8d2010-06-08 16:52:24 +000095
Kate Stoneb9c1b512016-09-06 20:57:50 +000096 for (pos = set_a.begin(); pos != set_a.end(); ++pos)
97 union_set.insert(*pos);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000098
Kate Stoneb9c1b512016-09-06 20:57:50 +000099 // Put all the elements of set_b that are not already there into the union.
100 for (pos = set_b.begin(); pos != set_b.end(); ++pos) {
101 pos_union = union_set.find(*pos);
102 if (pos_union == union_set.end())
103 union_set.insert(*pos);
104 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000105}
106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107bool Options::VerifyOptions(CommandReturnObject &result) {
108 bool options_are_valid = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000109
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110 int num_levels = GetRequiredOptions().size();
111 if (num_levels) {
112 for (int i = 0; i < num_levels && !options_are_valid; ++i) {
Adrian Prantl05097242018-04-30 16:49:04 +0000113 // This is the correct set of options if: 1). m_seen_options contains
114 // all of m_required_options[i] (i.e. all the required options at this
115 // level are a subset of m_seen_options); AND 2). { m_seen_options -
116 // m_required_options[i] is a subset of m_options_options[i] (i.e. all
117 // the rest of m_seen_options are in the set of optional options at this
118 // level.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000119
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120 // Check to see if all of m_required_options[i] are a subset of
121 // m_seen_options
122 if (IsASubset(GetRequiredOptions()[i], m_seen_options)) {
123 // Construct the set difference: remaining_options = {m_seen_options} -
124 // {m_required_options[i]}
125 OptionSet remaining_options;
126 OptionsSetDiff(m_seen_options, GetRequiredOptions()[i],
127 remaining_options);
128 // Check to see if remaining_options is a subset of
129 // m_optional_options[i]
130 if (IsASubset(remaining_options, GetOptionalOptions()[i]))
131 options_are_valid = true;
132 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000133 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000134 } else {
135 options_are_valid = true;
136 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000137
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138 if (options_are_valid) {
139 result.SetStatus(eReturnStatusSuccessFinishNoResult);
140 } else {
141 result.AppendError("invalid combination of options for the given command");
142 result.SetStatus(eReturnStatusFailed);
143 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000144
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145 return options_are_valid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000146}
147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148// This is called in the Options constructor, though we could call it lazily if
Adrian Prantl05097242018-04-30 16:49:04 +0000149// that ends up being a performance problem.
Jim Ingham86511212010-06-15 18:47:14 +0000150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151void Options::BuildValidOptionSets() {
152 // Check to see if we already did this.
153 if (m_required_options.size() != 0)
154 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000155
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156 // Check to see if there are any options.
157 int num_options = NumCommandOptions();
158 if (num_options == 0)
159 return;
160
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000161 auto opt_defs = GetDefinitions();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 m_required_options.resize(1);
163 m_optional_options.resize(1);
164
165 // First count the number of option sets we've got. Ignore
166 // LLDB_ALL_OPTION_SETS...
167
168 uint32_t num_option_sets = 0;
169
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000170 for (const auto &def : opt_defs) {
171 uint32_t this_usage_mask = def.usage_mask;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172 if (this_usage_mask == LLDB_OPT_SET_ALL) {
173 if (num_option_sets == 0)
174 num_option_sets = 1;
175 } else {
176 for (uint32_t j = 0; j < LLDB_MAX_NUM_OPTION_SETS; j++) {
177 if (this_usage_mask & (1 << j)) {
178 if (num_option_sets <= j)
179 num_option_sets = j + 1;
180 }
181 }
182 }
183 }
184
185 if (num_option_sets > 0) {
186 m_required_options.resize(num_option_sets);
187 m_optional_options.resize(num_option_sets);
188
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000189 for (const auto &def : opt_defs) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190 for (uint32_t j = 0; j < num_option_sets; j++) {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000191 if (def.usage_mask & 1 << j) {
192 if (def.required)
193 m_required_options[j].insert(def.short_option);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194 else
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000195 m_optional_options[j].insert(def.short_option);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 }
197 }
198 }
199 }
200}
201
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000202uint32_t Options::NumCommandOptions() { return GetDefinitions().size(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203
204Option *Options::GetLongOptions() {
205 // Check to see if this has already been done.
206 if (m_getopt_table.empty()) {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000207 auto defs = GetDefinitions();
208 if (defs.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 return nullptr;
210
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211 std::map<int, uint32_t> option_seen;
Enrico Granata4ebb8a42016-03-15 01:17:32 +0000212
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000213 m_getopt_table.resize(defs.size() + 1);
214 for (size_t i = 0; i < defs.size(); ++i) {
215 const int short_opt = defs[i].short_option;
Greg Claytoned8a7052010-09-18 03:37:20 +0000216
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000217 m_getopt_table[i].definition = &defs[i];
Kate Stoneb9c1b512016-09-06 20:57:50 +0000218 m_getopt_table[i].flag = nullptr;
219 m_getopt_table[i].val = short_opt;
Enrico Granatabef55ac2016-03-14 22:17:04 +0000220
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221 if (option_seen.find(short_opt) == option_seen.end()) {
222 option_seen[short_opt] = i;
223 } else if (short_opt) {
224 m_getopt_table[i].val = 0;
225 std::map<int, uint32_t>::const_iterator pos =
226 option_seen.find(short_opt);
227 StreamString strm;
228 if (isprint8(short_opt))
229 Host::SystemLog(Host::eSystemLogError,
230 "option[%u] --%s has a short option -%c that "
231 "conflicts with option[%u] --%s, short option won't "
232 "be used for --%s\n",
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000233 (int)i, defs[i].long_option, short_opt, pos->second,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 m_getopt_table[pos->second].definition->long_option,
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000235 defs[i].long_option);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236 else
237 Host::SystemLog(Host::eSystemLogError,
238 "option[%u] --%s has a short option 0x%x that "
239 "conflicts with option[%u] --%s, short option won't "
240 "be used for --%s\n",
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000241 (int)i, defs[i].long_option, short_opt, pos->second,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242 m_getopt_table[pos->second].definition->long_option,
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000243 defs[i].long_option);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000245 }
246
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247 // getopt_long_only requires a NULL final entry in the table:
248
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000249 m_getopt_table.back().definition = nullptr;
250 m_getopt_table.back().flag = nullptr;
251 m_getopt_table.back().val = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252 }
253
254 if (m_getopt_table.empty())
255 return nullptr;
256
257 return &m_getopt_table.front();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000258}
259
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260// This function takes INDENT, which tells how many spaces to output at the
Adrian Prantl05097242018-04-30 16:49:04 +0000261// front of each line; SPACES, which is a string containing 80 spaces; and
262// TEXT, which is the text that is to be output. It outputs the text, on
Kate Stoneb9c1b512016-09-06 20:57:50 +0000263// multiple lines if necessary, to RESULT, with INDENT spaces at the front of
Adrian Prantl05097242018-04-30 16:49:04 +0000264// each line. It breaks lines on spaces, tabs or newlines, shortening the line
265// if necessary to not break in the middle of a word. It assumes that each
Kate Stoneb9c1b512016-09-06 20:57:50 +0000266// output line should contain a maximum of OUTPUT_MAX_COLUMNS characters.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000267
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268void Options::OutputFormattedUsageText(Stream &strm,
269 const OptionDefinition &option_def,
270 uint32_t output_max_columns) {
271 std::string actual_text;
272 if (option_def.validator) {
273 const char *condition = option_def.validator->ShortConditionString();
274 if (condition) {
275 actual_text = "[";
276 actual_text.append(condition);
277 actual_text.append("] ");
278 }
279 }
280 actual_text.append(option_def.usage_text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000281
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 // Will it all fit on one line?
283
284 if (static_cast<uint32_t>(actual_text.length() + strm.GetIndentLevel()) <
285 output_max_columns) {
286 // Output it as a single line.
287 strm.Indent(actual_text.c_str());
288 strm.EOL();
289 } else {
290 // We need to break it up into multiple lines.
291
292 int text_width = output_max_columns - strm.GetIndentLevel() - 1;
293 int start = 0;
294 int end = start;
295 int final_end = actual_text.length();
296 int sub_len;
297
298 while (end < final_end) {
299 // Don't start the 'text' on a space, since we're already outputting the
300 // indentation.
301 while ((start < final_end) && (actual_text[start] == ' '))
302 start++;
303
304 end = start + text_width;
305 if (end > final_end)
306 end = final_end;
307 else {
308 // If we're not at the end of the text, make sure we break the line on
309 // white space.
310 while (end > start && actual_text[end] != ' ' &&
311 actual_text[end] != '\t' && actual_text[end] != '\n')
312 end--;
313 }
314
315 sub_len = end - start;
316 if (start != 0)
317 strm.EOL();
318 strm.Indent();
319 assert(start < final_end);
320 assert(start + sub_len <= final_end);
321 strm.Write(actual_text.c_str() + start, sub_len);
322 start = end + 1;
323 }
324 strm.EOL();
325 }
326}
327
328bool Options::SupportsLongOption(const char *long_option) {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000329 if (!long_option || !long_option[0])
330 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000332 auto opt_defs = GetDefinitions();
333 if (opt_defs.empty())
334 return false;
335
336 const char *long_option_name = long_option;
337 if (long_option[0] == '-' && long_option[1] == '-')
338 long_option_name += 2;
339
340 for (auto &def : opt_defs) {
341 if (!def.long_option)
342 continue;
343
344 if (strcmp(def.long_option, long_option_name) == 0)
345 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346 }
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000347
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 return false;
349}
350
351enum OptionDisplayType {
352 eDisplayBestOption,
353 eDisplayShortOption,
354 eDisplayLongOption
355};
356
357static bool PrintOption(const OptionDefinition &opt_def,
358 OptionDisplayType display_type, const char *header,
359 const char *footer, bool show_optional, Stream &strm) {
360 const bool has_short_option = isprint8(opt_def.short_option) != 0;
361
362 if (display_type == eDisplayShortOption && !has_short_option)
363 return false;
364
365 if (header && header[0])
366 strm.PutCString(header);
367
368 if (show_optional && !opt_def.required)
369 strm.PutChar('[');
370 const bool show_short_option =
371 has_short_option && display_type != eDisplayLongOption;
372 if (show_short_option)
373 strm.Printf("-%c", opt_def.short_option);
374 else
375 strm.Printf("--%s", opt_def.long_option);
376 switch (opt_def.option_has_arg) {
377 case OptionParser::eNoArgument:
378 break;
379 case OptionParser::eRequiredArgument:
380 strm.Printf(" <%s>", CommandObject::GetArgumentName(opt_def.argument_type));
381 break;
382
383 case OptionParser::eOptionalArgument:
384 strm.Printf("%s[<%s>]", show_short_option ? "" : "=",
385 CommandObject::GetArgumentName(opt_def.argument_type));
386 break;
387 }
388 if (show_optional && !opt_def.required)
389 strm.PutChar(']');
390 if (footer && footer[0])
391 strm.PutCString(footer);
392 return true;
393}
394
395void Options::GenerateOptionUsage(Stream &strm, CommandObject *cmd,
396 uint32_t screen_width) {
397 const bool only_print_args = cmd->IsDashDashCommand();
398
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000399 auto opt_defs = GetDefinitions();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 const uint32_t save_indent_level = strm.GetIndentLevel();
Zachary Turnera4496982016-10-05 21:14:38 +0000401 llvm::StringRef name;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402
403 StreamString arguments_str;
404
405 if (cmd) {
406 name = cmd->GetCommandName();
407 cmd->GetFormattedCommandArguments(arguments_str);
408 } else
409 name = "";
410
411 strm.PutCString("\nCommand Options Usage:\n");
412
413 strm.IndentMore(2);
414
Adrian Prantl05097242018-04-30 16:49:04 +0000415 // First, show each usage level set of options, e.g. <cmd> [options-for-
416 // level-0]
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417 // <cmd>
418 // [options-for-level-1]
419 // etc.
420
421 const uint32_t num_options = NumCommandOptions();
422 if (num_options == 0)
423 return;
424
425 uint32_t num_option_sets = GetRequiredOptions().size();
426
427 uint32_t i;
428
429 if (!only_print_args) {
430 for (uint32_t opt_set = 0; opt_set < num_option_sets; ++opt_set) {
431 uint32_t opt_set_mask;
432
433 opt_set_mask = 1 << opt_set;
434 if (opt_set > 0)
435 strm.Printf("\n");
436 strm.Indent(name);
437
438 // Different option sets may require different args.
439 StreamString args_str;
440 if (cmd)
441 cmd->GetFormattedCommandArguments(args_str, opt_set_mask);
442
Adrian Prantl05097242018-04-30 16:49:04 +0000443 // First go through and print all options that take no arguments as a
444 // single string. If a command has "-a" "-b" and "-c", this will show up
445 // as [-abc]
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446
447 std::set<int> options;
448 std::set<int>::const_iterator options_pos, options_end;
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000449 for (auto &def : opt_defs) {
450 if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451 // Add current option to the end of out_stream.
452
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000453 if (def.required && def.option_has_arg == OptionParser::eNoArgument) {
454 options.insert(def.short_option);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455 }
456 }
457 }
458
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000459 if (!options.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 // We have some required options with no arguments
461 strm.PutCString(" -");
462 for (i = 0; i < 2; ++i)
463 for (options_pos = options.begin(), options_end = options.end();
464 options_pos != options_end; ++options_pos) {
465 if (i == 0 && ::islower(*options_pos))
466 continue;
467 if (i == 1 && ::isupper(*options_pos))
468 continue;
469 strm << (char)*options_pos;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000470 }
471 }
472
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000473 options.clear();
474 for (auto &def : opt_defs) {
475 if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 // Add current option to the end of out_stream.
477
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000478 if (!def.required &&
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000479 def.option_has_arg == OptionParser::eNoArgument) {
480 options.insert(def.short_option);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481 }
482 }
483 }
484
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000485 if (!options.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 // We have some required options with no arguments
487 strm.PutCString(" [-");
488 for (i = 0; i < 2; ++i)
489 for (options_pos = options.begin(), options_end = options.end();
490 options_pos != options_end; ++options_pos) {
491 if (i == 0 && ::islower(*options_pos))
492 continue;
493 if (i == 1 && ::isupper(*options_pos))
494 continue;
495 strm << (char)*options_pos;
496 }
497 strm.PutChar(']');
498 }
499
500 // First go through and print the required options (list them up front).
501
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000502 for (auto &def : opt_defs) {
503 if (def.usage_mask & opt_set_mask && isprint8(def.short_option)) {
504 if (def.required && def.option_has_arg != OptionParser::eNoArgument)
505 PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506 }
507 }
508
509 // Now go through again, and this time only print the optional options.
510
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000511 for (auto &def : opt_defs) {
512 if (def.usage_mask & opt_set_mask) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513 // Add current option to the end of out_stream.
514
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000515 if (!def.required && def.option_has_arg != OptionParser::eNoArgument)
516 PrintOption(def, eDisplayBestOption, " ", nullptr, true, strm);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 }
518 }
519
520 if (args_str.GetSize() > 0) {
521 if (cmd->WantsRawCommandString() && !only_print_args)
522 strm.Printf(" --");
523
Zachary Turnerc1564272016-11-16 21:15:24 +0000524 strm << " " << args_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 if (only_print_args)
526 break;
527 }
528 }
529 }
530
531 if (cmd && (only_print_args || cmd->WantsRawCommandString()) &&
532 arguments_str.GetSize() > 0) {
533 if (!only_print_args)
534 strm.PutChar('\n');
535 strm.Indent(name);
Zachary Turnerc1564272016-11-16 21:15:24 +0000536 strm << " " << arguments_str.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537 }
538
539 strm.Printf("\n\n");
540
541 if (!only_print_args) {
542 // Now print out all the detailed information about the various options:
543 // long form, short form and help text:
544 // -short <argument> ( --long_name <argument> )
545 // help text
546
547 // This variable is used to keep track of which options' info we've printed
Adrian Prantl05097242018-04-30 16:49:04 +0000548 // out, because some options can be in more than one usage level, but we
549 // only want to print the long form of its information once.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550
551 std::multimap<int, uint32_t> options_seen;
552 strm.IndentMore(5);
553
554 // Put the unique command options in a vector & sort it, so we can output
Adrian Prantl05097242018-04-30 16:49:04 +0000555 // them alphabetically (by short_option) when writing out detailed help for
556 // each option.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000558 i = 0;
559 for (auto &def : opt_defs)
560 options_seen.insert(std::make_pair(def.short_option, i++));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561
Adrian Prantl05097242018-04-30 16:49:04 +0000562 // Go through the unique'd and alphabetically sorted vector of options,
563 // find the table entry for each option and write out the detailed help
564 // information for that option.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565
566 bool first_option_printed = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567
568 for (auto pos : options_seen) {
569 i = pos.second;
570 // Print out the help information for this option.
571
572 // Put a newline separation between arguments
573 if (first_option_printed)
574 strm.EOL();
575 else
576 first_option_printed = true;
577
578 CommandArgumentType arg_type = opt_defs[i].argument_type;
579
580 StreamString arg_name_str;
581 arg_name_str.Printf("<%s>", CommandObject::GetArgumentName(arg_type));
582
583 strm.Indent();
584 if (opt_defs[i].short_option && isprint8(opt_defs[i].short_option)) {
585 PrintOption(opt_defs[i], eDisplayShortOption, nullptr, nullptr, false,
586 strm);
587 PrintOption(opt_defs[i], eDisplayLongOption, " ( ", " )", false, strm);
588 } else {
589 // Short option is not printable, just print long option
590 PrintOption(opt_defs[i], eDisplayLongOption, nullptr, nullptr, false,
591 strm);
592 }
593 strm.EOL();
594
595 strm.IndentMore(5);
596
597 if (opt_defs[i].usage_text)
598 OutputFormattedUsageText(strm, opt_defs[i], screen_width);
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000599 if (!opt_defs[i].enum_values.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 strm.Indent();
601 strm.Printf("Values: ");
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000602 bool is_first = true;
603 for (const auto &enum_value : opt_defs[i].enum_values) {
604 if (is_first) {
605 strm.Printf("%s", enum_value.string_value);
606 is_first = false;
607 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608 else
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000609 strm.Printf(" | %s", enum_value.string_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000610 }
611 strm.EOL();
612 }
613 strm.IndentLess(5);
614 }
615 }
616
617 // Restore the indent level
618 strm.SetIndentLevel(save_indent_level);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000619}
620
Kate Stoneb9c1b512016-09-06 20:57:50 +0000621// This function is called when we have been given a potentially incomplete set
Adrian Prantl05097242018-04-30 16:49:04 +0000622// of options, such as when an alias has been defined (more options might be
623// added at at the time the alias is invoked). We need to verify that the
624// options in the set m_seen_options are all part of a set that may be used
625// together, but m_seen_options may be missing some of the "required" options.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000626
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627bool Options::VerifyPartialOptions(CommandReturnObject &result) {
628 bool options_are_valid = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000629
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630 int num_levels = GetRequiredOptions().size();
631 if (num_levels) {
632 for (int i = 0; i < num_levels && !options_are_valid; ++i) {
633 // In this case we are treating all options as optional rather than
Adrian Prantl05097242018-04-30 16:49:04 +0000634 // required. Therefore a set of options is correct if m_seen_options is a
635 // subset of the union of m_required_options and m_optional_options.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636 OptionSet union_set;
637 OptionsSetUnion(GetRequiredOptions()[i], GetOptionalOptions()[i],
638 union_set);
639 if (IsASubset(m_seen_options, union_set))
640 options_are_valid = true;
641 }
642 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000643
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644 return options_are_valid;
645}
Jim Inghamd6ccc602010-06-24 20:30:15 +0000646
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000647bool Options::HandleOptionCompletion(CompletionRequest &request,
648 OptionElementVector &opt_element_vector,
649 CommandInterpreter &interpreter) {
650 request.SetWordComplete(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651
652 // For now we just scan the completions to see if the cursor position is in
653 // an option or its argument. Otherwise we'll call HandleArgumentCompletion.
Adrian Prantl05097242018-04-30 16:49:04 +0000654 // In the future we can use completion to validate options as well if we
655 // want.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000657 auto opt_defs = GetDefinitions();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000659 std::string cur_opt_std_str = request.GetCursorArgumentPrefix().str();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660 const char *cur_opt_str = cur_opt_std_str.c_str();
661
662 for (size_t i = 0; i < opt_element_vector.size(); i++) {
663 int opt_pos = opt_element_vector[i].opt_pos;
664 int opt_arg_pos = opt_element_vector[i].opt_arg_pos;
665 int opt_defs_index = opt_element_vector[i].opt_defs_index;
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000666 if (opt_pos == request.GetCursorIndex()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000667 // We're completing the option itself.
668
669 if (opt_defs_index == OptionArgElement::eBareDash) {
670 // We're completing a bare dash. That means all options are open.
671 // FIXME: We should scan the other options provided and only complete
672 // options
673 // within the option group they belong to.
674 char opt_str[3] = {'-', 'a', '\0'};
675
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000676 for (auto &def : opt_defs) {
677 if (!def.short_option)
678 continue;
679 opt_str[1] = def.short_option;
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +0000680 request.AddCompletion(opt_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000681 }
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000682
Kate Stoneb9c1b512016-09-06 20:57:50 +0000683 return true;
684 } else if (opt_defs_index == OptionArgElement::eBareDoubleDash) {
685 std::string full_name("--");
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000686 for (auto &def : opt_defs) {
687 if (!def.short_option)
688 continue;
689
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690 full_name.erase(full_name.begin() + 2, full_name.end());
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000691 full_name.append(def.long_option);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +0000692 request.AddCompletion(full_name.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 }
694 return true;
695 } else if (opt_defs_index != OptionArgElement::eUnrecognizedArg) {
Adrian Prantl05097242018-04-30 16:49:04 +0000696 // We recognized it, if it an incomplete long option, complete it
697 // anyway (getopt_long_only is happy with shortest unique string, but
698 // it's still a nice thing to do.) Otherwise return The string so the
699 // upper level code will know this is a full match and add the " ".
Kate Stoneb9c1b512016-09-06 20:57:50 +0000700 if (cur_opt_str && strlen(cur_opt_str) > 2 && cur_opt_str[0] == '-' &&
701 cur_opt_str[1] == '-' &&
702 strcmp(opt_defs[opt_defs_index].long_option, cur_opt_str) != 0) {
703 std::string full_name("--");
704 full_name.append(opt_defs[opt_defs_index].long_option);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +0000705 request.AddCompletion(full_name.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706 return true;
707 } else {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +0000708 request.AddCompletion(request.GetCursorArgument());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 return true;
710 }
711 } else {
712 // FIXME - not handling wrong options yet:
713 // Check to see if they are writing a long option & complete it.
714 // I think we will only get in here if the long option table has two
715 // elements
Adrian Prantl05097242018-04-30 16:49:04 +0000716 // that are not unique up to this point. getopt_long_only does
717 // shortest unique match for long options already.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718
719 if (cur_opt_str && strlen(cur_opt_str) > 2 && cur_opt_str[0] == '-' &&
720 cur_opt_str[1] == '-') {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000721 for (auto &def : opt_defs) {
722 if (!def.long_option)
723 continue;
724
725 if (strstr(def.long_option, cur_opt_str + 2) == def.long_option) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000726 std::string full_name("--");
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000727 full_name.append(def.long_option);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +0000728 request.AddCompletion(full_name.c_str());
Jim Inghamd6ccc602010-06-24 20:30:15 +0000729 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732 return true;
733 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000734
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000735 } else if (opt_arg_pos == request.GetCursorIndex()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000736 // Okay the cursor is on the completion of an argument. See if it has a
737 // completion, otherwise return no matches.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000739 CompletionRequest subrequest = request;
740 subrequest.SetCursorCharPosition(subrequest.GetCursorArgument().size());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 if (opt_defs_index != -1) {
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000742 HandleOptionArgumentCompletion(subrequest, opt_element_vector, i,
743 interpreter);
744 request.SetWordComplete(subrequest.GetWordComplete());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745 return true;
746 } else {
747 // No completion callback means no completions...
748 return true;
749 }
750
751 } else {
752 // Not the last element, keep going.
753 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000754 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755 }
756 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000757}
758
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759bool Options::HandleOptionArgumentCompletion(
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000760 CompletionRequest &request, OptionElementVector &opt_element_vector,
761 int opt_element_index, CommandInterpreter &interpreter) {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000762 auto opt_defs = GetDefinitions();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000763 std::unique_ptr<SearchFilter> filter_up;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000764
Kate Stoneb9c1b512016-09-06 20:57:50 +0000765 int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos;
766 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
767
768 // See if this is an enumeration type option, and if so complete it here:
769
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000770 const auto &enum_values = opt_defs[opt_defs_index].enum_values;
771 if (!enum_values.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 bool return_value = false;
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000773 std::string match_string(
774 request.GetParsedLine().GetArgumentAtIndex(opt_arg_pos),
775 request.GetParsedLine().GetArgumentAtIndex(opt_arg_pos) +
776 request.GetCursorCharPosition());
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000777
778 for (const auto &enum_value : enum_values) {
779 if (strstr(enum_value.string_value, match_string.c_str()) ==
780 enum_value.string_value) {
781 request.AddCompletion(enum_value.string_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000782 return_value = true;
783 }
784 }
785 return return_value;
786 }
787
Adrian Prantl05097242018-04-30 16:49:04 +0000788 // If this is a source file or symbol type completion, and there is a -shlib
789 // option somewhere in the supplied arguments, then make a search filter for
790 // that shared library.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 // FIXME: Do we want to also have an "OptionType" so we don't have to match
792 // string names?
793
794 uint32_t completion_mask = opt_defs[opt_defs_index].completion_type;
795
796 if (completion_mask == 0) {
797 lldb::CommandArgumentType option_arg_type =
798 opt_defs[opt_defs_index].argument_type;
799 if (option_arg_type != eArgTypeNone) {
800 const CommandObject::ArgumentTableEntry *arg_entry =
801 CommandObject::FindArgumentDataByType(
802 opt_defs[opt_defs_index].argument_type);
803 if (arg_entry)
804 completion_mask = arg_entry->completion_type;
805 }
806 }
807
808 if (completion_mask & CommandCompletions::eSourceFileCompletion ||
809 completion_mask & CommandCompletions::eSymbolCompletion) {
810 for (size_t i = 0; i < opt_element_vector.size(); i++) {
811 int cur_defs_index = opt_element_vector[i].opt_defs_index;
812
813 // trying to use <0 indices will definitely cause problems
814 if (cur_defs_index == OptionArgElement::eUnrecognizedArg ||
815 cur_defs_index == OptionArgElement::eBareDash ||
816 cur_defs_index == OptionArgElement::eBareDoubleDash)
817 continue;
818
819 int cur_arg_pos = opt_element_vector[i].opt_arg_pos;
820 const char *cur_opt_name = opt_defs[cur_defs_index].long_option;
821
822 // If this is the "shlib" option and there was an argument provided,
823 // restrict it to that shared library.
824 if (cur_opt_name && strcmp(cur_opt_name, "shlib") == 0 &&
825 cur_arg_pos != -1) {
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000826 const char *module_name =
827 request.GetParsedLine().GetArgumentAtIndex(cur_arg_pos);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 if (module_name) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000829 FileSpec module_spec(module_name);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 lldb::TargetSP target_sp =
831 interpreter.GetDebugger().GetSelectedTarget();
832 // Search filters require a target...
833 if (target_sp)
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000834 filter_up.reset(new SearchFilterByModule(target_sp, module_spec));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836 break;
837 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 return CommandCompletions::InvokeCommonCompletionCallbacks(
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000842 interpreter, completion_mask, request, filter_up.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000843}
Greg Claytonf6b8b582011-04-13 00:18:08 +0000844
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845void OptionGroupOptions::Append(OptionGroup *group) {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000846 auto group_option_defs = group->GetDefinitions();
847 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000848 m_option_infos.push_back(OptionInfo(group, i));
849 m_option_defs.push_back(group_option_defs[i]);
850 }
Greg Clayton84c39662011-04-27 22:04:39 +0000851}
852
Kate Stoneb9c1b512016-09-06 20:57:50 +0000853const OptionGroup *OptionGroupOptions::GetGroupWithOption(char short_opt) {
854 for (uint32_t i = 0; i < m_option_defs.size(); i++) {
855 OptionDefinition opt_def = m_option_defs[i];
856 if (opt_def.short_option == short_opt)
857 return m_option_infos[i].option_group;
858 }
859 return nullptr;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000860}
861
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862void OptionGroupOptions::Append(OptionGroup *group, uint32_t src_mask,
863 uint32_t dst_mask) {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000864 auto group_option_defs = group->GetDefinitions();
865 for (uint32_t i = 0; i < group_option_defs.size(); ++i) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 if (group_option_defs[i].usage_mask & src_mask) {
867 m_option_infos.push_back(OptionInfo(group, i));
868 m_option_defs.push_back(group_option_defs[i]);
869 m_option_defs.back().usage_mask = dst_mask;
Greg Claytonf6b8b582011-04-13 00:18:08 +0000870 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 }
Greg Claytonf6b8b582011-04-13 00:18:08 +0000872}
873
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874void OptionGroupOptions::Finalize() {
875 m_did_finalize = true;
Greg Claytonf6b8b582011-04-13 00:18:08 +0000876}
877
Zachary Turner97206d52017-05-12 04:51:55 +0000878Status OptionGroupOptions::SetOptionValue(uint32_t option_idx,
879 llvm::StringRef option_value,
880 ExecutionContext *execution_context) {
Adrian Prantl05097242018-04-30 16:49:04 +0000881 // After calling OptionGroupOptions::Append(...), you must finalize the
882 // groups by calling OptionGroupOptions::Finlize()
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883 assert(m_did_finalize);
Zachary Turner97206d52017-05-12 04:51:55 +0000884 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 if (option_idx < m_option_infos.size()) {
886 error = m_option_infos[option_idx].option_group->SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000887 m_option_infos[option_idx].option_index, option_value,
888 execution_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889
890 } else {
891 error.SetErrorString("invalid option index"); // Shouldn't happen...
892 }
893 return error;
Greg Claytonf6b8b582011-04-13 00:18:08 +0000894}
895
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896void OptionGroupOptions::OptionParsingStarting(
897 ExecutionContext *execution_context) {
898 std::set<OptionGroup *> group_set;
899 OptionInfos::iterator pos, end = m_option_infos.end();
900 for (pos = m_option_infos.begin(); pos != end; ++pos) {
901 OptionGroup *group = pos->option_group;
902 if (group_set.find(group) == group_set.end()) {
903 group->OptionParsingStarting(execution_context);
904 group_set.insert(group);
Greg Claytonab65b342011-04-13 22:47:15 +0000905 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 }
Greg Claytonf6b8b582011-04-13 00:18:08 +0000907}
Zachary Turner97206d52017-05-12 04:51:55 +0000908Status
909OptionGroupOptions::OptionParsingFinished(ExecutionContext *execution_context) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 std::set<OptionGroup *> group_set;
Zachary Turner97206d52017-05-12 04:51:55 +0000911 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 OptionInfos::iterator pos, end = m_option_infos.end();
913 for (pos = m_option_infos.begin(); pos != end; ++pos) {
914 OptionGroup *group = pos->option_group;
915 if (group_set.find(group) == group_set.end()) {
916 error = group->OptionParsingFinished(execution_context);
917 group_set.insert(group);
918 if (error.Fail())
919 return error;
Greg Claytonf6b8b582011-04-13 00:18:08 +0000920 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000921 }
922 return error;
Greg Claytonf6b8b582011-04-13 00:18:08 +0000923}
Pavel Labath5f56fca2018-03-09 10:39:40 +0000924
925// OptionParser permutes the arguments while processing them, so we create a
926// temporary array holding to avoid modification of the input arguments. The
927// options themselves are never modified, but the API expects a char * anyway,
928// hence the const_cast.
929static std::vector<char *> GetArgvForParsing(const Args &args) {
930 std::vector<char *> result;
931 // OptionParser always skips the first argument as it is based on getopt().
932 result.push_back(const_cast<char *>("<FAKE-ARG0>"));
933 for (const Args::ArgEntry &entry : args)
934 result.push_back(const_cast<char *>(entry.c_str()));
935 return result;
936}
937
938// Given a permuted argument, find it's position in the original Args vector.
939static Args::const_iterator FindOriginalIter(const char *arg,
940 const Args &original) {
941 return llvm::find_if(
942 original, [arg](const Args::ArgEntry &D) { return D.c_str() == arg; });
943}
944
945// Given a permuted argument, find it's index in the original Args vector.
946static size_t FindOriginalIndex(const char *arg, const Args &original) {
947 return std::distance(original.begin(), FindOriginalIter(arg, original));
948}
949
950// Construct a new Args object, consisting of the entries from the original
951// arguments, but in the permuted order.
952static Args ReconstituteArgsAfterParsing(llvm::ArrayRef<char *> parsed,
953 const Args &original) {
954 Args result;
955 for (const char *arg : parsed) {
956 auto pos = FindOriginalIter(arg, original);
957 assert(pos != original.end());
958 result.AppendArgument(pos->ref, pos->quote);
959 }
960 return result;
961}
962
963static size_t FindArgumentIndexForOption(const Args &args,
964 const Option &long_option) {
965 std::string short_opt = llvm::formatv("-{0}", char(long_option.val)).str();
966 std::string long_opt =
967 llvm::formatv("--{0}", long_option.definition->long_option);
968 for (const auto &entry : llvm::enumerate(args)) {
969 if (entry.value().ref.startswith(short_opt) ||
970 entry.value().ref.startswith(long_opt))
971 return entry.index();
972 }
973
974 return size_t(-1);
975}
976
977llvm::Expected<Args> Options::ParseAlias(const Args &args,
978 OptionArgVector *option_arg_vector,
979 std::string &input_line) {
980 StreamString sstr;
981 int i;
982 Option *long_options = GetLongOptions();
983
984 if (long_options == nullptr) {
985 return llvm::make_error<llvm::StringError>("Invalid long options",
986 llvm::inconvertibleErrorCode());
987 }
988
989 for (i = 0; long_options[i].definition != nullptr; ++i) {
990 if (long_options[i].flag == nullptr) {
991 sstr << (char)long_options[i].val;
992 switch (long_options[i].definition->option_has_arg) {
993 default:
994 case OptionParser::eNoArgument:
995 break;
996 case OptionParser::eRequiredArgument:
997 sstr << ":";
998 break;
999 case OptionParser::eOptionalArgument:
1000 sstr << "::";
1001 break;
1002 }
1003 }
1004 }
1005
1006 Args args_copy = args;
1007 std::vector<char *> argv = GetArgvForParsing(args);
1008
1009 std::unique_lock<std::mutex> lock;
1010 OptionParser::Prepare(lock);
1011 int val;
1012 while (1) {
1013 int long_options_index = -1;
1014 val = OptionParser::Parse(argv.size(), &*argv.begin(), sstr.GetString(),
1015 long_options, &long_options_index);
1016
1017 if (val == -1)
1018 break;
1019
1020 if (val == '?') {
1021 return llvm::make_error<llvm::StringError>(
1022 "Unknown or ambiguous option", llvm::inconvertibleErrorCode());
1023 }
1024
1025 if (val == 0)
1026 continue;
1027
1028 OptionSeen(val);
1029
1030 // Look up the long option index
1031 if (long_options_index == -1) {
1032 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1033 long_options[j].val;
1034 ++j) {
1035 if (long_options[j].val == val) {
1036 long_options_index = j;
1037 break;
1038 }
1039 }
1040 }
1041
1042 // See if the option takes an argument, and see if one was supplied.
1043 if (long_options_index == -1) {
1044 return llvm::make_error<llvm::StringError>(
1045 llvm::formatv("Invalid option with value '{0}'.", char(val)).str(),
1046 llvm::inconvertibleErrorCode());
1047 }
1048
1049 StreamString option_str;
1050 option_str.Printf("-%c", val);
1051 const OptionDefinition *def = long_options[long_options_index].definition;
1052 int has_arg =
1053 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1054
1055 const char *option_arg = nullptr;
1056 switch (has_arg) {
1057 case OptionParser::eRequiredArgument:
1058 if (OptionParser::GetOptionArgument() == nullptr) {
1059 return llvm::make_error<llvm::StringError>(
1060 llvm::formatv("Option '{0}' is missing argument specifier.",
1061 option_str.GetString())
1062 .str(),
1063 llvm::inconvertibleErrorCode());
1064 }
1065 LLVM_FALLTHROUGH;
1066 case OptionParser::eOptionalArgument:
1067 option_arg = OptionParser::GetOptionArgument();
1068 LLVM_FALLTHROUGH;
1069 case OptionParser::eNoArgument:
1070 break;
1071 default:
1072 return llvm::make_error<llvm::StringError>(
1073 llvm::formatv("error with options table; invalid value in has_arg "
1074 "field for option '{0}'.",
1075 char(val))
1076 .str(),
1077 llvm::inconvertibleErrorCode());
1078 }
1079 if (!option_arg)
1080 option_arg = "<no-argument>";
1081 option_arg_vector->emplace_back(option_str.GetString(), has_arg,
1082 option_arg);
1083
Adrian Prantl05097242018-04-30 16:49:04 +00001084 // Find option in the argument list; also see if it was supposed to take an
1085 // argument and if one was supplied. Remove option (and argument, if
Pavel Labath5f56fca2018-03-09 10:39:40 +00001086 // given) from the argument list. Also remove them from the
1087 // raw_input_string, if one was passed in.
1088 size_t idx =
1089 FindArgumentIndexForOption(args_copy, long_options[long_options_index]);
1090 if (idx == size_t(-1))
1091 continue;
1092
1093 if (!input_line.empty()) {
1094 auto tmp_arg = args_copy[idx].ref;
1095 size_t pos = input_line.find(tmp_arg);
1096 if (pos != std::string::npos)
1097 input_line.erase(pos, tmp_arg.size());
1098 }
1099 args_copy.DeleteArgumentAtIndex(idx);
1100 if ((long_options[long_options_index].definition->option_has_arg !=
1101 OptionParser::eNoArgument) &&
1102 (OptionParser::GetOptionArgument() != nullptr) &&
1103 (idx < args_copy.GetArgumentCount()) &&
1104 (args_copy[idx].ref == OptionParser::GetOptionArgument())) {
1105 if (input_line.size() > 0) {
1106 auto tmp_arg = args_copy[idx].ref;
1107 size_t pos = input_line.find(tmp_arg);
1108 if (pos != std::string::npos)
1109 input_line.erase(pos, tmp_arg.size());
1110 }
1111 args_copy.DeleteArgumentAtIndex(idx);
1112 }
1113 }
1114
1115 return std::move(args_copy);
1116}
1117
1118OptionElementVector Options::ParseForCompletion(const Args &args,
1119 uint32_t cursor_index) {
1120 OptionElementVector option_element_vector;
1121 StreamString sstr;
1122 Option *long_options = GetLongOptions();
1123 option_element_vector.clear();
1124
1125 if (long_options == nullptr)
1126 return option_element_vector;
1127
Adrian Prantl05097242018-04-30 16:49:04 +00001128 // Leading : tells getopt to return a : for a missing option argument AND to
1129 // suppress error messages.
Pavel Labath5f56fca2018-03-09 10:39:40 +00001130
1131 sstr << ":";
1132 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1133 if (long_options[i].flag == nullptr) {
1134 sstr << (char)long_options[i].val;
1135 switch (long_options[i].definition->option_has_arg) {
1136 default:
1137 case OptionParser::eNoArgument:
1138 break;
1139 case OptionParser::eRequiredArgument:
1140 sstr << ":";
1141 break;
1142 case OptionParser::eOptionalArgument:
1143 sstr << "::";
1144 break;
1145 }
1146 }
1147 }
1148
1149 std::unique_lock<std::mutex> lock;
1150 OptionParser::Prepare(lock);
1151 OptionParser::EnableError(false);
1152
1153 int val;
1154 auto opt_defs = GetDefinitions();
1155
1156 std::vector<char *> dummy_vec = GetArgvForParsing(args);
1157
1158 // I stick an element on the end of the input, because if the last element
1159 // is option that requires an argument, getopt_long_only will freak out.
1160 dummy_vec.push_back(const_cast<char *>("<FAKE-VALUE>"));
1161
1162 bool failed_once = false;
1163 uint32_t dash_dash_pos = -1;
1164
1165 while (1) {
1166 bool missing_argument = false;
1167 int long_options_index = -1;
1168
1169 val = OptionParser::Parse(dummy_vec.size(), &dummy_vec[0], sstr.GetString(),
1170 long_options, &long_options_index);
1171
1172 if (val == -1) {
1173 // When we're completing a "--" which is the last option on line,
1174 if (failed_once)
1175 break;
1176
1177 failed_once = true;
1178
1179 // If this is a bare "--" we mark it as such so we can complete it
1180 // successfully later. Handling the "--" is a little tricky, since that
1181 // may mean end of options or arguments, or the user might want to
1182 // complete options by long name. I make this work by checking whether
1183 // the cursor is in the "--" argument, and if so I assume we're
1184 // completing the long option, otherwise I let it pass to
1185 // OptionParser::Parse which will terminate the option parsing. Note, in
1186 // either case we continue parsing the line so we can figure out what
1187 // other options were passed. This will be useful when we come to
1188 // restricting completions based on what other options we've seen on the
1189 // line.
1190
1191 if (static_cast<size_t>(OptionParser::GetOptionIndex()) <
1192 dummy_vec.size() &&
1193 (strcmp(dummy_vec[OptionParser::GetOptionIndex() - 1], "--") == 0)) {
1194 dash_dash_pos = FindOriginalIndex(
1195 dummy_vec[OptionParser::GetOptionIndex() - 1], args);
1196 if (dash_dash_pos == cursor_index) {
1197 option_element_vector.push_back(
1198 OptionArgElement(OptionArgElement::eBareDoubleDash, dash_dash_pos,
1199 OptionArgElement::eBareDoubleDash));
1200 continue;
1201 } else
1202 break;
1203 } else
1204 break;
1205 } else if (val == '?') {
1206 option_element_vector.push_back(OptionArgElement(
1207 OptionArgElement::eUnrecognizedArg,
1208 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1209 args),
1210 OptionArgElement::eUnrecognizedArg));
1211 continue;
1212 } else if (val == 0) {
1213 continue;
1214 } else if (val == ':') {
1215 // This is a missing argument.
1216 val = OptionParser::GetOptionErrorCause();
1217 missing_argument = true;
1218 }
1219
1220 OptionSeen(val);
1221
1222 // Look up the long option index
1223 if (long_options_index == -1) {
1224 for (int j = 0; long_options[j].definition || long_options[j].flag ||
1225 long_options[j].val;
1226 ++j) {
1227 if (long_options[j].val == val) {
1228 long_options_index = j;
1229 break;
1230 }
1231 }
1232 }
1233
1234 // See if the option takes an argument, and see if one was supplied.
1235 if (long_options_index >= 0) {
1236 int opt_defs_index = -1;
1237 for (size_t i = 0; i < opt_defs.size(); i++) {
1238 if (opt_defs[i].short_option != val)
1239 continue;
1240 opt_defs_index = i;
1241 break;
1242 }
1243
1244 const OptionDefinition *def = long_options[long_options_index].definition;
1245 int has_arg =
1246 (def == nullptr) ? OptionParser::eNoArgument : def->option_has_arg;
1247 switch (has_arg) {
1248 case OptionParser::eNoArgument:
1249 option_element_vector.push_back(OptionArgElement(
1250 opt_defs_index,
1251 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1252 args),
1253 0));
1254 break;
1255 case OptionParser::eRequiredArgument:
1256 if (OptionParser::GetOptionArgument() != nullptr) {
1257 int arg_index;
1258 if (missing_argument)
1259 arg_index = -1;
1260 else
1261 arg_index = OptionParser::GetOptionIndex() - 2;
1262
1263 option_element_vector.push_back(OptionArgElement(
1264 opt_defs_index,
1265 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1266 args),
1267 arg_index));
1268 } else {
1269 option_element_vector.push_back(OptionArgElement(
1270 opt_defs_index,
1271 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1272 args),
1273 -1));
1274 }
1275 break;
1276 case OptionParser::eOptionalArgument:
1277 if (OptionParser::GetOptionArgument() != nullptr) {
1278 option_element_vector.push_back(OptionArgElement(
1279 opt_defs_index,
1280 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1281 args),
1282 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1283 args)));
1284 } else {
1285 option_element_vector.push_back(OptionArgElement(
1286 opt_defs_index,
1287 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 2],
1288 args),
1289 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1290 args)));
1291 }
1292 break;
1293 default:
1294 // The options table is messed up. Here we'll just continue
1295 option_element_vector.push_back(OptionArgElement(
1296 OptionArgElement::eUnrecognizedArg,
1297 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1298 args),
1299 OptionArgElement::eUnrecognizedArg));
1300 break;
1301 }
1302 } else {
1303 option_element_vector.push_back(OptionArgElement(
1304 OptionArgElement::eUnrecognizedArg,
1305 FindOriginalIndex(dummy_vec[OptionParser::GetOptionIndex() - 1],
1306 args),
1307 OptionArgElement::eUnrecognizedArg));
1308 }
1309 }
1310
1311 // Finally we have to handle the case where the cursor index points at a
Adrian Prantl05097242018-04-30 16:49:04 +00001312 // single "-". We want to mark that in the option_element_vector, but only
1313 // if it is not after the "--". But it turns out that OptionParser::Parse
1314 // just ignores an isolated "-". So we have to look it up by hand here. We
1315 // only care if it is AT the cursor position. Note, a single quoted dash is
1316 // not the same as a single dash...
Pavel Labath5f56fca2018-03-09 10:39:40 +00001317
1318 const Args::ArgEntry &cursor = args[cursor_index];
1319 if ((static_cast<int32_t>(dash_dash_pos) == -1 ||
1320 cursor_index < dash_dash_pos) &&
Raphael Isemann3a0e1272018-07-10 20:17:38 +00001321 !cursor.IsQuoted() && cursor.ref == "-") {
Pavel Labath5f56fca2018-03-09 10:39:40 +00001322 option_element_vector.push_back(
1323 OptionArgElement(OptionArgElement::eBareDash, cursor_index,
1324 OptionArgElement::eBareDash));
1325 }
1326 return option_element_vector;
1327}
1328
1329llvm::Expected<Args> Options::Parse(const Args &args,
1330 ExecutionContext *execution_context,
1331 lldb::PlatformSP platform_sp,
1332 bool require_validation) {
1333 StreamString sstr;
1334 Status error;
1335 Option *long_options = GetLongOptions();
1336 if (long_options == nullptr) {
1337 return llvm::make_error<llvm::StringError>("Invalid long options.",
1338 llvm::inconvertibleErrorCode());
1339 }
1340
1341 for (int i = 0; long_options[i].definition != nullptr; ++i) {
1342 if (long_options[i].flag == nullptr) {
1343 if (isprint8(long_options[i].val)) {
1344 sstr << (char)long_options[i].val;
1345 switch (long_options[i].definition->option_has_arg) {
1346 default:
1347 case OptionParser::eNoArgument:
1348 break;
1349 case OptionParser::eRequiredArgument:
1350 sstr << ':';
1351 break;
1352 case OptionParser::eOptionalArgument:
1353 sstr << "::";
1354 break;
1355 }
1356 }
1357 }
1358 }
1359 std::vector<char *> argv = GetArgvForParsing(args);
1360 std::unique_lock<std::mutex> lock;
1361 OptionParser::Prepare(lock);
1362 int val;
1363 while (1) {
1364 int long_options_index = -1;
1365 val = OptionParser::Parse(argv.size(), &*argv.begin(), sstr.GetString(),
1366 long_options, &long_options_index);
1367 if (val == -1)
1368 break;
1369
1370 // Did we get an error?
1371 if (val == '?') {
1372 error.SetErrorStringWithFormat("unknown or ambiguous option");
1373 break;
1374 }
1375 // The option auto-set itself
1376 if (val == 0)
1377 continue;
1378
1379 OptionSeen(val);
1380
1381 // Lookup the long option index
1382 if (long_options_index == -1) {
1383 for (int i = 0; long_options[i].definition || long_options[i].flag ||
1384 long_options[i].val;
1385 ++i) {
1386 if (long_options[i].val == val) {
1387 long_options_index = i;
1388 break;
1389 }
1390 }
1391 }
1392 // Call the callback with the option
1393 if (long_options_index >= 0 &&
1394 long_options[long_options_index].definition) {
1395 const OptionDefinition *def = long_options[long_options_index].definition;
1396
1397 if (!platform_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00001398 // User did not pass in an explicit platform. Try to grab from the
1399 // execution context.
Pavel Labath5f56fca2018-03-09 10:39:40 +00001400 TargetSP target_sp =
1401 execution_context ? execution_context->GetTargetSP() : TargetSP();
1402 platform_sp = target_sp ? target_sp->GetPlatform() : PlatformSP();
1403 }
1404 OptionValidator *validator = def->validator;
1405
1406 if (!platform_sp && require_validation) {
Adrian Prantl05097242018-04-30 16:49:04 +00001407 // Caller requires validation but we cannot validate as we don't have
1408 // the mandatory platform against which to validate.
Pavel Labath5f56fca2018-03-09 10:39:40 +00001409 return llvm::make_error<llvm::StringError>(
1410 "cannot validate options: no platform available",
1411 llvm::inconvertibleErrorCode());
1412 }
1413
1414 bool validation_failed = false;
1415 if (platform_sp) {
1416 // Ensure we have an execution context, empty or not.
1417 ExecutionContext dummy_context;
1418 ExecutionContext *exe_ctx_p =
1419 execution_context ? execution_context : &dummy_context;
1420 if (validator && !validator->IsValid(*platform_sp, *exe_ctx_p)) {
1421 validation_failed = true;
1422 error.SetErrorStringWithFormat("Option \"%s\" invalid. %s",
1423 def->long_option,
1424 def->validator->LongConditionString());
1425 }
1426 }
1427
1428 // As long as validation didn't fail, we set the option value.
1429 if (!validation_failed)
1430 error =
1431 SetOptionValue(long_options_index,
1432 (def->option_has_arg == OptionParser::eNoArgument)
1433 ? nullptr
1434 : OptionParser::GetOptionArgument(),
1435 execution_context);
1436 } else {
1437 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
1438 }
Pavel Labath5f56fca2018-03-09 10:39:40 +00001439 }
1440
Tatyana Krasnukhaf388d172019-02-26 14:50:40 +00001441 if (error.Fail())
1442 return error.ToError();
1443
Pavel Labath5f56fca2018-03-09 10:39:40 +00001444 argv.erase(argv.begin(), argv.begin() + OptionParser::GetOptionIndex());
1445 return ReconstituteArgsAfterParsing(argv, args);
1446}