blob: 75cec78096227602b4150e74c70e9be556924ebb [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
Sean Callanan841026f2010-07-23 00:16:21 +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"
Stephen Wilson63c468c2010-07-23 21:47:22 +000022#include "lldb/Expression/ClangFunction.h"
Chris Lattner24943d22010-06-08 16:52:24 +000023#include "lldb/Expression/DWARFExpression.h"
24#include "lldb/Host/Host.h"
Sean Callanan841026f2010-07-23 00:16:21 +000025#include "lldb/Core/Debugger.h"
Greg Clayton63094e02010-06-23 01:19:29 +000026#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000027#include "lldb/Interpreter/CommandReturnObject.h"
28#include "lldb/Symbol/ObjectFile.h"
29#include "lldb/Symbol/Variable.h"
30#include "lldb/Target/Process.h"
31#include "lldb/Target/StackFrame.h"
32#include "lldb/Target/Target.h"
Sean Callanan841026f2010-07-23 00:16:21 +000033#include "llvm/ADT/StringRef.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034
35using namespace lldb;
36using namespace lldb_private;
37
38CommandObjectExpression::CommandOptions::CommandOptions () :
39 Options()
40{
41 // Keep only one place to reset the values to their defaults
42 ResetOptionValues();
43}
44
45
46CommandObjectExpression::CommandOptions::~CommandOptions ()
47{
48}
49
50Error
51CommandObjectExpression::CommandOptions::SetOptionValue (int option_idx, const char *option_arg)
52{
53 Error error;
54
55 char short_option = (char) m_getopt_table[option_idx].val;
56
57 switch (short_option)
58 {
59 case 'l':
60 if (language.SetLanguageFromCString (option_arg) == false)
61 {
62 error.SetErrorStringWithFormat("Invalid language option argument '%s'.\n", option_arg);
63 }
64 break;
65
66 case 'g':
67 debug = true;
68 break;
69
70 case 'f':
71 error = Args::StringToFormat(option_arg, format);
72 break;
Sean Callanan848960c2010-06-23 23:18:04 +000073
74 case 'i':
75 use_ir = true;
76 break;
Chris Lattner24943d22010-06-08 16:52:24 +000077
78 default:
79 error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
80 break;
81 }
82
83 return error;
84}
85
86void
87CommandObjectExpression::CommandOptions::ResetOptionValues ()
88{
89 Options::ResetOptionValues();
90 language.Clear();
91 debug = false;
92 format = eFormatDefault;
93 show_types = true;
94 show_summary = true;
Sean Callanan848960c2010-06-23 23:18:04 +000095 use_ir = false;
Chris Lattner24943d22010-06-08 16:52:24 +000096}
97
98const lldb::OptionDefinition*
99CommandObjectExpression::CommandOptions::GetDefinitions ()
100{
101 return g_option_table;
102}
103
104CommandObjectExpression::CommandObjectExpression () :
105 CommandObject (
106 "expression",
107 "Evaluate a C expression in the current program context, using variables currently in scope.",
108 "expression [<cmd-options>] <expr>"),
109 m_expr_line_count (0),
110 m_expr_lines ()
111{
112 SetHelpLong(
113"Examples: \n\
114\n\
115 expr my_struct->a = my_array[3] \n\
116 expr -f bin -- (index * 8) + 5 \n\
117 expr char c[] = \"foo\"; c[0]\n");
118}
119
120CommandObjectExpression::~CommandObjectExpression ()
121{
122}
123
124Options *
125CommandObjectExpression::GetOptions ()
126{
127 return &m_options;
128}
129
130
131bool
132CommandObjectExpression::Execute
133(
Greg Clayton63094e02010-06-23 01:19:29 +0000134 CommandInterpreter &interpreter,
Chris Lattner24943d22010-06-08 16:52:24 +0000135 Args& command,
Chris Lattner24943d22010-06-08 16:52:24 +0000136 CommandReturnObject &result
137)
138{
139 return false;
140}
141
142
143size_t
144CommandObjectExpression::MultiLineExpressionCallback
145(
146 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000147 InputReader &reader,
Chris Lattner24943d22010-06-08 16:52:24 +0000148 lldb::InputReaderAction notification,
149 const char *bytes,
150 size_t bytes_len
151)
152{
Chris Lattner24943d22010-06-08 16:52:24 +0000153 CommandObjectExpression *cmd_object_expr = (CommandObjectExpression *) baton;
154
155 switch (notification)
156 {
157 case eInputReaderActivate:
Greg Clayton63094e02010-06-23 01:19:29 +0000158 reader.GetDebugger().GetOutputStream().Printf("%s\n", "Enter expressions, then terminate with an empty line to evaluate:");
Chris Lattner24943d22010-06-08 16:52:24 +0000159 // Fall through
160 case eInputReaderReactivate:
161 //if (out_fh)
Greg Clayton63094e02010-06-23 01:19:29 +0000162 // reader.GetDebugger().GetOutputStream().Printf ("%3u: ", cmd_object_expr->m_expr_line_count);
Chris Lattner24943d22010-06-08 16:52:24 +0000163 break;
164
165 case eInputReaderDeactivate:
166 break;
167
168 case eInputReaderGotToken:
169 ++cmd_object_expr->m_expr_line_count;
170 if (bytes && bytes_len)
171 {
172 cmd_object_expr->m_expr_lines.append (bytes, bytes_len + 1);
173 }
174
175 if (bytes_len == 0)
Greg Clayton63094e02010-06-23 01:19:29 +0000176 reader.SetIsDone(true);
Chris Lattner24943d22010-06-08 16:52:24 +0000177 //else if (out_fh && !reader->IsDone())
178 // ::fprintf (out_fh, "%3u: ", cmd_object_expr->m_expr_line_count);
179 break;
180
181 case eInputReaderDone:
182 {
Chris Lattner24943d22010-06-08 16:52:24 +0000183 bool bare = false;
184 cmd_object_expr->EvaluateExpression (cmd_object_expr->m_expr_lines.c_str(),
185 bare,
Greg Clayton63094e02010-06-23 01:19:29 +0000186 reader.GetDebugger().GetOutputStream(),
187 reader.GetDebugger().GetErrorStream());
Chris Lattner24943d22010-06-08 16:52:24 +0000188 }
189 break;
190 }
191
192 return bytes_len;
193}
194
195bool
196CommandObjectExpression::EvaluateExpression (const char *expr, bool bare, Stream &output_stream, Stream &error_stream)
197{
Sean Callanan46b62492010-06-24 00:16:27 +0000198 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
199
200 ////////////////////////////////////
201 // Set up the target and compiler
202 //
203
Chris Lattner24943d22010-06-08 16:52:24 +0000204 Target *target = m_exe_ctx.target;
Sean Callanan46b62492010-06-24 00:16:27 +0000205
206 if (!target)
207 {
208 error_stream.PutCString ("error: invalid target\n");
209 return false;
210 }
211
212 ConstString target_triple;
213
214 target->GetTargetTriple (target_triple);
Chris Lattner24943d22010-06-08 16:52:24 +0000215
216 if (!target_triple)
217 target_triple = Host::GetTargetTriple ();
Sean Callanan46b62492010-06-24 00:16:27 +0000218
219 if (!target_triple)
Chris Lattner24943d22010-06-08 16:52:24 +0000220 {
Sean Callanan46b62492010-06-24 00:16:27 +0000221 error_stream.PutCString ("error: invalid target triple\n");
222 return false;
223 }
224
225 ClangExpressionDeclMap expr_decl_map (&m_exe_ctx);
226 ClangExpression clang_expr (target_triple.AsCString (), &expr_decl_map);
227
228 //////////////////////////
229 // Parse the expression
230 //
231
232 unsigned num_errors;
233
234 if (bare)
235 num_errors = clang_expr.ParseBareExpression (llvm::StringRef (expr), error_stream);
236 else
Sean Callanan8c6934d2010-07-01 20:08:22 +0000237 num_errors = clang_expr.ParseExpression (expr, error_stream, m_options.use_ir);
Sean Callanan46b62492010-06-24 00:16:27 +0000238
239 if (num_errors)
240 {
241 error_stream.Printf ("error: %d errors parsing expression\n", num_errors);
242 return false;
243 }
244
245 ///////////////////////////////////////////////
246 // Convert the output of the parser to DWARF
247 //
248
249 StreamString dwarf_opcodes;
250 dwarf_opcodes.SetByteOrder (eByteOrderHost);
251 dwarf_opcodes.GetFlags ().Set (Stream::eBinary);
252
253 ClangExpressionVariableList expr_local_vars;
254
255 bool success;
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000256 bool canInterpret = false;
Sean Callanan46b62492010-06-24 00:16:27 +0000257
Sean Callanan841026f2010-07-23 00:16:21 +0000258 clang::ASTContext *ast_context = clang_expr.GetASTContext ();
259 Value expr_result;
260 Error expr_error;
261
Sean Callanan46b62492010-06-24 00:16:27 +0000262 if (m_options.use_ir)
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000263 {
264 canInterpret = clang_expr.ConvertIRToDWARF (expr_local_vars, dwarf_opcodes);
265
266 if (canInterpret)
267 {
268 if (log)
269 log->Printf("Code can be interpreted.");
270 success = true;
271 }
272 else
273 {
274 if (log)
275 log->Printf("Code cannot be interpreted and must be run in the target.");
276 success = clang_expr.PrepareIRForTarget (expr_local_vars);
277 }
Sean Callananbafd6852010-07-14 23:40:29 +0000278
279 if (!success)
280 {
281 error_stream.PutCString ("error: expression couldn't be converted to IR\n");
282 return false;
283 }
284
285 if (canInterpret)
286 {
287 // TODO interpret IR
288 return false;
289 }
290 else
291 {
292 if (!clang_expr.JITFunction (m_exe_ctx, "___clang_expr"))
293 {
294 error_stream.PutCString ("error: IR could not be JIT compiled\n");
295 return false;
296 }
297
298 if (!clang_expr.WriteJITCode (m_exe_ctx))
299 {
300 error_stream.PutCString ("error: JIT code could not be written to the target\n");
301 return false;
302 }
303
304 lldb::addr_t function_address(clang_expr.GetFunctionAddress ("___clang_expr"));
305
306 if (function_address == LLDB_INVALID_ADDRESS)
307 {
308 error_stream.PutCString ("JIT compiled code's address couldn't be found\n");
309 return false;
310 }
311
Sean Callananf328c9f2010-07-20 23:31:16 +0000312 lldb::addr_t struct_address;
Sean Callanan810f22d2010-07-16 00:09:46 +0000313
Sean Callanan841026f2010-07-23 00:16:21 +0000314 if (!expr_decl_map.Materialize(&m_exe_ctx, struct_address, expr_error))
Sean Callanan810f22d2010-07-16 00:09:46 +0000315 {
Sean Callanan841026f2010-07-23 00:16:21 +0000316 error_stream.Printf ("Couldn't materialize struct: %s\n", expr_error.AsCString("unknown error"));
Sean Callanan810f22d2010-07-16 00:09:46 +0000317 return false;
318 }
319
Sean Callanan841026f2010-07-23 00:16:21 +0000320 if (log)
321 {
322 log->Printf("Function address : 0x%llx", (uint64_t)function_address);
323 log->Printf("Structure address : 0x%llx", (uint64_t)struct_address);
Sean Callanan841026f2010-07-23 00:16:21 +0000324
Sean Callanan8541f2f2010-07-23 02:19:15 +0000325 StreamString insns;
326
327 Error err = clang_expr.DisassembleFunction(insns, m_exe_ctx, "___clang_expr");
328
329 if (!err.Success())
330 {
331 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
332 }
333 else
334 {
335 log->Printf("Function disassembly:\n%s", insns.GetData());
336 }
337 }
338
Sean Callanan841026f2010-07-23 00:16:21 +0000339 ClangFunction::ExecutionResults execution_result =
340 ClangFunction::ExecuteFunction (m_exe_ctx, function_address, struct_address, true, true, 10000, error_stream);
341
342 if (execution_result != ClangFunction::eExecutionCompleted)
343 {
344 const char *result_name;
345
346 switch (execution_result)
347 {
348 case ClangFunction::eExecutionCompleted:
349 result_name = "eExecutionCompleted";
350 break;
351 case ClangFunction::eExecutionDiscarded:
352 result_name = "eExecutionDiscarded";
353 break;
354 case ClangFunction::eExecutionInterrupted:
355 result_name = "eExecutionInterrupted";
356 break;
357 case ClangFunction::eExecutionSetupError:
358 result_name = "eExecutionSetupError";
359 break;
360 case ClangFunction::eExecutionTimedOut:
361 result_name = "eExecutionTimedOut";
362 break;
363 }
364
365 error_stream.Printf ("Couldn't execute function; result was %s\n", result_name);
366 return false;
367 }
368
369 if (!expr_decl_map.Dematerialize(&m_exe_ctx, expr_result, expr_error))
370 {
371 error_stream.Printf ("Couldn't dematerialize struct: %s\n", expr_error.AsCString("unknown error"));
372 return false;
373 }
Sean Callananbafd6852010-07-14 23:40:29 +0000374 }
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000375 }
Sean Callanan46b62492010-06-24 00:16:27 +0000376 else
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000377 {
Sean Callanan46b62492010-06-24 00:16:27 +0000378 success = (clang_expr.ConvertExpressionToDWARF (expr_local_vars, dwarf_opcodes) == 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000379
Sean Callananbafd6852010-07-14 23:40:29 +0000380 if (!success)
381 {
382 error_stream.PutCString ("error: expression couldn't be translated to DWARF\n");
383 return false;
384 }
Chris Lattner24943d22010-06-08 16:52:24 +0000385
Sean Callananbafd6852010-07-14 23:40:29 +0000386 //////////////////////////////////////////
387 // Evaluate the generated DWARF opcodes
388 //
Chris Lattner24943d22010-06-08 16:52:24 +0000389
Sean Callananbafd6852010-07-14 23:40:29 +0000390 DataExtractor dwarf_opcodes_data (dwarf_opcodes.GetData (), dwarf_opcodes.GetSize (), eByteOrderHost, 8);
391 DWARFExpression dwarf_expr (dwarf_opcodes_data, 0, dwarf_opcodes_data.GetByteSize (), NULL);
392
393 dwarf_expr.SetExpressionLocalVariableList(&expr_local_vars);
394
395 if (log)
396 {
397 StreamString stream_string;
398
399 log->PutCString ("Expression parsed ok, dwarf opcodes:");
400
401 stream_string.PutCString ("\n");
402 stream_string.IndentMore ();
403 dwarf_expr.GetDescription (&stream_string, lldb::eDescriptionLevelVerbose);
404 stream_string.IndentLess ();
405 stream_string.EOL ();
406
407 log->PutCString (stream_string.GetString ().c_str ());
408 }
409
Sean Callananbafd6852010-07-14 23:40:29 +0000410 success = dwarf_expr.Evaluate (&m_exe_ctx, ast_context, NULL, expr_result, &expr_error);
411
412 if (!success)
413 {
414 error_stream.Printf ("error: couldn't evaluate DWARF expression: %s\n", expr_error.AsCString ());
415 return false;
416 }
Sean Callanan841026f2010-07-23 00:16:21 +0000417 }
Sean Callananbafd6852010-07-14 23:40:29 +0000418
Sean Callanan841026f2010-07-23 00:16:21 +0000419 ///////////////////////////////////////
420 // Interpret the result and print it
421 //
422
423 lldb::Format format = m_options.format;
424
425 // Resolve any values that are possible
426 expr_result.ResolveValue (&m_exe_ctx, ast_context);
427
428 if (expr_result.GetContextType () == Value::eContextTypeInvalid &&
429 expr_result.GetValueType () == Value::eValueTypeScalar &&
430 format == eFormatDefault)
431 {
432 // The expression result is just a scalar with no special formatting
433 expr_result.GetScalar ().GetValue (&output_stream, m_options.show_types);
434 output_stream.EOL ();
Sean Callanan46b62492010-06-24 00:16:27 +0000435 return true;
436 }
Sean Callanan841026f2010-07-23 00:16:21 +0000437
438 // The expression result is more complext and requires special handling
439 DataExtractor data;
440 expr_error = expr_result.GetValueAsData (&m_exe_ctx, ast_context, data, 0);
441
442 if (!expr_error.Success ())
443 {
444 error_stream.Printf ("error: couldn't resolve result value: %s\n", expr_error.AsCString ());
445 return false;
446 }
447
448 if (format == eFormatDefault)
449 format = expr_result.GetValueDefaultFormat ();
450
451 void *clang_type = expr_result.GetValueOpaqueClangQualType ();
452
453 if (clang_type)
454 {
455 if (m_options.show_types)
456 output_stream.PutCString(ClangASTType::GetClangTypeName (clang_type).GetCString());
457
458 ClangASTType::DumpValue (ast_context, // The ASTContext that the clang type belongs to
459 clang_type, // The opaque clang type we want to dump that value of
460 &m_exe_ctx, // The execution context for memory and variable access
461 &output_stream, // Stream to dump to
462 format, // Format to use when dumping
463 data, // A buffer containing the bytes for the clang type
464 0, // Byte offset within "data" where value is
465 data.GetByteSize (), // Size in bytes of the value we are dumping
466 0, // Bitfield bit size
467 0, // Bitfield bit offset
468 m_options.show_types, // Show types?
469 m_options.show_summary, // Show summary?
470 m_options.debug, // Debug logging output?
471 UINT32_MAX); // Depth to dump in case this is an aggregate type
472 }
473 else
474 {
475 data.Dump (&output_stream, // Stream to dump to
476 0, // Byte offset within "data"
477 format, // Format to use when dumping
478 data.GetByteSize (), // Size in bytes of each item we are dumping
479 1, // Number of items to dump
480 UINT32_MAX, // Number of items per line
481 LLDB_INVALID_ADDRESS, // Invalid address, don't show any offset/address context
482 0, // Bitfield bit size
483 0); // Bitfield bit offset
484 }
485 output_stream.EOL();
486
487 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000488}
489
490bool
491CommandObjectExpression::ExecuteRawCommandString
492(
Greg Clayton63094e02010-06-23 01:19:29 +0000493 CommandInterpreter &interpreter,
Chris Lattner24943d22010-06-08 16:52:24 +0000494 const char *command,
Chris Lattner24943d22010-06-08 16:52:24 +0000495 CommandReturnObject &result
496)
497{
Sean Callanan46b62492010-06-24 00:16:27 +0000498 m_exe_ctx = interpreter.GetDebugger().GetExecutionContext();
Chris Lattner24943d22010-06-08 16:52:24 +0000499
500 m_options.ResetOptionValues();
501
502 const char * expr = NULL;
503
504 if (command[0] == '\0')
505 {
506 m_expr_lines.clear();
507 m_expr_line_count = 0;
508
Greg Clayton63094e02010-06-23 01:19:29 +0000509 InputReaderSP reader_sp (new InputReader(interpreter.GetDebugger()));
Chris Lattner24943d22010-06-08 16:52:24 +0000510 if (reader_sp)
511 {
512 Error err (reader_sp->Initialize (CommandObjectExpression::MultiLineExpressionCallback,
513 this, // baton
514 eInputReaderGranularityLine, // token size, to pass to callback function
Greg Clayton63094e02010-06-23 01:19:29 +0000515 NULL, // end token
Chris Lattner24943d22010-06-08 16:52:24 +0000516 NULL, // prompt
517 true)); // echo input
518 if (err.Success())
519 {
Greg Clayton63094e02010-06-23 01:19:29 +0000520 interpreter.GetDebugger().PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000521 result.SetStatus (eReturnStatusSuccessFinishNoResult);
522 }
523 else
524 {
525 result.AppendError (err.AsCString());
526 result.SetStatus (eReturnStatusFailed);
527 }
528 }
529 else
530 {
531 result.AppendError("out of memory");
532 result.SetStatus (eReturnStatusFailed);
533 }
534 return result.Succeeded();
535 }
536
537 if (command[0] == '-')
538 {
539 // We have some options and these options MUST end with --.
540 const char *end_options = NULL;
541 const char *s = command;
542 while (s && s[0])
543 {
544 end_options = ::strstr (s, "--");
545 if (end_options)
546 {
547 end_options += 2; // Get past the "--"
548 if (::isspace (end_options[0]))
549 {
550 expr = end_options;
551 while (::isspace (*expr))
552 ++expr;
553 break;
554 }
555 }
556 s = end_options;
557 }
558
559 if (end_options)
560 {
Greg Clayton63094e02010-06-23 01:19:29 +0000561 Args args (command, end_options - command);
562 if (!ParseOptions (interpreter, args, result))
Chris Lattner24943d22010-06-08 16:52:24 +0000563 return false;
564 }
565 }
566
Chris Lattner24943d22010-06-08 16:52:24 +0000567 if (expr == NULL)
568 expr = command;
Sean Callanan46b62492010-06-24 00:16:27 +0000569
570 return EvaluateExpression (expr, false, result.GetOutputStream(), result.GetErrorStream());
Chris Lattner24943d22010-06-08 16:52:24 +0000571}
572
573lldb::OptionDefinition
574CommandObjectExpression::CommandOptions::g_option_table[] =
575{
Greg Clayton12bec712010-06-28 21:30:43 +0000576{ 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 +0000577{ 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."},
578{ LLDB_OPT_SET_ALL, false, "debug", 'g', no_argument, NULL, 0, NULL, "Enable verbose debug logging of the expression parsing and evaluation."},
579{ 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 +0000580{ 0, false, NULL, 0, 0, NULL, NULL, NULL, NULL }
581};
582