blob: e60ae2b3a91bd9fe2b79904a844bcc6c3f69dc74 [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{
197 bool success = false;
198 ConstString target_triple;
199 Target *target = m_exe_ctx.target;
200 if (target)
201 target->GetTargetTriple(target_triple);
202
203 if (!target_triple)
204 target_triple = Host::GetTargetTriple ();
205
Chris Lattner24943d22010-06-08 16:52:24 +0000206 if (target_triple)
207 {
208 const bool show_types = m_options.show_types;
209 const bool show_summary = m_options.show_summary;
210 const bool debug = m_options.debug;
211
212 ClangExpressionDeclMap expr_decl_map(&m_exe_ctx);
213 ClangExpression clang_expr(target_triple.AsCString(), &expr_decl_map);
214
215 unsigned num_errors = 0;
216
217 if (bare)
218 num_errors = clang_expr.ParseBareExpression (llvm::StringRef(expr), error_stream);
219 else
220 num_errors = clang_expr.ParseExpression (expr, error_stream);
221
222 if (num_errors == 0)
223 {
224 StreamString dwarf_opcodes;
225 dwarf_opcodes.SetByteOrder(eByteOrderHost);
226 dwarf_opcodes.GetFlags().Set(Stream::eBinary);
227 ClangExpressionVariableList expr_local_vars;
Sean Callanan848960c2010-06-23 23:18:04 +0000228
229 bool success;
230
231 if (m_options.use_ir)
232 success = (clang_expr.ConvertIRToDWARF (expr_local_vars, dwarf_opcodes) == 0);
233 else
234 success = (clang_expr.ConvertExpressionToDWARF (expr_local_vars, dwarf_opcodes) == 0);
235
236 if (!success)
237 {
238 output_stream << "Expression couldn't be translated to DWARF\n";
239 return false;
240 }
Chris Lattner24943d22010-06-08 16:52:24 +0000241
242 DataExtractor dwarf_opcodes_data(dwarf_opcodes.GetData(), dwarf_opcodes.GetSize(), eByteOrderHost, 8);
243 DWARFExpression expr(dwarf_opcodes_data, 0, dwarf_opcodes_data.GetByteSize(), NULL);
244 expr.SetExpressionLocalVariableList(&expr_local_vars);
245 if (debug)
246 {
247 output_stream << "Expression parsed ok, dwarf opcodes:";
248 output_stream.IndentMore();
249 expr.GetDescription(&output_stream, lldb::eDescriptionLevelVerbose);
250 output_stream.IndentLess();
251 output_stream.EOL();
252 }
253
254 clang::ASTContext *ast_context = clang_expr.GetASTContext();
255 Value expr_result;
256 Error expr_error;
257 bool expr_success = expr.Evaluate (&m_exe_ctx, ast_context, NULL, expr_result, &expr_error);
258 if (expr_success)
259 {
260 lldb::Format format = m_options.format;
261
262 // Resolve any values that are possible
263 expr_result.ResolveValue(&m_exe_ctx, ast_context);
264
265 if (expr_result.GetContextType() == Value::eContextTypeInvalid &&
266 expr_result.GetValueType() == Value::eValueTypeScalar &&
267 format == eFormatDefault)
268 {
269 // The expression result is just a scalar with no special formatting
270 expr_result.GetScalar().GetValue (&output_stream, show_types);
271 output_stream.EOL();
272 }
273 else
274 {
275 DataExtractor data;
276 expr_error = expr_result.GetValueAsData (&m_exe_ctx, ast_context, data, 0);
277 if (expr_error.Success())
278 {
279 if (format == eFormatDefault)
280 format = expr_result.GetValueDefaultFormat ();
281
282 void *clang_type = expr_result.GetValueOpaqueClangQualType();
283 if (clang_type)
284 {
285 if (show_types)
286 Type::DumpClangTypeName(&output_stream, clang_type);
287
288 Type::DumpValue (
289 &m_exe_ctx, // The execution context for memory and variable access
290 ast_context, // The ASTContext that the clang type belongs to
291 clang_type, // The opaque clang type we want to dump that value of
292 &output_stream, // Stream to dump to
293 format, // Format to use when dumping
294 data, // A buffer containing the bytes for the clang type
295 0, // Byte offset within "data" where value is
296 data.GetByteSize(), // Size in bytes of the value we are dumping
297 0, // Bitfield bit size
298 0, // Bitfield bit offset
299 show_types, // Show types?
300 show_summary, // Show summary?
301 debug, // Debug logging output?
302 UINT32_MAX); // Depth to dump in case this is an aggregate type
303 }
304 else
305 {
306 data.Dump(&output_stream, // Stream to dump to
307 0, // Byte offset within "data"
308 format, // Format to use when dumping
309 data.GetByteSize(), // Size in bytes of each item we are dumping
310 1, // Number of items to dump
311 UINT32_MAX, // Number of items per line
312 LLDB_INVALID_ADDRESS, // Invalid address, don't show any offset/address context
313 0, // Bitfield bit size
314 0); // Bitfield bit offset
315 }
316 output_stream.EOL();
317 }
318 else
319 {
320 error_stream.Printf ("error: %s\n", expr_error.AsCString());
321 success = false;
322 }
323 }
324 }
325 else
326 {
327 error_stream.Printf ("error: %s\n", expr_error.AsCString());
328 }
329 }
330 }
331 else
332 {
333 error_stream.PutCString ("error: invalid target triple\n");
334 }
335
336 return success;
337}
338
339bool
340CommandObjectExpression::ExecuteRawCommandString
341(
Greg Clayton63094e02010-06-23 01:19:29 +0000342 CommandInterpreter &interpreter,
Chris Lattner24943d22010-06-08 16:52:24 +0000343 const char *command,
Chris Lattner24943d22010-06-08 16:52:24 +0000344 CommandReturnObject &result
345)
346{
347 ConstString target_triple;
Greg Clayton63094e02010-06-23 01:19:29 +0000348 Target *target = interpreter.GetDebugger().GetCurrentTarget().get();
Chris Lattner24943d22010-06-08 16:52:24 +0000349 if (target)
350 target->GetTargetTriple(target_triple);
351
352 if (!target_triple)
353 target_triple = Host::GetTargetTriple ();
354
Greg Clayton63094e02010-06-23 01:19:29 +0000355 ExecutionContext exe_ctx(interpreter.GetDebugger().GetExecutionContext());
Chris Lattner24943d22010-06-08 16:52:24 +0000356
357 Stream &output_stream = result.GetOutputStream();
358
359 m_options.ResetOptionValues();
360
361 const char * expr = NULL;
362
363 if (command[0] == '\0')
364 {
365 m_expr_lines.clear();
366 m_expr_line_count = 0;
367
Greg Clayton63094e02010-06-23 01:19:29 +0000368 InputReaderSP reader_sp (new InputReader(interpreter.GetDebugger()));
Chris Lattner24943d22010-06-08 16:52:24 +0000369 if (reader_sp)
370 {
371 Error err (reader_sp->Initialize (CommandObjectExpression::MultiLineExpressionCallback,
372 this, // baton
373 eInputReaderGranularityLine, // token size, to pass to callback function
Greg Clayton63094e02010-06-23 01:19:29 +0000374 NULL, // end token
Chris Lattner24943d22010-06-08 16:52:24 +0000375 NULL, // prompt
376 true)); // echo input
377 if (err.Success())
378 {
Greg Clayton63094e02010-06-23 01:19:29 +0000379 interpreter.GetDebugger().PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000380 result.SetStatus (eReturnStatusSuccessFinishNoResult);
381 }
382 else
383 {
384 result.AppendError (err.AsCString());
385 result.SetStatus (eReturnStatusFailed);
386 }
387 }
388 else
389 {
390 result.AppendError("out of memory");
391 result.SetStatus (eReturnStatusFailed);
392 }
393 return result.Succeeded();
394 }
395
396 if (command[0] == '-')
397 {
398 // We have some options and these options MUST end with --.
399 const char *end_options = NULL;
400 const char *s = command;
401 while (s && s[0])
402 {
403 end_options = ::strstr (s, "--");
404 if (end_options)
405 {
406 end_options += 2; // Get past the "--"
407 if (::isspace (end_options[0]))
408 {
409 expr = end_options;
410 while (::isspace (*expr))
411 ++expr;
412 break;
413 }
414 }
415 s = end_options;
416 }
417
418 if (end_options)
419 {
Greg Clayton63094e02010-06-23 01:19:29 +0000420 Args args (command, end_options - command);
421 if (!ParseOptions (interpreter, args, result))
Chris Lattner24943d22010-06-08 16:52:24 +0000422 return false;
423 }
424 }
425
426 const bool show_types = m_options.show_types;
427 const bool show_summary = m_options.show_summary;
428 const bool debug = m_options.debug;
429
430
431 if (expr == NULL)
432 expr = command;
433
434 if (target_triple)
435 {
436 ClangExpressionDeclMap expr_decl_map(&exe_ctx);
437
438 ClangExpression clang_expr(target_triple.AsCString(), &expr_decl_map);
439
440 unsigned num_errors = clang_expr.ParseExpression (expr, result.GetErrorStream());
441
442 if (num_errors == 0)
443 {
444 StreamString dwarf_opcodes;
445 dwarf_opcodes.SetByteOrder(eByteOrderHost);
446 dwarf_opcodes.GetFlags().Set(Stream::eBinary);
447 ClangExpressionVariableList expr_local_vars;
Sean Callanan848960c2010-06-23 23:18:04 +0000448
449 bool success = true;
450
451 if (m_options.use_ir)
452 success = (clang_expr.ConvertIRToDWARF (expr_local_vars, dwarf_opcodes) == 0);
453 else
454 success = (clang_expr.ConvertExpressionToDWARF (expr_local_vars, dwarf_opcodes) == 0);
455
Chris Lattner24943d22010-06-08 16:52:24 +0000456
457 result.SetStatus (eReturnStatusSuccessFinishResult);
458
459 DataExtractor dwarf_opcodes_data(dwarf_opcodes.GetData(), dwarf_opcodes.GetSize(), eByteOrderHost, 8);
460 DWARFExpression expr(dwarf_opcodes_data, 0, dwarf_opcodes_data.GetByteSize(), NULL);
461 expr.SetExpressionLocalVariableList(&expr_local_vars);
462 expr.SetExpressionDeclMap(&expr_decl_map);
Sean Callanan848960c2010-06-23 23:18:04 +0000463
Chris Lattner24943d22010-06-08 16:52:24 +0000464 if (debug)
465 {
466 output_stream << "Expression parsed ok, dwarf opcodes:";
467 output_stream.IndentMore();
468 expr.GetDescription(&output_stream, lldb::eDescriptionLevelVerbose);
469 output_stream.IndentLess();
470 output_stream.EOL();
471 }
472
473 clang::ASTContext *ast_context = clang_expr.GetASTContext();
474 Value expr_result;
475 Error expr_error;
476 bool expr_success = expr.Evaluate (&exe_ctx, ast_context, NULL, expr_result, &expr_error);
477 if (expr_success)
478 {
479 lldb::Format format = m_options.format;
480
481 // Resolve any values that are possible
482 expr_result.ResolveValue(&exe_ctx, ast_context);
483
484 if (expr_result.GetContextType() == Value::eContextTypeInvalid &&
485 expr_result.GetValueType() == Value::eValueTypeScalar &&
486 format == eFormatDefault)
487 {
488 // The expression result is just a scalar with no special formatting
489 expr_result.GetScalar().GetValue (&output_stream, show_types);
490 output_stream.EOL();
491 }
492 else
493 {
494 DataExtractor data;
495 expr_error = expr_result.GetValueAsData (&exe_ctx, ast_context, data, 0);
496 if (expr_error.Success())
497 {
498 if (format == eFormatDefault)
499 format = expr_result.GetValueDefaultFormat ();
500
501 void *clang_type = expr_result.GetValueOpaqueClangQualType();
502 if (clang_type)
503 {
504 if (show_types)
505 Type::DumpClangTypeName(&output_stream, clang_type);
506
507 Type::DumpValue (
508 &exe_ctx, // The execution context for memory and variable access
509 ast_context, // The ASTContext that the clang type belongs to
510 clang_type, // The opaque clang type we want to dump that value of
511 &output_stream, // Stream to dump to
512 format, // Format to use when dumping
513 data, // A buffer containing the bytes for the clang type
514 0, // Byte offset within "data" where value is
515 data.GetByteSize(), // Size in bytes of the value we are dumping
516 0, // Bitfield bit size
517 0, // Bitfield bit offset
518 show_types, // Show types?
519 show_summary, // Show summary?
520 debug, // Debug logging output?
521 UINT32_MAX); // Depth to dump in case this is an aggregate type
522 }
523 else
524 {
525 data.Dump(&output_stream, // Stream to dump to
526 0, // Byte offset within "data"
527 format, // Format to use when dumping
528 data.GetByteSize(), // Size in bytes of each item we are dumping
529 1, // Number of items to dump
530 UINT32_MAX, // Number of items per line
531 LLDB_INVALID_ADDRESS, // Invalid address, don't show any offset/address context
532 0, // Bitfield bit size
533 0); // Bitfield bit offset
534 }
535 output_stream.EOL();
536 }
537 else
538 {
539 result.AppendError(expr_error.AsCString());
540 result.SetStatus (eReturnStatusFailed);
541 }
542 }
543 }
544 else
545 {
546 result.AppendError (expr_error.AsCString());
547 result.SetStatus (eReturnStatusFailed);
548 }
549 }
550 else
551 {
552 result.SetStatus (eReturnStatusFailed);
553 }
554 }
555 else
556 {
557 result.AppendError ("invalid target triple");
558 result.SetStatus (eReturnStatusFailed);
559 }
560 return result.Succeeded();
561}
562
563lldb::OptionDefinition
564CommandObjectExpression::CommandOptions::g_option_table[] =
565{
Sean Callanan848960c2010-06-23 23:18:04 +0000566{ LLDB_OPT_SET_ALL, true, "language", 'l', required_argument, NULL, 0, "[c|c++|objc|objc++]", "Sets the language to use when parsing the expression."},
567{ 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."},
568{ LLDB_OPT_SET_ALL, false, "debug", 'g', no_argument, NULL, 0, NULL, "Enable verbose debug logging of the expression parsing and evaluation."},
569{ 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 +0000570{ 0, false, NULL, 0, 0, NULL, NULL, NULL, NULL }
571};
572