1 //===-- DynamicLoaderDarwinKernel.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 #include "lldb/lldb-python.h"
11 
12 #include "lldb/Breakpoint/StoppointCallbackContext.h"
13 #include "lldb/Core/DataBuffer.h"
14 #include "lldb/Core/DataBufferHeap.h"
15 #include "lldb/Core/Debugger.h"
16 #include "lldb/Core/Log.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/ModuleSpec.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/Section.h"
21 #include "lldb/Core/State.h"
22 #include "lldb/Host/Symbols.h"
23 #include "lldb/Symbol/ObjectFile.h"
24 #include "lldb/Target/RegisterContext.h"
25 #include "lldb/Target/StackFrame.h"
26 #include "lldb/Target/Target.h"
27 #include "lldb/Target/Thread.h"
28 #include "lldb/Target/ThreadPlanRunToAddress.h"
29 
30 
31 #include "DynamicLoaderDarwinKernel.h"
32 
33 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
34 #ifdef ENABLE_DEBUG_PRINTF
35 #include <stdio.h>
36 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
37 #else
38 #define DEBUG_PRINTF(fmt, ...)
39 #endif
40 
41 using namespace lldb;
42 using namespace lldb_private;
43 
44 // Progressively greater amounts of scanning we will allow
45 // For some targets very early in startup, we can't do any random reads of memory or we can crash the device
46 // so a setting is needed that can completely disable the KASLR scans.
47 
48 enum KASLRScanType
49 {
50     eKASLRScanNone = 0,         // No reading into the inferior at all
51     eKASLRScanLowgloAddresses,  // Check one word of memory for a possible kernel addr, then see if a kernel is there
52     eKASLRScanNearPC,           // Scan backwards from the current $pc looking for kernel; checking at 96 locations total
53     eKASLRScanExhaustiveScan    // Scan through the entire possible kernel address range looking for a kernel
54 };
55 
56 OptionEnumValueElement
57 g_kaslr_kernel_scan_enum_values[] =
58 {
59     { eKASLRScanNone,            "none",            "Do not read memory looking for a Darwin kernel when attaching." },
60     { eKASLRScanLowgloAddresses, "basic",           "Check for the Darwin kernel's load addr in the lowglo page (boot-args=debug) only." },
61     { eKASLRScanNearPC,          "fast-scan",       "Scan near the pc value on attach to find the Darwin kernel's load address."},
62     { eKASLRScanExhaustiveScan,  "exhaustive-scan", "Scan through the entire potential address range of Darwin kernel (only on 32-bit targets)."},
63     { 0, NULL, NULL }
64 };
65 
66 static PropertyDefinition
67 g_properties[] =
68 {
69     { "load-kexts" , OptionValue::eTypeBoolean, true, true, NULL, NULL, "Automatically loads kext images when attaching to a kernel." },
70     { "scan-type",   OptionValue::eTypeEnum,    true, eKASLRScanNearPC, NULL, g_kaslr_kernel_scan_enum_values, "Control how many reads lldb will make while searching for a Darwin kernel on attach." },
71     {  NULL        , OptionValue::eTypeInvalid, false, 0  , NULL, NULL, NULL  }
72 };
73 
74 enum {
75     ePropertyLoadKexts,
76     ePropertyScanType
77 };
78 
79 class DynamicLoaderDarwinKernelProperties : public Properties
80 {
81 public:
82 
83     static ConstString &
84     GetSettingName ()
85     {
86         static ConstString g_setting_name("darwin-kernel");
87         return g_setting_name;
88     }
89 
90     DynamicLoaderDarwinKernelProperties() :
91         Properties ()
92     {
93         m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
94         m_collection_sp->Initialize(g_properties);
95     }
96 
97     virtual
98     ~DynamicLoaderDarwinKernelProperties()
99     {
100     }
101 
102     bool
103     GetLoadKexts() const
104     {
105         const uint32_t idx = ePropertyLoadKexts;
106         return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
107     }
108 
109     KASLRScanType
110     GetScanType() const
111     {
112         const uint32_t idx = ePropertyScanType;
113         return (KASLRScanType) m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
114     }
115 
116 
117 };
118 
119 typedef STD_SHARED_PTR(DynamicLoaderDarwinKernelProperties) DynamicLoaderDarwinKernelPropertiesSP;
120 
121 static const DynamicLoaderDarwinKernelPropertiesSP &
122 GetGlobalProperties()
123 {
124     static DynamicLoaderDarwinKernelPropertiesSP g_settings_sp;
125     if (!g_settings_sp)
126         g_settings_sp.reset (new DynamicLoaderDarwinKernelProperties ());
127     return g_settings_sp;
128 }
129 
130 //----------------------------------------------------------------------
131 // Create an instance of this class. This function is filled into
132 // the plugin info class that gets handed out by the plugin factory and
133 // allows the lldb to instantiate an instance of this class.
134 //----------------------------------------------------------------------
135 DynamicLoader *
136 DynamicLoaderDarwinKernel::CreateInstance (Process* process, bool force)
137 {
138     if (!force)
139     {
140         // If the user provided an executable binary and it is not a kernel,
141         // this plugin should not create an instance.
142         Module* exe_module = process->GetTarget().GetExecutableModulePointer();
143         if (exe_module)
144         {
145             ObjectFile *object_file = exe_module->GetObjectFile();
146             if (object_file)
147             {
148                 if (object_file->GetStrata() != ObjectFile::eStrataKernel)
149                 {
150                     return NULL;
151                 }
152             }
153         }
154 
155         // If the target's architecture does not look like an Apple environment,
156         // this plugin should not create an instance.
157         const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple();
158         switch (triple_ref.getOS())
159         {
160             case llvm::Triple::Darwin:
161             case llvm::Triple::MacOSX:
162             case llvm::Triple::IOS:
163                 if (triple_ref.getVendor() != llvm::Triple::Apple)
164                 {
165                    return NULL;
166                 }
167                 break;
168             // If we have triple like armv7-unknown-unknown, we should try looking for a Darwin kernel.
169             case llvm::Triple::UnknownOS:
170                 break;
171             default:
172                 return NULL;
173                 break;
174         }
175     }
176 
177     // At this point if there is an ExecutableModule, it is a kernel and the Target is some variant of an Apple system.
178     // If the Process hasn't provided the kernel load address, we need to look around in memory to find it.
179 
180     addr_t kernel_load_address = process->GetImageInfoAddress();
181     if (kernel_load_address == LLDB_INVALID_ADDRESS)
182     {
183         kernel_load_address = SearchForKernelAtSameLoadAddr (process);
184         if (kernel_load_address == LLDB_INVALID_ADDRESS)
185         {
186             kernel_load_address = SearchForKernelWithDebugHints (process);
187             if (kernel_load_address == LLDB_INVALID_ADDRESS)
188             {
189                 kernel_load_address = SearchForKernelNearPC (process);
190                 if (kernel_load_address == LLDB_INVALID_ADDRESS)
191                 {
192                     kernel_load_address = SearchForKernelViaExhaustiveSearch (process);
193                 }
194             }
195         }
196     }
197 
198     if (kernel_load_address != LLDB_INVALID_ADDRESS)
199     {
200         process->SetCanJIT(false);
201         return new DynamicLoaderDarwinKernel (process, kernel_load_address);
202     }
203     return NULL;
204 }
205 
206 //----------------------------------------------------------------------
207 // Check if the kernel binary is loaded in memory without a slide.
208 // First verify that the ExecutableModule is a kernel before we proceed.
209 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
210 //----------------------------------------------------------------------
211 lldb::addr_t
212 DynamicLoaderDarwinKernel::SearchForKernelAtSameLoadAddr (Process *process)
213 {
214     Module *exe_module = process->GetTarget().GetExecutableModulePointer();
215     if (exe_module == NULL)
216         return LLDB_INVALID_ADDRESS;
217 
218     ObjectFile *exe_objfile = exe_module->GetObjectFile();
219     if (exe_objfile == NULL)
220         return LLDB_INVALID_ADDRESS;
221 
222     if (exe_objfile->GetType() != ObjectFile::eTypeExecutable || exe_objfile->GetStrata() != ObjectFile::eStrataKernel)
223         return LLDB_INVALID_ADDRESS;
224 
225     if (!exe_objfile->GetHeaderAddress().IsValid())
226         return LLDB_INVALID_ADDRESS;
227 
228     if (CheckForKernelImageAtAddress (exe_objfile->GetHeaderAddress().GetFileAddress(), process) == exe_module->GetUUID())
229         return exe_objfile->GetHeaderAddress().GetFileAddress();
230 
231     return LLDB_INVALID_ADDRESS;
232 }
233 
234 //----------------------------------------------------------------------
235 // If the debug flag is included in the boot-args nvram setting, the kernel's load address
236 // will be noted in the lowglo page at a fixed address
237 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
238 //----------------------------------------------------------------------
239 lldb::addr_t
240 DynamicLoaderDarwinKernel::SearchForKernelWithDebugHints (Process *process)
241 {
242     if (GetGlobalProperties()->GetScanType() == eKASLRScanNone)
243         return LLDB_INVALID_ADDRESS;
244 
245     Error read_err;
246     addr_t addr = LLDB_INVALID_ADDRESS;
247     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
248     {
249         addr = process->ReadUnsignedIntegerFromMemory (0xffffff8000002010ULL, 8, LLDB_INVALID_ADDRESS, read_err);
250     }
251     else
252     {
253         addr = process->ReadUnsignedIntegerFromMemory (0xffff0110, 4, LLDB_INVALID_ADDRESS, read_err);
254     }
255 
256     if (addr == 0)
257         addr = LLDB_INVALID_ADDRESS;
258 
259     if (addr != LLDB_INVALID_ADDRESS)
260     {
261         if (CheckForKernelImageAtAddress (addr, process).IsValid())
262             return addr;
263     }
264 
265     return LLDB_INVALID_ADDRESS;
266 }
267 
268 //----------------------------------------------------------------------
269 // If the kernel is currently executing when lldb attaches, and we don't have
270 // a better way of finding the kernel's load address, try searching backwards
271 // from the current pc value looking for the kernel's Mach header in memory.
272 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
273 //----------------------------------------------------------------------
274 lldb::addr_t
275 DynamicLoaderDarwinKernel::SearchForKernelNearPC (Process *process)
276 {
277     if (GetGlobalProperties()->GetScanType() == eKASLRScanNone
278         || GetGlobalProperties()->GetScanType() == eKASLRScanLowgloAddresses)
279     {
280         return LLDB_INVALID_ADDRESS;
281     }
282 
283     ThreadSP thread = process->GetThreadList().GetSelectedThread ();
284     if (thread.get() == NULL)
285         return LLDB_INVALID_ADDRESS;
286     addr_t pc = thread->GetRegisterContext ()->GetPC(LLDB_INVALID_ADDRESS);
287 
288     if (pc == LLDB_INVALID_ADDRESS)
289         return LLDB_INVALID_ADDRESS;
290 
291     addr_t kernel_range_low, kernel_range_high;
292     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
293     {
294         kernel_range_low = 1ULL << 63;
295         kernel_range_high = UINT64_MAX;
296     }
297     else
298     {
299         kernel_range_low = 1ULL << 31;
300         kernel_range_high = UINT32_MAX;
301     }
302 
303     // Outside the normal kernel address range, this is probably userland code running right now
304     if (pc < kernel_range_low)
305         LLDB_INVALID_ADDRESS;
306 
307     // The kernel will load at at one megabyte boundary (0x100000), or at that boundary plus
308     // an offset of one page (0x1000) or two, depending on the device.
309 
310     // Round the current pc down to the nearest one megabyte boundary - the place where we will start searching.
311     addr_t addr = pc & ~0xfffff;
312 
313     int i = 0;
314     while (i < 32 && pc >= kernel_range_low)
315     {
316         if (CheckForKernelImageAtAddress (addr, process).IsValid())
317             return addr;
318         if (CheckForKernelImageAtAddress (addr + 0x1000, process).IsValid())
319             return addr + 0x1000;
320         if (CheckForKernelImageAtAddress (addr + 0x2000, process).IsValid())
321             return addr + 0x2000;
322         i++;
323         addr -= 0x100000;
324     }
325 
326     return LLDB_INVALID_ADDRESS;
327 }
328 
329 //----------------------------------------------------------------------
330 // Scan through the valid address range for a kernel binary.
331 // This is uselessly slow in 64-bit environments so we don't even try it.
332 // This scan is not enabled by default even for 32-bit targets.
333 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
334 //----------------------------------------------------------------------
335 lldb::addr_t
336 DynamicLoaderDarwinKernel::SearchForKernelViaExhaustiveSearch (Process *process)
337 {
338     if (GetGlobalProperties()->GetScanType() != eKASLRScanExhaustiveScan)
339     {
340         return LLDB_INVALID_ADDRESS;
341     }
342 
343     addr_t kernel_range_low, kernel_range_high;
344     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
345     {
346         kernel_range_low = 1ULL << 63;
347         kernel_range_high = UINT64_MAX;
348     }
349     else
350     {
351         kernel_range_low = 1ULL << 31;
352         kernel_range_high = UINT32_MAX;
353     }
354 
355     // Stepping through memory at one-megabyte resolution looking for a kernel
356     // rarely works (fast enough) with a 64-bit address space -- for now, let's
357     // not even bother.  We may be attaching to something which *isn't* a kernel
358     // and we don't want to spin for minutes on-end looking for a kernel.
359     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
360         return LLDB_INVALID_ADDRESS;
361 
362     addr_t addr = kernel_range_low;
363 
364     while (addr >= kernel_range_low && addr < kernel_range_high)
365     {
366         if (CheckForKernelImageAtAddress (addr, process).IsValid())
367             return addr;
368         if (CheckForKernelImageAtAddress (addr + 0x1000, process).IsValid())
369             return addr + 0x1000;
370         if (CheckForKernelImageAtAddress (addr + 0x2000, process).IsValid())
371             return addr + 0x2000;
372         addr += 0x100000;
373     }
374     return LLDB_INVALID_ADDRESS;
375 }
376 
377 //----------------------------------------------------------------------
378 // Given an address in memory, look to see if there is a kernel image at that
379 // address.
380 // Returns a UUID; if a kernel was not found at that address, UUID.IsValid() will be false.
381 //----------------------------------------------------------------------
382 lldb_private::UUID
383 DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress (lldb::addr_t addr, Process *process)
384 {
385     if (addr == LLDB_INVALID_ADDRESS)
386         return UUID();
387 
388     // First try a quick test -- read the first 4 bytes and see if there is a valid Mach-O magic field there
389     // (the first field of the mach_header/mach_header_64 struct).
390 
391     Error read_error;
392     uint64_t result = process->ReadUnsignedIntegerFromMemory (addr, 4, LLDB_INVALID_ADDRESS, read_error);
393     if (result != llvm::MachO::HeaderMagic64
394         && result != llvm::MachO::HeaderMagic32
395         && result != llvm::MachO::HeaderMagic32Swapped
396         && result != llvm::MachO::HeaderMagic64Swapped)
397     {
398         return UUID();
399     }
400 
401     // Read the mach header and see whether it looks like a kernel
402     llvm::MachO::mach_header header;
403     if (process->DoReadMemory (addr, &header, sizeof(header), read_error) != sizeof(header))
404         return UUID();
405 
406     if (header.magic == llvm::MachO::HeaderMagic32Swapped ||
407         header.magic == llvm::MachO::HeaderMagic64Swapped)
408     {
409         header.magic        = llvm::ByteSwap_32(header.magic);
410         header.cputype      = llvm::ByteSwap_32(header.cputype);
411         header.cpusubtype   = llvm::ByteSwap_32(header.cpusubtype);
412         header.filetype     = llvm::ByteSwap_32(header.filetype);
413         header.ncmds        = llvm::ByteSwap_32(header.ncmds);
414         header.sizeofcmds   = llvm::ByteSwap_32(header.sizeofcmds);
415         header.flags        = llvm::ByteSwap_32(header.flags);
416     }
417 
418     // A kernel is an executable which does not have the dynamic link object flag set.
419     if (header.filetype == llvm::MachO::HeaderFileTypeExecutable
420         && (header.flags & llvm::MachO::HeaderFlagBitIsDynamicLinkObject) == 0)
421     {
422         // Create a full module to get the UUID
423         ModuleSP memory_module_sp = process->ReadModuleFromMemory (FileSpec ("temp_mach_kernel", false), addr);
424         if (!memory_module_sp.get())
425             return UUID();
426 
427         ObjectFile *exe_objfile = memory_module_sp->GetObjectFile();
428         if (exe_objfile == NULL)
429             return UUID();
430 
431         if (exe_objfile->GetType() == ObjectFile::eTypeExecutable && exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
432         {
433             return memory_module_sp->GetUUID();
434         }
435     }
436 
437     return UUID();
438 }
439 
440 //----------------------------------------------------------------------
441 // Constructor
442 //----------------------------------------------------------------------
443 DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel (Process* process, lldb::addr_t kernel_addr) :
444     DynamicLoader(process),
445     m_kernel_load_address (kernel_addr),
446     m_kernel(),
447     m_kext_summary_header_ptr_addr (),
448     m_kext_summary_header_addr (),
449     m_kext_summary_header (),
450     m_kext_summaries(),
451     m_mutex(Mutex::eMutexTypeRecursive),
452     m_break_id (LLDB_INVALID_BREAK_ID)
453 {
454 }
455 
456 //----------------------------------------------------------------------
457 // Destructor
458 //----------------------------------------------------------------------
459 DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel()
460 {
461     Clear(true);
462 }
463 
464 void
465 DynamicLoaderDarwinKernel::UpdateIfNeeded()
466 {
467     LoadKernelModuleIfNeeded();
468     SetNotificationBreakpointIfNeeded ();
469 }
470 //------------------------------------------------------------------
471 /// Called after attaching a process.
472 ///
473 /// Allow DynamicLoader plug-ins to execute some code after
474 /// attaching to a process.
475 //------------------------------------------------------------------
476 void
477 DynamicLoaderDarwinKernel::DidAttach ()
478 {
479     PrivateInitialize(m_process);
480     UpdateIfNeeded();
481 }
482 
483 //------------------------------------------------------------------
484 /// Called after attaching a process.
485 ///
486 /// Allow DynamicLoader plug-ins to execute some code after
487 /// attaching to a process.
488 //------------------------------------------------------------------
489 void
490 DynamicLoaderDarwinKernel::DidLaunch ()
491 {
492     PrivateInitialize(m_process);
493     UpdateIfNeeded();
494 }
495 
496 
497 //----------------------------------------------------------------------
498 // Clear out the state of this class.
499 //----------------------------------------------------------------------
500 void
501 DynamicLoaderDarwinKernel::Clear (bool clear_process)
502 {
503     Mutex::Locker locker(m_mutex);
504 
505     if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
506         m_process->ClearBreakpointSiteByID(m_break_id);
507 
508     if (clear_process)
509         m_process = NULL;
510     m_kernel.Clear(false);
511     m_kext_summary_header_ptr_addr.Clear();
512     m_kext_summary_header_addr.Clear();
513     m_kext_summaries.clear();
514     m_break_id = LLDB_INVALID_BREAK_ID;
515 }
516 
517 
518 bool
519 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::LoadImageAtFileAddress (Process *process)
520 {
521     if (IsLoaded())
522         return true;
523 
524     if (module_sp)
525     {
526         bool changed = false;
527         if (module_sp->SetLoadAddress (process->GetTarget(), 0, changed))
528             load_process_stop_id = process->GetStopID();
529     }
530     return false;
531 }
532 
533 bool
534 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::LoadImageUsingMemoryModule (Process *process)
535 {
536     if (IsLoaded())
537         return true;
538 
539     bool uuid_is_valid = uuid.IsValid();
540     bool memory_module_is_kernel = false;
541 
542     Target &target = process->GetTarget();
543     ModuleSP memory_module_sp;
544 
545     // If this is a kext and the user asked us to ignore kexts, don't try to load it.
546     if (kernel_image == false && GetGlobalProperties()->GetLoadKexts() == false)
547     {
548         return false;
549     }
550 
551     // Use the memory module as the module if we have one
552     if (address != LLDB_INVALID_ADDRESS)
553     {
554         FileSpec file_spec;
555         if (module_sp)
556             file_spec = module_sp->GetFileSpec();
557         else
558             file_spec.SetFile (name, false);
559 
560         memory_module_sp = process->ReadModuleFromMemory (file_spec, address);
561         if (memory_module_sp && !uuid_is_valid)
562         {
563             uuid = memory_module_sp->GetUUID();
564             uuid_is_valid = uuid.IsValid();
565         }
566         if (memory_module_sp
567             && memory_module_sp->GetObjectFile()
568             && memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable
569             && memory_module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel)
570         {
571             memory_module_is_kernel = true;
572             if (memory_module_sp->GetArchitecture().IsValid())
573             {
574                 target.SetArchitecture(memory_module_sp->GetArchitecture());
575             }
576         }
577     }
578 
579     if (!module_sp)
580     {
581         if (uuid_is_valid)
582         {
583             const ModuleList &target_images = target.GetImages();
584             module_sp = target_images.FindModule(uuid);
585 
586             if (!module_sp)
587             {
588                 ModuleSpec module_spec;
589                 module_spec.GetUUID() = uuid;
590                 module_spec.GetArchitecture() = target.GetArchitecture();
591 
592                 // For the kernel, we really do need an on-disk file copy of the
593                 // binary.
594                 bool force_symbols_search = false;
595                 if (memory_module_is_kernel)
596                 {
597                     force_symbols_search = true;
598                 }
599 
600                 if (Symbols::DownloadObjectAndSymbolFile (module_spec, force_symbols_search))
601                 {
602                     if (module_spec.GetFileSpec().Exists())
603                     {
604                         module_sp.reset(new Module (module_spec.GetFileSpec(), target.GetArchitecture()));
605                         if (module_sp.get() && module_sp->MatchesModuleSpec (module_spec))
606                         {
607                             ModuleList loaded_module_list;
608                             loaded_module_list.Append (module_sp);
609                             target.ModulesDidLoad (loaded_module_list);
610                         }
611                     }
612                 }
613 
614                 // Ask the Target to find this file on the local system, if possible.
615                 // This will search in the list of currently-loaded files, look in the
616                 // standard search paths on the system, and on a Mac it will try calling
617                 // the DebugSymbols framework with the UUID to find the binary via its
618                 // search methods.
619                 if (!module_sp)
620                 {
621                     module_sp = target.GetSharedModule (module_spec);
622                 }
623 
624                 // If we managed to find a module, append it to the target's list of images
625                 if (module_sp && module_sp->GetUUID() == memory_module_sp->GetUUID())
626                 {
627                     target.GetImages().Append(module_sp);
628                     if (memory_module_is_kernel && target.GetExecutableModulePointer() != module_sp.get())
629                     {
630                         target.SetExecutableModule (module_sp, false);
631                     }
632                 }
633             }
634         }
635     }
636 
637 
638     static ConstString g_section_name_LINKEDIT ("__LINKEDIT");
639 
640     if (memory_module_sp && module_sp)
641     {
642         if (module_sp->GetUUID() == memory_module_sp->GetUUID())
643         {
644             ObjectFile *ondisk_object_file = module_sp->GetObjectFile();
645             ObjectFile *memory_object_file = memory_module_sp->GetObjectFile();
646 
647             if (memory_object_file && ondisk_object_file)
648             {
649                 // Kexts are classified with a type of ObjectFile::eTypeSharedLibrary and
650                 // a strata of ObjectFile::eStrataKernel. Ignore __LINKEDIT for kexts
651                 const bool ignore_linkedit = ondisk_object_file->GetType() == ObjectFile::eTypeSharedLibrary;
652 
653                 SectionList *ondisk_section_list = ondisk_object_file->GetSectionList ();
654                 SectionList *memory_section_list = memory_object_file->GetSectionList ();
655                 if (memory_section_list && ondisk_section_list)
656                 {
657                     const uint32_t num_ondisk_sections = ondisk_section_list->GetSize();
658                     // There may be CTF sections in the memory image so we can't
659                     // always just compare the number of sections (which are actually
660                     // segments in mach-o parlance)
661                     uint32_t sect_idx = 0;
662 
663                     // Use the memory_module's addresses for each section to set the
664                     // file module's load address as appropriate.  We don't want to use
665                     // a single slide value for the entire kext - different segments may
666                     // be slid different amounts by the kext loader.
667 
668                     uint32_t num_sections_loaded = 0;
669                     for (sect_idx=0; sect_idx<num_ondisk_sections; ++sect_idx)
670                     {
671                         SectionSP ondisk_section_sp(ondisk_section_list->GetSectionAtIndex(sect_idx));
672                         if (ondisk_section_sp)
673                         {
674                             // Don't ever load __LINKEDIT as it may or may not be actually
675                             // mapped into memory and there is no current way to tell.
676                             // I filed rdar://problem/12851706 to track being able to tell
677                             // if the __LINKEDIT is actually mapped, but until then, we need
678                             // to not load the __LINKEDIT
679                             if (ignore_linkedit && ondisk_section_sp->GetName() == g_section_name_LINKEDIT)
680                                 continue;
681 
682                             const Section *memory_section = memory_section_list->FindSectionByName(ondisk_section_sp->GetName()).get();
683                             if (memory_section)
684                             {
685                                 target.GetSectionLoadList().SetSectionLoadAddress (ondisk_section_sp, memory_section->GetFileAddress());
686                                 ++num_sections_loaded;
687                             }
688                         }
689                     }
690                     if (num_sections_loaded > 0)
691                         load_process_stop_id = process->GetStopID();
692                     else
693                         module_sp.reset(); // No sections were loaded
694                 }
695                 else
696                     module_sp.reset(); // One or both section lists
697             }
698             else
699                 module_sp.reset(); // One or both object files missing
700         }
701         else
702             module_sp.reset(); // UUID mismatch
703     }
704 
705     bool is_loaded = IsLoaded();
706 
707     if (so_address.IsValid())
708     {
709         if (is_loaded)
710             so_address.SetLoadAddress (address, &target);
711         else
712             target.GetImages().ResolveFileAddress (address, so_address);
713 
714     }
715 
716     if (is_loaded && module_sp && memory_module_is_kernel)
717     {
718         Stream *s = &target.GetDebugger().GetOutputStream();
719         if (s)
720         {
721             char uuidbuf[64];
722             s->Printf ("Kernel UUID: %s\n", module_sp->GetUUID().GetAsCString(uuidbuf, sizeof (uuidbuf)));
723             s->Printf ("Load Address: 0x%" PRIx64 "\n", address);
724             if (module_sp->GetFileSpec().GetDirectory().IsEmpty())
725             {
726                 s->Printf ("Loaded kernel file %s\n", module_sp->GetFileSpec().GetFilename().AsCString());
727             }
728             else
729             {
730                 s->Printf ("Loaded kernel file %s/%s\n",
731                               module_sp->GetFileSpec().GetDirectory().AsCString(),
732                               module_sp->GetFileSpec().GetFilename().AsCString());
733             }
734             s->Flush ();
735         }
736     }
737     return is_loaded;
738 }
739 
740 uint32_t
741 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::GetAddressByteSize ()
742 {
743     if (module_sp)
744         return module_sp->GetArchitecture().GetAddressByteSize();
745     return 0;
746 }
747 
748 lldb::ByteOrder
749 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::GetByteOrder()
750 {
751     if (module_sp)
752         return module_sp->GetArchitecture().GetByteOrder();
753     return lldb::endian::InlHostByteOrder();
754 }
755 
756 lldb_private::ArchSpec
757 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::GetArchitecture () const
758 {
759     if (module_sp)
760         return module_sp->GetArchitecture();
761     return lldb_private::ArchSpec ();
762 }
763 
764 
765 //----------------------------------------------------------------------
766 // Load the kernel module and initialize the "m_kernel" member. Return
767 // true _only_ if the kernel is loaded the first time through (subsequent
768 // calls to this function should return false after the kernel has been
769 // already loaded).
770 //----------------------------------------------------------------------
771 void
772 DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded()
773 {
774     if (!m_kext_summary_header_ptr_addr.IsValid())
775     {
776         m_kernel.Clear(false);
777         m_kernel.module_sp = m_process->GetTarget().GetExecutableModule();
778         m_kernel.kernel_image = true;
779 
780         ConstString kernel_name("mach_kernel");
781         if (m_kernel.module_sp.get()
782             && m_kernel.module_sp->GetObjectFile()
783             && !m_kernel.module_sp->GetObjectFile()->GetFileSpec().GetFilename().IsEmpty())
784         {
785             kernel_name = m_kernel.module_sp->GetObjectFile()->GetFileSpec().GetFilename();
786         }
787         strncpy (m_kernel.name, kernel_name.AsCString(), sizeof(m_kernel.name));
788         m_kernel.name[sizeof (m_kernel.name) - 1] = '\0';
789 
790         if (m_kernel.address == LLDB_INVALID_ADDRESS)
791         {
792             m_kernel.address = m_kernel_load_address;
793             if (m_kernel.address == LLDB_INVALID_ADDRESS && m_kernel.module_sp)
794             {
795                 // We didn't get a hint from the process, so we will
796                 // try the kernel at the address that it exists at in
797                 // the file if we have one
798                 ObjectFile *kernel_object_file = m_kernel.module_sp->GetObjectFile();
799                 if (kernel_object_file)
800                 {
801                     addr_t load_address = kernel_object_file->GetHeaderAddress().GetLoadAddress(&m_process->GetTarget());
802                     addr_t file_address = kernel_object_file->GetHeaderAddress().GetFileAddress();
803                     if (load_address != LLDB_INVALID_ADDRESS && load_address != 0)
804                     {
805                         m_kernel.address = load_address;
806                         if (load_address != file_address)
807                         {
808                             // Don't accidentally relocate the kernel to the File address --
809                             // the Load address has already been set to its actual in-memory address.
810                             // Mark it as IsLoaded.
811                             m_kernel.load_process_stop_id = m_process->GetStopID();
812                         }
813                     }
814                     else
815                     {
816                         m_kernel.address = file_address;
817                     }
818                 }
819             }
820         }
821 
822         if (m_kernel.address != LLDB_INVALID_ADDRESS)
823         {
824             if (!m_kernel.LoadImageUsingMemoryModule (m_process))
825             {
826                 m_kernel.LoadImageAtFileAddress (m_process);
827             }
828         }
829 
830         if (m_kernel.IsLoaded() && m_kernel.module_sp)
831         {
832             static ConstString kext_summary_symbol ("gLoadedKextSummaries");
833             const Symbol *symbol = m_kernel.module_sp->FindFirstSymbolWithNameAndType (kext_summary_symbol, eSymbolTypeData);
834             if (symbol)
835             {
836                 m_kext_summary_header_ptr_addr = symbol->GetAddress();
837                 // Update all image infos
838                 ReadAllKextSummaries ();
839             }
840         }
841         else
842         {
843             m_kernel.Clear(false);
844         }
845     }
846 }
847 
848 //----------------------------------------------------------------------
849 // Static callback function that gets called when our DYLD notification
850 // breakpoint gets hit. We update all of our image infos and then
851 // let our super class DynamicLoader class decide if we should stop
852 // or not (based on global preference).
853 //----------------------------------------------------------------------
854 bool
855 DynamicLoaderDarwinKernel::BreakpointHitCallback (void *baton,
856                                                   StoppointCallbackContext *context,
857                                                   user_id_t break_id,
858                                                   user_id_t break_loc_id)
859 {
860     return static_cast<DynamicLoaderDarwinKernel*>(baton)->BreakpointHit (context, break_id, break_loc_id);
861 }
862 
863 bool
864 DynamicLoaderDarwinKernel::BreakpointHit (StoppointCallbackContext *context,
865                                           user_id_t break_id,
866                                           user_id_t break_loc_id)
867 {
868     LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
869     if (log)
870         log->Printf ("DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
871 
872     ReadAllKextSummaries ();
873 
874     if (log)
875         PutToLog(log.get());
876 
877     return GetStopWhenImagesChange();
878 }
879 
880 
881 bool
882 DynamicLoaderDarwinKernel::ReadKextSummaryHeader ()
883 {
884     Mutex::Locker locker(m_mutex);
885 
886     // the all image infos is already valid for this process stop ID
887 
888     m_kext_summaries.clear();
889     if (m_kext_summary_header_ptr_addr.IsValid())
890     {
891         const uint32_t addr_size = m_kernel.GetAddressByteSize ();
892         const ByteOrder byte_order = m_kernel.GetByteOrder();
893         Error error;
894         // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure
895         // which is currenty 4 uint32_t and a pointer.
896         uint8_t buf[24];
897         DataExtractor data (buf, sizeof(buf), byte_order, addr_size);
898         const size_t count = 4 * sizeof(uint32_t) + addr_size;
899         const bool prefer_file_cache = false;
900         if (m_process->GetTarget().ReadPointerFromMemory (m_kext_summary_header_ptr_addr,
901                                                           prefer_file_cache,
902                                                           error,
903                                                           m_kext_summary_header_addr))
904         {
905             // We got a valid address for our kext summary header and make sure it isn't NULL
906             if (m_kext_summary_header_addr.IsValid() &&
907                 m_kext_summary_header_addr.GetFileAddress() != 0)
908             {
909                 const size_t bytes_read = m_process->GetTarget().ReadMemory (m_kext_summary_header_addr, prefer_file_cache, buf, count, error);
910                 if (bytes_read == count)
911                 {
912                     lldb::offset_t offset = 0;
913                     m_kext_summary_header.version = data.GetU32(&offset);
914                     if (m_kext_summary_header.version >= 2)
915                     {
916                         m_kext_summary_header.entry_size = data.GetU32(&offset);
917                     }
918                     else
919                     {
920                         // Versions less than 2 didn't have an entry size, it was hard coded
921                         m_kext_summary_header.entry_size = KERNEL_MODULE_ENTRY_SIZE_VERSION_1;
922                     }
923                     m_kext_summary_header.entry_count = data.GetU32(&offset);
924                     return true;
925                 }
926             }
927         }
928     }
929     m_kext_summary_header_addr.Clear();
930     return false;
931 }
932 
933 
934 bool
935 DynamicLoaderDarwinKernel::ParseKextSummaries (const Address &kext_summary_addr,
936                                                uint32_t count)
937 {
938     OSKextLoadedKextSummary::collection kext_summaries;
939     LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
940     if (log)
941         log->Printf ("Adding %d modules.\n", count);
942 
943     Mutex::Locker locker(m_mutex);
944 
945     if (!ReadKextSummaries (kext_summary_addr, count, kext_summaries))
946         return false;
947 
948     Stream *s = &m_process->GetTarget().GetDebugger().GetOutputStream();
949     if (s)
950         s->Printf ("Loading %d kext modules ", count);
951     for (uint32_t i = 0; i < count; i++)
952     {
953         if (!kext_summaries[i].LoadImageUsingMemoryModule (m_process))
954             kext_summaries[i].LoadImageAtFileAddress (m_process);
955 
956         if (s)
957             s->Printf (".");
958 
959         if (log)
960             kext_summaries[i].PutToLog (log.get());
961     }
962     if (s)
963     {
964         s->Printf (" done.\n");
965         s->Flush ();
966     }
967 
968     bool return_value = AddModulesUsingImageInfos (kext_summaries);
969     return return_value;
970 }
971 
972 // Adds the modules in image_infos to m_kext_summaries.
973 // NB don't call this passing in m_kext_summaries.
974 
975 bool
976 DynamicLoaderDarwinKernel::AddModulesUsingImageInfos (OSKextLoadedKextSummary::collection &image_infos)
977 {
978     // Now add these images to the main list.
979     ModuleList loaded_module_list;
980 
981     for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
982     {
983         OSKextLoadedKextSummary &image_info = image_infos[idx];
984         m_kext_summaries.push_back(image_info);
985 
986         if (image_info.module_sp && m_process->GetStopID() == image_info.load_process_stop_id)
987             loaded_module_list.AppendIfNeeded (image_infos[idx].module_sp);
988     }
989 
990     m_process->GetTarget().ModulesDidLoad (loaded_module_list);
991     return true;
992 }
993 
994 
995 uint32_t
996 DynamicLoaderDarwinKernel::ReadKextSummaries (const Address &kext_summary_addr,
997                                               uint32_t image_infos_count,
998                                               OSKextLoadedKextSummary::collection &image_infos)
999 {
1000     const ByteOrder endian = m_kernel.GetByteOrder();
1001     const uint32_t addr_size = m_kernel.GetAddressByteSize();
1002 
1003     image_infos.resize(image_infos_count);
1004     const size_t count = image_infos.size() * m_kext_summary_header.entry_size;
1005     DataBufferHeap data(count, 0);
1006     Error error;
1007 
1008     const bool prefer_file_cache = false;
1009     const size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary_addr,
1010                                                                  prefer_file_cache,
1011                                                                  data.GetBytes(),
1012                                                                  data.GetByteSize(),
1013                                                                  error);
1014     if (bytes_read == count)
1015     {
1016 
1017         DataExtractor extractor (data.GetBytes(), data.GetByteSize(), endian, addr_size);
1018         uint32_t i=0;
1019         for (uint32_t kext_summary_offset = 0;
1020              i < image_infos.size() && extractor.ValidOffsetForDataOfSize(kext_summary_offset, m_kext_summary_header.entry_size);
1021              ++i, kext_summary_offset += m_kext_summary_header.entry_size)
1022         {
1023             lldb::offset_t offset = kext_summary_offset;
1024             const void *name_data = extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME);
1025             if (name_data == NULL)
1026                 break;
1027             memcpy (image_infos[i].name, name_data, KERNEL_MODULE_MAX_NAME);
1028             image_infos[i].uuid.SetBytes(extractor.GetData (&offset, 16));
1029             image_infos[i].address          = extractor.GetU64(&offset);
1030             if (!image_infos[i].so_address.SetLoadAddress (image_infos[i].address, &m_process->GetTarget()))
1031                 m_process->GetTarget().GetImages().ResolveFileAddress (image_infos[i].address, image_infos[i].so_address);
1032             image_infos[i].size             = extractor.GetU64(&offset);
1033             image_infos[i].version          = extractor.GetU64(&offset);
1034             image_infos[i].load_tag         = extractor.GetU32(&offset);
1035             image_infos[i].flags            = extractor.GetU32(&offset);
1036             if ((offset - kext_summary_offset) < m_kext_summary_header.entry_size)
1037             {
1038                 image_infos[i].reference_list = extractor.GetU64(&offset);
1039             }
1040             else
1041             {
1042                 image_infos[i].reference_list = 0;
1043             }
1044         }
1045         if (i < image_infos.size())
1046             image_infos.resize(i);
1047     }
1048     else
1049     {
1050         image_infos.clear();
1051     }
1052     return image_infos.size();
1053 }
1054 
1055 bool
1056 DynamicLoaderDarwinKernel::ReadAllKextSummaries ()
1057 {
1058     LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
1059 
1060     Mutex::Locker locker(m_mutex);
1061 
1062     if (ReadKextSummaryHeader ())
1063     {
1064         if (m_kext_summary_header.entry_count > 0 && m_kext_summary_header_addr.IsValid())
1065         {
1066             Address summary_addr (m_kext_summary_header_addr);
1067             summary_addr.Slide(m_kext_summary_header.GetSize());
1068             if (!ParseKextSummaries (summary_addr, m_kext_summary_header.entry_count))
1069             {
1070                 m_kext_summaries.clear();
1071             }
1072             return true;
1073         }
1074     }
1075     return false;
1076 }
1077 
1078 //----------------------------------------------------------------------
1079 // Dump an image info structure to the file handle provided.
1080 //----------------------------------------------------------------------
1081 void
1082 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::PutToLog (Log *log) const
1083 {
1084     if (log == NULL)
1085         return;
1086     const uint8_t *u = (uint8_t *)uuid.GetBytes();
1087 
1088     if (address == LLDB_INVALID_ADDRESS)
1089     {
1090         if (u)
1091         {
1092             log->Printf("\tuuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X name=\"%s\" (UNLOADED)",
1093                         u[ 0], u[ 1], u[ 2], u[ 3],
1094                         u[ 4], u[ 5], u[ 6], u[ 7],
1095                         u[ 8], u[ 9], u[10], u[11],
1096                         u[12], u[13], u[14], u[15],
1097                         name);
1098         }
1099         else
1100             log->Printf("\tname=\"%s\" (UNLOADED)", name);
1101     }
1102     else
1103     {
1104         if (u)
1105         {
1106             log->Printf("\taddr=0x%16.16" PRIx64 " size=0x%16.16" PRIx64 " version=0x%16.16" PRIx64 " load-tag=0x%8.8x flags=0x%8.8x ref-list=0x%16.16" PRIx64 " uuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X name=\"%s\"",
1107                         address, size, version, load_tag, flags, reference_list,
1108                         u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7],
1109                         u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15],
1110                         name);
1111         }
1112         else
1113         {
1114             log->Printf("\t[0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") version=0x%16.16" PRIx64 " load-tag=0x%8.8x flags=0x%8.8x ref-list=0x%16.16" PRIx64 " name=\"%s\"",
1115                         address, address+size, version, load_tag, flags, reference_list,
1116                         name);
1117         }
1118     }
1119 }
1120 
1121 //----------------------------------------------------------------------
1122 // Dump the _dyld_all_image_infos members and all current image infos
1123 // that we have parsed to the file handle provided.
1124 //----------------------------------------------------------------------
1125 void
1126 DynamicLoaderDarwinKernel::PutToLog(Log *log) const
1127 {
1128     if (log == NULL)
1129         return;
1130 
1131     Mutex::Locker locker(m_mutex);
1132     log->Printf("gLoadedKextSummaries = 0x%16.16" PRIx64 " { version=%u, entry_size=%u, entry_count=%u }",
1133                 m_kext_summary_header_addr.GetFileAddress(),
1134                 m_kext_summary_header.version,
1135                 m_kext_summary_header.entry_size,
1136                 m_kext_summary_header.entry_count);
1137 
1138     size_t i;
1139     const size_t count = m_kext_summaries.size();
1140     if (count > 0)
1141     {
1142         log->PutCString("Loaded:");
1143         for (i = 0; i<count; i++)
1144             m_kext_summaries[i].PutToLog(log);
1145     }
1146 }
1147 
1148 void
1149 DynamicLoaderDarwinKernel::PrivateInitialize(Process *process)
1150 {
1151     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1152     Clear(true);
1153     m_process = process;
1154 }
1155 
1156 void
1157 DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded ()
1158 {
1159     if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.module_sp)
1160     {
1161         DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1162 
1163 
1164         const bool internal_bp = true;
1165         const LazyBool skip_prologue = eLazyBoolNo;
1166         FileSpecList module_spec_list;
1167         module_spec_list.Append (m_kernel.module_sp->GetFileSpec());
1168         Breakpoint *bp = m_process->GetTarget().CreateBreakpoint (&module_spec_list,
1169                                                                   NULL,
1170                                                                   "OSKextLoadedKextSummariesUpdated",
1171                                                                   eFunctionNameTypeFull,
1172                                                                   skip_prologue,
1173                                                                   internal_bp).get();
1174 
1175         bp->SetCallback (DynamicLoaderDarwinKernel::BreakpointHitCallback, this, true);
1176         m_break_id = bp->GetID();
1177     }
1178 }
1179 
1180 //----------------------------------------------------------------------
1181 // Member function that gets called when the process state changes.
1182 //----------------------------------------------------------------------
1183 void
1184 DynamicLoaderDarwinKernel::PrivateProcessStateChanged (Process *process, StateType state)
1185 {
1186     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, StateAsCString(state));
1187     switch (state)
1188     {
1189     case eStateConnected:
1190     case eStateAttaching:
1191     case eStateLaunching:
1192     case eStateInvalid:
1193     case eStateUnloaded:
1194     case eStateExited:
1195     case eStateDetached:
1196         Clear(false);
1197         break;
1198 
1199     case eStateStopped:
1200         UpdateIfNeeded();
1201         break;
1202 
1203     case eStateRunning:
1204     case eStateStepping:
1205     case eStateCrashed:
1206     case eStateSuspended:
1207         break;
1208     }
1209 }
1210 
1211 ThreadPlanSP
1212 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
1213 {
1214     ThreadPlanSP thread_plan_sp;
1215     LogSP log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1216     if (log)
1217         log->Printf ("Could not find symbol for step through.");
1218     return thread_plan_sp;
1219 }
1220 
1221 Error
1222 DynamicLoaderDarwinKernel::CanLoadImage ()
1223 {
1224     Error error;
1225     error.SetErrorString("always unsafe to load or unload shared libraries in the darwin kernel");
1226     return error;
1227 }
1228 
1229 void
1230 DynamicLoaderDarwinKernel::Initialize()
1231 {
1232     PluginManager::RegisterPlugin (GetPluginNameStatic(),
1233                                    GetPluginDescriptionStatic(),
1234                                    CreateInstance,
1235                                    DebuggerInitialize);
1236 }
1237 
1238 void
1239 DynamicLoaderDarwinKernel::Terminate()
1240 {
1241     PluginManager::UnregisterPlugin (CreateInstance);
1242 }
1243 
1244 void
1245 DynamicLoaderDarwinKernel::DebuggerInitialize (lldb_private::Debugger &debugger)
1246 {
1247     if (!PluginManager::GetSettingForDynamicLoaderPlugin (debugger, DynamicLoaderDarwinKernelProperties::GetSettingName()))
1248     {
1249         const bool is_global_setting = true;
1250         PluginManager::CreateSettingForDynamicLoaderPlugin (debugger,
1251                                                             GetGlobalProperties()->GetValueProperties(),
1252                                                             ConstString ("Properties for the DynamicLoaderDarwinKernel plug-in."),
1253                                                             is_global_setting);
1254     }
1255 }
1256 
1257 const char *
1258 DynamicLoaderDarwinKernel::GetPluginNameStatic()
1259 {
1260     return "dynamic-loader.darwin-kernel";
1261 }
1262 
1263 const char *
1264 DynamicLoaderDarwinKernel::GetPluginDescriptionStatic()
1265 {
1266     return "Dynamic loader plug-in that watches for shared library loads/unloads in the MacOSX kernel.";
1267 }
1268 
1269 
1270 //------------------------------------------------------------------
1271 // PluginInterface protocol
1272 //------------------------------------------------------------------
1273 const char *
1274 DynamicLoaderDarwinKernel::GetPluginName()
1275 {
1276     return "DynamicLoaderDarwinKernel";
1277 }
1278 
1279 const char *
1280 DynamicLoaderDarwinKernel::GetShortPluginName()
1281 {
1282     return GetPluginNameStatic();
1283 }
1284 
1285 uint32_t
1286 DynamicLoaderDarwinKernel::GetPluginVersion()
1287 {
1288     return 1;
1289 }
1290 
1291 lldb::ByteOrder
1292 DynamicLoaderDarwinKernel::GetByteOrderFromMagic (uint32_t magic)
1293 {
1294     switch (magic)
1295     {
1296         case llvm::MachO::HeaderMagic32:
1297         case llvm::MachO::HeaderMagic64:
1298             return lldb::endian::InlHostByteOrder();
1299 
1300         case llvm::MachO::HeaderMagic32Swapped:
1301         case llvm::MachO::HeaderMagic64Swapped:
1302             if (lldb::endian::InlHostByteOrder() == lldb::eByteOrderBig)
1303                 return lldb::eByteOrderLittle;
1304             else
1305                 return lldb::eByteOrderBig;
1306 
1307         default:
1308             break;
1309     }
1310     return lldb::eByteOrderInvalid;
1311 }
1312 
1313