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