blob: 59b54e1a9601424f85714943d432f834758b88f7 [file] [log] [blame]
Sean Callanan65dafa82010-08-27 01:01:44 +00001//===-- ClangUserExpression.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// C Includes
11#include <stdio.h>
12#if HAVE_SYS_TYPES_H
13# include <sys/types.h>
14#endif
15
16// C++ Includes
17#include <cstdlib>
18#include <string>
19#include <map>
20
21#include "lldb/Core/ConstString.h"
22#include "lldb/Core/Log.h"
23#include "lldb/Core/StreamString.h"
Greg Claytond1719722010-10-05 03:13:51 +000024#include "lldb/Core/ValueObjectConstResult.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000025#include "lldb/Expression/ClangExpressionDeclMap.h"
26#include "lldb/Expression/ClangExpressionParser.h"
27#include "lldb/Expression/ClangFunction.h"
28#include "lldb/Expression/ASTResultSynthesizer.h"
29#include "lldb/Expression/ClangUserExpression.h"
30#include "lldb/Host/Host.h"
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000031#include "lldb/Symbol/VariableList.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000032#include "lldb/Target/ExecutionContext.h"
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000033#include "lldb/Target/StackFrame.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000034#include "lldb/Target/Target.h"
35
36using namespace lldb_private;
37
38ClangUserExpression::ClangUserExpression (const char *expr) :
39 m_expr_text(expr),
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000040 m_transformed_text(),
41 m_jit_addr(LLDB_INVALID_ADDRESS),
42 m_cplusplus(false),
43 m_objectivec(false),
44 m_needs_object_ptr(false)
Sean Callanan65dafa82010-08-27 01:01:44 +000045{
Sean Callanan65dafa82010-08-27 01:01:44 +000046}
47
Sean Callanan830a9032010-08-27 23:31:21 +000048ClangUserExpression::~ClangUserExpression ()
49{
50}
51
Sean Callanan65dafa82010-08-27 01:01:44 +000052clang::ASTConsumer *
53ClangUserExpression::ASTTransformer (clang::ASTConsumer *passthrough)
54{
55 return new ASTResultSynthesizer(passthrough);
56}
57
Sean Callanan3c9c5eb2010-09-21 00:44:12 +000058void
59ClangUserExpression::ScanContext(ExecutionContext &exe_ctx)
60{
61 if (!exe_ctx.frame)
62 return;
63
64 VariableList *vars = exe_ctx.frame->GetVariableList(false);
65
66 if (!vars)
67 return;
68
69 if (vars->FindVariable(ConstString("this")).get())
70 m_cplusplus = true;
71 else if (vars->FindVariable(ConstString("self")).get())
72 m_objectivec = true;
73}
74
Sean Callanan550f2762010-10-22 23:25:16 +000075// This is a really nasty hack, meant to fix Objective-C expressions of the form
76// (int)[myArray count]. Right now, because the type information for count is
77// not available, [myArray count] returns id, which can't be directly cast to
78// int without causing a clang error.
79static void
80ApplyObjcCastHack(std::string &expr)
81{
82#define OBJC_CAST_HACK_FROM "(int)["
83#define OBJC_CAST_HACK_TO "(int)(long long)["
84
85 size_t from_offset;
86
87 while ((from_offset = expr.find(OBJC_CAST_HACK_FROM)) != expr.npos)
88 expr.replace(from_offset, sizeof(OBJC_CAST_HACK_FROM) - 1, OBJC_CAST_HACK_TO);
89
90#undef OBJC_CAST_HACK_TO
91#undef OBJC_CAST_HACK_FROM
92}
93
Sean Callanan30892372010-10-24 20:45:49 +000094// Another hack, meant to allow use of unichar despite it not being available in
95// the type information. Although we could special-case it in type lookup,
96// hopefully we'll figure out a way to #include the same environment as is
97// present in the original source file rather than try to hack specific type
98// definitions in as needed.
99static void
100ApplyUnicharHack(std::string &expr)
101{
102#define UNICHAR_HACK_FROM "unichar"
103#define UNICHAR_HACK_TO "unsigned short"
104
105 size_t from_offset;
106
107 while ((from_offset = expr.find(UNICHAR_HACK_FROM)) != expr.npos)
108 expr.replace(from_offset, sizeof(UNICHAR_HACK_FROM) - 1, UNICHAR_HACK_TO);
109
110#undef UNICHAR_HACK_TO
111#undef UNICHAR_HACK_FROM
112}
113
Sean Callanan550f2762010-10-22 23:25:16 +0000114bool
Sean Callanan65dafa82010-08-27 01:01:44 +0000115ClangUserExpression::Parse (Stream &error_stream, ExecutionContext &exe_ctx)
116{
117 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
118
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000119 ScanContext(exe_ctx);
120
121 StreamString m_transformed_stream;
122
123 ////////////////////////////////////
124 // Generate the expression
125 //
Sean Callanan550f2762010-10-22 23:25:16 +0000126
127 ApplyObjcCastHack(m_expr_text);
Sean Callanan30892372010-10-24 20:45:49 +0000128 ApplyUnicharHack(m_expr_text);
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000129
130 if (m_cplusplus)
131 {
132 m_transformed_stream.Printf("void \n"
Sean Callanan550f2762010-10-22 23:25:16 +0000133 "$__lldb_class::%s(void *$__lldb_arg) \n"
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000134 "{ \n"
135 " %s; \n"
136 "} \n",
137 FunctionName(),
138 m_expr_text.c_str());
139
140 m_needs_object_ptr = true;
141 }
142 else
143 {
144 m_transformed_stream.Printf("void \n"
Sean Callanan550f2762010-10-22 23:25:16 +0000145 "%s(void *$__lldb_arg) \n"
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000146 "{ \n"
147 " %s; \n"
148 "} \n",
149 FunctionName(),
150 m_expr_text.c_str());
151 }
152
153 m_transformed_text = m_transformed_stream.GetData();
154
155
156 if (log)
157 log->Printf("Parsing the following code:\n%s", m_transformed_text.c_str());
158
Sean Callanan65dafa82010-08-27 01:01:44 +0000159 ////////////////////////////////////
160 // Set up the target and compiler
161 //
162
163 Target *target = exe_ctx.target;
164
165 if (!target)
166 {
167 error_stream.PutCString ("error: invalid target\n");
168 return false;
169 }
170
171 ConstString target_triple;
172
173 target->GetTargetTriple (target_triple);
174
175 if (!target_triple)
176 target_triple = Host::GetTargetTriple ();
177
178 if (!target_triple)
179 {
180 error_stream.PutCString ("error: invalid target triple\n");
181 return false;
182 }
183
184 //////////////////////////
185 // Parse the expression
186 //
187
188 m_expr_decl_map.reset(new ClangExpressionDeclMap(&exe_ctx));
189
190 ClangExpressionParser parser(target_triple.GetCString(), *this);
191
192 unsigned num_errors = parser.Parse (error_stream);
193
194 if (num_errors)
195 {
196 error_stream.Printf ("error: %d errors parsing expression\n", num_errors);
197 return false;
198 }
199
200 ///////////////////////////////////////////////
201 // Convert the output of the parser to DWARF
202 //
203
204 m_dwarf_opcodes.reset(new StreamString);
205 m_dwarf_opcodes->SetByteOrder (lldb::eByteOrderHost);
206 m_dwarf_opcodes->GetFlags ().Set (Stream::eBinary);
207
208 m_local_variables.reset(new ClangExpressionVariableStore());
209
210 Error dwarf_error = parser.MakeDWARF ();
211
212 if (dwarf_error.Success())
213 {
214 if (log)
215 log->Printf("Code can be interpreted.");
216
217 return true;
218 }
219
220 //////////////////////////////////
221 // JIT the output of the parser
222 //
223
224 m_dwarf_opcodes.reset();
225
Sean Callanan830a9032010-08-27 23:31:21 +0000226 lldb::addr_t jit_end;
227
228 Error jit_error = parser.MakeJIT (m_jit_addr, jit_end, exe_ctx);
Sean Callanan65dafa82010-08-27 01:01:44 +0000229
230 if (jit_error.Success())
231 {
232 if (log)
233 {
234 log->Printf("Code can be run in the target.");
235
236 StreamString disassembly_stream;
237
238 Error err = parser.DisassembleFunction(disassembly_stream, exe_ctx);
239
240 if (!err.Success())
241 {
242 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
243 }
244 else
245 {
246 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
247 }
248 }
249
250 return true;
251 }
252 else
253 {
254 error_stream.Printf ("error: expression can't be interpreted or run\n", num_errors);
255 return false;
256 }
257}
258
259bool
Jim Inghamd1686902010-10-14 23:45:03 +0000260ClangUserExpression::PrepareToExecuteJITExpression (Stream &error_stream,
Sean Callananab06af92010-10-19 23:57:21 +0000261 ExecutionContext &exe_ctx,
262 lldb::addr_t &struct_address,
263 lldb::addr_t &object_ptr)
Sean Callanan65dafa82010-08-27 01:01:44 +0000264{
265 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
266
Jim Inghamd1686902010-10-14 23:45:03 +0000267 if (m_jit_addr != LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000268 {
Sean Callanan65dafa82010-08-27 01:01:44 +0000269
270 Error materialize_error;
271
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000272
273 if (m_needs_object_ptr && !(m_expr_decl_map->GetObjectPointer(object_ptr, &exe_ctx, materialize_error)))
274 {
275 error_stream.Printf("Couldn't get required object pointer: %s\n", materialize_error.AsCString());
276 return false;
277 }
278
Sean Callanan65dafa82010-08-27 01:01:44 +0000279 if (!m_expr_decl_map->Materialize(&exe_ctx, struct_address, materialize_error))
280 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000281 error_stream.Printf("Couldn't materialize struct: %s\n", materialize_error.AsCString());
Sean Callanan65dafa82010-08-27 01:01:44 +0000282 return false;
283 }
284
285 if (log)
286 {
287 log->Printf("Function address : 0x%llx", (uint64_t)m_jit_addr);
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000288
289 if (m_needs_object_ptr)
290 log->Printf("Object pointer : 0x%llx", (uint64_t)object_ptr);
291
Sean Callanan65dafa82010-08-27 01:01:44 +0000292 log->Printf("Structure address : 0x%llx", (uint64_t)struct_address);
293
294 StreamString args;
295
296 Error dump_error;
297
Sean Callanane8a59a82010-09-13 21:34:21 +0000298 if (struct_address)
Sean Callanan65dafa82010-08-27 01:01:44 +0000299 {
Sean Callanane8a59a82010-09-13 21:34:21 +0000300 if (!m_expr_decl_map->DumpMaterializedStruct(&exe_ctx, args, dump_error))
301 {
302 log->Printf("Couldn't extract variable values : %s", dump_error.AsCString("unknown error"));
303 }
304 else
305 {
306 log->Printf("Structure contents:\n%s", args.GetData());
307 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000308 }
309 }
Jim Inghamd1686902010-10-14 23:45:03 +0000310 }
311 return true;
312}
313
314ThreadPlan *
315ClangUserExpression::GetThreadPlanToExecuteJITExpression (Stream &error_stream,
316 ExecutionContext &exe_ctx)
317{
318 lldb::addr_t struct_address;
319
320 lldb::addr_t object_ptr = NULL;
321
322 PrepareToExecuteJITExpression (error_stream, exe_ctx, struct_address, object_ptr);
323
324 return ClangFunction::GetThreadPlanToCallFunction (exe_ctx,
325 m_jit_addr,
326 struct_address,
327 error_stream,
328 true,
329 true,
330 (m_needs_object_ptr ? &object_ptr : NULL));
331}
332
333bool
334ClangUserExpression::FinalizeJITExecution (Stream &error_stream,
335 ExecutionContext &exe_ctx,
336 ClangExpressionVariable *&result)
337{
338 Error expr_error;
339
340 if (!m_expr_decl_map->Dematerialize(&exe_ctx, result, expr_error))
341 {
342 error_stream.Printf ("Couldn't dematerialize struct : %s\n", expr_error.AsCString("unknown error"));
343 return false;
344 }
345 return true;
346}
347
348bool
349ClangUserExpression::Execute (Stream &error_stream,
350 ExecutionContext &exe_ctx,
351 ClangExpressionVariable *&result)
352{
353 if (m_dwarf_opcodes.get())
354 {
355 // TODO execute the JITted opcodes
356
357 error_stream.Printf("We don't currently support executing DWARF expressions");
358
359 return false;
360 }
361 else if (m_jit_addr != LLDB_INVALID_ADDRESS)
362 {
363 lldb::addr_t struct_address;
364
365 lldb::addr_t object_ptr = NULL;
366
367 PrepareToExecuteJITExpression (error_stream, exe_ctx, struct_address, object_ptr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000368
369 ClangFunction::ExecutionResults execution_result =
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000370 ClangFunction::ExecuteFunction (exe_ctx,
371 m_jit_addr,
372 struct_address,
373 true,
374 true,
Sean Callanan0027cec2010-10-07 18:17:31 +0000375 10000000,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000376 error_stream,
377 (m_needs_object_ptr ? &object_ptr : NULL));
Sean Callanan65dafa82010-08-27 01:01:44 +0000378
379 if (execution_result != ClangFunction::eExecutionCompleted)
380 {
381 const char *result_name;
382
383 switch (execution_result)
384 {
385 case ClangFunction::eExecutionCompleted:
386 result_name = "eExecutionCompleted";
387 break;
388 case ClangFunction::eExecutionDiscarded:
389 result_name = "eExecutionDiscarded";
390 break;
391 case ClangFunction::eExecutionInterrupted:
392 result_name = "eExecutionInterrupted";
393 break;
394 case ClangFunction::eExecutionSetupError:
395 result_name = "eExecutionSetupError";
396 break;
397 case ClangFunction::eExecutionTimedOut:
398 result_name = "eExecutionTimedOut";
399 break;
400 }
401
402 error_stream.Printf ("Couldn't execute function; result was %s\n", result_name);
403 return false;
404 }
405
Jim Inghamd1686902010-10-14 23:45:03 +0000406 return FinalizeJITExecution (error_stream, exe_ctx, result);
Sean Callanan65dafa82010-08-27 01:01:44 +0000407 }
408 else
409 {
410 error_stream.Printf("Expression can't be run; neither DWARF nor a JIT compiled function are present");
411 return false;
412 }
413}
414
415StreamString &
416ClangUserExpression::DwarfOpcodeStream ()
417{
418 if (!m_dwarf_opcodes.get())
419 m_dwarf_opcodes.reset(new StreamString());
420
421 return *m_dwarf_opcodes.get();
422}
Greg Clayton377e0b42010-10-05 00:31:29 +0000423
424
Greg Claytond1719722010-10-05 03:13:51 +0000425lldb::ValueObjectSP
426ClangUserExpression::Evaluate (ExecutionContext &exe_ctx, const char *expr_cstr)
Greg Clayton377e0b42010-10-05 00:31:29 +0000427{
428 Error error;
Greg Claytond1719722010-10-05 03:13:51 +0000429 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton377e0b42010-10-05 00:31:29 +0000430 ClangUserExpression user_expression (expr_cstr);
431
432 StreamString error_stream;
433
434 if (!user_expression.Parse (error_stream, exe_ctx))
435 {
436 if (error_stream.GetString().empty())
437 error.SetErrorString ("expression failed to parse, unknown error");
438 else
439 error.SetErrorString (error_stream.GetString().c_str());
440 }
441 else
442 {
443 ClangExpressionVariable *expr_result = NULL;
444
445 error_stream.GetString().clear();
446
447 if (!user_expression.Execute (error_stream, exe_ctx, expr_result))
448 {
449 if (error_stream.GetString().empty())
450 error.SetErrorString ("expression failed to execute, unknown error");
451 else
452 error.SetErrorString (error_stream.GetString().c_str());
453 }
454 else
455 {
456 // TODO: seems weird to get a pointer to a result object back from
457 // a function. Do we own it? Feels like we do, but from looking at the
458 // code we don't. Might be best to make this a reference and state
459 // explicitly that we don't own it when we get a reference back from
460 // the execute?
461 if (expr_result)
462 {
463 result_valobj_sp = expr_result->GetExpressionResult (&exe_ctx);
464 }
465 else
466 {
Sean Callanan44820ec2010-10-19 20:15:00 +0000467 error.SetErrorString ("Expression did not return a result");
Greg Clayton377e0b42010-10-05 00:31:29 +0000468 }
469 }
470 }
Sean Callanan44820ec2010-10-19 20:15:00 +0000471
Greg Claytond1719722010-10-05 03:13:51 +0000472 if (result_valobj_sp.get() == NULL)
473 result_valobj_sp.reset (new ValueObjectConstResult (error));
474
475 return result_valobj_sp;
Greg Clayton377e0b42010-10-05 00:31:29 +0000476}