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