1 //===-- CommandObjectExpression.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 "CommandObjectExpression.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 #include "lldb/Interpreter/Args.h"
17 #include "lldb/Core/Value.h"
18 #include "lldb/Core/InputReader.h"
19 #include "lldb/Core/ValueObjectVariable.h"
20 #include "lldb/Expression/ClangExpressionVariable.h"
21 #include "lldb/Expression/ClangUserExpression.h"
22 #include "lldb/Expression/ClangFunction.h"
23 #include "lldb/Expression/DWARFExpression.h"
24 #include "lldb/Host/Host.h"
25 #include "lldb/Core/Debugger.h"
26 #include "lldb/Interpreter/CommandInterpreter.h"
27 #include "lldb/Interpreter/CommandReturnObject.h"
28 #include "lldb/Target/ObjCLanguageRuntime.h"
29 #include "lldb/Symbol/ObjectFile.h"
30 #include "lldb/Symbol/Variable.h"
31 #include "lldb/Target/Process.h"
32 #include "lldb/Target/StackFrame.h"
33 #include "lldb/Target/Target.h"
34 #include "lldb/Target/Thread.h"
35 #include "llvm/ADT/StringRef.h"
36 
37 using namespace lldb;
38 using namespace lldb_private;
39 
40 CommandObjectExpression::CommandOptions::CommandOptions (CommandInterpreter &interpreter) :
41     Options(interpreter)
42 {
43     // Keep only one place to reset the values to their defaults
44     OptionParsingStarting();
45 }
46 
47 
48 CommandObjectExpression::CommandOptions::~CommandOptions ()
49 {
50 }
51 
52 Error
53 CommandObjectExpression::CommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
54 {
55     Error error;
56 
57     char short_option = (char) m_getopt_table[option_idx].val;
58 
59     switch (short_option)
60     {
61       //case 'l':
62       //if (language.SetLanguageFromCString (option_arg) == false)
63       //{
64       //    error.SetErrorStringWithFormat("Invalid language option argument '%s'.\n", option_arg);
65       //}
66       //break;
67 
68     case 'g':
69         debug = true;
70         break;
71 
72     case 'f':
73         error = Args::StringToFormat(option_arg, format, NULL);
74         break;
75 
76     case 'o':
77         print_object = true;
78         break;
79 
80     case 'd':
81         {
82             bool success;
83             bool result;
84             result = Args::StringToBoolean(option_arg, true, &success);
85             if (!success)
86                 error.SetErrorStringWithFormat("Invalid dynamic value setting: \"%s\".\n", option_arg);
87             else
88             {
89                 if (result)
90                     use_dynamic = eLazyBoolYes;
91                 else
92                     use_dynamic = eLazyBoolNo;
93             }
94         }
95         break;
96 
97     case 'u':
98         {
99             bool success;
100             unwind_on_error = Args::StringToBoolean(option_arg, true, &success);
101             if (!success)
102                 error.SetErrorStringWithFormat("Could not convert \"%s\" to a boolean value.", option_arg);
103             break;
104         }
105     default:
106         error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
107         break;
108     }
109 
110     return error;
111 }
112 
113 void
114 CommandObjectExpression::CommandOptions::OptionParsingStarting ()
115 {
116     //language.Clear();
117     debug = false;
118     format = eFormatDefault;
119     print_object = false;
120     use_dynamic = eLazyBoolCalculate;
121     unwind_on_error = true;
122     show_types = true;
123     show_summary = true;
124 }
125 
126 const OptionDefinition*
127 CommandObjectExpression::CommandOptions::GetDefinitions ()
128 {
129     return g_option_table;
130 }
131 
132 CommandObjectExpression::CommandObjectExpression (CommandInterpreter &interpreter) :
133     CommandObject (interpreter,
134                    "expression",
135                    "Evaluate a C/ObjC/C++ expression in the current program context, using variables currently in scope.",
136                    NULL),
137     m_options (interpreter),
138     m_expr_line_count (0),
139     m_expr_lines ()
140 {
141   SetHelpLong(
142 "Examples: \n\
143 \n\
144    expr my_struct->a = my_array[3] \n\
145    expr -f bin -- (index * 8) + 5 \n\
146    expr char c[] = \"foo\"; c[0]\n");
147 
148     CommandArgumentEntry arg;
149     CommandArgumentData expression_arg;
150 
151     // Define the first (and only) variant of this arg.
152     expression_arg.arg_type = eArgTypeExpression;
153     expression_arg.arg_repetition = eArgRepeatPlain;
154 
155     // There is only one variant this argument could be; put it into the argument entry.
156     arg.push_back (expression_arg);
157 
158     // Push the data for the first argument into the m_arguments vector.
159     m_arguments.push_back (arg);
160 }
161 
162 CommandObjectExpression::~CommandObjectExpression ()
163 {
164 }
165 
166 Options *
167 CommandObjectExpression::GetOptions ()
168 {
169     return &m_options;
170 }
171 
172 
173 bool
174 CommandObjectExpression::Execute
175 (
176     Args& command,
177     CommandReturnObject &result
178 )
179 {
180     return false;
181 }
182 
183 
184 size_t
185 CommandObjectExpression::MultiLineExpressionCallback
186 (
187     void *baton,
188     InputReader &reader,
189     lldb::InputReaderAction notification,
190     const char *bytes,
191     size_t bytes_len
192 )
193 {
194     CommandObjectExpression *cmd_object_expr = (CommandObjectExpression *) baton;
195     bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
196 
197     switch (notification)
198     {
199     case eInputReaderActivate:
200         if (!batch_mode)
201         {
202             StreamSP async_strm_sp(reader.GetDebugger().GetAsyncOutputStream());
203             if (async_strm_sp)
204             {
205                 async_strm_sp->PutCString("Enter expressions, then terminate with an empty line to evaluate:\n");
206                 async_strm_sp->Flush();
207             }
208         }
209         // Fall through
210     case eInputReaderReactivate:
211         break;
212 
213     case eInputReaderDeactivate:
214         break;
215 
216     case eInputReaderAsynchronousOutputWritten:
217         break;
218 
219     case eInputReaderGotToken:
220         ++cmd_object_expr->m_expr_line_count;
221         if (bytes && bytes_len)
222         {
223             cmd_object_expr->m_expr_lines.append (bytes, bytes_len + 1);
224         }
225 
226         if (bytes_len == 0)
227             reader.SetIsDone(true);
228         break;
229 
230     case eInputReaderInterrupt:
231         cmd_object_expr->m_expr_lines.clear();
232         reader.SetIsDone (true);
233         if (!batch_mode)
234         {
235             StreamSP async_strm_sp (reader.GetDebugger().GetAsyncOutputStream());
236             if (async_strm_sp)
237             {
238                 async_strm_sp->PutCString("Expression evaluation cancelled.\n");
239                 async_strm_sp->Flush();
240             }
241         }
242         break;
243 
244     case eInputReaderEndOfFile:
245         reader.SetIsDone (true);
246         break;
247 
248     case eInputReaderDone:
249 		if (cmd_object_expr->m_expr_lines.size() > 0)
250         {
251             StreamSP output_stream = reader.GetDebugger().GetAsyncOutputStream();
252             StreamSP error_stream = reader.GetDebugger().GetAsyncErrorStream();
253             cmd_object_expr->EvaluateExpression (cmd_object_expr->m_expr_lines.c_str(),
254                                                  output_stream.get(),
255                                                  error_stream.get());
256             output_stream->Flush();
257             error_stream->Flush();
258         }
259         break;
260     }
261 
262     return bytes_len;
263 }
264 
265 bool
266 CommandObjectExpression::EvaluateExpression
267 (
268     const char *expr,
269     Stream *output_stream,
270     Stream *error_stream,
271     CommandReturnObject *result
272 )
273 {
274     Target *target = m_exe_ctx.GetTargetPtr();
275     if (target)
276     {
277         lldb::ValueObjectSP result_valobj_sp;
278 
279         ExecutionResults exe_results;
280 
281         bool keep_in_memory = true;
282         lldb::DynamicValueType use_dynamic;
283         // If use dynamic is not set, get it from the target:
284         switch (m_options.use_dynamic)
285         {
286         case eLazyBoolCalculate:
287             use_dynamic = target->GetPreferDynamicValue();
288             break;
289         case eLazyBoolYes:
290             use_dynamic = lldb::eDynamicCanRunTarget;
291             break;
292         case eLazyBoolNo:
293             use_dynamic = lldb::eNoDynamicValues;
294             break;
295         }
296 
297         exe_results = target->EvaluateExpression (expr,
298                                                   m_exe_ctx.GetFramePtr(),
299                                                   eExecutionPolicyOnlyWhenNeeded,
300                                                   m_options.unwind_on_error,
301                                                   keep_in_memory,
302                                                   use_dynamic,
303                                                   result_valobj_sp);
304 
305         if (exe_results == eExecutionInterrupted && !m_options.unwind_on_error)
306         {
307             uint32_t start_frame = 0;
308             uint32_t num_frames = 1;
309             uint32_t num_frames_with_source = 0;
310             Thread *thread = m_exe_ctx.GetThreadPtr();
311             if (thread)
312             {
313                 thread->GetStatus (result->GetOutputStream(),
314                                    start_frame,
315                                    num_frames,
316                                    num_frames_with_source);
317             }
318             else
319             {
320                 Process *process = m_exe_ctx.GetProcessPtr();
321                 if (process)
322                 {
323                     bool only_threads_with_stop_reason = true;
324                     process->GetThreadStatus (result->GetOutputStream(),
325                                               only_threads_with_stop_reason,
326                                               start_frame,
327                                               num_frames,
328                                               num_frames_with_source);
329                 }
330             }
331         }
332 
333         if (result_valobj_sp)
334         {
335             if (result_valobj_sp->GetError().Success())
336             {
337                 if (m_options.format != eFormatDefault)
338                     result_valobj_sp->SetFormat (m_options.format);
339 
340                 ValueObject::DumpValueObject (*(output_stream),
341                                               result_valobj_sp.get(),   // Variable object to dump
342                                               result_valobj_sp->GetName().GetCString(),// Root object name
343                                               0,                        // Pointer depth to traverse (zero means stop at pointers)
344                                               0,                        // Current depth, this is the top most, so zero...
345                                               UINT32_MAX,               // Max depth to go when dumping concrete types, dump everything...
346                                               m_options.show_types,     // Show types when dumping?
347                                               false,                    // Show locations of variables, no since this is a host address which we don't care to see
348                                               m_options.print_object,   // Print the objective C object?
349                                               use_dynamic,
350                                               true,                     // Use synthetic children if available
351                                               true,                     // Scope is already checked. Const results are always in scope.
352                                               false,                    // Don't flatten output
353                                               0,                        // Always use summaries (you might want an option --no-summary like there is for frame variable)
354                                               false);                   // Do not show more children than settings allow
355                 if (result)
356                     result->SetStatus (eReturnStatusSuccessFinishResult);
357             }
358             else
359             {
360                 if (result_valobj_sp->GetError().GetError() == ClangUserExpression::kNoResult)
361                 {
362                     error_stream->PutCString("<no result>\n");
363 
364                     if (result)
365                         result->SetStatus (eReturnStatusSuccessFinishResult);
366                 }
367                 else
368                 {
369                     const char *error_cstr = result_valobj_sp->GetError().AsCString();
370                     if (error_cstr && error_cstr[0])
371                     {
372                         int error_cstr_len = strlen (error_cstr);
373                         const bool ends_with_newline = error_cstr[error_cstr_len - 1] == '\n';
374                         if (strstr(error_cstr, "error:") != error_cstr)
375                             error_stream->PutCString ("error: ");
376                         error_stream->Write(error_cstr, error_cstr_len);
377                         if (!ends_with_newline)
378                             error_stream->EOL();
379                     }
380                     else
381                     {
382                         error_stream->PutCString ("error: unknown error\n");
383                     }
384 
385                     if (result)
386                         result->SetStatus (eReturnStatusFailed);
387                 }
388             }
389         }
390     }
391     else
392     {
393         error_stream->Printf ("error: invalid execution context for expression\n");
394         return false;
395     }
396 
397     return true;
398 }
399 
400 bool
401 CommandObjectExpression::ExecuteRawCommandString
402 (
403     const char *command,
404     CommandReturnObject &result
405 )
406 {
407     m_exe_ctx = m_interpreter.GetExecutionContext();
408 
409     m_options.NotifyOptionParsingStarting();
410 
411     const char * expr = NULL;
412 
413     if (command[0] == '\0')
414     {
415         m_expr_lines.clear();
416         m_expr_line_count = 0;
417 
418         InputReaderSP reader_sp (new InputReader(m_interpreter.GetDebugger()));
419         if (reader_sp)
420         {
421             Error err (reader_sp->Initialize (CommandObjectExpression::MultiLineExpressionCallback,
422                                               this,                         // baton
423                                               eInputReaderGranularityLine,  // token size, to pass to callback function
424                                               NULL,                         // end token
425                                               NULL,                         // prompt
426                                               true));                       // echo input
427             if (err.Success())
428             {
429                 m_interpreter.GetDebugger().PushInputReader (reader_sp);
430                 result.SetStatus (eReturnStatusSuccessFinishNoResult);
431             }
432             else
433             {
434                 result.AppendError (err.AsCString());
435                 result.SetStatus (eReturnStatusFailed);
436             }
437         }
438         else
439         {
440             result.AppendError("out of memory");
441             result.SetStatus (eReturnStatusFailed);
442         }
443         return result.Succeeded();
444     }
445 
446     if (command[0] == '-')
447     {
448         // We have some options and these options MUST end with --.
449         const char *end_options = NULL;
450         const char *s = command;
451         while (s && s[0])
452         {
453             end_options = ::strstr (s, "--");
454             if (end_options)
455             {
456                 end_options += 2; // Get past the "--"
457                 if (::isspace (end_options[0]))
458                 {
459                     expr = end_options;
460                     while (::isspace (*expr))
461                         ++expr;
462                     break;
463                 }
464             }
465             s = end_options;
466         }
467 
468         if (end_options)
469         {
470             Args args (command, end_options - command);
471             if (!ParseOptions (args, result))
472                 return false;
473 
474             Error error (m_options.NotifyOptionParsingFinished());
475             if (error.Fail())
476             {
477                 result.AppendError (error.AsCString());
478                 result.SetStatus (eReturnStatusFailed);
479                 return false;
480             }
481         }
482     }
483 
484     if (expr == NULL)
485         expr = command;
486 
487     if (EvaluateExpression (expr, &(result.GetOutputStream()), &(result.GetErrorStream()), &result))
488         return true;
489 
490     result.SetStatus (eReturnStatusFailed);
491     return false;
492 }
493 
494 OptionDefinition
495 CommandObjectExpression::CommandOptions::g_option_table[] =
496 {
497 //{ LLDB_OPT_SET_ALL, false, "language",   'l', required_argument, NULL, 0, "[c|c++|objc|objc++]",          "Sets the language to use when parsing the expression."},
498 //{ LLDB_OPT_SET_1, false, "format",     'f', required_argument, NULL, 0, "[ [bool|b] | [bin] | [char|c] | [oct|o] | [dec|i|d|u] | [hex|x] | [float|f] | [cstr|s] ]",  "Specify the format that the expression output should use."},
499 { LLDB_OPT_SET_1,   false, "format",             'f', required_argument, NULL, 0, eArgTypeExprFormat, "Specify the format that the expression output should use."},
500 { LLDB_OPT_SET_2,   false, "object-description", 'o', no_argument,       NULL, 0, eArgTypeNone,       "Print the object description of the value resulting from the expression."},
501 { LLDB_OPT_SET_2,   false, "dynamic-value",      'd', required_argument, NULL, 0, eArgTypeBoolean,    "Upcast the value resulting from the expression to its dynamic type if available."},
502 { LLDB_OPT_SET_ALL, false, "unwind-on-error",    'u', required_argument, NULL, 0, eArgTypeBoolean,    "Clean up program state if the expression causes a crash, breakpoint hit or signal."},
503 { LLDB_OPT_SET_ALL, false, "debug",              'g', no_argument,       NULL, 0, eArgTypeNone,       "Enable verbose debug logging of the expression parsing and evaluation."},
504 { 0,                false, NULL,                 0,   0,                 NULL, 0, eArgTypeNone,       NULL }
505 };
506 
507