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