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