LLDB mainline
CommandObject.cpp
Go to the documentation of this file.
1//===-- CommandObject.cpp -------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include <map>
12#include <sstream>
13#include <string>
14
15#include <cctype>
16#include <cstdlib>
17
18#include "lldb/Core/Address.h"
22#include "llvm/ADT/ScopeExit.h"
23
24// These are for the Sourcename completers.
25// FIXME: Make a separate file for the completers.
27#include "lldb/Target/Process.h"
28#include "lldb/Target/Target.h"
31
33
36
37using namespace lldb;
38using namespace lldb_private;
39
40// CommandObject
41
43 llvm::StringRef name, llvm::StringRef help,
44 llvm::StringRef syntax, uint32_t flags)
45 : m_interpreter(interpreter), m_cmd_name(std::string(name)),
48 m_cmd_help_short = std::string(help);
49 m_cmd_syntax = std::string(syntax);
50}
51
53
54llvm::StringRef CommandObject::GetHelp() { return m_cmd_help_short; }
55
56llvm::StringRef CommandObject::GetHelpLong() { return m_cmd_help_long; }
57
58llvm::StringRef CommandObject::GetSyntax() {
59 if (!m_cmd_syntax.empty())
60 return m_cmd_syntax;
61
62 StreamString syntax_str;
63 syntax_str.PutCString(GetCommandName());
64
65 if (!IsDashDashCommand() && GetOptions() != nullptr)
66 syntax_str.PutCString(" <cmd-options>");
67
68 if (!m_arguments.empty()) {
69 syntax_str.PutCString(" ");
70
72 GetOptions()->NumCommandOptions())
73 syntax_str.PutCString("-- ");
75 }
76 m_cmd_syntax = std::string(syntax_str.GetString());
77
78 return m_cmd_syntax;
79}
80
81llvm::StringRef CommandObject::GetCommandName() const { return m_cmd_name; }
82
83void CommandObject::SetCommandName(llvm::StringRef name) {
84 m_cmd_name = std::string(name);
85}
86
87void CommandObject::SetHelp(llvm::StringRef str) {
88 m_cmd_help_short = std::string(str);
89}
90
91void CommandObject::SetHelpLong(llvm::StringRef str) {
92 m_cmd_help_long = std::string(str);
93}
94
95void CommandObject::SetSyntax(llvm::StringRef str) {
96 m_cmd_syntax = std::string(str);
97}
98
100 // By default commands don't have options unless this virtual function is
101 // overridden by base classes.
102 return nullptr;
103}
104
106 // See if the subclass has options?
107 Options *options = GetOptions();
108 if (options != nullptr) {
110
112 options->NotifyOptionParsingStarting(&exe_ctx);
113
114 const bool require_validation = true;
115 llvm::Expected<Args> args_or = options->Parse(
116 args, &exe_ctx, GetCommandInterpreter().GetPlatform(true),
117 require_validation);
118
119 if (args_or) {
120 args = std::move(*args_or);
121 error = options->NotifyOptionParsingFinished(&exe_ctx);
122 } else {
123 error = Status::FromError(args_or.takeError());
124 }
125
126 if (error.Fail()) {
127 result.SetError(error.takeError());
129 return false;
130 }
131
132 if (llvm::Error error = options->VerifyOptions()) {
133 result.SetError(std::move(error));
135 return false;
136 }
137
139 return true;
140 }
141 return true;
142}
143
145 // Nothing should be stored in m_exe_ctx between running commands as
146 // m_exe_ctx has shared pointers to the target, process, thread and frame and
147 // we don't want any CommandObject instances to keep any of these objects
148 // around longer than for a single command. Every command should call
149 // CommandObject::Cleanup() after it has completed.
150 //
151 // The dummy target is allowed here because it is always alive, never causes
152 // resource leaks, and can appear when a command (e.g. "command source") is
153 // invoked re-entrantly before the outer Cleanup() has run.
154 assert(!m_exe_ctx.GetTargetPtr() ||
155 m_exe_ctx.GetTargetPtr()->IsDummyTarget());
156 assert(!m_exe_ctx.GetProcessPtr());
157 assert(!m_exe_ctx.GetThreadPtr());
158 assert(!m_exe_ctx.GetFramePtr());
159
160 // Lock down the interpreter's execution context prior to running the command
161 // so we guarantee the selected target, process, thread and frame can't go
162 // away during the execution
163 m_exe_ctx = m_interpreter.GetExecutionContext();
164
165 const uint32_t flags = GetFlags().Get();
166 if (flags & (eCommandRequiresTarget | eCommandRequiresProcess |
167 eCommandRequiresThread | eCommandRequiresFrame |
168 eCommandTryTargetAPILock)) {
169
170 Target *target = m_exe_ctx.GetTargetPtr();
171 if ((flags & eCommandRequiresTarget) &&
172 (!target || target->IsDummyTarget())) {
174 return false;
175 }
176
177 if ((flags & eCommandRequiresProcess) && !m_exe_ctx.HasProcessScope()) {
178 if (!target || target->IsDummyTarget())
180 else
182 return false;
183 }
184
185 if ((flags & eCommandRequiresThread) && !m_exe_ctx.HasThreadScope()) {
186 if (!target || target->IsDummyTarget())
188 else if (!m_exe_ctx.HasProcessScope())
190 else
192 return false;
193 }
194
195 if ((flags & eCommandRequiresFrame) && !m_exe_ctx.HasFrameScope()) {
196 if (!target || target->IsDummyTarget())
198 else if (!m_exe_ctx.HasProcessScope())
200 else if (!m_exe_ctx.HasThreadScope())
202 else
204 return false;
205 }
206
207 if ((flags & eCommandRequiresRegContext) &&
208 (m_exe_ctx.GetRegisterContext() == nullptr)) {
210 return false;
211 }
212
213 if (flags & eCommandTryTargetAPILock) {
214 if (target && !target->IsDummyTarget())
216 std::unique_lock<std::recursive_mutex>(target->GetAPIMutex());
217 }
218 }
219
220 if (GetFlags().AnySet(eCommandProcessMustBeLaunched |
221 eCommandProcessMustBePaused)) {
222 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
223 if (process == nullptr) {
224 // A process that is not running is considered paused.
225 if (GetFlags().Test(eCommandProcessMustBeLaunched)) {
226 result.AppendError("process must exist");
227 return false;
228 }
229 } else {
230 StateType state = process->GetState();
231 switch (state) {
232 case eStateInvalid:
233 case eStateSuspended:
234 case eStateCrashed:
235 case eStateStopped:
236 break;
237
238 case eStateConnected:
239 case eStateAttaching:
240 case eStateLaunching:
241 case eStateDetached:
242 case eStateExited:
243 case eStateUnloaded:
244 if (GetFlags().Test(eCommandProcessMustBeLaunched)) {
245 result.AppendError("process must be launched");
246 return false;
247 }
248 break;
249
250 case eStateRunning:
251 case eStateStepping:
252 if (GetFlags().Test(eCommandProcessMustBePaused)) {
253 result.AppendError("Process is running. Use 'process interrupt' to "
254 "pause execution.");
255 return false;
256 }
257 }
258 }
259 }
260
261 if (GetFlags().Test(eCommandProcessMustBeTraced)) {
262 Target *target = m_exe_ctx.GetTargetPtr();
263 if (target && !target->GetTrace()) {
264 result.AppendError("process is not being traced");
265 return false;
266 }
267 }
268
269 return true;
270}
271
273 m_exe_ctx.Clear();
274 if (m_api_locker.owns_lock())
275 m_api_locker.unlock();
276}
277
279
280 m_exe_ctx = m_interpreter.GetExecutionContext();
281 llvm::scope_exit reset_ctx([this]() { Cleanup(); });
282
283 // Default implementation of WantsCompletion() is !WantsRawCommandString().
284 // Subclasses who want raw command string but desire, for example, argument
285 // completion should override WantsCompletion() to return true, instead.
287 // FIXME: Abstract telling the completion to insert the completion
288 // character.
289 return;
290 } else {
291 // Can we do anything generic with the options?
292 Options *cur_options = GetOptions();
293 OptionElementVector opt_element_vector;
294
295 if (cur_options != nullptr) {
296 opt_element_vector = cur_options->ParseForCompletion(
297 request.GetParsedLine(), request.GetCursorIndex());
298
299 bool handled_by_options = cur_options->HandleOptionCompletion(
300 request, opt_element_vector, GetCommandInterpreter());
301 if (handled_by_options)
302 return;
303 }
304
305 // If we got here, the last word is not an option or an option argument.
306 HandleArgumentCompletion(request, opt_element_vector);
307 }
308}
309
311 CompletionRequest &request, OptionElementVector &opt_element_vector) {
312 size_t num_arg_entries = GetNumArgumentEntries();
313 if (num_arg_entries != 1)
314 return;
315
317 if (!entry_ptr) {
318 assert(entry_ptr && "We said there was one entry, but there wasn't.");
319 return; // Not worth crashing if asserts are off...
320 }
321
322 CommandArgumentEntry &entry = *entry_ptr;
323 // For now, we only handle the simple case of one homogenous argument type.
324 if (entry.size() != 1)
325 return;
326
327 // Look up the completion type, and if it has one, invoke it:
328 const CommandObject::ArgumentTableEntry *arg_entry =
329 FindArgumentDataByType(entry[0].arg_type);
330 const ArgumentRepetitionType repeat = entry[0].arg_repetition;
331
332 if (arg_entry == nullptr || arg_entry->completion_type == lldb::eNoCompletion)
333 return;
334
335 // FIXME: This should be handled higher in the Command Parser.
336 // Check the case where this command only takes one argument, and don't do
337 // the completion if we aren't on the first entry:
338 if (repeat == eArgRepeatPlain && request.GetCursorIndex() != 0)
339 return;
340
342 GetCommandInterpreter(), arg_entry->completion_type, request, nullptr);
343
344}
345
346bool CommandObject::HelpTextContainsWord(llvm::StringRef search_word,
347 bool search_short_help,
348 bool search_long_help,
349 bool search_syntax,
350 bool search_options) {
351 bool found_word = false;
352
353 llvm::StringRef short_help = GetHelp();
354 llvm::StringRef long_help = GetHelpLong();
355 llvm::StringRef syntax_help = GetSyntax();
356
357 if (search_short_help && short_help.contains_insensitive(search_word))
358 found_word = true;
359 else if (search_long_help && long_help.contains_insensitive(search_word))
360 found_word = true;
361 else if (search_syntax && syntax_help.contains_insensitive(search_word))
362 found_word = true;
363
364 if (!found_word && search_options && GetOptions() != nullptr) {
365 StreamString usage_help;
367 usage_help, *this,
368 GetCommandInterpreter().GetDebugger().GetTerminalWidth(),
369 GetCommandInterpreter().GetDebugger().GetUseColor());
370 if (!usage_help.Empty()) {
371 llvm::StringRef usage_text = usage_help.GetString();
372 if (usage_text.contains_insensitive(search_word))
373 found_word = true;
374 }
375 }
376
377 return found_word;
378}
379
381 CommandReturnObject &result,
382 OptionGroupOptions &group_options,
383 ExecutionContext &exe_ctx) {
384 if (!ParseOptions(args, result))
385 return false;
386
387 Status error(group_options.NotifyOptionParsingFinished(&exe_ctx));
388 if (error.Fail()) {
389 result.AppendError(error.AsCString());
390 return false;
391 }
392 return true;
393}
394
396 CommandArgumentType arg_type, ArgumentRepetitionType repetition_type) {
397
398 CommandArgumentEntry arg_entry;
399 CommandArgumentData simple_arg;
400
401 // Define the first (and only) variant of this arg.
402 simple_arg.arg_type = arg_type;
403 simple_arg.arg_repetition = repetition_type;
404
405 // There is only one variant this argument could be; put it into the argument
406 // entry.
407 arg_entry.push_back(simple_arg);
408
409 // Push the data for the first argument into the m_arguments vector.
410 m_arguments.push_back(arg_entry);
411}
412
414
417 if (static_cast<size_t>(idx) < m_arguments.size())
418 return &(m_arguments[idx]);
419
420 return nullptr;
421}
422
425 for (int i = 0; i < eArgTypeLastArg; ++i)
426 if (g_argument_table[i].arg_type == arg_type)
427 return &(g_argument_table[i]);
428
429 return nullptr;
430}
431
433 CommandInterpreter &interpreter) {
434 const ArgumentTableEntry *entry = &(g_argument_table[arg_type]);
435
436 // The table is *supposed* to be kept in arg_type order, but someone *could*
437 // have messed it up...
438
439 if (entry->arg_type != arg_type)
441
442 if (!entry)
443 return;
444
445 StreamString name_str;
446 name_str.Printf("<%s>", entry->arg_name);
447
448 if (entry->help_function) {
449 llvm::StringRef help_text = entry->help_function();
450 if (!entry->help_function.self_formatting) {
451 interpreter.OutputFormattedHelpText(str, name_str.GetString(), "--",
452 help_text, name_str.GetSize());
453 } else {
454 interpreter.OutputHelpText(str, name_str.GetString(), "--", help_text,
455 name_str.GetSize());
456 }
457 } else {
458 interpreter.OutputFormattedHelpText(str, name_str.GetString(), "--",
459 entry->help_text, name_str.GetSize());
460
461 // Print enum values and their description if any.
462 OptionEnumValues enum_values = g_argument_table[arg_type].enum_values;
463 if (!enum_values.empty()) {
464 str.EOL();
465 size_t longest = 0;
466 for (const OptionEnumValueElement &element : enum_values)
467 longest =
468 std::max(longest, llvm::StringRef(element.string_value).size());
469 str.IndentMore(5);
470 for (const OptionEnumValueElement &element : enum_values) {
471 str.Indent();
472 interpreter.OutputHelpText(str, element.string_value, ":",
473 element.usage, longest);
474 }
475 str.IndentLess(5);
476 str.EOL();
477 }
478 }
479}
480
482 const ArgumentTableEntry *entry = &(g_argument_table[arg_type]);
483
484 // The table is *supposed* to be kept in arg_type order, but someone *could*
485 // have messed it up...
486
487 if (entry->arg_type != arg_type)
489
490 if (entry)
491 return entry->arg_name;
492
493 return nullptr;
494}
495
497 return (arg_repeat_type == eArgRepeatPairPlain) ||
498 (arg_repeat_type == eArgRepeatPairOptional) ||
499 (arg_repeat_type == eArgRepeatPairPlus) ||
500 (arg_repeat_type == eArgRepeatPairStar) ||
501 (arg_repeat_type == eArgRepeatPairRange) ||
502 (arg_repeat_type == eArgRepeatPairRangeOptional);
503}
504
505std::optional<ArgumentRepetitionType>
507 return llvm::StringSwitch<ArgumentRepetitionType>(string)
508 .Case("plain", eArgRepeatPlain)
509 .Case("optional", eArgRepeatOptional)
510 .Case("plus", eArgRepeatPlus)
511 .Case("star", eArgRepeatStar)
512 .Case("range", eArgRepeatRange)
513 .Case("pair-plain", eArgRepeatPairPlain)
514 .Case("pair-optional", eArgRepeatPairOptional)
515 .Case("pair-plus", eArgRepeatPairPlus)
516 .Case("pair-star", eArgRepeatPairStar)
517 .Case("pair-range", eArgRepeatPairRange)
518 .Case("pair-range-optional", eArgRepeatPairRangeOptional)
519 .Default({});
520}
521
523OptSetFiltered(uint32_t opt_set_mask,
526 for (unsigned i = 0; i < cmd_arg_entry.size(); ++i)
527 if (opt_set_mask & cmd_arg_entry[i].arg_opt_set_association)
528 ret_val.push_back(cmd_arg_entry[i]);
529 return ret_val;
530}
531
532// Default parameter value of opt_set_mask is LLDB_OPT_SET_ALL, which means
533// take all the argument data into account. On rare cases where some argument
534// sticks with certain option sets, this function returns the option set
535// filtered args.
537 uint32_t opt_set_mask) {
538 int num_args = m_arguments.size();
539 for (int i = 0; i < num_args; ++i) {
540 if (i > 0)
541 str.Printf(" ");
542 CommandArgumentEntry arg_entry =
543 opt_set_mask == LLDB_OPT_SET_ALL
544 ? m_arguments[i]
545 : OptSetFiltered(opt_set_mask, m_arguments[i]);
546 // This argument is not associated with the current option set, so skip it.
547 if (arg_entry.empty())
548 continue;
549 int num_alternatives = arg_entry.size();
550
551 if ((num_alternatives == 2) && IsPairType(arg_entry[0].arg_repetition)) {
552 const char *first_name = GetArgumentName(arg_entry[0].arg_type);
553 const char *second_name = GetArgumentName(arg_entry[1].arg_type);
554 switch (arg_entry[0].arg_repetition) {
556 str.Printf("<%s> <%s>", first_name, second_name);
557 break;
559 str.Printf("[<%s> <%s>]", first_name, second_name);
560 break;
562 str.Printf("<%s> <%s> [<%s> <%s> [...]]", first_name, second_name,
563 first_name, second_name);
564 break;
566 str.Printf("[<%s> <%s> [<%s> <%s> [...]]]", first_name, second_name,
567 first_name, second_name);
568 break;
570 str.Printf("<%s_1> <%s_1> ... <%s_n> <%s_n>", first_name, second_name,
571 first_name, second_name);
572 break;
574 str.Printf("[<%s_1> <%s_1> ... <%s_n> <%s_n>]", first_name, second_name,
575 first_name, second_name);
576 break;
577 // Explicitly test for all the rest of the cases, so if new types get
578 // added we will notice the missing case statement(s).
579 case eArgRepeatPlain:
581 case eArgRepeatPlus:
582 case eArgRepeatStar:
583 case eArgRepeatRange:
584 // These should not be reached, as they should fail the IsPairType test
585 // above.
586 break;
587 }
588 } else {
589 StreamString names;
590 for (int j = 0; j < num_alternatives; ++j) {
591 if (j > 0)
592 names.Printf(" | ");
593 names.Printf("%s", GetArgumentName(arg_entry[j].arg_type));
594 }
595
596 std::string name_str = std::string(names.GetString());
597 switch (arg_entry[0].arg_repetition) {
598 case eArgRepeatPlain:
599 str.Printf("<%s>", name_str.c_str());
600 break;
601 case eArgRepeatPlus:
602 str.Printf("<%s> [<%s> [...]]", name_str.c_str(), name_str.c_str());
603 break;
604 case eArgRepeatStar:
605 str.Printf("[<%s> [<%s> [...]]]", name_str.c_str(), name_str.c_str());
606 break;
608 str.Printf("[<%s>]", name_str.c_str());
609 break;
610 case eArgRepeatRange:
611 str.Printf("<%s_1> .. <%s_n>", name_str.c_str(), name_str.c_str());
612 break;
613 // Explicitly test for all the rest of the cases, so if new types get
614 // added we will notice the missing case statement(s).
621 // These should not be hit, as they should pass the IsPairType test
622 // above, and control should have gone into the other branch of the if
623 // statement.
624 break;
625 }
626 }
627 }
628}
629
631CommandObject::LookupArgumentName(llvm::StringRef arg_name) {
633
634 arg_name = arg_name.ltrim('<').rtrim('>');
635
636 for (int i = 0; i < eArgTypeLastArg; ++i)
637 if (arg_name == g_argument_table[i].arg_name)
638 return_type = g_argument_table[i].arg_type;
639
640 return return_type;
641}
642
644 llvm::StringRef long_help) {
646 std::stringstream lineStream{std::string(long_help)};
647 std::string line;
648 while (std::getline(lineStream, line)) {
649 if (line.empty()) {
650 output_strm << "\n";
651 continue;
652 }
653 size_t result = line.find_first_not_of(" \t");
654 if (result == std::string::npos) {
655 result = 0;
656 }
657 std::string whitespace_prefix = line.substr(0, result);
658 std::string remainder = line.substr(result);
659 interpreter.OutputFormattedHelpText(output_strm, whitespace_prefix,
660 remainder);
661 }
662}
663
669
672 std::string help_text(GetHelp());
673 if (WantsRawCommandString()) {
674 help_text.append(" Expects 'raw' input (see 'help raw-input'.)");
675 }
676 interpreter.OutputFormattedHelpText(output_strm, "", help_text);
677 output_strm << "\nSyntax: " << GetSyntax() << "\n";
678 Options *options = GetOptions();
679 if (options != nullptr) {
680 options->GenerateOptionUsage(
681 output_strm, *this,
682 GetCommandInterpreter().GetDebugger().GetTerminalWidth(),
683 GetCommandInterpreter().GetDebugger().GetUseColor());
684 }
685 llvm::StringRef long_help = GetHelpLong();
686 if (!long_help.empty()) {
687 FormatLongHelpText(output_strm, long_help);
688 }
689 if (!IsDashDashCommand() && options && options->NumCommandOptions() > 0) {
691 // Emit the message about using ' -- ' between the end of the command
692 // options and the raw input conditionally, i.e., only if the command
693 // object does not want completion.
694 interpreter.OutputFormattedHelpText(
695 output_strm, "", "",
696 "\nImportant Note: Because this command takes 'raw' input, if you "
697 "use any command options"
698 " you must use ' -- ' between the end of the command options and the "
699 "beginning of the raw input.",
700 1);
701 } else if (GetNumArgumentEntries() > 0) {
702 // Also emit a warning about using "--" in case you are using a command
703 // that takes options and arguments.
704 interpreter.OutputFormattedHelpText(
705 output_strm, "", "",
706 "\nThis command takes options and free-form arguments. If your "
707 "arguments resemble"
708 " option specifiers (i.e., they start with a - or --), you must use "
709 "' -- ' between"
710 " the end of the command options and the beginning of the arguments.",
711 1);
712 }
713 }
714}
715
718 CommandArgumentData id_arg;
719 CommandArgumentData id_range_arg;
720
721 // Create the first variant for the first (and only) argument for this
722 // command.
723 switch (type) {
724 case eBreakpointArgs:
726 id_range_arg.arg_type = eArgTypeBreakpointIDRange;
727 break;
728 case eWatchpointArgs:
730 id_range_arg.arg_type = eArgTypeWatchpointIDRange;
731 break;
732 }
734 id_range_arg.arg_repetition = eArgRepeatOptional;
735
736 // The first (and only) argument for this command could be either an id or an
737 // id_range. Push both variants into the entry for the first argument for
738 // this command.
739 arg.push_back(id_arg);
740 arg.push_back(id_range_arg);
741 m_arguments.push_back(arg);
742}
743
745 const lldb::CommandArgumentType arg_type) {
746 assert(arg_type < eArgTypeLastArg &&
747 "Invalid argument type passed to GetArgumentTypeAsCString");
748 return g_argument_table[arg_type].arg_name;
749}
750
752 const lldb::CommandArgumentType arg_type) {
753 assert(arg_type < eArgTypeLastArg &&
754 "Invalid argument type passed to GetArgumentDescriptionAsCString");
755 return g_argument_table[arg_type].help_text;
756}
757
759 return m_interpreter.GetDebugger().GetDummyTarget();
760}
761
763 // Prefer the frozen execution context in the command object.
764 if (Target *target = m_exe_ctx.GetTargetPtr())
765 return *target;
766
767 // Fallback to the command interpreter's execution context in case we get
768 // called after DoExecute has finished. For example, when doing multi-line
769 // expression that uses an input reader or breakpoint callbacks.
770 return m_interpreter.GetExecutionContext().GetTargetRef();
771}
772
774 Thread *thread_to_use = m_exe_ctx.GetThreadPtr();
775 if (thread_to_use)
776 return thread_to_use;
777
778 Process *process = m_exe_ctx.GetProcessPtr();
779 if (!process) {
780 Target *target = m_exe_ctx.GetTargetPtr();
781 if (!target) {
782 target = m_interpreter.GetDebugger().GetSelectedTarget().get();
783 }
784 if (target)
785 process = target->GetProcessSP().get();
786 }
787
788 if (process)
789 return process->GetThreadList().GetSelectedThread().get();
790 else
791 return nullptr;
792}
793
794void CommandObjectParsed::Execute(const char *args_string,
795 CommandReturnObject &result) {
796 bool handled = false;
797 Args cmd_args(args_string);
798 if (HasOverrideCallback()) {
799 Args full_args(GetCommandName());
800 full_args.AppendArguments(cmd_args);
801 handled =
803 }
804 if (!handled) {
805 for (auto entry : llvm::enumerate(cmd_args.entries())) {
806 const Args::ArgEntry &value = entry.value();
807 if (!value.ref().empty() && value.GetQuoteChar() == '`') {
808 // We have to put the backtick back in place for PreprocessCommand.
809 std::string opt_string = value.c_str();
811 error = m_interpreter.PreprocessToken(opt_string);
812 if (error.Success())
813 cmd_args.ReplaceArgumentAtIndex(entry.index(), opt_string);
814 }
815 }
816
817 if (CheckRequirements(result)) {
818 if (ParseOptions(cmd_args, result)) {
819 // Call the command-specific version of 'Execute', passing it the
820 // already processed arguments.
821 if (cmd_args.GetArgumentCount() != 0 && m_arguments.empty()) {
822 result.AppendErrorWithFormatv("'{0}' doesn't take any arguments.",
824 Cleanup();
825 return;
826 }
827 m_interpreter.IncreaseCommandUsage(*this);
828 DoExecute(cmd_args, result);
829 }
830 }
831
832 Cleanup();
833 }
834}
835
836void CommandObjectRaw::Execute(const char *args_string,
837 CommandReturnObject &result) {
838 bool handled = false;
839 if (HasOverrideCallback()) {
840 std::string full_command(GetCommandName());
841 full_command += ' ';
842 full_command += args_string;
843 const char *argv[2] = {nullptr, nullptr};
844 argv[0] = full_command.c_str();
845 handled = InvokeOverrideCallback(argv, result);
846 }
847 if (!handled) {
848 if (CheckRequirements(result))
849 DoExecute(args_string, result);
850
851 Cleanup();
852 }
853}
static CommandObject::CommandArgumentEntry OptSetFiltered(uint32_t opt_set_mask, CommandObject::CommandArgumentEntry &cmd_arg_entry)
static llvm::raw_ostream & error(Stream &strm)
A command line argument class.
Definition Args.h:33
void AppendArguments(const Args &rhs)
Definition Args.cpp:307
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
void ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str, char quote_char='\0')
Replaces the argument value at index idx to arg_str if idx is a valid argument index.
Definition Args.cpp:347
llvm::ArrayRef< ArgEntry > entries() const
Definition Args.h:132
const char ** GetConstArgumentVector() const
Gets the argument vector.
Definition Args.cpp:289
static bool InvokeCommonCompletionCallbacks(CommandInterpreter &interpreter, uint32_t completion_mask, lldb_private::CompletionRequest &request, SearchFilter *searcher)
void OutputFormattedHelpText(Stream &strm, llvm::StringRef prefix, llvm::StringRef help_text)
ExecutionContext GetExecutionContext() const
void OutputHelpText(Stream &stream, llvm::StringRef command_word, llvm::StringRef separator, llvm::StringRef help_text, uint32_t max_word_len)
virtual void DoExecute(Args &command, CommandReturnObject &result)=0
void Execute(const char *args_string, CommandReturnObject &result) override
void Execute(const char *args_string, CommandReturnObject &result) override
virtual void DoExecute(llvm::StringRef command, CommandReturnObject &result)=0
std::vector< CommandArgumentData > CommandArgumentEntry
CommandArgumentEntry * GetArgumentEntryAtIndex(int idx)
virtual void SetHelpLong(llvm::StringRef str)
virtual bool WantsRawCommandString()=0
void GenerateHelpText(CommandReturnObject &result)
lldb::CommandOverrideCallback m_deprecated_command_override_callback
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
std::unique_lock< std::recursive_mutex > m_api_locker
bool ParseOptionsAndNotify(Args &args, CommandReturnObject &result, OptionGroupOptions &group_options, ExecutionContext &exe_ctx)
virtual const char * GetInvalidProcessDescription()
virtual llvm::StringRef GetHelpLong()
static const ArgumentTableEntry * FindArgumentDataByType(lldb::CommandArgumentType arg_type)
llvm::StringRef GetCommandName() const
static std::optional< ArgumentRepetitionType > ArgRepetitionFromString(llvm::StringRef string)
static lldb::CommandArgumentType LookupArgumentName(llvm::StringRef arg_name)
void GetFormattedCommandArguments(Stream &str, uint32_t opt_set_mask=LLDB_OPT_SET_ALL)
bool HelpTextContainsWord(llvm::StringRef search_word, bool search_short_help=true, bool search_long_help=true, bool search_syntax=true, bool search_options=true)
virtual const char * GetInvalidTargetDescription()
std::vector< CommandArgumentEntry > m_arguments
lldb_private::CommandOverrideCallbackWithResult m_command_override_callback
void AddIDsArgumentData(IDType type)
CommandInterpreter & GetCommandInterpreter()
static const char * GetArgumentTypeAsCString(const lldb::CommandArgumentType arg_type)
CommandInterpreter & m_interpreter
virtual const char * GetInvalidRegContextDescription()
virtual Options * GetOptions()
void SetSyntax(llvm::StringRef str)
static const char * GetArgumentDescriptionAsCString(const lldb::CommandArgumentType arg_type)
CommandObject(CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help="", llvm::StringRef syntax="", uint32_t flags=0)
virtual const char * GetInvalidFrameDescription()
void SetCommandName(llvm::StringRef name)
Flags & GetFlags()
The flags accessor.
virtual void HandleArgumentCompletion(CompletionRequest &request, OptionElementVector &opt_element_vector)
The default version handles argument definitions that have only one argument type,...
bool ParseOptions(Args &args, CommandReturnObject &result)
void FormatLongHelpText(Stream &output_strm, llvm::StringRef long_help)
virtual llvm::StringRef GetSyntax()
virtual const char * GetInvalidThreadDescription()
static void GetArgumentHelp(Stream &str, lldb::CommandArgumentType arg_type, CommandInterpreter &interpreter)
bool CheckRequirements(CommandReturnObject &result)
Check the command to make sure anything required by this command is available.
virtual void HandleCompletion(CompletionRequest &request)
This default version handles calling option argument completions and then calls HandleArgumentComplet...
static bool IsPairType(ArgumentRepetitionType arg_repeat_type)
static const char * GetArgumentName(lldb::CommandArgumentType arg_type)
virtual llvm::StringRef GetHelp()
bool InvokeOverrideCallback(const char **argv, CommandReturnObject &result)
virtual void SetHelp(llvm::StringRef str)
void AppendError(llvm::StringRef in_string)
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormatv(const char *format, Args &&...args)
"lldb/Utility/ArgCompletionRequest.h"
A class to manage flag bits.
Definition Debugger.h:100
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
ValueType Get() const
Get accessor for all flags.
Definition Flags.h:40
A command line option parsing protocol class.
Definition Options.h:58
void GenerateOptionUsage(Stream &strm, CommandObject &cmd, uint32_t screen_width, bool use_color)
Definition Options.cpp:351
llvm::Error VerifyOptions()
Definition Options.cpp:517
uint32_t NumCommandOptions()
Definition Options.cpp:200
Status NotifyOptionParsingFinished(ExecutionContext *execution_context)
Definition Options.cpp:80
void NotifyOptionParsingStarting(ExecutionContext *execution_context)
Definition Options.cpp:73
bool HandleOptionCompletion(lldb_private::CompletionRequest &request, OptionElementVector &option_map, CommandInterpreter &interpreter)
Handles the generic bits of figuring out whether we are in an option, and if so completing it.
Definition Options.cpp:584
llvm::Expected< Args > Parse(const Args &args, ExecutionContext *execution_context, lldb::PlatformSP platform_sp, bool require_validation)
Parse the provided arguments.
Definition Options.cpp:1257
OptionElementVector ParseForCompletion(const Args &args, uint32_t cursor_index)
Definition Options.cpp:1079
A plug-in interface definition class for debugging a process.
Definition Process.h:355
ThreadList & GetThreadList()
Definition Process.h:2312
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1259
An error handling class.
Definition Status.h:118
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:155
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:132
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:153
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:202
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:199
lldb::TraceSP GetTrace()
Get the Trace object containing processor trace information of this target.
Definition Target.cpp:3594
const lldb::ProcessSP & GetProcessSP() const
Definition Target.cpp:314
std::recursive_mutex & GetAPIMutex()
Definition Target.cpp:5392
bool IsDummyTarget() const
Definition Target.h:660
lldb::ThreadSP GetSelectedThread()
#define LLDB_OPT_SET_ALL
A class that represents a running process on the host machine.
std::vector< OptionArgElement > OptionElementVector
Definition Options.h:43
llvm::ArrayRef< OptionEnumValueElement > OptionEnumValues
static constexpr CommandObject::ArgumentTableEntry g_argument_table[]
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateConnected
Process is connected to remote debug services, but not launched or attached to anything yet.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateSuspended
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateLaunching
Process is in the process of launching.
@ eStateAttaching
Process is currently trying to attach.
@ eStateExited
Process has exited and can't be examined.
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
@ eReturnStatusFailed
@ eReturnStatusSuccessFinishNoResult
@ eArgTypeBreakpointIDRange
@ eArgTypeBreakpointID
@ eArgTypeWatchpointID
@ eArgTypeWatchpointIDRange
const char * c_str() const
Definition Args.h:51
llvm::StringRef ref() const
Definition Args.h:50
char GetQuoteChar() const
Definition Args.h:55
Entries in the main argument information table.
Used to build individual command argument lists.