blob: 303ca17cc56d86ed3dd93eef3e0de15c9ac85332 [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"
Sean Callanan841026f2010-07-23 00:16:21 +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);
324 }
325
326 ClangFunction::ExecutionResults execution_result =
327 ClangFunction::ExecuteFunction (m_exe_ctx, function_address, struct_address, true, true, 10000, error_stream);
328
329 if (execution_result != ClangFunction::eExecutionCompleted)
330 {
331 const char *result_name;
332
333 switch (execution_result)
334 {
335 case ClangFunction::eExecutionCompleted:
336 result_name = "eExecutionCompleted";
337 break;
338 case ClangFunction::eExecutionDiscarded:
339 result_name = "eExecutionDiscarded";
340 break;
341 case ClangFunction::eExecutionInterrupted:
342 result_name = "eExecutionInterrupted";
343 break;
344 case ClangFunction::eExecutionSetupError:
345 result_name = "eExecutionSetupError";
346 break;
347 case ClangFunction::eExecutionTimedOut:
348 result_name = "eExecutionTimedOut";
349 break;
350 }
351
352 error_stream.Printf ("Couldn't execute function; result was %s\n", result_name);
353 return false;
354 }
355
356 if (!expr_decl_map.Dematerialize(&m_exe_ctx, expr_result, expr_error))
357 {
358 error_stream.Printf ("Couldn't dematerialize struct: %s\n", expr_error.AsCString("unknown error"));
359 return false;
360 }
Sean Callananbafd6852010-07-14 23:40:29 +0000361 }
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000362 }
Sean Callanan46b62492010-06-24 00:16:27 +0000363 else
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000364 {
Sean Callanan46b62492010-06-24 00:16:27 +0000365 success = (clang_expr.ConvertExpressionToDWARF (expr_local_vars, dwarf_opcodes) == 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000366
Sean Callananbafd6852010-07-14 23:40:29 +0000367 if (!success)
368 {
369 error_stream.PutCString ("error: expression couldn't be translated to DWARF\n");
370 return false;
371 }
Chris Lattner24943d22010-06-08 16:52:24 +0000372
Sean Callananbafd6852010-07-14 23:40:29 +0000373 //////////////////////////////////////////
374 // Evaluate the generated DWARF opcodes
375 //
Chris Lattner24943d22010-06-08 16:52:24 +0000376
Sean Callananbafd6852010-07-14 23:40:29 +0000377 DataExtractor dwarf_opcodes_data (dwarf_opcodes.GetData (), dwarf_opcodes.GetSize (), eByteOrderHost, 8);
378 DWARFExpression dwarf_expr (dwarf_opcodes_data, 0, dwarf_opcodes_data.GetByteSize (), NULL);
379
380 dwarf_expr.SetExpressionLocalVariableList(&expr_local_vars);
381
382 if (log)
383 {
384 StreamString stream_string;
385
386 log->PutCString ("Expression parsed ok, dwarf opcodes:");
387
388 stream_string.PutCString ("\n");
389 stream_string.IndentMore ();
390 dwarf_expr.GetDescription (&stream_string, lldb::eDescriptionLevelVerbose);
391 stream_string.IndentLess ();
392 stream_string.EOL ();
393
394 log->PutCString (stream_string.GetString ().c_str ());
395 }
396
Sean Callananbafd6852010-07-14 23:40:29 +0000397 success = dwarf_expr.Evaluate (&m_exe_ctx, ast_context, NULL, expr_result, &expr_error);
398
399 if (!success)
400 {
401 error_stream.Printf ("error: couldn't evaluate DWARF expression: %s\n", expr_error.AsCString ());
402 return false;
403 }
Sean Callanan841026f2010-07-23 00:16:21 +0000404 }
Sean Callananbafd6852010-07-14 23:40:29 +0000405
Sean Callanan841026f2010-07-23 00:16:21 +0000406 ///////////////////////////////////////
407 // Interpret the result and print it
408 //
409
410 lldb::Format format = m_options.format;
411
412 // Resolve any values that are possible
413 expr_result.ResolveValue (&m_exe_ctx, ast_context);
414
415 if (expr_result.GetContextType () == Value::eContextTypeInvalid &&
416 expr_result.GetValueType () == Value::eValueTypeScalar &&
417 format == eFormatDefault)
418 {
419 // The expression result is just a scalar with no special formatting
420 expr_result.GetScalar ().GetValue (&output_stream, m_options.show_types);
421 output_stream.EOL ();
Sean Callanan46b62492010-06-24 00:16:27 +0000422 return true;
423 }
Sean Callanan841026f2010-07-23 00:16:21 +0000424
425 // The expression result is more complext and requires special handling
426 DataExtractor data;
427 expr_error = expr_result.GetValueAsData (&m_exe_ctx, ast_context, data, 0);
428
429 if (!expr_error.Success ())
430 {
431 error_stream.Printf ("error: couldn't resolve result value: %s\n", expr_error.AsCString ());
432 return false;
433 }
434
435 if (format == eFormatDefault)
436 format = expr_result.GetValueDefaultFormat ();
437
438 void *clang_type = expr_result.GetValueOpaqueClangQualType ();
439
440 if (clang_type)
441 {
442 if (m_options.show_types)
443 output_stream.PutCString(ClangASTType::GetClangTypeName (clang_type).GetCString());
444
445 ClangASTType::DumpValue (ast_context, // The ASTContext that the clang type belongs to
446 clang_type, // The opaque clang type we want to dump that value of
447 &m_exe_ctx, // The execution context for memory and variable access
448 &output_stream, // Stream to dump to
449 format, // Format to use when dumping
450 data, // A buffer containing the bytes for the clang type
451 0, // Byte offset within "data" where value is
452 data.GetByteSize (), // Size in bytes of the value we are dumping
453 0, // Bitfield bit size
454 0, // Bitfield bit offset
455 m_options.show_types, // Show types?
456 m_options.show_summary, // Show summary?
457 m_options.debug, // Debug logging output?
458 UINT32_MAX); // Depth to dump in case this is an aggregate type
459 }
460 else
461 {
462 data.Dump (&output_stream, // Stream to dump to
463 0, // Byte offset within "data"
464 format, // Format to use when dumping
465 data.GetByteSize (), // Size in bytes of each item we are dumping
466 1, // Number of items to dump
467 UINT32_MAX, // Number of items per line
468 LLDB_INVALID_ADDRESS, // Invalid address, don't show any offset/address context
469 0, // Bitfield bit size
470 0); // Bitfield bit offset
471 }
472 output_stream.EOL();
473
474 return true;
Chris Lattner24943d22010-06-08 16:52:24 +0000475}
476
477bool
478CommandObjectExpression::ExecuteRawCommandString
479(
Greg Clayton63094e02010-06-23 01:19:29 +0000480 CommandInterpreter &interpreter,
Chris Lattner24943d22010-06-08 16:52:24 +0000481 const char *command,
Chris Lattner24943d22010-06-08 16:52:24 +0000482 CommandReturnObject &result
483)
484{
Sean Callanan46b62492010-06-24 00:16:27 +0000485 m_exe_ctx = interpreter.GetDebugger().GetExecutionContext();
Chris Lattner24943d22010-06-08 16:52:24 +0000486
487 m_options.ResetOptionValues();
488
489 const char * expr = NULL;
490
491 if (command[0] == '\0')
492 {
493 m_expr_lines.clear();
494 m_expr_line_count = 0;
495
Greg Clayton63094e02010-06-23 01:19:29 +0000496 InputReaderSP reader_sp (new InputReader(interpreter.GetDebugger()));
Chris Lattner24943d22010-06-08 16:52:24 +0000497 if (reader_sp)
498 {
499 Error err (reader_sp->Initialize (CommandObjectExpression::MultiLineExpressionCallback,
500 this, // baton
501 eInputReaderGranularityLine, // token size, to pass to callback function
Greg Clayton63094e02010-06-23 01:19:29 +0000502 NULL, // end token
Chris Lattner24943d22010-06-08 16:52:24 +0000503 NULL, // prompt
504 true)); // echo input
505 if (err.Success())
506 {
Greg Clayton63094e02010-06-23 01:19:29 +0000507 interpreter.GetDebugger().PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000508 result.SetStatus (eReturnStatusSuccessFinishNoResult);
509 }
510 else
511 {
512 result.AppendError (err.AsCString());
513 result.SetStatus (eReturnStatusFailed);
514 }
515 }
516 else
517 {
518 result.AppendError("out of memory");
519 result.SetStatus (eReturnStatusFailed);
520 }
521 return result.Succeeded();
522 }
523
524 if (command[0] == '-')
525 {
526 // We have some options and these options MUST end with --.
527 const char *end_options = NULL;
528 const char *s = command;
529 while (s && s[0])
530 {
531 end_options = ::strstr (s, "--");
532 if (end_options)
533 {
534 end_options += 2; // Get past the "--"
535 if (::isspace (end_options[0]))
536 {
537 expr = end_options;
538 while (::isspace (*expr))
539 ++expr;
540 break;
541 }
542 }
543 s = end_options;
544 }
545
546 if (end_options)
547 {
Greg Clayton63094e02010-06-23 01:19:29 +0000548 Args args (command, end_options - command);
549 if (!ParseOptions (interpreter, args, result))
Chris Lattner24943d22010-06-08 16:52:24 +0000550 return false;
551 }
552 }
553
Chris Lattner24943d22010-06-08 16:52:24 +0000554 if (expr == NULL)
555 expr = command;
Sean Callanan46b62492010-06-24 00:16:27 +0000556
557 return EvaluateExpression (expr, false, result.GetOutputStream(), result.GetErrorStream());
Chris Lattner24943d22010-06-08 16:52:24 +0000558}
559
560lldb::OptionDefinition
561CommandObjectExpression::CommandOptions::g_option_table[] =
562{
Greg Clayton12bec712010-06-28 21:30:43 +0000563{ 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 +0000564{ 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."},
565{ LLDB_OPT_SET_ALL, false, "debug", 'g', no_argument, NULL, 0, NULL, "Enable verbose debug logging of the expression parsing and evaluation."},
566{ 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 +0000567{ 0, false, NULL, 0, 0, NULL, NULL, NULL, NULL }
568};
569