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