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         const bool resolve_path = false;
697         image_infos[i].file_spec.SetFile(raw_path, resolve_path,
698                                          FileSpec::Style::native);
699       }
700     }
701     return true;
702   } else {
703     return false;
704   }
705 }
706 
707 //----------------------------------------------------------------------
708 // If we have found where the "_dyld_all_image_infos" lives in memory, read the
709 // current info from it, and then update all image load addresses (or lack
710 // thereof).  Only do this if this is the first time we're reading the dyld
711 // infos.  Return true if we actually read anything, and false otherwise.
712 //----------------------------------------------------------------------
713 bool DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos() {
714   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
715 
716   std::lock_guard<std::recursive_mutex> guard(m_mutex);
717   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
718   if (m_process->GetStopID() == m_dyld_image_infos_stop_id ||
719       m_dyld_image_infos.size() != 0)
720     return false;
721 
722   if (ReadAllImageInfosStructure()) {
723     // Nothing to load or unload?
724     if (m_dyld_all_image_infos.dylib_info_count == 0)
725       return true;
726 
727     if (m_dyld_all_image_infos.dylib_info_addr == 0) {
728       // DYLD is updating the images now.  So we should say we have no images,
729       // and then we'll
730       // figure it out when we hit the added breakpoint.
731       return false;
732     } else {
733       if (!AddModulesUsingImageInfosAddress(
734               m_dyld_all_image_infos.dylib_info_addr,
735               m_dyld_all_image_infos.dylib_info_count)) {
736         DEBUG_PRINTF("%s", "unable to read all data for all_dylib_infos.");
737         m_dyld_image_infos.clear();
738       }
739     }
740 
741     // Now we have one more bit of business.  If there is a library left in the
742     // images for our target that doesn't have a load address, then it must be
743     // something that we were expecting to load (for instance we read a load
744     // command for it) but it didn't in fact load - probably because
745     // DYLD_*_PATH pointed to an equivalent version.  We don't want it to stay
746     // in the target's module list or it will confuse us, so unload it here.
747     Target &target = m_process->GetTarget();
748     const ModuleList &target_modules = target.GetImages();
749     ModuleList not_loaded_modules;
750     std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
751 
752     size_t num_modules = target_modules.GetSize();
753     for (size_t i = 0; i < num_modules; i++) {
754       ModuleSP module_sp = target_modules.GetModuleAtIndexUnlocked(i);
755       if (!module_sp->IsLoadedInTarget(&target)) {
756         if (log) {
757           StreamString s;
758           module_sp->GetDescription(&s);
759           log->Printf("Unloading pre-run module: %s.", s.GetData());
760         }
761         not_loaded_modules.Append(module_sp);
762       }
763     }
764 
765     if (not_loaded_modules.GetSize() != 0) {
766       target.GetImages().Remove(not_loaded_modules);
767     }
768 
769     return true;
770   } else
771     return false;
772 }
773 
774 //----------------------------------------------------------------------
775 // Read a mach_header at ADDR into HEADER, and also fill in the load command
776 // data into LOAD_COMMAND_DATA if it is non-NULL.
777 //
778 // Returns true if we succeed, false if we fail for any reason.
779 //----------------------------------------------------------------------
780 bool DynamicLoaderMacOSXDYLD::ReadMachHeader(lldb::addr_t addr,
781                                              llvm::MachO::mach_header *header,
782                                              DataExtractor *load_command_data) {
783   DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0);
784   Status error;
785   size_t bytes_read = m_process->ReadMemory(addr, header_bytes.GetBytes(),
786                                             header_bytes.GetByteSize(), error);
787   if (bytes_read == sizeof(llvm::MachO::mach_header)) {
788     lldb::offset_t offset = 0;
789     ::memset(header, 0, sizeof(llvm::MachO::mach_header));
790 
791     // Get the magic byte unswapped so we can figure out what we are dealing
792     // with
793     DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(),
794                        endian::InlHostByteOrder(), 4);
795     header->magic = data.GetU32(&offset);
796     lldb::addr_t load_cmd_addr = addr;
797     data.SetByteOrder(
798         DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic));
799     switch (header->magic) {
800     case llvm::MachO::MH_MAGIC:
801     case llvm::MachO::MH_CIGAM:
802       data.SetAddressByteSize(4);
803       load_cmd_addr += sizeof(llvm::MachO::mach_header);
804       break;
805 
806     case llvm::MachO::MH_MAGIC_64:
807     case llvm::MachO::MH_CIGAM_64:
808       data.SetAddressByteSize(8);
809       load_cmd_addr += sizeof(llvm::MachO::mach_header_64);
810       break;
811 
812     default:
813       return false;
814     }
815 
816     // Read the rest of dyld's mach header
817     if (data.GetU32(&offset, &header->cputype,
818                     (sizeof(llvm::MachO::mach_header) / sizeof(uint32_t)) -
819                         1)) {
820       if (load_command_data == NULL)
821         return true; // We were able to read the mach_header and weren't asked
822                      // to read the load command bytes
823 
824       DataBufferSP load_cmd_data_sp(new DataBufferHeap(header->sizeofcmds, 0));
825 
826       size_t load_cmd_bytes_read =
827           m_process->ReadMemory(load_cmd_addr, load_cmd_data_sp->GetBytes(),
828                                 load_cmd_data_sp->GetByteSize(), error);
829 
830       if (load_cmd_bytes_read == header->sizeofcmds) {
831         // Set the load command data and also set the correct endian swap
832         // settings and the correct address size
833         load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds);
834         load_command_data->SetByteOrder(data.GetByteOrder());
835         load_command_data->SetAddressByteSize(data.GetAddressByteSize());
836         return true; // We successfully read the mach_header and the load
837                      // command data
838       }
839 
840       return false; // We weren't able to read the load command data
841     }
842   }
843   return false; // We failed the read the mach_header
844 }
845 
846 //----------------------------------------------------------------------
847 // Parse the load commands for an image
848 //----------------------------------------------------------------------
849 uint32_t DynamicLoaderMacOSXDYLD::ParseLoadCommands(const DataExtractor &data,
850                                                     ImageInfo &dylib_info,
851                                                     FileSpec *lc_id_dylinker) {
852   lldb::offset_t offset = 0;
853   uint32_t cmd_idx;
854   Segment segment;
855   dylib_info.Clear(true);
856 
857   for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++) {
858     // Clear out any load command specific data from DYLIB_INFO since we are
859     // about to read it.
860 
861     if (data.ValidOffsetForDataOfSize(offset,
862                                       sizeof(llvm::MachO::load_command))) {
863       llvm::MachO::load_command load_cmd;
864       lldb::offset_t load_cmd_offset = offset;
865       load_cmd.cmd = data.GetU32(&offset);
866       load_cmd.cmdsize = data.GetU32(&offset);
867       switch (load_cmd.cmd) {
868       case llvm::MachO::LC_SEGMENT: {
869         segment.name.SetTrimmedCStringWithLength(
870             (const char *)data.GetData(&offset, 16), 16);
871         // We are putting 4 uint32_t values 4 uint64_t values so we have to use
872         // multiple 32 bit gets below.
873         segment.vmaddr = data.GetU32(&offset);
874         segment.vmsize = data.GetU32(&offset);
875         segment.fileoff = data.GetU32(&offset);
876         segment.filesize = data.GetU32(&offset);
877         // Extract maxprot, initprot, nsects and flags all at once
878         data.GetU32(&offset, &segment.maxprot, 4);
879         dylib_info.segments.push_back(segment);
880       } break;
881 
882       case llvm::MachO::LC_SEGMENT_64: {
883         segment.name.SetTrimmedCStringWithLength(
884             (const char *)data.GetData(&offset, 16), 16);
885         // Extract vmaddr, vmsize, fileoff, and filesize all at once
886         data.GetU64(&offset, &segment.vmaddr, 4);
887         // Extract maxprot, initprot, nsects and flags all at once
888         data.GetU32(&offset, &segment.maxprot, 4);
889         dylib_info.segments.push_back(segment);
890       } break;
891 
892       case llvm::MachO::LC_ID_DYLINKER:
893         if (lc_id_dylinker) {
894           const lldb::offset_t name_offset =
895               load_cmd_offset + data.GetU32(&offset);
896           const char *path = data.PeekCStr(name_offset);
897           lc_id_dylinker->SetFile(path, true, FileSpec::Style::native);
898         }
899         break;
900 
901       case llvm::MachO::LC_UUID:
902         dylib_info.uuid = UUID::fromOptionalData(data.GetData(&offset, 16), 16);
903         break;
904 
905       default:
906         break;
907       }
908       // Set offset to be the beginning of the next load command.
909       offset = load_cmd_offset + load_cmd.cmdsize;
910     }
911   }
912 
913   // All sections listed in the dyld image info structure will all either be
914   // fixed up already, or they will all be off by a single slide amount that is
915   // determined by finding the first segment that is at file offset zero which
916   // also has bytes (a file size that is greater than zero) in the object file.
917 
918   // Determine the slide amount (if any)
919   const size_t num_sections = dylib_info.segments.size();
920   for (size_t i = 0; i < num_sections; ++i) {
921     // Iterate through the object file sections to find the first section that
922     // starts of file offset zero and that has bytes in the file...
923     if ((dylib_info.segments[i].fileoff == 0 &&
924          dylib_info.segments[i].filesize > 0) ||
925         (dylib_info.segments[i].name == ConstString("__TEXT"))) {
926       dylib_info.slide = dylib_info.address - dylib_info.segments[i].vmaddr;
927       // We have found the slide amount, so we can exit this for loop.
928       break;
929     }
930   }
931   return cmd_idx;
932 }
933 
934 //----------------------------------------------------------------------
935 // Read the mach_header and load commands for each image that the
936 // _dyld_all_image_infos structure points to and cache the results.
937 //----------------------------------------------------------------------
938 
939 void DynamicLoaderMacOSXDYLD::UpdateImageInfosHeaderAndLoadCommands(
940     ImageInfo::collection &image_infos, uint32_t infos_count,
941     bool update_executable) {
942   uint32_t exe_idx = UINT32_MAX;
943   // Read any UUID values that we can get
944   for (uint32_t i = 0; i < infos_count; i++) {
945     if (!image_infos[i].UUIDValid()) {
946       DataExtractor data; // Load command data
947       if (!ReadMachHeader(image_infos[i].address, &image_infos[i].header,
948                           &data))
949         continue;
950 
951       ParseLoadCommands(data, image_infos[i], NULL);
952 
953       if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE)
954         exe_idx = i;
955     }
956   }
957 
958   Target &target = m_process->GetTarget();
959 
960   if (exe_idx < image_infos.size()) {
961     const bool can_create = true;
962     ModuleSP exe_module_sp(
963         FindTargetModuleForImageInfo(image_infos[exe_idx], can_create, NULL));
964 
965     if (exe_module_sp) {
966       UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);
967 
968       if (exe_module_sp.get() != target.GetExecutableModulePointer()) {
969         // Don't load dependent images since we are in dyld where we will know
970         // and find out about all images that are loaded. Also when setting the
971         // executable module, it will clear the targets module list, and if we
972         // have an in memory dyld module, it will get removed from the list so
973         // we will need to add it back after setting the executable module, so
974         // we first try and see if we already have a weak pointer to the dyld
975         // module, make it into a shared pointer, then add the executable, then
976         // re-add it back to make sure it is always in the list.
977         ModuleSP dyld_module_sp(GetDYLDModule());
978 
979         m_process->GetTarget().SetExecutableModule(exe_module_sp,
980                                                    eLoadDependentsNo);
981 
982         if (dyld_module_sp) {
983           if (target.GetImages().AppendIfNeeded(dyld_module_sp)) {
984             std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
985 
986             // Also add it to the section list.
987             UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
988           }
989         }
990       }
991     }
992   }
993 }
994 
995 //----------------------------------------------------------------------
996 // Dump the _dyld_all_image_infos members and all current image infos that we
997 // have parsed to the file handle provided.
998 //----------------------------------------------------------------------
999 void DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const {
1000   if (log == NULL)
1001     return;
1002 
1003   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1004   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1005   log->Printf(
1006       "dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8" PRIx64
1007       ", notify=0x%8.8" PRIx64 " }",
1008       m_dyld_all_image_infos.version, m_dyld_all_image_infos.dylib_info_count,
1009       (uint64_t)m_dyld_all_image_infos.dylib_info_addr,
1010       (uint64_t)m_dyld_all_image_infos.notification);
1011   size_t i;
1012   const size_t count = m_dyld_image_infos.size();
1013   if (count > 0) {
1014     log->PutCString("Loaded:");
1015     for (i = 0; i < count; i++)
1016       m_dyld_image_infos[i].PutToLog(log);
1017   }
1018 }
1019 
1020 bool DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint() {
1021   DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n",
1022                __FUNCTION__, StateAsCString(m_process->GetState()));
1023   if (m_break_id == LLDB_INVALID_BREAK_ID) {
1024     if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS) {
1025       Address so_addr;
1026       // Set the notification breakpoint and install a breakpoint callback
1027       // function that will get called each time the breakpoint gets hit. We
1028       // will use this to track when shared libraries get loaded/unloaded.
1029       bool resolved = m_process->GetTarget().ResolveLoadAddress(
1030           m_dyld_all_image_infos.notification, so_addr);
1031       if (!resolved) {
1032         ModuleSP dyld_module_sp = GetDYLDModule();
1033         if (dyld_module_sp) {
1034           std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1035 
1036           UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);
1037           resolved = m_process->GetTarget().ResolveLoadAddress(
1038               m_dyld_all_image_infos.notification, so_addr);
1039         }
1040       }
1041 
1042       if (resolved) {
1043         Breakpoint *dyld_break =
1044             m_process->GetTarget().CreateBreakpoint(so_addr, true, false).get();
1045         dyld_break->SetCallback(DynamicLoaderMacOSXDYLD::NotifyBreakpointHit,
1046                                 this, true);
1047         dyld_break->SetBreakpointKind("shared-library-event");
1048         m_break_id = dyld_break->GetID();
1049       }
1050     }
1051   }
1052   return m_break_id != LLDB_INVALID_BREAK_ID;
1053 }
1054 
1055 Status DynamicLoaderMacOSXDYLD::CanLoadImage() {
1056   Status error;
1057   // In order for us to tell if we can load a shared library we verify that the
1058   // dylib_info_addr isn't zero (which means no shared libraries have been set
1059   // yet, or dyld is currently mucking with the shared library list).
1060   if (ReadAllImageInfosStructure()) {
1061     // TODO: also check the _dyld_global_lock_held variable in
1062     // libSystem.B.dylib?
1063     // TODO: check the malloc lock?
1064     // TODO: check the objective C lock?
1065     if (m_dyld_all_image_infos.dylib_info_addr != 0)
1066       return error; // Success
1067   }
1068 
1069   error.SetErrorString("unsafe to load or unload shared libraries");
1070   return error;
1071 }
1072 
1073 bool DynamicLoaderMacOSXDYLD::GetSharedCacheInformation(
1074     lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,
1075     LazyBool &private_shared_cache) {
1076   base_address = LLDB_INVALID_ADDRESS;
1077   uuid.Clear();
1078   using_shared_cache = eLazyBoolCalculate;
1079   private_shared_cache = eLazyBoolCalculate;
1080 
1081   if (m_process) {
1082     addr_t all_image_infos = m_process->GetImageInfoAddress();
1083 
1084     // The address returned by GetImageInfoAddress may be the address of dyld
1085     // (don't want) or it may be the address of the dyld_all_image_infos
1086     // structure (want). The first four bytes will be either the version field
1087     // (all_image_infos) or a Mach-O file magic constant. Version 13 and higher
1088     // of dyld_all_image_infos is required to get the sharedCacheUUID field.
1089 
1090     Status err;
1091     uint32_t version_or_magic =
1092         m_process->ReadUnsignedIntegerFromMemory(all_image_infos, 4, -1, err);
1093     if (version_or_magic != static_cast<uint32_t>(-1) &&
1094         version_or_magic != llvm::MachO::MH_MAGIC &&
1095         version_or_magic != llvm::MachO::MH_CIGAM &&
1096         version_or_magic != llvm::MachO::MH_MAGIC_64 &&
1097         version_or_magic != llvm::MachO::MH_CIGAM_64 &&
1098         version_or_magic >= 13) {
1099       addr_t sharedCacheUUID_address = LLDB_INVALID_ADDRESS;
1100       int wordsize = m_process->GetAddressByteSize();
1101       if (wordsize == 8) {
1102         sharedCacheUUID_address =
1103             all_image_infos + 160; // sharedCacheUUID <mach-o/dyld_images.h>
1104       }
1105       if (wordsize == 4) {
1106         sharedCacheUUID_address =
1107             all_image_infos + 84; // sharedCacheUUID <mach-o/dyld_images.h>
1108       }
1109       if (sharedCacheUUID_address != LLDB_INVALID_ADDRESS) {
1110         uuid_t shared_cache_uuid;
1111         if (m_process->ReadMemory(sharedCacheUUID_address, shared_cache_uuid,
1112                                   sizeof(uuid_t), err) == sizeof(uuid_t)) {
1113           uuid = UUID::fromOptionalData(shared_cache_uuid, 16);
1114           if (uuid.IsValid()) {
1115             using_shared_cache = eLazyBoolYes;
1116           }
1117         }
1118 
1119         if (version_or_magic >= 15) {
1120           // The sharedCacheBaseAddress field is the next one in the
1121           // dyld_all_image_infos struct.
1122           addr_t sharedCacheBaseAddr_address = sharedCacheUUID_address + 16;
1123           Status error;
1124           base_address = m_process->ReadUnsignedIntegerFromMemory(
1125               sharedCacheBaseAddr_address, wordsize, LLDB_INVALID_ADDRESS,
1126               error);
1127           if (error.Fail())
1128             base_address = LLDB_INVALID_ADDRESS;
1129         }
1130 
1131         return true;
1132       }
1133 
1134       //
1135       // add
1136       // NB: sharedCacheBaseAddress is the next field in dyld_all_image_infos
1137       // after
1138       // sharedCacheUUID -- that is, 16 bytes after it, if we wanted to fetch
1139       // it.
1140     }
1141   }
1142   return false;
1143 }
1144 
1145 void DynamicLoaderMacOSXDYLD::Initialize() {
1146   PluginManager::RegisterPlugin(GetPluginNameStatic(),
1147                                 GetPluginDescriptionStatic(), CreateInstance);
1148 }
1149 
1150 void DynamicLoaderMacOSXDYLD::Terminate() {
1151   PluginManager::UnregisterPlugin(CreateInstance);
1152 }
1153 
1154 lldb_private::ConstString DynamicLoaderMacOSXDYLD::GetPluginNameStatic() {
1155   static ConstString g_name("macosx-dyld");
1156   return g_name;
1157 }
1158 
1159 const char *DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic() {
1160   return "Dynamic loader plug-in that watches for shared library loads/unloads "
1161          "in MacOSX user processes.";
1162 }
1163 
1164 //------------------------------------------------------------------
1165 // PluginInterface protocol
1166 //------------------------------------------------------------------
1167 lldb_private::ConstString DynamicLoaderMacOSXDYLD::GetPluginName() {
1168   return GetPluginNameStatic();
1169 }
1170 
1171 uint32_t DynamicLoaderMacOSXDYLD::GetPluginVersion() { return 1; }
1172 
1173 uint32_t DynamicLoaderMacOSXDYLD::AddrByteSize() {
1174   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
1175 
1176   switch (m_dyld.header.magic) {
1177   case llvm::MachO::MH_MAGIC:
1178   case llvm::MachO::MH_CIGAM:
1179     return 4;
1180 
1181   case llvm::MachO::MH_MAGIC_64:
1182   case llvm::MachO::MH_CIGAM_64:
1183     return 8;
1184 
1185   default:
1186     break;
1187   }
1188   return 0;
1189 }
1190 
1191 lldb::ByteOrder DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(uint32_t magic) {
1192   switch (magic) {
1193   case llvm::MachO::MH_MAGIC:
1194   case llvm::MachO::MH_MAGIC_64:
1195     return endian::InlHostByteOrder();
1196 
1197   case llvm::MachO::MH_CIGAM:
1198   case llvm::MachO::MH_CIGAM_64:
1199     if (endian::InlHostByteOrder() == lldb::eByteOrderBig)
1200       return lldb::eByteOrderLittle;
1201     else
1202       return lldb::eByteOrderBig;
1203 
1204   default:
1205     break;
1206   }
1207   return lldb::eByteOrderInvalid;
1208 }
1209