xref: /llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp (revision bd3f26069840d2743e150004ab98cc3f0c969f08)
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 #define CASE_AND_STREAM(s, def, width)                  \
27     case def: s->Printf("%-*s", width, #def); break;
28 
29 using namespace lldb;
30 using namespace lldb_private;
31 using namespace elf;
32 using namespace llvm::ELF;
33 
34 //------------------------------------------------------------------
35 // Static methods.
36 //------------------------------------------------------------------
37 void
38 ObjectFileELF::Initialize()
39 {
40     PluginManager::RegisterPlugin(GetPluginNameStatic(),
41                                   GetPluginDescriptionStatic(),
42                                   CreateInstance);
43 }
44 
45 void
46 ObjectFileELF::Terminate()
47 {
48     PluginManager::UnregisterPlugin(CreateInstance);
49 }
50 
51 const char *
52 ObjectFileELF::GetPluginNameStatic()
53 {
54     return "object-file.elf";
55 }
56 
57 const char *
58 ObjectFileELF::GetPluginDescriptionStatic()
59 {
60     return "ELF object file reader.";
61 }
62 
63 ObjectFile *
64 ObjectFileELF::CreateInstance(Module *module,
65                               DataBufferSP &data_sp,
66                               const FileSpec *file, addr_t offset,
67                               addr_t length)
68 {
69     if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + offset))
70     {
71         const uint8_t *magic = data_sp->GetBytes() + offset;
72         if (ELFHeader::MagicBytesMatch(magic))
73         {
74             unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
75             if (address_size == 4 || address_size == 8)
76             {
77                 std::auto_ptr<ObjectFileELF> objfile_ap(
78                     new ObjectFileELF(module, data_sp, file, offset, length));
79                 ArchSpec spec;
80                 if (objfile_ap->GetArchitecture(spec) &&
81                     objfile_ap->SetModulesArchitecture(spec))
82                     return objfile_ap.release();
83             }
84         }
85     }
86     return NULL;
87 }
88 
89 
90 //------------------------------------------------------------------
91 // PluginInterface protocol
92 //------------------------------------------------------------------
93 const char *
94 ObjectFileELF::GetPluginName()
95 {
96     return "ObjectFileELF";
97 }
98 
99 const char *
100 ObjectFileELF::GetShortPluginName()
101 {
102     return GetPluginNameStatic();
103 }
104 
105 uint32_t
106 ObjectFileELF::GetPluginVersion()
107 {
108     return m_plugin_version;
109 }
110 
111 void
112 ObjectFileELF::GetPluginCommandHelp(const char *command, Stream *strm)
113 {
114 }
115 
116 Error
117 ObjectFileELF::ExecutePluginCommand(Args &command, Stream *strm)
118 {
119     Error error;
120     error.SetErrorString("No plug-in commands are currently supported.");
121     return error;
122 }
123 
124 Log *
125 ObjectFileELF::EnablePluginLogging(Stream *strm, Args &command)
126 {
127     return NULL;
128 }
129 
130 //------------------------------------------------------------------
131 // ObjectFile protocol
132 //------------------------------------------------------------------
133 
134 ObjectFileELF::ObjectFileELF(Module* module, DataBufferSP& dataSP,
135                              const FileSpec* file, addr_t offset,
136                              addr_t length)
137     : ObjectFile(module, file, offset, length, dataSP),
138       m_header(),
139       m_program_headers(),
140       m_section_headers(),
141       m_sections_ap(),
142       m_symtab_ap(),
143       m_filespec_ap(),
144       m_shstr_data()
145 {
146     if (file)
147         m_file = *file;
148     ::memset(&m_header, 0, sizeof(m_header));
149 }
150 
151 ObjectFileELF::~ObjectFileELF()
152 {
153 }
154 
155 bool
156 ObjectFileELF::IsExecutable() const
157 {
158     return m_header.e_entry != 0;
159 }
160 
161 ByteOrder
162 ObjectFileELF::GetByteOrder() const
163 {
164     if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
165         return eByteOrderBig;
166     if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
167         return eByteOrderLittle;
168     return eByteOrderInvalid;
169 }
170 
171 size_t
172 ObjectFileELF::GetAddressByteSize() const
173 {
174     return m_data.GetAddressByteSize();
175 }
176 
177 unsigned
178 ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I)
179 {
180     return std::distance(m_section_headers.begin(), I) + 1;
181 }
182 
183 unsigned
184 ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const
185 {
186     return std::distance(m_section_headers.begin(), I) + 1;
187 }
188 
189 bool
190 ObjectFileELF::ParseHeader()
191 {
192     uint32_t offset = GetOffset();
193     return m_header.Parse(m_data, &offset);
194 }
195 
196 bool
197 ObjectFileELF::GetUUID(lldb_private::UUID* uuid)
198 {
199     // FIXME: Return MD5 sum here.  See comment in ObjectFile.h.
200     return false;
201 }
202 
203 uint32_t
204 ObjectFileELF::GetDependentModules(FileSpecList &files)
205 {
206     size_t num_modules = ParseDependentModules();
207     uint32_t num_specs = 0;
208 
209     for (unsigned i = 0; i < num_modules; ++i)
210     {
211         if (files.AppendIfUnique(m_filespec_ap->GetFileSpecAtIndex(i)))
212             num_specs++;
213     }
214 
215     return num_specs;
216 }
217 
218 Address
219 ObjectFileELF::GetImageInfoAddress()
220 {
221     if (!ParseSectionHeaders())
222         return Address();
223 
224     user_id_t dynsym_id = 0;
225     for (SectionHeaderCollIter sh_pos = m_section_headers.begin();
226          sh_pos != m_section_headers.end(); ++sh_pos)
227     {
228         if (sh_pos->sh_type == SHT_DYNAMIC)
229         {
230             dynsym_id = SectionIndex(sh_pos);
231             break;
232         }
233     }
234 
235     if (!dynsym_id)
236         return Address();
237 
238     SectionList *section_list = GetSectionList();
239     if (!section_list)
240         return Address();
241 
242     // Resolve the dynamic table entries.
243     Section *dynsym = section_list->FindSectionByID(dynsym_id).get();
244     if (!dynsym)
245         return Address();
246 
247     DataExtractor dynsym_data;
248     if (dynsym->ReadSectionDataFromObjectFile(this, dynsym_data))
249     {
250         ELFDynamic symbol;
251         const unsigned section_size = dynsym_data.GetByteSize();
252         unsigned offset = 0;
253         unsigned cursor = 0;
254 
255         // Look for a DT_DEBUG entry.
256         while (cursor < section_size)
257         {
258             offset = cursor;
259             if (!symbol.Parse(dynsym_data, &cursor))
260                 break;
261 
262             if (symbol.d_tag != DT_DEBUG)
263                 continue;
264 
265             return Address(dynsym, offset + sizeof(symbol.d_tag));
266         }
267     }
268 
269     return Address();
270 }
271 
272 lldb_private::Address
273 ObjectFileELF::GetEntryPointAddress ()
274 {
275     // If the object file is not an executable it can't hold the entry point.  m_entry_point_address
276     // is initialized to an invalid address, so we can just return that.
277     // If m_entry_point_address is valid it means we've found it already, so return the cached value.
278 
279     if (!IsExecutable() || m_entry_point_address.IsValid())
280         return m_entry_point_address;
281 
282     // FIXME: This is just looking for the "start" symbol, but that will fail if "start" is stripped.
283     // There's probably a better way in ELF to find the start address of an executable module.
284 
285     SymbolContextList contexts;
286     SymbolContext context;
287     if (!m_module->FindSymbolsWithNameAndType(ConstString ("start"), lldb::eSymbolTypeCode, contexts))
288         return m_entry_point_address;
289 
290     contexts.GetContextAtIndex(0, context);
291 
292     m_entry_point_address = context.symbol->GetValue();
293 
294     return m_entry_point_address;
295 
296 }
297 
298 //----------------------------------------------------------------------
299 // ParseDependentModules
300 //----------------------------------------------------------------------
301 size_t
302 ObjectFileELF::ParseDependentModules()
303 {
304     if (m_filespec_ap.get())
305         return m_filespec_ap->GetSize();
306 
307     m_filespec_ap.reset(new FileSpecList());
308 
309     if (!(ParseSectionHeaders() && GetSectionHeaderStringTable()))
310         return 0;
311 
312     // Locate the dynamic table.
313     user_id_t dynsym_id = 0;
314     user_id_t dynstr_id = 0;
315     for (SectionHeaderCollIter sh_pos = m_section_headers.begin();
316          sh_pos != m_section_headers.end(); ++sh_pos)
317     {
318         if (sh_pos->sh_type == SHT_DYNAMIC)
319         {
320             dynsym_id = SectionIndex(sh_pos);
321             dynstr_id = sh_pos->sh_link + 1; // Section ID's are 1 based.
322             break;
323         }
324     }
325 
326     if (!(dynsym_id && dynstr_id))
327         return 0;
328 
329     SectionList *section_list = GetSectionList();
330     if (!section_list)
331         return 0;
332 
333     // Resolve and load the dynamic table entries and corresponding string
334     // table.
335     Section *dynsym = section_list->FindSectionByID(dynsym_id).get();
336     Section *dynstr = section_list->FindSectionByID(dynstr_id).get();
337     if (!(dynsym && dynstr))
338         return 0;
339 
340     DataExtractor dynsym_data;
341     DataExtractor dynstr_data;
342     if (dynsym->ReadSectionDataFromObjectFile(this, dynsym_data) &&
343         dynstr->ReadSectionDataFromObjectFile(this, dynstr_data))
344     {
345         ELFDynamic symbol;
346         const unsigned section_size = dynsym_data.GetByteSize();
347         unsigned offset = 0;
348 
349         // The only type of entries we are concerned with are tagged DT_NEEDED,
350         // yielding the name of a required library.
351         while (offset < section_size)
352         {
353             if (!symbol.Parse(dynsym_data, &offset))
354                 break;
355 
356             if (symbol.d_tag != DT_NEEDED)
357                 continue;
358 
359             uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
360             const char *lib_name = dynstr_data.PeekCStr(str_index);
361             m_filespec_ap->Append(FileSpec(lib_name, true));
362         }
363     }
364 
365     return m_filespec_ap->GetSize();
366 }
367 
368 //----------------------------------------------------------------------
369 // ParseProgramHeaders
370 //----------------------------------------------------------------------
371 size_t
372 ObjectFileELF::ParseProgramHeaders()
373 {
374     // We have already parsed the program headers
375     if (!m_program_headers.empty())
376         return m_program_headers.size();
377 
378     // If there are no program headers to read we are done.
379     if (m_header.e_phnum == 0)
380         return 0;
381 
382     m_program_headers.resize(m_header.e_phnum);
383     if (m_program_headers.size() != m_header.e_phnum)
384         return 0;
385 
386     const size_t ph_size = m_header.e_phnum * m_header.e_phentsize;
387     const elf_off ph_offset = m_offset + m_header.e_phoff;
388     DataBufferSP buffer_sp(m_file.ReadFileContents(ph_offset, ph_size));
389 
390     if (buffer_sp.get() == NULL || buffer_sp->GetByteSize() != ph_size)
391         return 0;
392 
393     DataExtractor data(buffer_sp, m_data.GetByteOrder(),
394                        m_data.GetAddressByteSize());
395 
396     uint32_t idx;
397     uint32_t offset;
398     for (idx = 0, offset = 0; idx < m_header.e_phnum; ++idx)
399     {
400         if (m_program_headers[idx].Parse(data, &offset) == false)
401             break;
402     }
403 
404     if (idx < m_program_headers.size())
405         m_program_headers.resize(idx);
406 
407     return m_program_headers.size();
408 }
409 
410 //----------------------------------------------------------------------
411 // ParseSectionHeaders
412 //----------------------------------------------------------------------
413 size_t
414 ObjectFileELF::ParseSectionHeaders()
415 {
416     // We have already parsed the section headers
417     if (!m_section_headers.empty())
418         return m_section_headers.size();
419 
420     // If there are no section headers we are done.
421     if (m_header.e_shnum == 0)
422         return 0;
423 
424     m_section_headers.resize(m_header.e_shnum);
425     if (m_section_headers.size() != m_header.e_shnum)
426         return 0;
427 
428     const size_t sh_size = m_header.e_shnum * m_header.e_shentsize;
429     const elf_off sh_offset = m_offset + m_header.e_shoff;
430     DataBufferSP buffer_sp(m_file.ReadFileContents(sh_offset, sh_size));
431 
432     if (buffer_sp.get() == NULL || buffer_sp->GetByteSize() != sh_size)
433         return 0;
434 
435     DataExtractor data(buffer_sp,
436                        m_data.GetByteOrder(),
437                        m_data.GetAddressByteSize());
438 
439     uint32_t idx;
440     uint32_t offset;
441     for (idx = 0, offset = 0; idx < m_header.e_shnum; ++idx)
442     {
443         if (m_section_headers[idx].Parse(data, &offset) == false)
444             break;
445     }
446     if (idx < m_section_headers.size())
447         m_section_headers.resize(idx);
448 
449     return m_section_headers.size();
450 }
451 
452 size_t
453 ObjectFileELF::GetSectionHeaderStringTable()
454 {
455     if (m_shstr_data.GetByteSize() == 0)
456     {
457         const unsigned strtab_idx = m_header.e_shstrndx;
458 
459         if (strtab_idx && strtab_idx < m_section_headers.size())
460         {
461             const ELFSectionHeader &sheader = m_section_headers[strtab_idx];
462             const size_t byte_size = sheader.sh_size;
463             const Elf64_Off offset = m_offset + sheader.sh_offset;
464             DataBufferSP buffer_sp(m_file.ReadFileContents(offset, byte_size));
465 
466             if (buffer_sp.get() == NULL || buffer_sp->GetByteSize() != byte_size)
467                 return 0;
468 
469             m_shstr_data.SetData(buffer_sp);
470         }
471     }
472     return m_shstr_data.GetByteSize();
473 }
474 
475 lldb::user_id_t
476 ObjectFileELF::GetSectionIndexByName(const char *name)
477 {
478     if (!(ParseSectionHeaders() && GetSectionHeaderStringTable()))
479         return 0;
480 
481     // Search the collection of section headers for one with a matching name.
482     for (SectionHeaderCollIter I = m_section_headers.begin();
483          I != m_section_headers.end(); ++I)
484     {
485         const char *sectionName = m_shstr_data.PeekCStr(I->sh_name);
486 
487         if (!sectionName)
488             return 0;
489 
490         if (strcmp(name, sectionName) != 0)
491             continue;
492 
493         return SectionIndex(I);
494     }
495 
496     return 0;
497 }
498 
499 SectionList *
500 ObjectFileELF::GetSectionList()
501 {
502     if (m_sections_ap.get())
503         return m_sections_ap.get();
504 
505     if (ParseSectionHeaders() && GetSectionHeaderStringTable())
506     {
507         m_sections_ap.reset(new SectionList());
508 
509         for (SectionHeaderCollIter I = m_section_headers.begin();
510              I != m_section_headers.end(); ++I)
511         {
512             const ELFSectionHeader &header = *I;
513 
514             ConstString name(m_shstr_data.PeekCStr(header.sh_name));
515             uint64_t size = header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
516 
517             static ConstString g_sect_name_text (".text");
518             static ConstString g_sect_name_data (".data");
519             static ConstString g_sect_name_bss (".bss");
520             static ConstString g_sect_name_dwarf_debug_abbrev (".debug_abbrev");
521             static ConstString g_sect_name_dwarf_debug_aranges (".debug_aranges");
522             static ConstString g_sect_name_dwarf_debug_frame (".debug_frame");
523             static ConstString g_sect_name_dwarf_debug_info (".debug_info");
524             static ConstString g_sect_name_dwarf_debug_line (".debug_line");
525             static ConstString g_sect_name_dwarf_debug_loc (".debug_loc");
526             static ConstString g_sect_name_dwarf_debug_macinfo (".debug_macinfo");
527             static ConstString g_sect_name_dwarf_debug_pubnames (".debug_pubnames");
528             static ConstString g_sect_name_dwarf_debug_pubtypes (".debug_pubtypes");
529             static ConstString g_sect_name_dwarf_debug_ranges (".debug_ranges");
530             static ConstString g_sect_name_dwarf_debug_str (".debug_str");
531             static ConstString g_sect_name_eh_frame (".eh_frame");
532 
533             SectionType sect_type = eSectionTypeOther;
534 
535             if      (name == g_sect_name_text)                  sect_type = eSectionTypeCode;
536             else if (name == g_sect_name_data)                  sect_type = eSectionTypeData;
537             else if (name == g_sect_name_bss)                   sect_type = eSectionTypeZeroFill;
538             else if (name == g_sect_name_dwarf_debug_abbrev)    sect_type = eSectionTypeDWARFDebugAbbrev;
539             else if (name == g_sect_name_dwarf_debug_aranges)   sect_type = eSectionTypeDWARFDebugAranges;
540             else if (name == g_sect_name_dwarf_debug_frame)     sect_type = eSectionTypeDWARFDebugFrame;
541             else if (name == g_sect_name_dwarf_debug_info)      sect_type = eSectionTypeDWARFDebugInfo;
542             else if (name == g_sect_name_dwarf_debug_line)      sect_type = eSectionTypeDWARFDebugLine;
543             else if (name == g_sect_name_dwarf_debug_loc)       sect_type = eSectionTypeDWARFDebugLoc;
544             else if (name == g_sect_name_dwarf_debug_macinfo)   sect_type = eSectionTypeDWARFDebugMacInfo;
545             else if (name == g_sect_name_dwarf_debug_pubnames)  sect_type = eSectionTypeDWARFDebugPubNames;
546             else if (name == g_sect_name_dwarf_debug_pubtypes)  sect_type = eSectionTypeDWARFDebugPubTypes;
547             else if (name == g_sect_name_dwarf_debug_ranges)    sect_type = eSectionTypeDWARFDebugRanges;
548             else if (name == g_sect_name_dwarf_debug_str)       sect_type = eSectionTypeDWARFDebugStr;
549             else if (name == g_sect_name_eh_frame)              sect_type = eSectionTypeEHFrame;
550 
551 
552             SectionSP section(new Section(
553                 0,                  // Parent section.
554                 GetModule(),        // Module to which this section belongs.
555                 SectionIndex(I),    // Section ID.
556                 name,               // Section name.
557                 sect_type,          // Section type.
558                 header.sh_addr,     // VM address.
559                 header.sh_size,     // VM size in bytes of this section.
560                 header.sh_offset,   // Offset of this section in the file.
561                 size,               // Size of the section as found in the file.
562                 header.sh_flags));  // Flags for this section.
563 
564             m_sections_ap->AddSection(section);
565         }
566     }
567 
568     return m_sections_ap.get();
569 }
570 
571 static void
572 ParseSymbols(Symtab *symtab, SectionList *section_list,
573              const ELFSectionHeader &symtab_shdr,
574              const DataExtractor &symtab_data,
575              const DataExtractor &strtab_data)
576 {
577     ELFSymbol symbol;
578     uint32_t offset = 0;
579     const unsigned numSymbols =
580         symtab_data.GetByteSize() / symtab_shdr.sh_entsize;
581 
582     static ConstString text_section_name(".text");
583     static ConstString init_section_name(".init");
584     static ConstString fini_section_name(".fini");
585     static ConstString ctors_section_name(".ctors");
586     static ConstString dtors_section_name(".dtors");
587 
588     static ConstString data_section_name(".data");
589     static ConstString rodata_section_name(".rodata");
590     static ConstString rodata1_section_name(".rodata1");
591     static ConstString data2_section_name(".data1");
592     static ConstString bss_section_name(".bss");
593 
594     for (unsigned i = 0; i < numSymbols; ++i)
595     {
596         if (symbol.Parse(symtab_data, &offset) == false)
597             break;
598 
599         Section *symbol_section = NULL;
600         SymbolType symbol_type = eSymbolTypeInvalid;
601         Elf64_Half symbol_idx = symbol.st_shndx;
602 
603         switch (symbol_idx)
604         {
605         case SHN_ABS:
606             symbol_type = eSymbolTypeAbsolute;
607             break;
608         case SHN_UNDEF:
609             symbol_type = eSymbolTypeUndefined;
610             break;
611         default:
612             symbol_section = section_list->GetSectionAtIndex(symbol_idx).get();
613             break;
614         }
615 
616         switch (symbol.getType())
617         {
618         default:
619         case STT_NOTYPE:
620             // The symbol's type is not specified.
621             break;
622 
623         case STT_OBJECT:
624             // The symbol is associated with a data object, such as a variable,
625             // an array, etc.
626             symbol_type = eSymbolTypeData;
627             break;
628 
629         case STT_FUNC:
630             // The symbol is associated with a function or other executable code.
631             symbol_type = eSymbolTypeCode;
632             break;
633 
634         case STT_SECTION:
635             // The symbol is associated with a section. Symbol table entries of
636             // this type exist primarily for relocation and normally have
637             // STB_LOCAL binding.
638             break;
639 
640         case STT_FILE:
641             // Conventionally, the symbol's name gives the name of the source
642             // file associated with the object file. A file symbol has STB_LOCAL
643             // binding, its section index is SHN_ABS, and it precedes the other
644             // STB_LOCAL symbols for the file, if it is present.
645             symbol_type = eSymbolTypeObjectFile;
646             break;
647         }
648 
649         if (symbol_type == eSymbolTypeInvalid)
650         {
651             if (symbol_section)
652             {
653                 const ConstString &sect_name = symbol_section->GetName();
654                 if (sect_name == text_section_name ||
655                     sect_name == init_section_name ||
656                     sect_name == fini_section_name ||
657                     sect_name == ctors_section_name ||
658                     sect_name == dtors_section_name)
659                 {
660                     symbol_type = eSymbolTypeCode;
661                 }
662                 else if (sect_name == data_section_name ||
663                          sect_name == data2_section_name ||
664                          sect_name == rodata_section_name ||
665                          sect_name == rodata1_section_name ||
666                          sect_name == bss_section_name)
667                 {
668                     symbol_type = eSymbolTypeData;
669                 }
670             }
671         }
672 
673         uint64_t symbol_value = symbol.st_value;
674         if (symbol_section != NULL)
675             symbol_value -= symbol_section->GetFileAddress();
676         const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
677         bool is_global = symbol.getBinding() == STB_GLOBAL;
678         uint32_t flags = symbol.st_other << 8 | symbol.st_info;
679 
680         Symbol dc_symbol(
681             i,               // ID is the original symbol table index.
682             symbol_name,     // Symbol name.
683             false,           // Is the symbol name mangled?
684             symbol_type,     // Type of this symbol
685             is_global,       // Is this globally visible?
686             false,           // Is this symbol debug info?
687             false,           // Is this symbol a trampoline?
688             false,           // Is this symbol artificial?
689             symbol_section,  // Section in which this symbol is defined or null.
690             symbol_value,    // Offset in section or symbol value.
691             symbol.st_size,  // Size in bytes of this symbol.
692             flags);          // Symbol flags.
693         symtab->AddSymbol(dc_symbol);
694     }
695 }
696 
697 void
698 ObjectFileELF::ParseSymbolTable(Symtab *symbol_table,
699                                 const ELFSectionHeader &symtab_hdr,
700                                 user_id_t symtab_id)
701 {
702     assert(symtab_hdr.sh_type == SHT_SYMTAB ||
703            symtab_hdr.sh_type == SHT_DYNSYM);
704 
705     // Parse in the section list if needed.
706     SectionList *section_list = GetSectionList();
707     if (!section_list)
708         return;
709 
710     // Section ID's are ones based.
711     user_id_t strtab_id = symtab_hdr.sh_link + 1;
712 
713     Section *symtab = section_list->FindSectionByID(symtab_id).get();
714     Section *strtab = section_list->FindSectionByID(strtab_id).get();
715     if (symtab && strtab)
716     {
717         DataExtractor symtab_data;
718         DataExtractor strtab_data;
719         if (symtab->ReadSectionDataFromObjectFile(this, symtab_data) &&
720             strtab->ReadSectionDataFromObjectFile(this, strtab_data))
721         {
722             ParseSymbols(symbol_table, section_list, symtab_hdr,
723                          symtab_data, strtab_data);
724         }
725     }
726 }
727 
728 Symtab *
729 ObjectFileELF::GetSymtab()
730 {
731     if (m_symtab_ap.get())
732         return m_symtab_ap.get();
733 
734     Symtab *symbol_table = new Symtab(this);
735     m_symtab_ap.reset(symbol_table);
736 
737     Mutex::Locker locker (symbol_table->GetMutex ());
738 
739     if (!(ParseSectionHeaders() && GetSectionHeaderStringTable()))
740         return symbol_table;
741 
742     // Locate and parse all linker symbol tables.
743     for (SectionHeaderCollIter I = m_section_headers.begin();
744          I != m_section_headers.end(); ++I)
745     {
746         if (I->sh_type == SHT_SYMTAB)
747         {
748             const ELFSectionHeader &symtab_section = *I;
749             user_id_t section_id = SectionIndex(I);
750             ParseSymbolTable (symbol_table, symtab_section, section_id);
751         }
752     }
753 
754     return symbol_table;
755 }
756 
757 //===----------------------------------------------------------------------===//
758 // Dump
759 //
760 // Dump the specifics of the runtime file container (such as any headers
761 // segments, sections, etc).
762 //----------------------------------------------------------------------
763 void
764 ObjectFileELF::Dump(Stream *s)
765 {
766     DumpELFHeader(s, m_header);
767     s->EOL();
768     DumpELFProgramHeaders(s);
769     s->EOL();
770     DumpELFSectionHeaders(s);
771     s->EOL();
772     SectionList *section_list = GetSectionList();
773     if (section_list)
774         section_list->Dump(s, NULL, true, UINT32_MAX);
775     Symtab *symtab = GetSymtab();
776     if (symtab)
777         symtab->Dump(s, NULL, lldb::eSortOrderNone);
778     s->EOL();
779     DumpDependentModules(s);
780     s->EOL();
781 }
782 
783 //----------------------------------------------------------------------
784 // DumpELFHeader
785 //
786 // Dump the ELF header to the specified output stream
787 //----------------------------------------------------------------------
788 void
789 ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header)
790 {
791     s->PutCString("ELF Header\n");
792     s->Printf("e_ident[EI_MAG0   ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
793     s->Printf("e_ident[EI_MAG1   ] = 0x%2.2x '%c'\n",
794               header.e_ident[EI_MAG1], header.e_ident[EI_MAG1]);
795     s->Printf("e_ident[EI_MAG2   ] = 0x%2.2x '%c'\n",
796               header.e_ident[EI_MAG2], header.e_ident[EI_MAG2]);
797     s->Printf("e_ident[EI_MAG3   ] = 0x%2.2x '%c'\n",
798               header.e_ident[EI_MAG3], header.e_ident[EI_MAG3]);
799 
800     s->Printf("e_ident[EI_CLASS  ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
801     s->Printf("e_ident[EI_DATA   ] = 0x%2.2x ", header.e_ident[EI_DATA]);
802     DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
803     s->Printf ("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
804     s->Printf ("e_ident[EI_PAD    ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
805 
806     s->Printf("e_type      = 0x%4.4x ", header.e_type);
807     DumpELFHeader_e_type(s, header.e_type);
808     s->Printf("\ne_machine   = 0x%4.4x\n", header.e_machine);
809     s->Printf("e_version   = 0x%8.8x\n", header.e_version);
810     s->Printf("e_entry     = 0x%8.8lx\n", header.e_entry);
811     s->Printf("e_phoff     = 0x%8.8lx\n", header.e_phoff);
812     s->Printf("e_shoff     = 0x%8.8lx\n", header.e_shoff);
813     s->Printf("e_flags     = 0x%8.8x\n", header.e_flags);
814     s->Printf("e_ehsize    = 0x%4.4x\n", header.e_ehsize);
815     s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
816     s->Printf("e_phnum     = 0x%4.4x\n", header.e_phnum);
817     s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
818     s->Printf("e_shnum     = 0x%4.4x\n", header.e_shnum);
819     s->Printf("e_shstrndx  = 0x%4.4x\n", header.e_shstrndx);
820 }
821 
822 //----------------------------------------------------------------------
823 // DumpELFHeader_e_type
824 //
825 // Dump an token value for the ELF header member e_type
826 //----------------------------------------------------------------------
827 void
828 ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type)
829 {
830     switch (e_type)
831     {
832     case ET_NONE:   *s << "ET_NONE"; break;
833     case ET_REL:    *s << "ET_REL"; break;
834     case ET_EXEC:   *s << "ET_EXEC"; break;
835     case ET_DYN:    *s << "ET_DYN"; break;
836     case ET_CORE:   *s << "ET_CORE"; break;
837     default:
838         break;
839     }
840 }
841 
842 //----------------------------------------------------------------------
843 // DumpELFHeader_e_ident_EI_DATA
844 //
845 // Dump an token value for the ELF header member e_ident[EI_DATA]
846 //----------------------------------------------------------------------
847 void
848 ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s, unsigned char ei_data)
849 {
850     switch (ei_data)
851     {
852     case ELFDATANONE:   *s << "ELFDATANONE"; break;
853     case ELFDATA2LSB:   *s << "ELFDATA2LSB - Little Endian"; break;
854     case ELFDATA2MSB:   *s << "ELFDATA2MSB - Big Endian"; break;
855     default:
856         break;
857     }
858 }
859 
860 
861 //----------------------------------------------------------------------
862 // DumpELFProgramHeader
863 //
864 // Dump a single ELF program header to the specified output stream
865 //----------------------------------------------------------------------
866 void
867 ObjectFileELF::DumpELFProgramHeader(Stream *s, const ELFProgramHeader &ph)
868 {
869     DumpELFProgramHeader_p_type(s, ph.p_type);
870     s->Printf(" %8.8lx %8.8lx %8.8lx", ph.p_offset, ph.p_vaddr, ph.p_paddr);
871     s->Printf(" %8.8lx %8.8lx %8.8lx (", ph.p_filesz, ph.p_memsz, ph.p_flags);
872 
873     DumpELFProgramHeader_p_flags(s, ph.p_flags);
874     s->Printf(") %8.8x", ph.p_align);
875 }
876 
877 //----------------------------------------------------------------------
878 // DumpELFProgramHeader_p_type
879 //
880 // Dump an token value for the ELF program header member p_type which
881 // describes the type of the program header
882 // ----------------------------------------------------------------------
883 void
884 ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type)
885 {
886     const int kStrWidth = 10;
887     switch (p_type)
888     {
889     CASE_AND_STREAM(s, PT_NULL      , kStrWidth);
890     CASE_AND_STREAM(s, PT_LOAD      , kStrWidth);
891     CASE_AND_STREAM(s, PT_DYNAMIC   , kStrWidth);
892     CASE_AND_STREAM(s, PT_INTERP    , kStrWidth);
893     CASE_AND_STREAM(s, PT_NOTE      , kStrWidth);
894     CASE_AND_STREAM(s, PT_SHLIB     , kStrWidth);
895     CASE_AND_STREAM(s, PT_PHDR      , kStrWidth);
896     default:
897         s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
898         break;
899     }
900 }
901 
902 
903 //----------------------------------------------------------------------
904 // DumpELFProgramHeader_p_flags
905 //
906 // Dump an token value for the ELF program header member p_flags
907 //----------------------------------------------------------------------
908 void
909 ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags)
910 {
911     *s  << ((p_flags & PF_X) ? "PF_X" : "    ")
912         << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
913         << ((p_flags & PF_W) ? "PF_W" : "    ")
914         << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
915         << ((p_flags & PF_R) ? "PF_R" : "    ");
916 }
917 
918 //----------------------------------------------------------------------
919 // DumpELFProgramHeaders
920 //
921 // Dump all of the ELF program header to the specified output stream
922 //----------------------------------------------------------------------
923 void
924 ObjectFileELF::DumpELFProgramHeaders(Stream *s)
925 {
926     if (ParseProgramHeaders())
927     {
928         s->PutCString("Program Headers\n");
929         s->PutCString("IDX  p_type     p_offset p_vaddr  p_paddr  "
930                       "p_filesz p_memsz  p_flags                   p_align\n");
931         s->PutCString("==== ---------- -------- -------- -------- "
932                       "-------- -------- ------------------------- --------\n");
933 
934         uint32_t idx = 0;
935         for (ProgramHeaderCollConstIter I = m_program_headers.begin();
936              I != m_program_headers.end(); ++I, ++idx)
937         {
938             s->Printf("[%2u] ", idx);
939             ObjectFileELF::DumpELFProgramHeader(s, *I);
940             s->EOL();
941         }
942     }
943 }
944 
945 //----------------------------------------------------------------------
946 // DumpELFSectionHeader
947 //
948 // Dump a single ELF section header to the specified output stream
949 //----------------------------------------------------------------------
950 void
951 ObjectFileELF::DumpELFSectionHeader(Stream *s, const ELFSectionHeader &sh)
952 {
953     s->Printf("%8.8x ", sh.sh_name);
954     DumpELFSectionHeader_sh_type(s, sh.sh_type);
955     s->Printf(" %8.8lx (", sh.sh_flags);
956     DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
957     s->Printf(") %8.8lx %8.8lx %8.8lx", sh.sh_addr, sh.sh_offset, sh.sh_size);
958     s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
959     s->Printf(" %8.8lx %8.8lx", sh.sh_addralign, sh.sh_entsize);
960 }
961 
962 //----------------------------------------------------------------------
963 // DumpELFSectionHeader_sh_type
964 //
965 // Dump an token value for the ELF section header member sh_type which
966 // describes the type of the section
967 //----------------------------------------------------------------------
968 void
969 ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type)
970 {
971     const int kStrWidth = 12;
972     switch (sh_type)
973     {
974     CASE_AND_STREAM(s, SHT_NULL     , kStrWidth);
975     CASE_AND_STREAM(s, SHT_PROGBITS , kStrWidth);
976     CASE_AND_STREAM(s, SHT_SYMTAB   , kStrWidth);
977     CASE_AND_STREAM(s, SHT_STRTAB   , kStrWidth);
978     CASE_AND_STREAM(s, SHT_RELA     , kStrWidth);
979     CASE_AND_STREAM(s, SHT_HASH     , kStrWidth);
980     CASE_AND_STREAM(s, SHT_DYNAMIC  , kStrWidth);
981     CASE_AND_STREAM(s, SHT_NOTE     , kStrWidth);
982     CASE_AND_STREAM(s, SHT_NOBITS   , kStrWidth);
983     CASE_AND_STREAM(s, SHT_REL      , kStrWidth);
984     CASE_AND_STREAM(s, SHT_SHLIB    , kStrWidth);
985     CASE_AND_STREAM(s, SHT_DYNSYM   , kStrWidth);
986     CASE_AND_STREAM(s, SHT_LOPROC   , kStrWidth);
987     CASE_AND_STREAM(s, SHT_HIPROC   , kStrWidth);
988     CASE_AND_STREAM(s, SHT_LOUSER   , kStrWidth);
989     CASE_AND_STREAM(s, SHT_HIUSER   , kStrWidth);
990     default:
991         s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
992         break;
993     }
994 }
995 
996 //----------------------------------------------------------------------
997 // DumpELFSectionHeader_sh_flags
998 //
999 // Dump an token value for the ELF section header member sh_flags
1000 //----------------------------------------------------------------------
1001 void
1002 ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s, elf_word sh_flags)
1003 {
1004     *s  << ((sh_flags & SHF_WRITE) ? "WRITE" : "     ")
1005         << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
1006         << ((sh_flags & SHF_ALLOC) ? "ALLOC" : "     ")
1007         << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
1008         << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : "         ");
1009 }
1010 
1011 //----------------------------------------------------------------------
1012 // DumpELFSectionHeaders
1013 //
1014 // Dump all of the ELF section header to the specified output stream
1015 //----------------------------------------------------------------------
1016 void
1017 ObjectFileELF::DumpELFSectionHeaders(Stream *s)
1018 {
1019     if (!(ParseSectionHeaders() && GetSectionHeaderStringTable()))
1020         return;
1021 
1022     s->PutCString("Section Headers\n");
1023     s->PutCString("IDX  name     type         flags                            "
1024                   "addr     offset   size     link     info     addralgn "
1025                   "entsize  Name\n");
1026     s->PutCString("==== -------- ------------ -------------------------------- "
1027                   "-------- -------- -------- -------- -------- -------- "
1028                   "-------- ====================\n");
1029 
1030     uint32_t idx = 0;
1031     for (SectionHeaderCollConstIter I = m_section_headers.begin();
1032          I != m_section_headers.end(); ++I, ++idx)
1033     {
1034         s->Printf("[%2u] ", idx);
1035         ObjectFileELF::DumpELFSectionHeader(s, *I);
1036         const char* section_name = m_shstr_data.PeekCStr(I->sh_name);
1037         if (section_name)
1038             *s << ' ' << section_name << "\n";
1039     }
1040 }
1041 
1042 void
1043 ObjectFileELF::DumpDependentModules(lldb_private::Stream *s)
1044 {
1045     size_t num_modules = ParseDependentModules();
1046 
1047     if (num_modules > 0)
1048     {
1049         s->PutCString("Dependent Modules:\n");
1050         for (unsigned i = 0; i < num_modules; ++i)
1051         {
1052             const FileSpec &spec = m_filespec_ap->GetFileSpecAtIndex(i);
1053             s->Printf("   %s\n", spec.GetFilename().GetCString());
1054         }
1055     }
1056 }
1057 
1058 bool
1059 ObjectFileELF::GetArchitecture (ArchSpec &arch)
1060 {
1061     if (!ParseHeader())
1062         return false;
1063 
1064     arch.SetArchitecture (lldb::eArchTypeELF, m_header.e_machine, LLDB_INVALID_CPUTYPE);
1065     arch.GetTriple().setOSName (Host::GetOSString().GetCString());
1066     arch.GetTriple().setVendorName(Host::GetVendorString().GetCString());
1067     return true;
1068 }
1069 
1070