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