1 //===-- ObjectFileELF.cpp ------------------------------------- -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "ObjectFileELF.h"
15 #include "lldb/Core/ArchSpec.h"
16 #include "lldb/Core/DataBuffer.h"
17 #include "lldb/Core/Error.h"
18 #include "lldb/Core/FileSpecList.h"
19 #include "lldb/Core/Log.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/ModuleSpec.h"
22 #include "lldb/Core/PluginManager.h"
23 #include "lldb/Core/Section.h"
24 #include "lldb/Core/Stream.h"
25 #include "lldb/Symbol/DWARFCallFrameInfo.h"
26 #include "lldb/Symbol/SymbolContext.h"
27 #include "lldb/Target/SectionLoadList.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Host/Host.h"
31 #include "llvm/ADT/PointerUnion.h"
33 #define CASE_AND_STREAM(s, def, width) \
34 case def: s->Printf("%-*s", width, #def); break;
37 using namespace lldb_private;
39 using namespace llvm::ELF;
42 //===----------------------------------------------------------------------===//
43 /// @class ELFRelocation
44 /// @brief Generic wrapper for ELFRel and ELFRela.
46 /// This helper class allows us to parse both ELFRel and ELFRela relocation
47 /// entries in a generic manner.
52 /// Constructs an ELFRelocation entry with a personality as given by @p
55 /// @param type Either DT_REL or DT_RELA. Any other value is invalid.
56 ELFRelocation(unsigned type);
61 Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
64 RelocType32(const ELFRelocation &rel);
67 RelocType64(const ELFRelocation &rel);
70 RelocSymbol32(const ELFRelocation &rel);
73 RelocSymbol64(const ELFRelocation &rel);
76 typedef llvm::PointerUnion<ELFRel*, ELFRela*> RelocUnion;
81 ELFRelocation::ELFRelocation(unsigned type)
85 else if (type == DT_RELA)
86 reloc = new ELFRela();
88 assert(false && "unexpected relocation type");
89 reloc = static_cast<ELFRel*>(NULL);
93 ELFRelocation::~ELFRelocation()
95 if (reloc.is<ELFRel*>())
96 delete reloc.get<ELFRel*>();
98 delete reloc.get<ELFRela*>();
102 ELFRelocation::Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)
104 if (reloc.is<ELFRel*>())
105 return reloc.get<ELFRel*>()->Parse(data, offset);
107 return reloc.get<ELFRela*>()->Parse(data, offset);
111 ELFRelocation::RelocType32(const ELFRelocation &rel)
113 if (rel.reloc.is<ELFRel*>())
114 return ELFRel::RelocType32(*rel.reloc.get<ELFRel*>());
116 return ELFRela::RelocType32(*rel.reloc.get<ELFRela*>());
120 ELFRelocation::RelocType64(const ELFRelocation &rel)
122 if (rel.reloc.is<ELFRel*>())
123 return ELFRel::RelocType64(*rel.reloc.get<ELFRel*>());
125 return ELFRela::RelocType64(*rel.reloc.get<ELFRela*>());
129 ELFRelocation::RelocSymbol32(const ELFRelocation &rel)
131 if (rel.reloc.is<ELFRel*>())
132 return ELFRel::RelocSymbol32(*rel.reloc.get<ELFRel*>());
134 return ELFRela::RelocSymbol32(*rel.reloc.get<ELFRela*>());
138 ELFRelocation::RelocSymbol64(const ELFRelocation &rel)
140 if (rel.reloc.is<ELFRel*>())
141 return ELFRel::RelocSymbol64(*rel.reloc.get<ELFRel*>());
143 return ELFRela::RelocSymbol64(*rel.reloc.get<ELFRela*>());
146 } // end anonymous namespace
149 ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset)
152 if (data.GetU32(offset, &n_namesz, 3) == NULL)
155 // The name field is required to be nul-terminated, and n_namesz
156 // includes the terminating nul in observed implementations (contrary
157 // to the ELF-64 spec). A special case is needed for cores generated
158 // by some older Linux versions, which write a note named "CORE"
159 // without a nul terminator and n_namesz = 4.
163 if (data.ExtractBytes (*offset, 4, data.GetByteOrder(), buf) != 4)
165 if (strncmp (buf, "CORE", 4) == 0)
173 const char *cstr = data.GetCStr(offset, llvm::RoundUpToAlignment (n_namesz, 4));
176 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SYMBOLS));
178 log->Printf("Failed to parse note name lacking nul terminator");
186 //------------------------------------------------------------------
188 //------------------------------------------------------------------
190 ObjectFileELF::Initialize()
192 PluginManager::RegisterPlugin(GetPluginNameStatic(),
193 GetPluginDescriptionStatic(),
195 CreateMemoryInstance,
196 GetModuleSpecifications);
200 ObjectFileELF::Terminate()
202 PluginManager::UnregisterPlugin(CreateInstance);
205 lldb_private::ConstString
206 ObjectFileELF::GetPluginNameStatic()
208 static ConstString g_name("elf");
213 ObjectFileELF::GetPluginDescriptionStatic()
215 return "ELF object file reader.";
219 ObjectFileELF::CreateInstance (const lldb::ModuleSP &module_sp,
220 DataBufferSP &data_sp,
221 lldb::offset_t data_offset,
222 const lldb_private::FileSpec* file,
223 lldb::offset_t file_offset,
224 lldb::offset_t length)
228 data_sp = file->MemoryMapFileContents(file_offset, length);
232 if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset))
234 const uint8_t *magic = data_sp->GetBytes() + data_offset;
235 if (ELFHeader::MagicBytesMatch(magic))
237 // Update the data to contain the entire file if it doesn't already
238 if (data_sp->GetByteSize() < length) {
239 data_sp = file->MemoryMapFileContents(file_offset, length);
241 magic = data_sp->GetBytes();
243 unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
244 if (address_size == 4 || address_size == 8)
246 std::unique_ptr<ObjectFileELF> objfile_ap(new ObjectFileELF(module_sp, data_sp, data_offset, file, file_offset, length));
248 if (objfile_ap->GetArchitecture(spec) &&
249 objfile_ap->SetModulesArchitecture(spec))
250 return objfile_ap.release();
259 ObjectFileELF::CreateMemoryInstance (const lldb::ModuleSP &module_sp,
260 DataBufferSP& data_sp,
261 const lldb::ProcessSP &process_sp,
262 lldb::addr_t header_addr)
268 ObjectFileELF::MagicBytesMatch (DataBufferSP& data_sp,
269 lldb::addr_t data_offset,
270 lldb::addr_t data_length)
272 if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset))
274 const uint8_t *magic = data_sp->GetBytes() + data_offset;
275 return ELFHeader::MagicBytesMatch(magic);
281 * crc function from http://svnweb.freebsd.org/base/head/sys/libkern/crc32.c
283 * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or
284 * code or tables extracted from it, as desired without restriction.
287 calc_gnu_debuglink_crc32(const void *buf, size_t size)
289 static const uint32_t g_crc32_tab[] =
291 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
292 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
293 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
294 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
295 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
296 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
297 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
298 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
299 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
300 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
301 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
302 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
303 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
304 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
305 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
306 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
307 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
308 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
309 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
310 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
311 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
312 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
313 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
314 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
315 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
316 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
317 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
318 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
319 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
320 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
321 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
322 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
323 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
324 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
325 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
326 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
327 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
328 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
329 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
330 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
331 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
332 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
333 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
335 const uint8_t *p = (const uint8_t *)buf;
340 crc = g_crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
345 ObjectFileELF::GetModuleSpecifications (const lldb_private::FileSpec& file,
346 lldb::DataBufferSP& data_sp,
347 lldb::offset_t data_offset,
348 lldb::offset_t file_offset,
349 lldb::offset_t length,
350 lldb_private::ModuleSpecList &specs)
352 const size_t initial_count = specs.GetSize();
354 if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize()))
357 data.SetData(data_sp);
358 elf::ELFHeader header;
359 if (header.Parse(data, &data_offset))
364 spec.GetFileSpec() = file;
365 spec.GetArchitecture().SetArchitecture(eArchTypeELF,
367 LLDB_INVALID_CPUTYPE);
368 if (spec.GetArchitecture().IsValid())
370 // We could parse the ABI tag information (in .note, .notes, or .note.ABI-tag) to get the
371 // machine information. However, this info isn't guaranteed to exist or be correct. Details:
372 // http://refspecs.linuxfoundation.org/LSB_1.2.0/gLSB/noteabitag.html
373 // Instead of passing potentially incorrect information down the pipeline, grab
374 // the host information and use it.
375 spec.GetArchitecture().GetTriple().setOSName (Host::GetOSString().GetCString());
376 spec.GetArchitecture().GetTriple().setVendorName(Host::GetVendorString().GetCString());
378 // Try to get the UUID from the section list. Usually that's at the end, so
379 // map the file in if we don't have it already.
380 size_t section_header_end = header.e_shoff + header.e_shnum * header.e_shentsize;
381 if (section_header_end > data_sp->GetByteSize())
383 data_sp = file.MemoryMapFileContents (file_offset, section_header_end);
384 data.SetData(data_sp);
387 uint32_t gnu_debuglink_crc = 0;
388 std::string gnu_debuglink_file;
389 SectionHeaderColl section_headers;
390 lldb_private::UUID &uuid = spec.GetUUID();
391 GetSectionHeaderInfo(section_headers, data, header, uuid, gnu_debuglink_file, gnu_debuglink_crc);
395 if (!gnu_debuglink_crc)
397 // Need to map entire file into memory to calculate the crc.
398 data_sp = file.MemoryMapFileContents (file_offset, SIZE_MAX);
399 data.SetData(data_sp);
400 gnu_debuglink_crc = calc_gnu_debuglink_crc32 (data.GetDataStart(), data.GetByteSize());
402 if (gnu_debuglink_crc)
404 // Use 4 bytes of crc from the .gnu_debuglink section.
405 uint32_t uuidt[4] = { gnu_debuglink_crc, 0, 0, 0 };
406 uuid.SetBytes (uuidt, sizeof(uuidt));
416 return specs.GetSize() - initial_count;
419 //------------------------------------------------------------------
420 // PluginInterface protocol
421 //------------------------------------------------------------------
422 lldb_private::ConstString
423 ObjectFileELF::GetPluginName()
425 return GetPluginNameStatic();
429 ObjectFileELF::GetPluginVersion()
431 return m_plugin_version;
433 //------------------------------------------------------------------
434 // ObjectFile protocol
435 //------------------------------------------------------------------
437 ObjectFileELF::ObjectFileELF (const lldb::ModuleSP &module_sp,
438 DataBufferSP& data_sp,
439 lldb::offset_t data_offset,
440 const FileSpec* file,
441 lldb::offset_t file_offset,
442 lldb::offset_t length) :
443 ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
451 ::memset(&m_header, 0, sizeof(m_header));
452 m_gnu_debuglink_crc = 0;
453 m_gnu_debuglink_file.clear();
456 ObjectFileELF::~ObjectFileELF()
461 ObjectFileELF::IsExecutable() const
463 return m_header.e_entry != 0;
467 ObjectFileELF::SetLoadAddress (Target &target,
469 bool value_is_offset)
471 ModuleSP module_sp = GetModule();
474 size_t num_loaded_sections = 0;
475 SectionList *section_list = GetSectionList ();
480 const size_t num_sections = section_list->GetSize();
483 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
485 // Iterate through the object file sections to find all
486 // of the sections that have SHF_ALLOC in their flag bits.
487 SectionSP section_sp (section_list->GetSectionAtIndex (sect_idx));
488 // if (section_sp && !section_sp->IsThreadSpecific())
489 if (section_sp && section_sp->Test(SHF_ALLOC))
491 if (target.GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress() + value))
492 ++num_loaded_sections;
495 return num_loaded_sections > 0;
499 // Not sure how to slide an ELF file given the base address
500 // of the ELF file in memory
504 return false; // If it changed
508 ObjectFileELF::GetByteOrder() const
510 if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
511 return eByteOrderBig;
512 if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
513 return eByteOrderLittle;
514 return eByteOrderInvalid;
518 ObjectFileELF::GetAddressByteSize() const
520 return m_data.GetAddressByteSize();
524 ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I)
526 return std::distance(m_section_headers.begin(), I) + 1u;
530 ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const
532 return std::distance(m_section_headers.begin(), I) + 1u;
536 ObjectFileELF::ParseHeader()
538 lldb::offset_t offset = 0;
539 return m_header.Parse(m_data, &offset);
543 ObjectFileELF::GetUUID(lldb_private::UUID* uuid)
545 // Need to parse the section list to get the UUIDs, so make sure that's been done.
546 if (!ParseSectionHeaders())
549 if (m_uuid.IsValid())
551 // We have the full build id uuid.
557 if (!m_gnu_debuglink_crc)
558 m_gnu_debuglink_crc = calc_gnu_debuglink_crc32 (m_data.GetDataStart(), m_data.GetByteSize());
559 if (m_gnu_debuglink_crc)
561 // Use 4 bytes of crc from the .gnu_debuglink section.
562 uint32_t uuidt[4] = { m_gnu_debuglink_crc, 0, 0, 0 };
563 uuid->SetBytes (uuidt, sizeof(uuidt));
571 lldb_private::FileSpecList
572 ObjectFileELF::GetDebugSymbolFilePaths()
574 FileSpecList file_spec_list;
576 if (!m_gnu_debuglink_file.empty())
578 FileSpec file_spec (m_gnu_debuglink_file.c_str(), false);
579 file_spec_list.Append (file_spec);
581 return file_spec_list;
585 ObjectFileELF::GetDependentModules(FileSpecList &files)
587 size_t num_modules = ParseDependentModules();
588 uint32_t num_specs = 0;
590 for (unsigned i = 0; i < num_modules; ++i)
592 if (files.AppendIfUnique(m_filespec_ap->GetFileSpecAtIndex(i)))
600 ObjectFileELF::GetImageInfoAddress(Target *target)
602 if (!ParseDynamicSymbols())
605 SectionList *section_list = GetSectionList();
609 // Find the SHT_DYNAMIC (.dynamic) section.
610 SectionSP dynsym_section_sp (section_list->FindSectionByType (eSectionTypeELFDynamicLinkInfo, true));
611 if (!dynsym_section_sp)
613 assert (dynsym_section_sp->GetObjectFile() == this);
615 user_id_t dynsym_id = dynsym_section_sp->GetID();
616 const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
620 for (size_t i = 0; i < m_dynamic_symbols.size(); ++i)
622 ELFDynamic &symbol = m_dynamic_symbols[i];
624 if (symbol.d_tag == DT_DEBUG)
626 // Compute the offset as the number of previous entries plus the
628 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
629 return Address(dynsym_section_sp, offset);
631 else if (symbol.d_tag == DT_MIPS_RLD_MAP && target)
633 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
634 addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target);
635 if (dyn_base == LLDB_INVALID_ADDRESS)
639 if (target->ReadPointerFromMemory(dyn_base + offset, false, error, addr))
647 lldb_private::Address
648 ObjectFileELF::GetEntryPointAddress ()
650 if (m_entry_point_address.IsValid())
651 return m_entry_point_address;
653 if (!ParseHeader() || !IsExecutable())
654 return m_entry_point_address;
656 SectionList *section_list = GetSectionList();
657 addr_t offset = m_header.e_entry;
660 m_entry_point_address.SetOffset(offset);
662 m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
663 return m_entry_point_address;
666 //----------------------------------------------------------------------
667 // ParseDependentModules
668 //----------------------------------------------------------------------
670 ObjectFileELF::ParseDependentModules()
672 if (m_filespec_ap.get())
673 return m_filespec_ap->GetSize();
675 m_filespec_ap.reset(new FileSpecList());
677 if (!ParseSectionHeaders())
680 SectionList *section_list = GetSectionList();
684 // Find the SHT_DYNAMIC section.
685 Section *dynsym = section_list->FindSectionByType (eSectionTypeELFDynamicLinkInfo, true).get();
688 assert (dynsym->GetObjectFile() == this);
690 const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex (dynsym->GetID());
693 // sh_link: section header index of string table used by entries in the section.
694 Section *dynstr = section_list->FindSectionByID (header->sh_link + 1).get();
698 DataExtractor dynsym_data;
699 DataExtractor dynstr_data;
700 if (ReadSectionData(dynsym, dynsym_data) &&
701 ReadSectionData(dynstr, dynstr_data))
704 const lldb::offset_t section_size = dynsym_data.GetByteSize();
705 lldb::offset_t offset = 0;
707 // The only type of entries we are concerned with are tagged DT_NEEDED,
708 // yielding the name of a required library.
709 while (offset < section_size)
711 if (!symbol.Parse(dynsym_data, &offset))
714 if (symbol.d_tag != DT_NEEDED)
717 uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
718 const char *lib_name = dynstr_data.PeekCStr(str_index);
719 m_filespec_ap->Append(FileSpec(lib_name, true));
723 return m_filespec_ap->GetSize();
726 //----------------------------------------------------------------------
727 // ParseProgramHeaders
728 //----------------------------------------------------------------------
730 ObjectFileELF::ParseProgramHeaders()
732 // We have already parsed the program headers
733 if (!m_program_headers.empty())
734 return m_program_headers.size();
736 // If there are no program headers to read we are done.
737 if (m_header.e_phnum == 0)
740 m_program_headers.resize(m_header.e_phnum);
741 if (m_program_headers.size() != m_header.e_phnum)
744 const size_t ph_size = m_header.e_phnum * m_header.e_phentsize;
745 const elf_off ph_offset = m_header.e_phoff;
747 if (GetData (ph_offset, ph_size, data) != ph_size)
751 lldb::offset_t offset;
752 for (idx = 0, offset = 0; idx < m_header.e_phnum; ++idx)
754 if (m_program_headers[idx].Parse(data, &offset) == false)
758 if (idx < m_program_headers.size())
759 m_program_headers.resize(idx);
761 return m_program_headers.size();
765 ParseNoteGNUBuildID(DataExtractor &data, lldb_private::UUID &uuid)
767 // Try to parse the note section (ie .note.gnu.build-id|.notes|.note|...) and get the build id.
768 // BuildID documentation: https://fedoraproject.org/wiki/Releases/FeatureBuildId
769 lldb::offset_t offset = 0;
770 static const uint32_t g_gnu_build_id = 3; // NT_GNU_BUILD_ID from elf.h
774 ELFNote note = ELFNote();
775 if (!note.Parse(data, &offset))
778 // 16 bytes is UUID|MD5, 20 bytes is SHA1
779 if (note.n_name == "GNU" && (note.n_type == g_gnu_build_id) &&
780 (note.n_descsz == 16 || note.n_descsz == 20))
783 if (data.GetU8 (&offset, &uuidbuf, note.n_descsz) == NULL)
785 uuid.SetBytes (uuidbuf, note.n_descsz);
788 offset += llvm::RoundUpToAlignment(note.n_descsz, 4);
793 //----------------------------------------------------------------------
794 // GetSectionHeaderInfo
795 //----------------------------------------------------------------------
797 ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl §ion_headers,
798 lldb_private::DataExtractor &object_data,
799 const elf::ELFHeader &header,
800 lldb_private::UUID &uuid,
801 std::string &gnu_debuglink_file,
802 uint32_t &gnu_debuglink_crc)
804 // We have already parsed the section headers
805 if (!section_headers.empty())
806 return section_headers.size();
808 // If there are no section headers we are done.
809 if (header.e_shnum == 0)
812 section_headers.resize(header.e_shnum);
813 if (section_headers.size() != header.e_shnum)
816 const size_t sh_size = header.e_shnum * header.e_shentsize;
817 const elf_off sh_offset = header.e_shoff;
818 DataExtractor sh_data;
819 if (sh_data.SetData (object_data, sh_offset, sh_size) != sh_size)
823 lldb::offset_t offset;
824 for (idx = 0, offset = 0; idx < header.e_shnum; ++idx)
826 if (section_headers[idx].Parse(sh_data, &offset) == false)
829 if (idx < section_headers.size())
830 section_headers.resize(idx);
832 const unsigned strtab_idx = header.e_shstrndx;
833 if (strtab_idx && strtab_idx < section_headers.size())
835 const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
836 const size_t byte_size = sheader.sh_size;
837 const Elf64_Off offset = sheader.sh_offset;
838 lldb_private::DataExtractor shstr_data;
840 if (shstr_data.SetData (object_data, offset, byte_size) == byte_size)
842 for (SectionHeaderCollIter I = section_headers.begin();
843 I != section_headers.end(); ++I)
845 static ConstString g_sect_name_gnu_debuglink (".gnu_debuglink");
846 const ELFSectionHeaderInfo &header = *I;
847 const uint64_t section_size = header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
848 ConstString name(shstr_data.PeekCStr(I->sh_name));
850 I->section_name = name;
852 if (name == g_sect_name_gnu_debuglink)
855 if (section_size && (data.SetData (object_data, header.sh_offset, section_size) == section_size))
857 lldb::offset_t gnu_debuglink_offset = 0;
858 gnu_debuglink_file = data.GetCStr (&gnu_debuglink_offset);
859 gnu_debuglink_offset = llvm::RoundUpToAlignment (gnu_debuglink_offset, 4);
860 data.GetU32 (&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
864 if (header.sh_type == SHT_NOTE && !uuid.IsValid())
867 if (section_size && (data.SetData (object_data, header.sh_offset, section_size) == section_size))
869 ParseNoteGNUBuildID (data, uuid);
874 return section_headers.size();
878 section_headers.clear();
883 ObjectFileELF::GetProgramHeaderCount()
885 return ParseProgramHeaders();
888 const elf::ELFProgramHeader *
889 ObjectFileELF::GetProgramHeaderByIndex(lldb::user_id_t id)
891 if (!id || !ParseProgramHeaders())
894 if (--id < m_program_headers.size())
895 return &m_program_headers[id];
901 ObjectFileELF::GetSegmentDataByIndex(lldb::user_id_t id)
903 const elf::ELFProgramHeader *segment_header = GetProgramHeaderByIndex(id);
904 if (segment_header == NULL)
905 return DataExtractor();
906 return DataExtractor(m_data, segment_header->p_offset, segment_header->p_filesz);
909 //----------------------------------------------------------------------
910 // ParseSectionHeaders
911 //----------------------------------------------------------------------
913 ObjectFileELF::ParseSectionHeaders()
915 return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid, m_gnu_debuglink_file, m_gnu_debuglink_crc);
918 const ObjectFileELF::ELFSectionHeaderInfo *
919 ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id)
921 if (!id || !ParseSectionHeaders())
924 if (--id < m_section_headers.size())
925 return &m_section_headers[id];
931 ObjectFileELF::CreateSections(SectionList &unified_section_list)
933 if (!m_sections_ap.get() && ParseSectionHeaders())
935 m_sections_ap.reset(new SectionList());
937 for (SectionHeaderCollIter I = m_section_headers.begin();
938 I != m_section_headers.end(); ++I)
940 const ELFSectionHeaderInfo &header = *I;
942 ConstString& name = I->section_name;
943 const uint64_t file_size = header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
944 const uint64_t vm_size = header.sh_flags & SHF_ALLOC ? header.sh_size : 0;
946 static ConstString g_sect_name_text (".text");
947 static ConstString g_sect_name_data (".data");
948 static ConstString g_sect_name_bss (".bss");
949 static ConstString g_sect_name_tdata (".tdata");
950 static ConstString g_sect_name_tbss (".tbss");
951 static ConstString g_sect_name_dwarf_debug_abbrev (".debug_abbrev");
952 static ConstString g_sect_name_dwarf_debug_aranges (".debug_aranges");
953 static ConstString g_sect_name_dwarf_debug_frame (".debug_frame");
954 static ConstString g_sect_name_dwarf_debug_info (".debug_info");
955 static ConstString g_sect_name_dwarf_debug_line (".debug_line");
956 static ConstString g_sect_name_dwarf_debug_loc (".debug_loc");
957 static ConstString g_sect_name_dwarf_debug_macinfo (".debug_macinfo");
958 static ConstString g_sect_name_dwarf_debug_pubnames (".debug_pubnames");
959 static ConstString g_sect_name_dwarf_debug_pubtypes (".debug_pubtypes");
960 static ConstString g_sect_name_dwarf_debug_ranges (".debug_ranges");
961 static ConstString g_sect_name_dwarf_debug_str (".debug_str");
962 static ConstString g_sect_name_eh_frame (".eh_frame");
964 SectionType sect_type = eSectionTypeOther;
966 bool is_thread_specific = false;
968 if (name == g_sect_name_text) sect_type = eSectionTypeCode;
969 else if (name == g_sect_name_data) sect_type = eSectionTypeData;
970 else if (name == g_sect_name_bss) sect_type = eSectionTypeZeroFill;
971 else if (name == g_sect_name_tdata)
973 sect_type = eSectionTypeData;
974 is_thread_specific = true;
976 else if (name == g_sect_name_tbss)
978 sect_type = eSectionTypeZeroFill;
979 is_thread_specific = true;
981 // .debug_abbrev – Abbreviations used in the .debug_info section
982 // .debug_aranges – Lookup table for mapping addresses to compilation units
983 // .debug_frame – Call frame information
984 // .debug_info – The core DWARF information section
985 // .debug_line – Line number information
986 // .debug_loc – Location lists used in DW_AT_location attributes
987 // .debug_macinfo – Macro information
988 // .debug_pubnames – Lookup table for mapping object and function names to compilation units
989 // .debug_pubtypes – Lookup table for mapping type names to compilation units
990 // .debug_ranges – Address ranges used in DW_AT_ranges attributes
991 // .debug_str – String table used in .debug_info
992 // MISSING? .gnu_debugdata - "mini debuginfo / MiniDebugInfo" section, http://sourceware.org/gdb/onlinedocs/gdb/MiniDebugInfo.html
993 // MISSING? .debug-index - http://src.chromium.org/viewvc/chrome/trunk/src/build/gdb-add-index?pathrev=144644
994 // MISSING? .debug_types - Type descriptions from DWARF 4? See http://gcc.gnu.org/wiki/DwarfSeparateTypeInfo
995 else if (name == g_sect_name_dwarf_debug_abbrev) sect_type = eSectionTypeDWARFDebugAbbrev;
996 else if (name == g_sect_name_dwarf_debug_aranges) sect_type = eSectionTypeDWARFDebugAranges;
997 else if (name == g_sect_name_dwarf_debug_frame) sect_type = eSectionTypeDWARFDebugFrame;
998 else if (name == g_sect_name_dwarf_debug_info) sect_type = eSectionTypeDWARFDebugInfo;
999 else if (name == g_sect_name_dwarf_debug_line) sect_type = eSectionTypeDWARFDebugLine;
1000 else if (name == g_sect_name_dwarf_debug_loc) sect_type = eSectionTypeDWARFDebugLoc;
1001 else if (name == g_sect_name_dwarf_debug_macinfo) sect_type = eSectionTypeDWARFDebugMacInfo;
1002 else if (name == g_sect_name_dwarf_debug_pubnames) sect_type = eSectionTypeDWARFDebugPubNames;
1003 else if (name == g_sect_name_dwarf_debug_pubtypes) sect_type = eSectionTypeDWARFDebugPubTypes;
1004 else if (name == g_sect_name_dwarf_debug_ranges) sect_type = eSectionTypeDWARFDebugRanges;
1005 else if (name == g_sect_name_dwarf_debug_str) sect_type = eSectionTypeDWARFDebugStr;
1006 else if (name == g_sect_name_eh_frame) sect_type = eSectionTypeEHFrame;
1008 switch (header.sh_type)
1011 assert (sect_type == eSectionTypeOther);
1012 sect_type = eSectionTypeELFSymbolTable;
1015 assert (sect_type == eSectionTypeOther);
1016 sect_type = eSectionTypeELFDynamicSymbols;
1020 assert (sect_type == eSectionTypeOther);
1021 sect_type = eSectionTypeELFRelocationEntries;
1024 assert (sect_type == eSectionTypeOther);
1025 sect_type = eSectionTypeELFDynamicLinkInfo;
1029 SectionSP section_sp (new Section(GetModule(), // Module to which this section belongs.
1030 this, // ObjectFile to which this section belongs and should read section data from.
1031 SectionIndex(I), // Section ID.
1032 name, // Section name.
1033 sect_type, // Section type.
1034 header.sh_addr, // VM address.
1035 vm_size, // VM size in bytes of this section.
1036 header.sh_offset, // Offset of this section in the file.
1037 file_size, // Size of the section as found in the file.
1038 header.sh_flags)); // Flags for this section.
1040 if (is_thread_specific)
1041 section_sp->SetIsThreadSpecific (is_thread_specific);
1042 m_sections_ap->AddSection(section_sp);
1046 if (m_sections_ap.get())
1048 if (GetType() == eTypeDebugInfo)
1050 static const SectionType g_sections[] =
1052 eSectionTypeDWARFDebugAranges,
1053 eSectionTypeDWARFDebugInfo,
1054 eSectionTypeDWARFDebugAbbrev,
1055 eSectionTypeDWARFDebugFrame,
1056 eSectionTypeDWARFDebugLine,
1057 eSectionTypeDWARFDebugStr,
1058 eSectionTypeDWARFDebugLoc,
1059 eSectionTypeDWARFDebugMacInfo,
1060 eSectionTypeDWARFDebugPubNames,
1061 eSectionTypeDWARFDebugPubTypes,
1062 eSectionTypeDWARFDebugRanges,
1063 eSectionTypeELFSymbolTable,
1065 SectionList *elf_section_list = m_sections_ap.get();
1066 for (size_t idx = 0; idx < sizeof(g_sections) / sizeof(g_sections[0]); ++idx)
1068 SectionType section_type = g_sections[idx];
1069 SectionSP section_sp (elf_section_list->FindSectionByType (section_type, true));
1072 SectionSP module_section_sp (unified_section_list.FindSectionByType (section_type, true));
1073 if (module_section_sp)
1074 unified_section_list.ReplaceSection (module_section_sp->GetID(), section_sp);
1076 unified_section_list.AddSection (section_sp);
1082 unified_section_list = *m_sections_ap;
1089 ObjectFileELF::ParseSymbols (Symtab *symtab,
1091 SectionList *section_list,
1092 const size_t num_symbols,
1093 const DataExtractor &symtab_data,
1094 const DataExtractor &strtab_data)
1097 lldb::offset_t offset = 0;
1099 static ConstString text_section_name(".text");
1100 static ConstString init_section_name(".init");
1101 static ConstString fini_section_name(".fini");
1102 static ConstString ctors_section_name(".ctors");
1103 static ConstString dtors_section_name(".dtors");
1105 static ConstString data_section_name(".data");
1106 static ConstString rodata_section_name(".rodata");
1107 static ConstString rodata1_section_name(".rodata1");
1108 static ConstString data2_section_name(".data1");
1109 static ConstString bss_section_name(".bss");
1111 //StreamFile strm(stdout, false);
1113 for (i = 0; i < num_symbols; ++i)
1115 if (symbol.Parse(symtab_data, &offset) == false)
1118 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
1120 // No need to add symbols that have no names
1121 if (symbol_name == NULL || symbol_name[0] == '\0')
1124 //symbol.Dump (&strm, i, &strtab_data, section_list);
1126 SectionSP symbol_section_sp;
1127 SymbolType symbol_type = eSymbolTypeInvalid;
1128 Elf64_Half symbol_idx = symbol.st_shndx;
1133 symbol_type = eSymbolTypeAbsolute;
1136 symbol_type = eSymbolTypeUndefined;
1139 symbol_section_sp = section_list->GetSectionAtIndex(symbol_idx);
1143 // If a symbol is undefined do not process it further even if it has a STT type
1144 if (symbol_type != eSymbolTypeUndefined)
1146 switch (symbol.getType())
1150 // The symbol's type is not specified.
1154 // The symbol is associated with a data object, such as a variable,
1156 symbol_type = eSymbolTypeData;
1160 // The symbol is associated with a function or other executable code.
1161 symbol_type = eSymbolTypeCode;
1165 // The symbol is associated with a section. Symbol table entries of
1166 // this type exist primarily for relocation and normally have
1167 // STB_LOCAL binding.
1171 // Conventionally, the symbol's name gives the name of the source
1172 // file associated with the object file. A file symbol has STB_LOCAL
1173 // binding, its section index is SHN_ABS, and it precedes the other
1174 // STB_LOCAL symbols for the file, if it is present.
1175 symbol_type = eSymbolTypeSourceFile;
1179 // The symbol is associated with an indirect function. The actual
1180 // function will be resolved if it is referenced.
1181 symbol_type = eSymbolTypeResolver;
1186 if (symbol_type == eSymbolTypeInvalid)
1188 if (symbol_section_sp)
1190 const ConstString §_name = symbol_section_sp->GetName();
1191 if (sect_name == text_section_name ||
1192 sect_name == init_section_name ||
1193 sect_name == fini_section_name ||
1194 sect_name == ctors_section_name ||
1195 sect_name == dtors_section_name)
1197 symbol_type = eSymbolTypeCode;
1199 else if (sect_name == data_section_name ||
1200 sect_name == data2_section_name ||
1201 sect_name == rodata_section_name ||
1202 sect_name == rodata1_section_name ||
1203 sect_name == bss_section_name)
1205 symbol_type = eSymbolTypeData;
1210 // If the symbol section we've found has no data (SHT_NOBITS), then check the module section
1211 // list. This can happen if we're parsing the debug file and it has no .text section, for example.
1212 if (symbol_section_sp && (symbol_section_sp->GetFileSize() == 0))
1214 ModuleSP module_sp(GetModule());
1217 SectionList *module_section_list = module_sp->GetSectionList();
1218 if (module_section_list && module_section_list != section_list)
1220 const ConstString §_name = symbol_section_sp->GetName();
1221 lldb::SectionSP section_sp (module_section_list->FindSectionByName (sect_name));
1222 if (section_sp && section_sp->GetFileSize())
1224 symbol_section_sp = section_sp;
1230 uint64_t symbol_value = symbol.st_value;
1231 if (symbol_section_sp)
1232 symbol_value -= symbol_section_sp->GetFileAddress();
1233 bool is_global = symbol.getBinding() == STB_GLOBAL;
1234 uint32_t flags = symbol.st_other << 8 | symbol.st_info;
1235 bool is_mangled = symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
1237 i + start_id, // ID is the original symbol table index.
1238 symbol_name, // Symbol name.
1239 is_mangled, // Is the symbol name mangled?
1240 symbol_type, // Type of this symbol
1241 is_global, // Is this globally visible?
1242 false, // Is this symbol debug info?
1243 false, // Is this symbol a trampoline?
1244 false, // Is this symbol artificial?
1245 symbol_section_sp, // Section in which this symbol is defined or null.
1246 symbol_value, // Offset in section or symbol value.
1247 symbol.st_size, // Size in bytes of this symbol.
1248 true, // Size is valid
1249 flags); // Symbol flags.
1250 symtab->AddSymbol(dc_symbol);
1257 ObjectFileELF::ParseSymbolTable(Symtab *symbol_table, user_id_t start_id, lldb_private::Section *symtab)
1259 if (symtab->GetObjectFile() != this)
1261 // If the symbol table section is owned by a different object file, have it do the
1263 ObjectFileELF *obj_file_elf = static_cast<ObjectFileELF *>(symtab->GetObjectFile());
1264 return obj_file_elf->ParseSymbolTable (symbol_table, start_id, symtab);
1267 // Get section list for this object file.
1268 SectionList *section_list = m_sections_ap.get();
1272 user_id_t symtab_id = symtab->GetID();
1273 const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
1274 assert(symtab_hdr->sh_type == SHT_SYMTAB ||
1275 symtab_hdr->sh_type == SHT_DYNSYM);
1277 // sh_link: section header index of associated string table.
1278 // Section ID's are ones based.
1279 user_id_t strtab_id = symtab_hdr->sh_link + 1;
1280 Section *strtab = section_list->FindSectionByID(strtab_id).get();
1282 unsigned num_symbols = 0;
1283 if (symtab && strtab)
1285 assert (symtab->GetObjectFile() == this);
1286 assert (strtab->GetObjectFile() == this);
1288 DataExtractor symtab_data;
1289 DataExtractor strtab_data;
1290 if (ReadSectionData(symtab, symtab_data) &&
1291 ReadSectionData(strtab, strtab_data))
1293 size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
1295 num_symbols = ParseSymbols(symbol_table, start_id,
1296 section_list, num_symbols,
1297 symtab_data, strtab_data);
1305 ObjectFileELF::ParseDynamicSymbols()
1307 if (m_dynamic_symbols.size())
1308 return m_dynamic_symbols.size();
1310 SectionList *section_list = GetSectionList();
1314 // Find the SHT_DYNAMIC section.
1315 Section *dynsym = section_list->FindSectionByType (eSectionTypeELFDynamicLinkInfo, true).get();
1318 assert (dynsym->GetObjectFile() == this);
1321 DataExtractor dynsym_data;
1322 if (ReadSectionData(dynsym, dynsym_data))
1324 const lldb::offset_t section_size = dynsym_data.GetByteSize();
1325 lldb::offset_t cursor = 0;
1327 while (cursor < section_size)
1329 if (!symbol.Parse(dynsym_data, &cursor))
1332 m_dynamic_symbols.push_back(symbol);
1336 return m_dynamic_symbols.size();
1340 ObjectFileELF::FindDynamicSymbol(unsigned tag)
1342 if (!ParseDynamicSymbols())
1345 DynamicSymbolCollIter I = m_dynamic_symbols.begin();
1346 DynamicSymbolCollIter E = m_dynamic_symbols.end();
1347 for ( ; I != E; ++I)
1349 ELFDynamic *symbol = &*I;
1351 if (symbol->d_tag == tag)
1359 ObjectFileELF::PLTRelocationType()
1362 // This member specifies the type of relocation entry to which the
1363 // procedure linkage table refers. The d_val member holds DT_REL or
1364 // DT_RELA, as appropriate. All relocations in a procedure linkage table
1365 // must use the same relocation.
1366 const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
1369 return symbol->d_val;
1375 ParsePLTRelocations(Symtab *symbol_table,
1378 const ELFHeader *hdr,
1379 const ELFSectionHeader *rel_hdr,
1380 const ELFSectionHeader *plt_hdr,
1381 const ELFSectionHeader *sym_hdr,
1382 const lldb::SectionSP &plt_section_sp,
1383 DataExtractor &rel_data,
1384 DataExtractor &symtab_data,
1385 DataExtractor &strtab_data)
1387 ELFRelocation rel(rel_type);
1389 lldb::offset_t offset = 0;
1390 // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are 16 bytes.
1391 // So round the entsize up by the alignment if addralign is set.
1392 const elf_xword plt_entsize = plt_hdr->sh_addralign ?
1393 llvm::RoundUpToAlignment (plt_hdr->sh_entsize, plt_hdr->sh_addralign) : plt_hdr->sh_entsize;
1394 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
1396 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
1397 reloc_info_fn reloc_type;
1398 reloc_info_fn reloc_symbol;
1402 reloc_type = ELFRelocation::RelocType32;
1403 reloc_symbol = ELFRelocation::RelocSymbol32;
1407 reloc_type = ELFRelocation::RelocType64;
1408 reloc_symbol = ELFRelocation::RelocSymbol64;
1411 unsigned slot_type = hdr->GetRelocationJumpSlotType();
1413 for (i = 0; i < num_relocations; ++i)
1415 if (rel.Parse(rel_data, &offset) == false)
1418 if (reloc_type(rel) != slot_type)
1421 lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
1422 uint64_t plt_index = (i + 1) * plt_entsize;
1424 if (!symbol.Parse(symtab_data, &symbol_offset))
1427 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
1428 bool is_mangled = symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
1431 i + start_id, // Symbol table index
1432 symbol_name, // symbol name.
1433 is_mangled, // is the symbol name mangled?
1434 eSymbolTypeTrampoline, // Type of this symbol
1435 false, // Is this globally visible?
1436 false, // Is this symbol debug info?
1437 true, // Is this symbol a trampoline?
1438 true, // Is this symbol artificial?
1439 plt_section_sp, // Section in which this symbol is defined or null.
1440 plt_index, // Offset in section or symbol value.
1441 plt_entsize, // Size in bytes of this symbol.
1442 true, // Size is valid
1443 0); // Symbol flags.
1445 symbol_table->AddSymbol(jump_symbol);
1452 ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table,
1454 const ELFSectionHeaderInfo *rel_hdr,
1457 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
1459 // The link field points to the associated symbol table. The info field
1460 // points to the section holding the plt.
1461 user_id_t symtab_id = rel_hdr->sh_link;
1462 user_id_t plt_id = rel_hdr->sh_info;
1464 if (!symtab_id || !plt_id)
1467 // Section ID's are ones based;
1471 const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
1475 const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
1479 SectionList *section_list = m_sections_ap.get();
1483 Section *rel_section = section_list->FindSectionByID(rel_id).get();
1487 SectionSP plt_section_sp (section_list->FindSectionByID(plt_id));
1488 if (!plt_section_sp)
1491 Section *symtab = section_list->FindSectionByID(symtab_id).get();
1495 // sh_link points to associated string table.
1496 Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link + 1).get();
1500 DataExtractor rel_data;
1501 if (!ReadSectionData(rel_section, rel_data))
1504 DataExtractor symtab_data;
1505 if (!ReadSectionData(symtab, symtab_data))
1508 DataExtractor strtab_data;
1509 if (!ReadSectionData(strtab, strtab_data))
1512 unsigned rel_type = PLTRelocationType();
1516 return ParsePLTRelocations (symbol_table,
1530 ObjectFileELF::GetSymtab()
1532 ModuleSP module_sp(GetModule());
1536 // We always want to use the main object file so we (hopefully) only have one cached copy
1537 // of our symtab, dynamic sections, etc.
1538 ObjectFile *module_obj_file = module_sp->GetObjectFile();
1539 if (module_obj_file && module_obj_file != this)
1540 return module_obj_file->GetSymtab();
1542 if (m_symtab_ap.get() == NULL)
1544 SectionList *section_list = GetSectionList();
1548 uint64_t symbol_id = 0;
1549 lldb_private::Mutex::Locker locker(module_sp->GetMutex());
1551 m_symtab_ap.reset(new Symtab(this));
1553 // Sharable objects and dynamic executables usually have 2 distinct symbol
1554 // tables, one named ".symtab", and the other ".dynsym". The dynsym is a smaller
1555 // version of the symtab that only contains global symbols. The information found
1556 // in the dynsym is therefore also found in the symtab, while the reverse is not
1557 // necessarily true.
1558 Section *symtab = section_list->FindSectionByType (eSectionTypeELFSymbolTable, true).get();
1561 // The symtab section is non-allocable and can be stripped, so if it doesn't exist
1562 // then use the dynsym section which should always be there.
1563 symtab = section_list->FindSectionByType (eSectionTypeELFDynamicSymbols, true).get();
1566 symbol_id += ParseSymbolTable (m_symtab_ap.get(), symbol_id, symtab);
1569 // If present, this entry's d_ptr member holds the address of relocation
1570 // entries associated solely with the procedure linkage table. Separating
1571 // these relocation entries lets the dynamic linker ignore them during
1572 // process initialization, if lazy binding is enabled. If this entry is
1573 // present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
1575 const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
1578 // Synthesize trampoline symbols to help navigate the PLT.
1579 addr_t addr = symbol->d_ptr;
1580 Section *reloc_section = section_list->FindSectionContainingFileAddress(addr).get();
1583 user_id_t reloc_id = reloc_section->GetID();
1584 const ELFSectionHeaderInfo *reloc_header = GetSectionHeaderByIndex(reloc_id);
1585 assert(reloc_header);
1587 ParseTrampolineSymbols (m_symtab_ap.get(), symbol_id, reloc_header, reloc_id);
1591 return m_symtab_ap.get();
1595 ObjectFileELF::ResolveSymbolForAddress(const Address& so_addr, bool verify_unique)
1597 if (!m_symtab_ap.get())
1598 return nullptr; // GetSymtab() should be called first.
1600 const SectionList *section_list = GetSectionList();
1604 if (DWARFCallFrameInfo *eh_frame = GetUnwindTable().GetEHFrameInfo())
1607 if (eh_frame->GetAddressRange (so_addr, range))
1609 const addr_t file_addr = range.GetBaseAddress().GetFileAddress();
1610 Symbol * symbol = verify_unique ? m_symtab_ap->FindSymbolContainingFileAddress(file_addr) : nullptr;
1614 // Note that a (stripped) symbol won't be found by GetSymtab()...
1615 lldb::SectionSP eh_sym_section_sp = section_list->FindSectionContainingFileAddress(file_addr);
1616 if (eh_sym_section_sp.get())
1618 addr_t section_base = eh_sym_section_sp->GetFileAddress();
1619 addr_t offset = file_addr - section_base;
1620 uint64_t symbol_id = m_symtab_ap->GetNumSymbols();
1623 symbol_id, // Symbol table index.
1624 "???", // Symbol name.
1625 false, // Is the symbol name mangled?
1626 eSymbolTypeCode, // Type of this symbol.
1627 true, // Is this globally visible?
1628 false, // Is this symbol debug info?
1629 false, // Is this symbol a trampoline?
1630 true, // Is this symbol artificial?
1631 eh_sym_section_sp, // Section in which this symbol is defined or null.
1632 offset, // Offset in section or symbol value.
1633 range.GetByteSize(), // Size in bytes of this symbol.
1634 true, // Size is valid.
1635 0); // Symbol flags.
1636 if (symbol_id == m_symtab_ap->AddSymbol(eh_symbol))
1637 return m_symtab_ap->SymbolAtIndex(symbol_id);
1646 ObjectFileELF::IsStripped ()
1648 // TODO: determine this for ELF
1652 //===----------------------------------------------------------------------===//
1655 // Dump the specifics of the runtime file container (such as any headers
1656 // segments, sections, etc).
1657 //----------------------------------------------------------------------
1659 ObjectFileELF::Dump(Stream *s)
1661 DumpELFHeader(s, m_header);
1663 DumpELFProgramHeaders(s);
1665 DumpELFSectionHeaders(s);
1667 SectionList *section_list = GetSectionList();
1669 section_list->Dump(s, NULL, true, UINT32_MAX);
1670 Symtab *symtab = GetSymtab();
1672 symtab->Dump(s, NULL, eSortOrderNone);
1674 DumpDependentModules(s);
1678 //----------------------------------------------------------------------
1681 // Dump the ELF header to the specified output stream
1682 //----------------------------------------------------------------------
1684 ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header)
1686 s->PutCString("ELF Header\n");
1687 s->Printf("e_ident[EI_MAG0 ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
1688 s->Printf("e_ident[EI_MAG1 ] = 0x%2.2x '%c'\n",
1689 header.e_ident[EI_MAG1], header.e_ident[EI_MAG1]);
1690 s->Printf("e_ident[EI_MAG2 ] = 0x%2.2x '%c'\n",
1691 header.e_ident[EI_MAG2], header.e_ident[EI_MAG2]);
1692 s->Printf("e_ident[EI_MAG3 ] = 0x%2.2x '%c'\n",
1693 header.e_ident[EI_MAG3], header.e_ident[EI_MAG3]);
1695 s->Printf("e_ident[EI_CLASS ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
1696 s->Printf("e_ident[EI_DATA ] = 0x%2.2x ", header.e_ident[EI_DATA]);
1697 DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
1698 s->Printf ("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
1699 s->Printf ("e_ident[EI_PAD ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
1701 s->Printf("e_type = 0x%4.4x ", header.e_type);
1702 DumpELFHeader_e_type(s, header.e_type);
1703 s->Printf("\ne_machine = 0x%4.4x\n", header.e_machine);
1704 s->Printf("e_version = 0x%8.8x\n", header.e_version);
1705 s->Printf("e_entry = 0x%8.8" PRIx64 "\n", header.e_entry);
1706 s->Printf("e_phoff = 0x%8.8" PRIx64 "\n", header.e_phoff);
1707 s->Printf("e_shoff = 0x%8.8" PRIx64 "\n", header.e_shoff);
1708 s->Printf("e_flags = 0x%8.8x\n", header.e_flags);
1709 s->Printf("e_ehsize = 0x%4.4x\n", header.e_ehsize);
1710 s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
1711 s->Printf("e_phnum = 0x%4.4x\n", header.e_phnum);
1712 s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
1713 s->Printf("e_shnum = 0x%4.4x\n", header.e_shnum);
1714 s->Printf("e_shstrndx = 0x%4.4x\n", header.e_shstrndx);
1717 //----------------------------------------------------------------------
1718 // DumpELFHeader_e_type
1720 // Dump an token value for the ELF header member e_type
1721 //----------------------------------------------------------------------
1723 ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type)
1727 case ET_NONE: *s << "ET_NONE"; break;
1728 case ET_REL: *s << "ET_REL"; break;
1729 case ET_EXEC: *s << "ET_EXEC"; break;
1730 case ET_DYN: *s << "ET_DYN"; break;
1731 case ET_CORE: *s << "ET_CORE"; break;
1737 //----------------------------------------------------------------------
1738 // DumpELFHeader_e_ident_EI_DATA
1740 // Dump an token value for the ELF header member e_ident[EI_DATA]
1741 //----------------------------------------------------------------------
1743 ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s, unsigned char ei_data)
1747 case ELFDATANONE: *s << "ELFDATANONE"; break;
1748 case ELFDATA2LSB: *s << "ELFDATA2LSB - Little Endian"; break;
1749 case ELFDATA2MSB: *s << "ELFDATA2MSB - Big Endian"; break;
1756 //----------------------------------------------------------------------
1757 // DumpELFProgramHeader
1759 // Dump a single ELF program header to the specified output stream
1760 //----------------------------------------------------------------------
1762 ObjectFileELF::DumpELFProgramHeader(Stream *s, const ELFProgramHeader &ph)
1764 DumpELFProgramHeader_p_type(s, ph.p_type);
1765 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset, ph.p_vaddr, ph.p_paddr);
1766 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz, ph.p_flags);
1768 DumpELFProgramHeader_p_flags(s, ph.p_flags);
1769 s->Printf(") %8.8" PRIx64, ph.p_align);
1772 //----------------------------------------------------------------------
1773 // DumpELFProgramHeader_p_type
1775 // Dump an token value for the ELF program header member p_type which
1776 // describes the type of the program header
1777 // ----------------------------------------------------------------------
1779 ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type)
1781 const int kStrWidth = 15;
1784 CASE_AND_STREAM(s, PT_NULL , kStrWidth);
1785 CASE_AND_STREAM(s, PT_LOAD , kStrWidth);
1786 CASE_AND_STREAM(s, PT_DYNAMIC , kStrWidth);
1787 CASE_AND_STREAM(s, PT_INTERP , kStrWidth);
1788 CASE_AND_STREAM(s, PT_NOTE , kStrWidth);
1789 CASE_AND_STREAM(s, PT_SHLIB , kStrWidth);
1790 CASE_AND_STREAM(s, PT_PHDR , kStrWidth);
1791 CASE_AND_STREAM(s, PT_TLS , kStrWidth);
1792 CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
1794 s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
1800 //----------------------------------------------------------------------
1801 // DumpELFProgramHeader_p_flags
1803 // Dump an token value for the ELF program header member p_flags
1804 //----------------------------------------------------------------------
1806 ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags)
1808 *s << ((p_flags & PF_X) ? "PF_X" : " ")
1809 << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
1810 << ((p_flags & PF_W) ? "PF_W" : " ")
1811 << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
1812 << ((p_flags & PF_R) ? "PF_R" : " ");
1815 //----------------------------------------------------------------------
1816 // DumpELFProgramHeaders
1818 // Dump all of the ELF program header to the specified output stream
1819 //----------------------------------------------------------------------
1821 ObjectFileELF::DumpELFProgramHeaders(Stream *s)
1823 if (ParseProgramHeaders())
1825 s->PutCString("Program Headers\n");
1826 s->PutCString("IDX p_type p_offset p_vaddr p_paddr "
1827 "p_filesz p_memsz p_flags p_align\n");
1828 s->PutCString("==== --------------- -------- -------- -------- "
1829 "-------- -------- ------------------------- --------\n");
1832 for (ProgramHeaderCollConstIter I = m_program_headers.begin();
1833 I != m_program_headers.end(); ++I, ++idx)
1835 s->Printf("[%2u] ", idx);
1836 ObjectFileELF::DumpELFProgramHeader(s, *I);
1842 //----------------------------------------------------------------------
1843 // DumpELFSectionHeader
1845 // Dump a single ELF section header to the specified output stream
1846 //----------------------------------------------------------------------
1848 ObjectFileELF::DumpELFSectionHeader(Stream *s, const ELFSectionHeaderInfo &sh)
1850 s->Printf("%8.8x ", sh.sh_name);
1851 DumpELFSectionHeader_sh_type(s, sh.sh_type);
1852 s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
1853 DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
1854 s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr, sh.sh_offset, sh.sh_size);
1855 s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
1856 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
1859 //----------------------------------------------------------------------
1860 // DumpELFSectionHeader_sh_type
1862 // Dump an token value for the ELF section header member sh_type which
1863 // describes the type of the section
1864 //----------------------------------------------------------------------
1866 ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type)
1868 const int kStrWidth = 12;
1871 CASE_AND_STREAM(s, SHT_NULL , kStrWidth);
1872 CASE_AND_STREAM(s, SHT_PROGBITS , kStrWidth);
1873 CASE_AND_STREAM(s, SHT_SYMTAB , kStrWidth);
1874 CASE_AND_STREAM(s, SHT_STRTAB , kStrWidth);
1875 CASE_AND_STREAM(s, SHT_RELA , kStrWidth);
1876 CASE_AND_STREAM(s, SHT_HASH , kStrWidth);
1877 CASE_AND_STREAM(s, SHT_DYNAMIC , kStrWidth);
1878 CASE_AND_STREAM(s, SHT_NOTE , kStrWidth);
1879 CASE_AND_STREAM(s, SHT_NOBITS , kStrWidth);
1880 CASE_AND_STREAM(s, SHT_REL , kStrWidth);
1881 CASE_AND_STREAM(s, SHT_SHLIB , kStrWidth);
1882 CASE_AND_STREAM(s, SHT_DYNSYM , kStrWidth);
1883 CASE_AND_STREAM(s, SHT_LOPROC , kStrWidth);
1884 CASE_AND_STREAM(s, SHT_HIPROC , kStrWidth);
1885 CASE_AND_STREAM(s, SHT_LOUSER , kStrWidth);
1886 CASE_AND_STREAM(s, SHT_HIUSER , kStrWidth);
1888 s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
1893 //----------------------------------------------------------------------
1894 // DumpELFSectionHeader_sh_flags
1896 // Dump an token value for the ELF section header member sh_flags
1897 //----------------------------------------------------------------------
1899 ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s, elf_xword sh_flags)
1901 *s << ((sh_flags & SHF_WRITE) ? "WRITE" : " ")
1902 << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
1903 << ((sh_flags & SHF_ALLOC) ? "ALLOC" : " ")
1904 << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
1905 << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : " ");
1908 //----------------------------------------------------------------------
1909 // DumpELFSectionHeaders
1911 // Dump all of the ELF section header to the specified output stream
1912 //----------------------------------------------------------------------
1914 ObjectFileELF::DumpELFSectionHeaders(Stream *s)
1916 if (!ParseSectionHeaders())
1919 s->PutCString("Section Headers\n");
1920 s->PutCString("IDX name type flags "
1921 "addr offset size link info addralgn "
1923 s->PutCString("==== -------- ------------ -------------------------------- "
1924 "-------- -------- -------- -------- -------- -------- "
1925 "-------- ====================\n");
1928 for (SectionHeaderCollConstIter I = m_section_headers.begin();
1929 I != m_section_headers.end(); ++I, ++idx)
1931 s->Printf("[%2u] ", idx);
1932 ObjectFileELF::DumpELFSectionHeader(s, *I);
1933 const char* section_name = I->section_name.AsCString("");
1935 *s << ' ' << section_name << "\n";
1940 ObjectFileELF::DumpDependentModules(lldb_private::Stream *s)
1942 size_t num_modules = ParseDependentModules();
1944 if (num_modules > 0)
1946 s->PutCString("Dependent Modules:\n");
1947 for (unsigned i = 0; i < num_modules; ++i)
1949 const FileSpec &spec = m_filespec_ap->GetFileSpecAtIndex(i);
1950 s->Printf(" %s\n", spec.GetFilename().GetCString());
1956 ObjectFileELF::GetArchitecture (ArchSpec &arch)
1961 arch.SetArchitecture (eArchTypeELF, m_header.e_machine, LLDB_INVALID_CPUTYPE);
1962 arch.GetTriple().setOSName (Host::GetOSString().GetCString());
1963 arch.GetTriple().setVendorName(Host::GetVendorString().GetCString());
1968 ObjectFileELF::CalculateType()
1970 switch (m_header.e_type)
1972 case llvm::ELF::ET_NONE:
1974 return eTypeUnknown;
1976 case llvm::ELF::ET_REL:
1977 // 1 - Relocatable file
1978 return eTypeObjectFile;
1980 case llvm::ELF::ET_EXEC:
1981 // 2 - Executable file
1982 return eTypeExecutable;
1984 case llvm::ELF::ET_DYN:
1985 // 3 - Shared object file
1986 return eTypeSharedLibrary;
1990 return eTypeCoreFile;
1995 return eTypeUnknown;
1999 ObjectFileELF::CalculateStrata()
2001 switch (m_header.e_type)
2003 case llvm::ELF::ET_NONE:
2005 return eStrataUnknown;
2007 case llvm::ELF::ET_REL:
2008 // 1 - Relocatable file
2009 return eStrataUnknown;
2011 case llvm::ELF::ET_EXEC:
2012 // 2 - Executable file
2013 // TODO: is there any way to detect that an executable is a kernel
2014 // related executable by inspecting the program headers, section
2015 // headers, symbols, or any other flag bits???
2018 case llvm::ELF::ET_DYN:
2019 // 3 - Shared object file
2020 // TODO: is there any way to detect that an shared library is a kernel
2021 // related executable by inspecting the program headers, section
2022 // headers, symbols, or any other flag bits???
2023 return eStrataUnknown;
2027 // TODO: is there any way to detect that an core file is a kernel
2028 // related executable by inspecting the program headers, section
2029 // headers, symbols, or any other flag bits???
2030 return eStrataUnknown;
2035 return eStrataUnknown;