xref: /llvm-project/lldb/source/Commands/CommandObjectExpression.cpp (revision 007d5be6533923ecc61742c83f6c7c7c27d4f18c)
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         bool success;
99         unwind_on_error = Args::StringToBoolean(option_arg, true, &success);
100         if (!success)
101             error.SetErrorStringWithFormat("Could not convert \"%s\" to a boolean value.", option_arg);
102         break;
103 
104     default:
105         error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
106         break;
107     }
108 
109     return error;
110 }
111 
112 void
113 CommandObjectExpression::CommandOptions::OptionParsingStarting ()
114 {
115     //language.Clear();
116     debug = false;
117     format = eFormatDefault;
118     print_object = false;
119     use_dynamic = eLazyBoolCalculate;
120     unwind_on_error = true;
121     show_types = true;
122     show_summary = true;
123 }
124 
125 const OptionDefinition*
126 CommandObjectExpression::CommandOptions::GetDefinitions ()
127 {
128     return g_option_table;
129 }
130 
131 CommandObjectExpression::CommandObjectExpression (CommandInterpreter &interpreter) :
132     CommandObject (interpreter,
133                    "expression",
134                    "Evaluate a C/ObjC/C++ expression in the current program context, using variables currently in scope.",
135                    NULL),
136     m_options (interpreter),
137     m_expr_line_count (0),
138     m_expr_lines ()
139 {
140   SetHelpLong(
141 "Examples: \n\
142 \n\
143    expr my_struct->a = my_array[3] \n\
144    expr -f bin -- (index * 8) + 5 \n\
145    expr char c[] = \"foo\"; c[0]\n");
146 
147     CommandArgumentEntry arg;
148     CommandArgumentData expression_arg;
149 
150     // Define the first (and only) variant of this arg.
151     expression_arg.arg_type = eArgTypeExpression;
152     expression_arg.arg_repetition = eArgRepeatPlain;
153 
154     // There is only one variant this argument could be; put it into the argument entry.
155     arg.push_back (expression_arg);
156 
157     // Push the data for the first argument into the m_arguments vector.
158     m_arguments.push_back (arg);
159 }
160 
161 CommandObjectExpression::~CommandObjectExpression ()
162 {
163 }
164 
165 Options *
166 CommandObjectExpression::GetOptions ()
167 {
168     return &m_options;
169 }
170 
171 
172 bool
173 CommandObjectExpression::Execute
174 (
175     Args& command,
176     CommandReturnObject &result
177 )
178 {
179     return false;
180 }
181 
182 
183 size_t
184 CommandObjectExpression::MultiLineExpressionCallback
185 (
186     void *baton,
187     InputReader &reader,
188     lldb::InputReaderAction notification,
189     const char *bytes,
190     size_t bytes_len
191 )
192 {
193     CommandObjectExpression *cmd_object_expr = (CommandObjectExpression *) baton;
194 
195     switch (notification)
196     {
197     case eInputReaderActivate:
198         reader.GetDebugger().GetOutputStream().Printf("%s\n", "Enter expressions, then terminate with an empty line to evaluate:");
199         // Fall through
200     case eInputReaderReactivate:
201         //if (out_fh)
202         //    reader.GetDebugger().GetOutputStream().Printf ("%3u: ", cmd_object_expr->m_expr_line_count);
203         break;
204 
205     case eInputReaderDeactivate:
206         break;
207 
208     case eInputReaderAsynchronousOutputWritten:
209         break;
210 
211     case eInputReaderGotToken:
212         ++cmd_object_expr->m_expr_line_count;
213         if (bytes && bytes_len)
214         {
215             cmd_object_expr->m_expr_lines.append (bytes, bytes_len + 1);
216         }
217 
218         if (bytes_len == 0)
219             reader.SetIsDone(true);
220         //else if (out_fh && !reader->IsDone())
221         //    ::fprintf (out_fh, "%3u: ", cmd_object_expr->m_expr_line_count);
222         break;
223 
224     case eInputReaderInterrupt:
225         cmd_object_expr->m_expr_lines.clear();
226         reader.SetIsDone (true);
227         reader.GetDebugger().GetOutputStream().Printf("%s\n", "Expression evaluation cancelled.");
228         break;
229 
230     case eInputReaderEndOfFile:
231         reader.SetIsDone (true);
232         break;
233 
234     case eInputReaderDone:
235 		if (cmd_object_expr->m_expr_lines.size() > 0)
236         {
237             cmd_object_expr->EvaluateExpression (cmd_object_expr->m_expr_lines.c_str(),
238                                                  reader.GetDebugger().GetOutputStream(),
239                                                  reader.GetDebugger().GetErrorStream());
240         }
241         break;
242     }
243 
244     return bytes_len;
245 }
246 
247 bool
248 CommandObjectExpression::EvaluateExpression
249 (
250     const char *expr,
251     Stream &output_stream,
252     Stream &error_stream,
253     CommandReturnObject *result
254 )
255 {
256     if (m_exe_ctx.target)
257     {
258         lldb::ValueObjectSP result_valobj_sp;
259 
260         ExecutionResults exe_results;
261 
262         bool keep_in_memory = true;
263         lldb::DynamicValueType use_dynamic;
264         // If use dynamic is not set, get it from the target:
265         switch (m_options.use_dynamic)
266         {
267         case eLazyBoolCalculate:
268             use_dynamic = m_exe_ctx.target->GetPreferDynamicValue();
269             break;
270         case eLazyBoolYes:
271             use_dynamic = lldb::eDynamicCanRunTarget;
272             break;
273         case eLazyBoolNo:
274             use_dynamic = lldb::eNoDynamicValues;
275             break;
276         }
277 
278         exe_results = m_exe_ctx.target->EvaluateExpression(expr, m_exe_ctx.frame, m_options.unwind_on_error, keep_in_memory, use_dynamic, result_valobj_sp);
279 
280         if (exe_results == eExecutionInterrupted && !m_options.unwind_on_error)
281         {
282             uint32_t start_frame = 0;
283             uint32_t num_frames = 1;
284             uint32_t num_frames_with_source = 0;
285             if (m_exe_ctx.thread)
286             {
287                 m_exe_ctx.thread->GetStatus (result->GetOutputStream(),
288                                              start_frame,
289                                              num_frames,
290                                              num_frames_with_source);
291             }
292             else if (m_exe_ctx.process)
293             {
294                 bool only_threads_with_stop_reason = true;
295                 m_exe_ctx.process->GetThreadStatus (result->GetOutputStream(),
296                                                     only_threads_with_stop_reason,
297                                                     start_frame,
298                                                     num_frames,
299                                                     num_frames_with_source);
300             }
301         }
302 
303         if (result_valobj_sp)
304         {
305             if (result_valobj_sp->GetError().Success())
306             {
307                 if (m_options.format != eFormatDefault)
308                     result_valobj_sp->SetFormat (m_options.format);
309 
310                 ValueObject::DumpValueObject (output_stream,
311                                               result_valobj_sp.get(),   // Variable object to dump
312                                               result_valobj_sp->GetName().GetCString(),// Root object name
313                                               0,                        // Pointer depth to traverse (zero means stop at pointers)
314                                               0,                        // Current depth, this is the top most, so zero...
315                                               UINT32_MAX,               // Max depth to go when dumping concrete types, dump everything...
316                                               m_options.show_types,     // Show types when dumping?
317                                               false,                    // Show locations of variables, no since this is a host address which we don't care to see
318                                               m_options.print_object,   // Print the objective C object?
319                                               use_dynamic,
320                                               true,                     // Scope is already checked. Const results are always in scope.
321                                               false);                   // Don't flatten output
322                 if (result)
323                     result->SetStatus (eReturnStatusSuccessFinishResult);
324             }
325             else
326             {
327                 error_stream.PutCString(result_valobj_sp->GetError().AsCString());
328                 if (result)
329                     result->SetStatus (eReturnStatusFailed);
330             }
331         }
332     }
333     else
334     {
335         error_stream.Printf ("error: invalid execution context for expression\n");
336         return false;
337     }
338 
339     return true;
340 }
341 
342 bool
343 CommandObjectExpression::ExecuteRawCommandString
344 (
345     const char *command,
346     CommandReturnObject &result
347 )
348 {
349     m_exe_ctx = m_interpreter.GetExecutionContext();
350 
351     m_options.NotifyOptionParsingStarting();
352 
353     const char * expr = NULL;
354 
355     if (command[0] == '\0')
356     {
357         m_expr_lines.clear();
358         m_expr_line_count = 0;
359 
360         InputReaderSP reader_sp (new InputReader(m_interpreter.GetDebugger()));
361         if (reader_sp)
362         {
363             Error err (reader_sp->Initialize (CommandObjectExpression::MultiLineExpressionCallback,
364                                               this,                         // baton
365                                               eInputReaderGranularityLine,  // token size, to pass to callback function
366                                               NULL,                         // end token
367                                               NULL,                         // prompt
368                                               true));                       // echo input
369             if (err.Success())
370             {
371                 m_interpreter.GetDebugger().PushInputReader (reader_sp);
372                 result.SetStatus (eReturnStatusSuccessFinishNoResult);
373             }
374             else
375             {
376                 result.AppendError (err.AsCString());
377                 result.SetStatus (eReturnStatusFailed);
378             }
379         }
380         else
381         {
382             result.AppendError("out of memory");
383             result.SetStatus (eReturnStatusFailed);
384         }
385         return result.Succeeded();
386     }
387 
388     if (command[0] == '-')
389     {
390         // We have some options and these options MUST end with --.
391         const char *end_options = NULL;
392         const char *s = command;
393         while (s && s[0])
394         {
395             end_options = ::strstr (s, "--");
396             if (end_options)
397             {
398                 end_options += 2; // Get past the "--"
399                 if (::isspace (end_options[0]))
400                 {
401                     expr = end_options;
402                     while (::isspace (*expr))
403                         ++expr;
404                     break;
405                 }
406             }
407             s = end_options;
408         }
409 
410         if (end_options)
411         {
412             Args args (command, end_options - command);
413             if (!ParseOptions (args, result))
414                 return false;
415 
416             Error error (m_options.NotifyOptionParsingFinished());
417             if (error.Fail())
418             {
419                 result.AppendError (error.AsCString());
420                 result.SetStatus (eReturnStatusFailed);
421                 return false;
422             }
423         }
424     }
425 
426     if (expr == NULL)
427         expr = command;
428 
429     if (EvaluateExpression (expr, result.GetOutputStream(), result.GetErrorStream(), &result))
430         return true;
431 
432     result.SetStatus (eReturnStatusFailed);
433     return false;
434 }
435 
436 OptionDefinition
437 CommandObjectExpression::CommandOptions::g_option_table[] =
438 {
439   //{ LLDB_OPT_SET_ALL, false, "language",   'l', required_argument, NULL, 0, "[c|c++|objc|objc++]",          "Sets the language to use when parsing the expression."},
440 //{ 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."},
441 { LLDB_OPT_SET_1, false, "format",             'f', required_argument, NULL, 0, eArgTypeExprFormat,  "Specify the format that the expression output should use."},
442 { LLDB_OPT_SET_2, false, "object-description", 'o', no_argument,       NULL, 0, eArgTypeNone, "Print the object description of the value resulting from the expression."},
443 { 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."},
444 { 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."},
445 { LLDB_OPT_SET_ALL, false, "debug",            'g', no_argument,       NULL, 0, eArgTypeNone, "Enable verbose debug logging of the expression parsing and evaluation."},
446 { LLDB_OPT_SET_ALL, false, "use-ir",           'i', no_argument,       NULL, 0, eArgTypeNone, "[Temporary] Instructs the expression evaluator to use IR instead of ASTs."},
447 { 0, false, NULL, 0, 0, NULL, NULL, eArgTypeNone, NULL }
448 };
449 
450