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 #include "lldb/Breakpoint/StoppointCallbackContext.h"
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/ModuleSpec.h"
14 #include "lldb/Core/PluginManager.h"
15 #include "lldb/Core/Section.h"
16 #include "lldb/Symbol/ClangASTContext.h"
17 #include "lldb/Symbol/Function.h"
18 #include "lldb/Symbol/ObjectFile.h"
19 #include "lldb/Target/ABI.h"
20 #include "lldb/Target/ObjCLanguageRuntime.h"
21 #include "lldb/Target/RegisterContext.h"
22 #include "lldb/Target/StackFrame.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/Thread.h"
25 #include "lldb/Target/ThreadPlanRunToAddress.h"
26 #include "lldb/Utility/DataBuffer.h"
27 #include "lldb/Utility/DataBufferHeap.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/State.h"
30 
31 #include "DynamicLoaderDarwin.h"
32 #include "DynamicLoaderMacOSXDYLD.h"
33 
34 //#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN
35 #ifdef ENABLE_DEBUG_PRINTF
36 #include <stdio.h>
37 #define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)
38 #else
39 #define DEBUG_PRINTF(fmt, ...)
40 #endif
41 
42 #ifndef __APPLE__
43 #include "Utility/UuidCompatibility.h"
44 #else
45 #include <uuid/uuid.h>
46 #endif
47 
48 using namespace lldb;
49 using namespace lldb_private;
50 
51 //----------------------------------------------------------------------
52 // Create an instance of this class. This function is filled into the plugin
53 // info class that gets handed out by the plugin factory and allows the lldb to
54 // instantiate an instance of this class.
55 //----------------------------------------------------------------------
56 DynamicLoader *DynamicLoaderMacOSXDYLD::CreateInstance(Process *process,
57                                                        bool force) {
58   bool create = force;
59   if (!create) {
60     create = true;
61     Module *exe_module = process->GetTarget().GetExecutableModulePointer();
62     if (exe_module) {
63       ObjectFile *object_file = exe_module->GetObjectFile();
64       if (object_file) {
65         create = (object_file->GetStrata() == ObjectFile::eStrataUser);
66       }
67     }
68 
69     if (create) {
70       const llvm::Triple &triple_ref =
71           process->GetTarget().GetArchitecture().GetTriple();
72       switch (triple_ref.getOS()) {
73       case llvm::Triple::Darwin:
74       case llvm::Triple::MacOSX:
75       case llvm::Triple::IOS:
76       case llvm::Triple::TvOS:
77       case llvm::Triple::WatchOS:
78       // NEED_BRIDGEOS_TRIPLE case llvm::Triple::BridgeOS:
79         create = triple_ref.getVendor() == llvm::Triple::Apple;
80         break;
81       default:
82         create = false;
83         break;
84       }
85     }
86   }
87 
88   if (UseDYLDSPI(process) == true) {
89     create = false;
90   }
91 
92   if (create)
93     return new DynamicLoaderMacOSXDYLD(process);
94   return NULL;
95 }
96 
97 //----------------------------------------------------------------------
98 // Constructor
99 //----------------------------------------------------------------------
100 DynamicLoaderMacOSXDYLD::DynamicLoaderMacOSXDYLD(Process *process)
101     : DynamicLoaderDarwin(process),
102       m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS),
103       m_dyld_all_image_infos(), m_dyld_all_image_infos_stop_id(UINT32_MAX),
104       m_break_id(LLDB_INVALID_BREAK_ID), m_mutex(),
105       m_process_image_addr_is_all_images_infos(false) {}
106 
107 //----------------------------------------------------------------------
108 // Destructor
109 //----------------------------------------------------------------------
110 DynamicLoaderMacOSXDYLD::~DynamicLoaderMacOSXDYLD() {
111   if (LLDB_BREAK_ID_IS_VALID(m_break_id))
112     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
113 }
114 
115 bool DynamicLoaderMacOSXDYLD::ProcessDidExec() {
116   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
117   bool did_exec = false;
118   if (m_process) {
119     // If we are stopped after an exec, we will have only one thread...
120     if (m_process->GetThreadList().GetSize() == 1) {
121       // We know if a process has exec'ed if our "m_dyld_all_image_infos_addr"
122       // value differs from the Process' image info address. When a process
123       // execs itself it might cause a change if ASLR is enabled.
124       const addr_t shlib_addr = m_process->GetImageInfoAddress();
125       if (m_process_image_addr_is_all_images_infos == true &&
126           shlib_addr != m_dyld_all_image_infos_addr) {
127         // The image info address from the process is the
128         // 'dyld_all_image_infos' address and it has changed.
129         did_exec = true;
130       } else if (m_process_image_addr_is_all_images_infos == false &&
131                  shlib_addr == m_dyld.address) {
132         // The image info address from the process is the mach_header address
133         // for dyld and it has changed.
134         did_exec = true;
135       } else {
136         // ASLR might be disabled and dyld could have ended up in the same
137         // location. We should try and detect if we are stopped at
138         // '_dyld_start'
139         ThreadSP thread_sp(m_process->GetThreadList().GetThreadAtIndex(0));
140         if (thread_sp) {
141           lldb::StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
142           if (frame_sp) {
143             const Symbol *symbol =
144                 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol;
145             if (symbol) {
146               if (symbol->GetName() == ConstString("_dyld_start"))
147                 did_exec = true;
148             }
149           }
150         }
151       }
152 
153       if (did_exec) {
154         m_libpthread_module_wp.reset();
155         m_pthread_getspecific_addr.Clear();
156       }
157     }
158   }
159   return did_exec;
160 }
161 
162 //----------------------------------------------------------------------
163 // Clear out the state of this class.
164 //----------------------------------------------------------------------
165 void DynamicLoaderMacOSXDYLD::DoClear() {
166   std::lock_guard<std::recursive_mutex> guard(m_mutex);
167 
168   if (LLDB_BREAK_ID_IS_VALID(m_break_id))
169     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
170 
171   m_dyld_all_image_infos_addr = LLDB_INVALID_ADDRESS;
172   m_dyld_all_image_infos.Clear();
173   m_break_id = LLDB_INVALID_BREAK_ID;
174 }
175 
176 //----------------------------------------------------------------------
177 // Check if we have found DYLD yet
178 //----------------------------------------------------------------------
179 bool DynamicLoaderMacOSXDYLD::DidSetNotificationBreakpoint() {
180   return LLDB_BREAK_ID_IS_VALID(m_break_id);
181 }
182 
183 void DynamicLoaderMacOSXDYLD::ClearNotificationBreakpoint() {
184   if (LLDB_BREAK_ID_IS_VALID(m_break_id)) {
185     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
186   }
187 }
188 
189 //----------------------------------------------------------------------
190 // Try and figure out where dyld is by first asking the Process if it knows
191 // (which currently calls down in the lldb::Process to get the DYLD info
192 // (available on SnowLeopard only). If that fails, then check in the default
193 // addresses.
194 //----------------------------------------------------------------------
195 void DynamicLoaderMacOSXDYLD::DoInitialImageFetch() {
196   if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS) {
197     // Check the image info addr as it might point to the mach header for dyld,
198     // or it might point to the dyld_all_image_infos struct
199     const addr_t shlib_addr = m_process->GetImageInfoAddress();
200     if (shlib_addr != LLDB_INVALID_ADDRESS) {
201       ByteOrder byte_order =
202           m_process->GetTarget().GetArchitecture().GetByteOrder();
203       uint8_t buf[4];
204       DataExtractor data(buf, sizeof(buf), byte_order, 4);
205       Status error;
206       if (m_process->ReadMemory(shlib_addr, buf, 4, error) == 4) {
207         lldb::offset_t offset = 0;
208         uint32_t magic = data.GetU32(&offset);
209         switch (magic) {
210         case llvm::MachO::MH_MAGIC:
211         case llvm::MachO::MH_MAGIC_64:
212         case llvm::MachO::MH_CIGAM:
213         case llvm::MachO::MH_CIGAM_64:
214           m_process_image_addr_is_all_images_infos = false;
215           ReadDYLDInfoFromMemoryAndSetNotificationCallback(shlib_addr);
216           return;
217 
218         default:
219           break;
220         }
221       }
222       // Maybe it points to the all image infos?
223       m_dyld_all_image_infos_addr = shlib_addr;
224       m_process_image_addr_is_all_images_infos = true;
225     }
226   }
227 
228   if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) {
229     if (ReadAllImageInfosStructure()) {
230       if (m_dyld_all_image_infos.dyldImageLoadAddress != LLDB_INVALID_ADDRESS)
231         ReadDYLDInfoFromMemoryAndSetNotificationCallback(
232             m_dyld_all_image_infos.dyldImageLoadAddress);
233       else
234         ReadDYLDInfoFromMemoryAndSetNotificationCallback(
235             m_dyld_all_image_infos_addr & 0xfffffffffff00000ull);
236       return;
237     }
238   }
239 
240   // Check some default values
241   Module *executable = m_process->GetTarget().GetExecutableModulePointer();
242 
243   if (executable) {
244     const ArchSpec &exe_arch = executable->GetArchitecture();
245     if (exe_arch.GetAddressByteSize() == 8) {
246       ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x7fff5fc00000ull);
247     } else if (exe_arch.GetMachine() == llvm::Triple::arm ||
248                exe_arch.GetMachine() == llvm::Triple::thumb ||
249                exe_arch.GetMachine() == llvm::Triple::aarch64) {
250       ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x2fe00000);
251     } else {
252       ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x8fe00000);
253     }
254   }
255   return;
256 }
257 
258 //----------------------------------------------------------------------
259 // Assume that dyld is in memory at ADDR and try to parse it's load commands
260 //----------------------------------------------------------------------
261 bool DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(
262     lldb::addr_t addr) {
263   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
264   DataExtractor data; // Load command data
265   static ConstString g_dyld_all_image_infos("dyld_all_image_infos");
266   if (ReadMachHeader(addr, &m_dyld.header, &data)) {
267     if (m_dyld.header.filetype == llvm::MachO::MH_DYLINKER) {
268       m_dyld.address = addr;
269       ModuleSP dyld_module_sp;
270       if (ParseLoadCommands(data, m_dyld, &m_dyld.file_spec)) {
271         if (m_dyld.file_spec) {
272           UpdateDYLDImageInfoFromNewImageInfo(m_dyld);
273         }
274       }
275       dyld_module_sp = GetDYLDModule();
276 
277       Target &target = m_process->GetTarget();
278 
279       if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS &&
280           dyld_module_sp.get()) {
281         const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType(
282             g_dyld_all_image_infos, eSymbolTypeData);
283         if (symbol)
284           m_dyld_all_image_infos_addr = symbol->GetLoadAddress(&target);
285       }
286 
287       // Update all image infos
288       InitializeFromAllImageInfos();
289 
290       // If we didn't have an executable before, but now we do, then the dyld
291       // module shared pointer might be unique and we may need to add it again
292       // (since Target::SetExecutableModule() will clear the images). So append
293       // the dyld module back to the list if it is
294       /// unique!
295       if (dyld_module_sp) {
296         target.GetImages().AppendIfNeeded(dyld_module_sp);
297 
298         // At this point we should have read in dyld's module, and so we should
299         // set breakpoints in it:
300         ModuleList modules;
301         modules.Append(dyld_module_sp);
302         target.ModulesDidLoad(modules);
303         SetDYLDModule(dyld_module_sp);
304       }
305 
306       return true;
307     }
308   }
309   return false;
310 }
311 
312 bool DynamicLoaderMacOSXDYLD::NeedToDoInitialImageFetch() {
313   return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS;
314 }
315 
316 //----------------------------------------------------------------------
317 // Static callback function that gets called when our DYLD notification
318 // breakpoint gets hit. We update all of our image infos and then let our super
319 // class DynamicLoader class decide if we should stop or not (based on global
320 // preference).
321 //----------------------------------------------------------------------
322 bool DynamicLoaderMacOSXDYLD::NotifyBreakpointHit(
323     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
324     lldb::user_id_t break_loc_id) {
325   // Let the event know that the images have changed
326   // DYLD passes three arguments to the notification breakpoint.
327   // Arg1: enum dyld_image_mode mode - 0 = adding, 1 = removing Arg2: uint32_t
328   // infoCount        - Number of shared libraries added Arg3: dyld_image_info
329   // info[]    - Array of structs of the form:
330   //                                     const struct mach_header
331   //                                     *imageLoadAddress
332   //                                     const char               *imageFilePath
333   //                                     uintptr_t imageFileModDate (a time_t)
334 
335   DynamicLoaderMacOSXDYLD *dyld_instance = (DynamicLoaderMacOSXDYLD *)baton;
336 
337   // First step is to see if we've already initialized the all image infos.  If
338   // we haven't then this function will do so and return true.  In the course
339   // of initializing the all_image_infos it will read the complete current
340   // state, so we don't need to figure out what has changed from the data
341   // passed in to us.
342 
343   ExecutionContext exe_ctx(context->exe_ctx_ref);
344   Process *process = exe_ctx.GetProcessPtr();
345 
346   // This is a sanity check just in case this dyld_instance is an old dyld
347   // plugin's breakpoint still lying around.
348   if (process != dyld_instance->m_process)
349     return false;
350 
351   if (dyld_instance->InitializeFromAllImageInfos())
352     return dyld_instance->GetStopWhenImagesChange();
353 
354   const lldb::ABISP &abi = process->GetABI();
355   if (abi) {
356     // Build up the value array to store the three arguments given above, then
357     // get the values from the ABI:
358 
359     ClangASTContext *clang_ast_context =
360         process->GetTarget().GetScratchClangASTContext();
361     ValueList argument_values;
362     Value input_value;
363 
364     CompilerType clang_void_ptr_type =
365         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
366     CompilerType clang_uint32_type =
367         clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
368             lldb::eEncodingUint, 32);
369     input_value.SetValueType(Value::eValueTypeScalar);
370     input_value.SetCompilerType(clang_uint32_type);
371     //        input_value.SetContext (Value::eContextTypeClangType,
372     //        clang_uint32_type);
373     argument_values.PushValue(input_value);
374     argument_values.PushValue(input_value);
375     input_value.SetCompilerType(clang_void_ptr_type);
376     //        input_value.SetContext (Value::eContextTypeClangType,
377     //        clang_void_ptr_type);
378     argument_values.PushValue(input_value);
379 
380     if (abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values)) {
381       uint32_t dyld_mode =
382           argument_values.GetValueAtIndex(0)->GetScalar().UInt(-1);
383       if (dyld_mode != static_cast<uint32_t>(-1)) {
384         // Okay the mode was right, now get the number of elements, and the
385         // array of new elements...
386         uint32_t image_infos_count =
387             argument_values.GetValueAtIndex(1)->GetScalar().UInt(-1);
388         if (image_infos_count != static_cast<uint32_t>(-1)) {
389           // Got the number added, now go through the array of added elements,
390           // putting out the mach header address, and adding the image. Note,
391           // I'm not putting in logging here, since the AddModules &
392           // RemoveModules functions do all the logging internally.
393 
394           lldb::addr_t image_infos_addr =
395               argument_values.GetValueAtIndex(2)->GetScalar().ULongLong();
396           if (dyld_mode == 0) {
397             // This is add:
398             dyld_instance->AddModulesUsingImageInfosAddress(image_infos_addr,
399                                                             image_infos_count);
400           } else {
401             // This is remove:
402             dyld_instance->RemoveModulesUsingImageInfosAddress(
403                 image_infos_addr, image_infos_count);
404           }
405         }
406       }
407     }
408   } else {
409     process->GetTarget().GetDebugger().GetAsyncErrorStream()->Printf(
410         "No ABI plugin located for triple %s -- shared libraries will not be "
411         "registered!\n",
412         process->GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
413   }
414 
415   // Return true to stop the target, false to just let the target run
416   return dyld_instance->GetStopWhenImagesChange();
417 }
418 
419 bool DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure() {
420   std::lock_guard<std::recursive_mutex> guard(m_mutex);
421 
422   // the all image infos is already valid for this process stop ID
423   if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id)
424     return true;
425 
426   m_dyld_all_image_infos.Clear();
427   if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) {
428     ByteOrder byte_order =
429         m_process->GetTarget().GetArchitecture().GetByteOrder();
430     uint32_t addr_size =
431         m_process->GetTarget().GetArchitecture().GetAddressByteSize();
432 
433     uint8_t buf[256];
434     DataExtractor data(buf, sizeof(buf), byte_order, addr_size);
435     lldb::offset_t offset = 0;
436 
437     const size_t count_v2 = sizeof(uint32_t) + // version
438                             sizeof(uint32_t) + // infoArrayCount
439                             addr_size +        // infoArray
440                             addr_size +        // notification
441                             addr_size + // processDetachedFromSharedRegion +
442                                         // libSystemInitialized + pad
443                             addr_size;  // dyldImageLoadAddress
444     const size_t count_v11 = count_v2 + addr_size +  // jitInfo
445                              addr_size +             // dyldVersion
446                              addr_size +             // errorMessage
447                              addr_size +             // terminationFlags
448                              addr_size +             // coreSymbolicationShmPage
449                              addr_size +             // systemOrderFlag
450                              addr_size +             // uuidArrayCount
451                              addr_size +             // uuidArray
452                              addr_size +             // dyldAllImageInfosAddress
453                              addr_size +             // initialImageCount
454                              addr_size +             // errorKind
455                              addr_size +             // errorClientOfDylibPath
456                              addr_size +             // errorTargetDylibPath
457                              addr_size;              // errorSymbol
458     const size_t count_v13 = count_v11 + addr_size + // sharedCacheSlide
459                              sizeof(uuid_t);         // sharedCacheUUID
460     UNUSED_IF_ASSERT_DISABLED(count_v13);
461     assert(sizeof(buf) >= count_v13);
462 
463     Status error;
464     if (m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, 4, error) ==
465         4) {
466       m_dyld_all_image_infos.version = data.GetU32(&offset);
467       // If anything in the high byte is set, we probably got the byte order
468       // incorrect (the process might not have it set correctly yet due to
469       // attaching to a program without a specified file).
470       if (m_dyld_all_image_infos.version & 0xff000000) {
471         // We have guessed the wrong byte order. Swap it and try reading the
472         // version again.
473         if (byte_order == eByteOrderLittle)
474           byte_order = eByteOrderBig;
475         else
476           byte_order = eByteOrderLittle;
477 
478         data.SetByteOrder(byte_order);
479         offset = 0;
480         m_dyld_all_image_infos.version = data.GetU32(&offset);
481       }
482     } else {
483       return false;
484     }
485 
486     const size_t count =
487         (m_dyld_all_image_infos.version >= 11) ? count_v11 : count_v2;
488 
489     const size_t bytes_read =
490         m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, count, error);
491     if (bytes_read == count) {
492       offset = 0;
493       m_dyld_all_image_infos.version = data.GetU32(&offset);
494       m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset);
495       m_dyld_all_image_infos.dylib_info_addr = data.GetPointer(&offset);
496       m_dyld_all_image_infos.notification = data.GetPointer(&offset);
497       m_dyld_all_image_infos.processDetachedFromSharedRegion =
498           data.GetU8(&offset);
499       m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset);
500       // Adjust for padding.
501       offset += addr_size - 2;
502       m_dyld_all_image_infos.dyldImageLoadAddress = data.GetPointer(&offset);
503       if (m_dyld_all_image_infos.version >= 11) {
504         offset += addr_size * 8;
505         uint64_t dyld_all_image_infos_addr = data.GetPointer(&offset);
506 
507         // When we started, we were given the actual address of the
508         // all_image_infos struct (probably via TASK_DYLD_INFO) in memory -
509         // this address is stored in m_dyld_all_image_infos_addr and is the
510         // most accurate address we have.
511 
512         // We read the dyld_all_image_infos struct from memory; it contains its
513         // own address. If the address in the struct does not match the actual
514         // address, the dyld we're looking at has been loaded at a different
515         // location (slid) from where it intended to load.  The addresses in
516         // the dyld_all_image_infos struct are the original, non-slid
517         // addresses, and need to be adjusted.  Most importantly the address of
518         // dyld and the notification address need to be adjusted.
519 
520         if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr) {
521           uint64_t image_infos_offset =
522               dyld_all_image_infos_addr -
523               m_dyld_all_image_infos.dyldImageLoadAddress;
524           uint64_t notification_offset =
525               m_dyld_all_image_infos.notification -
526               m_dyld_all_image_infos.dyldImageLoadAddress;
527           m_dyld_all_image_infos.dyldImageLoadAddress =
528               m_dyld_all_image_infos_addr - image_infos_offset;
529           m_dyld_all_image_infos.notification =
530               m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset;
531         }
532       }
533       m_dyld_all_image_infos_stop_id = m_process->GetStopID();
534       return true;
535     }
536   }
537   return false;
538 }
539 
540 bool DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfosAddress(
541     lldb::addr_t image_infos_addr, uint32_t image_infos_count) {
542   ImageInfo::collection image_infos;
543   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
544   if (log)
545     log->Printf("Adding %d modules.\n", image_infos_count);
546 
547   std::lock_guard<std::recursive_mutex> guard(m_mutex);
548   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
549   if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
550     return true;
551 
552   StructuredData::ObjectSP image_infos_json_sp =
553       m_process->GetLoadedDynamicLibrariesInfos(image_infos_addr,
554                                                 image_infos_count);
555   if (image_infos_json_sp.get() && image_infos_json_sp->GetAsDictionary() &&
556       image_infos_json_sp->GetAsDictionary()->HasKey("images") &&
557       image_infos_json_sp->GetAsDictionary()
558           ->GetValueForKey("images")
559           ->GetAsArray() &&
560       image_infos_json_sp->GetAsDictionary()
561               ->GetValueForKey("images")
562               ->GetAsArray()
563               ->GetSize() == image_infos_count) {
564     bool return_value = false;
565     if (JSONImageInformationIntoImageInfo(image_infos_json_sp, image_infos)) {
566       UpdateSpecialBinariesFromNewImageInfos(image_infos);
567       return_value = AddModulesUsingImageInfos(image_infos);
568     }
569     m_dyld_image_infos_stop_id = m_process->GetStopID();
570     return return_value;
571   }
572 
573   if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos))
574     return false;
575 
576   UpdateImageInfosHeaderAndLoadCommands(image_infos, image_infos_count, false);
577   bool return_value = AddModulesUsingImageInfos(image_infos);
578   m_dyld_image_infos_stop_id = m_process->GetStopID();
579   return return_value;
580 }
581 
582 bool DynamicLoaderMacOSXDYLD::RemoveModulesUsingImageInfosAddress(
583     lldb::addr_t image_infos_addr, uint32_t image_infos_count) {
584   ImageInfo::collection image_infos;
585   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
586 
587   std::lock_guard<std::recursive_mutex> guard(m_mutex);
588   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
589   if (m_process->GetStopID() == m_dyld_image_infos_stop_id)
590     return true;
591 
592   // First read in the image_infos for the removed modules, and their headers &
593   // load commands.
594   if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos)) {
595     if (log)
596       log->PutCString("Failed reading image infos array.");
597     return false;
598   }
599 
600   if (log)
601     log->Printf("Removing %d modules.", image_infos_count);
602 
603   ModuleList unloaded_module_list;
604   for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {
605     if (log) {
606       log->Printf("Removing module at address=0x%16.16" PRIx64 ".",
607                   image_infos[idx].address);
608       image_infos[idx].PutToLog(log);
609     }
610 
611     // Remove this image_infos from the m_all_image_infos.  We do the
612     // comparison by address rather than by file spec because we can have many
613     // modules with the same "file spec" in the case that they are modules
614     // loaded from memory.
615     //
616     // Also copy over the uuid from the old entry to the removed entry so we
617     // can use it to lookup the module in the module list.
618 
619     ImageInfo::collection::iterator pos, end = m_dyld_image_infos.end();
620     for (pos = m_dyld_image_infos.begin(); pos != end; pos++) {
621       if (image_infos[idx].address == (*pos).address) {
622         image_infos[idx].uuid = (*pos).uuid;
623 
624         // Add the module from this image_info to the "unloaded_module_list".
625         // We'll remove them all at one go later on.
626 
627         ModuleSP unload_image_module_sp(
628             FindTargetModuleForImageInfo(image_infos[idx], false, NULL));
629         if (unload_image_module_sp.get()) {
630           // When we unload, be sure to use the image info from the old list,
631           // since that has sections correctly filled in.
632           UnloadModuleSections(unload_image_module_sp.get(), *pos);
633           unloaded_module_list.AppendIfNeeded(unload_image_module_sp);
634         } else {
635           if (log) {
636             log->Printf("Could not find module for unloading info entry:");
637             image_infos[idx].PutToLog(log);
638           }
639         }
640 
641         // Then remove it from the m_dyld_image_infos:
642 
643         m_dyld_image_infos.erase(pos);
644         break;
645       }
646     }
647 
648     if (pos == end) {
649       if (log) {
650         log->Printf("Could not find image_info entry for unloading image:");
651         image_infos[idx].PutToLog(log);
652       }
653     }
654   }
655   if (unloaded_module_list.GetSize() > 0) {
656     if (log) {
657       log->PutCString("Unloaded:");
658       unloaded_module_list.LogUUIDAndPaths(
659           log, "DynamicLoaderMacOSXDYLD::ModulesDidUnload");
660     }
661     m_process->GetTarget().GetImages().Remove(unloaded_module_list);
662   }
663   m_dyld_image_infos_stop_id = m_process->GetStopID();
664   return true;
665 }
666 
667 bool DynamicLoaderMacOSXDYLD::ReadImageInfos(
668     lldb::addr_t image_infos_addr, uint32_t image_infos_count,
669     ImageInfo::collection &image_infos) {
670   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
671   const ByteOrder endian = GetByteOrderFromMagic(m_dyld.header.magic);
672   const uint32_t addr_size = m_dyld.GetAddressByteSize();
673 
674   image_infos.resize(image_infos_count);
675   const size_t count = image_infos.size() * 3 * addr_size;
676   DataBufferHeap info_data(count, 0);
677   Status error;
678   const size_t bytes_read = m_process->ReadMemory(
679       image_infos_addr, info_data.GetBytes(), info_data.GetByteSize(), error);
680   if (bytes_read == count) {
681     lldb::offset_t info_data_offset = 0;
682     DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(),
683                                 endian, addr_size);
684     for (size_t i = 0;
685          i < image_infos.size() && info_data_ref.ValidOffset(info_data_offset);
686          i++) {
687       image_infos[i].address = info_data_ref.GetPointer(&info_data_offset);
688       lldb::addr_t path_addr = info_data_ref.GetPointer(&info_data_offset);
689       image_infos[i].mod_date = info_data_ref.GetPointer(&info_data_offset);
690 
691       char raw_path[PATH_MAX];
692       m_process->ReadCStringFromMemory(path_addr, raw_path, sizeof(raw_path),
693                                        error);
694       // don't resolve the path
695       if (error.Success()) {
696         image_infos[i].file_spec.SetFile(raw_path, FileSpec::Style::native);
697       }
698     }
699     return true;
700   } else {
701     return false;
702   }
703 }
704 
705 //----------------------------------------------------------------------
706 // If we have found where the "_dyld_all_image_infos" lives in memory, read the
707 // current info from it, and then update all image load addresses (or lack
708 // thereof).  Only do this if this is the first time we're reading the dyld
709 // infos.  Return true if we actually read anything, and false otherwise.
710 //----------------------------------------------------------------------
711 bool DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos() {
712   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
713 
714   std::lock_guard<std::recursive_mutex> guard(m_mutex);
715   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
716   if (m_process->GetStopID() == m_dyld_image_infos_stop_id ||
717       m_dyld_image_infos.size() != 0)
718     return false;
719 
720   if (ReadAllImageInfosStructure()) {
721     // Nothing to load or unload?
722     if (m_dyld_all_image_infos.dylib_info_count == 0)
723       return true;
724 
725     if (m_dyld_all_image_infos.dylib_info_addr == 0) {
726       // DYLD is updating the images now.  So we should say we have no images,
727       // and then we'll
728       // figure it out when we hit the added breakpoint.
729       return false;
730     } else {
731       if (!AddModulesUsingImageInfosAddress(
732               m_dyld_all_image_infos.dylib_info_addr,
733               m_dyld_all_image_infos.dylib_info_count)) {
734         DEBUG_PRINTF("%s", "unable to read all data for all_dylib_infos.");
735         m_dyld_image_infos.clear();
736       }
737     }
738 
739     // Now we have one more bit of business.  If there is a library left in the
740     // images for our target that doesn't have a load address, then it must be
741     // something that we were expecting to load (for instance we read a load
742     // command for it) but it didn't in fact load - probably because
743     // DYLD_*_PATH pointed to an equivalent version.  We don't want it to stay
744     // in the target's module list or it will confuse us, so unload it here.
745     Target &target = m_process->GetTarget();
746     const ModuleList &target_modules = target.GetImages();
747     ModuleList not_loaded_modules;
748     std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
749 
750     size_t num_modules = target_modules.GetSize();
751     for (size_t i = 0; i < num_modules; i++) {
752       ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
753       if (!module_sp->IsLoadedInTarget(&target)) {
754         if (log) {
755           StreamString s;
756           module_sp->GetDescription(&s);
757           log->Printf("Unloading pre-run module: %s.", s.GetData());
758         }
759         not_loaded_modules.Append(module_sp);
760       }
761     }
762 
763     if (not_loaded_modules.GetSize() != 0) {
764       target.GetImages().Remove(not_loaded_modules);
765     }
766 
767     return true;
768   } else
769     return false;
770 }
771 
772 //----------------------------------------------------------------------
773 // Read a mach_header at ADDR into HEADER, and also fill in the load command
774 // data into LOAD_COMMAND_DATA if it is non-NULL.
775 //
776 // Returns true if we succeed, false if we fail for any reason.
777 //----------------------------------------------------------------------
778 bool DynamicLoaderMacOSXDYLD::ReadMachHeader(lldb::addr_t addr,
779                                              llvm::MachO::mach_header *header,
780                                              DataExtractor *load_command_data) {
781   DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0);
782   Status error;
783   size_t bytes_read = m_process->ReadMemory(addr, header_bytes.GetBytes(),
784                                             header_bytes.GetByteSize(), error);
785   if (bytes_read == sizeof(llvm::MachO::mach_header)) {
786     lldb::offset_t offset = 0;
787     ::memset(header, 0, sizeof(llvm::MachO::mach_header));
788 
789     // Get the magic byte unswapped so we can figure out what we are dealing
790     // with
791     DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(),
792                        endian::InlHostByteOrder(), 4);
793     header->magic = data.GetU32(&offset);
794     lldb::addr_t load_cmd_addr = addr;
795     data.SetByteOrder(
796         DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic));
797     switch (header->magic) {
798     case llvm::MachO::MH_MAGIC:
799     case llvm::MachO::MH_CIGAM:
800       data.SetAddressByteSize(4);
801       load_cmd_addr += sizeof(llvm::MachO::mach_header);
802       break;
803 
804     case llvm::MachO::MH_MAGIC_64:
805     case llvm::MachO::MH_CIGAM_64:
806       data.SetAddressByteSize(8);
807       load_cmd_addr += sizeof(llvm::MachO::mach_header_64);
808       break;
809 
810     default:
811       return false;
812     }
813 
814     // Read the rest of dyld's mach header
815     if (data.GetU32(&offset, &header->cputype,
816                     (sizeof(llvm::MachO::mach_header) / sizeof(uint32_t)) -
817                         1)) {
818       if (load_command_data == NULL)
819         return true; // We were able to read the mach_header and weren't asked
820                      // to read the load command bytes
821 
822       DataBufferSP load_cmd_data_sp(new DataBufferHeap(header->sizeofcmds, 0));
823 
824       size_t load_cmd_bytes_read =
825           m_process->ReadMemory(load_cmd_addr, load_cmd_data_sp->GetBytes(),
826                                 load_cmd_data_sp->GetByteSize(), error);
827 
828       if (load_cmd_bytes_read == header->sizeofcmds) {
829         // Set the load command data and also set the correct endian swap
830         // settings and the correct address size
831         load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds);
832         load_command_data->SetByteOrder(data.GetByteOrder());
833         load_command_data->SetAddressByteSize(data.GetAddressByteSize());
834         return true; // We successfully read the mach_header and the load
835                      // command data
836       }
837 
838       return false; // We weren't able to read the load command data
839     }
840   }
841   return false; // We failed the read the mach_header
842 }
843 
844 //----------------------------------------------------------------------
845 // Parse the load commands for an image
846 //----------------------------------------------------------------------
847 uint32_t DynamicLoaderMacOSXDYLD::ParseLoadCommands(const DataExtractor &data,
848                                                     ImageInfo &dylib_info,
849                                                     FileSpec *lc_id_dylinker) {
850   lldb::offset_t offset = 0;
851   uint32_t cmd_idx;
852   Segment segment;
853   dylib_info.Clear(true);
854 
855   for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++) {
856     // Clear out any load command specific data from DYLIB_INFO since we are
857     // about to read it.
858 
859     if (data.ValidOffsetForDataOfSize(offset,
860                                       sizeof(llvm::MachO::load_command))) {
861       llvm::MachO::load_command load_cmd;
862       lldb::offset_t load_cmd_offset = offset;
863       load_cmd.cmd = data.GetU32(&offset);
864       load_cmd.cmdsize = data.GetU32(&offset);
865       switch (load_cmd.cmd) {
866       case llvm::MachO::LC_SEGMENT: {
867         segment.name.SetTrimmedCStringWithLength(
868             (const char *)data.GetData(&offset, 16), 16);
869         // We are putting 4 uint32_t values 4 uint64_t values so we have to use
870         // multiple 32 bit gets below.
871         segment.vmaddr = data.GetU32(&offset);
872         segment.vmsize = data.GetU32(&offset);
873         segment.fileoff = data.GetU32(&offset);
874         segment.filesize = data.GetU32(&offset);
875         // Extract maxprot, initprot, nsects and flags all at once
876         data.GetU32(&offset, &segment.maxprot, 4);
877         dylib_info.segments.push_back(segment);
878       } break;
879 
880       case llvm::MachO::LC_SEGMENT_64: {
881         segment.name.SetTrimmedCStringWithLength(
882             (const char *)data.GetData(&offset, 16), 16);
883         // Extract vmaddr, vmsize, fileoff, and filesize all at once
884         data.GetU64(&offset, &segment.vmaddr, 4);
885         // Extract maxprot, initprot, nsects and flags all at once
886         data.GetU32(&offset, &segment.maxprot, 4);
887         dylib_info.segments.push_back(segment);
888       } break;
889 
890       case llvm::MachO::LC_ID_DYLINKER:
891         if (lc_id_dylinker) {
892           const lldb::offset_t name_offset =
893               load_cmd_offset + data.GetU32(&offset);
894           const char *path = data.PeekCStr(name_offset);
895           lc_id_dylinker->SetFile(path, FileSpec::Style::native);
896           FileSystem::Instance().Resolve(*lc_id_dylinker);
897         }
898         break;
899 
900       case llvm::MachO::LC_UUID:
901         dylib_info.uuid = UUID::fromOptionalData(data.GetData(&offset, 16), 16);
902         break;
903 
904       default:
905         break;
906       }
907       // Set offset to be the beginning of the next load command.
908       offset = load_cmd_offset + load_cmd.cmdsize;
909     }
910   }
911 
912   // All sections listed in the dyld image info structure will all either be
913   // fixed up already, or they will all be off by a single slide amount that is
914   // determined by finding the first segment that is at file offset zero which
915   // also has bytes (a file size that is greater than zero) in the object file.
916 
917   // Determine the slide amount (if any)
918   const size_t num_sections = dylib_info.segments.size();
919   for (size_t i = 0; i < num_sections; ++i) {
920     // Iterate through the object file sections to find the first section that
921     // starts of file offset zero and that has bytes in the file...
922     if ((dylib_info.segments[i].fileoff == 0 &&
923          dylib_info.segments[i].filesize > 0) ||
924         (dylib_info.segments[i].name == ConstString("__TEXT"))) {
925       dylib_info.slide = dylib_info.address - dylib_info.segments[i].vmaddr;
926       // We have found the slide amount, so we can exit this for loop.
927       break;
928     }
929   }
930   return cmd_idx;
931 }
932 
933 //----------------------------------------------------------------------
934 // Read the mach_header and load commands for each image that the
935 // _dyld_all_image_infos structure points to and cache the results.
936 //----------------------------------------------------------------------
937 
938 void DynamicLoaderMacOSXDYLD::UpdateImageInfosHeaderAndLoadCommands(
939     ImageInfo::collection &image_infos, uint32_t infos_count,
940     bool update_executable) {
941   uint32_t exe_idx = UINT32_MAX;
942   // Read any UUID values that we can get
943   for (uint32_t i = 0; i < infos_count; i++) {
944     if (!image_infos[i].UUIDValid()) {
945       DataExtractor data; // Load command data
946       if (!ReadMachHeader(image_infos[i].address, &image_infos[i].header,
947                           &data))
948         continue;
949 
950       ParseLoadCommands(data, image_infos[i], NULL);
951 
952       if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE)
953         exe_idx = i;
954     }
955   }
956 
957   Target &target = m_process->GetTarget();
958 
959   if (exe_idx < image_infos.size()) {
960     const bool can_create = true;
961     ModuleSP exe_module_sp(
962         FindTargetModuleForImageInfo(image_infos[exe_idx], can_create, NULL));
963 
964     if (exe_module_sp) {
965       UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
966 
967       if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
968         // Don't load dependent images since we are in dyld where we will know
969         // and find out about all images that are loaded. Also when setting the
970         // executable module, it will clear the targets module list, and if we
971         // have an in memory dyld module, it will get removed from the list so
972         // we will need to add it back after setting the executable module, so
973         // we first try and see if we already have a weak pointer to the dyld
974         // module, make it into a shared pointer, then add the executable, then
975         // re-add it back to make sure it is always in the list.
976         ModuleSP dyld_module_sp(GetDYLDModule());
977 
978         m_process->GetTarget().SetExecutableModule(exe_module_sp,
979                                                    eLoadDependentsNo);
980 
981         if (dyld_module_sp) {
982           if (target.GetImages().AppendIfNeeded(dyld_module_sp)) {
983             std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
984 
985             // Also add it to the section list.
986             UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
987           }
988         }
989       }
990     }
991   }
992 }
993 
994 //----------------------------------------------------------------------
995 // Dump the _dyld_all_image_infos members and all current image infos that we
996 // have parsed to the file handle provided.
997 //----------------------------------------------------------------------
998 void DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const {
999   if (log == NULL)
1000     return;
1001 
1002   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1003   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1004   log->Printf(
1005       "dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8" PRIx64
1006       ", notify=0x%8.8" PRIx64 " }",
1007       m_dyld_all_image_infos.version, m_dyld_all_image_infos.dylib_info_count,
1008       (uint64_t)m_dyld_all_image_infos.dylib_info_addr,
1009       (uint64_t)m_dyld_all_image_infos.notification);
1010   size_t i;
1011   const size_t count = m_dyld_image_infos.size();
1012   if (count > 0) {
1013     log->PutCString("Loaded:");
1014     for (i = 0; i < count; i++)
1015       m_dyld_image_infos[i].PutToLog(log);
1016   }
1017 }
1018 
1019 bool DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint() {
1020   DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n",
1021                __FUNCTION__, StateAsCString(m_process->GetState()));
1022   if (m_break_id == LLDB_INVALID_BREAK_ID) {
1023     if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS) {
1024       Address so_addr;
1025       // Set the notification breakpoint and install a breakpoint callback
1026       // function that will get called each time the breakpoint gets hit. We
1027       // will use this to track when shared libraries get loaded/unloaded.
1028       bool resolved = m_process->GetTarget().ResolveLoadAddress(
1029           m_dyld_all_image_infos.notification, so_addr);
1030       if (!resolved) {
1031         ModuleSP dyld_module_sp = GetDYLDModule();
1032         if (dyld_module_sp) {
1033           std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1034 
1035           UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
1036           resolved = m_process->GetTarget().ResolveLoadAddress(
1037               m_dyld_all_image_infos.notification, so_addr);
1038         }
1039       }
1040 
1041       if (resolved) {
1042         Breakpoint *dyld_break =
1043             m_process->GetTarget().CreateBreakpoint(so_addr, true, false).get();
1044         dyld_break->SetCallback(DynamicLoaderMacOSXDYLD::NotifyBreakpointHit,
1045                                 this, true);
1046         dyld_break->SetBreakpointKind("shared-library-event");
1047         m_break_id = dyld_break->GetID();
1048       }
1049     }
1050   }
1051   return m_break_id != LLDB_INVALID_BREAK_ID;
1052 }
1053 
1054 Status DynamicLoaderMacOSXDYLD::CanLoadImage() {
1055   Status error;
1056   // In order for us to tell if we can load a shared library we verify that the
1057   // dylib_info_addr isn't zero (which means no shared libraries have been set
1058   // yet, or dyld is currently mucking with the shared library list).
1059   if (ReadAllImageInfosStructure()) {
1060     // TODO: also check the _dyld_global_lock_held variable in
1061     // libSystem.B.dylib?
1062     // TODO: check the malloc lock?
1063     // TODO: check the objective C lock?
1064     if (m_dyld_all_image_infos.dylib_info_addr != 0)
1065       return error; // Success
1066   }
1067 
1068   error.SetErrorString("unsafe to load or unload shared libraries");
1069   return error;
1070 }
1071 
1072 bool DynamicLoaderMacOSXDYLD::GetSharedCacheInformation(
1073     lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,
1074     LazyBool &private_shared_cache) {
1075   base_address = LLDB_INVALID_ADDRESS;
1076   uuid.Clear();
1077   using_shared_cache = eLazyBoolCalculate;
1078   private_shared_cache = eLazyBoolCalculate;
1079 
1080   if (m_process) {
1081     addr_t all_image_infos = m_process->GetImageInfoAddress();
1082 
1083     // The address returned by GetImageInfoAddress may be the address of dyld
1084     // (don't want) or it may be the address of the dyld_all_image_infos
1085     // structure (want). The first four bytes will be either the version field
1086     // (all_image_infos) or a Mach-O file magic constant. Version 13 and higher
1087     // of dyld_all_image_infos is required to get the sharedCacheUUID field.
1088 
1089     Status err;
1090     uint32_t version_or_magic =
1091         m_process->ReadUnsignedIntegerFromMemory(all_image_infos, 4, -1, err);
1092     if (version_or_magic != static_cast<uint32_t>(-1) &&
1093         version_or_magic != llvm::MachO::MH_MAGIC &&
1094         version_or_magic != llvm::MachO::MH_CIGAM &&
1095         version_or_magic != llvm::MachO::MH_MAGIC_64 &&
1096         version_or_magic != llvm::MachO::MH_CIGAM_64 &&
1097         version_or_magic >= 13) {
1098       addr_t sharedCacheUUID_address = LLDB_INVALID_ADDRESS;
1099       int wordsize = m_process->GetAddressByteSize();
1100       if (wordsize == 8) {
1101         sharedCacheUUID_address =
1102             all_image_infos + 160; // sharedCacheUUID <mach-o/dyld_images.h>
1103       }
1104       if (wordsize == 4) {
1105         sharedCacheUUID_address =
1106             all_image_infos + 84; // sharedCacheUUID <mach-o/dyld_images.h>
1107       }
1108       if (sharedCacheUUID_address != LLDB_INVALID_ADDRESS) {
1109         uuid_t shared_cache_uuid;
1110         if (m_process->ReadMemory(sharedCacheUUID_address, shared_cache_uuid,
1111                                   sizeof(uuid_t), err) == sizeof(uuid_t)) {
1112           uuid = UUID::fromOptionalData(shared_cache_uuid, 16);
1113           if (uuid.IsValid()) {
1114             using_shared_cache = eLazyBoolYes;
1115           }
1116         }
1117 
1118         if (version_or_magic >= 15) {
1119           // The sharedCacheBaseAddress field is the next one in the
1120           // dyld_all_image_infos struct.
1121           addr_t sharedCacheBaseAddr_address = sharedCacheUUID_address + 16;
1122           Status error;
1123           base_address = m_process->ReadUnsignedIntegerFromMemory(
1124               sharedCacheBaseAddr_address, wordsize, LLDB_INVALID_ADDRESS,
1125               error);
1126           if (error.Fail())
1127             base_address = LLDB_INVALID_ADDRESS;
1128         }
1129 
1130         return true;
1131       }
1132 
1133       //
1134       // add
1135       // NB: sharedCacheBaseAddress is the next field in dyld_all_image_infos
1136       // after
1137       // sharedCacheUUID -- that is, 16 bytes after it, if we wanted to fetch
1138       // it.
1139     }
1140   }
1141   return false;
1142 }
1143 
1144 void DynamicLoaderMacOSXDYLD::Initialize() {
1145   PluginManager::RegisterPlugin(GetPluginNameStatic(),
1146                                 GetPluginDescriptionStatic(), CreateInstance);
1147 }
1148 
1149 void DynamicLoaderMacOSXDYLD::Terminate() {
1150   PluginManager::UnregisterPlugin(CreateInstance);
1151 }
1152 
1153 lldb_private::ConstString DynamicLoaderMacOSXDYLD::GetPluginNameStatic() {
1154   static ConstString g_name("macosx-dyld");
1155   return g_name;
1156 }
1157 
1158 const char *DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic() {
1159   return "Dynamic loader plug-in that watches for shared library loads/unloads "
1160          "in MacOSX user processes.";
1161 }
1162 
1163 //------------------------------------------------------------------
1164 // PluginInterface protocol
1165 //------------------------------------------------------------------
1166 lldb_private::ConstString DynamicLoaderMacOSXDYLD::GetPluginName() {
1167   return GetPluginNameStatic();
1168 }
1169 
1170 uint32_t DynamicLoaderMacOSXDYLD::GetPluginVersion() { return 1; }
1171 
1172 uint32_t DynamicLoaderMacOSXDYLD::AddrByteSize() {
1173   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1174 
1175   switch (m_dyld.header.magic) {
1176   case llvm::MachO::MH_MAGIC:
1177   case llvm::MachO::MH_CIGAM:
1178     return 4;
1179 
1180   case llvm::MachO::MH_MAGIC_64:
1181   case llvm::MachO::MH_CIGAM_64:
1182     return 8;
1183 
1184   default:
1185     break;
1186   }
1187   return 0;
1188 }
1189 
1190 lldb::ByteOrder DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(uint32_t magic) {
1191   switch (magic) {
1192   case llvm::MachO::MH_MAGIC:
1193   case llvm::MachO::MH_MAGIC_64:
1194     return endian::InlHostByteOrder();
1195 
1196   case llvm::MachO::MH_CIGAM:
1197   case llvm::MachO::MH_CIGAM_64:
1198     if (endian::InlHostByteOrder() == lldb::eByteOrderBig)
1199       return lldb::eByteOrderLittle;
1200     else
1201       return lldb::eByteOrderBig;
1202 
1203   default:
1204     break;
1205   }
1206   return lldb::eByteOrderInvalid;
1207 }
1208