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