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