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
9#include "lldb/Interpreter/CommandObject.h"
10
11#include <map>
12#include <sstream>
13#include <string>
14
15#include <cctype>
16#include <cstdlib>
17
18#include "lldb/Core/Address.h"
19#include "lldb/Interpreter/CommandOptionArgumentTable.h"
20#include "lldb/Interpreter/Options.h"
21#include "lldb/Utility/ArchSpec.h"
22#include "llvm/ADT/ScopeExit.h"
23
24// These are for the Sourcename completers.
25// FIXME: Make a separate file for the completers.
26#include "lldb/DataFormatters/FormatManager.h"
27#include "lldb/Target/Process.h"
28#include "lldb/Target/Target.h"
29#include "lldb/Utility/FileSpec.h"
30#include "lldb/Utility/FileSpecList.h"
31
32#include "lldb/Target/Language.h"
33
34#include "lldb/Interpreter/CommandInterpreter.h"
35#include "lldb/Interpreter/CommandOptionArgumentTable.h"
36#include "lldb/Interpreter/CommandReturnObject.h"
37
38using namespace lldb;
39using namespace lldb_private;
40
41// CommandObject
42
43CommandObject::CommandObject(CommandInterpreter &interpreter,
44 llvm::StringRef name, llvm::StringRef help,
45 llvm::StringRef syntax, uint32_t flags)
46 : m_interpreter(interpreter), m_cmd_name(std::string(name)),
47 m_flags(flags), m_deprecated_command_override_callback(nullptr),
48 m_command_override_callback(nullptr), m_command_override_baton(nullptr) {
49 m_cmd_help_short = std::string(help);
50 m_cmd_syntax = std::string(syntax);
51}
52
53Debugger &CommandObject::GetDebugger() { return m_interpreter.GetDebugger(); }
54
55llvm::StringRef CommandObject::GetHelp() { return m_cmd_help_short; }
56
57llvm::StringRef CommandObject::GetHelpLong() { return m_cmd_help_long; }
58
59llvm::StringRef CommandObject::GetSyntax() {
60 if (!m_cmd_syntax.empty())
61 return m_cmd_syntax;
62
63 StreamString syntax_str;
64 syntax_str.PutCString(cstr: GetCommandName());
65
66 if (!IsDashDashCommand() && GetOptions() != nullptr)
67 syntax_str.PutCString(cstr: " <cmd-options>");
68
69 if (!m_arguments.empty()) {
70 syntax_str.PutCString(cstr: " ");
71
72 if (!IsDashDashCommand() && WantsRawCommandString() && GetOptions() &&
73 GetOptions()->NumCommandOptions())
74 syntax_str.PutCString(cstr: "-- ");
75 GetFormattedCommandArguments(str&: syntax_str);
76 }
77 m_cmd_syntax = std::string(syntax_str.GetString());
78
79 return m_cmd_syntax;
80}
81
82llvm::StringRef CommandObject::GetCommandName() const { return m_cmd_name; }
83
84void CommandObject::SetCommandName(llvm::StringRef name) {
85 m_cmd_name = std::string(name);
86}
87
88void CommandObject::SetHelp(llvm::StringRef str) {
89 m_cmd_help_short = std::string(str);
90}
91
92void CommandObject::SetHelpLong(llvm::StringRef str) {
93 m_cmd_help_long = std::string(str);
94}
95
96void CommandObject::SetSyntax(llvm::StringRef str) {
97 m_cmd_syntax = std::string(str);
98}
99
100Options *CommandObject::GetOptions() {
101 // By default commands don't have options unless this virtual function is
102 // overridden by base classes.
103 return nullptr;
104}
105
106bool CommandObject::ParseOptions(Args &args, CommandReturnObject &result) {
107 // See if the subclass has options?
108 Options *options = GetOptions();
109 if (options != nullptr) {
110 Status error;
111
112 auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
113 options->NotifyOptionParsingStarting(execution_context: &exe_ctx);
114
115 const bool require_validation = true;
116 llvm::Expected<Args> args_or = options->Parse(
117 args, execution_context: &exe_ctx, platform_sp: GetCommandInterpreter().GetPlatform(prefer_target_platform: true),
118 require_validation);
119
120 if (args_or) {
121 args = std::move(*args_or);
122 error = options->NotifyOptionParsingFinished(execution_context: &exe_ctx);
123 } else
124 error = args_or.takeError();
125
126 if (error.Success()) {
127 if (options->VerifyOptions(result))
128 return true;
129 } else {
130 const char *error_cstr = error.AsCString();
131 if (error_cstr) {
132 // We got an error string, lets use that
133 result.AppendError(in_string: error_cstr);
134 } else {
135 // No error string, output the usage information into result
136 options->GenerateOptionUsage(
137 strm&: result.GetErrorStream(), cmd&: *this,
138 screen_width: GetCommandInterpreter().GetDebugger().GetTerminalWidth());
139 }
140 }
141 result.SetStatus(eReturnStatusFailed);
142 return false;
143 }
144 return true;
145}
146
147bool CommandObject::CheckRequirements(CommandReturnObject &result) {
148 // Nothing should be stored in m_exe_ctx between running commands as
149 // m_exe_ctx has shared pointers to the target, process, thread and frame and
150 // we don't want any CommandObject instances to keep any of these objects
151 // around longer than for a single command. Every command should call
152 // CommandObject::Cleanup() after it has completed.
153 assert(!m_exe_ctx.GetTargetPtr());
154 assert(!m_exe_ctx.GetProcessPtr());
155 assert(!m_exe_ctx.GetThreadPtr());
156 assert(!m_exe_ctx.GetFramePtr());
157
158 // Lock down the interpreter's execution context prior to running the command
159 // so we guarantee the selected target, process, thread and frame can't go
160 // away during the execution
161 m_exe_ctx = m_interpreter.GetExecutionContext();
162
163 const uint32_t flags = GetFlags().Get();
164 if (flags & (eCommandRequiresTarget | eCommandRequiresProcess |
165 eCommandRequiresThread | eCommandRequiresFrame |
166 eCommandTryTargetAPILock)) {
167
168 if ((flags & eCommandRequiresTarget) && !m_exe_ctx.HasTargetScope()) {
169 result.AppendError(in_string: GetInvalidTargetDescription());
170 return false;
171 }
172
173 if ((flags & eCommandRequiresProcess) && !m_exe_ctx.HasProcessScope()) {
174 if (!m_exe_ctx.HasTargetScope())
175 result.AppendError(in_string: GetInvalidTargetDescription());
176 else
177 result.AppendError(in_string: GetInvalidProcessDescription());
178 return false;
179 }
180
181 if ((flags & eCommandRequiresThread) && !m_exe_ctx.HasThreadScope()) {
182 if (!m_exe_ctx.HasTargetScope())
183 result.AppendError(in_string: GetInvalidTargetDescription());
184 else if (!m_exe_ctx.HasProcessScope())
185 result.AppendError(in_string: GetInvalidProcessDescription());
186 else
187 result.AppendError(in_string: GetInvalidThreadDescription());
188 return false;
189 }
190
191 if ((flags & eCommandRequiresFrame) && !m_exe_ctx.HasFrameScope()) {
192 if (!m_exe_ctx.HasTargetScope())
193 result.AppendError(in_string: GetInvalidTargetDescription());
194 else if (!m_exe_ctx.HasProcessScope())
195 result.AppendError(in_string: GetInvalidProcessDescription());
196 else if (!m_exe_ctx.HasThreadScope())
197 result.AppendError(in_string: GetInvalidThreadDescription());
198 else
199 result.AppendError(in_string: GetInvalidFrameDescription());
200 return false;
201 }
202
203 if ((flags & eCommandRequiresRegContext) &&
204 (m_exe_ctx.GetRegisterContext() == nullptr)) {
205 result.AppendError(in_string: GetInvalidRegContextDescription());
206 return false;
207 }
208
209 if (flags & eCommandTryTargetAPILock) {
210 Target *target = m_exe_ctx.GetTargetPtr();
211 if (target)
212 m_api_locker =
213 std::unique_lock<std::recursive_mutex>(target->GetAPIMutex());
214 }
215 }
216
217 if (GetFlags().AnySet(mask: eCommandProcessMustBeLaunched |
218 eCommandProcessMustBePaused)) {
219 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
220 if (process == nullptr) {
221 // A process that is not running is considered paused.
222 if (GetFlags().Test(bit: eCommandProcessMustBeLaunched)) {
223 result.AppendError(in_string: "Process must exist.");
224 return false;
225 }
226 } else {
227 StateType state = process->GetState();
228 switch (state) {
229 case eStateInvalid:
230 case eStateSuspended:
231 case eStateCrashed:
232 case eStateStopped:
233 break;
234
235 case eStateConnected:
236 case eStateAttaching:
237 case eStateLaunching:
238 case eStateDetached:
239 case eStateExited:
240 case eStateUnloaded:
241 if (GetFlags().Test(bit: eCommandProcessMustBeLaunched)) {
242 result.AppendError(in_string: "Process must be launched.");
243 return false;
244 }
245 break;
246
247 case eStateRunning:
248 case eStateStepping:
249 if (GetFlags().Test(bit: eCommandProcessMustBePaused)) {
250 result.AppendError(in_string: "Process is running. Use 'process interrupt' to "
251 "pause execution.");
252 return false;
253 }
254 }
255 }
256 }
257
258 if (GetFlags().Test(bit: eCommandProcessMustBeTraced)) {
259 Target *target = m_exe_ctx.GetTargetPtr();
260 if (target && !target->GetTrace()) {
261 result.AppendError(in_string: "Process is not being traced.");
262 return false;
263 }
264 }
265
266 return true;
267}
268
269void CommandObject::Cleanup() {
270 m_exe_ctx.Clear();
271 if (m_api_locker.owns_lock())
272 m_api_locker.unlock();
273}
274
275void CommandObject::HandleCompletion(CompletionRequest &request) {
276
277 m_exe_ctx = m_interpreter.GetExecutionContext();
278 auto reset_ctx = llvm::make_scope_exit(F: [this]() { Cleanup(); });
279
280 // Default implementation of WantsCompletion() is !WantsRawCommandString().
281 // Subclasses who want raw command string but desire, for example, argument
282 // completion should override WantsCompletion() to return true, instead.
283 if (WantsRawCommandString() && !WantsCompletion()) {
284 // FIXME: Abstract telling the completion to insert the completion
285 // character.
286 return;
287 } else {
288 // Can we do anything generic with the options?
289 Options *cur_options = GetOptions();
290 CommandReturnObject result(m_interpreter.GetDebugger().GetUseColor());
291 OptionElementVector opt_element_vector;
292
293 if (cur_options != nullptr) {
294 opt_element_vector = cur_options->ParseForCompletion(
295 args: request.GetParsedLine(), cursor_index: request.GetCursorIndex());
296
297 bool handled_by_options = cur_options->HandleOptionCompletion(
298 request, option_map&: opt_element_vector, interpreter&: GetCommandInterpreter());
299 if (handled_by_options)
300 return;
301 }
302
303 // If we got here, the last word is not an option or an option argument.
304 HandleArgumentCompletion(request, opt_element_vector);
305 }
306}
307
308bool CommandObject::HelpTextContainsWord(llvm::StringRef search_word,
309 bool search_short_help,
310 bool search_long_help,
311 bool search_syntax,
312 bool search_options) {
313 std::string options_usage_help;
314
315 bool found_word = false;
316
317 llvm::StringRef short_help = GetHelp();
318 llvm::StringRef long_help = GetHelpLong();
319 llvm::StringRef syntax_help = GetSyntax();
320
321 if (search_short_help && short_help.contains_insensitive(Other: search_word))
322 found_word = true;
323 else if (search_long_help && long_help.contains_insensitive(Other: search_word))
324 found_word = true;
325 else if (search_syntax && syntax_help.contains_insensitive(Other: search_word))
326 found_word = true;
327
328 if (!found_word && search_options && GetOptions() != nullptr) {
329 StreamString usage_help;
330 GetOptions()->GenerateOptionUsage(
331 strm&: usage_help, cmd&: *this,
332 screen_width: GetCommandInterpreter().GetDebugger().GetTerminalWidth());
333 if (!usage_help.Empty()) {
334 llvm::StringRef usage_text = usage_help.GetString();
335 if (usage_text.contains_insensitive(Other: search_word))
336 found_word = true;
337 }
338 }
339
340 return found_word;
341}
342
343bool CommandObject::ParseOptionsAndNotify(Args &args,
344 CommandReturnObject &result,
345 OptionGroupOptions &group_options,
346 ExecutionContext &exe_ctx) {
347 if (!ParseOptions(args, result))
348 return false;
349
350 Status error(group_options.NotifyOptionParsingFinished(execution_context: &exe_ctx));
351 if (error.Fail()) {
352 result.AppendError(in_string: error.AsCString());
353 return false;
354 }
355 return true;
356}
357
358int CommandObject::GetNumArgumentEntries() { return m_arguments.size(); }
359
360CommandObject::CommandArgumentEntry *
361CommandObject::GetArgumentEntryAtIndex(int idx) {
362 if (static_cast<size_t>(idx) < m_arguments.size())
363 return &(m_arguments[idx]);
364
365 return nullptr;
366}
367
368const CommandObject::ArgumentTableEntry *
369CommandObject::FindArgumentDataByType(CommandArgumentType arg_type) {
370 for (int i = 0; i < eArgTypeLastArg; ++i)
371 if (g_argument_table[i].arg_type == arg_type)
372 return &(g_argument_table[i]);
373
374 return nullptr;
375}
376
377void CommandObject::GetArgumentHelp(Stream &str, CommandArgumentType arg_type,
378 CommandInterpreter &interpreter) {
379 const ArgumentTableEntry *entry = &(g_argument_table[arg_type]);
380
381 // The table is *supposed* to be kept in arg_type order, but someone *could*
382 // have messed it up...
383
384 if (entry->arg_type != arg_type)
385 entry = CommandObject::FindArgumentDataByType(arg_type);
386
387 if (!entry)
388 return;
389
390 StreamString name_str;
391 name_str.Printf(format: "<%s>", entry->arg_name);
392
393 if (entry->help_function) {
394 llvm::StringRef help_text = entry->help_function();
395 if (!entry->help_function.self_formatting) {
396 interpreter.OutputFormattedHelpText(stream&: str, command_word: name_str.GetString(), separator: "--",
397 help_text, max_word_len: name_str.GetSize());
398 } else {
399 interpreter.OutputHelpText(stream&: str, command_word: name_str.GetString(), separator: "--", help_text,
400 max_word_len: name_str.GetSize());
401 }
402 } else {
403 interpreter.OutputFormattedHelpText(stream&: str, command_word: name_str.GetString(), separator: "--",
404 help_text: entry->help_text, max_word_len: name_str.GetSize());
405
406 // Print enum values and their description if any.
407 OptionEnumValues enum_values = g_argument_table[arg_type].enum_values;
408 if (!enum_values.empty()) {
409 str.EOL();
410 size_t longest = 0;
411 for (const OptionEnumValueElement &element : enum_values)
412 longest =
413 std::max(a: longest, b: llvm::StringRef(element.string_value).size());
414 str.IndentMore(amount: 5);
415 for (const OptionEnumValueElement &element : enum_values) {
416 str.Indent();
417 interpreter.OutputHelpText(stream&: str, command_word: element.string_value, separator: ":",
418 help_text: element.usage, max_word_len: longest);
419 }
420 str.IndentLess(amount: 5);
421 str.EOL();
422 }
423 }
424}
425
426const char *CommandObject::GetArgumentName(CommandArgumentType arg_type) {
427 const ArgumentTableEntry *entry = &(g_argument_table[arg_type]);
428
429 // The table is *supposed* to be kept in arg_type order, but someone *could*
430 // have messed it up...
431
432 if (entry->arg_type != arg_type)
433 entry = CommandObject::FindArgumentDataByType(arg_type);
434
435 if (entry)
436 return entry->arg_name;
437
438 return nullptr;
439}
440
441bool CommandObject::IsPairType(ArgumentRepetitionType arg_repeat_type) {
442 return (arg_repeat_type == eArgRepeatPairPlain) ||
443 (arg_repeat_type == eArgRepeatPairOptional) ||
444 (arg_repeat_type == eArgRepeatPairPlus) ||
445 (arg_repeat_type == eArgRepeatPairStar) ||
446 (arg_repeat_type == eArgRepeatPairRange) ||
447 (arg_repeat_type == eArgRepeatPairRangeOptional);
448}
449
450std::optional<ArgumentRepetitionType>
451CommandObject::ArgRepetitionFromString(llvm::StringRef string) {
452 return llvm::StringSwitch<ArgumentRepetitionType>(string)
453 .Case(S: "plain", Value: eArgRepeatPlain)
454 .Case(S: "optional", Value: eArgRepeatOptional)
455 .Case(S: "plus", Value: eArgRepeatPlus)
456 .Case(S: "star", Value: eArgRepeatStar)
457 .Case(S: "range", Value: eArgRepeatRange)
458 .Case(S: "pair-plain", Value: eArgRepeatPairPlain)
459 .Case(S: "pair-optional", Value: eArgRepeatPairOptional)
460 .Case(S: "pair-plus", Value: eArgRepeatPairPlus)
461 .Case(S: "pair-star", Value: eArgRepeatPairStar)
462 .Case(S: "pair-range", Value: eArgRepeatPairRange)
463 .Case(S: "pair-range-optional", Value: eArgRepeatPairRangeOptional)
464 .Default(Value: {});
465}
466
467static CommandObject::CommandArgumentEntry
468OptSetFiltered(uint32_t opt_set_mask,
469 CommandObject::CommandArgumentEntry &cmd_arg_entry) {
470 CommandObject::CommandArgumentEntry ret_val;
471 for (unsigned i = 0; i < cmd_arg_entry.size(); ++i)
472 if (opt_set_mask & cmd_arg_entry[i].arg_opt_set_association)
473 ret_val.push_back(x: cmd_arg_entry[i]);
474 return ret_val;
475}
476
477// Default parameter value of opt_set_mask is LLDB_OPT_SET_ALL, which means
478// take all the argument data into account. On rare cases where some argument
479// sticks with certain option sets, this function returns the option set
480// filtered args.
481void CommandObject::GetFormattedCommandArguments(Stream &str,
482 uint32_t opt_set_mask) {
483 int num_args = m_arguments.size();
484 for (int i = 0; i < num_args; ++i) {
485 if (i > 0)
486 str.Printf(format: " ");
487 CommandArgumentEntry arg_entry =
488 opt_set_mask == LLDB_OPT_SET_ALL
489 ? m_arguments[i]
490 : OptSetFiltered(opt_set_mask, cmd_arg_entry&: m_arguments[i]);
491 // This argument is not associated with the current option set, so skip it.
492 if (arg_entry.empty())
493 continue;
494 int num_alternatives = arg_entry.size();
495
496 if ((num_alternatives == 2) && IsPairType(arg_repeat_type: arg_entry[0].arg_repetition)) {
497 const char *first_name = GetArgumentName(arg_type: arg_entry[0].arg_type);
498 const char *second_name = GetArgumentName(arg_type: arg_entry[1].arg_type);
499 switch (arg_entry[0].arg_repetition) {
500 case eArgRepeatPairPlain:
501 str.Printf(format: "<%s> <%s>", first_name, second_name);
502 break;
503 case eArgRepeatPairOptional:
504 str.Printf(format: "[<%s> <%s>]", first_name, second_name);
505 break;
506 case eArgRepeatPairPlus:
507 str.Printf(format: "<%s> <%s> [<%s> <%s> [...]]", first_name, second_name,
508 first_name, second_name);
509 break;
510 case eArgRepeatPairStar:
511 str.Printf(format: "[<%s> <%s> [<%s> <%s> [...]]]", first_name, second_name,
512 first_name, second_name);
513 break;
514 case eArgRepeatPairRange:
515 str.Printf(format: "<%s_1> <%s_1> ... <%s_n> <%s_n>", first_name, second_name,
516 first_name, second_name);
517 break;
518 case eArgRepeatPairRangeOptional:
519 str.Printf(format: "[<%s_1> <%s_1> ... <%s_n> <%s_n>]", first_name, second_name,
520 first_name, second_name);
521 break;
522 // Explicitly test for all the rest of the cases, so if new types get
523 // added we will notice the missing case statement(s).
524 case eArgRepeatPlain:
525 case eArgRepeatOptional:
526 case eArgRepeatPlus:
527 case eArgRepeatStar:
528 case eArgRepeatRange:
529 // These should not be reached, as they should fail the IsPairType test
530 // above.
531 break;
532 }
533 } else {
534 StreamString names;
535 for (int j = 0; j < num_alternatives; ++j) {
536 if (j > 0)
537 names.Printf(format: " | ");
538 names.Printf(format: "%s", GetArgumentName(arg_type: arg_entry[j].arg_type));
539 }
540
541 std::string name_str = std::string(names.GetString());
542 switch (arg_entry[0].arg_repetition) {
543 case eArgRepeatPlain:
544 str.Printf(format: "<%s>", name_str.c_str());
545 break;
546 case eArgRepeatPlus:
547 str.Printf(format: "<%s> [<%s> [...]]", name_str.c_str(), name_str.c_str());
548 break;
549 case eArgRepeatStar:
550 str.Printf(format: "[<%s> [<%s> [...]]]", name_str.c_str(), name_str.c_str());
551 break;
552 case eArgRepeatOptional:
553 str.Printf(format: "[<%s>]", name_str.c_str());
554 break;
555 case eArgRepeatRange:
556 str.Printf(format: "<%s_1> .. <%s_n>", name_str.c_str(), name_str.c_str());
557 break;
558 // Explicitly test for all the rest of the cases, so if new types get
559 // added we will notice the missing case statement(s).
560 case eArgRepeatPairPlain:
561 case eArgRepeatPairOptional:
562 case eArgRepeatPairPlus:
563 case eArgRepeatPairStar:
564 case eArgRepeatPairRange:
565 case eArgRepeatPairRangeOptional:
566 // These should not be hit, as they should pass the IsPairType test
567 // above, and control should have gone into the other branch of the if
568 // statement.
569 break;
570 }
571 }
572 }
573}
574
575CommandArgumentType
576CommandObject::LookupArgumentName(llvm::StringRef arg_name) {
577 CommandArgumentType return_type = eArgTypeLastArg;
578
579 arg_name = arg_name.ltrim(Char: '<').rtrim(Char: '>');
580
581 for (int i = 0; i < eArgTypeLastArg; ++i)
582 if (arg_name == g_argument_table[i].arg_name)
583 return_type = g_argument_table[i].arg_type;
584
585 return return_type;
586}
587
588void CommandObject::FormatLongHelpText(Stream &output_strm,
589 llvm::StringRef long_help) {
590 CommandInterpreter &interpreter = GetCommandInterpreter();
591 std::stringstream lineStream{std::string(long_help)};
592 std::string line;
593 while (std::getline(is&: lineStream, str&: line)) {
594 if (line.empty()) {
595 output_strm << "\n";
596 continue;
597 }
598 size_t result = line.find_first_not_of(s: " \t");
599 if (result == std::string::npos) {
600 result = 0;
601 }
602 std::string whitespace_prefix = line.substr(pos: 0, n: result);
603 std::string remainder = line.substr(pos: result);
604 interpreter.OutputFormattedHelpText(strm&: output_strm, prefix: whitespace_prefix,
605 help_text: remainder);
606 }
607}
608
609void CommandObject::GenerateHelpText(CommandReturnObject &result) {
610 GenerateHelpText(result&: result.GetOutputStream());
611
612 result.SetStatus(eReturnStatusSuccessFinishNoResult);
613}
614
615void CommandObject::GenerateHelpText(Stream &output_strm) {
616 CommandInterpreter &interpreter = GetCommandInterpreter();
617 std::string help_text(GetHelp());
618 if (WantsRawCommandString()) {
619 help_text.append(s: " Expects 'raw' input (see 'help raw-input'.)");
620 }
621 interpreter.OutputFormattedHelpText(strm&: output_strm, prefix: "", help_text);
622 output_strm << "\nSyntax: " << GetSyntax() << "\n";
623 Options *options = GetOptions();
624 if (options != nullptr) {
625 options->GenerateOptionUsage(
626 strm&: output_strm, cmd&: *this,
627 screen_width: GetCommandInterpreter().GetDebugger().GetTerminalWidth());
628 }
629 llvm::StringRef long_help = GetHelpLong();
630 if (!long_help.empty()) {
631 FormatLongHelpText(output_strm, long_help);
632 }
633 if (!IsDashDashCommand() && options && options->NumCommandOptions() > 0) {
634 if (WantsRawCommandString() && !WantsCompletion()) {
635 // Emit the message about using ' -- ' between the end of the command
636 // options and the raw input conditionally, i.e., only if the command
637 // object does not want completion.
638 interpreter.OutputFormattedHelpText(
639 stream&: output_strm, command_word: "", separator: "",
640 help_text: "\nImportant Note: Because this command takes 'raw' input, if you "
641 "use any command options"
642 " you must use ' -- ' between the end of the command options and the "
643 "beginning of the raw input.",
644 max_word_len: 1);
645 } else if (GetNumArgumentEntries() > 0) {
646 // Also emit a warning about using "--" in case you are using a command
647 // that takes options and arguments.
648 interpreter.OutputFormattedHelpText(
649 stream&: output_strm, command_word: "", separator: "",
650 help_text: "\nThis command takes options and free-form arguments. If your "
651 "arguments resemble"
652 " option specifiers (i.e., they start with a - or --), you must use "
653 "' -- ' between"
654 " the end of the command options and the beginning of the arguments.",
655 max_word_len: 1);
656 }
657 }
658}
659
660void CommandObject::AddIDsArgumentData(CommandArgumentEntry &arg,
661 CommandArgumentType ID,
662 CommandArgumentType IDRange) {
663 CommandArgumentData id_arg;
664 CommandArgumentData id_range_arg;
665
666 // Create the first variant for the first (and only) argument for this
667 // command.
668 id_arg.arg_type = ID;
669 id_arg.arg_repetition = eArgRepeatOptional;
670
671 // Create the second variant for the first (and only) argument for this
672 // command.
673 id_range_arg.arg_type = IDRange;
674 id_range_arg.arg_repetition = eArgRepeatOptional;
675
676 // The first (and only) argument for this command could be either an id or an
677 // id_range. Push both variants into the entry for the first argument for
678 // this command.
679 arg.push_back(x: id_arg);
680 arg.push_back(x: id_range_arg);
681}
682
683const char *CommandObject::GetArgumentTypeAsCString(
684 const lldb::CommandArgumentType arg_type) {
685 assert(arg_type < eArgTypeLastArg &&
686 "Invalid argument type passed to GetArgumentTypeAsCString");
687 return g_argument_table[arg_type].arg_name;
688}
689
690const char *CommandObject::GetArgumentDescriptionAsCString(
691 const lldb::CommandArgumentType arg_type) {
692 assert(arg_type < eArgTypeLastArg &&
693 "Invalid argument type passed to GetArgumentDescriptionAsCString");
694 return g_argument_table[arg_type].help_text;
695}
696
697Target &CommandObject::GetDummyTarget() {
698 return m_interpreter.GetDebugger().GetDummyTarget();
699}
700
701Target &CommandObject::GetSelectedOrDummyTarget(bool prefer_dummy) {
702 return m_interpreter.GetDebugger().GetSelectedOrDummyTarget(prefer_dummy);
703}
704
705Target &CommandObject::GetSelectedTarget() {
706 assert(m_flags.AnySet(eCommandRequiresTarget | eCommandProcessMustBePaused |
707 eCommandProcessMustBeLaunched | eCommandRequiresFrame |
708 eCommandRequiresThread | eCommandRequiresProcess |
709 eCommandRequiresRegContext) &&
710 "GetSelectedTarget called from object that may have no target");
711 return *m_interpreter.GetDebugger().GetSelectedTarget();
712}
713
714Thread *CommandObject::GetDefaultThread() {
715 Thread *thread_to_use = m_exe_ctx.GetThreadPtr();
716 if (thread_to_use)
717 return thread_to_use;
718
719 Process *process = m_exe_ctx.GetProcessPtr();
720 if (!process) {
721 Target *target = m_exe_ctx.GetTargetPtr();
722 if (!target) {
723 target = m_interpreter.GetDebugger().GetSelectedTarget().get();
724 }
725 if (target)
726 process = target->GetProcessSP().get();
727 }
728
729 if (process)
730 return process->GetThreadList().GetSelectedThread().get();
731 else
732 return nullptr;
733}
734
735void CommandObjectParsed::Execute(const char *args_string,
736 CommandReturnObject &result) {
737 bool handled = false;
738 Args cmd_args(args_string);
739 if (HasOverrideCallback()) {
740 Args full_args(GetCommandName());
741 full_args.AppendArguments(rhs: cmd_args);
742 handled =
743 InvokeOverrideCallback(argv: full_args.GetConstArgumentVector(), result);
744 }
745 if (!handled) {
746 for (auto entry : llvm::enumerate(First: cmd_args.entries())) {
747 const Args::ArgEntry &value = entry.value();
748 if (!value.ref().empty() && value.GetQuoteChar() == '`') {
749 // We have to put the backtick back in place for PreprocessCommand.
750 std::string opt_string = value.c_str();
751 Status error;
752 error = m_interpreter.PreprocessToken(token&: opt_string);
753 if (error.Success())
754 cmd_args.ReplaceArgumentAtIndex(idx: entry.index(), arg_str: opt_string);
755 }
756 }
757
758 if (CheckRequirements(result)) {
759 if (ParseOptions(args&: cmd_args, result)) {
760 // Call the command-specific version of 'Execute', passing it the
761 // already processed arguments.
762 if (cmd_args.GetArgumentCount() != 0 && m_arguments.empty()) {
763 result.AppendErrorWithFormatv(format: "'{0}' doesn't take any arguments.",
764 args: GetCommandName());
765 Cleanup();
766 return;
767 }
768 m_interpreter.IncreaseCommandUsage(cmd_obj: *this);
769 DoExecute(command&: cmd_args, result);
770 }
771 }
772
773 Cleanup();
774 }
775}
776
777void CommandObjectRaw::Execute(const char *args_string,
778 CommandReturnObject &result) {
779 bool handled = false;
780 if (HasOverrideCallback()) {
781 std::string full_command(GetCommandName());
782 full_command += ' ';
783 full_command += args_string;
784 const char *argv[2] = {nullptr, nullptr};
785 argv[0] = full_command.c_str();
786 handled = InvokeOverrideCallback(argv, result);
787 }
788 if (!handled) {
789 if (CheckRequirements(result))
790 DoExecute(command: args_string, result);
791
792 Cleanup();
793 }
794}
795

source code of lldb/source/Interpreter/CommandObject.cpp