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