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