AppleObjCTrampolineHandler.cpp revision 321369
1//===-- AppleObjCTrampolineHandler.cpp ----------------------------*- C++ 2//-*-===// 3// 4// The LLVM Compiler Infrastructure 5// 6// This file is distributed under the University of Illinois Open Source 7// License. See LICENSE.TXT for details. 8// 9//===----------------------------------------------------------------------===// 10 11#include "AppleObjCTrampolineHandler.h" 12 13// C Includes 14// C++ Includes 15// Other libraries and framework includes 16// Project includes 17#include "AppleThreadPlanStepThroughObjCTrampoline.h" 18 19#include "lldb/Breakpoint/StoppointCallbackContext.h" 20#include "lldb/Core/Debugger.h" 21#include "lldb/Core/Module.h" 22#include "lldb/Core/StreamFile.h" 23#include "lldb/Core/Value.h" 24#include "lldb/Expression/DiagnosticManager.h" 25#include "lldb/Expression/FunctionCaller.h" 26#include "lldb/Expression/UserExpression.h" 27#include "lldb/Expression/UtilityFunction.h" 28#include "lldb/Symbol/ClangASTContext.h" 29#include "lldb/Symbol/Symbol.h" 30#include "lldb/Target/ABI.h" 31#include "lldb/Target/ExecutionContext.h" 32#include "lldb/Target/ObjCLanguageRuntime.h" 33#include "lldb/Target/Process.h" 34#include "lldb/Target/RegisterContext.h" 35#include "lldb/Target/Target.h" 36#include "lldb/Target/Thread.h" 37#include "lldb/Target/ThreadPlanRunToAddress.h" 38#include "lldb/Utility/ConstString.h" 39#include "lldb/Utility/FileSpec.h" 40#include "lldb/Utility/Log.h" 41 42#include "llvm/ADT/STLExtras.h" 43 44using namespace lldb; 45using namespace lldb_private; 46 47const char *AppleObjCTrampolineHandler::g_lookup_implementation_function_name = 48 "__lldb_objc_find_implementation_for_selector"; 49const char *AppleObjCTrampolineHandler:: 50 g_lookup_implementation_with_stret_function_code = 51 " \n\ 52extern \"C\" \n\ 53{ \n\ 54 extern void *class_getMethodImplementation(void *objc_class, void *sel); \n\ 55 extern void *class_getMethodImplementation_stret(void *objc_class, void *sel); \n\ 56 extern void * object_getClass (id object); \n\ 57 extern void * sel_getUid(char *name); \n\ 58 extern int printf(const char *format, ...); \n\ 59} \n\ 60extern \"C\" void * __lldb_objc_find_implementation_for_selector (void *object, \n\ 61 void *sel, \n\ 62 int is_stret, \n\ 63 int is_super, \n\ 64 int is_super2, \n\ 65 int is_fixup, \n\ 66 int is_fixed, \n\ 67 int debug) \n\ 68{ \n\ 69 struct __lldb_imp_return_struct \n\ 70 { \n\ 71 void *class_addr; \n\ 72 void *sel_addr; \n\ 73 void *impl_addr; \n\ 74 }; \n\ 75 \n\ 76 struct __lldb_objc_class { \n\ 77 void *isa; \n\ 78 void *super_ptr; \n\ 79 }; \n\ 80 struct __lldb_objc_super { \n\ 81 void *reciever; \n\ 82 struct __lldb_objc_class *class_ptr; \n\ 83 }; \n\ 84 struct __lldb_msg_ref { \n\ 85 void *dont_know; \n\ 86 void *sel; \n\ 87 }; \n\ 88 \n\ 89 struct __lldb_imp_return_struct return_struct; \n\ 90 \n\ 91 if (debug) \n\ 92 printf (\"\\n*** Called with obj: 0x%p sel: 0x%p is_stret: %d is_super: %d, \" \n\ 93 \"is_super2: %d, is_fixup: %d, is_fixed: %d\\n\", \n\ 94 object, sel, is_stret, is_super, is_super2, is_fixup, is_fixed); \n\ 95 if (is_super) \n\ 96 { \n\ 97 if (is_super2) \n\ 98 { \n\ 99 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr; \n\ 100 } \n\ 101 else \n\ 102 { \n\ 103 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr; \n\ 104 } \n\ 105 } \n\ 106 else \n\ 107 { \n\ 108 // This code seems a little funny, but has its reasons... \n\ 109 // The call to [object class] is here because if this is a class, and has not been called into \n\ 110 // yet, we need to do something to force the class to initialize itself. \n\ 111 // Then the call to object_getClass will actually return the correct class, either the class \n\ 112 // if object is a class instance, or the meta-class if it is a class pointer. \n\ 113 void *class_ptr = (void *) [(id) object class]; \n\ 114 return_struct.class_addr = (id) object_getClass((id) object); \n\ 115 if (debug) \n\ 116 { \n\ 117 if (class_ptr == object) \n\ 118 { \n\ 119 printf (\"Found a class object, need to use the meta class %p -> %p\\n\", \n\ 120 class_ptr, return_struct.class_addr); \n\ 121 } \n\ 122 else \n\ 123 { \n\ 124 printf (\"[object class] returned: %p object_getClass: %p.\\n\", \n\ 125 class_ptr, return_struct.class_addr); \n\ 126 } \n\ 127 } \n\ 128 } \n\ 129 \n\ 130 if (is_fixup) \n\ 131 { \n\ 132 if (is_fixed) \n\ 133 { \n\ 134 return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel; \n\ 135 } \n\ 136 else \n\ 137 { \n\ 138 char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel; \n\ 139 return_struct.sel_addr = sel_getUid (sel_name); \n\ 140 if (debug) \n\ 141 printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\", \n\ 142 return_struct.sel_addr, sel_name); \n\ 143 } \n\ 144 } \n\ 145 else \n\ 146 { \n\ 147 return_struct.sel_addr = sel; \n\ 148 } \n\ 149 \n\ 150 if (is_stret) \n\ 151 { \n\ 152 return_struct.impl_addr = class_getMethodImplementation_stret (return_struct.class_addr, \n\ 153 return_struct.sel_addr); \n\ 154 } \n\ 155 else \n\ 156 { \n\ 157 return_struct.impl_addr = class_getMethodImplementation (return_struct.class_addr, \n\ 158 return_struct.sel_addr); \n\ 159 } \n\ 160 if (debug) \n\ 161 printf (\"\\n*** Returning implementation: %p.\\n\", return_struct.impl_addr); \n\ 162 \n\ 163 return return_struct.impl_addr; \n\ 164} \n\ 165"; 166const char * 167 AppleObjCTrampolineHandler::g_lookup_implementation_no_stret_function_code = 168 " \n\ 169extern \"C\" \n\ 170{ \n\ 171 extern void *class_getMethodImplementation(void *objc_class, void *sel); \n\ 172 extern void * object_getClass (id object); \n\ 173 extern void * sel_getUid(char *name); \n\ 174 extern int printf(const char *format, ...); \n\ 175} \n\ 176extern \"C\" void * __lldb_objc_find_implementation_for_selector (void *object, \n\ 177 void *sel, \n\ 178 int is_stret, \n\ 179 int is_super, \n\ 180 int is_super2, \n\ 181 int is_fixup, \n\ 182 int is_fixed, \n\ 183 int debug) \n\ 184{ \n\ 185 struct __lldb_imp_return_struct \n\ 186 { \n\ 187 void *class_addr; \n\ 188 void *sel_addr; \n\ 189 void *impl_addr; \n\ 190 }; \n\ 191 \n\ 192 struct __lldb_objc_class { \n\ 193 void *isa; \n\ 194 void *super_ptr; \n\ 195 }; \n\ 196 struct __lldb_objc_super { \n\ 197 void *reciever; \n\ 198 struct __lldb_objc_class *class_ptr; \n\ 199 }; \n\ 200 struct __lldb_msg_ref { \n\ 201 void *dont_know; \n\ 202 void *sel; \n\ 203 }; \n\ 204 \n\ 205 struct __lldb_imp_return_struct return_struct; \n\ 206 \n\ 207 if (debug) \n\ 208 printf (\"\\n*** Called with obj: 0x%p sel: 0x%p is_stret: %d is_super: %d, \" \n\ 209 \"is_super2: %d, is_fixup: %d, is_fixed: %d\\n\", \n\ 210 object, sel, is_stret, is_super, is_super2, is_fixup, is_fixed); \n\ 211 if (is_super) \n\ 212 { \n\ 213 if (is_super2) \n\ 214 { \n\ 215 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr->super_ptr; \n\ 216 } \n\ 217 else \n\ 218 { \n\ 219 return_struct.class_addr = ((__lldb_objc_super *) object)->class_ptr; \n\ 220 } \n\ 221 } \n\ 222 else \n\ 223 { \n\ 224 // This code seems a little funny, but has its reasons... \n\ 225 // The call to [object class] is here because if this is a class, and has not been called into \n\ 226 // yet, we need to do something to force the class to initialize itself. \n\ 227 // Then the call to object_getClass will actually return the correct class, either the class \n\ 228 // if object is a class instance, or the meta-class if it is a class pointer. \n\ 229 void *class_ptr = (void *) [(id) object class]; \n\ 230 return_struct.class_addr = (id) object_getClass((id) object); \n\ 231 if (debug) \n\ 232 { \n\ 233 if (class_ptr == object) \n\ 234 { \n\ 235 printf (\"Found a class object, need to return the meta class %p -> %p\\n\", \n\ 236 class_ptr, return_struct.class_addr); \n\ 237 } \n\ 238 else \n\ 239 { \n\ 240 printf (\"[object class] returned: %p object_getClass: %p.\\n\", \n\ 241 class_ptr, return_struct.class_addr); \n\ 242 } \n\ 243 } \n\ 244 } \n\ 245 \n\ 246 if (is_fixup) \n\ 247 { \n\ 248 if (is_fixed) \n\ 249 { \n\ 250 return_struct.sel_addr = ((__lldb_msg_ref *) sel)->sel; \n\ 251 } \n\ 252 else \n\ 253 { \n\ 254 char *sel_name = (char *) ((__lldb_msg_ref *) sel)->sel; \n\ 255 return_struct.sel_addr = sel_getUid (sel_name); \n\ 256 if (debug) \n\ 257 printf (\"\\n*** Got fixed up selector: %p for name %s.\\n\", \n\ 258 return_struct.sel_addr, sel_name); \n\ 259 } \n\ 260 } \n\ 261 else \n\ 262 { \n\ 263 return_struct.sel_addr = sel; \n\ 264 } \n\ 265 \n\ 266 return_struct.impl_addr = class_getMethodImplementation (return_struct.class_addr, \n\ 267 return_struct.sel_addr); \n\ 268 if (debug) \n\ 269 printf (\"\\n*** Returning implementation: 0x%p.\\n\", return_struct.impl_addr); \n\ 270 \n\ 271 return return_struct.impl_addr; \n\ 272} \n\ 273"; 274 275AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::VTableRegion( 276 AppleObjCVTables *owner, lldb::addr_t header_addr) 277 : m_valid(true), m_owner(owner), m_header_addr(header_addr), 278 m_code_start_addr(0), m_code_end_addr(0), m_next_region(0) { 279 SetUpRegion(); 280} 281 282AppleObjCTrampolineHandler::~AppleObjCTrampolineHandler() {} 283 284void AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::SetUpRegion() { 285 // The header looks like: 286 // 287 // uint16_t headerSize 288 // uint16_t descSize 289 // uint32_t descCount 290 // void * next 291 // 292 // First read in the header: 293 294 char memory_buffer[16]; 295 ProcessSP process_sp = m_owner->GetProcessSP(); 296 if (!process_sp) 297 return; 298 DataExtractor data(memory_buffer, sizeof(memory_buffer), 299 process_sp->GetByteOrder(), 300 process_sp->GetAddressByteSize()); 301 size_t actual_size = 8 + process_sp->GetAddressByteSize(); 302 Status error; 303 size_t bytes_read = 304 process_sp->ReadMemory(m_header_addr, memory_buffer, actual_size, error); 305 if (bytes_read != actual_size) { 306 m_valid = false; 307 return; 308 } 309 310 lldb::offset_t offset = 0; 311 const uint16_t header_size = data.GetU16(&offset); 312 const uint16_t descriptor_size = data.GetU16(&offset); 313 const size_t num_descriptors = data.GetU32(&offset); 314 315 m_next_region = data.GetPointer(&offset); 316 317 // If the header size is 0, that means we've come in too early before this 318 // data is set up. 319 // Set ourselves as not valid, and continue. 320 if (header_size == 0 || num_descriptors == 0) { 321 m_valid = false; 322 return; 323 } 324 325 // Now read in all the descriptors: 326 // The descriptor looks like: 327 // 328 // uint32_t offset 329 // uint32_t flags 330 // 331 // Where offset is either 0 - in which case it is unused, or 332 // it is the offset of the vtable code from the beginning of the descriptor 333 // record. 334 // Below, we'll convert that into an absolute code address, since I don't want 335 // to have 336 // to compute it over and over. 337 338 // Ingest the whole descriptor array: 339 const lldb::addr_t desc_ptr = m_header_addr + header_size; 340 const size_t desc_array_size = num_descriptors * descriptor_size; 341 DataBufferSP data_sp(new DataBufferHeap(desc_array_size, '\0')); 342 uint8_t *dst = (uint8_t *)data_sp->GetBytes(); 343 344 DataExtractor desc_extractor(dst, desc_array_size, process_sp->GetByteOrder(), 345 process_sp->GetAddressByteSize()); 346 bytes_read = process_sp->ReadMemory(desc_ptr, dst, desc_array_size, error); 347 if (bytes_read != desc_array_size) { 348 m_valid = false; 349 return; 350 } 351 352 // The actual code for the vtables will be laid out consecutively, so I also 353 // compute the start and end of the whole code block. 354 355 offset = 0; 356 m_code_start_addr = 0; 357 m_code_end_addr = 0; 358 359 for (size_t i = 0; i < num_descriptors; i++) { 360 lldb::addr_t start_offset = offset; 361 uint32_t voffset = desc_extractor.GetU32(&offset); 362 uint32_t flags = desc_extractor.GetU32(&offset); 363 lldb::addr_t code_addr = desc_ptr + start_offset + voffset; 364 m_descriptors.push_back(VTableDescriptor(flags, code_addr)); 365 366 if (m_code_start_addr == 0 || code_addr < m_code_start_addr) 367 m_code_start_addr = code_addr; 368 if (code_addr > m_code_end_addr) 369 m_code_end_addr = code_addr; 370 371 offset = start_offset + descriptor_size; 372 } 373 // Finally, a little bird told me that all the vtable code blocks are the same 374 // size. 375 // Let's compute the blocks and if they are all the same add the size to the 376 // code end address: 377 lldb::addr_t code_size = 0; 378 bool all_the_same = true; 379 for (size_t i = 0; i < num_descriptors - 1; i++) { 380 lldb::addr_t this_size = 381 m_descriptors[i + 1].code_start - m_descriptors[i].code_start; 382 if (code_size == 0) 383 code_size = this_size; 384 else { 385 if (this_size != code_size) 386 all_the_same = false; 387 if (this_size > code_size) 388 code_size = this_size; 389 } 390 } 391 if (all_the_same) 392 m_code_end_addr += code_size; 393} 394 395bool AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion:: 396 AddressInRegion(lldb::addr_t addr, uint32_t &flags) { 397 if (!IsValid()) 398 return false; 399 400 if (addr < m_code_start_addr || addr > m_code_end_addr) 401 return false; 402 403 std::vector<VTableDescriptor>::iterator pos, end = m_descriptors.end(); 404 for (pos = m_descriptors.begin(); pos != end; pos++) { 405 if (addr <= (*pos).code_start) { 406 flags = (*pos).flags; 407 return true; 408 } 409 } 410 return false; 411} 412 413void AppleObjCTrampolineHandler::AppleObjCVTables::VTableRegion::Dump( 414 Stream &s) { 415 s.Printf("Header addr: 0x%" PRIx64 " Code start: 0x%" PRIx64 416 " Code End: 0x%" PRIx64 " Next: 0x%" PRIx64 "\n", 417 m_header_addr, m_code_start_addr, m_code_end_addr, m_next_region); 418 size_t num_elements = m_descriptors.size(); 419 for (size_t i = 0; i < num_elements; i++) { 420 s.Indent(); 421 s.Printf("Code start: 0x%" PRIx64 " Flags: %d\n", 422 m_descriptors[i].code_start, m_descriptors[i].flags); 423 } 424} 425 426AppleObjCTrampolineHandler::AppleObjCVTables::AppleObjCVTables( 427 const ProcessSP &process_sp, const ModuleSP &objc_module_sp) 428 : m_process_wp(), m_trampoline_header(LLDB_INVALID_ADDRESS), 429 m_trampolines_changed_bp_id(LLDB_INVALID_BREAK_ID), 430 m_objc_module_sp(objc_module_sp) { 431 if (process_sp) 432 m_process_wp = process_sp; 433} 434 435AppleObjCTrampolineHandler::AppleObjCVTables::~AppleObjCVTables() { 436 ProcessSP process_sp = GetProcessSP(); 437 if (process_sp) { 438 if (m_trampolines_changed_bp_id != LLDB_INVALID_BREAK_ID) 439 process_sp->GetTarget().RemoveBreakpointByID(m_trampolines_changed_bp_id); 440 } 441} 442 443bool AppleObjCTrampolineHandler::AppleObjCVTables::InitializeVTableSymbols() { 444 if (m_trampoline_header != LLDB_INVALID_ADDRESS) 445 return true; 446 447 ProcessSP process_sp = GetProcessSP(); 448 if (process_sp) { 449 Target &target = process_sp->GetTarget(); 450 451 const ModuleList &target_modules = target.GetImages(); 452 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex()); 453 size_t num_modules = target_modules.GetSize(); 454 if (!m_objc_module_sp) { 455 for (size_t i = 0; i < num_modules; i++) { 456 if (process_sp->GetObjCLanguageRuntime()->IsModuleObjCLibrary( 457 target_modules.GetModuleAtIndexUnlocked(i))) { 458 m_objc_module_sp = target_modules.GetModuleAtIndexUnlocked(i); 459 break; 460 } 461 } 462 } 463 464 if (m_objc_module_sp) { 465 ConstString trampoline_name("gdb_objc_trampolines"); 466 const Symbol *trampoline_symbol = 467 m_objc_module_sp->FindFirstSymbolWithNameAndType(trampoline_name, 468 eSymbolTypeData); 469 if (trampoline_symbol != NULL) { 470 m_trampoline_header = trampoline_symbol->GetLoadAddress(&target); 471 if (m_trampoline_header == LLDB_INVALID_ADDRESS) 472 return false; 473 474 // Next look up the "changed" symbol and set a breakpoint on that... 475 ConstString changed_name("gdb_objc_trampolines_changed"); 476 const Symbol *changed_symbol = 477 m_objc_module_sp->FindFirstSymbolWithNameAndType(changed_name, 478 eSymbolTypeCode); 479 if (changed_symbol != NULL) { 480 const Address changed_symbol_addr = changed_symbol->GetAddress(); 481 if (!changed_symbol_addr.IsValid()) 482 return false; 483 484 lldb::addr_t changed_addr = 485 changed_symbol_addr.GetOpcodeLoadAddress(&target); 486 if (changed_addr != LLDB_INVALID_ADDRESS) { 487 BreakpointSP trampolines_changed_bp_sp = 488 target.CreateBreakpoint(changed_addr, true, false); 489 if (trampolines_changed_bp_sp) { 490 m_trampolines_changed_bp_id = trampolines_changed_bp_sp->GetID(); 491 trampolines_changed_bp_sp->SetCallback(RefreshTrampolines, this, 492 true); 493 trampolines_changed_bp_sp->SetBreakpointKind( 494 "objc-trampolines-changed"); 495 return true; 496 } 497 } 498 } 499 } 500 } 501 } 502 return false; 503} 504 505bool AppleObjCTrampolineHandler::AppleObjCVTables::RefreshTrampolines( 506 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, 507 lldb::user_id_t break_loc_id) { 508 AppleObjCVTables *vtable_handler = (AppleObjCVTables *)baton; 509 if (vtable_handler->InitializeVTableSymbols()) { 510 // The Update function is called with the address of an added region. So we 511 // grab that address, and 512 // feed it into ReadRegions. Of course, our friend the ABI will get the 513 // values for us. 514 ExecutionContext exe_ctx(context->exe_ctx_ref); 515 Process *process = exe_ctx.GetProcessPtr(); 516 const ABI *abi = process->GetABI().get(); 517 518 ClangASTContext *clang_ast_context = 519 process->GetTarget().GetScratchClangASTContext(); 520 ValueList argument_values; 521 Value input_value; 522 CompilerType clang_void_ptr_type = 523 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType(); 524 525 input_value.SetValueType(Value::eValueTypeScalar); 526 // input_value.SetContext (Value::eContextTypeClangType, 527 // clang_void_ptr_type); 528 input_value.SetCompilerType(clang_void_ptr_type); 529 argument_values.PushValue(input_value); 530 531 bool success = 532 abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values); 533 if (!success) 534 return false; 535 536 // Now get a pointer value from the zeroth argument. 537 Status error; 538 DataExtractor data; 539 error = argument_values.GetValueAtIndex(0)->GetValueAsData(&exe_ctx, data, 540 0, NULL); 541 lldb::offset_t offset = 0; 542 lldb::addr_t region_addr = data.GetPointer(&offset); 543 544 if (region_addr != 0) 545 vtable_handler->ReadRegions(region_addr); 546 } 547 return false; 548} 549 550bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions() { 551 // The no argument version reads the start region from the value of the 552 // gdb_regions_header, and 553 // gets started from there. 554 555 m_regions.clear(); 556 if (!InitializeVTableSymbols()) 557 return false; 558 Status error; 559 ProcessSP process_sp = GetProcessSP(); 560 if (process_sp) { 561 lldb::addr_t region_addr = 562 process_sp->ReadPointerFromMemory(m_trampoline_header, error); 563 if (error.Success()) 564 return ReadRegions(region_addr); 565 } 566 return false; 567} 568 569bool AppleObjCTrampolineHandler::AppleObjCVTables::ReadRegions( 570 lldb::addr_t region_addr) { 571 ProcessSP process_sp = GetProcessSP(); 572 if (!process_sp) 573 return false; 574 575 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 576 577 // We aren't starting at the trampoline symbol. 578 InitializeVTableSymbols(); 579 lldb::addr_t next_region = region_addr; 580 581 // Read in the sizes of the headers. 582 while (next_region != 0) { 583 m_regions.push_back(VTableRegion(this, next_region)); 584 if (!m_regions.back().IsValid()) { 585 m_regions.clear(); 586 return false; 587 } 588 if (log) { 589 StreamString s; 590 m_regions.back().Dump(s); 591 log->Printf("Read vtable region: \n%s", s.GetData()); 592 } 593 594 next_region = m_regions.back().GetNextRegionAddr(); 595 } 596 597 return true; 598} 599 600bool AppleObjCTrampolineHandler::AppleObjCVTables::IsAddressInVTables( 601 lldb::addr_t addr, uint32_t &flags) { 602 region_collection::iterator pos, end = m_regions.end(); 603 for (pos = m_regions.begin(); pos != end; pos++) { 604 if ((*pos).AddressInRegion(addr, flags)) 605 return true; 606 } 607 return false; 608} 609 610const AppleObjCTrampolineHandler::DispatchFunction 611 AppleObjCTrampolineHandler::g_dispatch_functions[] = { 612 // NAME STRET SUPER SUPER2 FIXUP TYPE 613 {"objc_msgSend", false, false, false, DispatchFunction::eFixUpNone}, 614 {"objc_msgSend_fixup", false, false, false, 615 DispatchFunction::eFixUpToFix}, 616 {"objc_msgSend_fixedup", false, false, false, 617 DispatchFunction::eFixUpFixed}, 618 {"objc_msgSend_stret", true, false, false, 619 DispatchFunction::eFixUpNone}, 620 {"objc_msgSend_stret_fixup", true, false, false, 621 DispatchFunction::eFixUpToFix}, 622 {"objc_msgSend_stret_fixedup", true, false, false, 623 DispatchFunction::eFixUpFixed}, 624 {"objc_msgSend_fpret", false, false, false, 625 DispatchFunction::eFixUpNone}, 626 {"objc_msgSend_fpret_fixup", false, false, false, 627 DispatchFunction::eFixUpToFix}, 628 {"objc_msgSend_fpret_fixedup", false, false, false, 629 DispatchFunction::eFixUpFixed}, 630 {"objc_msgSend_fp2ret", false, false, true, 631 DispatchFunction::eFixUpNone}, 632 {"objc_msgSend_fp2ret_fixup", false, false, true, 633 DispatchFunction::eFixUpToFix}, 634 {"objc_msgSend_fp2ret_fixedup", false, false, true, 635 DispatchFunction::eFixUpFixed}, 636 {"objc_msgSendSuper", false, true, false, DispatchFunction::eFixUpNone}, 637 {"objc_msgSendSuper_stret", true, true, false, 638 DispatchFunction::eFixUpNone}, 639 {"objc_msgSendSuper2", false, true, true, DispatchFunction::eFixUpNone}, 640 {"objc_msgSendSuper2_fixup", false, true, true, 641 DispatchFunction::eFixUpToFix}, 642 {"objc_msgSendSuper2_fixedup", false, true, true, 643 DispatchFunction::eFixUpFixed}, 644 {"objc_msgSendSuper2_stret", true, true, true, 645 DispatchFunction::eFixUpNone}, 646 {"objc_msgSendSuper2_stret_fixup", true, true, true, 647 DispatchFunction::eFixUpToFix}, 648 {"objc_msgSendSuper2_stret_fixedup", true, true, true, 649 DispatchFunction::eFixUpFixed}, 650}; 651 652AppleObjCTrampolineHandler::AppleObjCTrampolineHandler( 653 const ProcessSP &process_sp, const ModuleSP &objc_module_sp) 654 : m_process_wp(), m_objc_module_sp(objc_module_sp), 655 m_lookup_implementation_function_code(nullptr), 656 m_impl_fn_addr(LLDB_INVALID_ADDRESS), 657 m_impl_stret_fn_addr(LLDB_INVALID_ADDRESS), 658 m_msg_forward_addr(LLDB_INVALID_ADDRESS) { 659 if (process_sp) 660 m_process_wp = process_sp; 661 // Look up the known resolution functions: 662 663 ConstString get_impl_name("class_getMethodImplementation"); 664 ConstString get_impl_stret_name("class_getMethodImplementation_stret"); 665 ConstString msg_forward_name("_objc_msgForward"); 666 ConstString msg_forward_stret_name("_objc_msgForward_stret"); 667 668 Target *target = process_sp ? &process_sp->GetTarget() : NULL; 669 const Symbol *class_getMethodImplementation = 670 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_name, 671 eSymbolTypeCode); 672 const Symbol *class_getMethodImplementation_stret = 673 m_objc_module_sp->FindFirstSymbolWithNameAndType(get_impl_stret_name, 674 eSymbolTypeCode); 675 const Symbol *msg_forward = m_objc_module_sp->FindFirstSymbolWithNameAndType( 676 msg_forward_name, eSymbolTypeCode); 677 const Symbol *msg_forward_stret = 678 m_objc_module_sp->FindFirstSymbolWithNameAndType(msg_forward_stret_name, 679 eSymbolTypeCode); 680 681 if (class_getMethodImplementation) 682 m_impl_fn_addr = 683 class_getMethodImplementation->GetAddress().GetOpcodeLoadAddress( 684 target); 685 if (class_getMethodImplementation_stret) 686 m_impl_stret_fn_addr = 687 class_getMethodImplementation_stret->GetAddress().GetOpcodeLoadAddress( 688 target); 689 if (msg_forward) 690 m_msg_forward_addr = msg_forward->GetAddress().GetOpcodeLoadAddress(target); 691 if (msg_forward_stret) 692 m_msg_forward_stret_addr = 693 msg_forward_stret->GetAddress().GetOpcodeLoadAddress(target); 694 695 // FIXME: Do some kind of logging here. 696 if (m_impl_fn_addr == LLDB_INVALID_ADDRESS) { 697 // If we can't even find the ordinary get method implementation function, 698 // then we aren't going to be able to 699 // step through any method dispatches. Warn to that effect and get out of 700 // here. 701 if (process_sp->CanJIT()) { 702 process_sp->GetTarget().GetDebugger().GetErrorFile()->Printf( 703 "Could not find implementation lookup function \"%s\"" 704 " step in through ObjC method dispatch will not work.\n", 705 get_impl_name.AsCString()); 706 } 707 return; 708 } else if (m_impl_stret_fn_addr == LLDB_INVALID_ADDRESS) { 709 // It there is no stret return lookup function, assume that it is the same 710 // as the straight lookup: 711 m_impl_stret_fn_addr = m_impl_fn_addr; 712 // Also we will use the version of the lookup code that doesn't rely on the 713 // stret version of the function. 714 m_lookup_implementation_function_code = 715 g_lookup_implementation_no_stret_function_code; 716 } else { 717 m_lookup_implementation_function_code = 718 g_lookup_implementation_with_stret_function_code; 719 } 720 721 // Look up the addresses for the objc dispatch functions and cache them. For 722 // now I'm inspecting the symbol 723 // names dynamically to figure out how to dispatch to them. If it becomes 724 // more complicated than this we can 725 // turn the g_dispatch_functions char * array into a template table, and 726 // populate the DispatchFunction map 727 // from there. 728 729 for (size_t i = 0; i != llvm::array_lengthof(g_dispatch_functions); i++) { 730 ConstString name_const_str(g_dispatch_functions[i].name); 731 const Symbol *msgSend_symbol = 732 m_objc_module_sp->FindFirstSymbolWithNameAndType(name_const_str, 733 eSymbolTypeCode); 734 if (msgSend_symbol && msgSend_symbol->ValueIsAddress()) { 735 // FixMe: Make g_dispatch_functions static table of DispatchFunctions, and 736 // have the map be address->index. 737 // Problem is we also need to lookup the dispatch function. For now we 738 // could have a side table of stret & non-stret 739 // dispatch functions. If that's as complex as it gets, we're fine. 740 741 lldb::addr_t sym_addr = 742 msgSend_symbol->GetAddressRef().GetOpcodeLoadAddress(target); 743 744 m_msgSend_map.insert(std::pair<lldb::addr_t, int>(sym_addr, i)); 745 } 746 } 747 748 // Build our vtable dispatch handler here: 749 m_vtables_ap.reset(new AppleObjCVTables(process_sp, m_objc_module_sp)); 750 if (m_vtables_ap.get()) 751 m_vtables_ap->ReadRegions(); 752} 753 754lldb::addr_t 755AppleObjCTrampolineHandler::SetupDispatchFunction(Thread &thread, 756 ValueList &dispatch_values) { 757 ThreadSP thread_sp(thread.shared_from_this()); 758 ExecutionContext exe_ctx(thread_sp); 759 DiagnosticManager diagnostics; 760 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 761 762 lldb::addr_t args_addr = LLDB_INVALID_ADDRESS; 763 FunctionCaller *impl_function_caller = nullptr; 764 765 // Scope for mutex locker: 766 { 767 std::lock_guard<std::mutex> guard(m_impl_function_mutex); 768 769 // First stage is to make the ClangUtility to hold our injected function: 770 771 if (!m_impl_code.get()) { 772 if (m_lookup_implementation_function_code != NULL) { 773 Status error; 774 m_impl_code.reset(exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage( 775 m_lookup_implementation_function_code, eLanguageTypeObjC, 776 g_lookup_implementation_function_name, error)); 777 if (error.Fail()) { 778 if (log) 779 log->Printf( 780 "Failed to get Utility Function for implementation lookup: %s.", 781 error.AsCString()); 782 m_impl_code.reset(); 783 return args_addr; 784 } 785 786 if (!m_impl_code->Install(diagnostics, exe_ctx)) { 787 if (log) { 788 log->Printf("Failed to install implementation lookup."); 789 diagnostics.Dump(log); 790 } 791 m_impl_code.reset(); 792 return args_addr; 793 } 794 } else { 795 if (log) 796 log->Printf("No method lookup implementation code."); 797 return LLDB_INVALID_ADDRESS; 798 } 799 800 // Next make the runner function for our implementation utility function. 801 ClangASTContext *clang_ast_context = 802 thread.GetProcess()->GetTarget().GetScratchClangASTContext(); 803 CompilerType clang_void_ptr_type = 804 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType(); 805 Status error; 806 807 impl_function_caller = m_impl_code->MakeFunctionCaller( 808 clang_void_ptr_type, dispatch_values, thread_sp, error); 809 if (error.Fail()) { 810 if (log) 811 log->Printf( 812 "Error getting function caller for dispatch lookup: \"%s\".", 813 error.AsCString()); 814 return args_addr; 815 } 816 } else { 817 impl_function_caller = m_impl_code->GetFunctionCaller(); 818 } 819 } 820 821 diagnostics.Clear(); 822 823 // Now write down the argument values for this particular call. This looks 824 // like it might be a race condition 825 // if other threads were calling into here, but actually it isn't because we 826 // allocate a new args structure for 827 // this call by passing args_addr = LLDB_INVALID_ADDRESS... 828 829 if (!impl_function_caller->WriteFunctionArguments( 830 exe_ctx, args_addr, dispatch_values, diagnostics)) { 831 if (log) { 832 log->Printf("Error writing function arguments."); 833 diagnostics.Dump(log); 834 } 835 return args_addr; 836 } 837 838 return args_addr; 839} 840 841ThreadPlanSP 842AppleObjCTrampolineHandler::GetStepThroughDispatchPlan(Thread &thread, 843 bool stop_others) { 844 ThreadPlanSP ret_plan_sp; 845 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC(); 846 847 DispatchFunction this_dispatch; 848 bool found_it = false; 849 850 // First step is to look and see if we are in one of the known ObjC dispatch 851 // functions. We've already compiled 852 // a table of same, so consult it. 853 854 MsgsendMap::iterator pos; 855 pos = m_msgSend_map.find(curr_pc); 856 if (pos != m_msgSend_map.end()) { 857 this_dispatch = g_dispatch_functions[(*pos).second]; 858 found_it = true; 859 } 860 861 // Next check to see if we are in a vtable region: 862 863 if (!found_it) { 864 uint32_t flags; 865 if (m_vtables_ap.get()) { 866 found_it = m_vtables_ap->IsAddressInVTables(curr_pc, flags); 867 if (found_it) { 868 this_dispatch.name = "vtable"; 869 this_dispatch.stret_return = 870 (flags & AppleObjCVTables::eOBJC_TRAMPOLINE_STRET) == 871 AppleObjCVTables::eOBJC_TRAMPOLINE_STRET; 872 this_dispatch.is_super = false; 873 this_dispatch.is_super2 = false; 874 this_dispatch.fixedup = DispatchFunction::eFixUpFixed; 875 } 876 } 877 } 878 879 if (found_it) { 880 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 881 882 // We are decoding a method dispatch. 883 // First job is to pull the arguments out: 884 885 lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0); 886 887 const ABI *abi = NULL; 888 ProcessSP process_sp(thread.CalculateProcess()); 889 if (process_sp) 890 abi = process_sp->GetABI().get(); 891 if (abi == NULL) 892 return ret_plan_sp; 893 894 TargetSP target_sp(thread.CalculateTarget()); 895 896 ClangASTContext *clang_ast_context = target_sp->GetScratchClangASTContext(); 897 ValueList argument_values; 898 Value void_ptr_value; 899 CompilerType clang_void_ptr_type = 900 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType(); 901 void_ptr_value.SetValueType(Value::eValueTypeScalar); 902 // void_ptr_value.SetContext (Value::eContextTypeClangType, 903 // clang_void_ptr_type); 904 void_ptr_value.SetCompilerType(clang_void_ptr_type); 905 906 int obj_index; 907 int sel_index; 908 909 // If this is a struct return dispatch, then the first argument is the 910 // return struct pointer, and the object is the second, and the selector is 911 // the third. 912 // Otherwise the object is the first and the selector the second. 913 if (this_dispatch.stret_return) { 914 obj_index = 1; 915 sel_index = 2; 916 argument_values.PushValue(void_ptr_value); 917 argument_values.PushValue(void_ptr_value); 918 argument_values.PushValue(void_ptr_value); 919 } else { 920 obj_index = 0; 921 sel_index = 1; 922 argument_values.PushValue(void_ptr_value); 923 argument_values.PushValue(void_ptr_value); 924 } 925 926 bool success = abi->GetArgumentValues(thread, argument_values); 927 if (!success) 928 return ret_plan_sp; 929 930 lldb::addr_t obj_addr = 931 argument_values.GetValueAtIndex(obj_index)->GetScalar().ULongLong(); 932 if (obj_addr == 0x0) { 933 if (log) 934 log->Printf( 935 "Asked to step to dispatch to nil object, returning empty plan."); 936 return ret_plan_sp; 937 } 938 939 ExecutionContext exe_ctx(thread.shared_from_this()); 940 Process *process = exe_ctx.GetProcessPtr(); 941 // isa_addr will store the class pointer that the method is being dispatched 942 // to - so either the class 943 // directly or the super class if this is one of the objc_msgSendSuper 944 // flavors. That's mostly used to 945 // look up the class/selector pair in our cache. 946 947 lldb::addr_t isa_addr = LLDB_INVALID_ADDRESS; 948 lldb::addr_t sel_addr = 949 argument_values.GetValueAtIndex(sel_index)->GetScalar().ULongLong(); 950 951 // Figure out the class this is being dispatched to and see if we've already 952 // cached this method call, 953 // If so we can push a run-to-address plan directly. Otherwise we have to 954 // figure out where 955 // the implementation lives. 956 957 if (this_dispatch.is_super) { 958 if (this_dispatch.is_super2) { 959 // In the objc_msgSendSuper2 case, we don't get the object directly, we 960 // get a structure containing 961 // the object and the class to which the super message is being sent. 962 // So we need to dig the super 963 // out of the class and use that. 964 965 Value super_value(*(argument_values.GetValueAtIndex(obj_index))); 966 super_value.GetScalar() += process->GetAddressByteSize(); 967 super_value.ResolveValue(&exe_ctx); 968 969 if (super_value.GetScalar().IsValid()) { 970 971 // isa_value now holds the class pointer. The second word of the 972 // class pointer is the super-class pointer: 973 super_value.GetScalar() += process->GetAddressByteSize(); 974 super_value.ResolveValue(&exe_ctx); 975 if (super_value.GetScalar().IsValid()) 976 isa_addr = super_value.GetScalar().ULongLong(); 977 else { 978 if (log) 979 log->Printf("Failed to extract the super class value from the " 980 "class in objc_super."); 981 } 982 } else { 983 if (log) 984 log->Printf("Failed to extract the class value from objc_super."); 985 } 986 } else { 987 // In the objc_msgSendSuper case, we don't get the object directly, we 988 // get a two element structure containing 989 // the object and the super class to which the super message is being 990 // sent. So the class we want is 991 // the second element of this structure. 992 993 Value super_value(*(argument_values.GetValueAtIndex(obj_index))); 994 super_value.GetScalar() += process->GetAddressByteSize(); 995 super_value.ResolveValue(&exe_ctx); 996 997 if (super_value.GetScalar().IsValid()) { 998 isa_addr = super_value.GetScalar().ULongLong(); 999 } else { 1000 if (log) 1001 log->Printf("Failed to extract the class value from objc_super."); 1002 } 1003 } 1004 } else { 1005 // In the direct dispatch case, the object->isa is the class pointer we 1006 // want. 1007 1008 // This is a little cheesy, but since object->isa is the first field, 1009 // making the object value a load address value and resolving it will get 1010 // the pointer sized data pointed to by that value... 1011 1012 // Note, it isn't a fatal error not to be able to get the address from the 1013 // object, since this might 1014 // be a "tagged pointer" which isn't a real object, but rather some word 1015 // length encoded dingus. 1016 1017 Value isa_value(*(argument_values.GetValueAtIndex(obj_index))); 1018 1019 isa_value.SetValueType(Value::eValueTypeLoadAddress); 1020 isa_value.ResolveValue(&exe_ctx); 1021 if (isa_value.GetScalar().IsValid()) { 1022 isa_addr = isa_value.GetScalar().ULongLong(); 1023 } else { 1024 if (log) 1025 log->Printf("Failed to extract the isa value from object."); 1026 } 1027 } 1028 1029 // Okay, we've got the address of the class for which we're resolving this, 1030 // let's see if it's in our cache: 1031 lldb::addr_t impl_addr = LLDB_INVALID_ADDRESS; 1032 1033 if (isa_addr != LLDB_INVALID_ADDRESS) { 1034 if (log) { 1035 log->Printf("Resolving call for class - 0x%" PRIx64 1036 " and selector - 0x%" PRIx64, 1037 isa_addr, sel_addr); 1038 } 1039 ObjCLanguageRuntime *objc_runtime = 1040 thread.GetProcess()->GetObjCLanguageRuntime(); 1041 assert(objc_runtime != NULL); 1042 1043 impl_addr = objc_runtime->LookupInMethodCache(isa_addr, sel_addr); 1044 } 1045 1046 if (impl_addr != LLDB_INVALID_ADDRESS) { 1047 // Yup, it was in the cache, so we can run to that address directly. 1048 1049 if (log) 1050 log->Printf("Found implementation address in cache: 0x%" PRIx64, 1051 impl_addr); 1052 1053 ret_plan_sp.reset( 1054 new ThreadPlanRunToAddress(thread, impl_addr, stop_others)); 1055 } else { 1056 // We haven't seen this class/selector pair yet. Look it up. 1057 StreamString errors; 1058 Address impl_code_address; 1059 1060 ValueList dispatch_values; 1061 1062 // We've will inject a little function in the target that takes the 1063 // object, selector and some flags, 1064 // and figures out the implementation. Looks like: 1065 // void *__lldb_objc_find_implementation_for_selector (void *object, 1066 // void *sel, 1067 // int is_stret, 1068 // int is_super, 1069 // int is_super2, 1070 // int is_fixup, 1071 // int is_fixed, 1072 // int debug) 1073 // So set up the arguments for that call. 1074 1075 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(obj_index))); 1076 dispatch_values.PushValue(*(argument_values.GetValueAtIndex(sel_index))); 1077 1078 Value flag_value; 1079 CompilerType clang_int_type = 1080 clang_ast_context->GetBuiltinTypeForEncodingAndBitSize( 1081 lldb::eEncodingSint, 32); 1082 flag_value.SetValueType(Value::eValueTypeScalar); 1083 // flag_value.SetContext (Value::eContextTypeClangType, clang_int_type); 1084 flag_value.SetCompilerType(clang_int_type); 1085 1086 if (this_dispatch.stret_return) 1087 flag_value.GetScalar() = 1; 1088 else 1089 flag_value.GetScalar() = 0; 1090 dispatch_values.PushValue(flag_value); 1091 1092 if (this_dispatch.is_super) 1093 flag_value.GetScalar() = 1; 1094 else 1095 flag_value.GetScalar() = 0; 1096 dispatch_values.PushValue(flag_value); 1097 1098 if (this_dispatch.is_super2) 1099 flag_value.GetScalar() = 1; 1100 else 1101 flag_value.GetScalar() = 0; 1102 dispatch_values.PushValue(flag_value); 1103 1104 switch (this_dispatch.fixedup) { 1105 case DispatchFunction::eFixUpNone: 1106 flag_value.GetScalar() = 0; 1107 dispatch_values.PushValue(flag_value); 1108 dispatch_values.PushValue(flag_value); 1109 break; 1110 case DispatchFunction::eFixUpFixed: 1111 flag_value.GetScalar() = 1; 1112 dispatch_values.PushValue(flag_value); 1113 flag_value.GetScalar() = 1; 1114 dispatch_values.PushValue(flag_value); 1115 break; 1116 case DispatchFunction::eFixUpToFix: 1117 flag_value.GetScalar() = 1; 1118 dispatch_values.PushValue(flag_value); 1119 flag_value.GetScalar() = 0; 1120 dispatch_values.PushValue(flag_value); 1121 break; 1122 } 1123 if (log && log->GetVerbose()) 1124 flag_value.GetScalar() = 1; 1125 else 1126 flag_value.GetScalar() = 0; // FIXME - Set to 0 when debugging is done. 1127 dispatch_values.PushValue(flag_value); 1128 1129 // The step through code might have to fill in the cache, so it is not 1130 // safe to run only one thread. 1131 // So we override the stop_others value passed in to us here: 1132 const bool trampoline_stop_others = false; 1133 ret_plan_sp.reset(new AppleThreadPlanStepThroughObjCTrampoline( 1134 thread, this, dispatch_values, isa_addr, sel_addr, 1135 trampoline_stop_others)); 1136 if (log) { 1137 StreamString s; 1138 ret_plan_sp->GetDescription(&s, eDescriptionLevelFull); 1139 log->Printf("Using ObjC step plan: %s.\n", s.GetData()); 1140 } 1141 } 1142 } 1143 1144 return ret_plan_sp; 1145} 1146 1147FunctionCaller * 1148AppleObjCTrampolineHandler::GetLookupImplementationFunctionCaller() { 1149 return m_impl_code->GetFunctionCaller(); 1150} 1151