xref: /llvm-project/lldb/source/Commands/CommandObjectExpression.cpp (revision 6035b67d2c27cc1af134293acb06ce7463f88671)
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 "CommandObjectThread.h" // For DisplayThreadInfo.
17 #include "lldb/Interpreter/Args.h"
18 #include "lldb/Core/Value.h"
19 #include "lldb/Core/InputReader.h"
20 #include "lldb/Core/ValueObjectVariable.h"
21 #include "lldb/Expression/ClangExpressionVariable.h"
22 #include "lldb/Expression/ClangUserExpression.h"
23 #include "lldb/Expression/ClangFunction.h"
24 #include "lldb/Expression/DWARFExpression.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Core/Debugger.h"
27 #include "lldb/Interpreter/CommandInterpreter.h"
28 #include "lldb/Interpreter/CommandReturnObject.h"
29 #include "lldb/Target/ObjCLanguageRuntime.h"
30 #include "lldb/Symbol/ObjectFile.h"
31 #include "lldb/Symbol/Variable.h"
32 #include "lldb/Target/Process.h"
33 #include "lldb/Target/StackFrame.h"
34 #include "lldb/Target/Target.h"
35 #include "llvm/ADT/StringRef.h"
36 
37 using namespace lldb;
38 using namespace lldb_private;
39 
40 CommandObjectExpression::CommandOptions::CommandOptions () :
41     Options()
42 {
43     // Keep only one place to reset the values to their defaults
44     ResetOptionValues();
45 }
46 
47 
48 CommandObjectExpression::CommandOptions::~CommandOptions ()
49 {
50 }
51 
52 Error
53 CommandObjectExpression::CommandOptions::SetOptionValue (int 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);
74         break;
75 
76     case 'o':
77         print_object = true;
78         break;
79 
80     case 'u':
81         bool success;
82         unwind_on_error = Args::StringToBoolean(option_arg, true, &success);
83         if (!success)
84             error.SetErrorStringWithFormat("Could not convert \"%s\" to a boolean value.", option_arg);
85         break;
86 
87     default:
88         error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
89         break;
90     }
91 
92     return error;
93 }
94 
95 void
96 CommandObjectExpression::CommandOptions::ResetOptionValues ()
97 {
98     //language.Clear();
99     debug = false;
100     format = eFormatDefault;
101     print_object = false;
102     unwind_on_error = true;
103     show_types = true;
104     show_summary = true;
105 }
106 
107 const OptionDefinition*
108 CommandObjectExpression::CommandOptions::GetDefinitions ()
109 {
110     return g_option_table;
111 }
112 
113 CommandObjectExpression::CommandObjectExpression (CommandInterpreter &interpreter) :
114     CommandObject (interpreter,
115                    "expression",
116                    "Evaluate a C/ObjC/C++ expression in the current program context, using variables currently in scope.",
117                    NULL),
118     m_expr_line_count (0),
119     m_expr_lines ()
120 {
121   SetHelpLong(
122 "Examples: \n\
123 \n\
124    expr my_struct->a = my_array[3] \n\
125    expr -f bin -- (index * 8) + 5 \n\
126    expr char c[] = \"foo\"; c[0]\n");
127 
128     CommandArgumentEntry arg;
129     CommandArgumentData expression_arg;
130 
131     // Define the first (and only) variant of this arg.
132     expression_arg.arg_type = eArgTypeExpression;
133     expression_arg.arg_repetition = eArgRepeatPlain;
134 
135     // There is only one variant this argument could be; put it into the argument entry.
136     arg.push_back (expression_arg);
137 
138     // Push the data for the first argument into the m_arguments vector.
139     m_arguments.push_back (arg);
140 }
141 
142 CommandObjectExpression::~CommandObjectExpression ()
143 {
144 }
145 
146 Options *
147 CommandObjectExpression::GetOptions ()
148 {
149     return &m_options;
150 }
151 
152 
153 bool
154 CommandObjectExpression::Execute
155 (
156     Args& command,
157     CommandReturnObject &result
158 )
159 {
160     return false;
161 }
162 
163 
164 size_t
165 CommandObjectExpression::MultiLineExpressionCallback
166 (
167     void *baton,
168     InputReader &reader,
169     lldb::InputReaderAction notification,
170     const char *bytes,
171     size_t bytes_len
172 )
173 {
174     CommandObjectExpression *cmd_object_expr = (CommandObjectExpression *) baton;
175 
176     switch (notification)
177     {
178     case eInputReaderActivate:
179         reader.GetDebugger().GetOutputStream().Printf("%s\n", "Enter expressions, then terminate with an empty line to evaluate:");
180         // Fall through
181     case eInputReaderReactivate:
182         //if (out_fh)
183         //    reader.GetDebugger().GetOutputStream().Printf ("%3u: ", cmd_object_expr->m_expr_line_count);
184         break;
185 
186     case eInputReaderDeactivate:
187         break;
188 
189     case eInputReaderGotToken:
190         ++cmd_object_expr->m_expr_line_count;
191         if (bytes && bytes_len)
192         {
193             cmd_object_expr->m_expr_lines.append (bytes, bytes_len + 1);
194         }
195 
196         if (bytes_len == 0)
197             reader.SetIsDone(true);
198         //else if (out_fh && !reader->IsDone())
199         //    ::fprintf (out_fh, "%3u: ", cmd_object_expr->m_expr_line_count);
200         break;
201 
202     case eInputReaderInterrupt:
203         cmd_object_expr->m_expr_lines.clear();
204         reader.SetIsDone (true);
205         reader.GetDebugger().GetOutputStream().Printf("%s\n", "Expression evaluation cancelled.");
206         break;
207 
208     case eInputReaderEndOfFile:
209         reader.SetIsDone (true);
210         break;
211 
212     case eInputReaderDone:
213 		if (cmd_object_expr->m_expr_lines.size() > 0)
214         {
215             cmd_object_expr->EvaluateExpression (cmd_object_expr->m_expr_lines.c_str(),
216                                                  reader.GetDebugger().GetOutputStream(),
217                                                  reader.GetDebugger().GetErrorStream());
218         }
219         break;
220     }
221 
222     return bytes_len;
223 }
224 
225 bool
226 CommandObjectExpression::EvaluateExpression
227 (
228     const char *expr,
229     Stream &output_stream,
230     Stream &error_stream,
231     CommandReturnObject *result
232 )
233 {
234     if (m_exe_ctx.target)
235     {
236         lldb::ValueObjectSP result_valobj_sp;
237 
238         ExecutionResults exe_results;
239 
240         bool keep_in_memory = true;
241 
242         exe_results = m_exe_ctx.target->EvaluateExpression(expr, m_exe_ctx.frame, m_options.unwind_on_error, keep_in_memory, result_valobj_sp);
243 
244         if (exe_results == eExecutionInterrupted && !m_options.unwind_on_error)
245         {
246             if (m_exe_ctx.thread)
247                 lldb_private::DisplayThreadInfo (m_interpreter, result->GetOutputStream(), m_exe_ctx.thread, false, true);
248             else
249                 lldb_private::DisplayThreadsInfo (m_interpreter, &m_exe_ctx, *result, true, true);
250         }
251 
252         if (result_valobj_sp)
253         {
254             if (result_valobj_sp->GetError().Success())
255             {
256                 if (m_options.format != eFormatDefault)
257                     result_valobj_sp->SetFormat (m_options.format);
258 
259                 ValueObject::DumpValueObject (output_stream,
260                                               result_valobj_sp.get(),   // Variable object to dump
261                                               result_valobj_sp->GetName().GetCString(),// Root object name
262                                               0,                        // Pointer depth to traverse (zero means stop at pointers)
263                                               0,                        // Current depth, this is the top most, so zero...
264                                               UINT32_MAX,               // Max depth to go when dumping concrete types, dump everything...
265                                               m_options.show_types,     // Show types when dumping?
266                                               false,                    // Show locations of variables, no since this is a host address which we don't care to see
267                                               m_options.print_object,   // Print the objective C object?
268                                               true,                     // Scope is already checked. Const results are always in scope.
269                                               false);                   // Don't flatten output
270                 if (result)
271                     result->SetStatus (eReturnStatusSuccessFinishResult);
272             }
273             else
274             {
275                 error_stream.PutCString(result_valobj_sp->GetError().AsCString());
276                 if (result)
277                     result->SetStatus (eReturnStatusFailed);
278             }
279         }
280     }
281     else
282     {
283         error_stream.Printf ("error: invalid execution context for expression\n");
284         return false;
285     }
286 
287     return true;
288 }
289 
290 bool
291 CommandObjectExpression::ExecuteRawCommandString
292 (
293     const char *command,
294     CommandReturnObject &result
295 )
296 {
297     m_exe_ctx = m_interpreter.GetDebugger().GetExecutionContext();
298 
299     m_options.Reset();
300 
301     const char * expr = NULL;
302 
303     if (command[0] == '\0')
304     {
305         m_expr_lines.clear();
306         m_expr_line_count = 0;
307 
308         InputReaderSP reader_sp (new InputReader(m_interpreter.GetDebugger()));
309         if (reader_sp)
310         {
311             Error err (reader_sp->Initialize (CommandObjectExpression::MultiLineExpressionCallback,
312                                               this,                         // baton
313                                               eInputReaderGranularityLine,  // token size, to pass to callback function
314                                               NULL,                         // end token
315                                               NULL,                         // prompt
316                                               true));                       // echo input
317             if (err.Success())
318             {
319                 m_interpreter.GetDebugger().PushInputReader (reader_sp);
320                 result.SetStatus (eReturnStatusSuccessFinishNoResult);
321             }
322             else
323             {
324                 result.AppendError (err.AsCString());
325                 result.SetStatus (eReturnStatusFailed);
326             }
327         }
328         else
329         {
330             result.AppendError("out of memory");
331             result.SetStatus (eReturnStatusFailed);
332         }
333         return result.Succeeded();
334     }
335 
336     if (command[0] == '-')
337     {
338         // We have some options and these options MUST end with --.
339         const char *end_options = NULL;
340         const char *s = command;
341         while (s && s[0])
342         {
343             end_options = ::strstr (s, "--");
344             if (end_options)
345             {
346                 end_options += 2; // Get past the "--"
347                 if (::isspace (end_options[0]))
348                 {
349                     expr = end_options;
350                     while (::isspace (*expr))
351                         ++expr;
352                     break;
353                 }
354             }
355             s = end_options;
356         }
357 
358         if (end_options)
359         {
360             Args args (command, end_options - command);
361             if (!ParseOptions (args, result))
362                 return false;
363         }
364     }
365 
366     if (expr == NULL)
367         expr = command;
368 
369     if (EvaluateExpression (expr, result.GetOutputStream(), result.GetErrorStream(), &result))
370         return true;
371 
372     result.SetStatus (eReturnStatusFailed);
373     return false;
374 }
375 
376 OptionDefinition
377 CommandObjectExpression::CommandOptions::g_option_table[] =
378 {
379   //{ LLDB_OPT_SET_ALL, false, "language",   'l', required_argument, NULL, 0, "[c|c++|objc|objc++]",          "Sets the language to use when parsing the expression."},
380 //{ 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."},
381 { LLDB_OPT_SET_1, false, "format",             'f', required_argument, NULL, 0, eArgTypeExprFormat,  "Specify the format that the expression output should use."},
382 { LLDB_OPT_SET_2, false, "object-description", 'o', no_argument,       NULL, 0, eArgTypeNone, "Print the object description of the value resulting from the expression."},
383 { 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."},
384 { LLDB_OPT_SET_ALL, false, "debug",            'g', no_argument,       NULL, 0, eArgTypeNone, "Enable verbose debug logging of the expression parsing and evaluation."},
385 { LLDB_OPT_SET_ALL, false, "use-ir",           'i', no_argument,       NULL, 0, eArgTypeNone, "[Temporary] Instructs the expression evaluator to use IR instead of ASTs."},
386 { 0, false, NULL, 0, 0, NULL, NULL, eArgTypeNone, NULL }
387 };
388 
389