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