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