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