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