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