1 //===-- CommandObjectFrame.cpp ----------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 // Other libraries and framework includes
16 #include "CommandObjectFrame.h"
17 #include "lldb/Core/Debugger.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/StreamFile.h"
20 #include "lldb/Core/StreamString.h"
21 #include "lldb/Core/Timer.h"
22 #include "lldb/Core/Value.h"
23 #include "lldb/Core/ValueObject.h"
24 #include "lldb/Core/ValueObjectVariable.h"
25 #include "lldb/DataFormatters/DataVisualization.h"
26 #include "lldb/DataFormatters/ValueObjectPrinter.h"
27 #include "lldb/Host/Host.h"
28 #include "lldb/Host/StringConvert.h"
29 #include "lldb/Interpreter/Args.h"
30 #include "lldb/Interpreter/CommandInterpreter.h"
31 #include "lldb/Interpreter/CommandReturnObject.h"
32 #include "lldb/Interpreter/OptionGroupFormat.h"
33 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
34 #include "lldb/Interpreter/OptionGroupVariable.h"
35 #include "lldb/Interpreter/Options.h"
36 #include "lldb/Symbol/ClangASTContext.h"
37 #include "lldb/Symbol/CompilerType.h"
38 #include "lldb/Symbol/Function.h"
39 #include "lldb/Symbol/ObjectFile.h"
40 #include "lldb/Symbol/SymbolContext.h"
41 #include "lldb/Symbol/Type.h"
42 #include "lldb/Symbol/Variable.h"
43 #include "lldb/Symbol/VariableList.h"
44 #include "lldb/Target/Process.h"
45 #include "lldb/Target/StackFrame.h"
46 #include "lldb/Target/StopInfo.h"
47 #include "lldb/Target/Target.h"
48 #include "lldb/Target/Thread.h"
49 #include "lldb/Utility/LLDBAssert.h"
52 using namespace lldb_private;
54 #pragma mark CommandObjectFrameDiagnose
56 //-------------------------------------------------------------------------
57 // CommandObjectFrameInfo
58 //-------------------------------------------------------------------------
60 //-------------------------------------------------------------------------
61 // CommandObjectFrameDiagnose
62 //-------------------------------------------------------------------------
64 static OptionDefinition g_frame_diag_options[] = {
66 { LLDB_OPT_SET_1, false, "register", 'r', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeRegisterName, "A register to diagnose." },
67 { LLDB_OPT_SET_1, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddress, "An address to diagnose." },
68 { LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "An optional offset. Requires --register." }
72 class CommandObjectFrameDiagnose : public CommandObjectParsed {
74 class CommandOptions : public Options {
76 CommandOptions() : Options() { OptionParsingStarting(nullptr); }
78 ~CommandOptions() override = default;
80 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
81 ExecutionContext *execution_context) override {
83 const int short_option = m_getopt_table[option_idx].val;
84 switch (short_option) {
86 reg = ConstString(option_arg);
91 if (option_arg.getAsInteger(0, *address)) {
93 error.SetErrorStringWithFormat("invalid address argument '%s'",
94 option_arg.str().c_str());
100 if (option_arg.getAsInteger(0, *offset)) {
102 error.SetErrorStringWithFormat("invalid offset argument '%s'",
103 option_arg.str().c_str());
108 error.SetErrorStringWithFormat("invalid short option character '%c'",
116 void OptionParsingStarting(ExecutionContext *execution_context) override {
122 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
123 return llvm::makeArrayRef(g_frame_diag_options);
127 llvm::Optional<lldb::addr_t> address;
128 llvm::Optional<ConstString> reg;
129 llvm::Optional<int64_t> offset;
132 CommandObjectFrameDiagnose(CommandInterpreter &interpreter)
133 : CommandObjectParsed(interpreter, "frame diagnose",
134 "Try to determine what path path the current stop "
135 "location used to get to a register or address",
137 eCommandRequiresThread | eCommandTryTargetAPILock |
138 eCommandProcessMustBeLaunched |
139 eCommandProcessMustBePaused),
141 CommandArgumentEntry arg;
142 CommandArgumentData index_arg;
144 // Define the first (and only) variant of this arg.
145 index_arg.arg_type = eArgTypeFrameIndex;
146 index_arg.arg_repetition = eArgRepeatOptional;
148 // There is only one variant this argument could be; put it into the
150 arg.push_back(index_arg);
152 // Push the data for the first argument into the m_arguments vector.
153 m_arguments.push_back(arg);
156 ~CommandObjectFrameDiagnose() override = default;
158 Options *GetOptions() override { return &m_options; }
161 bool DoExecute(Args &command, CommandReturnObject &result) override {
162 Thread *thread = m_exe_ctx.GetThreadPtr();
163 StackFrameSP frame_sp = thread->GetSelectedFrame();
165 ValueObjectSP valobj_sp;
167 if (m_options.address.hasValue()) {
168 if (m_options.reg.hasValue() || m_options.offset.hasValue()) {
170 "`frame diagnose --address` is incompatible with other arguments.");
171 result.SetStatus(eReturnStatusFailed);
174 valobj_sp = frame_sp->GuessValueForAddress(m_options.address.getValue());
175 } else if (m_options.reg.hasValue()) {
176 valobj_sp = frame_sp->GuessValueForRegisterAndOffset(
177 m_options.reg.getValue(), m_options.offset.getValueOr(0));
179 StopInfoSP stop_info_sp = thread->GetStopInfo();
181 result.AppendError("No arguments provided, and no stop info.");
182 result.SetStatus(eReturnStatusFailed);
186 valobj_sp = StopInfo::GetCrashingDereference(stop_info_sp);
190 result.AppendError("No diagnosis available.");
191 result.SetStatus(eReturnStatusFailed);
195 const bool qualify_cxx_base_classes = false;
197 DumpValueObjectOptions::DeclPrintingHelper helper =
198 [&valobj_sp, qualify_cxx_base_classes](
199 ConstString type, ConstString var,
200 const DumpValueObjectOptions &opts, Stream &stream) -> bool {
201 const ValueObject::GetExpressionPathFormat format = ValueObject::
202 GetExpressionPathFormat::eGetExpressionPathFormatHonorPointers;
203 valobj_sp->GetExpressionPath(stream, qualify_cxx_base_classes, format);
204 stream.PutCString(" =");
208 DumpValueObjectOptions options;
209 options.SetDeclPrintingHelper(helper);
210 ValueObjectPrinter printer(valobj_sp.get(), &result.GetOutputStream(),
212 printer.PrintValueObject();
218 CommandOptions m_options;
221 #pragma mark CommandObjectFrameInfo
223 //-------------------------------------------------------------------------
224 // CommandObjectFrameInfo
225 //-------------------------------------------------------------------------
227 class CommandObjectFrameInfo : public CommandObjectParsed {
229 CommandObjectFrameInfo(CommandInterpreter &interpreter)
230 : CommandObjectParsed(
231 interpreter, "frame info", "List information about the current "
232 "stack frame in the current thread.",
234 eCommandRequiresFrame | eCommandTryTargetAPILock |
235 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
237 ~CommandObjectFrameInfo() override = default;
240 bool DoExecute(Args &command, CommandReturnObject &result) override {
241 m_exe_ctx.GetFrameRef().DumpUsingSettingsFormat(&result.GetOutputStream());
242 result.SetStatus(eReturnStatusSuccessFinishResult);
243 return result.Succeeded();
247 #pragma mark CommandObjectFrameSelect
249 //-------------------------------------------------------------------------
250 // CommandObjectFrameSelect
251 //-------------------------------------------------------------------------
253 static OptionDefinition g_frame_select_options[] = {
255 { LLDB_OPT_SET_1, false, "relative", 'r', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset, "A relative frame index offset from the current frame index." },
259 class CommandObjectFrameSelect : public CommandObjectParsed {
261 class CommandOptions : public Options {
263 CommandOptions() : Options() { OptionParsingStarting(nullptr); }
265 ~CommandOptions() override = default;
267 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
268 ExecutionContext *execution_context) override {
270 const int short_option = m_getopt_table[option_idx].val;
271 switch (short_option) {
273 if (option_arg.getAsInteger(0, relative_frame_offset)) {
274 relative_frame_offset = INT32_MIN;
275 error.SetErrorStringWithFormat("invalid frame offset argument '%s'",
276 option_arg.str().c_str());
281 error.SetErrorStringWithFormat("invalid short option character '%c'",
289 void OptionParsingStarting(ExecutionContext *execution_context) override {
290 relative_frame_offset = INT32_MIN;
293 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
294 return llvm::makeArrayRef(g_frame_select_options);
297 int32_t relative_frame_offset;
300 CommandObjectFrameSelect(CommandInterpreter &interpreter)
301 : CommandObjectParsed(
302 interpreter, "frame select", "Select the current stack frame by "
303 "index from within the current thread "
304 "(see 'thread backtrace'.)",
306 eCommandRequiresThread | eCommandTryTargetAPILock |
307 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
309 CommandArgumentEntry arg;
310 CommandArgumentData index_arg;
312 // Define the first (and only) variant of this arg.
313 index_arg.arg_type = eArgTypeFrameIndex;
314 index_arg.arg_repetition = eArgRepeatOptional;
316 // There is only one variant this argument could be; put it into the
318 arg.push_back(index_arg);
320 // Push the data for the first argument into the m_arguments vector.
321 m_arguments.push_back(arg);
324 ~CommandObjectFrameSelect() override = default;
326 Options *GetOptions() override { return &m_options; }
329 bool DoExecute(Args &command, CommandReturnObject &result) override {
330 // No need to check "thread" for validity as eCommandRequiresThread ensures
332 Thread *thread = m_exe_ctx.GetThreadPtr();
334 uint32_t frame_idx = UINT32_MAX;
335 if (m_options.relative_frame_offset != INT32_MIN) {
336 // The one and only argument is a signed relative frame index
337 frame_idx = thread->GetSelectedFrameIndex();
338 if (frame_idx == UINT32_MAX)
341 if (m_options.relative_frame_offset < 0) {
342 if (static_cast<int32_t>(frame_idx) >= -m_options.relative_frame_offset)
343 frame_idx += m_options.relative_frame_offset;
345 if (frame_idx == 0) {
346 // If you are already at the bottom of the stack, then just warn and
347 // don't reset the frame.
348 result.AppendError("Already at the bottom of the stack.");
349 result.SetStatus(eReturnStatusFailed);
354 } else if (m_options.relative_frame_offset > 0) {
355 // I don't want "up 20" where "20" takes you past the top of the stack
357 // an error, but rather to just go to the top. So I have to count the
359 const uint32_t num_frames = thread->GetStackFrameCount();
360 if (static_cast<int32_t>(num_frames - frame_idx) >
361 m_options.relative_frame_offset)
362 frame_idx += m_options.relative_frame_offset;
364 if (frame_idx == num_frames - 1) {
365 // If we are already at the top of the stack, just warn and don't
367 result.AppendError("Already at the top of the stack.");
368 result.SetStatus(eReturnStatusFailed);
371 frame_idx = num_frames - 1;
375 if (command.GetArgumentCount() > 1) {
376 result.AppendErrorWithFormat(
377 "too many arguments; expected frame-index, saw '%s'.\n",
379 m_options.GenerateOptionUsage(
380 result.GetErrorStream(), this,
381 GetCommandInterpreter().GetDebugger().GetTerminalWidth());
385 if (command.GetArgumentCount() == 1) {
386 if (command[0].ref.getAsInteger(0, frame_idx)) {
387 result.AppendErrorWithFormat("invalid frame index argument '%s'.",
389 result.SetStatus(eReturnStatusFailed);
392 } else if (command.GetArgumentCount() == 0) {
393 frame_idx = thread->GetSelectedFrameIndex();
394 if (frame_idx == UINT32_MAX) {
400 bool success = thread->SetSelectedFrameByIndexNoisily(
401 frame_idx, result.GetOutputStream());
403 m_exe_ctx.SetFrameSP(thread->GetSelectedFrame());
404 result.SetStatus(eReturnStatusSuccessFinishResult);
406 result.AppendErrorWithFormat("Frame index (%u) out of range.\n",
408 result.SetStatus(eReturnStatusFailed);
411 return result.Succeeded();
415 CommandOptions m_options;
418 #pragma mark CommandObjectFrameVariable
419 //----------------------------------------------------------------------
420 // List images with associated information
421 //----------------------------------------------------------------------
422 class CommandObjectFrameVariable : public CommandObjectParsed {
424 CommandObjectFrameVariable(CommandInterpreter &interpreter)
425 : CommandObjectParsed(
426 interpreter, "frame variable",
427 "Show variables for the current stack frame. Defaults to all "
428 "arguments and local variables in scope. Names of argument, "
429 "local, file static and file global variables can be specified. "
430 "Children of aggregate variables can be specified such as "
432 nullptr, eCommandRequiresFrame | eCommandTryTargetAPILock |
433 eCommandProcessMustBeLaunched |
434 eCommandProcessMustBePaused | eCommandRequiresProcess),
437 true), // Include the frame specific options by passing "true"
438 m_option_format(eFormatDefault),
440 CommandArgumentEntry arg;
441 CommandArgumentData var_name_arg;
443 // Define the first (and only) variant of this arg.
444 var_name_arg.arg_type = eArgTypeVarName;
445 var_name_arg.arg_repetition = eArgRepeatStar;
447 // There is only one variant this argument could be; put it into the
449 arg.push_back(var_name_arg);
451 // Push the data for the first argument into the m_arguments vector.
452 m_arguments.push_back(arg);
454 m_option_group.Append(&m_option_variable, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
455 m_option_group.Append(&m_option_format,
456 OptionGroupFormat::OPTION_GROUP_FORMAT |
457 OptionGroupFormat::OPTION_GROUP_GDB_FMT,
459 m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
460 m_option_group.Finalize();
463 ~CommandObjectFrameVariable() override = default;
465 Options *GetOptions() override { return &m_option_group; }
467 int HandleArgumentCompletion(Args &input, int &cursor_index,
468 int &cursor_char_position,
469 OptionElementVector &opt_element_vector,
470 int match_start_point, int max_return_elements,
472 StringList &matches) override {
473 // Arguments are the standard source file completer.
474 auto completion_str = input[cursor_index].ref;
475 completion_str = completion_str.take_front(cursor_char_position);
477 CommandCompletions::InvokeCommonCompletionCallbacks(
478 GetCommandInterpreter(), CommandCompletions::eVariablePathCompletion,
479 completion_str, match_start_point, max_return_elements, nullptr,
480 word_complete, matches);
481 return matches.GetSize();
485 llvm::StringRef GetScopeString(VariableSP var_sp) {
487 return llvm::StringRef::withNullAsEmpty(nullptr);
489 switch (var_sp->GetScope()) {
490 case eValueTypeVariableGlobal:
492 case eValueTypeVariableStatic:
494 case eValueTypeVariableArgument:
496 case eValueTypeVariableLocal:
498 case eValueTypeVariableThreadLocal:
504 return llvm::StringRef::withNullAsEmpty(nullptr);
507 bool DoExecute(Args &command, CommandReturnObject &result) override {
508 // No need to check "frame" for validity as eCommandRequiresFrame ensures it
510 StackFrame *frame = m_exe_ctx.GetFramePtr();
512 Stream &s = result.GetOutputStream();
514 // Be careful about the stack frame, if any summary formatter runs code, it
515 // might clear the StackFrameList
516 // for the thread. So hold onto a shared pointer to the frame so it stays
519 VariableList *variable_list =
520 frame->GetVariableList(m_option_variable.show_globals);
523 ValueObjectSP valobj_sp;
525 TypeSummaryImplSP summary_format_sp;
526 if (!m_option_variable.summary.IsCurrentValueEmpty())
527 DataVisualization::NamedSummaryFormats::GetSummaryFormat(
528 ConstString(m_option_variable.summary.GetCurrentValue()),
530 else if (!m_option_variable.summary_string.IsCurrentValueEmpty())
531 summary_format_sp.reset(new StringSummaryFormat(
532 TypeSummaryImpl::Flags(),
533 m_option_variable.summary_string.GetCurrentValue()));
535 DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
536 eLanguageRuntimeDescriptionDisplayVerbosityFull, eFormatDefault,
539 const SymbolContext &sym_ctx =
540 frame->GetSymbolContext(eSymbolContextFunction);
541 if (sym_ctx.function && sym_ctx.function->IsTopLevelFunction())
542 m_option_variable.show_globals = true;
545 const Format format = m_option_format.GetFormat();
546 options.SetFormat(format);
548 if (!command.empty()) {
549 VariableList regex_var_list;
551 // If we have any args to the variable command, we will make
552 // variable objects from them...
553 for (auto &entry : command) {
554 if (m_option_variable.use_regex) {
555 const size_t regex_start_index = regex_var_list.GetSize();
556 llvm::StringRef name_str = entry.ref;
557 RegularExpression regex(name_str);
558 if (regex.Compile(name_str)) {
559 size_t num_matches = 0;
560 const size_t num_new_regex_vars =
561 variable_list->AppendVariablesIfUnique(regex, regex_var_list,
563 if (num_new_regex_vars > 0) {
564 for (size_t regex_idx = regex_start_index,
565 end_index = regex_var_list.GetSize();
566 regex_idx < end_index; ++regex_idx) {
567 var_sp = regex_var_list.GetVariableAtIndex(regex_idx);
569 valobj_sp = frame->GetValueObjectForFrameVariable(
570 var_sp, m_varobj_options.use_dynamic);
572 std::string scope_string;
573 if (m_option_variable.show_scope)
574 scope_string = GetScopeString(var_sp).str();
576 if (!scope_string.empty())
577 s.PutCString(scope_string);
579 if (m_option_variable.show_decl &&
580 var_sp->GetDeclaration().GetFile()) {
581 bool show_fullpaths = false;
582 bool show_module = true;
583 if (var_sp->DumpDeclaration(&s, show_fullpaths,
587 valobj_sp->Dump(result.GetOutputStream(), options);
591 } else if (num_matches == 0) {
592 result.GetErrorStream().Printf("error: no variables matched "
593 "the regular expression '%s'.\n",
597 char regex_error[1024];
598 if (regex.GetErrorAsCString(regex_error, sizeof(regex_error)))
599 result.GetErrorStream().Printf("error: %s\n", regex_error);
601 result.GetErrorStream().Printf(
602 "error: unknown regex error when compiling '%s'\n",
605 } else // No regex, either exact variable names or variable
609 uint32_t expr_path_options =
610 StackFrame::eExpressionPathOptionCheckPtrVsMember |
611 StackFrame::eExpressionPathOptionsAllowDirectIVarAccess |
612 StackFrame::eExpressionPathOptionsInspectAnonymousUnions;
613 lldb::VariableSP var_sp;
614 valobj_sp = frame->GetValueForVariableExpressionPath(
615 entry.ref, m_varobj_options.use_dynamic, expr_path_options,
618 std::string scope_string;
619 if (m_option_variable.show_scope)
620 scope_string = GetScopeString(var_sp).str();
622 if (!scope_string.empty())
623 s.PutCString(scope_string);
625 // if (format != eFormatDefault)
626 // valobj_sp->SetFormat (format);
627 if (m_option_variable.show_decl && var_sp &&
628 var_sp->GetDeclaration().GetFile()) {
629 var_sp->GetDeclaration().DumpStopContext(&s, false);
633 options.SetFormat(format);
634 options.SetVariableFormatDisplayLanguage(
635 valobj_sp->GetPreferredDisplayLanguage());
637 Stream &output_stream = result.GetOutputStream();
638 options.SetRootValueObjectName(
639 valobj_sp->GetParent() ? entry.c_str() : nullptr);
640 valobj_sp->Dump(output_stream, options);
642 const char *error_cstr = error.AsCString(nullptr);
644 result.GetErrorStream().Printf("error: %s\n", error_cstr);
646 result.GetErrorStream().Printf("error: unable to find any "
647 "variable expression path that "
653 } else // No command arg specified. Use variable_list, instead.
655 const size_t num_variables = variable_list->GetSize();
656 if (num_variables > 0) {
657 for (size_t i = 0; i < num_variables; i++) {
658 var_sp = variable_list->GetVariableAtIndex(i);
659 bool dump_variable = true;
660 std::string scope_string;
661 if (dump_variable && m_option_variable.show_scope)
662 scope_string = GetScopeString(var_sp).str();
665 // Use the variable object code to make sure we are
666 // using the same APIs as the public API will be
668 valobj_sp = frame->GetValueObjectForFrameVariable(
669 var_sp, m_varobj_options.use_dynamic);
671 // When dumping all variables, don't print any variables
672 // that are not in scope to avoid extra unneeded output
673 if (valobj_sp->IsInScope()) {
674 if (!valobj_sp->GetTargetSP()
675 ->GetDisplayRuntimeSupportValues() &&
676 valobj_sp->IsRuntimeSupportValue())
679 if (!scope_string.empty())
680 s.PutCString(scope_string);
682 if (m_option_variable.show_decl &&
683 var_sp->GetDeclaration().GetFile()) {
684 var_sp->GetDeclaration().DumpStopContext(&s, false);
688 options.SetFormat(format);
689 options.SetVariableFormatDisplayLanguage(
690 valobj_sp->GetPreferredDisplayLanguage());
691 options.SetRootValueObjectName(
692 var_sp ? var_sp->GetName().AsCString() : nullptr);
693 valobj_sp->Dump(result.GetOutputStream(), options);
700 result.SetStatus(eReturnStatusSuccessFinishResult);
703 if (m_interpreter.TruncationWarningNecessary()) {
704 result.GetOutputStream().Printf(m_interpreter.TruncationWarningText(),
706 m_interpreter.TruncationWarningGiven();
709 return result.Succeeded();
713 OptionGroupOptions m_option_group;
714 OptionGroupVariable m_option_variable;
715 OptionGroupFormat m_option_format;
716 OptionGroupValueObjectDisplay m_varobj_options;
719 #pragma mark CommandObjectMultiwordFrame
721 //-------------------------------------------------------------------------
722 // CommandObjectMultiwordFrame
723 //-------------------------------------------------------------------------
725 CommandObjectMultiwordFrame::CommandObjectMultiwordFrame(
726 CommandInterpreter &interpreter)
727 : CommandObjectMultiword(interpreter, "frame", "Commands for selecting and "
728 "examing the current "
729 "thread's stack frames.",
730 "frame <subcommand> [<subcommand-options>]") {
731 LoadSubCommand("diagnose",
732 CommandObjectSP(new CommandObjectFrameDiagnose(interpreter)));
733 LoadSubCommand("info",
734 CommandObjectSP(new CommandObjectFrameInfo(interpreter)));
735 LoadSubCommand("select",
736 CommandObjectSP(new CommandObjectFrameSelect(interpreter)));
737 LoadSubCommand("variable",
738 CommandObjectSP(new CommandObjectFrameVariable(interpreter)));
741 CommandObjectMultiwordFrame::~CommandObjectMultiwordFrame() = default;