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/Breakpoint/StoppointCallbackContext.h"
11 #include "lldb/Core/DataBuffer.h"
12 #include "lldb/Core/DataBufferHeap.h"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/Log.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/PluginManager.h"
17 #include "lldb/Core/State.h"
18 #include "lldb/Symbol/ObjectFile.h"
19 #include "lldb/Target/ObjCLanguageRuntime.h"
20 #include "lldb/Target/RegisterContext.h"
21 #include "lldb/Target/Target.h"
22 #include "lldb/Target/Thread.h"
23 #include "lldb/Target/ThreadPlanRunToAddress.h"
24 #include "lldb/Target/StackFrame.h"
25 
26 #include "DynamicLoaderDarwinKernel.h"
27 
28 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
29 #ifdef ENABLE_DEBUG_PRINTF
30 #include <stdio.h>
31 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
32 #else
33 #define DEBUG_PRINTF(fmt, ...)
34 #endif
35 
36 using namespace lldb;
37 using namespace lldb_private;
38 
39 /// FIXME - The ObjC Runtime trampoline handler doesn't really belong here.
40 /// I am putting it here so I can invoke it in the Trampoline code here, but
41 /// it should be moved to the ObjC Runtime support when it is set up.
42 
43 
44 //----------------------------------------------------------------------
45 // Create an instance of this class. This function is filled into
46 // the plugin info class that gets handed out by the plugin factory and
47 // allows the lldb to instantiate an instance of this class.
48 //----------------------------------------------------------------------
49 DynamicLoader *
50 DynamicLoaderDarwinKernel::CreateInstance (Process* process, bool force)
51 {
52     bool create = force;
53     if (!create)
54     {
55         Module* exe_module = process->GetTarget().GetExecutableModulePointer();
56         if (exe_module)
57         {
58             ObjectFile *object_file = exe_module->GetObjectFile();
59             if (object_file)
60             {
61                 create = (object_file->GetStrata() == ObjectFile::eStrataKernel);
62             }
63         }
64 
65         if (create)
66         {
67             const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple();
68             create = triple_ref.getOS() == llvm::Triple::Darwin && triple_ref.getVendor() == llvm::Triple::Apple;
69         }
70     }
71 
72     if (create)
73     {
74         process->SetCanJIT(false);
75         return new DynamicLoaderDarwinKernel (process);
76     }
77     return NULL;
78 }
79 
80 //----------------------------------------------------------------------
81 // Constructor
82 //----------------------------------------------------------------------
83 DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel (Process* process) :
84     DynamicLoader(process),
85     m_kernel(),
86     m_kext_summary_header_ptr_addr (),
87     m_kext_summary_header_addr (),
88     m_kext_summary_header (),
89     m_kext_summaries(),
90     m_mutex(Mutex::eMutexTypeRecursive),
91     m_break_id (LLDB_INVALID_BREAK_ID)
92 {
93 }
94 
95 //----------------------------------------------------------------------
96 // Destructor
97 //----------------------------------------------------------------------
98 DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel()
99 {
100     Clear(true);
101 }
102 
103 void
104 DynamicLoaderDarwinKernel::UpdateIfNeeded()
105 {
106     LoadKernelModuleIfNeeded();
107     SetNotificationBreakpointIfNeeded ();
108 }
109 //------------------------------------------------------------------
110 /// Called after attaching a process.
111 ///
112 /// Allow DynamicLoader plug-ins to execute some code after
113 /// attaching to a process.
114 //------------------------------------------------------------------
115 void
116 DynamicLoaderDarwinKernel::DidAttach ()
117 {
118     PrivateInitialize(m_process);
119     UpdateIfNeeded();
120 }
121 
122 //------------------------------------------------------------------
123 /// Called after attaching a process.
124 ///
125 /// Allow DynamicLoader plug-ins to execute some code after
126 /// attaching to a process.
127 //------------------------------------------------------------------
128 void
129 DynamicLoaderDarwinKernel::DidLaunch ()
130 {
131     PrivateInitialize(m_process);
132     UpdateIfNeeded();
133 }
134 
135 
136 //----------------------------------------------------------------------
137 // Clear out the state of this class.
138 //----------------------------------------------------------------------
139 void
140 DynamicLoaderDarwinKernel::Clear (bool clear_process)
141 {
142     Mutex::Locker locker(m_mutex);
143 
144     if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
145         m_process->ClearBreakpointSiteByID(m_break_id);
146 
147     if (clear_process)
148         m_process = NULL;
149     m_kernel.Clear(false);
150     m_kext_summary_header_ptr_addr.Clear();
151     m_kext_summary_header_addr.Clear();
152     m_kext_summaries.clear();
153     m_break_id = LLDB_INVALID_BREAK_ID;
154 }
155 
156 
157 bool
158 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::LoadImageAtFileAddress (Process *process)
159 {
160     if (IsLoaded())
161         return true;
162 
163     if (module_sp)
164     {
165         bool changed = false;
166         if (module_sp->SetLoadAddress (process->GetTarget(), 0, changed))
167             load_process_stop_id = process->GetStopID();
168     }
169     return false;
170 }
171 
172 bool
173 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::LoadImageUsingMemoryModule (Process *process)
174 {
175     if (IsLoaded())
176         return true;
177 
178     bool uuid_is_valid = uuid.IsValid();
179 
180     Target &target = process->GetTarget();
181     ModuleSP memory_module_sp;
182     // Use the memory module as the module if we have one...
183     if (address != LLDB_INVALID_ADDRESS)
184     {
185         FileSpec file_spec;
186         if (module_sp)
187             file_spec = module_sp->GetFileSpec();
188         else
189             file_spec.SetFile (name, false);
190 
191         memory_module_sp = process->ReadModuleFromMemory (file_spec, address, false, false);
192         if (memory_module_sp && !uuid_is_valid)
193         {
194             uuid = memory_module_sp->GetUUID();
195             uuid_is_valid = uuid.IsValid();
196         }
197     }
198 
199     if (!module_sp)
200     {
201         bool uuid_is_valid = uuid.IsValid();
202         if (uuid_is_valid)
203         {
204             ModuleList &target_images = target.GetImages();
205             module_sp = target_images.FindModule(uuid);
206 
207             if (!module_sp)
208             {
209                 ModuleSpec module_spec;
210                 module_spec.GetUUID() = uuid;
211                 module_sp = target.GetSharedModule (module_spec);
212             }
213         }
214     }
215 
216 
217     if (memory_module_sp)
218     {
219         // Someone already supplied a file, make sure it is the right one.
220         if (module_sp)
221         {
222             if (module_sp->GetUUID() == memory_module_sp->GetUUID())
223             {
224                 ObjectFile *ondisk_object_file = module_sp->GetObjectFile();
225                 ObjectFile *memory_object_file = memory_module_sp->GetObjectFile();
226                 if (memory_object_file && ondisk_object_file)
227                 {
228                     SectionList *ondisk_section_list = ondisk_object_file->GetSectionList ();
229                     SectionList *memory_section_list = memory_object_file->GetSectionList ();
230                     if (memory_section_list && ondisk_section_list)
231                     {
232                         const uint32_t num_ondisk_sections = ondisk_section_list->GetSize();
233                         // There may be CTF sections in the memory image so we can't
234                         // always just compare the number of sections (which are actually
235                         // segments in mach-o parlance)
236                         uint32_t sect_idx = 0;
237 
238 
239                         // We now iterate through all sections in the file module
240                         // and look to see if the memory module has a load address
241                         // for that section.
242                         uint32_t num_sections_loaded = 0;
243                         for (sect_idx=0; sect_idx<num_ondisk_sections; ++sect_idx)
244                         {
245                             const Section *ondisk_section = ondisk_section_list->GetSectionAtIndex(sect_idx).get();
246                             if (ondisk_section)
247                             {
248                                 const Section *memory_section = memory_section_list->FindSectionByName(ondisk_section->GetName()).get();
249                                 if (memory_section)
250                                 {
251                                     target.GetSectionLoadList().SetSectionLoadAddress (ondisk_section, memory_section->GetFileAddress());
252                                     ++num_sections_loaded;
253                                 }
254                             }
255                         }
256                         if (num_sections_loaded > 0)
257                             load_process_stop_id = process->GetStopID();
258                         else
259                             module_sp.reset(); // No sections were loaded
260                     }
261                     else
262                         module_sp.reset(); // One or both section lists
263                 }
264                 else
265                     module_sp.reset(); // One or both object files missing
266             }
267             else
268                 module_sp.reset(); // UUID mismatch
269         }
270 
271         // Use the memory module as the module if we didn't like the file
272         // module we either found or were supplied with
273         if (!module_sp)
274         {
275             module_sp = memory_module_sp;
276             // Load the memory image in the target as all adresses are already correct
277             bool changed = false;
278             target.GetImages().Append (memory_module_sp);
279             if (module_sp->SetLoadAddress (target, 0, changed))
280                 load_process_stop_id = process->GetStopID();
281         }
282     }
283     bool is_loaded = IsLoaded();
284 
285     if (so_address.IsValid())
286     {
287         if (is_loaded)
288             so_address.SetLoadAddress (address, &target);
289         else
290             target.GetImages().ResolveFileAddress (address, so_address);
291 
292     }
293     return is_loaded;
294 }
295 
296 //----------------------------------------------------------------------
297 // Load the kernel module and initialize the "m_kernel" member. Return
298 // true _only_ if the kernel is loaded the first time through (subsequent
299 // calls to this function should return false after the kernel has been
300 // already loaded).
301 //----------------------------------------------------------------------
302 void
303 DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded()
304 {
305     if (!m_kext_summary_header_ptr_addr.IsValid())
306     {
307         m_kernel.Clear(false);
308         m_kernel.module_sp = m_process->GetTarget().GetExecutableModule();
309         strncpy(m_kernel.name, "mach_kernel", sizeof(m_kernel.name));
310         if (m_kernel.address == LLDB_INVALID_ADDRESS)
311         {
312             m_kernel.address = m_process->GetImageInfoAddress ();
313             if (m_kernel.address == LLDB_INVALID_ADDRESS && m_kernel.module_sp)
314             {
315                 // We didn't get a hint from the process, so we will
316                 // try the kernel at the address that it exists at in
317                 // the file if we have one
318                 ObjectFile *kernel_object_file = m_kernel.module_sp->GetObjectFile();
319                 if (kernel_object_file)
320                     m_kernel.address = kernel_object_file->GetHeaderAddress().GetFileAddress();
321             }
322         }
323 
324         if (m_kernel.address != LLDB_INVALID_ADDRESS)
325         {
326             if (!m_kernel.LoadImageUsingMemoryModule (m_process))
327             {
328                 m_kernel.LoadImageAtFileAddress (m_process);
329             }
330         }
331 
332         if (m_kernel.IsLoaded())
333         {
334             static ConstString kext_summary_symbol ("gLoadedKextSummaries");
335             const Symbol *symbol = m_kernel.module_sp->FindFirstSymbolWithNameAndType (kext_summary_symbol, eSymbolTypeData);
336             if (symbol)
337             {
338                 m_kext_summary_header_ptr_addr = symbol->GetAddress();
339                 // Update all image infos
340                 ReadAllKextSummaries ();
341             }
342         }
343         else
344         {
345             m_kernel.Clear(false);
346         }
347     }
348 }
349 
350 //----------------------------------------------------------------------
351 // Static callback function that gets called when our DYLD notification
352 // breakpoint gets hit. We update all of our image infos and then
353 // let our super class DynamicLoader class decide if we should stop
354 // or not (based on global preference).
355 //----------------------------------------------------------------------
356 bool
357 DynamicLoaderDarwinKernel::BreakpointHitCallback (void *baton,
358                                                   StoppointCallbackContext *context,
359                                                   user_id_t break_id,
360                                                   user_id_t break_loc_id)
361 {
362     return static_cast<DynamicLoaderDarwinKernel*>(baton)->BreakpointHit (context, break_id, break_loc_id);
363 }
364 
365 bool
366 DynamicLoaderDarwinKernel::BreakpointHit (StoppointCallbackContext *context,
367                                           user_id_t break_id,
368                                           user_id_t break_loc_id)
369 {
370     LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
371     if (log)
372         log->Printf ("DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
373 
374     ReadAllKextSummaries ();
375 
376     if (log)
377         PutToLog(log.get());
378 
379     return GetStopWhenImagesChange();
380 }
381 
382 
383 bool
384 DynamicLoaderDarwinKernel::ReadKextSummaryHeader ()
385 {
386     Mutex::Locker locker(m_mutex);
387 
388     // the all image infos is already valid for this process stop ID
389 
390     m_kext_summaries.clear();
391     if (m_kext_summary_header_ptr_addr.IsValid())
392     {
393         const uint32_t addr_size = m_kernel.GetAddressByteSize ();
394         const ByteOrder byte_order = m_kernel.GetByteOrder();
395         Error error;
396         // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure
397         // which is currenty 4 uint32_t and a pointer.
398         uint8_t buf[24];
399         DataExtractor data (buf, sizeof(buf), byte_order, addr_size);
400         const size_t count = 4 * sizeof(uint32_t) + addr_size;
401         const bool prefer_file_cache = false;
402         if (m_process->GetTarget().ReadPointerFromMemory (m_kext_summary_header_ptr_addr,
403                                                           prefer_file_cache,
404                                                           error,
405                                                           m_kext_summary_header_addr))
406         {
407             // We got a valid address for our kext summary header and make sure it isn't NULL
408             if (m_kext_summary_header_addr.IsValid() &&
409                 m_kext_summary_header_addr.GetFileAddress() != 0)
410             {
411                 const size_t bytes_read = m_process->GetTarget().ReadMemory (m_kext_summary_header_addr, prefer_file_cache, buf, count, error);
412                 if (bytes_read == count)
413                 {
414                     uint32_t offset = 0;
415                     m_kext_summary_header.version = data.GetU32(&offset);
416                     if (m_kext_summary_header.version >= 2)
417                     {
418                         m_kext_summary_header.entry_size = data.GetU32(&offset);
419                     }
420                     else
421                     {
422                         // Versions less than 2 didn't have an entry size, it was hard coded
423                         m_kext_summary_header.entry_size = KERNEL_MODULE_ENTRY_SIZE_VERSION_1;
424                     }
425                     m_kext_summary_header.entry_count = data.GetU32(&offset);
426                     return true;
427                 }
428             }
429         }
430     }
431     m_kext_summary_header_addr.Clear();
432     return false;
433 }
434 
435 
436 bool
437 DynamicLoaderDarwinKernel::ParseKextSummaries (const Address &kext_summary_addr,
438                                                uint32_t count)
439 {
440     OSKextLoadedKextSummary::collection kext_summaries;
441     LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
442     if (log)
443         log->Printf ("Adding %d modules.\n", count);
444 
445     Mutex::Locker locker(m_mutex);
446 
447     if (!ReadKextSummaries (kext_summary_addr, count, kext_summaries))
448         return false;
449 
450     Stream *s = &m_process->GetTarget().GetDebugger().GetOutputStream();
451     for (uint32_t i = 0; i < count; i++)
452     {
453         if (s)
454         {
455             const uint8_t *u = (const uint8_t *)kext_summaries[i].uuid.GetBytes();
456             if (u)
457             {
458                 s->Printf("Loading kext: %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 0x%16.16llx \"%s\"...",
459                           u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7],
460                           u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15],
461                           kext_summaries[i].address, kext_summaries[i].name);
462             }
463             else
464             {
465                 s->Printf("0x%16.16llx \"%s\"...", kext_summaries[i].address, kext_summaries[i].name);
466             }
467         }
468 
469         if (!kext_summaries[i].LoadImageUsingMemoryModule (m_process))
470             kext_summaries[i].LoadImageAtFileAddress (m_process);
471 
472         if (s)
473         {
474             if (kext_summaries[i].module_sp)
475             {
476                 if (kext_summaries[i].module_sp->GetFileSpec().GetDirectory())
477                     s->Printf("\n  found kext: %s/%s\n",
478                               kext_summaries[i].module_sp->GetFileSpec().GetDirectory().AsCString(),
479                               kext_summaries[i].module_sp->GetFileSpec().GetFilename().AsCString());
480                 else
481                     s->Printf("\n  found kext: %s\n",
482                               kext_summaries[i].module_sp->GetFileSpec().GetFilename().AsCString());
483             }
484             else
485                 s->Printf (" failed to locate/load.\n");
486         }
487 
488         if (log)
489             kext_summaries[i].PutToLog (log.get());
490     }
491     bool return_value = AddModulesUsingImageInfos (kext_summaries);
492     return return_value;
493 }
494 
495 // Adds the modules in image_infos to m_kext_summaries.
496 // NB don't call this passing in m_kext_summaries.
497 
498 bool
499 DynamicLoaderDarwinKernel::AddModulesUsingImageInfos (OSKextLoadedKextSummary::collection &image_infos)
500 {
501     // Now add these images to the main list.
502     ModuleList loaded_module_list;
503 
504     for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
505     {
506         OSKextLoadedKextSummary &image_info = image_infos[idx];
507         m_kext_summaries.push_back(image_info);
508 
509         if (image_info.module_sp && m_process->GetStopID() == image_info.load_process_stop_id)
510             loaded_module_list.AppendIfNeeded (image_infos[idx].module_sp);
511     }
512 
513     if (loaded_module_list.GetSize() > 0)
514     {
515         m_process->GetTarget().ModulesDidLoad (loaded_module_list);
516     }
517     return true;
518 }
519 
520 
521 uint32_t
522 DynamicLoaderDarwinKernel::ReadKextSummaries (const Address &kext_summary_addr,
523                                               uint32_t image_infos_count,
524                                               OSKextLoadedKextSummary::collection &image_infos)
525 {
526     const ByteOrder endian = m_kernel.GetByteOrder();
527     const uint32_t addr_size = m_kernel.GetAddressByteSize();
528 
529     image_infos.resize(image_infos_count);
530     const size_t count = image_infos.size() * m_kext_summary_header.entry_size;
531     DataBufferHeap data(count, 0);
532     Error error;
533 
534     Stream *s = &m_process->GetTarget().GetDebugger().GetOutputStream();
535 
536     if (s)
537         s->Printf ("Reading %u kext summaries...\n", image_infos_count);
538     const bool prefer_file_cache = false;
539     const size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary_addr,
540                                                                  prefer_file_cache,
541                                                                  data.GetBytes(),
542                                                                  data.GetByteSize(),
543                                                                  error);
544     if (bytes_read == count)
545     {
546 
547         DataExtractor extractor (data.GetBytes(), data.GetByteSize(), endian, addr_size);
548         uint32_t i=0;
549         for (uint32_t kext_summary_offset = 0;
550              i < image_infos.size() && extractor.ValidOffsetForDataOfSize(kext_summary_offset, m_kext_summary_header.entry_size);
551              ++i, kext_summary_offset += m_kext_summary_header.entry_size)
552         {
553             uint32_t offset = kext_summary_offset;
554             const void *name_data = extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME);
555             if (name_data == NULL)
556                 break;
557             memcpy (image_infos[i].name, name_data, KERNEL_MODULE_MAX_NAME);
558             image_infos[i].uuid.SetBytes(extractor.GetData (&offset, 16));
559             image_infos[i].address          = extractor.GetU64(&offset);
560             if (!image_infos[i].so_address.SetLoadAddress (image_infos[i].address, &m_process->GetTarget()))
561                 m_process->GetTarget().GetImages().ResolveFileAddress (image_infos[i].address, image_infos[i].so_address);
562             image_infos[i].size             = extractor.GetU64(&offset);
563             image_infos[i].version          = extractor.GetU64(&offset);
564             image_infos[i].load_tag         = extractor.GetU32(&offset);
565             image_infos[i].flags            = extractor.GetU32(&offset);
566             if ((offset - kext_summary_offset) < m_kext_summary_header.entry_size)
567             {
568                 image_infos[i].reference_list = extractor.GetU64(&offset);
569             }
570             else
571             {
572                 image_infos[i].reference_list = 0;
573             }
574 //            printf ("[%3u] %*.*s: address=0x%16.16llx, size=0x%16.16llx, version=0x%16.16llx, load_tag=0x%8.8x, flags=0x%8.8x\n",
575 //                    i,
576 //                    KERNEL_MODULE_MAX_NAME, KERNEL_MODULE_MAX_NAME,  (char *)name_data,
577 //                    image_infos[i].address,
578 //                    image_infos[i].size,
579 //                    image_infos[i].version,
580 //                    image_infos[i].load_tag,
581 //                    image_infos[i].flags);
582         }
583         if (i < image_infos.size())
584             image_infos.resize(i);
585     }
586     else
587     {
588         image_infos.clear();
589     }
590     return image_infos.size();
591 }
592 
593 bool
594 DynamicLoaderDarwinKernel::ReadAllKextSummaries ()
595 {
596     LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
597 
598     Mutex::Locker locker(m_mutex);
599 
600     if (ReadKextSummaryHeader ())
601     {
602         if (m_kext_summary_header.entry_count > 0 && m_kext_summary_header_addr.IsValid())
603         {
604             Address summary_addr (m_kext_summary_header_addr);
605             summary_addr.Slide(m_kext_summary_header.GetSize());
606             if (!ParseKextSummaries (summary_addr, m_kext_summary_header.entry_count))
607             {
608                 m_kext_summaries.clear();
609             }
610             return true;
611         }
612     }
613     return false;
614 }
615 
616 //----------------------------------------------------------------------
617 // Dump an image info structure to the file handle provided.
618 //----------------------------------------------------------------------
619 void
620 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::PutToLog (Log *log) const
621 {
622     if (log == NULL)
623         return;
624     const uint8_t *u = (uint8_t *)uuid.GetBytes();
625 
626     if (address == LLDB_INVALID_ADDRESS)
627     {
628         if (u)
629         {
630             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)",
631                         u[ 0], u[ 1], u[ 2], u[ 3],
632                         u[ 4], u[ 5], u[ 6], u[ 7],
633                         u[ 8], u[ 9], u[10], u[11],
634                         u[12], u[13], u[14], u[15],
635                         name);
636         }
637         else
638             log->Printf("\tname=\"%s\" (UNLOADED)", name);
639     }
640     else
641     {
642         if (u)
643         {
644             log->Printf("\taddr=0x%16.16llx size=0x%16.16llx version=0x%16.16llx load-tag=0x%8.8x flags=0x%8.8x ref-list=0x%16.16llx 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\"",
645                         address, size, version, load_tag, flags, reference_list,
646                         u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7],
647                         u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15],
648                         name);
649         }
650         else
651         {
652             log->Printf("\t[0x%16.16llx - 0x%16.16llx) version=0x%16.16llx load-tag=0x%8.8x flags=0x%8.8x ref-list=0x%16.16llx name=\"%s\"",
653                         address, address+size, version, load_tag, flags, reference_list,
654                         name);
655         }
656     }
657 }
658 
659 //----------------------------------------------------------------------
660 // Dump the _dyld_all_image_infos members and all current image infos
661 // that we have parsed to the file handle provided.
662 //----------------------------------------------------------------------
663 void
664 DynamicLoaderDarwinKernel::PutToLog(Log *log) const
665 {
666     if (log == NULL)
667         return;
668 
669     Mutex::Locker locker(m_mutex);
670     log->Printf("gLoadedKextSummaries = 0x%16.16llx { version=%u, entry_size=%u, entry_count=%u }",
671                 m_kext_summary_header_addr.GetFileAddress(),
672                 m_kext_summary_header.version,
673                 m_kext_summary_header.entry_size,
674                 m_kext_summary_header.entry_count);
675 
676     size_t i;
677     const size_t count = m_kext_summaries.size();
678     if (count > 0)
679     {
680         log->PutCString("Loaded:");
681         for (i = 0; i<count; i++)
682             m_kext_summaries[i].PutToLog(log);
683     }
684 }
685 
686 void
687 DynamicLoaderDarwinKernel::PrivateInitialize(Process *process)
688 {
689     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
690     Clear(true);
691     m_process = process;
692     m_process->GetTarget().GetSectionLoadList().Clear();
693 }
694 
695 void
696 DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded ()
697 {
698     if (m_break_id == LLDB_INVALID_BREAK_ID && m_kernel.module_sp)
699     {
700         DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
701 
702 
703         const bool internal_bp = false;
704         const LazyBool skip_prologue = eLazyBoolNo;
705         FileSpecList module_spec_list;
706         module_spec_list.Append (m_kernel.module_sp->GetFileSpec());
707         Breakpoint *bp = m_process->GetTarget().CreateBreakpoint (&module_spec_list,
708                                                                   NULL,
709                                                                   "OSKextLoadedKextSummariesUpdated",
710                                                                   eFunctionNameTypeFull,
711                                                                   internal_bp,
712                                                                   skip_prologue).get();
713 
714         bp->SetCallback (DynamicLoaderDarwinKernel::BreakpointHitCallback, this, true);
715         m_break_id = bp->GetID();
716     }
717 }
718 
719 //----------------------------------------------------------------------
720 // Member function that gets called when the process state changes.
721 //----------------------------------------------------------------------
722 void
723 DynamicLoaderDarwinKernel::PrivateProcessStateChanged (Process *process, StateType state)
724 {
725     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, StateAsCString(state));
726     switch (state)
727     {
728     case eStateConnected:
729     case eStateAttaching:
730     case eStateLaunching:
731     case eStateInvalid:
732     case eStateUnloaded:
733     case eStateExited:
734     case eStateDetached:
735         Clear(false);
736         break;
737 
738     case eStateStopped:
739         UpdateIfNeeded();
740         break;
741 
742     case eStateRunning:
743     case eStateStepping:
744     case eStateCrashed:
745     case eStateSuspended:
746         break;
747 
748     default:
749         break;
750     }
751 }
752 
753 ThreadPlanSP
754 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
755 {
756     ThreadPlanSP thread_plan_sp;
757     LogSP log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
758     if (log)
759         log->Printf ("Could not find symbol for step through.");
760     return thread_plan_sp;
761 }
762 
763 Error
764 DynamicLoaderDarwinKernel::CanLoadImage ()
765 {
766     Error error;
767     error.SetErrorString("always unsafe to load or unload shared libraries in the darwin kernel");
768     return error;
769 }
770 
771 void
772 DynamicLoaderDarwinKernel::Initialize()
773 {
774     PluginManager::RegisterPlugin (GetPluginNameStatic(),
775                                    GetPluginDescriptionStatic(),
776                                    CreateInstance);
777 }
778 
779 void
780 DynamicLoaderDarwinKernel::Terminate()
781 {
782     PluginManager::UnregisterPlugin (CreateInstance);
783 }
784 
785 
786 const char *
787 DynamicLoaderDarwinKernel::GetPluginNameStatic()
788 {
789     return "dynamic-loader.macosx-kernel";
790 }
791 
792 const char *
793 DynamicLoaderDarwinKernel::GetPluginDescriptionStatic()
794 {
795     return "Dynamic loader plug-in that watches for shared library loads/unloads in the MacOSX kernel.";
796 }
797 
798 
799 //------------------------------------------------------------------
800 // PluginInterface protocol
801 //------------------------------------------------------------------
802 const char *
803 DynamicLoaderDarwinKernel::GetPluginName()
804 {
805     return "DynamicLoaderDarwinKernel";
806 }
807 
808 const char *
809 DynamicLoaderDarwinKernel::GetShortPluginName()
810 {
811     return GetPluginNameStatic();
812 }
813 
814 uint32_t
815 DynamicLoaderDarwinKernel::GetPluginVersion()
816 {
817     return 1;
818 }
819 
820