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