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