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. The dummy target is only adopted when the
183 // command opts in via eCommandAllowsDummyTarget, so other commands won't
184 // accidentally see it through m_exe_ctx.
185 const uint32_t flags = GetFlags().Get();
186 const bool adopt_dummy_target = flags & eCommandAllowsDummyTarget;
187 m_exe_ctx = m_interpreter.GetExecutionContext(adopt_dummy_target);
188
189 if (flags & (eCommandRequiresTarget | eCommandRequiresProcess |
190 eCommandRequiresThread | eCommandRequiresFrame |
191 eCommandTryTargetAPILock)) {
192
193 Target *target = m_exe_ctx.GetTargetPtr();
194 if ((flags & eCommandRequiresTarget) &&
195 (!target || target->IsDummyTarget())) {
197 return false;
198 }
199
200 if ((flags & eCommandRequiresProcess) && !m_exe_ctx.HasProcessScope()) {
201 if (!target || target->IsDummyTarget())
203 else
205 return false;
206 }
207
208 if ((flags & eCommandRequiresThread) && !m_exe_ctx.HasThreadScope()) {
209 if (!target || target->IsDummyTarget())
211 else if (!m_exe_ctx.HasProcessScope())
213 else
215 return false;
216 }
217
218 if ((flags & eCommandRequiresFrame) && !m_exe_ctx.HasFrameScope()) {
219 if (!target || target->IsDummyTarget())
221 else if (!m_exe_ctx.HasProcessScope())
223 else if (!m_exe_ctx.HasThreadScope())
225 else
227 return false;
228 }
229
230 if ((flags & eCommandRequiresRegContext) &&
231 (m_exe_ctx.GetRegisterContext() == nullptr)) {
233 return false;
234 }
235
236 if (flags & eCommandTryTargetAPILock) {
237 if (target && !target->IsDummyTarget())
239 std::unique_lock<std::recursive_mutex>(target->GetAPIMutex());
240 }
241 }
242
243 if (GetFlags().AnySet(eCommandProcessMustBeLaunched |
244 eCommandProcessMustBePaused)) {
245 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
246 if (process == nullptr) {
247 // A process that is not running is considered paused.
248 if (GetFlags().Test(eCommandProcessMustBeLaunched)) {
249 result.AppendError("process must exist");
250 return false;
251 }
252 } else {
253 StateType state = process->GetState();
254 switch (state) {
255 case eStateInvalid:
256 case eStateSuspended:
257 case eStateCrashed:
258 case eStateStopped:
259 break;
260
261 case eStateConnected:
262 case eStateAttaching:
263 case eStateLaunching:
264 case eStateDetached:
265 case eStateExited:
266 case eStateUnloaded:
267 if (GetFlags().Test(eCommandProcessMustBeLaunched)) {
268 result.AppendError("process must be launched");
269 return false;
270 }
271 break;
272
273 case eStateRunning:
274 case eStateStepping:
275 if (GetFlags().Test(eCommandProcessMustBePaused)) {
276 result.AppendError("Process is running. Use 'process interrupt' to "
277 "pause execution.");
278 return false;
279 }
280 }
281 }
282 }
283
284 if (GetFlags().Test(eCommandProcessMustBeTraced)) {
285 Target *target = m_exe_ctx.GetTargetPtr();
286 if (target && !target->GetTrace()) {
287 result.AppendError("process is not being traced");
288 return false;
289 }
290 }
291
292 return true;
293}
294
296 m_exe_ctx.Clear();
297 if (m_api_locker.owns_lock())
298 m_api_locker.unlock();
299}
300
302
303 m_exe_ctx = m_interpreter.GetExecutionContext();
304 llvm::scope_exit reset_ctx([this]() { Cleanup(); });
305
306 // Default implementation of WantsCompletion() is !WantsRawCommandString().
307 // Subclasses who want raw command string but desire, for example, argument
308 // completion should override WantsCompletion() to return true, instead.
310 // FIXME: Abstract telling the completion to insert the completion
311 // character.
312 return;
313 } else {
314 // Can we do anything generic with the options?
315 Options *cur_options = GetOptions();
316 OptionElementVector opt_element_vector;
317
318 if (cur_options != nullptr) {
319 opt_element_vector = cur_options->ParseForCompletion(
320 request.GetParsedLine(), request.GetCursorIndex());
321
322 bool handled_by_options = cur_options->HandleOptionCompletion(
323 request, opt_element_vector, GetCommandInterpreter());
324 if (handled_by_options)
325 return;
326 }
327
328 // If we got here, the last word is not an option or an option argument.
329 HandleArgumentCompletion(request, opt_element_vector);
330 }
331}
332
334 CompletionRequest &request, OptionElementVector &opt_element_vector) {
335 size_t num_arg_entries = GetNumArgumentEntries();
336 if (num_arg_entries != 1)
337 return;
338
340 if (!entry_ptr) {
341 assert(entry_ptr && "We said there was one entry, but there wasn't.");
342 return; // Not worth crashing if asserts are off...
343 }
344
345 CommandArgumentEntry &entry = *entry_ptr;
346 // For now, we only handle the simple case of one homogenous argument type.
347 if (entry.size() != 1)
348 return;
349
350 // Look up the completion type, and if it has one, invoke it:
351 const CommandObject::ArgumentTableEntry *arg_entry =
352 FindArgumentDataByType(entry[0].arg_type);
353 const ArgumentRepetitionType repeat = entry[0].arg_repetition;
354
355 if (arg_entry == nullptr || arg_entry->completion_type == lldb::eNoCompletion)
356 return;
357
358 // FIXME: This should be handled higher in the Command Parser.
359 // Check the case where this command only takes one argument, and don't do
360 // the completion if we aren't on the first entry:
361 if (repeat == eArgRepeatPlain && request.GetCursorIndex() != 0)
362 return;
363
365 GetCommandInterpreter(), arg_entry->completion_type, request, nullptr);
366
367}
368
369bool CommandObject::HelpTextContainsWord(llvm::StringRef search_word,
370 bool search_short_help,
371 bool search_long_help,
372 bool search_syntax,
373 bool search_options) {
374 bool found_word = false;
375
376 llvm::StringRef short_help = GetHelp();
377 llvm::StringRef long_help = GetHelpLong();
378 llvm::StringRef syntax_help = GetSyntax();
379
380 if (search_short_help && short_help.contains_insensitive(search_word))
381 found_word = true;
382 else if (search_long_help && long_help.contains_insensitive(search_word))
383 found_word = true;
384 else if (search_syntax && syntax_help.contains_insensitive(search_word))
385 found_word = true;
386
387 if (!found_word && search_options && GetOptions() != nullptr) {
388 StreamString usage_help;
390 usage_help, *this,
391 GetCommandInterpreter().GetDebugger().GetTerminalWidth(),
392 GetCommandInterpreter().GetDebugger().GetUseColor());
393 if (!usage_help.Empty()) {
394 llvm::StringRef usage_text = usage_help.GetString();
395 if (usage_text.contains_insensitive(search_word))
396 found_word = true;
397 }
398 }
399
400 return found_word;
401}
402
404 CommandReturnObject &result,
405 OptionGroupOptions &group_options,
406 ExecutionContext &exe_ctx) {
407 if (!ParseOptions(args, result))
408 return false;
409
410 Status error(group_options.NotifyOptionParsingFinished(&exe_ctx));
411 if (error.Fail()) {
412 result.AppendError(error.AsCString());
413 return false;
414 }
415 return true;
416}
417
419 CommandArgumentType arg_type, ArgumentRepetitionType repetition_type) {
420
421 CommandArgumentEntry arg_entry;
422 CommandArgumentData simple_arg;
423
424 // Define the first (and only) variant of this arg.
425 simple_arg.arg_type = arg_type;
426 simple_arg.arg_repetition = repetition_type;
427
428 // There is only one variant this argument could be; put it into the argument
429 // entry.
430 arg_entry.push_back(simple_arg);
431
432 // Push the data for the first argument into the m_arguments vector.
433 m_arguments.push_back(arg_entry);
434}
435
437
440 if (static_cast<size_t>(idx) < m_arguments.size())
441 return &(m_arguments[idx]);
442
443 return nullptr;
444}
445
448 for (int i = 0; i < eArgTypeLastArg; ++i)
449 if (g_argument_table[i].arg_type == arg_type)
450 return &(g_argument_table[i]);
451
452 return nullptr;
453}
454
456 CommandInterpreter &interpreter) {
457 const ArgumentTableEntry *entry = &(g_argument_table[arg_type]);
458
459 // The table is *supposed* to be kept in arg_type order, but someone *could*
460 // have messed it up...
461
462 if (entry->arg_type != arg_type)
464
465 if (!entry)
466 return;
467
468 StreamString name_str;
469 name_str.Printf("<%s>", entry->arg_name);
470
471 if (entry->help_function) {
472 llvm::StringRef help_text = entry->help_function();
473 if (!entry->help_function.self_formatting) {
474 interpreter.OutputFormattedHelpText(str, name_str.GetString(), "--",
475 help_text, name_str.GetSize());
476 } else {
477 interpreter.OutputHelpText(str, name_str.GetString(), "--", help_text,
478 name_str.GetSize());
479 }
480 } else {
481 interpreter.OutputFormattedHelpText(str, name_str.GetString(), "--",
482 entry->help_text, name_str.GetSize());
483
484 // Print enum values and their description if any.
485 OptionEnumValues enum_values = g_argument_table[arg_type].enum_values;
486 if (!enum_values.empty()) {
487 str.EOL();
488 size_t longest = 0;
489 for (const OptionEnumValueElement &element : enum_values)
490 longest =
491 std::max(longest, llvm::StringRef(element.string_value).size());
492 str.IndentMore(5);
493 for (const OptionEnumValueElement &element : enum_values) {
494 str.Indent();
495 interpreter.OutputHelpText(str, element.string_value, ":",
496 element.usage, longest);
497 }
498 str.IndentLess(5);
499 str.EOL();
500 }
501 }
502}
503
505 const ArgumentTableEntry *entry = &(g_argument_table[arg_type]);
506
507 // The table is *supposed* to be kept in arg_type order, but someone *could*
508 // have messed it up...
509
510 if (entry->arg_type != arg_type)
512
513 if (entry)
514 return entry->arg_name;
515
516 return nullptr;
517}
518
520 return (arg_repeat_type == eArgRepeatPairPlain) ||
521 (arg_repeat_type == eArgRepeatPairOptional) ||
522 (arg_repeat_type == eArgRepeatPairPlus) ||
523 (arg_repeat_type == eArgRepeatPairStar) ||
524 (arg_repeat_type == eArgRepeatPairRange) ||
525 (arg_repeat_type == eArgRepeatPairRangeOptional);
526}
527
528std::optional<ArgumentRepetitionType>
530 return llvm::StringSwitch<ArgumentRepetitionType>(string)
531 .Case("plain", eArgRepeatPlain)
532 .Case("optional", eArgRepeatOptional)
533 .Case("plus", eArgRepeatPlus)
534 .Case("star", eArgRepeatStar)
535 .Case("range", eArgRepeatRange)
536 .Case("pair-plain", eArgRepeatPairPlain)
537 .Case("pair-optional", eArgRepeatPairOptional)
538 .Case("pair-plus", eArgRepeatPairPlus)
539 .Case("pair-star", eArgRepeatPairStar)
540 .Case("pair-range", eArgRepeatPairRange)
541 .Case("pair-range-optional", eArgRepeatPairRangeOptional)
542 .Default({});
543}
544
546OptSetFiltered(uint32_t opt_set_mask,
549 for (unsigned i = 0; i < cmd_arg_entry.size(); ++i)
550 if (opt_set_mask & cmd_arg_entry[i].arg_opt_set_association)
551 ret_val.push_back(cmd_arg_entry[i]);
552 return ret_val;
553}
554
555// Default parameter value of opt_set_mask is LLDB_OPT_SET_ALL, which means
556// take all the argument data into account. On rare cases where some argument
557// sticks with certain option sets, this function returns the option set
558// filtered args.
560 uint32_t opt_set_mask) {
561 int num_args = m_arguments.size();
562 for (int i = 0; i < num_args; ++i) {
563 if (i > 0)
564 str.Printf(" ");
565 CommandArgumentEntry arg_entry =
566 opt_set_mask == LLDB_OPT_SET_ALL
567 ? m_arguments[i]
568 : OptSetFiltered(opt_set_mask, m_arguments[i]);
569 // This argument is not associated with the current option set, so skip it.
570 if (arg_entry.empty())
571 continue;
572 int num_alternatives = arg_entry.size();
573
574 if ((num_alternatives == 2) && IsPairType(arg_entry[0].arg_repetition)) {
575 const char *first_name = GetArgumentName(arg_entry[0].arg_type);
576 const char *second_name = GetArgumentName(arg_entry[1].arg_type);
577 switch (arg_entry[0].arg_repetition) {
579 str.Printf("<%s> <%s>", first_name, second_name);
580 break;
582 str.Printf("[<%s> <%s>]", first_name, second_name);
583 break;
585 str.Printf("<%s> <%s> [<%s> <%s> [...]]", first_name, second_name,
586 first_name, second_name);
587 break;
589 str.Printf("[<%s> <%s> [<%s> <%s> [...]]]", first_name, second_name,
590 first_name, second_name);
591 break;
593 str.Printf("<%s_1> <%s_1> ... <%s_n> <%s_n>", first_name, second_name,
594 first_name, second_name);
595 break;
597 str.Printf("[<%s_1> <%s_1> ... <%s_n> <%s_n>]", first_name, second_name,
598 first_name, second_name);
599 break;
600 // Explicitly test for all the rest of the cases, so if new types get
601 // added we will notice the missing case statement(s).
602 case eArgRepeatPlain:
604 case eArgRepeatPlus:
605 case eArgRepeatStar:
606 case eArgRepeatRange:
607 // These should not be reached, as they should fail the IsPairType test
608 // above.
609 break;
610 }
611 } else {
612 StreamString names;
613 for (int j = 0; j < num_alternatives; ++j) {
614 if (j > 0)
615 names.Printf(" | ");
616 names.Printf("%s", GetArgumentName(arg_entry[j].arg_type));
617 }
618
619 std::string name_str = std::string(names.GetString());
620 switch (arg_entry[0].arg_repetition) {
621 case eArgRepeatPlain:
622 str.Printf("<%s>", name_str.c_str());
623 break;
624 case eArgRepeatPlus:
625 str.Printf("<%s> [<%s> [...]]", name_str.c_str(), name_str.c_str());
626 break;
627 case eArgRepeatStar:
628 str.Printf("[<%s> [<%s> [...]]]", name_str.c_str(), name_str.c_str());
629 break;
631 str.Printf("[<%s>]", name_str.c_str());
632 break;
633 case eArgRepeatRange:
634 str.Printf("<%s_1> .. <%s_n>", name_str.c_str(), name_str.c_str());
635 break;
636 // Explicitly test for all the rest of the cases, so if new types get
637 // added we will notice the missing case statement(s).
644 // These should not be hit, as they should pass the IsPairType test
645 // above, and control should have gone into the other branch of the if
646 // statement.
647 break;
648 }
649 }
650 }
651}
652
654CommandObject::LookupArgumentName(llvm::StringRef arg_name) {
656
657 arg_name = arg_name.ltrim('<').rtrim('>');
658
659 for (int i = 0; i < eArgTypeLastArg; ++i)
660 if (arg_name == g_argument_table[i].arg_name)
661 return_type = g_argument_table[i].arg_type;
662
663 return return_type;
664}
665
667 llvm::StringRef long_help) {
669 std::stringstream lineStream{std::string(long_help)};
670 std::string line;
671 while (std::getline(lineStream, line)) {
672 if (line.empty()) {
673 output_strm << "\n";
674 continue;
675 }
676 size_t result = line.find_first_not_of(" \t");
677 if (result == std::string::npos) {
678 result = 0;
679 }
680 std::string whitespace_prefix = line.substr(0, result);
681 std::string remainder = line.substr(result);
682 interpreter.OutputFormattedHelpText(output_strm, whitespace_prefix,
683 remainder);
684 }
685}
686
692
695 std::string help_text(GetHelp());
696 if (WantsRawCommandString()) {
697 help_text.append(" Expects 'raw' input (see 'help raw-input'.)");
698 }
699 interpreter.OutputFormattedHelpText(output_strm, "", help_text);
700 output_strm << "\nSyntax: " << GetSyntax() << "\n";
701 Options *options = GetOptions();
702 if (options != nullptr) {
703 options->GenerateOptionUsage(
704 output_strm, *this,
705 GetCommandInterpreter().GetDebugger().GetTerminalWidth(),
706 GetCommandInterpreter().GetDebugger().GetUseColor());
707 }
708 llvm::StringRef long_help = GetHelpLong();
709 if (!long_help.empty()) {
710 FormatLongHelpText(output_strm, long_help);
711 }
712 if (!IsDashDashCommand() && options && options->NumCommandOptions() > 0) {
714 // Emit the message about using ' -- ' between the end of the command
715 // options and the raw input conditionally, i.e., only if the command
716 // object does not want completion.
717 interpreter.OutputFormattedHelpText(
718 output_strm, "", "",
719 "\nImportant Note: Because this command takes 'raw' input, if you "
720 "use any command options"
721 " you must use ' -- ' between the end of the command options and the "
722 "beginning of the raw input.",
723 1);
724 } else if (GetNumArgumentEntries() > 0) {
725 // Also emit a warning about using "--" in case you are using a command
726 // that takes options and arguments.
727 interpreter.OutputFormattedHelpText(
728 output_strm, "", "",
729 "\nThis command takes options and free-form arguments. If your "
730 "arguments resemble"
731 " option specifiers (i.e., they start with a - or --), you must use "
732 "' -- ' between"
733 " the end of the command options and the beginning of the arguments.",
734 1);
735 }
736 }
737}
738
741 CommandArgumentData id_arg;
742 CommandArgumentData id_range_arg;
743
744 // Create the first variant for the first (and only) argument for this
745 // command.
746 switch (type) {
747 case eBreakpointArgs:
749 id_range_arg.arg_type = eArgTypeBreakpointIDRange;
750 break;
751 case eWatchpointArgs:
753 id_range_arg.arg_type = eArgTypeWatchpointIDRange;
754 break;
755 }
757 id_range_arg.arg_repetition = eArgRepeatOptional;
758
759 // The first (and only) argument for this command could be either an id or an
760 // id_range. Push both variants into the entry for the first argument for
761 // this command.
762 arg.push_back(id_arg);
763 arg.push_back(id_range_arg);
764 m_arguments.push_back(arg);
765}
766
768 const lldb::CommandArgumentType arg_type) {
769 assert(arg_type < eArgTypeLastArg &&
770 "Invalid argument type passed to GetArgumentTypeAsCString");
771 return g_argument_table[arg_type].arg_name;
772}
773
775 const lldb::CommandArgumentType arg_type) {
776 assert(arg_type < eArgTypeLastArg &&
777 "Invalid argument type passed to GetArgumentDescriptionAsCString");
778 return g_argument_table[arg_type].help_text;
779}
780
782 return m_interpreter.GetDebugger().GetDummyTarget();
783}
784
786 // Prefer the frozen execution context in the command object, falling back
787 // to the interpreter's execution context for paths like multi-line
788 // expressions or breakpoint callbacks that run after DoExecute has
789 // finished. Both honor eCommandAllowsDummyTarget when deciding whether to
790 // substitute the dummy target, so no post-hoc filtering is needed.
791 const uint32_t flags = GetFlags().Get();
792 const bool adopt_dummy_target = flags & eCommandAllowsDummyTarget;
793 Target *target = m_exe_ctx.GetTargetPtr();
794 if (!target)
795 target =
796 m_interpreter.GetExecutionContext(adopt_dummy_target).GetTargetPtr();
797
798 // CheckRequirements has already guaranteed a non-dummy target for any
799 // command declaring a Requires* flag.
800 assert(target || !(flags & (eCommandRequiresTarget | eCommandRequiresProcess |
801 eCommandRequiresThread | eCommandRequiresFrame)));
802 return target;
803}
804
806 Thread *thread_to_use = m_exe_ctx.GetThreadPtr();
807 if (thread_to_use)
808 return thread_to_use;
809
810 Process *process = m_exe_ctx.GetProcessPtr();
811 if (!process) {
812 Target *target = m_exe_ctx.GetTargetPtr();
813 if (!target) {
814 target = m_interpreter.GetSelectedTarget().get();
815 }
816 if (target)
817 process = target->GetProcessSP().get();
818 }
819
820 if (process)
821 return process->GetThreadList().GetSelectedThread().get();
822 else
823 return nullptr;
824}
825
826void CommandObjectParsed::Execute(const char *args_string,
827 CommandReturnObject &result) {
828 bool handled = false;
829 Args cmd_args(args_string);
830 if (HasOverrideCallback()) {
831 Args full_args(GetCommandName());
832 full_args.AppendArguments(cmd_args);
833 handled =
835 }
836 if (!handled) {
837 for (auto entry : llvm::enumerate(cmd_args.entries())) {
838 const Args::ArgEntry &value = entry.value();
839 if (!value.ref().empty() && value.GetQuoteChar() == '`') {
840 // We have to put the backtick back in place for PreprocessCommand.
841 std::string opt_string = value.c_str();
843 error = m_interpreter.PreprocessToken(opt_string);
844 if (error.Success())
845 cmd_args.ReplaceArgumentAtIndex(entry.index(), opt_string);
846 }
847 }
848
849 if (CheckRequirements(result)) {
850 if (ParseOptions(cmd_args, result)) {
851 // Call the command-specific version of 'Execute', passing it the
852 // already processed arguments.
853 if (cmd_args.GetArgumentCount() != 0 && m_arguments.empty()) {
854 result.AppendErrorWithFormatv("'{0}' doesn't take any arguments.",
856 Cleanup();
857 return;
858 }
859 m_interpreter.IncreaseCommandUsage(*this);
860 DoExecuteStatusCheck check(result);
861 DoExecute(cmd_args, result);
862 }
863 }
864
865 Cleanup();
866 }
867}
868
869void CommandObjectRaw::Execute(const char *args_string,
870 CommandReturnObject &result) {
871 bool handled = false;
872 if (HasOverrideCallback()) {
873 std::string full_command(GetCommandName());
874 full_command += ' ';
875 full_command += args_string;
876 const char *argv[2] = {nullptr, nullptr};
877 argv[0] = full_command.c_str();
878 handled = InvokeOverrideCallback(argv, result);
879 }
880 if (!handled) {
881 if (CheckRequirements(result)) {
882 DoExecuteStatusCheck check(result);
883 DoExecute(args_string, result);
884 }
885
886 Cleanup();
887 }
888}
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)
void OutputHelpText(Stream &stream, llvm::StringRef command_word, llvm::StringRef separator, llvm::StringRef help_text, uint32_t max_word_len)
ExecutionContext GetExecutionContext(bool adopt_dummy_target=true) const
Returns the execution context the interpreter should run a command in.
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)
Target * GetTarget()
Get the target this command should operate on.
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:1256
OptionElementVector ParseForCompletion(const Args &args, uint32_t cursor_index)
Definition Options.cpp:1078
A plug-in interface definition class for debugging a process.
Definition Process.h:357
ThreadList & GetThreadList()
Definition Process.h:2380
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:3723
const lldb::ProcessSP & GetProcessSP() const
Definition Target.cpp:328
std::recursive_mutex & GetAPIMutex()
Definition Target.cpp:5959
bool IsDummyTarget() const
Definition Target.h:671
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.