1 //===-- DynamicLoaderMacOSXDYLD.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 
11 #include "llvm/Support/MachO.h"
12 
13 #include "lldb/Breakpoint/StoppointCallbackContext.h"
14 #include "lldb/Core/DataBuffer.h"
15 #include "lldb/Core/DataBufferHeap.h"
16 #include "lldb/Core/Log.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/ModuleSpec.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/Section.h"
21 #include "lldb/Core/State.h"
22 #include "lldb/Symbol/Function.h"
23 #include "lldb/Symbol/ObjectFile.h"
24 #include "lldb/Target/ObjCLanguageRuntime.h"
25 #include "lldb/Target/RegisterContext.h"
26 #include "lldb/Target/Target.h"
27 #include "lldb/Target/Thread.h"
28 #include "lldb/Target/ThreadPlanRunToAddress.h"
29 #include "lldb/Target/StackFrame.h"
30 
31 #include "DynamicLoaderMacOSXDYLD.h"
32 
33 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
34 #ifdef ENABLE_DEBUG_PRINTF
35 #include <stdio.h>
36 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
37 #else
38 #define DEBUG_PRINTF(fmt, ...)
39 #endif
40 
41 using namespace lldb;
42 using namespace lldb_private;
43 
44 /// FIXME - The ObjC Runtime trampoline handler doesn't really belong here.
45 /// I am putting it here so I can invoke it in the Trampoline code here, but
46 /// it should be moved to the ObjC Runtime support when it is set up.
47 
48 
49 DynamicLoaderMacOSXDYLD::DYLDImageInfo *
50 DynamicLoaderMacOSXDYLD::GetImageInfo (Module *module)
51 {
52     const UUID &module_uuid = module->GetUUID();
53     DYLDImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
54 
55     // First try just by UUID as it is the safest.
56     if (module_uuid.IsValid())
57     {
58         for (pos = m_dyld_image_infos.begin(); pos != end; ++pos)
59         {
60             if (pos->uuid == module_uuid)
61                 return &(*pos);
62         }
63 
64         if (m_dyld.uuid == module_uuid)
65             return &m_dyld;
66     }
67 
68     // Next try by platform path only for things that don't have a valid UUID
69     // since if a file has a valid UUID in real life it should also in the
70     // dyld info. This is the next safest because the paths in the dyld info
71     // are platform paths, not local paths. For local debugging platform == local
72     // paths.
73     const FileSpec &platform_file_spec = module->GetPlatformFileSpec();
74     for (pos = m_dyld_image_infos.begin(); pos != end; ++pos)
75     {
76         if (pos->file_spec == platform_file_spec && pos->uuid.IsValid() == false)
77             return &(*pos);
78     }
79 
80     if (m_dyld.file_spec == platform_file_spec && m_dyld.uuid.IsValid() == false)
81         return &m_dyld;
82 
83     return NULL;
84 }
85 
86 //----------------------------------------------------------------------
87 // Create an instance of this class. This function is filled into
88 // the plugin info class that gets handed out by the plugin factory and
89 // allows the lldb to instantiate an instance of this class.
90 //----------------------------------------------------------------------
91 DynamicLoader *
92 DynamicLoaderMacOSXDYLD::CreateInstance (Process* process, bool force)
93 {
94     bool create = force;
95     if (!create)
96     {
97         create = true;
98         Module* exe_module = process->GetTarget().GetExecutableModulePointer();
99         if (exe_module)
100         {
101             ObjectFile *object_file = exe_module->GetObjectFile();
102             if (object_file)
103             {
104                 create = (object_file->GetStrata() == ObjectFile::eStrataUser);
105             }
106         }
107 
108         if (create)
109         {
110             const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple();
111             switch (triple_ref.getOS())
112             {
113                 case llvm::Triple::Darwin:
114                 case llvm::Triple::MacOSX:
115                 case llvm::Triple::IOS:
116                     create = triple_ref.getVendor() == llvm::Triple::Apple;
117                     break;
118                 default:
119                     create = false;
120                     break;
121             }
122         }
123     }
124 
125     if (create)
126         return new DynamicLoaderMacOSXDYLD (process);
127     return NULL;
128 }
129 
130 //----------------------------------------------------------------------
131 // Constructor
132 //----------------------------------------------------------------------
133 DynamicLoaderMacOSXDYLD::DynamicLoaderMacOSXDYLD (Process* process) :
134     DynamicLoader(process),
135     m_dyld(),
136     m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS),
137     m_dyld_all_image_infos(),
138     m_dyld_all_image_infos_stop_id (UINT32_MAX),
139     m_break_id(LLDB_INVALID_BREAK_ID),
140     m_dyld_image_infos(),
141     m_dyld_image_infos_stop_id (UINT32_MAX),
142     m_mutex(Mutex::eMutexTypeRecursive),
143     m_process_image_addr_is_all_images_infos (false)
144 {
145 }
146 
147 //----------------------------------------------------------------------
148 // Destructor
149 //----------------------------------------------------------------------
150 DynamicLoaderMacOSXDYLD::~DynamicLoaderMacOSXDYLD()
151 {
152     Clear(true);
153 }
154 
155 //------------------------------------------------------------------
156 /// Called after attaching a process.
157 ///
158 /// Allow DynamicLoader plug-ins to execute some code after
159 /// attaching to a process.
160 //------------------------------------------------------------------
161 void
162 DynamicLoaderMacOSXDYLD::DidAttach ()
163 {
164     PrivateInitialize(m_process);
165     LocateDYLD ();
166     SetNotificationBreakpoint ();
167 }
168 
169 //------------------------------------------------------------------
170 /// Called after attaching a process.
171 ///
172 /// Allow DynamicLoader plug-ins to execute some code after
173 /// attaching to a process.
174 //------------------------------------------------------------------
175 void
176 DynamicLoaderMacOSXDYLD::DidLaunch ()
177 {
178     PrivateInitialize(m_process);
179     LocateDYLD ();
180     SetNotificationBreakpoint ();
181 }
182 
183 bool
184 DynamicLoaderMacOSXDYLD::ProcessDidExec ()
185 {
186     if (m_process)
187     {
188         // If we are stopped after an exec, we will have only one thread...
189         if (m_process->GetThreadList().GetSize() == 1)
190         {
191             // We know if a process has exec'ed if our "m_dyld_all_image_infos_addr"
192             // value differs from the Process' image info address. When a process
193             // execs itself it might cause a change if ASLR is enabled.
194             const addr_t shlib_addr = m_process->GetImageInfoAddress ();
195             if (m_process_image_addr_is_all_images_infos == true && shlib_addr != m_dyld_all_image_infos_addr)
196             {
197                 // The image info address from the process is the 'dyld_all_image_infos'
198                 // address and it has changed.
199                 return true;
200             }
201 
202             if (m_process_image_addr_is_all_images_infos == false && shlib_addr == m_dyld.address)
203             {
204                 // The image info address from the process is the mach_header
205                 // address for dyld and it has changed.
206                 return true;
207             }
208 
209             // ASLR might be disabled and dyld could have ended up in the same
210             // location. We should try and detect if we are stopped at '_dyld_start'
211             ThreadSP thread_sp (m_process->GetThreadList().GetThreadAtIndex(0));
212             if (thread_sp)
213             {
214                 lldb::StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex(0));
215                 if (frame_sp)
216                 {
217                     const Symbol *symbol = frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol;
218                     if (symbol)
219                     {
220                         if (symbol->GetName() == ConstString("_dyld_start"))
221                             return true;
222                     }
223                 }
224             }
225         }
226     }
227     return false;
228 }
229 
230 
231 
232 //----------------------------------------------------------------------
233 // Clear out the state of this class.
234 //----------------------------------------------------------------------
235 void
236 DynamicLoaderMacOSXDYLD::Clear (bool clear_process)
237 {
238     Mutex::Locker locker(m_mutex);
239 
240     if (m_process->IsAlive() && LLDB_BREAK_ID_IS_VALID(m_break_id))
241         m_process->ClearBreakpointSiteByID(m_break_id);
242 
243     if (clear_process)
244         m_process = NULL;
245     m_dyld.Clear(false);
246     m_dyld_all_image_infos_addr = LLDB_INVALID_ADDRESS;
247     m_dyld_all_image_infos.Clear();
248     m_break_id = LLDB_INVALID_BREAK_ID;
249     m_dyld_image_infos.clear();
250 }
251 
252 //----------------------------------------------------------------------
253 // Check if we have found DYLD yet
254 //----------------------------------------------------------------------
255 bool
256 DynamicLoaderMacOSXDYLD::DidSetNotificationBreakpoint() const
257 {
258     return LLDB_BREAK_ID_IS_VALID (m_break_id);
259 }
260 
261 //----------------------------------------------------------------------
262 // Try and figure out where dyld is by first asking the Process
263 // if it knows (which currently calls down in the the lldb::Process
264 // to get the DYLD info (available on SnowLeopard only). If that fails,
265 // then check in the default addresses.
266 //----------------------------------------------------------------------
267 bool
268 DynamicLoaderMacOSXDYLD::LocateDYLD()
269 {
270     if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS)
271     {
272         // Check the image info addr as it might point to the
273         // mach header for dyld, or it might point to the
274         // dyld_all_image_infos struct
275         const addr_t shlib_addr = m_process->GetImageInfoAddress ();
276         ByteOrder byte_order = m_process->GetTarget().GetArchitecture().GetByteOrder();
277         uint8_t buf[4];
278         DataExtractor data (buf, sizeof(buf), byte_order, 4);
279         Error error;
280         if (m_process->ReadMemory (shlib_addr, buf, 4, error) == 4)
281         {
282             uint32_t offset = 0;
283             uint32_t magic = data.GetU32 (&offset);
284             switch (magic)
285             {
286             case llvm::MachO::HeaderMagic32:
287             case llvm::MachO::HeaderMagic64:
288             case llvm::MachO::HeaderMagic32Swapped:
289             case llvm::MachO::HeaderMagic64Swapped:
290                 m_process_image_addr_is_all_images_infos = false;
291                 return ReadDYLDInfoFromMemoryAndSetNotificationCallback(shlib_addr);
292 
293             default:
294                 break;
295             }
296         }
297         // Maybe it points to the all image infos?
298         m_dyld_all_image_infos_addr = shlib_addr;
299         m_process_image_addr_is_all_images_infos = true;
300     }
301 
302     if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS)
303     {
304         if (ReadAllImageInfosStructure ())
305         {
306             if (m_dyld_all_image_infos.dyldImageLoadAddress != LLDB_INVALID_ADDRESS)
307                 return ReadDYLDInfoFromMemoryAndSetNotificationCallback (m_dyld_all_image_infos.dyldImageLoadAddress);
308             else
309                 return ReadDYLDInfoFromMemoryAndSetNotificationCallback (m_dyld_all_image_infos_addr & 0xfffffffffff00000ull);
310         }
311     }
312 
313     // Check some default values
314     Module *executable = m_process->GetTarget().GetExecutableModulePointer();
315 
316     if (executable)
317     {
318         const ArchSpec &exe_arch = executable->GetArchitecture();
319         if (exe_arch.GetAddressByteSize() == 8)
320         {
321             return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x7fff5fc00000ull);
322         }
323         else if (exe_arch.GetMachine() == llvm::Triple::arm || exe_arch.GetMachine() == llvm::Triple::thumb)
324         {
325             return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x2fe00000);
326         }
327         else
328         {
329             return ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x8fe00000);
330         }
331     }
332     return false;
333 }
334 
335 ModuleSP
336 DynamicLoaderMacOSXDYLD::FindTargetModuleForDYLDImageInfo (const DYLDImageInfo &image_info, bool can_create, bool *did_create_ptr)
337 {
338     if (did_create_ptr)
339         *did_create_ptr = false;
340 
341 
342     const ModuleList &target_images = m_process->GetTarget().GetImages();
343     ModuleSpec module_spec (image_info.file_spec, image_info.GetArchitecture ());
344     module_spec.GetUUID() = image_info.uuid;
345     ModuleSP module_sp (target_images.FindFirstModule (module_spec));
346 
347     if (module_sp && !module_spec.GetUUID().IsValid() && !module_sp->GetUUID().IsValid())
348     {
349         // No UUID, we must rely upon the cached module modification
350         // time and the modification time of the file on disk
351         if (module_sp->GetModificationTime() != module_sp->GetFileSpec().GetModificationTime())
352             module_sp.reset();
353     }
354 
355     if (!module_sp)
356     {
357         if (can_create)
358         {
359             module_sp = m_process->GetTarget().GetSharedModule (module_spec);
360             if (!module_sp || module_sp->GetObjectFile() == NULL)
361             {
362                 const bool add_image_to_target = true;
363                 const bool load_image_sections_in_target = false;
364                 module_sp = m_process->ReadModuleFromMemory (image_info.file_spec,
365                                                              image_info.address,
366                                                              add_image_to_target,
367                                                              load_image_sections_in_target);
368             }
369 
370             if (did_create_ptr)
371                 *did_create_ptr = (bool) module_sp;
372         }
373     }
374     return module_sp;
375 }
376 
377 //----------------------------------------------------------------------
378 // Assume that dyld is in memory at ADDR and try to parse it's load
379 // commands
380 //----------------------------------------------------------------------
381 bool
382 DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(lldb::addr_t addr)
383 {
384     DataExtractor data; // Load command data
385     if (ReadMachHeader (addr, &m_dyld.header, &data))
386     {
387         if (m_dyld.header.filetype == llvm::MachO::HeaderFileTypeDynamicLinkEditor)
388         {
389             m_dyld.address = addr;
390             ModuleSP dyld_module_sp;
391             if (ParseLoadCommands (data, m_dyld, &m_dyld.file_spec))
392             {
393                 if (m_dyld.file_spec)
394                 {
395                     dyld_module_sp = FindTargetModuleForDYLDImageInfo (m_dyld, true, NULL);
396 
397                     if (dyld_module_sp)
398                         UpdateImageLoadAddress (dyld_module_sp.get(), m_dyld);
399                 }
400             }
401 
402             if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS && dyld_module_sp.get())
403             {
404                 static ConstString g_dyld_all_image_infos ("dyld_all_image_infos");
405                 const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType (g_dyld_all_image_infos, eSymbolTypeData);
406                 if (symbol)
407                     m_dyld_all_image_infos_addr = symbol->GetAddress().GetLoadAddress(&m_process->GetTarget());
408             }
409 
410             // Update all image infos
411             InitializeFromAllImageInfos ();
412 
413             // If we didn't have an executable before, but now we do, then the
414             // dyld module shared pointer might be unique and we may need to add
415             // it again (since Target::SetExecutableModule() will clear the
416             // images). So append the dyld module back to the list if it is
417             /// unique!
418             if (dyld_module_sp && m_process->GetTarget().GetImages().AppendIfNeeded (dyld_module_sp))
419                 UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
420 
421             return true;
422         }
423     }
424     return false;
425 }
426 
427 bool
428 DynamicLoaderMacOSXDYLD::NeedToLocateDYLD () const
429 {
430     return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS;
431 }
432 
433 bool
434 DynamicLoaderMacOSXDYLD::UpdateCommPageLoadAddress(Module *module)
435 {
436     bool changed = false;
437     if (module)
438     {
439         ObjectFile *image_object_file = module->GetObjectFile();
440         if (image_object_file)
441         {
442             SectionList *section_list = image_object_file->GetSectionList ();
443             if (section_list)
444             {
445                 uint32_t num_sections = section_list->GetSize();
446                 for (uint32_t i=0; i<num_sections; ++i)
447                 {
448                     SectionSP section_sp (section_list->GetSectionAtIndex (i));
449                     if (section_sp)
450                     {
451                         const addr_t new_section_load_addr = section_sp->GetFileAddress ();
452                         const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section_sp);
453                         if (old_section_load_addr == LLDB_INVALID_ADDRESS ||
454                             old_section_load_addr != new_section_load_addr)
455                         {
456                             if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section_sp, section_sp->GetFileAddress ()))
457                                 changed = true;
458                         }
459                     }
460                 }
461             }
462         }
463     }
464     return changed;
465 }
466 
467 //----------------------------------------------------------------------
468 // Update the load addresses for all segments in MODULE using the
469 // updated INFO that is passed in.
470 //----------------------------------------------------------------------
471 bool
472 DynamicLoaderMacOSXDYLD::UpdateImageLoadAddress (Module *module, DYLDImageInfo& info)
473 {
474     bool changed = false;
475     if (module)
476     {
477         ObjectFile *image_object_file = module->GetObjectFile();
478         if (image_object_file)
479         {
480             SectionList *section_list = image_object_file->GetSectionList ();
481             if (section_list)
482             {
483                 std::vector<uint32_t> inaccessible_segment_indexes;
484                 // We now know the slide amount, so go through all sections
485                 // and update the load addresses with the correct values.
486                 uint32_t num_segments = info.segments.size();
487                 for (uint32_t i=0; i<num_segments; ++i)
488                 {
489                     // Only load a segment if it has protections. Things like
490                     // __PAGEZERO don't have any protections, and they shouldn't
491                     // be slid
492                     SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
493 
494                     if (info.segments[i].maxprot == 0)
495                     {
496                         inaccessible_segment_indexes.push_back(i);
497                     }
498                     else
499                     {
500                         const addr_t new_section_load_addr = info.segments[i].vmaddr + info.slide;
501                         static ConstString g_section_name_LINKEDIT ("__LINKEDIT");
502 
503                         if (section_sp)
504                         {
505                             // __LINKEDIT sections from files in the shared cache
506                             // can overlap so check to see what the segment name is
507                             // and pass "false" so we don't warn of overlapping
508                             // "Section" objects, and "true" for all other sections.
509                             const bool warn_multiple = section_sp->GetName() != g_section_name_LINKEDIT;
510 
511                             const addr_t old_section_load_addr = m_process->GetTarget().GetSectionLoadList().GetSectionLoadAddress (section_sp);
512                             if (old_section_load_addr == LLDB_INVALID_ADDRESS ||
513                                 old_section_load_addr != new_section_load_addr)
514                             {
515                                 if (m_process->GetTarget().GetSectionLoadList().SetSectionLoadAddress (section_sp, new_section_load_addr, warn_multiple))
516                                     changed = true;
517                             }
518                         }
519                         else
520                         {
521                             Host::SystemLog (Host::eSystemLogWarning,
522                                              "warning: unable to find and load segment named '%s' at 0x%" PRIx64 " in '%s/%s' in macosx dynamic loader plug-in.\n",
523                                              info.segments[i].name.AsCString("<invalid>"),
524                                              (uint64_t)new_section_load_addr,
525                                              image_object_file->GetFileSpec().GetDirectory().AsCString(),
526                                              image_object_file->GetFileSpec().GetFilename().AsCString());
527                         }
528                     }
529                 }
530 
531                 // If the loaded the file (it changed) and we have segments that
532                 // are not readable or writeable, add them to the invalid memory
533                 // region cache for the process. This will typically only be
534                 // the __PAGEZERO segment in the main executable. We might be able
535                 // to apply this more generally to more sections that have no
536                 // protections in the future, but for now we are going to just
537                 // do __PAGEZERO.
538                 if (changed && !inaccessible_segment_indexes.empty())
539                 {
540                     for (uint32_t i=0; i<inaccessible_segment_indexes.size(); ++i)
541                     {
542                         const uint32_t seg_idx = inaccessible_segment_indexes[i];
543                         SectionSP section_sp(section_list->FindSectionByName(info.segments[seg_idx].name));
544 
545                         if (section_sp)
546                         {
547                             static ConstString g_pagezero_section_name("__PAGEZERO");
548                             if (g_pagezero_section_name == section_sp->GetName())
549                             {
550                                 // __PAGEZERO never slides...
551                                 const lldb::addr_t vmaddr = info.segments[seg_idx].vmaddr;
552                                 const lldb::addr_t vmsize = info.segments[seg_idx].vmsize;
553                                 Process::LoadRange pagezero_range (vmaddr, vmsize);
554                                 m_process->AddInvalidMemoryRegion(pagezero_range);
555                             }
556                         }
557                     }
558                 }
559             }
560         }
561     }
562     return changed;
563 }
564 
565 //----------------------------------------------------------------------
566 // Update the load addresses for all segments in MODULE using the
567 // updated INFO that is passed in.
568 //----------------------------------------------------------------------
569 bool
570 DynamicLoaderMacOSXDYLD::UnloadImageLoadAddress (Module *module, DYLDImageInfo& info)
571 {
572     bool changed = false;
573     if (module)
574     {
575         ObjectFile *image_object_file = module->GetObjectFile();
576         if (image_object_file)
577         {
578             SectionList *section_list = image_object_file->GetSectionList ();
579             if (section_list)
580             {
581                 uint32_t num_segments = info.segments.size();
582                 for (uint32_t i=0; i<num_segments; ++i)
583                 {
584                     SectionSP section_sp(section_list->FindSectionByName(info.segments[i].name));
585                     if (section_sp)
586                     {
587                         const addr_t old_section_load_addr = info.segments[i].vmaddr + info.slide;
588                         if (m_process->GetTarget().GetSectionLoadList().SetSectionUnloaded (section_sp, old_section_load_addr))
589                             changed = true;
590                     }
591                     else
592                     {
593                         Host::SystemLog (Host::eSystemLogWarning,
594                                          "warning: unable to find and unload segment named '%s' in '%s/%s' in macosx dynamic loader plug-in.\n",
595                                          info.segments[i].name.AsCString("<invalid>"),
596                                          image_object_file->GetFileSpec().GetDirectory().AsCString(),
597                                          image_object_file->GetFileSpec().GetFilename().AsCString());
598                     }
599                 }
600             }
601         }
602     }
603     return changed;
604 }
605 
606 
607 //----------------------------------------------------------------------
608 // Static callback function that gets called when our DYLD notification
609 // breakpoint gets hit. We update all of our image infos and then
610 // let our super class DynamicLoader class decide if we should stop
611 // or not (based on global preference).
612 //----------------------------------------------------------------------
613 bool
614 DynamicLoaderMacOSXDYLD::NotifyBreakpointHit (void *baton,
615                                               StoppointCallbackContext *context,
616                                               lldb::user_id_t break_id,
617                                               lldb::user_id_t break_loc_id)
618 {
619     // Let the event know that the images have changed
620     // DYLD passes three arguments to the notification breakpoint.
621     // Arg1: enum dyld_image_mode mode - 0 = adding, 1 = removing
622     // Arg2: uint32_t infoCount        - Number of shared libraries added
623     // Arg3: dyld_image_info info[]    - Array of structs of the form:
624     //                                     const struct mach_header *imageLoadAddress
625     //                                     const char               *imageFilePath
626     //                                     uintptr_t                 imageFileModDate (a time_t)
627 
628     DynamicLoaderMacOSXDYLD* dyld_instance = (DynamicLoaderMacOSXDYLD*) baton;
629 
630     // First step is to see if we've already initialized the all image infos.  If we haven't then this function
631     // will do so and return true.  In the course of initializing the all_image_infos it will read the complete
632     // current state, so we don't need to figure out what has changed from the data passed in to us.
633 
634     if (dyld_instance->InitializeFromAllImageInfos())
635         return dyld_instance->GetStopWhenImagesChange();
636 
637     ExecutionContext exe_ctx (context->exe_ctx_ref);
638     Process *process = exe_ctx.GetProcessPtr();
639     const lldb::ABISP &abi = process->GetABI();
640     if (abi)
641     {
642         // Build up the value array to store the three arguments given above, then get the values from the ABI:
643 
644         ClangASTContext *clang_ast_context = process->GetTarget().GetScratchClangASTContext();
645         ValueList argument_values;
646         Value input_value;
647 
648         void *clang_void_ptr_type = clang_ast_context->GetVoidPtrType(false);
649         void *clang_uint32_type   = clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(lldb::eEncodingUint, 32);
650         input_value.SetValueType (Value::eValueTypeScalar);
651         input_value.SetContext (Value::eContextTypeClangType, clang_uint32_type);
652         argument_values.PushValue(input_value);
653         argument_values.PushValue(input_value);
654         input_value.SetContext (Value::eContextTypeClangType, clang_void_ptr_type);
655         argument_values.PushValue (input_value);
656 
657         if (abi->GetArgumentValues (exe_ctx.GetThreadRef(), argument_values))
658         {
659             uint32_t dyld_mode = argument_values.GetValueAtIndex(0)->GetScalar().UInt (-1);
660             if (dyld_mode != -1)
661             {
662                 // Okay the mode was right, now get the number of elements, and the array of new elements...
663                 uint32_t image_infos_count = argument_values.GetValueAtIndex(1)->GetScalar().UInt (-1);
664                 if (image_infos_count != -1)
665                 {
666                     // Got the number added, now go through the array of added elements, putting out the mach header
667                     // address, and adding the image.
668                     // Note, I'm not putting in logging here, since the AddModules & RemoveModules functions do
669                     // all the logging internally.
670 
671                     lldb::addr_t image_infos_addr = argument_values.GetValueAtIndex(2)->GetScalar().ULongLong();
672                     if (dyld_mode == 0)
673                     {
674                         // This is add:
675                         dyld_instance->AddModulesUsingImageInfosAddress (image_infos_addr, image_infos_count);
676                     }
677                     else
678                     {
679                         // This is remove:
680                         dyld_instance->RemoveModulesUsingImageInfosAddress (image_infos_addr, image_infos_count);
681                     }
682 
683                 }
684             }
685         }
686     }
687 
688     // Return true to stop the target, false to just let the target run
689     return dyld_instance->GetStopWhenImagesChange();
690 }
691 
692 bool
693 DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure ()
694 {
695     Mutex::Locker locker(m_mutex);
696 
697     // the all image infos is already valid for this process stop ID
698     if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id)
699         return true;
700 
701     m_dyld_all_image_infos.Clear();
702     if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS)
703     {
704         ByteOrder byte_order = m_process->GetTarget().GetArchitecture().GetByteOrder();
705         uint32_t addr_size = 4;
706         if (m_dyld_all_image_infos_addr > UINT32_MAX)
707             addr_size = 8;
708 
709         uint8_t buf[256];
710         DataExtractor data (buf, sizeof(buf), byte_order, addr_size);
711         uint32_t offset = 0;
712 
713         const size_t count_v2 =  sizeof (uint32_t) + // version
714                                  sizeof (uint32_t) + // infoArrayCount
715                                  addr_size +         // infoArray
716                                  addr_size +         // notification
717                                  addr_size +         // processDetachedFromSharedRegion + libSystemInitialized + pad
718                                  addr_size;          // dyldImageLoadAddress
719         const size_t count_v11 = count_v2 +
720                                  addr_size +         // jitInfo
721                                  addr_size +         // dyldVersion
722                                  addr_size +         // errorMessage
723                                  addr_size +         // terminationFlags
724                                  addr_size +         // coreSymbolicationShmPage
725                                  addr_size +         // systemOrderFlag
726                                  addr_size +         // uuidArrayCount
727                                  addr_size +         // uuidArray
728                                  addr_size +         // dyldAllImageInfosAddress
729                                  addr_size +         // initialImageCount
730                                  addr_size +         // errorKind
731                                  addr_size +         // errorClientOfDylibPath
732                                  addr_size +         // errorTargetDylibPath
733                                  addr_size;          // errorSymbol
734         assert (sizeof (buf) >= count_v11);
735 
736         int count;
737         Error error;
738         if (m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, 4, error) == 4)
739         {
740             m_dyld_all_image_infos.version = data.GetU32(&offset);
741             // If anything in the high byte is set, we probably got the byte
742             // order incorrect (the process might not have it set correctly
743             // yet due to attaching to a program without a specified file).
744             if (m_dyld_all_image_infos.version & 0xff000000)
745             {
746                 // We have guessed the wrong byte order. Swap it and try
747                 // reading the version again.
748                 if (byte_order == eByteOrderLittle)
749                     byte_order = eByteOrderBig;
750                 else
751                     byte_order = eByteOrderLittle;
752 
753                 data.SetByteOrder (byte_order);
754                 offset = 0;
755                 m_dyld_all_image_infos.version = data.GetU32(&offset);
756             }
757         }
758         else
759         {
760             return false;
761         }
762 
763         if (m_dyld_all_image_infos.version >= 11)
764             count = count_v11;
765         else
766             count = count_v2;
767 
768         const size_t bytes_read = m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, count, error);
769         if (bytes_read == count)
770         {
771             offset = 0;
772             m_dyld_all_image_infos.version = data.GetU32(&offset);
773             m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset);
774             m_dyld_all_image_infos.dylib_info_addr = data.GetPointer(&offset);
775             m_dyld_all_image_infos.notification = data.GetPointer(&offset);
776             m_dyld_all_image_infos.processDetachedFromSharedRegion = data.GetU8(&offset);
777             m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset);
778             // Adjust for padding.
779             offset += addr_size - 2;
780             m_dyld_all_image_infos.dyldImageLoadAddress = data.GetPointer(&offset);
781             if (m_dyld_all_image_infos.version >= 11)
782             {
783                 offset += addr_size * 8;
784                 uint64_t dyld_all_image_infos_addr = data.GetPointer(&offset);
785 
786                 // When we started, we were given the actual address of the all_image_infos
787                 // struct (probably via TASK_DYLD_INFO) in memory - this address is stored in
788                 // m_dyld_all_image_infos_addr and is the most accurate address we have.
789 
790                 // We read the dyld_all_image_infos struct from memory; it contains its own address.
791                 // If the address in the struct does not match the actual address,
792                 // the dyld we're looking at has been loaded at a different location (slid) from
793                 // where it intended to load.  The addresses in the dyld_all_image_infos struct
794                 // are the original, non-slid addresses, and need to be adjusted.  Most importantly
795                 // the address of dyld and the notification address need to be adjusted.
796 
797                 if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr)
798                 {
799                     uint64_t image_infos_offset = dyld_all_image_infos_addr - m_dyld_all_image_infos.dyldImageLoadAddress;
800                     uint64_t notification_offset = m_dyld_all_image_infos.notification - m_dyld_all_image_infos.dyldImageLoadAddress;
801                     m_dyld_all_image_infos.dyldImageLoadAddress = m_dyld_all_image_infos_addr - image_infos_offset;
802                     m_dyld_all_image_infos.notification = m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset;
803                 }
804             }
805             m_dyld_all_image_infos_stop_id = m_process->GetStopID();
806             return true;
807         }
808     }
809     return false;
810 }
811 
812 
813 bool
814 DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfosAddress (lldb::addr_t image_infos_addr, uint32_t image_infos_count)
815 {
816     DYLDImageInfo::collection image_infos;
817     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
818     if (log)
819         log->Printf ("Adding %d modules.\n", image_infos_count);
820 
821     Mutex::Locker locker(m_mutex);
822     if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
823         return true;
824 
825     if (!ReadImageInfos (image_infos_addr, image_infos_count, image_infos))
826         return false;
827 
828     UpdateImageInfosHeaderAndLoadCommands (image_infos, image_infos_count, false);
829     bool return_value = AddModulesUsingImageInfos (image_infos);
830     m_dyld_image_infos_stop_id = m_process->GetStopID();
831     return return_value;
832 }
833 
834 // Adds the modules in image_infos to m_dyld_image_infos.
835 // NB don't call this passing in m_dyld_image_infos.
836 
837 bool
838 DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfos (DYLDImageInfo::collection &image_infos)
839 {
840     // Now add these images to the main list.
841     ModuleList loaded_module_list;
842     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
843 
844     for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
845     {
846         if (log)
847         {
848             log->Printf ("Adding new image at address=0x%16.16" PRIx64 ".", image_infos[idx].address);
849             image_infos[idx].PutToLog (log.get());
850         }
851 
852         m_dyld_image_infos.push_back(image_infos[idx]);
853 
854         ModuleSP image_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[idx], true, NULL));
855 
856         if (image_module_sp)
857         {
858             if (image_infos[idx].header.filetype == llvm::MachO::HeaderFileTypeDynamicLinkEditor)
859                 image_module_sp->SetIsDynamicLinkEditor (true);
860 
861             ObjectFile *objfile = image_module_sp->GetObjectFile ();
862             if (objfile)
863             {
864                 SectionList *sections = objfile->GetSectionList();
865                 if (sections)
866                 {
867                     ConstString commpage_dbstr("__commpage");
868                     Section *commpage_section = sections->FindSectionByName(commpage_dbstr).get();
869                     if (commpage_section)
870                     {
871                         const ModuleList& target_images = m_process->GetTarget().GetImages();
872                         ModuleSpec module_spec (objfile->GetFileSpec(), image_infos[idx].GetArchitecture ());
873                         module_spec.GetObjectName() = commpage_dbstr;
874                         ModuleSP commpage_image_module_sp(target_images.FindFirstModule (module_spec));
875                         if (!commpage_image_module_sp)
876                         {
877                             module_spec.SetObjectOffset (objfile->GetOffset() + commpage_section->GetFileOffset());
878                             commpage_image_module_sp  = m_process->GetTarget().GetSharedModule (module_spec);
879                             if (!commpage_image_module_sp || commpage_image_module_sp->GetObjectFile() == NULL)
880                             {
881                                 const bool add_image_to_target = true;
882                                 const bool load_image_sections_in_target = false;
883                                 commpage_image_module_sp = m_process->ReadModuleFromMemory (image_infos[idx].file_spec,
884                                                                                             image_infos[idx].address,
885                                                                                             add_image_to_target,
886                                                                                             load_image_sections_in_target);
887                             }
888                         }
889                         if (commpage_image_module_sp)
890                             UpdateCommPageLoadAddress (commpage_image_module_sp.get());
891                     }
892                 }
893             }
894 
895             // UpdateImageLoadAddress will return true if any segments
896             // change load address. We need to check this so we don't
897             // mention that all loaded shared libraries are newly loaded
898             // each time we hit out dyld breakpoint since dyld will list all
899             // shared libraries each time.
900             if (UpdateImageLoadAddress (image_module_sp.get(), image_infos[idx]))
901             {
902                 loaded_module_list.AppendIfNeeded (image_module_sp);
903             }
904         }
905     }
906 
907     if (loaded_module_list.GetSize() > 0)
908     {
909         // FIXME: This should really be in the Runtime handlers class, which should get
910         // called by the target's ModulesDidLoad, but we're doing it all locally for now
911         // to save time.
912         // Also, I'm assuming there can be only one libobjc dylib loaded...
913 
914         ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime(true);
915         if (objc_runtime != NULL && !objc_runtime->HasReadObjCLibrary())
916         {
917             size_t num_modules = loaded_module_list.GetSize();
918             for (int i = 0; i < num_modules; i++)
919             {
920                 if (objc_runtime->IsModuleObjCLibrary (loaded_module_list.GetModuleAtIndex (i)))
921                 {
922                     objc_runtime->ReadObjCLibrary (loaded_module_list.GetModuleAtIndex (i));
923                     break;
924                 }
925             }
926         }
927         if (log)
928             loaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderMacOSXDYLD::ModulesDidLoad");
929         m_process->GetTarget().ModulesDidLoad (loaded_module_list);
930     }
931     return true;
932 }
933 
934 bool
935 DynamicLoaderMacOSXDYLD::RemoveModulesUsingImageInfosAddress (lldb::addr_t image_infos_addr, uint32_t image_infos_count)
936 {
937     DYLDImageInfo::collection image_infos;
938     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
939 
940     Mutex::Locker locker(m_mutex);
941     if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
942         return true;
943 
944     // First read in the image_infos for the removed modules, and their headers & load commands.
945     if (!ReadImageInfos (image_infos_addr, image_infos_count, image_infos))
946     {
947         if (log)
948             log->PutCString ("Failed reading image infos array.");
949         return false;
950     }
951 
952     if (log)
953         log->Printf ("Removing %d modules.", image_infos_count);
954 
955     ModuleList unloaded_module_list;
956     for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
957     {
958         if (log)
959         {
960             log->Printf ("Removing module at address=0x%16.16" PRIx64 ".", image_infos[idx].address);
961             image_infos[idx].PutToLog (log.get());
962         }
963 
964         // Remove this image_infos from the m_all_image_infos.  We do the comparision by address
965         // rather than by file spec because we can have many modules with the same "file spec" in the
966         // case that they are modules loaded from memory.
967         //
968         // Also copy over the uuid from the old entry to the removed entry so we can
969         // use it to lookup the module in the module list.
970 
971         DYLDImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
972         for (pos = m_dyld_image_infos.begin(); pos != end; pos++)
973         {
974             if (image_infos[idx].address == (*pos).address)
975             {
976                 image_infos[idx].uuid = (*pos).uuid;
977 
978                 // Add the module from this image_info to the "unloaded_module_list".  We'll remove them all at
979                 // one go later on.
980 
981                 ModuleSP unload_image_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[idx], false, NULL));
982                 if (unload_image_module_sp.get())
983                 {
984                     // When we unload, be sure to use the image info from the old list,
985                     // since that has sections correctly filled in.
986                     UnloadImageLoadAddress (unload_image_module_sp.get(), *pos);
987                     unloaded_module_list.AppendIfNeeded (unload_image_module_sp);
988                 }
989                 else
990                 {
991                     if (log)
992                     {
993                         log->Printf ("Could not find module for unloading info entry:");
994                         image_infos[idx].PutToLog(log.get());
995                     }
996                 }
997 
998                 // Then remove it from the m_dyld_image_infos:
999 
1000                 m_dyld_image_infos.erase(pos);
1001                 break;
1002             }
1003         }
1004 
1005         if (pos == end)
1006         {
1007             if (log)
1008             {
1009                 log->Printf ("Could not find image_info entry for unloading image:");
1010                 image_infos[idx].PutToLog(log.get());
1011             }
1012         }
1013     }
1014     if (unloaded_module_list.GetSize() > 0)
1015     {
1016         if (log)
1017         {
1018             log->PutCString("Unloaded:");
1019             unloaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderMacOSXDYLD::ModulesDidUnload");
1020         }
1021         m_process->GetTarget().GetImages().Remove (unloaded_module_list);
1022     }
1023     m_dyld_image_infos_stop_id = m_process->GetStopID();
1024     return true;
1025 }
1026 
1027 bool
1028 DynamicLoaderMacOSXDYLD::ReadImageInfos (lldb::addr_t image_infos_addr,
1029                                          uint32_t image_infos_count,
1030                                          DYLDImageInfo::collection &image_infos)
1031 {
1032     const ByteOrder endian = m_dyld.GetByteOrder();
1033     const uint32_t addr_size = m_dyld.GetAddressByteSize();
1034 
1035     image_infos.resize(image_infos_count);
1036     const size_t count = image_infos.size() * 3 * addr_size;
1037     DataBufferHeap info_data(count, 0);
1038     Error error;
1039     const size_t bytes_read = m_process->ReadMemory (image_infos_addr,
1040                                                      info_data.GetBytes(),
1041                                                      info_data.GetByteSize(),
1042                                                      error);
1043     if (bytes_read == count)
1044     {
1045         uint32_t info_data_offset = 0;
1046         DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(), endian, addr_size);
1047         for (int i = 0; i < image_infos.size() && info_data_ref.ValidOffset(info_data_offset); i++)
1048         {
1049             image_infos[i].address = info_data_ref.GetPointer(&info_data_offset);
1050             lldb::addr_t path_addr = info_data_ref.GetPointer(&info_data_offset);
1051             image_infos[i].mod_date = info_data_ref.GetPointer(&info_data_offset);
1052 
1053             char raw_path[PATH_MAX];
1054             m_process->ReadCStringFromMemory (path_addr, raw_path, sizeof(raw_path), error);
1055             // don't resolve the path
1056             if (error.Success())
1057             {
1058                 const bool resolve_path = false;
1059                 image_infos[i].file_spec.SetFile(raw_path, resolve_path);
1060             }
1061         }
1062         return true;
1063     }
1064     else
1065     {
1066         return false;
1067     }
1068 }
1069 
1070 //----------------------------------------------------------------------
1071 // If we have found where the "_dyld_all_image_infos" lives in memory,
1072 // read the current info from it, and then update all image load
1073 // addresses (or lack thereof).  Only do this if this is the first time
1074 // we're reading the dyld infos.  Return true if we actually read anything,
1075 // and false otherwise.
1076 //----------------------------------------------------------------------
1077 bool
1078 DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos ()
1079 {
1080     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
1081 
1082     Mutex::Locker locker(m_mutex);
1083     if (m_process->GetStopID() == m_dyld_image_infos_stop_id
1084           || m_dyld_image_infos.size() != 0)
1085         return false;
1086 
1087     if (ReadAllImageInfosStructure ())
1088     {
1089         // Nothing to load or unload?
1090         if (m_dyld_all_image_infos.dylib_info_count == 0)
1091             return true;
1092 
1093         if (m_dyld_all_image_infos.dylib_info_addr == 0)
1094         {
1095             // DYLD is updating the images now.  So we should say we have no images, and then we'll
1096             // figure it out when we hit the added breakpoint.
1097             return false;
1098         }
1099         else
1100         {
1101             if (!AddModulesUsingImageInfosAddress (m_dyld_all_image_infos.dylib_info_addr,
1102                                                    m_dyld_all_image_infos.dylib_info_count))
1103             {
1104                 DEBUG_PRINTF( "unable to read all data for all_dylib_infos.");
1105                 m_dyld_image_infos.clear();
1106             }
1107         }
1108 
1109         // Now we have one more bit of business.  If there is a library left in the images for our target that
1110         // doesn't have a load address, then it must be something that we were expecting to load (for instance we
1111         // read a load command for it) but it didn't in fact load - probably because DYLD_*_PATH pointed
1112         // to an equivalent version.  We don't want it to stay in the target's module list or it will confuse
1113         // us, so unload it here.
1114         Target &target = m_process->GetTarget();
1115         const ModuleList &target_modules = target.GetImages();
1116         ModuleList not_loaded_modules;
1117         Mutex::Locker modules_locker(target_modules.GetMutex());
1118 
1119         size_t num_modules = target_modules.GetSize();
1120         for (size_t i = 0; i < num_modules; i++)
1121         {
1122             ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked (i);
1123             if (!module_sp->IsLoadedInTarget (&target))
1124             {
1125                 if (log)
1126                 {
1127                     StreamString s;
1128                     module_sp->GetDescription (&s);
1129                     log->Printf ("Unloading pre-run module: %s.", s.GetData ());
1130                 }
1131                 not_loaded_modules.Append (module_sp);
1132             }
1133         }
1134 
1135         if (not_loaded_modules.GetSize() != 0)
1136         {
1137             target.GetImages().Remove(not_loaded_modules);
1138         }
1139 
1140         return true;
1141     }
1142     else
1143         return false;
1144 }
1145 
1146 //----------------------------------------------------------------------
1147 // Read a mach_header at ADDR into HEADER, and also fill in the load
1148 // command data into LOAD_COMMAND_DATA if it is non-NULL.
1149 //
1150 // Returns true if we succeed, false if we fail for any reason.
1151 //----------------------------------------------------------------------
1152 bool
1153 DynamicLoaderMacOSXDYLD::ReadMachHeader (lldb::addr_t addr, llvm::MachO::mach_header *header, DataExtractor *load_command_data)
1154 {
1155     DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0);
1156     Error error;
1157     size_t bytes_read = m_process->ReadMemory (addr,
1158                                                header_bytes.GetBytes(),
1159                                                header_bytes.GetByteSize(),
1160                                                error);
1161     if (bytes_read == sizeof(llvm::MachO::mach_header))
1162     {
1163         uint32_t offset = 0;
1164         ::memset (header, 0, sizeof(llvm::MachO::mach_header));
1165 
1166         // Get the magic byte unswapped so we can figure out what we are dealing with
1167         DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(), lldb::endian::InlHostByteOrder(), 4);
1168         header->magic = data.GetU32(&offset);
1169         lldb::addr_t load_cmd_addr = addr;
1170         data.SetByteOrder(DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic));
1171         switch (header->magic)
1172         {
1173         case llvm::MachO::HeaderMagic32:
1174         case llvm::MachO::HeaderMagic32Swapped:
1175             data.SetAddressByteSize(4);
1176             load_cmd_addr += sizeof(llvm::MachO::mach_header);
1177             break;
1178 
1179         case llvm::MachO::HeaderMagic64:
1180         case llvm::MachO::HeaderMagic64Swapped:
1181             data.SetAddressByteSize(8);
1182             load_cmd_addr += sizeof(llvm::MachO::mach_header_64);
1183             break;
1184 
1185         default:
1186             return false;
1187         }
1188 
1189         // Read the rest of dyld's mach header
1190         if (data.GetU32(&offset, &header->cputype, (sizeof(llvm::MachO::mach_header)/sizeof(uint32_t)) - 1))
1191         {
1192             if (load_command_data == NULL)
1193                 return true; // We were able to read the mach_header and weren't asked to read the load command bytes
1194 
1195             DataBufferSP load_cmd_data_sp(new DataBufferHeap(header->sizeofcmds, 0));
1196 
1197             size_t load_cmd_bytes_read = m_process->ReadMemory (load_cmd_addr,
1198                                                                 load_cmd_data_sp->GetBytes(),
1199                                                                 load_cmd_data_sp->GetByteSize(),
1200                                                                 error);
1201 
1202             if (load_cmd_bytes_read == header->sizeofcmds)
1203             {
1204                 // Set the load command data and also set the correct endian
1205                 // swap settings and the correct address size
1206                 load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds);
1207                 load_command_data->SetByteOrder(data.GetByteOrder());
1208                 load_command_data->SetAddressByteSize(data.GetAddressByteSize());
1209                 return true; // We successfully read the mach_header and the load command data
1210             }
1211 
1212             return false; // We weren't able to read the load command data
1213         }
1214     }
1215     return false; // We failed the read the mach_header
1216 }
1217 
1218 
1219 //----------------------------------------------------------------------
1220 // Parse the load commands for an image
1221 //----------------------------------------------------------------------
1222 uint32_t
1223 DynamicLoaderMacOSXDYLD::ParseLoadCommands (const DataExtractor& data, DYLDImageInfo& dylib_info, FileSpec *lc_id_dylinker)
1224 {
1225     uint32_t offset = 0;
1226     uint32_t cmd_idx;
1227     Segment segment;
1228     dylib_info.Clear (true);
1229 
1230     for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++)
1231     {
1232         // Clear out any load command specific data from DYLIB_INFO since
1233         // we are about to read it.
1234 
1235         if (data.ValidOffsetForDataOfSize (offset, sizeof(llvm::MachO::load_command)))
1236         {
1237             llvm::MachO::load_command load_cmd;
1238             uint32_t load_cmd_offset = offset;
1239             load_cmd.cmd = data.GetU32 (&offset);
1240             load_cmd.cmdsize = data.GetU32 (&offset);
1241             switch (load_cmd.cmd)
1242             {
1243             case llvm::MachO::LoadCommandSegment32:
1244                 {
1245                     segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
1246                     // We are putting 4 uint32_t values 4 uint64_t values so
1247                     // we have to use multiple 32 bit gets below.
1248                     segment.vmaddr = data.GetU32 (&offset);
1249                     segment.vmsize = data.GetU32 (&offset);
1250                     segment.fileoff = data.GetU32 (&offset);
1251                     segment.filesize = data.GetU32 (&offset);
1252                     // Extract maxprot, initprot, nsects and flags all at once
1253                     data.GetU32(&offset, &segment.maxprot, 4);
1254                     dylib_info.segments.push_back (segment);
1255                 }
1256                 break;
1257 
1258             case llvm::MachO::LoadCommandSegment64:
1259                 {
1260                     segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
1261                     // Extract vmaddr, vmsize, fileoff, and filesize all at once
1262                     data.GetU64(&offset, &segment.vmaddr, 4);
1263                     // Extract maxprot, initprot, nsects and flags all at once
1264                     data.GetU32(&offset, &segment.maxprot, 4);
1265                     dylib_info.segments.push_back (segment);
1266                 }
1267                 break;
1268 
1269             case llvm::MachO::LoadCommandDynamicLinkerIdent:
1270                 if (lc_id_dylinker)
1271                 {
1272                     uint32_t name_offset = load_cmd_offset + data.GetU32 (&offset);
1273                     const char *path = data.PeekCStr (name_offset);
1274                     lc_id_dylinker->SetFile (path, true);
1275                 }
1276                 break;
1277 
1278             case llvm::MachO::LoadCommandUUID:
1279                 dylib_info.uuid.SetBytes(data.GetData (&offset, 16));
1280                 break;
1281 
1282             default:
1283                 break;
1284             }
1285             // Set offset to be the beginning of the next load command.
1286             offset = load_cmd_offset + load_cmd.cmdsize;
1287         }
1288     }
1289 
1290     // All sections listed in the dyld image info structure will all
1291     // either be fixed up already, or they will all be off by a single
1292     // slide amount that is determined by finding the first segment
1293     // that is at file offset zero which also has bytes (a file size
1294     // that is greater than zero) in the object file.
1295 
1296     // Determine the slide amount (if any)
1297     const size_t num_sections = dylib_info.segments.size();
1298     for (size_t i = 0; i < num_sections; ++i)
1299     {
1300         // Iterate through the object file sections to find the
1301         // first section that starts of file offset zero and that
1302         // has bytes in the file...
1303         if (dylib_info.segments[i].fileoff == 0 && dylib_info.segments[i].filesize > 0)
1304         {
1305             dylib_info.slide = dylib_info.address - dylib_info.segments[i].vmaddr;
1306             // We have found the slide amount, so we can exit
1307             // this for loop.
1308             break;
1309         }
1310     }
1311     return cmd_idx;
1312 }
1313 
1314 //----------------------------------------------------------------------
1315 // Read the mach_header and load commands for each image that the
1316 // _dyld_all_image_infos structure points to and cache the results.
1317 //----------------------------------------------------------------------
1318 
1319 void
1320 DynamicLoaderMacOSXDYLD::UpdateImageInfosHeaderAndLoadCommands(DYLDImageInfo::collection &image_infos,
1321                                                                uint32_t infos_count,
1322                                                                bool update_executable)
1323 {
1324     uint32_t exe_idx = UINT32_MAX;
1325     LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
1326     // Read any UUID values that we can get
1327     for (uint32_t i = 0; i < infos_count; i++)
1328     {
1329         if (!image_infos[i].UUIDValid())
1330         {
1331             DataExtractor data; // Load command data
1332             if (!ReadMachHeader (image_infos[i].address, &image_infos[i].header, &data))
1333                 continue;
1334 
1335             ParseLoadCommands (data, image_infos[i], NULL);
1336 
1337             if (image_infos[i].header.filetype == llvm::MachO::HeaderFileTypeExecutable)
1338                 exe_idx = i;
1339 
1340         }
1341     }
1342 
1343     if (exe_idx < image_infos.size())
1344     {
1345         const bool can_create = true;
1346         ModuleSP exe_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[exe_idx], can_create, NULL));
1347 
1348         if (!exe_module_sp)
1349         {
1350             ArchSpec exe_arch_spec (image_infos[exe_idx].GetArchitecture ());
1351             ModuleSpec module_spec (image_infos[exe_idx].file_spec,
1352                                     image_infos[exe_idx].GetArchitecture ());
1353             module_spec.GetUUID() = image_infos[exe_idx].uuid;
1354             exe_module_sp = m_process->GetTarget().GetSharedModule (module_spec);
1355             if (!exe_module_sp || exe_module_sp->GetObjectFile() == NULL)
1356             {
1357                 const bool add_image_to_target = true;
1358                 const bool load_image_sections_in_target = false;
1359                 exe_module_sp = m_process->ReadModuleFromMemory (image_infos[exe_idx].file_spec,
1360                                                                  image_infos[exe_idx].address,
1361                                                                  add_image_to_target,
1362                                                                  load_image_sections_in_target);
1363             }
1364         }
1365 
1366         if (exe_module_sp)
1367         {
1368             if (exe_module_sp.get() != m_process->GetTarget().GetExecutableModulePointer())
1369             {
1370                 // Don't load dependent images since we are in dyld where we will know
1371                 // and find out about all images that are loaded
1372                 const bool get_dependent_images = false;
1373                 m_process->GetTarget().SetExecutableModule (exe_module_sp,
1374                                                             get_dependent_images);
1375             }
1376         }
1377     }
1378 }
1379 
1380 //----------------------------------------------------------------------
1381 // On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
1382 // functions written in hand-written assembly, and also have hand-written unwind
1383 // information in the eh_frame section.  Normally we prefer analyzing the
1384 // assembly instructions of a curently executing frame to unwind from that frame --
1385 // but on hand-written functions this profiling can fail.  We should use the
1386 // eh_frame instructions for these functions all the time.
1387 //
1388 // As an aside, it would be better if the eh_frame entries had a flag (or were
1389 // extensible so they could have an Apple-specific flag) which indicates that
1390 // the instructions are asynchronous -- accurate at every instruction, instead
1391 // of our normal default assumption that they are not.
1392 //----------------------------------------------------------------------
1393 
1394 bool
1395 DynamicLoaderMacOSXDYLD::AlwaysRelyOnEHUnwindInfo (SymbolContext &sym_ctx)
1396 {
1397     ModuleSP module_sp;
1398     if (sym_ctx.symbol)
1399     {
1400         module_sp = sym_ctx.symbol->GetAddress().GetModule();
1401     }
1402     if (module_sp.get() == NULL && sym_ctx.function)
1403     {
1404         module_sp = sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
1405     }
1406     if (module_sp.get() == NULL)
1407         return false;
1408 
1409     ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime();
1410     if (objc_runtime != NULL && objc_runtime->IsModuleObjCLibrary (module_sp))
1411     {
1412         return true;
1413     }
1414 
1415     return false;
1416 }
1417 
1418 
1419 
1420 //----------------------------------------------------------------------
1421 // Dump a Segment to the file handle provided.
1422 //----------------------------------------------------------------------
1423 void
1424 DynamicLoaderMacOSXDYLD::Segment::PutToLog (Log *log, lldb::addr_t slide) const
1425 {
1426     if (log)
1427     {
1428         if (slide == 0)
1429             log->Printf ("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
1430                          name.AsCString(""),
1431                          vmaddr + slide,
1432                          vmaddr + slide + vmsize);
1433         else
1434             log->Printf ("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") slide = 0x%" PRIx64,
1435                          name.AsCString(""),
1436                          vmaddr + slide,
1437                          vmaddr + slide + vmsize,
1438                          slide);
1439     }
1440 }
1441 
1442 const DynamicLoaderMacOSXDYLD::Segment *
1443 DynamicLoaderMacOSXDYLD::DYLDImageInfo::FindSegment (const ConstString &name) const
1444 {
1445     const size_t num_segments = segments.size();
1446     for (size_t i=0; i<num_segments; ++i)
1447     {
1448         if (segments[i].name == name)
1449             return &segments[i];
1450     }
1451     return NULL;
1452 }
1453 
1454 
1455 //----------------------------------------------------------------------
1456 // Dump an image info structure to the file handle provided.
1457 //----------------------------------------------------------------------
1458 void
1459 DynamicLoaderMacOSXDYLD::DYLDImageInfo::PutToLog (Log *log) const
1460 {
1461     if (log == NULL)
1462         return;
1463     uint8_t *u = (uint8_t *)uuid.GetBytes();
1464 
1465     if (address == LLDB_INVALID_ADDRESS)
1466     {
1467         if (u)
1468         {
1469             log->Printf("\t                           modtime=0x%8.8" PRIx64 " uuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X path='%s/%s' (UNLOADED)",
1470                         mod_date,
1471                         u[ 0], u[ 1], u[ 2], u[ 3],
1472                         u[ 4], u[ 5], u[ 6], u[ 7],
1473                         u[ 8], u[ 9], u[10], u[11],
1474                         u[12], u[13], u[14], u[15],
1475                         file_spec.GetDirectory().AsCString(),
1476                         file_spec.GetFilename().AsCString());
1477         }
1478         else
1479             log->Printf("\t                           modtime=0x%8.8" PRIx64 " path='%s/%s' (UNLOADED)",
1480                         mod_date,
1481                         file_spec.GetDirectory().AsCString(),
1482                         file_spec.GetFilename().AsCString());
1483     }
1484     else
1485     {
1486         if (u)
1487         {
1488             log->Printf("\taddress=0x%16.16" PRIx64 " modtime=0x%8.8" PRIx64 " uuid=%2.2X%2.2X%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X path='%s/%s'",
1489                         address,
1490                         mod_date,
1491                         u[ 0], u[ 1], u[ 2], u[ 3],
1492                         u[ 4], u[ 5], u[ 6], u[ 7],
1493                         u[ 8], u[ 9], u[10], u[11],
1494                         u[12], u[13], u[14], u[15],
1495                         file_spec.GetDirectory().AsCString(),
1496                         file_spec.GetFilename().AsCString());
1497         }
1498         else
1499         {
1500             log->Printf("\taddress=0x%16.16" PRIx64 " modtime=0x%8.8" PRIx64 " path='%s/%s'",
1501                         address,
1502                         mod_date,
1503                         file_spec.GetDirectory().AsCString(),
1504                         file_spec.GetFilename().AsCString());
1505 
1506         }
1507         for (uint32_t i=0; i<segments.size(); ++i)
1508             segments[i].PutToLog(log, slide);
1509     }
1510 }
1511 
1512 //----------------------------------------------------------------------
1513 // Dump the _dyld_all_image_infos members and all current image infos
1514 // that we have parsed to the file handle provided.
1515 //----------------------------------------------------------------------
1516 void
1517 DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const
1518 {
1519     if (log == NULL)
1520         return;
1521 
1522     Mutex::Locker locker(m_mutex);
1523     log->Printf("dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8" PRIx64 ", notify=0x%8.8" PRIx64 " }",
1524                     m_dyld_all_image_infos.version,
1525                     m_dyld_all_image_infos.dylib_info_count,
1526                     (uint64_t)m_dyld_all_image_infos.dylib_info_addr,
1527                     (uint64_t)m_dyld_all_image_infos.notification);
1528     size_t i;
1529     const size_t count = m_dyld_image_infos.size();
1530     if (count > 0)
1531     {
1532         log->PutCString("Loaded:");
1533         for (i = 0; i<count; i++)
1534             m_dyld_image_infos[i].PutToLog(log);
1535     }
1536 }
1537 
1538 void
1539 DynamicLoaderMacOSXDYLD::PrivateInitialize(Process *process)
1540 {
1541     DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1542     Clear(true);
1543     m_process = process;
1544     m_process->GetTarget().GetSectionLoadList().Clear();
1545 }
1546 
1547 bool
1548 DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint ()
1549 {
1550     DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1551     if (m_break_id == LLDB_INVALID_BREAK_ID)
1552     {
1553         if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS)
1554         {
1555             Address so_addr;
1556             // Set the notification breakpoint and install a breakpoint
1557             // callback function that will get called each time the
1558             // breakpoint gets hit. We will use this to track when shared
1559             // libraries get loaded/unloaded.
1560 
1561             if (m_process->GetTarget().GetSectionLoadList().ResolveLoadAddress(m_dyld_all_image_infos.notification, so_addr))
1562             {
1563                 Breakpoint *dyld_break = m_process->GetTarget().CreateBreakpoint (so_addr, true).get();
1564                 dyld_break->SetCallback (DynamicLoaderMacOSXDYLD::NotifyBreakpointHit, this, true);
1565                 m_break_id = dyld_break->GetID();
1566             }
1567         }
1568     }
1569     return m_break_id != LLDB_INVALID_BREAK_ID;
1570 }
1571 
1572 //----------------------------------------------------------------------
1573 // Member function that gets called when the process state changes.
1574 //----------------------------------------------------------------------
1575 void
1576 DynamicLoaderMacOSXDYLD::PrivateProcessStateChanged (Process *process, StateType state)
1577 {
1578     DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s(%s)\n", __FUNCTION__, StateAsCString(state));
1579     switch (state)
1580     {
1581     case eStateConnected:
1582     case eStateAttaching:
1583     case eStateLaunching:
1584     case eStateInvalid:
1585     case eStateUnloaded:
1586     case eStateExited:
1587     case eStateDetached:
1588         Clear(false);
1589         break;
1590 
1591     case eStateStopped:
1592         // Keep trying find dyld and set our notification breakpoint each time
1593         // we stop until we succeed
1594         if (!DidSetNotificationBreakpoint () && m_process->IsAlive())
1595         {
1596             if (NeedToLocateDYLD ())
1597                 LocateDYLD ();
1598 
1599             SetNotificationBreakpoint ();
1600         }
1601         break;
1602 
1603     case eStateRunning:
1604     case eStateStepping:
1605     case eStateCrashed:
1606     case eStateSuspended:
1607         break;
1608 
1609     default:
1610         break;
1611     }
1612 }
1613 
1614 // This bit in the n_desc field of the mach file means that this is a
1615 // stub that runs arbitrary code to determine the trampoline target.
1616 // We've established a naming convention with the CoreOS folks for the
1617 // equivalent symbols they will use for this (which the objc guys didn't follow...)
1618 // For now we'll just look for all symbols matching that naming convention...
1619 
1620 #define MACH_O_N_SYMBOL_RESOLVER 0x100
1621 
1622 ThreadPlanSP
1623 DynamicLoaderMacOSXDYLD::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
1624 {
1625     ThreadPlanSP thread_plan_sp;
1626     StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
1627     const SymbolContext &current_context = current_frame->GetSymbolContext(eSymbolContextSymbol);
1628     Symbol *current_symbol = current_context.symbol;
1629     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1630 
1631     if (current_symbol != NULL)
1632     {
1633         if (current_symbol->IsTrampoline())
1634         {
1635             const ConstString &trampoline_name = current_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1636 
1637             if (trampoline_name)
1638             {
1639                 SymbolContextList target_symbols;
1640                 TargetSP target_sp (thread.CalculateTarget());
1641                 const ModuleList &images = target_sp->GetImages();
1642 
1643                 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode, target_symbols);
1644 
1645                 size_t num_original_symbols = target_symbols.GetSize();
1646                 // FIXME: The resolver symbol is only valid in object files.  In binaries it is reused for the
1647                 // shared library slot number.  So we'll have to look this up in the dyld info.
1648                 // For now, just turn this off.
1649 
1650                 // bool orig_is_resolver = (current_symbol->GetFlags() & MACH_O_N_SYMBOL_RESOLVER) == MACH_O_N_SYMBOL_RESOLVER;
1651                 // FIXME: Actually that isn't true, the N_SYMBOL_RESOLVER bit is only valid in .o files.  You can't use
1652                 // the symbol flags to tell whether something is a symbol resolver in a linked image.
1653                 bool orig_is_resolver = false;
1654 
1655                 if (num_original_symbols > 0)
1656                 {
1657                     // We found symbols that look like they are the targets to our symbol.  Now look through the
1658                     // modules containing our symbols to see if there are any for our symbol.
1659 
1660                     ModuleList modules_to_search;
1661 
1662                     for (size_t i = 0; i < num_original_symbols; i++)
1663                     {
1664                         SymbolContext sc;
1665                         target_symbols.GetContextAtIndex(i, sc);
1666 
1667                         ModuleSP module_sp (sc.symbol->CalculateSymbolContextModule());
1668                         if (module_sp)
1669                              modules_to_search.AppendIfNeeded(module_sp);
1670                     }
1671 
1672                     // If the original stub symbol is a resolver, then we don't want to break on the symbol with the
1673                     // original name, but instead on all the symbols it could resolve to since otherwise we would stop
1674                     // in the middle of the resolution...
1675                     // Note that the stub is not of the resolver type it will point to the equivalent symbol,
1676                     // not the original name, so in that case we don't need to do anything.
1677 
1678                     if (orig_is_resolver)
1679                     {
1680                         target_symbols.Clear();
1681 
1682                         FindEquivalentSymbols (current_symbol, modules_to_search, target_symbols);
1683                     }
1684 
1685                     // FIXME - Make the Run to Address take multiple addresses, and
1686                     // run to any of them.
1687                     uint32_t num_symbols = target_symbols.GetSize();
1688                     if (num_symbols > 0)
1689                     {
1690                         std::vector<lldb::addr_t>  addresses;
1691                         addresses.resize (num_symbols);
1692                         for (uint32_t i = 0; i < num_symbols; i++)
1693                         {
1694                             SymbolContext context;
1695                             AddressRange addr_range;
1696                             if (target_symbols.GetContextAtIndex(i, context))
1697                             {
1698                                 context.GetAddressRange (eSymbolContextEverything, 0, false, addr_range);
1699                                 lldb::addr_t load_addr = addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
1700                                 addresses[i] = load_addr;
1701                             }
1702                         }
1703                         if (addresses.size() > 0)
1704                             thread_plan_sp.reset (new ThreadPlanRunToAddress (thread, addresses, stop_others));
1705                         else
1706                         {
1707                             if (log)
1708                                 log->Printf ("Couldn't resolve the symbol contexts.");
1709                         }
1710                     }
1711                     else
1712                     {
1713                         if (log)
1714                         {
1715                             log->Printf ("Found a resolver stub for: \"%s\" but could not find any symbols it resolves to.",
1716                                          trampoline_name.AsCString());
1717                         }
1718                     }
1719                 }
1720                 else
1721                 {
1722                     if (log)
1723                     {
1724                         log->Printf ("Could not find symbol for trampoline target: \"%s\"", trampoline_name.AsCString());
1725                     }
1726                 }
1727             }
1728         }
1729     }
1730     else
1731     {
1732         if (log)
1733             log->Printf ("Could not find symbol for step through.");
1734     }
1735 
1736     return thread_plan_sp;
1737 }
1738 
1739 size_t
1740 DynamicLoaderMacOSXDYLD::FindEquivalentSymbols (lldb_private::Symbol *original_symbol,
1741                                                lldb_private::ModuleList &images,
1742                                                lldb_private::SymbolContextList &equivalent_symbols)
1743 {
1744     const ConstString &trampoline_name = original_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1745     if (!trampoline_name)
1746         return 0;
1747 
1748     size_t initial_size = equivalent_symbols.GetSize();
1749 
1750     static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Z0-9]+)$";
1751     std::string equivalent_regex_buf("^");
1752     equivalent_regex_buf.append (trampoline_name.GetCString());
1753     equivalent_regex_buf.append (resolver_name_regex);
1754 
1755     RegularExpression equivalent_name_regex (equivalent_regex_buf.c_str());
1756     const bool append = true;
1757     images.FindSymbolsMatchingRegExAndType (equivalent_name_regex, eSymbolTypeCode, equivalent_symbols, append);
1758 
1759     return equivalent_symbols.GetSize() - initial_size;
1760 }
1761 
1762 Error
1763 DynamicLoaderMacOSXDYLD::CanLoadImage ()
1764 {
1765     Error error;
1766     // In order for us to tell if we can load a shared library we verify that
1767     // the dylib_info_addr isn't zero (which means no shared libraries have
1768     // been set yet, or dyld is currently mucking with the shared library list).
1769     if (ReadAllImageInfosStructure ())
1770     {
1771         // TODO: also check the _dyld_global_lock_held variable in libSystem.B.dylib?
1772         // TODO: check the malloc lock?
1773         // TODO: check the objective C lock?
1774         if (m_dyld_all_image_infos.dylib_info_addr != 0)
1775             return error; // Success
1776     }
1777 
1778     error.SetErrorString("unsafe to load or unload shared libraries");
1779     return error;
1780 }
1781 
1782 void
1783 DynamicLoaderMacOSXDYLD::Initialize()
1784 {
1785     PluginManager::RegisterPlugin (GetPluginNameStatic(),
1786                                    GetPluginDescriptionStatic(),
1787                                    CreateInstance);
1788 }
1789 
1790 void
1791 DynamicLoaderMacOSXDYLD::Terminate()
1792 {
1793     PluginManager::UnregisterPlugin (CreateInstance);
1794 }
1795 
1796 
1797 const char *
1798 DynamicLoaderMacOSXDYLD::GetPluginNameStatic()
1799 {
1800     return "dynamic-loader.macosx-dyld";
1801 }
1802 
1803 const char *
1804 DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic()
1805 {
1806     return "Dynamic loader plug-in that watches for shared library loads/unloads in MacOSX user processes.";
1807 }
1808 
1809 
1810 //------------------------------------------------------------------
1811 // PluginInterface protocol
1812 //------------------------------------------------------------------
1813 const char *
1814 DynamicLoaderMacOSXDYLD::GetPluginName()
1815 {
1816     return "DynamicLoaderMacOSXDYLD";
1817 }
1818 
1819 const char *
1820 DynamicLoaderMacOSXDYLD::GetShortPluginName()
1821 {
1822     return GetPluginNameStatic();
1823 }
1824 
1825 uint32_t
1826 DynamicLoaderMacOSXDYLD::GetPluginVersion()
1827 {
1828     return 1;
1829 }
1830 
1831 uint32_t
1832 DynamicLoaderMacOSXDYLD::AddrByteSize()
1833 {
1834     switch (m_dyld.header.magic)
1835     {
1836         case llvm::MachO::HeaderMagic32:
1837         case llvm::MachO::HeaderMagic32Swapped:
1838             return 4;
1839 
1840         case llvm::MachO::HeaderMagic64:
1841         case llvm::MachO::HeaderMagic64Swapped:
1842             return 8;
1843 
1844         default:
1845             break;
1846     }
1847     return 0;
1848 }
1849 
1850 lldb::ByteOrder
1851 DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic (uint32_t magic)
1852 {
1853     switch (magic)
1854     {
1855         case llvm::MachO::HeaderMagic32:
1856         case llvm::MachO::HeaderMagic64:
1857             return lldb::endian::InlHostByteOrder();
1858 
1859         case llvm::MachO::HeaderMagic32Swapped:
1860         case llvm::MachO::HeaderMagic64Swapped:
1861             if (lldb::endian::InlHostByteOrder() == lldb::eByteOrderBig)
1862                 return lldb::eByteOrderLittle;
1863             else
1864                 return lldb::eByteOrderBig;
1865 
1866         default:
1867             break;
1868     }
1869     return lldb::eByteOrderInvalid;
1870 }
1871 
1872 lldb::ByteOrder
1873 DynamicLoaderMacOSXDYLD::DYLDImageInfo::GetByteOrder()
1874 {
1875     return DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header.magic);
1876 }
1877 
1878