1 //===-- ClangFunction.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
11 // C Includes
12 // C++ Includes
13 // Other libraries and framework includes
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/RecordLayout.h"
16 #include "clang/CodeGen/CodeGenAction.h"
17 #include "clang/CodeGen/ModuleBuilder.h"
18 #include "clang/Frontend/CompilerInstance.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/ExecutionEngine/ExecutionEngine.h"
22 #include "llvm/IR/Module.h"
23
24 // Project includes
25 #include "lldb/Core/DataExtractor.h"
26 #include "lldb/Core/Log.h"
27 #include "lldb/Core/Module.h"
28 #include "lldb/Core/State.h"
29 #include "lldb/Core/ValueObject.h"
30 #include "lldb/Core/ValueObjectList.h"
31 #include "lldb/Expression/ASTStructExtractor.h"
32 #include "lldb/Expression/ClangExpressionParser.h"
33 #include "lldb/Expression/ClangFunction.h"
34 #include "lldb/Expression/IRExecutionUnit.h"
35 #include "lldb/Interpreter/CommandReturnObject.h"
36 #include "lldb/Symbol/ClangASTContext.h"
37 #include "lldb/Symbol/Function.h"
38 #include "lldb/Symbol/Type.h"
39 #include "lldb/Target/ExecutionContext.h"
40 #include "lldb/Target/Process.h"
41 #include "lldb/Target/RegisterContext.h"
42 #include "lldb/Target/Target.h"
43 #include "lldb/Target/Thread.h"
44 #include "lldb/Target/ThreadPlan.h"
45 #include "lldb/Target/ThreadPlanCallFunction.h"
46
47 using namespace lldb_private;
48
49 //----------------------------------------------------------------------
50 // ClangFunction constructor
51 //----------------------------------------------------------------------
ClangFunction(ExecutionContextScope & exe_scope,const ClangASTType & return_type,const Address & functionAddress,const ValueList & arg_value_list,const char * name)52 ClangFunction::ClangFunction
53 (
54 ExecutionContextScope &exe_scope,
55 const ClangASTType &return_type,
56 const Address& functionAddress,
57 const ValueList &arg_value_list,
58 const char *name
59 ) :
60 m_execution_unit_sp(),
61 m_parser(),
62 m_jit_module_wp(),
63 m_name (name ? name : "<unknown>"),
64 m_function_ptr (NULL),
65 m_function_addr (functionAddress),
66 m_function_return_type(return_type),
67 m_wrapper_function_name ("__lldb_caller_function"),
68 m_wrapper_struct_name ("__lldb_caller_struct"),
69 m_wrapper_args_addrs (),
70 m_arg_values (arg_value_list),
71 m_compiled (false),
72 m_JITted (false)
73 {
74 m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess());
75 // Can't make a ClangFunction without a process.
76 assert (m_jit_process_wp.lock());
77 }
78
ClangFunction(ExecutionContextScope & exe_scope,Function & function,ClangASTContext * ast_context,const ValueList & arg_value_list,const char * name)79 ClangFunction::ClangFunction
80 (
81 ExecutionContextScope &exe_scope,
82 Function &function,
83 ClangASTContext *ast_context,
84 const ValueList &arg_value_list,
85 const char *name
86 ) :
87 m_name (name ? name : "<unknown>"),
88 m_function_ptr (&function),
89 m_function_addr (),
90 m_function_return_type (),
91 m_wrapper_function_name ("__lldb_function_caller"),
92 m_wrapper_struct_name ("__lldb_caller_struct"),
93 m_wrapper_args_addrs (),
94 m_arg_values (arg_value_list),
95 m_compiled (false),
96 m_JITted (false)
97 {
98 m_jit_process_wp = exe_scope.CalculateProcess();
99 // Can't make a ClangFunction without a process.
100 assert (m_jit_process_wp.lock());
101
102 m_function_addr = m_function_ptr->GetAddressRange().GetBaseAddress();
103 m_function_return_type = m_function_ptr->GetClangType().GetFunctionReturnType();
104 }
105
106 //----------------------------------------------------------------------
107 // Destructor
108 //----------------------------------------------------------------------
~ClangFunction()109 ClangFunction::~ClangFunction()
110 {
111 lldb::ProcessSP process_sp (m_jit_process_wp.lock());
112 if (process_sp)
113 {
114 lldb::ModuleSP jit_module_sp (m_jit_module_wp.lock());
115 if (jit_module_sp)
116 process_sp->GetTarget().GetImages().Remove(jit_module_sp);
117 }
118 }
119
120 unsigned
CompileFunction(Stream & errors)121 ClangFunction::CompileFunction (Stream &errors)
122 {
123 if (m_compiled)
124 return 0;
125
126 // FIXME: How does clang tell us there's no return value? We need to handle that case.
127 unsigned num_errors = 0;
128
129 std::string return_type_str (m_function_return_type.GetTypeName().AsCString(""));
130
131 // Cons up the function we're going to wrap our call in, then compile it...
132 // We declare the function "extern "C"" because the compiler might be in C++
133 // mode which would mangle the name and then we couldn't find it again...
134 m_wrapper_function_text.clear();
135 m_wrapper_function_text.append ("extern \"C\" void ");
136 m_wrapper_function_text.append (m_wrapper_function_name);
137 m_wrapper_function_text.append (" (void *input)\n{\n struct ");
138 m_wrapper_function_text.append (m_wrapper_struct_name);
139 m_wrapper_function_text.append (" \n {\n");
140 m_wrapper_function_text.append (" ");
141 m_wrapper_function_text.append (return_type_str);
142 m_wrapper_function_text.append (" (*fn_ptr) (");
143
144 // Get the number of arguments. If we have a function type and it is prototyped,
145 // trust that, otherwise use the values we were given.
146
147 // FIXME: This will need to be extended to handle Variadic functions. We'll need
148 // to pull the defined arguments out of the function, then add the types from the
149 // arguments list for the variable arguments.
150
151 uint32_t num_args = UINT32_MAX;
152 bool trust_function = false;
153 // GetArgumentCount returns -1 for an unprototyped function.
154 ClangASTType function_clang_type;
155 if (m_function_ptr)
156 {
157 function_clang_type = m_function_ptr->GetClangType();
158 if (function_clang_type)
159 {
160 int num_func_args = function_clang_type.GetFunctionArgumentCount();
161 if (num_func_args >= 0)
162 {
163 trust_function = true;
164 num_args = num_func_args;
165 }
166 }
167 }
168
169 if (num_args == UINT32_MAX)
170 num_args = m_arg_values.GetSize();
171
172 std::string args_buffer; // This one stores the definition of all the args in "struct caller".
173 std::string args_list_buffer; // This one stores the argument list called from the structure.
174 for (size_t i = 0; i < num_args; i++)
175 {
176 std::string type_name;
177
178 if (trust_function)
179 {
180 type_name = function_clang_type.GetFunctionArgumentTypeAtIndex(i).GetTypeName().AsCString("");
181 }
182 else
183 {
184 ClangASTType clang_qual_type = m_arg_values.GetValueAtIndex(i)->GetClangType ();
185 if (clang_qual_type)
186 {
187 type_name = clang_qual_type.GetTypeName().AsCString("");
188 }
189 else
190 {
191 errors.Printf("Could not determine type of input value %" PRIu64 ".", (uint64_t)i);
192 return 1;
193 }
194 }
195
196 m_wrapper_function_text.append (type_name);
197 if (i < num_args - 1)
198 m_wrapper_function_text.append (", ");
199
200 char arg_buf[32];
201 args_buffer.append (" ");
202 args_buffer.append (type_name);
203 snprintf(arg_buf, 31, "arg_%" PRIu64, (uint64_t)i);
204 args_buffer.push_back (' ');
205 args_buffer.append (arg_buf);
206 args_buffer.append (";\n");
207
208 args_list_buffer.append ("__lldb_fn_data->");
209 args_list_buffer.append (arg_buf);
210 if (i < num_args - 1)
211 args_list_buffer.append (", ");
212
213 }
214 m_wrapper_function_text.append (");\n"); // Close off the function calling prototype.
215
216 m_wrapper_function_text.append (args_buffer);
217
218 m_wrapper_function_text.append (" ");
219 m_wrapper_function_text.append (return_type_str);
220 m_wrapper_function_text.append (" return_value;");
221 m_wrapper_function_text.append ("\n };\n struct ");
222 m_wrapper_function_text.append (m_wrapper_struct_name);
223 m_wrapper_function_text.append ("* __lldb_fn_data = (struct ");
224 m_wrapper_function_text.append (m_wrapper_struct_name);
225 m_wrapper_function_text.append (" *) input;\n");
226
227 m_wrapper_function_text.append (" __lldb_fn_data->return_value = __lldb_fn_data->fn_ptr (");
228 m_wrapper_function_text.append (args_list_buffer);
229 m_wrapper_function_text.append (");\n}\n");
230
231 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
232 if (log)
233 log->Printf ("Expression: \n\n%s\n\n", m_wrapper_function_text.c_str());
234
235 // Okay, now compile this expression
236
237 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
238 if (jit_process_sp)
239 {
240 const bool generate_debug_info = true;
241 m_parser.reset(new ClangExpressionParser(jit_process_sp.get(), *this, generate_debug_info));
242
243 num_errors = m_parser->Parse (errors);
244 }
245 else
246 {
247 errors.Printf("no process - unable to inject function");
248 num_errors = 1;
249 }
250
251 m_compiled = (num_errors == 0);
252
253 if (!m_compiled)
254 return num_errors;
255
256 return num_errors;
257 }
258
259 bool
WriteFunctionWrapper(ExecutionContext & exe_ctx,Stream & errors)260 ClangFunction::WriteFunctionWrapper (ExecutionContext &exe_ctx, Stream &errors)
261 {
262 Process *process = exe_ctx.GetProcessPtr();
263
264 if (!process)
265 return false;
266
267 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
268
269 if (process != jit_process_sp.get())
270 return false;
271
272 if (!m_compiled)
273 return false;
274
275 if (m_JITted)
276 return true;
277
278 bool can_interpret = false; // should stay that way
279
280 Error jit_error (m_parser->PrepareForExecution (m_jit_start_addr,
281 m_jit_end_addr,
282 m_execution_unit_sp,
283 exe_ctx,
284 can_interpret,
285 eExecutionPolicyAlways));
286
287 if (!jit_error.Success())
288 return false;
289
290 if (m_parser->GetGenerateDebugInfo())
291 {
292 lldb::ModuleSP jit_module_sp ( m_execution_unit_sp->GetJITModule());
293
294 if (jit_module_sp)
295 {
296 ConstString const_func_name(FunctionName());
297 FileSpec jit_file;
298 jit_file.GetFilename() = const_func_name;
299 jit_module_sp->SetFileSpecAndObjectName (jit_file, ConstString());
300 m_jit_module_wp = jit_module_sp;
301 process->GetTarget().GetImages().Append(jit_module_sp);
302 }
303 }
304 if (process && m_jit_start_addr)
305 m_jit_process_wp = process->shared_from_this();
306
307 m_JITted = true;
308
309 return true;
310 }
311
312 bool
WriteFunctionArguments(ExecutionContext & exe_ctx,lldb::addr_t & args_addr_ref,Stream & errors)313 ClangFunction::WriteFunctionArguments (ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, Stream &errors)
314 {
315 return WriteFunctionArguments(exe_ctx, args_addr_ref, m_function_addr, m_arg_values, errors);
316 }
317
318 // FIXME: Assure that the ValueList we were passed in is consistent with the one that defined this function.
319
320 bool
WriteFunctionArguments(ExecutionContext & exe_ctx,lldb::addr_t & args_addr_ref,Address function_address,ValueList & arg_values,Stream & errors)321 ClangFunction::WriteFunctionArguments (ExecutionContext &exe_ctx,
322 lldb::addr_t &args_addr_ref,
323 Address function_address,
324 ValueList &arg_values,
325 Stream &errors)
326 {
327 // All the information to reconstruct the struct is provided by the
328 // StructExtractor.
329 if (!m_struct_valid)
330 {
331 errors.Printf("Argument information was not correctly parsed, so the function cannot be called.");
332 return false;
333 }
334
335 Error error;
336 using namespace clang;
337 lldb::ExpressionResults return_value = lldb::eExpressionSetupError;
338
339 Process *process = exe_ctx.GetProcessPtr();
340
341 if (process == NULL)
342 return return_value;
343
344 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
345
346 if (process != jit_process_sp.get())
347 return false;
348
349 if (args_addr_ref == LLDB_INVALID_ADDRESS)
350 {
351 args_addr_ref = process->AllocateMemory(m_struct_size, lldb::ePermissionsReadable|lldb::ePermissionsWritable, error);
352 if (args_addr_ref == LLDB_INVALID_ADDRESS)
353 return false;
354 m_wrapper_args_addrs.push_back (args_addr_ref);
355 }
356 else
357 {
358 // Make sure this is an address that we've already handed out.
359 if (find (m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr_ref) == m_wrapper_args_addrs.end())
360 {
361 return false;
362 }
363 }
364
365 // TODO: verify fun_addr needs to be a callable address
366 Scalar fun_addr (function_address.GetCallableLoadAddress(exe_ctx.GetTargetPtr()));
367 uint64_t first_offset = m_member_offsets[0];
368 process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr, process->GetAddressByteSize(), error);
369
370 // FIXME: We will need to extend this for Variadic functions.
371
372 Error value_error;
373
374 size_t num_args = arg_values.GetSize();
375 if (num_args != m_arg_values.GetSize())
376 {
377 errors.Printf ("Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "", (uint64_t)num_args, (uint64_t)m_arg_values.GetSize());
378 return false;
379 }
380
381 for (size_t i = 0; i < num_args; i++)
382 {
383 // FIXME: We should sanity check sizes.
384
385 uint64_t offset = m_member_offsets[i+1]; // Clang sizes are in bytes.
386 Value *arg_value = arg_values.GetValueAtIndex(i);
387
388 // FIXME: For now just do scalars:
389
390 // Special case: if it's a pointer, don't do anything (the ABI supports passing cstrings)
391
392 if (arg_value->GetValueType() == Value::eValueTypeHostAddress &&
393 arg_value->GetContextType() == Value::eContextTypeInvalid &&
394 arg_value->GetClangType().IsPointerType())
395 continue;
396
397 const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx);
398
399 if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar, arg_scalar.GetByteSize(), error))
400 return false;
401 }
402
403 return true;
404 }
405
406 bool
InsertFunction(ExecutionContext & exe_ctx,lldb::addr_t & args_addr_ref,Stream & errors)407 ClangFunction::InsertFunction (ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, Stream &errors)
408 {
409 using namespace clang;
410
411 if (CompileFunction(errors) != 0)
412 return false;
413 if (!WriteFunctionWrapper(exe_ctx, errors))
414 return false;
415 if (!WriteFunctionArguments(exe_ctx, args_addr_ref, errors))
416 return false;
417
418 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
419 if (log)
420 log->Printf ("Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n", m_jit_start_addr, args_addr_ref);
421
422 return true;
423 }
424
425 lldb::ThreadPlanSP
GetThreadPlanToCallFunction(ExecutionContext & exe_ctx,lldb::addr_t args_addr,const EvaluateExpressionOptions & options,Stream & errors)426 ClangFunction::GetThreadPlanToCallFunction (ExecutionContext &exe_ctx,
427 lldb::addr_t args_addr,
428 const EvaluateExpressionOptions &options,
429 Stream &errors)
430 {
431 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
432
433 if (log)
434 log->Printf("-- [ClangFunction::GetThreadPlanToCallFunction] Creating thread plan to call function \"%s\" --", m_name.c_str());
435
436 // FIXME: Use the errors Stream for better error reporting.
437 Thread *thread = exe_ctx.GetThreadPtr();
438 if (thread == NULL)
439 {
440 errors.Printf("Can't call a function without a valid thread.");
441 return NULL;
442 }
443
444 // Okay, now run the function:
445
446 Address wrapper_address (m_jit_start_addr);
447
448 lldb::addr_t args = { args_addr };
449
450 lldb::ThreadPlanSP new_plan_sp (new ThreadPlanCallFunction (*thread,
451 wrapper_address,
452 ClangASTType(),
453 args,
454 options));
455 new_plan_sp->SetIsMasterPlan(true);
456 new_plan_sp->SetOkayToDiscard (false);
457 return new_plan_sp;
458 }
459
460 bool
FetchFunctionResults(ExecutionContext & exe_ctx,lldb::addr_t args_addr,Value & ret_value)461 ClangFunction::FetchFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr, Value &ret_value)
462 {
463 // Read the return value - it is the last field in the struct:
464 // FIXME: How does clang tell us there's no return value? We need to handle that case.
465 // FIXME: Create our ThreadPlanCallFunction with the return ClangASTType, and then use GetReturnValueObject
466 // to fetch the value. That way we can fetch any values we need.
467
468 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
469
470 if (log)
471 log->Printf("-- [ClangFunction::FetchFunctionResults] Fetching function results for \"%s\"--", m_name.c_str());
472
473 Process *process = exe_ctx.GetProcessPtr();
474
475 if (process == NULL)
476 return false;
477
478 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock());
479
480 if (process != jit_process_sp.get())
481 return false;
482
483 Error error;
484 ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory (args_addr + m_return_offset, m_return_size, 0, error);
485
486 if (error.Fail())
487 return false;
488
489 ret_value.SetClangType(m_function_return_type);
490 ret_value.SetValueType(Value::eValueTypeScalar);
491 return true;
492 }
493
494 void
DeallocateFunctionResults(ExecutionContext & exe_ctx,lldb::addr_t args_addr)495 ClangFunction::DeallocateFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr)
496 {
497 std::list<lldb::addr_t>::iterator pos;
498 pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr);
499 if (pos != m_wrapper_args_addrs.end())
500 m_wrapper_args_addrs.erase(pos);
501
502 exe_ctx.GetProcessRef().DeallocateMemory(args_addr);
503 }
504
505 lldb::ExpressionResults
ExecuteFunction(ExecutionContext & exe_ctx,lldb::addr_t * args_addr_ptr,const EvaluateExpressionOptions & options,Stream & errors,Value & results)506 ClangFunction::ExecuteFunction(
507 ExecutionContext &exe_ctx,
508 lldb::addr_t *args_addr_ptr,
509 const EvaluateExpressionOptions &options,
510 Stream &errors,
511 Value &results)
512 {
513 using namespace clang;
514 lldb::ExpressionResults return_value = lldb::eExpressionSetupError;
515
516 // ClangFunction::ExecuteFunction execution is always just to get the result. Do make sure we ignore
517 // breakpoints, unwind on error, and don't try to debug it.
518 EvaluateExpressionOptions real_options = options;
519 real_options.SetDebug(false);
520 real_options.SetUnwindOnError(true);
521 real_options.SetIgnoreBreakpoints(true);
522
523 lldb::addr_t args_addr;
524
525 if (args_addr_ptr != NULL)
526 args_addr = *args_addr_ptr;
527 else
528 args_addr = LLDB_INVALID_ADDRESS;
529
530 if (CompileFunction(errors) != 0)
531 return lldb::eExpressionSetupError;
532
533 if (args_addr == LLDB_INVALID_ADDRESS)
534 {
535 if (!InsertFunction(exe_ctx, args_addr, errors))
536 return lldb::eExpressionSetupError;
537 }
538
539 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP));
540
541 if (log)
542 log->Printf("== [ClangFunction::ExecuteFunction] Executing function \"%s\" ==", m_name.c_str());
543
544 lldb::ThreadPlanSP call_plan_sp = GetThreadPlanToCallFunction (exe_ctx,
545 args_addr,
546 real_options,
547 errors);
548 if (!call_plan_sp)
549 return lldb::eExpressionSetupError;
550
551 // We need to make sure we record the fact that we are running an expression here
552 // otherwise this fact will fail to be recorded when fetching an Objective-C object description
553 if (exe_ctx.GetProcessPtr())
554 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true);
555
556 return_value = exe_ctx.GetProcessRef().RunThreadPlan (exe_ctx,
557 call_plan_sp,
558 real_options,
559 errors);
560
561 if (log)
562 {
563 if (return_value != lldb::eExpressionCompleted)
564 {
565 log->Printf("== [ClangFunction::ExecuteFunction] Execution of \"%s\" completed abnormally ==", m_name.c_str());
566 }
567 else
568 {
569 log->Printf("== [ClangFunction::ExecuteFunction] Execution of \"%s\" completed normally ==", m_name.c_str());
570 }
571 }
572
573 if (exe_ctx.GetProcessPtr())
574 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false);
575
576 if (args_addr_ptr != NULL)
577 *args_addr_ptr = args_addr;
578
579 if (return_value != lldb::eExpressionCompleted)
580 return return_value;
581
582 FetchFunctionResults(exe_ctx, args_addr, results);
583
584 if (args_addr_ptr == NULL)
585 DeallocateFunctionResults(exe_ctx, args_addr);
586
587 return lldb::eExpressionCompleted;
588 }
589
590 clang::ASTConsumer *
ASTTransformer(clang::ASTConsumer * passthrough)591 ClangFunction::ASTTransformer (clang::ASTConsumer *passthrough)
592 {
593 m_struct_extractor.reset(new ASTStructExtractor(passthrough, m_wrapper_struct_name.c_str(), *this));
594
595 return m_struct_extractor.get();
596 }
597