1 //===-- FunctionCaller.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 15 // Project includes 16 #include "lldb/Core/DataExtractor.h" 17 #include "lldb/Core/Log.h" 18 #include "lldb/Core/Module.h" 19 #include "lldb/Core/State.h" 20 #include "lldb/Core/ValueObject.h" 21 #include "lldb/Core/ValueObjectList.h" 22 #include "lldb/Expression/FunctionCaller.h" 23 #include "lldb/Expression/IRExecutionUnit.h" 24 #include "lldb/Interpreter/CommandReturnObject.h" 25 #include "lldb/Symbol/Function.h" 26 #include "lldb/Symbol/Type.h" 27 #include "lldb/Target/ExecutionContext.h" 28 #include "lldb/Target/Process.h" 29 #include "lldb/Target/RegisterContext.h" 30 #include "lldb/Target/Target.h" 31 #include "lldb/Target/Thread.h" 32 #include "lldb/Target/ThreadPlan.h" 33 #include "lldb/Target/ThreadPlanCallFunction.h" 34 35 using namespace lldb_private; 36 37 //---------------------------------------------------------------------- 38 // FunctionCaller constructor 39 //---------------------------------------------------------------------- 40 FunctionCaller::FunctionCaller 41 ( 42 ExecutionContextScope &exe_scope, 43 const CompilerType &return_type, 44 const Address& functionAddress, 45 const ValueList &arg_value_list, 46 const char *name 47 ) : 48 Expression (exe_scope), 49 m_execution_unit_sp(), 50 m_parser(), 51 m_jit_module_wp(), 52 m_name (name ? name : "<unknown>"), 53 m_function_ptr (NULL), 54 m_function_addr (functionAddress), 55 m_function_return_type(return_type), 56 m_wrapper_function_name ("__lldb_caller_function"), 57 m_wrapper_struct_name ("__lldb_caller_struct"), 58 m_wrapper_args_addrs (), 59 m_arg_values (arg_value_list), 60 m_compiled (false), 61 m_JITted (false) 62 { 63 m_jit_process_wp = lldb::ProcessWP(exe_scope.CalculateProcess()); 64 // Can't make a FunctionCaller without a process. 65 assert (m_jit_process_wp.lock()); 66 } 67 68 //---------------------------------------------------------------------- 69 // Destructor 70 //---------------------------------------------------------------------- 71 FunctionCaller::~FunctionCaller() 72 { 73 lldb::ProcessSP process_sp (m_jit_process_wp.lock()); 74 if (process_sp) 75 { 76 lldb::ModuleSP jit_module_sp (m_jit_module_wp.lock()); 77 if (jit_module_sp) 78 process_sp->GetTarget().GetImages().Remove(jit_module_sp); 79 } 80 } 81 82 bool 83 FunctionCaller::WriteFunctionWrapper (ExecutionContext &exe_ctx, Stream &errors) 84 { 85 Process *process = exe_ctx.GetProcessPtr(); 86 87 if (!process) 88 return false; 89 90 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock()); 91 92 if (process != jit_process_sp.get()) 93 return false; 94 95 if (!m_compiled) 96 return false; 97 98 if (m_JITted) 99 return true; 100 101 bool can_interpret = false; // should stay that way 102 103 Error jit_error (m_parser->PrepareForExecution (m_jit_start_addr, 104 m_jit_end_addr, 105 m_execution_unit_sp, 106 exe_ctx, 107 can_interpret, 108 eExecutionPolicyAlways)); 109 110 if (!jit_error.Success()) 111 return false; 112 113 if (m_parser->GetGenerateDebugInfo()) 114 { 115 lldb::ModuleSP jit_module_sp ( m_execution_unit_sp->GetJITModule()); 116 117 if (jit_module_sp) 118 { 119 ConstString const_func_name(FunctionName()); 120 FileSpec jit_file; 121 jit_file.GetFilename() = const_func_name; 122 jit_module_sp->SetFileSpecAndObjectName (jit_file, ConstString()); 123 m_jit_module_wp = jit_module_sp; 124 process->GetTarget().GetImages().Append(jit_module_sp); 125 } 126 } 127 if (process && m_jit_start_addr) 128 m_jit_process_wp = process->shared_from_this(); 129 130 m_JITted = true; 131 132 return true; 133 } 134 135 bool 136 FunctionCaller::WriteFunctionArguments (ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, Stream &errors) 137 { 138 return WriteFunctionArguments(exe_ctx, args_addr_ref, m_arg_values, errors); 139 } 140 141 // FIXME: Assure that the ValueList we were passed in is consistent with the one that defined this function. 142 143 bool 144 FunctionCaller::WriteFunctionArguments (ExecutionContext &exe_ctx, 145 lldb::addr_t &args_addr_ref, 146 ValueList &arg_values, 147 Stream &errors) 148 { 149 // All the information to reconstruct the struct is provided by the 150 // StructExtractor. 151 if (!m_struct_valid) 152 { 153 errors.Printf("Argument information was not correctly parsed, so the function cannot be called."); 154 return false; 155 } 156 157 Error error; 158 lldb::ExpressionResults return_value = lldb::eExpressionSetupError; 159 160 Process *process = exe_ctx.GetProcessPtr(); 161 162 if (process == NULL) 163 return return_value; 164 165 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock()); 166 167 if (process != jit_process_sp.get()) 168 return false; 169 170 if (args_addr_ref == LLDB_INVALID_ADDRESS) 171 { 172 args_addr_ref = process->AllocateMemory(m_struct_size, lldb::ePermissionsReadable|lldb::ePermissionsWritable, error); 173 if (args_addr_ref == LLDB_INVALID_ADDRESS) 174 return false; 175 m_wrapper_args_addrs.push_back (args_addr_ref); 176 } 177 else 178 { 179 // Make sure this is an address that we've already handed out. 180 if (find (m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr_ref) == m_wrapper_args_addrs.end()) 181 { 182 return false; 183 } 184 } 185 186 // TODO: verify fun_addr needs to be a callable address 187 Scalar fun_addr (m_function_addr.GetCallableLoadAddress(exe_ctx.GetTargetPtr())); 188 uint64_t first_offset = m_member_offsets[0]; 189 process->WriteScalarToMemory(args_addr_ref + first_offset, fun_addr, process->GetAddressByteSize(), error); 190 191 // FIXME: We will need to extend this for Variadic functions. 192 193 Error value_error; 194 195 size_t num_args = arg_values.GetSize(); 196 if (num_args != m_arg_values.GetSize()) 197 { 198 errors.Printf ("Wrong number of arguments - was: %" PRIu64 " should be: %" PRIu64 "", (uint64_t)num_args, (uint64_t)m_arg_values.GetSize()); 199 return false; 200 } 201 202 for (size_t i = 0; i < num_args; i++) 203 { 204 // FIXME: We should sanity check sizes. 205 206 uint64_t offset = m_member_offsets[i+1]; // Clang sizes are in bytes. 207 Value *arg_value = arg_values.GetValueAtIndex(i); 208 209 // FIXME: For now just do scalars: 210 211 // Special case: if it's a pointer, don't do anything (the ABI supports passing cstrings) 212 213 if (arg_value->GetValueType() == Value::eValueTypeHostAddress && 214 arg_value->GetContextType() == Value::eContextTypeInvalid && 215 arg_value->GetCompilerType().IsPointerType()) 216 continue; 217 218 const Scalar &arg_scalar = arg_value->ResolveValue(&exe_ctx); 219 220 if (!process->WriteScalarToMemory(args_addr_ref + offset, arg_scalar, arg_scalar.GetByteSize(), error)) 221 return false; 222 } 223 224 return true; 225 } 226 227 bool 228 FunctionCaller::InsertFunction (ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, Stream &errors) 229 { 230 if (CompileFunction(errors) != 0) 231 return false; 232 if (!WriteFunctionWrapper(exe_ctx, errors)) 233 return false; 234 if (!WriteFunctionArguments(exe_ctx, args_addr_ref, errors)) 235 return false; 236 237 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 238 if (log) 239 log->Printf ("Call Address: 0x%" PRIx64 " Struct Address: 0x%" PRIx64 ".\n", m_jit_start_addr, args_addr_ref); 240 241 return true; 242 } 243 244 lldb::ThreadPlanSP 245 FunctionCaller::GetThreadPlanToCallFunction (ExecutionContext &exe_ctx, 246 lldb::addr_t args_addr, 247 const EvaluateExpressionOptions &options, 248 Stream &errors) 249 { 250 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP)); 251 252 if (log) 253 log->Printf("-- [FunctionCaller::GetThreadPlanToCallFunction] Creating thread plan to call function \"%s\" --", m_name.c_str()); 254 255 // FIXME: Use the errors Stream for better error reporting. 256 Thread *thread = exe_ctx.GetThreadPtr(); 257 if (thread == NULL) 258 { 259 errors.Printf("Can't call a function without a valid thread."); 260 return NULL; 261 } 262 263 // Okay, now run the function: 264 265 Address wrapper_address (m_jit_start_addr); 266 267 lldb::addr_t args = { args_addr }; 268 269 lldb::ThreadPlanSP new_plan_sp (new ThreadPlanCallFunction (*thread, 270 wrapper_address, 271 CompilerType(), 272 args, 273 options)); 274 new_plan_sp->SetIsMasterPlan(true); 275 new_plan_sp->SetOkayToDiscard (false); 276 return new_plan_sp; 277 } 278 279 bool 280 FunctionCaller::FetchFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr, Value &ret_value) 281 { 282 // Read the return value - it is the last field in the struct: 283 // FIXME: How does clang tell us there's no return value? We need to handle that case. 284 // FIXME: Create our ThreadPlanCallFunction with the return CompilerType, and then use GetReturnValueObject 285 // to fetch the value. That way we can fetch any values we need. 286 287 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP)); 288 289 if (log) 290 log->Printf("-- [FunctionCaller::FetchFunctionResults] Fetching function results for \"%s\"--", m_name.c_str()); 291 292 Process *process = exe_ctx.GetProcessPtr(); 293 294 if (process == NULL) 295 return false; 296 297 lldb::ProcessSP jit_process_sp(m_jit_process_wp.lock()); 298 299 if (process != jit_process_sp.get()) 300 return false; 301 302 Error error; 303 ret_value.GetScalar() = process->ReadUnsignedIntegerFromMemory (args_addr + m_return_offset, m_return_size, 0, error); 304 305 if (error.Fail()) 306 return false; 307 308 ret_value.SetCompilerType(m_function_return_type); 309 ret_value.SetValueType(Value::eValueTypeScalar); 310 return true; 311 } 312 313 void 314 FunctionCaller::DeallocateFunctionResults (ExecutionContext &exe_ctx, lldb::addr_t args_addr) 315 { 316 std::list<lldb::addr_t>::iterator pos; 317 pos = std::find(m_wrapper_args_addrs.begin(), m_wrapper_args_addrs.end(), args_addr); 318 if (pos != m_wrapper_args_addrs.end()) 319 m_wrapper_args_addrs.erase(pos); 320 321 exe_ctx.GetProcessRef().DeallocateMemory(args_addr); 322 } 323 324 lldb::ExpressionResults 325 FunctionCaller::ExecuteFunction( 326 ExecutionContext &exe_ctx, 327 lldb::addr_t *args_addr_ptr, 328 const EvaluateExpressionOptions &options, 329 Stream &errors, 330 Value &results) 331 { 332 lldb::ExpressionResults return_value = lldb::eExpressionSetupError; 333 334 // FunctionCaller::ExecuteFunction execution is always just to get the result. Do make sure we ignore 335 // breakpoints, unwind on error, and don't try to debug it. 336 EvaluateExpressionOptions real_options = options; 337 real_options.SetDebug(false); 338 real_options.SetUnwindOnError(true); 339 real_options.SetIgnoreBreakpoints(true); 340 341 lldb::addr_t args_addr; 342 343 if (args_addr_ptr != NULL) 344 args_addr = *args_addr_ptr; 345 else 346 args_addr = LLDB_INVALID_ADDRESS; 347 348 if (CompileFunction(errors) != 0) 349 return lldb::eExpressionSetupError; 350 351 if (args_addr == LLDB_INVALID_ADDRESS) 352 { 353 if (!InsertFunction(exe_ctx, args_addr, errors)) 354 return lldb::eExpressionSetupError; 355 } 356 357 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_EXPRESSIONS | LIBLLDB_LOG_STEP)); 358 359 if (log) 360 log->Printf("== [FunctionCaller::ExecuteFunction] Executing function \"%s\" ==", m_name.c_str()); 361 362 lldb::ThreadPlanSP call_plan_sp = GetThreadPlanToCallFunction (exe_ctx, 363 args_addr, 364 real_options, 365 errors); 366 if (!call_plan_sp) 367 return lldb::eExpressionSetupError; 368 369 // We need to make sure we record the fact that we are running an expression here 370 // otherwise this fact will fail to be recorded when fetching an Objective-C object description 371 if (exe_ctx.GetProcessPtr()) 372 exe_ctx.GetProcessPtr()->SetRunningUserExpression(true); 373 374 return_value = exe_ctx.GetProcessRef().RunThreadPlan (exe_ctx, 375 call_plan_sp, 376 real_options, 377 errors); 378 379 if (log) 380 { 381 if (return_value != lldb::eExpressionCompleted) 382 { 383 log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" completed abnormally ==", m_name.c_str()); 384 } 385 else 386 { 387 log->Printf("== [FunctionCaller::ExecuteFunction] Execution of \"%s\" completed normally ==", m_name.c_str()); 388 } 389 } 390 391 if (exe_ctx.GetProcessPtr()) 392 exe_ctx.GetProcessPtr()->SetRunningUserExpression(false); 393 394 if (args_addr_ptr != NULL) 395 *args_addr_ptr = args_addr; 396 397 if (return_value != lldb::eExpressionCompleted) 398 return return_value; 399 400 FetchFunctionResults(exe_ctx, args_addr, results); 401 402 if (args_addr_ptr == NULL) 403 DeallocateFunctionResults(exe_ctx, args_addr); 404 405 return lldb::eExpressionCompleted; 406 } 407