1 //===-- ObjectFileMachO.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 "llvm/ADT/StringRef.h" 11 12 #include "lldb/lldb-private-log.h" 13 #include "lldb/Core/ArchSpec.h" 14 #include "lldb/Core/DataBuffer.h" 15 #include "lldb/Core/Debugger.h" 16 #include "lldb/Core/FileSpecList.h" 17 #include "lldb/Core/Log.h" 18 #include "lldb/Core/Module.h" 19 #include "lldb/Core/ModuleSpec.h" 20 #include "lldb/Core/PluginManager.h" 21 #include "lldb/Core/RangeMap.h" 22 #include "lldb/Core/Section.h" 23 #include "lldb/Core/StreamFile.h" 24 #include "lldb/Core/StreamString.h" 25 #include "lldb/Core/Timer.h" 26 #include "lldb/Core/UUID.h" 27 #include "lldb/Host/Host.h" 28 #include "lldb/Host/FileSpec.h" 29 #include "lldb/Symbol/ClangNamespaceDecl.h" 30 #include "lldb/Symbol/DWARFCallFrameInfo.h" 31 #include "lldb/Symbol/ObjectFile.h" 32 #include "lldb/Target/Platform.h" 33 #include "lldb/Target/Process.h" 34 #include "lldb/Target/SectionLoadList.h" 35 #include "lldb/Target/Target.h" 36 #include "Plugins/Process/Utility/RegisterContextDarwin_arm.h" 37 #include "Plugins/Process/Utility/RegisterContextDarwin_arm64.h" 38 #include "Plugins/Process/Utility/RegisterContextDarwin_i386.h" 39 #include "Plugins/Process/Utility/RegisterContextDarwin_x86_64.h" 40 41 #include "lldb/Utility/SafeMachO.h" 42 43 #include "ObjectFileMachO.h" 44 45 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__)) 46 // GetLLDBSharedCacheUUID() needs to call dlsym() 47 #include <dlfcn.h> 48 #endif 49 50 #ifndef __APPLE__ 51 #include "Utility/UuidCompatibility.h" 52 #endif 53 54 using namespace lldb; 55 using namespace lldb_private; 56 using namespace llvm::MachO; 57 58 class RegisterContextDarwin_x86_64_Mach : public RegisterContextDarwin_x86_64 59 { 60 public: 61 RegisterContextDarwin_x86_64_Mach (lldb_private::Thread &thread, const DataExtractor &data) : 62 RegisterContextDarwin_x86_64 (thread, 0) 63 { 64 SetRegisterDataFrom_LC_THREAD (data); 65 } 66 67 virtual void 68 InvalidateAllRegisters () 69 { 70 // Do nothing... registers are always valid... 71 } 72 73 void 74 SetRegisterDataFrom_LC_THREAD (const DataExtractor &data) 75 { 76 lldb::offset_t offset = 0; 77 SetError (GPRRegSet, Read, -1); 78 SetError (FPURegSet, Read, -1); 79 SetError (EXCRegSet, Read, -1); 80 bool done = false; 81 82 while (!done) 83 { 84 int flavor = data.GetU32 (&offset); 85 if (flavor == 0) 86 done = true; 87 else 88 { 89 uint32_t i; 90 uint32_t count = data.GetU32 (&offset); 91 switch (flavor) 92 { 93 case GPRRegSet: 94 for (i=0; i<count; ++i) 95 (&gpr.rax)[i] = data.GetU64(&offset); 96 SetError (GPRRegSet, Read, 0); 97 done = true; 98 99 break; 100 case FPURegSet: 101 // TODO: fill in FPU regs.... 102 //SetError (FPURegSet, Read, -1); 103 done = true; 104 105 break; 106 case EXCRegSet: 107 exc.trapno = data.GetU32(&offset); 108 exc.err = data.GetU32(&offset); 109 exc.faultvaddr = data.GetU64(&offset); 110 SetError (EXCRegSet, Read, 0); 111 done = true; 112 break; 113 case 7: 114 case 8: 115 case 9: 116 // fancy flavors that encapsulate of the the above 117 // falvors... 118 break; 119 120 default: 121 done = true; 122 break; 123 } 124 } 125 } 126 } 127 protected: 128 virtual int 129 DoReadGPR (lldb::tid_t tid, int flavor, GPR &gpr) 130 { 131 return 0; 132 } 133 134 virtual int 135 DoReadFPU (lldb::tid_t tid, int flavor, FPU &fpu) 136 { 137 return 0; 138 } 139 140 virtual int 141 DoReadEXC (lldb::tid_t tid, int flavor, EXC &exc) 142 { 143 return 0; 144 } 145 146 virtual int 147 DoWriteGPR (lldb::tid_t tid, int flavor, const GPR &gpr) 148 { 149 return 0; 150 } 151 152 virtual int 153 DoWriteFPU (lldb::tid_t tid, int flavor, const FPU &fpu) 154 { 155 return 0; 156 } 157 158 virtual int 159 DoWriteEXC (lldb::tid_t tid, int flavor, const EXC &exc) 160 { 161 return 0; 162 } 163 }; 164 165 166 class RegisterContextDarwin_i386_Mach : public RegisterContextDarwin_i386 167 { 168 public: 169 RegisterContextDarwin_i386_Mach (lldb_private::Thread &thread, const DataExtractor &data) : 170 RegisterContextDarwin_i386 (thread, 0) 171 { 172 SetRegisterDataFrom_LC_THREAD (data); 173 } 174 175 virtual void 176 InvalidateAllRegisters () 177 { 178 // Do nothing... registers are always valid... 179 } 180 181 void 182 SetRegisterDataFrom_LC_THREAD (const DataExtractor &data) 183 { 184 lldb::offset_t offset = 0; 185 SetError (GPRRegSet, Read, -1); 186 SetError (FPURegSet, Read, -1); 187 SetError (EXCRegSet, Read, -1); 188 bool done = false; 189 190 while (!done) 191 { 192 int flavor = data.GetU32 (&offset); 193 if (flavor == 0) 194 done = true; 195 else 196 { 197 uint32_t i; 198 uint32_t count = data.GetU32 (&offset); 199 switch (flavor) 200 { 201 case GPRRegSet: 202 for (i=0; i<count; ++i) 203 (&gpr.eax)[i] = data.GetU32(&offset); 204 SetError (GPRRegSet, Read, 0); 205 done = true; 206 207 break; 208 case FPURegSet: 209 // TODO: fill in FPU regs.... 210 //SetError (FPURegSet, Read, -1); 211 done = true; 212 213 break; 214 case EXCRegSet: 215 exc.trapno = data.GetU32(&offset); 216 exc.err = data.GetU32(&offset); 217 exc.faultvaddr = data.GetU32(&offset); 218 SetError (EXCRegSet, Read, 0); 219 done = true; 220 break; 221 case 7: 222 case 8: 223 case 9: 224 // fancy flavors that encapsulate of the the above 225 // falvors... 226 break; 227 228 default: 229 done = true; 230 break; 231 } 232 } 233 } 234 } 235 protected: 236 virtual int 237 DoReadGPR (lldb::tid_t tid, int flavor, GPR &gpr) 238 { 239 return 0; 240 } 241 242 virtual int 243 DoReadFPU (lldb::tid_t tid, int flavor, FPU &fpu) 244 { 245 return 0; 246 } 247 248 virtual int 249 DoReadEXC (lldb::tid_t tid, int flavor, EXC &exc) 250 { 251 return 0; 252 } 253 254 virtual int 255 DoWriteGPR (lldb::tid_t tid, int flavor, const GPR &gpr) 256 { 257 return 0; 258 } 259 260 virtual int 261 DoWriteFPU (lldb::tid_t tid, int flavor, const FPU &fpu) 262 { 263 return 0; 264 } 265 266 virtual int 267 DoWriteEXC (lldb::tid_t tid, int flavor, const EXC &exc) 268 { 269 return 0; 270 } 271 }; 272 273 class RegisterContextDarwin_arm_Mach : public RegisterContextDarwin_arm 274 { 275 public: 276 RegisterContextDarwin_arm_Mach (lldb_private::Thread &thread, const DataExtractor &data) : 277 RegisterContextDarwin_arm (thread, 0) 278 { 279 SetRegisterDataFrom_LC_THREAD (data); 280 } 281 282 virtual void 283 InvalidateAllRegisters () 284 { 285 // Do nothing... registers are always valid... 286 } 287 288 void 289 SetRegisterDataFrom_LC_THREAD (const DataExtractor &data) 290 { 291 lldb::offset_t offset = 0; 292 SetError (GPRRegSet, Read, -1); 293 SetError (FPURegSet, Read, -1); 294 SetError (EXCRegSet, Read, -1); 295 bool done = false; 296 297 while (!done) 298 { 299 int flavor = data.GetU32 (&offset); 300 uint32_t count = data.GetU32 (&offset); 301 lldb::offset_t next_thread_state = offset + (count * 4); 302 switch (flavor) 303 { 304 case GPRRegSet: 305 for (uint32_t i=0; i<count; ++i) 306 { 307 gpr.r[i] = data.GetU32(&offset); 308 } 309 310 // Note that gpr.cpsr is also copied by the above loop; this loop technically extends 311 // one element past the end of the gpr.r[] array. 312 313 SetError (GPRRegSet, Read, 0); 314 offset = next_thread_state; 315 break; 316 317 case FPURegSet: 318 { 319 uint8_t *fpu_reg_buf = (uint8_t*) &fpu.floats.s[0]; 320 const int fpu_reg_buf_size = sizeof (fpu.floats); 321 if (data.ExtractBytes (offset, fpu_reg_buf_size, eByteOrderLittle, fpu_reg_buf) == fpu_reg_buf_size) 322 { 323 offset += fpu_reg_buf_size; 324 fpu.fpscr = data.GetU32(&offset); 325 SetError (FPURegSet, Read, 0); 326 } 327 else 328 { 329 done = true; 330 } 331 } 332 offset = next_thread_state; 333 break; 334 335 case EXCRegSet: 336 if (count == 3) 337 { 338 exc.exception = data.GetU32(&offset); 339 exc.fsr = data.GetU32(&offset); 340 exc.far = data.GetU32(&offset); 341 SetError (EXCRegSet, Read, 0); 342 } 343 done = true; 344 offset = next_thread_state; 345 break; 346 347 // Unknown register set flavor, stop trying to parse. 348 default: 349 done = true; 350 } 351 } 352 } 353 protected: 354 virtual int 355 DoReadGPR (lldb::tid_t tid, int flavor, GPR &gpr) 356 { 357 return -1; 358 } 359 360 virtual int 361 DoReadFPU (lldb::tid_t tid, int flavor, FPU &fpu) 362 { 363 return -1; 364 } 365 366 virtual int 367 DoReadEXC (lldb::tid_t tid, int flavor, EXC &exc) 368 { 369 return -1; 370 } 371 372 virtual int 373 DoReadDBG (lldb::tid_t tid, int flavor, DBG &dbg) 374 { 375 return -1; 376 } 377 378 virtual int 379 DoWriteGPR (lldb::tid_t tid, int flavor, const GPR &gpr) 380 { 381 return 0; 382 } 383 384 virtual int 385 DoWriteFPU (lldb::tid_t tid, int flavor, const FPU &fpu) 386 { 387 return 0; 388 } 389 390 virtual int 391 DoWriteEXC (lldb::tid_t tid, int flavor, const EXC &exc) 392 { 393 return 0; 394 } 395 396 virtual int 397 DoWriteDBG (lldb::tid_t tid, int flavor, const DBG &dbg) 398 { 399 return -1; 400 } 401 }; 402 403 class RegisterContextDarwin_arm64_Mach : public RegisterContextDarwin_arm64 404 { 405 public: 406 RegisterContextDarwin_arm64_Mach (lldb_private::Thread &thread, const DataExtractor &data) : 407 RegisterContextDarwin_arm64 (thread, 0) 408 { 409 SetRegisterDataFrom_LC_THREAD (data); 410 } 411 412 virtual void 413 InvalidateAllRegisters () 414 { 415 // Do nothing... registers are always valid... 416 } 417 418 void 419 SetRegisterDataFrom_LC_THREAD (const DataExtractor &data) 420 { 421 lldb::offset_t offset = 0; 422 SetError (GPRRegSet, Read, -1); 423 SetError (FPURegSet, Read, -1); 424 SetError (EXCRegSet, Read, -1); 425 bool done = false; 426 while (!done) 427 { 428 int flavor = data.GetU32 (&offset); 429 uint32_t count = data.GetU32 (&offset); 430 lldb::offset_t next_thread_state = offset + (count * 4); 431 switch (flavor) 432 { 433 case GPRRegSet: 434 // x0-x29 + fp + lr + sp + pc (== 33 64-bit registers) plus cpsr (1 32-bit register) 435 if (count >= (33 * 2) + 1) 436 { 437 for (uint32_t i=0; i<33; ++i) 438 gpr.x[i] = data.GetU64(&offset); 439 gpr.cpsr = data.GetU32(&offset); 440 SetError (GPRRegSet, Read, 0); 441 } 442 offset = next_thread_state; 443 break; 444 case FPURegSet: 445 { 446 uint8_t *fpu_reg_buf = (uint8_t*) &fpu.v[0]; 447 const int fpu_reg_buf_size = sizeof (fpu); 448 if (fpu_reg_buf_size == count 449 && data.ExtractBytes (offset, fpu_reg_buf_size, eByteOrderLittle, fpu_reg_buf) == fpu_reg_buf_size) 450 { 451 SetError (FPURegSet, Read, 0); 452 } 453 else 454 { 455 done = true; 456 } 457 } 458 offset = next_thread_state; 459 break; 460 case EXCRegSet: 461 if (count == 4) 462 { 463 exc.far = data.GetU64(&offset); 464 exc.esr = data.GetU32(&offset); 465 exc.exception = data.GetU32(&offset); 466 SetError (EXCRegSet, Read, 0); 467 } 468 offset = next_thread_state; 469 break; 470 default: 471 done = true; 472 break; 473 } 474 } 475 } 476 protected: 477 virtual int 478 DoReadGPR (lldb::tid_t tid, int flavor, GPR &gpr) 479 { 480 return -1; 481 } 482 483 virtual int 484 DoReadFPU (lldb::tid_t tid, int flavor, FPU &fpu) 485 { 486 return -1; 487 } 488 489 virtual int 490 DoReadEXC (lldb::tid_t tid, int flavor, EXC &exc) 491 { 492 return -1; 493 } 494 495 virtual int 496 DoReadDBG (lldb::tid_t tid, int flavor, DBG &dbg) 497 { 498 return -1; 499 } 500 501 virtual int 502 DoWriteGPR (lldb::tid_t tid, int flavor, const GPR &gpr) 503 { 504 return 0; 505 } 506 507 virtual int 508 DoWriteFPU (lldb::tid_t tid, int flavor, const FPU &fpu) 509 { 510 return 0; 511 } 512 513 virtual int 514 DoWriteEXC (lldb::tid_t tid, int flavor, const EXC &exc) 515 { 516 return 0; 517 } 518 519 virtual int 520 DoWriteDBG (lldb::tid_t tid, int flavor, const DBG &dbg) 521 { 522 return -1; 523 } 524 }; 525 526 static uint32_t 527 MachHeaderSizeFromMagic(uint32_t magic) 528 { 529 switch (magic) 530 { 531 case MH_MAGIC: 532 case MH_CIGAM: 533 return sizeof(struct mach_header); 534 535 case MH_MAGIC_64: 536 case MH_CIGAM_64: 537 return sizeof(struct mach_header_64); 538 break; 539 540 default: 541 break; 542 } 543 return 0; 544 } 545 546 #define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008 547 548 void 549 ObjectFileMachO::Initialize() 550 { 551 PluginManager::RegisterPlugin (GetPluginNameStatic(), 552 GetPluginDescriptionStatic(), 553 CreateInstance, 554 CreateMemoryInstance, 555 GetModuleSpecifications); 556 } 557 558 void 559 ObjectFileMachO::Terminate() 560 { 561 PluginManager::UnregisterPlugin (CreateInstance); 562 } 563 564 565 lldb_private::ConstString 566 ObjectFileMachO::GetPluginNameStatic() 567 { 568 static ConstString g_name("mach-o"); 569 return g_name; 570 } 571 572 const char * 573 ObjectFileMachO::GetPluginDescriptionStatic() 574 { 575 return "Mach-o object file reader (32 and 64 bit)"; 576 } 577 578 ObjectFile * 579 ObjectFileMachO::CreateInstance (const lldb::ModuleSP &module_sp, 580 DataBufferSP& data_sp, 581 lldb::offset_t data_offset, 582 const FileSpec* file, 583 lldb::offset_t file_offset, 584 lldb::offset_t length) 585 { 586 if (!data_sp) 587 { 588 data_sp = file->MemoryMapFileContents(file_offset, length); 589 data_offset = 0; 590 } 591 592 if (ObjectFileMachO::MagicBytesMatch(data_sp, data_offset, length)) 593 { 594 // Update the data to contain the entire file if it doesn't already 595 if (data_sp->GetByteSize() < length) 596 { 597 data_sp = file->MemoryMapFileContents(file_offset, length); 598 data_offset = 0; 599 } 600 std::unique_ptr<ObjectFile> objfile_ap(new ObjectFileMachO (module_sp, data_sp, data_offset, file, file_offset, length)); 601 if (objfile_ap.get() && objfile_ap->ParseHeader()) 602 return objfile_ap.release(); 603 } 604 return NULL; 605 } 606 607 ObjectFile * 608 ObjectFileMachO::CreateMemoryInstance (const lldb::ModuleSP &module_sp, 609 DataBufferSP& data_sp, 610 const ProcessSP &process_sp, 611 lldb::addr_t header_addr) 612 { 613 if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) 614 { 615 std::unique_ptr<ObjectFile> objfile_ap(new ObjectFileMachO (module_sp, data_sp, process_sp, header_addr)); 616 if (objfile_ap.get() && objfile_ap->ParseHeader()) 617 return objfile_ap.release(); 618 } 619 return NULL; 620 } 621 622 size_t 623 ObjectFileMachO::GetModuleSpecifications (const lldb_private::FileSpec& file, 624 lldb::DataBufferSP& data_sp, 625 lldb::offset_t data_offset, 626 lldb::offset_t file_offset, 627 lldb::offset_t length, 628 lldb_private::ModuleSpecList &specs) 629 { 630 const size_t initial_count = specs.GetSize(); 631 632 if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) 633 { 634 DataExtractor data; 635 data.SetData(data_sp); 636 llvm::MachO::mach_header header; 637 if (ParseHeader (data, &data_offset, header)) 638 { 639 size_t header_and_load_cmds = header.sizeofcmds + MachHeaderSizeFromMagic(header.magic); 640 if (header_and_load_cmds >= data_sp->GetByteSize()) 641 { 642 data_sp = file.ReadFileContents(file_offset, header_and_load_cmds); 643 data.SetData(data_sp); 644 data_offset = MachHeaderSizeFromMagic(header.magic); 645 } 646 if (data_sp) 647 { 648 ModuleSpec spec; 649 spec.GetFileSpec() = file; 650 spec.SetObjectOffset(file_offset); 651 652 if (GetArchitecture (header, data, data_offset, spec.GetArchitecture())) 653 { 654 if (spec.GetArchitecture().IsValid()) 655 { 656 GetUUID (header, data, data_offset, spec.GetUUID()); 657 specs.Append(spec); 658 } 659 } 660 } 661 } 662 } 663 return specs.GetSize() - initial_count; 664 } 665 666 667 668 const ConstString & 669 ObjectFileMachO::GetSegmentNameTEXT() 670 { 671 static ConstString g_segment_name_TEXT ("__TEXT"); 672 return g_segment_name_TEXT; 673 } 674 675 const ConstString & 676 ObjectFileMachO::GetSegmentNameDATA() 677 { 678 static ConstString g_segment_name_DATA ("__DATA"); 679 return g_segment_name_DATA; 680 } 681 682 const ConstString & 683 ObjectFileMachO::GetSegmentNameOBJC() 684 { 685 static ConstString g_segment_name_OBJC ("__OBJC"); 686 return g_segment_name_OBJC; 687 } 688 689 const ConstString & 690 ObjectFileMachO::GetSegmentNameLINKEDIT() 691 { 692 static ConstString g_section_name_LINKEDIT ("__LINKEDIT"); 693 return g_section_name_LINKEDIT; 694 } 695 696 const ConstString & 697 ObjectFileMachO::GetSectionNameEHFrame() 698 { 699 static ConstString g_section_name_eh_frame ("__eh_frame"); 700 return g_section_name_eh_frame; 701 } 702 703 bool 704 ObjectFileMachO::MagicBytesMatch (DataBufferSP& data_sp, 705 lldb::addr_t data_offset, 706 lldb::addr_t data_length) 707 { 708 DataExtractor data; 709 data.SetData (data_sp, data_offset, data_length); 710 lldb::offset_t offset = 0; 711 uint32_t magic = data.GetU32(&offset); 712 return MachHeaderSizeFromMagic(magic) != 0; 713 } 714 715 716 ObjectFileMachO::ObjectFileMachO(const lldb::ModuleSP &module_sp, 717 DataBufferSP& data_sp, 718 lldb::offset_t data_offset, 719 const FileSpec* file, 720 lldb::offset_t file_offset, 721 lldb::offset_t length) : 722 ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset), 723 m_mach_segments(), 724 m_mach_sections(), 725 m_entry_point_address(), 726 m_thread_context_offsets(), 727 m_thread_context_offsets_valid(false) 728 { 729 ::memset (&m_header, 0, sizeof(m_header)); 730 ::memset (&m_dysymtab, 0, sizeof(m_dysymtab)); 731 } 732 733 ObjectFileMachO::ObjectFileMachO (const lldb::ModuleSP &module_sp, 734 lldb::DataBufferSP& header_data_sp, 735 const lldb::ProcessSP &process_sp, 736 lldb::addr_t header_addr) : 737 ObjectFile(module_sp, process_sp, header_addr, header_data_sp), 738 m_mach_segments(), 739 m_mach_sections(), 740 m_entry_point_address(), 741 m_thread_context_offsets(), 742 m_thread_context_offsets_valid(false) 743 { 744 ::memset (&m_header, 0, sizeof(m_header)); 745 ::memset (&m_dysymtab, 0, sizeof(m_dysymtab)); 746 } 747 748 ObjectFileMachO::~ObjectFileMachO() 749 { 750 } 751 752 bool 753 ObjectFileMachO::ParseHeader (DataExtractor &data, 754 lldb::offset_t *data_offset_ptr, 755 llvm::MachO::mach_header &header) 756 { 757 data.SetByteOrder (lldb::endian::InlHostByteOrder()); 758 // Leave magic in the original byte order 759 header.magic = data.GetU32(data_offset_ptr); 760 bool can_parse = false; 761 bool is_64_bit = false; 762 switch (header.magic) 763 { 764 case MH_MAGIC: 765 data.SetByteOrder (lldb::endian::InlHostByteOrder()); 766 data.SetAddressByteSize(4); 767 can_parse = true; 768 break; 769 770 case MH_MAGIC_64: 771 data.SetByteOrder (lldb::endian::InlHostByteOrder()); 772 data.SetAddressByteSize(8); 773 can_parse = true; 774 is_64_bit = true; 775 break; 776 777 case MH_CIGAM: 778 data.SetByteOrder(lldb::endian::InlHostByteOrder() == eByteOrderBig ? eByteOrderLittle : eByteOrderBig); 779 data.SetAddressByteSize(4); 780 can_parse = true; 781 break; 782 783 case MH_CIGAM_64: 784 data.SetByteOrder(lldb::endian::InlHostByteOrder() == eByteOrderBig ? eByteOrderLittle : eByteOrderBig); 785 data.SetAddressByteSize(8); 786 is_64_bit = true; 787 can_parse = true; 788 break; 789 790 default: 791 break; 792 } 793 794 if (can_parse) 795 { 796 data.GetU32(data_offset_ptr, &header.cputype, 6); 797 if (is_64_bit) 798 *data_offset_ptr += 4; 799 return true; 800 } 801 else 802 { 803 memset(&header, 0, sizeof(header)); 804 } 805 return false; 806 } 807 808 bool 809 ObjectFileMachO::ParseHeader () 810 { 811 ModuleSP module_sp(GetModule()); 812 if (module_sp) 813 { 814 lldb_private::Mutex::Locker locker(module_sp->GetMutex()); 815 bool can_parse = false; 816 lldb::offset_t offset = 0; 817 m_data.SetByteOrder (lldb::endian::InlHostByteOrder()); 818 // Leave magic in the original byte order 819 m_header.magic = m_data.GetU32(&offset); 820 switch (m_header.magic) 821 { 822 case MH_MAGIC: 823 m_data.SetByteOrder (lldb::endian::InlHostByteOrder()); 824 m_data.SetAddressByteSize(4); 825 can_parse = true; 826 break; 827 828 case MH_MAGIC_64: 829 m_data.SetByteOrder (lldb::endian::InlHostByteOrder()); 830 m_data.SetAddressByteSize(8); 831 can_parse = true; 832 break; 833 834 case MH_CIGAM: 835 m_data.SetByteOrder(lldb::endian::InlHostByteOrder() == eByteOrderBig ? eByteOrderLittle : eByteOrderBig); 836 m_data.SetAddressByteSize(4); 837 can_parse = true; 838 break; 839 840 case MH_CIGAM_64: 841 m_data.SetByteOrder(lldb::endian::InlHostByteOrder() == eByteOrderBig ? eByteOrderLittle : eByteOrderBig); 842 m_data.SetAddressByteSize(8); 843 can_parse = true; 844 break; 845 846 default: 847 break; 848 } 849 850 if (can_parse) 851 { 852 m_data.GetU32(&offset, &m_header.cputype, 6); 853 854 855 ArchSpec mach_arch; 856 857 if (GetArchitecture (mach_arch)) 858 { 859 // Check if the module has a required architecture 860 const ArchSpec &module_arch = module_sp->GetArchitecture(); 861 if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch)) 862 return false; 863 864 if (SetModulesArchitecture (mach_arch)) 865 { 866 const size_t header_and_lc_size = m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic); 867 if (m_data.GetByteSize() < header_and_lc_size) 868 { 869 DataBufferSP data_sp; 870 ProcessSP process_sp (m_process_wp.lock()); 871 if (process_sp) 872 { 873 data_sp = ReadMemory (process_sp, m_memory_addr, header_and_lc_size); 874 } 875 else 876 { 877 // Read in all only the load command data from the file on disk 878 data_sp = m_file.ReadFileContents(m_file_offset, header_and_lc_size); 879 if (data_sp->GetByteSize() != header_and_lc_size) 880 return false; 881 } 882 if (data_sp) 883 m_data.SetData (data_sp); 884 } 885 } 886 return true; 887 } 888 } 889 else 890 { 891 memset(&m_header, 0, sizeof(struct mach_header)); 892 } 893 } 894 return false; 895 } 896 897 898 ByteOrder 899 ObjectFileMachO::GetByteOrder () const 900 { 901 return m_data.GetByteOrder (); 902 } 903 904 bool 905 ObjectFileMachO::IsExecutable() const 906 { 907 return m_header.filetype == MH_EXECUTE; 908 } 909 910 uint32_t 911 ObjectFileMachO::GetAddressByteSize () const 912 { 913 return m_data.GetAddressByteSize (); 914 } 915 916 AddressClass 917 ObjectFileMachO::GetAddressClass (lldb::addr_t file_addr) 918 { 919 Symtab *symtab = GetSymtab(); 920 if (symtab) 921 { 922 Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr); 923 if (symbol) 924 { 925 if (symbol->ValueIsAddress()) 926 { 927 SectionSP section_sp (symbol->GetAddress().GetSection()); 928 if (section_sp) 929 { 930 const lldb::SectionType section_type = section_sp->GetType(); 931 switch (section_type) 932 { 933 case eSectionTypeInvalid: return eAddressClassUnknown; 934 case eSectionTypeCode: 935 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) 936 { 937 // For ARM we have a bit in the n_desc field of the symbol 938 // that tells us ARM/Thumb which is bit 0x0008. 939 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB) 940 return eAddressClassCodeAlternateISA; 941 } 942 return eAddressClassCode; 943 944 case eSectionTypeContainer: return eAddressClassUnknown; 945 case eSectionTypeData: 946 case eSectionTypeDataCString: 947 case eSectionTypeDataCStringPointers: 948 case eSectionTypeDataSymbolAddress: 949 case eSectionTypeData4: 950 case eSectionTypeData8: 951 case eSectionTypeData16: 952 case eSectionTypeDataPointers: 953 case eSectionTypeZeroFill: 954 case eSectionTypeDataObjCMessageRefs: 955 case eSectionTypeDataObjCCFStrings: 956 return eAddressClassData; 957 case eSectionTypeDebug: 958 case eSectionTypeDWARFDebugAbbrev: 959 case eSectionTypeDWARFDebugAranges: 960 case eSectionTypeDWARFDebugFrame: 961 case eSectionTypeDWARFDebugInfo: 962 case eSectionTypeDWARFDebugLine: 963 case eSectionTypeDWARFDebugLoc: 964 case eSectionTypeDWARFDebugMacInfo: 965 case eSectionTypeDWARFDebugPubNames: 966 case eSectionTypeDWARFDebugPubTypes: 967 case eSectionTypeDWARFDebugRanges: 968 case eSectionTypeDWARFDebugStr: 969 case eSectionTypeDWARFAppleNames: 970 case eSectionTypeDWARFAppleTypes: 971 case eSectionTypeDWARFAppleNamespaces: 972 case eSectionTypeDWARFAppleObjC: 973 return eAddressClassDebug; 974 case eSectionTypeEHFrame: return eAddressClassRuntime; 975 case eSectionTypeELFSymbolTable: 976 case eSectionTypeELFDynamicSymbols: 977 case eSectionTypeELFRelocationEntries: 978 case eSectionTypeELFDynamicLinkInfo: 979 case eSectionTypeOther: return eAddressClassUnknown; 980 } 981 } 982 } 983 984 const SymbolType symbol_type = symbol->GetType(); 985 switch (symbol_type) 986 { 987 case eSymbolTypeAny: return eAddressClassUnknown; 988 case eSymbolTypeAbsolute: return eAddressClassUnknown; 989 990 case eSymbolTypeCode: 991 case eSymbolTypeTrampoline: 992 case eSymbolTypeResolver: 993 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) 994 { 995 // For ARM we have a bit in the n_desc field of the symbol 996 // that tells us ARM/Thumb which is bit 0x0008. 997 if (symbol->GetFlags() & MACHO_NLIST_ARM_SYMBOL_IS_THUMB) 998 return eAddressClassCodeAlternateISA; 999 } 1000 return eAddressClassCode; 1001 1002 case eSymbolTypeData: return eAddressClassData; 1003 case eSymbolTypeRuntime: return eAddressClassRuntime; 1004 case eSymbolTypeException: return eAddressClassRuntime; 1005 case eSymbolTypeSourceFile: return eAddressClassDebug; 1006 case eSymbolTypeHeaderFile: return eAddressClassDebug; 1007 case eSymbolTypeObjectFile: return eAddressClassDebug; 1008 case eSymbolTypeCommonBlock: return eAddressClassDebug; 1009 case eSymbolTypeBlock: return eAddressClassDebug; 1010 case eSymbolTypeLocal: return eAddressClassData; 1011 case eSymbolTypeParam: return eAddressClassData; 1012 case eSymbolTypeVariable: return eAddressClassData; 1013 case eSymbolTypeVariableType: return eAddressClassDebug; 1014 case eSymbolTypeLineEntry: return eAddressClassDebug; 1015 case eSymbolTypeLineHeader: return eAddressClassDebug; 1016 case eSymbolTypeScopeBegin: return eAddressClassDebug; 1017 case eSymbolTypeScopeEnd: return eAddressClassDebug; 1018 case eSymbolTypeAdditional: return eAddressClassUnknown; 1019 case eSymbolTypeCompiler: return eAddressClassDebug; 1020 case eSymbolTypeInstrumentation:return eAddressClassDebug; 1021 case eSymbolTypeUndefined: return eAddressClassUnknown; 1022 case eSymbolTypeObjCClass: return eAddressClassRuntime; 1023 case eSymbolTypeObjCMetaClass: return eAddressClassRuntime; 1024 case eSymbolTypeObjCIVar: return eAddressClassRuntime; 1025 case eSymbolTypeReExported: return eAddressClassRuntime; 1026 } 1027 } 1028 } 1029 return eAddressClassUnknown; 1030 } 1031 1032 Symtab * 1033 ObjectFileMachO::GetSymtab() 1034 { 1035 ModuleSP module_sp(GetModule()); 1036 if (module_sp) 1037 { 1038 lldb_private::Mutex::Locker locker(module_sp->GetMutex()); 1039 if (m_symtab_ap.get() == NULL) 1040 { 1041 m_symtab_ap.reset(new Symtab(this)); 1042 Mutex::Locker symtab_locker (m_symtab_ap->GetMutex()); 1043 ParseSymtab (); 1044 m_symtab_ap->Finalize (); 1045 } 1046 } 1047 return m_symtab_ap.get(); 1048 } 1049 1050 bool 1051 ObjectFileMachO::IsStripped () 1052 { 1053 if (m_dysymtab.cmd == 0) 1054 { 1055 ModuleSP module_sp(GetModule()); 1056 if (module_sp) 1057 { 1058 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 1059 for (uint32_t i=0; i<m_header.ncmds; ++i) 1060 { 1061 const lldb::offset_t load_cmd_offset = offset; 1062 1063 load_command lc; 1064 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL) 1065 break; 1066 if (lc.cmd == LC_DYSYMTAB) 1067 { 1068 m_dysymtab.cmd = lc.cmd; 1069 m_dysymtab.cmdsize = lc.cmdsize; 1070 if (m_data.GetU32 (&offset, &m_dysymtab.ilocalsym, (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) == NULL) 1071 { 1072 // Clear m_dysymtab if we were unable to read all items from the load command 1073 ::memset (&m_dysymtab, 0, sizeof(m_dysymtab)); 1074 } 1075 } 1076 offset = load_cmd_offset + lc.cmdsize; 1077 } 1078 } 1079 } 1080 if (m_dysymtab.cmd) 1081 return m_dysymtab.nlocalsym <= 1; 1082 return false; 1083 } 1084 1085 void 1086 ObjectFileMachO::CreateSections (SectionList &unified_section_list) 1087 { 1088 if (!m_sections_ap.get()) 1089 { 1090 m_sections_ap.reset(new SectionList()); 1091 1092 const bool is_dsym = (m_header.filetype == MH_DSYM); 1093 lldb::user_id_t segID = 0; 1094 lldb::user_id_t sectID = 0; 1095 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 1096 uint32_t i; 1097 const bool is_core = GetType() == eTypeCoreFile; 1098 //bool dump_sections = false; 1099 ModuleSP module_sp (GetModule()); 1100 // First look up any LC_ENCRYPTION_INFO load commands 1101 typedef RangeArray<uint32_t, uint32_t, 8> EncryptedFileRanges; 1102 EncryptedFileRanges encrypted_file_ranges; 1103 encryption_info_command encryption_cmd; 1104 for (i=0; i<m_header.ncmds; ++i) 1105 { 1106 const lldb::offset_t load_cmd_offset = offset; 1107 if (m_data.GetU32(&offset, &encryption_cmd, 2) == NULL) 1108 break; 1109 1110 if (encryption_cmd.cmd == LC_ENCRYPTION_INFO) 1111 { 1112 if (m_data.GetU32(&offset, &encryption_cmd.cryptoff, 3)) 1113 { 1114 if (encryption_cmd.cryptid != 0) 1115 { 1116 EncryptedFileRanges::Entry entry; 1117 entry.SetRangeBase(encryption_cmd.cryptoff); 1118 entry.SetByteSize(encryption_cmd.cryptsize); 1119 encrypted_file_ranges.Append(entry); 1120 } 1121 } 1122 } 1123 offset = load_cmd_offset + encryption_cmd.cmdsize; 1124 } 1125 1126 offset = MachHeaderSizeFromMagic(m_header.magic); 1127 1128 struct segment_command_64 load_cmd; 1129 for (i=0; i<m_header.ncmds; ++i) 1130 { 1131 const lldb::offset_t load_cmd_offset = offset; 1132 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL) 1133 break; 1134 1135 if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64) 1136 { 1137 if (m_data.GetU8(&offset, (uint8_t*)load_cmd.segname, 16)) 1138 { 1139 bool add_section = true; 1140 bool add_to_unified = true; 1141 ConstString const_segname (load_cmd.segname, std::min<size_t>(strlen(load_cmd.segname), sizeof(load_cmd.segname))); 1142 1143 SectionSP unified_section_sp(unified_section_list.FindSectionByName(const_segname)); 1144 if (is_dsym && unified_section_sp) 1145 { 1146 if (const_segname == GetSegmentNameLINKEDIT()) 1147 { 1148 // We need to keep the __LINKEDIT segment private to this object file only 1149 add_to_unified = false; 1150 } 1151 else 1152 { 1153 // This is the dSYM file and this section has already been created by 1154 // the object file, no need to create it. 1155 add_section = false; 1156 } 1157 } 1158 load_cmd.vmaddr = m_data.GetAddress(&offset); 1159 load_cmd.vmsize = m_data.GetAddress(&offset); 1160 load_cmd.fileoff = m_data.GetAddress(&offset); 1161 load_cmd.filesize = m_data.GetAddress(&offset); 1162 if (m_length != 0 && load_cmd.filesize != 0) 1163 { 1164 if (load_cmd.fileoff > m_length) 1165 { 1166 // We have a load command that says it extends past the end of hte file. This is likely 1167 // a corrupt file. We don't have any way to return an error condition here (this method 1168 // was likely invokved from something like ObjectFile::GetSectionList()) -- all we can do 1169 // is null out the SectionList vector and if a process has been set up, dump a message 1170 // to stdout. The most common case here is core file debugging with a truncated file. 1171 const char *lc_segment_name = load_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT"; 1172 module_sp->ReportWarning("load command %u %s has a fileoff (0x%" PRIx64 ") that extends beyond the end of the file (0x%" PRIx64 "), ignoring this section", 1173 i, 1174 lc_segment_name, 1175 load_cmd.fileoff, 1176 m_length); 1177 1178 load_cmd.fileoff = 0; 1179 load_cmd.filesize = 0; 1180 } 1181 1182 if (load_cmd.fileoff + load_cmd.filesize > m_length) 1183 { 1184 // We have a load command that says it extends past the end of hte file. This is likely 1185 // a corrupt file. We don't have any way to return an error condition here (this method 1186 // was likely invokved from something like ObjectFile::GetSectionList()) -- all we can do 1187 // is null out the SectionList vector and if a process has been set up, dump a message 1188 // to stdout. The most common case here is core file debugging with a truncated file. 1189 const char *lc_segment_name = load_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT"; 1190 GetModule()->ReportWarning("load command %u %s has a fileoff + filesize (0x%" PRIx64 ") that extends beyond the end of the file (0x%" PRIx64 "), the segment will be truncated to match", 1191 i, 1192 lc_segment_name, 1193 load_cmd.fileoff + load_cmd.filesize, 1194 m_length); 1195 1196 // Tuncase the length 1197 load_cmd.filesize = m_length - load_cmd.fileoff; 1198 } 1199 } 1200 if (m_data.GetU32(&offset, &load_cmd.maxprot, 4)) 1201 { 1202 1203 const bool segment_is_encrypted = (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0; 1204 1205 // Keep a list of mach segments around in case we need to 1206 // get at data that isn't stored in the abstracted Sections. 1207 m_mach_segments.push_back (load_cmd); 1208 1209 // Use a segment ID of the segment index shifted left by 8 so they 1210 // never conflict with any of the sections. 1211 SectionSP segment_sp; 1212 if (add_section && (const_segname || is_core)) 1213 { 1214 segment_sp.reset(new Section (module_sp, // Module to which this section belongs 1215 this, // Object file to which this sections belongs 1216 ++segID << 8, // Section ID is the 1 based segment index shifted right by 8 bits as not to collide with any of the 256 section IDs that are possible 1217 const_segname, // Name of this section 1218 eSectionTypeContainer, // This section is a container of other sections. 1219 load_cmd.vmaddr, // File VM address == addresses as they are found in the object file 1220 load_cmd.vmsize, // VM size in bytes of this section 1221 load_cmd.fileoff, // Offset to the data for this section in the file 1222 load_cmd.filesize, // Size in bytes of this section as found in the the file 1223 load_cmd.flags)); // Flags for this section 1224 1225 segment_sp->SetIsEncrypted (segment_is_encrypted); 1226 m_sections_ap->AddSection(segment_sp); 1227 if (add_to_unified) 1228 unified_section_list.AddSection(segment_sp); 1229 } 1230 else if (unified_section_sp) 1231 { 1232 if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) 1233 { 1234 // Check to see if the module was read from memory? 1235 if (module_sp->GetObjectFile()->GetHeaderAddress().IsValid()) 1236 { 1237 // We have a module that is in memory and needs to have its 1238 // file address adjusted. We need to do this because when we 1239 // load a file from memory, its addresses will be slid already, 1240 // yet the addresses in the new symbol file will still be unslid. 1241 // Since everything is stored as section offset, this shouldn't 1242 // cause any problems. 1243 1244 // Make sure we've parsed the symbol table from the 1245 // ObjectFile before we go around changing its Sections. 1246 module_sp->GetObjectFile()->GetSymtab(); 1247 // eh_frame would present the same problems but we parse that on 1248 // a per-function basis as-needed so it's more difficult to 1249 // remove its use of the Sections. Realistically, the environments 1250 // where this code path will be taken will not have eh_frame sections. 1251 1252 unified_section_sp->SetFileAddress(load_cmd.vmaddr); 1253 } 1254 } 1255 m_sections_ap->AddSection(unified_section_sp); 1256 } 1257 1258 struct section_64 sect64; 1259 ::memset (§64, 0, sizeof(sect64)); 1260 // Push a section into our mach sections for the section at 1261 // index zero (NO_SECT) if we don't have any mach sections yet... 1262 if (m_mach_sections.empty()) 1263 m_mach_sections.push_back(sect64); 1264 uint32_t segment_sect_idx; 1265 const lldb::user_id_t first_segment_sectID = sectID + 1; 1266 1267 1268 const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8; 1269 for (segment_sect_idx=0; segment_sect_idx<load_cmd.nsects; ++segment_sect_idx) 1270 { 1271 if (m_data.GetU8(&offset, (uint8_t*)sect64.sectname, sizeof(sect64.sectname)) == NULL) 1272 break; 1273 if (m_data.GetU8(&offset, (uint8_t*)sect64.segname, sizeof(sect64.segname)) == NULL) 1274 break; 1275 sect64.addr = m_data.GetAddress(&offset); 1276 sect64.size = m_data.GetAddress(&offset); 1277 1278 if (m_data.GetU32(&offset, §64.offset, num_u32s) == NULL) 1279 break; 1280 1281 // Keep a list of mach sections around in case we need to 1282 // get at data that isn't stored in the abstracted Sections. 1283 m_mach_sections.push_back (sect64); 1284 1285 if (add_section) 1286 { 1287 ConstString section_name (sect64.sectname, std::min<size_t>(strlen(sect64.sectname), sizeof(sect64.sectname))); 1288 if (!const_segname) 1289 { 1290 // We have a segment with no name so we need to conjure up 1291 // segments that correspond to the section's segname if there 1292 // isn't already such a section. If there is such a section, 1293 // we resize the section so that it spans all sections. 1294 // We also mark these sections as fake so address matches don't 1295 // hit if they land in the gaps between the child sections. 1296 const_segname.SetTrimmedCStringWithLength(sect64.segname, sizeof(sect64.segname)); 1297 segment_sp = unified_section_list.FindSectionByName (const_segname); 1298 if (segment_sp.get()) 1299 { 1300 Section *segment = segment_sp.get(); 1301 // Grow the section size as needed. 1302 const lldb::addr_t sect64_min_addr = sect64.addr; 1303 const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size; 1304 const lldb::addr_t curr_seg_byte_size = segment->GetByteSize(); 1305 const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress(); 1306 const lldb::addr_t curr_seg_max_addr = curr_seg_min_addr + curr_seg_byte_size; 1307 if (sect64_min_addr >= curr_seg_min_addr) 1308 { 1309 const lldb::addr_t new_seg_byte_size = sect64_max_addr - curr_seg_min_addr; 1310 // Only grow the section size if needed 1311 if (new_seg_byte_size > curr_seg_byte_size) 1312 segment->SetByteSize (new_seg_byte_size); 1313 } 1314 else 1315 { 1316 // We need to change the base address of the segment and 1317 // adjust the child section offsets for all existing children. 1318 const lldb::addr_t slide_amount = sect64_min_addr - curr_seg_min_addr; 1319 segment->Slide(slide_amount, false); 1320 segment->GetChildren().Slide(-slide_amount, false); 1321 segment->SetByteSize (curr_seg_max_addr - sect64_min_addr); 1322 } 1323 1324 // Grow the section size as needed. 1325 if (sect64.offset) 1326 { 1327 const lldb::addr_t segment_min_file_offset = segment->GetFileOffset(); 1328 const lldb::addr_t segment_max_file_offset = segment_min_file_offset + segment->GetFileSize(); 1329 1330 const lldb::addr_t section_min_file_offset = sect64.offset; 1331 const lldb::addr_t section_max_file_offset = section_min_file_offset + sect64.size; 1332 const lldb::addr_t new_file_offset = std::min (section_min_file_offset, segment_min_file_offset); 1333 const lldb::addr_t new_file_size = std::max (section_max_file_offset, segment_max_file_offset) - new_file_offset; 1334 segment->SetFileOffset (new_file_offset); 1335 segment->SetFileSize (new_file_size); 1336 } 1337 } 1338 else 1339 { 1340 // Create a fake section for the section's named segment 1341 segment_sp.reset(new Section (segment_sp, // Parent section 1342 module_sp, // Module to which this section belongs 1343 this, // Object file to which this section belongs 1344 ++segID << 8, // Section ID is the 1 based segment index shifted right by 8 bits as not to collide with any of the 256 section IDs that are possible 1345 const_segname, // Name of this section 1346 eSectionTypeContainer, // This section is a container of other sections. 1347 sect64.addr, // File VM address == addresses as they are found in the object file 1348 sect64.size, // VM size in bytes of this section 1349 sect64.offset, // Offset to the data for this section in the file 1350 sect64.offset ? sect64.size : 0, // Size in bytes of this section as found in the the file 1351 load_cmd.flags)); // Flags for this section 1352 segment_sp->SetIsFake(true); 1353 1354 m_sections_ap->AddSection(segment_sp); 1355 if (add_to_unified) 1356 unified_section_list.AddSection(segment_sp); 1357 segment_sp->SetIsEncrypted (segment_is_encrypted); 1358 } 1359 } 1360 assert (segment_sp.get()); 1361 1362 uint32_t mach_sect_type = sect64.flags & SECTION_TYPE; 1363 static ConstString g_sect_name_objc_data ("__objc_data"); 1364 static ConstString g_sect_name_objc_msgrefs ("__objc_msgrefs"); 1365 static ConstString g_sect_name_objc_selrefs ("__objc_selrefs"); 1366 static ConstString g_sect_name_objc_classrefs ("__objc_classrefs"); 1367 static ConstString g_sect_name_objc_superrefs ("__objc_superrefs"); 1368 static ConstString g_sect_name_objc_const ("__objc_const"); 1369 static ConstString g_sect_name_objc_classlist ("__objc_classlist"); 1370 static ConstString g_sect_name_cfstring ("__cfstring"); 1371 1372 static ConstString g_sect_name_dwarf_debug_abbrev ("__debug_abbrev"); 1373 static ConstString g_sect_name_dwarf_debug_aranges ("__debug_aranges"); 1374 static ConstString g_sect_name_dwarf_debug_frame ("__debug_frame"); 1375 static ConstString g_sect_name_dwarf_debug_info ("__debug_info"); 1376 static ConstString g_sect_name_dwarf_debug_line ("__debug_line"); 1377 static ConstString g_sect_name_dwarf_debug_loc ("__debug_loc"); 1378 static ConstString g_sect_name_dwarf_debug_macinfo ("__debug_macinfo"); 1379 static ConstString g_sect_name_dwarf_debug_pubnames ("__debug_pubnames"); 1380 static ConstString g_sect_name_dwarf_debug_pubtypes ("__debug_pubtypes"); 1381 static ConstString g_sect_name_dwarf_debug_ranges ("__debug_ranges"); 1382 static ConstString g_sect_name_dwarf_debug_str ("__debug_str"); 1383 static ConstString g_sect_name_dwarf_apple_names ("__apple_names"); 1384 static ConstString g_sect_name_dwarf_apple_types ("__apple_types"); 1385 static ConstString g_sect_name_dwarf_apple_namespaces ("__apple_namespac"); 1386 static ConstString g_sect_name_dwarf_apple_objc ("__apple_objc"); 1387 static ConstString g_sect_name_eh_frame ("__eh_frame"); 1388 static ConstString g_sect_name_DATA ("__DATA"); 1389 static ConstString g_sect_name_TEXT ("__TEXT"); 1390 1391 lldb::SectionType sect_type = eSectionTypeOther; 1392 1393 if (section_name == g_sect_name_dwarf_debug_abbrev) 1394 sect_type = eSectionTypeDWARFDebugAbbrev; 1395 else if (section_name == g_sect_name_dwarf_debug_aranges) 1396 sect_type = eSectionTypeDWARFDebugAranges; 1397 else if (section_name == g_sect_name_dwarf_debug_frame) 1398 sect_type = eSectionTypeDWARFDebugFrame; 1399 else if (section_name == g_sect_name_dwarf_debug_info) 1400 sect_type = eSectionTypeDWARFDebugInfo; 1401 else if (section_name == g_sect_name_dwarf_debug_line) 1402 sect_type = eSectionTypeDWARFDebugLine; 1403 else if (section_name == g_sect_name_dwarf_debug_loc) 1404 sect_type = eSectionTypeDWARFDebugLoc; 1405 else if (section_name == g_sect_name_dwarf_debug_macinfo) 1406 sect_type = eSectionTypeDWARFDebugMacInfo; 1407 else if (section_name == g_sect_name_dwarf_debug_pubnames) 1408 sect_type = eSectionTypeDWARFDebugPubNames; 1409 else if (section_name == g_sect_name_dwarf_debug_pubtypes) 1410 sect_type = eSectionTypeDWARFDebugPubTypes; 1411 else if (section_name == g_sect_name_dwarf_debug_ranges) 1412 sect_type = eSectionTypeDWARFDebugRanges; 1413 else if (section_name == g_sect_name_dwarf_debug_str) 1414 sect_type = eSectionTypeDWARFDebugStr; 1415 else if (section_name == g_sect_name_dwarf_apple_names) 1416 sect_type = eSectionTypeDWARFAppleNames; 1417 else if (section_name == g_sect_name_dwarf_apple_types) 1418 sect_type = eSectionTypeDWARFAppleTypes; 1419 else if (section_name == g_sect_name_dwarf_apple_namespaces) 1420 sect_type = eSectionTypeDWARFAppleNamespaces; 1421 else if (section_name == g_sect_name_dwarf_apple_objc) 1422 sect_type = eSectionTypeDWARFAppleObjC; 1423 else if (section_name == g_sect_name_objc_selrefs) 1424 sect_type = eSectionTypeDataCStringPointers; 1425 else if (section_name == g_sect_name_objc_msgrefs) 1426 sect_type = eSectionTypeDataObjCMessageRefs; 1427 else if (section_name == g_sect_name_eh_frame) 1428 sect_type = eSectionTypeEHFrame; 1429 else if (section_name == g_sect_name_cfstring) 1430 sect_type = eSectionTypeDataObjCCFStrings; 1431 else if (section_name == g_sect_name_objc_data || 1432 section_name == g_sect_name_objc_classrefs || 1433 section_name == g_sect_name_objc_superrefs || 1434 section_name == g_sect_name_objc_const || 1435 section_name == g_sect_name_objc_classlist) 1436 { 1437 sect_type = eSectionTypeDataPointers; 1438 } 1439 1440 if (sect_type == eSectionTypeOther) 1441 { 1442 switch (mach_sect_type) 1443 { 1444 // TODO: categorize sections by other flags for regular sections 1445 case S_REGULAR: 1446 if (segment_sp->GetName() == g_sect_name_TEXT) 1447 sect_type = eSectionTypeCode; 1448 else if (segment_sp->GetName() == g_sect_name_DATA) 1449 sect_type = eSectionTypeData; 1450 else 1451 sect_type = eSectionTypeOther; 1452 break; 1453 case S_ZEROFILL: sect_type = eSectionTypeZeroFill; break; 1454 case S_CSTRING_LITERALS: sect_type = eSectionTypeDataCString; break; // section with only literal C strings 1455 case S_4BYTE_LITERALS: sect_type = eSectionTypeData4; break; // section with only 4 byte literals 1456 case S_8BYTE_LITERALS: sect_type = eSectionTypeData8; break; // section with only 8 byte literals 1457 case S_LITERAL_POINTERS: sect_type = eSectionTypeDataPointers; break; // section with only pointers to literals 1458 case S_NON_LAZY_SYMBOL_POINTERS: sect_type = eSectionTypeDataPointers; break; // section with only non-lazy symbol pointers 1459 case S_LAZY_SYMBOL_POINTERS: sect_type = eSectionTypeDataPointers; break; // section with only lazy symbol pointers 1460 case S_SYMBOL_STUBS: sect_type = eSectionTypeCode; break; // section with only symbol stubs, byte size of stub in the reserved2 field 1461 case S_MOD_INIT_FUNC_POINTERS: sect_type = eSectionTypeDataPointers; break; // section with only function pointers for initialization 1462 case S_MOD_TERM_FUNC_POINTERS: sect_type = eSectionTypeDataPointers; break; // section with only function pointers for termination 1463 case S_COALESCED: sect_type = eSectionTypeOther; break; 1464 case S_GB_ZEROFILL: sect_type = eSectionTypeZeroFill; break; 1465 case S_INTERPOSING: sect_type = eSectionTypeCode; break; // section with only pairs of function pointers for interposing 1466 case S_16BYTE_LITERALS: sect_type = eSectionTypeData16; break; // section with only 16 byte literals 1467 case S_DTRACE_DOF: sect_type = eSectionTypeDebug; break; 1468 case S_LAZY_DYLIB_SYMBOL_POINTERS: sect_type = eSectionTypeDataPointers; break; 1469 default: break; 1470 } 1471 } 1472 1473 SectionSP section_sp(new Section (segment_sp, 1474 module_sp, 1475 this, 1476 ++sectID, 1477 section_name, 1478 sect_type, 1479 sect64.addr - segment_sp->GetFileAddress(), 1480 sect64.size, 1481 sect64.offset, 1482 sect64.offset == 0 ? 0 : sect64.size, 1483 sect64.flags)); 1484 // Set the section to be encrypted to match the segment 1485 1486 bool section_is_encrypted = false; 1487 if (!segment_is_encrypted && load_cmd.filesize != 0) 1488 section_is_encrypted = encrypted_file_ranges.FindEntryThatContains(sect64.offset) != NULL; 1489 1490 section_sp->SetIsEncrypted (segment_is_encrypted || section_is_encrypted); 1491 segment_sp->GetChildren().AddSection(section_sp); 1492 1493 if (segment_sp->IsFake()) 1494 { 1495 segment_sp.reset(); 1496 const_segname.Clear(); 1497 } 1498 } 1499 } 1500 if (segment_sp && is_dsym) 1501 { 1502 if (first_segment_sectID <= sectID) 1503 { 1504 lldb::user_id_t sect_uid; 1505 for (sect_uid = first_segment_sectID; sect_uid <= sectID; ++sect_uid) 1506 { 1507 SectionSP curr_section_sp(segment_sp->GetChildren().FindSectionByID (sect_uid)); 1508 SectionSP next_section_sp; 1509 if (sect_uid + 1 <= sectID) 1510 next_section_sp = segment_sp->GetChildren().FindSectionByID (sect_uid+1); 1511 1512 if (curr_section_sp.get()) 1513 { 1514 if (curr_section_sp->GetByteSize() == 0) 1515 { 1516 if (next_section_sp.get() != NULL) 1517 curr_section_sp->SetByteSize ( next_section_sp->GetFileAddress() - curr_section_sp->GetFileAddress() ); 1518 else 1519 curr_section_sp->SetByteSize ( load_cmd.vmsize ); 1520 } 1521 } 1522 } 1523 } 1524 } 1525 } 1526 } 1527 } 1528 else if (load_cmd.cmd == LC_DYSYMTAB) 1529 { 1530 m_dysymtab.cmd = load_cmd.cmd; 1531 m_dysymtab.cmdsize = load_cmd.cmdsize; 1532 m_data.GetU32 (&offset, &m_dysymtab.ilocalsym, (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2); 1533 } 1534 1535 offset = load_cmd_offset + load_cmd.cmdsize; 1536 } 1537 1538 // StreamFile s(stdout, false); // REMOVE THIS LINE 1539 // s.Printf ("Sections for %s:\n", m_file.GetPath().c_str());// REMOVE THIS LINE 1540 // m_sections_ap->Dump(&s, NULL, true, UINT32_MAX);// REMOVE THIS LINE 1541 } 1542 } 1543 1544 class MachSymtabSectionInfo 1545 { 1546 public: 1547 1548 MachSymtabSectionInfo (SectionList *section_list) : 1549 m_section_list (section_list), 1550 m_section_infos() 1551 { 1552 // Get the number of sections down to a depth of 1 to include 1553 // all segments and their sections, but no other sections that 1554 // may be added for debug map or 1555 m_section_infos.resize(section_list->GetNumSections(1)); 1556 } 1557 1558 1559 SectionSP 1560 GetSection (uint8_t n_sect, addr_t file_addr) 1561 { 1562 if (n_sect == 0) 1563 return SectionSP(); 1564 if (n_sect < m_section_infos.size()) 1565 { 1566 if (!m_section_infos[n_sect].section_sp) 1567 { 1568 SectionSP section_sp (m_section_list->FindSectionByID (n_sect)); 1569 m_section_infos[n_sect].section_sp = section_sp; 1570 if (section_sp) 1571 { 1572 m_section_infos[n_sect].vm_range.SetBaseAddress (section_sp->GetFileAddress()); 1573 m_section_infos[n_sect].vm_range.SetByteSize (section_sp->GetByteSize()); 1574 } 1575 else 1576 { 1577 Host::SystemLog (Host::eSystemLogError, "error: unable to find section for section %u\n", n_sect); 1578 } 1579 } 1580 if (m_section_infos[n_sect].vm_range.Contains(file_addr)) 1581 { 1582 // Symbol is in section. 1583 return m_section_infos[n_sect].section_sp; 1584 } 1585 else if (m_section_infos[n_sect].vm_range.GetByteSize () == 0 && 1586 m_section_infos[n_sect].vm_range.GetBaseAddress() == file_addr) 1587 { 1588 // Symbol is in section with zero size, but has the same start 1589 // address as the section. This can happen with linker symbols 1590 // (symbols that start with the letter 'l' or 'L'. 1591 return m_section_infos[n_sect].section_sp; 1592 } 1593 } 1594 return m_section_list->FindSectionContainingFileAddress(file_addr); 1595 } 1596 1597 protected: 1598 struct SectionInfo 1599 { 1600 SectionInfo () : 1601 vm_range(), 1602 section_sp () 1603 { 1604 } 1605 1606 VMRange vm_range; 1607 SectionSP section_sp; 1608 }; 1609 SectionList *m_section_list; 1610 std::vector<SectionInfo> m_section_infos; 1611 }; 1612 1613 struct TrieEntry 1614 { 1615 TrieEntry () : 1616 name(), 1617 address(LLDB_INVALID_ADDRESS), 1618 flags (0), 1619 other(0), 1620 import_name() 1621 { 1622 } 1623 1624 void 1625 Clear () 1626 { 1627 name.Clear(); 1628 address = LLDB_INVALID_ADDRESS; 1629 flags = 0; 1630 other = 0; 1631 import_name.Clear(); 1632 } 1633 1634 void 1635 Dump () const 1636 { 1637 printf ("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"", 1638 static_cast<unsigned long long>(address), 1639 static_cast<unsigned long long>(flags), 1640 static_cast<unsigned long long>(other), name.GetCString()); 1641 if (import_name) 1642 printf (" -> \"%s\"\n", import_name.GetCString()); 1643 else 1644 printf ("\n"); 1645 } 1646 ConstString name; 1647 uint64_t address; 1648 uint64_t flags; 1649 uint64_t other; 1650 ConstString import_name; 1651 }; 1652 1653 struct TrieEntryWithOffset 1654 { 1655 lldb::offset_t nodeOffset; 1656 TrieEntry entry; 1657 1658 TrieEntryWithOffset (lldb::offset_t offset) : 1659 nodeOffset (offset), 1660 entry() 1661 { 1662 } 1663 1664 void 1665 Dump (uint32_t idx) const 1666 { 1667 printf ("[%3u] 0x%16.16llx: ", idx, 1668 static_cast<unsigned long long>(nodeOffset)); 1669 entry.Dump(); 1670 } 1671 1672 bool 1673 operator<(const TrieEntryWithOffset& other) const 1674 { 1675 return ( nodeOffset < other.nodeOffset ); 1676 } 1677 }; 1678 1679 static void 1680 ParseTrieEntries (DataExtractor &data, 1681 lldb::offset_t offset, 1682 std::vector<llvm::StringRef> &nameSlices, 1683 std::set<lldb::addr_t> &resolver_addresses, 1684 std::vector<TrieEntryWithOffset>& output) 1685 { 1686 if (!data.ValidOffset(offset)) 1687 return; 1688 1689 const uint64_t terminalSize = data.GetULEB128(&offset); 1690 lldb::offset_t children_offset = offset + terminalSize; 1691 if ( terminalSize != 0 ) { 1692 TrieEntryWithOffset e (offset); 1693 e.entry.flags = data.GetULEB128(&offset); 1694 const char *import_name = NULL; 1695 if ( e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT ) { 1696 e.entry.address = 0; 1697 e.entry.other = data.GetULEB128(&offset); // dylib ordinal 1698 import_name = data.GetCStr(&offset); 1699 } 1700 else { 1701 e.entry.address = data.GetULEB128(&offset); 1702 if ( e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER ) 1703 { 1704 //resolver_addresses.insert(e.entry.address); 1705 e.entry.other = data.GetULEB128(&offset); 1706 resolver_addresses.insert(e.entry.other); 1707 } 1708 else 1709 e.entry.other = 0; 1710 } 1711 // Only add symbols that are reexport symbols with a valid import name 1712 if (EXPORT_SYMBOL_FLAGS_REEXPORT & e.entry.flags && import_name && import_name[0]) 1713 { 1714 std::string name; 1715 if (!nameSlices.empty()) 1716 { 1717 for (auto name_slice: nameSlices) 1718 name.append(name_slice.data(), name_slice.size()); 1719 } 1720 if (name.size() > 1) 1721 { 1722 // Skip the leading '_' 1723 e.entry.name.SetCStringWithLength(name.c_str() + 1,name.size() - 1); 1724 } 1725 if (import_name) 1726 { 1727 // Skip the leading '_' 1728 e.entry.import_name.SetCString(import_name+1); 1729 } 1730 output.push_back(e); 1731 } 1732 } 1733 1734 const uint8_t childrenCount = data.GetU8(&children_offset); 1735 for (uint8_t i=0; i < childrenCount; ++i) { 1736 nameSlices.push_back(data.GetCStr(&children_offset)); 1737 lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset); 1738 if (childNodeOffset) 1739 { 1740 ParseTrieEntries(data, 1741 childNodeOffset, 1742 nameSlices, 1743 resolver_addresses, 1744 output); 1745 } 1746 nameSlices.pop_back(); 1747 } 1748 } 1749 1750 size_t 1751 ObjectFileMachO::ParseSymtab () 1752 { 1753 Timer scoped_timer(__PRETTY_FUNCTION__, 1754 "ObjectFileMachO::ParseSymtab () module = %s", 1755 m_file.GetFilename().AsCString("")); 1756 ModuleSP module_sp (GetModule()); 1757 if (!module_sp) 1758 return 0; 1759 1760 struct symtab_command symtab_load_command = { 0, 0, 0, 0, 0, 0 }; 1761 struct linkedit_data_command function_starts_load_command = { 0, 0, 0, 0 }; 1762 struct dyld_info_command dyld_info = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 1763 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts; 1764 FunctionStarts function_starts; 1765 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 1766 uint32_t i; 1767 FileSpecList dylib_files; 1768 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SYMBOLS)); 1769 1770 for (i=0; i<m_header.ncmds; ++i) 1771 { 1772 const lldb::offset_t cmd_offset = offset; 1773 // Read in the load command and load command size 1774 struct load_command lc; 1775 if (m_data.GetU32(&offset, &lc, 2) == NULL) 1776 break; 1777 // Watch for the symbol table load command 1778 switch (lc.cmd) 1779 { 1780 case LC_SYMTAB: 1781 symtab_load_command.cmd = lc.cmd; 1782 symtab_load_command.cmdsize = lc.cmdsize; 1783 // Read in the rest of the symtab load command 1784 if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) == 0) // fill in symoff, nsyms, stroff, strsize fields 1785 return 0; 1786 if (symtab_load_command.symoff == 0) 1787 { 1788 if (log) 1789 module_sp->LogMessage(log, "LC_SYMTAB.symoff == 0"); 1790 return 0; 1791 } 1792 1793 if (symtab_load_command.stroff == 0) 1794 { 1795 if (log) 1796 module_sp->LogMessage(log, "LC_SYMTAB.stroff == 0"); 1797 return 0; 1798 } 1799 1800 if (symtab_load_command.nsyms == 0) 1801 { 1802 if (log) 1803 module_sp->LogMessage(log, "LC_SYMTAB.nsyms == 0"); 1804 return 0; 1805 } 1806 1807 if (symtab_load_command.strsize == 0) 1808 { 1809 if (log) 1810 module_sp->LogMessage(log, "LC_SYMTAB.strsize == 0"); 1811 return 0; 1812 } 1813 break; 1814 1815 case LC_DYLD_INFO: 1816 case LC_DYLD_INFO_ONLY: 1817 if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) 1818 { 1819 dyld_info.cmd = lc.cmd; 1820 dyld_info.cmdsize = lc.cmdsize; 1821 } 1822 else 1823 { 1824 memset (&dyld_info, 0, sizeof(dyld_info)); 1825 } 1826 break; 1827 1828 case LC_LOAD_DYLIB: 1829 case LC_LOAD_WEAK_DYLIB: 1830 case LC_REEXPORT_DYLIB: 1831 case LC_LOADFVMLIB: 1832 case LC_LOAD_UPWARD_DYLIB: 1833 { 1834 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset); 1835 const char *path = m_data.PeekCStr(name_offset); 1836 if (path) 1837 { 1838 FileSpec file_spec(path, false); 1839 // Strip the path if there is @rpath, @executanble, etc so we just use the basename 1840 if (path[0] == '@') 1841 file_spec.GetDirectory().Clear(); 1842 1843 if (lc.cmd == LC_REEXPORT_DYLIB) 1844 { 1845 m_reexported_dylibs.AppendIfUnique(file_spec); 1846 } 1847 1848 dylib_files.Append(file_spec); 1849 } 1850 } 1851 break; 1852 1853 case LC_FUNCTION_STARTS: 1854 function_starts_load_command.cmd = lc.cmd; 1855 function_starts_load_command.cmdsize = lc.cmdsize; 1856 if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) == NULL) // fill in symoff, nsyms, stroff, strsize fields 1857 memset (&function_starts_load_command, 0, sizeof(function_starts_load_command)); 1858 break; 1859 1860 default: 1861 break; 1862 } 1863 offset = cmd_offset + lc.cmdsize; 1864 } 1865 1866 if (symtab_load_command.cmd) 1867 { 1868 Symtab *symtab = m_symtab_ap.get(); 1869 SectionList *section_list = GetSectionList(); 1870 if (section_list == NULL) 1871 return 0; 1872 1873 const uint32_t addr_byte_size = m_data.GetAddressByteSize(); 1874 const ByteOrder byte_order = m_data.GetByteOrder(); 1875 bool bit_width_32 = addr_byte_size == 4; 1876 const size_t nlist_byte_size = bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64); 1877 1878 DataExtractor nlist_data (NULL, 0, byte_order, addr_byte_size); 1879 DataExtractor strtab_data (NULL, 0, byte_order, addr_byte_size); 1880 DataExtractor function_starts_data (NULL, 0, byte_order, addr_byte_size); 1881 DataExtractor indirect_symbol_index_data (NULL, 0, byte_order, addr_byte_size); 1882 DataExtractor dyld_trie_data (NULL, 0, byte_order, addr_byte_size); 1883 1884 const addr_t nlist_data_byte_size = symtab_load_command.nsyms * nlist_byte_size; 1885 const addr_t strtab_data_byte_size = symtab_load_command.strsize; 1886 addr_t strtab_addr = LLDB_INVALID_ADDRESS; 1887 1888 ProcessSP process_sp (m_process_wp.lock()); 1889 Process *process = process_sp.get(); 1890 1891 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete; 1892 1893 if (process) 1894 { 1895 Target &target = process->GetTarget(); 1896 1897 memory_module_load_level = target.GetMemoryModuleLoadLevel(); 1898 1899 SectionSP linkedit_section_sp(section_list->FindSectionByName(GetSegmentNameLINKEDIT())); 1900 // Reading mach file from memory in a process or core file... 1901 1902 if (linkedit_section_sp) 1903 { 1904 const addr_t linkedit_load_addr = linkedit_section_sp->GetLoadBaseAddress(&target); 1905 const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset(); 1906 const addr_t symoff_addr = linkedit_load_addr + symtab_load_command.symoff - linkedit_file_offset; 1907 strtab_addr = linkedit_load_addr + symtab_load_command.stroff - linkedit_file_offset; 1908 1909 bool data_was_read = false; 1910 1911 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__)) 1912 if (m_header.flags & 0x80000000u && process->GetAddressByteSize() == sizeof (void*)) 1913 { 1914 // This mach-o memory file is in the dyld shared cache. If this 1915 // program is not remote and this is iOS, then this process will 1916 // share the same shared cache as the process we are debugging and 1917 // we can read the entire __LINKEDIT from the address space in this 1918 // process. This is a needed optimization that is used for local iOS 1919 // debugging only since all shared libraries in the shared cache do 1920 // not have corresponding files that exist in the file system of the 1921 // device. They have been combined into a single file. This means we 1922 // always have to load these files from memory. All of the symbol and 1923 // string tables from all of the __LINKEDIT sections from the shared 1924 // libraries in the shared cache have been merged into a single large 1925 // symbol and string table. Reading all of this symbol and string table 1926 // data across can slow down debug launch times, so we optimize this by 1927 // reading the memory for the __LINKEDIT section from this process. 1928 1929 UUID lldb_shared_cache(GetLLDBSharedCacheUUID()); 1930 UUID process_shared_cache(GetProcessSharedCacheUUID(process)); 1931 bool use_lldb_cache = true; 1932 if (lldb_shared_cache.IsValid() && process_shared_cache.IsValid() && lldb_shared_cache != process_shared_cache) 1933 { 1934 use_lldb_cache = false; 1935 ModuleSP module_sp (GetModule()); 1936 if (module_sp) 1937 module_sp->ReportWarning ("shared cache in process does not match lldb's own shared cache, startup will be slow."); 1938 1939 } 1940 1941 PlatformSP platform_sp (target.GetPlatform()); 1942 if (platform_sp && platform_sp->IsHost() && use_lldb_cache) 1943 { 1944 data_was_read = true; 1945 nlist_data.SetData((void *)symoff_addr, nlist_data_byte_size, eByteOrderLittle); 1946 strtab_data.SetData((void *)strtab_addr, strtab_data_byte_size, eByteOrderLittle); 1947 if (function_starts_load_command.cmd) 1948 { 1949 const addr_t func_start_addr = linkedit_load_addr + function_starts_load_command.dataoff - linkedit_file_offset; 1950 function_starts_data.SetData ((void *)func_start_addr, function_starts_load_command.datasize, eByteOrderLittle); 1951 } 1952 } 1953 } 1954 #endif 1955 1956 if (!data_was_read) 1957 { 1958 if (memory_module_load_level == eMemoryModuleLoadLevelComplete) 1959 { 1960 DataBufferSP nlist_data_sp (ReadMemory (process_sp, symoff_addr, nlist_data_byte_size)); 1961 if (nlist_data_sp) 1962 nlist_data.SetData (nlist_data_sp, 0, nlist_data_sp->GetByteSize()); 1963 // Load strings individually from memory when loading from memory since shared cache 1964 // string tables contain strings for all symbols from all shared cached libraries 1965 //DataBufferSP strtab_data_sp (ReadMemory (process_sp, strtab_addr, strtab_data_byte_size)); 1966 //if (strtab_data_sp) 1967 // strtab_data.SetData (strtab_data_sp, 0, strtab_data_sp->GetByteSize()); 1968 if (m_dysymtab.nindirectsyms != 0) 1969 { 1970 const addr_t indirect_syms_addr = linkedit_load_addr + m_dysymtab.indirectsymoff - linkedit_file_offset; 1971 DataBufferSP indirect_syms_data_sp (ReadMemory (process_sp, indirect_syms_addr, m_dysymtab.nindirectsyms * 4)); 1972 if (indirect_syms_data_sp) 1973 indirect_symbol_index_data.SetData (indirect_syms_data_sp, 0, indirect_syms_data_sp->GetByteSize()); 1974 } 1975 } 1976 1977 if (memory_module_load_level >= eMemoryModuleLoadLevelPartial) 1978 { 1979 if (function_starts_load_command.cmd) 1980 { 1981 const addr_t func_start_addr = linkedit_load_addr + function_starts_load_command.dataoff - linkedit_file_offset; 1982 DataBufferSP func_start_data_sp (ReadMemory (process_sp, func_start_addr, function_starts_load_command.datasize)); 1983 if (func_start_data_sp) 1984 function_starts_data.SetData (func_start_data_sp, 0, func_start_data_sp->GetByteSize()); 1985 } 1986 } 1987 } 1988 } 1989 } 1990 else 1991 { 1992 nlist_data.SetData (m_data, 1993 symtab_load_command.symoff, 1994 nlist_data_byte_size); 1995 strtab_data.SetData (m_data, 1996 symtab_load_command.stroff, 1997 strtab_data_byte_size); 1998 1999 if (dyld_info.export_size > 0) 2000 { 2001 dyld_trie_data.SetData (m_data, 2002 dyld_info.export_off, 2003 dyld_info.export_size); 2004 } 2005 2006 if (m_dysymtab.nindirectsyms != 0) 2007 { 2008 indirect_symbol_index_data.SetData (m_data, 2009 m_dysymtab.indirectsymoff, 2010 m_dysymtab.nindirectsyms * 4); 2011 } 2012 if (function_starts_load_command.cmd) 2013 { 2014 function_starts_data.SetData (m_data, 2015 function_starts_load_command.dataoff, 2016 function_starts_load_command.datasize); 2017 } 2018 } 2019 2020 if (nlist_data.GetByteSize() == 0 && memory_module_load_level == eMemoryModuleLoadLevelComplete) 2021 { 2022 if (log) 2023 module_sp->LogMessage(log, "failed to read nlist data"); 2024 return 0; 2025 } 2026 2027 2028 const bool have_strtab_data = strtab_data.GetByteSize() > 0; 2029 if (!have_strtab_data) 2030 { 2031 if (process) 2032 { 2033 if (strtab_addr == LLDB_INVALID_ADDRESS) 2034 { 2035 if (log) 2036 module_sp->LogMessage(log, "failed to locate the strtab in memory"); 2037 return 0; 2038 } 2039 } 2040 else 2041 { 2042 if (log) 2043 module_sp->LogMessage(log, "failed to read strtab data"); 2044 return 0; 2045 } 2046 } 2047 2048 const ConstString &g_segment_name_TEXT = GetSegmentNameTEXT(); 2049 const ConstString &g_segment_name_DATA = GetSegmentNameDATA(); 2050 const ConstString &g_segment_name_OBJC = GetSegmentNameOBJC(); 2051 const ConstString &g_section_name_eh_frame = GetSectionNameEHFrame(); 2052 SectionSP text_section_sp(section_list->FindSectionByName(g_segment_name_TEXT)); 2053 SectionSP data_section_sp(section_list->FindSectionByName(g_segment_name_DATA)); 2054 SectionSP objc_section_sp(section_list->FindSectionByName(g_segment_name_OBJC)); 2055 SectionSP eh_frame_section_sp; 2056 if (text_section_sp.get()) 2057 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName (g_section_name_eh_frame); 2058 else 2059 eh_frame_section_sp = section_list->FindSectionByName (g_section_name_eh_frame); 2060 2061 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM); 2062 2063 // lldb works best if it knows the start addresss of all functions in a module. 2064 // Linker symbols or debug info are normally the best source of information for start addr / size but 2065 // they may be stripped in a released binary. 2066 // Two additional sources of information exist in Mach-O binaries: 2067 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each function's start address in the 2068 // binary, relative to the text section. 2069 // eh_frame - the eh_frame FDEs have the start addr & size of each function 2070 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on all modern binaries. 2071 // Binaries built to run on older releases may need to use eh_frame information. 2072 2073 if (text_section_sp && function_starts_data.GetByteSize()) 2074 { 2075 FunctionStarts::Entry function_start_entry; 2076 function_start_entry.data = false; 2077 lldb::offset_t function_start_offset = 0; 2078 function_start_entry.addr = text_section_sp->GetFileAddress(); 2079 uint64_t delta; 2080 while ((delta = function_starts_data.GetULEB128(&function_start_offset)) > 0) 2081 { 2082 // Now append the current entry 2083 function_start_entry.addr += delta; 2084 function_starts.Append(function_start_entry); 2085 } 2086 } 2087 else 2088 { 2089 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the load command claiming an eh_frame 2090 // but it doesn't actually have the eh_frame content. And if we have a dSYM, we don't need to do any 2091 // of this fill-in-the-missing-symbols works anyway - the debug info should give us all the functions in 2092 // the module. 2093 if (text_section_sp.get() && eh_frame_section_sp.get() && m_type != eTypeDebugInfo) 2094 { 2095 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp, eRegisterKindGCC, true); 2096 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions; 2097 eh_frame.GetFunctionAddressAndSizeVector (functions); 2098 addr_t text_base_addr = text_section_sp->GetFileAddress(); 2099 size_t count = functions.GetSize(); 2100 for (size_t i = 0; i < count; ++i) 2101 { 2102 const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func = functions.GetEntryAtIndex (i); 2103 if (func) 2104 { 2105 FunctionStarts::Entry function_start_entry; 2106 function_start_entry.addr = func->base - text_base_addr; 2107 function_starts.Append(function_start_entry); 2108 } 2109 } 2110 } 2111 } 2112 2113 const size_t function_starts_count = function_starts.GetSize(); 2114 2115 const user_id_t TEXT_eh_frame_sectID = eh_frame_section_sp.get() ? eh_frame_section_sp->GetID() : NO_SECT; 2116 2117 lldb::offset_t nlist_data_offset = 0; 2118 2119 uint32_t N_SO_index = UINT32_MAX; 2120 2121 MachSymtabSectionInfo section_info (section_list); 2122 std::vector<uint32_t> N_FUN_indexes; 2123 std::vector<uint32_t> N_NSYM_indexes; 2124 std::vector<uint32_t> N_INCL_indexes; 2125 std::vector<uint32_t> N_BRAC_indexes; 2126 std::vector<uint32_t> N_COMM_indexes; 2127 typedef std::multimap <uint64_t, uint32_t> ValueToSymbolIndexMap; 2128 typedef std::map <uint32_t, uint32_t> NListIndexToSymbolIndexMap; 2129 typedef std::map <const char *, uint32_t> ConstNameToSymbolIndexMap; 2130 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx; 2131 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx; 2132 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx; 2133 // Any symbols that get merged into another will get an entry 2134 // in this map so we know 2135 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx; 2136 uint32_t nlist_idx = 0; 2137 Symbol *symbol_ptr = NULL; 2138 2139 uint32_t sym_idx = 0; 2140 Symbol *sym = NULL; 2141 size_t num_syms = 0; 2142 std::string memory_symbol_name; 2143 uint32_t unmapped_local_symbols_found = 0; 2144 2145 std::vector<TrieEntryWithOffset> trie_entries; 2146 std::set<lldb::addr_t> resolver_addresses; 2147 2148 if (dyld_trie_data.GetByteSize() > 0) 2149 { 2150 std::vector<llvm::StringRef> nameSlices; 2151 ParseTrieEntries (dyld_trie_data, 2152 0, 2153 nameSlices, 2154 resolver_addresses, 2155 trie_entries); 2156 2157 ConstString text_segment_name ("__TEXT"); 2158 SectionSP text_segment_sp = GetSectionList()->FindSectionByName(text_segment_name); 2159 if (text_segment_sp) 2160 { 2161 const lldb::addr_t text_segment_file_addr = text_segment_sp->GetFileAddress(); 2162 if (text_segment_file_addr != LLDB_INVALID_ADDRESS) 2163 { 2164 for (auto &e : trie_entries) 2165 e.entry.address += text_segment_file_addr; 2166 } 2167 } 2168 } 2169 2170 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__)) 2171 2172 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been optimized by moving LOCAL 2173 // symbols out of the memory mapped portion of the DSC. The symbol information has all been retained, 2174 // but it isn't available in the normal nlist data. However, there *are* duplicate entries of *some* 2175 // LOCAL symbols in the normal nlist data. To handle this situation correctly, we must first attempt 2176 // to parse any DSC unmapped symbol information. If we find any, we set a flag that tells the normal 2177 // nlist parser to ignore all LOCAL symbols. 2178 2179 if (m_header.flags & 0x80000000u) 2180 { 2181 // Before we can start mapping the DSC, we need to make certain the target process is actually 2182 // using the cache we can find. 2183 2184 // Next we need to determine the correct path for the dyld shared cache. 2185 2186 ArchSpec header_arch; 2187 GetArchitecture(header_arch); 2188 char dsc_path[PATH_MAX]; 2189 2190 snprintf(dsc_path, sizeof(dsc_path), "%s%s%s", 2191 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR */ 2192 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */ 2193 header_arch.GetArchitectureName()); 2194 2195 FileSpec dsc_filespec(dsc_path, false); 2196 2197 // We need definitions of two structures in the on-disk DSC, copy them here manually 2198 struct lldb_copy_dyld_cache_header_v0 2199 { 2200 char magic[16]; // e.g. "dyld_v0 i386", "dyld_v1 armv7", etc. 2201 uint32_t mappingOffset; // file offset to first dyld_cache_mapping_info 2202 uint32_t mappingCount; // number of dyld_cache_mapping_info entries 2203 uint32_t imagesOffset; 2204 uint32_t imagesCount; 2205 uint64_t dyldBaseAddress; 2206 uint64_t codeSignatureOffset; 2207 uint64_t codeSignatureSize; 2208 uint64_t slideInfoOffset; 2209 uint64_t slideInfoSize; 2210 uint64_t localSymbolsOffset; // file offset of where local symbols are stored 2211 uint64_t localSymbolsSize; // size of local symbols information 2212 }; 2213 struct lldb_copy_dyld_cache_header_v1 2214 { 2215 char magic[16]; // e.g. "dyld_v0 i386", "dyld_v1 armv7", etc. 2216 uint32_t mappingOffset; // file offset to first dyld_cache_mapping_info 2217 uint32_t mappingCount; // number of dyld_cache_mapping_info entries 2218 uint32_t imagesOffset; 2219 uint32_t imagesCount; 2220 uint64_t dyldBaseAddress; 2221 uint64_t codeSignatureOffset; 2222 uint64_t codeSignatureSize; 2223 uint64_t slideInfoOffset; 2224 uint64_t slideInfoSize; 2225 uint64_t localSymbolsOffset; 2226 uint64_t localSymbolsSize; 2227 uint8_t uuid[16]; // v1 and above, also recorded in dyld_all_image_infos v13 and later 2228 }; 2229 2230 struct lldb_copy_dyld_cache_mapping_info 2231 { 2232 uint64_t address; 2233 uint64_t size; 2234 uint64_t fileOffset; 2235 uint32_t maxProt; 2236 uint32_t initProt; 2237 }; 2238 2239 struct lldb_copy_dyld_cache_local_symbols_info 2240 { 2241 uint32_t nlistOffset; 2242 uint32_t nlistCount; 2243 uint32_t stringsOffset; 2244 uint32_t stringsSize; 2245 uint32_t entriesOffset; 2246 uint32_t entriesCount; 2247 }; 2248 struct lldb_copy_dyld_cache_local_symbols_entry 2249 { 2250 uint32_t dylibOffset; 2251 uint32_t nlistStartIndex; 2252 uint32_t nlistCount; 2253 }; 2254 2255 /* The dyld_cache_header has a pointer to the dyld_cache_local_symbols_info structure (localSymbolsOffset). 2256 The dyld_cache_local_symbols_info structure gives us three things: 2257 1. The start and count of the nlist records in the dyld_shared_cache file 2258 2. The start and size of the strings for these nlist records 2259 3. The start and count of dyld_cache_local_symbols_entry entries 2260 2261 There is one dyld_cache_local_symbols_entry per dylib/framework in the dyld shared cache. 2262 The "dylibOffset" field is the Mach-O header of this dylib/framework in the dyld shared cache. 2263 The dyld_cache_local_symbols_entry also lists the start of this dylib/framework's nlist records 2264 and the count of how many nlist records there are for this dylib/framework. 2265 */ 2266 2267 // Process the dsc header to find the unmapped symbols 2268 // 2269 // Save some VM space, do not map the entire cache in one shot. 2270 2271 DataBufferSP dsc_data_sp; 2272 dsc_data_sp = dsc_filespec.MemoryMapFileContents(0, sizeof(struct lldb_copy_dyld_cache_header_v1)); 2273 2274 if (dsc_data_sp) 2275 { 2276 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size); 2277 2278 char version_str[17]; 2279 int version = -1; 2280 lldb::offset_t offset = 0; 2281 memcpy (version_str, dsc_header_data.GetData (&offset, 16), 16); 2282 version_str[16] = '\0'; 2283 if (strncmp (version_str, "dyld_v", 6) == 0 && isdigit (version_str[6])) 2284 { 2285 int v; 2286 if (::sscanf (version_str + 6, "%d", &v) == 1) 2287 { 2288 version = v; 2289 } 2290 } 2291 2292 UUID dsc_uuid; 2293 if (version >= 1) 2294 { 2295 offset = offsetof (struct lldb_copy_dyld_cache_header_v1, uuid); 2296 uint8_t uuid_bytes[sizeof (uuid_t)]; 2297 memcpy (uuid_bytes, dsc_header_data.GetData (&offset, sizeof (uuid_t)), sizeof (uuid_t)); 2298 dsc_uuid.SetBytes (uuid_bytes); 2299 } 2300 2301 bool uuid_match = true; 2302 if (dsc_uuid.IsValid() && process) 2303 { 2304 UUID shared_cache_uuid(GetProcessSharedCacheUUID(process)); 2305 2306 if (shared_cache_uuid.IsValid() && dsc_uuid != shared_cache_uuid) 2307 { 2308 // The on-disk dyld_shared_cache file is not the same as the one in this 2309 // process' memory, don't use it. 2310 uuid_match = false; 2311 ModuleSP module_sp (GetModule()); 2312 if (module_sp) 2313 module_sp->ReportWarning ("process shared cache does not match on-disk dyld_shared_cache file, some symbol names will be missing."); 2314 } 2315 } 2316 2317 offset = offsetof (struct lldb_copy_dyld_cache_header_v1, mappingOffset); 2318 2319 uint32_t mappingOffset = dsc_header_data.GetU32(&offset); 2320 2321 // If the mappingOffset points to a location inside the header, we've 2322 // opened an old dyld shared cache, and should not proceed further. 2323 if (uuid_match && mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v0)) 2324 { 2325 2326 DataBufferSP dsc_mapping_info_data_sp = dsc_filespec.MemoryMapFileContents(mappingOffset, sizeof (struct lldb_copy_dyld_cache_mapping_info)); 2327 DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp, byte_order, addr_byte_size); 2328 offset = 0; 2329 2330 // The File addresses (from the in-memory Mach-O load commands) for the shared libraries 2331 // in the shared library cache need to be adjusted by an offset to match up with the 2332 // dylibOffset identifying field in the dyld_cache_local_symbol_entry's. This offset is 2333 // recorded in mapping_offset_value. 2334 const uint64_t mapping_offset_value = dsc_mapping_info_data.GetU64(&offset); 2335 2336 offset = offsetof (struct lldb_copy_dyld_cache_header_v1, localSymbolsOffset); 2337 uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset); 2338 uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset); 2339 2340 if (localSymbolsOffset && localSymbolsSize) 2341 { 2342 // Map the local symbols 2343 if (DataBufferSP dsc_local_symbols_data_sp = dsc_filespec.MemoryMapFileContents(localSymbolsOffset, localSymbolsSize)) 2344 { 2345 DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp, byte_order, addr_byte_size); 2346 2347 offset = 0; 2348 2349 // Read the local_symbols_infos struct in one shot 2350 struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info; 2351 dsc_local_symbols_data.GetU32(&offset, &local_symbols_info.nlistOffset, 6); 2352 2353 SectionSP text_section_sp(section_list->FindSectionByName(GetSegmentNameTEXT())); 2354 2355 uint32_t header_file_offset = (text_section_sp->GetFileAddress() - mapping_offset_value); 2356 2357 offset = local_symbols_info.entriesOffset; 2358 for (uint32_t entry_index = 0; entry_index < local_symbols_info.entriesCount; entry_index++) 2359 { 2360 struct lldb_copy_dyld_cache_local_symbols_entry local_symbols_entry; 2361 local_symbols_entry.dylibOffset = dsc_local_symbols_data.GetU32(&offset); 2362 local_symbols_entry.nlistStartIndex = dsc_local_symbols_data.GetU32(&offset); 2363 local_symbols_entry.nlistCount = dsc_local_symbols_data.GetU32(&offset); 2364 2365 if (header_file_offset == local_symbols_entry.dylibOffset) 2366 { 2367 unmapped_local_symbols_found = local_symbols_entry.nlistCount; 2368 2369 // The normal nlist code cannot correctly size the Symbols array, we need to allocate it here. 2370 sym = symtab->Resize (symtab_load_command.nsyms + m_dysymtab.nindirectsyms + unmapped_local_symbols_found - m_dysymtab.nlocalsym); 2371 num_syms = symtab->GetNumSymbols(); 2372 2373 nlist_data_offset = local_symbols_info.nlistOffset + (nlist_byte_size * local_symbols_entry.nlistStartIndex); 2374 uint32_t string_table_offset = local_symbols_info.stringsOffset; 2375 2376 for (uint32_t nlist_index = 0; nlist_index < local_symbols_entry.nlistCount; nlist_index++) 2377 { 2378 ///////////////////////////// 2379 { 2380 struct nlist_64 nlist; 2381 if (!dsc_local_symbols_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size)) 2382 break; 2383 2384 nlist.n_strx = dsc_local_symbols_data.GetU32_unchecked(&nlist_data_offset); 2385 nlist.n_type = dsc_local_symbols_data.GetU8_unchecked (&nlist_data_offset); 2386 nlist.n_sect = dsc_local_symbols_data.GetU8_unchecked (&nlist_data_offset); 2387 nlist.n_desc = dsc_local_symbols_data.GetU16_unchecked (&nlist_data_offset); 2388 nlist.n_value = dsc_local_symbols_data.GetAddress_unchecked (&nlist_data_offset); 2389 2390 SymbolType type = eSymbolTypeInvalid; 2391 const char *symbol_name = dsc_local_symbols_data.PeekCStr(string_table_offset + nlist.n_strx); 2392 2393 if (symbol_name == NULL) 2394 { 2395 // No symbol should be NULL, even the symbols with no 2396 // string values should have an offset zero which points 2397 // to an empty C-string 2398 Host::SystemLog (Host::eSystemLogError, 2399 "error: DSC unmapped local symbol[%u] has invalid string table offset 0x%x in %s, ignoring symbol\n", 2400 entry_index, 2401 nlist.n_strx, 2402 module_sp->GetFileSpec().GetPath().c_str()); 2403 continue; 2404 } 2405 if (symbol_name[0] == '\0') 2406 symbol_name = NULL; 2407 2408 const char *symbol_name_non_abi_mangled = NULL; 2409 2410 SectionSP symbol_section; 2411 uint32_t symbol_byte_size = 0; 2412 bool add_nlist = true; 2413 bool is_debug = ((nlist.n_type & N_STAB) != 0); 2414 bool demangled_is_synthesized = false; 2415 bool is_gsym = false; 2416 2417 assert (sym_idx < num_syms); 2418 2419 sym[sym_idx].SetDebug (is_debug); 2420 2421 if (is_debug) 2422 { 2423 switch (nlist.n_type) 2424 { 2425 case N_GSYM: 2426 // global symbol: name,,NO_SECT,type,0 2427 // Sometimes the N_GSYM value contains the address. 2428 2429 // FIXME: In the .o files, we have a GSYM and a debug symbol for all the ObjC data. They 2430 // have the same address, but we want to ensure that we always find only the real symbol, 2431 // 'cause we don't currently correctly attribute the GSYM one to the ObjCClass/Ivar/MetaClass 2432 // symbol type. This is a temporary hack to make sure the ObjectiveC symbols get treated 2433 // correctly. To do this right, we should coalesce all the GSYM & global symbols that have the 2434 // same address. 2435 2436 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O' 2437 && (strncmp (symbol_name, "_OBJC_IVAR_$_", strlen ("_OBJC_IVAR_$_")) == 0 2438 || strncmp (symbol_name, "_OBJC_CLASS_$_", strlen ("_OBJC_CLASS_$_")) == 0 2439 || strncmp (symbol_name, "_OBJC_METACLASS_$_", strlen ("_OBJC_METACLASS_$_")) == 0)) 2440 add_nlist = false; 2441 else 2442 { 2443 is_gsym = true; 2444 sym[sym_idx].SetExternal(true); 2445 if (nlist.n_value != 0) 2446 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 2447 type = eSymbolTypeData; 2448 } 2449 break; 2450 2451 case N_FNAME: 2452 // procedure name (f77 kludge): name,,NO_SECT,0,0 2453 type = eSymbolTypeCompiler; 2454 break; 2455 2456 case N_FUN: 2457 // procedure: name,,n_sect,linenumber,address 2458 if (symbol_name) 2459 { 2460 type = eSymbolTypeCode; 2461 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 2462 2463 N_FUN_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx)); 2464 // We use the current number of symbols in the symbol table in lieu of 2465 // using nlist_idx in case we ever start trimming entries out 2466 N_FUN_indexes.push_back(sym_idx); 2467 } 2468 else 2469 { 2470 type = eSymbolTypeCompiler; 2471 2472 if ( !N_FUN_indexes.empty() ) 2473 { 2474 // Copy the size of the function into the original STAB entry so we don't have 2475 // to hunt for it later 2476 symtab->SymbolAtIndex(N_FUN_indexes.back())->SetByteSize(nlist.n_value); 2477 N_FUN_indexes.pop_back(); 2478 // We don't really need the end function STAB as it contains the size which 2479 // we already placed with the original symbol, so don't add it if we want a 2480 // minimal symbol table 2481 add_nlist = false; 2482 } 2483 } 2484 break; 2485 2486 case N_STSYM: 2487 // static symbol: name,,n_sect,type,address 2488 N_STSYM_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx)); 2489 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 2490 type = eSymbolTypeData; 2491 break; 2492 2493 case N_LCSYM: 2494 // .lcomm symbol: name,,n_sect,type,address 2495 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 2496 type = eSymbolTypeCommonBlock; 2497 break; 2498 2499 case N_BNSYM: 2500 // We use the current number of symbols in the symbol table in lieu of 2501 // using nlist_idx in case we ever start trimming entries out 2502 // Skip these if we want minimal symbol tables 2503 add_nlist = false; 2504 break; 2505 2506 case N_ENSYM: 2507 // Set the size of the N_BNSYM to the terminating index of this N_ENSYM 2508 // so that we can always skip the entire symbol if we need to navigate 2509 // more quickly at the source level when parsing STABS 2510 // Skip these if we want minimal symbol tables 2511 add_nlist = false; 2512 break; 2513 2514 2515 case N_OPT: 2516 // emitted with gcc2_compiled and in gcc source 2517 type = eSymbolTypeCompiler; 2518 break; 2519 2520 case N_RSYM: 2521 // register sym: name,,NO_SECT,type,register 2522 type = eSymbolTypeVariable; 2523 break; 2524 2525 case N_SLINE: 2526 // src line: 0,,n_sect,linenumber,address 2527 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 2528 type = eSymbolTypeLineEntry; 2529 break; 2530 2531 case N_SSYM: 2532 // structure elt: name,,NO_SECT,type,struct_offset 2533 type = eSymbolTypeVariableType; 2534 break; 2535 2536 case N_SO: 2537 // source file name 2538 type = eSymbolTypeSourceFile; 2539 if (symbol_name == NULL) 2540 { 2541 add_nlist = false; 2542 if (N_SO_index != UINT32_MAX) 2543 { 2544 // Set the size of the N_SO to the terminating index of this N_SO 2545 // so that we can always skip the entire N_SO if we need to navigate 2546 // more quickly at the source level when parsing STABS 2547 symbol_ptr = symtab->SymbolAtIndex(N_SO_index); 2548 symbol_ptr->SetByteSize(sym_idx); 2549 symbol_ptr->SetSizeIsSibling(true); 2550 } 2551 N_NSYM_indexes.clear(); 2552 N_INCL_indexes.clear(); 2553 N_BRAC_indexes.clear(); 2554 N_COMM_indexes.clear(); 2555 N_FUN_indexes.clear(); 2556 N_SO_index = UINT32_MAX; 2557 } 2558 else 2559 { 2560 // We use the current number of symbols in the symbol table in lieu of 2561 // using nlist_idx in case we ever start trimming entries out 2562 const bool N_SO_has_full_path = symbol_name[0] == '/'; 2563 if (N_SO_has_full_path) 2564 { 2565 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) 2566 { 2567 // We have two consecutive N_SO entries where the first contains a directory 2568 // and the second contains a full path. 2569 sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name), false); 2570 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1; 2571 add_nlist = false; 2572 } 2573 else 2574 { 2575 // This is the first entry in a N_SO that contains a directory or 2576 // a full path to the source file 2577 N_SO_index = sym_idx; 2578 } 2579 } 2580 else if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) 2581 { 2582 // This is usually the second N_SO entry that contains just the filename, 2583 // so here we combine it with the first one if we are minimizing the symbol table 2584 const char *so_path = sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString(); 2585 if (so_path && so_path[0]) 2586 { 2587 std::string full_so_path (so_path); 2588 const size_t double_slash_pos = full_so_path.find("//"); 2589 if (double_slash_pos != std::string::npos) 2590 { 2591 // The linker has been generating bad N_SO entries with doubled up paths 2592 // in the format "%s%s" where the first string in the DW_AT_comp_dir, 2593 // and the second is the directory for the source file so you end up with 2594 // a path that looks like "/tmp/src//tmp/src/" 2595 FileSpec so_dir(so_path, false); 2596 if (!so_dir.Exists()) 2597 { 2598 so_dir.SetFile(&full_so_path[double_slash_pos + 1], false); 2599 if (so_dir.Exists()) 2600 { 2601 // Trim off the incorrect path 2602 full_so_path.erase(0, double_slash_pos + 1); 2603 } 2604 } 2605 } 2606 if (*full_so_path.rbegin() != '/') 2607 full_so_path += '/'; 2608 full_so_path += symbol_name; 2609 sym[sym_idx - 1].GetMangled().SetValue(ConstString(full_so_path.c_str()), false); 2610 add_nlist = false; 2611 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1; 2612 } 2613 } 2614 else 2615 { 2616 // This could be a relative path to a N_SO 2617 N_SO_index = sym_idx; 2618 } 2619 } 2620 break; 2621 2622 case N_OSO: 2623 // object file name: name,,0,0,st_mtime 2624 type = eSymbolTypeObjectFile; 2625 break; 2626 2627 case N_LSYM: 2628 // local sym: name,,NO_SECT,type,offset 2629 type = eSymbolTypeLocal; 2630 break; 2631 2632 //---------------------------------------------------------------------- 2633 // INCL scopes 2634 //---------------------------------------------------------------------- 2635 case N_BINCL: 2636 // include file beginning: name,,NO_SECT,0,sum 2637 // We use the current number of symbols in the symbol table in lieu of 2638 // using nlist_idx in case we ever start trimming entries out 2639 N_INCL_indexes.push_back(sym_idx); 2640 type = eSymbolTypeScopeBegin; 2641 break; 2642 2643 case N_EINCL: 2644 // include file end: name,,NO_SECT,0,0 2645 // Set the size of the N_BINCL to the terminating index of this N_EINCL 2646 // so that we can always skip the entire symbol if we need to navigate 2647 // more quickly at the source level when parsing STABS 2648 if ( !N_INCL_indexes.empty() ) 2649 { 2650 symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back()); 2651 symbol_ptr->SetByteSize(sym_idx + 1); 2652 symbol_ptr->SetSizeIsSibling(true); 2653 N_INCL_indexes.pop_back(); 2654 } 2655 type = eSymbolTypeScopeEnd; 2656 break; 2657 2658 case N_SOL: 2659 // #included file name: name,,n_sect,0,address 2660 type = eSymbolTypeHeaderFile; 2661 2662 // We currently don't use the header files on darwin 2663 add_nlist = false; 2664 break; 2665 2666 case N_PARAMS: 2667 // compiler parameters: name,,NO_SECT,0,0 2668 type = eSymbolTypeCompiler; 2669 break; 2670 2671 case N_VERSION: 2672 // compiler version: name,,NO_SECT,0,0 2673 type = eSymbolTypeCompiler; 2674 break; 2675 2676 case N_OLEVEL: 2677 // compiler -O level: name,,NO_SECT,0,0 2678 type = eSymbolTypeCompiler; 2679 break; 2680 2681 case N_PSYM: 2682 // parameter: name,,NO_SECT,type,offset 2683 type = eSymbolTypeVariable; 2684 break; 2685 2686 case N_ENTRY: 2687 // alternate entry: name,,n_sect,linenumber,address 2688 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 2689 type = eSymbolTypeLineEntry; 2690 break; 2691 2692 //---------------------------------------------------------------------- 2693 // Left and Right Braces 2694 //---------------------------------------------------------------------- 2695 case N_LBRAC: 2696 // left bracket: 0,,NO_SECT,nesting level,address 2697 // We use the current number of symbols in the symbol table in lieu of 2698 // using nlist_idx in case we ever start trimming entries out 2699 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 2700 N_BRAC_indexes.push_back(sym_idx); 2701 type = eSymbolTypeScopeBegin; 2702 break; 2703 2704 case N_RBRAC: 2705 // right bracket: 0,,NO_SECT,nesting level,address 2706 // Set the size of the N_LBRAC to the terminating index of this N_RBRAC 2707 // so that we can always skip the entire symbol if we need to navigate 2708 // more quickly at the source level when parsing STABS 2709 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 2710 if ( !N_BRAC_indexes.empty() ) 2711 { 2712 symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back()); 2713 symbol_ptr->SetByteSize(sym_idx + 1); 2714 symbol_ptr->SetSizeIsSibling(true); 2715 N_BRAC_indexes.pop_back(); 2716 } 2717 type = eSymbolTypeScopeEnd; 2718 break; 2719 2720 case N_EXCL: 2721 // deleted include file: name,,NO_SECT,0,sum 2722 type = eSymbolTypeHeaderFile; 2723 break; 2724 2725 //---------------------------------------------------------------------- 2726 // COMM scopes 2727 //---------------------------------------------------------------------- 2728 case N_BCOMM: 2729 // begin common: name,,NO_SECT,0,0 2730 // We use the current number of symbols in the symbol table in lieu of 2731 // using nlist_idx in case we ever start trimming entries out 2732 type = eSymbolTypeScopeBegin; 2733 N_COMM_indexes.push_back(sym_idx); 2734 break; 2735 2736 case N_ECOML: 2737 // end common (local name): 0,,n_sect,0,address 2738 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 2739 // Fall through 2740 2741 case N_ECOMM: 2742 // end common: name,,n_sect,0,0 2743 // Set the size of the N_BCOMM to the terminating index of this N_ECOMM/N_ECOML 2744 // so that we can always skip the entire symbol if we need to navigate 2745 // more quickly at the source level when parsing STABS 2746 if ( !N_COMM_indexes.empty() ) 2747 { 2748 symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back()); 2749 symbol_ptr->SetByteSize(sym_idx + 1); 2750 symbol_ptr->SetSizeIsSibling(true); 2751 N_COMM_indexes.pop_back(); 2752 } 2753 type = eSymbolTypeScopeEnd; 2754 break; 2755 2756 case N_LENG: 2757 // second stab entry with length information 2758 type = eSymbolTypeAdditional; 2759 break; 2760 2761 default: break; 2762 } 2763 } 2764 else 2765 { 2766 //uint8_t n_pext = N_PEXT & nlist.n_type; 2767 uint8_t n_type = N_TYPE & nlist.n_type; 2768 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0); 2769 2770 switch (n_type) 2771 { 2772 case N_INDR: // Fall through 2773 case N_PBUD: // Fall through 2774 case N_UNDF: 2775 type = eSymbolTypeUndefined; 2776 break; 2777 2778 case N_ABS: 2779 type = eSymbolTypeAbsolute; 2780 break; 2781 2782 case N_SECT: 2783 { 2784 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 2785 2786 if (symbol_section == NULL) 2787 { 2788 // TODO: warn about this? 2789 add_nlist = false; 2790 break; 2791 } 2792 2793 if (TEXT_eh_frame_sectID == nlist.n_sect) 2794 { 2795 type = eSymbolTypeException; 2796 } 2797 else 2798 { 2799 uint32_t section_type = symbol_section->Get() & SECTION_TYPE; 2800 2801 switch (section_type) 2802 { 2803 case S_REGULAR: break; // regular section 2804 //case S_ZEROFILL: type = eSymbolTypeData; break; // zero fill on demand section 2805 case S_CSTRING_LITERALS: type = eSymbolTypeData; break; // section with only literal C strings 2806 case S_4BYTE_LITERALS: type = eSymbolTypeData; break; // section with only 4 byte literals 2807 case S_8BYTE_LITERALS: type = eSymbolTypeData; break; // section with only 8 byte literals 2808 case S_LITERAL_POINTERS: type = eSymbolTypeTrampoline; break; // section with only pointers to literals 2809 case S_NON_LAZY_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break; // section with only non-lazy symbol pointers 2810 case S_LAZY_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break; // section with only lazy symbol pointers 2811 case S_SYMBOL_STUBS: type = eSymbolTypeTrampoline; break; // section with only symbol stubs, byte size of stub in the reserved2 field 2812 case S_MOD_INIT_FUNC_POINTERS: type = eSymbolTypeCode; break; // section with only function pointers for initialization 2813 case S_MOD_TERM_FUNC_POINTERS: type = eSymbolTypeCode; break; // section with only function pointers for termination 2814 //case S_COALESCED: type = eSymbolType; break; // section contains symbols that are to be coalesced 2815 //case S_GB_ZEROFILL: type = eSymbolTypeData; break; // zero fill on demand section (that can be larger than 4 gigabytes) 2816 case S_INTERPOSING: type = eSymbolTypeTrampoline; break; // section with only pairs of function pointers for interposing 2817 case S_16BYTE_LITERALS: type = eSymbolTypeData; break; // section with only 16 byte literals 2818 case S_DTRACE_DOF: type = eSymbolTypeInstrumentation; break; 2819 case S_LAZY_DYLIB_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break; 2820 default: break; 2821 } 2822 2823 if (type == eSymbolTypeInvalid) 2824 { 2825 const char *symbol_sect_name = symbol_section->GetName().AsCString(); 2826 if (symbol_section->IsDescendant (text_section_sp.get())) 2827 { 2828 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS | 2829 S_ATTR_SELF_MODIFYING_CODE | 2830 S_ATTR_SOME_INSTRUCTIONS)) 2831 type = eSymbolTypeData; 2832 else 2833 type = eSymbolTypeCode; 2834 } 2835 else if (symbol_section->IsDescendant(data_section_sp.get())) 2836 { 2837 if (symbol_sect_name && ::strstr (symbol_sect_name, "__objc") == symbol_sect_name) 2838 { 2839 type = eSymbolTypeRuntime; 2840 2841 if (symbol_name && 2842 symbol_name[0] == '_' && 2843 symbol_name[1] == 'O' && 2844 symbol_name[2] == 'B') 2845 { 2846 llvm::StringRef symbol_name_ref(symbol_name); 2847 static const llvm::StringRef g_objc_v2_prefix_class ("_OBJC_CLASS_$_"); 2848 static const llvm::StringRef g_objc_v2_prefix_metaclass ("_OBJC_METACLASS_$_"); 2849 static const llvm::StringRef g_objc_v2_prefix_ivar ("_OBJC_IVAR_$_"); 2850 if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) 2851 { 2852 symbol_name_non_abi_mangled = symbol_name + 1; 2853 symbol_name = symbol_name + g_objc_v2_prefix_class.size(); 2854 type = eSymbolTypeObjCClass; 2855 demangled_is_synthesized = true; 2856 } 2857 else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass)) 2858 { 2859 symbol_name_non_abi_mangled = symbol_name + 1; 2860 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size(); 2861 type = eSymbolTypeObjCMetaClass; 2862 demangled_is_synthesized = true; 2863 } 2864 else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) 2865 { 2866 symbol_name_non_abi_mangled = symbol_name + 1; 2867 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size(); 2868 type = eSymbolTypeObjCIVar; 2869 demangled_is_synthesized = true; 2870 } 2871 } 2872 } 2873 else if (symbol_sect_name && ::strstr (symbol_sect_name, "__gcc_except_tab") == symbol_sect_name) 2874 { 2875 type = eSymbolTypeException; 2876 } 2877 else 2878 { 2879 type = eSymbolTypeData; 2880 } 2881 } 2882 else if (symbol_sect_name && ::strstr (symbol_sect_name, "__IMPORT") == symbol_sect_name) 2883 { 2884 type = eSymbolTypeTrampoline; 2885 } 2886 else if (symbol_section->IsDescendant(objc_section_sp.get())) 2887 { 2888 type = eSymbolTypeRuntime; 2889 if (symbol_name && symbol_name[0] == '.') 2890 { 2891 llvm::StringRef symbol_name_ref(symbol_name); 2892 static const llvm::StringRef g_objc_v1_prefix_class (".objc_class_name_"); 2893 if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) 2894 { 2895 symbol_name_non_abi_mangled = symbol_name; 2896 symbol_name = symbol_name + g_objc_v1_prefix_class.size(); 2897 type = eSymbolTypeObjCClass; 2898 demangled_is_synthesized = true; 2899 } 2900 } 2901 } 2902 } 2903 } 2904 } 2905 break; 2906 } 2907 } 2908 2909 if (add_nlist) 2910 { 2911 uint64_t symbol_value = nlist.n_value; 2912 if (symbol_name_non_abi_mangled) 2913 { 2914 sym[sym_idx].GetMangled().SetMangledName (ConstString(symbol_name_non_abi_mangled)); 2915 sym[sym_idx].GetMangled().SetDemangledName (ConstString(symbol_name)); 2916 } 2917 else 2918 { 2919 bool symbol_name_is_mangled = false; 2920 2921 if (symbol_name && symbol_name[0] == '_') 2922 { 2923 symbol_name_is_mangled = symbol_name[1] == '_'; 2924 symbol_name++; // Skip the leading underscore 2925 } 2926 2927 if (symbol_name) 2928 { 2929 ConstString const_symbol_name(symbol_name); 2930 sym[sym_idx].GetMangled().SetValue(const_symbol_name, symbol_name_is_mangled); 2931 if (is_gsym && is_debug) 2932 N_GSYM_name_to_sym_idx[sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString()] = sym_idx; 2933 } 2934 } 2935 if (symbol_section) 2936 { 2937 const addr_t section_file_addr = symbol_section->GetFileAddress(); 2938 if (symbol_byte_size == 0 && function_starts_count > 0) 2939 { 2940 addr_t symbol_lookup_file_addr = nlist.n_value; 2941 // Do an exact address match for non-ARM addresses, else get the closest since 2942 // the symbol might be a thumb symbol which has an address with bit zero set 2943 FunctionStarts::Entry *func_start_entry = function_starts.FindEntry (symbol_lookup_file_addr, !is_arm); 2944 if (is_arm && func_start_entry) 2945 { 2946 // Verify that the function start address is the symbol address (ARM) 2947 // or the symbol address + 1 (thumb) 2948 if (func_start_entry->addr != symbol_lookup_file_addr && 2949 func_start_entry->addr != (symbol_lookup_file_addr + 1)) 2950 { 2951 // Not the right entry, NULL it out... 2952 func_start_entry = NULL; 2953 } 2954 } 2955 if (func_start_entry) 2956 { 2957 func_start_entry->data = true; 2958 2959 addr_t symbol_file_addr = func_start_entry->addr; 2960 uint32_t symbol_flags = 0; 2961 if (is_arm) 2962 { 2963 if (symbol_file_addr & 1) 2964 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB; 2965 symbol_file_addr &= 0xfffffffffffffffeull; 2966 } 2967 2968 const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry); 2969 const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize(); 2970 if (next_func_start_entry) 2971 { 2972 addr_t next_symbol_file_addr = next_func_start_entry->addr; 2973 // Be sure the clear the Thumb address bit when we calculate the size 2974 // from the current and next address 2975 if (is_arm) 2976 next_symbol_file_addr &= 0xfffffffffffffffeull; 2977 symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr); 2978 } 2979 else 2980 { 2981 symbol_byte_size = section_end_file_addr - symbol_file_addr; 2982 } 2983 } 2984 } 2985 symbol_value -= section_file_addr; 2986 } 2987 2988 if (is_debug == false) 2989 { 2990 if (type == eSymbolTypeCode) 2991 { 2992 // See if we can find a N_FUN entry for any code symbols. 2993 // If we do find a match, and the name matches, then we 2994 // can merge the two into just the function symbol to avoid 2995 // duplicate entries in the symbol table 2996 std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range; 2997 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value); 2998 if (range.first != range.second) 2999 { 3000 bool found_it = false; 3001 for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos) 3002 { 3003 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled)) 3004 { 3005 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second; 3006 // We just need the flags from the linker symbol, so put these flags 3007 // into the N_FUN flags to avoid duplicate symbols in the symbol table 3008 sym[pos->second].SetExternal(sym[sym_idx].IsExternal()); 3009 sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc); 3010 if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end()) 3011 sym[pos->second].SetType (eSymbolTypeResolver); 3012 sym[sym_idx].Clear(); 3013 found_it = true; 3014 break; 3015 } 3016 } 3017 if (found_it) 3018 continue; 3019 } 3020 else 3021 { 3022 if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end()) 3023 type = eSymbolTypeResolver; 3024 } 3025 } 3026 else if (type == eSymbolTypeData) 3027 { 3028 // See if we can find a N_STSYM entry for any data symbols. 3029 // If we do find a match, and the name matches, then we 3030 // can merge the two into just the Static symbol to avoid 3031 // duplicate entries in the symbol table 3032 std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range; 3033 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value); 3034 if (range.first != range.second) 3035 { 3036 bool found_it = false; 3037 for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos) 3038 { 3039 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled)) 3040 { 3041 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second; 3042 // We just need the flags from the linker symbol, so put these flags 3043 // into the N_STSYM flags to avoid duplicate symbols in the symbol table 3044 sym[pos->second].SetExternal(sym[sym_idx].IsExternal()); 3045 sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc); 3046 sym[sym_idx].Clear(); 3047 found_it = true; 3048 break; 3049 } 3050 } 3051 if (found_it) 3052 continue; 3053 } 3054 else 3055 { 3056 // Combine N_GSYM stab entries with the non stab symbol 3057 ConstNameToSymbolIndexMap::const_iterator pos = N_GSYM_name_to_sym_idx.find(sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString()); 3058 if (pos != N_GSYM_name_to_sym_idx.end()) 3059 { 3060 const uint32_t GSYM_sym_idx = pos->second; 3061 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx; 3062 // Copy the address, because often the N_GSYM address has an invalid address of zero 3063 // when the global is a common symbol 3064 sym[GSYM_sym_idx].GetAddress().SetSection (symbol_section); 3065 sym[GSYM_sym_idx].GetAddress().SetOffset (symbol_value); 3066 // We just need the flags from the linker symbol, so put these flags 3067 // into the N_STSYM flags to avoid duplicate symbols in the symbol table 3068 sym[GSYM_sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc); 3069 sym[sym_idx].Clear(); 3070 continue; 3071 } 3072 } 3073 } 3074 } 3075 3076 sym[sym_idx].SetID (nlist_idx); 3077 sym[sym_idx].SetType (type); 3078 sym[sym_idx].GetAddress().SetSection (symbol_section); 3079 sym[sym_idx].GetAddress().SetOffset (symbol_value); 3080 sym[sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc); 3081 3082 if (symbol_byte_size > 0) 3083 sym[sym_idx].SetByteSize(symbol_byte_size); 3084 3085 if (demangled_is_synthesized) 3086 sym[sym_idx].SetDemangledNameIsSynthesized(true); 3087 ++sym_idx; 3088 } 3089 else 3090 { 3091 sym[sym_idx].Clear(); 3092 } 3093 3094 } 3095 ///////////////////////////// 3096 } 3097 break; // No more entries to consider 3098 } 3099 } 3100 } 3101 } 3102 } 3103 } 3104 } 3105 3106 // Must reset this in case it was mutated above! 3107 nlist_data_offset = 0; 3108 #endif 3109 3110 if (nlist_data.GetByteSize() > 0) 3111 { 3112 3113 // If the sym array was not created while parsing the DSC unmapped 3114 // symbols, create it now. 3115 if (sym == NULL) 3116 { 3117 sym = symtab->Resize (symtab_load_command.nsyms + m_dysymtab.nindirectsyms); 3118 num_syms = symtab->GetNumSymbols(); 3119 } 3120 3121 if (unmapped_local_symbols_found) 3122 { 3123 assert(m_dysymtab.ilocalsym == 0); 3124 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size); 3125 nlist_idx = m_dysymtab.nlocalsym; 3126 } 3127 else 3128 { 3129 nlist_idx = 0; 3130 } 3131 3132 for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) 3133 { 3134 struct nlist_64 nlist; 3135 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size)) 3136 break; 3137 3138 nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset); 3139 nlist.n_type = nlist_data.GetU8_unchecked (&nlist_data_offset); 3140 nlist.n_sect = nlist_data.GetU8_unchecked (&nlist_data_offset); 3141 nlist.n_desc = nlist_data.GetU16_unchecked (&nlist_data_offset); 3142 nlist.n_value = nlist_data.GetAddress_unchecked (&nlist_data_offset); 3143 3144 SymbolType type = eSymbolTypeInvalid; 3145 const char *symbol_name = NULL; 3146 3147 if (have_strtab_data) 3148 { 3149 symbol_name = strtab_data.PeekCStr(nlist.n_strx); 3150 3151 if (symbol_name == NULL) 3152 { 3153 // No symbol should be NULL, even the symbols with no 3154 // string values should have an offset zero which points 3155 // to an empty C-string 3156 Host::SystemLog (Host::eSystemLogError, 3157 "error: symbol[%u] has invalid string table offset 0x%x in %s, ignoring symbol\n", 3158 nlist_idx, 3159 nlist.n_strx, 3160 module_sp->GetFileSpec().GetPath().c_str()); 3161 continue; 3162 } 3163 if (symbol_name[0] == '\0') 3164 symbol_name = NULL; 3165 } 3166 else 3167 { 3168 const addr_t str_addr = strtab_addr + nlist.n_strx; 3169 Error str_error; 3170 if (process->ReadCStringFromMemory(str_addr, memory_symbol_name, str_error)) 3171 symbol_name = memory_symbol_name.c_str(); 3172 } 3173 const char *symbol_name_non_abi_mangled = NULL; 3174 3175 SectionSP symbol_section; 3176 lldb::addr_t symbol_byte_size = 0; 3177 bool add_nlist = true; 3178 bool is_gsym = false; 3179 bool is_debug = ((nlist.n_type & N_STAB) != 0); 3180 bool demangled_is_synthesized = false; 3181 3182 assert (sym_idx < num_syms); 3183 3184 sym[sym_idx].SetDebug (is_debug); 3185 3186 if (is_debug) 3187 { 3188 switch (nlist.n_type) 3189 { 3190 case N_GSYM: 3191 // global symbol: name,,NO_SECT,type,0 3192 // Sometimes the N_GSYM value contains the address. 3193 3194 // FIXME: In the .o files, we have a GSYM and a debug symbol for all the ObjC data. They 3195 // have the same address, but we want to ensure that we always find only the real symbol, 3196 // 'cause we don't currently correctly attribute the GSYM one to the ObjCClass/Ivar/MetaClass 3197 // symbol type. This is a temporary hack to make sure the ObjectiveC symbols get treated 3198 // correctly. To do this right, we should coalesce all the GSYM & global symbols that have the 3199 // same address. 3200 3201 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O' 3202 && (strncmp (symbol_name, "_OBJC_IVAR_$_", strlen ("_OBJC_IVAR_$_")) == 0 3203 || strncmp (symbol_name, "_OBJC_CLASS_$_", strlen ("_OBJC_CLASS_$_")) == 0 3204 || strncmp (symbol_name, "_OBJC_METACLASS_$_", strlen ("_OBJC_METACLASS_$_")) == 0)) 3205 add_nlist = false; 3206 else 3207 { 3208 is_gsym = true; 3209 sym[sym_idx].SetExternal(true); 3210 if (nlist.n_value != 0) 3211 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 3212 type = eSymbolTypeData; 3213 } 3214 break; 3215 3216 case N_FNAME: 3217 // procedure name (f77 kludge): name,,NO_SECT,0,0 3218 type = eSymbolTypeCompiler; 3219 break; 3220 3221 case N_FUN: 3222 // procedure: name,,n_sect,linenumber,address 3223 if (symbol_name) 3224 { 3225 type = eSymbolTypeCode; 3226 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 3227 3228 N_FUN_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx)); 3229 // We use the current number of symbols in the symbol table in lieu of 3230 // using nlist_idx in case we ever start trimming entries out 3231 N_FUN_indexes.push_back(sym_idx); 3232 } 3233 else 3234 { 3235 type = eSymbolTypeCompiler; 3236 3237 if ( !N_FUN_indexes.empty() ) 3238 { 3239 // Copy the size of the function into the original STAB entry so we don't have 3240 // to hunt for it later 3241 symtab->SymbolAtIndex(N_FUN_indexes.back())->SetByteSize(nlist.n_value); 3242 N_FUN_indexes.pop_back(); 3243 // We don't really need the end function STAB as it contains the size which 3244 // we already placed with the original symbol, so don't add it if we want a 3245 // minimal symbol table 3246 add_nlist = false; 3247 } 3248 } 3249 break; 3250 3251 case N_STSYM: 3252 // static symbol: name,,n_sect,type,address 3253 N_STSYM_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx)); 3254 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 3255 type = eSymbolTypeData; 3256 break; 3257 3258 case N_LCSYM: 3259 // .lcomm symbol: name,,n_sect,type,address 3260 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 3261 type = eSymbolTypeCommonBlock; 3262 break; 3263 3264 case N_BNSYM: 3265 // We use the current number of symbols in the symbol table in lieu of 3266 // using nlist_idx in case we ever start trimming entries out 3267 // Skip these if we want minimal symbol tables 3268 add_nlist = false; 3269 break; 3270 3271 case N_ENSYM: 3272 // Set the size of the N_BNSYM to the terminating index of this N_ENSYM 3273 // so that we can always skip the entire symbol if we need to navigate 3274 // more quickly at the source level when parsing STABS 3275 // Skip these if we want minimal symbol tables 3276 add_nlist = false; 3277 break; 3278 3279 3280 case N_OPT: 3281 // emitted with gcc2_compiled and in gcc source 3282 type = eSymbolTypeCompiler; 3283 break; 3284 3285 case N_RSYM: 3286 // register sym: name,,NO_SECT,type,register 3287 type = eSymbolTypeVariable; 3288 break; 3289 3290 case N_SLINE: 3291 // src line: 0,,n_sect,linenumber,address 3292 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 3293 type = eSymbolTypeLineEntry; 3294 break; 3295 3296 case N_SSYM: 3297 // structure elt: name,,NO_SECT,type,struct_offset 3298 type = eSymbolTypeVariableType; 3299 break; 3300 3301 case N_SO: 3302 // source file name 3303 type = eSymbolTypeSourceFile; 3304 if (symbol_name == NULL) 3305 { 3306 add_nlist = false; 3307 if (N_SO_index != UINT32_MAX) 3308 { 3309 // Set the size of the N_SO to the terminating index of this N_SO 3310 // so that we can always skip the entire N_SO if we need to navigate 3311 // more quickly at the source level when parsing STABS 3312 symbol_ptr = symtab->SymbolAtIndex(N_SO_index); 3313 symbol_ptr->SetByteSize(sym_idx); 3314 symbol_ptr->SetSizeIsSibling(true); 3315 } 3316 N_NSYM_indexes.clear(); 3317 N_INCL_indexes.clear(); 3318 N_BRAC_indexes.clear(); 3319 N_COMM_indexes.clear(); 3320 N_FUN_indexes.clear(); 3321 N_SO_index = UINT32_MAX; 3322 } 3323 else 3324 { 3325 // We use the current number of symbols in the symbol table in lieu of 3326 // using nlist_idx in case we ever start trimming entries out 3327 const bool N_SO_has_full_path = symbol_name[0] == '/'; 3328 if (N_SO_has_full_path) 3329 { 3330 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) 3331 { 3332 // We have two consecutive N_SO entries where the first contains a directory 3333 // and the second contains a full path. 3334 sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name), false); 3335 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1; 3336 add_nlist = false; 3337 } 3338 else 3339 { 3340 // This is the first entry in a N_SO that contains a directory or 3341 // a full path to the source file 3342 N_SO_index = sym_idx; 3343 } 3344 } 3345 else if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) 3346 { 3347 // This is usually the second N_SO entry that contains just the filename, 3348 // so here we combine it with the first one if we are minimizing the symbol table 3349 const char *so_path = sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString(); 3350 if (so_path && so_path[0]) 3351 { 3352 std::string full_so_path (so_path); 3353 const size_t double_slash_pos = full_so_path.find("//"); 3354 if (double_slash_pos != std::string::npos) 3355 { 3356 // The linker has been generating bad N_SO entries with doubled up paths 3357 // in the format "%s%s" where the first string in the DW_AT_comp_dir, 3358 // and the second is the directory for the source file so you end up with 3359 // a path that looks like "/tmp/src//tmp/src/" 3360 FileSpec so_dir(so_path, false); 3361 if (!so_dir.Exists()) 3362 { 3363 so_dir.SetFile(&full_so_path[double_slash_pos + 1], false); 3364 if (so_dir.Exists()) 3365 { 3366 // Trim off the incorrect path 3367 full_so_path.erase(0, double_slash_pos + 1); 3368 } 3369 } 3370 } 3371 if (*full_so_path.rbegin() != '/') 3372 full_so_path += '/'; 3373 full_so_path += symbol_name; 3374 sym[sym_idx - 1].GetMangled().SetValue(ConstString(full_so_path.c_str()), false); 3375 add_nlist = false; 3376 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1; 3377 } 3378 } 3379 else 3380 { 3381 // This could be a relative path to a N_SO 3382 N_SO_index = sym_idx; 3383 } 3384 } 3385 3386 break; 3387 3388 case N_OSO: 3389 // object file name: name,,0,0,st_mtime 3390 type = eSymbolTypeObjectFile; 3391 break; 3392 3393 case N_LSYM: 3394 // local sym: name,,NO_SECT,type,offset 3395 type = eSymbolTypeLocal; 3396 break; 3397 3398 //---------------------------------------------------------------------- 3399 // INCL scopes 3400 //---------------------------------------------------------------------- 3401 case N_BINCL: 3402 // include file beginning: name,,NO_SECT,0,sum 3403 // We use the current number of symbols in the symbol table in lieu of 3404 // using nlist_idx in case we ever start trimming entries out 3405 N_INCL_indexes.push_back(sym_idx); 3406 type = eSymbolTypeScopeBegin; 3407 break; 3408 3409 case N_EINCL: 3410 // include file end: name,,NO_SECT,0,0 3411 // Set the size of the N_BINCL to the terminating index of this N_EINCL 3412 // so that we can always skip the entire symbol if we need to navigate 3413 // more quickly at the source level when parsing STABS 3414 if ( !N_INCL_indexes.empty() ) 3415 { 3416 symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back()); 3417 symbol_ptr->SetByteSize(sym_idx + 1); 3418 symbol_ptr->SetSizeIsSibling(true); 3419 N_INCL_indexes.pop_back(); 3420 } 3421 type = eSymbolTypeScopeEnd; 3422 break; 3423 3424 case N_SOL: 3425 // #included file name: name,,n_sect,0,address 3426 type = eSymbolTypeHeaderFile; 3427 3428 // We currently don't use the header files on darwin 3429 add_nlist = false; 3430 break; 3431 3432 case N_PARAMS: 3433 // compiler parameters: name,,NO_SECT,0,0 3434 type = eSymbolTypeCompiler; 3435 break; 3436 3437 case N_VERSION: 3438 // compiler version: name,,NO_SECT,0,0 3439 type = eSymbolTypeCompiler; 3440 break; 3441 3442 case N_OLEVEL: 3443 // compiler -O level: name,,NO_SECT,0,0 3444 type = eSymbolTypeCompiler; 3445 break; 3446 3447 case N_PSYM: 3448 // parameter: name,,NO_SECT,type,offset 3449 type = eSymbolTypeVariable; 3450 break; 3451 3452 case N_ENTRY: 3453 // alternate entry: name,,n_sect,linenumber,address 3454 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 3455 type = eSymbolTypeLineEntry; 3456 break; 3457 3458 //---------------------------------------------------------------------- 3459 // Left and Right Braces 3460 //---------------------------------------------------------------------- 3461 case N_LBRAC: 3462 // left bracket: 0,,NO_SECT,nesting level,address 3463 // We use the current number of symbols in the symbol table in lieu of 3464 // using nlist_idx in case we ever start trimming entries out 3465 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 3466 N_BRAC_indexes.push_back(sym_idx); 3467 type = eSymbolTypeScopeBegin; 3468 break; 3469 3470 case N_RBRAC: 3471 // right bracket: 0,,NO_SECT,nesting level,address 3472 // Set the size of the N_LBRAC to the terminating index of this N_RBRAC 3473 // so that we can always skip the entire symbol if we need to navigate 3474 // more quickly at the source level when parsing STABS 3475 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 3476 if ( !N_BRAC_indexes.empty() ) 3477 { 3478 symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back()); 3479 symbol_ptr->SetByteSize(sym_idx + 1); 3480 symbol_ptr->SetSizeIsSibling(true); 3481 N_BRAC_indexes.pop_back(); 3482 } 3483 type = eSymbolTypeScopeEnd; 3484 break; 3485 3486 case N_EXCL: 3487 // deleted include file: name,,NO_SECT,0,sum 3488 type = eSymbolTypeHeaderFile; 3489 break; 3490 3491 //---------------------------------------------------------------------- 3492 // COMM scopes 3493 //---------------------------------------------------------------------- 3494 case N_BCOMM: 3495 // begin common: name,,NO_SECT,0,0 3496 // We use the current number of symbols in the symbol table in lieu of 3497 // using nlist_idx in case we ever start trimming entries out 3498 type = eSymbolTypeScopeBegin; 3499 N_COMM_indexes.push_back(sym_idx); 3500 break; 3501 3502 case N_ECOML: 3503 // end common (local name): 0,,n_sect,0,address 3504 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 3505 // Fall through 3506 3507 case N_ECOMM: 3508 // end common: name,,n_sect,0,0 3509 // Set the size of the N_BCOMM to the terminating index of this N_ECOMM/N_ECOML 3510 // so that we can always skip the entire symbol if we need to navigate 3511 // more quickly at the source level when parsing STABS 3512 if ( !N_COMM_indexes.empty() ) 3513 { 3514 symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back()); 3515 symbol_ptr->SetByteSize(sym_idx + 1); 3516 symbol_ptr->SetSizeIsSibling(true); 3517 N_COMM_indexes.pop_back(); 3518 } 3519 type = eSymbolTypeScopeEnd; 3520 break; 3521 3522 case N_LENG: 3523 // second stab entry with length information 3524 type = eSymbolTypeAdditional; 3525 break; 3526 3527 default: break; 3528 } 3529 } 3530 else 3531 { 3532 //uint8_t n_pext = N_PEXT & nlist.n_type; 3533 uint8_t n_type = N_TYPE & nlist.n_type; 3534 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0); 3535 3536 switch (n_type) 3537 { 3538 case N_INDR:// Fall through 3539 case N_PBUD:// Fall through 3540 case N_UNDF: 3541 type = eSymbolTypeUndefined; 3542 break; 3543 3544 case N_ABS: 3545 type = eSymbolTypeAbsolute; 3546 break; 3547 3548 case N_SECT: 3549 { 3550 symbol_section = section_info.GetSection (nlist.n_sect, nlist.n_value); 3551 3552 if (!symbol_section) 3553 { 3554 // TODO: warn about this? 3555 add_nlist = false; 3556 break; 3557 } 3558 3559 if (TEXT_eh_frame_sectID == nlist.n_sect) 3560 { 3561 type = eSymbolTypeException; 3562 } 3563 else 3564 { 3565 uint32_t section_type = symbol_section->Get() & SECTION_TYPE; 3566 3567 switch (section_type) 3568 { 3569 case S_REGULAR: break; // regular section 3570 //case S_ZEROFILL: type = eSymbolTypeData; break; // zero fill on demand section 3571 case S_CSTRING_LITERALS: type = eSymbolTypeData; break; // section with only literal C strings 3572 case S_4BYTE_LITERALS: type = eSymbolTypeData; break; // section with only 4 byte literals 3573 case S_8BYTE_LITERALS: type = eSymbolTypeData; break; // section with only 8 byte literals 3574 case S_LITERAL_POINTERS: type = eSymbolTypeTrampoline; break; // section with only pointers to literals 3575 case S_NON_LAZY_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break; // section with only non-lazy symbol pointers 3576 case S_LAZY_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break; // section with only lazy symbol pointers 3577 case S_SYMBOL_STUBS: type = eSymbolTypeTrampoline; break; // section with only symbol stubs, byte size of stub in the reserved2 field 3578 case S_MOD_INIT_FUNC_POINTERS: type = eSymbolTypeCode; break; // section with only function pointers for initialization 3579 case S_MOD_TERM_FUNC_POINTERS: type = eSymbolTypeCode; break; // section with only function pointers for termination 3580 //case S_COALESCED: type = eSymbolType; break; // section contains symbols that are to be coalesced 3581 //case S_GB_ZEROFILL: type = eSymbolTypeData; break; // zero fill on demand section (that can be larger than 4 gigabytes) 3582 case S_INTERPOSING: type = eSymbolTypeTrampoline; break; // section with only pairs of function pointers for interposing 3583 case S_16BYTE_LITERALS: type = eSymbolTypeData; break; // section with only 16 byte literals 3584 case S_DTRACE_DOF: type = eSymbolTypeInstrumentation; break; 3585 case S_LAZY_DYLIB_SYMBOL_POINTERS: type = eSymbolTypeTrampoline; break; 3586 default: break; 3587 } 3588 3589 if (type == eSymbolTypeInvalid) 3590 { 3591 const char *symbol_sect_name = symbol_section->GetName().AsCString(); 3592 if (symbol_section->IsDescendant (text_section_sp.get())) 3593 { 3594 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS | 3595 S_ATTR_SELF_MODIFYING_CODE | 3596 S_ATTR_SOME_INSTRUCTIONS)) 3597 type = eSymbolTypeData; 3598 else 3599 type = eSymbolTypeCode; 3600 } 3601 else 3602 if (symbol_section->IsDescendant(data_section_sp.get())) 3603 { 3604 if (symbol_sect_name && ::strstr (symbol_sect_name, "__objc") == symbol_sect_name) 3605 { 3606 type = eSymbolTypeRuntime; 3607 3608 if (symbol_name && 3609 symbol_name[0] == '_' && 3610 symbol_name[1] == 'O' && 3611 symbol_name[2] == 'B') 3612 { 3613 llvm::StringRef symbol_name_ref(symbol_name); 3614 static const llvm::StringRef g_objc_v2_prefix_class ("_OBJC_CLASS_$_"); 3615 static const llvm::StringRef g_objc_v2_prefix_metaclass ("_OBJC_METACLASS_$_"); 3616 static const llvm::StringRef g_objc_v2_prefix_ivar ("_OBJC_IVAR_$_"); 3617 if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) 3618 { 3619 symbol_name_non_abi_mangled = symbol_name + 1; 3620 symbol_name = symbol_name + g_objc_v2_prefix_class.size(); 3621 type = eSymbolTypeObjCClass; 3622 demangled_is_synthesized = true; 3623 } 3624 else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass)) 3625 { 3626 symbol_name_non_abi_mangled = symbol_name + 1; 3627 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size(); 3628 type = eSymbolTypeObjCMetaClass; 3629 demangled_is_synthesized = true; 3630 } 3631 else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) 3632 { 3633 symbol_name_non_abi_mangled = symbol_name + 1; 3634 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size(); 3635 type = eSymbolTypeObjCIVar; 3636 demangled_is_synthesized = true; 3637 } 3638 } 3639 } 3640 else 3641 if (symbol_sect_name && ::strstr (symbol_sect_name, "__gcc_except_tab") == symbol_sect_name) 3642 { 3643 type = eSymbolTypeException; 3644 } 3645 else 3646 { 3647 type = eSymbolTypeData; 3648 } 3649 } 3650 else 3651 if (symbol_sect_name && ::strstr (symbol_sect_name, "__IMPORT") == symbol_sect_name) 3652 { 3653 type = eSymbolTypeTrampoline; 3654 } 3655 else 3656 if (symbol_section->IsDescendant(objc_section_sp.get())) 3657 { 3658 type = eSymbolTypeRuntime; 3659 if (symbol_name && symbol_name[0] == '.') 3660 { 3661 llvm::StringRef symbol_name_ref(symbol_name); 3662 static const llvm::StringRef g_objc_v1_prefix_class (".objc_class_name_"); 3663 if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) 3664 { 3665 symbol_name_non_abi_mangled = symbol_name; 3666 symbol_name = symbol_name + g_objc_v1_prefix_class.size(); 3667 type = eSymbolTypeObjCClass; 3668 demangled_is_synthesized = true; 3669 } 3670 } 3671 } 3672 } 3673 } 3674 } 3675 break; 3676 } 3677 } 3678 3679 if (add_nlist) 3680 { 3681 uint64_t symbol_value = nlist.n_value; 3682 3683 if (symbol_name_non_abi_mangled) 3684 { 3685 sym[sym_idx].GetMangled().SetMangledName (ConstString(symbol_name_non_abi_mangled)); 3686 sym[sym_idx].GetMangled().SetDemangledName (ConstString(symbol_name)); 3687 } 3688 else 3689 { 3690 bool symbol_name_is_mangled = false; 3691 3692 if (symbol_name && symbol_name[0] == '_') 3693 { 3694 symbol_name_is_mangled = symbol_name[1] == '_'; 3695 symbol_name++; // Skip the leading underscore 3696 } 3697 3698 if (symbol_name) 3699 { 3700 ConstString const_symbol_name(symbol_name); 3701 sym[sym_idx].GetMangled().SetValue(const_symbol_name, symbol_name_is_mangled); 3702 if (is_gsym && is_debug) 3703 { 3704 N_GSYM_name_to_sym_idx[sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString()] = sym_idx; 3705 } 3706 } 3707 } 3708 if (symbol_section) 3709 { 3710 const addr_t section_file_addr = symbol_section->GetFileAddress(); 3711 if (symbol_byte_size == 0 && function_starts_count > 0) 3712 { 3713 addr_t symbol_lookup_file_addr = nlist.n_value; 3714 // Do an exact address match for non-ARM addresses, else get the closest since 3715 // the symbol might be a thumb symbol which has an address with bit zero set 3716 FunctionStarts::Entry *func_start_entry = function_starts.FindEntry (symbol_lookup_file_addr, !is_arm); 3717 if (is_arm && func_start_entry) 3718 { 3719 // Verify that the function start address is the symbol address (ARM) 3720 // or the symbol address + 1 (thumb) 3721 if (func_start_entry->addr != symbol_lookup_file_addr && 3722 func_start_entry->addr != (symbol_lookup_file_addr + 1)) 3723 { 3724 // Not the right entry, NULL it out... 3725 func_start_entry = NULL; 3726 } 3727 } 3728 if (func_start_entry) 3729 { 3730 func_start_entry->data = true; 3731 3732 addr_t symbol_file_addr = func_start_entry->addr; 3733 if (is_arm) 3734 symbol_file_addr &= 0xfffffffffffffffeull; 3735 3736 const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry); 3737 const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize(); 3738 if (next_func_start_entry) 3739 { 3740 addr_t next_symbol_file_addr = next_func_start_entry->addr; 3741 // Be sure the clear the Thumb address bit when we calculate the size 3742 // from the current and next address 3743 if (is_arm) 3744 next_symbol_file_addr &= 0xfffffffffffffffeull; 3745 symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr); 3746 } 3747 else 3748 { 3749 symbol_byte_size = section_end_file_addr - symbol_file_addr; 3750 } 3751 } 3752 } 3753 symbol_value -= section_file_addr; 3754 } 3755 3756 if (is_debug == false) 3757 { 3758 if (type == eSymbolTypeCode) 3759 { 3760 // See if we can find a N_FUN entry for any code symbols. 3761 // If we do find a match, and the name matches, then we 3762 // can merge the two into just the function symbol to avoid 3763 // duplicate entries in the symbol table 3764 std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range; 3765 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value); 3766 if (range.first != range.second) 3767 { 3768 bool found_it = false; 3769 for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos) 3770 { 3771 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled)) 3772 { 3773 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second; 3774 // We just need the flags from the linker symbol, so put these flags 3775 // into the N_FUN flags to avoid duplicate symbols in the symbol table 3776 sym[pos->second].SetExternal(sym[sym_idx].IsExternal()); 3777 sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc); 3778 if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end()) 3779 sym[pos->second].SetType (eSymbolTypeResolver); 3780 sym[sym_idx].Clear(); 3781 found_it = true; 3782 break; 3783 } 3784 } 3785 if (found_it) 3786 continue; 3787 } 3788 else 3789 { 3790 if (resolver_addresses.find(nlist.n_value) != resolver_addresses.end()) 3791 type = eSymbolTypeResolver; 3792 } 3793 } 3794 else if (type == eSymbolTypeData) 3795 { 3796 // See if we can find a N_STSYM entry for any data symbols. 3797 // If we do find a match, and the name matches, then we 3798 // can merge the two into just the Static symbol to avoid 3799 // duplicate entries in the symbol table 3800 std::pair<ValueToSymbolIndexMap::const_iterator, ValueToSymbolIndexMap::const_iterator> range; 3801 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value); 3802 if (range.first != range.second) 3803 { 3804 bool found_it = false; 3805 for (ValueToSymbolIndexMap::const_iterator pos = range.first; pos != range.second; ++pos) 3806 { 3807 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == sym[pos->second].GetMangled().GetName(Mangled::ePreferMangled)) 3808 { 3809 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second; 3810 // We just need the flags from the linker symbol, so put these flags 3811 // into the N_STSYM flags to avoid duplicate symbols in the symbol table 3812 sym[pos->second].SetExternal(sym[sym_idx].IsExternal()); 3813 sym[pos->second].SetFlags (nlist.n_type << 16 | nlist.n_desc); 3814 sym[sym_idx].Clear(); 3815 found_it = true; 3816 break; 3817 } 3818 } 3819 if (found_it) 3820 continue; 3821 } 3822 else 3823 { 3824 // Combine N_GSYM stab entries with the non stab symbol 3825 ConstNameToSymbolIndexMap::const_iterator pos = N_GSYM_name_to_sym_idx.find(sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled).GetCString()); 3826 if (pos != N_GSYM_name_to_sym_idx.end()) 3827 { 3828 const uint32_t GSYM_sym_idx = pos->second; 3829 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx; 3830 // Copy the address, because often the N_GSYM address has an invalid address of zero 3831 // when the global is a common symbol 3832 sym[GSYM_sym_idx].GetAddress().SetSection (symbol_section); 3833 sym[GSYM_sym_idx].GetAddress().SetOffset (symbol_value); 3834 // We just need the flags from the linker symbol, so put these flags 3835 // into the N_STSYM flags to avoid duplicate symbols in the symbol table 3836 sym[GSYM_sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc); 3837 sym[sym_idx].Clear(); 3838 continue; 3839 } 3840 } 3841 } 3842 } 3843 3844 sym[sym_idx].SetID (nlist_idx); 3845 sym[sym_idx].SetType (type); 3846 sym[sym_idx].GetAddress().SetSection (symbol_section); 3847 sym[sym_idx].GetAddress().SetOffset (symbol_value); 3848 sym[sym_idx].SetFlags (nlist.n_type << 16 | nlist.n_desc); 3849 3850 if (symbol_byte_size > 0) 3851 sym[sym_idx].SetByteSize(symbol_byte_size); 3852 3853 if (demangled_is_synthesized) 3854 sym[sym_idx].SetDemangledNameIsSynthesized(true); 3855 3856 ++sym_idx; 3857 } 3858 else 3859 { 3860 sym[sym_idx].Clear(); 3861 } 3862 } 3863 } 3864 3865 uint32_t synthetic_sym_id = symtab_load_command.nsyms; 3866 3867 if (function_starts_count > 0) 3868 { 3869 char synthetic_function_symbol[PATH_MAX]; 3870 uint32_t num_synthetic_function_symbols = 0; 3871 for (i=0; i<function_starts_count; ++i) 3872 { 3873 if (function_starts.GetEntryRef (i).data == false) 3874 ++num_synthetic_function_symbols; 3875 } 3876 3877 if (num_synthetic_function_symbols > 0) 3878 { 3879 if (num_syms < sym_idx + num_synthetic_function_symbols) 3880 { 3881 num_syms = sym_idx + num_synthetic_function_symbols; 3882 sym = symtab->Resize (num_syms); 3883 } 3884 uint32_t synthetic_function_symbol_idx = 0; 3885 for (i=0; i<function_starts_count; ++i) 3886 { 3887 const FunctionStarts::Entry *func_start_entry = function_starts.GetEntryAtIndex (i); 3888 if (func_start_entry->data == false) 3889 { 3890 addr_t symbol_file_addr = func_start_entry->addr; 3891 uint32_t symbol_flags = 0; 3892 if (is_arm) 3893 { 3894 if (symbol_file_addr & 1) 3895 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB; 3896 symbol_file_addr &= 0xfffffffffffffffeull; 3897 } 3898 Address symbol_addr; 3899 if (module_sp->ResolveFileAddress (symbol_file_addr, symbol_addr)) 3900 { 3901 SectionSP symbol_section (symbol_addr.GetSection()); 3902 uint32_t symbol_byte_size = 0; 3903 if (symbol_section) 3904 { 3905 const addr_t section_file_addr = symbol_section->GetFileAddress(); 3906 const FunctionStarts::Entry *next_func_start_entry = function_starts.FindNextEntry (func_start_entry); 3907 const addr_t section_end_file_addr = section_file_addr + symbol_section->GetByteSize(); 3908 if (next_func_start_entry) 3909 { 3910 addr_t next_symbol_file_addr = next_func_start_entry->addr; 3911 if (is_arm) 3912 next_symbol_file_addr &= 0xfffffffffffffffeull; 3913 symbol_byte_size = std::min<lldb::addr_t>(next_symbol_file_addr - symbol_file_addr, section_end_file_addr - symbol_file_addr); 3914 } 3915 else 3916 { 3917 symbol_byte_size = section_end_file_addr - symbol_file_addr; 3918 } 3919 snprintf (synthetic_function_symbol, 3920 sizeof(synthetic_function_symbol), 3921 "___lldb_unnamed_function%u$$%s", 3922 ++synthetic_function_symbol_idx, 3923 module_sp->GetFileSpec().GetFilename().GetCString()); 3924 sym[sym_idx].SetID (synthetic_sym_id++); 3925 sym[sym_idx].GetMangled().SetDemangledName(ConstString(synthetic_function_symbol)); 3926 sym[sym_idx].SetType (eSymbolTypeCode); 3927 sym[sym_idx].SetIsSynthetic (true); 3928 sym[sym_idx].GetAddress() = symbol_addr; 3929 if (symbol_flags) 3930 sym[sym_idx].SetFlags (symbol_flags); 3931 if (symbol_byte_size) 3932 sym[sym_idx].SetByteSize (symbol_byte_size); 3933 ++sym_idx; 3934 } 3935 } 3936 } 3937 } 3938 } 3939 } 3940 3941 // Trim our symbols down to just what we ended up with after 3942 // removing any symbols. 3943 if (sym_idx < num_syms) 3944 { 3945 num_syms = sym_idx; 3946 sym = symtab->Resize (num_syms); 3947 } 3948 3949 // Now synthesize indirect symbols 3950 if (m_dysymtab.nindirectsyms != 0) 3951 { 3952 if (indirect_symbol_index_data.GetByteSize()) 3953 { 3954 NListIndexToSymbolIndexMap::const_iterator end_index_pos = m_nlist_idx_to_sym_idx.end(); 3955 3956 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size(); ++sect_idx) 3957 { 3958 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) == S_SYMBOL_STUBS) 3959 { 3960 uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2; 3961 if (symbol_stub_byte_size == 0) 3962 continue; 3963 3964 const uint32_t num_symbol_stubs = m_mach_sections[sect_idx].size / symbol_stub_byte_size; 3965 3966 if (num_symbol_stubs == 0) 3967 continue; 3968 3969 const uint32_t symbol_stub_index_offset = m_mach_sections[sect_idx].reserved1; 3970 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx) 3971 { 3972 const uint32_t symbol_stub_index = symbol_stub_index_offset + stub_idx; 3973 const lldb::addr_t symbol_stub_addr = m_mach_sections[sect_idx].addr + (stub_idx * symbol_stub_byte_size); 3974 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4; 3975 if (indirect_symbol_index_data.ValidOffsetForDataOfSize(symbol_stub_offset, 4)) 3976 { 3977 const uint32_t stub_sym_id = indirect_symbol_index_data.GetU32 (&symbol_stub_offset); 3978 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL)) 3979 continue; 3980 3981 NListIndexToSymbolIndexMap::const_iterator index_pos = m_nlist_idx_to_sym_idx.find (stub_sym_id); 3982 Symbol *stub_symbol = NULL; 3983 if (index_pos != end_index_pos) 3984 { 3985 // We have a remapping from the original nlist index to 3986 // a current symbol index, so just look this up by index 3987 stub_symbol = symtab->SymbolAtIndex (index_pos->second); 3988 } 3989 else 3990 { 3991 // We need to lookup a symbol using the original nlist 3992 // symbol index since this index is coming from the 3993 // S_SYMBOL_STUBS 3994 stub_symbol = symtab->FindSymbolByID (stub_sym_id); 3995 } 3996 3997 if (stub_symbol) 3998 { 3999 Address so_addr(symbol_stub_addr, section_list); 4000 4001 if (stub_symbol->GetType() == eSymbolTypeUndefined) 4002 { 4003 // Change the external symbol into a trampoline that makes sense 4004 // These symbols were N_UNDF N_EXT, and are useless to us, so we 4005 // can re-use them so we don't have to make up a synthetic symbol 4006 // for no good reason. 4007 if (resolver_addresses.find(symbol_stub_addr) == resolver_addresses.end()) 4008 stub_symbol->SetType (eSymbolTypeTrampoline); 4009 else 4010 stub_symbol->SetType (eSymbolTypeResolver); 4011 stub_symbol->SetExternal (false); 4012 stub_symbol->GetAddress() = so_addr; 4013 stub_symbol->SetByteSize (symbol_stub_byte_size); 4014 } 4015 else 4016 { 4017 // Make a synthetic symbol to describe the trampoline stub 4018 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled()); 4019 if (sym_idx >= num_syms) 4020 { 4021 sym = symtab->Resize (++num_syms); 4022 stub_symbol = NULL; // this pointer no longer valid 4023 } 4024 sym[sym_idx].SetID (synthetic_sym_id++); 4025 sym[sym_idx].GetMangled() = stub_symbol_mangled_name; 4026 if (resolver_addresses.find(symbol_stub_addr) == resolver_addresses.end()) 4027 sym[sym_idx].SetType (eSymbolTypeTrampoline); 4028 else 4029 sym[sym_idx].SetType (eSymbolTypeResolver); 4030 sym[sym_idx].SetIsSynthetic (true); 4031 sym[sym_idx].GetAddress() = so_addr; 4032 sym[sym_idx].SetByteSize (symbol_stub_byte_size); 4033 ++sym_idx; 4034 } 4035 } 4036 else 4037 { 4038 if (log) 4039 log->Warning ("symbol stub referencing symbol table symbol %u that isn't in our minimal symbol table, fix this!!!", stub_sym_id); 4040 } 4041 } 4042 } 4043 } 4044 } 4045 } 4046 } 4047 4048 4049 if (!trie_entries.empty()) 4050 { 4051 for (const auto &e : trie_entries) 4052 { 4053 if (e.entry.import_name) 4054 { 4055 // Make a synthetic symbol to describe re-exported symbol. 4056 if (sym_idx >= num_syms) 4057 sym = symtab->Resize (++num_syms); 4058 sym[sym_idx].SetID (synthetic_sym_id++); 4059 sym[sym_idx].GetMangled() = Mangled(e.entry.name); 4060 sym[sym_idx].SetType (eSymbolTypeReExported); 4061 sym[sym_idx].SetIsSynthetic (true); 4062 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name); 4063 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) 4064 { 4065 sym[sym_idx].SetReExportedSymbolSharedLibrary(dylib_files.GetFileSpecAtIndex(e.entry.other-1)); 4066 } 4067 ++sym_idx; 4068 } 4069 } 4070 } 4071 4072 4073 4074 // StreamFile s(stdout, false); 4075 // s.Printf ("Symbol table before CalculateSymbolSizes():\n"); 4076 // symtab->Dump(&s, NULL, eSortOrderNone); 4077 // Set symbol byte sizes correctly since mach-o nlist entries don't have sizes 4078 symtab->CalculateSymbolSizes(); 4079 4080 // s.Printf ("Symbol table after CalculateSymbolSizes():\n"); 4081 // symtab->Dump(&s, NULL, eSortOrderNone); 4082 4083 return symtab->GetNumSymbols(); 4084 } 4085 return 0; 4086 } 4087 4088 4089 void 4090 ObjectFileMachO::Dump (Stream *s) 4091 { 4092 ModuleSP module_sp(GetModule()); 4093 if (module_sp) 4094 { 4095 lldb_private::Mutex::Locker locker(module_sp->GetMutex()); 4096 s->Printf("%p: ", static_cast<void*>(this)); 4097 s->Indent(); 4098 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64) 4099 s->PutCString("ObjectFileMachO64"); 4100 else 4101 s->PutCString("ObjectFileMachO32"); 4102 4103 ArchSpec header_arch; 4104 GetArchitecture(header_arch); 4105 4106 *s << ", file = '" << m_file << "', arch = " << header_arch.GetArchitectureName() << "\n"; 4107 4108 SectionList *sections = GetSectionList(); 4109 if (sections) 4110 sections->Dump(s, NULL, true, UINT32_MAX); 4111 4112 if (m_symtab_ap.get()) 4113 m_symtab_ap->Dump(s, NULL, eSortOrderNone); 4114 } 4115 } 4116 4117 bool 4118 ObjectFileMachO::GetUUID (const llvm::MachO::mach_header &header, 4119 const lldb_private::DataExtractor &data, 4120 lldb::offset_t lc_offset, 4121 lldb_private::UUID& uuid) 4122 { 4123 uint32_t i; 4124 struct uuid_command load_cmd; 4125 4126 lldb::offset_t offset = lc_offset; 4127 for (i=0; i<header.ncmds; ++i) 4128 { 4129 const lldb::offset_t cmd_offset = offset; 4130 if (data.GetU32(&offset, &load_cmd, 2) == NULL) 4131 break; 4132 4133 if (load_cmd.cmd == LC_UUID) 4134 { 4135 const uint8_t *uuid_bytes = data.PeekData(offset, 16); 4136 4137 if (uuid_bytes) 4138 { 4139 // OpenCL on Mac OS X uses the same UUID for each of its object files. 4140 // We pretend these object files have no UUID to prevent crashing. 4141 4142 const uint8_t opencl_uuid[] = { 0x8c, 0x8e, 0xb3, 0x9b, 4143 0x3b, 0xa8, 4144 0x4b, 0x16, 4145 0xb6, 0xa4, 4146 0x27, 0x63, 0xbb, 0x14, 0xf0, 0x0d }; 4147 4148 if (!memcmp(uuid_bytes, opencl_uuid, 16)) 4149 return false; 4150 4151 uuid.SetBytes (uuid_bytes); 4152 return true; 4153 } 4154 return false; 4155 } 4156 offset = cmd_offset + load_cmd.cmdsize; 4157 } 4158 return false; 4159 } 4160 4161 4162 bool 4163 ObjectFileMachO::GetArchitecture (const llvm::MachO::mach_header &header, 4164 const lldb_private::DataExtractor &data, 4165 lldb::offset_t lc_offset, 4166 ArchSpec &arch) 4167 { 4168 arch.SetArchitecture (eArchTypeMachO, header.cputype, header.cpusubtype); 4169 4170 if (arch.IsValid()) 4171 { 4172 llvm::Triple &triple = arch.GetTriple(); 4173 if (header.filetype == MH_PRELOAD) 4174 { 4175 // Set OS to "unknown" - this is a standalone binary with no dyld et al 4176 triple.setOS(llvm::Triple::UnknownOS); 4177 return true; 4178 } 4179 else 4180 { 4181 struct load_command load_cmd; 4182 4183 lldb::offset_t offset = lc_offset; 4184 for (uint32_t i=0; i<header.ncmds; ++i) 4185 { 4186 const lldb::offset_t cmd_offset = offset; 4187 if (data.GetU32(&offset, &load_cmd, 2) == NULL) 4188 break; 4189 4190 switch (load_cmd.cmd) 4191 { 4192 case LC_VERSION_MIN_IPHONEOS: 4193 triple.setOS (llvm::Triple::IOS); 4194 return true; 4195 4196 case LC_VERSION_MIN_MACOSX: 4197 triple.setOS (llvm::Triple::MacOSX); 4198 return true; 4199 4200 default: 4201 break; 4202 } 4203 4204 offset = cmd_offset + load_cmd.cmdsize; 4205 } 4206 4207 if (header.cputype == CPU_TYPE_ARM || header.cputype == CPU_TYPE_ARM64) 4208 triple.setOS (llvm::Triple::IOS); 4209 else 4210 triple.setOS (llvm::Triple::MacOSX); 4211 } 4212 } 4213 return arch.IsValid(); 4214 } 4215 4216 bool 4217 ObjectFileMachO::GetUUID (lldb_private::UUID* uuid) 4218 { 4219 ModuleSP module_sp(GetModule()); 4220 if (module_sp) 4221 { 4222 lldb_private::Mutex::Locker locker(module_sp->GetMutex()); 4223 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 4224 return GetUUID (m_header, m_data, offset, *uuid); 4225 } 4226 return false; 4227 } 4228 4229 4230 uint32_t 4231 ObjectFileMachO::GetDependentModules (FileSpecList& files) 4232 { 4233 uint32_t count = 0; 4234 ModuleSP module_sp(GetModule()); 4235 if (module_sp) 4236 { 4237 lldb_private::Mutex::Locker locker(module_sp->GetMutex()); 4238 struct load_command load_cmd; 4239 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 4240 const bool resolve_path = false; // Don't resolve the dependend file paths since they may not reside on this system 4241 uint32_t i; 4242 for (i=0; i<m_header.ncmds; ++i) 4243 { 4244 const uint32_t cmd_offset = offset; 4245 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL) 4246 break; 4247 4248 switch (load_cmd.cmd) 4249 { 4250 case LC_LOAD_DYLIB: 4251 case LC_LOAD_WEAK_DYLIB: 4252 case LC_REEXPORT_DYLIB: 4253 case LC_LOAD_DYLINKER: 4254 case LC_LOADFVMLIB: 4255 case LC_LOAD_UPWARD_DYLIB: 4256 { 4257 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset); 4258 const char *path = m_data.PeekCStr(name_offset); 4259 // Skip any path that starts with '@' since these are usually: 4260 // @executable_path/.../file 4261 // @rpath/.../file 4262 if (path && path[0] != '@') 4263 { 4264 FileSpec file_spec(path, resolve_path); 4265 if (files.AppendIfUnique(file_spec)) 4266 count++; 4267 } 4268 } 4269 break; 4270 4271 default: 4272 break; 4273 } 4274 offset = cmd_offset + load_cmd.cmdsize; 4275 } 4276 } 4277 return count; 4278 } 4279 4280 lldb_private::Address 4281 ObjectFileMachO::GetEntryPointAddress () 4282 { 4283 // If the object file is not an executable it can't hold the entry point. m_entry_point_address 4284 // is initialized to an invalid address, so we can just return that. 4285 // If m_entry_point_address is valid it means we've found it already, so return the cached value. 4286 4287 if (!IsExecutable() || m_entry_point_address.IsValid()) 4288 return m_entry_point_address; 4289 4290 // Otherwise, look for the UnixThread or Thread command. The data for the Thread command is given in 4291 // /usr/include/mach-o.h, but it is basically: 4292 // 4293 // uint32_t flavor - this is the flavor argument you would pass to thread_get_state 4294 // uint32_t count - this is the count of longs in the thread state data 4295 // struct XXX_thread_state state - this is the structure from <machine/thread_status.h> corresponding to the flavor. 4296 // <repeat this trio> 4297 // 4298 // So we just keep reading the various register flavors till we find the GPR one, then read the PC out of there. 4299 // FIXME: We will need to have a "RegisterContext data provider" class at some point that can get all the registers 4300 // out of data in this form & attach them to a given thread. That should underlie the MacOS X User process plugin, 4301 // and we'll also need it for the MacOS X Core File process plugin. When we have that we can also use it here. 4302 // 4303 // For now we hard-code the offsets and flavors we need: 4304 // 4305 // 4306 4307 ModuleSP module_sp(GetModule()); 4308 if (module_sp) 4309 { 4310 lldb_private::Mutex::Locker locker(module_sp->GetMutex()); 4311 struct load_command load_cmd; 4312 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 4313 uint32_t i; 4314 lldb::addr_t start_address = LLDB_INVALID_ADDRESS; 4315 bool done = false; 4316 4317 for (i=0; i<m_header.ncmds; ++i) 4318 { 4319 const lldb::offset_t cmd_offset = offset; 4320 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL) 4321 break; 4322 4323 switch (load_cmd.cmd) 4324 { 4325 case LC_UNIXTHREAD: 4326 case LC_THREAD: 4327 { 4328 while (offset < cmd_offset + load_cmd.cmdsize) 4329 { 4330 uint32_t flavor = m_data.GetU32(&offset); 4331 uint32_t count = m_data.GetU32(&offset); 4332 if (count == 0) 4333 { 4334 // We've gotten off somehow, log and exit; 4335 return m_entry_point_address; 4336 } 4337 4338 switch (m_header.cputype) 4339 { 4340 case llvm::MachO::CPU_TYPE_ARM: 4341 if (flavor == 1) // ARM_THREAD_STATE from mach/arm/thread_status.h 4342 { 4343 offset += 60; // This is the offset of pc in the GPR thread state data structure. 4344 start_address = m_data.GetU32(&offset); 4345 done = true; 4346 } 4347 break; 4348 case llvm::MachO::CPU_TYPE_ARM64: 4349 if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h 4350 { 4351 offset += 256; // This is the offset of pc in the GPR thread state data structure. 4352 start_address = m_data.GetU64(&offset); 4353 done = true; 4354 } 4355 break; 4356 case llvm::MachO::CPU_TYPE_I386: 4357 if (flavor == 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h 4358 { 4359 offset += 40; // This is the offset of eip in the GPR thread state data structure. 4360 start_address = m_data.GetU32(&offset); 4361 done = true; 4362 } 4363 break; 4364 case llvm::MachO::CPU_TYPE_X86_64: 4365 if (flavor == 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h 4366 { 4367 offset += 16 * 8; // This is the offset of rip in the GPR thread state data structure. 4368 start_address = m_data.GetU64(&offset); 4369 done = true; 4370 } 4371 break; 4372 default: 4373 return m_entry_point_address; 4374 } 4375 // Haven't found the GPR flavor yet, skip over the data for this flavor: 4376 if (done) 4377 break; 4378 offset += count * 4; 4379 } 4380 } 4381 break; 4382 case LC_MAIN: 4383 { 4384 ConstString text_segment_name ("__TEXT"); 4385 uint64_t entryoffset = m_data.GetU64(&offset); 4386 SectionSP text_segment_sp = GetSectionList()->FindSectionByName(text_segment_name); 4387 if (text_segment_sp) 4388 { 4389 done = true; 4390 start_address = text_segment_sp->GetFileAddress() + entryoffset; 4391 } 4392 } 4393 4394 default: 4395 break; 4396 } 4397 if (done) 4398 break; 4399 4400 // Go to the next load command: 4401 offset = cmd_offset + load_cmd.cmdsize; 4402 } 4403 4404 if (start_address != LLDB_INVALID_ADDRESS) 4405 { 4406 // We got the start address from the load commands, so now resolve that address in the sections 4407 // of this ObjectFile: 4408 if (!m_entry_point_address.ResolveAddressUsingFileSections (start_address, GetSectionList())) 4409 { 4410 m_entry_point_address.Clear(); 4411 } 4412 } 4413 else 4414 { 4415 // We couldn't read the UnixThread load command - maybe it wasn't there. As a fallback look for the 4416 // "start" symbol in the main executable. 4417 4418 ModuleSP module_sp (GetModule()); 4419 4420 if (module_sp) 4421 { 4422 SymbolContextList contexts; 4423 SymbolContext context; 4424 if (module_sp->FindSymbolsWithNameAndType(ConstString ("start"), eSymbolTypeCode, contexts)) 4425 { 4426 if (contexts.GetContextAtIndex(0, context)) 4427 m_entry_point_address = context.symbol->GetAddress(); 4428 } 4429 } 4430 } 4431 } 4432 4433 return m_entry_point_address; 4434 4435 } 4436 4437 lldb_private::Address 4438 ObjectFileMachO::GetHeaderAddress () 4439 { 4440 lldb_private::Address header_addr; 4441 SectionList *section_list = GetSectionList(); 4442 if (section_list) 4443 { 4444 SectionSP text_segment_sp (section_list->FindSectionByName (GetSegmentNameTEXT())); 4445 if (text_segment_sp) 4446 { 4447 header_addr.SetSection (text_segment_sp); 4448 header_addr.SetOffset (0); 4449 } 4450 } 4451 return header_addr; 4452 } 4453 4454 uint32_t 4455 ObjectFileMachO::GetNumThreadContexts () 4456 { 4457 ModuleSP module_sp(GetModule()); 4458 if (module_sp) 4459 { 4460 lldb_private::Mutex::Locker locker(module_sp->GetMutex()); 4461 if (!m_thread_context_offsets_valid) 4462 { 4463 m_thread_context_offsets_valid = true; 4464 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 4465 FileRangeArray::Entry file_range; 4466 thread_command thread_cmd; 4467 for (uint32_t i=0; i<m_header.ncmds; ++i) 4468 { 4469 const uint32_t cmd_offset = offset; 4470 if (m_data.GetU32(&offset, &thread_cmd, 2) == NULL) 4471 break; 4472 4473 if (thread_cmd.cmd == LC_THREAD) 4474 { 4475 file_range.SetRangeBase (offset); 4476 file_range.SetByteSize (thread_cmd.cmdsize - 8); 4477 m_thread_context_offsets.Append (file_range); 4478 } 4479 offset = cmd_offset + thread_cmd.cmdsize; 4480 } 4481 } 4482 } 4483 return m_thread_context_offsets.GetSize(); 4484 } 4485 4486 lldb::RegisterContextSP 4487 ObjectFileMachO::GetThreadContextAtIndex (uint32_t idx, lldb_private::Thread &thread) 4488 { 4489 lldb::RegisterContextSP reg_ctx_sp; 4490 4491 ModuleSP module_sp(GetModule()); 4492 if (module_sp) 4493 { 4494 lldb_private::Mutex::Locker locker(module_sp->GetMutex()); 4495 if (!m_thread_context_offsets_valid) 4496 GetNumThreadContexts (); 4497 4498 const FileRangeArray::Entry *thread_context_file_range = m_thread_context_offsets.GetEntryAtIndex (idx); 4499 if (thread_context_file_range) 4500 { 4501 4502 DataExtractor data (m_data, 4503 thread_context_file_range->GetRangeBase(), 4504 thread_context_file_range->GetByteSize()); 4505 4506 switch (m_header.cputype) 4507 { 4508 case llvm::MachO::CPU_TYPE_ARM64: 4509 reg_ctx_sp.reset (new RegisterContextDarwin_arm64_Mach (thread, data)); 4510 break; 4511 4512 case llvm::MachO::CPU_TYPE_ARM: 4513 reg_ctx_sp.reset (new RegisterContextDarwin_arm_Mach (thread, data)); 4514 break; 4515 4516 case llvm::MachO::CPU_TYPE_I386: 4517 reg_ctx_sp.reset (new RegisterContextDarwin_i386_Mach (thread, data)); 4518 break; 4519 4520 case llvm::MachO::CPU_TYPE_X86_64: 4521 reg_ctx_sp.reset (new RegisterContextDarwin_x86_64_Mach (thread, data)); 4522 break; 4523 } 4524 } 4525 } 4526 return reg_ctx_sp; 4527 } 4528 4529 4530 ObjectFile::Type 4531 ObjectFileMachO::CalculateType() 4532 { 4533 switch (m_header.filetype) 4534 { 4535 case MH_OBJECT: // 0x1u 4536 if (GetAddressByteSize () == 4) 4537 { 4538 // 32 bit kexts are just object files, but they do have a valid 4539 // UUID load command. 4540 UUID uuid; 4541 if (GetUUID(&uuid)) 4542 { 4543 // this checking for the UUID load command is not enough 4544 // we could eventually look for the symbol named 4545 // "OSKextGetCurrentIdentifier" as this is required of kexts 4546 if (m_strata == eStrataInvalid) 4547 m_strata = eStrataKernel; 4548 return eTypeSharedLibrary; 4549 } 4550 } 4551 return eTypeObjectFile; 4552 4553 case MH_EXECUTE: return eTypeExecutable; // 0x2u 4554 case MH_FVMLIB: return eTypeSharedLibrary; // 0x3u 4555 case MH_CORE: return eTypeCoreFile; // 0x4u 4556 case MH_PRELOAD: return eTypeSharedLibrary; // 0x5u 4557 case MH_DYLIB: return eTypeSharedLibrary; // 0x6u 4558 case MH_DYLINKER: return eTypeDynamicLinker; // 0x7u 4559 case MH_BUNDLE: return eTypeSharedLibrary; // 0x8u 4560 case MH_DYLIB_STUB: return eTypeStubLibrary; // 0x9u 4561 case MH_DSYM: return eTypeDebugInfo; // 0xAu 4562 case MH_KEXT_BUNDLE: return eTypeSharedLibrary; // 0xBu 4563 default: 4564 break; 4565 } 4566 return eTypeUnknown; 4567 } 4568 4569 ObjectFile::Strata 4570 ObjectFileMachO::CalculateStrata() 4571 { 4572 switch (m_header.filetype) 4573 { 4574 case MH_OBJECT: // 0x1u 4575 { 4576 // 32 bit kexts are just object files, but they do have a valid 4577 // UUID load command. 4578 UUID uuid; 4579 if (GetUUID(&uuid)) 4580 { 4581 // this checking for the UUID load command is not enough 4582 // we could eventually look for the symbol named 4583 // "OSKextGetCurrentIdentifier" as this is required of kexts 4584 if (m_type == eTypeInvalid) 4585 m_type = eTypeSharedLibrary; 4586 4587 return eStrataKernel; 4588 } 4589 } 4590 return eStrataUnknown; 4591 4592 case MH_EXECUTE: // 0x2u 4593 // Check for the MH_DYLDLINK bit in the flags 4594 if (m_header.flags & MH_DYLDLINK) 4595 { 4596 return eStrataUser; 4597 } 4598 else 4599 { 4600 SectionList *section_list = GetSectionList(); 4601 if (section_list) 4602 { 4603 static ConstString g_kld_section_name ("__KLD"); 4604 if (section_list->FindSectionByName(g_kld_section_name)) 4605 return eStrataKernel; 4606 } 4607 } 4608 return eStrataRawImage; 4609 4610 case MH_FVMLIB: return eStrataUser; // 0x3u 4611 case MH_CORE: return eStrataUnknown; // 0x4u 4612 case MH_PRELOAD: return eStrataRawImage; // 0x5u 4613 case MH_DYLIB: return eStrataUser; // 0x6u 4614 case MH_DYLINKER: return eStrataUser; // 0x7u 4615 case MH_BUNDLE: return eStrataUser; // 0x8u 4616 case MH_DYLIB_STUB: return eStrataUser; // 0x9u 4617 case MH_DSYM: return eStrataUnknown; // 0xAu 4618 case MH_KEXT_BUNDLE: return eStrataKernel; // 0xBu 4619 default: 4620 break; 4621 } 4622 return eStrataUnknown; 4623 } 4624 4625 4626 uint32_t 4627 ObjectFileMachO::GetVersion (uint32_t *versions, uint32_t num_versions) 4628 { 4629 ModuleSP module_sp(GetModule()); 4630 if (module_sp) 4631 { 4632 lldb_private::Mutex::Locker locker(module_sp->GetMutex()); 4633 struct dylib_command load_cmd; 4634 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 4635 uint32_t version_cmd = 0; 4636 uint64_t version = 0; 4637 uint32_t i; 4638 for (i=0; i<m_header.ncmds; ++i) 4639 { 4640 const lldb::offset_t cmd_offset = offset; 4641 if (m_data.GetU32(&offset, &load_cmd, 2) == NULL) 4642 break; 4643 4644 if (load_cmd.cmd == LC_ID_DYLIB) 4645 { 4646 if (version_cmd == 0) 4647 { 4648 version_cmd = load_cmd.cmd; 4649 if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == NULL) 4650 break; 4651 version = load_cmd.dylib.current_version; 4652 } 4653 break; // Break for now unless there is another more complete version 4654 // number load command in the future. 4655 } 4656 offset = cmd_offset + load_cmd.cmdsize; 4657 } 4658 4659 if (version_cmd == LC_ID_DYLIB) 4660 { 4661 if (versions != NULL && num_versions > 0) 4662 { 4663 if (num_versions > 0) 4664 versions[0] = (version & 0xFFFF0000ull) >> 16; 4665 if (num_versions > 1) 4666 versions[1] = (version & 0x0000FF00ull) >> 8; 4667 if (num_versions > 2) 4668 versions[2] = (version & 0x000000FFull); 4669 // Fill in an remaining version numbers with invalid values 4670 for (i=3; i<num_versions; ++i) 4671 versions[i] = UINT32_MAX; 4672 } 4673 // The LC_ID_DYLIB load command has a version with 3 version numbers 4674 // in it, so always return 3 4675 return 3; 4676 } 4677 } 4678 return false; 4679 } 4680 4681 bool 4682 ObjectFileMachO::GetArchitecture (ArchSpec &arch) 4683 { 4684 ModuleSP module_sp(GetModule()); 4685 if (module_sp) 4686 { 4687 lldb_private::Mutex::Locker locker(module_sp->GetMutex()); 4688 return GetArchitecture (m_header, m_data, MachHeaderSizeFromMagic(m_header.magic), arch); 4689 } 4690 return false; 4691 } 4692 4693 4694 UUID 4695 ObjectFileMachO::GetProcessSharedCacheUUID (Process *process) 4696 { 4697 UUID uuid; 4698 if (process) 4699 { 4700 addr_t all_image_infos = process->GetImageInfoAddress(); 4701 4702 // The address returned by GetImageInfoAddress may be the address of dyld (don't want) 4703 // or it may be the address of the dyld_all_image_infos structure (want). The first four 4704 // bytes will be either the version field (all_image_infos) or a Mach-O file magic constant. 4705 // Version 13 and higher of dyld_all_image_infos is required to get the sharedCacheUUID field. 4706 4707 Error err; 4708 uint32_t version_or_magic = process->ReadUnsignedIntegerFromMemory (all_image_infos, 4, -1, err); 4709 if (version_or_magic != static_cast<uint32_t>(-1) 4710 && version_or_magic != MH_MAGIC 4711 && version_or_magic != MH_CIGAM 4712 && version_or_magic != MH_MAGIC_64 4713 && version_or_magic != MH_CIGAM_64 4714 && version_or_magic >= 13) 4715 { 4716 addr_t sharedCacheUUID_address = LLDB_INVALID_ADDRESS; 4717 int wordsize = process->GetAddressByteSize(); 4718 if (wordsize == 8) 4719 { 4720 sharedCacheUUID_address = all_image_infos + 160; // sharedCacheUUID <mach-o/dyld_images.h> 4721 } 4722 if (wordsize == 4) 4723 { 4724 sharedCacheUUID_address = all_image_infos + 84; // sharedCacheUUID <mach-o/dyld_images.h> 4725 } 4726 if (sharedCacheUUID_address != LLDB_INVALID_ADDRESS) 4727 { 4728 uuid_t shared_cache_uuid; 4729 if (process->ReadMemory (sharedCacheUUID_address, shared_cache_uuid, sizeof (uuid_t), err) == sizeof (uuid_t)) 4730 { 4731 uuid.SetBytes (shared_cache_uuid); 4732 } 4733 } 4734 } 4735 } 4736 return uuid; 4737 } 4738 4739 UUID 4740 ObjectFileMachO::GetLLDBSharedCacheUUID () 4741 { 4742 UUID uuid; 4743 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__)) 4744 uint8_t *(*dyld_get_all_image_infos)(void); 4745 dyld_get_all_image_infos = (uint8_t*(*)()) dlsym (RTLD_DEFAULT, "_dyld_get_all_image_infos"); 4746 if (dyld_get_all_image_infos) 4747 { 4748 uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos(); 4749 if (dyld_all_image_infos_address) 4750 { 4751 uint32_t *version = (uint32_t*) dyld_all_image_infos_address; // version <mach-o/dyld_images.h> 4752 if (*version >= 13) 4753 { 4754 uuid_t *sharedCacheUUID_address = 0; 4755 int wordsize = sizeof (uint8_t *); 4756 if (wordsize == 8) 4757 { 4758 sharedCacheUUID_address = (uuid_t*) ((uint8_t*) dyld_all_image_infos_address + 160); // sharedCacheUUID <mach-o/dyld_images.h> 4759 } 4760 else 4761 { 4762 sharedCacheUUID_address = (uuid_t*) ((uint8_t*) dyld_all_image_infos_address + 84); // sharedCacheUUID <mach-o/dyld_images.h> 4763 } 4764 uuid.SetBytes (sharedCacheUUID_address); 4765 } 4766 } 4767 } 4768 #endif 4769 return uuid; 4770 } 4771 4772 uint32_t 4773 ObjectFileMachO::GetMinimumOSVersion (uint32_t *versions, uint32_t num_versions) 4774 { 4775 if (m_min_os_versions.empty()) 4776 { 4777 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 4778 bool success = false; 4779 for (uint32_t i=0; success == false && i < m_header.ncmds; ++i) 4780 { 4781 const lldb::offset_t load_cmd_offset = offset; 4782 4783 version_min_command lc; 4784 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL) 4785 break; 4786 if (lc.cmd == LC_VERSION_MIN_MACOSX || lc.cmd == LC_VERSION_MIN_IPHONEOS) 4787 { 4788 if (m_data.GetU32 (&offset, &lc.version, (sizeof(lc) / sizeof(uint32_t)) - 2)) 4789 { 4790 const uint32_t xxxx = lc.version >> 16; 4791 const uint32_t yy = (lc.version >> 8) & 0xffu; 4792 const uint32_t zz = lc.version & 0xffu; 4793 if (xxxx) 4794 { 4795 m_min_os_versions.push_back(xxxx); 4796 if (yy) 4797 { 4798 m_min_os_versions.push_back(yy); 4799 if (zz) 4800 m_min_os_versions.push_back(zz); 4801 } 4802 } 4803 success = true; 4804 } 4805 } 4806 offset = load_cmd_offset + lc.cmdsize; 4807 } 4808 4809 if (success == false) 4810 { 4811 // Push an invalid value so we don't keep trying to 4812 m_min_os_versions.push_back(UINT32_MAX); 4813 } 4814 } 4815 4816 if (m_min_os_versions.size() > 1 || m_min_os_versions[0] != UINT32_MAX) 4817 { 4818 if (versions != NULL && num_versions > 0) 4819 { 4820 for (size_t i=0; i<num_versions; ++i) 4821 { 4822 if (i < m_min_os_versions.size()) 4823 versions[i] = m_min_os_versions[i]; 4824 else 4825 versions[i] = 0; 4826 } 4827 } 4828 return m_min_os_versions.size(); 4829 } 4830 // Call the superclasses version that will empty out the data 4831 return ObjectFile::GetMinimumOSVersion (versions, num_versions); 4832 } 4833 4834 uint32_t 4835 ObjectFileMachO::GetSDKVersion(uint32_t *versions, uint32_t num_versions) 4836 { 4837 if (m_sdk_versions.empty()) 4838 { 4839 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 4840 bool success = false; 4841 for (uint32_t i=0; success == false && i < m_header.ncmds; ++i) 4842 { 4843 const lldb::offset_t load_cmd_offset = offset; 4844 4845 version_min_command lc; 4846 if (m_data.GetU32(&offset, &lc.cmd, 2) == NULL) 4847 break; 4848 if (lc.cmd == LC_VERSION_MIN_MACOSX || lc.cmd == LC_VERSION_MIN_IPHONEOS) 4849 { 4850 if (m_data.GetU32 (&offset, &lc.version, (sizeof(lc) / sizeof(uint32_t)) - 2)) 4851 { 4852 const uint32_t xxxx = lc.reserved >> 16; 4853 const uint32_t yy = (lc.reserved >> 8) & 0xffu; 4854 const uint32_t zz = lc.reserved & 0xffu; 4855 if (xxxx) 4856 { 4857 m_sdk_versions.push_back(xxxx); 4858 if (yy) 4859 { 4860 m_sdk_versions.push_back(yy); 4861 if (zz) 4862 m_sdk_versions.push_back(zz); 4863 } 4864 } 4865 success = true; 4866 } 4867 } 4868 offset = load_cmd_offset + lc.cmdsize; 4869 } 4870 4871 if (success == false) 4872 { 4873 // Push an invalid value so we don't keep trying to 4874 m_sdk_versions.push_back(UINT32_MAX); 4875 } 4876 } 4877 4878 if (m_sdk_versions.size() > 1 || m_sdk_versions[0] != UINT32_MAX) 4879 { 4880 if (versions != NULL && num_versions > 0) 4881 { 4882 for (size_t i=0; i<num_versions; ++i) 4883 { 4884 if (i < m_sdk_versions.size()) 4885 versions[i] = m_sdk_versions[i]; 4886 else 4887 versions[i] = 0; 4888 } 4889 } 4890 return m_sdk_versions.size(); 4891 } 4892 // Call the superclasses version that will empty out the data 4893 return ObjectFile::GetSDKVersion (versions, num_versions); 4894 } 4895 4896 4897 //------------------------------------------------------------------ 4898 // PluginInterface protocol 4899 //------------------------------------------------------------------ 4900 lldb_private::ConstString 4901 ObjectFileMachO::GetPluginName() 4902 { 4903 return GetPluginNameStatic(); 4904 } 4905 4906 uint32_t 4907 ObjectFileMachO::GetPluginVersion() 4908 { 4909 return 1; 4910 } 4911 4912 4913 bool 4914 ObjectFileMachO::SetLoadAddress (Target &target, 4915 lldb::addr_t value, 4916 bool value_is_offset) 4917 { 4918 bool changed = false; 4919 ModuleSP module_sp = GetModule(); 4920 if (module_sp) 4921 { 4922 size_t num_loaded_sections = 0; 4923 SectionList *section_list = GetSectionList (); 4924 if (section_list) 4925 { 4926 lldb::addr_t mach_base_file_addr = LLDB_INVALID_ADDRESS; 4927 const size_t num_sections = section_list->GetSize(); 4928 4929 const bool is_memory_image = (bool)m_process_wp.lock(); 4930 const Strata strata = GetStrata(); 4931 static ConstString g_linkedit_segname ("__LINKEDIT"); 4932 if (value_is_offset) 4933 { 4934 // "value" is an offset to apply to each top level segment 4935 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) 4936 { 4937 // Iterate through the object file sections to find all 4938 // of the sections that size on disk (to avoid __PAGEZERO) 4939 // and load them 4940 SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx)); 4941 if (section_sp && 4942 section_sp->GetFileSize() > 0 && 4943 section_sp->IsThreadSpecific() == false && 4944 module_sp.get() == section_sp->GetModule().get()) 4945 { 4946 // Ignore __LINKEDIT and __DWARF segments 4947 if (section_sp->GetName() == g_linkedit_segname) 4948 { 4949 // Only map __LINKEDIT if we have an in memory image and this isn't 4950 // a kernel binary like a kext or mach_kernel. 4951 if (is_memory_image == false || strata == eStrataKernel) 4952 continue; 4953 } 4954 if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + value)) 4955 ++num_loaded_sections; 4956 } 4957 } 4958 } 4959 else 4960 { 4961 // "value" is the new base address of the mach_header, adjust each 4962 // section accordingly 4963 4964 // First find the address of the mach header which is the first non-zero 4965 // file sized section whose file offset is zero as this will be subtracted 4966 // from each other valid section's vmaddr and then get "base_addr" added to 4967 // it when loading the module in the target 4968 for (size_t sect_idx = 0; 4969 sect_idx < num_sections && mach_base_file_addr == LLDB_INVALID_ADDRESS; 4970 ++sect_idx) 4971 { 4972 // Iterate through the object file sections to find all 4973 // of the sections that size on disk (to avoid __PAGEZERO) 4974 // and load them 4975 Section *section = section_list->GetSectionAtIndex (sect_idx).get(); 4976 if (section && 4977 section->GetFileSize() > 0 && 4978 section->GetFileOffset() == 0 && 4979 section->IsThreadSpecific() == false && 4980 module_sp.get() == section->GetModule().get()) 4981 { 4982 // Ignore __LINKEDIT and __DWARF segments 4983 if (section->GetName() == g_linkedit_segname) 4984 { 4985 // Only map __LINKEDIT if we have an in memory image and this isn't 4986 // a kernel binary like a kext or mach_kernel. 4987 if (is_memory_image == false || strata == eStrataKernel) 4988 continue; 4989 } 4990 mach_base_file_addr = section->GetFileAddress(); 4991 } 4992 } 4993 4994 if (mach_base_file_addr != LLDB_INVALID_ADDRESS) 4995 { 4996 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) 4997 { 4998 // Iterate through the object file sections to find all 4999 // of the sections that size on disk (to avoid __PAGEZERO) 5000 // and load them 5001 SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx)); 5002 if (section_sp && 5003 section_sp->GetFileSize() > 0 && 5004 section_sp->IsThreadSpecific() == false && 5005 module_sp.get() == section_sp->GetModule().get()) 5006 { 5007 // Ignore __LINKEDIT and __DWARF segments 5008 if (section_sp->GetName() == g_linkedit_segname) 5009 { 5010 // Only map __LINKEDIT if we have an in memory image and this isn't 5011 // a kernel binary like a kext or mach_kernel. 5012 if (is_memory_image == false || strata == eStrataKernel) 5013 continue; 5014 } 5015 if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() - mach_base_file_addr + value)) 5016 ++num_loaded_sections; 5017 } 5018 } 5019 } 5020 } 5021 } 5022 changed = num_loaded_sections > 0; 5023 return num_loaded_sections > 0; 5024 } 5025 return changed; 5026 } 5027 5028