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