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