xref: /llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp (revision 35729bb1f8250df77c8b2d4025fa87d4db777b3b)
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()
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)
543         {
544             // Compute the offset as the number of previous entries plus the
545             // size of d_tag.
546             addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
547             return Address(dynsym_section_sp, offset);
548         }
549     }
550 
551     return Address();
552 }
553 
554 lldb_private::Address
555 ObjectFileELF::GetEntryPointAddress ()
556 {
557     if (m_entry_point_address.IsValid())
558         return m_entry_point_address;
559 
560     if (!ParseHeader() || !IsExecutable())
561         return m_entry_point_address;
562 
563     SectionList *section_list = GetSectionList();
564     addr_t offset = m_header.e_entry;
565 
566     if (!section_list)
567         m_entry_point_address.SetOffset(offset);
568     else
569         m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
570     return m_entry_point_address;
571 }
572 
573 //----------------------------------------------------------------------
574 // ParseDependentModules
575 //----------------------------------------------------------------------
576 size_t
577 ObjectFileELF::ParseDependentModules()
578 {
579     if (m_filespec_ap.get())
580         return m_filespec_ap->GetSize();
581 
582     m_filespec_ap.reset(new FileSpecList());
583 
584     if (!ParseSectionHeaders())
585         return 0;
586 
587     SectionList *section_list = GetSectionList();
588     if (!section_list)
589         return 0;
590 
591     // Find the SHT_DYNAMIC section.
592     Section *dynsym = section_list->FindSectionByType (eSectionTypeELFDynamicLinkInfo, true).get();
593     if (!dynsym)
594         return 0;
595     assert (dynsym->GetObjectFile() == this);
596 
597     const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex (dynsym->GetID());
598     if (!header)
599         return 0;
600     // sh_link: section header index of string table used by entries in the section.
601     Section *dynstr = section_list->FindSectionByID (header->sh_link + 1).get();
602     if (!dynstr)
603         return 0;
604 
605     DataExtractor dynsym_data;
606     DataExtractor dynstr_data;
607     if (ReadSectionData(dynsym, dynsym_data) &&
608         ReadSectionData(dynstr, dynstr_data))
609     {
610         ELFDynamic symbol;
611         const lldb::offset_t section_size = dynsym_data.GetByteSize();
612         lldb::offset_t offset = 0;
613 
614         // The only type of entries we are concerned with are tagged DT_NEEDED,
615         // yielding the name of a required library.
616         while (offset < section_size)
617         {
618             if (!symbol.Parse(dynsym_data, &offset))
619                 break;
620 
621             if (symbol.d_tag != DT_NEEDED)
622                 continue;
623 
624             uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
625             const char *lib_name = dynstr_data.PeekCStr(str_index);
626             m_filespec_ap->Append(FileSpec(lib_name, true));
627         }
628     }
629 
630     return m_filespec_ap->GetSize();
631 }
632 
633 //----------------------------------------------------------------------
634 // ParseProgramHeaders
635 //----------------------------------------------------------------------
636 size_t
637 ObjectFileELF::ParseProgramHeaders()
638 {
639     // We have already parsed the program headers
640     if (!m_program_headers.empty())
641         return m_program_headers.size();
642 
643     // If there are no program headers to read we are done.
644     if (m_header.e_phnum == 0)
645         return 0;
646 
647     m_program_headers.resize(m_header.e_phnum);
648     if (m_program_headers.size() != m_header.e_phnum)
649         return 0;
650 
651     const size_t ph_size = m_header.e_phnum * m_header.e_phentsize;
652     const elf_off ph_offset = m_header.e_phoff;
653     DataExtractor data;
654     if (GetData (ph_offset, ph_size, data) != ph_size)
655         return 0;
656 
657     uint32_t idx;
658     lldb::offset_t offset;
659     for (idx = 0, offset = 0; idx < m_header.e_phnum; ++idx)
660     {
661         if (m_program_headers[idx].Parse(data, &offset) == false)
662             break;
663     }
664 
665     if (idx < m_program_headers.size())
666         m_program_headers.resize(idx);
667 
668     return m_program_headers.size();
669 }
670 
671 static bool
672 ParseNoteGNUBuildID(DataExtractor &data, lldb_private::UUID &uuid)
673 {
674     // Try to parse the note section (ie .note.gnu.build-id|.notes|.note|...) and get the build id.
675     // BuildID documentation: https://fedoraproject.org/wiki/Releases/FeatureBuildId
676     struct
677     {
678         uint32_t name_len;  // Length of note name
679         uint32_t desc_len;  // Length of note descriptor
680         uint32_t type;      // Type of note (1 is ABI_TAG, 3 is BUILD_ID)
681     } notehdr;
682     lldb::offset_t offset = 0;
683     static const uint32_t g_gnu_build_id = 3; // NT_GNU_BUILD_ID from elf.h
684 
685     while (true)
686     {
687         if (data.GetU32 (&offset, &notehdr, 3) == NULL)
688             return false;
689 
690         notehdr.name_len = llvm::RoundUpToAlignment (notehdr.name_len, 4);
691         notehdr.desc_len = llvm::RoundUpToAlignment (notehdr.desc_len, 4);
692 
693         lldb::offset_t offset_next_note = offset + notehdr.name_len + notehdr.desc_len;
694 
695         // 16 bytes is UUID|MD5, 20 bytes is SHA1
696         if ((notehdr.type == g_gnu_build_id) && (notehdr.name_len == 4) &&
697             (notehdr.desc_len == 16 || notehdr.desc_len == 20))
698         {
699             char name[4];
700             if (data.GetU8 (&offset, name, 4) == NULL)
701                 return false;
702             if (!strcmp(name, "GNU"))
703             {
704                 uint8_t uuidbuf[20];
705                 if (data.GetU8 (&offset, &uuidbuf, notehdr.desc_len) == NULL)
706                     return false;
707                 uuid.SetBytes (uuidbuf, notehdr.desc_len);
708                 return true;
709             }
710         }
711         offset = offset_next_note;
712     }
713     return false;
714 }
715 
716 //----------------------------------------------------------------------
717 // GetSectionHeaderInfo
718 //----------------------------------------------------------------------
719 size_t
720 ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,
721                                     lldb_private::DataExtractor &object_data,
722                                     const elf::ELFHeader &header,
723                                     lldb_private::UUID &uuid,
724                                     std::string &gnu_debuglink_file,
725                                     uint32_t &gnu_debuglink_crc)
726 {
727     // We have already parsed the section headers
728     if (!section_headers.empty())
729         return section_headers.size();
730 
731     // If there are no section headers we are done.
732     if (header.e_shnum == 0)
733         return 0;
734 
735     section_headers.resize(header.e_shnum);
736     if (section_headers.size() != header.e_shnum)
737         return 0;
738 
739     const size_t sh_size = header.e_shnum * header.e_shentsize;
740     const elf_off sh_offset = header.e_shoff;
741     DataExtractor sh_data;
742     if (sh_data.SetData (object_data, sh_offset, sh_size) != sh_size)
743         return 0;
744 
745     uint32_t idx;
746     lldb::offset_t offset;
747     for (idx = 0, offset = 0; idx < header.e_shnum; ++idx)
748     {
749         if (section_headers[idx].Parse(sh_data, &offset) == false)
750             break;
751     }
752     if (idx < section_headers.size())
753         section_headers.resize(idx);
754 
755     const unsigned strtab_idx = header.e_shstrndx;
756     if (strtab_idx && strtab_idx < section_headers.size())
757     {
758         const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
759         const size_t byte_size = sheader.sh_size;
760         const Elf64_Off offset = sheader.sh_offset;
761         lldb_private::DataExtractor shstr_data;
762 
763         if (shstr_data.SetData (object_data, offset, byte_size) == byte_size)
764         {
765             for (SectionHeaderCollIter I = section_headers.begin();
766                  I != section_headers.end(); ++I)
767             {
768                 static ConstString g_sect_name_gnu_debuglink (".gnu_debuglink");
769                 const ELFSectionHeaderInfo &header = *I;
770                 const uint64_t section_size = header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
771                 ConstString name(shstr_data.PeekCStr(I->sh_name));
772 
773                 I->section_name = name;
774 
775                 if (name == g_sect_name_gnu_debuglink)
776                 {
777                     DataExtractor data;
778                     if (section_size && (data.SetData (object_data, header.sh_offset, section_size) == section_size))
779                     {
780                         lldb::offset_t gnu_debuglink_offset = 0;
781                         gnu_debuglink_file = data.GetCStr (&gnu_debuglink_offset);
782                         gnu_debuglink_offset = llvm::RoundUpToAlignment (gnu_debuglink_offset, 4);
783                         data.GetU32 (&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
784                     }
785                 }
786 
787                 if (header.sh_type == SHT_NOTE && !uuid.IsValid())
788                 {
789                     DataExtractor data;
790                     if (section_size && (data.SetData (object_data, header.sh_offset, section_size) == section_size))
791                     {
792                         ParseNoteGNUBuildID (data, uuid);
793                     }
794                 }
795             }
796 
797             return section_headers.size();
798         }
799     }
800 
801     section_headers.clear();
802     return 0;
803 }
804 
805 size_t
806 ObjectFileELF::GetProgramHeaderCount()
807 {
808     return ParseProgramHeaders();
809 }
810 
811 const elf::ELFProgramHeader *
812 ObjectFileELF::GetProgramHeaderByIndex(lldb::user_id_t id)
813 {
814     if (!id || !ParseProgramHeaders())
815         return NULL;
816 
817     if (--id < m_program_headers.size())
818         return &m_program_headers[id];
819 
820     return NULL;
821 }
822 
823 DataExtractor
824 ObjectFileELF::GetSegmentDataByIndex(lldb::user_id_t id)
825 {
826     const elf::ELFProgramHeader *segment_header = GetProgramHeaderByIndex(id);
827     if (segment_header == NULL)
828         return DataExtractor();
829     return DataExtractor(m_data, segment_header->p_offset, segment_header->p_filesz);
830 }
831 
832 //----------------------------------------------------------------------
833 // ParseSectionHeaders
834 //----------------------------------------------------------------------
835 size_t
836 ObjectFileELF::ParseSectionHeaders()
837 {
838     return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid, m_gnu_debuglink_file, m_gnu_debuglink_crc);
839 }
840 
841 const ObjectFileELF::ELFSectionHeaderInfo *
842 ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id)
843 {
844     if (!id || !ParseSectionHeaders())
845         return NULL;
846 
847     if (--id < m_section_headers.size())
848         return &m_section_headers[id];
849 
850     return NULL;
851 }
852 
853 void
854 ObjectFileELF::CreateSections(SectionList &unified_section_list)
855 {
856     if (!m_sections_ap.get() && ParseSectionHeaders())
857     {
858         m_sections_ap.reset(new SectionList());
859 
860         for (SectionHeaderCollIter I = m_section_headers.begin();
861              I != m_section_headers.end(); ++I)
862         {
863             const ELFSectionHeaderInfo &header = *I;
864 
865             ConstString& name = I->section_name;
866             const uint64_t file_size = header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
867             const uint64_t vm_size = header.sh_flags & SHF_ALLOC ? header.sh_size : 0;
868 
869             static ConstString g_sect_name_text (".text");
870             static ConstString g_sect_name_data (".data");
871             static ConstString g_sect_name_bss (".bss");
872             static ConstString g_sect_name_tdata (".tdata");
873             static ConstString g_sect_name_tbss (".tbss");
874             static ConstString g_sect_name_dwarf_debug_abbrev (".debug_abbrev");
875             static ConstString g_sect_name_dwarf_debug_aranges (".debug_aranges");
876             static ConstString g_sect_name_dwarf_debug_frame (".debug_frame");
877             static ConstString g_sect_name_dwarf_debug_info (".debug_info");
878             static ConstString g_sect_name_dwarf_debug_line (".debug_line");
879             static ConstString g_sect_name_dwarf_debug_loc (".debug_loc");
880             static ConstString g_sect_name_dwarf_debug_macinfo (".debug_macinfo");
881             static ConstString g_sect_name_dwarf_debug_pubnames (".debug_pubnames");
882             static ConstString g_sect_name_dwarf_debug_pubtypes (".debug_pubtypes");
883             static ConstString g_sect_name_dwarf_debug_ranges (".debug_ranges");
884             static ConstString g_sect_name_dwarf_debug_str (".debug_str");
885             static ConstString g_sect_name_eh_frame (".eh_frame");
886 
887             SectionType sect_type = eSectionTypeOther;
888 
889             bool is_thread_specific = false;
890 
891             if      (name == g_sect_name_text)                  sect_type = eSectionTypeCode;
892             else if (name == g_sect_name_data)                  sect_type = eSectionTypeData;
893             else if (name == g_sect_name_bss)                   sect_type = eSectionTypeZeroFill;
894             else if (name == g_sect_name_tdata)
895             {
896                 sect_type = eSectionTypeData;
897                 is_thread_specific = true;
898             }
899             else if (name == g_sect_name_tbss)
900             {
901                 sect_type = eSectionTypeZeroFill;
902                 is_thread_specific = true;
903             }
904             // .debug_abbrev – Abbreviations used in the .debug_info section
905             // .debug_aranges – Lookup table for mapping addresses to compilation units
906             // .debug_frame – Call frame information
907             // .debug_info – The core DWARF information section
908             // .debug_line – Line number information
909             // .debug_loc – Location lists used in DW_AT_location attributes
910             // .debug_macinfo – Macro information
911             // .debug_pubnames – Lookup table for mapping object and function names to compilation units
912             // .debug_pubtypes – Lookup table for mapping type names to compilation units
913             // .debug_ranges – Address ranges used in DW_AT_ranges attributes
914             // .debug_str – String table used in .debug_info
915             // MISSING? .gnu_debugdata - "mini debuginfo / MiniDebugInfo" section, http://sourceware.org/gdb/onlinedocs/gdb/MiniDebugInfo.html
916             // MISSING? .debug-index - http://src.chromium.org/viewvc/chrome/trunk/src/build/gdb-add-index?pathrev=144644
917             // MISSING? .debug_types - Type descriptions from DWARF 4? See http://gcc.gnu.org/wiki/DwarfSeparateTypeInfo
918             else if (name == g_sect_name_dwarf_debug_abbrev)    sect_type = eSectionTypeDWARFDebugAbbrev;
919             else if (name == g_sect_name_dwarf_debug_aranges)   sect_type = eSectionTypeDWARFDebugAranges;
920             else if (name == g_sect_name_dwarf_debug_frame)     sect_type = eSectionTypeDWARFDebugFrame;
921             else if (name == g_sect_name_dwarf_debug_info)      sect_type = eSectionTypeDWARFDebugInfo;
922             else if (name == g_sect_name_dwarf_debug_line)      sect_type = eSectionTypeDWARFDebugLine;
923             else if (name == g_sect_name_dwarf_debug_loc)       sect_type = eSectionTypeDWARFDebugLoc;
924             else if (name == g_sect_name_dwarf_debug_macinfo)   sect_type = eSectionTypeDWARFDebugMacInfo;
925             else if (name == g_sect_name_dwarf_debug_pubnames)  sect_type = eSectionTypeDWARFDebugPubNames;
926             else if (name == g_sect_name_dwarf_debug_pubtypes)  sect_type = eSectionTypeDWARFDebugPubTypes;
927             else if (name == g_sect_name_dwarf_debug_ranges)    sect_type = eSectionTypeDWARFDebugRanges;
928             else if (name == g_sect_name_dwarf_debug_str)       sect_type = eSectionTypeDWARFDebugStr;
929             else if (name == g_sect_name_eh_frame)              sect_type = eSectionTypeEHFrame;
930 
931             switch (header.sh_type)
932             {
933                 case SHT_SYMTAB:
934                     assert (sect_type == eSectionTypeOther);
935                     sect_type = eSectionTypeELFSymbolTable;
936                     break;
937                 case SHT_DYNSYM:
938                     assert (sect_type == eSectionTypeOther);
939                     sect_type = eSectionTypeELFDynamicSymbols;
940                     break;
941                 case SHT_RELA:
942                 case SHT_REL:
943                     assert (sect_type == eSectionTypeOther);
944                     sect_type = eSectionTypeELFRelocationEntries;
945                     break;
946                 case SHT_DYNAMIC:
947                     assert (sect_type == eSectionTypeOther);
948                     sect_type = eSectionTypeELFDynamicLinkInfo;
949                     break;
950             }
951 
952             SectionSP section_sp (new Section(GetModule(),        // Module to which this section belongs.
953                                               this,               // ObjectFile to which this section belongs and should read section data from.
954                                               SectionIndex(I),    // Section ID.
955                                               name,               // Section name.
956                                               sect_type,          // Section type.
957                                               header.sh_addr,     // VM address.
958                                               vm_size,            // VM size in bytes of this section.
959                                               header.sh_offset,   // Offset of this section in the file.
960                                               file_size,          // Size of the section as found in the file.
961                                               header.sh_flags));  // Flags for this section.
962 
963             if (is_thread_specific)
964                 section_sp->SetIsThreadSpecific (is_thread_specific);
965             m_sections_ap->AddSection(section_sp);
966         }
967     }
968 
969     if (m_sections_ap.get())
970     {
971         if (GetType() == eTypeDebugInfo)
972         {
973             static const SectionType g_sections[] =
974             {
975                 eSectionTypeDWARFDebugAranges,
976                 eSectionTypeDWARFDebugInfo,
977                 eSectionTypeDWARFDebugAbbrev,
978                 eSectionTypeDWARFDebugFrame,
979                 eSectionTypeDWARFDebugLine,
980                 eSectionTypeDWARFDebugStr,
981                 eSectionTypeDWARFDebugLoc,
982                 eSectionTypeDWARFDebugMacInfo,
983                 eSectionTypeDWARFDebugPubNames,
984                 eSectionTypeDWARFDebugPubTypes,
985                 eSectionTypeDWARFDebugRanges,
986                 eSectionTypeELFSymbolTable,
987             };
988             SectionList *elf_section_list = m_sections_ap.get();
989             for (size_t idx = 0; idx < sizeof(g_sections) / sizeof(g_sections[0]); ++idx)
990             {
991                 SectionType section_type = g_sections[idx];
992                 SectionSP section_sp (elf_section_list->FindSectionByType (section_type, true));
993                 if (section_sp)
994                 {
995                     SectionSP module_section_sp (unified_section_list.FindSectionByType (section_type, true));
996                     if (module_section_sp)
997                         unified_section_list.ReplaceSection (module_section_sp->GetID(), section_sp);
998                     else
999                         unified_section_list.AddSection (section_sp);
1000                 }
1001             }
1002         }
1003         else
1004         {
1005             unified_section_list = *m_sections_ap;
1006         }
1007     }
1008 }
1009 
1010 // private
1011 unsigned
1012 ObjectFileELF::ParseSymbols (Symtab *symtab,
1013                              user_id_t start_id,
1014                              SectionList *section_list,
1015                              const size_t num_symbols,
1016                              const DataExtractor &symtab_data,
1017                              const DataExtractor &strtab_data)
1018 {
1019     ELFSymbol symbol;
1020     lldb::offset_t offset = 0;
1021 
1022     static ConstString text_section_name(".text");
1023     static ConstString init_section_name(".init");
1024     static ConstString fini_section_name(".fini");
1025     static ConstString ctors_section_name(".ctors");
1026     static ConstString dtors_section_name(".dtors");
1027 
1028     static ConstString data_section_name(".data");
1029     static ConstString rodata_section_name(".rodata");
1030     static ConstString rodata1_section_name(".rodata1");
1031     static ConstString data2_section_name(".data1");
1032     static ConstString bss_section_name(".bss");
1033 
1034     //StreamFile strm(stdout, false);
1035     unsigned i;
1036     for (i = 0; i < num_symbols; ++i)
1037     {
1038         if (symbol.Parse(symtab_data, &offset) == false)
1039             break;
1040 
1041         const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
1042 
1043         // No need to add symbols that have no names
1044         if (symbol_name == NULL || symbol_name[0] == '\0')
1045             continue;
1046 
1047         //symbol.Dump (&strm, i, &strtab_data, section_list);
1048 
1049         SectionSP symbol_section_sp;
1050         SymbolType symbol_type = eSymbolTypeInvalid;
1051         Elf64_Half symbol_idx = symbol.st_shndx;
1052 
1053         switch (symbol_idx)
1054         {
1055         case SHN_ABS:
1056             symbol_type = eSymbolTypeAbsolute;
1057             break;
1058         case SHN_UNDEF:
1059             symbol_type = eSymbolTypeUndefined;
1060             break;
1061         default:
1062             symbol_section_sp = section_list->GetSectionAtIndex(symbol_idx);
1063             break;
1064         }
1065 
1066         // If a symbol is undefined do not process it further even if it has a STT type
1067         if (symbol_type != eSymbolTypeUndefined)
1068         {
1069             switch (symbol.getType())
1070             {
1071             default:
1072             case STT_NOTYPE:
1073                 // The symbol's type is not specified.
1074                 break;
1075 
1076             case STT_OBJECT:
1077                 // The symbol is associated with a data object, such as a variable,
1078                 // an array, etc.
1079                 symbol_type = eSymbolTypeData;
1080                 break;
1081 
1082             case STT_FUNC:
1083                 // The symbol is associated with a function or other executable code.
1084                 symbol_type = eSymbolTypeCode;
1085                 break;
1086 
1087             case STT_SECTION:
1088                 // The symbol is associated with a section. Symbol table entries of
1089                 // this type exist primarily for relocation and normally have
1090                 // STB_LOCAL binding.
1091                 break;
1092 
1093             case STT_FILE:
1094                 // Conventionally, the symbol's name gives the name of the source
1095                 // file associated with the object file. A file symbol has STB_LOCAL
1096                 // binding, its section index is SHN_ABS, and it precedes the other
1097                 // STB_LOCAL symbols for the file, if it is present.
1098                 symbol_type = eSymbolTypeSourceFile;
1099                 break;
1100 
1101             case STT_GNU_IFUNC:
1102                 // The symbol is associated with an indirect function. The actual
1103                 // function will be resolved if it is referenced.
1104                 symbol_type = eSymbolTypeResolver;
1105                 break;
1106             }
1107         }
1108 
1109         if (symbol_type == eSymbolTypeInvalid)
1110         {
1111             if (symbol_section_sp)
1112             {
1113                 const ConstString &sect_name = symbol_section_sp->GetName();
1114                 if (sect_name == text_section_name ||
1115                     sect_name == init_section_name ||
1116                     sect_name == fini_section_name ||
1117                     sect_name == ctors_section_name ||
1118                     sect_name == dtors_section_name)
1119                 {
1120                     symbol_type = eSymbolTypeCode;
1121                 }
1122                 else if (sect_name == data_section_name ||
1123                          sect_name == data2_section_name ||
1124                          sect_name == rodata_section_name ||
1125                          sect_name == rodata1_section_name ||
1126                          sect_name == bss_section_name)
1127                 {
1128                     symbol_type = eSymbolTypeData;
1129                 }
1130             }
1131         }
1132 
1133         // If the symbol section we've found has no data (SHT_NOBITS), then check the module section
1134         // list. This can happen if we're parsing the debug file and it has no .text section, for example.
1135         if (symbol_section_sp && (symbol_section_sp->GetFileSize() == 0))
1136         {
1137             ModuleSP module_sp(GetModule());
1138             if (module_sp)
1139             {
1140                 SectionList *module_section_list = module_sp->GetSectionList();
1141                 if (module_section_list && module_section_list != section_list)
1142                 {
1143                     const ConstString &sect_name = symbol_section_sp->GetName();
1144                     lldb::SectionSP section_sp (module_section_list->FindSectionByName (sect_name));
1145                     if (section_sp && section_sp->GetFileSize())
1146                     {
1147                         symbol_section_sp = section_sp;
1148                     }
1149                 }
1150             }
1151         }
1152 
1153         uint64_t symbol_value = symbol.st_value;
1154         if (symbol_section_sp)
1155             symbol_value -= symbol_section_sp->GetFileAddress();
1156         bool is_global = symbol.getBinding() == STB_GLOBAL;
1157         uint32_t flags = symbol.st_other << 8 | symbol.st_info;
1158         bool is_mangled = symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
1159         Symbol dc_symbol(
1160             i + start_id,       // ID is the original symbol table index.
1161             symbol_name,        // Symbol name.
1162             is_mangled,         // Is the symbol name mangled?
1163             symbol_type,        // Type of this symbol
1164             is_global,          // Is this globally visible?
1165             false,              // Is this symbol debug info?
1166             false,              // Is this symbol a trampoline?
1167             false,              // Is this symbol artificial?
1168             symbol_section_sp,  // Section in which this symbol is defined or null.
1169             symbol_value,       // Offset in section or symbol value.
1170             symbol.st_size,     // Size in bytes of this symbol.
1171             true,               // Size is valid
1172             flags);             // Symbol flags.
1173         symtab->AddSymbol(dc_symbol);
1174     }
1175 
1176     return i;
1177 }
1178 
1179 unsigned
1180 ObjectFileELF::ParseSymbolTable(Symtab *symbol_table, user_id_t start_id, lldb_private::Section *symtab)
1181 {
1182     if (symtab->GetObjectFile() != this)
1183     {
1184         // If the symbol table section is owned by a different object file, have it do the
1185         // parsing.
1186         ObjectFileELF *obj_file_elf = static_cast<ObjectFileELF *>(symtab->GetObjectFile());
1187         return obj_file_elf->ParseSymbolTable (symbol_table, start_id, symtab);
1188     }
1189 
1190     // Get section list for this object file.
1191     SectionList *section_list = m_sections_ap.get();
1192     if (!section_list)
1193         return 0;
1194 
1195     user_id_t symtab_id = symtab->GetID();
1196     const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
1197     assert(symtab_hdr->sh_type == SHT_SYMTAB ||
1198            symtab_hdr->sh_type == SHT_DYNSYM);
1199 
1200     // sh_link: section header index of associated string table.
1201     // Section ID's are ones based.
1202     user_id_t strtab_id = symtab_hdr->sh_link + 1;
1203     Section *strtab = section_list->FindSectionByID(strtab_id).get();
1204 
1205     unsigned num_symbols = 0;
1206     if (symtab && strtab)
1207     {
1208         assert (symtab->GetObjectFile() == this);
1209         assert (strtab->GetObjectFile() == this);
1210 
1211         DataExtractor symtab_data;
1212         DataExtractor strtab_data;
1213         if (ReadSectionData(symtab, symtab_data) &&
1214             ReadSectionData(strtab, strtab_data))
1215         {
1216             size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
1217 
1218             num_symbols = ParseSymbols(symbol_table, start_id,
1219                                        section_list, num_symbols,
1220                                        symtab_data, strtab_data);
1221         }
1222     }
1223 
1224     return num_symbols;
1225 }
1226 
1227 size_t
1228 ObjectFileELF::ParseDynamicSymbols()
1229 {
1230     if (m_dynamic_symbols.size())
1231         return m_dynamic_symbols.size();
1232 
1233     SectionList *section_list = GetSectionList();
1234     if (!section_list)
1235         return 0;
1236 
1237     // Find the SHT_DYNAMIC section.
1238     Section *dynsym = section_list->FindSectionByType (eSectionTypeELFDynamicLinkInfo, true).get();
1239     if (!dynsym)
1240         return 0;
1241     assert (dynsym->GetObjectFile() == this);
1242 
1243     ELFDynamic symbol;
1244     DataExtractor dynsym_data;
1245     if (ReadSectionData(dynsym, dynsym_data))
1246     {
1247         const lldb::offset_t section_size = dynsym_data.GetByteSize();
1248         lldb::offset_t cursor = 0;
1249 
1250         while (cursor < section_size)
1251         {
1252             if (!symbol.Parse(dynsym_data, &cursor))
1253                 break;
1254 
1255             m_dynamic_symbols.push_back(symbol);
1256         }
1257     }
1258 
1259     return m_dynamic_symbols.size();
1260 }
1261 
1262 const ELFDynamic *
1263 ObjectFileELF::FindDynamicSymbol(unsigned tag)
1264 {
1265     if (!ParseDynamicSymbols())
1266         return NULL;
1267 
1268     DynamicSymbolCollIter I = m_dynamic_symbols.begin();
1269     DynamicSymbolCollIter E = m_dynamic_symbols.end();
1270     for ( ; I != E; ++I)
1271     {
1272         ELFDynamic *symbol = &*I;
1273 
1274         if (symbol->d_tag == tag)
1275             return symbol;
1276     }
1277 
1278     return NULL;
1279 }
1280 
1281 unsigned
1282 ObjectFileELF::PLTRelocationType()
1283 {
1284     // DT_PLTREL
1285     //  This member specifies the type of relocation entry to which the
1286     //  procedure linkage table refers. The d_val member holds DT_REL or
1287     //  DT_RELA, as appropriate. All relocations in a procedure linkage table
1288     //  must use the same relocation.
1289     const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
1290 
1291     if (symbol)
1292         return symbol->d_val;
1293 
1294     return 0;
1295 }
1296 
1297 static unsigned
1298 ParsePLTRelocations(Symtab *symbol_table,
1299                     user_id_t start_id,
1300                     unsigned rel_type,
1301                     const ELFHeader *hdr,
1302                     const ELFSectionHeader *rel_hdr,
1303                     const ELFSectionHeader *plt_hdr,
1304                     const ELFSectionHeader *sym_hdr,
1305                     const lldb::SectionSP &plt_section_sp,
1306                     DataExtractor &rel_data,
1307                     DataExtractor &symtab_data,
1308                     DataExtractor &strtab_data)
1309 {
1310     ELFRelocation rel(rel_type);
1311     ELFSymbol symbol;
1312     lldb::offset_t offset = 0;
1313     // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are 16 bytes.
1314     // So round the entsize up by the alignment if addralign is set.
1315     const elf_xword plt_entsize = plt_hdr->sh_addralign ?
1316         llvm::RoundUpToAlignment (plt_hdr->sh_entsize, plt_hdr->sh_addralign) : plt_hdr->sh_entsize;
1317     const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
1318 
1319     typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
1320     reloc_info_fn reloc_type;
1321     reloc_info_fn reloc_symbol;
1322 
1323     if (hdr->Is32Bit())
1324     {
1325         reloc_type = ELFRelocation::RelocType32;
1326         reloc_symbol = ELFRelocation::RelocSymbol32;
1327     }
1328     else
1329     {
1330         reloc_type = ELFRelocation::RelocType64;
1331         reloc_symbol = ELFRelocation::RelocSymbol64;
1332     }
1333 
1334     unsigned slot_type = hdr->GetRelocationJumpSlotType();
1335     unsigned i;
1336     for (i = 0; i < num_relocations; ++i)
1337     {
1338         if (rel.Parse(rel_data, &offset) == false)
1339             break;
1340 
1341         if (reloc_type(rel) != slot_type)
1342             continue;
1343 
1344         lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
1345         uint64_t plt_index = (i + 1) * plt_entsize;
1346 
1347         if (!symbol.Parse(symtab_data, &symbol_offset))
1348             break;
1349 
1350         const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
1351         bool is_mangled = symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
1352 
1353         Symbol jump_symbol(
1354             i + start_id,    // Symbol table index
1355             symbol_name,     // symbol name.
1356             is_mangled,      // is the symbol name mangled?
1357             eSymbolTypeTrampoline, // Type of this symbol
1358             false,           // Is this globally visible?
1359             false,           // Is this symbol debug info?
1360             true,            // Is this symbol a trampoline?
1361             true,            // Is this symbol artificial?
1362             plt_section_sp,  // Section in which this symbol is defined or null.
1363             plt_index,       // Offset in section or symbol value.
1364             plt_entsize,     // Size in bytes of this symbol.
1365             true,            // Size is valid
1366             0);              // Symbol flags.
1367 
1368         symbol_table->AddSymbol(jump_symbol);
1369     }
1370 
1371     return i;
1372 }
1373 
1374 unsigned
1375 ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table,
1376                                       user_id_t start_id,
1377                                       const ELFSectionHeaderInfo *rel_hdr,
1378                                       user_id_t rel_id)
1379 {
1380     assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
1381 
1382     // The link field points to the associated symbol table. The info field
1383     // points to the section holding the plt.
1384     user_id_t symtab_id = rel_hdr->sh_link;
1385     user_id_t plt_id = rel_hdr->sh_info;
1386 
1387     if (!symtab_id || !plt_id)
1388         return 0;
1389 
1390     // Section ID's are ones based;
1391     symtab_id++;
1392     plt_id++;
1393 
1394     const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
1395     if (!plt_hdr)
1396         return 0;
1397 
1398     const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
1399     if (!sym_hdr)
1400         return 0;
1401 
1402     SectionList *section_list = m_sections_ap.get();
1403     if (!section_list)
1404         return 0;
1405 
1406     Section *rel_section = section_list->FindSectionByID(rel_id).get();
1407     if (!rel_section)
1408         return 0;
1409 
1410     SectionSP plt_section_sp (section_list->FindSectionByID(plt_id));
1411     if (!plt_section_sp)
1412         return 0;
1413 
1414     Section *symtab = section_list->FindSectionByID(symtab_id).get();
1415     if (!symtab)
1416         return 0;
1417 
1418     // sh_link points to associated string table.
1419     Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link + 1).get();
1420     if (!strtab)
1421         return 0;
1422 
1423     DataExtractor rel_data;
1424     if (!ReadSectionData(rel_section, rel_data))
1425         return 0;
1426 
1427     DataExtractor symtab_data;
1428     if (!ReadSectionData(symtab, symtab_data))
1429         return 0;
1430 
1431     DataExtractor strtab_data;
1432     if (!ReadSectionData(strtab, strtab_data))
1433         return 0;
1434 
1435     unsigned rel_type = PLTRelocationType();
1436     if (!rel_type)
1437         return 0;
1438 
1439     return ParsePLTRelocations (symbol_table,
1440                                 start_id,
1441                                 rel_type,
1442                                 &m_header,
1443                                 rel_hdr,
1444                                 plt_hdr,
1445                                 sym_hdr,
1446                                 plt_section_sp,
1447                                 rel_data,
1448                                 symtab_data,
1449                                 strtab_data);
1450 }
1451 
1452 Symtab *
1453 ObjectFileELF::GetSymtab()
1454 {
1455     ModuleSP module_sp(GetModule());
1456     if (!module_sp)
1457         return NULL;
1458 
1459     // We always want to use the main object file so we (hopefully) only have one cached copy
1460     // of our symtab, dynamic sections, etc.
1461     ObjectFile *module_obj_file = module_sp->GetObjectFile();
1462     if (module_obj_file && module_obj_file != this)
1463         return module_obj_file->GetSymtab();
1464 
1465     if (m_symtab_ap.get() == NULL)
1466     {
1467         SectionList *section_list = GetSectionList();
1468         if (!section_list)
1469             return NULL;
1470 
1471         uint64_t symbol_id = 0;
1472         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
1473 
1474         m_symtab_ap.reset(new Symtab(this));
1475 
1476         // Sharable objects and dynamic executables usually have 2 distinct symbol
1477         // tables, one named ".symtab", and the other ".dynsym". The dynsym is a smaller
1478         // version of the symtab that only contains global symbols. The information found
1479         // in the dynsym is therefore also found in the symtab, while the reverse is not
1480         // necessarily true.
1481         Section *symtab = section_list->FindSectionByType (eSectionTypeELFSymbolTable, true).get();
1482         if (!symtab)
1483         {
1484             // The symtab section is non-allocable and can be stripped, so if it doesn't exist
1485             // then use the dynsym section which should always be there.
1486             symtab = section_list->FindSectionByType (eSectionTypeELFDynamicSymbols, true).get();
1487         }
1488         if (symtab)
1489             symbol_id += ParseSymbolTable (m_symtab_ap.get(), symbol_id, symtab);
1490 
1491         // DT_JMPREL
1492         //      If present, this entry's d_ptr member holds the address of relocation
1493         //      entries associated solely with the procedure linkage table. Separating
1494         //      these relocation entries lets the dynamic linker ignore them during
1495         //      process initialization, if lazy binding is enabled. If this entry is
1496         //      present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
1497         //      also be present.
1498         const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
1499         if (symbol)
1500         {
1501             // Synthesize trampoline symbols to help navigate the PLT.
1502             addr_t addr = symbol->d_ptr;
1503             Section *reloc_section = section_list->FindSectionContainingFileAddress(addr).get();
1504             if (reloc_section)
1505             {
1506                 user_id_t reloc_id = reloc_section->GetID();
1507                 const ELFSectionHeaderInfo *reloc_header = GetSectionHeaderByIndex(reloc_id);
1508                 assert(reloc_header);
1509 
1510                 ParseTrampolineSymbols (m_symtab_ap.get(), symbol_id, reloc_header, reloc_id);
1511             }
1512         }
1513     }
1514     return m_symtab_ap.get();
1515 }
1516 
1517 Symbol *
1518 ObjectFileELF::ResolveSymbolForAddress(const Address& so_addr, bool verify_unique)
1519 {
1520     if (!m_symtab_ap.get())
1521         return nullptr; // GetSymtab() should be called first.
1522 
1523     const SectionList *section_list = GetSectionList();
1524     if (!section_list)
1525         return nullptr;
1526 
1527     if (DWARFCallFrameInfo *eh_frame = GetUnwindTable().GetEHFrameInfo())
1528     {
1529         AddressRange range;
1530         if (eh_frame->GetAddressRange (so_addr, range))
1531         {
1532             const addr_t file_addr = range.GetBaseAddress().GetFileAddress();
1533             Symbol * symbol = verify_unique ? m_symtab_ap->FindSymbolContainingFileAddress(file_addr) : nullptr;
1534             if (symbol)
1535                 return symbol;
1536 
1537             // Note that a (stripped) symbol won't be found by GetSymtab()...
1538             lldb::SectionSP eh_sym_section_sp = section_list->FindSectionContainingFileAddress(file_addr);
1539             if (eh_sym_section_sp.get())
1540             {
1541                 addr_t section_base = eh_sym_section_sp->GetFileAddress();
1542                 addr_t offset = file_addr - section_base;
1543                 uint64_t symbol_id = m_symtab_ap->GetNumSymbols();
1544 
1545                 Symbol eh_symbol(
1546                         symbol_id,            // Symbol table index.
1547                         "???",                // Symbol name.
1548                         false,                // Is the symbol name mangled?
1549                         eSymbolTypeCode,      // Type of this symbol.
1550                         true,                 // Is this globally visible?
1551                         false,                // Is this symbol debug info?
1552                         false,                // Is this symbol a trampoline?
1553                         true,                 // Is this symbol artificial?
1554                         eh_sym_section_sp,    // Section in which this symbol is defined or null.
1555                         offset,               // Offset in section or symbol value.
1556                         range.GetByteSize(),  // Size in bytes of this symbol.
1557                         true,                 // Size is valid.
1558                         0);                   // Symbol flags.
1559                 if (symbol_id == m_symtab_ap->AddSymbol(eh_symbol))
1560                     return m_symtab_ap->SymbolAtIndex(symbol_id);
1561             }
1562         }
1563     }
1564     return nullptr;
1565 }
1566 
1567 
1568 bool
1569 ObjectFileELF::IsStripped ()
1570 {
1571     // TODO: determine this for ELF
1572     return false;
1573 }
1574 
1575 //===----------------------------------------------------------------------===//
1576 // Dump
1577 //
1578 // Dump the specifics of the runtime file container (such as any headers
1579 // segments, sections, etc).
1580 //----------------------------------------------------------------------
1581 void
1582 ObjectFileELF::Dump(Stream *s)
1583 {
1584     DumpELFHeader(s, m_header);
1585     s->EOL();
1586     DumpELFProgramHeaders(s);
1587     s->EOL();
1588     DumpELFSectionHeaders(s);
1589     s->EOL();
1590     SectionList *section_list = GetSectionList();
1591     if (section_list)
1592         section_list->Dump(s, NULL, true, UINT32_MAX);
1593     Symtab *symtab = GetSymtab();
1594     if (symtab)
1595         symtab->Dump(s, NULL, eSortOrderNone);
1596     s->EOL();
1597     DumpDependentModules(s);
1598     s->EOL();
1599 }
1600 
1601 //----------------------------------------------------------------------
1602 // DumpELFHeader
1603 //
1604 // Dump the ELF header to the specified output stream
1605 //----------------------------------------------------------------------
1606 void
1607 ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header)
1608 {
1609     s->PutCString("ELF Header\n");
1610     s->Printf("e_ident[EI_MAG0   ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
1611     s->Printf("e_ident[EI_MAG1   ] = 0x%2.2x '%c'\n",
1612               header.e_ident[EI_MAG1], header.e_ident[EI_MAG1]);
1613     s->Printf("e_ident[EI_MAG2   ] = 0x%2.2x '%c'\n",
1614               header.e_ident[EI_MAG2], header.e_ident[EI_MAG2]);
1615     s->Printf("e_ident[EI_MAG3   ] = 0x%2.2x '%c'\n",
1616               header.e_ident[EI_MAG3], header.e_ident[EI_MAG3]);
1617 
1618     s->Printf("e_ident[EI_CLASS  ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
1619     s->Printf("e_ident[EI_DATA   ] = 0x%2.2x ", header.e_ident[EI_DATA]);
1620     DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
1621     s->Printf ("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
1622     s->Printf ("e_ident[EI_PAD    ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
1623 
1624     s->Printf("e_type      = 0x%4.4x ", header.e_type);
1625     DumpELFHeader_e_type(s, header.e_type);
1626     s->Printf("\ne_machine   = 0x%4.4x\n", header.e_machine);
1627     s->Printf("e_version   = 0x%8.8x\n", header.e_version);
1628     s->Printf("e_entry     = 0x%8.8" PRIx64 "\n", header.e_entry);
1629     s->Printf("e_phoff     = 0x%8.8" PRIx64 "\n", header.e_phoff);
1630     s->Printf("e_shoff     = 0x%8.8" PRIx64 "\n", header.e_shoff);
1631     s->Printf("e_flags     = 0x%8.8x\n", header.e_flags);
1632     s->Printf("e_ehsize    = 0x%4.4x\n", header.e_ehsize);
1633     s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
1634     s->Printf("e_phnum     = 0x%4.4x\n", header.e_phnum);
1635     s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
1636     s->Printf("e_shnum     = 0x%4.4x\n", header.e_shnum);
1637     s->Printf("e_shstrndx  = 0x%4.4x\n", header.e_shstrndx);
1638 }
1639 
1640 //----------------------------------------------------------------------
1641 // DumpELFHeader_e_type
1642 //
1643 // Dump an token value for the ELF header member e_type
1644 //----------------------------------------------------------------------
1645 void
1646 ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type)
1647 {
1648     switch (e_type)
1649     {
1650     case ET_NONE:   *s << "ET_NONE"; break;
1651     case ET_REL:    *s << "ET_REL"; break;
1652     case ET_EXEC:   *s << "ET_EXEC"; break;
1653     case ET_DYN:    *s << "ET_DYN"; break;
1654     case ET_CORE:   *s << "ET_CORE"; break;
1655     default:
1656         break;
1657     }
1658 }
1659 
1660 //----------------------------------------------------------------------
1661 // DumpELFHeader_e_ident_EI_DATA
1662 //
1663 // Dump an token value for the ELF header member e_ident[EI_DATA]
1664 //----------------------------------------------------------------------
1665 void
1666 ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s, unsigned char ei_data)
1667 {
1668     switch (ei_data)
1669     {
1670     case ELFDATANONE:   *s << "ELFDATANONE"; break;
1671     case ELFDATA2LSB:   *s << "ELFDATA2LSB - Little Endian"; break;
1672     case ELFDATA2MSB:   *s << "ELFDATA2MSB - Big Endian"; break;
1673     default:
1674         break;
1675     }
1676 }
1677 
1678 
1679 //----------------------------------------------------------------------
1680 // DumpELFProgramHeader
1681 //
1682 // Dump a single ELF program header to the specified output stream
1683 //----------------------------------------------------------------------
1684 void
1685 ObjectFileELF::DumpELFProgramHeader(Stream *s, const ELFProgramHeader &ph)
1686 {
1687     DumpELFProgramHeader_p_type(s, ph.p_type);
1688     s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset, ph.p_vaddr, ph.p_paddr);
1689     s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz, ph.p_flags);
1690 
1691     DumpELFProgramHeader_p_flags(s, ph.p_flags);
1692     s->Printf(") %8.8" PRIx64, ph.p_align);
1693 }
1694 
1695 //----------------------------------------------------------------------
1696 // DumpELFProgramHeader_p_type
1697 //
1698 // Dump an token value for the ELF program header member p_type which
1699 // describes the type of the program header
1700 // ----------------------------------------------------------------------
1701 void
1702 ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type)
1703 {
1704     const int kStrWidth = 15;
1705     switch (p_type)
1706     {
1707     CASE_AND_STREAM(s, PT_NULL        , kStrWidth);
1708     CASE_AND_STREAM(s, PT_LOAD        , kStrWidth);
1709     CASE_AND_STREAM(s, PT_DYNAMIC     , kStrWidth);
1710     CASE_AND_STREAM(s, PT_INTERP      , kStrWidth);
1711     CASE_AND_STREAM(s, PT_NOTE        , kStrWidth);
1712     CASE_AND_STREAM(s, PT_SHLIB       , kStrWidth);
1713     CASE_AND_STREAM(s, PT_PHDR        , kStrWidth);
1714     CASE_AND_STREAM(s, PT_TLS         , kStrWidth);
1715     CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
1716     default:
1717         s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
1718         break;
1719     }
1720 }
1721 
1722 
1723 //----------------------------------------------------------------------
1724 // DumpELFProgramHeader_p_flags
1725 //
1726 // Dump an token value for the ELF program header member p_flags
1727 //----------------------------------------------------------------------
1728 void
1729 ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags)
1730 {
1731     *s  << ((p_flags & PF_X) ? "PF_X" : "    ")
1732         << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
1733         << ((p_flags & PF_W) ? "PF_W" : "    ")
1734         << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
1735         << ((p_flags & PF_R) ? "PF_R" : "    ");
1736 }
1737 
1738 //----------------------------------------------------------------------
1739 // DumpELFProgramHeaders
1740 //
1741 // Dump all of the ELF program header to the specified output stream
1742 //----------------------------------------------------------------------
1743 void
1744 ObjectFileELF::DumpELFProgramHeaders(Stream *s)
1745 {
1746     if (ParseProgramHeaders())
1747     {
1748         s->PutCString("Program Headers\n");
1749         s->PutCString("IDX  p_type          p_offset p_vaddr  p_paddr  "
1750                       "p_filesz p_memsz  p_flags                   p_align\n");
1751         s->PutCString("==== --------------- -------- -------- -------- "
1752                       "-------- -------- ------------------------- --------\n");
1753 
1754         uint32_t idx = 0;
1755         for (ProgramHeaderCollConstIter I = m_program_headers.begin();
1756              I != m_program_headers.end(); ++I, ++idx)
1757         {
1758             s->Printf("[%2u] ", idx);
1759             ObjectFileELF::DumpELFProgramHeader(s, *I);
1760             s->EOL();
1761         }
1762     }
1763 }
1764 
1765 //----------------------------------------------------------------------
1766 // DumpELFSectionHeader
1767 //
1768 // Dump a single ELF section header to the specified output stream
1769 //----------------------------------------------------------------------
1770 void
1771 ObjectFileELF::DumpELFSectionHeader(Stream *s, const ELFSectionHeaderInfo &sh)
1772 {
1773     s->Printf("%8.8x ", sh.sh_name);
1774     DumpELFSectionHeader_sh_type(s, sh.sh_type);
1775     s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
1776     DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
1777     s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr, sh.sh_offset, sh.sh_size);
1778     s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
1779     s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
1780 }
1781 
1782 //----------------------------------------------------------------------
1783 // DumpELFSectionHeader_sh_type
1784 //
1785 // Dump an token value for the ELF section header member sh_type which
1786 // describes the type of the section
1787 //----------------------------------------------------------------------
1788 void
1789 ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type)
1790 {
1791     const int kStrWidth = 12;
1792     switch (sh_type)
1793     {
1794     CASE_AND_STREAM(s, SHT_NULL     , kStrWidth);
1795     CASE_AND_STREAM(s, SHT_PROGBITS , kStrWidth);
1796     CASE_AND_STREAM(s, SHT_SYMTAB   , kStrWidth);
1797     CASE_AND_STREAM(s, SHT_STRTAB   , kStrWidth);
1798     CASE_AND_STREAM(s, SHT_RELA     , kStrWidth);
1799     CASE_AND_STREAM(s, SHT_HASH     , kStrWidth);
1800     CASE_AND_STREAM(s, SHT_DYNAMIC  , kStrWidth);
1801     CASE_AND_STREAM(s, SHT_NOTE     , kStrWidth);
1802     CASE_AND_STREAM(s, SHT_NOBITS   , kStrWidth);
1803     CASE_AND_STREAM(s, SHT_REL      , kStrWidth);
1804     CASE_AND_STREAM(s, SHT_SHLIB    , kStrWidth);
1805     CASE_AND_STREAM(s, SHT_DYNSYM   , kStrWidth);
1806     CASE_AND_STREAM(s, SHT_LOPROC   , kStrWidth);
1807     CASE_AND_STREAM(s, SHT_HIPROC   , kStrWidth);
1808     CASE_AND_STREAM(s, SHT_LOUSER   , kStrWidth);
1809     CASE_AND_STREAM(s, SHT_HIUSER   , kStrWidth);
1810     default:
1811         s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
1812         break;
1813     }
1814 }
1815 
1816 //----------------------------------------------------------------------
1817 // DumpELFSectionHeader_sh_flags
1818 //
1819 // Dump an token value for the ELF section header member sh_flags
1820 //----------------------------------------------------------------------
1821 void
1822 ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s, elf_xword sh_flags)
1823 {
1824     *s  << ((sh_flags & SHF_WRITE) ? "WRITE" : "     ")
1825         << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
1826         << ((sh_flags & SHF_ALLOC) ? "ALLOC" : "     ")
1827         << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
1828         << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : "         ");
1829 }
1830 
1831 //----------------------------------------------------------------------
1832 // DumpELFSectionHeaders
1833 //
1834 // Dump all of the ELF section header to the specified output stream
1835 //----------------------------------------------------------------------
1836 void
1837 ObjectFileELF::DumpELFSectionHeaders(Stream *s)
1838 {
1839     if (!ParseSectionHeaders())
1840         return;
1841 
1842     s->PutCString("Section Headers\n");
1843     s->PutCString("IDX  name     type         flags                            "
1844                   "addr     offset   size     link     info     addralgn "
1845                   "entsize  Name\n");
1846     s->PutCString("==== -------- ------------ -------------------------------- "
1847                   "-------- -------- -------- -------- -------- -------- "
1848                   "-------- ====================\n");
1849 
1850     uint32_t idx = 0;
1851     for (SectionHeaderCollConstIter I = m_section_headers.begin();
1852          I != m_section_headers.end(); ++I, ++idx)
1853     {
1854         s->Printf("[%2u] ", idx);
1855         ObjectFileELF::DumpELFSectionHeader(s, *I);
1856         const char* section_name = I->section_name.AsCString("");
1857         if (section_name)
1858             *s << ' ' << section_name << "\n";
1859     }
1860 }
1861 
1862 void
1863 ObjectFileELF::DumpDependentModules(lldb_private::Stream *s)
1864 {
1865     size_t num_modules = ParseDependentModules();
1866 
1867     if (num_modules > 0)
1868     {
1869         s->PutCString("Dependent Modules:\n");
1870         for (unsigned i = 0; i < num_modules; ++i)
1871         {
1872             const FileSpec &spec = m_filespec_ap->GetFileSpecAtIndex(i);
1873             s->Printf("   %s\n", spec.GetFilename().GetCString());
1874         }
1875     }
1876 }
1877 
1878 bool
1879 ObjectFileELF::GetArchitecture (ArchSpec &arch)
1880 {
1881     if (!ParseHeader())
1882         return false;
1883 
1884     arch.SetArchitecture (eArchTypeELF, m_header.e_machine, LLDB_INVALID_CPUTYPE);
1885     arch.GetTriple().setOSName (Host::GetOSString().GetCString());
1886     arch.GetTriple().setVendorName(Host::GetVendorString().GetCString());
1887     return true;
1888 }
1889 
1890 ObjectFile::Type
1891 ObjectFileELF::CalculateType()
1892 {
1893     switch (m_header.e_type)
1894     {
1895         case llvm::ELF::ET_NONE:
1896             // 0 - No file type
1897             return eTypeUnknown;
1898 
1899         case llvm::ELF::ET_REL:
1900             // 1 - Relocatable file
1901             return eTypeObjectFile;
1902 
1903         case llvm::ELF::ET_EXEC:
1904             // 2 - Executable file
1905             return eTypeExecutable;
1906 
1907         case llvm::ELF::ET_DYN:
1908             // 3 - Shared object file
1909             return eTypeSharedLibrary;
1910 
1911         case ET_CORE:
1912             // 4 - Core file
1913             return eTypeCoreFile;
1914 
1915         default:
1916             break;
1917     }
1918     return eTypeUnknown;
1919 }
1920 
1921 ObjectFile::Strata
1922 ObjectFileELF::CalculateStrata()
1923 {
1924     switch (m_header.e_type)
1925     {
1926         case llvm::ELF::ET_NONE:
1927             // 0 - No file type
1928             return eStrataUnknown;
1929 
1930         case llvm::ELF::ET_REL:
1931             // 1 - Relocatable file
1932             return eStrataUnknown;
1933 
1934         case llvm::ELF::ET_EXEC:
1935             // 2 - Executable file
1936             // TODO: is there any way to detect that an executable is a kernel
1937             // related executable by inspecting the program headers, section
1938             // headers, symbols, or any other flag bits???
1939             return eStrataUser;
1940 
1941         case llvm::ELF::ET_DYN:
1942             // 3 - Shared object file
1943             // TODO: is there any way to detect that an shared library is a kernel
1944             // related executable by inspecting the program headers, section
1945             // headers, symbols, or any other flag bits???
1946             return eStrataUnknown;
1947 
1948         case ET_CORE:
1949             // 4 - Core file
1950             // TODO: is there any way to detect that an core file is a kernel
1951             // related executable by inspecting the program headers, section
1952             // headers, symbols, or any other flag bits???
1953             return eStrataUnknown;
1954 
1955         default:
1956             break;
1957     }
1958     return eStrataUnknown;
1959 }
1960 
1961