blob: 84b8bff9a261f35ed78ed5e4063c1c9d01b9caed [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- 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
Chris Lattner24943d22010-06-08 16:52:24 +000014#include "clang/AST/ASTContext.h"
15#include "clang/AST/RecordLayout.h"
Greg Claytonc4f51102010-07-02 18:39:06 +000016#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/ExecutionEngine/ExecutionEngine.h"
Chris Lattner24943d22010-06-08 16:52:24 +000021#include "llvm/Module.h"
Chris Lattner24943d22010-06-08 16:52:24 +000022
23// Project includes
Sean Callanan65dafa82010-08-27 01:01:44 +000024#include "lldb/Expression/ASTStructExtractor.h"
25#include "lldb/Expression/ClangExpressionParser.h"
Chris Lattner24943d22010-06-08 16:52:24 +000026#include "lldb/Expression/ClangFunction.h"
27#include "lldb/Symbol/Type.h"
28#include "lldb/Core/DataExtractor.h"
Jim Ingham3ae449a2010-11-17 02:32:00 +000029#include "lldb/Core/State.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Core/ValueObject.h"
31#include "lldb/Core/ValueObjectList.h"
32#include "lldb/Interpreter/CommandReturnObject.h"
33#include "lldb/Symbol/ClangASTContext.h"
34#include "lldb/Symbol/Function.h"
35#include "lldb/Target/ExecutionContext.h"
36#include "lldb/Target/Process.h"
Sean Callanan841026f2010-07-23 00:16:21 +000037#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000038#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000039#include "lldb/Target/Thread.h"
40#include "lldb/Target/ThreadPlan.h"
41#include "lldb/Target/ThreadPlanCallFunction.h"
42#include "lldb/Core/Log.h"
43
44using namespace lldb_private;
Sean Callanan65dafa82010-08-27 01:01:44 +000045
Chris Lattner24943d22010-06-08 16:52:24 +000046//----------------------------------------------------------------------
47// ClangFunction constructor
48//----------------------------------------------------------------------
Greg Clayton8de27c72010-10-15 22:48:33 +000049ClangFunction::ClangFunction
50(
51 const char *target_triple,
52 ClangASTContext *ast_context,
53 void *return_qualtype,
54 const Address& functionAddress,
55 const ValueList &arg_value_list
56) :
Sean Callanan65dafa82010-08-27 01:01:44 +000057 m_target_triple (target_triple),
Chris Lattner24943d22010-06-08 16:52:24 +000058 m_function_ptr (NULL),
Greg Clayton54e7afa2010-07-09 20:39:50 +000059 m_function_addr (functionAddress),
Chris Lattner24943d22010-06-08 16:52:24 +000060 m_function_return_qual_type(return_qualtype),
Greg Clayton54e7afa2010-07-09 20:39:50 +000061 m_clang_ast_context (ast_context),
Chris Lattner24943d22010-06-08 16:52:24 +000062 m_wrapper_function_name ("__lldb_caller_function"),
63 m_wrapper_struct_name ("__lldb_caller_struct"),
Greg Clayton54e7afa2010-07-09 20:39:50 +000064 m_wrapper_function_addr (),
65 m_wrapper_args_addrs (),
Greg Clayton54e7afa2010-07-09 20:39:50 +000066 m_arg_values (arg_value_list),
Chris Lattner24943d22010-06-08 16:52:24 +000067 m_compiled (false),
68 m_JITted (false)
69{
70}
71
Greg Clayton8de27c72010-10-15 22:48:33 +000072ClangFunction::ClangFunction
73(
74 const char *target_triple,
75 Function &function,
76 ClangASTContext *ast_context,
77 const ValueList &arg_value_list
78) :
Sean Callanan65dafa82010-08-27 01:01:44 +000079 m_target_triple (target_triple),
Chris Lattner24943d22010-06-08 16:52:24 +000080 m_function_ptr (&function),
Greg Clayton54e7afa2010-07-09 20:39:50 +000081 m_function_addr (),
82 m_function_return_qual_type (),
Chris Lattner24943d22010-06-08 16:52:24 +000083 m_clang_ast_context (ast_context),
Chris Lattner24943d22010-06-08 16:52:24 +000084 m_wrapper_function_name ("__lldb_function_caller"),
85 m_wrapper_struct_name ("__lldb_caller_struct"),
Greg Clayton54e7afa2010-07-09 20:39:50 +000086 m_wrapper_function_addr (),
87 m_wrapper_args_addrs (),
Greg Clayton54e7afa2010-07-09 20:39:50 +000088 m_arg_values (arg_value_list),
Chris Lattner24943d22010-06-08 16:52:24 +000089 m_compiled (false),
90 m_JITted (false)
91{
92 m_function_addr = m_function_ptr->GetAddressRange().GetBaseAddress();
Greg Clayton462d4142010-09-29 01:12:09 +000093 m_function_return_qual_type = m_function_ptr->GetReturnType().GetClangType();
Chris Lattner24943d22010-06-08 16:52:24 +000094}
95
96//----------------------------------------------------------------------
97// Destructor
98//----------------------------------------------------------------------
99ClangFunction::~ClangFunction()
100{
101}
102
103unsigned
104ClangFunction::CompileFunction (Stream &errors)
105{
Sean Callanan65dafa82010-08-27 01:01:44 +0000106 if (m_compiled)
107 return 0;
108
Chris Lattner24943d22010-06-08 16:52:24 +0000109 // FIXME: How does clang tell us there's no return value? We need to handle that case.
110 unsigned num_errors = 0;
111
Sean Callanan65dafa82010-08-27 01:01:44 +0000112 std::string return_type_str = ClangASTContext::GetTypeName(m_function_return_qual_type);
113
114 // Cons up the function we're going to wrap our call in, then compile it...
115 // We declare the function "extern "C"" because the compiler might be in C++
116 // mode which would mangle the name and then we couldn't find it again...
117 m_wrapper_function_text.clear();
118 m_wrapper_function_text.append ("extern \"C\" void ");
119 m_wrapper_function_text.append (m_wrapper_function_name);
120 m_wrapper_function_text.append (" (void *input)\n{\n struct ");
121 m_wrapper_function_text.append (m_wrapper_struct_name);
122 m_wrapper_function_text.append (" \n {\n");
123 m_wrapper_function_text.append (" ");
124 m_wrapper_function_text.append (return_type_str);
125 m_wrapper_function_text.append (" (*fn_ptr) (");
126
127 // Get the number of arguments. If we have a function type and it is prototyped,
128 // trust that, otherwise use the values we were given.
129
130 // FIXME: This will need to be extended to handle Variadic functions. We'll need
131 // to pull the defined arguments out of the function, then add the types from the
132 // arguments list for the variable arguments.
133
134 uint32_t num_args = UINT32_MAX;
135 bool trust_function = false;
136 // GetArgumentCount returns -1 for an unprototyped function.
137 if (m_function_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +0000138 {
Sean Callanan65dafa82010-08-27 01:01:44 +0000139 int num_func_args = m_function_ptr->GetArgumentCount();
140 if (num_func_args >= 0)
141 trust_function = true;
142 else
143 num_args = num_func_args;
144 }
Chris Lattner24943d22010-06-08 16:52:24 +0000145
Sean Callanan65dafa82010-08-27 01:01:44 +0000146 if (num_args == UINT32_MAX)
147 num_args = m_arg_values.GetSize();
Chris Lattner24943d22010-06-08 16:52:24 +0000148
Sean Callanan65dafa82010-08-27 01:01:44 +0000149 std::string args_buffer; // This one stores the definition of all the args in "struct caller".
150 std::string args_list_buffer; // This one stores the argument list called from the structure.
151 for (size_t i = 0; i < num_args; i++)
152 {
153 const char *type_string;
154 std::string type_stdstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000155
Sean Callanan65dafa82010-08-27 01:01:44 +0000156 if (trust_function)
Chris Lattner24943d22010-06-08 16:52:24 +0000157 {
Sean Callanan65dafa82010-08-27 01:01:44 +0000158 type_string = m_function_ptr->GetArgumentTypeAtIndex(i).GetName().AsCString();
Chris Lattner24943d22010-06-08 16:52:24 +0000159 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000160 else
Chris Lattner24943d22010-06-08 16:52:24 +0000161 {
Sean Callanan65dafa82010-08-27 01:01:44 +0000162 Value *arg_value = m_arg_values.GetValueAtIndex(i);
Greg Clayton462d4142010-09-29 01:12:09 +0000163 void *clang_qual_type = arg_value->GetClangType ();
Sean Callanan65dafa82010-08-27 01:01:44 +0000164 if (clang_qual_type != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000165 {
Sean Callanan65dafa82010-08-27 01:01:44 +0000166 type_stdstr = ClangASTContext::GetTypeName(clang_qual_type);
167 type_string = type_stdstr.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +0000168 }
169 else
Sean Callanan65dafa82010-08-27 01:01:44 +0000170 {
171 errors.Printf("Could not determine type of input value %d.", i);
Chris Lattner24943d22010-06-08 16:52:24 +0000172 return 1;
173 }
Chris Lattner24943d22010-06-08 16:52:24 +0000174 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000175
176 m_wrapper_function_text.append (type_string);
177 if (i < num_args - 1)
178 m_wrapper_function_text.append (", ");
179
180 char arg_buf[32];
181 args_buffer.append (" ");
182 args_buffer.append (type_string);
183 snprintf(arg_buf, 31, "arg_%zd", i);
184 args_buffer.push_back (' ');
185 args_buffer.append (arg_buf);
186 args_buffer.append (";\n");
187
188 args_list_buffer.append ("__lldb_fn_data->");
189 args_list_buffer.append (arg_buf);
190 if (i < num_args - 1)
191 args_list_buffer.append (", ");
192
Chris Lattner24943d22010-06-08 16:52:24 +0000193 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000194 m_wrapper_function_text.append (");\n"); // Close off the function calling prototype.
195
196 m_wrapper_function_text.append (args_buffer);
197
198 m_wrapper_function_text.append (" ");
199 m_wrapper_function_text.append (return_type_str);
200 m_wrapper_function_text.append (" return_value;");
201 m_wrapper_function_text.append ("\n };\n struct ");
202 m_wrapper_function_text.append (m_wrapper_struct_name);
203 m_wrapper_function_text.append ("* __lldb_fn_data = (struct ");
204 m_wrapper_function_text.append (m_wrapper_struct_name);
205 m_wrapper_function_text.append (" *) input;\n");
206
207 m_wrapper_function_text.append (" __lldb_fn_data->return_value = __lldb_fn_data->fn_ptr (");
208 m_wrapper_function_text.append (args_list_buffer);
209 m_wrapper_function_text.append (");\n}\n");
210
Greg Claytone005f2c2010-11-06 01:53:30 +0000211 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Sean Callanan65dafa82010-08-27 01:01:44 +0000212 if (log)
213 log->Printf ("Expression: \n\n%s\n\n", m_wrapper_function_text.c_str());
214
215 // Okay, now compile this expression
216
217 m_parser.reset(new ClangExpressionParser(m_target_triple.c_str(), *this));
218
219 num_errors = m_parser->Parse (errors);
220
221 m_compiled = (num_errors == 0);
222
223 if (!m_compiled)
224 return num_errors;
Chris Lattner24943d22010-06-08 16:52:24 +0000225
226 return num_errors;
227}
228
229bool
Sean Callananc78d6482010-07-26 22:14:36 +0000230ClangFunction::WriteFunctionWrapper (ExecutionContext &exe_ctx, Stream &errors)
Chris Lattner24943d22010-06-08 16:52:24 +0000231{
Sean Callananc78d6482010-07-26 22:14:36 +0000232 Process *process = exe_ctx.process;
Chris Lattner24943d22010-06-08 16:52:24 +0000233
Sean Callanan65dafa82010-08-27 01:01:44 +0000234 if (!process)
235 return false;
236
237 if (!m_compiled)
Chris Lattner24943d22010-06-08 16:52:24 +0000238 return false;
239
Sean Callanan65dafa82010-08-27 01:01:44 +0000240 if (m_JITted)
241 return true;
242
Sean Callanan830a9032010-08-27 23:31:21 +0000243 lldb::addr_t wrapper_function_end;
244
245 Error jit_error = m_parser->MakeJIT(m_wrapper_function_addr, wrapper_function_end, exe_ctx);
Sean Callanan65dafa82010-08-27 01:01:44 +0000246
247 if (!jit_error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +0000248 return false;
249
250 return true;
251}
252
253bool
Sean Callananc78d6482010-07-26 22:14:36 +0000254ClangFunction::WriteFunctionArguments (ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, Stream &errors)
Chris Lattner24943d22010-06-08 16:52:24 +0000255{
Sean Callananc78d6482010-07-26 22:14:36 +0000256 return WriteFunctionArguments(exe_ctx, args_addr_ref, m_function_addr, m_arg_values, errors);
Chris Lattner24943d22010-06-08 16:52:24 +0000257}
258
259// FIXME: Assure that the ValueList we were passed in is consistent with the one that defined this function.
260
261bool
Jim Ingham681778e2010-09-10 23:07:48 +0000262ClangFunction::WriteFunctionArguments (ExecutionContext &exe_ctx,
263 lldb::addr_t &args_addr_ref,
264 Address function_address,
265 ValueList &arg_values,
266 Stream &errors)
Chris Lattner24943d22010-06-08 16:52:24 +0000267{
Sean Callanan65dafa82010-08-27 01:01:44 +0000268 // All the information to reconstruct the struct is provided by the
269 // StructExtractor.
270 if (!m_struct_valid)
271 {
272 errors.Printf("Argument information was not correctly parsed, so the function cannot be called.");
273 return false;
274 }
275
Chris Lattner24943d22010-06-08 16:52:24 +0000276 Error error;
277 using namespace clang;
278 ExecutionResults return_value = eExecutionSetupError;
279
Sean Callananc78d6482010-07-26 22:14:36 +0000280 Process *process = exe_ctx.process;
Chris Lattner24943d22010-06-08 16:52:24 +0000281
282 if (process == NULL)
283 return return_value;
Sean Callanan65dafa82010-08-27 01:01:44 +0000284
Chris Lattner24943d22010-06-08 16:52:24 +0000285 if (args_addr_ref == LLDB_INVALID_ADDRESS)
286 {
Sean Callanan65dafa82010-08-27 01:01:44 +0000287 args_addr_ref = process->AllocateMemory(m_struct_size, lldb::ePermissionsReadable|lldb::ePermissionsWritable, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000288 if (args_addr_ref == LLDB_INVALID_ADDRESS)
289 return false;
290 m_wrapper_args_addrs.push_back (args_addr_ref);
291 }
292 else
293 {
294 // Make sure this is an address that we've already handed out.
295 if (find (m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr_ref) == m_wrapper_args_addrs.end())
296 {
297 return false;
298 }
299 }
300
301 // FIXME: This is fake, and just assumes that it matches that architecture.
302 // Make a data extractor and put the address into the right byte order & size.
303
Greg Claytoneea26402010-09-14 23:36:40 +0000304 uint64_t fun_addr = function_address.GetLoadAddress(exe_ctx.target);
Sean Callanan65dafa82010-08-27 01:01:44 +0000305 int first_offset = m_member_offsets[0];
Chris Lattner24943d22010-06-08 16:52:24 +0000306 process->WriteMemory(args_addr_ref + first_offset, &fun_addr, 8, error);
307
308 // FIXME: We will need to extend this for Variadic functions.
309
310 Error value_error;
311
312 size_t num_args = arg_values.GetSize();
313 if (num_args != m_arg_values.GetSize())
314 {
315 errors.Printf ("Wrong number of arguments - was: %d should be: %d", num_args, m_arg_values.GetSize());
316 return false;
317 }
318
Greg Clayton54e7afa2010-07-09 20:39:50 +0000319 for (size_t i = 0; i < num_args; i++)
Chris Lattner24943d22010-06-08 16:52:24 +0000320 {
321 // FIXME: We should sanity check sizes.
322
Sean Callanan65dafa82010-08-27 01:01:44 +0000323 int offset = m_member_offsets[i+1]; // Clang sizes are in bytes.
Chris Lattner24943d22010-06-08 16:52:24 +0000324 Value *arg_value = arg_values.GetValueAtIndex(i);
325
326 // FIXME: For now just do scalars:
327
328 // Special case: if it's a pointer, don't do anything (the ABI supports passing cstrings)
329
330 if (arg_value->GetValueType() == Value::eValueTypeHostAddress &&
Greg Clayton6916e352010-11-13 03:52:47 +0000331 arg_value->GetContextType() == Value::eContextTypeClangType &&
Greg Clayton462d4142010-09-29 01:12:09 +0000332 ClangASTContext::IsPointerType(arg_value->GetClangType()))
Chris Lattner24943d22010-06-08 16:52:24 +0000333 continue;
334
Sean Callananc78d6482010-07-26 22:14:36 +0000335 const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx, m_clang_ast_context->getASTContext());
Chris Lattner24943d22010-06-08 16:52:24 +0000336
337 int byte_size = arg_scalar.GetByteSize();
338 std::vector<uint8_t> buffer;
339 buffer.resize(byte_size);
340 DataExtractor value_data;
341 arg_scalar.GetData (value_data);
Greg Clayton53d68e72010-07-20 22:52:08 +0000342 value_data.ExtractBytes(0, byte_size, process->GetByteOrder(), &buffer.front());
343 process->WriteMemory(args_addr_ref + offset, &buffer.front(), byte_size, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000344 }
345
346 return true;
347}
348
349bool
Sean Callananc78d6482010-07-26 22:14:36 +0000350ClangFunction::InsertFunction (ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, Stream &errors)
Chris Lattner24943d22010-06-08 16:52:24 +0000351{
352 using namespace clang;
353
354 if (CompileFunction(errors) != 0)
355 return false;
Sean Callananc78d6482010-07-26 22:14:36 +0000356 if (!WriteFunctionWrapper(exe_ctx, errors))
Chris Lattner24943d22010-06-08 16:52:24 +0000357 return false;
Sean Callananc78d6482010-07-26 22:14:36 +0000358 if (!WriteFunctionArguments(exe_ctx, args_addr_ref, errors))
Chris Lattner24943d22010-06-08 16:52:24 +0000359 return false;
360
Greg Claytone005f2c2010-11-06 01:53:30 +0000361 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +0000362 if (log)
Greg Clayton54e7afa2010-07-09 20:39:50 +0000363 log->Printf ("Call Address: 0x%llx Struct Address: 0x%llx.\n", m_wrapper_function_addr, args_addr_ref);
Chris Lattner24943d22010-06-08 16:52:24 +0000364
365 return true;
366}
367
368ThreadPlan *
Jim Inghamea9d4262010-11-05 19:25:48 +0000369ClangFunction::GetThreadPlanToCallFunction (ExecutionContext &exe_ctx,
370 lldb::addr_t func_addr,
371 lldb::addr_t &args_addr,
372 Stream &errors,
373 bool stop_others,
374 bool discard_on_error,
375 lldb::addr_t *this_arg)
Chris Lattner24943d22010-06-08 16:52:24 +0000376{
377 // FIXME: Use the errors Stream for better error reporting.
378
Sean Callananc78d6482010-07-26 22:14:36 +0000379 Process *process = exe_ctx.process;
Chris Lattner24943d22010-06-08 16:52:24 +0000380
381 if (process == NULL)
382 {
383 errors.Printf("Can't call a function without a process.");
384 return NULL;
385 }
386
387 // Okay, now run the function:
388
Sean Callanan841026f2010-07-23 00:16:21 +0000389 Address wrapper_address (NULL, func_addr);
Sean Callananc78d6482010-07-26 22:14:36 +0000390 ThreadPlan *new_plan = new ThreadPlanCallFunction (*exe_ctx.thread,
Chris Lattner24943d22010-06-08 16:52:24 +0000391 wrapper_address,
392 args_addr,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000393 stop_others,
394 discard_on_error,
395 this_arg);
Chris Lattner24943d22010-06-08 16:52:24 +0000396 return new_plan;
397}
398
399bool
Sean Callananc78d6482010-07-26 22:14:36 +0000400ClangFunction::FetchFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr, Value &ret_value)
Chris Lattner24943d22010-06-08 16:52:24 +0000401{
402 // Read the return value - it is the last field in the struct:
403 // FIXME: How does clang tell us there's no return value? We need to handle that case.
404
405 std::vector<uint8_t> data_buffer;
406 data_buffer.resize(m_return_size);
Sean Callananc78d6482010-07-26 22:14:36 +0000407 Process *process = exe_ctx.process;
Chris Lattner24943d22010-06-08 16:52:24 +0000408 Error error;
Sean Callanan65dafa82010-08-27 01:01:44 +0000409 size_t bytes_read = process->ReadMemory(args_addr + m_return_offset, &data_buffer.front(), m_return_size, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000410
411 if (bytes_read == 0)
412 {
413 return false;
414 }
415
416 if (bytes_read < m_return_size)
417 return false;
418
Greg Clayton53d68e72010-07-20 22:52:08 +0000419 DataExtractor data(&data_buffer.front(), m_return_size, process->GetByteOrder(), process->GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +0000420 // FIXME: Assuming an integer scalar for now:
421
422 uint32_t offset = 0;
423 uint64_t return_integer = data.GetMaxU64(&offset, m_return_size);
424
Greg Clayton6916e352010-11-13 03:52:47 +0000425 ret_value.SetContext (Value::eContextTypeClangType, m_function_return_qual_type);
Chris Lattner24943d22010-06-08 16:52:24 +0000426 ret_value.SetValueType(Value::eValueTypeScalar);
427 ret_value.GetScalar() = return_integer;
428 return true;
429}
430
431void
Sean Callananc78d6482010-07-26 22:14:36 +0000432ClangFunction::DeallocateFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr)
Chris Lattner24943d22010-06-08 16:52:24 +0000433{
434 std::list<lldb::addr_t>::iterator pos;
435 pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr);
436 if (pos != m_wrapper_args_addrs.end())
437 m_wrapper_args_addrs.erase(pos);
438
Sean Callananc78d6482010-07-26 22:14:36 +0000439 exe_ctx.process->DeallocateMemory(args_addr);
Chris Lattner24943d22010-06-08 16:52:24 +0000440}
441
442ClangFunction::ExecutionResults
Sean Callananc78d6482010-07-26 22:14:36 +0000443ClangFunction::ExecuteFunction(ExecutionContext &exe_ctx, Stream &errors, Value &results)
Chris Lattner24943d22010-06-08 16:52:24 +0000444{
Sean Callananc78d6482010-07-26 22:14:36 +0000445 return ExecuteFunction (exe_ctx, errors, 1000, true, results);
Chris Lattner24943d22010-06-08 16:52:24 +0000446}
447
448ClangFunction::ExecutionResults
Sean Callananc78d6482010-07-26 22:14:36 +0000449ClangFunction::ExecuteFunction(ExecutionContext &exe_ctx, Stream &errors, bool stop_others, Value &results)
Chris Lattner24943d22010-06-08 16:52:24 +0000450{
Jim Inghamea9d4262010-11-05 19:25:48 +0000451 const bool try_all_threads = false;
452 const bool discard_on_error = true;
453 return ExecuteFunction (exe_ctx, NULL, errors, stop_others, NULL, try_all_threads, discard_on_error, results);
Chris Lattner24943d22010-06-08 16:52:24 +0000454}
455
456ClangFunction::ExecutionResults
457ClangFunction::ExecuteFunction(
Sean Callananc78d6482010-07-26 22:14:36 +0000458 ExecutionContext &exe_ctx,
Chris Lattner24943d22010-06-08 16:52:24 +0000459 Stream &errors,
460 uint32_t single_thread_timeout_usec,
461 bool try_all_threads,
462 Value &results)
463{
Jim Inghamea9d4262010-11-05 19:25:48 +0000464 const bool stop_others = true;
465 const bool discard_on_error = true;
466 return ExecuteFunction (exe_ctx, NULL, errors, stop_others, single_thread_timeout_usec,
467 try_all_threads, discard_on_error, results);
Chris Lattner24943d22010-06-08 16:52:24 +0000468}
469
Sean Callanan841026f2010-07-23 00:16:21 +0000470// This is the static function
471ClangFunction::ExecutionResults
472ClangFunction::ExecuteFunction (
Sean Callananc78d6482010-07-26 22:14:36 +0000473 ExecutionContext &exe_ctx,
Sean Callanan841026f2010-07-23 00:16:21 +0000474 lldb::addr_t function_address,
475 lldb::addr_t &void_arg,
476 bool stop_others,
477 bool try_all_threads,
Jim Inghamea9d4262010-11-05 19:25:48 +0000478 bool discard_on_error,
Sean Callanan841026f2010-07-23 00:16:21 +0000479 uint32_t single_thread_timeout_usec,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000480 Stream &errors,
481 lldb::addr_t *this_arg)
Chris Lattner24943d22010-06-08 16:52:24 +0000482{
Sean Callananc78d6482010-07-26 22:14:36 +0000483 // Save this value for restoration of the execution context after we run
Jim Ingham681778e2010-09-10 23:07:48 +0000484 uint32_t tid = exe_ctx.thread->GetIndexID();
Sean Callananc78d6482010-07-26 22:14:36 +0000485
Jim Ingham681778e2010-09-10 23:07:48 +0000486 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
487 // so we should arrange to reset them as well.
488
489 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
490 lldb::StackFrameSP selected_frame_sp;
491
492 uint32_t selected_tid;
493 if (selected_thread_sp != NULL)
494 {
495 selected_tid = selected_thread_sp->GetIndexID();
496 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
497 }
498 else
499 {
500 selected_tid = LLDB_INVALID_THREAD_ID;
501 }
502
Sean Callanan841026f2010-07-23 00:16:21 +0000503 ClangFunction::ExecutionResults return_value = eExecutionSetupError;
Jim Inghamea9d4262010-11-05 19:25:48 +0000504 lldb::ThreadPlanSP call_plan_sp(ClangFunction::GetThreadPlanToCallFunction(exe_ctx, function_address, void_arg,
505 errors, stop_others, discard_on_error,
506 this_arg));
Chris Lattner24943d22010-06-08 16:52:24 +0000507
508 ThreadPlanCallFunction *call_plan_ptr = static_cast<ThreadPlanCallFunction *> (call_plan_sp.get());
509
Chris Lattner24943d22010-06-08 16:52:24 +0000510 if (call_plan_sp == NULL)
Sean Callanan841026f2010-07-23 00:16:21 +0000511 return eExecutionSetupError;
512
Chris Lattner24943d22010-06-08 16:52:24 +0000513 call_plan_sp->SetPrivate(true);
Sean Callananc78d6482010-07-26 22:14:36 +0000514 exe_ctx.thread->QueueThreadPlan(call_plan_sp, true);
Jim Ingham3ae449a2010-11-17 02:32:00 +0000515
516 Listener listener("ClangFunction temporary listener");
517 exe_ctx.process->HijackProcessEvents(&listener);
518
519 Error resume_error = exe_ctx.process->Resume ();
520 if (!resume_error.Success())
521 {
522 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
523 exe_ctx.process->RestoreProcessEvents();
524 return eExecutionSetupError;
525 }
Sean Callanan841026f2010-07-23 00:16:21 +0000526
Chris Lattner24943d22010-06-08 16:52:24 +0000527 // We need to call the function synchronously, so spin waiting for it to return.
528 // If we get interrupted while executing, we're going to lose our context, and
529 // won't be able to gather the result at this point.
Jim Ingham3ae449a2010-11-17 02:32:00 +0000530 // We set the timeout AFTER the resume, since the resume takes some time and we
531 // don't want to charge that to the timeout.
Sean Callanan841026f2010-07-23 00:16:21 +0000532
Chris Lattner24943d22010-06-08 16:52:24 +0000533 TimeValue* timeout_ptr = NULL;
534 TimeValue real_timeout;
Sean Callanan841026f2010-07-23 00:16:21 +0000535
Chris Lattner24943d22010-06-08 16:52:24 +0000536 if (single_thread_timeout_usec != 0)
537 {
538 real_timeout = TimeValue::Now();
539 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
540 timeout_ptr = &real_timeout;
541 }
Sean Callanan841026f2010-07-23 00:16:21 +0000542
Greg Claytone005f2c2010-11-06 01:53:30 +0000543 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +0000544 while (1)
545 {
546 lldb::EventSP event_sp;
Jim Ingham63e24d72010-10-11 23:53:14 +0000547 lldb::StateType stop_state = lldb::eStateInvalid;
Chris Lattner24943d22010-06-08 16:52:24 +0000548 // Now wait for the process to stop again:
Jim Ingham63e24d72010-10-11 23:53:14 +0000549 bool got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Sean Callanan841026f2010-07-23 00:16:21 +0000550
Jim Ingham3ae449a2010-11-17 02:32:00 +0000551 if (!got_event)
Chris Lattner24943d22010-06-08 16:52:24 +0000552 {
553 // Right now this is the only way to tell we've timed out...
554 // We should interrupt the process here...
555 // Not really sure what to do if Halt fails here...
Chris Lattner24943d22010-06-08 16:52:24 +0000556 if (log)
Jim Ingham681778e2010-09-10 23:07:48 +0000557 if (try_all_threads)
Jim Inghamd1686902010-10-14 23:45:03 +0000558 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.",
559 single_thread_timeout_usec);
Jim Ingham681778e2010-09-10 23:07:48 +0000560 else
Jim Inghamd1686902010-10-14 23:45:03 +0000561 log->Printf ("Running function with timeout: %d timed out, abandoning execution.",
562 single_thread_timeout_usec);
Sean Callanan841026f2010-07-23 00:16:21 +0000563
Sean Callananc78d6482010-07-26 22:14:36 +0000564 if (exe_ctx.process->Halt().Success())
Chris Lattner24943d22010-06-08 16:52:24 +0000565 {
566 timeout_ptr = NULL;
Jim Ingham3ae449a2010-11-17 02:32:00 +0000567 if (log)
568 log->Printf ("Halt succeeded.");
Chris Lattner24943d22010-06-08 16:52:24 +0000569
Jim Ingham3ae449a2010-11-17 02:32:00 +0000570 // Between the time that we got the timeout and the time we halted, but target
571 // might have actually completed the plan. If so, we're done. Note, I call WFE here with a short
572 // timeout to
573 got_event = listener.WaitForEvent(NULL, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000574
Jim Ingham3ae449a2010-11-17 02:32:00 +0000575 if (got_event)
Chris Lattner24943d22010-06-08 16:52:24 +0000576 {
Jim Ingham3ae449a2010-11-17 02:32:00 +0000577 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
578 if (log)
579 {
580 log->Printf ("Stopped with event: %s", StateAsCString(stop_state));
581 if (stop_state == lldb::eStateStopped && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
582 log->Printf (" Event was the Halt interruption event.");
583 }
584
Sean Callananc78d6482010-07-26 22:14:36 +0000585 if (exe_ctx.thread->IsThreadPlanDone (call_plan_sp.get()))
Chris Lattner24943d22010-06-08 16:52:24 +0000586 {
Jim Ingham3ae449a2010-11-17 02:32:00 +0000587 if (log)
588 log->Printf ("Even though we timed out, the call plan was done. Exiting wait loop.");
Chris Lattner24943d22010-06-08 16:52:24 +0000589 return_value = eExecutionCompleted;
590 break;
591 }
Jim Ingham3ae449a2010-11-17 02:32:00 +0000592
593 if (try_all_threads)
594 {
595
596 call_plan_ptr->SetStopOthers (false);
597 if (log)
598 log->Printf ("About to resume.");
599
600 exe_ctx.process->Resume();
601 continue;
602 }
603 else
604 {
605 exe_ctx.process->RestoreProcessEvents ();
606 return eExecutionInterrupted;
607 }
Jim Ingham63e24d72010-10-11 23:53:14 +0000608 }
Chris Lattner24943d22010-06-08 16:52:24 +0000609 }
610 }
Jim Ingham63e24d72010-10-11 23:53:14 +0000611
612 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham3ae449a2010-11-17 02:32:00 +0000613 if (log)
614 log->Printf("Got event: %s.", StateAsCString(stop_state));
Jim Ingham63e24d72010-10-11 23:53:14 +0000615
Chris Lattner24943d22010-06-08 16:52:24 +0000616 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
617 continue;
Sean Callanan841026f2010-07-23 00:16:21 +0000618
Sean Callananc78d6482010-07-26 22:14:36 +0000619 if (exe_ctx.thread->IsThreadPlanDone (call_plan_sp.get()))
Chris Lattner24943d22010-06-08 16:52:24 +0000620 {
621 return_value = eExecutionCompleted;
622 break;
623 }
Sean Callananc78d6482010-07-26 22:14:36 +0000624 else if (exe_ctx.thread->WasThreadPlanDiscarded (call_plan_sp.get()))
Chris Lattner24943d22010-06-08 16:52:24 +0000625 {
626 return_value = eExecutionDiscarded;
627 break;
628 }
629 else
630 {
Sean Callanan841026f2010-07-23 00:16:21 +0000631 if (log)
632 {
633 StreamString s;
634 event_sp->Dump (&s);
635 StreamString ts;
636
637 const char *event_explanation;
638
639 do
640 {
641 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
642
643 if (!event_data)
644 {
645 event_explanation = "<no event data>";
646 break;
647 }
648
649 Process *process = event_data->GetProcessSP().get();
650
651 if (!process)
652 {
653 event_explanation = "<no process>";
654 break;
655 }
656
657 ThreadList &thread_list = process->GetThreadList();
658
659 uint32_t num_threads = thread_list.GetSize();
660 uint32_t thread_index;
661
662 ts.Printf("<%u threads> ", num_threads);
663
664 for (thread_index = 0;
665 thread_index < num_threads;
666 ++thread_index)
667 {
668 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
669
670 if (!thread)
671 {
672 ts.Printf("<?> ");
673 continue;
674 }
675
Sean Callanan841026f2010-07-23 00:16:21 +0000676 ts.Printf("<");
677 RegisterContext *register_context = thread->GetRegisterContext();
678
679 if (register_context)
680 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
681 else
682 ts.Printf("[ip unknown] ");
683
Jim Ingham6297a3a2010-10-20 00:39:53 +0000684 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
685 if (stop_info_sp)
Greg Clayton643ee732010-08-04 01:40:35 +0000686 {
Jim Ingham6297a3a2010-10-20 00:39:53 +0000687 const char *stop_desc = stop_info_sp->GetDescription();
Greg Clayton643ee732010-08-04 01:40:35 +0000688 if (stop_desc)
689 ts.PutCString (stop_desc);
690 }
Sean Callanan841026f2010-07-23 00:16:21 +0000691 ts.Printf(">");
692 }
693
694 event_explanation = ts.GetData();
695 } while (0);
696
Caroline Tice926060e2010-10-29 21:48:37 +0000697 if (log)
698 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan841026f2010-07-23 00:16:21 +0000699 }
700
Jim Inghamea9d4262010-11-05 19:25:48 +0000701 if (discard_on_error && call_plan_sp)
702 {
703 exe_ctx.thread->DiscardThreadPlansUpToPlan (call_plan_sp);
704 }
Chris Lattner24943d22010-06-08 16:52:24 +0000705 return_value = eExecutionInterrupted;
706 break;
707 }
Chris Lattner24943d22010-06-08 16:52:24 +0000708 }
Sean Callanan841026f2010-07-23 00:16:21 +0000709
Jim Ingham63e24d72010-10-11 23:53:14 +0000710 if (exe_ctx.process)
711 exe_ctx.process->RestoreProcessEvents ();
712
Sean Callananc78d6482010-07-26 22:14:36 +0000713 // Thread we ran the function in may have gone away because we ran the target
714 // Check that it's still there.
Jim Ingham681778e2010-09-10 23:07:48 +0000715 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
Jim Ingham324067b2010-09-30 00:54:27 +0000716 if (exe_ctx.thread)
717 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
Sean Callananc78d6482010-07-26 22:14:36 +0000718
Jim Ingham681778e2010-09-10 23:07:48 +0000719 // Also restore the current process'es selected frame & thread, since this function calling may
720 // be done behind the user's back.
721
722 if (selected_tid != LLDB_INVALID_THREAD_ID)
723 {
724 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
725 {
726 // We were able to restore the selected thread, now restore the frame:
727 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
728 }
729 }
730
Sean Callanan841026f2010-07-23 00:16:21 +0000731 return return_value;
732}
Chris Lattner24943d22010-06-08 16:52:24 +0000733
Sean Callanan841026f2010-07-23 00:16:21 +0000734ClangFunction::ExecutionResults
735ClangFunction::ExecuteFunction(
Sean Callananc78d6482010-07-26 22:14:36 +0000736 ExecutionContext &exe_ctx,
Sean Callanan841026f2010-07-23 00:16:21 +0000737 lldb::addr_t *args_addr_ptr,
738 Stream &errors,
739 bool stop_others,
740 uint32_t single_thread_timeout_usec,
Jim Inghamea9d4262010-11-05 19:25:48 +0000741 bool try_all_threads,
742 bool discard_on_error,
Sean Callanan841026f2010-07-23 00:16:21 +0000743 Value &results)
744{
745 using namespace clang;
746 ExecutionResults return_value = eExecutionSetupError;
747
748 lldb::addr_t args_addr;
749
750 if (args_addr_ptr != NULL)
751 args_addr = *args_addr_ptr;
752 else
753 args_addr = LLDB_INVALID_ADDRESS;
754
755 if (CompileFunction(errors) != 0)
756 return eExecutionSetupError;
757
758 if (args_addr == LLDB_INVALID_ADDRESS)
759 {
Sean Callananc78d6482010-07-26 22:14:36 +0000760 if (!InsertFunction(exe_ctx, args_addr, errors))
Sean Callanan841026f2010-07-23 00:16:21 +0000761 return eExecutionSetupError;
762 }
763
Jim Ingham681778e2010-09-10 23:07:48 +0000764 return_value = ClangFunction::ExecuteFunction(exe_ctx, m_wrapper_function_addr, args_addr, stop_others,
Jim Inghamea9d4262010-11-05 19:25:48 +0000765 try_all_threads, discard_on_error, single_thread_timeout_usec, errors);
Sean Callanan841026f2010-07-23 00:16:21 +0000766
767 if (args_addr_ptr != NULL)
768 *args_addr_ptr = args_addr;
769
Chris Lattner24943d22010-06-08 16:52:24 +0000770 if (return_value != eExecutionCompleted)
771 return return_value;
772
Sean Callananc78d6482010-07-26 22:14:36 +0000773 FetchFunctionResults(exe_ctx, args_addr, results);
Chris Lattner24943d22010-06-08 16:52:24 +0000774
775 if (args_addr_ptr == NULL)
Sean Callananc78d6482010-07-26 22:14:36 +0000776 DeallocateFunctionResults(exe_ctx, args_addr);
Chris Lattner24943d22010-06-08 16:52:24 +0000777
778 return eExecutionCompleted;
779}
780
Sean Callanan65dafa82010-08-27 01:01:44 +0000781clang::ASTConsumer *
782ClangFunction::ASTTransformer (clang::ASTConsumer *passthrough)
Chris Lattner24943d22010-06-08 16:52:24 +0000783{
Sean Callanan65dafa82010-08-27 01:01:44 +0000784 return new ASTStructExtractor(passthrough, m_wrapper_struct_name.c_str(), *this);
Chris Lattner24943d22010-06-08 16:52:24 +0000785}