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