xref: /llvm-project/lldb/source/Commands/CommandObjectFrame.cpp (revision 0c489f58cd948e2493bbb6ffac74a4465d91dba2)
1 //===-- CommandObjectFrame.cpp ----------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "CommandObjectFrame.h"
11 
12 // C Includes
13 // C++ Includes
14 #include <string>
15 // Other libraries and framework includes
16 // Project includes
17 #include "lldb/Core/DataVisualization.h"
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Core/StreamFile.h"
21 #include "lldb/Core/StreamString.h"
22 #include "lldb/Core/Timer.h"
23 #include "lldb/Core/Value.h"
24 #include "lldb/Core/ValueObject.h"
25 #include "lldb/Core/ValueObjectVariable.h"
26 #include "lldb/Host/Host.h"
27 #include "lldb/Interpreter/Args.h"
28 #include "lldb/Interpreter/CommandInterpreter.h"
29 #include "lldb/Interpreter/CommandReturnObject.h"
30 #include "lldb/Interpreter/Options.h"
31 #include "lldb/Interpreter/OptionGroupFormat.h"
32 #include "lldb/Interpreter/OptionGroupValueObjectDisplay.h"
33 #include "lldb/Interpreter/OptionGroupVariable.h"
34 #include "lldb/Symbol/ClangASTType.h"
35 #include "lldb/Symbol/ClangASTContext.h"
36 #include "lldb/Symbol/ObjectFile.h"
37 #include "lldb/Symbol/SymbolContext.h"
38 #include "lldb/Symbol/Type.h"
39 #include "lldb/Symbol/Variable.h"
40 #include "lldb/Symbol/VariableList.h"
41 #include "lldb/Target/Process.h"
42 #include "lldb/Target/StackFrame.h"
43 #include "lldb/Target/Thread.h"
44 #include "lldb/Target/Target.h"
45 
46 using namespace lldb;
47 using namespace lldb_private;
48 
49 #pragma mark CommandObjectFrameInfo
50 
51 //-------------------------------------------------------------------------
52 // CommandObjectFrameInfo
53 //-------------------------------------------------------------------------
54 
55 class CommandObjectFrameInfo : public CommandObject
56 {
57 public:
58 
59     CommandObjectFrameInfo (CommandInterpreter &interpreter) :
60         CommandObject (interpreter,
61                        "frame info",
62                        "List information about the currently selected frame in the current thread.",
63                        "frame info",
64                        eFlagProcessMustBeLaunched | eFlagProcessMustBePaused)
65     {
66     }
67 
68     ~CommandObjectFrameInfo ()
69     {
70     }
71 
72     bool
73     Execute (Args& command,
74              CommandReturnObject &result)
75     {
76         ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
77         StackFrame *frame = exe_ctx.GetFramePtr();
78         if (frame)
79         {
80             frame->DumpUsingSettingsFormat (&result.GetOutputStream());
81             result.SetStatus (eReturnStatusSuccessFinishResult);
82         }
83         else
84         {
85             result.AppendError ("no current frame");
86             result.SetStatus (eReturnStatusFailed);
87         }
88         return result.Succeeded();
89     }
90 };
91 
92 #pragma mark CommandObjectFrameSelect
93 
94 //-------------------------------------------------------------------------
95 // CommandObjectFrameSelect
96 //-------------------------------------------------------------------------
97 
98 class CommandObjectFrameSelect : public CommandObject
99 {
100 public:
101 
102    class CommandOptions : public Options
103     {
104     public:
105 
106         CommandOptions (CommandInterpreter &interpreter) :
107             Options(interpreter)
108         {
109             OptionParsingStarting ();
110         }
111 
112         virtual
113         ~CommandOptions ()
114         {
115         }
116 
117         virtual Error
118         SetOptionValue (uint32_t option_idx, const char *option_arg)
119         {
120             Error error;
121             bool success = false;
122             char short_option = (char) m_getopt_table[option_idx].val;
123             switch (short_option)
124             {
125             case 'r':
126                 relative_frame_offset = Args::StringToSInt32 (option_arg, INT32_MIN, 0, &success);
127                 if (!success)
128                     error.SetErrorStringWithFormat ("invalid frame offset argument '%s'", option_arg);
129                 break;
130 
131             default:
132                 error.SetErrorStringWithFormat ("invalid short option character '%c'", short_option);
133                 break;
134             }
135 
136             return error;
137         }
138 
139         void
140         OptionParsingStarting ()
141         {
142             relative_frame_offset = INT32_MIN;
143         }
144 
145         const OptionDefinition*
146         GetDefinitions ()
147         {
148             return g_option_table;
149         }
150 
151         // Options table: Required for subclasses of Options.
152 
153         static OptionDefinition g_option_table[];
154         int32_t relative_frame_offset;
155     };
156 
157     CommandObjectFrameSelect (CommandInterpreter &interpreter) :
158         CommandObject (interpreter,
159                        "frame select",
160                        "Select a frame by index from within the current thread and make it the current frame.",
161                        NULL,
162                        eFlagProcessMustBeLaunched | eFlagProcessMustBePaused),
163         m_options (interpreter)
164     {
165         CommandArgumentEntry arg;
166         CommandArgumentData index_arg;
167 
168         // Define the first (and only) variant of this arg.
169         index_arg.arg_type = eArgTypeFrameIndex;
170         index_arg.arg_repetition = eArgRepeatOptional;
171 
172         // There is only one variant this argument could be; put it into the argument entry.
173         arg.push_back (index_arg);
174 
175         // Push the data for the first argument into the m_arguments vector.
176         m_arguments.push_back (arg);
177     }
178 
179     ~CommandObjectFrameSelect ()
180     {
181     }
182 
183     virtual
184     Options *
185     GetOptions ()
186     {
187         return &m_options;
188     }
189 
190 
191     bool
192     Execute (Args& command,
193              CommandReturnObject &result)
194     {
195         ExecutionContext exe_ctx (m_interpreter.GetExecutionContext());
196         Thread *thread = exe_ctx.GetThreadPtr();
197         if (thread)
198         {
199             uint32_t frame_idx = UINT32_MAX;
200             if (m_options.relative_frame_offset != INT32_MIN)
201             {
202                 // The one and only argument is a signed relative frame index
203                 frame_idx = thread->GetSelectedFrameIndex ();
204                 if (frame_idx == UINT32_MAX)
205                     frame_idx = 0;
206 
207                 if (m_options.relative_frame_offset < 0)
208                 {
209                     if (frame_idx >= -m_options.relative_frame_offset)
210                         frame_idx += m_options.relative_frame_offset;
211                     else
212                     {
213                         if (frame_idx == 0)
214                         {
215                             //If you are already at the bottom of the stack, then just warn and don't reset the frame.
216                             result.AppendError("Already at the bottom of the stack");
217                             result.SetStatus(eReturnStatusFailed);
218                             return false;
219                         }
220                         else
221                             frame_idx = 0;
222                     }
223                 }
224                 else if (m_options.relative_frame_offset > 0)
225                 {
226                     // I don't want "up 20" where "20" takes you past the top of the stack to produce
227                     // an error, but rather to just go to the top.  So I have to count the stack here...
228                     const uint32_t num_frames = thread->GetStackFrameCount();
229                     if (num_frames - frame_idx > m_options.relative_frame_offset)
230                         frame_idx += m_options.relative_frame_offset;
231                     else
232                     {
233                         if (frame_idx == num_frames - 1)
234                         {
235                             //If we are already at the top of the stack, just warn and don't reset the frame.
236                             result.AppendError("Already at the top of the stack");
237                             result.SetStatus(eReturnStatusFailed);
238                             return false;
239                         }
240                         else
241                             frame_idx = num_frames - 1;
242                     }
243                 }
244             }
245             else
246             {
247                 if (command.GetArgumentCount() == 1)
248                 {
249                     const char *frame_idx_cstr = command.GetArgumentAtIndex(0);
250                     frame_idx = Args::StringToUInt32 (frame_idx_cstr, UINT32_MAX, 0);
251                 }
252                 else if (command.GetArgumentCount() == 0)
253                 {
254                     frame_idx = thread->GetSelectedFrameIndex ();
255                     if (frame_idx == UINT32_MAX)
256                     {
257                         frame_idx = 0;
258                     }
259                 }
260                 else
261                 {
262                     result.AppendError ("invalid arguments.\n");
263                     m_options.GenerateOptionUsage (result.GetErrorStream(), this);
264                 }
265             }
266 
267             bool success = thread->SetSelectedFrameByIndex (frame_idx);
268             if (success)
269             {
270                 exe_ctx.SetFrameSP(thread->GetSelectedFrame ());
271                 StackFrame *frame = exe_ctx.GetFramePtr();
272                 if (frame)
273                 {
274                     bool already_shown = false;
275                     SymbolContext frame_sc(frame->GetSymbolContext(eSymbolContextLineEntry));
276                     if (m_interpreter.GetDebugger().GetUseExternalEditor() && frame_sc.line_entry.file && frame_sc.line_entry.line != 0)
277                     {
278                         already_shown = Host::OpenFileInExternalEditor (frame_sc.line_entry.file, frame_sc.line_entry.line);
279                     }
280 
281                     bool show_frame_info = true;
282                     bool show_source = !already_shown;
283                     Debugger &debugger = m_interpreter.GetDebugger();
284                     const uint32_t source_lines_before = debugger.GetStopSourceLineCount(true);
285                     const uint32_t source_lines_after = debugger.GetStopSourceLineCount(false);
286                     if (frame->GetStatus (result.GetOutputStream(),
287                                           show_frame_info,
288                                           show_source,
289                                           source_lines_before,
290                                           source_lines_after))
291                     {
292                         result.SetStatus (eReturnStatusSuccessFinishResult);
293                         return result.Succeeded();
294                     }
295                 }
296             }
297             result.AppendErrorWithFormat ("Frame index (%u) out of range.\n", frame_idx);
298         }
299         else
300         {
301             result.AppendError ("no current thread");
302         }
303         result.SetStatus (eReturnStatusFailed);
304         return false;
305     }
306 protected:
307 
308     CommandOptions m_options;
309 };
310 
311 OptionDefinition
312 CommandObjectFrameSelect::CommandOptions::g_option_table[] =
313 {
314 { LLDB_OPT_SET_1, false, "relative", 'r', required_argument, NULL, 0, eArgTypeOffset, "A relative frame index offset from the current frame index."},
315 { 0, false, NULL, 0, 0, NULL, NULL, eArgTypeNone, NULL }
316 };
317 
318 #pragma mark CommandObjectFrameVariable
319 //----------------------------------------------------------------------
320 // List images with associated information
321 //----------------------------------------------------------------------
322 class CommandObjectFrameVariable : public CommandObject
323 {
324 public:
325 
326     CommandObjectFrameVariable (CommandInterpreter &interpreter) :
327         CommandObject (interpreter,
328                        "frame variable",
329                        "Show frame variables. All argument and local variables "
330                        "that are in scope will be shown when no arguments are given. "
331                        "If any arguments are specified, they can be names of "
332                        "argument, local, file static and file global variables. "
333                        "Children of aggregate variables can be specified such as "
334                        "'var->child.x'.",
335                        NULL,
336                        eFlagProcessMustBeLaunched | eFlagProcessMustBePaused),
337         m_option_group (interpreter),
338         m_option_variable(true), // Include the frame specific options by passing "true"
339         m_option_format (eFormatDefault),
340         m_varobj_options()
341     {
342         CommandArgumentEntry arg;
343         CommandArgumentData var_name_arg;
344 
345         // Define the first (and only) variant of this arg.
346         var_name_arg.arg_type = eArgTypeVarName;
347         var_name_arg.arg_repetition = eArgRepeatStar;
348 
349         // There is only one variant this argument could be; put it into the argument entry.
350         arg.push_back (var_name_arg);
351 
352         // Push the data for the first argument into the m_arguments vector.
353         m_arguments.push_back (arg);
354 
355         m_option_group.Append (&m_option_variable, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
356         m_option_group.Append (&m_option_format, OptionGroupFormat::OPTION_GROUP_FORMAT | OptionGroupFormat::OPTION_GROUP_GDB_FMT, LLDB_OPT_SET_1);
357         m_option_group.Append (&m_varobj_options, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
358         m_option_group.Finalize();
359     }
360 
361     virtual
362     ~CommandObjectFrameVariable ()
363     {
364     }
365 
366     virtual
367     Options *
368     GetOptions ()
369     {
370         return &m_option_group;
371     }
372 
373 
374     virtual bool
375     Execute
376     (
377         Args& command,
378         CommandReturnObject &result
379     )
380     {
381         ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
382         StackFrame *frame = exe_ctx.GetFramePtr();
383         if (frame == NULL)
384         {
385             result.AppendError ("you must be stopped in a valid stack frame to view frame variables.");
386             result.SetStatus (eReturnStatusFailed);
387             return false;
388         }
389 
390         Stream &s = result.GetOutputStream();
391 
392         bool get_file_globals = true;
393 
394         // Be careful about the stack frame, if any summary formatter runs code, it might clear the StackFrameList
395         // for the thread.  So hold onto a shared pointer to the frame so it stays alive.
396 
397         VariableList *variable_list = frame->GetVariableList (get_file_globals);
398 
399         VariableSP var_sp;
400         ValueObjectSP valobj_sp;
401 
402         const char *name_cstr = NULL;
403         size_t idx;
404 
405         TypeSummaryImplSP summary_format_sp;
406         if (!m_option_variable.summary.empty())
407             DataVisualization::NamedSummaryFormats::GetSummaryFormat(ConstString(m_option_variable.summary.c_str()), summary_format_sp);
408 
409         ValueObject::DumpValueObjectOptions options;
410 
411         options.SetMaximumPointerDepth(m_varobj_options.ptr_depth)
412             .SetMaximumDepth(m_varobj_options.max_depth)
413             .SetShowTypes(m_varobj_options.show_types)
414             .SetShowLocation(m_varobj_options.show_location)
415             .SetUseObjectiveC(m_varobj_options.use_objc)
416             .SetUseDynamicType(m_varobj_options.use_dynamic)
417             .SetUseSyntheticValue((lldb::SyntheticValueType)m_varobj_options.use_synth)
418             .SetFlatOutput(m_varobj_options.flat_output)
419             .SetOmitSummaryDepth(m_varobj_options.no_summary_depth)
420             .SetIgnoreCap(m_varobj_options.ignore_cap)
421             .SetSummary(summary_format_sp);
422 
423         if (m_varobj_options.be_raw)
424             options.SetRawDisplay(true);
425 
426         if (variable_list)
427         {
428             const Format format = m_option_format.GetFormat();
429             options.SetFormat(format);
430 
431             if (command.GetArgumentCount() > 0)
432             {
433                 VariableList regex_var_list;
434 
435                 // If we have any args to the variable command, we will make
436                 // variable objects from them...
437                 for (idx = 0; (name_cstr = command.GetArgumentAtIndex(idx)) != NULL; ++idx)
438                 {
439                     if (m_option_variable.use_regex)
440                     {
441                         const uint32_t regex_start_index = regex_var_list.GetSize();
442                         RegularExpression regex (name_cstr);
443                         if (regex.Compile(name_cstr))
444                         {
445                             size_t num_matches = 0;
446                             const size_t num_new_regex_vars = variable_list->AppendVariablesIfUnique(regex,
447                                                                                                      regex_var_list,
448                                                                                                      num_matches);
449                             if (num_new_regex_vars > 0)
450                             {
451                                 for (uint32_t regex_idx = regex_start_index, end_index = regex_var_list.GetSize();
452                                      regex_idx < end_index;
453                                      ++regex_idx)
454                                 {
455                                     var_sp = regex_var_list.GetVariableAtIndex (regex_idx);
456                                     if (var_sp)
457                                     {
458                                         valobj_sp = frame->GetValueObjectForFrameVariable (var_sp, m_varobj_options.use_dynamic);
459                                         if (valobj_sp)
460                                         {
461 //                                            if (format != eFormatDefault)
462 //                                                valobj_sp->SetFormat (format);
463 
464                                             if (m_option_variable.show_decl && var_sp->GetDeclaration ().GetFile())
465                                             {
466                                                 bool show_fullpaths = false;
467                                                 bool show_module = true;
468                                                 if (var_sp->DumpDeclaration(&s, show_fullpaths, show_module))
469                                                     s.PutCString (": ");
470                                             }
471                                             ValueObject::DumpValueObject (result.GetOutputStream(),
472                                                                           valobj_sp.get(),
473                                                                           options);
474                                         }
475                                     }
476                                 }
477                             }
478                             else if (num_matches == 0)
479                             {
480                                 result.GetErrorStream().Printf ("error: no variables matched the regular expression '%s'.\n", name_cstr);
481                             }
482                         }
483                         else
484                         {
485                             char regex_error[1024];
486                             if (regex.GetErrorAsCString(regex_error, sizeof(regex_error)))
487                                 result.GetErrorStream().Printf ("error: %s\n", regex_error);
488                             else
489                                 result.GetErrorStream().Printf ("error: unkown regex error when compiling '%s'\n", name_cstr);
490                         }
491                     }
492                     else // No regex, either exact variable names or variable expressions.
493                     {
494                         Error error;
495                         uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember;
496                         lldb::VariableSP var_sp;
497                         valobj_sp = frame->GetValueForVariableExpressionPath (name_cstr,
498                                                                               m_varobj_options.use_dynamic,
499                                                                               expr_path_options,
500                                                                               var_sp,
501                                                                               error);
502                         if (valobj_sp)
503                         {
504 //                            if (format != eFormatDefault)
505 //                                valobj_sp->SetFormat (format);
506                             if (m_option_variable.show_decl && var_sp && var_sp->GetDeclaration ().GetFile())
507                             {
508                                 var_sp->GetDeclaration ().DumpStopContext (&s, false);
509                                 s.PutCString (": ");
510                             }
511 
512                             options.SetFormat(format);
513 
514                             Stream &output_stream = result.GetOutputStream();
515                             options.SetRootValueObjectName(valobj_sp->GetParent() ? name_cstr : NULL);
516                             ValueObject::DumpValueObject (output_stream,
517                                                           valobj_sp.get(),
518                                                           options);
519                         }
520                         else
521                         {
522                             const char *error_cstr = error.AsCString(NULL);
523                             if (error_cstr)
524                                 result.GetErrorStream().Printf("error: %s\n", error_cstr);
525                             else
526                                 result.GetErrorStream().Printf ("error: unable to find any variable expression path that matches '%s'\n", name_cstr);
527                         }
528                     }
529                 }
530             }
531             else // No command arg specified.  Use variable_list, instead.
532             {
533                 const uint32_t num_variables = variable_list->GetSize();
534                 if (num_variables > 0)
535                 {
536                     for (uint32_t i=0; i<num_variables; i++)
537                     {
538                         var_sp = variable_list->GetVariableAtIndex(i);
539                         bool dump_variable = true;
540                         switch (var_sp->GetScope())
541                         {
542                             case eValueTypeVariableGlobal:
543                                 dump_variable = m_option_variable.show_globals;
544                                 if (dump_variable && m_option_variable.show_scope)
545                                     s.PutCString("GLOBAL: ");
546                                 break;
547 
548                             case eValueTypeVariableStatic:
549                                 dump_variable = m_option_variable.show_globals;
550                                 if (dump_variable && m_option_variable.show_scope)
551                                     s.PutCString("STATIC: ");
552                                 break;
553 
554                             case eValueTypeVariableArgument:
555                                 dump_variable = m_option_variable.show_args;
556                                 if (dump_variable && m_option_variable.show_scope)
557                                     s.PutCString("   ARG: ");
558                                 break;
559 
560                             case eValueTypeVariableLocal:
561                                 dump_variable = m_option_variable.show_locals;
562                                 if (dump_variable && m_option_variable.show_scope)
563                                     s.PutCString(" LOCAL: ");
564                                 break;
565 
566                             default:
567                                 break;
568                         }
569 
570                         if (dump_variable)
571                         {
572                             // Use the variable object code to make sure we are
573                             // using the same APIs as the the public API will be
574                             // using...
575                             valobj_sp = frame->GetValueObjectForFrameVariable (var_sp,
576                                                                                m_varobj_options.use_dynamic);
577                             if (valobj_sp)
578                             {
579 //                                if (format != eFormatDefault)
580 //                                    valobj_sp->SetFormat (format);
581 
582                                 // When dumping all variables, don't print any variables
583                                 // that are not in scope to avoid extra unneeded output
584                                 if (valobj_sp->IsInScope ())
585                                 {
586                                     if (m_option_variable.show_decl && var_sp->GetDeclaration ().GetFile())
587                                     {
588                                         var_sp->GetDeclaration ().DumpStopContext (&s, false);
589                                         s.PutCString (": ");
590                                     }
591 
592                                     options.SetFormat(format);
593                                     options.SetRootValueObjectName(name_cstr);
594                                     ValueObject::DumpValueObject (result.GetOutputStream(),
595                                                                   valobj_sp.get(),
596                                                                   options);
597                                 }
598                             }
599                         }
600                     }
601                 }
602             }
603             result.SetStatus (eReturnStatusSuccessFinishResult);
604         }
605 
606         if (m_interpreter.TruncationWarningNecessary())
607         {
608             result.GetOutputStream().Printf(m_interpreter.TruncationWarningText(),
609                                             m_cmd_name.c_str());
610             m_interpreter.TruncationWarningGiven();
611         }
612 
613         return result.Succeeded();
614     }
615 protected:
616 
617     OptionGroupOptions m_option_group;
618     OptionGroupVariable m_option_variable;
619     OptionGroupFormat m_option_format;
620     OptionGroupValueObjectDisplay m_varobj_options;
621 };
622 
623 
624 #pragma mark CommandObjectMultiwordFrame
625 
626 //-------------------------------------------------------------------------
627 // CommandObjectMultiwordFrame
628 //-------------------------------------------------------------------------
629 
630 CommandObjectMultiwordFrame::CommandObjectMultiwordFrame (CommandInterpreter &interpreter) :
631     CommandObjectMultiword (interpreter,
632                             "frame",
633                             "A set of commands for operating on the current thread's frames.",
634                             "frame <subcommand> [<subcommand-options>]")
635 {
636     LoadSubCommand ("info",   CommandObjectSP (new CommandObjectFrameInfo (interpreter)));
637     LoadSubCommand ("select", CommandObjectSP (new CommandObjectFrameSelect (interpreter)));
638     LoadSubCommand ("variable", CommandObjectSP (new CommandObjectFrameVariable (interpreter)));
639 }
640 
641 CommandObjectMultiwordFrame::~CommandObjectMultiwordFrame ()
642 {
643 }
644 
645