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