xref: /llvm-project/lldb/source/Commands/CommandObjectExpression.cpp (revision efed613172d902cf2ce49f68dd36f15a29a34dab)
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 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.process)
235     {
236         error_stream.Printf ("Execution context doesn't contain a process\n");
237         return false;
238     }
239 
240     const char *prefix = NULL;
241 
242     if (m_exe_ctx.target)
243         prefix = m_exe_ctx.target->GetExpressionPrefixContentsAsCString();
244 
245     lldb::ValueObjectSP result_valobj_sp (ClangUserExpression::Evaluate (m_exe_ctx, m_options.unwind_on_error, expr, prefix));
246     assert (result_valobj_sp.get());
247     if (result_valobj_sp->GetError().Success())
248     {
249         if (m_options.format != eFormatDefault)
250             result_valobj_sp->SetFormat (m_options.format);
251 
252         ValueObject::DumpValueObject (output_stream,
253                                       m_exe_ctx.GetBestExecutionContextScope(),
254                                       result_valobj_sp.get(),   // Variable object to dump
255                                       result_valobj_sp->GetName().AsCString(),// Root object name
256                                       0,                        // Pointer depth to traverse (zero means stop at pointers)
257                                       0,                        // Current depth, this is the top most, so zero...
258                                       UINT32_MAX,               // Max depth to go when dumping concrete types, dump everything...
259                                       m_options.show_types,     // Show types when dumping?
260                                       false,                    // Show locations of variables, no since this is a host address which we don't care to see
261                                       m_options.print_object,   // Print the objective C object?
262                                       true,                     // Scope is already checked. Const results are always in scope.
263                                       false);                   // Don't flatten output
264         if (result)
265             result->SetStatus (eReturnStatusSuccessFinishResult);
266     }
267     else
268     {
269         error_stream.PutCString(result_valobj_sp->GetError().AsCString());
270         if (result)
271             result->SetStatus (eReturnStatusFailed);
272     }
273 
274     return true;
275 }
276 
277 bool
278 CommandObjectExpression::ExecuteRawCommandString
279 (
280     const char *command,
281     CommandReturnObject &result
282 )
283 {
284     m_exe_ctx = m_interpreter.GetDebugger().GetExecutionContext();
285 
286     m_options.ResetOptionValues();
287 
288     const char * expr = NULL;
289 
290     if (command[0] == '\0')
291     {
292         m_expr_lines.clear();
293         m_expr_line_count = 0;
294 
295         InputReaderSP reader_sp (new InputReader(m_interpreter.GetDebugger()));
296         if (reader_sp)
297         {
298             Error err (reader_sp->Initialize (CommandObjectExpression::MultiLineExpressionCallback,
299                                               this,                         // baton
300                                               eInputReaderGranularityLine,  // token size, to pass to callback function
301                                               NULL,                         // end token
302                                               NULL,                         // prompt
303                                               true));                       // echo input
304             if (err.Success())
305             {
306                 m_interpreter.GetDebugger().PushInputReader (reader_sp);
307                 result.SetStatus (eReturnStatusSuccessFinishNoResult);
308             }
309             else
310             {
311                 result.AppendError (err.AsCString());
312                 result.SetStatus (eReturnStatusFailed);
313             }
314         }
315         else
316         {
317             result.AppendError("out of memory");
318             result.SetStatus (eReturnStatusFailed);
319         }
320         return result.Succeeded();
321     }
322 
323     if (command[0] == '-')
324     {
325         // We have some options and these options MUST end with --.
326         const char *end_options = NULL;
327         const char *s = command;
328         while (s && s[0])
329         {
330             end_options = ::strstr (s, "--");
331             if (end_options)
332             {
333                 end_options += 2; // Get past the "--"
334                 if (::isspace (end_options[0]))
335                 {
336                     expr = end_options;
337                     while (::isspace (*expr))
338                         ++expr;
339                     break;
340                 }
341             }
342             s = end_options;
343         }
344 
345         if (end_options)
346         {
347             Args args (command, end_options - command);
348             if (!ParseOptions (args, result))
349                 return false;
350         }
351     }
352 
353     if (expr == NULL)
354         expr = command;
355 
356     if (EvaluateExpression (expr, result.GetOutputStream(), result.GetErrorStream(), &result))
357         return true;
358 
359     result.SetStatus (eReturnStatusFailed);
360     return false;
361 }
362 
363 lldb::OptionDefinition
364 CommandObjectExpression::CommandOptions::g_option_table[] =
365 {
366   //{ LLDB_OPT_SET_ALL, false, "language",   'l', required_argument, NULL, 0, "[c|c++|objc|objc++]",          "Sets the language to use when parsing the expression."},
367 //{ 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."},
368 { LLDB_OPT_SET_1, false, "format",             'f', required_argument, NULL, 0, eArgTypeExprFormat,  "Specify the format that the expression output should use."},
369 { LLDB_OPT_SET_2, false, "object-description", 'o', no_argument,       NULL, 0, eArgTypeNone, "Print the object description of the value resulting from the expression."},
370 { 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."},
371 { LLDB_OPT_SET_ALL, false, "debug",            'g', no_argument,       NULL, 0, eArgTypeNone, "Enable verbose debug logging of the expression parsing and evaluation."},
372 { LLDB_OPT_SET_ALL, false, "use-ir",           'i', no_argument,       NULL, 0, eArgTypeNone, "[Temporary] Instructs the expression evaluator to use IR instead of ASTs."},
373 { 0, false, NULL, 0, 0, NULL, NULL, eArgTypeNone, NULL }
374 };
375 
376