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/ModuleSpec.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/Section.h"
23 #include "lldb/Core/Stream.h"
24 #include "lldb/Symbol/DWARFCallFrameInfo.h"
25 #include "lldb/Symbol/SymbolContext.h"
26 #include "lldb/Host/Host.h"
27 
28 #include "llvm/ADT/PointerUnion.h"
29 
30 #define CASE_AND_STREAM(s, def, width)                  \
31     case def: s->Printf("%-*s", width, #def); break;
32 
33 using namespace lldb;
34 using namespace lldb_private;
35 using namespace elf;
36 using namespace llvm::ELF;
37 
38 namespace {
39 //===----------------------------------------------------------------------===//
40 /// @class ELFRelocation
41 /// @brief Generic wrapper for ELFRel and ELFRela.
42 ///
43 /// This helper class allows us to parse both ELFRel and ELFRela relocation
44 /// entries in a generic manner.
45 class ELFRelocation
46 {
47 public:
48 
49     /// Constructs an ELFRelocation entry with a personality as given by @p
50     /// type.
51     ///
52     /// @param type Either DT_REL or DT_RELA.  Any other value is invalid.
53     ELFRelocation(unsigned type);
54 
55     ~ELFRelocation();
56 
57     bool
58     Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
59 
60     static unsigned
61     RelocType32(const ELFRelocation &rel);
62 
63     static unsigned
64     RelocType64(const ELFRelocation &rel);
65 
66     static unsigned
67     RelocSymbol32(const ELFRelocation &rel);
68 
69     static unsigned
70     RelocSymbol64(const ELFRelocation &rel);
71 
72 private:
73     typedef llvm::PointerUnion<ELFRel*, ELFRela*> RelocUnion;
74 
75     RelocUnion reloc;
76 };
77 
78 ELFRelocation::ELFRelocation(unsigned type)
79 {
80     if (type == DT_REL)
81         reloc = new ELFRel();
82     else if (type == DT_RELA)
83         reloc = new ELFRela();
84     else {
85         assert(false && "unexpected relocation type");
86         reloc = static_cast<ELFRel*>(NULL);
87     }
88 }
89 
90 ELFRelocation::~ELFRelocation()
91 {
92     if (reloc.is<ELFRel*>())
93         delete reloc.get<ELFRel*>();
94     else
95         delete reloc.get<ELFRela*>();
96 }
97 
98 bool
99 ELFRelocation::Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)
100 {
101     if (reloc.is<ELFRel*>())
102         return reloc.get<ELFRel*>()->Parse(data, offset);
103     else
104         return reloc.get<ELFRela*>()->Parse(data, offset);
105 }
106 
107 unsigned
108 ELFRelocation::RelocType32(const ELFRelocation &rel)
109 {
110     if (rel.reloc.is<ELFRel*>())
111         return ELFRel::RelocType32(*rel.reloc.get<ELFRel*>());
112     else
113         return ELFRela::RelocType32(*rel.reloc.get<ELFRela*>());
114 }
115 
116 unsigned
117 ELFRelocation::RelocType64(const ELFRelocation &rel)
118 {
119     if (rel.reloc.is<ELFRel*>())
120         return ELFRel::RelocType64(*rel.reloc.get<ELFRel*>());
121     else
122         return ELFRela::RelocType64(*rel.reloc.get<ELFRela*>());
123 }
124 
125 unsigned
126 ELFRelocation::RelocSymbol32(const ELFRelocation &rel)
127 {
128     if (rel.reloc.is<ELFRel*>())
129         return ELFRel::RelocSymbol32(*rel.reloc.get<ELFRel*>());
130     else
131         return ELFRela::RelocSymbol32(*rel.reloc.get<ELFRela*>());
132 }
133 
134 unsigned
135 ELFRelocation::RelocSymbol64(const ELFRelocation &rel)
136 {
137     if (rel.reloc.is<ELFRel*>())
138         return ELFRel::RelocSymbol64(*rel.reloc.get<ELFRel*>());
139     else
140         return ELFRela::RelocSymbol64(*rel.reloc.get<ELFRela*>());
141 }
142 
143 } // end anonymous namespace
144 
145 //------------------------------------------------------------------
146 // Static methods.
147 //------------------------------------------------------------------
148 void
149 ObjectFileELF::Initialize()
150 {
151     PluginManager::RegisterPlugin(GetPluginNameStatic(),
152                                   GetPluginDescriptionStatic(),
153                                   CreateInstance,
154                                   CreateMemoryInstance,
155                                   GetModuleSpecifications);
156 }
157 
158 void
159 ObjectFileELF::Terminate()
160 {
161     PluginManager::UnregisterPlugin(CreateInstance);
162 }
163 
164 lldb_private::ConstString
165 ObjectFileELF::GetPluginNameStatic()
166 {
167     static ConstString g_name("elf");
168     return g_name;
169 }
170 
171 const char *
172 ObjectFileELF::GetPluginDescriptionStatic()
173 {
174     return "ELF object file reader.";
175 }
176 
177 ObjectFile *
178 ObjectFileELF::CreateInstance (const lldb::ModuleSP &module_sp,
179                                DataBufferSP &data_sp,
180                                lldb::offset_t data_offset,
181                                const lldb_private::FileSpec* file,
182                                lldb::offset_t file_offset,
183                                lldb::offset_t length)
184 {
185     if (!data_sp)
186     {
187         data_sp = file->MemoryMapFileContents(file_offset, length);
188         data_offset = 0;
189     }
190 
191     if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset))
192     {
193         const uint8_t *magic = data_sp->GetBytes() + data_offset;
194         if (ELFHeader::MagicBytesMatch(magic))
195         {
196             // Update the data to contain the entire file if it doesn't already
197             if (data_sp->GetByteSize() < length) {
198                 data_sp = file->MemoryMapFileContents(file_offset, length);
199                 data_offset = 0;
200                 magic = data_sp->GetBytes();
201             }
202             unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
203             if (address_size == 4 || address_size == 8)
204             {
205                 std::unique_ptr<ObjectFileELF> objfile_ap(new ObjectFileELF(module_sp, data_sp, data_offset, file, file_offset, length));
206                 ArchSpec spec;
207                 if (objfile_ap->GetArchitecture(spec) &&
208                     objfile_ap->SetModulesArchitecture(spec))
209                     return objfile_ap.release();
210             }
211         }
212     }
213     return NULL;
214 }
215 
216 
217 ObjectFile*
218 ObjectFileELF::CreateMemoryInstance (const lldb::ModuleSP &module_sp,
219                                      DataBufferSP& data_sp,
220                                      const lldb::ProcessSP &process_sp,
221                                      lldb::addr_t header_addr)
222 {
223     return NULL;
224 }
225 
226 bool
227 ObjectFileELF::MagicBytesMatch (DataBufferSP& data_sp,
228                                   lldb::addr_t data_offset,
229                                   lldb::addr_t data_length)
230 {
231     if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset))
232     {
233         const uint8_t *magic = data_sp->GetBytes() + data_offset;
234         return ELFHeader::MagicBytesMatch(magic);
235     }
236     return false;
237 }
238 
239 /*
240  * crc function from http://svnweb.freebsd.org/base/head/sys/libkern/crc32.c
241  *
242  *   COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or
243  *   code or tables extracted from it, as desired without restriction.
244  */
245 static uint32_t
246 calc_gnu_debuglink_crc32(const void *buf, size_t size)
247 {
248     static const uint32_t g_crc32_tab[] =
249     {
250         0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
251         0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
252         0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
253         0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
254         0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
255         0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
256         0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
257         0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
258         0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
259         0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
260         0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
261         0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
262         0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
263         0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
264         0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
265         0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
266         0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
267         0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
268         0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
269         0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
270         0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
271         0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
272         0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
273         0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
274         0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
275         0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
276         0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
277         0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
278         0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
279         0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
280         0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
281         0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
282         0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
283         0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
284         0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
285         0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
286         0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
287         0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
288         0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
289         0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
290         0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
291         0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
292         0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
293     };
294     const uint8_t *p = (const uint8_t *)buf;
295     uint32_t crc;
296 
297     crc = ~0U;
298     while (size--)
299         crc = g_crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
300     return crc ^ ~0U;
301 }
302 
303 size_t
304 ObjectFileELF::GetModuleSpecifications (const lldb_private::FileSpec& file,
305                                         lldb::DataBufferSP& data_sp,
306                                         lldb::offset_t data_offset,
307                                         lldb::offset_t file_offset,
308                                         lldb::offset_t length,
309                                         lldb_private::ModuleSpecList &specs)
310 {
311     const size_t initial_count = specs.GetSize();
312 
313     if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize()))
314     {
315         DataExtractor data;
316         data.SetData(data_sp);
317         elf::ELFHeader header;
318         if (header.Parse(data, &data_offset))
319         {
320             if (data_sp)
321             {
322                 ModuleSpec spec;
323                 spec.GetFileSpec() = file;
324                 spec.GetArchitecture().SetArchitecture(eArchTypeELF,
325                                                        header.e_machine,
326                                                        LLDB_INVALID_CPUTYPE);
327                 if (spec.GetArchitecture().IsValid())
328                 {
329                     // We could parse the ABI tag information (in .note, .notes, or .note.ABI-tag) to get the
330                     // machine information. However, this info isn't guaranteed to exist or be correct. Details:
331                     //  http://refspecs.linuxfoundation.org/LSB_1.2.0/gLSB/noteabitag.html
332                     // Instead of passing potentially incorrect information down the pipeline, grab
333                     // the host information and use it.
334                     spec.GetArchitecture().GetTriple().setOSName (Host::GetOSString().GetCString());
335                     spec.GetArchitecture().GetTriple().setVendorName(Host::GetVendorString().GetCString());
336 
337                     // Try to get the UUID from the section list. Usually that's at the end, so
338                     // map the file in if we don't have it already.
339                     size_t section_header_end = header.e_shoff + header.e_shnum * header.e_shentsize;
340                     if (section_header_end > data_sp->GetByteSize())
341                     {
342                         data_sp = file.MemoryMapFileContents (file_offset, section_header_end);
343                         data.SetData(data_sp);
344                     }
345 
346                     uint32_t gnu_debuglink_crc = 0;
347                     std::string gnu_debuglink_file;
348                     SectionHeaderColl section_headers;
349                     lldb_private::UUID &uuid = spec.GetUUID();
350                     GetSectionHeaderInfo(section_headers, data, header, uuid, gnu_debuglink_file, gnu_debuglink_crc);
351 
352                     if (!uuid.IsValid())
353                     {
354                         if (!gnu_debuglink_crc)
355                         {
356                             // Need to map entire file into memory to calculate the crc.
357                             data_sp = file.MemoryMapFileContents (file_offset, SIZE_MAX);
358                             data.SetData(data_sp);
359                             gnu_debuglink_crc = calc_gnu_debuglink_crc32 (data.GetDataStart(), data.GetByteSize());
360                         }
361                         if (gnu_debuglink_crc)
362                         {
363                             // Use 4 bytes of crc from the .gnu_debuglink section.
364                             uint32_t uuidt[4] = { gnu_debuglink_crc, 0, 0, 0 };
365                             uuid.SetBytes (uuidt, sizeof(uuidt));
366                         }
367                     }
368 
369                     specs.Append(spec);
370                 }
371             }
372         }
373     }
374 
375     return specs.GetSize() - initial_count;
376 }
377 
378 //------------------------------------------------------------------
379 // PluginInterface protocol
380 //------------------------------------------------------------------
381 lldb_private::ConstString
382 ObjectFileELF::GetPluginName()
383 {
384     return GetPluginNameStatic();
385 }
386 
387 uint32_t
388 ObjectFileELF::GetPluginVersion()
389 {
390     return m_plugin_version;
391 }
392 //------------------------------------------------------------------
393 // ObjectFile protocol
394 //------------------------------------------------------------------
395 
396 ObjectFileELF::ObjectFileELF (const lldb::ModuleSP &module_sp,
397                               DataBufferSP& data_sp,
398                               lldb::offset_t data_offset,
399                               const FileSpec* file,
400                               lldb::offset_t file_offset,
401                               lldb::offset_t length) :
402     ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
403     m_header(),
404     m_program_headers(),
405     m_section_headers(),
406     m_filespec_ap()
407 {
408     if (file)
409         m_file = *file;
410     ::memset(&m_header, 0, sizeof(m_header));
411     m_gnu_debuglink_crc = 0;
412     m_gnu_debuglink_file.clear();
413 }
414 
415 ObjectFileELF::~ObjectFileELF()
416 {
417 }
418 
419 bool
420 ObjectFileELF::IsExecutable() const
421 {
422     return m_header.e_entry != 0;
423 }
424 
425 ByteOrder
426 ObjectFileELF::GetByteOrder() const
427 {
428     if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
429         return eByteOrderBig;
430     if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
431         return eByteOrderLittle;
432     return eByteOrderInvalid;
433 }
434 
435 uint32_t
436 ObjectFileELF::GetAddressByteSize() const
437 {
438     return m_data.GetAddressByteSize();
439 }
440 
441 size_t
442 ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I)
443 {
444     return std::distance(m_section_headers.begin(), I) + 1u;
445 }
446 
447 size_t
448 ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const
449 {
450     return std::distance(m_section_headers.begin(), I) + 1u;
451 }
452 
453 bool
454 ObjectFileELF::ParseHeader()
455 {
456     lldb::offset_t offset = 0;
457     return m_header.Parse(m_data, &offset);
458 }
459 
460 bool
461 ObjectFileELF::GetUUID(lldb_private::UUID* uuid)
462 {
463     // Need to parse the section list to get the UUIDs, so make sure that's been done.
464     if (!ParseSectionHeaders())
465         return false;
466 
467     if (m_uuid.IsValid())
468     {
469         // We have the full build id uuid.
470         *uuid = m_uuid;
471         return true;
472     }
473     else
474     {
475         if (!m_gnu_debuglink_crc)
476             m_gnu_debuglink_crc = calc_gnu_debuglink_crc32 (m_data.GetDataStart(), m_data.GetByteSize());
477         if (m_gnu_debuglink_crc)
478         {
479             // Use 4 bytes of crc from the .gnu_debuglink section.
480             uint32_t uuidt[4] = { m_gnu_debuglink_crc, 0, 0, 0 };
481             uuid->SetBytes (uuidt, sizeof(uuidt));
482             return true;
483         }
484     }
485 
486     return false;
487 }
488 
489 lldb_private::FileSpecList
490 ObjectFileELF::GetDebugSymbolFilePaths()
491 {
492     FileSpecList file_spec_list;
493 
494     if (!m_gnu_debuglink_file.empty())
495     {
496         FileSpec file_spec (m_gnu_debuglink_file.c_str(), false);
497         file_spec_list.Append (file_spec);
498     }
499     return file_spec_list;
500 }
501 
502 uint32_t
503 ObjectFileELF::GetDependentModules(FileSpecList &files)
504 {
505     size_t num_modules = ParseDependentModules();
506     uint32_t num_specs = 0;
507 
508     for (unsigned i = 0; i < num_modules; ++i)
509     {
510         if (files.AppendIfUnique(m_filespec_ap->GetFileSpecAtIndex(i)))
511             num_specs++;
512     }
513 
514     return num_specs;
515 }
516 
517 Address
518 ObjectFileELF::GetImageInfoAddress(bool &indirect)
519 {
520     if (!ParseDynamicSymbols())
521         return Address();
522 
523     SectionList *section_list = GetSectionList();
524     if (!section_list)
525         return Address();
526 
527     // Find the SHT_DYNAMIC (.dynamic) section.
528     SectionSP dynsym_section_sp (section_list->FindSectionByType (eSectionTypeELFDynamicLinkInfo, true));
529     if (!dynsym_section_sp)
530         return Address();
531     assert (dynsym_section_sp->GetObjectFile() == this);
532 
533     user_id_t dynsym_id = dynsym_section_sp->GetID();
534     const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
535     if (!dynsym_hdr)
536         return Address();
537 
538     for (size_t i = 0; i < m_dynamic_symbols.size(); ++i)
539     {
540         ELFDynamic &symbol = m_dynamic_symbols[i];
541 
542         if (symbol.d_tag == DT_DEBUG || symbol.d_tag == DT_MIPS_RLD_MAP)
543         {
544             indirect = (symbol.d_tag == DT_MIPS_RLD_MAP);
545             // Compute the offset as the number of previous entries plus the
546             // size of d_tag.
547             addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
548             return Address(dynsym_section_sp, offset);
549         }
550     }
551 
552     return Address();
553 }
554 
555 lldb_private::Address
556 ObjectFileELF::GetEntryPointAddress ()
557 {
558     if (m_entry_point_address.IsValid())
559         return m_entry_point_address;
560 
561     if (!ParseHeader() || !IsExecutable())
562         return m_entry_point_address;
563 
564     SectionList *section_list = GetSectionList();
565     addr_t offset = m_header.e_entry;
566 
567     if (!section_list)
568         m_entry_point_address.SetOffset(offset);
569     else
570         m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
571     return m_entry_point_address;
572 }
573 
574 //----------------------------------------------------------------------
575 // ParseDependentModules
576 //----------------------------------------------------------------------
577 size_t
578 ObjectFileELF::ParseDependentModules()
579 {
580     if (m_filespec_ap.get())
581         return m_filespec_ap->GetSize();
582 
583     m_filespec_ap.reset(new FileSpecList());
584 
585     if (!ParseSectionHeaders())
586         return 0;
587 
588     SectionList *section_list = GetSectionList();
589     if (!section_list)
590         return 0;
591 
592     // Find the SHT_DYNAMIC section.
593     Section *dynsym = section_list->FindSectionByType (eSectionTypeELFDynamicLinkInfo, true).get();
594     if (!dynsym)
595         return 0;
596     assert (dynsym->GetObjectFile() == this);
597 
598     const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex (dynsym->GetID());
599     if (!header)
600         return 0;
601     // sh_link: section header index of string table used by entries in the section.
602     Section *dynstr = section_list->FindSectionByID (header->sh_link + 1).get();
603     if (!dynstr)
604         return 0;
605 
606     DataExtractor dynsym_data;
607     DataExtractor dynstr_data;
608     if (ReadSectionData(dynsym, dynsym_data) &&
609         ReadSectionData(dynstr, dynstr_data))
610     {
611         ELFDynamic symbol;
612         const lldb::offset_t section_size = dynsym_data.GetByteSize();
613         lldb::offset_t offset = 0;
614 
615         // The only type of entries we are concerned with are tagged DT_NEEDED,
616         // yielding the name of a required library.
617         while (offset < section_size)
618         {
619             if (!symbol.Parse(dynsym_data, &offset))
620                 break;
621 
622             if (symbol.d_tag != DT_NEEDED)
623                 continue;
624 
625             uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
626             const char *lib_name = dynstr_data.PeekCStr(str_index);
627             m_filespec_ap->Append(FileSpec(lib_name, true));
628         }
629     }
630 
631     return m_filespec_ap->GetSize();
632 }
633 
634 //----------------------------------------------------------------------
635 // ParseProgramHeaders
636 //----------------------------------------------------------------------
637 size_t
638 ObjectFileELF::ParseProgramHeaders()
639 {
640     // We have already parsed the program headers
641     if (!m_program_headers.empty())
642         return m_program_headers.size();
643 
644     // If there are no program headers to read we are done.
645     if (m_header.e_phnum == 0)
646         return 0;
647 
648     m_program_headers.resize(m_header.e_phnum);
649     if (m_program_headers.size() != m_header.e_phnum)
650         return 0;
651 
652     const size_t ph_size = m_header.e_phnum * m_header.e_phentsize;
653     const elf_off ph_offset = m_header.e_phoff;
654     DataExtractor data;
655     if (GetData (ph_offset, ph_size, data) != ph_size)
656         return 0;
657 
658     uint32_t idx;
659     lldb::offset_t offset;
660     for (idx = 0, offset = 0; idx < m_header.e_phnum; ++idx)
661     {
662         if (m_program_headers[idx].Parse(data, &offset) == false)
663             break;
664     }
665 
666     if (idx < m_program_headers.size())
667         m_program_headers.resize(idx);
668 
669     return m_program_headers.size();
670 }
671 
672 static bool
673 ParseNoteGNUBuildID(DataExtractor &data, lldb_private::UUID &uuid)
674 {
675     // Try to parse the note section (ie .note.gnu.build-id|.notes|.note|...) and get the build id.
676     // BuildID documentation: https://fedoraproject.org/wiki/Releases/FeatureBuildId
677     struct
678     {
679         uint32_t name_len;  // Length of note name
680         uint32_t desc_len;  // Length of note descriptor
681         uint32_t type;      // Type of note (1 is ABI_TAG, 3 is BUILD_ID)
682     } notehdr;
683     lldb::offset_t offset = 0;
684     static const uint32_t g_gnu_build_id = 3; // NT_GNU_BUILD_ID from elf.h
685 
686     while (true)
687     {
688         if (data.GetU32 (&offset, &notehdr, 3) == NULL)
689             return false;
690 
691         notehdr.name_len = llvm::RoundUpToAlignment (notehdr.name_len, 4);
692         notehdr.desc_len = llvm::RoundUpToAlignment (notehdr.desc_len, 4);
693 
694         lldb::offset_t offset_next_note = offset + notehdr.name_len + notehdr.desc_len;
695 
696         // 16 bytes is UUID|MD5, 20 bytes is SHA1
697         if ((notehdr.type == g_gnu_build_id) && (notehdr.name_len == 4) &&
698             (notehdr.desc_len == 16 || notehdr.desc_len == 20))
699         {
700             char name[4];
701             if (data.GetU8 (&offset, name, 4) == NULL)
702                 return false;
703             if (!strcmp(name, "GNU"))
704             {
705                 uint8_t uuidbuf[20];
706                 if (data.GetU8 (&offset, &uuidbuf, notehdr.desc_len) == NULL)
707                     return false;
708                 uuid.SetBytes (uuidbuf, notehdr.desc_len);
709                 return true;
710             }
711         }
712         offset = offset_next_note;
713     }
714     return false;
715 }
716 
717 //----------------------------------------------------------------------
718 // GetSectionHeaderInfo
719 //----------------------------------------------------------------------
720 size_t
721 ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,
722                                     lldb_private::DataExtractor &object_data,
723                                     const elf::ELFHeader &header,
724                                     lldb_private::UUID &uuid,
725                                     std::string &gnu_debuglink_file,
726                                     uint32_t &gnu_debuglink_crc)
727 {
728     // We have already parsed the section headers
729     if (!section_headers.empty())
730         return section_headers.size();
731 
732     // If there are no section headers we are done.
733     if (header.e_shnum == 0)
734         return 0;
735 
736     section_headers.resize(header.e_shnum);
737     if (section_headers.size() != header.e_shnum)
738         return 0;
739 
740     const size_t sh_size = header.e_shnum * header.e_shentsize;
741     const elf_off sh_offset = header.e_shoff;
742     DataExtractor sh_data;
743     if (sh_data.SetData (object_data, sh_offset, sh_size) != sh_size)
744         return 0;
745 
746     uint32_t idx;
747     lldb::offset_t offset;
748     for (idx = 0, offset = 0; idx < header.e_shnum; ++idx)
749     {
750         if (section_headers[idx].Parse(sh_data, &offset) == false)
751             break;
752     }
753     if (idx < section_headers.size())
754         section_headers.resize(idx);
755 
756     const unsigned strtab_idx = header.e_shstrndx;
757     if (strtab_idx && strtab_idx < section_headers.size())
758     {
759         const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
760         const size_t byte_size = sheader.sh_size;
761         const Elf64_Off offset = sheader.sh_offset;
762         lldb_private::DataExtractor shstr_data;
763 
764         if (shstr_data.SetData (object_data, offset, byte_size) == byte_size)
765         {
766             for (SectionHeaderCollIter I = section_headers.begin();
767                  I != section_headers.end(); ++I)
768             {
769                 static ConstString g_sect_name_gnu_debuglink (".gnu_debuglink");
770                 const ELFSectionHeaderInfo &header = *I;
771                 const uint64_t section_size = header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
772                 ConstString name(shstr_data.PeekCStr(I->sh_name));
773 
774                 I->section_name = name;
775 
776                 if (name == g_sect_name_gnu_debuglink)
777                 {
778                     DataExtractor data;
779                     if (section_size && (data.SetData (object_data, header.sh_offset, section_size) == section_size))
780                     {
781                         lldb::offset_t gnu_debuglink_offset = 0;
782                         gnu_debuglink_file = data.GetCStr (&gnu_debuglink_offset);
783                         gnu_debuglink_offset = llvm::RoundUpToAlignment (gnu_debuglink_offset, 4);
784                         data.GetU32 (&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
785                     }
786                 }
787 
788                 if (header.sh_type == SHT_NOTE && !uuid.IsValid())
789                 {
790                     DataExtractor data;
791                     if (section_size && (data.SetData (object_data, header.sh_offset, section_size) == section_size))
792                     {
793                         ParseNoteGNUBuildID (data, uuid);
794                     }
795                 }
796             }
797 
798             return section_headers.size();
799         }
800     }
801 
802     section_headers.clear();
803     return 0;
804 }
805 
806 size_t
807 ObjectFileELF::GetProgramHeaderCount()
808 {
809     return ParseProgramHeaders();
810 }
811 
812 const elf::ELFProgramHeader *
813 ObjectFileELF::GetProgramHeaderByIndex(lldb::user_id_t id)
814 {
815     if (!id || !ParseProgramHeaders())
816         return NULL;
817 
818     if (--id < m_program_headers.size())
819         return &m_program_headers[id];
820 
821     return NULL;
822 }
823 
824 DataExtractor
825 ObjectFileELF::GetSegmentDataByIndex(lldb::user_id_t id)
826 {
827     const elf::ELFProgramHeader *segment_header = GetProgramHeaderByIndex(id);
828     if (segment_header == NULL)
829         return DataExtractor();
830     return DataExtractor(m_data, segment_header->p_offset, segment_header->p_filesz);
831 }
832 
833 //----------------------------------------------------------------------
834 // ParseSectionHeaders
835 //----------------------------------------------------------------------
836 size_t
837 ObjectFileELF::ParseSectionHeaders()
838 {
839     return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid, m_gnu_debuglink_file, m_gnu_debuglink_crc);
840 }
841 
842 const ObjectFileELF::ELFSectionHeaderInfo *
843 ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id)
844 {
845     if (!id || !ParseSectionHeaders())
846         return NULL;
847 
848     if (--id < m_section_headers.size())
849         return &m_section_headers[id];
850 
851     return NULL;
852 }
853 
854 void
855 ObjectFileELF::CreateSections(SectionList &unified_section_list)
856 {
857     if (!m_sections_ap.get() && ParseSectionHeaders())
858     {
859         m_sections_ap.reset(new SectionList());
860 
861         for (SectionHeaderCollIter I = m_section_headers.begin();
862              I != m_section_headers.end(); ++I)
863         {
864             const ELFSectionHeaderInfo &header = *I;
865 
866             ConstString& name = I->section_name;
867             const uint64_t file_size = header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
868             const uint64_t vm_size = header.sh_flags & SHF_ALLOC ? header.sh_size : 0;
869 
870             static ConstString g_sect_name_text (".text");
871             static ConstString g_sect_name_data (".data");
872             static ConstString g_sect_name_bss (".bss");
873             static ConstString g_sect_name_tdata (".tdata");
874             static ConstString g_sect_name_tbss (".tbss");
875             static ConstString g_sect_name_dwarf_debug_abbrev (".debug_abbrev");
876             static ConstString g_sect_name_dwarf_debug_aranges (".debug_aranges");
877             static ConstString g_sect_name_dwarf_debug_frame (".debug_frame");
878             static ConstString g_sect_name_dwarf_debug_info (".debug_info");
879             static ConstString g_sect_name_dwarf_debug_line (".debug_line");
880             static ConstString g_sect_name_dwarf_debug_loc (".debug_loc");
881             static ConstString g_sect_name_dwarf_debug_macinfo (".debug_macinfo");
882             static ConstString g_sect_name_dwarf_debug_pubnames (".debug_pubnames");
883             static ConstString g_sect_name_dwarf_debug_pubtypes (".debug_pubtypes");
884             static ConstString g_sect_name_dwarf_debug_ranges (".debug_ranges");
885             static ConstString g_sect_name_dwarf_debug_str (".debug_str");
886             static ConstString g_sect_name_eh_frame (".eh_frame");
887 
888             SectionType sect_type = eSectionTypeOther;
889 
890             bool is_thread_specific = false;
891 
892             if      (name == g_sect_name_text)                  sect_type = eSectionTypeCode;
893             else if (name == g_sect_name_data)                  sect_type = eSectionTypeData;
894             else if (name == g_sect_name_bss)                   sect_type = eSectionTypeZeroFill;
895             else if (name == g_sect_name_tdata)
896             {
897                 sect_type = eSectionTypeData;
898                 is_thread_specific = true;
899             }
900             else if (name == g_sect_name_tbss)
901             {
902                 sect_type = eSectionTypeZeroFill;
903                 is_thread_specific = true;
904             }
905             // .debug_abbrev – Abbreviations used in the .debug_info section
906             // .debug_aranges – Lookup table for mapping addresses to compilation units
907             // .debug_frame – Call frame information
908             // .debug_info – The core DWARF information section
909             // .debug_line – Line number information
910             // .debug_loc – Location lists used in DW_AT_location attributes
911             // .debug_macinfo – Macro information
912             // .debug_pubnames – Lookup table for mapping object and function names to compilation units
913             // .debug_pubtypes – Lookup table for mapping type names to compilation units
914             // .debug_ranges – Address ranges used in DW_AT_ranges attributes
915             // .debug_str – String table used in .debug_info
916             // MISSING? .gnu_debugdata - "mini debuginfo / MiniDebugInfo" section, http://sourceware.org/gdb/onlinedocs/gdb/MiniDebugInfo.html
917             // MISSING? .debug-index - http://src.chromium.org/viewvc/chrome/trunk/src/build/gdb-add-index?pathrev=144644
918             // MISSING? .debug_types - Type descriptions from DWARF 4? See http://gcc.gnu.org/wiki/DwarfSeparateTypeInfo
919             else if (name == g_sect_name_dwarf_debug_abbrev)    sect_type = eSectionTypeDWARFDebugAbbrev;
920             else if (name == g_sect_name_dwarf_debug_aranges)   sect_type = eSectionTypeDWARFDebugAranges;
921             else if (name == g_sect_name_dwarf_debug_frame)     sect_type = eSectionTypeDWARFDebugFrame;
922             else if (name == g_sect_name_dwarf_debug_info)      sect_type = eSectionTypeDWARFDebugInfo;
923             else if (name == g_sect_name_dwarf_debug_line)      sect_type = eSectionTypeDWARFDebugLine;
924             else if (name == g_sect_name_dwarf_debug_loc)       sect_type = eSectionTypeDWARFDebugLoc;
925             else if (name == g_sect_name_dwarf_debug_macinfo)   sect_type = eSectionTypeDWARFDebugMacInfo;
926             else if (name == g_sect_name_dwarf_debug_pubnames)  sect_type = eSectionTypeDWARFDebugPubNames;
927             else if (name == g_sect_name_dwarf_debug_pubtypes)  sect_type = eSectionTypeDWARFDebugPubTypes;
928             else if (name == g_sect_name_dwarf_debug_ranges)    sect_type = eSectionTypeDWARFDebugRanges;
929             else if (name == g_sect_name_dwarf_debug_str)       sect_type = eSectionTypeDWARFDebugStr;
930             else if (name == g_sect_name_eh_frame)              sect_type = eSectionTypeEHFrame;
931 
932             switch (header.sh_type)
933             {
934                 case SHT_SYMTAB:
935                     assert (sect_type == eSectionTypeOther);
936                     sect_type = eSectionTypeELFSymbolTable;
937                     break;
938                 case SHT_DYNSYM:
939                     assert (sect_type == eSectionTypeOther);
940                     sect_type = eSectionTypeELFDynamicSymbols;
941                     break;
942                 case SHT_RELA:
943                 case SHT_REL:
944                     assert (sect_type == eSectionTypeOther);
945                     sect_type = eSectionTypeELFRelocationEntries;
946                     break;
947                 case SHT_DYNAMIC:
948                     assert (sect_type == eSectionTypeOther);
949                     sect_type = eSectionTypeELFDynamicLinkInfo;
950                     break;
951             }
952 
953             SectionSP section_sp (new Section(GetModule(),        // Module to which this section belongs.
954                                               this,               // ObjectFile to which this section belongs and should read section data from.
955                                               SectionIndex(I),    // Section ID.
956                                               name,               // Section name.
957                                               sect_type,          // Section type.
958                                               header.sh_addr,     // VM address.
959                                               vm_size,            // VM size in bytes of this section.
960                                               header.sh_offset,   // Offset of this section in the file.
961                                               file_size,          // Size of the section as found in the file.
962                                               header.sh_flags));  // Flags for this section.
963 
964             if (is_thread_specific)
965                 section_sp->SetIsThreadSpecific (is_thread_specific);
966             m_sections_ap->AddSection(section_sp);
967         }
968     }
969 
970     if (m_sections_ap.get())
971     {
972         if (GetType() == eTypeDebugInfo)
973         {
974             static const SectionType g_sections[] =
975             {
976                 eSectionTypeDWARFDebugAranges,
977                 eSectionTypeDWARFDebugInfo,
978                 eSectionTypeDWARFDebugAbbrev,
979                 eSectionTypeDWARFDebugFrame,
980                 eSectionTypeDWARFDebugLine,
981                 eSectionTypeDWARFDebugStr,
982                 eSectionTypeDWARFDebugLoc,
983                 eSectionTypeDWARFDebugMacInfo,
984                 eSectionTypeDWARFDebugPubNames,
985                 eSectionTypeDWARFDebugPubTypes,
986                 eSectionTypeDWARFDebugRanges,
987                 eSectionTypeELFSymbolTable,
988             };
989             SectionList *elf_section_list = m_sections_ap.get();
990             for (size_t idx = 0; idx < sizeof(g_sections) / sizeof(g_sections[0]); ++idx)
991             {
992                 SectionType section_type = g_sections[idx];
993                 SectionSP section_sp (elf_section_list->FindSectionByType (section_type, true));
994                 if (section_sp)
995                 {
996                     SectionSP module_section_sp (unified_section_list.FindSectionByType (section_type, true));
997                     if (module_section_sp)
998                         unified_section_list.ReplaceSection (module_section_sp->GetID(), section_sp);
999                     else
1000                         unified_section_list.AddSection (section_sp);
1001                 }
1002             }
1003         }
1004         else
1005         {
1006             unified_section_list = *m_sections_ap;
1007         }
1008     }
1009 }
1010 
1011 // private
1012 unsigned
1013 ObjectFileELF::ParseSymbols (Symtab *symtab,
1014                              user_id_t start_id,
1015                              SectionList *section_list,
1016                              const size_t num_symbols,
1017                              const DataExtractor &symtab_data,
1018                              const DataExtractor &strtab_data)
1019 {
1020     ELFSymbol symbol;
1021     lldb::offset_t offset = 0;
1022 
1023     static ConstString text_section_name(".text");
1024     static ConstString init_section_name(".init");
1025     static ConstString fini_section_name(".fini");
1026     static ConstString ctors_section_name(".ctors");
1027     static ConstString dtors_section_name(".dtors");
1028 
1029     static ConstString data_section_name(".data");
1030     static ConstString rodata_section_name(".rodata");
1031     static ConstString rodata1_section_name(".rodata1");
1032     static ConstString data2_section_name(".data1");
1033     static ConstString bss_section_name(".bss");
1034 
1035     //StreamFile strm(stdout, false);
1036     unsigned i;
1037     for (i = 0; i < num_symbols; ++i)
1038     {
1039         if (symbol.Parse(symtab_data, &offset) == false)
1040             break;
1041 
1042         const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
1043 
1044         // No need to add symbols that have no names
1045         if (symbol_name == NULL || symbol_name[0] == '\0')
1046             continue;
1047 
1048         //symbol.Dump (&strm, i, &strtab_data, section_list);
1049 
1050         SectionSP symbol_section_sp;
1051         SymbolType symbol_type = eSymbolTypeInvalid;
1052         Elf64_Half symbol_idx = symbol.st_shndx;
1053 
1054         switch (symbol_idx)
1055         {
1056         case SHN_ABS:
1057             symbol_type = eSymbolTypeAbsolute;
1058             break;
1059         case SHN_UNDEF:
1060             symbol_type = eSymbolTypeUndefined;
1061             break;
1062         default:
1063             symbol_section_sp = section_list->GetSectionAtIndex(symbol_idx);
1064             break;
1065         }
1066 
1067         // If a symbol is undefined do not process it further even if it has a STT type
1068         if (symbol_type != eSymbolTypeUndefined)
1069         {
1070             switch (symbol.getType())
1071             {
1072             default:
1073             case STT_NOTYPE:
1074                 // The symbol's type is not specified.
1075                 break;
1076 
1077             case STT_OBJECT:
1078                 // The symbol is associated with a data object, such as a variable,
1079                 // an array, etc.
1080                 symbol_type = eSymbolTypeData;
1081                 break;
1082 
1083             case STT_FUNC:
1084                 // The symbol is associated with a function or other executable code.
1085                 symbol_type = eSymbolTypeCode;
1086                 break;
1087 
1088             case STT_SECTION:
1089                 // The symbol is associated with a section. Symbol table entries of
1090                 // this type exist primarily for relocation and normally have
1091                 // STB_LOCAL binding.
1092                 break;
1093 
1094             case STT_FILE:
1095                 // Conventionally, the symbol's name gives the name of the source
1096                 // file associated with the object file. A file symbol has STB_LOCAL
1097                 // binding, its section index is SHN_ABS, and it precedes the other
1098                 // STB_LOCAL symbols for the file, if it is present.
1099                 symbol_type = eSymbolTypeSourceFile;
1100                 break;
1101 
1102             case STT_GNU_IFUNC:
1103                 // The symbol is associated with an indirect function. The actual
1104                 // function will be resolved if it is referenced.
1105                 symbol_type = eSymbolTypeResolver;
1106                 break;
1107             }
1108         }
1109 
1110         if (symbol_type == eSymbolTypeInvalid)
1111         {
1112             if (symbol_section_sp)
1113             {
1114                 const ConstString &sect_name = symbol_section_sp->GetName();
1115                 if (sect_name == text_section_name ||
1116                     sect_name == init_section_name ||
1117                     sect_name == fini_section_name ||
1118                     sect_name == ctors_section_name ||
1119                     sect_name == dtors_section_name)
1120                 {
1121                     symbol_type = eSymbolTypeCode;
1122                 }
1123                 else if (sect_name == data_section_name ||
1124                          sect_name == data2_section_name ||
1125                          sect_name == rodata_section_name ||
1126                          sect_name == rodata1_section_name ||
1127                          sect_name == bss_section_name)
1128                 {
1129                     symbol_type = eSymbolTypeData;
1130                 }
1131             }
1132         }
1133 
1134         // If the symbol section we've found has no data (SHT_NOBITS), then check the module section
1135         // list. This can happen if we're parsing the debug file and it has no .text section, for example.
1136         if (symbol_section_sp && (symbol_section_sp->GetFileSize() == 0))
1137         {
1138             ModuleSP module_sp(GetModule());
1139             if (module_sp)
1140             {
1141                 SectionList *module_section_list = module_sp->GetSectionList();
1142                 if (module_section_list && module_section_list != section_list)
1143                 {
1144                     const ConstString &sect_name = symbol_section_sp->GetName();
1145                     lldb::SectionSP section_sp (module_section_list->FindSectionByName (sect_name));
1146                     if (section_sp && section_sp->GetFileSize())
1147                     {
1148                         symbol_section_sp = section_sp;
1149                     }
1150                 }
1151             }
1152         }
1153 
1154         uint64_t symbol_value = symbol.st_value;
1155         if (symbol_section_sp)
1156             symbol_value -= symbol_section_sp->GetFileAddress();
1157         bool is_global = symbol.getBinding() == STB_GLOBAL;
1158         uint32_t flags = symbol.st_other << 8 | symbol.st_info;
1159         bool is_mangled = symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
1160         Symbol dc_symbol(
1161             i + start_id,       // ID is the original symbol table index.
1162             symbol_name,        // Symbol name.
1163             is_mangled,         // Is the symbol name mangled?
1164             symbol_type,        // Type of this symbol
1165             is_global,          // Is this globally visible?
1166             false,              // Is this symbol debug info?
1167             false,              // Is this symbol a trampoline?
1168             false,              // Is this symbol artificial?
1169             symbol_section_sp,  // Section in which this symbol is defined or null.
1170             symbol_value,       // Offset in section or symbol value.
1171             symbol.st_size,     // Size in bytes of this symbol.
1172             true,               // Size is valid
1173             flags);             // Symbol flags.
1174         symtab->AddSymbol(dc_symbol);
1175     }
1176 
1177     return i;
1178 }
1179 
1180 unsigned
1181 ObjectFileELF::ParseSymbolTable(Symtab *symbol_table, user_id_t start_id, lldb_private::Section *symtab)
1182 {
1183     if (symtab->GetObjectFile() != this)
1184     {
1185         // If the symbol table section is owned by a different object file, have it do the
1186         // parsing.
1187         ObjectFileELF *obj_file_elf = static_cast<ObjectFileELF *>(symtab->GetObjectFile());
1188         return obj_file_elf->ParseSymbolTable (symbol_table, start_id, symtab);
1189     }
1190 
1191     // Get section list for this object file.
1192     SectionList *section_list = m_sections_ap.get();
1193     if (!section_list)
1194         return 0;
1195 
1196     user_id_t symtab_id = symtab->GetID();
1197     const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
1198     assert(symtab_hdr->sh_type == SHT_SYMTAB ||
1199            symtab_hdr->sh_type == SHT_DYNSYM);
1200 
1201     // sh_link: section header index of associated string table.
1202     // Section ID's are ones based.
1203     user_id_t strtab_id = symtab_hdr->sh_link + 1;
1204     Section *strtab = section_list->FindSectionByID(strtab_id).get();
1205 
1206     unsigned num_symbols = 0;
1207     if (symtab && strtab)
1208     {
1209         assert (symtab->GetObjectFile() == this);
1210         assert (strtab->GetObjectFile() == this);
1211 
1212         DataExtractor symtab_data;
1213         DataExtractor strtab_data;
1214         if (ReadSectionData(symtab, symtab_data) &&
1215             ReadSectionData(strtab, strtab_data))
1216         {
1217             size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
1218 
1219             num_symbols = ParseSymbols(symbol_table, start_id,
1220                                        section_list, num_symbols,
1221                                        symtab_data, strtab_data);
1222         }
1223     }
1224 
1225     return num_symbols;
1226 }
1227 
1228 size_t
1229 ObjectFileELF::ParseDynamicSymbols()
1230 {
1231     if (m_dynamic_symbols.size())
1232         return m_dynamic_symbols.size();
1233 
1234     SectionList *section_list = GetSectionList();
1235     if (!section_list)
1236         return 0;
1237 
1238     // Find the SHT_DYNAMIC section.
1239     Section *dynsym = section_list->FindSectionByType (eSectionTypeELFDynamicLinkInfo, true).get();
1240     if (!dynsym)
1241         return 0;
1242     assert (dynsym->GetObjectFile() == this);
1243 
1244     ELFDynamic symbol;
1245     DataExtractor dynsym_data;
1246     if (ReadSectionData(dynsym, dynsym_data))
1247     {
1248         const lldb::offset_t section_size = dynsym_data.GetByteSize();
1249         lldb::offset_t cursor = 0;
1250 
1251         while (cursor < section_size)
1252         {
1253             if (!symbol.Parse(dynsym_data, &cursor))
1254                 break;
1255 
1256             m_dynamic_symbols.push_back(symbol);
1257         }
1258     }
1259 
1260     return m_dynamic_symbols.size();
1261 }
1262 
1263 const ELFDynamic *
1264 ObjectFileELF::FindDynamicSymbol(unsigned tag)
1265 {
1266     if (!ParseDynamicSymbols())
1267         return NULL;
1268 
1269     DynamicSymbolCollIter I = m_dynamic_symbols.begin();
1270     DynamicSymbolCollIter E = m_dynamic_symbols.end();
1271     for ( ; I != E; ++I)
1272     {
1273         ELFDynamic *symbol = &*I;
1274 
1275         if (symbol->d_tag == tag)
1276             return symbol;
1277     }
1278 
1279     return NULL;
1280 }
1281 
1282 unsigned
1283 ObjectFileELF::PLTRelocationType()
1284 {
1285     // DT_PLTREL
1286     //  This member specifies the type of relocation entry to which the
1287     //  procedure linkage table refers. The d_val member holds DT_REL or
1288     //  DT_RELA, as appropriate. All relocations in a procedure linkage table
1289     //  must use the same relocation.
1290     const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
1291 
1292     if (symbol)
1293         return symbol->d_val;
1294 
1295     return 0;
1296 }
1297 
1298 static unsigned
1299 ParsePLTRelocations(Symtab *symbol_table,
1300                     user_id_t start_id,
1301                     unsigned rel_type,
1302                     const ELFHeader *hdr,
1303                     const ELFSectionHeader *rel_hdr,
1304                     const ELFSectionHeader *plt_hdr,
1305                     const ELFSectionHeader *sym_hdr,
1306                     const lldb::SectionSP &plt_section_sp,
1307                     DataExtractor &rel_data,
1308                     DataExtractor &symtab_data,
1309                     DataExtractor &strtab_data)
1310 {
1311     ELFRelocation rel(rel_type);
1312     ELFSymbol symbol;
1313     lldb::offset_t offset = 0;
1314     // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are 16 bytes.
1315     // So round the entsize up by the alignment if addralign is set.
1316     const elf_xword plt_entsize = plt_hdr->sh_addralign ?
1317         llvm::RoundUpToAlignment (plt_hdr->sh_entsize, plt_hdr->sh_addralign) : plt_hdr->sh_entsize;
1318     const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
1319 
1320     typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
1321     reloc_info_fn reloc_type;
1322     reloc_info_fn reloc_symbol;
1323 
1324     if (hdr->Is32Bit())
1325     {
1326         reloc_type = ELFRelocation::RelocType32;
1327         reloc_symbol = ELFRelocation::RelocSymbol32;
1328     }
1329     else
1330     {
1331         reloc_type = ELFRelocation::RelocType64;
1332         reloc_symbol = ELFRelocation::RelocSymbol64;
1333     }
1334 
1335     unsigned slot_type = hdr->GetRelocationJumpSlotType();
1336     unsigned i;
1337     for (i = 0; i < num_relocations; ++i)
1338     {
1339         if (rel.Parse(rel_data, &offset) == false)
1340             break;
1341 
1342         if (reloc_type(rel) != slot_type)
1343             continue;
1344 
1345         lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
1346         uint64_t plt_index = (i + 1) * plt_entsize;
1347 
1348         if (!symbol.Parse(symtab_data, &symbol_offset))
1349             break;
1350 
1351         const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
1352         bool is_mangled = symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
1353 
1354         Symbol jump_symbol(
1355             i + start_id,    // Symbol table index
1356             symbol_name,     // symbol name.
1357             is_mangled,      // is the symbol name mangled?
1358             eSymbolTypeTrampoline, // Type of this symbol
1359             false,           // Is this globally visible?
1360             false,           // Is this symbol debug info?
1361             true,            // Is this symbol a trampoline?
1362             true,            // Is this symbol artificial?
1363             plt_section_sp,  // Section in which this symbol is defined or null.
1364             plt_index,       // Offset in section or symbol value.
1365             plt_entsize,     // Size in bytes of this symbol.
1366             true,            // Size is valid
1367             0);              // Symbol flags.
1368 
1369         symbol_table->AddSymbol(jump_symbol);
1370     }
1371 
1372     return i;
1373 }
1374 
1375 unsigned
1376 ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table,
1377                                       user_id_t start_id,
1378                                       const ELFSectionHeaderInfo *rel_hdr,
1379                                       user_id_t rel_id)
1380 {
1381     assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
1382 
1383     // The link field points to the associated symbol table. The info field
1384     // points to the section holding the plt.
1385     user_id_t symtab_id = rel_hdr->sh_link;
1386     user_id_t plt_id = rel_hdr->sh_info;
1387 
1388     if (!symtab_id || !plt_id)
1389         return 0;
1390 
1391     // Section ID's are ones based;
1392     symtab_id++;
1393     plt_id++;
1394 
1395     const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
1396     if (!plt_hdr)
1397         return 0;
1398 
1399     const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
1400     if (!sym_hdr)
1401         return 0;
1402 
1403     SectionList *section_list = m_sections_ap.get();
1404     if (!section_list)
1405         return 0;
1406 
1407     Section *rel_section = section_list->FindSectionByID(rel_id).get();
1408     if (!rel_section)
1409         return 0;
1410 
1411     SectionSP plt_section_sp (section_list->FindSectionByID(plt_id));
1412     if (!plt_section_sp)
1413         return 0;
1414 
1415     Section *symtab = section_list->FindSectionByID(symtab_id).get();
1416     if (!symtab)
1417         return 0;
1418 
1419     // sh_link points to associated string table.
1420     Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link + 1).get();
1421     if (!strtab)
1422         return 0;
1423 
1424     DataExtractor rel_data;
1425     if (!ReadSectionData(rel_section, rel_data))
1426         return 0;
1427 
1428     DataExtractor symtab_data;
1429     if (!ReadSectionData(symtab, symtab_data))
1430         return 0;
1431 
1432     DataExtractor strtab_data;
1433     if (!ReadSectionData(strtab, strtab_data))
1434         return 0;
1435 
1436     unsigned rel_type = PLTRelocationType();
1437     if (!rel_type)
1438         return 0;
1439 
1440     return ParsePLTRelocations (symbol_table,
1441                                 start_id,
1442                                 rel_type,
1443                                 &m_header,
1444                                 rel_hdr,
1445                                 plt_hdr,
1446                                 sym_hdr,
1447                                 plt_section_sp,
1448                                 rel_data,
1449                                 symtab_data,
1450                                 strtab_data);
1451 }
1452 
1453 Symtab *
1454 ObjectFileELF::GetSymtab()
1455 {
1456     ModuleSP module_sp(GetModule());
1457     if (!module_sp)
1458         return NULL;
1459 
1460     // We always want to use the main object file so we (hopefully) only have one cached copy
1461     // of our symtab, dynamic sections, etc.
1462     ObjectFile *module_obj_file = module_sp->GetObjectFile();
1463     if (module_obj_file && module_obj_file != this)
1464         return module_obj_file->GetSymtab();
1465 
1466     if (m_symtab_ap.get() == NULL)
1467     {
1468         SectionList *section_list = GetSectionList();
1469         if (!section_list)
1470             return NULL;
1471 
1472         uint64_t symbol_id = 0;
1473         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
1474 
1475         m_symtab_ap.reset(new Symtab(this));
1476 
1477         // Sharable objects and dynamic executables usually have 2 distinct symbol
1478         // tables, one named ".symtab", and the other ".dynsym". The dynsym is a smaller
1479         // version of the symtab that only contains global symbols. The information found
1480         // in the dynsym is therefore also found in the symtab, while the reverse is not
1481         // necessarily true.
1482         Section *symtab = section_list->FindSectionByType (eSectionTypeELFSymbolTable, true).get();
1483         if (!symtab)
1484         {
1485             // The symtab section is non-allocable and can be stripped, so if it doesn't exist
1486             // then use the dynsym section which should always be there.
1487             symtab = section_list->FindSectionByType (eSectionTypeELFDynamicSymbols, true).get();
1488         }
1489         if (symtab)
1490             symbol_id += ParseSymbolTable (m_symtab_ap.get(), symbol_id, symtab);
1491 
1492         // DT_JMPREL
1493         //      If present, this entry's d_ptr member holds the address of relocation
1494         //      entries associated solely with the procedure linkage table. Separating
1495         //      these relocation entries lets the dynamic linker ignore them during
1496         //      process initialization, if lazy binding is enabled. If this entry is
1497         //      present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
1498         //      also be present.
1499         const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
1500         if (symbol)
1501         {
1502             // Synthesize trampoline symbols to help navigate the PLT.
1503             addr_t addr = symbol->d_ptr;
1504             Section *reloc_section = section_list->FindSectionContainingFileAddress(addr).get();
1505             if (reloc_section)
1506             {
1507                 user_id_t reloc_id = reloc_section->GetID();
1508                 const ELFSectionHeaderInfo *reloc_header = GetSectionHeaderByIndex(reloc_id);
1509                 assert(reloc_header);
1510 
1511                 ParseTrampolineSymbols (m_symtab_ap.get(), symbol_id, reloc_header, reloc_id);
1512             }
1513         }
1514     }
1515     return m_symtab_ap.get();
1516 }
1517 
1518 Symbol *
1519 ObjectFileELF::ResolveSymbolForAddress(const Address& so_addr, bool verify_unique)
1520 {
1521     if (!m_symtab_ap.get())
1522         return nullptr; // GetSymtab() should be called first.
1523 
1524     const SectionList *section_list = GetSectionList();
1525     if (!section_list)
1526         return nullptr;
1527 
1528     if (DWARFCallFrameInfo *eh_frame = GetUnwindTable().GetEHFrameInfo())
1529     {
1530         AddressRange range;
1531         if (eh_frame->GetAddressRange (so_addr, range))
1532         {
1533             const addr_t file_addr = range.GetBaseAddress().GetFileAddress();
1534             Symbol * symbol = verify_unique ? m_symtab_ap->FindSymbolContainingFileAddress(file_addr) : nullptr;
1535             if (symbol)
1536                 return symbol;
1537 
1538             // Note that a (stripped) symbol won't be found by GetSymtab()...
1539             lldb::SectionSP eh_sym_section_sp = section_list->FindSectionContainingFileAddress(file_addr);
1540             if (eh_sym_section_sp.get())
1541             {
1542                 addr_t section_base = eh_sym_section_sp->GetFileAddress();
1543                 addr_t offset = file_addr - section_base;
1544                 uint64_t symbol_id = m_symtab_ap->GetNumSymbols();
1545 
1546                 Symbol eh_symbol(
1547                         symbol_id,            // Symbol table index.
1548                         "???",                // Symbol name.
1549                         false,                // Is the symbol name mangled?
1550                         eSymbolTypeCode,      // Type of this symbol.
1551                         true,                 // Is this globally visible?
1552                         false,                // Is this symbol debug info?
1553                         false,                // Is this symbol a trampoline?
1554                         true,                 // Is this symbol artificial?
1555                         eh_sym_section_sp,    // Section in which this symbol is defined or null.
1556                         offset,               // Offset in section or symbol value.
1557                         range.GetByteSize(),  // Size in bytes of this symbol.
1558                         true,                 // Size is valid.
1559                         0);                   // Symbol flags.
1560                 if (symbol_id == m_symtab_ap->AddSymbol(eh_symbol))
1561                     return m_symtab_ap->SymbolAtIndex(symbol_id);
1562             }
1563         }
1564     }
1565     return nullptr;
1566 }
1567 
1568 
1569 bool
1570 ObjectFileELF::IsStripped ()
1571 {
1572     // TODO: determine this for ELF
1573     return false;
1574 }
1575 
1576 //===----------------------------------------------------------------------===//
1577 // Dump
1578 //
1579 // Dump the specifics of the runtime file container (such as any headers
1580 // segments, sections, etc).
1581 //----------------------------------------------------------------------
1582 void
1583 ObjectFileELF::Dump(Stream *s)
1584 {
1585     DumpELFHeader(s, m_header);
1586     s->EOL();
1587     DumpELFProgramHeaders(s);
1588     s->EOL();
1589     DumpELFSectionHeaders(s);
1590     s->EOL();
1591     SectionList *section_list = GetSectionList();
1592     if (section_list)
1593         section_list->Dump(s, NULL, true, UINT32_MAX);
1594     Symtab *symtab = GetSymtab();
1595     if (symtab)
1596         symtab->Dump(s, NULL, eSortOrderNone);
1597     s->EOL();
1598     DumpDependentModules(s);
1599     s->EOL();
1600 }
1601 
1602 //----------------------------------------------------------------------
1603 // DumpELFHeader
1604 //
1605 // Dump the ELF header to the specified output stream
1606 //----------------------------------------------------------------------
1607 void
1608 ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header)
1609 {
1610     s->PutCString("ELF Header\n");
1611     s->Printf("e_ident[EI_MAG0   ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
1612     s->Printf("e_ident[EI_MAG1   ] = 0x%2.2x '%c'\n",
1613               header.e_ident[EI_MAG1], header.e_ident[EI_MAG1]);
1614     s->Printf("e_ident[EI_MAG2   ] = 0x%2.2x '%c'\n",
1615               header.e_ident[EI_MAG2], header.e_ident[EI_MAG2]);
1616     s->Printf("e_ident[EI_MAG3   ] = 0x%2.2x '%c'\n",
1617               header.e_ident[EI_MAG3], header.e_ident[EI_MAG3]);
1618 
1619     s->Printf("e_ident[EI_CLASS  ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
1620     s->Printf("e_ident[EI_DATA   ] = 0x%2.2x ", header.e_ident[EI_DATA]);
1621     DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
1622     s->Printf ("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
1623     s->Printf ("e_ident[EI_PAD    ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
1624 
1625     s->Printf("e_type      = 0x%4.4x ", header.e_type);
1626     DumpELFHeader_e_type(s, header.e_type);
1627     s->Printf("\ne_machine   = 0x%4.4x\n", header.e_machine);
1628     s->Printf("e_version   = 0x%8.8x\n", header.e_version);
1629     s->Printf("e_entry     = 0x%8.8" PRIx64 "\n", header.e_entry);
1630     s->Printf("e_phoff     = 0x%8.8" PRIx64 "\n", header.e_phoff);
1631     s->Printf("e_shoff     = 0x%8.8" PRIx64 "\n", header.e_shoff);
1632     s->Printf("e_flags     = 0x%8.8x\n", header.e_flags);
1633     s->Printf("e_ehsize    = 0x%4.4x\n", header.e_ehsize);
1634     s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
1635     s->Printf("e_phnum     = 0x%4.4x\n", header.e_phnum);
1636     s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
1637     s->Printf("e_shnum     = 0x%4.4x\n", header.e_shnum);
1638     s->Printf("e_shstrndx  = 0x%4.4x\n", header.e_shstrndx);
1639 }
1640 
1641 //----------------------------------------------------------------------
1642 // DumpELFHeader_e_type
1643 //
1644 // Dump an token value for the ELF header member e_type
1645 //----------------------------------------------------------------------
1646 void
1647 ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type)
1648 {
1649     switch (e_type)
1650     {
1651     case ET_NONE:   *s << "ET_NONE"; break;
1652     case ET_REL:    *s << "ET_REL"; break;
1653     case ET_EXEC:   *s << "ET_EXEC"; break;
1654     case ET_DYN:    *s << "ET_DYN"; break;
1655     case ET_CORE:   *s << "ET_CORE"; break;
1656     default:
1657         break;
1658     }
1659 }
1660 
1661 //----------------------------------------------------------------------
1662 // DumpELFHeader_e_ident_EI_DATA
1663 //
1664 // Dump an token value for the ELF header member e_ident[EI_DATA]
1665 //----------------------------------------------------------------------
1666 void
1667 ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s, unsigned char ei_data)
1668 {
1669     switch (ei_data)
1670     {
1671     case ELFDATANONE:   *s << "ELFDATANONE"; break;
1672     case ELFDATA2LSB:   *s << "ELFDATA2LSB - Little Endian"; break;
1673     case ELFDATA2MSB:   *s << "ELFDATA2MSB - Big Endian"; break;
1674     default:
1675         break;
1676     }
1677 }
1678 
1679 
1680 //----------------------------------------------------------------------
1681 // DumpELFProgramHeader
1682 //
1683 // Dump a single ELF program header to the specified output stream
1684 //----------------------------------------------------------------------
1685 void
1686 ObjectFileELF::DumpELFProgramHeader(Stream *s, const ELFProgramHeader &ph)
1687 {
1688     DumpELFProgramHeader_p_type(s, ph.p_type);
1689     s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset, ph.p_vaddr, ph.p_paddr);
1690     s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz, ph.p_flags);
1691 
1692     DumpELFProgramHeader_p_flags(s, ph.p_flags);
1693     s->Printf(") %8.8" PRIx64, ph.p_align);
1694 }
1695 
1696 //----------------------------------------------------------------------
1697 // DumpELFProgramHeader_p_type
1698 //
1699 // Dump an token value for the ELF program header member p_type which
1700 // describes the type of the program header
1701 // ----------------------------------------------------------------------
1702 void
1703 ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type)
1704 {
1705     const int kStrWidth = 15;
1706     switch (p_type)
1707     {
1708     CASE_AND_STREAM(s, PT_NULL        , kStrWidth);
1709     CASE_AND_STREAM(s, PT_LOAD        , kStrWidth);
1710     CASE_AND_STREAM(s, PT_DYNAMIC     , kStrWidth);
1711     CASE_AND_STREAM(s, PT_INTERP      , kStrWidth);
1712     CASE_AND_STREAM(s, PT_NOTE        , kStrWidth);
1713     CASE_AND_STREAM(s, PT_SHLIB       , kStrWidth);
1714     CASE_AND_STREAM(s, PT_PHDR        , kStrWidth);
1715     CASE_AND_STREAM(s, PT_TLS         , kStrWidth);
1716     CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
1717     default:
1718         s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
1719         break;
1720     }
1721 }
1722 
1723 
1724 //----------------------------------------------------------------------
1725 // DumpELFProgramHeader_p_flags
1726 //
1727 // Dump an token value for the ELF program header member p_flags
1728 //----------------------------------------------------------------------
1729 void
1730 ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags)
1731 {
1732     *s  << ((p_flags & PF_X) ? "PF_X" : "    ")
1733         << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
1734         << ((p_flags & PF_W) ? "PF_W" : "    ")
1735         << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
1736         << ((p_flags & PF_R) ? "PF_R" : "    ");
1737 }
1738 
1739 //----------------------------------------------------------------------
1740 // DumpELFProgramHeaders
1741 //
1742 // Dump all of the ELF program header to the specified output stream
1743 //----------------------------------------------------------------------
1744 void
1745 ObjectFileELF::DumpELFProgramHeaders(Stream *s)
1746 {
1747     if (ParseProgramHeaders())
1748     {
1749         s->PutCString("Program Headers\n");
1750         s->PutCString("IDX  p_type          p_offset p_vaddr  p_paddr  "
1751                       "p_filesz p_memsz  p_flags                   p_align\n");
1752         s->PutCString("==== --------------- -------- -------- -------- "
1753                       "-------- -------- ------------------------- --------\n");
1754 
1755         uint32_t idx = 0;
1756         for (ProgramHeaderCollConstIter I = m_program_headers.begin();
1757              I != m_program_headers.end(); ++I, ++idx)
1758         {
1759             s->Printf("[%2u] ", idx);
1760             ObjectFileELF::DumpELFProgramHeader(s, *I);
1761             s->EOL();
1762         }
1763     }
1764 }
1765 
1766 //----------------------------------------------------------------------
1767 // DumpELFSectionHeader
1768 //
1769 // Dump a single ELF section header to the specified output stream
1770 //----------------------------------------------------------------------
1771 void
1772 ObjectFileELF::DumpELFSectionHeader(Stream *s, const ELFSectionHeaderInfo &sh)
1773 {
1774     s->Printf("%8.8x ", sh.sh_name);
1775     DumpELFSectionHeader_sh_type(s, sh.sh_type);
1776     s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
1777     DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
1778     s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr, sh.sh_offset, sh.sh_size);
1779     s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
1780     s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
1781 }
1782 
1783 //----------------------------------------------------------------------
1784 // DumpELFSectionHeader_sh_type
1785 //
1786 // Dump an token value for the ELF section header member sh_type which
1787 // describes the type of the section
1788 //----------------------------------------------------------------------
1789 void
1790 ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type)
1791 {
1792     const int kStrWidth = 12;
1793     switch (sh_type)
1794     {
1795     CASE_AND_STREAM(s, SHT_NULL     , kStrWidth);
1796     CASE_AND_STREAM(s, SHT_PROGBITS , kStrWidth);
1797     CASE_AND_STREAM(s, SHT_SYMTAB   , kStrWidth);
1798     CASE_AND_STREAM(s, SHT_STRTAB   , kStrWidth);
1799     CASE_AND_STREAM(s, SHT_RELA     , kStrWidth);
1800     CASE_AND_STREAM(s, SHT_HASH     , kStrWidth);
1801     CASE_AND_STREAM(s, SHT_DYNAMIC  , kStrWidth);
1802     CASE_AND_STREAM(s, SHT_NOTE     , kStrWidth);
1803     CASE_AND_STREAM(s, SHT_NOBITS   , kStrWidth);
1804     CASE_AND_STREAM(s, SHT_REL      , kStrWidth);
1805     CASE_AND_STREAM(s, SHT_SHLIB    , kStrWidth);
1806     CASE_AND_STREAM(s, SHT_DYNSYM   , kStrWidth);
1807     CASE_AND_STREAM(s, SHT_LOPROC   , kStrWidth);
1808     CASE_AND_STREAM(s, SHT_HIPROC   , kStrWidth);
1809     CASE_AND_STREAM(s, SHT_LOUSER   , kStrWidth);
1810     CASE_AND_STREAM(s, SHT_HIUSER   , kStrWidth);
1811     default:
1812         s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
1813         break;
1814     }
1815 }
1816 
1817 //----------------------------------------------------------------------
1818 // DumpELFSectionHeader_sh_flags
1819 //
1820 // Dump an token value for the ELF section header member sh_flags
1821 //----------------------------------------------------------------------
1822 void
1823 ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s, elf_xword sh_flags)
1824 {
1825     *s  << ((sh_flags & SHF_WRITE) ? "WRITE" : "     ")
1826         << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
1827         << ((sh_flags & SHF_ALLOC) ? "ALLOC" : "     ")
1828         << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
1829         << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : "         ");
1830 }
1831 
1832 //----------------------------------------------------------------------
1833 // DumpELFSectionHeaders
1834 //
1835 // Dump all of the ELF section header to the specified output stream
1836 //----------------------------------------------------------------------
1837 void
1838 ObjectFileELF::DumpELFSectionHeaders(Stream *s)
1839 {
1840     if (!ParseSectionHeaders())
1841         return;
1842 
1843     s->PutCString("Section Headers\n");
1844     s->PutCString("IDX  name     type         flags                            "
1845                   "addr     offset   size     link     info     addralgn "
1846                   "entsize  Name\n");
1847     s->PutCString("==== -------- ------------ -------------------------------- "
1848                   "-------- -------- -------- -------- -------- -------- "
1849                   "-------- ====================\n");
1850 
1851     uint32_t idx = 0;
1852     for (SectionHeaderCollConstIter I = m_section_headers.begin();
1853          I != m_section_headers.end(); ++I, ++idx)
1854     {
1855         s->Printf("[%2u] ", idx);
1856         ObjectFileELF::DumpELFSectionHeader(s, *I);
1857         const char* section_name = I->section_name.AsCString("");
1858         if (section_name)
1859             *s << ' ' << section_name << "\n";
1860     }
1861 }
1862 
1863 void
1864 ObjectFileELF::DumpDependentModules(lldb_private::Stream *s)
1865 {
1866     size_t num_modules = ParseDependentModules();
1867 
1868     if (num_modules > 0)
1869     {
1870         s->PutCString("Dependent Modules:\n");
1871         for (unsigned i = 0; i < num_modules; ++i)
1872         {
1873             const FileSpec &spec = m_filespec_ap->GetFileSpecAtIndex(i);
1874             s->Printf("   %s\n", spec.GetFilename().GetCString());
1875         }
1876     }
1877 }
1878 
1879 bool
1880 ObjectFileELF::GetArchitecture (ArchSpec &arch)
1881 {
1882     if (!ParseHeader())
1883         return false;
1884 
1885     arch.SetArchitecture (eArchTypeELF, m_header.e_machine, LLDB_INVALID_CPUTYPE);
1886     arch.GetTriple().setOSName (Host::GetOSString().GetCString());
1887     arch.GetTriple().setVendorName(Host::GetVendorString().GetCString());
1888     return true;
1889 }
1890 
1891 ObjectFile::Type
1892 ObjectFileELF::CalculateType()
1893 {
1894     switch (m_header.e_type)
1895     {
1896         case llvm::ELF::ET_NONE:
1897             // 0 - No file type
1898             return eTypeUnknown;
1899 
1900         case llvm::ELF::ET_REL:
1901             // 1 - Relocatable file
1902             return eTypeObjectFile;
1903 
1904         case llvm::ELF::ET_EXEC:
1905             // 2 - Executable file
1906             return eTypeExecutable;
1907 
1908         case llvm::ELF::ET_DYN:
1909             // 3 - Shared object file
1910             return eTypeSharedLibrary;
1911 
1912         case ET_CORE:
1913             // 4 - Core file
1914             return eTypeCoreFile;
1915 
1916         default:
1917             break;
1918     }
1919     return eTypeUnknown;
1920 }
1921 
1922 ObjectFile::Strata
1923 ObjectFileELF::CalculateStrata()
1924 {
1925     switch (m_header.e_type)
1926     {
1927         case llvm::ELF::ET_NONE:
1928             // 0 - No file type
1929             return eStrataUnknown;
1930 
1931         case llvm::ELF::ET_REL:
1932             // 1 - Relocatable file
1933             return eStrataUnknown;
1934 
1935         case llvm::ELF::ET_EXEC:
1936             // 2 - Executable file
1937             // TODO: is there any way to detect that an executable is a kernel
1938             // related executable by inspecting the program headers, section
1939             // headers, symbols, or any other flag bits???
1940             return eStrataUser;
1941 
1942         case llvm::ELF::ET_DYN:
1943             // 3 - Shared object file
1944             // TODO: is there any way to detect that an shared library is a kernel
1945             // related executable by inspecting the program headers, section
1946             // headers, symbols, or any other flag bits???
1947             return eStrataUnknown;
1948 
1949         case ET_CORE:
1950             // 4 - Core file
1951             // TODO: is there any way to detect that an core file is a kernel
1952             // related executable by inspecting the program headers, section
1953             // headers, symbols, or any other flag bits???
1954             return eStrataUnknown;
1955 
1956         default:
1957             break;
1958     }
1959     return eStrataUnknown;
1960 }
1961 
1962