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/Utility/SafeMachO.h"
13 
14 #include "lldb/Breakpoint/StoppointCallbackContext.h"
15 #include "lldb/Core/DataBuffer.h"
16 #include "lldb/Core/DataBufferHeap.h"
17 #include "lldb/Core/Debugger.h"
18 #include "lldb/Core/Log.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Core/ModuleSpec.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/Section.h"
23 #include "lldb/Core/State.h"
24 #include "lldb/Core/StreamFile.h"
25 #include "lldb/Host/Symbols.h"
26 #include "lldb/Symbol/ObjectFile.h"
27 #include "lldb/Target/RegisterContext.h"
28 #include "lldb/Target/StackFrame.h"
29 #include "lldb/Target/Target.h"
30 #include "lldb/Target/Thread.h"
31 #include "lldb/Target/ThreadPlanRunToAddress.h"
32 #include "Plugins/Platform/MacOSX/PlatformDarwinKernel.h"
33 
34 #include "DynamicLoaderDarwinKernel.h"
35 
36 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
37 #ifdef ENABLE_DEBUG_PRINTF
38 #include <stdio.h>
39 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
40 #else
41 #define DEBUG_PRINTF(fmt, ...)
42 #endif
43 
44 using namespace lldb;
45 using namespace lldb_private;
46 
47 // Progressively greater amounts of scanning we will allow
48 // For some targets very early in startup, we can't do any random reads of memory or we can crash the device
49 // so a setting is needed that can completely disable the KASLR scans.
50 
51 enum KASLRScanType
52 {
53     eKASLRScanNone = 0,         // No reading into the inferior at all
54     eKASLRScanLowgloAddresses,  // Check one word of memory for a possible kernel addr, then see if a kernel is there
55     eKASLRScanNearPC,           // Scan backwards from the current $pc looking for kernel; checking at 96 locations total
56     eKASLRScanExhaustiveScan    // Scan through the entire possible kernel address range looking for a kernel
57 };
58 
59 OptionEnumValueElement
60 g_kaslr_kernel_scan_enum_values[] =
61 {
62     { eKASLRScanNone,            "none",            "Do not read memory looking for a Darwin kernel when attaching." },
63     { eKASLRScanLowgloAddresses, "basic",           "Check for the Darwin kernel's load addr in the lowglo page (boot-args=debug) only." },
64     { eKASLRScanNearPC,          "fast-scan",       "Scan near the pc value on attach to find the Darwin kernel's load address."},
65     { eKASLRScanExhaustiveScan,  "exhaustive-scan", "Scan through the entire potential address range of Darwin kernel (only on 32-bit targets)."},
66     { 0, NULL, NULL }
67 };
68 
69 static PropertyDefinition
70 g_properties[] =
71 {
72     { "load-kexts" , OptionValue::eTypeBoolean, true, true, NULL, NULL, "Automatically loads kext images when attaching to a kernel." },
73     { "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." },
74     {  NULL        , OptionValue::eTypeInvalid, false, 0  , NULL, NULL, NULL  }
75 };
76 
77 enum {
78     ePropertyLoadKexts,
79     ePropertyScanType
80 };
81 
82 class DynamicLoaderDarwinKernelProperties : public Properties
83 {
84 public:
85 
86     static ConstString &
87     GetSettingName ()
88     {
89         static ConstString g_setting_name("darwin-kernel");
90         return g_setting_name;
91     }
92 
93     DynamicLoaderDarwinKernelProperties() :
94         Properties ()
95     {
96         m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
97         m_collection_sp->Initialize(g_properties);
98     }
99 
100     virtual
101     ~DynamicLoaderDarwinKernelProperties()
102     {
103     }
104 
105     bool
106     GetLoadKexts() const
107     {
108         const uint32_t idx = ePropertyLoadKexts;
109         return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
110     }
111 
112     KASLRScanType
113     GetScanType() const
114     {
115         const uint32_t idx = ePropertyScanType;
116         return (KASLRScanType) m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
117     }
118 
119 
120 };
121 
122 typedef std::shared_ptr<DynamicLoaderDarwinKernelProperties> DynamicLoaderDarwinKernelPropertiesSP;
123 
124 static const DynamicLoaderDarwinKernelPropertiesSP &
125 GetGlobalProperties()
126 {
127     static DynamicLoaderDarwinKernelPropertiesSP g_settings_sp;
128     if (!g_settings_sp)
129         g_settings_sp.reset (new DynamicLoaderDarwinKernelProperties ());
130     return g_settings_sp;
131 }
132 
133 //----------------------------------------------------------------------
134 // Create an instance of this class. This function is filled into
135 // the plugin info class that gets handed out by the plugin factory and
136 // allows the lldb to instantiate an instance of this class.
137 //----------------------------------------------------------------------
138 DynamicLoader *
139 DynamicLoaderDarwinKernel::CreateInstance (Process* process, bool force)
140 {
141     if (!force)
142     {
143         // If the user provided an executable binary and it is not a kernel,
144         // this plugin should not create an instance.
145         Module* exe_module = process->GetTarget().GetExecutableModulePointer();
146         if (exe_module)
147         {
148             ObjectFile *object_file = exe_module->GetObjectFile();
149             if (object_file)
150             {
151                 if (object_file->GetStrata() != ObjectFile::eStrataKernel)
152                 {
153                     return NULL;
154                 }
155             }
156         }
157 
158         // If the target's architecture does not look like an Apple environment,
159         // this plugin should not create an instance.
160         const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple();
161         switch (triple_ref.getOS())
162         {
163             case llvm::Triple::Darwin:
164             case llvm::Triple::MacOSX:
165             case llvm::Triple::IOS:
166                 if (triple_ref.getVendor() != llvm::Triple::Apple)
167                 {
168                    return NULL;
169                 }
170                 break;
171             // If we have triple like armv7-unknown-unknown, we should try looking for a Darwin kernel.
172             case llvm::Triple::UnknownOS:
173                 break;
174             default:
175                 return NULL;
176                 break;
177         }
178     }
179 
180     // At this point if there is an ExecutableModule, it is a kernel and the Target is some variant of an Apple system.
181     // If the Process hasn't provided the kernel load address, we need to look around in memory to find it.
182 
183     addr_t kernel_load_address = SearchForDarwinKernel (process);
184     if (kernel_load_address != LLDB_INVALID_ADDRESS)
185     {
186         process->SetCanJIT(false);
187         return new DynamicLoaderDarwinKernel (process, kernel_load_address);
188     }
189     return NULL;
190 }
191 
192 lldb::addr_t
193 DynamicLoaderDarwinKernel::SearchForDarwinKernel (Process *process)
194 {
195     addr_t kernel_load_address = process->GetImageInfoAddress();
196     if (kernel_load_address == LLDB_INVALID_ADDRESS)
197     {
198         kernel_load_address = SearchForKernelAtSameLoadAddr (process);
199         if (kernel_load_address == LLDB_INVALID_ADDRESS)
200         {
201             kernel_load_address = SearchForKernelWithDebugHints (process);
202             if (kernel_load_address == LLDB_INVALID_ADDRESS)
203             {
204                 kernel_load_address = SearchForKernelNearPC (process);
205                 if (kernel_load_address == LLDB_INVALID_ADDRESS)
206                 {
207                     kernel_load_address = SearchForKernelViaExhaustiveSearch (process);
208                 }
209             }
210         }
211     }
212     return kernel_load_address;
213 }
214 
215 //----------------------------------------------------------------------
216 // Check if the kernel binary is loaded in memory without a slide.
217 // First verify that the ExecutableModule is a kernel before we proceed.
218 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
219 //----------------------------------------------------------------------
220 lldb::addr_t
221 DynamicLoaderDarwinKernel::SearchForKernelAtSameLoadAddr (Process *process)
222 {
223     Module *exe_module = process->GetTarget().GetExecutableModulePointer();
224     if (exe_module == NULL)
225         return LLDB_INVALID_ADDRESS;
226 
227     ObjectFile *exe_objfile = exe_module->GetObjectFile();
228     if (exe_objfile == NULL)
229         return LLDB_INVALID_ADDRESS;
230 
231     if (exe_objfile->GetType() != ObjectFile::eTypeExecutable || exe_objfile->GetStrata() != ObjectFile::eStrataKernel)
232         return LLDB_INVALID_ADDRESS;
233 
234     if (!exe_objfile->GetHeaderAddress().IsValid())
235         return LLDB_INVALID_ADDRESS;
236 
237     if (CheckForKernelImageAtAddress (exe_objfile->GetHeaderAddress().GetFileAddress(), process) == exe_module->GetUUID())
238         return exe_objfile->GetHeaderAddress().GetFileAddress();
239 
240     return LLDB_INVALID_ADDRESS;
241 }
242 
243 //----------------------------------------------------------------------
244 // If the debug flag is included in the boot-args nvram setting, the kernel's load address
245 // will be noted in the lowglo page at a fixed address
246 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
247 //----------------------------------------------------------------------
248 lldb::addr_t
249 DynamicLoaderDarwinKernel::SearchForKernelWithDebugHints (Process *process)
250 {
251     if (GetGlobalProperties()->GetScanType() == eKASLRScanNone)
252         return LLDB_INVALID_ADDRESS;
253 
254     Error read_err;
255     addr_t addr = LLDB_INVALID_ADDRESS;
256     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
257     {
258         addr = process->ReadUnsignedIntegerFromMemory (0xffffff8000002010ULL, 8, LLDB_INVALID_ADDRESS, read_err);
259     }
260     else
261     {
262         addr = process->ReadUnsignedIntegerFromMemory (0xffff0110, 4, LLDB_INVALID_ADDRESS, read_err);
263     }
264 
265     if (addr == 0)
266         addr = LLDB_INVALID_ADDRESS;
267 
268     if (addr != LLDB_INVALID_ADDRESS)
269     {
270         if (CheckForKernelImageAtAddress (addr, process).IsValid())
271             return addr;
272     }
273 
274     return LLDB_INVALID_ADDRESS;
275 }
276 
277 //----------------------------------------------------------------------
278 // If the kernel is currently executing when lldb attaches, and we don't have
279 // a better way of finding the kernel's load address, try searching backwards
280 // from the current pc value looking for the kernel's Mach header in memory.
281 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
282 //----------------------------------------------------------------------
283 lldb::addr_t
284 DynamicLoaderDarwinKernel::SearchForKernelNearPC (Process *process)
285 {
286     if (GetGlobalProperties()->GetScanType() == eKASLRScanNone
287         || GetGlobalProperties()->GetScanType() == eKASLRScanLowgloAddresses)
288     {
289         return LLDB_INVALID_ADDRESS;
290     }
291 
292     ThreadSP thread = process->GetThreadList().GetSelectedThread ();
293     if (thread.get() == NULL)
294         return LLDB_INVALID_ADDRESS;
295     addr_t pc = thread->GetRegisterContext ()->GetPC(LLDB_INVALID_ADDRESS);
296 
297     if (pc == LLDB_INVALID_ADDRESS)
298         return LLDB_INVALID_ADDRESS;
299 
300     addr_t kernel_range_low;
301     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
302     {
303         kernel_range_low = 1ULL << 63;
304     }
305     else
306     {
307         kernel_range_low = 1ULL << 31;
308     }
309 
310     // Outside the normal kernel address range, this is probably userland code running right now
311     if (pc < kernel_range_low)
312         return LLDB_INVALID_ADDRESS;
313 
314     // The kernel will load at at one megabyte boundary (0x100000), or at that boundary plus
315     // an offset of one page (0x1000) or two, depending on the device.
316 
317     // Round the current pc down to the nearest one megabyte boundary - the place where we will start searching.
318     addr_t addr = pc & ~0xfffff;
319 
320     int i = 0;
321     while (i < 32 && pc >= kernel_range_low)
322     {
323         if (CheckForKernelImageAtAddress (addr, process).IsValid())
324             return addr;
325         if (CheckForKernelImageAtAddress (addr + 0x1000, process).IsValid())
326             return addr + 0x1000;
327         if (CheckForKernelImageAtAddress (addr + 0x2000, process).IsValid())
328             return addr + 0x2000;
329         i++;
330         addr -= 0x100000;
331     }
332 
333     return LLDB_INVALID_ADDRESS;
334 }
335 
336 //----------------------------------------------------------------------
337 // Scan through the valid address range for a kernel binary.
338 // This is uselessly slow in 64-bit environments so we don't even try it.
339 // This scan is not enabled by default even for 32-bit targets.
340 // Returns the address of the kernel if one was found, else LLDB_INVALID_ADDRESS.
341 //----------------------------------------------------------------------
342 lldb::addr_t
343 DynamicLoaderDarwinKernel::SearchForKernelViaExhaustiveSearch (Process *process)
344 {
345     if (GetGlobalProperties()->GetScanType() != eKASLRScanExhaustiveScan)
346     {
347         return LLDB_INVALID_ADDRESS;
348     }
349 
350     addr_t kernel_range_low, kernel_range_high;
351     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
352     {
353         kernel_range_low = 1ULL << 63;
354         kernel_range_high = UINT64_MAX;
355     }
356     else
357     {
358         kernel_range_low = 1ULL << 31;
359         kernel_range_high = UINT32_MAX;
360     }
361 
362     // Stepping through memory at one-megabyte resolution looking for a kernel
363     // rarely works (fast enough) with a 64-bit address space -- for now, let's
364     // not even bother.  We may be attaching to something which *isn't* a kernel
365     // and we don't want to spin for minutes on-end looking for a kernel.
366     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 8)
367         return LLDB_INVALID_ADDRESS;
368 
369     addr_t addr = kernel_range_low;
370 
371     while (addr >= kernel_range_low && addr < kernel_range_high)
372     {
373         if (CheckForKernelImageAtAddress (addr, process).IsValid())
374             return addr;
375         if (CheckForKernelImageAtAddress (addr + 0x1000, process).IsValid())
376             return addr + 0x1000;
377         if (CheckForKernelImageAtAddress (addr + 0x2000, process).IsValid())
378             return addr + 0x2000;
379         addr += 0x100000;
380     }
381     return LLDB_INVALID_ADDRESS;
382 }
383 
384 //----------------------------------------------------------------------
385 // Given an address in memory, look to see if there is a kernel image at that
386 // address.
387 // Returns a UUID; if a kernel was not found at that address, UUID.IsValid() will be false.
388 //----------------------------------------------------------------------
389 lldb_private::UUID
390 DynamicLoaderDarwinKernel::CheckForKernelImageAtAddress (lldb::addr_t addr, Process *process)
391 {
392     if (addr == LLDB_INVALID_ADDRESS)
393         return UUID();
394 
395     // First try a quick test -- read the first 4 bytes and see if there is a valid Mach-O magic field there
396     // (the first field of the mach_header/mach_header_64 struct).
397 
398     Error read_error;
399     uint64_t result = process->ReadUnsignedIntegerFromMemory (addr, 4, LLDB_INVALID_ADDRESS, read_error);
400     if (result != llvm::MachO::MH_MAGIC_64
401         && result != llvm::MachO::MH_MAGIC
402         && result != llvm::MachO::MH_CIGAM
403         && result != llvm::MachO::MH_CIGAM_64)
404     {
405         return UUID();
406     }
407 
408     // Read the mach header and see whether it looks like a kernel
409     llvm::MachO::mach_header header;
410     if (process->DoReadMemory (addr, &header, sizeof(header), read_error) != sizeof(header))
411         return UUID();
412 
413     if (header.magic == llvm::MachO::MH_CIGAM ||
414         header.magic == llvm::MachO::MH_CIGAM_64)
415     {
416         header.magic        = llvm::ByteSwap_32(header.magic);
417         header.cputype      = llvm::ByteSwap_32(header.cputype);
418         header.cpusubtype   = llvm::ByteSwap_32(header.cpusubtype);
419         header.filetype     = llvm::ByteSwap_32(header.filetype);
420         header.ncmds        = llvm::ByteSwap_32(header.ncmds);
421         header.sizeofcmds   = llvm::ByteSwap_32(header.sizeofcmds);
422         header.flags        = llvm::ByteSwap_32(header.flags);
423     }
424 
425     // A kernel is an executable which does not have the dynamic link object flag set.
426     if (header.filetype == llvm::MachO::MH_EXECUTE
427         && (header.flags & llvm::MachO::MH_DYLDLINK) == 0)
428     {
429         // Create a full module to get the UUID
430         ModuleSP memory_module_sp = process->ReadModuleFromMemory (FileSpec ("temp_mach_kernel", false), addr);
431         if (!memory_module_sp.get())
432             return UUID();
433 
434         ObjectFile *exe_objfile = memory_module_sp->GetObjectFile();
435         if (exe_objfile == NULL)
436             return UUID();
437 
438         if (exe_objfile->GetType() == ObjectFile::eTypeExecutable && exe_objfile->GetStrata() == ObjectFile::eStrataKernel)
439         {
440             ArchSpec kernel_arch (eArchTypeMachO, header.cputype, header.cpusubtype);
441             if (!process->GetTarget().GetArchitecture().IsCompatibleMatch(kernel_arch))
442             {
443                 process->GetTarget().SetArchitecture (kernel_arch);
444             }
445             return memory_module_sp->GetUUID();
446         }
447     }
448 
449     return UUID();
450 }
451 
452 //----------------------------------------------------------------------
453 // Constructor
454 //----------------------------------------------------------------------
455 DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel (Process* process, lldb::addr_t kernel_addr) :
456     DynamicLoader(process),
457     m_kernel_load_address (kernel_addr),
458     m_kernel(),
459     m_kext_summary_header_ptr_addr (),
460     m_kext_summary_header_addr (),
461     m_kext_summary_header (),
462     m_known_kexts (),
463     m_mutex(Mutex::eMutexTypeRecursive),
464     m_break_id (LLDB_INVALID_BREAK_ID)
465 {
466     PlatformSP platform_sp(Platform::FindPlugin (process, PlatformDarwinKernel::GetPluginNameStatic ()));
467     // Only select the darwin-kernel Platform if we've been asked to load kexts.
468     // It can take some time to scan over all of the kext info.plists and that
469     // shouldn't be done if kext loading is explicitly disabled.
470     if (platform_sp.get() && GetGlobalProperties()->GetLoadKexts())
471     {
472         process->GetTarget().SetPlatform (platform_sp);
473     }
474 }
475 
476 //----------------------------------------------------------------------
477 // Destructor
478 //----------------------------------------------------------------------
479 DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel()
480 {
481     Clear(true);
482 }
483 
484 void
485 DynamicLoaderDarwinKernel::UpdateIfNeeded()
486 {
487     LoadKernelModuleIfNeeded();
488     SetNotificationBreakpointIfNeeded ();
489 }
490 //------------------------------------------------------------------
491 /// Called after attaching a process.
492 ///
493 /// Allow DynamicLoader plug-ins to execute some code after
494 /// attaching to a process.
495 //------------------------------------------------------------------
496 void
497 DynamicLoaderDarwinKernel::DidAttach ()
498 {
499     PrivateInitialize(m_process);
500     UpdateIfNeeded();
501 }
502 
503 //------------------------------------------------------------------
504 /// Called after attaching a process.
505 ///
506 /// Allow DynamicLoader plug-ins to execute some code after
507 /// attaching to a process.
508 //------------------------------------------------------------------
509 void
510 DynamicLoaderDarwinKernel::DidLaunch ()
511 {
512     PrivateInitialize(m_process);
513     UpdateIfNeeded();
514 }
515 
516 
517 //----------------------------------------------------------------------
518 // Clear out the state of this class.
519 //----------------------------------------------------------------------
520 void
521 DynamicLoaderDarwinKernel::Clear (bool clear_process)
522 {
523     Mutex::Locker locker(m_mutex);
524 
525     if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
526         m_process->ClearBreakpointSiteByID(m_break_id);
527 
528     if (clear_process)
529         m_process = NULL;
530     m_kernel.Clear();
531     m_known_kexts.clear();
532     m_kext_summary_header_ptr_addr.Clear();
533     m_kext_summary_header_addr.Clear();
534     m_break_id = LLDB_INVALID_BREAK_ID;
535 }
536 
537 
538 bool
539 DynamicLoaderDarwinKernel::KextImageInfo::LoadImageAtFileAddress (Process *process)
540 {
541     if (IsLoaded())
542         return true;
543 
544     if (m_module_sp)
545     {
546         bool changed = false;
547         if (m_module_sp->SetLoadAddress (process->GetTarget(), 0, true, changed))
548             m_load_process_stop_id = process->GetStopID();
549     }
550     return false;
551 }
552 
553 void
554 DynamicLoaderDarwinKernel::KextImageInfo::SetModule (ModuleSP module_sp)
555 {
556     m_module_sp = module_sp;
557     if (module_sp.get() && module_sp->GetObjectFile())
558     {
559         if (module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable
560             && module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel)
561         {
562             m_kernel_image = true;
563         }
564         else
565         {
566             m_kernel_image = false;
567         }
568     }
569 }
570 
571 ModuleSP
572 DynamicLoaderDarwinKernel::KextImageInfo::GetModule ()
573 {
574     return m_module_sp;
575 }
576 
577 void
578 DynamicLoaderDarwinKernel::KextImageInfo::SetLoadAddress (addr_t load_addr)
579 {
580     m_load_address = load_addr;
581 }
582 
583 addr_t
584 DynamicLoaderDarwinKernel::KextImageInfo::GetLoadAddress () const
585 {
586     return m_load_address;
587 }
588 
589 uint64_t
590 DynamicLoaderDarwinKernel::KextImageInfo::GetSize () const
591 {
592     return m_size;
593 }
594 
595 void
596 DynamicLoaderDarwinKernel::KextImageInfo::SetSize (uint64_t size)
597 {
598     m_size = size;
599 }
600 
601 uint32_t
602 DynamicLoaderDarwinKernel::KextImageInfo::GetProcessStopId () const
603 {
604     return m_load_process_stop_id;
605 }
606 
607 void
608 DynamicLoaderDarwinKernel::KextImageInfo::SetProcessStopId (uint32_t stop_id)
609 {
610     m_load_process_stop_id = stop_id;
611 }
612 
613 bool
614 DynamicLoaderDarwinKernel::KextImageInfo::operator== (const KextImageInfo &rhs)
615 {
616     if (m_uuid.IsValid() || rhs.GetUUID().IsValid())
617     {
618         if (m_uuid == rhs.GetUUID())
619         {
620             return true;
621         }
622         return false;
623     }
624 
625     if (m_name == rhs.GetName() && m_load_address == rhs.GetLoadAddress())
626         return true;
627 
628     return false;
629 }
630 
631 void
632 DynamicLoaderDarwinKernel::KextImageInfo::SetName (const char *name)
633 {
634     m_name = name;
635 }
636 
637 std::string
638 DynamicLoaderDarwinKernel::KextImageInfo::GetName () const
639 {
640     return m_name;
641 }
642 
643 void
644 DynamicLoaderDarwinKernel::KextImageInfo::SetUUID (const UUID &uuid)
645 {
646     m_uuid = uuid;
647 }
648 
649 UUID
650 DynamicLoaderDarwinKernel::KextImageInfo::GetUUID () const
651 {
652     return m_uuid;
653 }
654 
655 // Given the m_load_address from the kext summaries, and a UUID, try to create an in-memory
656 // Module at that address.  Require that the MemoryModule have a matching UUID and detect
657 // if this MemoryModule is a kernel or a kext.
658 //
659 // Returns true if m_memory_module_sp is now set to a valid Module.
660 
661 bool
662 DynamicLoaderDarwinKernel::KextImageInfo::ReadMemoryModule (Process *process)
663 {
664     if (m_memory_module_sp.get() != NULL)
665         return true;
666     if (m_load_address == LLDB_INVALID_ADDRESS)
667         return false;
668 
669     FileSpec file_spec;
670     file_spec.SetFile (m_name.c_str(), false);
671 
672     ModuleSP memory_module_sp = process->ReadModuleFromMemory (file_spec, m_load_address);
673 
674     if (memory_module_sp.get() == NULL)
675         return false;
676 
677     bool is_kernel = false;
678     if (memory_module_sp->GetObjectFile())
679     {
680         if (memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeExecutable
681             && memory_module_sp->GetObjectFile()->GetStrata() == ObjectFile::eStrataKernel)
682         {
683             is_kernel = true;
684         }
685         else if (memory_module_sp->GetObjectFile()->GetType() == ObjectFile::eTypeSharedLibrary)
686         {
687             is_kernel = false;
688         }
689     }
690 
691     // If this is a kext, and the kernel specified what UUID we should find at this
692     // load address, require that the memory module have a matching UUID or something
693     // has gone wrong and we should discard it.
694     if (m_uuid.IsValid())
695     {
696         if (m_uuid != memory_module_sp->GetUUID())
697         {
698             return false;
699         }
700     }
701 
702     // If the in-memory Module has a UUID, let's use that.
703     if (!m_uuid.IsValid() && memory_module_sp->GetUUID().IsValid())
704     {
705         m_uuid = memory_module_sp->GetUUID();
706     }
707 
708     m_memory_module_sp = memory_module_sp;
709     m_kernel_image = is_kernel;
710     if (is_kernel)
711     {
712         if (memory_module_sp->GetArchitecture().IsValid())
713         {
714             process->GetTarget().SetArchitecture(memory_module_sp->GetArchitecture());
715         }
716         if (m_uuid.IsValid())
717         {
718             Module* exe_module = process->GetTarget().GetExecutableModulePointer();
719             if (exe_module && exe_module->GetUUID().IsValid())
720             {
721                 if (m_uuid != exe_module->GetUUID())
722                 {
723                     Stream *s = process->GetTarget().GetDebugger().GetOutputFile().get();
724                     if (s)
725                     {
726                         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",
727                                    exe_module->GetUUID().GetAsString().c_str(),
728                                    m_uuid.GetAsString().c_str());
729                         s->Flush ();
730                     }
731                 }
732             }
733         }
734     }
735 
736     return true;
737 }
738 
739 bool
740 DynamicLoaderDarwinKernel::KextImageInfo::IsKernel () const
741 {
742     return m_kernel_image == true;
743 }
744 
745 void
746 DynamicLoaderDarwinKernel::KextImageInfo::SetIsKernel (bool is_kernel)
747 {
748     m_kernel_image = is_kernel;
749 }
750 
751 bool
752 DynamicLoaderDarwinKernel::KextImageInfo::LoadImageUsingMemoryModule (Process *process)
753 {
754     if (IsLoaded())
755         return true;
756 
757 
758     Target &target = process->GetTarget();
759 
760     // If we don't have / can't create a memory module for this kext, don't try to load it - we won't
761     // have the correct segment load addresses.
762     if (!ReadMemoryModule (process))
763     {
764         return false;
765     }
766 
767     bool uuid_is_valid = m_uuid.IsValid();
768 
769     if (IsKernel() && uuid_is_valid && m_memory_module_sp.get())
770     {
771         Stream *s = target.GetDebugger().GetOutputFile().get();
772         if (s)
773         {
774             s->Printf ("Kernel UUID: %s\n", m_memory_module_sp->GetUUID().GetAsString().c_str());
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 (!m_module_sp && platform_sp)
816             {
817                 ConstString platform_name (platform_sp->GetPluginName());
818                 static ConstString g_platform_name (PlatformDarwinKernel::GetPluginNameStatic());
819                 if (platform_name == g_platform_name)
820                 {
821                     ModuleSpec kext_bundle_module_spec(module_spec);
822                     FileSpec kext_filespec(m_name.c_str(), false);
823                     kext_bundle_module_spec.GetFileSpec() = kext_filespec;
824                     platform_sp->GetSharedModule (kext_bundle_module_spec, m_module_sp, &target.GetExecutableSearchPaths(), NULL, NULL);
825                 }
826             }
827 
828             // Ask the Target to find this file on the local system, if possible.
829             // This will search in the list of currently-loaded files, look in the
830             // standard search paths on the system, and on a Mac it will try calling
831             // the DebugSymbols framework with the UUID to find the binary via its
832             // search methods.
833             if (!m_module_sp)
834             {
835                 m_module_sp = target.GetSharedModule (module_spec);
836             }
837 
838             if (IsKernel() && !m_module_sp)
839             {
840                 Stream *s = target.GetDebugger().GetOutputFile().get();
841                 if (s)
842                 {
843                     s->Printf ("WARNING: Unable to locate kernel binary on the debugger system.\n");
844                 }
845             }
846         }
847 
848         // If we managed to find a module, append it to the target's list of images.
849         // If we also have a memory module, require that they have matching UUIDs
850         if (m_module_sp)
851         {
852             bool uuid_match_ok = true;
853             if (m_memory_module_sp)
854             {
855                 if (m_module_sp->GetUUID() != m_memory_module_sp->GetUUID())
856                 {
857                     uuid_match_ok = false;
858                 }
859             }
860             if (uuid_match_ok)
861             {
862                 target.GetImages().AppendIfNeeded(m_module_sp);
863                 if (IsKernel() && target.GetExecutableModulePointer() != m_module_sp.get())
864                 {
865                     target.SetExecutableModule (m_module_sp, false);
866                 }
867             }
868         }
869     }
870 
871     if (!m_module_sp && !IsKernel() && m_uuid.IsValid() && !m_name.empty())
872     {
873         Stream *s = target.GetDebugger().GetOutputFile().get();
874         if (s)
875         {
876             s->Printf ("warning: Can't find binary/dSYM for %s (%s)\n",
877                        m_name.c_str(), m_uuid.GetAsString().c_str());
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.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().GetOutputFile().get();
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 > 128)
1152                     {
1153                         Stream *s = m_process->GetTarget().GetDebugger().GetOutputFile().get();
1154                         s->Printf ("WARNING: Unable to read kext summary header, got improbable version number %u\n", m_kext_summary_header.version);
1155                         // If we get an improbably large veriosn number, we're probably getting bad memory.
1156                         m_kext_summary_header_addr.Clear();
1157                         return false;
1158                     }
1159                     if (m_kext_summary_header.version >= 2)
1160                     {
1161                         m_kext_summary_header.entry_size = data.GetU32(&offset);
1162                         if (m_kext_summary_header.entry_size > 4096)
1163                         {
1164                             // If we get an improbably large entry_size, we're probably getting bad memory.
1165                             Stream *s = m_process->GetTarget().GetDebugger().GetOutputFile().get();
1166                             s->Printf ("WARNING: Unable to read kext summary header, got improbable entry_size %u\n", m_kext_summary_header.entry_size);
1167                             m_kext_summary_header_addr.Clear();
1168                             return false;
1169                         }
1170                     }
1171                     else
1172                     {
1173                         // Versions less than 2 didn't have an entry size, it was hard coded
1174                         m_kext_summary_header.entry_size = KERNEL_MODULE_ENTRY_SIZE_VERSION_1;
1175                     }
1176                     m_kext_summary_header.entry_count = data.GetU32(&offset);
1177                     if (m_kext_summary_header.entry_count > 10000)
1178                     {
1179                         // If we get an improbably large number of kexts, we're probably getting bad memory.
1180                         Stream *s = m_process->GetTarget().GetDebugger().GetOutputFile().get();
1181                         s->Printf ("WARNING: Unable to read kext summary header, got improbable number of kexts %u\n", m_kext_summary_header.entry_count);
1182                         m_kext_summary_header_addr.Clear();
1183                         return false;
1184                     }
1185                     return true;
1186                 }
1187             }
1188         }
1189     }
1190     m_kext_summary_header_addr.Clear();
1191     return false;
1192 }
1193 
1194 // We've either (a) just attached to a new kernel, or (b) the kexts-changed breakpoint was hit
1195 // and we need to figure out what kexts have been added or removed.
1196 // Read the kext summaries from the inferior kernel memory, compare them against the
1197 // m_known_kexts vector and update the m_known_kexts vector as needed to keep in sync with the
1198 // inferior.
1199 
1200 bool
1201 DynamicLoaderDarwinKernel::ParseKextSummaries (const Address &kext_summary_addr, uint32_t count)
1202 {
1203     KextImageInfo::collection kext_summaries;
1204     Log *log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
1205     if (log)
1206         log->Printf ("Kexts-changed breakpoint hit, there are %d kexts currently.\n", count);
1207 
1208     Mutex::Locker locker(m_mutex);
1209 
1210     if (!ReadKextSummaries (kext_summary_addr, count, kext_summaries))
1211         return false;
1212 
1213     // read the plugin.dynamic-loader.darwin-kernel.load-kexts setting -- if the user requested no
1214     // kext loading, don't print any messages about kexts & don't try to read them.
1215     const bool load_kexts = GetGlobalProperties()->GetLoadKexts();
1216 
1217     // By default, all kexts we've loaded in the past are marked as "remove" and all of the kexts
1218     // we just found out about from ReadKextSummaries are marked as "add".
1219     std::vector<bool> to_be_removed(m_known_kexts.size(), true);
1220     std::vector<bool> to_be_added(count, true);
1221 
1222     int number_of_new_kexts_being_added = 0;
1223     int number_of_old_kexts_being_removed = m_known_kexts.size();
1224 
1225     const uint32_t new_kexts_size = kext_summaries.size();
1226     const uint32_t old_kexts_size = m_known_kexts.size();
1227 
1228     // The m_known_kexts vector may have entries that have been Cleared,
1229     // or are a kernel.
1230     for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++)
1231     {
1232         bool ignore = false;
1233         KextImageInfo &image_info = m_known_kexts[old_kext];
1234         if (image_info.IsKernel())
1235         {
1236             ignore = true;
1237         }
1238         else if (image_info.GetLoadAddress() == LLDB_INVALID_ADDRESS && !image_info.GetModule())
1239         {
1240             ignore = true;
1241         }
1242 
1243         if (ignore)
1244         {
1245             number_of_old_kexts_being_removed--;
1246             to_be_removed[old_kext] = false;
1247         }
1248     }
1249 
1250     // Scan over the list of kexts we just read from the kernel, note those that
1251     // need to be added and those already loaded.
1252     for (uint32_t new_kext = 0; new_kext < new_kexts_size; new_kext++)
1253     {
1254         bool add_this_one = true;
1255         for (uint32_t old_kext = 0; old_kext < old_kexts_size; old_kext++)
1256         {
1257             if (m_known_kexts[old_kext] == kext_summaries[new_kext])
1258             {
1259                 // We already have this kext, don't re-load it.
1260                 to_be_added[new_kext] = false;
1261                 // This kext is still present, do not remove it.
1262                 to_be_removed[old_kext] = false;
1263 
1264                 number_of_old_kexts_being_removed--;
1265                 add_this_one = false;
1266                 break;
1267             }
1268         }
1269         if (add_this_one)
1270         {
1271             number_of_new_kexts_being_added++;
1272         }
1273     }
1274 
1275     if (number_of_new_kexts_being_added == 0 && number_of_old_kexts_being_removed == 0)
1276         return true;
1277 
1278     Stream *s = m_process->GetTarget().GetDebugger().GetOutputFile().get();
1279     if (s && load_kexts)
1280     {
1281         if (number_of_new_kexts_being_added > 0 && number_of_old_kexts_being_removed > 0)
1282         {
1283             s->Printf ("Loading %d kext modules and unloading %d kext modules ", number_of_new_kexts_being_added, number_of_old_kexts_being_removed);
1284         }
1285         else if (number_of_new_kexts_being_added > 0)
1286         {
1287             s->Printf ("Loading %d kext modules ", number_of_new_kexts_being_added);
1288         }
1289         else if (number_of_old_kexts_being_removed > 0)
1290         {
1291             s->Printf ("Unloading %d kext modules ", number_of_old_kexts_being_removed);
1292         }
1293     }
1294 
1295     if (log)
1296     {
1297         if (load_kexts)
1298         {
1299             log->Printf ("DynamicLoaderDarwinKernel::ParseKextSummaries: %d kexts added, %d kexts removed", number_of_new_kexts_being_added, number_of_old_kexts_being_removed);
1300         }
1301         else
1302         {
1303             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);
1304         }
1305     }
1306 
1307 
1308     if (number_of_new_kexts_being_added > 0)
1309     {
1310         ModuleList loaded_module_list;
1311 
1312         const uint32_t num_of_new_kexts = kext_summaries.size();
1313         for (uint32_t new_kext = 0; new_kext < num_of_new_kexts; new_kext++)
1314         {
1315             if (to_be_added[new_kext] == true)
1316             {
1317                 KextImageInfo &image_info = kext_summaries[new_kext];
1318                 if (load_kexts)
1319                 {
1320                     if (!image_info.LoadImageUsingMemoryModule (m_process))
1321                     {
1322                         image_info.LoadImageAtFileAddress (m_process);
1323                     }
1324                 }
1325 
1326                 m_known_kexts.push_back(image_info);
1327 
1328                 if (image_info.GetModule() && m_process->GetStopID() == image_info.GetProcessStopId())
1329                     loaded_module_list.AppendIfNeeded (image_info.GetModule());
1330 
1331                 if (s && load_kexts)
1332                     s->Printf (".");
1333 
1334                 if (log)
1335                     kext_summaries[new_kext].PutToLog (log);
1336             }
1337         }
1338         m_process->GetTarget().ModulesDidLoad (loaded_module_list);
1339     }
1340 
1341     if (number_of_old_kexts_being_removed > 0)
1342     {
1343         ModuleList loaded_module_list;
1344         const uint32_t num_of_old_kexts = m_known_kexts.size();
1345         for (uint32_t old_kext = 0; old_kext < num_of_old_kexts; old_kext++)
1346         {
1347             ModuleList unloaded_module_list;
1348             if (to_be_removed[old_kext])
1349             {
1350                 KextImageInfo &image_info = m_known_kexts[old_kext];
1351                 // You can't unload the kernel.
1352                 if (!image_info.IsKernel())
1353                 {
1354                     if (image_info.GetModule())
1355                     {
1356                         unloaded_module_list.AppendIfNeeded (image_info.GetModule());
1357                     }
1358                     if (s)
1359                         s->Printf (".");
1360                     image_info.Clear();
1361                     // should pull it out of the KextImageInfos vector but that would mutate the list and invalidate
1362                     // the to_be_removed bool vector; leaving it in place once Cleared() is relatively harmless.
1363                 }
1364             }
1365             m_process->GetTarget().ModulesDidUnload (unloaded_module_list, false);
1366         }
1367     }
1368 
1369     if (s && load_kexts)
1370     {
1371         s->Printf (" done.\n");
1372         s->Flush ();
1373     }
1374 
1375     return true;
1376 }
1377 
1378 uint32_t
1379 DynamicLoaderDarwinKernel::ReadKextSummaries (const Address &kext_summary_addr,
1380                                               uint32_t image_infos_count,
1381                                               KextImageInfo::collection &image_infos)
1382 {
1383     const ByteOrder endian = m_kernel.GetByteOrder();
1384     const uint32_t addr_size = m_kernel.GetAddressByteSize();
1385 
1386     image_infos.resize(image_infos_count);
1387     const size_t count = image_infos.size() * m_kext_summary_header.entry_size;
1388     DataBufferHeap data(count, 0);
1389     Error error;
1390 
1391     const bool prefer_file_cache = false;
1392     const size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary_addr,
1393                                                                  prefer_file_cache,
1394                                                                  data.GetBytes(),
1395                                                                  data.GetByteSize(),
1396                                                                  error);
1397     if (bytes_read == count)
1398     {
1399 
1400         DataExtractor extractor (data.GetBytes(), data.GetByteSize(), endian, addr_size);
1401         uint32_t i=0;
1402         for (uint32_t kext_summary_offset = 0;
1403              i < image_infos.size() && extractor.ValidOffsetForDataOfSize(kext_summary_offset, m_kext_summary_header.entry_size);
1404              ++i, kext_summary_offset += m_kext_summary_header.entry_size)
1405         {
1406             lldb::offset_t offset = kext_summary_offset;
1407             const void *name_data = extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME);
1408             if (name_data == NULL)
1409                 break;
1410             image_infos[i].SetName ((const char *) name_data);
1411             UUID uuid (extractor.GetData (&offset, 16), 16);
1412             image_infos[i].SetUUID (uuid);
1413             image_infos[i].SetLoadAddress (extractor.GetU64(&offset));
1414             image_infos[i].SetSize (extractor.GetU64(&offset));
1415         }
1416         if (i < image_infos.size())
1417             image_infos.resize(i);
1418     }
1419     else
1420     {
1421         image_infos.clear();
1422     }
1423     return image_infos.size();
1424 }
1425 
1426 bool
1427 DynamicLoaderDarwinKernel::ReadAllKextSummaries ()
1428 {
1429     Mutex::Locker locker(m_mutex);
1430 
1431     if (ReadKextSummaryHeader ())
1432     {
1433         if (m_kext_summary_header.entry_count > 0 && m_kext_summary_header_addr.IsValid())
1434         {
1435             Address summary_addr (m_kext_summary_header_addr);
1436             summary_addr.Slide(m_kext_summary_header.GetSize());
1437             if (!ParseKextSummaries (summary_addr, m_kext_summary_header.entry_count))
1438             {
1439                 m_known_kexts.clear();
1440             }
1441             return true;
1442         }
1443     }
1444     return false;
1445 }
1446 
1447 //----------------------------------------------------------------------
1448 // Dump an image info structure to the file handle provided.
1449 //----------------------------------------------------------------------
1450 void
1451 DynamicLoaderDarwinKernel::KextImageInfo::PutToLog (Log *log) const
1452 {
1453     if (log == NULL)
1454         return;
1455     const uint8_t *u = (uint8_t *) m_uuid.GetBytes();
1456 
1457     if (m_load_address == LLDB_INVALID_ADDRESS)
1458     {
1459         if (u)
1460         {
1461             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)",
1462                         u[ 0], u[ 1], u[ 2], u[ 3],
1463                         u[ 4], u[ 5], u[ 6], u[ 7],
1464                         u[ 8], u[ 9], u[10], u[11],
1465                         u[12], u[13], u[14], u[15],
1466                         m_name.c_str());
1467         }
1468         else
1469             log->Printf("\tname=\"%s\" (UNLOADED)", m_name.c_str());
1470     }
1471     else
1472     {
1473         if (u)
1474         {
1475             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\"",
1476                         m_load_address, m_size,
1477                         u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7],
1478                         u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15],
1479                         m_name.c_str());
1480         }
1481         else
1482         {
1483             log->Printf("\t[0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") name=\"%s\"",
1484                         m_load_address, m_load_address+m_size, m_name.c_str());
1485         }
1486     }
1487 }
1488 
1489 //----------------------------------------------------------------------
1490 // Dump the _dyld_all_image_infos members and all current image infos
1491 // that we have parsed to the file handle provided.
1492 //----------------------------------------------------------------------
1493 void
1494 DynamicLoaderDarwinKernel::PutToLog(Log *log) const
1495 {
1496     if (log == NULL)
1497         return;
1498 
1499     Mutex::Locker locker(m_mutex);
1500     log->Printf("gLoadedKextSummaries = 0x%16.16" PRIx64 " { version=%u, entry_size=%u, entry_count=%u }",
1501                 m_kext_summary_header_addr.GetFileAddress(),
1502                 m_kext_summary_header.version,
1503                 m_kext_summary_header.entry_size,
1504                 m_kext_summary_header.entry_count);
1505 
1506     size_t i;
1507     const size_t count = m_known_kexts.size();
1508     if (count > 0)
1509     {
1510         log->PutCString("Loaded:");
1511         for (i = 0; i<count; i++)
1512             m_known_kexts[i].PutToLog(log);
1513     }
1514 }
1515 
1516 void
1517 DynamicLoaderDarwinKernel::PrivateInitialize(Process *process)
1518 {
1519     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1520     Clear(true);
1521     m_process = process;
1522 }
1523 
1524 void
1525 DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded ()
1526 {
1527     if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.GetModule())
1528     {
1529         DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1530 
1531 
1532         const bool internal_bp = true;
1533         const bool hardware = false;
1534         const LazyBool skip_prologue = eLazyBoolNo;
1535         FileSpecList module_spec_list;
1536         module_spec_list.Append (m_kernel.GetModule()->GetFileSpec());
1537         Breakpoint *bp = m_process->GetTarget().CreateBreakpoint (&module_spec_list,
1538                                                                   NULL,
1539                                                                   "OSKextLoadedKextSummariesUpdated",
1540                                                                   eFunctionNameTypeFull,
1541                                                                   skip_prologue,
1542                                                                   internal_bp,
1543                                                                   hardware).get();
1544 
1545         bp->SetCallback (DynamicLoaderDarwinKernel::BreakpointHitCallback, this, true);
1546         m_break_id = bp->GetID();
1547     }
1548 }
1549 
1550 //----------------------------------------------------------------------
1551 // Member function that gets called when the process state changes.
1552 //----------------------------------------------------------------------
1553 void
1554 DynamicLoaderDarwinKernel::PrivateProcessStateChanged (Process *process, StateType state)
1555 {
1556     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, StateAsCString(state));
1557     switch (state)
1558     {
1559     case eStateConnected:
1560     case eStateAttaching:
1561     case eStateLaunching:
1562     case eStateInvalid:
1563     case eStateUnloaded:
1564     case eStateExited:
1565     case eStateDetached:
1566         Clear(false);
1567         break;
1568 
1569     case eStateStopped:
1570         UpdateIfNeeded();
1571         break;
1572 
1573     case eStateRunning:
1574     case eStateStepping:
1575     case eStateCrashed:
1576     case eStateSuspended:
1577         break;
1578     }
1579 }
1580 
1581 ThreadPlanSP
1582 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
1583 {
1584     ThreadPlanSP thread_plan_sp;
1585     Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1586     if (log)
1587         log->Printf ("Could not find symbol for step through.");
1588     return thread_plan_sp;
1589 }
1590 
1591 Error
1592 DynamicLoaderDarwinKernel::CanLoadImage ()
1593 {
1594     Error error;
1595     error.SetErrorString("always unsafe to load or unload shared libraries in the darwin kernel");
1596     return error;
1597 }
1598 
1599 void
1600 DynamicLoaderDarwinKernel::Initialize()
1601 {
1602     PluginManager::RegisterPlugin (GetPluginNameStatic(),
1603                                    GetPluginDescriptionStatic(),
1604                                    CreateInstance,
1605                                    DebuggerInitialize);
1606 }
1607 
1608 void
1609 DynamicLoaderDarwinKernel::Terminate()
1610 {
1611     PluginManager::UnregisterPlugin (CreateInstance);
1612 }
1613 
1614 void
1615 DynamicLoaderDarwinKernel::DebuggerInitialize (lldb_private::Debugger &debugger)
1616 {
1617     if (!PluginManager::GetSettingForDynamicLoaderPlugin (debugger, DynamicLoaderDarwinKernelProperties::GetSettingName()))
1618     {
1619         const bool is_global_setting = true;
1620         PluginManager::CreateSettingForDynamicLoaderPlugin (debugger,
1621                                                             GetGlobalProperties()->GetValueProperties(),
1622                                                             ConstString ("Properties for the DynamicLoaderDarwinKernel plug-in."),
1623                                                             is_global_setting);
1624     }
1625 }
1626 
1627 lldb_private::ConstString
1628 DynamicLoaderDarwinKernel::GetPluginNameStatic()
1629 {
1630     static ConstString g_name("darwin-kernel");
1631     return g_name;
1632 }
1633 
1634 const char *
1635 DynamicLoaderDarwinKernel::GetPluginDescriptionStatic()
1636 {
1637     return "Dynamic loader plug-in that watches for shared library loads/unloads in the MacOSX kernel.";
1638 }
1639 
1640 
1641 //------------------------------------------------------------------
1642 // PluginInterface protocol
1643 //------------------------------------------------------------------
1644 lldb_private::ConstString
1645 DynamicLoaderDarwinKernel::GetPluginName()
1646 {
1647     return GetPluginNameStatic();
1648 }
1649 
1650 uint32_t
1651 DynamicLoaderDarwinKernel::GetPluginVersion()
1652 {
1653     return 1;
1654 }
1655 
1656 lldb::ByteOrder
1657 DynamicLoaderDarwinKernel::GetByteOrderFromMagic (uint32_t magic)
1658 {
1659     switch (magic)
1660     {
1661         case llvm::MachO::MH_MAGIC:
1662         case llvm::MachO::MH_MAGIC_64:
1663             return lldb::endian::InlHostByteOrder();
1664 
1665         case llvm::MachO::MH_CIGAM:
1666         case llvm::MachO::MH_CIGAM_64:
1667             if (lldb::endian::InlHostByteOrder() == lldb::eByteOrderBig)
1668                 return lldb::eByteOrderLittle;
1669             else
1670                 return lldb::eByteOrderBig;
1671 
1672         default:
1673             break;
1674     }
1675     return lldb::eByteOrderInvalid;
1676 }
1677 
1678