blob: 56f97fb40273565f8671cbf3f32475804e324b08 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- 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
Jim Ingham84cdc152010-06-15 19:49:27 +000016#include "lldb/Interpreter/Args.h"
Chris Lattner24943d22010-06-08 16:52:24 +000017#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"
Greg Clayton63094e02010-06-23 01:19:29 +000024#include "lldb/Core/Debugger.h"
25#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000026#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
34using namespace lldb;
35using namespace lldb_private;
36
37CommandObjectExpression::CommandOptions::CommandOptions () :
38 Options()
39{
40 // Keep only one place to reset the values to their defaults
41 ResetOptionValues();
42}
43
44
45CommandObjectExpression::CommandOptions::~CommandOptions ()
46{
47}
48
49Error
50CommandObjectExpression::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;
Sean Callanan848960c2010-06-23 23:18:04 +000072
73 case 'i':
74 use_ir = true;
75 break;
Chris Lattner24943d22010-06-08 16:52:24 +000076
77 default:
78 error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
79 break;
80 }
81
82 return error;
83}
84
85void
86CommandObjectExpression::CommandOptions::ResetOptionValues ()
87{
88 Options::ResetOptionValues();
89 language.Clear();
90 debug = false;
91 format = eFormatDefault;
92 show_types = true;
93 show_summary = true;
Sean Callanan848960c2010-06-23 23:18:04 +000094 use_ir = false;
Chris Lattner24943d22010-06-08 16:52:24 +000095}
96
97const lldb::OptionDefinition*
98CommandObjectExpression::CommandOptions::GetDefinitions ()
99{
100 return g_option_table;
101}
102
103CommandObjectExpression::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
119CommandObjectExpression::~CommandObjectExpression ()
120{
121}
122
123Options *
124CommandObjectExpression::GetOptions ()
125{
126 return &m_options;
127}
128
129
130bool
131CommandObjectExpression::Execute
132(
Greg Clayton63094e02010-06-23 01:19:29 +0000133 CommandInterpreter &interpreter,
Chris Lattner24943d22010-06-08 16:52:24 +0000134 Args& command,
Chris Lattner24943d22010-06-08 16:52:24 +0000135 CommandReturnObject &result
136)
137{
138 return false;
139}
140
141
142size_t
143CommandObjectExpression::MultiLineExpressionCallback
144(
145 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000146 InputReader &reader,
Chris Lattner24943d22010-06-08 16:52:24 +0000147 lldb::InputReaderAction notification,
148 const char *bytes,
149 size_t bytes_len
150)
151{
Chris Lattner24943d22010-06-08 16:52:24 +0000152 CommandObjectExpression *cmd_object_expr = (CommandObjectExpression *) baton;
153
154 switch (notification)
155 {
156 case eInputReaderActivate:
Greg Clayton63094e02010-06-23 01:19:29 +0000157 reader.GetDebugger().GetOutputStream().Printf("%s\n", "Enter expressions, then terminate with an empty line to evaluate:");
Chris Lattner24943d22010-06-08 16:52:24 +0000158 // Fall through
159 case eInputReaderReactivate:
160 //if (out_fh)
Greg Clayton63094e02010-06-23 01:19:29 +0000161 // reader.GetDebugger().GetOutputStream().Printf ("%3u: ", cmd_object_expr->m_expr_line_count);
Chris Lattner24943d22010-06-08 16:52:24 +0000162 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)
Greg Clayton63094e02010-06-23 01:19:29 +0000175 reader.SetIsDone(true);
Chris Lattner24943d22010-06-08 16:52:24 +0000176 //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 {
Chris Lattner24943d22010-06-08 16:52:24 +0000182 bool bare = false;
183 cmd_object_expr->EvaluateExpression (cmd_object_expr->m_expr_lines.c_str(),
184 bare,
Greg Clayton63094e02010-06-23 01:19:29 +0000185 reader.GetDebugger().GetOutputStream(),
186 reader.GetDebugger().GetErrorStream());
Chris Lattner24943d22010-06-08 16:52:24 +0000187 }
188 break;
189 }
190
191 return bytes_len;
192}
193
194bool
195CommandObjectExpression::EvaluateExpression (const char *expr, bool bare, Stream &output_stream, Stream &error_stream)
196{
Sean Callanan46b62492010-06-24 00:16:27 +0000197 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
198
199 ////////////////////////////////////
200 // Set up the target and compiler
201 //
202
Chris Lattner24943d22010-06-08 16:52:24 +0000203 Target *target = m_exe_ctx.target;
Sean Callanan46b62492010-06-24 00:16:27 +0000204
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);
Chris Lattner24943d22010-06-08 16:52:24 +0000214
215 if (!target_triple)
216 target_triple = Host::GetTargetTriple ();
Sean Callanan46b62492010-06-24 00:16:27 +0000217
218 if (!target_triple)
Chris Lattner24943d22010-06-08 16:52:24 +0000219 {
Sean Callanan46b62492010-06-24 00:16:27 +0000220 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
Sean Callanan8c6934d2010-07-01 20:08:22 +0000236 num_errors = clang_expr.ParseExpression (expr, error_stream, m_options.use_ir);
Sean Callanan46b62492010-06-24 00:16:27 +0000237
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;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000255 bool canInterpret = false;
Sean Callanan46b62492010-06-24 00:16:27 +0000256
257 if (m_options.use_ir)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000258 {
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 }
Sean Callananbafd6852010-07-14 23:40:29 +0000273
274 if (!success)
275 {
276 error_stream.PutCString ("error: expression couldn't be converted to IR\n");
277 return false;
278 }
279
280 if (canInterpret)
281 {
282 // TODO interpret IR
283 return false;
284 }
285 else
286 {
287 if (!clang_expr.JITFunction (m_exe_ctx, "___clang_expr"))
288 {
289 error_stream.PutCString ("error: IR could not be JIT compiled\n");
290 return false;
291 }
292
293 if (!clang_expr.WriteJITCode (m_exe_ctx))
294 {
295 error_stream.PutCString ("error: JIT code could not be written to the target\n");
296 return false;
297 }
298
299 lldb::addr_t function_address(clang_expr.GetFunctionAddress ("___clang_expr"));
300
301 if (function_address == LLDB_INVALID_ADDRESS)
302 {
303 error_stream.PutCString ("JIT compiled code's address couldn't be found\n");
304 return false;
305 }
306
307 log->Printf("Function is at 0x%llx", (uint64_t)function_address);
308 }
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000309 }
Sean Callanan46b62492010-06-24 00:16:27 +0000310 else
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000311 {
Sean Callanan46b62492010-06-24 00:16:27 +0000312 success = (clang_expr.ConvertExpressionToDWARF (expr_local_vars, dwarf_opcodes) == 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000313
Sean Callananbafd6852010-07-14 23:40:29 +0000314 if (!success)
315 {
316 error_stream.PutCString ("error: expression couldn't be translated to DWARF\n");
317 return false;
318 }
Chris Lattner24943d22010-06-08 16:52:24 +0000319
Sean Callananbafd6852010-07-14 23:40:29 +0000320 //////////////////////////////////////////
321 // Evaluate the generated DWARF opcodes
322 //
Chris Lattner24943d22010-06-08 16:52:24 +0000323
Sean Callananbafd6852010-07-14 23:40:29 +0000324 DataExtractor dwarf_opcodes_data (dwarf_opcodes.GetData (), dwarf_opcodes.GetSize (), eByteOrderHost, 8);
325 DWARFExpression dwarf_expr (dwarf_opcodes_data, 0, dwarf_opcodes_data.GetByteSize (), NULL);
326
327 dwarf_expr.SetExpressionLocalVariableList(&expr_local_vars);
328
329 if (log)
330 {
331 StreamString stream_string;
332
333 log->PutCString ("Expression parsed ok, dwarf opcodes:");
334
335 stream_string.PutCString ("\n");
336 stream_string.IndentMore ();
337 dwarf_expr.GetDescription (&stream_string, lldb::eDescriptionLevelVerbose);
338 stream_string.IndentLess ();
339 stream_string.EOL ();
340
341 log->PutCString (stream_string.GetString ().c_str ());
342 }
343
344 clang::ASTContext *ast_context = clang_expr.GetASTContext ();
345 Value expr_result;
346 Error expr_error;
347 success = dwarf_expr.Evaluate (&m_exe_ctx, ast_context, NULL, expr_result, &expr_error);
348
349 if (!success)
350 {
351 error_stream.Printf ("error: couldn't evaluate DWARF expression: %s\n", expr_error.AsCString ());
352 return false;
353 }
354
355 ///////////////////////////////////////
356 // Interpret the result and print it
357 //
358
359 lldb::Format format = m_options.format;
360
361 // Resolve any values that are possible
362 expr_result.ResolveValue (&m_exe_ctx, ast_context);
363
364 if (expr_result.GetContextType () == Value::eContextTypeInvalid &&
365 expr_result.GetValueType () == Value::eValueTypeScalar &&
366 format == eFormatDefault)
367 {
368 // The expression result is just a scalar with no special formatting
369 expr_result.GetScalar ().GetValue (&output_stream, m_options.show_types);
370 output_stream.EOL ();
371 return true;
372 }
373
374 // The expression result is more complext and requires special handling
375 DataExtractor data;
376 expr_error = expr_result.GetValueAsData (&m_exe_ctx, ast_context, data, 0);
377
378 if (!expr_error.Success ())
379 {
380 error_stream.Printf ("error: couldn't resolve result value: %s\n", expr_error.AsCString ());
381 return false;
382 }
383
384 if (format == eFormatDefault)
385 format = expr_result.GetValueDefaultFormat ();
386
387 void *clang_type = expr_result.GetValueOpaqueClangQualType ();
388
389 if (clang_type)
390 {
391 if (m_options.show_types)
392 Type::DumpClangTypeName (&output_stream, clang_type);
393
394 Type::DumpValue (&m_exe_ctx, // The execution context for memory and variable access
395 ast_context, // The ASTContext that the clang type belongs to
396 clang_type, // The opaque clang type we want to dump that value of
397 &output_stream, // Stream to dump to
398 format, // Format to use when dumping
399 data, // A buffer containing the bytes for the clang type
400 0, // Byte offset within "data" where value is
401 data.GetByteSize (), // Size in bytes of the value we are dumping
402 0, // Bitfield bit size
403 0, // Bitfield bit offset
404 m_options.show_types, // Show types?
405 m_options.show_summary, // Show summary?
406 m_options.debug, // Debug logging output?
407 UINT32_MAX); // Depth to dump in case this is an aggregate type
408 }
409 else
410 {
411 data.Dump (&output_stream, // Stream to dump to
412 0, // Byte offset within "data"
413 format, // Format to use when dumping
414 data.GetByteSize (), // Size in bytes of each item we are dumping
415 1, // Number of items to dump
416 UINT32_MAX, // Number of items per line
417 LLDB_INVALID_ADDRESS, // Invalid address, don't show any offset/address context
418 0, // Bitfield bit size
419 0); // Bitfield bit offset
420 }
421 output_stream.EOL();
422
Sean Callanan46b62492010-06-24 00:16:27 +0000423 return true;
424 }
Chris Lattner24943d22010-06-08 16:52:24 +0000425}
426
427bool
428CommandObjectExpression::ExecuteRawCommandString
429(
Greg Clayton63094e02010-06-23 01:19:29 +0000430 CommandInterpreter &interpreter,
Chris Lattner24943d22010-06-08 16:52:24 +0000431 const char *command,
Chris Lattner24943d22010-06-08 16:52:24 +0000432 CommandReturnObject &result
433)
434{
Sean Callanan46b62492010-06-24 00:16:27 +0000435 m_exe_ctx = interpreter.GetDebugger().GetExecutionContext();
Chris Lattner24943d22010-06-08 16:52:24 +0000436
437 m_options.ResetOptionValues();
438
439 const char * expr = NULL;
440
441 if (command[0] == '\0')
442 {
443 m_expr_lines.clear();
444 m_expr_line_count = 0;
445
Greg Clayton63094e02010-06-23 01:19:29 +0000446 InputReaderSP reader_sp (new InputReader(interpreter.GetDebugger()));
Chris Lattner24943d22010-06-08 16:52:24 +0000447 if (reader_sp)
448 {
449 Error err (reader_sp->Initialize (CommandObjectExpression::MultiLineExpressionCallback,
450 this, // baton
451 eInputReaderGranularityLine, // token size, to pass to callback function
Greg Clayton63094e02010-06-23 01:19:29 +0000452 NULL, // end token
Chris Lattner24943d22010-06-08 16:52:24 +0000453 NULL, // prompt
454 true)); // echo input
455 if (err.Success())
456 {
Greg Clayton63094e02010-06-23 01:19:29 +0000457 interpreter.GetDebugger().PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000458 result.SetStatus (eReturnStatusSuccessFinishNoResult);
459 }
460 else
461 {
462 result.AppendError (err.AsCString());
463 result.SetStatus (eReturnStatusFailed);
464 }
465 }
466 else
467 {
468 result.AppendError("out of memory");
469 result.SetStatus (eReturnStatusFailed);
470 }
471 return result.Succeeded();
472 }
473
474 if (command[0] == '-')
475 {
476 // We have some options and these options MUST end with --.
477 const char *end_options = NULL;
478 const char *s = command;
479 while (s && s[0])
480 {
481 end_options = ::strstr (s, "--");
482 if (end_options)
483 {
484 end_options += 2; // Get past the "--"
485 if (::isspace (end_options[0]))
486 {
487 expr = end_options;
488 while (::isspace (*expr))
489 ++expr;
490 break;
491 }
492 }
493 s = end_options;
494 }
495
496 if (end_options)
497 {
Greg Clayton63094e02010-06-23 01:19:29 +0000498 Args args (command, end_options - command);
499 if (!ParseOptions (interpreter, args, result))
Chris Lattner24943d22010-06-08 16:52:24 +0000500 return false;
501 }
502 }
503
Chris Lattner24943d22010-06-08 16:52:24 +0000504 if (expr == NULL)
505 expr = command;
Sean Callanan46b62492010-06-24 00:16:27 +0000506
507 return EvaluateExpression (expr, false, result.GetOutputStream(), result.GetErrorStream());
Chris Lattner24943d22010-06-08 16:52:24 +0000508}
509
510lldb::OptionDefinition
511CommandObjectExpression::CommandOptions::g_option_table[] =
512{
Greg Clayton12bec712010-06-28 21:30:43 +0000513{ LLDB_OPT_SET_ALL, false, "language", 'l', required_argument, NULL, 0, "[c|c++|objc|objc++]", "Sets the language to use when parsing the expression."},
Sean Callanan848960c2010-06-23 23:18:04 +0000514{ 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."},
515{ LLDB_OPT_SET_ALL, false, "debug", 'g', no_argument, NULL, 0, NULL, "Enable verbose debug logging of the expression parsing and evaluation."},
516{ LLDB_OPT_SET_ALL, false, "use-ir", 'i', no_argument, NULL, 0, NULL, "[Temporary] Instructs the expression evaluator to use IR instead of ASTs."},
Chris Lattner24943d22010-06-08 16:52:24 +0000517{ 0, false, NULL, 0, 0, NULL, NULL, NULL, NULL }
518};
519