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