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