blob: 957be2acf9efd25a98b18933d13f0c465932f971 [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/ExecutionEngine/JIT.h"
22#include "llvm/Module.h"
Chris Lattner24943d22010-06-08 16:52:24 +000023
24// Project includes
25#include "lldb/Expression/ClangFunction.h"
26#include "lldb/Symbol/Type.h"
27#include "lldb/Core/DataExtractor.h"
28#include "lldb/Core/ValueObject.h"
29#include "lldb/Core/ValueObjectList.h"
30#include "lldb/Interpreter/CommandReturnObject.h"
31#include "lldb/Symbol/ClangASTContext.h"
32#include "lldb/Symbol/Function.h"
33#include "lldb/Target/ExecutionContext.h"
34#include "lldb/Target/Process.h"
Sean Callanan841026f2010-07-23 00:16:21 +000035#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000036#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000037#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
39#include "lldb/Target/ThreadPlanCallFunction.h"
40#include "lldb/Core/Log.h"
41
42using namespace lldb_private;
43//----------------------------------------------------------------------
44// ClangFunction constructor
45//----------------------------------------------------------------------
46ClangFunction::ClangFunction(const char *target_triple, ClangASTContext *ast_context, void *return_qualtype, const Address& functionAddress, const ValueList &arg_value_list) :
47 ClangExpression (target_triple, NULL),
Chris Lattner24943d22010-06-08 16:52:24 +000048 m_function_ptr (NULL),
Greg Clayton54e7afa2010-07-09 20:39:50 +000049 m_function_addr (functionAddress),
Chris Lattner24943d22010-06-08 16:52:24 +000050 m_function_return_qual_type(return_qualtype),
Greg Clayton54e7afa2010-07-09 20:39:50 +000051 m_clang_ast_context (ast_context),
Chris Lattner24943d22010-06-08 16:52:24 +000052 m_wrapper_function_name ("__lldb_caller_function"),
53 m_wrapper_struct_name ("__lldb_caller_struct"),
Greg Clayton54e7afa2010-07-09 20:39:50 +000054 m_wrapper_function_addr (),
55 m_wrapper_args_addrs (),
56 m_struct_layout (NULL),
57 m_arg_values (arg_value_list),
58 m_value_struct_size (0),
Chris Lattner24943d22010-06-08 16:52:24 +000059 m_return_offset(0),
Greg Clayton54e7afa2010-07-09 20:39:50 +000060 m_return_size (0),
Chris Lattner24943d22010-06-08 16:52:24 +000061 m_compiled (false),
62 m_JITted (false)
63{
64}
65
66ClangFunction::ClangFunction(const char *target_triple, Function &function, ClangASTContext *ast_context, const ValueList &arg_value_list) :
67 ClangExpression (target_triple, NULL),
68 m_function_ptr (&function),
Greg Clayton54e7afa2010-07-09 20:39:50 +000069 m_function_addr (),
70 m_function_return_qual_type (),
Chris Lattner24943d22010-06-08 16:52:24 +000071 m_clang_ast_context (ast_context),
Chris Lattner24943d22010-06-08 16:52:24 +000072 m_wrapper_function_name ("__lldb_function_caller"),
73 m_wrapper_struct_name ("__lldb_caller_struct"),
Greg Clayton54e7afa2010-07-09 20:39:50 +000074 m_wrapper_function_addr (),
75 m_wrapper_args_addrs (),
76 m_struct_layout (NULL),
77 m_arg_values (arg_value_list),
78 m_value_struct_size (0),
79 m_return_offset (0),
80 m_return_size (0),
Chris Lattner24943d22010-06-08 16:52:24 +000081 m_compiled (false),
82 m_JITted (false)
83{
84 m_function_addr = m_function_ptr->GetAddressRange().GetBaseAddress();
85 m_function_return_qual_type = m_function_ptr->GetReturnType().GetOpaqueClangQualType();
86}
87
88//----------------------------------------------------------------------
89// Destructor
90//----------------------------------------------------------------------
91ClangFunction::~ClangFunction()
92{
93}
94
95unsigned
96ClangFunction::CompileFunction (Stream &errors)
97{
98 // FIXME: How does clang tell us there's no return value? We need to handle that case.
99 unsigned num_errors = 0;
100
101 if (!m_compiled)
102 {
103 std::string return_type_str = ClangASTContext::GetTypeName(m_function_return_qual_type);
104
105 // Cons up the function we're going to wrap our call in, then compile it...
106 // We declare the function "extern "C"" because the compiler might be in C++
107 // mode which would mangle the name and then we couldn't find it again...
108 std::string expression;
109 expression.append ("extern \"C\" void ");
110 expression.append (m_wrapper_function_name);
111 expression.append (" (void *input)\n{\n struct ");
112 expression.append (m_wrapper_struct_name);
113 expression.append (" \n {\n");
114 expression.append (" ");
115 expression.append (return_type_str);
116 expression.append (" (*fn_ptr) (");
117
118 // Get the number of arguments. If we have a function type and it is prototyped,
119 // trust that, otherwise use the values we were given.
120
121 // FIXME: This will need to be extended to handle Variadic functions. We'll need
122 // to pull the defined arguments out of the function, then add the types from the
123 // arguments list for the variable arguments.
124
Greg Clayton54e7afa2010-07-09 20:39:50 +0000125 uint32_t num_args = UINT32_MAX;
Chris Lattner24943d22010-06-08 16:52:24 +0000126 bool trust_function = false;
127 // GetArgumentCount returns -1 for an unprototyped function.
128 if (m_function_ptr)
129 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000130 int num_func_args = m_function_ptr->GetArgumentCount();
131 if (num_func_args >= 0)
Chris Lattner24943d22010-06-08 16:52:24 +0000132 trust_function = true;
Greg Clayton54e7afa2010-07-09 20:39:50 +0000133 else
134 num_args = num_func_args;
Chris Lattner24943d22010-06-08 16:52:24 +0000135 }
136
Greg Clayton54e7afa2010-07-09 20:39:50 +0000137 if (num_args == UINT32_MAX)
Chris Lattner24943d22010-06-08 16:52:24 +0000138 num_args = m_arg_values.GetSize();
139
140 std::string args_buffer; // This one stores the definition of all the args in "struct caller".
141 std::string args_list_buffer; // This one stores the argument list called from the structure.
Greg Clayton54e7afa2010-07-09 20:39:50 +0000142 for (size_t i = 0; i < num_args; i++)
Chris Lattner24943d22010-06-08 16:52:24 +0000143 {
144 const char *type_string;
145 std::string type_stdstr;
146
147 if (trust_function)
148 {
149 type_string = m_function_ptr->GetArgumentTypeAtIndex(i).GetName().AsCString();
150 }
151 else
152 {
153 Value *arg_value = m_arg_values.GetValueAtIndex(i);
154 void *clang_qual_type = arg_value->GetOpaqueClangQualType ();
155 if (clang_qual_type != NULL)
156 {
157 type_stdstr = ClangASTContext::GetTypeName(clang_qual_type);
158 type_string = type_stdstr.c_str();
159 }
160 else
161 {
162 errors.Printf("Could not determine type of input value %d.", i);
163 return 1;
164 }
165 }
166
167
168 expression.append (type_string);
169 if (i < num_args - 1)
170 expression.append (", ");
171
172 char arg_buf[32];
173 args_buffer.append (" ");
174 args_buffer.append (type_string);
Greg Clayton54e7afa2010-07-09 20:39:50 +0000175 snprintf(arg_buf, 31, "arg_%zd", i);
Chris Lattner24943d22010-06-08 16:52:24 +0000176 args_buffer.push_back (' ');
177 args_buffer.append (arg_buf);
178 args_buffer.append (";\n");
179
180 args_list_buffer.append ("__lldb_fn_data->");
181 args_list_buffer.append (arg_buf);
182 if (i < num_args - 1)
183 args_list_buffer.append (", ");
184
185 }
186 expression.append (");\n"); // Close off the function calling prototype.
187
188 expression.append (args_buffer);
189
190 expression.append (" ");
191 expression.append (return_type_str);
192 expression.append (" return_value;");
193 expression.append ("\n };\n struct ");
194 expression.append (m_wrapper_struct_name);
195 expression.append ("* __lldb_fn_data = (struct ");
196 expression.append (m_wrapper_struct_name);
197 expression.append (" *) input;\n");
198
199 expression.append (" __lldb_fn_data->return_value = __lldb_fn_data->fn_ptr (");
200 expression.append (args_list_buffer);
201 expression.append (");\n}\n");
202
203 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);
204 if (log)
205 log->Printf ("Expression: \n\n%s\n\n", expression.c_str());
206
207 // Okay, now compile this expression:
208 num_errors = ParseBareExpression (expression.c_str(), errors);
209 m_compiled = (num_errors == 0);
210
211 if (m_compiled)
212 {
213 using namespace clang;
214 CompilerInstance *compiler_instance = GetCompilerInstance();
215 ASTContext &ast_context = compiler_instance->getASTContext();
216
217 DeclarationName wrapper_func_name(&ast_context.Idents.get(m_wrapper_function_name.c_str()));
218 FunctionDecl::lookup_result func_lookup = ast_context.getTranslationUnitDecl()->lookup(wrapper_func_name);
219 if (func_lookup.first == func_lookup.second)
220 return false;
221
222 FunctionDecl *wrapper_func = dyn_cast<FunctionDecl> (*(func_lookup.first));
223 if (!wrapper_func)
224 return false;
225
226 DeclarationName wrapper_struct_name(&ast_context.Idents.get(m_wrapper_struct_name.c_str()));
227 RecordDecl::lookup_result struct_lookup = wrapper_func->lookup(wrapper_struct_name);
228 if (struct_lookup.first == struct_lookup.second)
229 return false;
230
231 RecordDecl *wrapper_struct = dyn_cast<RecordDecl>(*(struct_lookup.first));
232
233 if (!wrapper_struct)
234 return false;
235
236 m_struct_layout = &ast_context.getASTRecordLayout (wrapper_struct);
237 if (!m_struct_layout)
238 {
239 m_compiled = false;
240 return 1;
241 }
242 m_return_offset = m_struct_layout->getFieldOffset(m_struct_layout->getFieldCount() - 1);
243 m_return_size = (m_struct_layout->getDataSize() - m_return_offset)/8;
244 }
245 }
246
247 return num_errors;
248}
249
250bool
Sean Callananc78d6482010-07-26 22:14:36 +0000251ClangFunction::WriteFunctionWrapper (ExecutionContext &exe_ctx, Stream &errors)
Chris Lattner24943d22010-06-08 16:52:24 +0000252{
Sean Callananc78d6482010-07-26 22:14:36 +0000253 Process *process = exe_ctx.process;
Chris Lattner24943d22010-06-08 16:52:24 +0000254
255 if (process == NULL)
256 return false;
257
258 if (!m_JITted)
259 {
260 // Next we should JIT it and insert the result into the target program.
Sean Callanan39ee6002010-08-13 00:28:39 +0000261 if (!JITFunction (m_wrapper_function_name.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +0000262 return false;
263
Sean Callananc78d6482010-07-26 22:14:36 +0000264 if (!WriteJITCode (exe_ctx))
Chris Lattner24943d22010-06-08 16:52:24 +0000265 return false;
266
267 m_JITted = true;
268 }
269
270 // Next get the call address for the function:
Greg Clayton54e7afa2010-07-09 20:39:50 +0000271 m_wrapper_function_addr = GetFunctionAddress (m_wrapper_function_name.c_str());
272 if (m_wrapper_function_addr == LLDB_INVALID_ADDRESS)
Chris Lattner24943d22010-06-08 16:52:24 +0000273 return false;
274
275 return true;
276}
277
278bool
Sean Callananc78d6482010-07-26 22:14:36 +0000279ClangFunction::WriteFunctionArguments (ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, Stream &errors)
Chris Lattner24943d22010-06-08 16:52:24 +0000280{
Sean Callananc78d6482010-07-26 22:14:36 +0000281 return WriteFunctionArguments(exe_ctx, args_addr_ref, m_function_addr, m_arg_values, errors);
Chris Lattner24943d22010-06-08 16:52:24 +0000282}
283
284// FIXME: Assure that the ValueList we were passed in is consistent with the one that defined this function.
285
286bool
Sean Callananc78d6482010-07-26 22:14:36 +0000287ClangFunction::WriteFunctionArguments (ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, Address function_address, ValueList &arg_values, Stream &errors)
Chris Lattner24943d22010-06-08 16:52:24 +0000288{
289 // Otherwise, allocate space for the argument passing struct, and write it.
290 // We use the information in the expression parser AST to
291 // figure out how to do this...
292 // We should probably transcode this in this object so we can ditch the compiler instance
293 // and all its associated data, and just keep the JITTed bytes.
294
295 Error error;
296 using namespace clang;
297 ExecutionResults return_value = eExecutionSetupError;
298
Sean Callananc78d6482010-07-26 22:14:36 +0000299 Process *process = exe_ctx.process;
Chris Lattner24943d22010-06-08 16:52:24 +0000300
301 if (process == NULL)
302 return return_value;
303
304 uint64_t struct_size = m_struct_layout->getSize()/8; // Clang returns sizes in bytes.
305
306 if (args_addr_ref == LLDB_INVALID_ADDRESS)
307 {
308 args_addr_ref = process->AllocateMemory(struct_size, lldb::ePermissionsReadable|lldb::ePermissionsWritable, error);
309 if (args_addr_ref == LLDB_INVALID_ADDRESS)
310 return false;
311 m_wrapper_args_addrs.push_back (args_addr_ref);
312 }
313 else
314 {
315 // Make sure this is an address that we've already handed out.
316 if (find (m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr_ref) == m_wrapper_args_addrs.end())
317 {
318 return false;
319 }
320 }
321
322 // FIXME: This is fake, and just assumes that it matches that architecture.
323 // Make a data extractor and put the address into the right byte order & size.
324
Sean Callananc78d6482010-07-26 22:14:36 +0000325 uint64_t fun_addr = function_address.GetLoadAddress(exe_ctx.process);
Chris Lattner24943d22010-06-08 16:52:24 +0000326 int first_offset = m_struct_layout->getFieldOffset(0)/8;
327 process->WriteMemory(args_addr_ref + first_offset, &fun_addr, 8, error);
328
329 // FIXME: We will need to extend this for Variadic functions.
330
331 Error value_error;
332
333 size_t num_args = arg_values.GetSize();
334 if (num_args != m_arg_values.GetSize())
335 {
336 errors.Printf ("Wrong number of arguments - was: %d should be: %d", num_args, m_arg_values.GetSize());
337 return false;
338 }
339
Greg Clayton54e7afa2010-07-09 20:39:50 +0000340 for (size_t i = 0; i < num_args; i++)
Chris Lattner24943d22010-06-08 16:52:24 +0000341 {
342 // FIXME: We should sanity check sizes.
343
344 int offset = m_struct_layout->getFieldOffset(i+1)/8; // Clang sizes are in bytes.
345 Value *arg_value = arg_values.GetValueAtIndex(i);
346
347 // FIXME: For now just do scalars:
348
349 // Special case: if it's a pointer, don't do anything (the ABI supports passing cstrings)
350
351 if (arg_value->GetValueType() == Value::eValueTypeHostAddress &&
352 arg_value->GetContextType() == Value::eContextTypeOpaqueClangQualType &&
353 ClangASTContext::IsPointerType(arg_value->GetValueOpaqueClangQualType()))
354 continue;
355
Sean Callananc78d6482010-07-26 22:14:36 +0000356 const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx, m_clang_ast_context->getASTContext());
Chris Lattner24943d22010-06-08 16:52:24 +0000357
358 int byte_size = arg_scalar.GetByteSize();
359 std::vector<uint8_t> buffer;
360 buffer.resize(byte_size);
361 DataExtractor value_data;
362 arg_scalar.GetData (value_data);
Greg Clayton53d68e72010-07-20 22:52:08 +0000363 value_data.ExtractBytes(0, byte_size, process->GetByteOrder(), &buffer.front());
364 process->WriteMemory(args_addr_ref + offset, &buffer.front(), byte_size, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000365 }
366
367 return true;
368}
369
370bool
Sean Callananc78d6482010-07-26 22:14:36 +0000371ClangFunction::InsertFunction (ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, Stream &errors)
Chris Lattner24943d22010-06-08 16:52:24 +0000372{
373 using namespace clang;
374
375 if (CompileFunction(errors) != 0)
376 return false;
Sean Callananc78d6482010-07-26 22:14:36 +0000377 if (!WriteFunctionWrapper(exe_ctx, errors))
Chris Lattner24943d22010-06-08 16:52:24 +0000378 return false;
Sean Callananc78d6482010-07-26 22:14:36 +0000379 if (!WriteFunctionArguments(exe_ctx, args_addr_ref, errors))
Chris Lattner24943d22010-06-08 16:52:24 +0000380 return false;
381
382 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);
383 if (log)
Greg Clayton54e7afa2010-07-09 20:39:50 +0000384 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 +0000385
386 return true;
387}
388
389ThreadPlan *
Sean Callananc78d6482010-07-26 22:14:36 +0000390ClangFunction::GetThreadPlanToCallFunction (ExecutionContext &exe_ctx, lldb::addr_t func_addr, lldb::addr_t &args_addr, Stream &errors, bool stop_others, bool discard_on_error)
Chris Lattner24943d22010-06-08 16:52:24 +0000391{
392 // FIXME: Use the errors Stream for better error reporting.
393
Sean Callananc78d6482010-07-26 22:14:36 +0000394 Process *process = exe_ctx.process;
Chris Lattner24943d22010-06-08 16:52:24 +0000395
396 if (process == NULL)
397 {
398 errors.Printf("Can't call a function without a process.");
399 return NULL;
400 }
401
402 // Okay, now run the function:
403
Sean Callanan841026f2010-07-23 00:16:21 +0000404 Address wrapper_address (NULL, func_addr);
Sean Callananc78d6482010-07-26 22:14:36 +0000405 ThreadPlan *new_plan = new ThreadPlanCallFunction (*exe_ctx.thread,
Chris Lattner24943d22010-06-08 16:52:24 +0000406 wrapper_address,
407 args_addr,
408 stop_others, discard_on_error);
409 return new_plan;
410}
411
412bool
Sean Callananc78d6482010-07-26 22:14:36 +0000413ClangFunction::FetchFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr, Value &ret_value)
Chris Lattner24943d22010-06-08 16:52:24 +0000414{
415 // Read the return value - it is the last field in the struct:
416 // FIXME: How does clang tell us there's no return value? We need to handle that case.
417
418 std::vector<uint8_t> data_buffer;
419 data_buffer.resize(m_return_size);
Sean Callananc78d6482010-07-26 22:14:36 +0000420 Process *process = exe_ctx.process;
Chris Lattner24943d22010-06-08 16:52:24 +0000421 Error error;
Greg Clayton53d68e72010-07-20 22:52:08 +0000422 size_t bytes_read = process->ReadMemory(args_addr + m_return_offset/8, &data_buffer.front(), m_return_size, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000423
424 if (bytes_read == 0)
425 {
426 return false;
427 }
428
429 if (bytes_read < m_return_size)
430 return false;
431
Greg Clayton53d68e72010-07-20 22:52:08 +0000432 DataExtractor data(&data_buffer.front(), m_return_size, process->GetByteOrder(), process->GetAddressByteSize());
Chris Lattner24943d22010-06-08 16:52:24 +0000433 // FIXME: Assuming an integer scalar for now:
434
435 uint32_t offset = 0;
436 uint64_t return_integer = data.GetMaxU64(&offset, m_return_size);
437
438 ret_value.SetContext (Value::eContextTypeOpaqueClangQualType, m_function_return_qual_type);
439 ret_value.SetValueType(Value::eValueTypeScalar);
440 ret_value.GetScalar() = return_integer;
441 return true;
442}
443
444void
Sean Callananc78d6482010-07-26 22:14:36 +0000445ClangFunction::DeallocateFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr)
Chris Lattner24943d22010-06-08 16:52:24 +0000446{
447 std::list<lldb::addr_t>::iterator pos;
448 pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr);
449 if (pos != m_wrapper_args_addrs.end())
450 m_wrapper_args_addrs.erase(pos);
451
Sean Callananc78d6482010-07-26 22:14:36 +0000452 exe_ctx.process->DeallocateMemory(args_addr);
Chris Lattner24943d22010-06-08 16:52:24 +0000453}
454
455ClangFunction::ExecutionResults
Sean Callananc78d6482010-07-26 22:14:36 +0000456ClangFunction::ExecuteFunction(ExecutionContext &exe_ctx, Stream &errors, Value &results)
Chris Lattner24943d22010-06-08 16:52:24 +0000457{
Sean Callananc78d6482010-07-26 22:14:36 +0000458 return ExecuteFunction (exe_ctx, errors, 1000, true, results);
Chris Lattner24943d22010-06-08 16:52:24 +0000459}
460
461ClangFunction::ExecutionResults
Sean Callananc78d6482010-07-26 22:14:36 +0000462ClangFunction::ExecuteFunction(ExecutionContext &exe_ctx, Stream &errors, bool stop_others, Value &results)
Chris Lattner24943d22010-06-08 16:52:24 +0000463{
Sean Callananc78d6482010-07-26 22:14:36 +0000464 return ExecuteFunction (exe_ctx, NULL, errors, stop_others, NULL, false, results);
Chris Lattner24943d22010-06-08 16:52:24 +0000465}
466
467ClangFunction::ExecutionResults
468ClangFunction::ExecuteFunction(
Sean Callananc78d6482010-07-26 22:14:36 +0000469 ExecutionContext &exe_ctx,
Chris Lattner24943d22010-06-08 16:52:24 +0000470 Stream &errors,
471 uint32_t single_thread_timeout_usec,
472 bool try_all_threads,
473 Value &results)
474{
Sean Callananc78d6482010-07-26 22:14:36 +0000475 return ExecuteFunction (exe_ctx, NULL, errors, true, single_thread_timeout_usec, try_all_threads, results);
Chris Lattner24943d22010-06-08 16:52:24 +0000476}
477
Sean Callanan841026f2010-07-23 00:16:21 +0000478// This is the static function
479ClangFunction::ExecutionResults
480ClangFunction::ExecuteFunction (
Sean Callananc78d6482010-07-26 22:14:36 +0000481 ExecutionContext &exe_ctx,
Sean Callanan841026f2010-07-23 00:16:21 +0000482 lldb::addr_t function_address,
483 lldb::addr_t &void_arg,
484 bool stop_others,
485 bool try_all_threads,
486 uint32_t single_thread_timeout_usec,
487 Stream &errors)
Chris Lattner24943d22010-06-08 16:52:24 +0000488{
Sean Callananc78d6482010-07-26 22:14:36 +0000489 // Save this value for restoration of the execution context after we run
490 uint32_t tid = exe_ctx.thread->GetID();
491
Sean Callanan841026f2010-07-23 00:16:21 +0000492 ClangFunction::ExecutionResults return_value = eExecutionSetupError;
Chris Lattner24943d22010-06-08 16:52:24 +0000493
Sean Callananc78d6482010-07-26 22:14:36 +0000494 lldb::ThreadPlanSP call_plan_sp(ClangFunction::GetThreadPlanToCallFunction(exe_ctx, function_address, void_arg, errors, stop_others, false));
Chris Lattner24943d22010-06-08 16:52:24 +0000495
496 ThreadPlanCallFunction *call_plan_ptr = static_cast<ThreadPlanCallFunction *> (call_plan_sp.get());
497
Chris Lattner24943d22010-06-08 16:52:24 +0000498 if (call_plan_sp == NULL)
Sean Callanan841026f2010-07-23 00:16:21 +0000499 return eExecutionSetupError;
500
Chris Lattner24943d22010-06-08 16:52:24 +0000501 call_plan_sp->SetPrivate(true);
Sean Callananc78d6482010-07-26 22:14:36 +0000502 exe_ctx.thread->QueueThreadPlan(call_plan_sp, true);
Sean Callanan841026f2010-07-23 00:16:21 +0000503
Chris Lattner24943d22010-06-08 16:52:24 +0000504 // We need to call the function synchronously, so spin waiting for it to return.
505 // If we get interrupted while executing, we're going to lose our context, and
506 // won't be able to gather the result at this point.
Sean Callanan841026f2010-07-23 00:16:21 +0000507
Chris Lattner24943d22010-06-08 16:52:24 +0000508 TimeValue* timeout_ptr = NULL;
509 TimeValue real_timeout;
Sean Callanan841026f2010-07-23 00:16:21 +0000510
Chris Lattner24943d22010-06-08 16:52:24 +0000511 if (single_thread_timeout_usec != 0)
512 {
513 real_timeout = TimeValue::Now();
514 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
515 timeout_ptr = &real_timeout;
516 }
Sean Callanan841026f2010-07-23 00:16:21 +0000517
Sean Callananc78d6482010-07-26 22:14:36 +0000518 exe_ctx.process->Resume ();
Sean Callanan841026f2010-07-23 00:16:21 +0000519
520 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);
Chris Lattner24943d22010-06-08 16:52:24 +0000521
522 while (1)
523 {
524 lldb::EventSP event_sp;
Sean Callanan841026f2010-07-23 00:16:21 +0000525
Chris Lattner24943d22010-06-08 16:52:24 +0000526 // Now wait for the process to stop again:
527 // FIXME: Probably want a time out.
Sean Callananc78d6482010-07-26 22:14:36 +0000528 lldb::StateType stop_state = exe_ctx.process->WaitForStateChangedEvents (timeout_ptr, event_sp);
Sean Callanan841026f2010-07-23 00:16:21 +0000529
Chris Lattner24943d22010-06-08 16:52:24 +0000530 if (stop_state == lldb::eStateInvalid && timeout_ptr != NULL)
531 {
532 // Right now this is the only way to tell we've timed out...
533 // We should interrupt the process here...
534 // Not really sure what to do if Halt fails here...
Chris Lattner24943d22010-06-08 16:52:24 +0000535 if (log)
536 log->Printf ("Running function with timeout: %d timed out, trying with all threads enabled.", single_thread_timeout_usec);
Sean Callanan841026f2010-07-23 00:16:21 +0000537
Sean Callananc78d6482010-07-26 22:14:36 +0000538 if (exe_ctx.process->Halt().Success())
Chris Lattner24943d22010-06-08 16:52:24 +0000539 {
540 timeout_ptr = NULL;
541
Sean Callananc78d6482010-07-26 22:14:36 +0000542 stop_state = exe_ctx.process->WaitForStateChangedEvents (timeout_ptr, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000543 if (stop_state == lldb::eStateInvalid)
544 {
545 errors.Printf ("Got an invalid stop state after halt.");
546 }
547 else if (stop_state != lldb::eStateStopped)
548 {
549 StreamString s;
550 event_sp->Dump (&s);
551
552 errors.Printf("Didn't get a stopped event after Halting the target, got: \"%s\"", s.GetData());
553 }
554
555 if (try_all_threads)
556 {
557 // Between the time that we got the timeout and the time we halted, but target
558 // might have actually completed the plan. If so, we're done.
Sean Callananc78d6482010-07-26 22:14:36 +0000559 if (exe_ctx.thread->IsThreadPlanDone (call_plan_sp.get()))
Chris Lattner24943d22010-06-08 16:52:24 +0000560 {
561 return_value = eExecutionCompleted;
562 break;
563 }
Sean Callanan841026f2010-07-23 00:16:21 +0000564
Chris Lattner24943d22010-06-08 16:52:24 +0000565 call_plan_ptr->SetStopOthers (false);
Sean Callananc78d6482010-07-26 22:14:36 +0000566 exe_ctx.process->Resume();
Chris Lattner24943d22010-06-08 16:52:24 +0000567 continue;
568 }
569 else
570 return eExecutionInterrupted;
571 }
572 }
573 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
574 continue;
Sean Callanan841026f2010-07-23 00:16:21 +0000575
Sean Callananc78d6482010-07-26 22:14:36 +0000576 if (exe_ctx.thread->IsThreadPlanDone (call_plan_sp.get()))
Chris Lattner24943d22010-06-08 16:52:24 +0000577 {
578 return_value = eExecutionCompleted;
579 break;
580 }
Sean Callananc78d6482010-07-26 22:14:36 +0000581 else if (exe_ctx.thread->WasThreadPlanDiscarded (call_plan_sp.get()))
Chris Lattner24943d22010-06-08 16:52:24 +0000582 {
583 return_value = eExecutionDiscarded;
584 break;
585 }
586 else
587 {
Sean Callanan841026f2010-07-23 00:16:21 +0000588 if (log)
589 {
590 StreamString s;
591 event_sp->Dump (&s);
592 StreamString ts;
593
594 const char *event_explanation;
595
596 do
597 {
598 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
599
600 if (!event_data)
601 {
602 event_explanation = "<no event data>";
603 break;
604 }
605
606 Process *process = event_data->GetProcessSP().get();
607
608 if (!process)
609 {
610 event_explanation = "<no process>";
611 break;
612 }
613
614 ThreadList &thread_list = process->GetThreadList();
615
616 uint32_t num_threads = thread_list.GetSize();
617 uint32_t thread_index;
618
619 ts.Printf("<%u threads> ", num_threads);
620
621 for (thread_index = 0;
622 thread_index < num_threads;
623 ++thread_index)
624 {
625 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
626
627 if (!thread)
628 {
629 ts.Printf("<?> ");
630 continue;
631 }
632
Sean Callanan841026f2010-07-23 00:16:21 +0000633 ts.Printf("<");
634 RegisterContext *register_context = thread->GetRegisterContext();
635
636 if (register_context)
637 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
638 else
639 ts.Printf("[ip unknown] ");
640
Greg Clayton643ee732010-08-04 01:40:35 +0000641 StopInfo *stop_info = thread->GetStopInfo();
642 if (stop_info)
643 {
644 const char *stop_desc = stop_info->GetDescription();
645 if (stop_desc)
646 ts.PutCString (stop_desc);
647 }
Sean Callanan841026f2010-07-23 00:16:21 +0000648 ts.Printf(">");
649 }
650
651 event_explanation = ts.GetData();
652 } while (0);
653
654 log->Printf("Execution interrupted: %s %s", s.GetData(), event_explanation);
655 }
656
Chris Lattner24943d22010-06-08 16:52:24 +0000657 return_value = eExecutionInterrupted;
658 break;
659 }
Chris Lattner24943d22010-06-08 16:52:24 +0000660 }
Sean Callanan841026f2010-07-23 00:16:21 +0000661
Sean Callananc78d6482010-07-26 22:14:36 +0000662 // Thread we ran the function in may have gone away because we ran the target
663 // Check that it's still there.
664 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByID(tid, true).get();
665 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
666
Sean Callanan841026f2010-07-23 00:16:21 +0000667 return return_value;
668}
Chris Lattner24943d22010-06-08 16:52:24 +0000669
Sean Callanan841026f2010-07-23 00:16:21 +0000670ClangFunction::ExecutionResults
671ClangFunction::ExecuteFunction(
Sean Callananc78d6482010-07-26 22:14:36 +0000672 ExecutionContext &exe_ctx,
Sean Callanan841026f2010-07-23 00:16:21 +0000673 lldb::addr_t *args_addr_ptr,
674 Stream &errors,
675 bool stop_others,
676 uint32_t single_thread_timeout_usec,
677 bool try_all_threads,
678 Value &results)
679{
680 using namespace clang;
681 ExecutionResults return_value = eExecutionSetupError;
682
683 lldb::addr_t args_addr;
684
685 if (args_addr_ptr != NULL)
686 args_addr = *args_addr_ptr;
687 else
688 args_addr = LLDB_INVALID_ADDRESS;
689
690 if (CompileFunction(errors) != 0)
691 return eExecutionSetupError;
692
693 if (args_addr == LLDB_INVALID_ADDRESS)
694 {
Sean Callananc78d6482010-07-26 22:14:36 +0000695 if (!InsertFunction(exe_ctx, args_addr, errors))
Sean Callanan841026f2010-07-23 00:16:21 +0000696 return eExecutionSetupError;
697 }
698
Sean Callananc78d6482010-07-26 22:14:36 +0000699 return_value = ClangFunction::ExecuteFunction(exe_ctx, m_wrapper_function_addr, args_addr, stop_others, try_all_threads, single_thread_timeout_usec, errors);
Sean Callanan841026f2010-07-23 00:16:21 +0000700
701 if (args_addr_ptr != NULL)
702 *args_addr_ptr = args_addr;
703
Chris Lattner24943d22010-06-08 16:52:24 +0000704 if (return_value != eExecutionCompleted)
705 return return_value;
706
Sean Callananc78d6482010-07-26 22:14:36 +0000707 FetchFunctionResults(exe_ctx, args_addr, results);
Chris Lattner24943d22010-06-08 16:52:24 +0000708
709 if (args_addr_ptr == NULL)
Sean Callananc78d6482010-07-26 22:14:36 +0000710 DeallocateFunctionResults(exe_ctx, args_addr);
Chris Lattner24943d22010-06-08 16:52:24 +0000711
712 return eExecutionCompleted;
713}
714
715ClangFunction::ExecutionResults
Sean Callananc78d6482010-07-26 22:14:36 +0000716ClangFunction::ExecuteFunctionWithABI(ExecutionContext &exe_ctx, Stream &errors, Value &results)
Chris Lattner24943d22010-06-08 16:52:24 +0000717{
718 // FIXME: Use the errors Stream for better error reporting.
719 using namespace clang;
720 ExecutionResults return_value = eExecutionSetupError;
721
Sean Callananc78d6482010-07-26 22:14:36 +0000722 Process *process = exe_ctx.process;
Chris Lattner24943d22010-06-08 16:52:24 +0000723
724 if (process == NULL)
725 {
726 errors.Printf("Can't call a function without a process.");
727 return return_value;
728 }
729
730 //unsigned int num_args = m_arg_values.GetSize();
731 //unsigned int arg_index;
732
733 //for (arg_index = 0; arg_index < num_args; ++arg_index)
Sean Callananc78d6482010-07-26 22:14:36 +0000734 // m_arg_values.GetValueAtIndex(arg_index)->ResolveValue(&exe_ctx, GetASTContext());
Chris Lattner24943d22010-06-08 16:52:24 +0000735
Sean Callananc78d6482010-07-26 22:14:36 +0000736 ThreadPlan *call_plan = exe_ctx.thread->QueueThreadPlanForCallFunction (false,
Chris Lattner24943d22010-06-08 16:52:24 +0000737 m_function_addr,
738 m_arg_values,
739 true);
740 if (call_plan == NULL)
741 return return_value;
742
743 call_plan->SetPrivate(true);
744
745 // We need to call the function synchronously, so spin waiting for it to return.
746 // If we get interrupted while executing, we're going to lose our context, and
747 // won't be able to gather the result at this point.
748
749 process->Resume ();
750
751 while (1)
752 {
753 lldb::EventSP event_sp;
754
755 // Now wait for the process to stop again:
756 // FIXME: Probably want a time out.
757 lldb::StateType stop_state = process->WaitForStateChangedEvents (NULL, event_sp);
758 if (stop_state == lldb::eStateRunning || stop_state == lldb::eStateStepping)
759 continue;
760
Sean Callananc78d6482010-07-26 22:14:36 +0000761 if (exe_ctx.thread->IsThreadPlanDone (call_plan))
Chris Lattner24943d22010-06-08 16:52:24 +0000762 {
763 return_value = eExecutionCompleted;
764 break;
765 }
Sean Callananc78d6482010-07-26 22:14:36 +0000766 else if (exe_ctx.thread->WasThreadPlanDiscarded (call_plan))
Chris Lattner24943d22010-06-08 16:52:24 +0000767 {
768 return_value = eExecutionDiscarded;
769 break;
770 }
771 else
772 {
773 return_value = eExecutionInterrupted;
774 break;
775 }
776
777 }
778
779 return eExecutionCompleted;
780}