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