1 //===-- ProcessMachCore.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 <errno.h>
12 #include <stdlib.h>
13 
14 // C++ Includes
15 #include "llvm/Support/MathExtras.h"
16 #include <mutex>
17 
18 // Other libraries and framework includes
19 #include "lldb/Core/DataBuffer.h"
20 #include "lldb/Core/Debugger.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/Module.h"
23 #include "lldb/Core/ModuleSpec.h"
24 #include "lldb/Core/Section.h"
25 #include "lldb/Core/State.h"
26 #include "lldb/Host/Host.h"
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Target/Target.h"
29 #include "lldb/Target/Thread.h"
30 
31 // Project includes
32 #include "ProcessMachCore.h"
33 #include "ThreadMachCore.h"
34 #include "StopInfoMachException.h"
35 
36 // Needed for the plug-in names for the dynamic loaders.
37 #include "lldb/Utility/SafeMachO.h"
38 
39 #include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h"
40 #include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
41 #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
42 
43 using namespace lldb;
44 using namespace lldb_private;
45 
46 ConstString
47 ProcessMachCore::GetPluginNameStatic()
48 {
49     static ConstString g_name("mach-o-core");
50     return g_name;
51 }
52 
53 const char *
54 ProcessMachCore::GetPluginDescriptionStatic()
55 {
56     return "Mach-O core file debugging plug-in.";
57 }
58 
59 void
60 ProcessMachCore::Terminate()
61 {
62     PluginManager::UnregisterPlugin (ProcessMachCore::CreateInstance);
63 }
64 
65 
66 lldb::ProcessSP
67 ProcessMachCore::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file)
68 {
69     lldb::ProcessSP process_sp;
70     if (crash_file)
71     {
72         const size_t header_size = sizeof(llvm::MachO::mach_header);
73         lldb::DataBufferSP data_sp (crash_file->ReadFileContents(0, header_size));
74         if (data_sp && data_sp->GetByteSize() == header_size)
75         {
76             DataExtractor data(data_sp, lldb::eByteOrderLittle, 4);
77 
78             lldb::offset_t data_offset = 0;
79             llvm::MachO::mach_header mach_header;
80             if (ObjectFileMachO::ParseHeader(data, &data_offset, mach_header))
81             {
82                 if (mach_header.filetype == llvm::MachO::MH_CORE)
83                     process_sp.reset(new ProcessMachCore (target, listener, *crash_file));
84             }
85         }
86 
87     }
88     return process_sp;
89 }
90 
91 bool
92 ProcessMachCore::CanDebug(Target &target, bool plugin_specified_by_name)
93 {
94     if (plugin_specified_by_name)
95         return true;
96 
97     // For now we are just making sure the file exists for a given module
98     if (!m_core_module_sp && m_core_file.Exists())
99     {
100         // Don't add the Target's architecture to the ModuleSpec - we may be working
101         // with a core file that doesn't have the correct cpusubtype in the header
102         // but we should still try to use it - ModuleSpecList::FindMatchingModuleSpec
103         // enforces a strict arch mach.
104         ModuleSpec core_module_spec(m_core_file);
105         Error error (ModuleList::GetSharedModule (core_module_spec,
106                                                   m_core_module_sp,
107                                                   NULL,
108                                                   NULL,
109                                                   NULL));
110 
111         if (m_core_module_sp)
112         {
113             const llvm::Triple &triple_ref = m_core_module_sp->GetArchitecture().GetTriple();
114             if (triple_ref.getVendor() == llvm::Triple::Apple)
115             {
116                 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
117                 if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile)
118                     return true;
119             }
120         }
121     }
122     return false;
123 }
124 
125 //----------------------------------------------------------------------
126 // ProcessMachCore constructor
127 //----------------------------------------------------------------------
128 ProcessMachCore::ProcessMachCore(Target& target, Listener &listener, const FileSpec &core_file) :
129     Process (target, listener),
130     m_core_aranges (),
131     m_core_module_sp (),
132     m_core_file (core_file),
133     m_dyld_addr (LLDB_INVALID_ADDRESS),
134     m_mach_kernel_addr (LLDB_INVALID_ADDRESS),
135     m_dyld_plugin_name ()
136 {
137 }
138 
139 //----------------------------------------------------------------------
140 // Destructor
141 //----------------------------------------------------------------------
142 ProcessMachCore::~ProcessMachCore()
143 {
144     Clear();
145     // We need to call finalize on the process before destroying ourselves
146     // to make sure all of the broadcaster cleanup goes as planned. If we
147     // destruct this class, then Process::~Process() might have problems
148     // trying to fully destroy the broadcaster.
149     Finalize();
150 }
151 
152 //----------------------------------------------------------------------
153 // PluginInterface
154 //----------------------------------------------------------------------
155 ConstString
156 ProcessMachCore::GetPluginName()
157 {
158     return GetPluginNameStatic();
159 }
160 
161 uint32_t
162 ProcessMachCore::GetPluginVersion()
163 {
164     return 1;
165 }
166 
167 bool
168 ProcessMachCore::GetDynamicLoaderAddress (lldb::addr_t addr)
169 {
170     llvm::MachO::mach_header header;
171     Error error;
172     if (DoReadMemory (addr, &header, sizeof(header), error) != sizeof(header))
173         return false;
174     if (header.magic == llvm::MachO::MH_CIGAM ||
175         header.magic == llvm::MachO::MH_CIGAM_64)
176     {
177         header.magic        = llvm::ByteSwap_32(header.magic);
178         header.cputype      = llvm::ByteSwap_32(header.cputype);
179         header.cpusubtype   = llvm::ByteSwap_32(header.cpusubtype);
180         header.filetype     = llvm::ByteSwap_32(header.filetype);
181         header.ncmds        = llvm::ByteSwap_32(header.ncmds);
182         header.sizeofcmds   = llvm::ByteSwap_32(header.sizeofcmds);
183         header.flags        = llvm::ByteSwap_32(header.flags);
184     }
185 
186     // TODO: swap header if needed...
187     //printf("0x%16.16" PRIx64 ": magic = 0x%8.8x, file_type= %u\n", vaddr, header.magic, header.filetype);
188     if (header.magic == llvm::MachO::MH_MAGIC ||
189         header.magic == llvm::MachO::MH_MAGIC_64)
190     {
191         // Check MH_EXECUTABLE to see if we can find the mach image
192         // that contains the shared library list. The dynamic loader
193         // (dyld) is what contains the list for user applications,
194         // and the mach kernel contains a global that has the list
195         // of kexts to load
196         switch (header.filetype)
197         {
198         case llvm::MachO::MH_DYLINKER:
199             //printf("0x%16.16" PRIx64 ": file_type = MH_DYLINKER\n", vaddr);
200             // Address of dyld "struct mach_header" in the core file
201             m_dyld_addr = addr;
202             return true;
203 
204         case llvm::MachO::MH_EXECUTE:
205             //printf("0x%16.16" PRIx64 ": file_type = MH_EXECUTE\n", vaddr);
206             // Check MH_EXECUTABLE file types to see if the dynamic link object flag
207             // is NOT set. If it isn't, then we have a mach_kernel.
208             if ((header.flags & llvm::MachO::MH_DYLDLINK) == 0)
209             {
210                 // Address of the mach kernel "struct mach_header" in the core file.
211                 m_mach_kernel_addr = addr;
212                 return true;
213             }
214             break;
215         }
216     }
217     return false;
218 }
219 
220 //----------------------------------------------------------------------
221 // Process Control
222 //----------------------------------------------------------------------
223 Error
224 ProcessMachCore::DoLoadCore ()
225 {
226     Error error;
227     if (!m_core_module_sp)
228     {
229         error.SetErrorString ("invalid core module");
230         return error;
231     }
232 
233     ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
234     if (core_objfile == NULL)
235     {
236         error.SetErrorString ("invalid core object file");
237         return error;
238     }
239 
240     if (core_objfile->GetNumThreadContexts() == 0)
241     {
242         error.SetErrorString ("core file doesn't contain any LC_THREAD load commands, or the LC_THREAD architecture is not supported in this lldb");
243         return error;
244     }
245 
246     SectionList *section_list = core_objfile->GetSectionList();
247     if (section_list == NULL)
248     {
249         error.SetErrorString ("core file has no sections");
250         return error;
251     }
252 
253     const uint32_t num_sections = section_list->GetNumSections(0);
254     if (num_sections == 0)
255     {
256         error.SetErrorString ("core file has no sections");
257         return error;
258     }
259 
260     SetCanJIT(false);
261 
262     llvm::MachO::mach_header header;
263     DataExtractor data (&header,
264                         sizeof(header),
265                         m_core_module_sp->GetArchitecture().GetByteOrder(),
266                         m_core_module_sp->GetArchitecture().GetAddressByteSize());
267 
268     bool ranges_are_sorted = true;
269     addr_t vm_addr = 0;
270     for (uint32_t i=0; i<num_sections; ++i)
271     {
272         Section *section = section_list->GetSectionAtIndex (i).get();
273         if (section)
274         {
275             lldb::addr_t section_vm_addr = section->GetFileAddress();
276             FileRange file_range (section->GetFileOffset(), section->GetFileSize());
277             VMRangeToFileOffset::Entry range_entry (section_vm_addr,
278                                                     section->GetByteSize(),
279                                                     file_range);
280 
281             if (vm_addr > section_vm_addr)
282                 ranges_are_sorted = false;
283             vm_addr = section->GetFileAddress();
284             VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
285 //            printf ("LC_SEGMENT[%u] arange=[0x%16.16" PRIx64 " - 0x%16.16" PRIx64 "), frange=[0x%8.8x - 0x%8.8x)\n",
286 //                    i,
287 //                    range_entry.GetRangeBase(),
288 //                    range_entry.GetRangeEnd(),
289 //                    range_entry.data.GetRangeBase(),
290 //                    range_entry.data.GetRangeEnd());
291 
292             if (last_entry &&
293                 last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
294                 last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase())
295             {
296                 last_entry->SetRangeEnd (range_entry.GetRangeEnd());
297                 last_entry->data.SetRangeEnd (range_entry.data.GetRangeEnd());
298                 //puts("combine");
299             }
300             else
301             {
302                 m_core_aranges.Append(range_entry);
303             }
304         }
305     }
306     if (!ranges_are_sorted)
307     {
308         m_core_aranges.Sort();
309     }
310 
311     if (m_dyld_addr == LLDB_INVALID_ADDRESS || m_mach_kernel_addr == LLDB_INVALID_ADDRESS)
312     {
313         // We need to locate the main executable in the memory ranges
314         // we have in the core file.  We need to search for both a user-process dyld binary
315         // and a kernel binary in memory; we must look at all the pages in the binary so
316         // we don't miss one or the other.  Step through all memory segments searching for
317         // a kernel binary and for a user process dyld -- we'll decide which to prefer
318         // later if both are present.
319 
320         const size_t num_core_aranges = m_core_aranges.GetSize();
321         for (size_t i = 0;
322              i < num_core_aranges && (m_dyld_addr == LLDB_INVALID_ADDRESS || m_mach_kernel_addr == LLDB_INVALID_ADDRESS);
323              ++i)
324         {
325             const VMRangeToFileOffset::Entry *entry = m_core_aranges.GetEntryAtIndex(i);
326             lldb::addr_t section_vm_addr_start = entry->GetRangeBase();
327             lldb::addr_t section_vm_addr_end = entry->GetRangeEnd();
328             for (lldb::addr_t section_vm_addr = section_vm_addr_start;
329                  section_vm_addr < section_vm_addr_end;
330                  section_vm_addr += 0x1000)
331             {
332                 GetDynamicLoaderAddress (section_vm_addr);
333             }
334         }
335     }
336 
337     // If we found both a user-process dyld and a kernel binary, we need to decide
338     // which to prefer.
339     if (GetCorefilePreference() == eKernelCorefile)
340     {
341         if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS)
342         {
343             m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
344         }
345         else if (m_dyld_addr != LLDB_INVALID_ADDRESS)
346         {
347             m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
348         }
349     }
350     else
351     {
352         if (m_dyld_addr != LLDB_INVALID_ADDRESS)
353         {
354             m_dyld_plugin_name = DynamicLoaderMacOSXDYLD::GetPluginNameStatic();
355         }
356         else if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS)
357         {
358             m_dyld_plugin_name = DynamicLoaderDarwinKernel::GetPluginNameStatic();
359         }
360     }
361 
362     // Even if the architecture is set in the target, we need to override
363     // it to match the core file which is always single arch.
364     ArchSpec arch (m_core_module_sp->GetArchitecture());
365     if (arch.GetCore() == ArchSpec::eCore_x86_32_i486)
366     {
367         arch.SetTriple ("i386", m_target.GetPlatform().get());
368     }
369     if (arch.IsValid())
370         m_target.SetArchitecture(arch);
371 
372     return error;
373 }
374 
375 lldb_private::DynamicLoader *
376 ProcessMachCore::GetDynamicLoader ()
377 {
378     if (m_dyld_ap.get() == NULL)
379         m_dyld_ap.reset (DynamicLoader::FindPlugin(this, m_dyld_plugin_name.IsEmpty() ? NULL : m_dyld_plugin_name.GetCString()));
380     return m_dyld_ap.get();
381 }
382 
383 bool
384 ProcessMachCore::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
385 {
386     if (old_thread_list.GetSize(false) == 0)
387     {
388         // Make up the thread the first time this is called so we can setup our one and only
389         // core thread state.
390         ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
391 
392         if (core_objfile)
393         {
394             const uint32_t num_threads = core_objfile->GetNumThreadContexts ();
395             for (lldb::tid_t tid = 0; tid < num_threads; ++tid)
396             {
397                 ThreadSP thread_sp(new ThreadMachCore (*this, tid));
398                 new_thread_list.AddThread (thread_sp);
399             }
400         }
401     }
402     else
403     {
404         const uint32_t num_threads = old_thread_list.GetSize(false);
405         for (uint32_t i=0; i<num_threads; ++i)
406             new_thread_list.AddThread (old_thread_list.GetThreadAtIndex (i, false));
407     }
408     return new_thread_list.GetSize(false) > 0;
409 }
410 
411 void
412 ProcessMachCore::RefreshStateAfterStop ()
413 {
414     // Let all threads recover from stopping and do any clean up based
415     // on the previous thread state (if any).
416     m_thread_list.RefreshStateAfterStop();
417     //SetThreadStopInfo (m_last_stop_packet);
418 }
419 
420 Error
421 ProcessMachCore::DoDestroy ()
422 {
423     return Error();
424 }
425 
426 //------------------------------------------------------------------
427 // Process Queries
428 //------------------------------------------------------------------
429 
430 bool
431 ProcessMachCore::IsAlive ()
432 {
433     return true;
434 }
435 
436 bool
437 ProcessMachCore::WarnBeforeDetach () const
438 {
439     return false;
440 }
441 
442 //------------------------------------------------------------------
443 // Process Memory
444 //------------------------------------------------------------------
445 size_t
446 ProcessMachCore::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
447 {
448     // Don't allow the caching that lldb_private::Process::ReadMemory does
449     // since in core files we have it all cached our our core file anyway.
450     return DoReadMemory (addr, buf, size, error);
451 }
452 
453 size_t
454 ProcessMachCore::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
455 {
456     ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
457 
458     if (core_objfile)
459     {
460         const VMRangeToFileOffset::Entry *core_memory_entry = m_core_aranges.FindEntryThatContains (addr);
461         if (core_memory_entry)
462         {
463             const addr_t offset = addr - core_memory_entry->GetRangeBase();
464             const addr_t bytes_left = core_memory_entry->GetRangeEnd() - addr;
465             size_t bytes_to_read = size;
466             if (bytes_to_read > bytes_left)
467                 bytes_to_read = bytes_left;
468             return core_objfile->CopyData (core_memory_entry->data.GetRangeBase() + offset, bytes_to_read, buf);
469         }
470         else
471         {
472             error.SetErrorStringWithFormat ("core file does not contain 0x%" PRIx64, addr);
473         }
474     }
475     return 0;
476 }
477 
478 void
479 ProcessMachCore::Clear()
480 {
481     m_thread_list.Clear();
482 }
483 
484 void
485 ProcessMachCore::Initialize()
486 {
487     static std::once_flag g_once_flag;
488 
489     std::call_once(g_once_flag, []() {
490         PluginManager::RegisterPlugin (GetPluginNameStatic(),
491                                        GetPluginDescriptionStatic(),
492                                        CreateInstance);
493     });
494 }
495 
496 addr_t
497 ProcessMachCore::GetImageInfoAddress()
498 {
499     // If we found both a user-process dyld and a kernel binary, we need to decide
500     // which to prefer.
501     if (GetCorefilePreference() == eKernelCorefile)
502     {
503         if (m_mach_kernel_addr != LLDB_INVALID_ADDRESS)
504         {
505             return m_mach_kernel_addr;
506         }
507         return m_dyld_addr;
508     }
509     else
510     {
511         if (m_dyld_addr != LLDB_INVALID_ADDRESS)
512         {
513             return m_dyld_addr;
514         }
515         return m_mach_kernel_addr;
516     }
517 }
518 
519 
520 lldb_private::ObjectFile *
521 ProcessMachCore::GetCoreObjectFile ()
522 {
523     return m_core_module_sp->GetObjectFile();
524 }
525