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