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