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 = SearchForDarwinKernel (process);
181     if (kernel_load_address != LLDB_INVALID_ADDRESS)
182     {
183         process->SetCanJIT(false);
184         return new DynamicLoaderDarwinKernel (process, kernel_load_address);
185     }
186     return NULL;
187 }
188 
189 lldb::addr_t
190 DynamicLoaderDarwinKernel::SearchForDarwinKernel (Process *process)
191 {
192     addr_t kernel_load_address = process->GetImageInfoAddress();
193     if (kernel_load_address == LLDB_INVALID_ADDRESS)
194     {
195         kernel_load_address = SearchForKernelAtSameLoadAddr (process);
196         if (kernel_load_address == LLDB_INVALID_ADDRESS)
197         {
198             kernel_load_address = SearchForKernelWithDebugHints (process);
199             if (kernel_load_address == LLDB_INVALID_ADDRESS)
200             {
201                 kernel_load_address = SearchForKernelNearPC (process);
202                 if (kernel_load_address == LLDB_INVALID_ADDRESS)
203                 {
204                     kernel_load_address = SearchForKernelViaExhaustiveSearch (process);
205                 }
206             }
207         }
208     }
209     return kernel_load_address;
210 }
211 
212 //----------------------------------------------------------------------
213 // Check if the kernel binary is loaded in memory without a slide.
214 // First verify that the ExecutableModule is a kernel before we proceed.
215 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
216 //----------------------------------------------------------------------
217 lldb::addr_t
218 DynamicLoaderDarwinKernel::SearchForKernelAtSameLoadAddr (Process *process)
219 {
220     Module *exe_module = process->GetTarget().GetExecutableModulePointer();
221     if (exe_module == NULL)
222         return LLDB_INVALID_ADDRESS;
223 
224     ObjectFile *exe_objfile = exe_module->GetObjectFile();
225     if (exe_objfile == NULL)
226         return LLDB_INVALID_ADDRESS;
227 
228     if (exe_objfile->GetType() != ObjectFile::eTypeExecutable || exe_objfile->GetStrata() != ObjectFile::eStrataKernel)
229         return LLDB_INVALID_ADDRESS;
230 
231     if (!exe_objfile->GetHeaderAddress().IsValid())
232         return LLDB_INVALID_ADDRESS;
233 
234     if (CheckForKernelImageAtAddress (exe_objfile->GetHeaderAddress().GetFileAddress(), process) == exe_module->GetUUID())
235         return exe_objfile->GetHeaderAddress().GetFileAddress();
236 
237     return LLDB_INVALID_ADDRESS;
238 }
239 
240 //----------------------------------------------------------------------
241 // If the debug flag is included in the boot-args nvram setting, the kernel's load address
242 // will be noted in the lowglo page at a fixed address
243 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
244 //----------------------------------------------------------------------
245 lldb::addr_t
246 DynamicLoaderDarwinKernel::SearchForKernelWithDebugHints (Process *process)
247 {
248     if (GetGlobalProperties()->GetScanType() == eKASLRScanNone)
249         return LLDB_INVALID_ADDRESS;
250 
251     Error read_err;
252     addr_t addr = LLDB_INVALID_ADDRESS;
253     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
254     {
255         addr = process->ReadUnsignedIntegerFromMemory (0xffffff8000002010ULL, 8, LLDB_INVALID_ADDRESS, read_err);
256     }
257     else
258     {
259         addr = process->ReadUnsignedIntegerFromMemory (0xffff0110, 4, LLDB_INVALID_ADDRESS, read_err);
260     }
261 
262     if (addr == 0)
263         addr = LLDB_INVALID_ADDRESS;
264 
265     if (addr != LLDB_INVALID_ADDRESS)
266     {
267         if (CheckForKernelImageAtAddress (addr, process).IsValid())
268             return addr;
269     }
270 
271     return LLDB_INVALID_ADDRESS;
272 }
273 
274 //----------------------------------------------------------------------
275 // If the kernel is currently executing when lldb attaches, and we don't have
276 // a better way of finding the kernel's load address, try searching backwards
277 // from the current pc value looking for the kernel's Mach header in memory.
278 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
279 //----------------------------------------------------------------------
280 lldb::addr_t
281 DynamicLoaderDarwinKernel::SearchForKernelNearPC (Process *process)
282 {
283     if (GetGlobalProperties()->GetScanType() == eKASLRScanNone
284         || GetGlobalProperties()->GetScanType() == eKASLRScanLowgloAddresses)
285     {
286         return LLDB_INVALID_ADDRESS;
287     }
288 
289     ThreadSP thread = process->GetThreadList().GetSelectedThread ();
290     if (thread.get() == NULL)
291         return LLDB_INVALID_ADDRESS;
292     addr_t pc = thread->GetRegisterContext ()->GetPC(LLDB_INVALID_ADDRESS);
293 
294     if (pc == LLDB_INVALID_ADDRESS)
295         return LLDB_INVALID_ADDRESS;
296 
297     addr_t kernel_range_low;
298     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
299     {
300         kernel_range_low = 1ULL << 63;
301     }
302     else
303     {
304         kernel_range_low = 1ULL << 31;
305     }
306 
307     // Outside the normal kernel address range, this is probably userland code running right now
308     if (pc < kernel_range_low)
309         return LLDB_INVALID_ADDRESS;
310 
311     // The kernel will load at at one megabyte boundary (0x100000), or at that boundary plus
312     // an offset of one page (0x1000) or two, depending on the device.
313 
314     // Round the current pc down to the nearest one megabyte boundary - the place where we will start searching.
315     addr_t addr = pc & ~0xfffff;
316 
317     int i = 0;
318     while (i < 32 && pc >= kernel_range_low)
319     {
320         if (CheckForKernelImageAtAddress (addr, process).IsValid())
321             return addr;
322         if (CheckForKernelImageAtAddress (addr + 0x1000, process).IsValid())
323             return addr + 0x1000;
324         if (CheckForKernelImageAtAddress (addr + 0x2000, process).IsValid())
325             return addr + 0x2000;
326         i++;
327         addr -= 0x100000;
328     }
329 
330     return LLDB_INVALID_ADDRESS;
331 }
332 
333 //----------------------------------------------------------------------
334 // Scan through the valid address range for a kernel binary.
335 // This is uselessly slow in 64-bit environments so we don't even try it.
336 // This scan is not enabled by default even for 32-bit targets.
337 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
338 //----------------------------------------------------------------------
339 lldb::addr_t
340 DynamicLoaderDarwinKernel::SearchForKernelViaExhaustiveSearch (Process *process)
341 {
342     if (GetGlobalProperties()->GetScanType() != eKASLRScanExhaustiveScan)
343     {
344         return LLDB_INVALID_ADDRESS;
345     }
346 
347     addr_t kernel_range_low, kernel_range_high;
348     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
349     {
350         kernel_range_low = 1ULL << 63;
351         kernel_range_high = UINT64_MAX;
352     }
353     else
354     {
355         kernel_range_low = 1ULL << 31;
356         kernel_range_high = UINT32_MAX;
357     }
358 
359     // Stepping through memory at one-megabyte resolution looking for a kernel
360     // rarely works (fast enough) with a 64-bit address space -- for now, let's
361     // not even bother.  We may be attaching to something which *isn't* a kernel
362     // and we don't want to spin for minutes on-end looking for a kernel.
363     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
364         return LLDB_INVALID_ADDRESS;
365 
366     addr_t addr = kernel_range_low;
367 
368     while (addr >= kernel_range_low && addr < kernel_range_high)
369     {
370         if (CheckForKernelImageAtAddress (addr, process).IsValid())
371             return addr;
372         if (CheckForKernelImageAtAddress (addr + 0x1000, process).IsValid())
373             return addr + 0x1000;
374         if (CheckForKernelImageAtAddress (addr + 0x2000, process).IsValid())
375             return addr + 0x2000;
376         addr += 0x100000;
377     }
378     return LLDB_INVALID_ADDRESS;
379 }
380 
381 //----------------------------------------------------------------------
382 // Given an address in memory, look to see if there is a kernel image at that
383 // address.
384 // Returns a UUID; if a kernel was not found at that address, UUID.IsValid() will be false.
385 //----------------------------------------------------------------------
386 lldb_private::UUID
387 DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress (lldb::addr_t addr, Process *process)
388 {
389     if (addr == LLDB_INVALID_ADDRESS)
390         return UUID();
391 
392     // First try a quick test -- read the first 4 bytes and see if there is a valid Mach-O magic field there
393     // (the first field of the mach_header/mach_header_64 struct).
394 
395     Error read_error;
396     uint64_t result = process->ReadUnsignedIntegerFromMemory (addr, 4, LLDB_INVALID_ADDRESS, read_error);
397     if (result != llvm::MachO::HeaderMagic64
398         && result != llvm::MachO::HeaderMagic32
399         && result != llvm::MachO::HeaderMagic32Swapped
400         && result != llvm::MachO::HeaderMagic64Swapped)
401     {
402         return UUID();
403     }
404 
405     // Read the mach header and see whether it looks like a kernel
406     llvm::MachO::mach_header header;
407     if (process->DoReadMemory (addr, &header, sizeof(header), read_error) != sizeof(header))
408         return UUID();
409 
410     if (header.magic == llvm::MachO::HeaderMagic32Swapped ||
411         header.magic == llvm::MachO::HeaderMagic64Swapped)
412     {
413         header.magic        = llvm::ByteSwap_32(header.magic);
414         header.cputype      = llvm::ByteSwap_32(header.cputype);
415         header.cpusubtype   = llvm::ByteSwap_32(header.cpusubtype);
416         header.filetype     = llvm::ByteSwap_32(header.filetype);
417         header.ncmds        = llvm::ByteSwap_32(header.ncmds);
418         header.sizeofcmds   = llvm::ByteSwap_32(header.sizeofcmds);
419         header.flags        = llvm::ByteSwap_32(header.flags);
420     }
421 
422     // A kernel is an executable which does not have the dynamic link object flag set.
423     if (header.filetype == llvm::MachO::HeaderFileTypeExecutable
424         && (header.flags & llvm::MachO::HeaderFlagBitIsDynamicLinkObject) == 0)
425     {
426         // Create a full module to get the UUID
427         ModuleSP memory_module_sp = process->ReadModuleFromMemory (FileSpec ("temp_mach_kernel", false), addr);
428         if (!memory_module_sp.get())
429             return UUID();
430 
431         ObjectFile *exe_objfile = memory_module_sp->GetObjectFile();
432         if (exe_objfile == NULL)
433             return UUID();
434 
435         if (exe_objfile->GetType() == ObjectFile::eTypeExecutable && exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
436         {
437             ArchSpec kernel_arch (eArchTypeMachO, header.cputype, header.cpusubtype);
438             if (!process->GetTarget().GetArchitecture().IsCompatibleMatch(kernel_arch))
439             {
440                 process->GetTarget().SetArchitecture (kernel_arch);
441             }
442             return memory_module_sp->GetUUID();
443         }
444     }
445 
446     return UUID();
447 }
448 
449 //----------------------------------------------------------------------
450 // Constructor
451 //----------------------------------------------------------------------
452 DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel (Process* process, lldb::addr_t kernel_addr) :
453     DynamicLoader(process),
454     m_kernel_load_address (kernel_addr),
455     m_kernel(),
456     m_kext_summary_header_ptr_addr (),
457     m_kext_summary_header_addr (),
458     m_kext_summary_header (),
459     m_known_kexts (),
460     m_mutex(Mutex::eMutexTypeRecursive),
461     m_break_id (LLDB_INVALID_BREAK_ID)
462 {
463     PlatformSP platform_sp(Platform::FindPlugin (process, "darwin-kernel"));
464     // Only select the darwin-kernel Platform if we've been asked to load kexts.
465     // It can take some time to scan over all of the kext info.plists and that
466     // shouldn't be done if kext loading is explicitly disabled.
467     if (platform_sp.get() && GetGlobalProperties()->GetLoadKexts())
468     {
469         process->GetTarget().SetPlatform (platform_sp);
470     }
471 }
472 
473 //----------------------------------------------------------------------
474 // Destructor
475 //----------------------------------------------------------------------
476 DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel()
477 {
478     Clear(true);
479 }
480 
481 void
482 DynamicLoaderDarwinKernel::UpdateIfNeeded()
483 {
484     LoadKernelModuleIfNeeded();
485     SetNotificationBreakpointIfNeeded ();
486 }
487 //------------------------------------------------------------------
488 /// Called after attaching a process.
489 ///
490 /// Allow DynamicLoader plug-ins to execute some code after
491 /// attaching to a process.
492 //------------------------------------------------------------------
493 void
494 DynamicLoaderDarwinKernel::DidAttach ()
495 {
496     PrivateInitialize(m_process);
497     UpdateIfNeeded();
498 }
499 
500 //------------------------------------------------------------------
501 /// Called after attaching a process.
502 ///
503 /// Allow DynamicLoader plug-ins to execute some code after
504 /// attaching to a process.
505 //------------------------------------------------------------------
506 void
507 DynamicLoaderDarwinKernel::DidLaunch ()
508 {
509     PrivateInitialize(m_process);
510     UpdateIfNeeded();
511 }
512 
513 
514 //----------------------------------------------------------------------
515 // Clear out the state of this class.
516 //----------------------------------------------------------------------
517 void
518 DynamicLoaderDarwinKernel::Clear (bool clear_process)
519 {
520     Mutex::Locker locker(m_mutex);
521 
522     if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
523         m_process->ClearBreakpointSiteByID(m_break_id);
524 
525     if (clear_process)
526         m_process = NULL;
527     m_kernel.Clear();
528     m_known_kexts.clear();
529     m_kext_summary_header_ptr_addr.Clear();
530     m_kext_summary_header_addr.Clear();
531     m_break_id = LLDB_INVALID_BREAK_ID;
532 }
533 
534 
535 bool
536 DynamicLoaderDarwinKernel::KextImageInfo::LoadImageAtFileAddress (Process *process)
537 {
538     if (IsLoaded())
539         return true;
540 
541     if (m_module_sp)
542     {
543         bool changed = false;
544         if (m_module_sp->SetLoadAddress (process->GetTarget(), 0, changed))
545             m_load_process_stop_id = process->GetStopID();
546     }
547     return false;
548 }
549 
550 void
551 DynamicLoaderDarwinKernel::KextImageInfo::SetModule (ModuleSP module_sp)
552 {
553     m_module_sp = module_sp;
554     if (module_sp.get() && module_sp->GetObjectFile())
555     {
556         if (module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable
557             && module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel)
558         {
559             m_kernel_image = true;
560         }
561         else
562         {
563             m_kernel_image = false;
564         }
565     }
566 }
567 
568 ModuleSP
569 DynamicLoaderDarwinKernel::KextImageInfo::GetModule ()
570 {
571     return m_module_sp;
572 }
573 
574 void
575 DynamicLoaderDarwinKernel::KextImageInfo::SetLoadAddress (addr_t load_addr)
576 {
577     m_load_address = load_addr;
578 }
579 
580 addr_t
581 DynamicLoaderDarwinKernel::KextImageInfo::GetLoadAddress () const
582 {
583     return m_load_address;
584 }
585 
586 uint64_t
587 DynamicLoaderDarwinKernel::KextImageInfo::GetSize () const
588 {
589     return m_size;
590 }
591 
592 void
593 DynamicLoaderDarwinKernel::KextImageInfo::SetSize (uint64_t size)
594 {
595     m_size = size;
596 }
597 
598 uint32_t
599 DynamicLoaderDarwinKernel::KextImageInfo::GetProcessStopId () const
600 {
601     return m_load_process_stop_id;
602 }
603 
604 void
605 DynamicLoaderDarwinKernel::KextImageInfo::SetProcessStopId (uint32_t stop_id)
606 {
607     m_load_process_stop_id = stop_id;
608 }
609 
610 bool
611 DynamicLoaderDarwinKernel::KextImageInfo::operator== (const KextImageInfo &rhs)
612 {
613     if (m_uuid.IsValid() || rhs.GetUUID().IsValid())
614     {
615         if (m_uuid == rhs.GetUUID())
616         {
617             return true;
618         }
619         return false;
620     }
621 
622     if (m_name == rhs.GetName() && m_load_address == rhs.GetLoadAddress())
623         return true;
624 
625     return false;
626 }
627 
628 void
629 DynamicLoaderDarwinKernel::KextImageInfo::SetName (const char *name)
630 {
631     m_name = name;
632 }
633 
634 std::string
635 DynamicLoaderDarwinKernel::KextImageInfo::GetName () const
636 {
637     return m_name;
638 }
639 
640 void
641 DynamicLoaderDarwinKernel::KextImageInfo::SetUUID (const UUID &uuid)
642 {
643     m_uuid = uuid;
644 }
645 
646 UUID
647 DynamicLoaderDarwinKernel::KextImageInfo::GetUUID () const
648 {
649     return m_uuid;
650 }
651 
652 // Given the m_load_address from the kext summaries, and a UUID, try to create an in-memory
653 // Module at that address.  Require that the MemoryModule have a matching UUID and detect
654 // if this MemoryModule is a kernel or a kext.
655 //
656 // Returns true if m_memory_module_sp is now set to a valid Module.
657 
658 bool
659 DynamicLoaderDarwinKernel::KextImageInfo::ReadMemoryModule (Process *process)
660 {
661     if (m_memory_module_sp.get() != NULL)
662         return true;
663     if (m_load_address == LLDB_INVALID_ADDRESS)
664         return false;
665 
666     FileSpec file_spec;
667     file_spec.SetFile (m_name.c_str(), false);
668 
669     ModuleSP memory_module_sp = process->ReadModuleFromMemory (file_spec, m_load_address);
670 
671     if (memory_module_sp.get() == NULL)
672         return false;
673 
674     bool is_kernel = false;
675     if (memory_module_sp->GetObjectFile())
676     {
677         if (memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable
678             && memory_module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel)
679         {
680             is_kernel = true;
681         }
682         else if (memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeSharedLibrary)
683         {
684             is_kernel = false;
685         }
686     }
687 
688     // If this is a kext, and the kernel specified what UUID we should find at this
689     // load address, require that the memory module have a matching UUID or something
690     // has gone wrong and we should discard it.
691     if (m_uuid.IsValid())
692     {
693         if (m_uuid != memory_module_sp->GetUUID())
694         {
695             return false;
696         }
697     }
698 
699     // If the in-memory Module has a UUID, let's use that.
700     if (!m_uuid.IsValid() && memory_module_sp->GetUUID().IsValid())
701     {
702         m_uuid = memory_module_sp->GetUUID();
703     }
704 
705     m_memory_module_sp = memory_module_sp;
706     m_kernel_image = is_kernel;
707     if (is_kernel)
708     {
709         if (memory_module_sp->GetArchitecture().IsValid())
710         {
711             process->GetTarget().SetArchitecture(memory_module_sp->GetArchitecture());
712         }
713         if (m_uuid.IsValid())
714         {
715             Module* exe_module = process->GetTarget().GetExecutableModulePointer();
716             if (exe_module && exe_module->GetUUID().IsValid())
717             {
718                 if (m_uuid != exe_module->GetUUID())
719                 {
720                     Stream *s = &process->GetTarget().GetDebugger().GetOutputStream();
721                     if (s)
722                     {
723                         char memory_module_uuidbuf[64];
724                         char exe_module_uuidbuf[64];
725                         s->Printf ("warning: Host-side kernel file has Mach-O UUID of %s but remote kernel has a UUID of %s -- a mismatched kernel file will result in a poor debugger experience.\n",
726                                    exe_module->GetUUID().GetAsCString(exe_module_uuidbuf, sizeof (exe_module_uuidbuf)),
727                                    m_uuid.GetAsCString(memory_module_uuidbuf, sizeof (memory_module_uuidbuf)));
728                         s->Flush ();
729                     }
730                 }
731             }
732         }
733     }
734 
735     return true;
736 }
737 
738 bool
739 DynamicLoaderDarwinKernel::KextImageInfo::IsKernel () const
740 {
741     return m_kernel_image == true;
742 }
743 
744 void
745 DynamicLoaderDarwinKernel::KextImageInfo::SetIsKernel (bool is_kernel)
746 {
747     m_kernel_image = is_kernel;
748 }
749 
750 bool
751 DynamicLoaderDarwinKernel::KextImageInfo::LoadImageUsingMemoryModule (Process *process)
752 {
753     if (IsLoaded())
754         return true;
755 
756 
757     Target &target = process->GetTarget();
758 
759     // If we don't have / can't create a memory module for this kext, don't try to load it - we won't
760     // have the correct segment load addresses.
761     if (!ReadMemoryModule (process))
762     {
763         return false;
764     }
765 
766     bool uuid_is_valid = m_uuid.IsValid();
767 
768     if (IsKernel() && uuid_is_valid && m_memory_module_sp.get())
769     {
770         Stream *s = &target.GetDebugger().GetOutputStream();
771         if (s)
772         {
773             char uuidbuf[64];
774             s->Printf ("Kernel UUID: %s\n", m_memory_module_sp->GetUUID().GetAsCString(uuidbuf, sizeof (uuidbuf)));
775             s->Printf ("Load Address: 0x%" PRIx64 "\n", m_load_address);
776         }
777     }
778 
779     if (!m_module_sp)
780     {
781         // See if the kext has already been loaded into the target, probably by the user doing target modules add.
782         const ModuleList &target_images = target.GetImages();
783         m_module_sp = target_images.FindModule(m_uuid);
784 
785         // Search for the kext on the local filesystem via the UUID
786         if (!m_module_sp && uuid_is_valid)
787         {
788             ModuleSpec module_spec;
789             module_spec.GetUUID() = m_uuid;
790             module_spec.GetArchitecture() = target.GetArchitecture();
791 
792             // For the kernel, we really do need an on-disk file copy of the binary to do anything useful.
793             // This will force a clal to
794             if (IsKernel())
795             {
796                 if (Symbols::DownloadObjectAndSymbolFile (module_spec, true))
797                 {
798                     if (module_spec.GetFileSpec().Exists())
799                     {
800                         m_module_sp.reset(new Module (module_spec.GetFileSpec(), target.GetArchitecture()));
801                         if (m_module_sp.get() && m_module_sp->MatchesModuleSpec (module_spec))
802                         {
803                             ModuleList loaded_module_list;
804                             loaded_module_list.Append (m_module_sp);
805                             target.ModulesDidLoad (loaded_module_list);
806                         }
807                     }
808                 }
809             }
810 
811             // If the current platform is PlatformDarwinKernel, create a ModuleSpec with the filename set
812             // to be the bundle ID for this kext, e.g. "com.apple.filesystems.msdosfs", and ask the platform
813             // to find it.
814             PlatformSP platform_sp (target.GetPlatform());
815             if (platform_sp)
816             {
817                 const char *pname = platform_sp->GetShortPluginName();
818                 if (pname && strcmp (pname, "darwin-kernel") == 0)
819                 {
820                     ModuleSpec kext_bundle_module_spec(module_spec);
821                     FileSpec kext_filespec(m_name.c_str(), false);
822                     kext_bundle_module_spec.GetFileSpec() = kext_filespec;
823                     platform_sp->GetSharedModule (kext_bundle_module_spec, m_module_sp, &target.GetExecutableSearchPaths(), NULL, NULL);
824                 }
825             }
826 
827             // Ask the Target to find this file on the local system, if possible.
828             // This will search in the list of currently-loaded files, look in the
829             // standard search paths on the system, and on a Mac it will try calling
830             // the DebugSymbols framework with the UUID to find the binary via its
831             // search methods.
832             if (!m_module_sp)
833             {
834                 m_module_sp = target.GetSharedModule (module_spec);
835             }
836 
837             if (IsKernel() && !m_module_sp)
838             {
839                 Stream *s = &target.GetDebugger().GetOutputStream();
840                 if (s)
841                 {
842                     s->Printf ("WARNING: Unable to locate kernel binary on the debugger system.\n");
843                 }
844             }
845         }
846 
847         // If we managed to find a module, append it to the target's list of images.
848         // If we also have a memory module, require that they have matching UUIDs
849         if (m_module_sp)
850         {
851             bool uuid_match_ok = true;
852             if (m_memory_module_sp)
853             {
854                 if (m_module_sp->GetUUID() != m_memory_module_sp->GetUUID())
855                 {
856                     uuid_match_ok = false;
857                 }
858             }
859             if (uuid_match_ok)
860             {
861                 target.GetImages().AppendIfNeeded(m_module_sp);
862                 if (IsKernel() && target.GetExecutableModulePointer() != m_module_sp.get())
863                 {
864                     target.SetExecutableModule (m_module_sp, false);
865                 }
866             }
867         }
868     }
869 
870     if (!m_module_sp && !IsKernel() && m_uuid.IsValid() && !m_name.empty())
871     {
872         Stream *s = &target.GetDebugger().GetOutputStream();
873         if (s)
874         {
875             char uuidbuf[64];
876             s->Printf ("warning: Can't find binary/dSYM for %s (%s)\n",
877                        m_name.c_str(), m_uuid.GetAsCString(uuidbuf, sizeof (uuidbuf)));
878         }
879     }
880 
881     static ConstString g_section_name_LINKEDIT ("__LINKEDIT");
882 
883     if (m_memory_module_sp && m_module_sp)
884     {
885         if (m_module_sp->GetUUID() == m_memory_module_sp->GetUUID())
886         {
887             ObjectFile *ondisk_object_file = m_module_sp->GetObjectFile();
888             ObjectFile *memory_object_file = m_memory_module_sp->GetObjectFile();
889 
890             if (memory_object_file && ondisk_object_file)
891             {
892                 // The memory_module for kexts may have an invalid __LINKEDIT seg; skip it.
893                 const bool ignore_linkedit = !IsKernel ();
894 
895                 SectionList *ondisk_section_list = ondisk_object_file->GetSectionList ();
896                 SectionList *memory_section_list = memory_object_file->GetSectionList ();
897                 if (memory_section_list && ondisk_section_list)
898                 {
899                     const uint32_t num_ondisk_sections = ondisk_section_list->GetSize();
900                     // There may be CTF sections in the memory image so we can't
901                     // always just compare the number of sections (which are actually
902                     // segments in mach-o parlance)
903                     uint32_t sect_idx = 0;
904 
905                     // Use the memory_module's addresses for each section to set the
906                     // file module's load address as appropriate.  We don't want to use
907                     // a single slide value for the entire kext - different segments may
908                     // be slid different amounts by the kext loader.
909 
910                     uint32_t num_sections_loaded = 0;
911                     for (sect_idx=0; sect_idx<num_ondisk_sections; ++sect_idx)
912                     {
913                         SectionSP ondisk_section_sp(ondisk_section_list->GetSectionAtIndex(sect_idx));
914                         if (ondisk_section_sp)
915                         {
916                             // Don't ever load __LINKEDIT as it may or may not be actually
917                             // mapped into memory and there is no current way to tell.
918                             // I filed rdar://problem/12851706 to track being able to tell
919                             // if the __LINKEDIT is actually mapped, but until then, we need
920                             // to not load the __LINKEDIT
921                             if (ignore_linkedit && ondisk_section_sp->GetName() == g_section_name_LINKEDIT)
922                                 continue;
923 
924                             const Section *memory_section = memory_section_list->FindSectionByName(ondisk_section_sp->GetName()).get();
925                             if (memory_section)
926                             {
927                                 target.GetSectionLoadList().SetSectionLoadAddress (ondisk_section_sp, memory_section->GetFileAddress());
928                                 ++num_sections_loaded;
929                             }
930                         }
931                     }
932                     if (num_sections_loaded > 0)
933                         m_load_process_stop_id = process->GetStopID();
934                     else
935                         m_module_sp.reset(); // No sections were loaded
936                 }
937                 else
938                     m_module_sp.reset(); // One or both section lists
939             }
940             else
941                 m_module_sp.reset(); // One or both object files missing
942         }
943         else
944             m_module_sp.reset(); // UUID mismatch
945     }
946 
947     bool is_loaded = IsLoaded();
948 
949     if (is_loaded && m_module_sp && IsKernel())
950     {
951         Stream *s = &target.GetDebugger().GetOutputStream();
952         if (s)
953         {
954             ObjectFile *kernel_object_file = m_module_sp->GetObjectFile();
955             if (kernel_object_file)
956             {
957                 addr_t file_address = kernel_object_file->GetHeaderAddress().GetFileAddress();
958                 if (m_load_address != LLDB_INVALID_ADDRESS && file_address != LLDB_INVALID_ADDRESS)
959                 {
960                     s->Printf ("Kernel slid 0x%" PRIx64 " in memory.\n", m_load_address - file_address);
961                 }
962             }
963             {
964                 s->Printf ("Loaded kernel file %s\n",
965                            m_module_sp->GetFileSpec().GetPath().c_str());
966             }
967             s->Flush ();
968         }
969     }
970     return is_loaded;
971 }
972 
973 uint32_t
974 DynamicLoaderDarwinKernel::KextImageInfo::GetAddressByteSize ()
975 {
976     if (m_memory_module_sp)
977         return m_memory_module_sp->GetArchitecture().GetAddressByteSize();
978     if (m_module_sp)
979         return m_module_sp->GetArchitecture().GetAddressByteSize();
980     return 0;
981 }
982 
983 lldb::ByteOrder
984 DynamicLoaderDarwinKernel::KextImageInfo::GetByteOrder()
985 {
986     if (m_memory_module_sp)
987         return m_memory_module_sp->GetArchitecture().GetByteOrder();
988     if (m_module_sp)
989         return m_module_sp->GetArchitecture().GetByteOrder();
990     return lldb::endian::InlHostByteOrder();
991 }
992 
993 lldb_private::ArchSpec
994 DynamicLoaderDarwinKernel::KextImageInfo::GetArchitecture () const
995 {
996     if (m_memory_module_sp)
997         return m_memory_module_sp->GetArchitecture();
998     if (m_module_sp)
999         return m_module_sp->GetArchitecture();
1000     return lldb_private::ArchSpec ();
1001 }
1002 
1003 
1004 //----------------------------------------------------------------------
1005 // Load the kernel module and initialize the "m_kernel" member. Return
1006 // true _only_ if the kernel is loaded the first time through (subsequent
1007 // calls to this function should return false after the kernel has been
1008 // already loaded).
1009 //----------------------------------------------------------------------
1010 void
1011 DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded()
1012 {
1013     if (!m_kext_summary_header_ptr_addr.IsValid())
1014     {
1015         m_kernel.Clear();
1016         m_kernel.SetModule (m_process->GetTarget().GetExecutableModule());
1017         m_kernel.SetIsKernel(true);
1018 
1019         ConstString kernel_name("mach_kernel");
1020         if (m_kernel.GetModule().get()
1021             && m_kernel.GetModule()->GetObjectFile()
1022             && !m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename().IsEmpty())
1023         {
1024             kernel_name = m_kernel.GetModule()->GetObjectFile()->GetFileSpec().GetFilename();
1025         }
1026         m_kernel.SetName (kernel_name.AsCString());
1027 
1028         if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS)
1029         {
1030             m_kernel.SetLoadAddress(m_kernel_load_address);
1031             if (m_kernel.GetLoadAddress() == LLDB_INVALID_ADDRESS && m_kernel.GetModule())
1032             {
1033                 // We didn't get a hint from the process, so we will
1034                 // try the kernel at the address that it exists at in
1035                 // the file if we have one
1036                 ObjectFile *kernel_object_file = m_kernel.GetModule()->GetObjectFile();
1037                 if (kernel_object_file)
1038                 {
1039                     addr_t load_address = kernel_object_file->GetHeaderAddress().GetLoadAddress(&m_process->GetTarget());
1040                     addr_t file_address = kernel_object_file->GetHeaderAddress().GetFileAddress();
1041                     if (load_address != LLDB_INVALID_ADDRESS && load_address != 0)
1042                     {
1043                         m_kernel.SetLoadAddress (load_address);
1044                         if (load_address != file_address)
1045                         {
1046                             // Don't accidentally relocate the kernel to the File address --
1047                             // the Load address has already been set to its actual in-memory address.
1048                             // Mark it as IsLoaded.
1049                             m_kernel.SetProcessStopId (m_process->GetStopID());
1050                         }
1051                     }
1052                     else
1053                     {
1054                         m_kernel.SetLoadAddress(file_address);
1055                     }
1056                 }
1057             }
1058         }
1059 
1060         if (m_kernel.GetLoadAddress() != LLDB_INVALID_ADDRESS)
1061         {
1062             if (!m_kernel.LoadImageUsingMemoryModule (m_process))
1063             {
1064                 m_kernel.LoadImageAtFileAddress (m_process);
1065             }
1066         }
1067 
1068         if (m_kernel.IsLoaded() && m_kernel.GetModule())
1069         {
1070             static ConstString kext_summary_symbol ("gLoadedKextSummaries");
1071             const Symbol *symbol = m_kernel.GetModule()->FindFirstSymbolWithNameAndType (kext_summary_symbol, eSymbolTypeData);
1072             if (symbol)
1073             {
1074                 m_kext_summary_header_ptr_addr = symbol->GetAddress();
1075                 // Update all image infos
1076                 ReadAllKextSummaries ();
1077             }
1078         }
1079         else
1080         {
1081             m_kernel.Clear();
1082         }
1083     }
1084 }
1085 
1086 //----------------------------------------------------------------------
1087 // Static callback function that gets called when our DYLD notification
1088 // breakpoint gets hit. We update all of our image infos and then
1089 // let our super class DynamicLoader class decide if we should stop
1090 // or not (based on global preference).
1091 //----------------------------------------------------------------------
1092 bool
1093 DynamicLoaderDarwinKernel::BreakpointHitCallback (void *baton,
1094                                                   StoppointCallbackContext *context,
1095                                                   user_id_t break_id,
1096                                                   user_id_t break_loc_id)
1097 {
1098     return static_cast<DynamicLoaderDarwinKernel*>(baton)->BreakpointHit (context, break_id, break_loc_id);
1099 }
1100 
1101 bool
1102 DynamicLoaderDarwinKernel::BreakpointHit (StoppointCallbackContext *context,
1103                                           user_id_t break_id,
1104                                           user_id_t break_loc_id)
1105 {
1106     Log *log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
1107     if (log)
1108         log->Printf ("DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
1109 
1110     ReadAllKextSummaries ();
1111 
1112     if (log)
1113         PutToLog(log);
1114 
1115     return GetStopWhenImagesChange();
1116 }
1117 
1118 
1119 bool
1120 DynamicLoaderDarwinKernel::ReadKextSummaryHeader ()
1121 {
1122     Mutex::Locker locker(m_mutex);
1123 
1124     // the all image infos is already valid for this process stop ID
1125 
1126     if (m_kext_summary_header_ptr_addr.IsValid())
1127     {
1128         const uint32_t addr_size = m_kernel.GetAddressByteSize ();
1129         const ByteOrder byte_order = m_kernel.GetByteOrder();
1130         Error error;
1131         // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure
1132         // which is currenty 4 uint32_t and a pointer.
1133         uint8_t buf[24];
1134         DataExtractor data (buf, sizeof(buf), byte_order, addr_size);
1135         const size_t count = 4 * sizeof(uint32_t) + addr_size;
1136         const bool prefer_file_cache = false;
1137         if (m_process->GetTarget().ReadPointerFromMemory (m_kext_summary_header_ptr_addr,
1138                                                           prefer_file_cache,
1139                                                           error,
1140                                                           m_kext_summary_header_addr))
1141         {
1142             // We got a valid address for our kext summary header and make sure it isn't NULL
1143             if (m_kext_summary_header_addr.IsValid() &&
1144                 m_kext_summary_header_addr.GetFileAddress() != 0)
1145             {
1146                 const size_t bytes_read = m_process->GetTarget().ReadMemory (m_kext_summary_header_addr, prefer_file_cache, buf, count, error);
1147                 if (bytes_read == count)
1148                 {
1149                     lldb::offset_t offset = 0;
1150                     m_kext_summary_header.version = data.GetU32(&offset);
1151                     if (m_kext_summary_header.version >= 2)
1152                     {
1153                         m_kext_summary_header.entry_size = data.GetU32(&offset);
1154                     }
1155                     else
1156                     {
1157                         // Versions less than 2 didn't have an entry size, it was hard coded
1158                         m_kext_summary_header.entry_size = KERNEL_MODULE_ENTRY_SIZE_VERSION_1;
1159                     }
1160                     m_kext_summary_header.entry_count = data.GetU32(&offset);
1161                     return true;
1162                 }
1163             }
1164         }
1165     }
1166     m_kext_summary_header_addr.Clear();
1167     return false;
1168 }
1169 
1170 // We've either (a) just attached to a new kernel, or (b) the kexts-changed breakpoint was hit
1171 // and we need to figure out what kexts have been added or removed.
1172 // Read the kext summaries from the inferior kernel memory, compare them against the
1173 // m_known_kexts vector and update the m_known_kexts vector as needed to keep in sync with the
1174 // inferior.
1175 
1176 bool
1177 DynamicLoaderDarwinKernel::ParseKextSummaries (const Address &kext_summary_addr, uint32_t count)
1178 {
1179     KextImageInfo::collection kext_summaries;
1180     Log *log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
1181     if (log)
1182         log->Printf ("Kexts-changed breakpoint hit, there are %d kexts currently.\n", count);
1183 
1184     Mutex::Locker locker(m_mutex);
1185 
1186     if (!ReadKextSummaries (kext_summary_addr, count, kext_summaries))
1187         return false;
1188 
1189     // read the plugin.dynamic-loader.darwin-kernel.load-kexts setting -- if the user requested no
1190     // kext loading, don't print any messages about kexts & don't try to read them.
1191     const bool load_kexts = GetGlobalProperties()->GetLoadKexts();
1192 
1193     // By default, all kexts we've loaded in the past are marked as "remove" and all of the kexts
1194     // we just found out about from ReadKextSummaries are marked as "add".
1195     std::vector<bool> to_be_removed(m_known_kexts.size(), true);
1196     std::vector<bool> to_be_added(count, true);
1197 
1198     int number_of_new_kexts_being_added = 0;
1199     int number_of_old_kexts_being_removed = m_known_kexts.size();
1200 
1201     const uint32_t new_kexts_size = kext_summaries.size();
1202     const uint32_t old_kexts_size = m_known_kexts.size();
1203 
1204     // The m_known_kexts vector may have entries that have been Cleared,
1205     // or are a kernel.
1206     for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++)
1207     {
1208         bool ignore = false;
1209         KextImageInfo &image_info = m_known_kexts[old_kext];
1210         if (image_info.IsKernel())
1211         {
1212             ignore = true;
1213         }
1214         else if (image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS && !image_info.GetModule())
1215         {
1216             ignore = true;
1217         }
1218 
1219         if (ignore)
1220         {
1221             number_of_old_kexts_being_removed--;
1222             to_be_removed[old_kext] = false;
1223         }
1224     }
1225 
1226     // Scan over the list of kexts we just read from the kernel, note those that
1227     // need to be added and those already loaded.
1228     for (uint32_t new_kext = 0; new_kext < new_kexts_size; new_kext++)
1229     {
1230         bool add_this_one = true;
1231         for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++)
1232         {
1233             if (m_known_kexts[old_kext] == kext_summaries[new_kext])
1234             {
1235                 // We already have this kext, don't re-load it.
1236                 to_be_added[new_kext] = false;
1237                 // This kext is still present, do not remove it.
1238                 to_be_removed[old_kext] = false;
1239 
1240                 number_of_old_kexts_being_removed--;
1241                 add_this_one = false;
1242                 break;
1243             }
1244         }
1245         if (add_this_one)
1246         {
1247             number_of_new_kexts_being_added++;
1248         }
1249     }
1250 
1251     if (number_of_new_kexts_being_added == 0 && number_of_old_kexts_being_removed == 0)
1252         return true;
1253 
1254     Stream *s = &m_process->GetTarget().GetDebugger().GetOutputStream();
1255     if (s && load_kexts)
1256     {
1257         if (number_of_new_kexts_being_added > 0 && number_of_old_kexts_being_removed > 0)
1258         {
1259             s->Printf ("Loading %d kext modules and unloading %d kext modules ", number_of_new_kexts_being_added, number_of_old_kexts_being_removed);
1260         }
1261         else if (number_of_new_kexts_being_added > 0)
1262         {
1263             s->Printf ("Loading %d kext modules ", number_of_new_kexts_being_added);
1264         }
1265         else if (number_of_old_kexts_being_removed > 0)
1266         {
1267             s->Printf ("Unloading %d kext modules ", number_of_old_kexts_being_removed);
1268         }
1269     }
1270 
1271     if (log)
1272     {
1273         if (load_kexts)
1274         {
1275             log->Printf ("DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts added, %d kexts removed", number_of_new_kexts_being_added, number_of_old_kexts_being_removed);
1276         }
1277         else
1278         {
1279             log->Printf ("DynamicLoaderDarwinKernel::ParseKextSummaries kext loading is disabled, else would have %d kexts added, %d kexts removed", number_of_new_kexts_being_added, number_of_old_kexts_being_removed);
1280         }
1281     }
1282 
1283 
1284     if (number_of_new_kexts_being_added > 0)
1285     {
1286         ModuleList loaded_module_list;
1287 
1288         const uint32_t num_of_new_kexts = kext_summaries.size();
1289         for (uint32_t new_kext = 0; new_kext < num_of_new_kexts; new_kext++)
1290         {
1291             if (to_be_added[new_kext] == true)
1292             {
1293                 KextImageInfo &image_info = kext_summaries[new_kext];
1294                 if (load_kexts)
1295                 {
1296                     if (!image_info.LoadImageUsingMemoryModule (m_process))
1297                     {
1298                         image_info.LoadImageAtFileAddress (m_process);
1299                     }
1300                 }
1301 
1302                 m_known_kexts.push_back(image_info);
1303 
1304                 if (image_info.GetModule() && m_process->GetStopID() == image_info.GetProcessStopId())
1305                     loaded_module_list.AppendIfNeeded (image_info.GetModule());
1306 
1307                 if (s && load_kexts)
1308                     s->Printf (".");
1309 
1310                 if (log)
1311                     kext_summaries[new_kext].PutToLog (log);
1312             }
1313         }
1314         m_process->GetTarget().ModulesDidLoad (loaded_module_list);
1315     }
1316 
1317     if (number_of_old_kexts_being_removed > 0)
1318     {
1319         ModuleList loaded_module_list;
1320         const uint32_t num_of_old_kexts = m_known_kexts.size();
1321         for (uint32_t old_kext = 0; old_kext < num_of_old_kexts; old_kext++)
1322         {
1323             ModuleList unloaded_module_list;
1324             if (to_be_removed[old_kext])
1325             {
1326                 KextImageInfo &image_info = m_known_kexts[old_kext];
1327                 // You can't unload the kernel.
1328                 if (!image_info.IsKernel())
1329                 {
1330                     if (image_info.GetModule())
1331                     {
1332                         unloaded_module_list.AppendIfNeeded (image_info.GetModule());
1333                     }
1334                     if (s)
1335                         s->Printf (".");
1336                     image_info.Clear();
1337                     // should pull it out of the KextImageInfos vector but that would mutate the list and invalidate
1338                     // the to_be_removed bool vector; leaving it in place once Cleared() is relatively harmless.
1339                 }
1340             }
1341             m_process->GetTarget().ModulesDidUnload (unloaded_module_list);
1342         }
1343     }
1344 
1345     if (s && load_kexts)
1346     {
1347         s->Printf (" done.\n");
1348         s->Flush ();
1349     }
1350 
1351     return true;
1352 }
1353 
1354 uint32_t
1355 DynamicLoaderDarwinKernel::ReadKextSummaries (const Address &kext_summary_addr,
1356                                               uint32_t image_infos_count,
1357                                               KextImageInfo::collection &image_infos)
1358 {
1359     const ByteOrder endian = m_kernel.GetByteOrder();
1360     const uint32_t addr_size = m_kernel.GetAddressByteSize();
1361 
1362     image_infos.resize(image_infos_count);
1363     const size_t count = image_infos.size() * m_kext_summary_header.entry_size;
1364     DataBufferHeap data(count, 0);
1365     Error error;
1366 
1367     const bool prefer_file_cache = false;
1368     const size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary_addr,
1369                                                                  prefer_file_cache,
1370                                                                  data.GetBytes(),
1371                                                                  data.GetByteSize(),
1372                                                                  error);
1373     if (bytes_read == count)
1374     {
1375 
1376         DataExtractor extractor (data.GetBytes(), data.GetByteSize(), endian, addr_size);
1377         uint32_t i=0;
1378         for (uint32_t kext_summary_offset = 0;
1379              i < image_infos.size() && extractor.ValidOffsetForDataOfSize(kext_summary_offset, m_kext_summary_header.entry_size);
1380              ++i, kext_summary_offset += m_kext_summary_header.entry_size)
1381         {
1382             lldb::offset_t offset = kext_summary_offset;
1383             const void *name_data = extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME);
1384             if (name_data == NULL)
1385                 break;
1386             image_infos[i].SetName ((const char *) name_data);
1387             UUID uuid (extractor.GetData (&offset, 16), 16);
1388             image_infos[i].SetUUID (uuid);
1389             image_infos[i].SetLoadAddress (extractor.GetU64(&offset));
1390             image_infos[i].SetSize (extractor.GetU64(&offset));
1391         }
1392         if (i < image_infos.size())
1393             image_infos.resize(i);
1394     }
1395     else
1396     {
1397         image_infos.clear();
1398     }
1399     return image_infos.size();
1400 }
1401 
1402 bool
1403 DynamicLoaderDarwinKernel::ReadAllKextSummaries ()
1404 {
1405     Mutex::Locker locker(m_mutex);
1406 
1407     if (ReadKextSummaryHeader ())
1408     {
1409         if (m_kext_summary_header.entry_count > 0 && m_kext_summary_header_addr.IsValid())
1410         {
1411             Address summary_addr (m_kext_summary_header_addr);
1412             summary_addr.Slide(m_kext_summary_header.GetSize());
1413             if (!ParseKextSummaries (summary_addr, m_kext_summary_header.entry_count))
1414             {
1415                 m_known_kexts.clear();
1416             }
1417             return true;
1418         }
1419     }
1420     return false;
1421 }
1422 
1423 //----------------------------------------------------------------------
1424 // Dump an image info structure to the file handle provided.
1425 //----------------------------------------------------------------------
1426 void
1427 DynamicLoaderDarwinKernel::KextImageInfo::PutToLog (Log *log) const
1428 {
1429     if (log == NULL)
1430         return;
1431     const uint8_t *u = (uint8_t *) m_uuid.GetBytes();
1432 
1433     if (m_load_address == LLDB_INVALID_ADDRESS)
1434     {
1435         if (u)
1436         {
1437             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)",
1438                         u[ 0], u[ 1], u[ 2], u[ 3],
1439                         u[ 4], u[ 5], u[ 6], u[ 7],
1440                         u[ 8], u[ 9], u[10], u[11],
1441                         u[12], u[13], u[14], u[15],
1442                         m_name.c_str());
1443         }
1444         else
1445             log->Printf("\tname=\"%s\" (UNLOADED)", m_name.c_str());
1446     }
1447     else
1448     {
1449         if (u)
1450         {
1451             log->Printf("\taddr=0x%16.16" PRIx64 " size=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\"",
1452                         m_load_address, m_size,
1453                         u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7],
1454                         u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15],
1455                         m_name.c_str());
1456         }
1457         else
1458         {
1459             log->Printf("\t[0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") name=\"%s\"",
1460                         m_load_address, m_load_address+m_size, m_name.c_str());
1461         }
1462     }
1463 }
1464 
1465 //----------------------------------------------------------------------
1466 // Dump the _dyld_all_image_infos members and all current image infos
1467 // that we have parsed to the file handle provided.
1468 //----------------------------------------------------------------------
1469 void
1470 DynamicLoaderDarwinKernel::PutToLog(Log *log) const
1471 {
1472     if (log == NULL)
1473         return;
1474 
1475     Mutex::Locker locker(m_mutex);
1476     log->Printf("gLoadedKextSummaries = 0x%16.16" PRIx64 " { version=%u, entry_size=%u, entry_count=%u }",
1477                 m_kext_summary_header_addr.GetFileAddress(),
1478                 m_kext_summary_header.version,
1479                 m_kext_summary_header.entry_size,
1480                 m_kext_summary_header.entry_count);
1481 
1482     size_t i;
1483     const size_t count = m_known_kexts.size();
1484     if (count > 0)
1485     {
1486         log->PutCString("Loaded:");
1487         for (i = 0; i<count; i++)
1488             m_known_kexts[i].PutToLog(log);
1489     }
1490 }
1491 
1492 void
1493 DynamicLoaderDarwinKernel::PrivateInitialize(Process *process)
1494 {
1495     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1496     Clear(true);
1497     m_process = process;
1498 }
1499 
1500 void
1501 DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded ()
1502 {
1503     if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.GetModule())
1504     {
1505         DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1506 
1507 
1508         const bool internal_bp = true;
1509         const LazyBool skip_prologue = eLazyBoolNo;
1510         FileSpecList module_spec_list;
1511         module_spec_list.Append (m_kernel.GetModule()->GetFileSpec());
1512         Breakpoint *bp = m_process->GetTarget().CreateBreakpoint (&module_spec_list,
1513                                                                   NULL,
1514                                                                   "OSKextLoadedKextSummariesUpdated",
1515                                                                   eFunctionNameTypeFull,
1516                                                                   skip_prologue,
1517                                                                   internal_bp).get();
1518 
1519         bp->SetCallback (DynamicLoaderDarwinKernel::BreakpointHitCallback, this, true);
1520         m_break_id = bp->GetID();
1521     }
1522 }
1523 
1524 //----------------------------------------------------------------------
1525 // Member function that gets called when the process state changes.
1526 //----------------------------------------------------------------------
1527 void
1528 DynamicLoaderDarwinKernel::PrivateProcessStateChanged (Process *process, StateType state)
1529 {
1530     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, StateAsCString(state));
1531     switch (state)
1532     {
1533     case eStateConnected:
1534     case eStateAttaching:
1535     case eStateLaunching:
1536     case eStateInvalid:
1537     case eStateUnloaded:
1538     case eStateExited:
1539     case eStateDetached:
1540         Clear(false);
1541         break;
1542 
1543     case eStateStopped:
1544         UpdateIfNeeded();
1545         break;
1546 
1547     case eStateRunning:
1548     case eStateStepping:
1549     case eStateCrashed:
1550     case eStateSuspended:
1551         break;
1552     }
1553 }
1554 
1555 ThreadPlanSP
1556 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
1557 {
1558     ThreadPlanSP thread_plan_sp;
1559     Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1560     if (log)
1561         log->Printf ("Could not find symbol for step through.");
1562     return thread_plan_sp;
1563 }
1564 
1565 Error
1566 DynamicLoaderDarwinKernel::CanLoadImage ()
1567 {
1568     Error error;
1569     error.SetErrorString("always unsafe to load or unload shared libraries in the darwin kernel");
1570     return error;
1571 }
1572 
1573 void
1574 DynamicLoaderDarwinKernel::Initialize()
1575 {
1576     PluginManager::RegisterPlugin (GetPluginNameStatic(),
1577                                    GetPluginDescriptionStatic(),
1578                                    CreateInstance,
1579                                    DebuggerInitialize);
1580 }
1581 
1582 void
1583 DynamicLoaderDarwinKernel::Terminate()
1584 {
1585     PluginManager::UnregisterPlugin (CreateInstance);
1586 }
1587 
1588 void
1589 DynamicLoaderDarwinKernel::DebuggerInitialize (lldb_private::Debugger &debugger)
1590 {
1591     if (!PluginManager::GetSettingForDynamicLoaderPlugin (debugger, DynamicLoaderDarwinKernelProperties::GetSettingName()))
1592     {
1593         const bool is_global_setting = true;
1594         PluginManager::CreateSettingForDynamicLoaderPlugin (debugger,
1595                                                             GetGlobalProperties()->GetValueProperties(),
1596                                                             ConstString ("Properties for the DynamicLoaderDarwinKernel plug-in."),
1597                                                             is_global_setting);
1598     }
1599 }
1600 
1601 const char *
1602 DynamicLoaderDarwinKernel::GetPluginNameStatic()
1603 {
1604     return "dynamic-loader.darwin-kernel";
1605 }
1606 
1607 const char *
1608 DynamicLoaderDarwinKernel::GetPluginDescriptionStatic()
1609 {
1610     return "Dynamic loader plug-in that watches for shared library loads/unloads in the MacOSX kernel.";
1611 }
1612 
1613 
1614 //------------------------------------------------------------------
1615 // PluginInterface protocol
1616 //------------------------------------------------------------------
1617 const char *
1618 DynamicLoaderDarwinKernel::GetPluginName()
1619 {
1620     return "DynamicLoaderDarwinKernel";
1621 }
1622 
1623 const char *
1624 DynamicLoaderDarwinKernel::GetShortPluginName()
1625 {
1626     return GetPluginNameStatic();
1627 }
1628 
1629 uint32_t
1630 DynamicLoaderDarwinKernel::GetPluginVersion()
1631 {
1632     return 1;
1633 }
1634 
1635 lldb::ByteOrder
1636 DynamicLoaderDarwinKernel::GetByteOrderFromMagic (uint32_t magic)
1637 {
1638     switch (magic)
1639     {
1640         case llvm::MachO::HeaderMagic32:
1641         case llvm::MachO::HeaderMagic64:
1642             return lldb::endian::InlHostByteOrder();
1643 
1644         case llvm::MachO::HeaderMagic32Swapped:
1645         case llvm::MachO::HeaderMagic64Swapped:
1646             if (lldb::endian::InlHostByteOrder() == lldb::eByteOrderBig)
1647                 return lldb::eByteOrderLittle;
1648             else
1649                 return lldb::eByteOrderBig;
1650 
1651         default:
1652             break;
1653     }
1654     return lldb::eByteOrderInvalid;
1655 }
1656 
1657