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