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                 SectionList *section_list = object_file->GetSectionList();
62                 if (section_list)
63                 {
64                     static ConstString g_kld_section_name ("__KLD");
65                     if (section_list->FindSectionByName (g_kld_section_name))
66                     {
67                         create = true;
68                     }
69                 }
70             }
71         }
72 
73         if (create)
74         {
75             const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple();
76             create = triple_ref.getOS() == llvm::Triple::Darwin && triple_ref.getVendor() == llvm::Triple::Apple;
77         }
78     }
79 
80     if (create)
81     {
82         process->SetCanJIT(false);
83         return new DynamicLoaderDarwinKernel (process);
84     }
85     return NULL;
86 }
87 
88 //----------------------------------------------------------------------
89 // Constructor
90 //----------------------------------------------------------------------
91 DynamicLoaderDarwinKernel::DynamicLoaderDarwinKernel (Process* process) :
92     DynamicLoader(process),
93     m_kernel(),
94     m_kext_summary_header_ptr_addr (),
95     m_kext_summary_header_addr (),
96     m_kext_summary_header (),
97     m_kext_summaries(),
98     m_mutex(Mutex::eMutexTypeRecursive),
99     m_break_id (LLDB_INVALID_BREAK_ID)
100 {
101 }
102 
103 //----------------------------------------------------------------------
104 // Destructor
105 //----------------------------------------------------------------------
106 DynamicLoaderDarwinKernel::~DynamicLoaderDarwinKernel()
107 {
108     Clear(true);
109 }
110 
111 void
112 DynamicLoaderDarwinKernel::UpdateIfNeeded()
113 {
114     LoadKernelModuleIfNeeded();
115     SetNotificationBreakpointIfNeeded ();
116 }
117 //------------------------------------------------------------------
118 /// Called after attaching a process.
119 ///
120 /// Allow DynamicLoader plug-ins to execute some code after
121 /// attaching to a process.
122 //------------------------------------------------------------------
123 void
124 DynamicLoaderDarwinKernel::DidAttach ()
125 {
126     PrivateInitialize(m_process);
127     UpdateIfNeeded();
128 }
129 
130 //------------------------------------------------------------------
131 /// Called after attaching a process.
132 ///
133 /// Allow DynamicLoader plug-ins to execute some code after
134 /// attaching to a process.
135 //------------------------------------------------------------------
136 void
137 DynamicLoaderDarwinKernel::DidLaunch ()
138 {
139     PrivateInitialize(m_process);
140     UpdateIfNeeded();
141 }
142 
143 
144 //----------------------------------------------------------------------
145 // Clear out the state of this class.
146 //----------------------------------------------------------------------
147 void
148 DynamicLoaderDarwinKernel::Clear (bool clear_process)
149 {
150     Mutex::Locker locker(m_mutex);
151 
152     if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
153         m_process->ClearBreakpointSiteByID(m_break_id);
154 
155     if (clear_process)
156         m_process = NULL;
157     m_kernel.Clear(false);
158     m_kext_summary_header_ptr_addr.Clear();
159     m_kext_summary_header_addr.Clear();
160     m_kext_summaries.clear();
161     m_break_id = LLDB_INVALID_BREAK_ID;
162 }
163 
164 
165 //----------------------------------------------------------------------
166 // Load the kernel module and initialize the "m_kernel" member. Return
167 // true _only_ if the kernel is loaded the first time through (subsequent
168 // calls to this function should return false after the kernel has been
169 // already loaded).
170 //----------------------------------------------------------------------
171 void
172 DynamicLoaderDarwinKernel::LoadKernelModuleIfNeeded()
173 {
174     if (!m_kext_summary_header_ptr_addr.IsValid())
175     {
176         m_kernel.Clear(false);
177         m_kernel.module_sp = m_process->GetTarget().GetExecutableModule();
178         if (m_kernel.module_sp)
179         {
180             static ConstString mach_header_name ("_mh_execute_header");
181             static ConstString kext_summary_symbol ("gLoadedKextSummaries");
182             const Symbol *symbol = NULL;
183             symbol = m_kernel.module_sp->FindFirstSymbolWithNameAndType (kext_summary_symbol, eSymbolTypeData);
184             if (symbol)
185                 m_kext_summary_header_ptr_addr = symbol->GetValue();
186 
187             symbol = m_kernel.module_sp->FindFirstSymbolWithNameAndType (mach_header_name, eSymbolTypeAbsolute);
188             if (symbol)
189             {
190                 // The "_mh_execute_header" symbol is absolute and not a section based
191                 // symbol that will have a valid address, so we need to resolve it...
192                 m_process->GetTarget().GetImages().ResolveFileAddress (symbol->GetValue().GetFileAddress(), m_kernel.so_address);
193                 DataExtractor data; // Load command data
194                 if (ReadMachHeader (m_kernel, &data))
195                 {
196                     if (m_kernel.header.filetype == llvm::MachO::HeaderFileTypeExecutable)
197                     {
198                         if (ParseLoadCommands (data, m_kernel))
199                             UpdateImageLoadAddress (m_kernel);
200 
201                         // Update all image infos
202                         ReadAllKextSummaries ();
203                     }
204                 }
205                 else
206                 {
207                     m_kernel.Clear(false);
208                 }
209             }
210         }
211     }
212 }
213 
214 bool
215 DynamicLoaderDarwinKernel::FindTargetModule (OSKextLoadedKextSummary &image_info, bool can_create, bool *did_create_ptr)
216 {
217     if (did_create_ptr)
218         *did_create_ptr = false;
219 
220     const bool image_info_uuid_is_valid = image_info.uuid.IsValid();
221 
222     if (image_info.module_sp)
223     {
224         if (image_info_uuid_is_valid)
225         {
226             if (image_info.module_sp->GetUUID() == image_info.uuid)
227                 return true;
228             else
229                 image_info.module_sp.reset();
230         }
231         else
232             return true;
233     }
234 
235     ModuleList &target_images = m_process->GetTarget().GetImages();
236     if (image_info_uuid_is_valid)
237         image_info.module_sp = target_images.FindModule(image_info.uuid);
238 
239     if (image_info.module_sp)
240         return true;
241 
242     ArchSpec arch (image_info.GetArchitecture ());
243     if (can_create)
244     {
245         if (image_info_uuid_is_valid)
246         {
247             image_info.module_sp = m_process->GetTarget().GetSharedModule (FileSpec(),
248                                                                            arch,
249                                                                            &image_info.uuid);
250             if (did_create_ptr)
251                 *did_create_ptr = image_info.module_sp;
252         }
253     }
254     return image_info.module_sp;
255 }
256 
257 bool
258 DynamicLoaderDarwinKernel::UpdateCommPageLoadAddress(Module *module)
259 {
260     bool changed = false;
261     if (module)
262     {
263         ObjectFile *image_object_file = module->GetObjectFile();
264         if (image_object_file)
265         {
266             SectionList *section_list = image_object_file->GetSectionList ();
267             if (section_list)
268             {
269                 uint32_t num_sections = section_list->GetSize();
270                 for (uint32_t i=0; i<num_sections; ++i)
271                 {
272                     Section* section = section_list->GetSectionAtIndex (i).get();
273                     if (section)
274                     {
275                         const addr_t new_section_load_addr = section->GetFileAddress ();
276                         const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section);
277                         if (old_section_load_addr == LLDB_INVALID_ADDRESS ||
278                             old_section_load_addr != new_section_load_addr)
279                         {
280                             if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section, section->GetFileAddress ()))
281                                 changed = true;
282                         }
283                     }
284                 }
285             }
286         }
287     }
288     return changed;
289 }
290 
291 //----------------------------------------------------------------------
292 // Update the load addresses for all segments in MODULE using the
293 // updated INFO that is passed in.
294 //----------------------------------------------------------------------
295 bool
296 DynamicLoaderDarwinKernel::UpdateImageLoadAddress (OSKextLoadedKextSummary& info)
297 {
298     Module *module = info.module_sp.get();
299     bool changed = false;
300     if (module)
301     {
302         ObjectFile *image_object_file = module->GetObjectFile();
303         if (image_object_file)
304         {
305             SectionList *section_list = image_object_file->GetSectionList ();
306             if (section_list)
307             {
308                 // We now know the slide amount, so go through all sections
309                 // and update the load addresses with the correct values.
310                 uint32_t num_segments = info.segments.size();
311                 for (uint32_t i=0; i<num_segments; ++i)
312                 {
313                     const addr_t new_section_load_addr = info.segments[i].vmaddr;
314                     if (section_list->FindSectionByName(info.segments[i].name))
315                     {
316                         SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
317                         if (section_sp)
318                         {
319                             const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section_sp.get());
320                             if (old_section_load_addr == LLDB_INVALID_ADDRESS ||
321                                 old_section_load_addr != new_section_load_addr)
322                             {
323                                 if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section_sp.get(), new_section_load_addr))
324                                     changed = true;
325                             }
326                         }
327                         else
328                         {
329                             Host::SystemLog (Host::eSystemLogWarning, "warning: unable to find and load segment named '%s' at 0x%llx in '%s/%s' in macosx dynamic loader plug-in.\n",
330                                              info.segments[i].name.AsCString("<invalid>"),
331                                              (uint64_t)new_section_load_addr,
332                                              image_object_file->GetFileSpec().GetDirectory().AsCString(),
333                                              image_object_file->GetFileSpec().GetFilename().AsCString());
334                         }
335                     }
336                     else
337                     {
338                         // The segment name is empty which means this is a .o file.
339                         // Object files in LLDB end up getting reorganized so that
340                         // the segment name that is in the section is promoted into
341                         // an actual segment, so we just need to go through all sections
342                         // and slide them by a single amount.
343 
344                         uint32_t num_sections = section_list->GetSize();
345                         for (uint32_t i=0; i<num_sections; ++i)
346                         {
347                             Section* section = section_list->GetSectionAtIndex (i).get();
348                             if (section)
349                             {
350                                 if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section, section->GetFileAddress() + new_section_load_addr))
351                                     changed = true;
352                             }
353                         }
354                     }
355                 }
356             }
357         }
358     }
359     return changed;
360 }
361 
362 //----------------------------------------------------------------------
363 // Update the load addresses for all segments in MODULE using the
364 // updated INFO that is passed in.
365 //----------------------------------------------------------------------
366 bool
367 DynamicLoaderDarwinKernel::UnloadImageLoadAddress (OSKextLoadedKextSummary& info)
368 {
369     Module *module = info.module_sp.get();
370     bool changed = false;
371     if (module)
372     {
373         ObjectFile *image_object_file = module->GetObjectFile();
374         if (image_object_file)
375         {
376             SectionList *section_list = image_object_file->GetSectionList ();
377             if (section_list)
378             {
379                 uint32_t num_segments = info.segments.size();
380                 for (uint32_t i=0; i<num_segments; ++i)
381                 {
382                     SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
383                     if (section_sp)
384                     {
385                         const addr_t old_section_load_addr = info.segments[i].vmaddr;
386                         if (m_process->GetTarget().GetSectionLoadList().SetSectionUnloaded (section_sp.get(), old_section_load_addr))
387                             changed = true;
388                     }
389                     else
390                     {
391                         Host::SystemLog (Host::eSystemLogWarning,
392                                          "warning: unable to find and unload segment named '%s' in '%s/%s' in macosx dynamic loader plug-in.\n",
393                                          info.segments[i].name.AsCString("<invalid>"),
394                                          image_object_file->GetFileSpec().GetDirectory().AsCString(),
395                                          image_object_file->GetFileSpec().GetFilename().AsCString());
396                     }
397                 }
398             }
399         }
400     }
401     return changed;
402 }
403 
404 
405 //----------------------------------------------------------------------
406 // Static callback function that gets called when our DYLD notification
407 // breakpoint gets hit. We update all of our image infos and then
408 // let our super class DynamicLoader class decide if we should stop
409 // or not (based on global preference).
410 //----------------------------------------------------------------------
411 bool
412 DynamicLoaderDarwinKernel::BreakpointHitCallback (void *baton,
413                                                   StoppointCallbackContext *context,
414                                                   user_id_t break_id,
415                                                   user_id_t break_loc_id)
416 {
417     return static_cast<DynamicLoaderDarwinKernel*>(baton)->BreakpointHit (context, break_id, break_loc_id);
418 }
419 
420 bool
421 DynamicLoaderDarwinKernel::BreakpointHit (StoppointCallbackContext *context,
422                                           user_id_t break_id,
423                                           user_id_t break_loc_id)
424 {
425     LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
426     if (log)
427         log->Printf ("DynamicLoaderDarwinKernel::BreakpointHit (...)\n");
428 
429     ReadAllKextSummaries ();
430 
431     if (log)
432         PutToLog(log.get());
433 
434     return GetStopWhenImagesChange();
435 }
436 
437 
438 bool
439 DynamicLoaderDarwinKernel::ReadKextSummaryHeader ()
440 {
441     Mutex::Locker locker(m_mutex);
442 
443     // the all image infos is already valid for this process stop ID
444 
445     m_kext_summaries.clear();
446     if (m_kext_summary_header_ptr_addr.IsValid())
447     {
448         const uint32_t addr_size = m_kernel.GetAddressByteSize ();
449         const ByteOrder byte_order = m_kernel.GetByteOrder();
450         Error error;
451         // Read enough bytes for a "OSKextLoadedKextSummaryHeader" structure
452         // which is currenty 4 uint32_t and a pointer.
453         uint8_t buf[24];
454         DataExtractor data (buf, sizeof(buf), byte_order, addr_size);
455         const size_t count = 4 * sizeof(uint32_t) + addr_size;
456         const bool prefer_file_cache = false;
457         if (m_process->GetTarget().ReadPointerFromMemory (m_kext_summary_header_ptr_addr,
458                                                           prefer_file_cache,
459                                                           error,
460                                                           m_kext_summary_header_addr))
461         {
462             // We got a valid address for our kext summary header and make sure it isn't NULL
463             if (m_kext_summary_header_addr.IsValid() &&
464                 m_kext_summary_header_addr.GetFileAddress() != 0)
465             {
466                 const size_t bytes_read = m_process->GetTarget().ReadMemory (m_kext_summary_header_addr, prefer_file_cache, buf, count, error);
467                 if (bytes_read == count)
468                 {
469                     uint32_t offset = 0;
470                     m_kext_summary_header.version = data.GetU32(&offset);
471                     if (m_kext_summary_header.version >= 2)
472                     {
473                         m_kext_summary_header.entry_size = data.GetU32(&offset);
474                     }
475                     else
476                     {
477                         // Versions less than 2 didn't have an entry size, it was hard coded
478                         m_kext_summary_header.entry_size = KERNEL_MODULE_ENTRY_SIZE_VERSION_1;
479                     }
480                     m_kext_summary_header.entry_count = data.GetU32(&offset);
481                     return true;
482                 }
483             }
484         }
485     }
486     m_kext_summary_header_addr.Clear();
487     return false;
488 }
489 
490 
491 bool
492 DynamicLoaderDarwinKernel::ParseKextSummaries (const Address &kext_summary_addr,
493                                                uint32_t count)
494 {
495     OSKextLoadedKextSummary::collection kext_summaries;
496     LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
497     if (log)
498         log->Printf ("Adding %d modules.\n", count);
499 
500     Mutex::Locker locker(m_mutex);
501 
502     if (!ReadKextSummaries (kext_summary_addr, count, kext_summaries))
503         return false;
504 
505     Stream *s = &m_process->GetTarget().GetDebugger().GetOutputStream();
506     for (uint32_t i = 0; i < count; i++)
507     {
508         if (s)
509         {
510             const uint8_t *u = (const uint8_t *)kext_summaries[i].uuid.GetBytes();
511             if (u)
512             {
513                 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\"...",
514                           u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7],
515                           u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15],
516                           kext_summaries[i].address, kext_summaries[i].name);
517             }
518             else
519             {
520                 s->Printf("0x%16.16llx \"%s\"...", kext_summaries[i].address, kext_summaries[i].name);
521             }
522         }
523 
524         DataExtractor data; // Load command data
525         if (ReadMachHeader (kext_summaries[i], &data))
526         {
527             ParseLoadCommands (data, kext_summaries[i]);
528         }
529 
530         if (s)
531         {
532             if (kext_summaries[i].module_sp)
533                 s->Printf("\n  found kext: %s/%s\n",
534                           kext_summaries[i].module_sp->GetFileSpec().GetDirectory().AsCString(),
535                           kext_summaries[i].module_sp->GetFileSpec().GetFilename().AsCString());
536             else
537                 s->Printf (" failed to locate/load.\n");
538         }
539 
540         if (log)
541             kext_summaries[i].PutToLog (log.get());
542     }
543     bool return_value = AddModulesUsingImageInfos (kext_summaries);
544     return return_value;
545 }
546 
547 // Adds the modules in image_infos to m_kext_summaries.
548 // NB don't call this passing in m_kext_summaries.
549 
550 bool
551 DynamicLoaderDarwinKernel::AddModulesUsingImageInfos (OSKextLoadedKextSummary::collection &image_infos)
552 {
553     // Now add these images to the main list.
554     ModuleList loaded_module_list;
555 
556     for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
557     {
558         m_kext_summaries.push_back(image_infos[idx]);
559 
560         if (FindTargetModule (image_infos[idx], true, NULL))
561         {
562             // UpdateImageLoadAddress will return true if any segments
563             // change load address. We need to check this so we don't
564             // mention that all loaded shared libraries are newly loaded
565             // each time we hit out dyld breakpoint since dyld will list all
566             // shared libraries each time.
567             if (UpdateImageLoadAddress (image_infos[idx]))
568             {
569                 loaded_module_list.AppendIfNeeded (image_infos[idx].module_sp);
570             }
571         }
572     }
573 
574     if (loaded_module_list.GetSize() > 0)
575     {
576         // FIXME: This should really be in the Runtime handlers class, which should get
577         // called by the target's ModulesDidLoad, but we're doing it all locally for now
578         // to save time.
579         // Also, I'm assuming there can be only one libobjc dylib loaded...
580 
581         ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime();
582         if (objc_runtime != NULL && !objc_runtime->HasReadObjCLibrary())
583         {
584             size_t num_modules = loaded_module_list.GetSize();
585             for (int i = 0; i < num_modules; i++)
586             {
587                 if (objc_runtime->IsModuleObjCLibrary (loaded_module_list.GetModuleAtIndex (i)))
588                 {
589                     objc_runtime->ReadObjCLibrary (loaded_module_list.GetModuleAtIndex (i));
590                     break;
591                 }
592             }
593         }
594 //        if (log)
595 //            loaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderDarwinKernel::ModulesDidLoad");
596         m_process->GetTarget().ModulesDidLoad (loaded_module_list);
597     }
598     return true;
599 }
600 
601 
602 uint32_t
603 DynamicLoaderDarwinKernel::ReadKextSummaries (const Address &kext_summary_addr,
604                                               uint32_t image_infos_count,
605                                               OSKextLoadedKextSummary::collection &image_infos)
606 {
607     const ByteOrder endian = m_kernel.GetByteOrder();
608     const uint32_t addr_size = m_kernel.GetAddressByteSize();
609 
610     image_infos.resize(image_infos_count);
611     const size_t count = image_infos.size() * m_kext_summary_header.entry_size;
612     DataBufferHeap data(count, 0);
613     Error error;
614 
615     Stream *s = &m_process->GetTarget().GetDebugger().GetOutputStream();
616 
617     if (s)
618         s->Printf ("Reading %u kext summaries...\n", image_infos_count);
619     const bool prefer_file_cache = false;
620     const size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary_addr,
621                                                                  prefer_file_cache,
622                                                                  data.GetBytes(),
623                                                                  data.GetByteSize(),
624                                                                  error);
625     if (bytes_read == count)
626     {
627 
628         DataExtractor extractor (data.GetBytes(), data.GetByteSize(), endian, addr_size);
629         uint32_t i=0;
630         for (uint32_t kext_summary_offset = 0;
631              i < image_infos.size() && extractor.ValidOffsetForDataOfSize(kext_summary_offset, m_kext_summary_header.entry_size);
632              ++i, kext_summary_offset += m_kext_summary_header.entry_size)
633         {
634             uint32_t offset = kext_summary_offset;
635             const void *name_data = extractor.GetData(&offset, KERNEL_MODULE_MAX_NAME);
636             if (name_data == NULL)
637                 break;
638             memcpy (image_infos[i].name, name_data, KERNEL_MODULE_MAX_NAME);
639             image_infos[i].uuid.SetBytes(extractor.GetData (&offset, 16));
640             image_infos[i].address          = extractor.GetU64(&offset);
641             if (!image_infos[i].so_address.SetLoadAddress (image_infos[i].address, &m_process->GetTarget()))
642                 m_process->GetTarget().GetImages().ResolveFileAddress (image_infos[i].address, image_infos[i].so_address);
643             image_infos[i].size             = extractor.GetU64(&offset);
644             image_infos[i].version          = extractor.GetU64(&offset);
645             image_infos[i].load_tag         = extractor.GetU32(&offset);
646             image_infos[i].flags            = extractor.GetU32(&offset);
647             if ((offset - kext_summary_offset) < m_kext_summary_header.entry_size)
648             {
649                 image_infos[i].reference_list = extractor.GetU64(&offset);
650             }
651             else
652             {
653                 image_infos[i].reference_list = 0;
654             }
655         }
656         if (i < image_infos.size())
657             image_infos.resize(i);
658     }
659     else
660     {
661         image_infos.clear();
662     }
663     return image_infos.size();
664 }
665 
666 bool
667 DynamicLoaderDarwinKernel::ReadAllKextSummaries ()
668 {
669     LogSP log(GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
670 
671     Mutex::Locker locker(m_mutex);
672 
673     if (ReadKextSummaryHeader ())
674     {
675         if (m_kext_summary_header.entry_count > 0 && m_kext_summary_header_addr.IsValid())
676         {
677             Address summary_addr (m_kext_summary_header_addr);
678             summary_addr.Slide(m_kext_summary_header.GetSize());
679             if (!ParseKextSummaries (summary_addr, m_kext_summary_header.entry_count))
680             {
681                 m_kext_summaries.clear();
682             }
683             return true;
684         }
685     }
686     return false;
687 }
688 
689 //----------------------------------------------------------------------
690 // Read a mach_header at ADDR into HEADER, and also fill in the load
691 // command data into LOAD_COMMAND_DATA if it is non-NULL.
692 //
693 // Returns true if we succeed, false if we fail for any reason.
694 //----------------------------------------------------------------------
695 bool
696 DynamicLoaderDarwinKernel::ReadMachHeader (OSKextLoadedKextSummary& kext_summary, DataExtractor *load_command_data)
697 {
698     DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0);
699     Error error;
700     const bool prefer_file_cache = false;
701     size_t bytes_read = m_process->GetTarget().ReadMemory (kext_summary.so_address,
702                                                            prefer_file_cache,
703                                                            header_bytes.GetBytes(),
704                                                            header_bytes.GetByteSize(),
705                                                            error);
706     if (bytes_read == sizeof(llvm::MachO::mach_header))
707     {
708         uint32_t offset = 0;
709         ::memset (&kext_summary.header, 0, sizeof(kext_summary.header));
710 
711         // Get the magic byte unswapped so we can figure out what we are dealing with
712         DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(), endian::InlHostByteOrder(), 4);
713         kext_summary.header.magic = data.GetU32(&offset);
714         Address load_cmd_addr = kext_summary.so_address;
715         data.SetByteOrder(DynamicLoaderDarwinKernel::GetByteOrderFromMagic(kext_summary.header.magic));
716         switch (kext_summary.header.magic)
717         {
718         case llvm::MachO::HeaderMagic32:
719         case llvm::MachO::HeaderMagic32Swapped:
720             data.SetAddressByteSize(4);
721             load_cmd_addr.Slide (sizeof(llvm::MachO::mach_header));
722             break;
723 
724         case llvm::MachO::HeaderMagic64:
725         case llvm::MachO::HeaderMagic64Swapped:
726             data.SetAddressByteSize(8);
727             load_cmd_addr.Slide (sizeof(llvm::MachO::mach_header_64));
728             break;
729 
730         default:
731             return false;
732         }
733 
734         // Read the rest of dyld's mach header
735         if (data.GetU32(&offset, &kext_summary.header.cputype, (sizeof(llvm::MachO::mach_header)/sizeof(uint32_t)) - 1))
736         {
737             if (load_command_data == NULL)
738                 return true; // We were able to read the mach_header and weren't asked to read the load command bytes
739 
740             DataBufferSP load_cmd_data_sp(new DataBufferHeap(kext_summary.header.sizeofcmds, 0));
741 
742             size_t load_cmd_bytes_read = m_process->GetTarget().ReadMemory (load_cmd_addr,
743                                                                             prefer_file_cache,
744                                                                             load_cmd_data_sp->GetBytes(),
745                                                                             load_cmd_data_sp->GetByteSize(),
746                                                                             error);
747 
748             if (load_cmd_bytes_read == kext_summary.header.sizeofcmds)
749             {
750                 // Set the load command data and also set the correct endian
751                 // swap settings and the correct address size
752                 load_command_data->SetData(load_cmd_data_sp, 0, kext_summary.header.sizeofcmds);
753                 load_command_data->SetByteOrder(data.GetByteOrder());
754                 load_command_data->SetAddressByteSize(data.GetAddressByteSize());
755                 return true; // We successfully read the mach_header and the load command data
756             }
757 
758             return false; // We weren't able to read the load command data
759         }
760     }
761     return false; // We failed the read the mach_header
762 }
763 
764 
765 //----------------------------------------------------------------------
766 // Parse the load commands for an image
767 //----------------------------------------------------------------------
768 uint32_t
769 DynamicLoaderDarwinKernel::ParseLoadCommands (const DataExtractor& data, OSKextLoadedKextSummary& image_info)
770 {
771     uint32_t offset = 0;
772     uint32_t cmd_idx;
773     Segment segment;
774     image_info.Clear (true);
775 
776     for (cmd_idx = 0; cmd_idx < image_info.header.ncmds; cmd_idx++)
777     {
778         // Clear out any load command specific data from image_info since
779         // we are about to read it.
780 
781         if (data.ValidOffsetForDataOfSize (offset, sizeof(llvm::MachO::load_command)))
782         {
783             llvm::MachO::load_command load_cmd;
784             uint32_t load_cmd_offset = offset;
785             load_cmd.cmd = data.GetU32 (&offset);
786             load_cmd.cmdsize = data.GetU32 (&offset);
787             switch (load_cmd.cmd)
788             {
789             case llvm::MachO::LoadCommandSegment32:
790                 {
791                     segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
792                     // We are putting 4 uint32_t values 4 uint64_t values so
793                     // we have to use multiple 32 bit gets below.
794                     segment.vmaddr = data.GetU32 (&offset);
795                     segment.vmsize = data.GetU32 (&offset);
796                     segment.fileoff = data.GetU32 (&offset);
797                     segment.filesize = data.GetU32 (&offset);
798                     // Extract maxprot, initprot, nsects and flags all at once
799                     data.GetU32(&offset, &segment.maxprot, 4);
800                     image_info.segments.push_back (segment);
801                 }
802                 break;
803 
804             case llvm::MachO::LoadCommandSegment64:
805                 {
806                     segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
807                     // Extract vmaddr, vmsize, fileoff, and filesize all at once
808                     data.GetU64(&offset, &segment.vmaddr, 4);
809                     // Extract maxprot, initprot, nsects and flags all at once
810                     data.GetU32(&offset, &segment.maxprot, 4);
811                     image_info.segments.push_back (segment);
812                 }
813                 break;
814 
815             case llvm::MachO::LoadCommandUUID:
816                 image_info.uuid.SetBytes(data.GetData (&offset, 16));
817                 break;
818 
819             default:
820                 break;
821             }
822             // Set offset to be the beginning of the next load command.
823             offset = load_cmd_offset + load_cmd.cmdsize;
824         }
825     }
826 #if 0
827     // No slide in the kernel...
828 
829     // All sections listed in the dyld image info structure will all
830     // either be fixed up already, or they will all be off by a single
831     // slide amount that is determined by finding the first segment
832     // that is at file offset zero which also has bytes (a file size
833     // that is greater than zero) in the object file.
834 
835     // Determine the slide amount (if any)
836     const size_t num_sections = image_info.segments.size();
837     for (size_t i = 0; i < num_sections; ++i)
838     {
839         // Iterate through the object file sections to find the
840         // first section that starts of file offset zero and that
841         // has bytes in the file...
842         if (image_info.segments[i].fileoff == 0 && image_info.segments[i].filesize > 0)
843         {
844             image_info.slide = image_info.address - image_info.segments[i].vmaddr;
845             // We have found the slide amount, so we can exit
846             // this for loop.
847             break;
848         }
849     }
850 #endif
851     if (image_info.uuid.IsValid())
852     {
853         bool did_create = false;
854         if (FindTargetModule(image_info, true, &did_create))
855         {
856             if (did_create)
857                 image_info.module_create_stop_id = m_process->GetStopID();
858         }
859     }
860     return cmd_idx;
861 }
862 
863 //----------------------------------------------------------------------
864 // Dump a Segment to the file handle provided.
865 //----------------------------------------------------------------------
866 void
867 DynamicLoaderDarwinKernel::Segment::PutToLog (Log *log, addr_t slide) const
868 {
869     if (log)
870     {
871         if (slide == 0)
872             log->Printf ("\t\t%16s [0x%16.16llx - 0x%16.16llx)",
873                          name.AsCString(""),
874                          vmaddr + slide,
875                          vmaddr + slide + vmsize);
876         else
877             log->Printf ("\t\t%16s [0x%16.16llx - 0x%16.16llx) slide = 0x%llx",
878                          name.AsCString(""),
879                          vmaddr + slide,
880                          vmaddr + slide + vmsize,
881                          slide);
882     }
883 }
884 
885 const DynamicLoaderDarwinKernel::Segment *
886 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::FindSegment (const ConstString &name) const
887 {
888     const size_t num_segments = segments.size();
889     for (size_t i=0; i<num_segments; ++i)
890     {
891         if (segments[i].name == name)
892             return &segments[i];
893     }
894     return NULL;
895 }
896 
897 
898 //----------------------------------------------------------------------
899 // Dump an image info structure to the file handle provided.
900 //----------------------------------------------------------------------
901 void
902 DynamicLoaderDarwinKernel::OSKextLoadedKextSummary::PutToLog (Log *log) const
903 {
904     if (log == NULL)
905         return;
906     const uint8_t *u = (uint8_t *)uuid.GetBytes();
907 
908     if (address == LLDB_INVALID_ADDRESS)
909     {
910         if (u)
911         {
912             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)",
913                         u[ 0], u[ 1], u[ 2], u[ 3],
914                         u[ 4], u[ 5], u[ 6], u[ 7],
915                         u[ 8], u[ 9], u[10], u[11],
916                         u[12], u[13], u[14], u[15],
917                         name);
918         }
919         else
920             log->Printf("\tname=\"%s\" (UNLOADED)", name);
921     }
922     else
923     {
924         if (u)
925         {
926             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\"",
927                         address, size, version, load_tag, flags, reference_list,
928                         u[ 0], u[ 1], u[ 2], u[ 3], u[ 4], u[ 5], u[ 6], u[ 7],
929                         u[ 8], u[ 9], u[10], u[11], u[12], u[13], u[14], u[15],
930                         name);
931         }
932         else
933         {
934             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\"",
935                         address, address+size, version, load_tag, flags, reference_list,
936                         name);
937         }
938         for (uint32_t i=0; i<segments.size(); ++i)
939             segments[i].PutToLog(log, 0);
940     }
941 }
942 
943 //----------------------------------------------------------------------
944 // Dump the _dyld_all_image_infos members and all current image infos
945 // that we have parsed to the file handle provided.
946 //----------------------------------------------------------------------
947 void
948 DynamicLoaderDarwinKernel::PutToLog(Log *log) const
949 {
950     if (log == NULL)
951         return;
952 
953     Mutex::Locker locker(m_mutex);
954     log->Printf("gLoadedKextSummaries = 0x%16.16llx { version=%u, entry_size=%u, entry_count=%u }",
955                 m_kext_summary_header_addr.GetFileAddress(),
956                 m_kext_summary_header.version,
957                 m_kext_summary_header.entry_size,
958                 m_kext_summary_header.entry_count);
959 
960     size_t i;
961     const size_t count = m_kext_summaries.size();
962     if (count > 0)
963     {
964         log->PutCString("Loaded:");
965         for (i = 0; i<count; i++)
966             m_kext_summaries[i].PutToLog(log);
967     }
968 }
969 
970 void
971 DynamicLoaderDarwinKernel::PrivateInitialize(Process *process)
972 {
973     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
974     Clear(true);
975     m_process = process;
976     m_process->GetTarget().GetSectionLoadList().Clear();
977 }
978 
979 void
980 DynamicLoaderDarwinKernel::SetNotificationBreakpointIfNeeded ()
981 {
982     if (m_break_id == LLDB_INVALID_BREAK_ID)
983     {
984         DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
985 
986 
987         const bool internal_bp = false;
988         const LazyBool skip_prologue = eLazyBoolNo;
989         FileSpecList module_spec_list;
990         module_spec_list.Append (m_kernel.module_sp->GetFileSpec());
991         Breakpoint *bp = m_process->GetTarget().CreateBreakpoint (&module_spec_list,
992                                                                   NULL,
993                                                                   "OSKextLoadedKextSummariesUpdated",
994                                                                   eFunctionNameTypeFull,
995                                                                   internal_bp,
996                                                                   skip_prologue).get();
997 
998         bp->SetCallback (DynamicLoaderDarwinKernel::BreakpointHitCallback, this, true);
999         m_break_id = bp->GetID();
1000     }
1001 }
1002 
1003 //----------------------------------------------------------------------
1004 // Member function that gets called when the process state changes.
1005 //----------------------------------------------------------------------
1006 void
1007 DynamicLoaderDarwinKernel::PrivateProcessStateChanged (Process *process, StateType state)
1008 {
1009     DEBUG_PRINTF("DynamicLoaderDarwinKernel::%s(%s)\n", __FUNCTION__, StateAsCString(state));
1010     switch (state)
1011     {
1012     case eStateConnected:
1013     case eStateAttaching:
1014     case eStateLaunching:
1015     case eStateInvalid:
1016     case eStateUnloaded:
1017     case eStateExited:
1018     case eStateDetached:
1019         Clear(false);
1020         break;
1021 
1022     case eStateStopped:
1023         UpdateIfNeeded();
1024         break;
1025 
1026     case eStateRunning:
1027     case eStateStepping:
1028     case eStateCrashed:
1029     case eStateSuspended:
1030         break;
1031 
1032     default:
1033         break;
1034     }
1035 }
1036 
1037 ThreadPlanSP
1038 DynamicLoaderDarwinKernel::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
1039 {
1040     ThreadPlanSP thread_plan_sp;
1041     LogSP log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1042     if (log)
1043         log->Printf ("Could not find symbol for step through.");
1044     return thread_plan_sp;
1045 }
1046 
1047 Error
1048 DynamicLoaderDarwinKernel::CanLoadImage ()
1049 {
1050     Error error;
1051     error.SetErrorString("always unsafe to load or unload shared libraries in the darwin kernel");
1052     return error;
1053 }
1054 
1055 void
1056 DynamicLoaderDarwinKernel::Initialize()
1057 {
1058     PluginManager::RegisterPlugin (GetPluginNameStatic(),
1059                                    GetPluginDescriptionStatic(),
1060                                    CreateInstance);
1061 }
1062 
1063 void
1064 DynamicLoaderDarwinKernel::Terminate()
1065 {
1066     PluginManager::UnregisterPlugin (CreateInstance);
1067 }
1068 
1069 
1070 const char *
1071 DynamicLoaderDarwinKernel::GetPluginNameStatic()
1072 {
1073     return "dynamic-loader.macosx-kernel";
1074 }
1075 
1076 const char *
1077 DynamicLoaderDarwinKernel::GetPluginDescriptionStatic()
1078 {
1079     return "Dynamic loader plug-in that watches for shared library loads/unloads in the MacOSX kernel.";
1080 }
1081 
1082 
1083 //------------------------------------------------------------------
1084 // PluginInterface protocol
1085 //------------------------------------------------------------------
1086 const char *
1087 DynamicLoaderDarwinKernel::GetPluginName()
1088 {
1089     return "DynamicLoaderDarwinKernel";
1090 }
1091 
1092 const char *
1093 DynamicLoaderDarwinKernel::GetShortPluginName()
1094 {
1095     return GetPluginNameStatic();
1096 }
1097 
1098 uint32_t
1099 DynamicLoaderDarwinKernel::GetPluginVersion()
1100 {
1101     return 1;
1102 }
1103 
1104