xref: /llvm-project/lldb/source/Commands/CommandObjectExpression.cpp (revision 399f1cafa64b9dc15be5b8b48bfd12d5449e5b6e)
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 "llvm/ADT/StringRef.h"
35 
36 using namespace lldb;
37 using namespace lldb_private;
38 
39 CommandObjectExpression::CommandOptions::CommandOptions () :
40     Options()
41 {
42     // Keep only one place to reset the values to their defaults
43     ResetOptionValues();
44 }
45 
46 
47 CommandObjectExpression::CommandOptions::~CommandOptions ()
48 {
49 }
50 
51 Error
52 CommandObjectExpression::CommandOptions::SetOptionValue (int option_idx, const char *option_arg)
53 {
54     Error error;
55 
56     char short_option = (char) m_getopt_table[option_idx].val;
57 
58     switch (short_option)
59     {
60       //case 'l':
61       //if (language.SetLanguageFromCString (option_arg) == false)
62       //{
63       //    error.SetErrorStringWithFormat("Invalid language option argument '%s'.\n", option_arg);
64       //}
65       //break;
66 
67     case 'g':
68         debug = true;
69         break;
70 
71     case 'f':
72         error = Args::StringToFormat(option_arg, format);
73         break;
74 
75     case 'o':
76         print_object = true;
77         break;
78 
79     case 'u':
80         bool success;
81         unwind_on_error = Args::StringToBoolean(option_arg, true, &success);
82         if (!success)
83             error.SetErrorStringWithFormat("Could not convert \"%s\" to a boolean value.", option_arg);
84         break;
85 
86     default:
87         error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
88         break;
89     }
90 
91     return error;
92 }
93 
94 void
95 CommandObjectExpression::CommandOptions::ResetOptionValues ()
96 {
97     Options::ResetOptionValues();
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 lldb::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 eInputReaderDone:
203         {
204             cmd_object_expr->EvaluateExpression (cmd_object_expr->m_expr_lines.c_str(),
205                                                  reader.GetDebugger().GetOutputStream(),
206                                                  reader.GetDebugger().GetErrorStream());
207         }
208         break;
209     }
210 
211     return bytes_len;
212 }
213 
214 bool
215 CommandObjectExpression::EvaluateExpression
216 (
217     const char *expr,
218     Stream &output_stream,
219     Stream &error_stream,
220     CommandReturnObject *result
221 )
222 {
223     if (!m_exe_ctx.process)
224     {
225         error_stream.Printf ("Execution context doesn't contain a process\n");
226         return false;
227     }
228 
229     const char *prefix = NULL;
230 
231     if (m_exe_ctx.target)
232         prefix = m_exe_ctx.target->GetExpressionPrefixContentsAsCString();
233 
234     lldb::ValueObjectSP result_valobj_sp (ClangUserExpression::Evaluate (m_exe_ctx, m_options.unwind_on_error, expr, prefix));
235     assert (result_valobj_sp.get());
236     if (result_valobj_sp->GetError().Success())
237     {
238         if (m_options.format != eFormatDefault)
239             result_valobj_sp->SetFormat (m_options.format);
240 
241         ValueObject::DumpValueObject (output_stream,
242                                       m_exe_ctx.GetBestExecutionContextScope(),
243                                       result_valobj_sp.get(),   // Variable object to dump
244                                       result_valobj_sp->GetName().AsCString(),// Root object name
245                                       0,                        // Pointer depth to traverse (zero means stop at pointers)
246                                       0,                        // Current depth, this is the top most, so zero...
247                                       UINT32_MAX,               // Max depth to go when dumping concrete types, dump everything...
248                                       m_options.show_types,     // Show types when dumping?
249                                       false,                    // Show locations of variables, no since this is a host address which we don't care to see
250                                       m_options.print_object,   // Print the objective C object?
251                                       true,                     // Scope is already checked. Const results are always in scope.
252                                       false);                   // Don't flatten output
253         if (result)
254             result->SetStatus (eReturnStatusSuccessFinishResult);
255     }
256     else
257     {
258         error_stream.PutCString(result_valobj_sp->GetError().AsCString());
259         if (result)
260             result->SetStatus (eReturnStatusFailed);
261     }
262 
263     return true;
264 }
265 
266 bool
267 CommandObjectExpression::ExecuteRawCommandString
268 (
269     const char *command,
270     CommandReturnObject &result
271 )
272 {
273     m_exe_ctx = m_interpreter.GetDebugger().GetExecutionContext();
274 
275     m_options.ResetOptionValues();
276 
277     const char * expr = NULL;
278 
279     if (command[0] == '\0')
280     {
281         m_expr_lines.clear();
282         m_expr_line_count = 0;
283 
284         InputReaderSP reader_sp (new InputReader(m_interpreter.GetDebugger()));
285         if (reader_sp)
286         {
287             Error err (reader_sp->Initialize (CommandObjectExpression::MultiLineExpressionCallback,
288                                               this,                         // baton
289                                               eInputReaderGranularityLine,  // token size, to pass to callback function
290                                               NULL,                         // end token
291                                               NULL,                         // prompt
292                                               true));                       // echo input
293             if (err.Success())
294             {
295                 m_interpreter.GetDebugger().PushInputReader (reader_sp);
296                 result.SetStatus (eReturnStatusSuccessFinishNoResult);
297             }
298             else
299             {
300                 result.AppendError (err.AsCString());
301                 result.SetStatus (eReturnStatusFailed);
302             }
303         }
304         else
305         {
306             result.AppendError("out of memory");
307             result.SetStatus (eReturnStatusFailed);
308         }
309         return result.Succeeded();
310     }
311 
312     if (command[0] == '-')
313     {
314         // We have some options and these options MUST end with --.
315         const char *end_options = NULL;
316         const char *s = command;
317         while (s && s[0])
318         {
319             end_options = ::strstr (s, "--");
320             if (end_options)
321             {
322                 end_options += 2; // Get past the "--"
323                 if (::isspace (end_options[0]))
324                 {
325                     expr = end_options;
326                     while (::isspace (*expr))
327                         ++expr;
328                     break;
329                 }
330             }
331             s = end_options;
332         }
333 
334         if (end_options)
335         {
336             Args args (command, end_options - command);
337             if (!ParseOptions (args, result))
338                 return false;
339         }
340     }
341 
342     if (expr == NULL)
343         expr = command;
344 
345     if (EvaluateExpression (expr, result.GetOutputStream(), result.GetErrorStream(), &result))
346         return true;
347 
348     result.SetStatus (eReturnStatusFailed);
349     return false;
350 }
351 
352 lldb::OptionDefinition
353 CommandObjectExpression::CommandOptions::g_option_table[] =
354 {
355   //{ LLDB_OPT_SET_ALL, false, "language",   'l', required_argument, NULL, 0, "[c|c++|objc|objc++]",          "Sets the language to use when parsing the expression."},
356 //{ 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."},
357 { LLDB_OPT_SET_1, false, "format",             'f', required_argument, NULL, 0, eArgTypeExprFormat,  "Specify the format that the expression output should use."},
358 { LLDB_OPT_SET_2, false, "object-description", 'o', no_argument,       NULL, 0, eArgTypeNone, "Print the object description of the value resulting from the expression."},
359 { 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."},
360 { LLDB_OPT_SET_ALL, false, "debug",            'g', no_argument,       NULL, 0, eArgTypeNone, "Enable verbose debug logging of the expression parsing and evaluation."},
361 { LLDB_OPT_SET_ALL, false, "use-ir",           'i', no_argument,       NULL, 0, eArgTypeNone, "[Temporary] Instructs the expression evaluator to use IR instead of ASTs."},
362 { 0, false, NULL, 0, 0, NULL, NULL, eArgTypeNone, NULL }
363 };
364 
365