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