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
40namespace {
41/// RAII scope that resets the result's status to eReturnStatusInvalid on entry
42/// and asserts on exit that DoExecute changed it (directly via SetStatus, or
43/// indirectly via AppendError/SetError, which call SetStatus internally).
44class DoExecuteStatusCheck {
45public:
46 explicit DoExecuteStatusCheck(CommandReturnObject &result)
47 : m_result(result) {
48 m_result.SetStatus(eReturnStatusInvalid);
49 }
50 ~DoExecuteStatusCheck() {
51 assert(m_result.GetStatus() != eReturnStatusInvalid &&
52 "DoExecute did not set a status on the CommandReturnObject");
53 }
54
55private:
56 CommandReturnObject &m_result;
57};
58} // namespace
59
60// CommandObject
61
63 llvm::StringRef name, llvm::StringRef help,
64 llvm::StringRef syntax, uint32_t flags)
65 : m_interpreter(interpreter), m_cmd_name(std::string(name)),
68 m_cmd_help_short = std::string(help);
69 m_cmd_syntax = std::string(syntax);
70}
71
73
74llvm::StringRef CommandObject::GetHelp() { return m_cmd_help_short; }
75
76llvm::StringRef CommandObject::GetHelpLong() { return m_cmd_help_long; }
77
78llvm::StringRef CommandObject::GetSyntax() {
79 if (!m_cmd_syntax.empty())
80 return m_cmd_syntax;
81
82 StreamString syntax_str;
83 syntax_str.PutCString(GetCommandName());
84
85 if (!IsDashDashCommand() && GetOptions() != nullptr)
86 syntax_str.PutCString(" <cmd-options>");
87
88 if (!m_arguments.empty()) {
89 syntax_str.PutCString(" ");
90
92 GetOptions()->NumCommandOptions())
93 syntax_str.PutCString("-- ");
95 }
96 m_cmd_syntax = std::string(syntax_str.GetString());
97
98 return m_cmd_syntax;
99}
100
101llvm::StringRef CommandObject::GetCommandName() const { return m_cmd_name; }
102
103void CommandObject::SetCommandName(llvm::StringRef name) {
104 m_cmd_name = std::string(name);
105}
106
107void CommandObject::SetHelp(llvm::StringRef str) {
108 m_cmd_help_short = std::string(str);
109}
110
111void CommandObject::SetHelpLong(llvm::StringRef str) {
112 m_cmd_help_long = std::string(str);
113}
114
115void CommandObject::SetSyntax(llvm::StringRef str) {
116 m_cmd_syntax = std::string(str);
117}
118
120 // By default commands don't have options unless this virtual function is
121 // overridden by base classes.
122 return nullptr;
123}
124
126 // See if the subclass has options?
127 Options *options = GetOptions();
128 if (options != nullptr) {
130
132 options->NotifyOptionParsingStarting(&exe_ctx);
133
134 const bool require_validation = true;
135 llvm::Expected<Args> args_or = options->Parse(
136 args, &exe_ctx, GetCommandInterpreter().GetPlatform(true),
137 require_validation);
138
139 if (args_or) {
140 args = std::move(*args_or);
141 error = options->NotifyOptionParsingFinished(&exe_ctx);
142 } else {
143 error = Status::FromError(args_or.takeError());
144 }
145
146 if (error.Fail()) {
147 result.SetError(error.takeError());
149 return false;
150 }
151
152 if (llvm::Error error = options->VerifyOptions()) {
153 result.SetError(std::move(error));
155 return false;
156 }
157
159 return true;
160 }
161 return true;
162}
163
165 // Nothing should be stored in m_exe_ctx between running commands as
166 // m_exe_ctx has shared pointers to the target, process, thread and frame and
167 // we don't want any CommandObject instances to keep any of these objects
168 // around longer than for a single command. Every command should call
169 // CommandObject::Cleanup() after it has completed.
170 //
171 // The dummy target is allowed here because it is always alive, never causes
172 // resource leaks, and can appear when a command (e.g. "command source") is
173 // invoked re-entrantly before the outer Cleanup() has run.
174 assert(!m_exe_ctx.GetTargetPtr() ||
175 m_exe_ctx.GetTargetPtr()->IsDummyTarget());
176 assert(!m_exe_ctx.GetProcessPtr());
177 assert(!m_exe_ctx.GetThreadPtr());
178 assert(!m_exe_ctx.GetFramePtr());
179
180 // Lock down the interpreter's execution context prior to running the command
181 // so we guarantee the selected target, process, thread and frame can't go
182 // away during the execution
183 m_exe_ctx = m_interpreter.GetExecutionContext();
184
185 const uint32_t flags = GetFlags().Get();
186 if (flags & (eCommandRequiresTarget | eCommandRequiresProcess |
187 eCommandRequiresThread | eCommandRequiresFrame |
188 eCommandTryTargetAPILock)) {
189
190 Target *target = m_exe_ctx.GetTargetPtr();
191 if ((flags & eCommandRequiresTarget) &&
192 (!target || target->IsDummyTarget())) {
194 return false;
195 }
196
197 if ((flags & eCommandRequiresProcess) && !m_exe_ctx.HasProcessScope()) {
198 if (!target || target->IsDummyTarget())
200 else
202 return false;
203 }
204
205 if ((flags & eCommandRequiresThread) && !m_exe_ctx.HasThreadScope()) {
206 if (!target || target->IsDummyTarget())
208 else if (!m_exe_ctx.HasProcessScope())
210 else
212 return false;
213 }
214
215 if ((flags & eCommandRequiresFrame) && !m_exe_ctx.HasFrameScope()) {
216 if (!target || target->IsDummyTarget())
218 else if (!m_exe_ctx.HasProcessScope())
220 else if (!m_exe_ctx.HasThreadScope())
222 else
224 return false;
225 }
226
227 if ((flags & eCommandRequiresRegContext) &&
228 (m_exe_ctx.GetRegisterContext() == nullptr)) {
230 return false;
231 }
232
233 if (flags & eCommandTryTargetAPILock) {
234 if (target && !target->IsDummyTarget())
236 std::unique_lock<std::recursive_mutex>(target->GetAPIMutex());
237 }
238 }
239
240 if (GetFlags().AnySet(eCommandProcessMustBeLaunched |
241 eCommandProcessMustBePaused)) {
242 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
243 if (process == nullptr) {
244 // A process that is not running is considered paused.
245 if (GetFlags().Test(eCommandProcessMustBeLaunched)) {
246 result.AppendError("process must exist");
247 return false;
248 }
249 } else {
250 StateType state = process->GetState();
251 switch (state) {
252 case eStateInvalid:
253 case eStateSuspended:
254 case eStateCrashed:
255 case eStateStopped:
256 break;
257
258 case eStateConnected:
259 case eStateAttaching:
260 case eStateLaunching:
261 case eStateDetached:
262 case eStateExited:
263 case eStateUnloaded:
264 if (GetFlags().Test(eCommandProcessMustBeLaunched)) {
265 result.AppendError("process must be launched");
266 return false;
267 }
268 break;
269
270 case eStateRunning:
271 case eStateStepping:
272 if (GetFlags().Test(eCommandProcessMustBePaused)) {
273 result.AppendError("Process is running. Use 'process interrupt' to "
274 "pause execution.");
275 return false;
276 }
277 }
278 }
279 }
280
281 if (GetFlags().Test(eCommandProcessMustBeTraced)) {
282 Target *target = m_exe_ctx.GetTargetPtr();
283 if (target && !target->GetTrace()) {
284 result.AppendError("process is not being traced");
285 return false;
286 }
287 }
288
289 return true;
290}
291
293 m_exe_ctx.Clear();
294 if (m_api_locker.owns_lock())
295 m_api_locker.unlock();
296}
297
299
300 m_exe_ctx = m_interpreter.GetExecutionContext();
301 llvm::scope_exit reset_ctx([this]() { Cleanup(); });
302
303 // Default implementation of WantsCompletion() is !WantsRawCommandString().
304 // Subclasses who want raw command string but desire, for example, argument
305 // completion should override WantsCompletion() to return true, instead.
307 // FIXME: Abstract telling the completion to insert the completion
308 // character.
309 return;
310 } else {
311 // Can we do anything generic with the options?
312 Options *cur_options = GetOptions();
313 OptionElementVector opt_element_vector;
314
315 if (cur_options != nullptr) {
316 opt_element_vector = cur_options->ParseForCompletion(
317 request.GetParsedLine(), request.GetCursorIndex());
318
319 bool handled_by_options = cur_options->HandleOptionCompletion(
320 request, opt_element_vector, GetCommandInterpreter());
321 if (handled_by_options)
322 return;
323 }
324
325 // If we got here, the last word is not an option or an option argument.
326 HandleArgumentCompletion(request, opt_element_vector);
327 }
328}
329
331 CompletionRequest &request, OptionElementVector &opt_element_vector) {
332 size_t num_arg_entries = GetNumArgumentEntries();
333 if (num_arg_entries != 1)
334 return;
335
337 if (!entry_ptr) {
338 assert(entry_ptr && "We said there was one entry, but there wasn't.");
339 return; // Not worth crashing if asserts are off...
340 }
341
342 CommandArgumentEntry &entry = *entry_ptr;
343 // For now, we only handle the simple case of one homogenous argument type.
344 if (entry.size() != 1)
345 return;
346
347 // Look up the completion type, and if it has one, invoke it:
348 const CommandObject::ArgumentTableEntry *arg_entry =
349 FindArgumentDataByType(entry[0].arg_type);
350 const ArgumentRepetitionType repeat = entry[0].arg_repetition;
351
352 if (arg_entry == nullptr || arg_entry->completion_type == lldb::eNoCompletion)
353 return;
354
355 // FIXME: This should be handled higher in the Command Parser.
356 // Check the case where this command only takes one argument, and don't do
357 // the completion if we aren't on the first entry:
358 if (repeat == eArgRepeatPlain && request.GetCursorIndex() != 0)
359 return;
360
362 GetCommandInterpreter(), arg_entry->completion_type, request, nullptr);
363
364}
365
366bool CommandObject::HelpTextContainsWord(llvm::StringRef search_word,
367 bool search_short_help,
368 bool search_long_help,
369 bool search_syntax,
370 bool search_options) {
371 bool found_word = false;
372
373 llvm::StringRef short_help = GetHelp();
374 llvm::StringRef long_help = GetHelpLong();
375 llvm::StringRef syntax_help = GetSyntax();
376
377 if (search_short_help && short_help.contains_insensitive(search_word))
378 found_word = true;
379 else if (search_long_help && long_help.contains_insensitive(search_word))
380 found_word = true;
381 else if (search_syntax && syntax_help.contains_insensitive(search_word))
382 found_word = true;
383
384 if (!found_word && search_options && GetOptions() != nullptr) {
385 StreamString usage_help;
387 usage_help, *this,
388 GetCommandInterpreter().GetDebugger().GetTerminalWidth(),
389 GetCommandInterpreter().GetDebugger().GetUseColor());
390 if (!usage_help.Empty()) {
391 llvm::StringRef usage_text = usage_help.GetString();
392 if (usage_text.contains_insensitive(search_word))
393 found_word = true;
394 }
395 }
396
397 return found_word;
398}
399
401 CommandReturnObject &result,
402 OptionGroupOptions &group_options,
403 ExecutionContext &exe_ctx) {
404 if (!ParseOptions(args, result))
405 return false;
406
407 Status error(group_options.NotifyOptionParsingFinished(&exe_ctx));
408 if (error.Fail()) {
409 result.AppendError(error.AsCString());
410 return false;
411 }
412 return true;
413}
414
416 CommandArgumentType arg_type, ArgumentRepetitionType repetition_type) {
417
418 CommandArgumentEntry arg_entry;
419 CommandArgumentData simple_arg;
420
421 // Define the first (and only) variant of this arg.
422 simple_arg.arg_type = arg_type;
423 simple_arg.arg_repetition = repetition_type;
424
425 // There is only one variant this argument could be; put it into the argument
426 // entry.
427 arg_entry.push_back(simple_arg);
428
429 // Push the data for the first argument into the m_arguments vector.
430 m_arguments.push_back(arg_entry);
431}
432
434
437 if (static_cast<size_t>(idx) < m_arguments.size())
438 return &(m_arguments[idx]);
439
440 return nullptr;
441}
442
445 for (int i = 0; i < eArgTypeLastArg; ++i)
446 if (g_argument_table[i].arg_type == arg_type)
447 return &(g_argument_table[i]);
448
449 return nullptr;
450}
451
453 CommandInterpreter &interpreter) {
454 const ArgumentTableEntry *entry = &(g_argument_table[arg_type]);
455
456 // The table is *supposed* to be kept in arg_type order, but someone *could*
457 // have messed it up...
458
459 if (entry->arg_type != arg_type)
461
462 if (!entry)
463 return;
464
465 StreamString name_str;
466 name_str.Printf("<%s>", entry->arg_name);
467
468 if (entry->help_function) {
469 llvm::StringRef help_text = entry->help_function();
470 if (!entry->help_function.self_formatting) {
471 interpreter.OutputFormattedHelpText(str, name_str.GetString(), "--",
472 help_text, name_str.GetSize());
473 } else {
474 interpreter.OutputHelpText(str, name_str.GetString(), "--", help_text,
475 name_str.GetSize());
476 }
477 } else {
478 interpreter.OutputFormattedHelpText(str, name_str.GetString(), "--",
479 entry->help_text, name_str.GetSize());
480
481 // Print enum values and their description if any.
482 OptionEnumValues enum_values = g_argument_table[arg_type].enum_values;
483 if (!enum_values.empty()) {
484 str.EOL();
485 size_t longest = 0;
486 for (const OptionEnumValueElement &element : enum_values)
487 longest =
488 std::max(longest, llvm::StringRef(element.string_value).size());
489 str.IndentMore(5);
490 for (const OptionEnumValueElement &element : enum_values) {
491 str.Indent();
492 interpreter.OutputHelpText(str, element.string_value, ":",
493 element.usage, longest);
494 }
495 str.IndentLess(5);
496 str.EOL();
497 }
498 }
499}
500
502 const ArgumentTableEntry *entry = &(g_argument_table[arg_type]);
503
504 // The table is *supposed* to be kept in arg_type order, but someone *could*
505 // have messed it up...
506
507 if (entry->arg_type != arg_type)
509
510 if (entry)
511 return entry->arg_name;
512
513 return nullptr;
514}
515
517 return (arg_repeat_type == eArgRepeatPairPlain) ||
518 (arg_repeat_type == eArgRepeatPairOptional) ||
519 (arg_repeat_type == eArgRepeatPairPlus) ||
520 (arg_repeat_type == eArgRepeatPairStar) ||
521 (arg_repeat_type == eArgRepeatPairRange) ||
522 (arg_repeat_type == eArgRepeatPairRangeOptional);
523}
524
525std::optional<ArgumentRepetitionType>
527 return llvm::StringSwitch<ArgumentRepetitionType>(string)
528 .Case("plain", eArgRepeatPlain)
529 .Case("optional", eArgRepeatOptional)
530 .Case("plus", eArgRepeatPlus)
531 .Case("star", eArgRepeatStar)
532 .Case("range", eArgRepeatRange)
533 .Case("pair-plain", eArgRepeatPairPlain)
534 .Case("pair-optional", eArgRepeatPairOptional)
535 .Case("pair-plus", eArgRepeatPairPlus)
536 .Case("pair-star", eArgRepeatPairStar)
537 .Case("pair-range", eArgRepeatPairRange)
538 .Case("pair-range-optional", eArgRepeatPairRangeOptional)
539 .Default({});
540}
541
543OptSetFiltered(uint32_t opt_set_mask,
546 for (unsigned i = 0; i < cmd_arg_entry.size(); ++i)
547 if (opt_set_mask & cmd_arg_entry[i].arg_opt_set_association)
548 ret_val.push_back(cmd_arg_entry[i]);
549 return ret_val;
550}
551
552// Default parameter value of opt_set_mask is LLDB_OPT_SET_ALL, which means
553// take all the argument data into account. On rare cases where some argument
554// sticks with certain option sets, this function returns the option set
555// filtered args.
557 uint32_t opt_set_mask) {
558 int num_args = m_arguments.size();
559 for (int i = 0; i < num_args; ++i) {
560 if (i > 0)
561 str.Printf(" ");
562 CommandArgumentEntry arg_entry =
563 opt_set_mask == LLDB_OPT_SET_ALL
564 ? m_arguments[i]
565 : OptSetFiltered(opt_set_mask, m_arguments[i]);
566 // This argument is not associated with the current option set, so skip it.
567 if (arg_entry.empty())
568 continue;
569 int num_alternatives = arg_entry.size();
570
571 if ((num_alternatives == 2) && IsPairType(arg_entry[0].arg_repetition)) {
572 const char *first_name = GetArgumentName(arg_entry[0].arg_type);
573 const char *second_name = GetArgumentName(arg_entry[1].arg_type);
574 switch (arg_entry[0].arg_repetition) {
576 str.Printf("<%s> <%s>", first_name, second_name);
577 break;
579 str.Printf("[<%s> <%s>]", first_name, second_name);
580 break;
582 str.Printf("<%s> <%s> [<%s> <%s> [...]]", first_name, second_name,
583 first_name, second_name);
584 break;
586 str.Printf("[<%s> <%s> [<%s> <%s> [...]]]", first_name, second_name,
587 first_name, second_name);
588 break;
590 str.Printf("<%s_1> <%s_1> ... <%s_n> <%s_n>", first_name, second_name,
591 first_name, second_name);
592 break;
594 str.Printf("[<%s_1> <%s_1> ... <%s_n> <%s_n>]", first_name, second_name,
595 first_name, second_name);
596 break;
597 // Explicitly test for all the rest of the cases, so if new types get
598 // added we will notice the missing case statement(s).
599 case eArgRepeatPlain:
601 case eArgRepeatPlus:
602 case eArgRepeatStar:
603 case eArgRepeatRange:
604 // These should not be reached, as they should fail the IsPairType test
605 // above.
606 break;
607 }
608 } else {
609 StreamString names;
610 for (int j = 0; j < num_alternatives; ++j) {
611 if (j > 0)
612 names.Printf(" | ");
613 names.Printf("%s", GetArgumentName(arg_entry[j].arg_type));
614 }
615
616 std::string name_str = std::string(names.GetString());
617 switch (arg_entry[0].arg_repetition) {
618 case eArgRepeatPlain:
619 str.Printf("<%s>", name_str.c_str());
620 break;
621 case eArgRepeatPlus:
622 str.Printf("<%s> [<%s> [...]]", name_str.c_str(), name_str.c_str());
623 break;
624 case eArgRepeatStar:
625 str.Printf("[<%s> [<%s> [...]]]", name_str.c_str(), name_str.c_str());
626 break;
628 str.Printf("[<%s>]", name_str.c_str());
629 break;
630 case eArgRepeatRange:
631 str.Printf("<%s_1> .. <%s_n>", name_str.c_str(), name_str.c_str());
632 break;
633 // Explicitly test for all the rest of the cases, so if new types get
634 // added we will notice the missing case statement(s).
641 // These should not be hit, as they should pass the IsPairType test
642 // above, and control should have gone into the other branch of the if
643 // statement.
644 break;
645 }
646 }
647 }
648}
649
651CommandObject::LookupArgumentName(llvm::StringRef arg_name) {
653
654 arg_name = arg_name.ltrim('<').rtrim('>');
655
656 for (int i = 0; i < eArgTypeLastArg; ++i)
657 if (arg_name == g_argument_table[i].arg_name)
658 return_type = g_argument_table[i].arg_type;
659
660 return return_type;
661}
662
664 llvm::StringRef long_help) {
666 std::stringstream lineStream{std::string(long_help)};
667 std::string line;
668 while (std::getline(lineStream, line)) {
669 if (line.empty()) {
670 output_strm << "\n";
671 continue;
672 }
673 size_t result = line.find_first_not_of(" \t");
674 if (result == std::string::npos) {
675 result = 0;
676 }
677 std::string whitespace_prefix = line.substr(0, result);
678 std::string remainder = line.substr(result);
679 interpreter.OutputFormattedHelpText(output_strm, whitespace_prefix,
680 remainder);
681 }
682}
683
689
692 std::string help_text(GetHelp());
693 if (WantsRawCommandString()) {
694 help_text.append(" Expects 'raw' input (see 'help raw-input'.)");
695 }
696 interpreter.OutputFormattedHelpText(output_strm, "", help_text);
697 output_strm << "\nSyntax: " << GetSyntax() << "\n";
698 Options *options = GetOptions();
699 if (options != nullptr) {
700 options->GenerateOptionUsage(
701 output_strm, *this,
702 GetCommandInterpreter().GetDebugger().GetTerminalWidth(),
703 GetCommandInterpreter().GetDebugger().GetUseColor());
704 }
705 llvm::StringRef long_help = GetHelpLong();
706 if (!long_help.empty()) {
707 FormatLongHelpText(output_strm, long_help);
708 }
709 if (!IsDashDashCommand() && options && options->NumCommandOptions() > 0) {
711 // Emit the message about using ' -- ' between the end of the command
712 // options and the raw input conditionally, i.e., only if the command
713 // object does not want completion.
714 interpreter.OutputFormattedHelpText(
715 output_strm, "", "",
716 "\nImportant Note: Because this command takes 'raw' input, if you "
717 "use any command options"
718 " you must use ' -- ' between the end of the command options and the "
719 "beginning of the raw input.",
720 1);
721 } else if (GetNumArgumentEntries() > 0) {
722 // Also emit a warning about using "--" in case you are using a command
723 // that takes options and arguments.
724 interpreter.OutputFormattedHelpText(
725 output_strm, "", "",
726 "\nThis command takes options and free-form arguments. If your "
727 "arguments resemble"
728 " option specifiers (i.e., they start with a - or --), you must use "
729 "' -- ' between"
730 " the end of the command options and the beginning of the arguments.",
731 1);
732 }
733 }
734}
735
738 CommandArgumentData id_arg;
739 CommandArgumentData id_range_arg;
740
741 // Create the first variant for the first (and only) argument for this
742 // command.
743 switch (type) {
744 case eBreakpointArgs:
746 id_range_arg.arg_type = eArgTypeBreakpointIDRange;
747 break;
748 case eWatchpointArgs:
750 id_range_arg.arg_type = eArgTypeWatchpointIDRange;
751 break;
752 }
754 id_range_arg.arg_repetition = eArgRepeatOptional;
755
756 // The first (and only) argument for this command could be either an id or an
757 // id_range. Push both variants into the entry for the first argument for
758 // this command.
759 arg.push_back(id_arg);
760 arg.push_back(id_range_arg);
761 m_arguments.push_back(arg);
762}
763
765 const lldb::CommandArgumentType arg_type) {
766 assert(arg_type < eArgTypeLastArg &&
767 "Invalid argument type passed to GetArgumentTypeAsCString");
768 return g_argument_table[arg_type].arg_name;
769}
770
772 const lldb::CommandArgumentType arg_type) {
773 assert(arg_type < eArgTypeLastArg &&
774 "Invalid argument type passed to GetArgumentDescriptionAsCString");
775 return g_argument_table[arg_type].help_text;
776}
777
779 return m_interpreter.GetDebugger().GetDummyTarget();
780}
781
783 // Prefer the frozen execution context in the command object.
784 if (Target *target = m_exe_ctx.GetTargetPtr())
785 return *target;
786
787 // Fallback to the command interpreter's execution context in case we get
788 // called after DoExecute has finished. For example, when doing multi-line
789 // expression that uses an input reader or breakpoint callbacks.
790 return m_interpreter.GetExecutionContext().GetTargetRef();
791}
792
794 Thread *thread_to_use = m_exe_ctx.GetThreadPtr();
795 if (thread_to_use)
796 return thread_to_use;
797
798 Process *process = m_exe_ctx.GetProcessPtr();
799 if (!process) {
800 Target *target = m_exe_ctx.GetTargetPtr();
801 if (!target) {
802 target = m_interpreter.GetDebugger().GetSelectedTarget().get();
803 }
804 if (target)
805 process = target->GetProcessSP().get();
806 }
807
808 if (process)
809 return process->GetThreadList().GetSelectedThread().get();
810 else
811 return nullptr;
812}
813
814void CommandObjectParsed::Execute(const char *args_string,
815 CommandReturnObject &result) {
816 bool handled = false;
817 Args cmd_args(args_string);
818 if (HasOverrideCallback()) {
819 Args full_args(GetCommandName());
820 full_args.AppendArguments(cmd_args);
821 handled =
823 }
824 if (!handled) {
825 for (auto entry : llvm::enumerate(cmd_args.entries())) {
826 const Args::ArgEntry &value = entry.value();
827 if (!value.ref().empty() && value.GetQuoteChar() == '`') {
828 // We have to put the backtick back in place for PreprocessCommand.
829 std::string opt_string = value.c_str();
831 error = m_interpreter.PreprocessToken(opt_string);
832 if (error.Success())
833 cmd_args.ReplaceArgumentAtIndex(entry.index(), opt_string);
834 }
835 }
836
837 if (CheckRequirements(result)) {
838 if (ParseOptions(cmd_args, result)) {
839 // Call the command-specific version of 'Execute', passing it the
840 // already processed arguments.
841 if (cmd_args.GetArgumentCount() != 0 && m_arguments.empty()) {
842 result.AppendErrorWithFormatv("'{0}' doesn't take any arguments.",
844 Cleanup();
845 return;
846 }
847 m_interpreter.IncreaseCommandUsage(*this);
848 DoExecuteStatusCheck check(result);
849 DoExecute(cmd_args, result);
850 }
851 }
852
853 Cleanup();
854 }
855}
856
857void CommandObjectRaw::Execute(const char *args_string,
858 CommandReturnObject &result) {
859 bool handled = false;
860 if (HasOverrideCallback()) {
861 std::string full_command(GetCommandName());
862 full_command += ' ';
863 full_command += args_string;
864 const char *argv[2] = {nullptr, nullptr};
865 argv[0] = full_command.c_str();
866 handled = InvokeOverrideCallback(argv, result);
867 }
868 if (!handled) {
869 if (CheckRequirements(result)) {
870 DoExecuteStatusCheck check(result);
871 DoExecute(args_string, result);
872 }
873
874 Cleanup();
875 }
876}
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, std::optional< Stream::HighlightSettings > highlight=std::nullopt)
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:356
ThreadList & GetThreadList()
Definition Process.h:2347
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1278
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:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
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:155
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:204
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:201
lldb::TraceSP GetTrace()
Get the Trace object containing processor trace information of this target.
Definition Target.cpp:3724
const lldb::ProcessSP & GetProcessSP() const
Definition Target.cpp:327
std::recursive_mutex & GetAPIMutex()
Definition Target.cpp:5957
bool IsDummyTarget() const
Definition Target.h:670
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
@ eReturnStatusInvalid
@ 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.