xref: /llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp (revision 5ce9c5657cb77c0f1919be0aa3c990009a7bc60b)
1 //===-- ObjectFileELF.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 "ObjectFileELF.h"
11 
12 #include <cassert>
13 #include <algorithm>
14 
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/Module.h"
20 #include "lldb/Core/PluginManager.h"
21 #include "lldb/Core/Section.h"
22 #include "lldb/Core/Stream.h"
23 #include "lldb/Symbol/SymbolContext.h"
24 #include "lldb/Host/Host.h"
25 
26 #include "llvm/ADT/PointerUnion.h"
27 
28 #define CASE_AND_STREAM(s, def, width)                  \
29     case def: s->Printf("%-*s", width, #def); break;
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 using namespace elf;
34 using namespace llvm::ELF;
35 
36 namespace {
37 //===----------------------------------------------------------------------===//
38 /// @class ELFRelocation
39 /// @brief Generic wrapper for ELFRel and ELFRela.
40 ///
41 /// This helper class allows us to parse both ELFRel and ELFRela relocation
42 /// entries in a generic manner.
43 class ELFRelocation
44 {
45 public:
46 
47     /// Constructs an ELFRelocation entry with a personality as given by @p
48     /// type.
49     ///
50     /// @param type Either DT_REL or DT_RELA.  Any other value is invalid.
51     ELFRelocation(unsigned type);
52 
53     ~ELFRelocation();
54 
55     bool
56     Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
57 
58     static unsigned
59     RelocType32(const ELFRelocation &rel);
60 
61     static unsigned
62     RelocType64(const ELFRelocation &rel);
63 
64     static unsigned
65     RelocSymbol32(const ELFRelocation &rel);
66 
67     static unsigned
68     RelocSymbol64(const ELFRelocation &rel);
69 
70 private:
71     typedef llvm::PointerUnion<ELFRel*, ELFRela*> RelocUnion;
72 
73     RelocUnion reloc;
74 };
75 
76 ELFRelocation::ELFRelocation(unsigned type)
77 {
78     if (type == DT_REL)
79         reloc = new ELFRel();
80     else if (type == DT_RELA)
81         reloc = new ELFRela();
82     else {
83         assert(false && "unexpected relocation type");
84         reloc = static_cast<ELFRel*>(NULL);
85     }
86 }
87 
88 ELFRelocation::~ELFRelocation()
89 {
90     if (reloc.is<ELFRel*>())
91         delete reloc.get<ELFRel*>();
92     else
93         delete reloc.get<ELFRela*>();
94 }
95 
96 bool
97 ELFRelocation::Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)
98 {
99     if (reloc.is<ELFRel*>())
100         return reloc.get<ELFRel*>()->Parse(data, offset);
101     else
102         return reloc.get<ELFRela*>()->Parse(data, offset);
103 }
104 
105 unsigned
106 ELFRelocation::RelocType32(const ELFRelocation &rel)
107 {
108     if (rel.reloc.is<ELFRel*>())
109         return ELFRel::RelocType32(*rel.reloc.get<ELFRel*>());
110     else
111         return ELFRela::RelocType32(*rel.reloc.get<ELFRela*>());
112 }
113 
114 unsigned
115 ELFRelocation::RelocType64(const ELFRelocation &rel)
116 {
117     if (rel.reloc.is<ELFRel*>())
118         return ELFRel::RelocType64(*rel.reloc.get<ELFRel*>());
119     else
120         return ELFRela::RelocType64(*rel.reloc.get<ELFRela*>());
121 }
122 
123 unsigned
124 ELFRelocation::RelocSymbol32(const ELFRelocation &rel)
125 {
126     if (rel.reloc.is<ELFRel*>())
127         return ELFRel::RelocSymbol32(*rel.reloc.get<ELFRel*>());
128     else
129         return ELFRela::RelocSymbol32(*rel.reloc.get<ELFRela*>());
130 }
131 
132 unsigned
133 ELFRelocation::RelocSymbol64(const ELFRelocation &rel)
134 {
135     if (rel.reloc.is<ELFRel*>())
136         return ELFRel::RelocSymbol64(*rel.reloc.get<ELFRel*>());
137     else
138         return ELFRela::RelocSymbol64(*rel.reloc.get<ELFRela*>());
139 }
140 
141 } // end anonymous namespace
142 
143 //------------------------------------------------------------------
144 // Static methods.
145 //------------------------------------------------------------------
146 void
147 ObjectFileELF::Initialize()
148 {
149     PluginManager::RegisterPlugin(GetPluginNameStatic(),
150                                   GetPluginDescriptionStatic(),
151                                   CreateInstance,
152                                   CreateMemoryInstance);
153 }
154 
155 void
156 ObjectFileELF::Terminate()
157 {
158     PluginManager::UnregisterPlugin(CreateInstance);
159 }
160 
161 const char *
162 ObjectFileELF::GetPluginNameStatic()
163 {
164     return "object-file.elf";
165 }
166 
167 const char *
168 ObjectFileELF::GetPluginDescriptionStatic()
169 {
170     return "ELF object file reader.";
171 }
172 
173 ObjectFile *
174 ObjectFileELF::CreateInstance (const lldb::ModuleSP &module_sp,
175                                DataBufferSP &data_sp,
176                                lldb::offset_t data_offset,
177                                const lldb_private::FileSpec* file,
178                                lldb::offset_t file_offset,
179                                lldb::offset_t length)
180 {
181     if (!data_sp)
182     {
183         data_sp = file->MemoryMapFileContents(file_offset, length);
184         data_offset = 0;
185     }
186 
187     if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset))
188     {
189         const uint8_t *magic = data_sp->GetBytes() + data_offset;
190         if (ELFHeader::MagicBytesMatch(magic))
191         {
192             // Update the data to contain the entire file
193             // Update the data to contain the entire file if it doesn't already
194             if (data_sp->GetByteSize() < length)
195                 data_sp = file->MemoryMapFileContents(file_offset, length);
196             unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
197             if (address_size == 4 || address_size == 8)
198             {
199                 std::auto_ptr<ObjectFileELF> objfile_ap(new ObjectFileELF(module_sp, data_sp, data_offset, file, file_offset, length));
200                 ArchSpec spec;
201                 if (objfile_ap->GetArchitecture(spec) &&
202                     objfile_ap->SetModulesArchitecture(spec))
203                     return objfile_ap.release();
204             }
205         }
206     }
207     return NULL;
208 }
209 
210 
211 ObjectFile*
212 ObjectFileELF::CreateMemoryInstance (const lldb::ModuleSP &module_sp,
213                                      DataBufferSP& data_sp,
214                                      const lldb::ProcessSP &process_sp,
215                                      lldb::addr_t header_addr)
216 {
217     return NULL;
218 }
219 
220 
221 //------------------------------------------------------------------
222 // PluginInterface protocol
223 //------------------------------------------------------------------
224 const char *
225 ObjectFileELF::GetPluginName()
226 {
227     return "ObjectFileELF";
228 }
229 
230 const char *
231 ObjectFileELF::GetShortPluginName()
232 {
233     return GetPluginNameStatic();
234 }
235 
236 uint32_t
237 ObjectFileELF::GetPluginVersion()
238 {
239     return m_plugin_version;
240 }
241 //------------------------------------------------------------------
242 // ObjectFile protocol
243 //------------------------------------------------------------------
244 
245 ObjectFileELF::ObjectFileELF (const lldb::ModuleSP &module_sp,
246                               DataBufferSP& data_sp,
247                               lldb::offset_t data_offset,
248                               const FileSpec* file,
249                               lldb::offset_t file_offset,
250                               lldb::offset_t length) :
251     ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
252     m_header(),
253     m_program_headers(),
254     m_section_headers(),
255     m_sections_ap(),
256     m_symtab_ap(),
257     m_filespec_ap(),
258     m_shstr_data()
259 {
260     if (file)
261         m_file = *file;
262     ::memset(&m_header, 0, sizeof(m_header));
263 }
264 
265 ObjectFileELF::~ObjectFileELF()
266 {
267 }
268 
269 bool
270 ObjectFileELF::IsExecutable() const
271 {
272     return m_header.e_entry != 0;
273 }
274 
275 ByteOrder
276 ObjectFileELF::GetByteOrder() const
277 {
278     if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
279         return eByteOrderBig;
280     if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
281         return eByteOrderLittle;
282     return eByteOrderInvalid;
283 }
284 
285 uint32_t
286 ObjectFileELF::GetAddressByteSize() const
287 {
288     return m_data.GetAddressByteSize();
289 }
290 
291 size_t
292 ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I)
293 {
294     return std::distance(m_section_headers.begin(), I) + 1u;
295 }
296 
297 size_t
298 ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const
299 {
300     return std::distance(m_section_headers.begin(), I) + 1u;
301 }
302 
303 bool
304 ObjectFileELF::ParseHeader()
305 {
306     lldb::offset_t offset = GetFileOffset();
307     return m_header.Parse(m_data, &offset);
308 }
309 
310 bool
311 ObjectFileELF::GetUUID(lldb_private::UUID* uuid)
312 {
313     // FIXME: Return MD5 sum here.  See comment in ObjectFile.h.
314     return false;
315 }
316 
317 uint32_t
318 ObjectFileELF::GetDependentModules(FileSpecList &files)
319 {
320     size_t num_modules = ParseDependentModules();
321     uint32_t num_specs = 0;
322 
323     for (unsigned i = 0; i < num_modules; ++i)
324     {
325         if (files.AppendIfUnique(m_filespec_ap->GetFileSpecAtIndex(i)))
326             num_specs++;
327     }
328 
329     return num_specs;
330 }
331 
332 user_id_t
333 ObjectFileELF::GetSectionIndexByType(unsigned type)
334 {
335     if (!ParseSectionHeaders())
336         return 0;
337 
338     for (SectionHeaderCollIter sh_pos = m_section_headers.begin();
339          sh_pos != m_section_headers.end(); ++sh_pos)
340     {
341         if (sh_pos->sh_type == type)
342             return SectionIndex(sh_pos);
343     }
344 
345     return 0;
346 }
347 
348 Address
349 ObjectFileELF::GetImageInfoAddress()
350 {
351     if (!ParseDynamicSymbols())
352         return Address();
353 
354     SectionList *section_list = GetSectionList();
355     if (!section_list)
356         return Address();
357 
358     user_id_t dynsym_id = GetSectionIndexByType(SHT_DYNAMIC);
359     if (!dynsym_id)
360         return Address();
361 
362     const ELFSectionHeader *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
363     if (!dynsym_hdr)
364         return Address();
365 
366     SectionSP dynsym_section_sp (section_list->FindSectionByID(dynsym_id));
367     if (dynsym_section_sp)
368     {
369         for (size_t i = 0; i < m_dynamic_symbols.size(); ++i)
370         {
371             ELFDynamic &symbol = m_dynamic_symbols[i];
372 
373             if (symbol.d_tag == DT_DEBUG)
374             {
375                 // Compute the offset as the number of previous entries plus the
376                 // size of d_tag.
377                 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
378                 return Address(dynsym_section_sp, offset);
379             }
380         }
381     }
382 
383     return Address();
384 }
385 
386 lldb_private::Address
387 ObjectFileELF::GetEntryPointAddress ()
388 {
389     SectionList *sections;
390     addr_t offset;
391 
392     if (m_entry_point_address.IsValid())
393         return m_entry_point_address;
394 
395     if (!ParseHeader() || !IsExecutable())
396         return m_entry_point_address;
397 
398     sections = GetSectionList();
399     offset = m_header.e_entry;
400 
401     if (!sections)
402     {
403         m_entry_point_address.SetOffset(offset);
404         return m_entry_point_address;
405     }
406 
407     m_entry_point_address.ResolveAddressUsingFileSections(offset, sections);
408 
409     return m_entry_point_address;
410 }
411 
412 //----------------------------------------------------------------------
413 // ParseDependentModules
414 //----------------------------------------------------------------------
415 size_t
416 ObjectFileELF::ParseDependentModules()
417 {
418     if (m_filespec_ap.get())
419         return m_filespec_ap->GetSize();
420 
421     m_filespec_ap.reset(new FileSpecList());
422 
423     if (!(ParseSectionHeaders() && GetSectionHeaderStringTable()))
424         return 0;
425 
426     // Locate the dynamic table.
427     user_id_t dynsym_id = 0;
428     user_id_t dynstr_id = 0;
429     for (SectionHeaderCollIter sh_pos = m_section_headers.begin();
430          sh_pos != m_section_headers.end(); ++sh_pos)
431     {
432         if (sh_pos->sh_type == SHT_DYNAMIC)
433         {
434             dynsym_id = SectionIndex(sh_pos);
435             dynstr_id = sh_pos->sh_link + 1; // Section ID's are 1 based.
436             break;
437         }
438     }
439 
440     if (!(dynsym_id && dynstr_id))
441         return 0;
442 
443     SectionList *section_list = GetSectionList();
444     if (!section_list)
445         return 0;
446 
447     // Resolve and load the dynamic table entries and corresponding string
448     // table.
449     Section *dynsym = section_list->FindSectionByID(dynsym_id).get();
450     Section *dynstr = section_list->FindSectionByID(dynstr_id).get();
451     if (!(dynsym && dynstr))
452         return 0;
453 
454     DataExtractor dynsym_data;
455     DataExtractor dynstr_data;
456     if (ReadSectionData(dynsym, dynsym_data) &&
457         ReadSectionData(dynstr, dynstr_data))
458     {
459         ELFDynamic symbol;
460         const lldb::offset_t section_size = dynsym_data.GetByteSize();
461         lldb::offset_t offset = 0;
462 
463         // The only type of entries we are concerned with are tagged DT_NEEDED,
464         // yielding the name of a required library.
465         while (offset < section_size)
466         {
467             if (!symbol.Parse(dynsym_data, &offset))
468                 break;
469 
470             if (symbol.d_tag != DT_NEEDED)
471                 continue;
472 
473             uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
474             const char *lib_name = dynstr_data.PeekCStr(str_index);
475             m_filespec_ap->Append(FileSpec(lib_name, true));
476         }
477     }
478 
479     return m_filespec_ap->GetSize();
480 }
481 
482 //----------------------------------------------------------------------
483 // ParseProgramHeaders
484 //----------------------------------------------------------------------
485 size_t
486 ObjectFileELF::ParseProgramHeaders()
487 {
488     // We have already parsed the program headers
489     if (!m_program_headers.empty())
490         return m_program_headers.size();
491 
492     // If there are no program headers to read we are done.
493     if (m_header.e_phnum == 0)
494         return 0;
495 
496     m_program_headers.resize(m_header.e_phnum);
497     if (m_program_headers.size() != m_header.e_phnum)
498         return 0;
499 
500     const size_t ph_size = m_header.e_phnum * m_header.e_phentsize;
501     const elf_off ph_offset = m_header.e_phoff;
502     DataExtractor data;
503     if (GetData (ph_offset, ph_size, data) != ph_size)
504         return 0;
505 
506     uint32_t idx;
507     lldb::offset_t offset;
508     for (idx = 0, offset = 0; idx < m_header.e_phnum; ++idx)
509     {
510         if (m_program_headers[idx].Parse(data, &offset) == false)
511             break;
512     }
513 
514     if (idx < m_program_headers.size())
515         m_program_headers.resize(idx);
516 
517     return m_program_headers.size();
518 }
519 
520 //----------------------------------------------------------------------
521 // ParseSectionHeaders
522 //----------------------------------------------------------------------
523 size_t
524 ObjectFileELF::ParseSectionHeaders()
525 {
526     // We have already parsed the section headers
527     if (!m_section_headers.empty())
528         return m_section_headers.size();
529 
530     // If there are no section headers we are done.
531     if (m_header.e_shnum == 0)
532         return 0;
533 
534     m_section_headers.resize(m_header.e_shnum);
535     if (m_section_headers.size() != m_header.e_shnum)
536         return 0;
537 
538     const size_t sh_size = m_header.e_shnum * m_header.e_shentsize;
539     const elf_off sh_offset = m_header.e_shoff;
540     DataExtractor data;
541     if (GetData (sh_offset, sh_size, data) != sh_size)
542         return 0;
543 
544     uint32_t idx;
545     lldb::offset_t offset;
546     for (idx = 0, offset = 0; idx < m_header.e_shnum; ++idx)
547     {
548         if (m_section_headers[idx].Parse(data, &offset) == false)
549             break;
550     }
551     if (idx < m_section_headers.size())
552         m_section_headers.resize(idx);
553 
554     return m_section_headers.size();
555 }
556 
557 size_t
558 ObjectFileELF::GetSectionHeaderStringTable()
559 {
560     if (m_shstr_data.GetByteSize() == 0)
561     {
562         const unsigned strtab_idx = m_header.e_shstrndx;
563 
564         if (strtab_idx && strtab_idx < m_section_headers.size())
565         {
566             const ELFSectionHeader &sheader = m_section_headers[strtab_idx];
567             const size_t byte_size = sheader.sh_size;
568             const Elf64_Off offset = sheader.sh_offset;
569             m_shstr_data.SetData (m_data, offset, byte_size);
570 
571             if (m_shstr_data.GetByteSize() != byte_size)
572                 return 0;
573         }
574     }
575     return m_shstr_data.GetByteSize();
576 }
577 
578 lldb::user_id_t
579 ObjectFileELF::GetSectionIndexByName(const char *name)
580 {
581     if (!(ParseSectionHeaders() && GetSectionHeaderStringTable()))
582         return 0;
583 
584     // Search the collection of section headers for one with a matching name.
585     for (SectionHeaderCollIter I = m_section_headers.begin();
586          I != m_section_headers.end(); ++I)
587     {
588         const char *sectionName = m_shstr_data.PeekCStr(I->sh_name);
589 
590         if (!sectionName)
591             return 0;
592 
593         if (strcmp(name, sectionName) != 0)
594             continue;
595 
596         return SectionIndex(I);
597     }
598 
599     return 0;
600 }
601 
602 const elf::ELFSectionHeader *
603 ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id)
604 {
605     if (!ParseSectionHeaders() || !id)
606         return NULL;
607 
608     if (--id < m_section_headers.size())
609         return &m_section_headers[id];
610 
611     return NULL;
612 }
613 
614 SectionList *
615 ObjectFileELF::GetSectionList()
616 {
617     if (m_sections_ap.get())
618         return m_sections_ap.get();
619 
620     if (ParseSectionHeaders() && GetSectionHeaderStringTable())
621     {
622         m_sections_ap.reset(new SectionList());
623 
624         for (SectionHeaderCollIter I = m_section_headers.begin();
625              I != m_section_headers.end(); ++I)
626         {
627             const ELFSectionHeader &header = *I;
628 
629             ConstString name(m_shstr_data.PeekCStr(header.sh_name));
630             const uint64_t file_size = header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
631             const uint64_t vm_size = header.sh_flags & SHF_ALLOC ? header.sh_size : 0;
632 
633             static ConstString g_sect_name_text (".text");
634             static ConstString g_sect_name_data (".data");
635             static ConstString g_sect_name_bss (".bss");
636             static ConstString g_sect_name_tdata (".tdata");
637             static ConstString g_sect_name_tbss (".tbss");
638             static ConstString g_sect_name_dwarf_debug_abbrev (".debug_abbrev");
639             static ConstString g_sect_name_dwarf_debug_aranges (".debug_aranges");
640             static ConstString g_sect_name_dwarf_debug_frame (".debug_frame");
641             static ConstString g_sect_name_dwarf_debug_info (".debug_info");
642             static ConstString g_sect_name_dwarf_debug_line (".debug_line");
643             static ConstString g_sect_name_dwarf_debug_loc (".debug_loc");
644             static ConstString g_sect_name_dwarf_debug_macinfo (".debug_macinfo");
645             static ConstString g_sect_name_dwarf_debug_pubnames (".debug_pubnames");
646             static ConstString g_sect_name_dwarf_debug_pubtypes (".debug_pubtypes");
647             static ConstString g_sect_name_dwarf_debug_ranges (".debug_ranges");
648             static ConstString g_sect_name_dwarf_debug_str (".debug_str");
649             static ConstString g_sect_name_eh_frame (".eh_frame");
650 
651             SectionType sect_type = eSectionTypeOther;
652 
653             bool is_thread_specific = false;
654 
655             if      (name == g_sect_name_text)                  sect_type = eSectionTypeCode;
656             else if (name == g_sect_name_data)                  sect_type = eSectionTypeData;
657             else if (name == g_sect_name_bss)                   sect_type = eSectionTypeZeroFill;
658             else if (name == g_sect_name_tdata)
659             {
660                 sect_type = eSectionTypeData;
661                 is_thread_specific = true;
662             }
663             else if (name == g_sect_name_tbss)
664             {
665                 sect_type = eSectionTypeZeroFill;
666                 is_thread_specific = true;
667             }
668             else if (name == g_sect_name_dwarf_debug_abbrev)    sect_type = eSectionTypeDWARFDebugAbbrev;
669             else if (name == g_sect_name_dwarf_debug_aranges)   sect_type = eSectionTypeDWARFDebugAranges;
670             else if (name == g_sect_name_dwarf_debug_frame)     sect_type = eSectionTypeDWARFDebugFrame;
671             else if (name == g_sect_name_dwarf_debug_info)      sect_type = eSectionTypeDWARFDebugInfo;
672             else if (name == g_sect_name_dwarf_debug_line)      sect_type = eSectionTypeDWARFDebugLine;
673             else if (name == g_sect_name_dwarf_debug_loc)       sect_type = eSectionTypeDWARFDebugLoc;
674             else if (name == g_sect_name_dwarf_debug_macinfo)   sect_type = eSectionTypeDWARFDebugMacInfo;
675             else if (name == g_sect_name_dwarf_debug_pubnames)  sect_type = eSectionTypeDWARFDebugPubNames;
676             else if (name == g_sect_name_dwarf_debug_pubtypes)  sect_type = eSectionTypeDWARFDebugPubTypes;
677             else if (name == g_sect_name_dwarf_debug_ranges)    sect_type = eSectionTypeDWARFDebugRanges;
678             else if (name == g_sect_name_dwarf_debug_str)       sect_type = eSectionTypeDWARFDebugStr;
679             else if (name == g_sect_name_eh_frame)              sect_type = eSectionTypeEHFrame;
680 
681 
682             SectionSP section_sp(new Section(
683                 GetModule(),        // Module to which this section belongs.
684                 SectionIndex(I),    // Section ID.
685                 name,               // Section name.
686                 sect_type,          // Section type.
687                 header.sh_addr,     // VM address.
688                 vm_size,            // VM size in bytes of this section.
689                 header.sh_offset,   // Offset of this section in the file.
690                 file_size,          // Size of the section as found in the file.
691                 header.sh_flags));  // Flags for this section.
692 
693             if (is_thread_specific)
694                 section_sp->SetIsThreadSpecific (is_thread_specific);
695             m_sections_ap->AddSection(section_sp);
696         }
697 
698         m_sections_ap->Finalize(); // Now that we're done adding sections, finalize to build fast-lookup caches
699     }
700 
701     return m_sections_ap.get();
702 }
703 
704 static unsigned
705 ParseSymbols(Symtab *symtab,
706              user_id_t start_id,
707              SectionList *section_list,
708              const ELFSectionHeader *symtab_shdr,
709              const DataExtractor &symtab_data,
710              const DataExtractor &strtab_data)
711 {
712     ELFSymbol symbol;
713     lldb::offset_t offset = 0;
714     const size_t num_symbols = symtab_data.GetByteSize() / symtab_shdr->sh_entsize;
715 
716     static ConstString text_section_name(".text");
717     static ConstString init_section_name(".init");
718     static ConstString fini_section_name(".fini");
719     static ConstString ctors_section_name(".ctors");
720     static ConstString dtors_section_name(".dtors");
721 
722     static ConstString data_section_name(".data");
723     static ConstString rodata_section_name(".rodata");
724     static ConstString rodata1_section_name(".rodata1");
725     static ConstString data2_section_name(".data1");
726     static ConstString bss_section_name(".bss");
727 
728     unsigned i;
729     for (i = 0; i < num_symbols; ++i)
730     {
731         if (symbol.Parse(symtab_data, &offset) == false)
732             break;
733 
734         SectionSP symbol_section_sp;
735         SymbolType symbol_type = eSymbolTypeInvalid;
736         Elf64_Half symbol_idx = symbol.st_shndx;
737 
738         switch (symbol_idx)
739         {
740         case SHN_ABS:
741             symbol_type = eSymbolTypeAbsolute;
742             break;
743         case SHN_UNDEF:
744             symbol_type = eSymbolTypeUndefined;
745             break;
746         default:
747             symbol_section_sp = section_list->GetSectionAtIndex(symbol_idx);
748             break;
749         }
750 
751         switch (symbol.getType())
752         {
753         default:
754         case STT_NOTYPE:
755             // The symbol's type is not specified.
756             break;
757 
758         case STT_OBJECT:
759             // The symbol is associated with a data object, such as a variable,
760             // an array, etc.
761             symbol_type = eSymbolTypeData;
762             break;
763 
764         case STT_FUNC:
765             // The symbol is associated with a function or other executable code.
766             symbol_type = eSymbolTypeCode;
767             break;
768 
769         case STT_SECTION:
770             // The symbol is associated with a section. Symbol table entries of
771             // this type exist primarily for relocation and normally have
772             // STB_LOCAL binding.
773             break;
774 
775         case STT_FILE:
776             // Conventionally, the symbol's name gives the name of the source
777             // file associated with the object file. A file symbol has STB_LOCAL
778             // binding, its section index is SHN_ABS, and it precedes the other
779             // STB_LOCAL symbols for the file, if it is present.
780             symbol_type = eSymbolTypeObjectFile;
781             break;
782         }
783 
784         if (symbol_type == eSymbolTypeInvalid)
785         {
786             if (symbol_section_sp)
787             {
788                 const ConstString &sect_name = symbol_section_sp->GetName();
789                 if (sect_name == text_section_name ||
790                     sect_name == init_section_name ||
791                     sect_name == fini_section_name ||
792                     sect_name == ctors_section_name ||
793                     sect_name == dtors_section_name)
794                 {
795                     symbol_type = eSymbolTypeCode;
796                 }
797                 else if (sect_name == data_section_name ||
798                          sect_name == data2_section_name ||
799                          sect_name == rodata_section_name ||
800                          sect_name == rodata1_section_name ||
801                          sect_name == bss_section_name)
802                 {
803                     symbol_type = eSymbolTypeData;
804                 }
805             }
806         }
807 
808         uint64_t symbol_value = symbol.st_value;
809         if (symbol_section_sp)
810             symbol_value -= symbol_section_sp->GetFileAddress();
811         const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
812         bool is_global = symbol.getBinding() == STB_GLOBAL;
813         uint32_t flags = symbol.st_other << 8 | symbol.st_info;
814         bool is_mangled = symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
815         Symbol dc_symbol(
816             i + start_id,       // ID is the original symbol table index.
817             symbol_name,        // Symbol name.
818             is_mangled,         // Is the symbol name mangled?
819             symbol_type,        // Type of this symbol
820             is_global,          // Is this globally visible?
821             false,              // Is this symbol debug info?
822             false,              // Is this symbol a trampoline?
823             false,              // Is this symbol artificial?
824             symbol_section_sp,  // Section in which this symbol is defined or null.
825             symbol_value,       // Offset in section or symbol value.
826             symbol.st_size,     // Size in bytes of this symbol.
827             flags);             // Symbol flags.
828         symtab->AddSymbol(dc_symbol);
829     }
830 
831     return i;
832 }
833 
834 unsigned
835 ObjectFileELF::ParseSymbolTable(Symtab *symbol_table, user_id_t start_id,
836                                 const ELFSectionHeader *symtab_hdr,
837                                 user_id_t symtab_id)
838 {
839     assert(symtab_hdr->sh_type == SHT_SYMTAB ||
840            symtab_hdr->sh_type == SHT_DYNSYM);
841 
842     // Parse in the section list if needed.
843     SectionList *section_list = GetSectionList();
844     if (!section_list)
845         return 0;
846 
847     // Section ID's are ones based.
848     user_id_t strtab_id = symtab_hdr->sh_link + 1;
849 
850     Section *symtab = section_list->FindSectionByID(symtab_id).get();
851     Section *strtab = section_list->FindSectionByID(strtab_id).get();
852     unsigned num_symbols = 0;
853     if (symtab && strtab)
854     {
855         DataExtractor symtab_data;
856         DataExtractor strtab_data;
857         if (ReadSectionData(symtab, symtab_data) &&
858             ReadSectionData(strtab, strtab_data))
859         {
860             num_symbols = ParseSymbols(symbol_table, start_id,
861                                        section_list, symtab_hdr,
862                                        symtab_data, strtab_data);
863         }
864     }
865 
866     return num_symbols;
867 }
868 
869 size_t
870 ObjectFileELF::ParseDynamicSymbols()
871 {
872     if (m_dynamic_symbols.size())
873         return m_dynamic_symbols.size();
874 
875     user_id_t dyn_id = GetSectionIndexByType(SHT_DYNAMIC);
876     if (!dyn_id)
877         return 0;
878 
879     SectionList *section_list = GetSectionList();
880     if (!section_list)
881         return 0;
882 
883     Section *dynsym = section_list->FindSectionByID(dyn_id).get();
884     if (!dynsym)
885         return 0;
886 
887     ELFDynamic symbol;
888     DataExtractor dynsym_data;
889     if (ReadSectionData(dynsym, dynsym_data))
890     {
891         const lldb::offset_t section_size = dynsym_data.GetByteSize();
892         lldb::offset_t cursor = 0;
893 
894         while (cursor < section_size)
895         {
896             if (!symbol.Parse(dynsym_data, &cursor))
897                 break;
898 
899             m_dynamic_symbols.push_back(symbol);
900         }
901     }
902 
903     return m_dynamic_symbols.size();
904 }
905 
906 const ELFDynamic *
907 ObjectFileELF::FindDynamicSymbol(unsigned tag)
908 {
909     if (!ParseDynamicSymbols())
910         return NULL;
911 
912     SectionList *section_list = GetSectionList();
913     if (!section_list)
914         return 0;
915 
916     DynamicSymbolCollIter I = m_dynamic_symbols.begin();
917     DynamicSymbolCollIter E = m_dynamic_symbols.end();
918     for ( ; I != E; ++I)
919     {
920         ELFDynamic *symbol = &*I;
921 
922         if (symbol->d_tag == tag)
923             return symbol;
924     }
925 
926     return NULL;
927 }
928 
929 Section *
930 ObjectFileELF::PLTSection()
931 {
932     const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
933     SectionList *section_list = GetSectionList();
934 
935     if (symbol && section_list)
936     {
937         addr_t addr = symbol->d_ptr;
938         return section_list->FindSectionContainingFileAddress(addr).get();
939     }
940 
941     return NULL;
942 }
943 
944 unsigned
945 ObjectFileELF::PLTRelocationType()
946 {
947     const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
948 
949     if (symbol)
950         return symbol->d_val;
951 
952     return 0;
953 }
954 
955 static unsigned
956 ParsePLTRelocations(Symtab *symbol_table,
957                     user_id_t start_id,
958                     unsigned rel_type,
959                     const ELFHeader *hdr,
960                     const ELFSectionHeader *rel_hdr,
961                     const ELFSectionHeader *plt_hdr,
962                     const ELFSectionHeader *sym_hdr,
963                     const lldb::SectionSP &plt_section_sp,
964                     DataExtractor &rel_data,
965                     DataExtractor &symtab_data,
966                     DataExtractor &strtab_data)
967 {
968     ELFRelocation rel(rel_type);
969     ELFSymbol symbol;
970     lldb::offset_t offset = 0;
971     const elf_xword plt_entsize = plt_hdr->sh_entsize;
972     const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
973 
974     typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
975     reloc_info_fn reloc_type;
976     reloc_info_fn reloc_symbol;
977 
978     if (hdr->Is32Bit())
979     {
980         reloc_type = ELFRelocation::RelocType32;
981         reloc_symbol = ELFRelocation::RelocSymbol32;
982     }
983     else
984     {
985         reloc_type = ELFRelocation::RelocType64;
986         reloc_symbol = ELFRelocation::RelocSymbol64;
987     }
988 
989     unsigned slot_type = hdr->GetRelocationJumpSlotType();
990     unsigned i;
991     for (i = 0; i < num_relocations; ++i)
992     {
993         if (rel.Parse(rel_data, &offset) == false)
994             break;
995 
996         if (reloc_type(rel) != slot_type)
997             continue;
998 
999         lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
1000         uint64_t plt_index = (i + 1) * plt_entsize;
1001 
1002         if (!symbol.Parse(symtab_data, &symbol_offset))
1003             break;
1004 
1005         const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
1006         bool is_mangled = symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
1007 
1008         Symbol jump_symbol(
1009             i + start_id,    // Symbol table index
1010             symbol_name,     // symbol name.
1011             is_mangled,      // is the symbol name mangled?
1012             eSymbolTypeTrampoline, // Type of this symbol
1013             false,           // Is this globally visible?
1014             false,           // Is this symbol debug info?
1015             true,            // Is this symbol a trampoline?
1016             true,            // Is this symbol artificial?
1017             plt_section_sp,  // Section in which this symbol is defined or null.
1018             plt_index,       // Offset in section or symbol value.
1019             plt_entsize,     // Size in bytes of this symbol.
1020             0);              // Symbol flags.
1021 
1022         symbol_table->AddSymbol(jump_symbol);
1023     }
1024 
1025     return i;
1026 }
1027 
1028 unsigned
1029 ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table,
1030                                       user_id_t start_id,
1031                                       const ELFSectionHeader *rel_hdr,
1032                                       user_id_t rel_id)
1033 {
1034     assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
1035 
1036     // The link field points to the asscoiated symbol table.  The info field
1037     // points to the section holding the plt.
1038     user_id_t symtab_id = rel_hdr->sh_link;
1039     user_id_t plt_id = rel_hdr->sh_info;
1040 
1041     if (!symtab_id || !plt_id)
1042         return 0;
1043 
1044     // Section ID's are ones based;
1045     symtab_id++;
1046     plt_id++;
1047 
1048     const ELFSectionHeader *plt_hdr = GetSectionHeaderByIndex(plt_id);
1049     if (!plt_hdr)
1050         return 0;
1051 
1052     const ELFSectionHeader *sym_hdr = GetSectionHeaderByIndex(symtab_id);
1053     if (!sym_hdr)
1054         return 0;
1055 
1056     SectionList *section_list = GetSectionList();
1057     if (!section_list)
1058         return 0;
1059 
1060     Section *rel_section = section_list->FindSectionByID(rel_id).get();
1061     if (!rel_section)
1062         return 0;
1063 
1064     SectionSP plt_section_sp (section_list->FindSectionByID(plt_id));
1065     if (!plt_section_sp)
1066         return 0;
1067 
1068     Section *symtab = section_list->FindSectionByID(symtab_id).get();
1069     if (!symtab)
1070         return 0;
1071 
1072     Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link + 1).get();
1073     if (!strtab)
1074         return 0;
1075 
1076     DataExtractor rel_data;
1077     if (!ReadSectionData(rel_section, rel_data))
1078         return 0;
1079 
1080     DataExtractor symtab_data;
1081     if (!ReadSectionData(symtab, symtab_data))
1082         return 0;
1083 
1084     DataExtractor strtab_data;
1085     if (!ReadSectionData(strtab, strtab_data))
1086         return 0;
1087 
1088     unsigned rel_type = PLTRelocationType();
1089     if (!rel_type)
1090         return 0;
1091 
1092     return ParsePLTRelocations (symbol_table,
1093                                 start_id,
1094                                 rel_type,
1095                                 &m_header,
1096                                 rel_hdr,
1097                                 plt_hdr,
1098                                 sym_hdr,
1099                                 plt_section_sp,
1100                                 rel_data,
1101                                 symtab_data,
1102                                 strtab_data);
1103 }
1104 
1105 Symtab *
1106 ObjectFileELF::GetSymtab()
1107 {
1108     if (m_symtab_ap.get())
1109         return m_symtab_ap.get();
1110 
1111     Symtab *symbol_table = new Symtab(this);
1112     m_symtab_ap.reset(symbol_table);
1113 
1114     Mutex::Locker locker(symbol_table->GetMutex());
1115 
1116     if (!(ParseSectionHeaders() && GetSectionHeaderStringTable()))
1117         return symbol_table;
1118 
1119     // Locate and parse all linker symbol tables.
1120     uint64_t symbol_id = 0;
1121     for (SectionHeaderCollIter I = m_section_headers.begin();
1122          I != m_section_headers.end(); ++I)
1123     {
1124         if (I->sh_type == SHT_SYMTAB || I->sh_type == SHT_DYNSYM)
1125         {
1126             const ELFSectionHeader &symtab_header = *I;
1127             user_id_t section_id = SectionIndex(I);
1128             symbol_id += ParseSymbolTable(symbol_table, symbol_id,
1129                                           &symtab_header, section_id);
1130         }
1131     }
1132 
1133     // Synthesize trampoline symbols to help navigate the PLT.
1134     Section *reloc_section = PLTSection();
1135     if (reloc_section)
1136     {
1137         user_id_t reloc_id = reloc_section->GetID();
1138         const ELFSectionHeader *reloc_header = GetSectionHeaderByIndex(reloc_id);
1139         assert(reloc_header);
1140 
1141         ParseTrampolineSymbols(symbol_table, symbol_id, reloc_header, reloc_id);
1142     }
1143 
1144     return symbol_table;
1145 }
1146 
1147 //===----------------------------------------------------------------------===//
1148 // Dump
1149 //
1150 // Dump the specifics of the runtime file container (such as any headers
1151 // segments, sections, etc).
1152 //----------------------------------------------------------------------
1153 void
1154 ObjectFileELF::Dump(Stream *s)
1155 {
1156     DumpELFHeader(s, m_header);
1157     s->EOL();
1158     DumpELFProgramHeaders(s);
1159     s->EOL();
1160     DumpELFSectionHeaders(s);
1161     s->EOL();
1162     SectionList *section_list = GetSectionList();
1163     if (section_list)
1164         section_list->Dump(s, NULL, true, UINT32_MAX);
1165     Symtab *symtab = GetSymtab();
1166     if (symtab)
1167         symtab->Dump(s, NULL, eSortOrderNone);
1168     s->EOL();
1169     DumpDependentModules(s);
1170     s->EOL();
1171 }
1172 
1173 //----------------------------------------------------------------------
1174 // DumpELFHeader
1175 //
1176 // Dump the ELF header to the specified output stream
1177 //----------------------------------------------------------------------
1178 void
1179 ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header)
1180 {
1181     s->PutCString("ELF Header\n");
1182     s->Printf("e_ident[EI_MAG0   ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
1183     s->Printf("e_ident[EI_MAG1   ] = 0x%2.2x '%c'\n",
1184               header.e_ident[EI_MAG1], header.e_ident[EI_MAG1]);
1185     s->Printf("e_ident[EI_MAG2   ] = 0x%2.2x '%c'\n",
1186               header.e_ident[EI_MAG2], header.e_ident[EI_MAG2]);
1187     s->Printf("e_ident[EI_MAG3   ] = 0x%2.2x '%c'\n",
1188               header.e_ident[EI_MAG3], header.e_ident[EI_MAG3]);
1189 
1190     s->Printf("e_ident[EI_CLASS  ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
1191     s->Printf("e_ident[EI_DATA   ] = 0x%2.2x ", header.e_ident[EI_DATA]);
1192     DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
1193     s->Printf ("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
1194     s->Printf ("e_ident[EI_PAD    ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
1195 
1196     s->Printf("e_type      = 0x%4.4x ", header.e_type);
1197     DumpELFHeader_e_type(s, header.e_type);
1198     s->Printf("\ne_machine   = 0x%4.4x\n", header.e_machine);
1199     s->Printf("e_version   = 0x%8.8x\n", header.e_version);
1200     s->Printf("e_entry     = 0x%8.8" PRIx64 "\n", header.e_entry);
1201     s->Printf("e_phoff     = 0x%8.8" PRIx64 "\n", header.e_phoff);
1202     s->Printf("e_shoff     = 0x%8.8" PRIx64 "\n", header.e_shoff);
1203     s->Printf("e_flags     = 0x%8.8x\n", header.e_flags);
1204     s->Printf("e_ehsize    = 0x%4.4x\n", header.e_ehsize);
1205     s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
1206     s->Printf("e_phnum     = 0x%4.4x\n", header.e_phnum);
1207     s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
1208     s->Printf("e_shnum     = 0x%4.4x\n", header.e_shnum);
1209     s->Printf("e_shstrndx  = 0x%4.4x\n", header.e_shstrndx);
1210 }
1211 
1212 //----------------------------------------------------------------------
1213 // DumpELFHeader_e_type
1214 //
1215 // Dump an token value for the ELF header member e_type
1216 //----------------------------------------------------------------------
1217 void
1218 ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type)
1219 {
1220     switch (e_type)
1221     {
1222     case ET_NONE:   *s << "ET_NONE"; break;
1223     case ET_REL:    *s << "ET_REL"; break;
1224     case ET_EXEC:   *s << "ET_EXEC"; break;
1225     case ET_DYN:    *s << "ET_DYN"; break;
1226     case ET_CORE:   *s << "ET_CORE"; break;
1227     default:
1228         break;
1229     }
1230 }
1231 
1232 //----------------------------------------------------------------------
1233 // DumpELFHeader_e_ident_EI_DATA
1234 //
1235 // Dump an token value for the ELF header member e_ident[EI_DATA]
1236 //----------------------------------------------------------------------
1237 void
1238 ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s, unsigned char ei_data)
1239 {
1240     switch (ei_data)
1241     {
1242     case ELFDATANONE:   *s << "ELFDATANONE"; break;
1243     case ELFDATA2LSB:   *s << "ELFDATA2LSB - Little Endian"; break;
1244     case ELFDATA2MSB:   *s << "ELFDATA2MSB - Big Endian"; break;
1245     default:
1246         break;
1247     }
1248 }
1249 
1250 
1251 //----------------------------------------------------------------------
1252 // DumpELFProgramHeader
1253 //
1254 // Dump a single ELF program header to the specified output stream
1255 //----------------------------------------------------------------------
1256 void
1257 ObjectFileELF::DumpELFProgramHeader(Stream *s, const ELFProgramHeader &ph)
1258 {
1259     DumpELFProgramHeader_p_type(s, ph.p_type);
1260     s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset, ph.p_vaddr, ph.p_paddr);
1261     s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz, ph.p_flags);
1262 
1263     DumpELFProgramHeader_p_flags(s, ph.p_flags);
1264     s->Printf(") %8.8" PRIx64, ph.p_align);
1265 }
1266 
1267 //----------------------------------------------------------------------
1268 // DumpELFProgramHeader_p_type
1269 //
1270 // Dump an token value for the ELF program header member p_type which
1271 // describes the type of the program header
1272 // ----------------------------------------------------------------------
1273 void
1274 ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type)
1275 {
1276     const int kStrWidth = 10;
1277     switch (p_type)
1278     {
1279     CASE_AND_STREAM(s, PT_NULL      , kStrWidth);
1280     CASE_AND_STREAM(s, PT_LOAD      , kStrWidth);
1281     CASE_AND_STREAM(s, PT_DYNAMIC   , kStrWidth);
1282     CASE_AND_STREAM(s, PT_INTERP    , kStrWidth);
1283     CASE_AND_STREAM(s, PT_NOTE      , kStrWidth);
1284     CASE_AND_STREAM(s, PT_SHLIB     , kStrWidth);
1285     CASE_AND_STREAM(s, PT_PHDR      , kStrWidth);
1286     default:
1287         s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
1288         break;
1289     }
1290 }
1291 
1292 
1293 //----------------------------------------------------------------------
1294 // DumpELFProgramHeader_p_flags
1295 //
1296 // Dump an token value for the ELF program header member p_flags
1297 //----------------------------------------------------------------------
1298 void
1299 ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags)
1300 {
1301     *s  << ((p_flags & PF_X) ? "PF_X" : "    ")
1302         << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
1303         << ((p_flags & PF_W) ? "PF_W" : "    ")
1304         << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
1305         << ((p_flags & PF_R) ? "PF_R" : "    ");
1306 }
1307 
1308 //----------------------------------------------------------------------
1309 // DumpELFProgramHeaders
1310 //
1311 // Dump all of the ELF program header to the specified output stream
1312 //----------------------------------------------------------------------
1313 void
1314 ObjectFileELF::DumpELFProgramHeaders(Stream *s)
1315 {
1316     if (ParseProgramHeaders())
1317     {
1318         s->PutCString("Program Headers\n");
1319         s->PutCString("IDX  p_type     p_offset p_vaddr  p_paddr  "
1320                       "p_filesz p_memsz  p_flags                   p_align\n");
1321         s->PutCString("==== ---------- -------- -------- -------- "
1322                       "-------- -------- ------------------------- --------\n");
1323 
1324         uint32_t idx = 0;
1325         for (ProgramHeaderCollConstIter I = m_program_headers.begin();
1326              I != m_program_headers.end(); ++I, ++idx)
1327         {
1328             s->Printf("[%2u] ", idx);
1329             ObjectFileELF::DumpELFProgramHeader(s, *I);
1330             s->EOL();
1331         }
1332     }
1333 }
1334 
1335 //----------------------------------------------------------------------
1336 // DumpELFSectionHeader
1337 //
1338 // Dump a single ELF section header to the specified output stream
1339 //----------------------------------------------------------------------
1340 void
1341 ObjectFileELF::DumpELFSectionHeader(Stream *s, const ELFSectionHeader &sh)
1342 {
1343     s->Printf("%8.8x ", sh.sh_name);
1344     DumpELFSectionHeader_sh_type(s, sh.sh_type);
1345     s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
1346     DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
1347     s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr, sh.sh_offset, sh.sh_size);
1348     s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
1349     s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
1350 }
1351 
1352 //----------------------------------------------------------------------
1353 // DumpELFSectionHeader_sh_type
1354 //
1355 // Dump an token value for the ELF section header member sh_type which
1356 // describes the type of the section
1357 //----------------------------------------------------------------------
1358 void
1359 ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type)
1360 {
1361     const int kStrWidth = 12;
1362     switch (sh_type)
1363     {
1364     CASE_AND_STREAM(s, SHT_NULL     , kStrWidth);
1365     CASE_AND_STREAM(s, SHT_PROGBITS , kStrWidth);
1366     CASE_AND_STREAM(s, SHT_SYMTAB   , kStrWidth);
1367     CASE_AND_STREAM(s, SHT_STRTAB   , kStrWidth);
1368     CASE_AND_STREAM(s, SHT_RELA     , kStrWidth);
1369     CASE_AND_STREAM(s, SHT_HASH     , kStrWidth);
1370     CASE_AND_STREAM(s, SHT_DYNAMIC  , kStrWidth);
1371     CASE_AND_STREAM(s, SHT_NOTE     , kStrWidth);
1372     CASE_AND_STREAM(s, SHT_NOBITS   , kStrWidth);
1373     CASE_AND_STREAM(s, SHT_REL      , kStrWidth);
1374     CASE_AND_STREAM(s, SHT_SHLIB    , kStrWidth);
1375     CASE_AND_STREAM(s, SHT_DYNSYM   , kStrWidth);
1376     CASE_AND_STREAM(s, SHT_LOPROC   , kStrWidth);
1377     CASE_AND_STREAM(s, SHT_HIPROC   , kStrWidth);
1378     CASE_AND_STREAM(s, SHT_LOUSER   , kStrWidth);
1379     CASE_AND_STREAM(s, SHT_HIUSER   , kStrWidth);
1380     default:
1381         s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
1382         break;
1383     }
1384 }
1385 
1386 //----------------------------------------------------------------------
1387 // DumpELFSectionHeader_sh_flags
1388 //
1389 // Dump an token value for the ELF section header member sh_flags
1390 //----------------------------------------------------------------------
1391 void
1392 ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s, elf_xword sh_flags)
1393 {
1394     *s  << ((sh_flags & SHF_WRITE) ? "WRITE" : "     ")
1395         << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
1396         << ((sh_flags & SHF_ALLOC) ? "ALLOC" : "     ")
1397         << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
1398         << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : "         ");
1399 }
1400 
1401 //----------------------------------------------------------------------
1402 // DumpELFSectionHeaders
1403 //
1404 // Dump all of the ELF section header to the specified output stream
1405 //----------------------------------------------------------------------
1406 void
1407 ObjectFileELF::DumpELFSectionHeaders(Stream *s)
1408 {
1409     if (!(ParseSectionHeaders() && GetSectionHeaderStringTable()))
1410         return;
1411 
1412     s->PutCString("Section Headers\n");
1413     s->PutCString("IDX  name     type         flags                            "
1414                   "addr     offset   size     link     info     addralgn "
1415                   "entsize  Name\n");
1416     s->PutCString("==== -------- ------------ -------------------------------- "
1417                   "-------- -------- -------- -------- -------- -------- "
1418                   "-------- ====================\n");
1419 
1420     uint32_t idx = 0;
1421     for (SectionHeaderCollConstIter I = m_section_headers.begin();
1422          I != m_section_headers.end(); ++I, ++idx)
1423     {
1424         s->Printf("[%2u] ", idx);
1425         ObjectFileELF::DumpELFSectionHeader(s, *I);
1426         const char* section_name = m_shstr_data.PeekCStr(I->sh_name);
1427         if (section_name)
1428             *s << ' ' << section_name << "\n";
1429     }
1430 }
1431 
1432 void
1433 ObjectFileELF::DumpDependentModules(lldb_private::Stream *s)
1434 {
1435     size_t num_modules = ParseDependentModules();
1436 
1437     if (num_modules > 0)
1438     {
1439         s->PutCString("Dependent Modules:\n");
1440         for (unsigned i = 0; i < num_modules; ++i)
1441         {
1442             const FileSpec &spec = m_filespec_ap->GetFileSpecAtIndex(i);
1443             s->Printf("   %s\n", spec.GetFilename().GetCString());
1444         }
1445     }
1446 }
1447 
1448 bool
1449 ObjectFileELF::GetArchitecture (ArchSpec &arch)
1450 {
1451     if (!ParseHeader())
1452         return false;
1453 
1454     arch.SetArchitecture (eArchTypeELF, m_header.e_machine, LLDB_INVALID_CPUTYPE);
1455     arch.GetTriple().setOSName (Host::GetOSString().GetCString());
1456     arch.GetTriple().setVendorName(Host::GetVendorString().GetCString());
1457     return true;
1458 }
1459 
1460 ObjectFile::Type
1461 ObjectFileELF::CalculateType()
1462 {
1463     switch (m_header.e_type)
1464     {
1465         case llvm::ELF::ET_NONE:
1466             // 0 - No file type
1467             return eTypeUnknown;
1468 
1469         case llvm::ELF::ET_REL:
1470             // 1 - Relocatable file
1471             return eTypeObjectFile;
1472 
1473         case llvm::ELF::ET_EXEC:
1474             // 2 - Executable file
1475             return eTypeExecutable;
1476 
1477         case llvm::ELF::ET_DYN:
1478             // 3 - Shared object file
1479             return eTypeSharedLibrary;
1480 
1481         case ET_CORE:
1482             // 4 - Core file
1483             return eTypeCoreFile;
1484 
1485         default:
1486             break;
1487     }
1488     return eTypeUnknown;
1489 }
1490 
1491 ObjectFile::Strata
1492 ObjectFileELF::CalculateStrata()
1493 {
1494     switch (m_header.e_type)
1495     {
1496         case llvm::ELF::ET_NONE:
1497             // 0 - No file type
1498             return eStrataUnknown;
1499 
1500         case llvm::ELF::ET_REL:
1501             // 1 - Relocatable file
1502             return eStrataUnknown;
1503 
1504         case llvm::ELF::ET_EXEC:
1505             // 2 - Executable file
1506             // TODO: is there any way to detect that an executable is a kernel
1507             // related executable by inspecting the program headers, section
1508             // headers, symbols, or any other flag bits???
1509             return eStrataUser;
1510 
1511         case llvm::ELF::ET_DYN:
1512             // 3 - Shared object file
1513             // TODO: is there any way to detect that an shared library is a kernel
1514             // related executable by inspecting the program headers, section
1515             // headers, symbols, or any other flag bits???
1516             return eStrataUnknown;
1517 
1518         case ET_CORE:
1519             // 4 - Core file
1520             // TODO: is there any way to detect that an core file is a kernel
1521             // related executable by inspecting the program headers, section
1522             // headers, symbols, or any other flag bits???
1523             return eStrataUnknown;
1524 
1525         default:
1526             break;
1527     }
1528     return eStrataUnknown;
1529 }
1530 
1531