xref: /llvm-project/lldb/source/Commands/CommandObjectExpression.cpp (revision 2ab712f2126397c7fafad47ea233ce56e28d17ef)
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/Expression/ClangExpression.h"
20 #include "lldb/Expression/ClangExpressionDeclMap.h"
21 #include "lldb/Expression/ClangExpressionVariable.h"
22 #include "lldb/Expression/DWARFExpression.h"
23 #include "lldb/Host/Host.h"
24 #include "lldb/Core/Debugger.h"
25 #include "lldb/Interpreter/CommandInterpreter.h"
26 #include "lldb/Interpreter/CommandReturnObject.h"
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Symbol/Variable.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/StackFrame.h"
31 #include "lldb/Target/Target.h"
32 #include "llvm/ADT/StringRef.h"
33 
34 using namespace lldb;
35 using namespace lldb_private;
36 
37 CommandObjectExpression::CommandOptions::CommandOptions () :
38     Options()
39 {
40     // Keep only one place to reset the values to their defaults
41     ResetOptionValues();
42 }
43 
44 
45 CommandObjectExpression::CommandOptions::~CommandOptions ()
46 {
47 }
48 
49 Error
50 CommandObjectExpression::CommandOptions::SetOptionValue (int option_idx, const char *option_arg)
51 {
52     Error error;
53 
54     char short_option = (char) m_getopt_table[option_idx].val;
55 
56     switch (short_option)
57     {
58     case 'l':
59         if (language.SetLanguageFromCString (option_arg) == false)
60         {
61             error.SetErrorStringWithFormat("Invalid language option argument '%s'.\n", option_arg);
62         }
63         break;
64 
65     case 'g':
66         debug = true;
67         break;
68 
69     case 'f':
70         error = Args::StringToFormat(option_arg, format);
71         break;
72 
73     case 'i':
74         use_ir = true;
75         break;
76 
77     default:
78         error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
79         break;
80     }
81 
82     return error;
83 }
84 
85 void
86 CommandObjectExpression::CommandOptions::ResetOptionValues ()
87 {
88     Options::ResetOptionValues();
89     language.Clear();
90     debug = false;
91     format = eFormatDefault;
92     show_types = true;
93     show_summary = true;
94     use_ir = false;
95 }
96 
97 const lldb::OptionDefinition*
98 CommandObjectExpression::CommandOptions::GetDefinitions ()
99 {
100     return g_option_table;
101 }
102 
103 CommandObjectExpression::CommandObjectExpression () :
104     CommandObject (
105             "expression",
106             "Evaluate a C expression in the current program context, using variables currently in scope.",
107             "expression [<cmd-options>] <expr>"),
108     m_expr_line_count (0),
109     m_expr_lines ()
110 {
111   SetHelpLong(
112 "Examples: \n\
113 \n\
114    expr my_struct->a = my_array[3] \n\
115    expr -f bin -- (index * 8) + 5 \n\
116    expr char c[] = \"foo\"; c[0]\n");
117 }
118 
119 CommandObjectExpression::~CommandObjectExpression ()
120 {
121 }
122 
123 Options *
124 CommandObjectExpression::GetOptions ()
125 {
126     return &m_options;
127 }
128 
129 
130 bool
131 CommandObjectExpression::Execute
132 (
133     CommandInterpreter &interpreter,
134     Args& command,
135     CommandReturnObject &result
136 )
137 {
138     return false;
139 }
140 
141 
142 size_t
143 CommandObjectExpression::MultiLineExpressionCallback
144 (
145     void *baton,
146     InputReader &reader,
147     lldb::InputReaderAction notification,
148     const char *bytes,
149     size_t bytes_len
150 )
151 {
152     CommandObjectExpression *cmd_object_expr = (CommandObjectExpression *) baton;
153 
154     switch (notification)
155     {
156     case eInputReaderActivate:
157         reader.GetDebugger().GetOutputStream().Printf("%s\n", "Enter expressions, then terminate with an empty line to evaluate:");
158         // Fall through
159     case eInputReaderReactivate:
160         //if (out_fh)
161         //    reader.GetDebugger().GetOutputStream().Printf ("%3u: ", cmd_object_expr->m_expr_line_count);
162         break;
163 
164     case eInputReaderDeactivate:
165         break;
166 
167     case eInputReaderGotToken:
168         ++cmd_object_expr->m_expr_line_count;
169         if (bytes && bytes_len)
170         {
171             cmd_object_expr->m_expr_lines.append (bytes, bytes_len + 1);
172         }
173 
174         if (bytes_len == 0)
175             reader.SetIsDone(true);
176         //else if (out_fh && !reader->IsDone())
177         //    ::fprintf (out_fh, "%3u: ", cmd_object_expr->m_expr_line_count);
178         break;
179 
180     case eInputReaderDone:
181         {
182             bool bare = false;
183             cmd_object_expr->EvaluateExpression (cmd_object_expr->m_expr_lines.c_str(),
184                                                  bare,
185                                                  reader.GetDebugger().GetOutputStream(),
186                                                  reader.GetDebugger().GetErrorStream());
187         }
188         break;
189     }
190 
191     return bytes_len;
192 }
193 
194 bool
195 CommandObjectExpression::EvaluateExpression (const char *expr, bool bare, Stream &output_stream, Stream &error_stream)
196 {
197     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
198 
199     ////////////////////////////////////
200     // Set up the target and compiler
201     //
202 
203     Target *target = m_exe_ctx.target;
204 
205     if (!target)
206     {
207         error_stream.PutCString ("error: invalid target\n");
208         return false;
209     }
210 
211     ConstString target_triple;
212 
213     target->GetTargetTriple (target_triple);
214 
215     if (!target_triple)
216         target_triple = Host::GetTargetTriple ();
217 
218     if (!target_triple)
219     {
220         error_stream.PutCString ("error: invalid target triple\n");
221         return false;
222     }
223 
224     ClangExpressionDeclMap expr_decl_map (&m_exe_ctx);
225     ClangExpression clang_expr (target_triple.AsCString (), &expr_decl_map);
226 
227     //////////////////////////
228     // Parse the expression
229     //
230 
231     unsigned num_errors;
232 
233     if (bare)
234         num_errors = clang_expr.ParseBareExpression (llvm::StringRef (expr), error_stream);
235     else
236         num_errors = clang_expr.ParseExpression (expr, error_stream, m_options.use_ir);
237 
238     if (num_errors)
239     {
240         error_stream.Printf ("error: %d errors parsing expression\n", num_errors);
241         return false;
242     }
243 
244     ///////////////////////////////////////////////
245     // Convert the output of the parser to DWARF
246     //
247 
248     StreamString dwarf_opcodes;
249     dwarf_opcodes.SetByteOrder (eByteOrderHost);
250     dwarf_opcodes.GetFlags ().Set (Stream::eBinary);
251 
252     ClangExpressionVariableList expr_local_vars;
253 
254     bool success;
255     bool canInterpret = false;
256 
257     if (m_options.use_ir)
258     {
259         canInterpret = clang_expr.ConvertIRToDWARF (expr_local_vars, dwarf_opcodes);
260 
261         if (canInterpret)
262         {
263             if (log)
264                 log->Printf("Code can be interpreted.");
265             success = true;
266         }
267         else
268         {
269             if (log)
270                 log->Printf("Code cannot be interpreted and must be run in the target.");
271             success = clang_expr.PrepareIRForTarget (expr_local_vars);
272         }
273     }
274     else
275     {
276         success = (clang_expr.ConvertExpressionToDWARF (expr_local_vars, dwarf_opcodes) == 0);
277     }
278 
279     if (!success)
280     {
281         error_stream.PutCString ("error: expression couldn't be translated to DWARF\n");
282         return false;
283     }
284 
285     //////////////////////////////////////////
286     // Evaluate the generated DWARF opcodes
287     //
288 
289     DataExtractor dwarf_opcodes_data (dwarf_opcodes.GetData (), dwarf_opcodes.GetSize (), eByteOrderHost, 8);
290     DWARFExpression dwarf_expr (dwarf_opcodes_data, 0, dwarf_opcodes_data.GetByteSize (), NULL);
291 
292     dwarf_expr.SetExpressionLocalVariableList(&expr_local_vars);
293 
294     if (log)
295     {
296         StreamString stream_string;
297 
298         log->PutCString ("Expression parsed ok, dwarf opcodes:");
299 
300         stream_string.PutCString ("\n");
301         stream_string.IndentMore ();
302         dwarf_expr.GetDescription (&stream_string, lldb::eDescriptionLevelVerbose);
303         stream_string.IndentLess ();
304         stream_string.EOL ();
305 
306         log->PutCString (stream_string.GetString ().c_str ());
307     }
308 
309     clang::ASTContext *ast_context = clang_expr.GetASTContext ();
310     Value expr_result;
311     Error expr_error;
312     success = dwarf_expr.Evaluate (&m_exe_ctx, ast_context, NULL, expr_result, &expr_error);
313 
314     if (!success)
315     {
316         error_stream.Printf ("error: couldn't evaluate DWARF expression: %s\n", expr_error.AsCString ());
317         return false;
318     }
319 
320     ///////////////////////////////////////
321     // Interpret the result and print it
322     //
323 
324     lldb::Format format = m_options.format;
325 
326     // Resolve any values that are possible
327     expr_result.ResolveValue (&m_exe_ctx, ast_context);
328 
329     if (expr_result.GetContextType () == Value::eContextTypeInvalid &&
330         expr_result.GetValueType () == Value::eValueTypeScalar &&
331         format == eFormatDefault)
332     {
333         // The expression result is just a scalar with no special formatting
334         expr_result.GetScalar ().GetValue (&output_stream, m_options.show_types);
335         output_stream.EOL ();
336         return true;
337     }
338 
339     // The expression result is more complext and requires special handling
340     DataExtractor data;
341     expr_error = expr_result.GetValueAsData (&m_exe_ctx, ast_context, data, 0);
342 
343     if (!expr_error.Success ())
344     {
345         error_stream.Printf ("error: couldn't resolve result value: %s\n", expr_error.AsCString ());
346         return false;
347     }
348 
349     if (format == eFormatDefault)
350         format = expr_result.GetValueDefaultFormat ();
351 
352     void *clang_type = expr_result.GetValueOpaqueClangQualType ();
353 
354     if (clang_type)
355     {
356         if (m_options.show_types)
357             Type::DumpClangTypeName (&output_stream, clang_type);
358 
359         Type::DumpValue (&m_exe_ctx,                // The execution context for memory and variable access
360                          ast_context,               // The ASTContext that the clang type belongs to
361                          clang_type,                // The opaque clang type we want to dump that value of
362                          &output_stream,            // Stream to dump to
363                          format,                    // Format to use when dumping
364                          data,                      // A buffer containing the bytes for the clang type
365                          0,                         // Byte offset within "data" where value is
366                          data.GetByteSize (),       // Size in bytes of the value we are dumping
367                          0,                         // Bitfield bit size
368                          0,                         // Bitfield bit offset
369                          m_options.show_types,      // Show types?
370                          m_options.show_summary,    // Show summary?
371                          m_options.debug,           // Debug logging output?
372                          UINT32_MAX);               // Depth to dump in case this is an aggregate type
373     }
374     else
375     {
376         data.Dump (&output_stream,          // Stream to dump to
377                    0,                       // Byte offset within "data"
378                    format,                  // Format to use when dumping
379                    data.GetByteSize (),     // Size in bytes of each item we are dumping
380                    1,                       // Number of items to dump
381                    UINT32_MAX,              // Number of items per line
382                    LLDB_INVALID_ADDRESS,    // Invalid address, don't show any offset/address context
383                    0,                       // Bitfield bit size
384                    0);                      // Bitfield bit offset
385     }
386     output_stream.EOL();
387 
388     return true;
389 }
390 
391 bool
392 CommandObjectExpression::ExecuteRawCommandString
393 (
394     CommandInterpreter &interpreter,
395     const char *command,
396     CommandReturnObject &result
397 )
398 {
399     m_exe_ctx = interpreter.GetDebugger().GetExecutionContext();
400 
401     m_options.ResetOptionValues();
402 
403     const char * expr = NULL;
404 
405     if (command[0] == '\0')
406     {
407         m_expr_lines.clear();
408         m_expr_line_count = 0;
409 
410         InputReaderSP reader_sp (new InputReader(interpreter.GetDebugger()));
411         if (reader_sp)
412         {
413             Error err (reader_sp->Initialize (CommandObjectExpression::MultiLineExpressionCallback,
414                                               this,                         // baton
415                                               eInputReaderGranularityLine,  // token size, to pass to callback function
416                                               NULL,                         // end token
417                                               NULL,                         // prompt
418                                               true));                       // echo input
419             if (err.Success())
420             {
421                 interpreter.GetDebugger().PushInputReader (reader_sp);
422                 result.SetStatus (eReturnStatusSuccessFinishNoResult);
423             }
424             else
425             {
426                 result.AppendError (err.AsCString());
427                 result.SetStatus (eReturnStatusFailed);
428             }
429         }
430         else
431         {
432             result.AppendError("out of memory");
433             result.SetStatus (eReturnStatusFailed);
434         }
435         return result.Succeeded();
436     }
437 
438     if (command[0] == '-')
439     {
440         // We have some options and these options MUST end with --.
441         const char *end_options = NULL;
442         const char *s = command;
443         while (s && s[0])
444         {
445             end_options = ::strstr (s, "--");
446             if (end_options)
447             {
448                 end_options += 2; // Get past the "--"
449                 if (::isspace (end_options[0]))
450                 {
451                     expr = end_options;
452                     while (::isspace (*expr))
453                         ++expr;
454                     break;
455                 }
456             }
457             s = end_options;
458         }
459 
460         if (end_options)
461         {
462             Args args (command, end_options - command);
463             if (!ParseOptions (interpreter, args, result))
464                 return false;
465         }
466     }
467 
468     if (expr == NULL)
469         expr = command;
470 
471     return EvaluateExpression (expr, false, result.GetOutputStream(), result.GetErrorStream());
472 }
473 
474 lldb::OptionDefinition
475 CommandObjectExpression::CommandOptions::g_option_table[] =
476 {
477 { LLDB_OPT_SET_ALL, false, "language",   'l', required_argument, NULL, 0, "[c|c++|objc|objc++]",          "Sets the language to use when parsing the expression."},
478 { LLDB_OPT_SET_ALL, 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."},
479 { LLDB_OPT_SET_ALL, false, "debug",      'g', no_argument,       NULL, 0, NULL,                           "Enable verbose debug logging of the expression parsing and evaluation."},
480 { LLDB_OPT_SET_ALL, false, "use-ir",     'i', no_argument,       NULL, 0, NULL,                           "[Temporary] Instructs the expression evaluator to use IR instead of ASTs."},
481 { 0, false, NULL, 0, 0, NULL, NULL, NULL, NULL }
482 };
483 
484