ProcessElfCore.cpp revision 280031
1//===-- ProcessElfCore.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// C Includes
11#include <stdlib.h>
12
13// Other libraries and framework includes
14#include "lldb/Core/PluginManager.h"
15#include "lldb/Core/Module.h"
16#include "lldb/Core/ModuleSpec.h"
17#include "lldb/Core/Section.h"
18#include "lldb/Core/State.h"
19#include "lldb/Core/DataBufferHeap.h"
20#include "lldb/Core/Log.h"
21#include "lldb/Target/Target.h"
22#include "lldb/Target/DynamicLoader.h"
23#include "lldb/Target/UnixSignals.h"
24
25#include "llvm/Support/ELF.h"
26
27#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
28#include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h"
29#include "Plugins/Process/Utility/FreeBSDSignals.h"
30#include "Plugins/Process/Utility/LinuxSignals.h"
31
32// Project includes
33#include "ProcessElfCore.h"
34#include "ThreadElfCore.h"
35
36using namespace lldb_private;
37
38ConstString
39ProcessElfCore::GetPluginNameStatic()
40{
41    static ConstString g_name("elf-core");
42    return g_name;
43}
44
45const char *
46ProcessElfCore::GetPluginDescriptionStatic()
47{
48    return "ELF core dump plug-in.";
49}
50
51void
52ProcessElfCore::Terminate()
53{
54    PluginManager::UnregisterPlugin (ProcessElfCore::CreateInstance);
55}
56
57
58lldb::ProcessSP
59ProcessElfCore::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file)
60{
61    lldb::ProcessSP process_sp;
62    if (crash_file)
63    {
64        // Read enough data for a ELF32 header or ELF64 header
65        const size_t header_size = sizeof(llvm::ELF::Elf64_Ehdr);
66
67        lldb::DataBufferSP data_sp (crash_file->ReadFileContents(0, header_size));
68        if (data_sp && data_sp->GetByteSize() == header_size &&
69            elf::ELFHeader::MagicBytesMatch (data_sp->GetBytes()))
70        {
71            elf::ELFHeader elf_header;
72            DataExtractor data(data_sp, lldb::eByteOrderLittle, 4);
73            lldb::offset_t data_offset = 0;
74            if (elf_header.Parse(data, &data_offset))
75            {
76                if (elf_header.e_type == llvm::ELF::ET_CORE)
77                    process_sp.reset(new ProcessElfCore (target, listener, *crash_file));
78            }
79        }
80    }
81    return process_sp;
82}
83
84bool
85ProcessElfCore::CanDebug(Target &target, bool plugin_specified_by_name)
86{
87    // For now we are just making sure the file exists for a given module
88    if (!m_core_module_sp && m_core_file.Exists())
89    {
90        ModuleSpec core_module_spec(m_core_file, target.GetArchitecture());
91        Error error (ModuleList::GetSharedModule (core_module_spec, m_core_module_sp,
92                                                  NULL, NULL, NULL));
93        if (m_core_module_sp)
94        {
95            ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
96            if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile)
97                return true;
98        }
99    }
100    return false;
101}
102
103//----------------------------------------------------------------------
104// ProcessElfCore constructor
105//----------------------------------------------------------------------
106ProcessElfCore::ProcessElfCore(Target& target, Listener &listener,
107                               const FileSpec &core_file) :
108    Process (target, listener),
109    m_core_module_sp (),
110    m_core_file (core_file),
111    m_dyld_plugin_name (),
112    m_os(llvm::Triple::UnknownOS),
113    m_thread_data_valid(false),
114    m_thread_data(),
115    m_core_aranges ()
116{
117}
118
119//----------------------------------------------------------------------
120// Destructor
121//----------------------------------------------------------------------
122ProcessElfCore::~ProcessElfCore()
123{
124    Clear();
125    // We need to call finalize on the process before destroying ourselves
126    // to make sure all of the broadcaster cleanup goes as planned. If we
127    // destruct this class, then Process::~Process() might have problems
128    // trying to fully destroy the broadcaster.
129    Finalize();
130}
131
132//----------------------------------------------------------------------
133// PluginInterface
134//----------------------------------------------------------------------
135ConstString
136ProcessElfCore::GetPluginName()
137{
138    return GetPluginNameStatic();
139}
140
141uint32_t
142ProcessElfCore::GetPluginVersion()
143{
144    return 1;
145}
146
147lldb::addr_t
148ProcessElfCore::AddAddressRangeFromLoadSegment(const elf::ELFProgramHeader *header)
149{
150    lldb::addr_t addr = header->p_vaddr;
151    FileRange file_range (header->p_offset, header->p_filesz);
152    VMRangeToFileOffset::Entry range_entry(addr, header->p_memsz, file_range);
153
154    VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
155    if (last_entry &&
156        last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
157        last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase() &&
158        last_entry->GetByteSize() == last_entry->data.GetByteSize())
159    {
160        last_entry->SetRangeEnd (range_entry.GetRangeEnd());
161        last_entry->data.SetRangeEnd (range_entry.data.GetRangeEnd());
162    }
163    else
164    {
165        m_core_aranges.Append(range_entry);
166    }
167
168    return addr;
169}
170
171//----------------------------------------------------------------------
172// Process Control
173//----------------------------------------------------------------------
174Error
175ProcessElfCore::DoLoadCore ()
176{
177    Error error;
178    if (!m_core_module_sp)
179    {
180        error.SetErrorString ("invalid core module");
181        return error;
182    }
183
184    ObjectFileELF *core = (ObjectFileELF *)(m_core_module_sp->GetObjectFile());
185    if (core == NULL)
186    {
187        error.SetErrorString ("invalid core object file");
188        return error;
189    }
190
191    const uint32_t num_segments = core->GetProgramHeaderCount();
192    if (num_segments == 0)
193    {
194        error.SetErrorString ("core file has no sections");
195        return error;
196    }
197
198    SetCanJIT(false);
199
200    m_thread_data_valid = true;
201
202    bool ranges_are_sorted = true;
203    lldb::addr_t vm_addr = 0;
204    /// Walk through segments and Thread and Address Map information.
205    /// PT_NOTE - Contains Thread and Register information
206    /// PT_LOAD - Contains a contiguous range of Process Address Space
207    for(uint32_t i = 1; i <= num_segments; i++)
208    {
209        const elf::ELFProgramHeader *header = core->GetProgramHeaderByIndex(i);
210        assert(header != NULL);
211
212        DataExtractor data = core->GetSegmentDataByIndex(i);
213
214        // Parse thread contexts and auxv structure
215        if (header->p_type == llvm::ELF::PT_NOTE)
216            ParseThreadContextsFromNoteSegment(header, data);
217
218        // PT_LOAD segments contains address map
219        if (header->p_type == llvm::ELF::PT_LOAD)
220        {
221            lldb::addr_t last_addr = AddAddressRangeFromLoadSegment(header);
222            if (vm_addr > last_addr)
223                ranges_are_sorted = false;
224            vm_addr = last_addr;
225        }
226    }
227
228    if (!ranges_are_sorted)
229        m_core_aranges.Sort();
230
231    // Even if the architecture is set in the target, we need to override
232    // it to match the core file which is always single arch.
233    ArchSpec arch (m_core_module_sp->GetArchitecture());
234    if (arch.IsValid())
235        m_target.SetArchitecture(arch);
236
237    switch (m_os)
238    {
239        case llvm::Triple::FreeBSD:
240        {
241            static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals ());
242            SetUnixSignals(s_freebsd_signals_sp);
243            break;
244        }
245        case llvm::Triple::Linux:
246        {
247            static UnixSignalsSP s_linux_signals_sp(new process_linux::LinuxSignals ());
248            SetUnixSignals(s_linux_signals_sp);
249            break;
250        }
251        default:
252            break;
253    }
254
255    return error;
256}
257
258lldb_private::DynamicLoader *
259ProcessElfCore::GetDynamicLoader ()
260{
261    if (m_dyld_ap.get() == NULL)
262        m_dyld_ap.reset (DynamicLoader::FindPlugin(this, DynamicLoaderPOSIXDYLD::GetPluginNameStatic().GetCString()));
263    return m_dyld_ap.get();
264}
265
266bool
267ProcessElfCore::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
268{
269    const uint32_t num_threads = GetNumThreadContexts ();
270    if (!m_thread_data_valid)
271        return false;
272
273    for (lldb::tid_t tid = 0; tid < num_threads; ++tid)
274    {
275        const ThreadData &td = m_thread_data[tid];
276        lldb::ThreadSP thread_sp(new ThreadElfCore (*this, tid, td));
277        new_thread_list.AddThread (thread_sp);
278    }
279    return new_thread_list.GetSize(false) > 0;
280}
281
282void
283ProcessElfCore::RefreshStateAfterStop ()
284{
285}
286
287Error
288ProcessElfCore::DoDestroy ()
289{
290    return Error();
291}
292
293//------------------------------------------------------------------
294// Process Queries
295//------------------------------------------------------------------
296
297bool
298ProcessElfCore::IsAlive ()
299{
300    return true;
301}
302
303//------------------------------------------------------------------
304// Process Memory
305//------------------------------------------------------------------
306size_t
307ProcessElfCore::ReadMemory (lldb::addr_t addr, void *buf, size_t size, Error &error)
308{
309    // Don't allow the caching that lldb_private::Process::ReadMemory does
310    // since in core files we have it all cached our our core file anyway.
311    return DoReadMemory (addr, buf, size, error);
312}
313
314size_t
315ProcessElfCore::DoReadMemory (lldb::addr_t addr, void *buf, size_t size, Error &error)
316{
317    ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
318
319    if (core_objfile == NULL)
320        return 0;
321
322    // Get the address range
323    const VMRangeToFileOffset::Entry *address_range = m_core_aranges.FindEntryThatContains (addr);
324    if (address_range == NULL || address_range->GetRangeEnd() < addr)
325    {
326        error.SetErrorStringWithFormat ("core file does not contain 0x%" PRIx64, addr);
327        return 0;
328    }
329
330    // Convert the address into core file offset
331    const lldb::addr_t offset = addr - address_range->GetRangeBase();
332    const lldb::addr_t file_start = address_range->data.GetRangeBase();
333    const lldb::addr_t file_end = address_range->data.GetRangeEnd();
334    size_t bytes_to_read = size; // Number of bytes to read from the core file
335    size_t bytes_copied = 0;     // Number of bytes actually read from the core file
336    size_t zero_fill_size = 0;   // Padding
337    lldb::addr_t bytes_left = 0; // Number of bytes available in the core file from the given address
338
339    // Figure out how many on-disk bytes remain in this segment
340    // starting at the given offset
341    if (file_end > file_start + offset)
342        bytes_left = file_end - (file_start + offset);
343
344    // Figure out how many bytes we need to zero-fill if we are
345    // reading more bytes than available in the on-disk segment
346    if (bytes_to_read > bytes_left)
347    {
348        zero_fill_size = bytes_to_read - bytes_left;
349        bytes_to_read = bytes_left;
350    }
351
352    // If there is data available on the core file read it
353    if (bytes_to_read)
354        bytes_copied = core_objfile->CopyData(offset + file_start, bytes_to_read, buf);
355
356    assert(zero_fill_size <= size);
357    // Pad remaining bytes
358    if (zero_fill_size)
359        memset(((char *)buf) + bytes_copied, 0, zero_fill_size);
360
361    return bytes_copied + zero_fill_size;
362}
363
364void
365ProcessElfCore::Clear()
366{
367    m_thread_list.Clear();
368    m_os = llvm::Triple::UnknownOS;
369
370    static UnixSignalsSP s_default_unix_signals_sp(new UnixSignals());
371    SetUnixSignals(s_default_unix_signals_sp);
372}
373
374void
375ProcessElfCore::Initialize()
376{
377    static bool g_initialized = false;
378
379    if (g_initialized == false)
380    {
381        g_initialized = true;
382        PluginManager::RegisterPlugin (GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance);
383    }
384}
385
386lldb::addr_t
387ProcessElfCore::GetImageInfoAddress()
388{
389    Target *target = &GetTarget();
390    ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
391    Address addr = obj_file->GetImageInfoAddress(target);
392
393    if (addr.IsValid())
394        return addr.GetLoadAddress(target);
395    return LLDB_INVALID_ADDRESS;
396}
397
398/// Core files PT_NOTE segment descriptor types
399enum {
400    NT_PRSTATUS     = 1,
401    NT_FPREGSET,
402    NT_PRPSINFO,
403    NT_TASKSTRUCT,
404    NT_PLATFORM,
405    NT_AUXV
406};
407
408namespace FREEBSD {
409
410enum {
411    NT_PRSTATUS      = 1,
412    NT_FPREGSET,
413    NT_PRPSINFO,
414    NT_THRMISC       = 7,
415    NT_PROCSTAT_AUXV = 16
416};
417
418}
419
420// Parse a FreeBSD NT_PRSTATUS note - see FreeBSD sys/procfs.h for details.
421static void
422ParseFreeBSDPrStatus(ThreadData &thread_data, DataExtractor &data,
423                     ArchSpec &arch)
424{
425    lldb::offset_t offset = 0;
426    bool lp64 = (arch.GetMachine() == llvm::Triple::mips64 ||
427                 arch.GetMachine() == llvm::Triple::ppc64 ||
428                 arch.GetMachine() == llvm::Triple::x86_64);
429    int pr_version = data.GetU32(&offset);
430
431    Log *log (GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
432    if (log)
433    {
434        if (pr_version > 1)
435            log->Printf("FreeBSD PRSTATUS unexpected version %d", pr_version);
436    }
437
438    // Skip padding, pr_statussz, pr_gregsetsz, pr_fpregsetsz, pr_osreldate
439    if (lp64)
440        offset += 32;
441    else
442        offset += 16;
443
444    thread_data.signo = data.GetU32(&offset); // pr_cursig
445    offset += 4;        // pr_pid
446    if (lp64)
447        offset += 4;
448
449    size_t len = data.GetByteSize() - offset;
450    thread_data.gpregset = DataExtractor(data, offset, len);
451}
452
453static void
454ParseFreeBSDThrMisc(ThreadData &thread_data, DataExtractor &data)
455{
456    lldb::offset_t offset = 0;
457    thread_data.name = data.GetCStr(&offset, 20);
458}
459
460/// Parse Thread context from PT_NOTE segment and store it in the thread list
461/// Notes:
462/// 1) A PT_NOTE segment is composed of one or more NOTE entries.
463/// 2) NOTE Entry contains a standard header followed by variable size data.
464///   (see ELFNote structure)
465/// 3) A Thread Context in a core file usually described by 3 NOTE entries.
466///    a) NT_PRSTATUS - Register context
467///    b) NT_PRPSINFO - Process info(pid..)
468///    c) NT_FPREGSET - Floating point registers
469/// 4) The NOTE entries can be in any order
470/// 5) If a core file contains multiple thread contexts then there is two data forms
471///    a) Each thread context(2 or more NOTE entries) contained in its own segment (PT_NOTE)
472///    b) All thread context is stored in a single segment(PT_NOTE).
473///        This case is little tricker since while parsing we have to find where the
474///        new thread starts. The current implementation marks beginning of
475///        new thread when it finds NT_PRSTATUS or NT_PRPSINFO NOTE entry.
476///    For case (b) there may be either one NT_PRPSINFO per thread, or a single
477///    one that applies to all threads (depending on the platform type).
478void
479ProcessElfCore::ParseThreadContextsFromNoteSegment(const elf::ELFProgramHeader *segment_header,
480                                                   DataExtractor segment_data)
481{
482    assert(segment_header && segment_header->p_type == llvm::ELF::PT_NOTE);
483
484    lldb::offset_t offset = 0;
485    std::unique_ptr<ThreadData> thread_data(new ThreadData);
486    bool have_prstatus = false;
487    bool have_prpsinfo = false;
488
489    ArchSpec arch = GetArchitecture();
490    ELFLinuxPrPsInfo prpsinfo;
491    ELFLinuxPrStatus prstatus;
492    size_t header_size;
493    size_t len;
494
495    // Loop through the NOTE entires in the segment
496    while (offset < segment_header->p_filesz)
497    {
498        ELFNote note = ELFNote();
499        note.Parse(segment_data, &offset);
500
501        // Beginning of new thread
502        if ((note.n_type == NT_PRSTATUS && have_prstatus) ||
503            (note.n_type == NT_PRPSINFO && have_prpsinfo))
504        {
505            assert(thread_data->gpregset.GetByteSize() > 0);
506            // Add the new thread to thread list
507            m_thread_data.push_back(*thread_data);
508            *thread_data = ThreadData();
509            have_prstatus = false;
510            have_prpsinfo = false;
511        }
512
513        size_t note_start, note_size;
514        note_start = offset;
515        note_size = llvm::RoundUpToAlignment(note.n_descsz, 4);
516
517        // Store the NOTE information in the current thread
518        DataExtractor note_data (segment_data, note_start, note_size);
519        if (note.n_name == "FreeBSD")
520        {
521            m_os = llvm::Triple::FreeBSD;
522            switch (note.n_type)
523            {
524                case FREEBSD::NT_PRSTATUS:
525                    have_prstatus = true;
526                    ParseFreeBSDPrStatus(*thread_data, note_data, arch);
527                    break;
528                case FREEBSD::NT_FPREGSET:
529                    thread_data->fpregset = note_data;
530                    break;
531                case FREEBSD::NT_PRPSINFO:
532                    have_prpsinfo = true;
533                    break;
534                case FREEBSD::NT_THRMISC:
535                    ParseFreeBSDThrMisc(*thread_data, note_data);
536                    break;
537                case FREEBSD::NT_PROCSTAT_AUXV:
538                    // FIXME: FreeBSD sticks an int at the beginning of the note
539                    m_auxv = DataExtractor(segment_data, note_start + 4, note_size - 4);
540                    break;
541                default:
542                    break;
543            }
544        }
545        else
546        {
547            switch (note.n_type)
548            {
549                case NT_PRSTATUS:
550                    have_prstatus = true;
551                    prstatus.Parse(note_data, arch);
552                    thread_data->signo = prstatus.pr_cursig;
553                    header_size = ELFLinuxPrStatus::GetSize(arch);
554                    len = note_data.GetByteSize() - header_size;
555                    thread_data->gpregset = DataExtractor(note_data, header_size, len);
556                    break;
557                case NT_FPREGSET:
558                    thread_data->fpregset = note_data;
559                    break;
560                case NT_PRPSINFO:
561                    have_prpsinfo = true;
562                    prpsinfo.Parse(note_data, arch);
563                    thread_data->name = prpsinfo.pr_fname;
564                    break;
565                case NT_AUXV:
566                    m_auxv = DataExtractor(note_data);
567                    break;
568                default:
569                    break;
570            }
571        }
572
573        offset += note_size;
574    }
575    // Add last entry in the note section
576    if (thread_data && thread_data->gpregset.GetByteSize() > 0)
577    {
578        m_thread_data.push_back(*thread_data);
579    }
580}
581
582uint32_t
583ProcessElfCore::GetNumThreadContexts ()
584{
585    if (!m_thread_data_valid)
586        DoLoadCore();
587    return m_thread_data.size();
588}
589
590ArchSpec
591ProcessElfCore::GetArchitecture()
592{
593    ObjectFileELF *core_file = (ObjectFileELF *)(m_core_module_sp->GetObjectFile());
594    ArchSpec arch;
595    core_file->GetArchitecture(arch);
596    return arch;
597}
598
599const lldb::DataBufferSP
600ProcessElfCore::GetAuxvData()
601{
602    const uint8_t *start = m_auxv.GetDataStart();
603    size_t len = m_auxv.GetByteSize();
604    lldb::DataBufferSP buffer(new lldb_private::DataBufferHeap(start, len));
605    return buffer;
606}
607