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 *
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 *
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 //----------------------------------------------------------------------
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 //----------------------------------------------------------------------
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
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
180 DynamicLoaderMacOSXDYLD::DidLaunch ()
181 {
182     PrivateInitialize(m_process);
183     LocateDYLD ();
184     SetNotificationBreakpoint ();
185 }
186 
187 bool
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
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
260 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
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
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
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
436 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
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
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
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         void *clang_void_ptr_type = clang_ast_context->GetVoidPtrType(false);
629         void *clang_uint32_type   = clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(lldb::eEncodingUint, 32);
630         input_value.SetValueType (Value::eValueTypeScalar);
631         input_value.SetContext (Value::eContextTypeClangType, clang_uint32_type);
632         argument_values.PushValue(input_value);
633         argument_values.PushValue(input_value);
634         input_value.SetContext (Value::eContextTypeClangType, clang_void_ptr_type);
635         argument_values.PushValue (input_value);
636 
637         if (abi->GetArgumentValues (exe_ctx.GetThreadRef(), argument_values))
638         {
639             uint32_t dyld_mode = argument_values.GetValueAtIndex(0)->GetScalar().UInt (-1);
640             if (dyld_mode != -1)
641             {
642                 // Okay the mode was right, now get the number of elements, and the array of new elements...
643                 uint32_t image_infos_count = argument_values.GetValueAtIndex(1)->GetScalar().UInt (-1);
644                 if (image_infos_count != -1)
645                 {
646                     // Got the number added, now go through the array of added elements, putting out the mach header
647                     // address, and adding the image.
648                     // Note, I'm not putting in logging here, since the AddModules & RemoveModules functions do
649                     // all the logging internally.
650 
651                     lldb::addr_t image_infos_addr = argument_values.GetValueAtIndex(2)->GetScalar().ULongLong();
652                     if (dyld_mode == 0)
653                     {
654                         // This is add:
655                         dyld_instance->AddModulesUsingImageInfosAddress (image_infos_addr, image_infos_count);
656                     }
657                     else
658                     {
659                         // This is remove:
660                         dyld_instance->RemoveModulesUsingImageInfosAddress (image_infos_addr, image_infos_count);
661                     }
662 
663                 }
664             }
665         }
666     }
667 
668     // Return true to stop the target, false to just let the target run
669     return dyld_instance->GetStopWhenImagesChange();
670 }
671 
672 bool
673 DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure ()
674 {
675     Mutex::Locker locker(m_mutex);
676 
677     // the all image infos is already valid for this process stop ID
678     if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id)
679         return true;
680 
681     m_dyld_all_image_infos.Clear();
682     if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS)
683     {
684         ByteOrder byte_order = m_process->GetTarget().GetArchitecture().GetByteOrder();
685         uint32_t addr_size = 4;
686         if (m_dyld_all_image_infos_addr > UINT32_MAX)
687             addr_size = 8;
688 
689         uint8_t buf[256];
690         DataExtractor data (buf, sizeof(buf), byte_order, addr_size);
691         lldb::offset_t offset = 0;
692 
693         const size_t count_v2 =  sizeof (uint32_t) + // version
694                                  sizeof (uint32_t) + // infoArrayCount
695                                  addr_size +         // infoArray
696                                  addr_size +         // notification
697                                  addr_size +         // processDetachedFromSharedRegion + libSystemInitialized + pad
698                                  addr_size;          // dyldImageLoadAddress
699         const size_t count_v11 = count_v2 +
700                                  addr_size +         // jitInfo
701                                  addr_size +         // dyldVersion
702                                  addr_size +         // errorMessage
703                                  addr_size +         // terminationFlags
704                                  addr_size +         // coreSymbolicationShmPage
705                                  addr_size +         // systemOrderFlag
706                                  addr_size +         // uuidArrayCount
707                                  addr_size +         // uuidArray
708                                  addr_size +         // dyldAllImageInfosAddress
709                                  addr_size +         // initialImageCount
710                                  addr_size +         // errorKind
711                                  addr_size +         // errorClientOfDylibPath
712                                  addr_size +         // errorTargetDylibPath
713                                  addr_size;          // errorSymbol
714         const size_t count_v13 = count_v11 +
715                                  addr_size +         // sharedCacheSlide
716                                  sizeof (uuid_t);    // sharedCacheUUID
717         assert (sizeof (buf) >= count_v13);
718 
719         Error error;
720         if (m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, 4, error) == 4)
721         {
722             m_dyld_all_image_infos.version = data.GetU32(&offset);
723             // If anything in the high byte is set, we probably got the byte
724             // order incorrect (the process might not have it set correctly
725             // yet due to attaching to a program without a specified file).
726             if (m_dyld_all_image_infos.version & 0xff000000)
727             {
728                 // We have guessed the wrong byte order. Swap it and try
729                 // reading the version again.
730                 if (byte_order == eByteOrderLittle)
731                     byte_order = eByteOrderBig;
732                 else
733                     byte_order = eByteOrderLittle;
734 
735                 data.SetByteOrder (byte_order);
736                 offset = 0;
737                 m_dyld_all_image_infos.version = data.GetU32(&offset);
738             }
739         }
740         else
741         {
742             return false;
743         }
744 
745         const size_t count = (m_dyld_all_image_infos.version >= 11) ? count_v11 : count_v2;
746 
747         const size_t bytes_read = m_process->ReadMemory (m_dyld_all_image_infos_addr, buf, count, error);
748         if (bytes_read == count)
749         {
750             offset = 0;
751             m_dyld_all_image_infos.version = data.GetU32(&offset);
752             m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset);
753             m_dyld_all_image_infos.dylib_info_addr = data.GetPointer(&offset);
754             m_dyld_all_image_infos.notification = data.GetPointer(&offset);
755             m_dyld_all_image_infos.processDetachedFromSharedRegion = data.GetU8(&offset);
756             m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset);
757             // Adjust for padding.
758             offset += addr_size - 2;
759             m_dyld_all_image_infos.dyldImageLoadAddress = data.GetPointer(&offset);
760             if (m_dyld_all_image_infos.version >= 11)
761             {
762                 offset += addr_size * 8;
763                 uint64_t dyld_all_image_infos_addr = data.GetPointer(&offset);
764 
765                 // When we started, we were given the actual address of the all_image_infos
766                 // struct (probably via TASK_DYLD_INFO) in memory - this address is stored in
767                 // m_dyld_all_image_infos_addr and is the most accurate address we have.
768 
769                 // We read the dyld_all_image_infos struct from memory; it contains its own address.
770                 // If the address in the struct does not match the actual address,
771                 // the dyld we're looking at has been loaded at a different location (slid) from
772                 // where it intended to load.  The addresses in the dyld_all_image_infos struct
773                 // are the original, non-slid addresses, and need to be adjusted.  Most importantly
774                 // the address of dyld and the notification address need to be adjusted.
775 
776                 if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr)
777                 {
778                     uint64_t image_infos_offset = dyld_all_image_infos_addr - m_dyld_all_image_infos.dyldImageLoadAddress;
779                     uint64_t notification_offset = m_dyld_all_image_infos.notification - m_dyld_all_image_infos.dyldImageLoadAddress;
780                     m_dyld_all_image_infos.dyldImageLoadAddress = m_dyld_all_image_infos_addr - image_infos_offset;
781                     m_dyld_all_image_infos.notification = m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset;
782                 }
783             }
784             m_dyld_all_image_infos_stop_id = m_process->GetStopID();
785             return true;
786         }
787     }
788     return false;
789 }
790 
791 
792 bool
793 DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfosAddress (lldb::addr_t image_infos_addr, uint32_t image_infos_count)
794 {
795     DYLDImageInfo::collection image_infos;
796     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
797     if (log)
798         log->Printf ("Adding %d modules.\n", image_infos_count);
799 
800     Mutex::Locker locker(m_mutex);
801     if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
802         return true;
803 
804     if (!ReadImageInfos (image_infos_addr, image_infos_count, image_infos))
805         return false;
806 
807     UpdateImageInfosHeaderAndLoadCommands (image_infos, image_infos_count, false);
808     bool return_value = AddModulesUsingImageInfos (image_infos);
809     m_dyld_image_infos_stop_id = m_process->GetStopID();
810     return return_value;
811 }
812 
813 // Adds the modules in image_infos to m_dyld_image_infos.
814 // NB don't call this passing in m_dyld_image_infos.
815 
816 bool
817 DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfos (DYLDImageInfo::collection &image_infos)
818 {
819     // Now add these images to the main list.
820     ModuleList loaded_module_list;
821     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
822     Target &target = m_process->GetTarget();
823     ModuleList& target_images = target.GetImages();
824 
825     for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
826     {
827         if (log)
828         {
829             log->Printf ("Adding new image at address=0x%16.16" PRIx64 ".", image_infos[idx].address);
830             image_infos[idx].PutToLog (log);
831         }
832 
833         m_dyld_image_infos.push_back(image_infos[idx]);
834 
835         ModuleSP image_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[idx], true, NULL));
836 
837         if (image_module_sp)
838         {
839             if (image_infos[idx].header.filetype == llvm::MachO::HeaderFileTypeDynamicLinkEditor)
840                 image_module_sp->SetIsDynamicLinkEditor (true);
841 
842             ObjectFile *objfile = image_module_sp->GetObjectFile ();
843             if (objfile)
844             {
845                 SectionList *sections = objfile->GetSectionList();
846                 if (sections)
847                 {
848                     ConstString commpage_dbstr("__commpage");
849                     Section *commpage_section = sections->FindSectionByName(commpage_dbstr).get();
850                     if (commpage_section)
851                     {
852                         ModuleSpec module_spec (objfile->GetFileSpec(), image_infos[idx].GetArchitecture ());
853                         module_spec.GetObjectName() = commpage_dbstr;
854                         ModuleSP commpage_image_module_sp(target_images.FindFirstModule (module_spec));
855                         if (!commpage_image_module_sp)
856                         {
857                             module_spec.SetObjectOffset (objfile->GetFileOffset() + commpage_section->GetFileOffset());
858                             commpage_image_module_sp  = target.GetSharedModule (module_spec);
859                             if (!commpage_image_module_sp || commpage_image_module_sp->GetObjectFile() == NULL)
860                             {
861                                 commpage_image_module_sp = m_process->ReadModuleFromMemory (image_infos[idx].file_spec,
862                                                                                             image_infos[idx].address);
863                                 // Always load a memory image right away in the target in case
864                                 // we end up trying to read the symbol table from memory... The
865                                 // __LINKEDIT will need to be mapped so we can figure out where
866                                 // the symbol table bits are...
867                                 bool changed = false;
868                                 UpdateImageLoadAddress (commpage_image_module_sp.get(), image_infos[idx]);
869                                 target.GetImages().Append(commpage_image_module_sp);
870                                 if (changed)
871                                 {
872                                     image_infos[idx].load_stop_id = m_process->GetStopID();
873                                     loaded_module_list.AppendIfNeeded (commpage_image_module_sp);
874                                 }
875                             }
876                         }
877                     }
878                 }
879             }
880 
881             // UpdateImageLoadAddress will return true if any segments
882             // change load address. We need to check this so we don't
883             // mention that all loaded shared libraries are newly loaded
884             // each time we hit out dyld breakpoint since dyld will list all
885             // shared libraries each time.
886             if (UpdateImageLoadAddress (image_module_sp.get(), image_infos[idx]))
887             {
888                 target_images.AppendIfNeeded(image_module_sp);
889                 loaded_module_list.AppendIfNeeded (image_module_sp);
890             }
891         }
892     }
893 
894     if (loaded_module_list.GetSize() > 0)
895     {
896         // FIXME: This should really be in the Runtime handlers class, which should get
897         // called by the target's ModulesDidLoad, but we're doing it all locally for now
898         // to save time.
899         // Also, I'm assuming there can be only one libobjc dylib loaded...
900 
901         ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime(true);
902         if (objc_runtime != NULL && !objc_runtime->HasReadObjCLibrary())
903         {
904             size_t num_modules = loaded_module_list.GetSize();
905             for (int i = 0; i < num_modules; i++)
906             {
907                 if (objc_runtime->IsModuleObjCLibrary (loaded_module_list.GetModuleAtIndex (i)))
908                 {
909                     objc_runtime->ReadObjCLibrary (loaded_module_list.GetModuleAtIndex (i));
910                     break;
911                 }
912             }
913         }
914         if (log)
915             loaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderMacOSXDYLD::ModulesDidLoad");
916         m_process->GetTarget().ModulesDidLoad (loaded_module_list);
917     }
918     return true;
919 }
920 
921 bool
922 DynamicLoaderMacOSXDYLD::RemoveModulesUsingImageInfosAddress (lldb::addr_t image_infos_addr, uint32_t image_infos_count)
923 {
924     DYLDImageInfo::collection image_infos;
925     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
926 
927     Mutex::Locker locker(m_mutex);
928     if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
929         return true;
930 
931     // First read in the image_infos for the removed modules, and their headers & load commands.
932     if (!ReadImageInfos (image_infos_addr, image_infos_count, image_infos))
933     {
934         if (log)
935             log->PutCString ("Failed reading image infos array.");
936         return false;
937     }
938 
939     if (log)
940         log->Printf ("Removing %d modules.", image_infos_count);
941 
942     ModuleList unloaded_module_list;
943     for (uint32_t idx = 0; idx < image_infos.size(); ++idx)
944     {
945         if (log)
946         {
947             log->Printf ("Removing module at address=0x%16.16" PRIx64 ".", image_infos[idx].address);
948             image_infos[idx].PutToLog (log);
949         }
950 
951         // Remove this image_infos from the m_all_image_infos.  We do the comparision by address
952         // rather than by file spec because we can have many modules with the same "file spec" in the
953         // case that they are modules loaded from memory.
954         //
955         // Also copy over the uuid from the old entry to the removed entry so we can
956         // use it to lookup the module in the module list.
957 
958         DYLDImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
959         for (pos = m_dyld_image_infos.begin(); pos != end; pos++)
960         {
961             if (image_infos[idx].address == (*pos).address)
962             {
963                 image_infos[idx].uuid = (*pos).uuid;
964 
965                 // Add the module from this image_info to the "unloaded_module_list".  We'll remove them all at
966                 // one go later on.
967 
968                 ModuleSP unload_image_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[idx], false, NULL));
969                 if (unload_image_module_sp.get())
970                 {
971                     // When we unload, be sure to use the image info from the old list,
972                     // since that has sections correctly filled in.
973                     UnloadImageLoadAddress (unload_image_module_sp.get(), *pos);
974                     unloaded_module_list.AppendIfNeeded (unload_image_module_sp);
975                 }
976                 else
977                 {
978                     if (log)
979                     {
980                         log->Printf ("Could not find module for unloading info entry:");
981                         image_infos[idx].PutToLog(log);
982                     }
983                 }
984 
985                 // Then remove it from the m_dyld_image_infos:
986 
987                 m_dyld_image_infos.erase(pos);
988                 break;
989             }
990         }
991 
992         if (pos == end)
993         {
994             if (log)
995             {
996                 log->Printf ("Could not find image_info entry for unloading image:");
997                 image_infos[idx].PutToLog(log);
998             }
999         }
1000     }
1001     if (unloaded_module_list.GetSize() > 0)
1002     {
1003         if (log)
1004         {
1005             log->PutCString("Unloaded:");
1006             unloaded_module_list.LogUUIDAndPaths (log, "DynamicLoaderMacOSXDYLD::ModulesDidUnload");
1007         }
1008         m_process->GetTarget().GetImages().Remove (unloaded_module_list);
1009     }
1010     m_dyld_image_infos_stop_id = m_process->GetStopID();
1011     return true;
1012 }
1013 
1014 bool
1015 DynamicLoaderMacOSXDYLD::ReadImageInfos (lldb::addr_t image_infos_addr,
1016                                          uint32_t image_infos_count,
1017                                          DYLDImageInfo::collection &image_infos)
1018 {
1019     const ByteOrder endian = m_dyld.GetByteOrder();
1020     const uint32_t addr_size = m_dyld.GetAddressByteSize();
1021 
1022     image_infos.resize(image_infos_count);
1023     const size_t count = image_infos.size() * 3 * addr_size;
1024     DataBufferHeap info_data(count, 0);
1025     Error error;
1026     const size_t bytes_read = m_process->ReadMemory (image_infos_addr,
1027                                                      info_data.GetBytes(),
1028                                                      info_data.GetByteSize(),
1029                                                      error);
1030     if (bytes_read == count)
1031     {
1032         lldb::offset_t info_data_offset = 0;
1033         DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(), endian, addr_size);
1034         for (int i = 0; i < image_infos.size() && info_data_ref.ValidOffset(info_data_offset); i++)
1035         {
1036             image_infos[i].address = info_data_ref.GetPointer(&info_data_offset);
1037             lldb::addr_t path_addr = info_data_ref.GetPointer(&info_data_offset);
1038             image_infos[i].mod_date = info_data_ref.GetPointer(&info_data_offset);
1039 
1040             char raw_path[PATH_MAX];
1041             m_process->ReadCStringFromMemory (path_addr, raw_path, sizeof(raw_path), error);
1042             // don't resolve the path
1043             if (error.Success())
1044             {
1045                 const bool resolve_path = false;
1046                 image_infos[i].file_spec.SetFile(raw_path, resolve_path);
1047             }
1048         }
1049         return true;
1050     }
1051     else
1052     {
1053         return false;
1054     }
1055 }
1056 
1057 //----------------------------------------------------------------------
1058 // If we have found where the "_dyld_all_image_infos" lives in memory,
1059 // read the current info from it, and then update all image load
1060 // addresses (or lack thereof).  Only do this if this is the first time
1061 // we're reading the dyld infos.  Return true if we actually read anything,
1062 // and false otherwise.
1063 //----------------------------------------------------------------------
1064 bool
1065 DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos ()
1066 {
1067     Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_DYNAMIC_LOADER));
1068 
1069     Mutex::Locker locker(m_mutex);
1070     if (m_process->GetStopID() == m_dyld_image_infos_stop_id
1071           || m_dyld_image_infos.size() != 0)
1072         return false;
1073 
1074     if (ReadAllImageInfosStructure ())
1075     {
1076         // Nothing to load or unload?
1077         if (m_dyld_all_image_infos.dylib_info_count == 0)
1078             return true;
1079 
1080         if (m_dyld_all_image_infos.dylib_info_addr == 0)
1081         {
1082             // DYLD is updating the images now.  So we should say we have no images, and then we'll
1083             // figure it out when we hit the added breakpoint.
1084             return false;
1085         }
1086         else
1087         {
1088             if (!AddModulesUsingImageInfosAddress (m_dyld_all_image_infos.dylib_info_addr,
1089                                                    m_dyld_all_image_infos.dylib_info_count))
1090             {
1091                 DEBUG_PRINTF("%s", "unable to read all data for all_dylib_infos.");
1092                 m_dyld_image_infos.clear();
1093             }
1094         }
1095 
1096         // Now we have one more bit of business.  If there is a library left in the images for our target that
1097         // doesn't have a load address, then it must be something that we were expecting to load (for instance we
1098         // read a load command for it) but it didn't in fact load - probably because DYLD_*_PATH pointed
1099         // to an equivalent version.  We don't want it to stay in the target's module list or it will confuse
1100         // us, so unload it here.
1101         Target &target = m_process->GetTarget();
1102         const ModuleList &target_modules = target.GetImages();
1103         ModuleList not_loaded_modules;
1104         Mutex::Locker modules_locker(target_modules.GetMutex());
1105 
1106         size_t num_modules = target_modules.GetSize();
1107         for (size_t i = 0; i < num_modules; i++)
1108         {
1109             ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked (i);
1110             if (!module_sp->IsLoadedInTarget (&target))
1111             {
1112                 if (log)
1113                 {
1114                     StreamString s;
1115                     module_sp->GetDescription (&s);
1116                     log->Printf ("Unloading pre-run module: %s.", s.GetData ());
1117                 }
1118                 not_loaded_modules.Append (module_sp);
1119             }
1120         }
1121 
1122         if (not_loaded_modules.GetSize() != 0)
1123         {
1124             target.GetImages().Remove(not_loaded_modules);
1125         }
1126 
1127         return true;
1128     }
1129     else
1130         return false;
1131 }
1132 
1133 //----------------------------------------------------------------------
1134 // Read a mach_header at ADDR into HEADER, and also fill in the load
1135 // command data into LOAD_COMMAND_DATA if it is non-NULL.
1136 //
1137 // Returns true if we succeed, false if we fail for any reason.
1138 //----------------------------------------------------------------------
1139 bool
1140 DynamicLoaderMacOSXDYLD::ReadMachHeader (lldb::addr_t addr, llvm::MachO::mach_header *header, DataExtractor *load_command_data)
1141 {
1142     DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0);
1143     Error error;
1144     size_t bytes_read = m_process->ReadMemory (addr,
1145                                                header_bytes.GetBytes(),
1146                                                header_bytes.GetByteSize(),
1147                                                error);
1148     if (bytes_read == sizeof(llvm::MachO::mach_header))
1149     {
1150         lldb::offset_t offset = 0;
1151         ::memset (header, 0, sizeof(llvm::MachO::mach_header));
1152 
1153         // Get the magic byte unswapped so we can figure out what we are dealing with
1154         DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(), lldb::endian::InlHostByteOrder(), 4);
1155         header->magic = data.GetU32(&offset);
1156         lldb::addr_t load_cmd_addr = addr;
1157         data.SetByteOrder(DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic));
1158         switch (header->magic)
1159         {
1160         case llvm::MachO::HeaderMagic32:
1161         case llvm::MachO::HeaderMagic32Swapped:
1162             data.SetAddressByteSize(4);
1163             load_cmd_addr += sizeof(llvm::MachO::mach_header);
1164             break;
1165 
1166         case llvm::MachO::HeaderMagic64:
1167         case llvm::MachO::HeaderMagic64Swapped:
1168             data.SetAddressByteSize(8);
1169             load_cmd_addr += sizeof(llvm::MachO::mach_header_64);
1170             break;
1171 
1172         default:
1173             return false;
1174         }
1175 
1176         // Read the rest of dyld's mach header
1177         if (data.GetU32(&offset, &header->cputype, (sizeof(llvm::MachO::mach_header)/sizeof(uint32_t)) - 1))
1178         {
1179             if (load_command_data == NULL)
1180                 return true; // We were able to read the mach_header and weren't asked to read the load command bytes
1181 
1182             DataBufferSP load_cmd_data_sp(new DataBufferHeap(header->sizeofcmds, 0));
1183 
1184             size_t load_cmd_bytes_read = m_process->ReadMemory (load_cmd_addr,
1185                                                                 load_cmd_data_sp->GetBytes(),
1186                                                                 load_cmd_data_sp->GetByteSize(),
1187                                                                 error);
1188 
1189             if (load_cmd_bytes_read == header->sizeofcmds)
1190             {
1191                 // Set the load command data and also set the correct endian
1192                 // swap settings and the correct address size
1193                 load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds);
1194                 load_command_data->SetByteOrder(data.GetByteOrder());
1195                 load_command_data->SetAddressByteSize(data.GetAddressByteSize());
1196                 return true; // We successfully read the mach_header and the load command data
1197             }
1198 
1199             return false; // We weren't able to read the load command data
1200         }
1201     }
1202     return false; // We failed the read the mach_header
1203 }
1204 
1205 
1206 //----------------------------------------------------------------------
1207 // Parse the load commands for an image
1208 //----------------------------------------------------------------------
1209 uint32_t
1210 DynamicLoaderMacOSXDYLD::ParseLoadCommands (const DataExtractor& data, DYLDImageInfo& dylib_info, FileSpec *lc_id_dylinker)
1211 {
1212     lldb::offset_t offset = 0;
1213     uint32_t cmd_idx;
1214     Segment segment;
1215     dylib_info.Clear (true);
1216 
1217     for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++)
1218     {
1219         // Clear out any load command specific data from DYLIB_INFO since
1220         // we are about to read it.
1221 
1222         if (data.ValidOffsetForDataOfSize (offset, sizeof(llvm::MachO::load_command)))
1223         {
1224             llvm::MachO::load_command load_cmd;
1225             lldb::offset_t load_cmd_offset = offset;
1226             load_cmd.cmd = data.GetU32 (&offset);
1227             load_cmd.cmdsize = data.GetU32 (&offset);
1228             switch (load_cmd.cmd)
1229             {
1230             case llvm::MachO::LoadCommandSegment32:
1231                 {
1232                     segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
1233                     // We are putting 4 uint32_t values 4 uint64_t values so
1234                     // we have to use multiple 32 bit gets below.
1235                     segment.vmaddr = data.GetU32 (&offset);
1236                     segment.vmsize = data.GetU32 (&offset);
1237                     segment.fileoff = data.GetU32 (&offset);
1238                     segment.filesize = data.GetU32 (&offset);
1239                     // Extract maxprot, initprot, nsects and flags all at once
1240                     data.GetU32(&offset, &segment.maxprot, 4);
1241                     dylib_info.segments.push_back (segment);
1242                 }
1243                 break;
1244 
1245             case llvm::MachO::LoadCommandSegment64:
1246                 {
1247                     segment.name.SetTrimmedCStringWithLength ((const char *)data.GetData(&offset, 16), 16);
1248                     // Extract vmaddr, vmsize, fileoff, and filesize all at once
1249                     data.GetU64(&offset, &segment.vmaddr, 4);
1250                     // Extract maxprot, initprot, nsects and flags all at once
1251                     data.GetU32(&offset, &segment.maxprot, 4);
1252                     dylib_info.segments.push_back (segment);
1253                 }
1254                 break;
1255 
1256             case llvm::MachO::LoadCommandDynamicLinkerIdent:
1257                 if (lc_id_dylinker)
1258                 {
1259                     const lldb::offset_t name_offset = load_cmd_offset + data.GetU32 (&offset);
1260                     const char *path = data.PeekCStr (name_offset);
1261                     lc_id_dylinker->SetFile (path, true);
1262                 }
1263                 break;
1264 
1265             case llvm::MachO::LoadCommandUUID:
1266                 dylib_info.uuid.SetBytes(data.GetData (&offset, 16));
1267                 break;
1268 
1269             default:
1270                 break;
1271             }
1272             // Set offset to be the beginning of the next load command.
1273             offset = load_cmd_offset + load_cmd.cmdsize;
1274         }
1275     }
1276 
1277     // All sections listed in the dyld image info structure will all
1278     // either be fixed up already, or they will all be off by a single
1279     // slide amount that is determined by finding the first segment
1280     // that is at file offset zero which also has bytes (a file size
1281     // that is greater than zero) in the object file.
1282 
1283     // Determine the slide amount (if any)
1284     const size_t num_sections = dylib_info.segments.size();
1285     for (size_t i = 0; i < num_sections; ++i)
1286     {
1287         // Iterate through the object file sections to find the
1288         // first section that starts of file offset zero and that
1289         // has bytes in the file...
1290         if (dylib_info.segments[i].fileoff == 0 && dylib_info.segments[i].filesize > 0)
1291         {
1292             dylib_info.slide = dylib_info.address - dylib_info.segments[i].vmaddr;
1293             // We have found the slide amount, so we can exit
1294             // this for loop.
1295             break;
1296         }
1297     }
1298     return cmd_idx;
1299 }
1300 
1301 //----------------------------------------------------------------------
1302 // Read the mach_header and load commands for each image that the
1303 // _dyld_all_image_infos structure points to and cache the results.
1304 //----------------------------------------------------------------------
1305 
1306 void
1307 DynamicLoaderMacOSXDYLD::UpdateImageInfosHeaderAndLoadCommands(DYLDImageInfo::collection &image_infos,
1308                                                                uint32_t infos_count,
1309                                                                bool update_executable)
1310 {
1311     uint32_t exe_idx = UINT32_MAX;
1312     // Read any UUID values that we can get
1313     for (uint32_t i = 0; i < infos_count; i++)
1314     {
1315         if (!image_infos[i].UUIDValid())
1316         {
1317             DataExtractor data; // Load command data
1318             if (!ReadMachHeader (image_infos[i].address, &image_infos[i].header, &data))
1319                 continue;
1320 
1321             ParseLoadCommands (data, image_infos[i], NULL);
1322 
1323             if (image_infos[i].header.filetype == llvm::MachO::HeaderFileTypeExecutable)
1324                 exe_idx = i;
1325 
1326         }
1327     }
1328 
1329     Target &target = m_process->GetTarget();
1330 
1331     if (exe_idx < image_infos.size())
1332     {
1333         const bool can_create = true;
1334         ModuleSP exe_module_sp (FindTargetModuleForDYLDImageInfo (image_infos[exe_idx], can_create, NULL));
1335 
1336         if (exe_module_sp)
1337         {
1338             UpdateImageLoadAddress (exe_module_sp.get(), image_infos[exe_idx]);
1339 
1340             if (exe_module_sp.get() != target.GetExecutableModulePointer())
1341             {
1342                 // Don't load dependent images since we are in dyld where we will know
1343                 // and find out about all images that are loaded
1344                 const bool get_dependent_images = false;
1345                 m_process->GetTarget().SetExecutableModule (exe_module_sp,
1346                                                             get_dependent_images);
1347             }
1348         }
1349     }
1350 }
1351 
1352 //----------------------------------------------------------------------
1353 // On Mac OS X libobjc (the Objective-C runtime) has several critical dispatch
1354 // functions written in hand-written assembly, and also have hand-written unwind
1355 // information in the eh_frame section.  Normally we prefer analyzing the
1356 // assembly instructions of a curently executing frame to unwind from that frame --
1357 // but on hand-written functions this profiling can fail.  We should use the
1358 // eh_frame instructions for these functions all the time.
1359 //
1360 // As an aside, it would be better if the eh_frame entries had a flag (or were
1361 // extensible so they could have an Apple-specific flag) which indicates that
1362 // the instructions are asynchronous -- accurate at every instruction, instead
1363 // of our normal default assumption that they are not.
1364 //----------------------------------------------------------------------
1365 
1366 bool
1367 DynamicLoaderMacOSXDYLD::AlwaysRelyOnEHUnwindInfo (SymbolContext &sym_ctx)
1368 {
1369     ModuleSP module_sp;
1370     if (sym_ctx.symbol)
1371     {
1372         module_sp = sym_ctx.symbol->GetAddress().GetModule();
1373     }
1374     if (module_sp.get() == NULL && sym_ctx.function)
1375     {
1376         module_sp = sym_ctx.function->GetAddressRange().GetBaseAddress().GetModule();
1377     }
1378     if (module_sp.get() == NULL)
1379         return false;
1380 
1381     ObjCLanguageRuntime *objc_runtime = m_process->GetObjCLanguageRuntime();
1382     if (objc_runtime != NULL && objc_runtime->IsModuleObjCLibrary (module_sp))
1383     {
1384         return true;
1385     }
1386 
1387     return false;
1388 }
1389 
1390 
1391 
1392 //----------------------------------------------------------------------
1393 // Dump a Segment to the file handle provided.
1394 //----------------------------------------------------------------------
1395 void
1396 DynamicLoaderMacOSXDYLD::Segment::PutToLog (Log *log, lldb::addr_t slide) const
1397 {
1398     if (log)
1399     {
1400         if (slide == 0)
1401             log->Printf ("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")",
1402                          name.AsCString(""),
1403                          vmaddr + slide,
1404                          vmaddr + slide + vmsize);
1405         else
1406             log->Printf ("\t\t%16s [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ") slide = 0x%" PRIx64,
1407                          name.AsCString(""),
1408                          vmaddr + slide,
1409                          vmaddr + slide + vmsize,
1410                          slide);
1411     }
1412 }
1413 
1414 const DynamicLoaderMacOSXDYLD::Segment *
1415 DynamicLoaderMacOSXDYLD::DYLDImageInfo::FindSegment (const ConstString &name) const
1416 {
1417     const size_t num_segments = segments.size();
1418     for (size_t i=0; i<num_segments; ++i)
1419     {
1420         if (segments[i].name == name)
1421             return &segments[i];
1422     }
1423     return NULL;
1424 }
1425 
1426 
1427 //----------------------------------------------------------------------
1428 // Dump an image info structure to the file handle provided.
1429 //----------------------------------------------------------------------
1430 void
1431 DynamicLoaderMacOSXDYLD::DYLDImageInfo::PutToLog (Log *log) const
1432 {
1433     if (log == NULL)
1434         return;
1435     uint8_t *u = (uint8_t *)uuid.GetBytes();
1436 
1437     if (address == LLDB_INVALID_ADDRESS)
1438     {
1439         if (u)
1440         {
1441             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)",
1442                         mod_date,
1443                         u[ 0], u[ 1], u[ 2], u[ 3],
1444                         u[ 4], u[ 5], u[ 6], u[ 7],
1445                         u[ 8], u[ 9], u[10], u[11],
1446                         u[12], u[13], u[14], u[15],
1447                         file_spec.GetPath().c_str());
1448         }
1449         else
1450             log->Printf("\t                           modtime=0x%8.8" PRIx64 " path='%s' (UNLOADED)",
1451                         mod_date,
1452                         file_spec.GetPath().c_str());
1453     }
1454     else
1455     {
1456         if (u)
1457         {
1458             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'",
1459                         address,
1460                         mod_date,
1461                         u[ 0], u[ 1], u[ 2], u[ 3],
1462                         u[ 4], u[ 5], u[ 6], u[ 7],
1463                         u[ 8], u[ 9], u[10], u[11],
1464                         u[12], u[13], u[14], u[15],
1465                         file_spec.GetPath().c_str());
1466         }
1467         else
1468         {
1469             log->Printf("\taddress=0x%16.16" PRIx64 " modtime=0x%8.8" PRIx64 " path='%s'",
1470                         address,
1471                         mod_date,
1472                         file_spec.GetPath().c_str());
1473 
1474         }
1475         for (uint32_t i=0; i<segments.size(); ++i)
1476             segments[i].PutToLog(log, slide);
1477     }
1478 }
1479 
1480 //----------------------------------------------------------------------
1481 // Dump the _dyld_all_image_infos members and all current image infos
1482 // that we have parsed to the file handle provided.
1483 //----------------------------------------------------------------------
1484 void
1485 DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const
1486 {
1487     if (log == NULL)
1488         return;
1489 
1490     Mutex::Locker locker(m_mutex);
1491     log->Printf("dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8" PRIx64 ", notify=0x%8.8" PRIx64 " }",
1492                     m_dyld_all_image_infos.version,
1493                     m_dyld_all_image_infos.dylib_info_count,
1494                     (uint64_t)m_dyld_all_image_infos.dylib_info_addr,
1495                     (uint64_t)m_dyld_all_image_infos.notification);
1496     size_t i;
1497     const size_t count = m_dyld_image_infos.size();
1498     if (count > 0)
1499     {
1500         log->PutCString("Loaded:");
1501         for (i = 0; i<count; i++)
1502             m_dyld_image_infos[i].PutToLog(log);
1503     }
1504 }
1505 
1506 void
1507 DynamicLoaderMacOSXDYLD::PrivateInitialize(Process *process)
1508 {
1509     DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1510     Clear(true);
1511     m_process = process;
1512     m_process->GetTarget().GetSectionLoadList().Clear();
1513 }
1514 
1515 bool
1516 DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint ()
1517 {
1518     DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n", __FUNCTION__, StateAsCString(m_process->GetState()));
1519     if (m_break_id == LLDB_INVALID_BREAK_ID)
1520     {
1521         if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS)
1522         {
1523             Address so_addr;
1524             // Set the notification breakpoint and install a breakpoint
1525             // callback function that will get called each time the
1526             // breakpoint gets hit. We will use this to track when shared
1527             // libraries get loaded/unloaded.
1528 
1529             if (m_process->GetTarget().GetSectionLoadList().ResolveLoadAddress(m_dyld_all_image_infos.notification, so_addr))
1530             {
1531                 Breakpoint *dyld_break = m_process->GetTarget().CreateBreakpoint (so_addr, true).get();
1532                 dyld_break->SetCallback (DynamicLoaderMacOSXDYLD::NotifyBreakpointHit, this, true);
1533                 dyld_break->SetBreakpointKind ("shared-library-event");
1534                 m_break_id = dyld_break->GetID();
1535             }
1536         }
1537     }
1538     return m_break_id != LLDB_INVALID_BREAK_ID;
1539 }
1540 
1541 //----------------------------------------------------------------------
1542 // Member function that gets called when the process state changes.
1543 //----------------------------------------------------------------------
1544 void
1545 DynamicLoaderMacOSXDYLD::PrivateProcessStateChanged (Process *process, StateType state)
1546 {
1547     DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s(%s)\n", __FUNCTION__, StateAsCString(state));
1548     switch (state)
1549     {
1550     case eStateConnected:
1551     case eStateAttaching:
1552     case eStateLaunching:
1553     case eStateInvalid:
1554     case eStateUnloaded:
1555     case eStateExited:
1556     case eStateDetached:
1557         Clear(false);
1558         break;
1559 
1560     case eStateStopped:
1561         // Keep trying find dyld and set our notification breakpoint each time
1562         // we stop until we succeed
1563         if (!DidSetNotificationBreakpoint () && m_process->IsAlive())
1564         {
1565             if (NeedToLocateDYLD ())
1566                 LocateDYLD ();
1567 
1568             SetNotificationBreakpoint ();
1569         }
1570         break;
1571 
1572     case eStateRunning:
1573     case eStateStepping:
1574     case eStateCrashed:
1575     case eStateSuspended:
1576         break;
1577     }
1578 }
1579 
1580 // This bit in the n_desc field of the mach file means that this is a
1581 // stub that runs arbitrary code to determine the trampoline target.
1582 // We've established a naming convention with the CoreOS folks for the
1583 // equivalent symbols they will use for this (which the objc guys didn't follow...)
1584 // For now we'll just look for all symbols matching that naming convention...
1585 
1586 #define MACH_O_N_SYMBOL_RESOLVER 0x100
1587 
1588 ThreadPlanSP
1589 DynamicLoaderMacOSXDYLD::GetStepThroughTrampolinePlan (Thread &thread, bool stop_others)
1590 {
1591     ThreadPlanSP thread_plan_sp;
1592     StackFrame *current_frame = thread.GetStackFrameAtIndex(0).get();
1593     const SymbolContext &current_context = current_frame->GetSymbolContext(eSymbolContextSymbol);
1594     Symbol *current_symbol = current_context.symbol;
1595     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
1596 
1597     if (current_symbol != NULL)
1598     {
1599         if (current_symbol->IsTrampoline())
1600         {
1601             const ConstString &trampoline_name = current_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1602 
1603             if (trampoline_name)
1604             {
1605                 SymbolContextList target_symbols;
1606                 TargetSP target_sp (thread.CalculateTarget());
1607                 const ModuleList &images = target_sp->GetImages();
1608 
1609                 images.FindSymbolsWithNameAndType(trampoline_name, eSymbolTypeCode, target_symbols);
1610 
1611                 size_t num_original_symbols = target_symbols.GetSize();
1612                 // FIXME: The resolver symbol is only valid in object files.  In binaries it is reused for the
1613                 // shared library slot number.  So we'll have to look this up in the dyld info.
1614                 // For now, just turn this off.
1615 
1616                 // bool orig_is_resolver = (current_symbol->GetFlags() & MACH_O_N_SYMBOL_RESOLVER) == MACH_O_N_SYMBOL_RESOLVER;
1617                 // FIXME: Actually that isn't true, the N_SYMBOL_RESOLVER bit is only valid in .o files.  You can't use
1618                 // the symbol flags to tell whether something is a symbol resolver in a linked image.
1619                 bool orig_is_resolver = false;
1620 
1621                 if (num_original_symbols > 0)
1622                 {
1623                     // We found symbols that look like they are the targets to our symbol.  Now look through the
1624                     // modules containing our symbols to see if there are any for our symbol.
1625 
1626                     ModuleList modules_to_search;
1627 
1628                     for (size_t i = 0; i < num_original_symbols; i++)
1629                     {
1630                         SymbolContext sc;
1631                         target_symbols.GetContextAtIndex(i, sc);
1632 
1633                         ModuleSP module_sp (sc.symbol->CalculateSymbolContextModule());
1634                         if (module_sp)
1635                              modules_to_search.AppendIfNeeded(module_sp);
1636                     }
1637 
1638                     // If the original stub symbol is a resolver, then we don't want to break on the symbol with the
1639                     // original name, but instead on all the symbols it could resolve to since otherwise we would stop
1640                     // in the middle of the resolution...
1641                     // Note that the stub is not of the resolver type it will point to the equivalent symbol,
1642                     // not the original name, so in that case we don't need to do anything.
1643 
1644                     if (orig_is_resolver)
1645                     {
1646                         target_symbols.Clear();
1647 
1648                         FindEquivalentSymbols (current_symbol, modules_to_search, target_symbols);
1649                     }
1650 
1651                     // FIXME - Make the Run to Address take multiple addresses, and
1652                     // run to any of them.
1653                     uint32_t num_symbols = target_symbols.GetSize();
1654                     if (num_symbols > 0)
1655                     {
1656                         std::vector<lldb::addr_t>  addresses;
1657                         addresses.resize (num_symbols);
1658                         for (uint32_t i = 0; i < num_symbols; i++)
1659                         {
1660                             SymbolContext context;
1661                             AddressRange addr_range;
1662                             if (target_symbols.GetContextAtIndex(i, context))
1663                             {
1664                                 context.GetAddressRange (eSymbolContextEverything, 0, false, addr_range);
1665                                 lldb::addr_t load_addr = addr_range.GetBaseAddress().GetLoadAddress(target_sp.get());
1666                                 addresses[i] = load_addr;
1667                             }
1668                         }
1669                         if (addresses.size() > 0)
1670                             thread_plan_sp.reset (new ThreadPlanRunToAddress (thread, addresses, stop_others));
1671                         else
1672                         {
1673                             if (log)
1674                                 log->Printf ("Couldn't resolve the symbol contexts.");
1675                         }
1676                     }
1677                     else
1678                     {
1679                         if (log)
1680                         {
1681                             log->Printf ("Found a resolver stub for: \"%s\" but could not find any symbols it resolves to.",
1682                                          trampoline_name.AsCString());
1683                         }
1684                     }
1685                 }
1686                 else
1687                 {
1688                     if (log)
1689                     {
1690                         log->Printf ("Could not find symbol for trampoline target: \"%s\"", trampoline_name.AsCString());
1691                     }
1692                 }
1693             }
1694         }
1695     }
1696     else
1697     {
1698         if (log)
1699             log->Printf ("Could not find symbol for step through.");
1700     }
1701 
1702     return thread_plan_sp;
1703 }
1704 
1705 size_t
1706 DynamicLoaderMacOSXDYLD::FindEquivalentSymbols (lldb_private::Symbol *original_symbol,
1707                                                lldb_private::ModuleList &images,
1708                                                lldb_private::SymbolContextList &equivalent_symbols)
1709 {
1710     const ConstString &trampoline_name = original_symbol->GetMangled().GetName(Mangled::ePreferMangled);
1711     if (!trampoline_name)
1712         return 0;
1713 
1714     size_t initial_size = equivalent_symbols.GetSize();
1715 
1716     static const char *resolver_name_regex = "(_gc|_non_gc|\\$[A-Z0-9]+)$";
1717     std::string equivalent_regex_buf("^");
1718     equivalent_regex_buf.append (trampoline_name.GetCString());
1719     equivalent_regex_buf.append (resolver_name_regex);
1720 
1721     RegularExpression equivalent_name_regex (equivalent_regex_buf.c_str());
1722     const bool append = true;
1723     images.FindSymbolsMatchingRegExAndType (equivalent_name_regex, eSymbolTypeCode, equivalent_symbols, append);
1724 
1725     return equivalent_symbols.GetSize() - initial_size;
1726 }
1727 
1728 Error
1729 DynamicLoaderMacOSXDYLD::CanLoadImage ()
1730 {
1731     Error error;
1732     // In order for us to tell if we can load a shared library we verify that
1733     // the dylib_info_addr isn't zero (which means no shared libraries have
1734     // been set yet, or dyld is currently mucking with the shared library list).
1735     if (ReadAllImageInfosStructure ())
1736     {
1737         // TODO: also check the _dyld_global_lock_held variable in libSystem.B.dylib?
1738         // TODO: check the malloc lock?
1739         // TODO: check the objective C lock?
1740         if (m_dyld_all_image_infos.dylib_info_addr != 0)
1741             return error; // Success
1742     }
1743 
1744     error.SetErrorString("unsafe to load or unload shared libraries");
1745     return error;
1746 }
1747 
1748 void
1749 DynamicLoaderMacOSXDYLD::Initialize()
1750 {
1751     PluginManager::RegisterPlugin (GetPluginNameStatic(),
1752                                    GetPluginDescriptionStatic(),
1753                                    CreateInstance);
1754 }
1755 
1756 void
1757 DynamicLoaderMacOSXDYLD::Terminate()
1758 {
1759     PluginManager::UnregisterPlugin (CreateInstance);
1760 }
1761 
1762 
1763 const char *
1764 DynamicLoaderMacOSXDYLD::GetPluginNameStatic()
1765 {
1766     return "dynamic-loader.macosx-dyld";
1767 }
1768 
1769 const char *
1770 DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic()
1771 {
1772     return "Dynamic loader plug-in that watches for shared library loads/unloads in MacOSX user processes.";
1773 }
1774 
1775 
1776 //------------------------------------------------------------------
1777 // PluginInterface protocol
1778 //------------------------------------------------------------------
1779 const char *
1780 DynamicLoaderMacOSXDYLD::GetPluginName()
1781 {
1782     return "DynamicLoaderMacOSXDYLD";
1783 }
1784 
1785 const char *
1786 DynamicLoaderMacOSXDYLD::GetShortPluginName()
1787 {
1788     return GetPluginNameStatic();
1789 }
1790 
1791 uint32_t
1792 DynamicLoaderMacOSXDYLD::GetPluginVersion()
1793 {
1794     return 1;
1795 }
1796 
1797 uint32_t
1798 DynamicLoaderMacOSXDYLD::AddrByteSize()
1799 {
1800     switch (m_dyld.header.magic)
1801     {
1802         case llvm::MachO::HeaderMagic32:
1803         case llvm::MachO::HeaderMagic32Swapped:
1804             return 4;
1805 
1806         case llvm::MachO::HeaderMagic64:
1807         case llvm::MachO::HeaderMagic64Swapped:
1808             return 8;
1809 
1810         default:
1811             break;
1812     }
1813     return 0;
1814 }
1815 
1816 lldb::ByteOrder
1817 DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic (uint32_t magic)
1818 {
1819     switch (magic)
1820     {
1821         case llvm::MachO::HeaderMagic32:
1822         case llvm::MachO::HeaderMagic64:
1823             return lldb::endian::InlHostByteOrder();
1824 
1825         case llvm::MachO::HeaderMagic32Swapped:
1826         case llvm::MachO::HeaderMagic64Swapped:
1827             if (lldb::endian::InlHostByteOrder() == lldb::eByteOrderBig)
1828                 return lldb::eByteOrderLittle;
1829             else
1830                 return lldb::eByteOrderBig;
1831 
1832         default:
1833             break;
1834     }
1835     return lldb::eByteOrderInvalid;
1836 }
1837 
1838 lldb::ByteOrder
1839 DynamicLoaderMacOSXDYLD::DYLDImageInfo::GetByteOrder()
1840 {
1841     return DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header.magic);
1842 }
1843 
1844